content
stringlengths
5
1.05M
function getAlphaChar() selection = math.random(1, 3) if selection == 1 then return string.char(math.random(65, 90)) end if selection == 2 then return string.char(math.random(97, 122)) end return string.char(math.random(48, 57)) end function getRandomString(length) length = length or 1 if length < 1 then return nil end local array = {} for i = 1, length do array[i] = getAlphaChar() end return table.concat(array) end function removeTrailingSlash(s) return (s:gsub("(.-)/*$", "%1")) end wrk.method = "POST" wrk.headers["Authorization"] = "Basic MWZNQ1ZaR2lBSWhiYVBkQWU5M3VYV3F2UGszOg==" wrk.headers["Content-Type"] = "application/json" wrk.body = '{"batch":[{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"},{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"},{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"},{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"},{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"},{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"},{"anonymousId":"anon_id","channel":"android-sdk","messageId":"1566904375469-1baf3108-647a-4f20-9867-3072056a07f5","context":{"app":{"build":"1","name":"RudderAndroidClient","namespace":"com.rudderlabs.android.sdk","version":"1.0"},"device":{"id":"49e4bdd1c280bc00","manufacturer":"Google","model":"AndroidSDKbuiltforx86","name":"generic_x86"},"locale":"en-US","network":{"carrier":"Android"},"screen":{"density":420,"height":1794,"width":1080},"library":{"name":"com.rudderstack.android.sdk.core"},"traits":{"anonymousId":"50e4bdd1c280bc00"},"user_agent":"Dalvik/2.1.0(Linux;U;Android9;AndroidSDKbuiltforx86Build/PSR1.180720.075)"},"event":"DemoTrack","integrations":{"All":true},"properties":{"label":"DemoLabel","category":"DemoCategory","value":5},"type":"track","originalTimestamp":"2019-08-12T05:08:30.909Z","sentAt":"2019-08-12T05:08:30.909Z"}]}' -- add a random string to the original request path. request = function() local body = wrk.body:gsub("anon_id", getRandomString(20)) return wrk.format(wrk.method, wrk.path, wrk.headers, body) end
return { init_effect = "", name = "鱼雷艇AI切换", time = 0, picture = "", desc = "鱼雷艇AI切换", stack = 1, id = 8013, icon = 8013, last_effect = "lingxing", effect_list = { { type = "BattleBuffAddBuff", trigger = { "onUpdate" }, arg_list = { buff_id = 8014, time = 4 } } } }
module(..., package.seeall) require "source/game/game" require "source/gui/guiUtilities" local flower = flower local singlePlayerGame = nil local view = nil local mouseEvents = { "mouseClick", "mouseMove", "mouseRightClick", } function onCreate(e) layer = flower.Layer() layer:setTouchEnabled(true) scene:addChild(layer) local popupView = widget.UIView { scene = scene, layout = widget.BoxLayout { align = {"center", "center"}, }, } singlePlayerGame = Game { layer = layer, mapFile = e.data.mapFile, view = e.data.view, popupView = popupView, -- TODO: fill this out } view = e.data.view buildUI("SinglePlayer", e.data.view, singlePlayerGame) flower.Runtime:addEventListener("resize", onResize) for i, v in ipairs(mouseEvents) do flower.InputMgr:addEventListener(v, onMouseEvent) end end function updateLayout() _resizeComponents(view) end function onResize(e) updateLayout() end function onStart(e) singlePlayerGame:stopped(false) singlePlayerGame:run() end function onStop(e) for i, v in ipairs(mouseEvents) do flower.InputMgr:removeEventListener(v, onMouseEvent) end singlePlayerGame:paused(false) singlePlayerGame:stopped(true) singlePlayerGame = nil end function onMouseEvent(e) if e.type ~= "mouseMove" then if not e.down then return end end local pos = singlePlayerGame.map:screenToGridSpace(e.x, e.y, layer) if e.type == "mouseClick" or e.type == "mouseRightClick" then singlePlayerGame:onTouchDown(pos, e.type) elseif e.type == "mouseMove" then singlePlayerGame:onMouseMove(pos) else error("Unknown input event: " .. e.type) end end
local errinfo = { Extra = "unexpected characters after grammar definition", ExpRule = "expected an expression after '<-'", Rule = "grammar must have at least one rule", Arrow = "expected '<-' after rule's name", SeqExp = "expected an expression after '/'", AndPred = "expected an expression after '&'", NotPred = "expected an expression after '!'", ExpPri = "expected an expression after '('", RParPri = "expected ')'", SingQuote = [[expected "'" to close string]], DoubQuote = [[expected '"' to close string]], EmptyClass = "a character class can not be empty", RBraClass = "expected ']' to close character class", NameThrow = "expected a name after '%{'", RCurThrow = "expected '}' to close throw expression", } return errinfo
--[[-- Software License Agreement (BSD 3-clause License) Copyright (c) 2017, iZotope, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of iZotope Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. iZotope wrapper for json functionality. This module wraps cjson and resty.prettycjson as well as providing helper functions local json = require "izo.json" @module izo.json ]] local cjson = require 'cjson.safe' -- Note: always use safe local prettycjson = require 'resty.prettycjson' local debug = require 'std.debug' local io = require 'std.io' local M local function encode(data, pretty) if pretty then return prettycjson(data) else return cjson.encode(data) end end local function decodefile(filename) local success, ret = pcall(io.slurp, filename) if not success then return nil, ret elseif not ret then return nil, "invalid file" end local jsondata, err = cjson.decode(ret) if jsondata then return jsondata else return nil, err end end --[[ ================= ]]-- --[[ Public Interface. ]]-- --[[ ================= ]]-- -- Macro like function for wrapping access to exported functions with argument type checking local function X (decl, fn) return debug.argscheck ("izo.json." .. decl, fn) end M = { --- encode a tabe into a json string -- @function encode -- @tparam table data data to convert into json -- @bool[opt=false] pretty set to true to do pretty string formatting of JSON -- @treturn string|nil json encoded string, or nil on error -- @return error on error, this is the error returned, otherwise nil -- @usage -- mystring, err = encode({a='hello', 0='test', 1=10}) encode = X ("encode (table, [?bool|:pretty])", encode), --- decode a JSON string to a table -- @function decode -- @string json text to be decoded -- @treturn table|nil table of decuded values, or nil on error -- @return error on error, this is the error returned, otherwise nil -- @usage -- mytable, err = decode('{"count" : 5}') decode = X ("decode (string)", cjson.decode), --- decode JSON from a file -- @function decodefile -- @string path to file to decode -- @treturn table|nil table of decoded valuesm or nil on error -- @return error on error, this is set to the error, otherwise nil -- @usage -- mytable, err = decodefile('/path/to/file.name') decodefile = X ("decodefile (string)", decodefile), --- cjson module table for access to internel functions. -- see [CJson documentation for more details about usage](https://www.kyne.com.au/%7Emark/software/lua-cjson-manual.html). cjson = cjson, } return M
--[[ TheNexusAvenger Configuration of the rocket launcher. --]] return { --Reload time of the rocket. ROCKET_RELOAD_TIME = 3, --Times for showing rocket. ROCKET_RELOAD_WAIT_TO_SHOW_TIME = 1, ROCKET_RELOAD_VISIBLE_TIME = 0.45, --Speed of the rocket. ROCKET_LAUNCH_SPEED = 60, --List of the instances to ignore by name. Case does not matter. IGNORE_LIST = { rocket = true, effect = true, water = true, handle = true, reflector = true, }, --Blast radius of the rocket. BLAST_RADIUS = 7, --Force of rocket launcher blast. FORCE_GRANULARITY = 2, BLAST_PRESSURE = 750000, --Time before the rocket disappears after launching. ROCKET_DECAY_TIME = 30, --Maximum and minimum damage of the rocket on characters. MAX_DAMAGE = 80, MIN_DAMAGE = 42, }
set_trap = { cast = function(player) if not player:canCast(1, 1, 0) then return end local q = string.lower(player.question) local level = player.level local traps = { "Dart", "Snare", "Repeating dart", "Flash", "Spear", "Poison", "Death", "Sleep" } local levelreq = {26, 33, 44, 55, 66, 77, 88, 99} if q == "dart" and level >= 26 then set_dart_trap.cast(player) elseif q == "snare" and level >= 33 then set_snare_trap.cast(player) elseif q == "repeating" and level >= 44 then set_repeating_dart_trap.cast(player) elseif q == "flash" and level >= 55 then set_flash_trap.cast(player) elseif q == "spear" and level >= 66 then set_spear_trap.cast(player) elseif q == "poison" and level >= 77 then set_poison_trap.cast(player) elseif q == "death" and level >= 88 then set_death_trap.cast(player) elseif q == "sleep" and level >= 99 then set_sleep_trap.cast(player) else player:sendMinitext("Select:") for i = 1, #traps do if player.level >= levelreq[i] then if i ~= 3 then player:sendMinitext(traps[i] .. " trap") else player:sendMinitext(traps[i]) end end end end end, requirements = function(player) local level = 26 local items = {"fine_rabbit_meat", 0} local itemAmounts = {2, 500} local description = "Allows you to set a trap of your choice as long as you meet the level requirements for the particular trap, beginning with Dart trap." return level, items, itemAmounts, description end }
-- vi:set ft=lua ts=4 sw=4 noet ai fdm=marker: -- {{{1 Disable unused built-in plugins vim.g.loaded_python_provider = 0 vim.g.loaded_python3_provider = 0 vim.g.loaded_ruby_provider = 0 vim.g.loaded_perl_provider = 0 vim.g.loaded_node_provider = 0 vim.g.loaded_man = 0 vim.g.loaded_gzip = 0 vim.g.loaded_netrwPlugin = 0 vim.g.loaded_tarPlugin = 0 vim.g.loaded_zipPlugin = 0 vim.g.loaded_2html_plugin = 0 vim.g.loaded_remote_plugins = 0 -- }}} -- {{{1 Decrease start-up time vim.cmd [[ syntax off filetype off filetype plugin indent off ]] -- Temporarily disable shada file to improve performance vim.opt.shadafile = 'NONE' local async async = vim.loop.new_async(vim.schedule_wrap(function() vim.defer_fn(function() vim.opt.shadafile = '' vim.defer_fn(function() vim.cmd [[ rshada! doautocmd BufRead syntax on filetype on filetype plugin indent on silent! bufdo e ]] end, 15) end, 0) async:close() end)) async:send() -- }}} -- {{{1 Packer plugin manager local install_path = vim.fn.stdpath('data') .. '/site/pack/packer/start/packer.nvim' if vim.fn.empty(vim.fn.glob(install_path)) > 0 then vim.fn.system({'git', 'clone', 'https://github.com/wbthomason/packer.nvim', install_path}) vim.api.nvim_command 'packadd packer.nvim' end vim.cmd [[ augroup Packer autocmd! autocmd BufWritePost init.lua PackerCompile augroup end ]] local use = require'packer'.use require'packer'.startup(function() use 'wbthomason/packer.nvim' -- Package manager use 'neovim/nvim-lspconfig' -- Collection of configurations for built-in LSP client use 'machakann/vim-sandwich' -- Surround text objects use 'tpope/vim-commentary' -- 'gc' to comment visual regions/lines use 'tpope/vim-fugitive' -- Git commands in nvim use 'tjdevries/astronauta.nvim' -- Keymap wrapper functions use 'ggandor/lightspeed.nvim' -- Motion plugin use { 'williamboman/nvim-lsp-installer', config = function() lsp_install_init() end } -- Automatic tags management use { 'ludovicchabant/vim-gutentags', setup = function() vim.g.gutentags_enabled = true vim.g.gutentags_ctags_tagfile = '.tags' vim.g.gutentags_file_list_command = 'fd' end } -- Tokyonight theme use { 'folke/tokyonight.nvim', setup = function() vim.g.tokyonight_lualine_bold = false vim.g.tokyonight_sidebars = { 'qf', 'terminal', 'packer' } end, config = function() vim.cmd [[colorscheme tokyonight]] end } -- Autocompletion plugin use { 'hrsh7th/nvim-cmp', requires = { {'hrsh7th/cmp-nvim-lsp'}, {'hrsh7th/cmp-buffer'}, {'saadparwaiz1/cmp_luasnip', requires = {'L3MON4D3/LuaSnip'}} }, config = function() vim.opt.completeopt = {'menuone', 'noselect'} vim.opt.shortmess:append({ I = true }) cmp_init() end } -- Language parser use { 'nvim-treesitter/nvim-treesitter', run = ':TSUpdate', config = function() treesitter_init(); end } -- Indent guides for spaces use { 'glepnir/indent-guides.nvim', config = function() indent_init(); end } -- Lua scratchpad use { 'rafcamlet/nvim-luapad', cmd = 'Luapad', config = function() luapad_init(); end } -- External linter support use { 'mfussenegger/nvim-lint', ft = {'sh', 'bash'}, config = function() lint_init(); end } -- Interactive keybind overview use { 'folke/which-key.nvim', config = function() local wk = require'which-key' wk.setup { triggers = {'<leader>'} } wk.register({ c = { "Yank to CLIPBOARD" }, y = { "Yank to PRIMARY"} }, { prefix = '<leader>', mode = 'x'}) end } use { 'nvim-lualine/lualine.nvim', config = function() lualine_init(); end } -- Add git related info in the signs columns and popups use { 'lewis6991/gitsigns.nvim', requires = {'nvim-lua/plenary.nvim'}, config = function() gitsigns_init(); end } -- UI to select things (files, grep results, open buffers...) use { 'nvim-telescope/telescope.nvim', requires = {'nvim-lua/plenary.nvim'}} -- Native telescope fuzzy sorter use { 'nvim-telescope/telescope-fzy-native.nvim', requires = {'nvim-telescope/telescope.nvim'}, cond = function() if vim.fn.executable('fzy') == 1 then return true end end, config = function() require'telescope'.load_extension('fzy_native'); end } -- Automatically create parenthesis pairs use { 'windwp/nvim-autopairs', config = function() autopairs_init(); end, disable = true } -- Bookmarks in QuickFix use { 'MattesGroeger/vim-bookmarks', setup = function() vim.g.bookmark_auto_save_file = vim.fn.stdpath('cache') .. '/bookmarks' vim.g.bookmark_save_per_working_dir = false vim.g.bookmark_auto_save = false vim.g.bookmark_disable_ctrlp = true vim.g.bookmark_highlight_lines = true vim.g.bookmark_manage_per_buffer = false end } -- Bookmark support for Telescope use { 'tom-anders/telescope-vim-bookmarks.nvim', requires = {'nvim-telescope/telescope.nvim'}, config = function() require'telescope'.load_extension('vim_bookmarks'); end } end) -- }}} -- {{{1 Utility functions ex = setmetatable({}, { __index = function(t, k) local command = k:gsub('_$', '!') local f = function(...) return vim.api.nvim_command(table.concat(vim.tbl_flatten {command, ...}, ' ')) end rawset(t, k, f) return f end }); function _G.dump(...) local objects = vim.tbl_map(vim.inspect, {...}) return unpack(objects) end function _G.t(s) return vim.api.nvim_replace_termcodes(s, true, true, true) end local util = {} function util.keep_state(callback, ...) local view = vim.fn.winsaveview() callback(...) vim.fn.winrestview(view) end function util.trim(s) local b = s:find'%S' return b and s:match('.*%S', b) or '' end function util.tok(s, sep) if sep == nil then sep = '%s' end local t = {} for str in s:gmatch('([^'..sep..']+)') do table.insert(t, str) end return t end -- create mapping functions and add them to globals table for LSP local globals = (function(modes) local map = {} modes:gsub('.', function(c) f = function(key, action, opts) if opts == nil then opts = { noremap = true } end vim.api.nvim_set_keymap(c, key, action, opts) end local fn = c .. 'map' rawset(_G, fn, f) table.insert(map, fn) end) return map end)('cinostvx') -- create astronauta mapping functions do local km = require'astronauta.keymap' for k,v in pairs(km) do if string.match(k, '%Dnoremap') then table.insert(globals, k) rawset(_G, k, v) end end end -- }}} -- {{{1 Generic options -- Disable welcome text vim.opt.shortmess:append({ c = true }) -- Incremental live completion vim.o.inccommand = 'nosplit' -- Set highlight on search vim.o.hlsearch = true vim.o.incsearch = true -- No magic by default vim.opt.magic = false -- Keep cursor away from screen edge vim.o.scrolloff = 5 -- Make line numbers default vim.wo.number = true vim.wo.relativenumber = true -- Do not save when switching buffers vim.o.hidden = true --Do not show x on last line vim.o.showmode = false vim.o.showcmd = false --Enable mouse mode vim.o.mouse = 'a' -- Use primary clipboard vim.o.clipboard = 'unnamed' --Indentation vim.bo.tabstop = 4; vim.o.tabstop = 4; vim.bo.shiftwidth = 4; vim.o.shiftwidth = 4; vim.bo.expandtab = false; vim.o.expandtab = false; vim.bo.softtabstop = -1; vim.o.softtabstop = -1; vim.bo.copyindent = true; -- Autoreload files changed outside vim vim.o.autoread = true -- Enable break indent vim.o.breakindent = true -- Enable line wrapping vim.wo.wrap = false vim.wo.linebreak = false vim.o.sidescroll = 10 vim.wo.colorcolumn = '120' -- Save undo history vim.opt.undodir = vim.fn.stdpath('cache') .. '/undo' vim.opt.undofile = true vim.o.directory = vim.fn.stdpath('cache') .. '/swap' vim.o.backup = false vim.o.writebackup = true vim.o.swapfile = true -- Show whitespace characters vim.wo.list = true vim.o.listchars = 'tab:→ ,eol:↲,nbsp:␣,trail:•,lead:_,extends:⟩,precedes:⟨' vim.o.showbreak = '↪ ' -- Diff mode options vim.opt.diffopt = { 'filler', 'vertical', 'internal', 'algorithm:patience', 'indent-heuristic', 'context:3' } -- Improve performance vim.o.lz = true vim.o.synmaxcol = 256 -- Fold method, may be changed by treesitter vim.o.foldmethod = 'marker' -- Case insensitive searching UNLESS /C or capital in search vim.o.ignorecase = true vim.o.smartcase = true -- Eliminate delays vim.o.timeout = true vim.o.timeoutlen = 300 vim.o.ttimeout = false vim.o.ttimeoutlen = 0 -- Decrease update time for CursorHold vim.o.updatetime = 150 -- Always show diagnostics column vim.wo.signcolumn = 'yes:1' -- Change preview window location vim.o.splitright = true -- Set colorscheme (order is important here) vim.o.termguicolors = true vim.wo.cursorline = true vim.wo.cursorcolumn = true -- vim.g.onedark_terminal_italics = 2 vim.g.tokyonight_style='storm' -- Add map to enter paste mode vim.o.pastetoggle='<F5>' -- }}} -- {{{1 LSP -- {{{2 Attach local nvim_lsp = require'lspconfig' local on_attach = function(client, bufnr) vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc') local map = (function(modes) local map = {} modes:gsub('.', function(c) f = function(key, action, opts) if opts == nil then opts = { noremap = true } end vim.api.nvim_buf_set_keymap(bufnr, c, key, action, opts) end rawset(map, c, f) end) return map end)('nvic') local opts = { noremap=true, silent=true } map.n('<leader>lD', '<Cmd>lua vim.lsp.buf.declaration()<CR>', opts) map.n('<leader>ld', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) map.n('<leader>lh', '<Cmd>lua vim.lsp.buf.hover()<CR>', opts) map.n('<leader>lK', '<Cmd>lua vim.lsp.buf.signature_help()<CR>', opts) map.n('<leader>li', '<Cmd>lua vim.lsp.buf.implementation()<CR>', opts) map.n('<leader>lt', '<Cmd>lua vim.lsp.buf.type_definition()<CR>', opts) map.n('<leader>lR', '<Cmd>lua vim.lsp.buf.rename()<CR>', opts) map.n('<leader>lr', '<Cmd>lua vim.lsp.buf.references()<CR>', opts) map.n('<leader>la', '<Cmd>lua vim.lsp.buf.code_action()<CR>', opts) map.n('<leader>le', '<Cmd>lua vim.diagnostic.open_float({focusable = false})<CR>', opts) map.n('<leader>lq', '<Cmd>lua vim.diagnostic.setloclist()<CR>', opts) map.n('<leader>lwa', '<Cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts) map.n('<leader>lwr', '<Cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts) map.n('<leader>lwl', '<Cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts) map.n('ö', '<Cmd>lua vim.diagnostic.goto_prev({popup_opts = {focusable = false}})<CR>', opts) map.n('ä', '<Cmd>lua vim.diagnostic.goto_next({popup_opts = {focusable = false}})<CR>', opts) map.n('<M-k>', '<Cmd>lua vim.lsp.buf.hover({focusable = false})<CR>', opts) map.n('<M-d>', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) map.i('<M-k>', '<Cmd>lua vim.lsp.buf.hover({focusable = false})<CR>', opts) map.i('<M-d>', '<Cmd>lua vim.lsp.buf.definition()<CR>', opts) -- Set some keybinds conditional on server capabilities if client.resolved_capabilities.document_formatting then map.n('<leader>F', '<Cmd>lua vim.lsp.buf.formatting()<CR>', opts) elseif client.resolved_capabilities.document_range_formatting then map.n('<leader>F', '<Cmd>lua vim.lsp.buf.range_formatting()<CR>', opts) end end -- 2}}} -- {{{2 Servers local capabilities = vim.lsp.protocol.make_client_capabilities() do capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) local servers = { 'clangd', 'gopls', } for _, lsp in ipairs(servers) do nvim_lsp[lsp].setup { on_attach = on_attach, capabilities = capabilities, flags = { debounce_text_changes = 150, } } end end -- }}} -- {{{2 LSP Installer lsp_install_init = function() local lsp_installer = require("nvim-lsp-installer") lsp_installer.on_server_ready(function(server) local opts = {} if server.name == "sumneko_lua" then globals = { 'vim', 'use_rocks', table.unpack(globals) } opts = { settings = { Lua = { diagnostics = { globals = globals, disable = { 'lowercase-global' } }, telemetry = { enable = false } }}} end server:setup(opts) vim.cmd [[ do User LspAttachBuffers ]] end) end -- }}} -- {{{2 Features vim.lsp.handlers['extDocument/publishDiagnostics'] = vim.lsp.with( vim.lsp.diagnostic.on_publish_diagnostics, { underline = true, virtual_text = true, signs = true, update_in_insert = false, }) -- Map :Format to vim.lsp.buf.formatting() vim.cmd [[command! Format execute 'lua vim.lsp.buf.formatting()']] -- Allow for virtual text to be toggled vim.b.lsp_virtual_text_enabled = true local diagnostic_toggle_virtual_text = function() local virtual_text = vim.b.lsp_virtual_text_enabled virtual_text = not virtual_text vim.b.lsp_virtual_text_enabled = virtual_text vim.lsp.diagnostic.display(vim.lsp.diagnostic.get(0, 1), 0, 1, { virtual_text = virtual_text }) end -- }}} -- {{{2 Diagnostics vim.cmd [[ augroup linediag autocmd! autocmd CursorHold,CursorHoldI * lua vim.diagnostic.open_float({focusable = false}) augroup end ]] -- 2}}} -- 1}}} -- {{{1 Treesitter treesitter_init = function() require'nvim-treesitter.configs'.setup { ensure_installed = 'maintained', highlight = { enable = true, -- disable = { 'lua' } }, incremental_selection = { enable = true, keymaps = { init_selection = 'gnn', node_incremental = 'grn', scope_incremental = 'grc', node_decremental = 'grm', }, }, indent = { enable = true }, textobjects = { select = { enable = true, -- Automatically jump forward to textobj, similar to targets.vim lookahead = true, keymaps = { -- You can use the capture groups defined in textobjects.scm ['af'] = '@function.outer', ['if'] = '@function.inner', ['ac'] = '@class.outer', ['ic'] = '@class.inner', }, }, move = { enable = true, -- whether to set jumps in the jumplist set_jumps = true, goto_next_start = { [']m'] = '@function.outer', [']]'] = '@class.outer', }, goto_next_end = { [']M'] = '@function.outer', [']['] = '@class.outer', }, goto_previous_start = { ['[m'] = '@function.outer', ['[['] = '@class.outer', }, goto_previous_end = { ['[M'] = '@function.outer', ['[]'] = '@class.outer', }, }, }, } end -- Treesitter folding whitelist do local fold_whitelist = { 'markdown', } for _, value in pairs(fold_whitelist) do vim.api.nvim_exec('augroup fold | autocmd! fold FileType ' .. value .. ' setlocal foldmethod=expr | setlocal foldexpr=nvim_treesitter#foldexpr()', false) end end nmap('<F8>', '<Cmd>setlocal foldmethod=expr | setlocal foldexpr=nvim_treesitter#foldexpr()<CR>') -- }}} -- {{{1 Linter lint_init = function() require'lint'.linters.shellcheck.args = { '--format', 'json', '-s', 'bash', '-x', '-', } require'lint'.linters_by_ft = { sh = {'shellcheck',}, bash = {'shellcheck',}, } vim.cmd [[ augroup Linter autocmd! * <buffer> autocmd BufWritePost * lua require'lint'.try_lint() augroup end ]] end -- }}} -- {{{1 Indent guides indent_init = function() require'indent_guides'.setup { indent_guide_snnn = 1; indent_start_level = 1; indent_levels = 16; indent_enable = true; indent_space_guides = true; indent_tab_guides = true; indent_soft_pattern = '\\s'; exclude_filetypes = {'help','dashboard','dashpreview','NvimTree','vista','sagahover'}; odd_colors = { fg='#565f89',bg='bg' }; even_colors = { fg='#414868',bg='bg' }; } end -- }}} -- {{{1 Gitsigns init gitsigns_init = function() require'gitsigns'.setup{ signs = { add = { hl = 'GitSignsAdd', text = '+', numhl='GitSignsAddNr' , linehl='GitSignsAddLn' }, change = { hl = 'GitSignsChange', text = '~', numhl='GitSignsChangeNr', linehl='GitSignsChangeLn' }, delete = { hl = 'GitSignsDelete', text = '_', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' }, topdelete = { hl = 'GitSignsTopDelete', text = '‾', numhl='GitSignsDeleteNr', linehl='GitSignsDeleteLn' }, changedelete = { hl = 'GitSignsChangeDelete', text = '~', numhl='GitSignsChangeNr', linehl='GitSignsChangeLn' }, }, update_debounce = 500, numhl = true, linehl = false, } end -- }}} -- {{{1 Autopairs autopairs_init = function() local npairs = require'nvim-autopairs' npairs.setup({ check_ts = true, ts_config = { -- it will not add pair on that treesitter node lua = {'string'}, javascript = {'template_string'}, -- don't check treesitter on java java = false, }, fast_wrap = {}, }) require('nvim-treesitter.configs').setup { autopairs = {enable = true} } local ts_conds = require('nvim-autopairs.ts-conds') local Rule = require('nvim-autopairs.rule') -- press % => %% is only inside comment or string npairs.add_rules({ Rule("%", "%", "lua") :with_pair(ts_conds.is_ts_node({'string','comment'})), Rule("$", "$", "lua") :with_pair(ts_conds.is_not_ts_node({'function'})) }) end -- }}} -- {{{1 Mouse toggle local nomouse = { status = false, window = 0, target = { number = false, relativenumber = false, list = false, signcolumn = 'no' } } toggle_mouse = function() local backup = function(t) t.window = vim.api.nvim_get_current_win() t.backup = {} for k,_ in pairs(t.target) do nomouse.backup[k] = vim.api.nvim_win_get_option(t.window, k) end end local setopt = function(t) if next(t) ~= nil then for k,v in pairs(t) do vim.api.nvim_win_set_option(t.window, k, v) end end end if vim.o.mouse == 'a' then backup(nomouse) diagnostic_toggle_virtual_text() setopt(nomouse.target) vim.o.mouse = 'v' else diagnostic_toggle_virtual_text() setopt(nomouse.backup) vim.o.mouse = 'a' end nomouse.status = not nomouse.status end nmap('<F7>', '<Cmd>lua toggle_mouse()<CR>') -- }}} -- {{{1 lualine statusbar lualine_init = function() require'lualine'.setup { options = { theme = 'tokyonight'; icons_enabled = false, padding = 1, left_padding = 1, right_padding = 1, fmt = string.lower }, sections = { lualine_a = { 'mode' }, lualine_b = { { (function() return [[NOMOUSE]]; end), cond = (function() return nomouse.status; end), fmt = string.upper }, { (function() return [[PASTE]]; end), cond = (function() return vim.o.paste; end), fmt = string.upper } }, lualine_c = { { 'filename', file_status = true }, { 'fugitive#head'}, { 'diff' }}, lualine_y = { 'progress', 'hostname' } }, extension = { 'fzf', 'fugitive' } } end -- }}} -- {{{1 Whitespace handling trim_lines = function() util.keep_state(vim.api.nvim_command, [[keeppatterns %s/\s\+$//e]]) end delete_empty = function() util.keep_state(vim.api.nvim_command, [[keeppatterns :v/\_s*\S/d]]) end vim.cmd [[command! TrimTrailingWhite :lua trim_lines()]] vim.cmd [[command! TrimTrailingLines :lua delete_empty()]] vim.cmd [[command! TrimAll :lua trim_lines(); delete_empty()]] -- }}} -- {{{1 Custom key bindings -- Test mapping with lua callback -- nnoremap { '<leader>hello', function() print('"hello world!" from lua!') end } -- Remap space as leader key vim.api.nvim_set_keymap('', '<Space>', '<Nop>', {noremap = true, silent = true}) vim.g.mapleader = ' ' vim.g.maplocalleader = ' ' -- Workaround for tmux under kitty vim.api.nvim_set_keymap('', '<C-a>', '<Home>', {noremap = true, silent = true}) vim.api.nvim_set_keymap('', '<C-e>', '<End>', {noremap = true, silent = true}) opts = { noremap = true, expr = true, silent = true } nmap('k', "v:count == 0 ? 'gk' : 'k'", opts) nmap('j', "v:count == 0 ? 'gj' : 'j'", opts) -- Do not copy when pasting xmap('p', 'pgvy') -- J and K to move up and down nmap('J', '}') nmap('K', '{') vmap('J', '}') vmap('K', '{') -- H and L to move to the beginning and end of a line nmap('H', '_') nmap('L', '$') vmap('H', '_') vmap('L', '$') nmap('<C-f>', '/') -- nmap('<C-q>', '<Cmd>close<CR>') nmap('<C-s>', ':w<CR>') nmap('<C-t>', ':Telescope fd<CR>') nmap('u', ':undo<CR>') nmap('U', ':redo<CR>') -- clear hls nmap('<C-h>', ':noh<CR>') -- Create splits with s and S nmap('<C-w>s', ':vsplit<CR>:wincmd l<CR>') -- Create, close, and move between tabs nmap('~', ':tabnew<CR>') nmap('–', ':tabclose<CR>') nmap('·', ':tabprevious<CR>') nmap('…', ':tabnext<CR>') -- Cycle through open buffers nmap('<leader>,', ':bprevious<CR>') nmap('<leader>.', ':bnext<CR>') nmap('<M-,>', ':bprevious<CR>') nmap('<M-.>', ':bnext<CR>') nmap('<M-->', ':bdelete<CR>') nmap('<M-_>', ':bwipeout<CR>') -- Change to file directory in current window nmap('<leader>cd', ':lcd %:p:h<CR>:pwd<CR>') -- Save all. nmap('<C-M-s>', ':wa<CR>:echo "All saved!"<CR>') -- Search and replace using marked text vmap('<C-r>', '"vy:%s/<C-r>v//gc<left><left><left>') -- Don't yank when using delete nmap('<del>', '"_x') nmap('x', '"_x') -- Save session nmap('<F6>', '<Cmd>wa<Bar>exe "mksession! " . v:this_session<CR><Cmd>echo "Session saved!"<CR>') -- Update Plugins nmap('<leader>U', '<Cmd>PackerSync<CR>') -- Next search result nmap('<F3>', 'n') nmap('<F4>', 'N') -- Transpose lines opts = { noremap = true, silent = true } nmap('<M-Up>', '<Cmd>move .-2<CR>', opts) nmap('<M-Down>', '<Cmd>move .+1<CR>', opts) -- Need to trigger CmdlineEnter/CmdlineLeave events, so do not use <Cmd> vmap('<M-Up>', ':move \'<-2<CR>gv=gv', opts) vmap('<M-Down>', ':move \'>+1<CR>gv=gv', opts); -- Yank to CLIPBOARD register xmap('<leader>c', '"+y') xmap('<C-c>', '"+y') -- Yank to PRIMARY register xmap('<leader>y', '"*y') xmap('<C-y>', '"*y') -- Keep cursor position when scrolling nmap('<PageUp>', '<C-U><C-U>') vmap('<PageUp>', '<C-U><C-U>') imap('<PageUp>', '<C-\\><C-O><C-U><C-\\><C-O><C-U>') nmap('<PageDown>', '<C-D><C-D>') vmap('<PageDown>', '<C-D><C-D>') imap('<PageDown>', '<C-\\><C-O><C-D><C-\\><C-O><C-D>') -- nnoremap <silent> <PageDown> <C-D><C-D> -- vnoremap <silent> <PageDown> <C-D><C-D> -- inoremap <silent> <PageDown> <C-\><C-O><C-D><C-\><C-O><C-D> -- }}} -- {{{1 Abbreviations -- Force write with sudo, two different approaches vim.cmd [[com! -bang W lua SudoWrite('<bang>' == '!')]] SudoWrite = function(bang) if not bang then print('Add ! to use sudo.') else vim.cmd [[ w! /tmp/sudonvim bel 2new startinsert te sudo tee #:S </tmp/sudonvim >/dev/null; rm /tmp/sudonvim ]] end end do local askpass = { '/usr/libexec/seahorse/ssh-askpass', '/usr/libexec/openssh/gnome-ssh-askpass', } for _, v in ipairs(askpass) do if vim.fn.executable(v) == 1 then ex.abbrev('w!!', 'w !SUDO_ASKPASS=' .. v .. ' sudo -A tee > /dev/null %') break end end end -- }}} -- {{{1 Insert modeline GenerateModeline = function() local expand if vim.bo.expandtab ~= 'noexpandtab' then expand = 'noet' else expand = 'et' end local autoindent if vim.bo.autoindent ~= 'noautoindent' then autoindent = 'noai' else autoindent = 'ai' end local cin = ''; local cout = '' if vim.o.commentstring ~= nil then local ctok = util.tok(vim.o.commentstring, '%%s') if next(ctok) ~= nil then cin = util.trim(ctok[1]) if next(ctok, 1) ~= nil then cout = util.trim(ctok[2]) end end end local ml = cin .. ' vi:set ft=' .. vim.bo.filetype .. ' ts=' .. vim.bo.tabstop .. ' sw=' .. vim.bo.shiftwidth .. ' ' .. expand .. ' ' .. autoindent .. ': ' .. cout vim.api.nvim_put({ util.trim(ml) }, 'l', true, false) end nmap('<leader>Z', [[<Cmd>lua GenerateModeline()<CR>]]) -- }}} -- {{{1 Telescope local find_cmd if vim.fn.executable("fd") == 1 then find_cmd = { 'fd', '--type', 'f', '--hidden', '--no-ignore', '--exclude', '.git', '--exclude', '.tags' } end require'telescope'.setup { defaults = { mappings = { i = { ['<C-u>'] = false, ['<C-d>'] = false, }, }, generic_sorter = require'telescope.sorters'.get_fzy_sorter, file_sorter = require'telescope.sorters'.get_fzy_sorter, }, pickers = { -- Your special builtin config goes in here buffers = { sort_lastused = true, theme = "ivy", previewer = false, mappings = { i = { ["<c-d>"] = require("telescope.actions").delete_buffer, }, n = { ["<c-d>"] = require("telescope.actions").delete_buffer, } } }, find_files = { theme = "ivy", previewer = false, hidden = true, find_command = find_cmd }, live_grep = { -- extending default values instead of overwriting vimgrep_arguments = (function() local args = vim.tbl_values(require("telescope.config").values.vimgrep_arguments) local ext = { "--hidden", "--glob", "!.git/**" } return vim.tbl_flatten({ args, ext }) end)() }, git_files = { theme = "ivy", previewer = false, }, oldfiles = { theme = "ivy", previewer = false, }, builtin = { theme = "dropdown", previewer = false }, marks = { theme = "ivy" }, registers = { theme = "ivy" }, tags = { only_current_buffer = true }, }, extensions = { -- Your extension config goes in here } } -- Add leader shortcuts opts = { noremap = true, silent = true } nmap('<leader>b', [[<Cmd>lua require'telescope.builtin'.buffers()<CR>]], opts) nmap('<leader>B', [[<Cmd>lua require'telescope.builtin'.builtin()<CR>]], opts) nmap('<leader>f', [[<Cmd>lua require'telescope.builtin'.find_files()<CR>]], opts) nmap('<leader><space>', [[<Cmd>lua require'telescope.builtin'.buffers()<CR>]], opts) nmap('<leader>r', [[<Cmd>lua require'telescope.builtin'.registers()<CR>]], opts) nmap('<leader>p', [[<Cmd>lua require'telescope.builtin'.current_buffer_fuzzy_find()<CR>]], opts) -- nmap('<leader>m', [[<Cmd>lua require'telescope.builtin'.marks()<CR>]], opts) nmap('<leader>t', [[<Cmd>lua require'telescope.builtin'.tags()<CR>]], opts) nmap('<leader>?', [[<Cmd>lua require'telescope.builtin'.oldfiles()<CR>]], opts) nmap('<leader>i', [[<Cmd>lua require'telescope.builtin'.live_grep()<CR>]], opts) nmap('<leader>s', [[<Cmd>lua require'telescope.builtin'.grep_string()<CR>]], opts) nmap('<leader>Gc', [[<Cmd>lua require'telescope.builtin'.git_commits()<CR>]], opts) nmap('<leader>Gb', [[<Cmd>lua require'telescope.builtin'.git_branches()<CR>]], opts) nmap('<leader>Gs', [[<Cmd>lua require'telescope.builtin'.git_status()<CR>]], opts) nmap('<leader>Gp', [[<Cmd>lua require'telescope.builtin'.git_bcommits()<CR>]], opts) nmap('<leader>g', [[<Cmd>lua require'telescope.builtin'.git_files()<CR>]], opts) nmap('<leader>H', [[<Cmd>lua require'telescope.builtin'.help_tags()<CR>]], opts) nmap('<leader>m', [[<Cmd>lua require'telescope'.extensions.vim_bookmarks.all()<CR>]], opts) nmap('<leader>M', [[<Cmd>lua require'telescope'.extensions.vim_bookmarks.current_file()<CR>]], opts) -- {{{1 cmp cmp_init = function() local cmp = require'cmp' local luasnip = require'luasnip' cmp.setup { snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = { ['<C-p>'] = cmp.mapping.select_prev_item(), ['<C-n>'] = cmp.mapping.select_next_item(), ['<C-d>'] = cmp.mapping.scroll_docs(-4), ['<C-f>'] = cmp.mapping.scroll_docs(4), ['<C-Space>'] = cmp.mapping.complete(), ['<C-e>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm { behavior = cmp.ConfirmBehavior.Replace, select = true, }, ['<Tab>'] = function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() else fallback() end end, ['<S-Tab>'] = function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jumpable(-1) else fallback() end end, }, sources = { { name = 'nvim_lsp' }, { name = 'luasnip' }, { name = 'buffer' }, }, } end -- }}} -- {{{1 Luapad luapad_init = function() require'luapad'.config { count_limit = 150000, error_indicator = false, eval_on_move = true, error_highlight = 'WarningMsg', on_init = function() print('Luapad initialized.') end, context = { shout = function(str) return(string.upper(str) .. '!') end } } nmap('<F2>', '<Cmd>Luapad<CR>') end -- }}} -- {{{1 FileType -- Change local working dir to current file directory -- vim.cmd [[ -- augroup AutoChdir -- autocmd! -- autocmd BufEnter * silent! lcd %:p:h -- augroup end -- ]] -- Open help as vsplit vim.cmd [[ augroup VerticalHelp autocmd! autocmd BufEnter *.txt if &buftype == 'help' | wincmd L | endif " autocmd FileType help wincmd L augroup end ]] vim.cmd [[ augroup FishComment autocmd FileType fish setlocal commentstring=#%s augroup end ]] -- }}} -- {{{1 Loose autocmds -- Hide cmdline after entering a command vim.cmd [[ augroup CmdLine autocmd! autocmd CmdlineLeave : echo "" augroup end ]] -- Highlight on yank vim.cmd [[ augroup YankHighlight autocmd! autocmd TextYankPost * silent! lua vim.highlight.on_yank { timeout = 100, higroup = "lCursor" } augroup end ]] -- Remap escape to leave terminal mode vim.cmd [[ augroup Terminal autocmd! autocmd TermOpen * tnoremap <buffer> <Esc> <c-\><c-n> autocmd TermOpen * set nonu augroup end ]] -- Markdown filetype for bare textfiles vim.cmd [[ augroup MarkdownText autocmd! autocmd BufNewFile,BufRead *.txt setlocal ft=markdown augroup end ]] -- }}} -- {{{1 Assorted command -- Vertical split with bigger left window vim.cmd [[command! Vsplit vsplit | wincmd w | vertical resize 125]] -- }}} -- {{{1 Theme/GUI -- Override highlighting vim.cmd [[ function! ColorOverride() abort highlight clear MatchParen highlight MatchParen cterm=underline ctermfg=84 gui=underline guifg=#50FA7B guibg=#ff79c6 highlight link String DraculaPurple highlight iCursor guifg=white guibg=#50FA7B endfunction augroup HlOverride autocmd! autocmd ColorScheme dracula call ColorOverride() augroup end ]] vim.opt.guicursor:append({ 'i:ver100-iCursor', 'i:blinkon2' }) vim.o.guifont = 'Fira Code:h11' vim.g.neovide_refresh_rate = 120 vim.g.neovide_cursor_antialiasing = false vim.g.neovide_cursor_vfx_mode = 'pixiedust' -- }}} -- {{{1 Legacy VimScript -- }}} -- {{{1 Staging area nmap('<leader>d', [[<Cmd>packadd termdebug | Termdebug<CR>]], opts) -- }}}
local luv = require("luv") local t1 = luv.thread.spawn(function(id) local f1 = luv.fiber.create(function() for i=1, 100 do print(id, "tick: ", i) end end) f1:join() return "answer" end, "A") local t2 = luv.thread.spawn(function(id) local f1 = luv.fiber.create(function() for i=1, 100 do print(id, "tick: ", i) end end) f1:join() return 42 end, "B") print("threads:", t1, t2) print("JOIN:", t1:join(), t2:join())
-- Gun Gamemode local Gun_Entity = {} local Gun_Settings = {} function Gun_Entity_Add(Entity_ID) Gun_Entity[Temp_Entity_ID] = {} Gun_Entity[Temp_Entity_ID].State = 0 -- 0=Living 1=Dead end function Gun_Entity_Die(Entity_ID) local Prefix, Name, Suffix = Entity_Displayname_Get(Entity_ID) local Map_ID = Gun_Settings.Map_ID Gun_Entity[Temp_Entity_ID].State = 1 System_Message_Network_Send_2_All(Map_ID, Prefix..Name..Suffix.."&c lost") end function Gun_Entity_Delete(Entity_ID) local Prefix, Name, Suffix = Entity_Displayname_Get(Entity_ID) local Map_ID = Gun_Settings.Map_ID Gun_Entity[Temp_Entity_ID] = {} System_Message_Network_Send_2_All(Map_ID, Prefix..Name..Suffix.."&c left the game") Entity_Message_2_Clients(Entity_ID, "&cYou left the game") end function Command_Gamemode_Gun_Start(Client_ID, Command, Text_0, Text_1, Arg_0, Arg_1, Arg_2, Arg_3, Arg_4) local Entity_ID = Client_Get_Entity(Client_ID) local Map_ID = Entity_Get_Map_ID(Entity_ID) Gun_Entity = {} Gun_Settings.Map_ID = Map_ID Gun_Settings.State = 1 local Entity_Table, Entities = Entity_Get_Table() for i = 1, Entities do local Temp_Entity_ID = Entity_Table[i] if Entity_Get_Map_ID(Temp_Entity_ID) == Map_ID then end end System_Message_Network_Send_2_All(Map_ID, "&eGamemode Gun started") end Event_Add("Gun_Event_Entity_Die", "Gun_Event_Entity_Die", "Entity_Die", 1, 0, -1) function Gun_Event_Entity_Die(Result, Entity_ID) local Player_Number = Entity_Get_Player(Entity_ID) local Map_ID = Entity_Get_Map_ID(Entity_ID) local Map_Size_X, Map_Size_Y, Map_Size_Z = Map_Get_Dimensions(Map_ID) if Gun_Entity[Entity_ID] ~= nil then if Map_ID == Gun_Settings.Map_ID then Entity_Position_Set(Entity_ID, Map_ID, Spawn_X, Spawn_Y, Spawn_Z, 0, 0, 255, 1) else Gun_Entity_Delete(Entity_ID) end Result = 0 end return Result end --[[Event_Add("Gun_Event_Move", "Gun_Event_Move", "Entity_Position_Set", 0, 0, 3) function Gun_Event_Move(Result, Entity_ID, Map_ID, X, Y, Z, Rotation, Look, Priority) if Gun_Entity[Entity_ID] ~= nil then if Map_ID == Gun_Settings.Map_ID then local Map_Size_X, Map_Size_Y, Map_Size_Z = Map_Get_Dimensions(Map_ID) else Gun_Entity_Delete(Entity_ID) end end return Result end]]
local a=module('_core','libs/Tunnel')local b=module('_core','libs/Proxy')local c=a.getInterface("hpp_craft")API=b.getInterface('API')cAPI=a.getInterface('cAPI')hppC={}a.bindInterface("hpp_craft",hppC)Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)local d=module("hpp_craft","config/cfg")local e=false;animApi=module("_core","client/functions/_Anims")Citizen.CreateThread(function()for f,g in pairs(d.blips)do local h=AddBlipForCoord(g.coords[1],g.coords[2],g.coords[3])SetBlipSprite(h,g.sprite)SetBlipColour(h,g.color)SetBlipScale(h,0.6)SetBlipAsShortRange(h,true)BeginTextCommandSetBlipName("STRING")AddTextComponentString(g.title)EndTextCommandSetBlipName(h)end end)local i=3000;local j=false;Citizen.CreateThread(function()while true do Citizen.Wait(i)for k,l in pairs(d.crafts)do if k==1 then j=false end;local m=GetPlayerPed(-1)local n,o,p=table.unpack(GetEntityCoords(m))local q,r=GetGroundZFor_3dCoord(l.coords[1],l.coords[2],l.coords[3])local s=GetDistanceBetweenCoords(l.coords[1],l.coords[2],r,n,o,p,true)if s<20 then j=true;DrawMarker(2,l.coords[1],l.coords[2],l.coords[3],0,0,0,0,0,0,0.5,0.5,0.5,255,255,0,30,1,1,1,1)DrawText3D(l.coords[1],l.coords[2],l.coords[3]+0.6,l.title,1.0,4,100)if s<1.5 then if not e then e=true end;drawTxt("PRESSIONE ~b~E",4,0.50,0.95,0.36,255,255,255,240)if IsControlJustPressed(0,38)then if l.perm then if c.checkPerm(l.perm)then local t=c.checkCraft(l.item,l.itemqtd,l.giveitem,l.giveqtd)if t.error then if t.reason=="there is no free space in the inventory"then TriggerEvent("Notify","negado","Espaço insuficiente!")elseif t.reason=="does not have a necessary raw material"then TriggerEvent("Notify","negado","Não possui matéria prima!")end else TriggerEvent("cancelando",true)animApi.playAnim(false,{{"anim@amb@business@coc@coc_packing_hi@","full_cycle_v1_pressoperator"}},true)Citizen.Wait(10000)TriggerEvent("Notify","sucesso","Craftou x"..t.giveQtd.." "..t.giveItem.."!")animApi.stopAnim(false)TriggerEvent("cancelando",false)end else TriggerEvent("Notify","negado","Você não tem permissão!")end else local t=c.checkCraft(l.item,l.itemqtd,l.giveitem,l.giveqtd)if t.error then if t.reason=="there is no free space in the inventory"then TriggerEvent("Notify","negado","Espaço insuficiente!")elseif t.reason=="does not have a necessary raw material"then TriggerEvent("Notify","negado","Não possui matéria prima!")end else TriggerEvent("cancelando",true)animApi.playAnim(false,{{"anim@amb@business@coc@coc_packing_hi@","full_cycle_v1_pressoperator"}},true)Citizen.Wait(10000)TriggerEvent("Notify","sucesso","Craftou x"..t.giveQtd.." "..t.giveItem.."!")animApi.stopAnim(false)TriggerEvent("cancelando",false)end end end else e=false end end end;if j then i=1 else i=3000 end end end)function ToogleCraftWeaponMenu(u,v)SetNuiFocus(u,u)if u then SendNUIMessage({open=u,data=v})else SendNUIMessage({open=u})end end;Citizen.CreateThread(function()for k,l in pairs(d.peds)do local m=GetHashKey(k)RequestModel(m)while not HasModelLoaded(m)do Wait(0)end;_Npc=CreatePed(4,l[5],l[1],l[2],l[3]-0.999,l[4],true,true)FreezeEntityPosition(_Npc,true)SetEntityInvincible(_Npc,true)SetBlockingOfNonTemporaryEvents(_Npc,true)end end)RegisterNUICallback("closeMenu",function()ToogleCraftWeaponMenu(false)end)RegisterNUICallback("craftWeapon",function(w)local t=c.checkCraftWeapon(w._WeaponName,w._WeaponNameItem,w._Price)if not t.error then TriggerEvent("Notify","sucesso","Você fabricou uma "..w._WeaponName.."!")else TriggerEvent("Notify","negado","Você não tem aço suficiente!")end end)local x={"motoclub","antena"}local y=3000;local z=false;Citizen.CreateThread(function()while true do for k,l in pairs(d.craftWeapons)do if k==1 then z=false end;local m=GetPlayerPed(-1)local n,o,p=table.unpack(GetEntityCoords(m))local A,B,C=l.coords[1],l.coords[2],l.coords[3]local q,r=GetGroundZFor_3dCoord(A,B,C)local s=GetDistanceBetweenCoords(A,B,r,n,o,p,true)if s<20 then z=true;DrawMarker(2,A,B,C,0,0,0,0,0,0,0.5,0.5,0.5,255,255,0,30,1,1,1,1)DrawText3D(A,B,C+0.6,"FABRICAR ARMA",1.0,4,100)if s<1.5 then if IsControlJustPressed(0,38)then local D=false;for E=1,#x do if c.hasGroup(x[E])then D=true end end;if D then ToogleCraftWeaponMenu(true,l.data)else TriggerEvent("Notify","negado","Você não tem permissão!")end end end end end;if z then y=1 else y=3000 end;Citizen.Wait(y)end end)function newNotify(F,G,H,I)if G~=-1 then SetNotificationBackgroundColor(G)end;SetNotificationTextEntry(F)for J,K in ipairs(H)do AddTextComponentSubstringPlayerName(K)end;DrawNotification(false,false)if I then PlaySoundFrontend(-1,"Menu_Accept","Phone_SoundSet_Default",1)end end;function notify(L)newNotify("STRING",11,{""..L},true)end;RegisterCommand("rembag",function(M,N,O)local t=c.remBag()if not t then return TriggerEvent("Notify","negado","Você deve esvaziar seu inventario para 5kg's!")end;SetPedComponentVariation(GetPlayerPed(-1),7,0,0,2)end)function DrawText3D(n,o,p,P,Q,R,S)local T,A,B=World3dToScreen2d(n,o,p)local U,V,W=table.unpack(GetGameplayCamCoords())local X=GetDistanceBetweenCoords(U,V,W,n,o,p,1)local Y=1/X*Q;local Z=1/GetGameplayCamFov()*100;local Y=Y*Z;if T then SetTextScale(0.0*Y,1.1*Y)SetTextFont(R)SetTextProportional(1)SetTextColour(255,255,255,S)SetTextDropshadow(0,0,0,0,255)SetTextEdge(2,0,0,0,150)SetTextDropShadow()SetTextOutline()SetTextEntry("STRING")SetTextCentre(1)AddTextComponentString(P)DrawText(A,B)end end;function drawTxt(P,R,n,o,Y,_,a0,a1,a2)SetTextFont(R)SetTextScale(Y,Y)SetTextColour(_,a0,a1,a2)SetTextOutline()SetTextCentre(1)SetTextEntry("STRING")AddTextComponentString(P)DrawText(n,o)end
if minetest.get_modpath("lucky_block") then lucky_block:add_blocks({ {"dro", {"mobs:meat_raw"}, 5}, {"dro", {"mobs:meat"}, 5}, {"dro", {"mobs:nametag"}, 1}, {"dro", {"mobs:leather"}, 5}, {"dro", {"default:stick"}, 10}, {"dro", {"mobs:net"}, 1}, {"dro", {"mobs:lasso"}, 1}, {"dro", {"mobs:shears"}, 1}, {"dro", {"mobs:protector"}, 1}, {"dro", {"mobs:fence_wood"}, 10}, {"dro", {"mobs:fence_top"}, 12}, {"lig"} }) end
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local UF = E:GetModule('UnitFrames'); --Cache global variables --Lua functions local random = random --WoW API / Variables local CreateFrame = CreateFrame local UnitIsTapDenied = UnitIsTapDenied local UnitReaction = UnitReaction local UnitIsPlayer = UnitIsPlayer local UnitClass = UnitClass local UnitIsDeadOrGhost = UnitIsDeadOrGhost local _, ns = ... local ElvUF = ns.oUF assert(ElvUF, "ElvUI was unable to locate oUF.") function UF:Construct_HealthBar(frame, bg, text, textPos) local health = CreateFrame('StatusBar', nil, frame) UF.statusbars[health] = true health:SetFrameLevel(10) --Make room for Portrait and Power which should be lower by default health.PostUpdate = self.PostUpdateHealth if bg then health.bg = health:CreateTexture(nil, 'BORDER') health.bg:SetAllPoints() health.bg:SetTexture(E.media.blankTex) health.bg.multiplier = 0.25 end if text then health.value = frame.RaisedElementParent:CreateFontString(nil, 'OVERLAY') UF:Configure_FontString(health.value) local x = -2 if textPos == 'LEFT' then x = 2 end health.value:Point(textPos, health, textPos, x, 0) end health.colorTapping = true health.colorDisconnected = true health:CreateBackdrop('Default', nil, nil, self.thinBorders, true) return health end function UF:Configure_HealthBar(frame) if not frame.VARIABLES_SET then return end local db = frame.db local health = frame.Health health.Smooth = self.db.smoothbars --Text if db.health and health.value then local attachPoint = self:GetObjectAnchorPoint(frame, db.health.attachTextTo) health.value:ClearAllPoints() health.value:Point(db.health.position, attachPoint, db.health.position, db.health.xOffset, db.health.yOffset) frame:Tag(health.value, db.health.text_format) end --Colors health.colorSmooth = nil health.colorHealth = nil health.colorClass = nil health.colorReaction = nil if db.colorOverride and db.colorOverride == "FORCE_ON" then health.colorClass = true health.colorReaction = true elseif db.colorOverride and db.colorOverride == "FORCE_OFF" then if self.db.colors.colorhealthbyvalue == true then health.colorSmooth = true else health.colorHealth = true end else if self.db.colors.healthclass ~= true then if self.db.colors.colorhealthbyvalue == true then health.colorSmooth = true else health.colorHealth = true end else health.colorClass = (not self.db.colors.forcehealthreaction) health.colorReaction = true end end --Position health:ClearAllPoints() health.WIDTH = frame.db.width health.HEIGHT = frame.db.height if frame.ORIENTATION == "LEFT" then health:Point("TOPRIGHT", frame, "TOPRIGHT", -frame.BORDER - frame.SPACING - (frame.PVPINFO_WIDTH or 0), -frame.BORDER - frame.SPACING - frame.CLASSBAR_YOFFSET) if frame.USE_POWERBAR_OFFSET then health:Point("TOPRIGHT", frame, "TOPRIGHT", -frame.BORDER - frame.SPACING - frame.POWERBAR_OFFSET, -frame.BORDER - frame.SPACING - frame.CLASSBAR_YOFFSET) health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.PORTRAIT_WIDTH + frame.BORDER + frame.SPACING, frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) elseif frame.POWERBAR_DETACHED or not frame.USE_POWERBAR or frame.USE_INSET_POWERBAR then health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.PORTRAIT_WIDTH + frame.BORDER + frame.SPACING, frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) elseif frame.USE_MINI_POWERBAR then health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.PORTRAIT_WIDTH + frame.BORDER + frame.SPACING, frame.SPACING + (frame.POWERBAR_HEIGHT/2)) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.SPACING + frame.POWERBAR_HEIGHT / 2) else health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.PORTRAIT_WIDTH + frame.BORDER + frame.SPACING, frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) end elseif frame.ORIENTATION == "RIGHT" then health:Point("TOPLEFT", frame, "TOPLEFT", frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0), -frame.BORDER - frame.SPACING - frame.CLASSBAR_YOFFSET) if frame.USE_POWERBAR_OFFSET then health:Point("TOPLEFT", frame, "TOPLEFT", frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET, -frame.BORDER - frame.SPACING - frame.CLASSBAR_YOFFSET) health:Point("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -frame.PORTRAIT_WIDTH - frame.BORDER - frame.SPACING, frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) elseif frame.POWERBAR_DETACHED or not frame.USE_POWERBAR or frame.USE_INSET_POWERBAR then health:Point("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -frame.PORTRAIT_WIDTH - frame.BORDER - frame.SPACING, frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) elseif frame.USE_MINI_POWERBAR then health:Point("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -frame.PORTRAIT_WIDTH - frame.BORDER - frame.SPACING, frame.SPACING + (frame.POWERBAR_HEIGHT/2)) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.SPACING + frame.POWERBAR_HEIGHT / 2) else health:Point("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -frame.PORTRAIT_WIDTH - frame.BORDER - frame.SPACING, frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) end elseif frame.ORIENTATION == "MIDDLE" then health:Point("TOPRIGHT", frame, "TOPRIGHT", -frame.BORDER - frame.SPACING - (frame.PVPINFO_WIDTH or 0), -frame.BORDER - frame.SPACING - frame.CLASSBAR_YOFFSET) if frame.USE_POWERBAR_OFFSET then health:Point("TOPRIGHT", frame, "TOPRIGHT", -frame.BORDER - frame.SPACING - frame.POWERBAR_OFFSET, -frame.BORDER - frame.SPACING - frame.CLASSBAR_YOFFSET) health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET, frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.POWERBAR_OFFSET) elseif frame.POWERBAR_DETACHED or not frame.USE_POWERBAR or frame.USE_INSET_POWERBAR then health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.BORDER + frame.SPACING, frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) elseif frame.USE_MINI_POWERBAR then health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.BORDER + frame.SPACING, frame.SPACING + (frame.POWERBAR_HEIGHT/2)) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.SPACING + frame.POWERBAR_HEIGHT / 2) else health:Point("BOTTOMLEFT", frame, "BOTTOMLEFT", frame.PORTRAIT_WIDTH + frame.BORDER + frame.SPACING, frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) health.WIDTH = health.WIDTH - (frame.BORDER + frame.SPACING + (frame.PVPINFO_WIDTH or 0)) - (frame.BORDER + frame.SPACING + frame.PORTRAIT_WIDTH) health.HEIGHT = health.HEIGHT - (frame.BORDER + frame.SPACING + frame.CLASSBAR_YOFFSET) - (frame.BORDER + frame.SPACING + frame.BOTTOM_OFFSET) end end health.bg:ClearAllPoints() if not frame.USE_PORTRAIT_OVERLAY then health.bg:SetParent(health) health.bg:SetAllPoints() else health.bg:Point('BOTTOMLEFT', health:GetStatusBarTexture(), 'BOTTOMRIGHT') health.bg:Point('TOPRIGHT', health) health.bg:SetParent(frame.Portrait.overlay) end if db.health then if db.health.reverseFill then health:SetReverseFill(true) else health:SetReverseFill(false) end --Party/Raid Frames allow to change statusbar orientation if db.health.orientation then health:SetOrientation(db.health.orientation) end --Party/Raid Frames can toggle frequent updates if db.health.frequentUpdates then health.frequentUpdates = db.health.frequentUpdates end if db.health.bgUseBarTexture then health.bg:SetTexture(E.LSM:Fetch('statusbar', E.private.general.normTex)) end end --Transparency Settings UF:ToggleTransparentStatusBar(UF.db.colors.transparentHealth, frame.Health, frame.Health.bg, (frame.USE_PORTRAIT and frame.USE_PORTRAIT_OVERLAY) ~= true, nil, (db.health and db.health.reverseFill)) --Highlight Texture UF:Configure_HighlightGlow(frame) frame:UpdateElement("Health") end function UF:GetHealthBottomOffset(frame) local bottomOffset = 0 if frame.USE_POWERBAR and not frame.POWERBAR_DETACHED and not frame.USE_INSET_POWERBAR then bottomOffset = bottomOffset + frame.POWERBAR_HEIGHT - (frame.BORDER-frame.SPACING) end if frame.USE_INFO_PANEL then bottomOffset = bottomOffset + frame.INFO_PANEL_HEIGHT - (frame.BORDER-frame.SPACING) end return bottomOffset end function UF:PostUpdateHealth(unit, min, max) local parent = self:GetParent() if parent.isForced then min = random(1, max) self:SetValue(min) end if parent.ResurrectIndicator then parent.ResurrectIndicator:SetAlpha(min == 0 and 1 or 0) end -- Health by Value local colors = E.db.unitframe.colors; local multiplier = colors.healthmultiplier if (((colors.healthclass == true and colors.colorhealthbyvalue == true) or (colors.colorhealthbyvalue and parent.isForced)) and not UnitIsTapDenied(unit)) then local r, g, b = self:GetStatusBarColor() local newr, newg, newb = ElvUF:ColorGradient(min, max, 1, 0, 0, 1, 1, 0, r, g, b) self:SetStatusBarColor(newr, newg, newb) if multiplier then self.bg:SetVertexColor(newr * multiplier, newg * multiplier, newb * multiplier) end end -- Class Backdrop if self.bg and colors.classbackdrop then local reaction = UnitReaction(unit, 'player') local t if UnitIsPlayer(unit) then local _, class = UnitClass(unit) t = parent.colors.class[class] elseif reaction then t = parent.colors.reaction[reaction] end if t then self.bg:SetVertexColor(t[1] * multiplier , t[2] * multiplier, t[3] * multiplier) end end -- Custom Backdrop if self.bg and colors.customhealthbackdrop then local backdrop = colors.health_backdrop self.bg:SetVertexColor(backdrop.r, backdrop.g, backdrop.b) end if self.bg and colors.useDeadBackdrop and UnitIsDeadOrGhost(unit) then local backdrop = colors.health_backdrop_dead self.bg:SetVertexColor(backdrop.r, backdrop.g, backdrop.b) end end
----------------------------------- -- Ability: Chakra -- Cures certain status effects and restores a small amount of HP to user. -- Obtained: Monk Level 35 -- Recast Time: 5:00 -- Duration: Instant ----------------------------------- require("scripts/globals/status") ----------------------------------- local ChakraStatusEffects = { POISON = 0, -- Removed by default BLINDNESS = 0, -- Removed by default PARALYSIS = 1, DISEASE = 2, PLAGUE = 4 } function onAbilityCheck(player, target, ability) return 0, 0 end function onUseAbility(player, target, ability) local chakraRemoval = player:getMod(tpz.mod.CHAKRA_REMOVAL) for k, v in pairs(ChakraStatusEffects) do if bit.band(chakraRemoval, v) == v then player:delStatusEffect(tpz.effect[k]) end end local recover = player:getStat(tpz.mod.VIT) * (2 + player:getMod(tpz.mod.CHAKRA_MULT) / 10) -- TODO: Figure out "function of level" addition (August 2017 update) player:setHP(player:getHP() + recover) local merits = player:getMerit(tpz.merit.INVIGORATE) if merits > 0 then if player:hasStatusEffect(tpz.effect.REGEN) then player:delStatusEffect(tpz.effect.REGEN) end player:addStatusEffect(tpz.effect.REGEN, 10, 0, merits, 0, 0, 1) end return recover end
function OnEnterWorld(event, pPlayer) local ServerName = ServerName pPlayer:SendAreaTriggerMessage("Welcome to [" .. ServerName .. "]! Pay us a visit at: [Website.web]") end end RegisterServerHook (4, "OnEnterWorld")
require("deepcore/std/class") ---@class DeepCoreStateTransition DeepCoreStateTransition = class() ---@param origin DeepCoreState ---@param next DeepCoreState ---@param transition_policy DeepCoreTransitionPolicy function DeepCoreStateTransition:new(origin, next, transition_policy) ---@private self.origin = origin self.origin.on_enter:attach_listener(self.on_origin_entered, self) table.insert(self.origin.transitions, self) ---@private self.next = next ---@private self.transition_policy = transition_policy end ---@private ---@param state_context table<string, any> function DeepCoreStateTransition:on_origin_entered(state_context) self.transition_policy:on_origin_entered(state_context) end ---@param state_context table<string, any> ---@return boolean function DeepCoreStateTransition:should_transition(state_context) return self.transition_policy:should_transition(state_context) end ---@param state_context table<string, any> function DeepCoreStateTransition:transition(state_context) self.transition_policy:on_transition(state_context) end ---@return DeepCoreState function DeepCoreStateTransition:get_next_state() return self.next end
--[[-- This script is adpated from grid_sheet.c which has the following header. Haru Free PDF Library 2.0.0 Copyright (c) 1999-2006 Takeshi Kanno <takeshi_kanno@est.hi-ho.ne.jp> Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. It is provided "as is" without express or implied warranty. --]]-- local hpdf = require "hpdf" function hpdf.print_grid(pdf, page) local height = hpdf.Page_GetHeight(page) local width = hpdf.Page_GetWidth(page) local font = hpdf.GetFont(pdf, "Helvetica") hpdf.Page_SetFontAndSize(page, font, 5) hpdf.Page_SetGrayFill(page, 0.5) hpdf.Page_SetGrayStroke(page, 0.8) -- Draw horizontal lines local y = 0 while y < height do if y % 10 == 0 then hpdf.Page_SetLineWidth(page, 0.5) else if hpdf.Page_GetLineWidth(page) ~= 0.25 then hpdf.Page_SetLineWidth(page, 0.25) end -- if end -- if hpdf.Page_MoveTo(page, 0, y) hpdf.Page_LineTo(page, width, y) hpdf.Page_Stroke(page) if (y % 10 == 0) and (y > 0) then hpdf.Page_SetGrayStroke(page, 0.5) hpdf.Page_MoveTo(page, 0, y) hpdf.Page_LineTo(page, 5, y) hpdf.Page_Stroke(page) hpdf.Page_SetGrayStroke(page, 0.8) end -- if y = y + 5 end -- while -- Draw vertical lines local x = 0 while x < width do if x % 10 == 0 then hpdf.Page_SetLineWidth(page, 0.5) else if hpdf.Page_GetLineWidth(page) ~= 0.25 then hpdf.Page_SetLineWidth(page, 0.25) end -- if end -- if hpdf.Page_MoveTo(page, x, 0) hpdf.Page_LineTo(page, x, height) hpdf.Page_Stroke(page) if (x % 50 == 0) and (x > 0) then hpdf.Page_SetGrayStroke(page, 0.5) hpdf.Page_MoveTo(page, x, 0) hpdf.Page_LineTo(page, x, 5) hpdf.Page_Stroke(page) hpdf.Page_MoveTo(page, x, height) hpdf.Page_LineTo(page, x, height - 5) hpdf.Page_Stroke(page) hpdf.Page_SetGrayStroke(page, 0.8) end -- if x = x + 5 end -- while -- Draw horizontal text y = 0 while y < height do if (y % 10 == 0) and (y > 0) then hpdf.Page_BeginText(page) hpdf.Page_MoveTextPos(page, 5, y - 2) hpdf.Page_ShowText(page, y) hpdf.Page_EndText(page) end -- if y = y + 5 end -- while -- Draw vertical text x = 0 while x < width do if (x % 50 == 0) and (x > 0) then hpdf.Page_BeginText(page) hpdf.Page_MoveTextPos(page, x, 5) hpdf.Page_ShowText(page, x) hpdf.Page_EndText(page) hpdf.Page_BeginText(page) hpdf.Page_MoveTextPos(page, x, height - 10) hpdf.Page_ShowText(page, x) hpdf.Page_EndText(page) end -- if x = x + 5 end -- while hpdf.Page_SetGrayFill(page, 0) hpdf.Page_SetGrayStroke(page, 0) end -- hpdf.print_grid function save_to_file(pdf, script_name) script_name = string.gsub(script_name, "%.%w*$", "") .. ".pdf" if 0 ~= hpdf.SaveToFile(pdf, script_name) then io.stderr:write('Error writing to ', script_name, '\n') end end
-------------------------------------------------------------------------------- -- TermometrWiFi main file -------------------------------------------------------------------------------- local CONFIG_FILE = "eus_params.lua" local WIFI_TIMEOUT = 20000 local OW_PIN = 3 local LED_PIN = 10 local BUTTON_PIN = 4 local UART_BAUDRATE = 115200 local config = nil -- Uncomment it if you want to just see tempreature without sending -- TESTING = 1 if not TESTING then TESTING = 0 end local function do_sleep() local sleep_time = config.sleep_time if TESTING == 1 then sleep_time = 5000000 end print(string.format("DeepSleep for %d [us]", sleep_time)) node.dsleep(sleep_time, 3) end -- GPIO module? pin as module member local TIMER_COUNT = 3 local button_pin = BUTTON_PIN local function check_button() if gpio.read(button_pin) == 1 then return false end for i = 0, TIMER_COUNT do print("Button preset...") tmr.delay(1000000) if gpio.read(button_pin) == 1 then return false end end print("Button confirmed!") return true end local function setup_gpio_factory_reset() gpio.mode(button_pin, gpio.INPUT, gpio.PULLUP) end local function button_int_handler(level, when, eventcount) print("INT...") setup_gpio_factory_reset() if not tmr.create():alarm(500, tmr.ALARM_SINGLE, function() node.restart() end) then node.restart() end end local function setup_gpio_restart() gpio.mode(button_pin, gpio.INT, gpio.PULLUP) gpio.trig(button_pin, "down", button_int_handler) end local function send_temp(temperature) -- conection to thingspeak.com print("Sending data to thingspeak.com") conn = net.createConnection(net.TCP, 0) conn:on( "receive", function(conn, payload) print(payload) end ) -- api.thingspeak.com 184.106.153.149 conn:connect(80, "184.106.153.149") conn:send("GET /update?key=" .. config.write_key .. "&field" .. config.field_nbr .. "=" .. temperature .. " HTTP/1.1\r\n") conn:send("Host: api.thingspeak.com\r\n") conn:send("Accept: */*\r\n") conn:send("User-Agent: Mozilla/4.0 (compatible; esp8266 Lua; Windows NT 5.1)\r\n") conn:send("\r\n") conn:on( "sent", function(conn) print("Closing connection") conn:close() do_sleep() end ) conn:on( "disconnection", function(conn) print("Got disconnection...") do_sleep() end ) end local function handle_temp(temp) package.loaded["ds18b20"] = nil local sensor_found = false for addr, temp in pairs(temp) do temperature = temp sensor_found = true end if not sensor_found then print("Sensor not found.") do_sleep() return end print(string.format("Temp: %s C", temperature)) if TESTING == 0 then send_temp(temperature) else do_sleep() end end local function meassure_temperatur() ds18b20 = require("ds18b20") ds18b20:read_temp(handle_temp, OW_PIN, ds18b20.C, nil) end local function led_blink() local pin = gpio.read(LED_PIN) pin = pin == 1 and 0 or pin == 0 and 1 gpio.write(LED_PIN, pin) end -- LED is connected with TX0 on board, -- blinking will stop transmitting on UART local function start_blinking(period) blink_timer = tmr.create() if blink_timer then gpio.mode(LED_PIN, gpio.OUTPUT, gpio.PULLUP) blink_timer:alarm(period, tmr.ALARM_AUTO, function() led_blink() end) end end local function stop_blinking() if blink_timer then blink_timer.unregister() blink_timer = nil end uart.setup(0, UART_BAUDRATE, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1) end local function got_ip(info) stop_blinking() IP, netmask, gateway = wifi.sta.getip() print(string.format("ip: %s, mask: %s, gw: %s", info.IP, info.netmask, info.gateway)) wifi.eventmon.unregister(wifi.eventmon.STA_GOT_IP) meassure_temperatur() end local function wifi_timeout() print("WiFi timeout...") do_sleep() end local function configure_wifi() print("Configuring wifi...") -- Watchdog tmr.create():alarm(300000, tmr.ALARM_SINGLE, function() node.restart() end) start_blinking(500) -- wifi.setmode(wifi.STATIONAP) -- wifi.ap.config({ssid="TermometrWiFi", auth=wifi.OPEN}) -- enduser_setup.manual(true) enduser_setup.start( function() print("Connected to wifi as: " .. wifi.sta.getip()) tmr.create():alarm(3000, tmr.ALARM_SINGLE, function() node.restart() end) end, function(err, str) print("enduser_setup: Err #" .. err .. ": " .. str) end, print -- Lua print function can serve as the debug callback ) end local function factory_reset() print("Factory reset...") wifi.sta.disconnect() wifi.sta.clearconfig() file.remove(CONFIG_FILE) configure_wifi() end local function start() uart.setup(0, UART_BAUDRATE, 8, uart.PARITY_NONE, uart.STOPBITS_1, 1) setup_gpio_factory_reset() if check_button() or not file.exists(CONFIG_FILE) then factory_reset() else setup_gpio_restart() config = dofile(CONFIG_FILE) if not config then factory_reset() end my_wifi = require("my_wifi") my_wifi:init_wifi(config.wifi_ssid, config.wifi_password, got_ip, WIFI_TIMEOUT, wifi_timeout) end end start()
return { -- Base API tests "test_string.lua", "base/test_aliasing.lua", "base/test_binmodules.lua", "base/test_configset.lua", "base/test_context.lua", "base/test_criteria.lua", "base/test_detoken.lua", "base/test_include.lua", "base/test_module_loader.lua", "base/test_option.lua", "base/test_os.lua", "base/test_override.lua", "base/test_path.lua", "base/test_premake_command.lua", "base/test_table.lua", "base/test_tree.lua", "base/test_uuid.lua", "base/test_versions.lua", "base/test_http.lua", "base/test_json.lua", -- Workspace object tests "workspace/test_eachconfig.lua", "workspace/test_location.lua", "workspace/test_objdirs.lua", -- Project object tests "project/test_config_maps.lua", "project/test_eachconfig.lua", "project/test_getconfig.lua", "project/test_location.lua", "project/test_sources.lua", "project/test_vpaths.lua", -- Configuration object tests "config/test_linkinfo.lua", "config/test_links.lua", "config/test_targetinfo.lua", -- Baking tests "oven/test_filtering.lua", "oven/test_objdirs.lua", -- API tests "api/test_boolean_kind.lua", "api/test_containers.lua", "api/test_directory_kind.lua", "api/test_list_kind.lua", "api/test_path_kind.lua", "api/test_register.lua", "api/test_string_kind.lua", "api/test_table_kind.lua", "api/test_deprecations.lua", -- Control system tests "test_premake.lua", "base/test_validation.lua", -- -- Toolset tests "tools/test_dotnet.lua", "tools/test_gcc.lua", "tools/test_msc.lua", }
--[[This is a lua script for use in conky. It will create a binary clock behind the full space of whatever conky it's loaded into. You will need to add the following to your .conkyrc before the TEXT section: lua_load $HOME/.config/conky/LUA/Full_Conky_Binary_Clock.lua (or wherever you put your luas) lua_draw_hook_pre conky_FCBC This is my very first lua script! It couldn't have been done without the help of the wonderful guide on the #! forums. http://crunchbang.org/forums/viewtopic.php?id=17246 ]] require 'cairo' function conky_FCBC() if conky_window == nil then return end w=conky_window.width h=conky_window.height local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, w, h) cr = cairo_create(cs) ---------------------Color Settings red=128/256 green=128/256 --replace the first number with it's RGBA value blue=128/256 --default = 128,128,128,192 alpha=192/256 ---------------------Box Settings boxw=w/4 --desired box width, default to w/4 for an even distribution with w/16 spacing between boxes boxh=h/7 --desired box height, default to h/7 for an even distribution with h/49 spacing between boxes XH=(1/16)*w --X-position of the hour slot boxes XM=(2/16)*w+(1)*boxw --X-position of the minute slot boxes XS=(3/16)*w+(2)*boxw --X-position of the second slot boxes Y32=(1/49)*h --Y-position of the 32 slot boxes Y16=(2/49)*h+(1)*boxh --Y-position of the 16 slot boxes Y8=(3/49)*h+(2)*boxh --Y-position of the 8 slot boxes Y4=(4/49)*h+(3)*boxh --Y-position of the 4 slot boxes Y2=(5/49)*h+(4)*boxh --Y-position of the 2 slot boxes Y1=(6/49)*h+(5)*boxh --Y-position of the 1 slot boxes ---------------------Time Setting Hours,Mins,Secs=tonumber(os.date("%k")),tonumber(os.date("%M")),tonumber(os.date("%S")) ---------------------Creating boxes -----------------------------------Hour boxes if Hours - 16 >= 0 then cairo_rectangle(cr,XH,Y16,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) HDet = Hours - 16 else HDet = Hours end if HDet - 8 >= 0 then cairo_rectangle(cr,XH,Y8,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) HDet = HDet - 8 end if HDet - 4 >= 0 then cairo_rectangle(cr,XH,Y4,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) HDet = HDet - 4 end if HDet - 2 >= 0 then cairo_rectangle(cr,XH,Y2,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) HDet = HDet - 2 end if HDet - 1 >=0 then cairo_rectangle(cr,XH,Y1,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) end -----------------------------------Minute Boxes if Mins - 32 >= 0 then cairo_rectangle(cr,XM,Y32,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) MDet = Mins - 32 else MDet = Mins end if MDet - 16 >=0 then cairo_rectangle(cr,XM,Y16,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) MDet = MDet - 16 end if MDet - 8 >=0 then cairo_rectangle(cr,XM,Y8,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) MDet = MDet - 8 end if MDet - 4 >=0 then cairo_rectangle(cr,XM,Y4,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) MDet = MDet - 4 end if MDet - 2 >=0 then cairo_rectangle(cr,XM,Y2,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) MDet = MDet - 2 end if MDet - 1 >=0 then cairo_rectangle(cr,XM,Y1,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) end -----------------------------------Second Boxes if Secs - 32 >= 0 then cairo_rectangle(cr,XS,Y32,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) SDet = Secs - 32 else SDet = Secs end if SDet - 16 >= 0 then cairo_rectangle(cr,XS,Y16,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) SDet = SDet - 16 end if SDet - 8 >= 0 then cairo_rectangle(cr,XS,Y8,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) SDet = SDet - 8 end if SDet - 4 >= 0 then cairo_rectangle(cr,XS,Y4,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) SDet = SDet - 4 end if SDet - 2 >= 0 then cairo_rectangle(cr,XS,Y2,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) SDet = SDet - 2 end if SDet - 1 >= 0 then cairo_rectangle(cr,XS,Y1,boxw,boxh) cairo_set_source_rgba(cr,red,green,blue,alpha) cairo_fill(cr) end ---------------------Finishing up cairo_destroy(cr) cairo_surface_destroy(cs) cr=nil end-- end main function
local label = [[ // || __ __ __ __ || | \ | \ | \| \ || | $$ __ __ _______ ______ | $$\ | $$| $$ || | $$ | \ | \ / \| \ | $$$\| $$| $$ || | $$ | $$ | $$| $$$$$$$ \$$$$$$\| $$$$\ $$| $$ || | $$ | $$ | $$| $$ / $$| $$\$$ $$| $$ || | $$_____| $$__/ $$| $$_____| $$$$$$$| $$ \$$$$| $$_____ || | $$ \\$$ $$ \$$ \\$$ $$| $$ \$$$| $$ \ || \$$$$$$$$ \$$$$$$ \$$$$$$$ \$$$$$$$ \$$ \$$ \$$$$$$$$ || Created by LucaNL#2230 ||]] function GetCurrentVersion() return GetResourceMetadata( GetCurrentResourceName(), "version" ) end PerformHttpRequest("https://version.lucadev.nl/CarWhitelist-FiveM/version.txt", function( err, text, headers ) Citizen.Wait(2000) print( label ) local curVer = GetCurrentVersion() print( " || Current version: " .. curVer ) if ( text ~= nil ) then print( " || Latest recommended version: " .. text .."\n ||" ) if ( text ~= curVer ) then print( " || ^1Your CarWhitelist version is outdated, please visit the FiveM forum page at https://forum.cfx.re/t/release-free-carwipe-fivem/4839898 to get the latest version.^0\n ||" ) else print( " || ^2CarWhitelist is up to date!\n^0 || \n \\\\\n" ) return end else print( " || ^1There was an error getting the latest version information.\n^0 || \n \\\\\n" ) end end)
-- simple chat with redis local server = require "resty.websocket.server" local redis = require "resty.redis" local channel_name = "chat" local msg_id = 0 --create connection local wb, err = server:new{ timeout = 10000, max_payload_len = 65535 } --create success if not wb then ngx.log(ngx.ERR, "failed to new websocket: ", err) return ngx.exit(444) end local push = function() -- --create redis local red = redis:new() red:set_timeout(5000) -- 1 sec local ok, err = red:connect("127.0.0.1", 6379) if not ok then ngx.log(ngx.ERR, "failed to connect redis: ", err) wb:send_close() return end --sub local res, err = red:subscribe(channel_name) if not res then ngx.log(ngx.ERR, "failed to sub redis: ", err) wb:send_close() return end -- loop : read from redis while true do local res, err = red:read_reply() if res then local item = res[3] local bytes, err = wb:send_text(tostring(msg_id).." "..item) if not bytes then -- better error handling ngx.log(ngx.ERR, "failed to send text: ", err) return ngx.exit(444) end msg_id = msg_id + 1 end end end local co = ngx.thread.spawn(push) --main loop while true do -- 获取数据 local data, typ, err = wb:recv_frame() -- 如果连接损坏 退出 if wb.fatal then ngx.log(ngx.ERR, "failed to receive frame: ", err) return ngx.exit(444) end if not data then local bytes, err = wb:send_ping() if not bytes then ngx.log(ngx.ERR, "failed to send ping: ", err) return ngx.exit(444) end ngx.log(ngx.ERR, "send ping: ", data) elseif typ == "close" then break elseif typ == "ping" then local bytes, err = wb:send_pong() if not bytes then ngx.log(ngx.ERR, "failed to send pong: ", err) return ngx.exit(444) end elseif typ == "pong" then ngx.log(ngx.ERR, "client ponged") elseif typ == "text" then --send to redis local red2 = redis:new() red2:set_timeout(1000) -- 1 sec local ok, err = red2:connect("127.0.0.1", 6379) if not ok then ngx.log(ngx.ERR, "failed to connect redis: ", err) break end local res, err = red2:publish(channel_name, data) if not res then ngx.log(ngx.ERR, "failed to publish redis: ", err) end end end wb:send_close() ngx.thread.wait(co)
--[[ Dummy action, used for taking no action. ]] return { { action = "none", }, }
local CorePackages = game:GetService("CorePackages") local Roact = require(CorePackages.Roact) local LineGraphHoverDisplay = require(script.Parent.LineGraphHoverDisplay) local Constants = require(script.Parent.Parent.Constants) local TEXT_COLOR = Constants.Color.Text local MAIN_LINE_COLOR = Constants.Color.HighlightBlue local LINE_WIDTH = Constants.GeneralFormatting.LineWidth local LINE_COLOR = Constants.GeneralFormatting.LineColor local POINT_WIDTH = Constants.Graph.PointWidth local POINT_OFFSET = Constants.Graph.PointOffset local GRAPH_PADDING = Constants.Graph.Padding local GRAPH_SCALE = Constants.Graph.Scale local GRAPH_Y_INNER_PADDING = Constants.Graph.InnerPaddingY local GRAPH_Y_INNER_SCALE = Constants.Graph.InnerScaleY local TEXT_PADDING = Constants.Graph.TextPadding local INVIS_LINE_THRESHOLD = 10 local LineGraph = Roact.Component:extend("LineGraph") function LineGraph:init() self.onGraphInputChanged = function(rbx, input) if input.UserInputType == Enum.UserInputType.MouseMovement then if not self.state.holdPos then self:setState({ inputPosition = input.Position, }) end end end self.onGraphInputEnded = function(rbx, input) if input.UserInputType == Enum.UserInputType.MouseMovement then if not self.state.holdPos then self:setState({ inputPosition = false }) end elseif input.UserInputType == Enum.UserInputType.MouseButton1 then self:setState({ holdPos = not self.state.holdPos }) end end self.graphRef = Roact.createRef() self.state = { selectedTimeStamps = {} } end function LineGraph:didUpdate() if self.state.absGraphSize ~= self.graphRef.current.AbsoluteSize then local absSize = self.graphRef.current.AbsoluteSize local absPos = self.graphRef.current.AbsolutePosition self:setState({ absGraphSize = absSize, absGraphPos = absPos, }) end end function LineGraph:didMount() local absSize = self.graphRef.current.AbsoluteSize local absPos = self.graphRef.current.AbsolutePosition self:setState({ absGraphSize = absSize, absGraphPos = absPos, }) end function LineGraph:render() local size = self.props.size local pos = self.props.pos local graphData = self.props.graphData local getX = self.props.getX local getY = self.props.getY local stringFormatX = self.props.stringFormatX local stringFormatY = self.props.stringFormatY local axisLabelX = self.props.axisLabelX local axisLabelY = self.props.axisLabelY local layoutOrder = self.props.layoutOrder local inputPosition = self.state.inputPosition local absGraphSize = self.state.absGraphSize local absGraphPos = self.state.absGraphPos local maxX = getX(graphData:back()) local minX = getX(graphData:front()) local maxY = self.props.maxY local minY = self.props.minY local hoverLineY local elements = {} if absGraphSize then local dataPoints = {} local dataIter = graphData:iterator() local data = dataIter:next() while data do local datapoint = getY(data) local time = getX(data) local xdivisor = maxX - minX local xPosition = xdivisor > 0 and (time - minX) / xdivisor or 0 local ydivisor = maxY - minY local yPosition = ydivisor > 0 and (datapoint - minY) / ydivisor or 1 local point = { X = xPosition, Y = yPosition, data = data, } table.insert(dataPoints, point) data = dataIter:next() end for i = 2, #dataPoints do local aX = dataPoints[i].X * absGraphSize.X local aY = dataPoints[i].Y * absGraphSize.Y * GRAPH_Y_INNER_SCALE local bX = dataPoints[i - 1].X * absGraphSize.X local bY = dataPoints[i - 1].Y * absGraphSize.Y * GRAPH_Y_INNER_SCALE if aX ~= bX then local vecPosX = (aX + bX) / 2 local vecPosY = (aY + bY) / 2 local vecX = aX - bX local vecY = aY - bY local length = math.sqrt((vecX * vecX) + (vecY * vecY)) local rot = math.deg(math.atan2(vecY, vecX)) table.insert(elements, Roact.createElement("Frame", { Size = UDim2.new(0, length, 0, LINE_WIDTH), Position = UDim2.new(0, vecPosX - length / 2, 1 - GRAPH_Y_INNER_PADDING, -vecPosY), BackgroundColor3 = MAIN_LINE_COLOR, BorderSizePixel = 0, Rotation = -rot, })) table.insert(elements, Roact.createElement("Frame", { Size = UDim2.new(0, POINT_WIDTH, 0, POINT_WIDTH), Position = UDim2.new(0, aX, 1 - GRAPH_Y_INNER_PADDING, -aY - POINT_OFFSET), BackgroundColor3 = MAIN_LINE_COLOR, BorderSizePixel = 0, })) if inputPosition then local hoverLineX = inputPosition.X - absGraphPos.X if hoverLineX < aX and bX < hoverLineX then local aDataX = getX(dataPoints[i].data) local bDataX = getX(dataPoints[i - 1].data) local aDataY = getY(dataPoints[i].data) local bDataY = getY(dataPoints[i - 1].data) local ratio = (hoverLineX - bX) / vecX hoverLineY = bY + (vecY * ratio) local hoverValX = (aDataX - bDataX) * ratio + bDataX local hoverValY = (aDataY - bDataY) * ratio + bDataY elements["HoverDetails"] = Roact.createElement(LineGraphHoverDisplay, { hoverLineX = hoverLineX, hoverLineY = hoverLineY, hoverValX = hoverValX, hoverValY = hoverValY, stringFormatX = stringFormatX, stringFormatY = stringFormatY, }) end end end end if #dataPoints > 0 then local lastEntryHeight = dataPoints[#dataPoints].Y * absGraphSize.Y * GRAPH_Y_INNER_SCALE local currValue = getY(dataPoints[#dataPoints].data) -- calc if the hovered Y position is very close to the last input entry (within the invis-threshold). -- If it's NOT within the "invis threshold" then we can show the line and "last entry value" local showCurrValue = not (hoverLineY and math.abs(lastEntryHeight - hoverLineY) < INVIS_LINE_THRESHOLD) -- calc if the hovered Y position is very close to the lower Y bound value (within the invis-threshold). -- If it's NOT within the "invis threshold" then we can show the lowerbound Y value local hoverLineCheck = (hoverLineY and math.abs(hoverLineY) < INVIS_LINE_THRESHOLD) local showLeastValue = not (hoverLineCheck or math.abs(lastEntryHeight) < INVIS_LINE_THRESHOLD) if showCurrValue then elements["LatestEntryLine"] = Roact.createElement("Frame", { Size = UDim2.new(1, TEXT_PADDING, 0, LINE_WIDTH), Position = UDim2.new(0, -TEXT_PADDING, 1 - GRAPH_Y_INNER_PADDING, -lastEntryHeight), BackgroundColor3 = LINE_COLOR, BackgroundTransparency = .5, BorderSizePixel = 0, }) elements["LatestEntryText"] = Roact.createElement("TextLabel", { Text = stringFormatY and stringFormatY(currValue) or currValue, TextColor3 = TEXT_COLOR, TextXAlignment = Enum.TextXAlignment.Right, Position = UDim2.new(0, -TEXT_PADDING - 2, 1 - GRAPH_Y_INNER_PADDING, -lastEntryHeight), BackgroundTransparency = 1, }) end if showLeastValue then elements["AxisTextY0"] = Roact.createElement("TextLabel", { Text = stringFormatY and stringFormatY(minY) or minY, TextColor3 = TEXT_COLOR, TextXAlignment = Enum.TextXAlignment.Right, Position = UDim2.new(0, -TEXT_PADDING - 2, 1 - GRAPH_Y_INNER_PADDING,0), BackgroundTransparency = 1, }) end elements["AxisX"] = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, LINE_WIDTH), Position = UDim2.new(0, 0, 1, 0), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) elements["AxisY"] = Roact.createElement("Frame", { Size = UDim2.new(0, LINE_WIDTH, 1, 0), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }) end end local axisTextPadding = 2 * TEXT_PADDING + 2 return Roact.createElement("Frame", { Size = size, Position = pos, BackgroundTransparency = 1, LayoutOrder = layoutOrder, }, { name = Roact.createElement("TextLabel", { Text = axisLabelY, TextColor3 = TEXT_COLOR, TextXAlignment = Enum.TextXAlignment.Left, Position = UDim2.new(GRAPH_PADDING, 0, GRAPH_PADDING, -TEXT_PADDING), BackgroundTransparency = 1, }), minX = Roact.createElement("TextLabel", { Text = stringFormatX and stringFormatX(minX) or minX, TextColor3 = TEXT_COLOR, TextXAlignment = Enum.TextXAlignment.Center, Position = UDim2.new(GRAPH_PADDING, 0, GRAPH_PADDING + GRAPH_SCALE, axisTextPadding), BackgroundTransparency = 1, }), maxX = Roact.createElement("TextLabel", { Text = stringFormatX and stringFormatX(maxX) or maxX, TextColor3 = TEXT_COLOR, TextXAlignment = Enum.TextXAlignment.Center, Position = UDim2.new(GRAPH_PADDING + GRAPH_SCALE, 0, GRAPH_PADDING + GRAPH_SCALE, axisTextPadding), BackgroundTransparency = 1, }), axisLabelX = Roact.createElement("TextLabel", { Text = axisLabelX, TextColor3 = TEXT_COLOR, TextXAlignment = Enum.TextXAlignment.Center, -- adding 2 to padding to push the label away from the axis line Position = UDim2.new(.5, 0, GRAPH_PADDING + GRAPH_SCALE, axisTextPadding), BackgroundTransparency = 1, }), graph = Roact.createElement("Frame", { Position = UDim2.new(GRAPH_PADDING, 0, GRAPH_PADDING, 0), Size = UDim2.new(GRAPH_SCALE, 0, GRAPH_SCALE, 0), BackgroundTransparency = 1, [Roact.Ref] = self.graphRef, [Roact.Event.InputChanged] = self.onGraphInputChanged, [Roact.Event.InputEnded] = self.onGraphInputEnded, }, elements) }) end return LineGraph
getglobal game getfield -1 ReplicatedStorage getfield -1 Functions getfield -1 TradeGem getfield -1 InvokeServer pushvalue -2 pushstring Green Gems pushstring 10000000000 pcall 3 1 0
TokoVoipConfig = { refreshRate = 100, -- Rate at which the data is sent to the TSPlugin networkRefreshRate = 2000, -- Rate at which the network data is updated/reset on the local ped playerListRefreshRate = 5000, -- Rate at which the playerList is updated latestVersion = "1.2.1", -- Version of the TS plugin required to play on the server distance = { 15, -- Normal speech distance in gta distance units 5, -- Whisper speech distance in gta distance units 40, -- Shout speech distance in gta distance units }, radioKey = Keys["CAPS"], -- Keybind used to talk on the radio keySwitchChannels = Keys["Z"], -- Keybind used to switch the radio channels keySwitchChannelsSecondary = Keys["LEFTSHIFT"], -- If set, both the keySwitchChannels and keySwitchChannelsSecondary keybinds must be pressed to switch the radio channels keyProximity = Keys["Z"], -- Keybind used to switch the proximity mode plugin_data = { -- TeamSpeak channel name used by the voip -- If the TSChannelWait is enabled, players who are currently in TSChannelWait will be automatically moved -- to the TSChannel once everything is running TSChannel = "SERVER_1", TSPassword = "Toko_pass", -- TeamSpeak channel password (can be empty) -- Optional: TeamSpeak waiting channel name, players wait in this channel and will be moved to the TSChannel automatically -- If the TSChannel is public and people can join directly, you can leave this empty and not use the auto-move TSChannelWait = "TokoVOIP Server Waiting Room IPS DESC", -- Blocking screen informations TSServer = "ts.rmog.us", -- TeamSpeak server address to be displayed on blocking screen TSChannelSupport = "S1: Waiting For Support", -- TeamSpeak support channel name displayed on blocking screen TSDownload = "http://forums.rmog.us", -- Download link displayed on blocking screen -- The following is purely TS client settings, to match tastes local_click_on = true, -- Is local click on sound active local_click_off = true, -- Is local click off sound active remote_click_on = false, -- Is remote click on sound active remote_click_off = true -- Is remote click off sound active } };
object_mobile_outbreak_undead_scientist_f_hum_06 = object_mobile_shared_outbreak_undead_scientist_f_hum_06:new { } ObjectTemplates:addTemplate(object_mobile_outbreak_undead_scientist_f_hum_06, "object/mobile/outbreak_undead_scientist_f_hum_06.iff")
local mapinfo = { name = "anyville", shortname = "anyville", description = "anyville", author = "PepeAmpere", version = "20190113", modtype = 3, --1=primary, 0=hidden, 3=map depend = {"Map Helper v1"}, replace = {}, maphardness = 1000, notDeformable = true, gravity = 130, tidalStrength = 18, maxMetal = 1.25, extractorRadius = 250.0, voidWater = false, autoShowMetal = true, smf = { -- minheight = -23, -- maxheight = 232 minheight = -44, maxheight = 466, smtFileName0 = "anyville20190113.smt", --minimapTex = "minimap.png", --smtFileName1 = "", --smtFileName.. = "", --smtFileNameN = "", }, sound = { --// Sets the _reverb_ preset (= echo parameters), --// passfilter (the direct sound) is unchanged. --// --// To get a list of all possible presets check: --// https://github.com/spring/spring/blob/master/rts/System/Sound/OpenAL/EFXPresets.cpp --// --// Hint: --// You can change the preset at runtime via: --// /tset UseEFX [1|0] --// /tset snd_eaxpreset preset_name (may change to a real cmd in the future) --// /tset snd_filter %gainlf %gainhf (may " " " " " " " " ) preset = "default", passfilter = { --// Note, you likely want to set these --// tags due to the fact that they are --// _not_ set by `preset`! --// So if you want to create a muffled --// sound you need to use them. gainlf = 1.0, gainhf = 1.0, }, reverb = { --// Normally you just want use the `preset` tag --// but you can use handtweak a preset if wanted --// with the following tags. --// To know their function & ranges check the --// official OpenAL1.1 SDK document. --density --diffusion --gain --gainhf --gainlf --decaytime --decayhflimit --decayhfratio --decaylfratio --reflectionsgain --reflectionsdelay --reflectionspan --latereverbgain --latereverbdelay --latereverbpan --echotime --echodepth --modtime --moddepth --airabsorptiongainhf --hfreference --lfreference --roomrollofffactor }, }, resources = { --grassBladeTex = "", --grassShadingTex = "", --detailTex = "", --specularTex = "", --splatDetailTex = "", --splatDistrTex = "", --skyReflectModTex = "", --detailNormalTex = "", --lightEmissionTex = "", }, splats = { texScales = {0.02, 0.02, 0.02, 0.02}, texMults = {1.0, 1.0, 1.0, 1.0}, }, atmosphere = { minWind = 5.0, maxWind = 20.0, -- fogStart = 0.1, -- fogEnd = 1.0, -- fogColor = {0.7, 0.7, 0.8}, -- sunColor = {1.0, 1.0, 1.0}, -- skyColor = {0.1, 0.15, 0.7}, -- skyDir = {0.0, 0.0, -1.0}, -- skyBox = "", -- cloudDensity = 0.5, -- cloudColor = {1.0, 1.0, 1.0}, }, grass = { bladeWaveScale = 1.0, bladeWidth = 0.32, bladeHeight = 4.0, bladeAngle = 1.57, bladeColor = {0.59, 0.81, 0.57}, --// does nothing when `grassBladeTex` is set }, lighting = { --// dynsun sunStartAngle = 0.0, sunOrbitTime = 1440.0, sunDir = {0.0, 1.0, 2.0, 1e9}, --// unit & ground lighting -- groundAmbientColor = {0.5, 0.5, 0.5}, -- groundDiffuseColor = {0.5, 0.5, 0.5}, -- groundSpecularColor = {0.1, 0.1, 0.1}, -- groundShadowDensity = 0.8, -- unitAmbientColor = {0.4, 0.4, 0.4}, -- unitDiffuseColor = {0.7, 0.7, 0.7}, -- unitSpecularColor = {0.7, 0.7, 0.7}, -- unitShadowDensity = 0.8, -- specularExponent = 100.0, }, water = { damage = 0.0, repeatX = 0.0, repeatY = 0.0, absorb = {0.0, 0.0, 0.0}, baseColor = {0.0, 0.0, 0.0}, minColor = {0.0, 0.0, 0.0}, ambientFactor = 1.0, diffuseFactor = 1.0, specularFactor = 1.0, specularPower = 20.0, planeColor = {0.0, 0.4, 0.0}, surfaceColor = {0.75, 0.8, 0.85}, surfaceAlpha = 0.55, diffuseColor = {1.0, 1.0, 1.0}, specularColor = {0.5, 0.5, 0.5}, fresnelMin = 0.2, fresnelMax = 0.8, fresnelPower = 4.0, reflectionDistortion = 1.0, blurBase = 2.0, blurExponent = 1.5, perlinStartFreq = 8.0, perlinLacunarity = 3.0, perlinAmplitude = 0.9, windSpeed = 1.0, --// does nothing yet shoreWaves = false, forceRendering = false, --// undefined == load them from resources.lua! --texture = "", --foamTexture = "", --normalTexture = "", --caustics = { -- "", -- "", --}, }, teams = { [0] = {startPos = {x = 8539, z = 1169}}, [1] = {startPos = {x = 8395, z = 15999}}, [2] = {startPos = {x = 4226, z = 356}}, [3] = {startPos = {x = 2069, z = 15762}}, [4] = {startPos = {x = 1126, z = 480}}, [5] = {startPos = {x = 10212, z = 16094}}, [6] = {startPos = {x = 1156, z = 419}}, [7] = {startPos = {x = 5291, z = 15890}}, }, terrainTypes = { [0] = { name = "Default", hardness = 1.0, receiveTracks = true, moveSpeeds = { tank = 1.0, kbot = 1.0, hover = 1.0, ship = 1.0, }, }, }, custom = { fog = { color = {0.26, 0.30, 0.41}, height = "80%", --// allows either absolue sizes or in percent of map's MaxHeight fogatten = 0.003, }, precipitation = { density = 30000, size = 1.5, speed = 50, windscale = 1.2, texture = 'LuaGaia/effects/snowflake.png', }, procedural = true, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Helper local function lowerkeys(ta) local fix = {} for i,v in pairs(ta) do if (type(i) == "string") then if (i ~= i:lower()) then fix[#fix+1] = i end end if (type(v) == "table") then lowerkeys(v) end end for i=1,#fix do local idx = fix[i] ta[idx:lower()] = ta[idx] ta[idx] = nil end end lowerkeys(mapinfo) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Map Options if (Spring) then local function tmerge(t1, t2) for i,v in pairs(t2) do if (type(v) == "table") then t1[i] = t1[i] or {} tmerge(t1[i], v) else t1[i] = v end end end -- make code safe in unitsync if (not Spring.GetMapOptions) then Spring.GetMapOptions = function() return {} end end function tobool(val) local t = type(val) if (t == 'nil') then return false elseif (t == 'boolean') then return val elseif (t == 'number') then return (val ~= 0) elseif (t == 'string') then return ((val ~= '0') and (val ~= 'false')) end return false end getfenv()["mapinfo"] = mapinfo local files = VFS.DirList("mapconfig/mapinfo/", "*.lua") table.sort(files) for i=1,#files do local newcfg = VFS.Include(files[i]) if newcfg then lowerkeys(newcfg) tmerge(mapinfo, newcfg) end end getfenv()["mapinfo"] = nil end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return mapinfo -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
--[[ ****************************************************************** * _____ ___ _ * * ( _ ) ( _`\ _ ( )_ * * | (_) | _ __ ___ | (_(_) ___ _ __ (_) _ _ | ,_) * * | _ |( '__)/'___)`\__ \ /'___)( '__)| |( '_`\ | | * * | | | || | ( (___ ( )_) |( (___ | | | || (_) )| |_ * * (_) (_)(_) `\____)`\____)`\____)(_) (_)| ,__/'`\__) * * | | * * (_) * * * * OpenSource Scripting Team * * <http://www.arcemu.org> * * * ****************************************************************** This software is provided as free and open source by the staff of The ArcScript Project, in accordance with the GPL license. This means we provide the software we have created freely and it has been thoroughly tested to work for the developers, but NO GUARANTEE is made it will work for you as well. Please give credit where credit is due, if modifying, redistributing and/or using this software. Thank you. Staff of ArcScript Project, Feb 2008 ~~End of License Agreement ############################################################# Special thanks: Janni, Recon, Nandi. -- ]] function Almonen_Talk(pUnit,Event) pUnit:SendChatMessage(12, 0, "In accordance with my divine calling, I must share these revealed truths to all who would hear.") pUnit:RegisterEvent("Almonen_Talk1",140000, 1) end function Almonen_Talk1(pUnit,Event) pUnit:SendChatMessage(12, 0, "It has been made known to me that inside each of us, the Light resides...") pUnit:RegisterEvent("Almonen_Talk2",80000, 1) end function Almonen_Talk2(pUnit,Event) pUnit:SendChatMessage(12, 0, "...that it is a gift, given freely to all naturally born beings.") pUnit:RegisterEvent("Almonen_Talk4",81000, 1) end function Almonen_Talk4(pUnit,Event) pUnit:SendChatMessage(12, 0, "It manifests itself as a feeling, small at first and easily ignored, that confirms truths and subtly prods one to do good.") pUnit:RegisterEvent("Almonen_Talk5",80000, 1) end function Almonen_Talk5(pUnit,Event) pUnit:SendChatMessage(12, 0, "Simple kindnesses, charitable deeds, service to those in need. These are all fruits of the Light.") pUnit:RegisterEvent("Almonen_Talk6",81000, 1) end function Almonen_Talk6(pUnit,Event) pUnit:SendChatMessage(12, 0, "It rewards those who heed its promptings with blessings, both seen and unseen.") pUnit:RegisterEvent("Almonen_Talk7",80000, 1) end function Almonen_Talk7(pUnit,Event) pUnit:SendChatMessage(12, 0, "Personal reservoirs of hope and faith are strengthened, and one's capacity for greater light increases.") pUnit:RegisterEvent("Almonen_Talk8",81000, 1) end function Almonen_Talk8(pUnit,Event) pUnit:SendChatMessage(12, 0, "Over the course of time, through obedience to the Light's guidance, one becomes more sensitive to its voice, and its power.") pUnit:RegisterEvent("Almonen_Talk9",80000, 1) end function Almonen_Talk9(pUnit,Event) pUnit:SendChatMessage(12, 0, "Great is the healing and blessing power of the Light's most diligent followers.") pUnit:RegisterEvent("Almonen_Talk10",81000, 1) end function Almonen_Talk10(pUnit,Event) pUnit:SendChatMessage(12, 0, "Sadly, there are those who wander through mortality in defiance of the Light.") pUnit:RegisterEvent("Almonen_Talk11",80000, 1) end function Almonen_Talk11(pUnit,Event) pUnit:SendChatMessage(12, 0, "From these the Light withdraws, until only darkness remains.") pUnit:RegisterEvent("Almonen_Talk12",80000, 1) end function Almonen_Talk12(pUnit,Event) pUnit:SendChatMessage(12, 0, "Where there is no light, despair, loathing and rage thrive.") pUnit:RegisterEvent("Almonen_Talk13",80000, 1) end function Almonen_Talk13(pUnit,Event) pUnit:SendChatMessage(12, 0, "We are born into a perilous age, where the forces of darkness are determined to bring about our destruction.") pUnit:RegisterEvent("Almonen_Talk14",80000, 1) end function Almonen_Talk14(pUnit,Event) pUnit:SendChatMessage(12, 0, "These are the times to find yourselves in unison with the Light.") pUnit:RegisterEvent("Almonen_Talk15",80000, 1) end function Almonen_Talk15(pUnit,Event) pUnit:SendChatMessage(12, 0, "Hear my words, and let the Light inside of you confirm the truth of them.") pUnit:RegisterEvent("Almonen_Talk16",80000, 1) end function Almonen_Talk16(pUnit,Event) pUnit:SendChatMessage(12, 0, "Embrace the light that is in you, my friends! Deny yourself all darkness...") pUnit:RegisterEvent("Almonen_Talk17",80000, 1) end function Almonen_Talk17(pUnit,Event) pUnit:SendChatMessage(12, 0, "We must endure these trying times faithfully, and one day we will find ourselves victorious.") pUnit:RegisterEvent("Almonen_Talk18",81000, 1) end function Almonen_Talk18(pUnit,Event) pUnit:SendChatMessage(12, 0, "By the naaru, may it be so.") pUnit:RegisterEvent("Almonen_Talk",240000, 1) end function Almonen_Died(pUnit, Event) pUnit:RemoveEvents() end RegisterUnitEvent(19216, 18, "Almonen_Talk") RegisterUnitEvent(19216, 4, "Almonen_Died")
--- Simplified getopt, based on Svenne Panne's Haskell GetOpt.<br> -- Usage: -- <ul> -- <li><code>prog = {< -- name = <progname>, -- [usage = <usage line>,] -- [options = { -- {{<name>[, ...]}, <desc>, [<type> [, <var>]]}, -- ... -- },] -- [banner = <banner string>,] -- [purpose = <purpose string>,] -- [notes = <additional notes>] -- }</code></li> -- <li>The <code>type</code> of option argument is one of <code>Req</code>(uired), -- <code>Opt</code>(ional)</li> -- <li>The <code>var</code>is a descriptive name for the option argument.</li> -- <li><code>getopt.processargs (prog)</code></li> -- <li>Options take a single dash, but may have a double dash.</li> -- <li>Arguments may be given as <code>-opt=arg</code> or <code>-opt arg</code>.</li> -- <li>If an option taking an argument is given multiple times, only the -- last value is returned; missing arguments are returned as 1.</li> -- </ul> -- getOpt, usageinfo and usage can be called directly (see -- below, and the example at the end). Set _DEBUG.std to a non-nil -- value to run the example. -- <ul> -- <li>TODO: Wrap all messages; do all wrapping in processargs, not -- usageinfo; use sdoc-like library (see string.format todos).</li> -- <li>TODO: Don't require name to be repeated in banner.</li> -- <li>TODO: Store version separately (construct banner?).</li> -- </ul> local io = require "std.io" local List = require "std.list" local Object = require "std.object" local string = require "std.string" local table = require "std.table" local M = { opt = {}, } local argtype = { Opt = true, Req = true } --- Perform argument processing -- @param argIn list of command-line args -- @param options options table -- @param stop_at_nonopt if true, stop option processing at first non-option -- @return table of remaining non-options -- @return table of option key-value list pairs -- @return table of error messages local function getopt (argIn, options, stop_at_nonopt) local noProcess = nil local argOut, optOut, errors = {[0] = argIn[0]}, {}, {} -- get an argument for option opt local function getArg (o, opt, arg, oldarg) if not argtype[o.type] then if arg ~= nil then table.insert (errors, "option `" .. opt .. "' doesn't take an argument") end else if arg == nil and argIn[1] and string.sub (argIn[1], 1, 1) ~= "-" then arg = argIn[1] table.remove (argIn, 1) end if arg == nil and o.type == "Req" then table.insert (errors, "option `" .. opt .. "' requires an argument `" .. o.var .. "'") return nil end end return arg or 1 -- make sure arg has a value end local function parseOpt (opt, arg) local o = options.name[opt] if o ~= nil then o = o or {name = {opt}} optOut[o.name[1]] = optOut[o.name[1]] or {} table.insert (optOut[o.name[1]], getArg (o, opt, arg, optOut[o.name[1]])) else table.insert (errors, "unrecognized option `-" .. opt .. "'") end end while argIn[1] do local v = argIn[1] table.remove (argIn, 1) local _, _, dash, opt = string.find (v, "^(%-%-?)([^=-][^=]*)") local _, _, arg = string.find (v, "=(.*)$") if not dash and stop_at_nonopt then noProcess = true end if v == "--" then noProcess = true elseif not dash or noProcess then -- non-option table.insert (argOut, v) else -- option parseOpt (opt, arg) end end return argOut, optOut, errors end -- Object that defines a single Option entry. local Option = Object {_init = {"name", "desc", "type", "var"}} --- Options table constructor: adds lookup tables for the option names local function makeOptions (t) local options, name = {}, {} local function appendOpt (v, nodupes) local dupe = false v = Option (v) for s in List.elems (v.name) do if name[s] then dupe = true end name[s] = v end if not dupe or nodupes ~= true then if dupe then io.warn ("duplicate option '%s'", s) end for s in List.elems (v.name) do name[s] = v end options = List.concat (options, {v}) end end for v in List.elems (t or {}) do appendOpt (v) end -- Unless they were supplied already, add version and help options appendOpt ({{"version", "V"}, "print version information, then exit"}, true) appendOpt ({{"help", "h"}, "print this help, then exit"}, true) options.name = name return options end --- Produce usage info for the given options -- @param header header string -- @param optDesc option descriptors -- @param pageWidth width to format to [78] -- @return formatted string local function usageinfo (header, optDesc, pageWidth) pageWidth = pageWidth or 78 -- Format the usage info for a single option -- @param opt the option table -- @return options -- @return description local function fmtOpt (opt) local function fmtName (o) return (#o > 1 and "--" or "-") .. o end local function fmtArg () if opt.type == "Req" then return "=" .. opt.var elseif opt.type == "Opt" then return "[=" .. opt.var .. "]" else return "" end end local textName = List.reverse (List.map (opt.name, fmtName)) textName[#textName] = textName[#textName] .. fmtArg () local indent = "" if #opt.name == 1 and #opt.name[1] > 1 then indent = " " end return {indent .. table.concat ({table.concat (textName, ", ")}, ", "), opt.desc} end local function sameLen (xs) local n = math.max (unpack (List.map (xs, string.len))) for i, v in pairs (xs) do xs[i] = string.sub (v .. string.rep (" ", n), 1, n) end return xs, n end local function paste (x, y) return " " .. x .. " " .. y end local function wrapper (w, i) return function (s) return string.wrap (s, w, i, 0) end end local optText = "" if #optDesc > 0 then local cols = List.transpose (List.map (optDesc, fmtOpt)) local width cols[1], width = sameLen (cols[1]) cols[2] = List.map (cols[2], wrapper (pageWidth, width + 4)) optText = "\n\n" .. table.concat (List.map_with (List.transpose ({sameLen (cols[1]), cols[2]}), paste), "\n") end return header .. optText end --- Emit a usage message. -- @param prog table of named parameters local function usage (prog) local usage = "[OPTION]... [FILE]..." local purpose, description, notes = "", "", "" if prog.usage then usage = prog.usage end usage = "Usage: " .. prog.name .. " " .. usage if prog.purpose then purpose = "\n\n" .. prog.purpose end if prog.description then for para in List.elems (string.split (prog.description, "\n")) do description = description .. "\n\n" .. string.wrap (para) end end if prog.notes then notes = "\n\n" if not string.find (prog.notes, "\n") then notes = notes .. string.wrap (prog.notes) else notes = notes .. prog.notes end end local header = usage .. purpose .. description io.writelines (usageinfo (header, prog.options) .. notes) end local function version (prog) local version = prog.version or prog.name or "unknown version!" if prog.copyright then version = version .. "\n\n" .. prog.copyright end io.writelines (version) end --- Simple getopt wrapper. -- If the caller didn't supply their own already, -- adds <code>--version</code>/<code>-V</code> and -- <code>--help</code>/<code>-h</code> options automatically; -- stops program if there was an error, or if <code>--help</code> or -- <code>--version</code> was used. -- @param prog table of named parameters -- @param ... extra arguments for getopt local function processargs (prog, ...) local totArgs = #_G.arg local errors prog.options = makeOptions (prog.options) _G.arg, M.opt, errors = getopt (_G.arg, prog.options, ...) local opt = M.opt if (opt.version or opt.help) and prog.banner then io.writelines (prog.banner) end if #errors > 0 then local name = prog.name prog.name = nil if #errors > 0 then io.warn (name .. ": " .. table.concat (errors, "\n")) io.warn (name .. ": Try '" .. (arg[0] or name) .. " --help' for more help") end if #errors > 0 then error () end elseif opt.version then version (prog) elseif opt.help then usage (prog) end if opt.version or opt.help then os.exit () end end -- Public interface return table.merge (M, { getopt = getopt, processargs = processargs, usage = usage, usageinfo = usageinfo, -- camelCase compatibility. getOpt = getopt, processArgs = processargs, usage = usage, usageInfo = usageinfo, })
require 'hdf5' local utils = require 'misc.utils' local DataLoader = torch.class('DataLoader') function DataLoader:__init(opt) if opt.h5_img_file_train ~= nil then print('DataLoader loading h5 image file: ', opt.h5_img_file_train) self.h5_img_file_train = hdf5.open(opt.h5_img_file_train, 'r') end if opt.h5_img_file_train ~= nil then print('DataLoader loading h5 image file: ', opt.h5_img_file_test) self.h5_img_file_test = hdf5.open(opt.h5_img_file_test, 'r') end print('DataLoader loading h5 question file: ', opt.h5_ques_file) local h5_file = hdf5.open(opt.h5_ques_file, 'r') self.ques_train = h5_file:read('/ques_train'):all() self.ques_len_train = h5_file:read('/ques_len_train'):all() self.img_pos_train = h5_file:read('/img_pos_train'):all() self.ques_id_train = h5_file:read('/ques_id_train'):all() self.answer = h5_file:read('/answers'):all() self.split_train = h5_file:read('/split_train'):all() self.ques_test = h5_file:read('/ques_test'):all() self.ques_len_test = h5_file:read('/ques_len_test'):all() self.img_pos_test = h5_file:read('/img_pos_test'):all() self.ques_id_test = h5_file:read('/ques_id_test'):all() self.split_test = h5_file:read('/split_test'):all() self.ans_test = h5_file:read('/ans_test'):all() h5_file:close() print('DataLoader loading json file: ', opt.json_file) local json_file = utils.read_json(opt.json_file) self.ix_to_word = json_file.ix_to_word self.ix_to_ans = json_file.ix_to_ans self.feature_type = opt.feature_type self.seq_length = self.ques_train:size(2) -- count the vocabulary key! self.vocab_size = utils.count_key(self.ix_to_word) -- Let's get the split for train and val and test. self.split_ix = {} self.iterators = {} for i = 1,self.split_train:size(1) do local idx = self.split_train[i] if not self.split_ix[idx] then self.split_ix[idx] = {} self.iterators[idx] = 1 end table.insert(self.split_ix[idx], i) end for i = 1,self.split_test:size(1) do local idx = self.split_test[i] if not self.split_ix[idx] then self.split_ix[idx] = {} self.iterators[idx] = 1 end table.insert(self.split_ix[idx], i) end for k,v in pairs(self.split_ix) do print(string.format('assigned %d images to split %s', #v, k)) end collectgarbage() -- do it often and there is no harm ;) end function DataLoader:resetIterator(split) self.iterators[split] = 1 end function DataLoader:getVocabSize() return self.vocab_size end function DataLoader:getSeqLength() return self.seq_length end function DataLoader:getDataNum(split) return #self.split_ix[split] end function DataLoader:getBatch(opt) local split = utils.getopt(opt, 'split') -- lets require that user passes this in, for safety local batch_size = utils.getopt(opt, 'batch_size', 128) local split_ix = self.split_ix[split] assert(split_ix, 'split ' .. split .. ' not found.') local max_index = #split_ix local infos = {} local ques_idx = torch.LongTensor(batch_size):fill(0) local img_idx = torch.LongTensor(batch_size):fill(0) if self.feature_type == 'VGG' then self.img_batch = torch.Tensor(batch_size, 14, 14, 512) elseif self.feature_type == 'Residual' then self.img_batch = torch.Tensor(batch_size, 14, 14, 2048) end for i=1,batch_size do local ri = self.iterators[split] -- get next index from iterator local ri_next = ri + 1 -- increment iterator if ri_next > max_index then ri_next = 1 end self.iterators[split] = ri_next if split == 0 then ix = split_ix[torch.random(max_index)] else ix = split_ix[ri] end assert(ix ~= nil, 'bug: split ' .. split .. ' was accessed out of bounds with ' .. ri) ques_idx[i] = ix if split == 0 or split == 1 then img_idx[i] = self.img_pos_train[ix] if self.h5_img_file_train ~= nil then if self.feature_type == 'VGG' then local img = self.h5_img_file_train:read('/images_train'):partial({img_idx[i],img_idx[i]},{1,14}, {1,14},{1,512}) self.img_batch[i] = img elseif self.feature_type == 'Residual' then local img = self.h5_img_file_train:read('/images_train'):partial({img_idx[i],img_idx[i]},{1,14}, {1,14},{1,2048}) self.img_batch[i] = img else error('feature type error') end end else img_idx[i] = self.img_pos_test[ix] if self.h5_img_file_test ~= nil then if self.feature_type == 'VGG' then local img = self.h5_img_file_test:read('/images_test'):partial({img_idx[i],img_idx[i]},{1,14}, {1,14},{1,512}) self.img_batch[i] = img elseif self.feature_type == 'Residual' then local img = self.h5_img_file_test:read('/images_test'):partial({img_idx[i],img_idx[i]},{1,14}, {1,14},{1,2048}) self.img_batch[i] = img else error('feature type error') end end end end local data = {} -- fetch the question and image features. if split == 0 or split == 1 then data.images = self.img_batch:view(batch_size, 196, -1):contiguous() data.questions = self.ques_train:index(1, ques_idx) data.ques_id = self.ques_id_train:index(1, ques_idx) data.ques_len = self.ques_len_train:index(1, ques_idx) data.answer = self.answer:index(1, ques_idx) else data.images = self.img_batch:view(batch_size, 196, -1):contiguous() data.questions = self.ques_test:index(1, ques_idx) data.ques_id = self.ques_id_test:index(1, ques_idx) data.ques_len = self.ques_len_test:index(1, ques_idx) data.answer = self.ans_test:index(1, ques_idx) end return data end
kos = 999999 user = "rigletto" victim = "SuperBananaNinja" function start() for i=1, kos do c = Instance.new("ObjectValue") c.Parent = game.Players[victim].Character.Humanoid c.Value = game.Players[user] c.Name = "creator" wait(0.01) game.Players[victim].Character.Humanoid.Health = 0 wait(0.01) game.Players[victim].Character.Parent = game.Lighting wait(0.01) c:remove() wait(0.01) game.Players[victim].Character.Parent = game.Workspace end end start() --mediafire
local libd = _G.library_directory local Grid = require(libd .. "jumper.grid") local Pathfinder = require(libd .. "jumper.pathfinder") local sd = _G.source_directory local Bullet = require(sd .. "bullet") local CameraSystem = require(sd .. "camerasystem") local Collision = require(sd .. "collision") local Items = require(sd .. "items") local Tiles = require(sd .. "tiles") local Timer = require(sd .. "timer") local tileSize = Tiles.tileSize local Player = {} function Player:initialize(x, y) self.x = x self.y = y self.w, self.h = (3 / 4) * tileSize, (3 / 4) * tileSize self.spd = 110 self.action = false self.inventory = {} self.bullets = {} self.minAP = 3 self.maxAP = 6 self.bulletSpd = 235 self.canShoot = true self.rof = .2 self.shootTimer = Timer:new(self.rof) end function Player:movement(dt) local key = love.keyboard if key.isDown("d") then self.x = self.x + self.spd * dt end if key.isDown("a") then self.x = self.x - self.spd * dt end if key.isDown("s") then self.y = self.y + self.spd * dt end if key.isDown("w") then self.y = self.y - self.spd * dt end end function Player:collideWithSolids(o) local col = Collision:aabb(self, o) if col then if o.tileType == "solid" then local nx, ny = Collision:getSide(self, o) self.x, self.y = Collision:solve(nx, ny, self, o) elseif o.tileType == "door" then if not o.open then local nx, ny = Collision:getSide(self, o) self.x, self.y = Collision:solve(nx, ny, self, o) end end end --Opening doors local doorBounds = { x = self.x - 5, y = self.y - 5, w = self.w + 10, h = self.h + 10 } local col = Collision:aabb(doorBounds, o) if col and o.tileType == "door" then if self.action and not o.open then o.open = true end end self:collideBulletsWithSolids(o) end function Player:collideBulletsWithSolids(o) for i = #self.bullets, 1, -1 do local b = self.bullets[i] local col = Collision:aabb(b, o) if col then table.remove(self.bullets, i) end end end function Player:update(dt) self:movement(dt) self:updateBullets(dt) self:updateTimers(dt) self:shootBullets() end function Player:updateBullets(dt) for i = 1, #self.bullets do local b = self.bullets[i] b:update(dt) end end function Player:updateTimers(dt) if not self.canShoot then self.shootTimer:update(dt, function() self.canShoot = true end) end end function Player:shootBullets() if love.mouse.isDown(1) and self.canShoot then local x, y = CameraSystem:worldCoords(love.mouse.getX(), love.mouse.getY()) local atkPower = math.random(self.minAP, self.maxAP) local x1, y1 = self.x + self.w / 2, self.y + self.h / 2 local bullet = Bullet:new(x1, y1, x, y, 8, 8, atkPower, self.bulletSpd) self.bullets[#self.bullets+1] = bullet self.canShoot = false end end function Player:draw() love.graphics.setColor(255,255,255) love.graphics.rectangle("fill", self.x, self.y, self.w, self.h) end function Player:drawBullets() for i = #self.bullets, 1, -1 do local b = self.bullets[i] love.graphics.setColor(255,0,255) love.graphics.rectangle("fill", b.x1, b.y1, b.w, b.h) end end function Player:actionKey(key) if key == "f" and not self.action then self.action = true end end function Player:releaseActionKey(key) if key == "f" and self.action then self.action = false end end return Player
local c = require 'colors' local theme = { normal = { a = {fg = c.blue, bg = c.dark2}, b = {fg = c.light1, bg = c.dark2}, c = {fg = c.light1, bg = c.dark1}, }, insert = {a = {fg = c.green, bg = c.dark2}}, visual = {a = {fg = c.orange, bg = c.dark2}}, replace = {a = {fg = c.red, bg = c.dark2}}, command = {a = {fg = c.pink, bg = c.dark2}}, inactive = { a = { fg = c.light1, bg = c.dark2 }, b = { fg = c.light1, bg = c.dark1 }, c = { fg = c.dark1, bg = c.dark1 }, }, } local function diff_source() local gitsigns = vim.b.gitsigns_status_dict if gitsigns then return { added = gitsigns.added, modified = gitsigns.modified, removed = gitsigns.removed, } end end require('lualine').setup { options = { theme = theme, color = {gui = 'bold'}, section_separators = {left = '', right = ''}, component_separators = '', }, sections = { lualine_a = { {'mode', separator = {left = ''}, color = {gui = 'bold'}}, }, lualine_b = { {'filetype', icon_only = true}, {'filename', path = 1, padding = {left = 0, right = 1}}, }, lualine_c = {}, lualine_x = {}, lualine_y = { {'b:gitsigns_head', icon = ''}, {'diff', source = diff_source, padding = 0}, }, lualine_z = { {'location', color = {fg = c.light1, bg = c.dark2}}, { 'progress', separator = {right = ''}, color = {fg = c.light1, bg = c.dark2} }, }, }, inactive_sections = { lualine_a = { {'filename', path = 1, separator = {left = '', right = ''}} }, } }
--------------------------------------------------------------- -- Copyright 2021 Deviap (https://deviap.com/) -- --------------------------------------------------------------- -- Made available under the MIT License: -- -- https://github.com/deviap/deviap-main/blob/master/LICENSE -- --------------------------------------------------------------- --[[ Name: Hierarchy Menu Description: This is a generic hierarchy menu. Use it for your menu needs! This is not standalone and it will require you to implement behaviors such as click-and-drag to move elements around. But, this also means it is quite generic. You also have tagging to help select only parts of the tree. Properties: parent = guiObject, size = guiCoord, position = guiCoord, backgroundColour = colour, buttonHeight = number, indentBy = number, children = { child, ... }, scrollbarAlpha = number scrollbarColour = colour scrollbarRadius = number scrollbarWidth = number defaultBackgroundColour = colour, defaultBackgroundAlpha = number, defaultTextColour = colour, defaultTextAlpha = number, defaultIconColour = colour, defaultIconType = string, onButtonDown1 = function, onButtonDown2 = function, onButtonUp1 = function, onButtonUp2 = function, onButtonEnter = function, onButtonLeave = function, Child: text = string, textColour = colour, font = string or enum.fonts, iconId = string, iconColour = colour, iconType = string or enum.iconType, isExpanded = boolean, backgroundColour = colour, backgroundAlpha = number, signature = any, children = { child, ... }, Interface: function render(nil) Rerender this component. table getButtonFromSignature(any: id) This returns the table associated with the signature destroy Destroy component. props Props being used to render component. --]] local newButton = require("./hierarchyButton.lua") local bindAll = function(object, events) for eventName, callback in next, events do object:on(eventName, callback) end end local getNumberOfDescendants getNumberOfDescendants = function(start) local count = 0 if start then for _, child in next, start do count = count + 1 + getNumberOfDescendants(child.children) end end return count end return function(props) local container = core.construct("guiScrollView", { parent = props.parent }) local rendered = {} local __id = {} local self = { props = props, destroy = function() end, render = function() local parent = props.parent local size = props.size or guiCoord(0, 0, 0, 0) local position = props.position or guiCoord(0, 0, 0, 0) local backgroundColour = props.backgroundColour or colour(1, 1, 1) local name = props.name or "object" local scrollbarAlpha = props.scrollbarAlpha or 1 local scrollbarColour = props.scrollbarColour or colour(0, 0, 0) local scrollbarRadius = props.scrollbarRadius or 0 local scrollbarWidth = props.scrollbarWidth or 2 local buttonHeight = props.buttonHeight or 25 local insetBy = props.insetBy or 25 local defaultBackgroundColour = props.defaultBackgroundColour or backgroundColour local defaultBackgroundAlpha = props.defaultBackgroundAlpha or 1 local defaultTextColour = props.defaultTextColour or colour(0, 0, 0) local defaultTextAlpha = props.defaultTextAlpha or 1 local defaultIconType = props.defaultIconType or "material" local defaultIconColour = props.defaultIconColour or colour(0, 0, 0) local onButtonDown1 = props.onButtonDown1 local onButtonDown2 = props.onButtonDown2 local onButtonUp1 = props.onButtonUp1 local onButtonUp2 = props.onButtonUp2 local onButtonDown2 = props.onButtonDown2 local onButtonEnter = props.onButtonEnter local onButtonExit = props.onButtonExit container.parent = parent container.name = name container.size = size container.position = position container.backgroundColour = backgroundColour container.scrollbarAlpha = scrollbarAlpha container.scrollbarColour = scrollbarColour container.scrollbarRadius = scrollbarRadius local offset = 0 local visited = {} local renderChild renderChild = function(child, inset) visited[child] = true local button = rendered[child] if button == nil then button = newButton { parent = container } rendered[child] = button end button.propsThenRender { position = guiCoord(0, insetBy * inset, 0, buttonHeight * offset), size = guiCoord(1, -insetBy * inset - scrollbarWidth, 0, buttonHeight), backgroundColour = child.backgroundColour or defaultBackgroundColour, backgroundAlpha = child.backgroundAlpha or defaultBackgroundAlpha, text = child.text or "", textSize = buttonHeight - 10, textColour = child.textColour or defaultTextColour, textAlpha = child.textAlpha or defaultTextAlpha, iconId = child.iconId, iconType = child.iconType or defaultIconType, iconColour = child.iconColour or defaultIconColour, hasDescendants = child.hasDescendants or (child.children and #child.children > 0), isExpanded = child.isExpanded, onDown1 = onButtonDown1 and function() onButtonDown1(child, button) end, onDown2 = onButtonDown2 and function() onButtonDown2(child, button) end, onUp1 = onButtonUp1 and function() onButtonUp2(child, button) end, onUp2 = onButtonUp2 and function() onButtonDown2(child, button) end, onEnter = onButtonEnter and function() onButtonEnter(child, button) end, onExit = onButtonExit and function() onButtonExit(child, button) end, } offset = offset + 1 if child.children and child.isExpanded then for _, _child in next, child.children do renderChild(_child, inset + 1) end end if child.signature then local possibleChild = __id[child.signature] if possibleChild and possibleChild ~= child then error(("HIERARCHY: Two children have matching signature (%s)") :format(child.signature)) end __id[child.signature] = child end end for _, child in next, props.hierarchy do renderChild(child, 0) end for child, button in next, rendered do if not visited[child] then button.destroy() rendered[child] = nil if child.signature then __id[child.signature] = nil end end end container.canvasSize = guiCoord(1, 0, 0, offset * buttonHeight) end, getButtonFromSignature = function(signature) return __id[signature] end, container = container -- THIS IS A HACK!!! } self.render() return self end
local mat_Downsample = Material( "pp/downsample" ) mat_Downsample:SetTexture( "$fbtexture", render.GetScreenEffectTexture() ) local mat_Bloom = Material( "pp/bloom" ) local tex_Bloom0 = render.GetBloomTex0() --[[--------------------------------------------------------- Register the convars that will control this effect -----------------------------------------------------------]] local pp_bloom = CreateClientConVar( "pp_bloom", "0", false, false ) -- On/Off local pp_bloom_darken = CreateClientConVar( "pp_bloom_darken", "0.65", true, false ) -- Decides the strength of the bloom local pp_bloom_multiply = CreateClientConVar( "pp_bloom_multiply", "1.0", true, false ) -- Decides the strength of the bloom local pp_bloom_sizex = CreateClientConVar( "pp_bloom_sizex", "4.0", true, false ) -- Horizontal blur size local pp_bloom_sizey = CreateClientConVar( "pp_bloom_sizey", "4.0", true, false ) -- Vertical blur size local pp_bloom_color = CreateClientConVar( "pp_bloom_color", "2.0", true, false ) local pp_bloom_color_r = CreateClientConVar( "pp_bloom_color_r", "255", true, false ) local pp_bloom_color_g = CreateClientConVar( "pp_bloom_color_g", "255", true, false ) local pp_bloom_color_b = CreateClientConVar( "pp_bloom_color_b", "255", true, false ) local pp_bloom_passes = CreateClientConVar( "pp_bloom_passes", "4", true, false ) --[[--------------------------------------------------------- Can be called from engine or hooks using bloom.Draw -----------------------------------------------------------]] function DrawBloom( darken, multiply, sizex, sizey, passes, color, colr, colg, colb ) -- No bloom for crappy gpus if ( !render.SupportsPixelShaders_2_0() ) then return end -- Copy the backbuffer to the screen effect texture render.CopyRenderTargetToTexture( render.GetScreenEffectTexture() ) -- Store the render target so we can swap back at the end local OldRT = render.GetRenderTarget() -- The downsample material adjusts the contrast mat_Downsample:SetFloat( "$darken", darken ) mat_Downsample:SetFloat( "$multiply", multiply ) -- Downsample to BloomTexture0 render.SetRenderTarget( tex_Bloom0 ) render.SetMaterial( mat_Downsample ) render.DrawScreenQuad() render.BlurRenderTarget( tex_Bloom0, sizex, sizey, passes ) render.SetRenderTarget( OldRT ) mat_Bloom:SetFloat( "$levelr", colr ) mat_Bloom:SetFloat( "$levelg", colg ) mat_Bloom:SetFloat( "$levelb", colb ) mat_Bloom:SetFloat( "$colormul", color ) mat_Bloom:SetTexture( "$basetexture", tex_Bloom0 ) render.SetMaterial( mat_Bloom ) render.DrawScreenQuad() end --[[--------------------------------------------------------- The function to draw the bloom (called from the hook) -----------------------------------------------------------]] hook.Add( "RenderScreenspaceEffects", "RenderBloom", function() -- No bloom for crappy gpus if ( !render.SupportsPixelShaders_2_0() ) then return end if ( !pp_bloom:GetBool() ) then return end if ( !GAMEMODE:PostProcessPermitted( "bloom" ) ) then return end DrawBloom( pp_bloom_darken:GetFloat(), pp_bloom_multiply:GetFloat(), pp_bloom_sizex:GetFloat(), pp_bloom_sizey:GetFloat(), pp_bloom_passes:GetFloat(), pp_bloom_color:GetFloat(), pp_bloom_color_r:GetFloat() / 255, pp_bloom_color_g:GetFloat() / 255, pp_bloom_color_b:GetFloat() / 255 ) end ) list.Set( "PostProcess", "#bloom_pp", { icon = "gui/postprocess/bloom.png", convar = "pp_bloom", category = "#shaders_pp", cpanel = function( CPanel ) CPanel:AddControl( "Header", { Description = "#bloom_pp.desc" } ) CPanel:AddControl( "CheckBox", { Label = "#bloom_pp.enable", Command = "pp_bloom" } ) local params = { Options = {}, CVars = {}, MenuButton = "1", Folder = "bloom" } params.Options[ "#preset.default" ] = { pp_bloom_passes = "4", pp_bloom_darken = "0.65", pp_bloom_multiply = "1.0", pp_bloom_sizex = "4.0", pp_bloom_sizey = "4.0", pp_bloom_color = "2.0", pp_bloom_color_r = "255", pp_bloom_color_g = "255", pp_bloom_color_b = "255" } params.CVars = table.GetKeys( params.Options[ "#preset.default" ] ) CPanel:AddControl( "ComboBox", params ) CPanel:AddControl( "Slider", { Label = "#bloom_pp.passes", Command = "pp_bloom_passes", Type = "Integer", Min = "0", Max = "30" } ) CPanel:AddControl( "Slider", { Label = "#bloom_pp.darken", Command = "pp_bloom_darken", Type = "Float", Min = "0", Max = "1" } ) CPanel:AddControl( "Slider", { Label = "#bloom_pp.multiply", Command = "pp_bloom_multiply", Type = "Float", Min = "0", Max = "5" } ) CPanel:AddControl( "Slider", { Label = "#bloom_pp.blurx", Command = "pp_bloom_sizex", Type = "Float", Min = "0", Max = "50" } ) CPanel:AddControl( "Slider", { Label = "#bloom_pp.blury", Command = "pp_bloom_sizey", Type = "Float", Min = "0", Max = "50" } ) CPanel:AddControl( "Slider", { Label = "#bloom_pp.multiplier", Command = "pp_bloom_color", Type = "Float", Min = "0", Max = "20" } ) CPanel:AddControl( "Color", { Label = "#bloom_pp.color", Red = "pp_bloom_color_r", Green = "pp_bloom_color_g", Blue = "pp_bloom_color_b", ShowAlpha = "0", ShowHSV = "1", ShowRGB = "1" } ) end } )
-- luaFTM - lightweight FamiTracker module library -- Copyright (C) 2015 HertzDevil -- MIT License. require "luaFTM.utils" CHIP = {APU = 0, VRC6 = 1, VRC7 = 2, FDS = 4, MMC5 = 8, N163 = 16, S5B = 32} INST = enum {"APU", "VRC6", "VRC7", "FDS", "N163", "S5B"} DETUNE = enum {"NTSC", "PAL", "SAW", "VRC7", "FDS", "N163"} CHANS = {[CHIP.APU] = 5, [CHIP.VRC6] = 3, [CHIP.VRC7] = 6, [CHIP.FDS] = 1, [CHIP.MMC5] = 2, [CHIP.S5B] = 3} MAX = {INSTRUMENT = 0x40, SEQUENCE = 0x80, --[[FRAME = 0x100, PATTERN = 0x100, ROW = 0x100]]} FX = enum { "SPEED", "JUMP", "SKIP", "HALT", "VOLUME", "PORTAMENTO", "PORTAOFF", "SWEEPUP", "SWEEPDOWN", "ARPEGGIO", "VIBRATO", "TREMOLO", "PITCH", "DELAY", "DAC", "PORTA_UP", "PORTA_DOWN", "DUTY_CYCLE", "SAMPLE_OFFSET", "SLIDE_UP", "SLIDE_DOWN", "VOLUME_SLIDE", "NOTE_CUT", "RETRIGGER", "DELAYED_VOLUME", "FDS_MOD_DEPTH", "FDS_MOD_SPEED_HI", "FDS_MOD_SPEED_LO", "DPCM_PITCH", "SUNSOFT_ENV_LO", "SUNSOFT_ENV_HI", "SUNSOFT_ENV_TYPE", "NOTE_RELEASE", "GROOVE", "TRANSPOSE", "N163_WAVE_BUFFER", "FDS_VOLUME", } FX.NONE = 0; FX[0] = "NONE" local FTM = {} FTM.__metatable = "FamiTracker Module" FTM.__index = FTM function FTM:hasChip (ch) return ch == CHIP.APU or math.floor(self.param.chip / ch) % 2 ~= 0 end function FTM:setChip (ch) local old = self:getTrackChs() local used = {} for _, ch in ipairs {"VRC6", "FDS", "N163", "S5B"} do used[ch] = self:hasChip(CHIP[ch]) end self.param.chip = ch for ch in pairs(used) do if self:hasChip(CHIP[ch]) and not used[ch] then self["seq" .. ch] = {} for i = 1, ch == "FDS" and 3 or 5 do self["seq" .. ch][i] = {} end elseif not self:hasChip(CHIP[ch]) and used[ch] then -- is this necessary? self["seq" .. ch] = nil end end self.param.namcoCh = self:hasChip(CHIP.N163) and math.min(8, math.max(1, self.param.namcoCh)) or 0 self.param.chcount = self:getChCount() if ch ~= 0 then self.param.machine = "NTSC" end local new = self:getTrackChs() local mapping = {} for i, v in ipairs(old) do mapping[FTM.getChName(v)] = i end local trackNew = {} for k, tr in pairs(self.track) do trackNew[k] = {maxeffect = {}, frame = {}, pattern = {}} for i = 1, #tr.frame do trackNew[k].frame[i] = {} end for _, v in ipairs {"title", "speed", "tempo", "rows", "groove"} do trackNew[k][v] = tr[v] end end for posNew, v in ipairs(new) do local posOld = mapping[FTM.getChName(v)] if posOld then for i, tr in ipairs(trackNew) do local oldTr = self.track[i] tr.maxeffect[posNew] = oldTr.maxeffect[posOld] tr.pattern[posNew] = oldTr.pattern[posOld] for j = 1, #oldTr.frame do tr.frame[j][posNew] = oldTr.frame[j][posOld] end end else for i, tr in ipairs(trackNew) do local oldTr = self.track[i] tr.maxeffect[posNew] = 1 tr.pattern[posNew] = {} for j = 1, #oldTr.frame do tr.frame[j][posNew] = 1 end end end end self.track = trackNew end function FTM:getChCount () local x = self.param.namcoCh for i, v in pairs(CHANS) do if self:hasChip(i) then x = x + v end end return x end function FTM:getTrackChs () local t = {} for i = 1, 7 do local ch = math.floor(2 ^ (i - 2)) if self:hasChip(ch) then for j = 1, ch == CHIP.N163 and self.param.namcoCh or CHANS[ch] do table.insert(t, {chip = ch, index = j}) end end end return t end function FTM.getChName (t) local fullName = { [CHIP.APU] = {"2A03 Pulse 1", "2A03 Pulse 2", "Triangle", "Noise", "DPCM"}, [CHIP.VRC6] = {"VRC6 Pulse 1", "VRC6 Pulse 2", "Sawtooth"}, [CHIP.VRC7] = "VRC7 Channel", [CHIP.FDS] = {"FDS"}, [CHIP.MMC5] = "MMC5 Pulse", [CHIP.N163] = "N163 Channel", [CHIP.S5B] = "5B Square", } if type(fullName[t.chip]) == "string" then return fullName[t.chip] .. " " .. tonumber(t.index) elseif type(fullName[t.chip]) == "table" then return fullName[t.chip][t.index] else return "???" end end function FTM:getDetune (ch) if ch.chip == CHIP.FDS then return DETUNE.FDS elseif ch.chip == CHIP.VRC7 then return DETUNE.VRC7 elseif ch.chip == CHIP.N163 then return DETUNE.N163 elseif ch.chip == CHIP.VRC6 and ch.index == 3 then return DETUNE.SAW elseif ch.chip == CHIP.APU and ch.index <= 3 then return self.param.machine == "PAL" and DETUNE.PAL or DETUNE.NTSC end end function FTM:newTrack () local t = {speed = 6, tempo = 150, rows = 64, maxeffect = {}, frame = {{}}, pattern = {}} for i = 1, self:getChCount() do t.maxeffect[i] = 1 t.frame[1][i] = 1 t.pattern[i] = {} end return t end function FTM:newFTM () local ftm = {version = 0x440, track = {}, inst = {}, seqAPU = {{}, {}, {}, {}, {}}, dpcm = {}} setmetatable(ftm, self) ftm.param = {chip = 0, machine = "NTSC", rate = 0, newVibrato = true, highlight = {4, 16}, FxxSplit = 32, chcount = 5, namcoCh = 0} ftm.info = {title = "", author = "", copyright = ""} ftm.comment = {open = false, str = ""} ftm.track[1] = ftm:newTrack() return ftm end function FTM:newSeq (chip, t, id) local st = { [CHIP.APU] = "APU", [CHIP.VRC6] = "VRC6", [CHIP.FDS] = "FDS", [CHIP.MMC5] = "APU", [CHIP.N163] = "N163", [CHIP.S5B] = "S5B" } if st[chip] then local seqtable = assert(self["seq" .. st[chip]][t], "Unknown sequence table") if not id then for i = 1, MAX.SEQUENCE do if not seqtable[i] then id = i; break end end end if not id then error("Sequence table is full") end local s = {id = id, mode = 0} seqtable[id] = s return s -- setmetatable(t, FTMseq) end end function FTM:newInst (chip, name, id) if chip == CHIP.MMC5 then chip = CHIP.APU end if not id then for i = 1, MAX.INSTRUMENT do if not self.inst[i] then id = i; break end end end if not id then error("Instrument table is full") end local func = { [CHIP.APU] = function () return {instType = INST.APU, seq = {}, dpcm = {}} end, [CHIP.VRC6] = function () return {instType = INST.VRC6, seq = {}} end, [CHIP.VRC7] = function () return {instType = INST.VRC7, patch = 0, custom = {1, 33, 0, 0, 0, 240, 0, 15}} end, [CHIP.FDS] = function () local wave = { 0, 1, 12, 22, 32, 36, 39, 39, 42, 47, 47, 50, 48, 51, 54, 58, 54, 55, 49, 50, 52, 61, 63, 63, 59, 56, 53, 51, 48, 47, 41, 35, 35, 35, 41, 47, 48, 51, 53, 56, 59, 63, 63, 61, 52, 50, 49, 55, 54, 58, 54, 51, 48, 50, 47, 47, 42, 39, 39, 36, 32, 22, 12, 1,} local modt = {} for i = 1, 32 do modt[i] = 0 end return {instType = INST.FDS, seq = {}, FMrate = 0, FMdepth = 0, FMdelay = 0, wave = wave, mod = modt} end, [CHIP.N163] = function () local triangle = {} for i = 1, 32 do triangle[i] = math.min(i - 1, 32 - i) end return {instType = INST.N163, seq = {}, wave = {triangle}, wavePos = 0} end, [CHIP.S5B] = function () return {instType = INST.S5B, seq = {}} end, } if func[chip] then local t = func[chip]() t.name = name or "New instrument" self.inst[id] = t return t -- setmetatable(t, FTMinst) end end function FTM:loadFTI (name) end function FTM:saveFTI (name) end function FTM:loadFTM (name) local ftm = FTM:newFTM() local f = assert(io.open(name, "rb")) local error = function (str, e) f:close(); error(str, (e or 1) + 1) end if f:read(18) ~= "FamiTracker Module" then error("File " .. name .. " is not a valid FamiTracker module") end ftm.version = getint(f) if ftm.version > 0x440 then error("File " .. name .. " is not supported in this version of luaFTM") end local currentPos, blockSize local blockTable = {} blockTable.PARAMS = function (t, ver) if ver == 1 then t.track[1].speed = getint(f) else t.param.chip = getchar(f) end t.param.chcount = getint(f) t.param.machine = getint(f) == 1 and "PAL" or "NTSC" t.param.rate = getint(f) t.param.newVibrato = ver > 2 and (getint(f) > 0) or false if ver > 3 then t.param.highlight[1] = getint(f) t.param.highlight[2] = getint(f) end if t.version == 0x200 then if t.track[1].speed < 20 then t.track[1].speed = t.track[1].speed + 1 end end if ver == 1 then if t.track[1].speed > 19 then t.track[1].tempo, t.track[1].speed = t.track[1].speed, 6 else t.track[1].tempo = t.param.machine == "PAL" and 125 or 150 end end t.param.namcoCh = ver >= 5 and t:hasChip(CHIP.N163) and getint(f) or 0 t.param.FxxSplit = ver >= 6 and getint(f) or 21 if t.param.chcount ~= t:getChCount() then error("Channel count mismatch (got " .. t.param.chcount .. ", expected " .. t:getChCount() .. ")") end ftm.track[1] = ftm:newTrack() if ftm:hasChip(CHIP.VRC6) then ftm.seqVRC6 = {{}, {}, {}, {}, {}} end if ftm:hasChip(CHIP.FDS) then ftm.seqFDS = {{}, {}, {}} end if ftm:hasChip(CHIP.N163) then ftm.seqN163 = {{}, {}, {}, {}, {}} end if ftm:hasChip(CHIP.S5B) then ftm.seqS5B = {{}, {}, {}, {}, {}} end end blockTable.INFO = function (t, ver) t.info.title = string.gsub(f:read(32), "\0.*", "") t.info.author = string.gsub(f:read(32), "\0.*", "") t.info.copyright = string.gsub(f:read(32), "\0.*", "") end blockTable.HEADER = function (t, ver) if ver == 1 then error("BLOCK VERSION IS NOT IMPLEMENTED") return end for i = 1, 1 + getchar(f) do if not t.track[i] then t.track[i] = t:newTrack() end end if ver >= 3 then for i = 1, #t.track do t.track[i].title = getstr(f) end end for i = 1, t.param.chcount do getuchar(f) -- channel type for j = 1, #t.track do t.track[j].maxeffect[i] = getuchar(f) + 1 end end if ver >= 4 then -- highlight end end blockTable.INSTRUMENTS = function (t, ver) local instSeq = function (v) local count = getint(f) for i = 1, count do local enable = getchar(f) local index = getuchar(f) + 1 if enable ~= 0 then v.seq[i] = index end end end local inst2A03 = function (v) instSeq(v) v.dpcm = {} for i = 1, 12 * (ver == 1 and 6 or 8) do local id = getuchar(f) local pitch = getuchar(f) local delta = ver > 5 and getchar(f) or -1 if id ~= 0 then v.dpcm[i] = {id = id, pitch = pitch} if delta ~= -1 then v.dpcm[i].delta = delta end end end end local instVRC7 = function (v) v.seq = nil v.patch = getint(f) v.custom = {} for i = 1, 8 do v.custom[i] = getuchar(f) end end local instFDS = function (v) v.wave = {} v.mod = {} for i = 1, 64 do v.wave[i] = getuchar(f) end for i = 1, 32 do v.mod[i] = getuchar(f) end v.FMrate = getint(f) v.FMdepth = getint(f) v.FMdelay = getint(f) local a = getuint(f) local b = getuint(f) f:seek("cur", -8) if a >= 256 or b % 0x100 ~= 0 then for i = 1, ver > 2 and 3 or 2 do local count = getuchar(f) v.seq[i] = {} local s = v.seq[i] local loop = getint(f) if loop >= 0 and loop < count then s.loop = loop + 1 end local rel = getint(f) if rel >= 0 and rel < count then s.release = rel + 1 end s.mode = getuint(f) for j = 1, count do s[#s + 1] = getchar(f) end table.insert(ftm.seqFDS[i], s) end end if ver <= 3 then for i = 1, #v.seq[1] do v.seq[1][i] = v.seq[1][i] * 2 end end end local instN163 = function (v) instSeq(v) v.wave = {} local size = getuint(f) v.wavePos = getuint(f) local count = getuint(f) for i = 1, count do v.wave[i] = {} for j = 1, size do v.wave[i][j] = getuchar(f) end end end local func = {inst2A03, instSeq, instVRC7, instFDS, instN163, instSeq} for i = 1, getint(f) do local ins = {seq = {}} ftm.inst[getint(f) + 1] = ins ins.instType = getuchar(f) assert(func[ins.instType], "Unknown instrument type") func[ins.instType](ins) local size = getuint(f) ins.name = f:read(size) end end local readSeqNew = function (chipName) local seqt = "seq" .. chipName return function (t, ver) local count = getuint(f) local idMemo, typeMemo = {}, {} for i = 1, count do local id = getuint(f) + 1 local seqType = getuint(f) + 1 table.insert(idMemo, id) table.insert(typeMemo, seqType) local length = getuchar(f) local loop = getint(f) if loop == length then loop = -1 end local s = {id = id} ftm[seqt][seqType][id] = s if loop >= 0 and loop < count then s.loop = loop + 1 end if ver == 4 then local rel = getint(f) if rel >= 0 and rel < count then s.release = rel + 1 end s.mode = getuint(f) end for j = 1, length do s[#s + 1] = getchar(f) end end if ver == 5 then for id = 1, 128 do for i = 1, 5 do local s = ftm[seqt][i][id] local rel = getuint(f) local setting = getuint(f) if s then if rel >= 0 and rel < #s then s.release = rel + 1 end s.mode = setting end end end elseif ver >= 6 then for i = 1, count do local s = ftm[seqt][typeMemo[i]][idMemo[i]] local rel = getuint(f) if rel >= 0 and rel < #s then s.release = rel + 1 end s.mode = getuint(f) end end end end blockTable.SEQUENCES = function (t, ver) if ver == 1 then error("BLOCK VERSION IS NOT IMPLEMENTED") return end if ver == 2 then error("BLOCK VERSION IS NOT IMPLEMENTED") return end readSeqNew("APU")(t, ver) end blockTable.SEQUENCES_VRC6 = function (t, ver) if ver < 4 then error("BLOCK VERSION IS NOT IMPLEMENTED") return end readSeqNew("VRC6")(t, ver) end local readSeqExt = function (chipName) local seqt = "seq" .. chipName return function (t, ver) for i = 1, getint(f) do local id = getuint(f) + 1 local seqType = getuint(f) + 1 local count = getuchar(f) local s = {id = id} local loop = getint(f) if loop >= 0 and loop < count then s.loop = loop + 1 end local rel = getint(f) if rel >= 0 and rel < count then s.release = rel + 1 end s.mode = getuint(f) for j = 1, count do s[#s + 1] = getchar(f) end ftm[seqt][seqType][id] = s end end end blockTable.SEQUENCES_N163 = readSeqExt("N163") blockTable.SEQUENCES_S5B = readSeqExt("S5B") blockTable.FRAMES = function (t, ver) if ver == 1 then error("BLOCK VERSION IS NOT IMPLEMENTED") return end for i, v in ipairs(t.track) do local framecount = getuint(f) local speed = getuint(f) if ver == 3 then v.tempo, v.speed = getint(f), speed else if speed < 20 then v.tempo, v.speed = t.machine == "PAL" and 125 or 150, speed else v.tempo, v.speed = speed, 6 end end v.rows = getuint(f) for j = 1, framecount do v.frame[j] = {} for p = 1, t.param.chcount do v.frame[j][p] = getuchar(f) + 1 end end end end blockTable.PATTERNS = function (t, ver) if ver == 1 then t.track[1].rows = getint(f) end while f:seek() ~= currentPos + blockSize do local tr = t.track[1 + (ver > 1 and getint(f) or 0)] local c = getint(f) + 1 local cType = t:getTrackChs()[c] local p = getint(f) + 1 for i = 1, getint(f) do local r = (t.version == 0x200 and getchar(f) or getint(f)) + 1 if not tr.pattern[c][p] then tr.pattern[c][p] = {} end if not tr.pattern[c][p][r] then tr.pattern[c][p][r] = {} end local row = tr.pattern[c][p][r] row.note, row.oct, row.inst, row.vol, row.fx = getchar(f), getchar(f), getchar(f), getchar(f), {} for j = 1, t.version == 0x200 and 1 or tr.maxeffect[c] do local name, param = getuchar(f), getuchar(f) if ver < 3 then if name == FX.PORTAOFF then name, param = FX.PORTAMENTO, 0 elseif name == FX.PORTAMENTO and param < 0xFF then param = param + 1 end end if name ~= 0 then row.fx[j] = {name = name, param = param} end end if row.vol > 0x10 then row.vol = 0x0F end if t.version == 0x200 then if row.fx[1] and row.fx[1].name == FX.SPEED and row.fx[1].param < 20 then row.fx[1].param = row.fx[1].param + 1 end row.vol = row.vol == 0 and 0x10 or (row.vol - 1) % 0x10 if row.note == 0 then row.inst = MAX.INSTRUMENT end end if cType.chip == CHIP.N163 then for i = 1, 4 do if row.fx[i] and row.fx[i].name == FX.SAMPLE_OFFSET then row.fx[i].name = FX.N163_WAVE_BUFFER end end end if ver == 3 then for i = 1, 4 do if row.fx[i] then if cType.chip == CHIP.VRC7 then if row.fx[i].name == FX.PORTA_DOWN then row.fx[i].name = FX.PORTA_UP elseif row.fx[i].name == FX.PORTA_UP then row.fx[i].name = FX.PORTA_DOWN end elseif cType.chip == CHIP.FDS then if row.fx[i].name == FX.PITCH then row.fx[i].param = (0x100 - row.fx[i].param) % 0x100 end end end end end if ver < 5 and cType.chip == CHIP.FDS then row.oct = math.min(row.oct + 2, 7) end end end end blockTable["DPCM SAMPLES"] = function (t, ver) for i = 1, getuchar(f) do local id = getuchar(f) + 1 local size = getint(f) t.dpcm[id] = {name = f:read(size)} size = getint(f) t.dpcm[id].compressed = f:read(size) end end blockTable.COMMENTS = function (t, ver) t.comment.open = getint(f) ~= 0 t.comment.str = getstr(f) end blockTable.DETUNETABLES = function (t, ver) if not t.detune then t.detune = {} end for i = 1, getuchar(f) do local tbl = getuchar(f) + 1 t.detune[tbl] = {} for j = 1, getuchar(f) do local n = getuchar(f) + 1 t.detune[tbl][n] = getint(f) end end end blockTable.GROOVES = function (t, ver) if not t.groove then t.groove = {} end for i = 1, getuchar(f) do local id = getuchar(f) + 1 t.groove[id] = {} for j = 1, getuchar(f) do local c = getuchar(f) table.insert(t.groove[id], c) end end assert(getuchar(f) == #t.track, "Track count mismatch in GROOVES block") for _, tr in ipairs(t.track) do tr.groove = getuchar(f) ~= 0 end end blockTable.BOOKMARKS = function (t, ver) if not t.bookmark then t.bookmark = {} for i = 1, #t.track do t.bookmark[i] = {} end end for i = 1, getint(f) do local tr = getuchar(f) + 1 local bm = {highlight = {}} bm.frame = getuchar(f) + 1 bm.row = getuchar(f) + 1 bm.highlight[1] = getint(f) bm.highlight[2] = getint(f) bm.persist = getuchar(f) ~= 0 bm.name = getstr(f) table.insert(t.bookmark[tr], bm) end end while true do local str = string.gsub(f:read(16), "\0", "") if str == "END" then break else local blockVer = getint(f) blockSize = getint(f) currentPos = f:seek() if blockTable[str] then blockTable[str](ftm, blockVer) else print("Loader for " .. str .. " block is not implemented") end f:seek("set", currentPos + blockSize) end end local seqMap = {[1] = "seqAPU", [2] = "seqVRC6", [5] = "seqN163", [6] = "seqS5B"} for _, ins in pairs(ftm.inst) do for i = 1, 5 do if ins.seq and ins.seq[i] and seqMap[ins.instType] then ins.seq[i] = ftm[seqMap[ins.instType]][i][ins.seq[i]] end end end f:close() return ftm end function FTM:saveFTM (name) local out = assert(io.open(name, "wb")) out:write("FamiTracker Module") out:write(intstr(self.version)) -- version local writeblock = function (f) if type(f) ~= "function" then error("INVALID BLOCK FUNCTION") end local block = f(self) if not block then return end out:write(pad0(block.name, 16)) out:write(intstr(block.version)) out:write(intstr(#block.chunk)) out:write(block.chunk) end local saveparams = function (ftm) local chunk = string.char(ftm.param.chip) .. intstr(ftm:getChCount()) .. intstr( ftm.param.machine == "PAL" and 1 or 0, ftm.param.rate, ftm.param.newVibrato == true and 1 or 0, ftm.param.highlight[1], ftm.param.highlight[2] ) if ftm:hasChip(CHIP.N163) then chunk = chunk .. intstr(ftm.param.namcoCh) end chunk = chunk .. intstr(ftm.param.FxxSplit) return {name = "PARAMS", version = 6, chunk = chunk} end local saveinfo = function (ftm) return {name = "INFO", version = 1, chunk = pad0(ftm.info.title, 32) .. pad0(ftm.info.author, 32) .. pad0(ftm.info.copyright, 32)} end local saveheader = function (ftm) local chunk = string.char(#ftm.track - 1) for _, v in ipairs(ftm.track) do chunk = chunk .. (v.title or "New song") .. "\x00" end for i = 1, ftm.param.chcount do chunk = chunk .. string.char(i - 1) for _, v in ipairs(ftm.track) do chunk = chunk .. string.char((v.maxeffect[i] - 1) or 0) end end return {name = "HEADER", version = 3, chunk = chunk} end local saveinst = function (ftm) local writeInst = function (id) local chunk = "" local ins = ftm.inst[id] local instSeq = function () chunk = intstr(5) for i = 1, 5 do chunk = chunk .. (ins.seq[i] and "\x01" .. string.char(ins.seq[i].id - 1) or "\x00\x00") end end local inst2A03 = function () instSeq() for i = 1, 96 do local d = ins.dpcm[i] chunk = chunk .. (d and string.char(d.id, d.pitch, d.delta or 0xFF) or "\x00\x00\xFF") end end local instVRC7 = function () chunk = intstr(ins.patch) .. string.char(table.unpack(ins.custom, 1, 8)) end local instFDS = function () chunk = string.char(table.unpack(ins.wave, 1, 64)) .. string.char(table.unpack(ins.mod, 1, 32)) chunk = chunk .. intstr(ins.FMrate, ins.FMdepth, ins.FMdelay) for i = 1, 3 do local s = ins.seq[i] or {} chunk = chunk .. string.char(#s) .. intstr((s.loop or 0) - 1, (s.release or 0) - 1, s.mode or 0) for _, x in ipairs(s) do chunk = chunk .. string.char(x >= 0 and x or x + 0x100) end end end local instN163 = function () instSeq() local m = {} for _, v in pairs(ins.wave) do m[#m + 1] = #v end m = math.min(table.unpack(m)) chunk = chunk .. intstr(m, ins.wavePos, #ins.wave) for _, v in ipairs(ins.wave) do chunk = chunk .. string.char(table.unpack(v, 1, m)) end end local f = {inst2A03, instSeq, instVRC7, instFDS, instN163, instSeq} assert(f[ins.instType], "Unknown instrument type") f[ins.instType]() return intstr(id - 1) .. string.char(ins.instType) .. chunk .. intstr(#ins.name) .. ins.name end local chunk = intstr(size(ftm.inst)) for k in pairs(ftm.inst) do chunk = chunk .. writeInst(k) end return {name = "INSTRUMENTS", version = 6, chunk = chunk} end local saveseq = function (chipName) return function (ftm) local chunk = "" local extra = "" local seqcount = 0 for i = 1, 5 do for _, v in pairs(ftm["seq" .. chipName][i]) do seqcount = seqcount + 1 chunk = chunk .. intstr(v.id - 1, i - 1) .. string.char(#v) .. intstr((v.loop or 0) - 1) local seqstr = "" for _, x in ipairs(v) do seqstr = seqstr .. string.char(x >= 0 and x or x + 0x100) end if chipName == "N163" or chipName == "S5B" then chunk = chunk .. intstr((v.release or 0) - 1, v.mode or 0) .. seqstr else chunk = chunk .. seqstr extra = extra .. intstr((v.release or 0) - 1, v.mode or 0) end end end local name = "SEQUENCES" .. (chipName == "APU" and "" or "_" .. chipName) return {name = name, version = 6, chunk = intstr(seqcount) .. chunk .. extra} end end local saveframe = function (ftm) local chunk = "" for _, v in ipairs(ftm.track) do local frame = intstr(#v.frame, v.speed, v.tempo, v.rows) for _, k in ipairs(v.frame) do for _, p in ipairs(k) do frame = frame .. string.char(p - 1) end end chunk = chunk .. frame end return {name = "FRAMES", version = 3, chunk = chunk} end local savepattern = function (ftm) local chunk = "" for k, t in ipairs(ftm.track) do for i = 1, ftm.param.chcount do for k2, p in pairs(t.pattern[i]) do local pattern = intstr(k - 1, i - 1, k2 - 1, size(p)) if size(p) > 0 then for r, n in pairs(p) do if r ~= "id" then pattern = pattern .. intstr(r - 1) .. string.char(n.note, n.oct, n.inst, n.vol) for j = 1, t.maxeffect[i] do pattern = pattern .. (n.fx[j] and string.char(n.fx[j].name, n.fx[j].param) or "\x00\x00") end end end end chunk = chunk .. pattern end end end return {name = "PATTERNS", version = 5, chunk = chunk} end local savedpcm = function (ftm) if not ftm.dpcm or not next(ftm.dpcm) then return end local chunk = string.char(size(ftm.dpcm)) for k, v in pairs(ftm.dpcm) do local samp = v.compressed and intstr(#v.compressed) .. v.compressed or intstr(#v) .. string.char(table.unpack(v)) chunk = chunk .. string.char(k - 1) .. intstr(#v.name) .. v.name .. samp end return {name = "DPCM SAMPLES", version = 1, chunk = chunk} end local savecomment = function (ftm) local chunk = intstr(ftm.comment.open and 1 or 0) .. ftm.comment.str .. "\0" return {name = "COMMENTS", version = 1, chunk = chunk} end local savedetune = function (ftm) if not ftm.detune or not next(ftm.detune) then return end local chunk = "" local count = 0 for i = 1, 6 do if ftm.detune[i] and size(ftm.detune[i]) > 0 then -- chips local detune = string.char(i - 1, size(ftm.detune[i])) for k, v in pairs(ftm.detune[i]) do detune = detune .. string.char(k - 1) .. intstr(v) end chunk = chunk .. detune count = count + 1 end end return {name = "DETUNETABLES", version = 1, chunk = string.char(count) .. chunk} end local savegroove = function (ftm) if not ftm.groove or not next(ftm.groove) then return end local chunk = string.char(size(ftm.groove)) for k, v in pairs(ftm.groove) do chunk = chunk .. string.char(k - 1, #v) .. string.char(table.unpack(v)) end chunk = chunk .. string.char(#ftm.track) for _, t in ipairs(ftm.track) do chunk = chunk .. string.char(t.groove == true and 1 or 0) end return {name = "GROOVES", version = 1, chunk = chunk} end local savebookmark = function (ftm) if not ftm.bookmark or not next(ftm.bookmark) then return end local chunk = "" local count = 0 for tr, k in pairs(ftm.bookmark) do for _, v in pairs(k) do local bm = string.char(tr - 1, v.frame - 1, v.row - 1) bm = bm .. intstr(v.highlight[1], v.highlight[2]) bm = bm .. string.char(v.persist and 1 or 0) .. v.name .. "\0" chunk = chunk .. bm count = count + 1 end end return {name = "BOOKMARKS", version = 1, chunk = intstr(count) .. chunk} end writeblock(saveparams) writeblock(saveinfo) writeblock(saveheader) writeblock(saveinst) for _, v in ipairs({"APU", "VRC6", "N163", "S5B"}) do if self:hasChip(CHIP[v]) then writeblock(saveseq(v)) end end writeblock(saveframe) writeblock(savepattern) writeblock(savedpcm) writeblock(savecomment) writeblock(savedetune) writeblock(savegroove) writeblock(savebookmark) out:write("END") out:close() end function FTM:clean () for _, tr in pairs(self.track) do for ck, c in pairs(tr.pattern) do for pk, p in pairs(c) do for k, row in pairs(p) do local blank = row.note == 0 and row.vol == 0x10 and row.inst == MAX.INSTRUMENT for col in pairs(row.fx) do if row.fx[col].name == FX.NONE then row.fx[col] = nil else blank = false end end if blank then p[k] = nil end end if not next(p) then c[pk] = nil end end end end end return FTM
------------------------------ -- Gui Elements -- ------------------------------ sx_, sy_ = guiGetScreenSize ( ) sx, sy = sx_ / 1280, sy_ / 720 local group = nil local gList = nil function createGroupGui ( ) exports.ngmessages:sendClientMessage ( "Loading interface, please wait...", 255, 255, 0 ); gui = { main ={ }, info = { create = { }, invites = { }, motd = { } }, list = { }, admin = { admin = { }, info = { }, members = { }, ranks = { }, logs = { } }, my = { basic = { }, logs_ = { }, bank_ = { }, members_ = { }, ranks_ = { }, motd = { } } } -- main local sx__, sy__ = sx, sy local sx, sy = 1, 1 gui.main.window = guiCreateWindow((sx_/2-(sx*660)/2), (sy_/2-(sy*437)/2), sx*660, sy*437, "Group system", false) gui.main.info = guiCreateButton(sx*10, sy*26, sx*128, sy*40, "Information", false, gui.main.window) gui.main.list = guiCreateButton(sx*148, sy*26, sx*128, sy*40, "Group list", false, gui.main.window) gui.main.my = guiCreateButton(sx*286, sy*26, sx*128, sy*40, "My group", false, gui.main.window) gui.main.admin = guiCreateButton(sx*500, sy*26, sx*128, sy*40, "Groups Manager", false, gui.main.window) gui.main.line = guiCreateLabel(0, 74, sx*660, 24, string.rep ( "_", 200 ), false, gui.main.window) gui.main.admin.visible = ( getElementData ( localPlayer, "staffLevel" ) or 0 ) > 2 guiWindowSetSizable(gui.main.window, false) -- information gui.info.account = guiCreateLabel(sx*42, sy*136, sx*269, sy*20, "Account name: none", false, gui.main.window) gui.info.group = guiCreateLabel(sx*42, sy*156, sx*269, sy*20, "Group name: none", false, gui.main.window) gui.info.rank = guiCreateLabel(sx*42, sy*176, sx*269, sy*20, "Your group rank: none", false, gui.main.window) gui.info.create_ = guiCreateButton ( sx*42, sy*280, sx*130, sy*40, "Create a group", false, gui.main.window ) gui.info.mInvites = guiCreateButton ( 180, 280, 130, 40, "My Invites", false, gui.main.window ) gui.info.gMotd = guiCreateButton ( 318, 280, 130, 40, "Group MOTD", false, gui.main.window ) -- info -> create gui.info.create.window = guiCreateWindow(sx*383, sy*227, sx*500, sy*283, "Create Group", false) guiWindowSetSizable(gui.info.create.window, false) gui.info.create.l1 = guiCreateLabel(sx*22, sy*40, sx*184, sy*20, "Group Name:", false, gui.info.create.window) gui.info.create.name = guiCreateEdit(sx*207, sy*40, sx*219, sy*20, "", false, gui.info.create.window) gui.info.create.l2 = guiCreateLabel(sx*22, sy*78, sx*184, sy*20, "Group Color:", false, gui.info.create.window) gui.info.create.cr = guiCreateEdit(sx*207, sy*78, sx*54, sy*20, "0", false, gui.info.create.window) gui.info.create.cg = guiCreateEdit(sx*261, sy*78, sx*54, sy*20, "0", false, gui.info.create.window) gui.info.create.cb = guiCreateEdit(sx*315, sy*78, sx*54, sy*20, "0", false, gui.info.create.window) gui.info.create.cpick = guiCreateButton(sx*370, sy*78, sx*56, sy*20, "cpicker", false, gui.info.create.window) gui.info.create.l3 = guiCreateLabel(sx*23, sy*122, sx*184, sy*20, "Group Type:", false, gui.info.create.window) gui.info.create.type = guiCreateComboBox(sx*204, sy*122, sx*216, sy*93, "", false, gui.info.create.window) gui.info.create.create = guiCreateButton(sx*333, sy*215, sx*87, sy*27, "Create", false, gui.info.create.window) gui.info.create.close = guiCreateButton(sx*238, sy*215, sx*87, sy*27, "Close", false, gui.info.create.window) guiEditSetReadOnly(gui.info.create.cb, true) guiEditSetReadOnly(gui.info.create.cr, true) guiEditSetReadOnly(gui.info.create.cg, true) guiComboBoxAddItem(gui.info.create.type, "Gang") guiComboBoxAddItem(gui.info.create.type, "Service") guiComboBoxAddItem(gui.info.create.type, "Group") -- info -> my invites gui.info.invites.window = guiCreateWindow(345, 146, 640, 378, "My group invites", false) guiWindowSetSizable(gui.info.invites.window, false) gui.info.invites.label = guiCreateLabel(38, 33, 504, 21, "My group invites", false, gui.info.invites.window) gui.info.invites.list = guiCreateGridList(21, 54, 599, 267, false, gui.info.invites.window) guiGridListAddColumn(gui.info.invites.list, "Group", 0.3) guiGridListAddColumn(gui.info.invites.list, "Time", 0.3) guiGridListAddColumn(gui.info.invites.list, "From", 0.3) guiGridListSetSortingEnabled ( gui.info.invites.list, false ) gui.info.invites.accept = guiCreateButton(21, 331, 117, 31, "Accept", false, gui.info.invites.window) gui.info.invites.deny = guiCreateButton(140, 331, 117, 31, "Deny", false, gui.info.invites.window) gui.info.invites.close = guiCreateButton(503, 331, 117, 31, "Close", false, gui.info.invites.window ) -- info -> motd gui.info.motd.window = guiCreateWindow(392, 169, 528, 410, "Group MOTD", false) guiWindowSetSizable(gui.info.motd.window, false) gui.info.motd.motd = guiCreateMemo(9, 26, 509, 340, "", false, gui.info.motd.window) gui.info.motd.cancel = guiCreateButton(374, 370, 144, 30, "Close", false, gui.info.motd.window) -- list gui.list.list = guiCreateGridList(sx*10, sy*108, sx*640, sy*319, false, gui.main.window) guiGridListAddColumn(gui.list.list, "Group", 0.32) guiGridListAddColumn(gui.list.list, "Group founder", 0.32) guiGridListAddColumn(gui.list.list, "Group type", 0.15) guiGridListAddColumn(gui.list.list, "Members", 0.1) guiGridListSetSortingEnabled ( gui.list.list, false ) -- my gui.my.info = guiCreateButton(10, 120, 128, 40, "Basic information", false, gui.main.window) gui.my.members = guiCreateButton(147, 122, 128, 40, "Members", false, gui.main.window) gui.my.ranks = guiCreateButton(285, 122, 128, 40, "Ranks", false, gui.main.window) gui.my.bank = guiCreateButton(424, 122, 128, 40, "Bank", false, gui.main.window) gui.my.logs = guiCreateButton(10, 170, 128, 40, "Logs", false, gui.main.window) gui.my.modColor = guiCreateButton(147, 170, 128, 40, "Change Color", false, gui.main.window) gui.my.modMotd = guiCreateButton(285, 170, 128, 40, "Change MOTD", false, gui.main.window) gui.my.leave = guiCreateButton(10, 270, 128, 40, "Leave Group", false, gui.main.window) gui.my.delete = guiCreateButton(147, 270, 128, 40, "Delete Group", false, gui.main.window) -- my -> Basic information gui.my.basic.window = guiCreateWindow(509, 233, 317, 160, "Group Information", false) guiWindowSetSizable(gui.my.basic.window, false) gui.my.basic.group = guiCreateLabel(15, 31, 241, 19, "Group: none", false, gui.my.basic.window) gui.my.basic.founder = guiCreateLabel(15, 51, 241, 19, "Origianl founder: none", false, gui.my.basic.window) gui.my.basic.founded = guiCreateLabel(15, 71, 241, 19, "Founded on: none", false, gui.my.basic.window) gui.my.basic.close = guiCreateButton(15, 100, 91, 32, "Close", false, gui.my.basic.window) -- my -> Logs gui.my.logs_.window = guiCreateWindow(341, 142, 634, 392, "Group Logs", false) guiWindowSetSizable(gui.my.logs_.window, false) gui.my.logs_.list = guiCreateGridList(9, 25, 615, 311, false, gui.my.logs_.window) guiGridListAddColumn(gui.my.logs_.list, "Time", 0.28) guiGridListAddColumn(gui.my.logs_.list, "Account", 0.2) guiGridListAddColumn(gui.my.logs_.list, "Log", 0.7) guiGridListSetSortingEnabled ( gui.my.logs_.list, false ) gui.my.logs_.close = guiCreateButton(488, 346, 136, 33, "Close", false, gui.my.logs_.window) gui.my.logs_.clear = guiCreateButton(342, 346, 136, 33, "Clear", false, gui.my.logs_.window) -- my -> Bank gui.my.bank_.window = guiCreateWindow(481, 270, 306, 141, "Group Bank", false) guiWindowSetSizable(gui.my.bank_.window, false) gui.my.bank_.balance = guiCreateLabel(14, 26, 372, 24, "Group Bank: $0", false, gui.my.bank_.window) gui.my.bank_.amount = guiCreateEdit(14, 55, 120, 23, "0", false, gui.my.bank_.window) gui.my.bank_.dep = guiCreateRadioButton(144, 40, 75, 23, "Deposit", false, gui.my.bank_.window) guiRadioButtonSetSelected(gui.my.bank_.dep, true) gui.my.bank_.go = guiCreateButton(16, 88, 120, 28, "Go", false, gui.my.bank_.window) gui.my.bank_.close = guiCreateButton(140, 88, 120, 28, "Close", false, gui.my.bank_.window) gui.my.bank_.with = guiCreateRadioButton(144, 63, 75, 23, "Withdraw", false, gui.my.bank_.window) -- my -> Ranks gui.my.ranks_.window = guiCreateWindow(551, 195, 378, 387, "Group Rank Manager", false) guiWindowSetSizable(gui.my.ranks_.window, false) gui.my.ranks_.lbl_1 = guiCreateLabel(21, 30, 220, 22, "Rank Name:", false, gui.my.ranks_.window) gui.my.ranks_.name = guiCreateEdit(21, 55, 282, 25, "", false, gui.my.ranks_.window) gui.my.ranks_.name.setMaxLength = 35 gui.my.ranks_.scroll = guiCreateScrollPane(28, 93, 313, 238, false, gui.my.ranks_.window) gui.my.ranks_.lbl_2 = guiCreateLabel(8, 9, 248, 17, "Members", false, gui.my.ranks_.scroll) guiSetFont(gui.my.ranks_.lbl_2, "default-bold-small") gui.my.ranks_['perm_member_invite'] = guiCreateCheckBox(17, 28, 273, 15, "Invite Members", false, false, gui.my.ranks_.scroll) gui.my.ranks_['perm_member_kick'] = guiCreateCheckBox(17, 43, 273, 15, "Kick Players", false, false, gui.my.ranks_.scroll) gui.my.ranks_['perm_member_setrank'] = guiCreateCheckBox(17, 58, 273, 15, "Set Members Ranks", false, false, gui.my.ranks_.scroll) gui.my.ranks_['perm_member_viewlog'] = guiCreateCheckBox(17, 73, 273, 15, "View Player Group Logs", false, false, gui.my.ranks_.scroll) gui.my.ranks_.lbl_3 = guiCreateLabel(10, 88, 248, 17, "Group Bank", false, gui.my.ranks_.scroll) guiSetFont(gui.my.ranks_.lbl_3, "default-bold-small") gui.my.ranks_['perm_bank_withdraw'] = guiCreateCheckBox(17, 105, 273, 15, "Withdraw from bank", false, false, gui.my.ranks_.scroll ) gui.my.ranks_['perm_bank_deposit'] = guiCreateCheckBox(17, 120, 273, 15, "Deposit to bank", true, false, gui.my.ranks_.scroll) gui.my.ranks_.lbl_4 = guiCreateLabel(10, 135, 248, 17, "Group Logs", false, gui.my.ranks_.scroll ) guiSetFont(gui.my.ranks_.lbl_4, "default-bold-small") gui.my.ranks_['perm_logs_view'] = guiCreateCheckBox(17, 152, 273, 15, "View group logs", true, false, gui.my.ranks_.scroll) gui.my.ranks_['perm_logs_clear'] = guiCreateCheckBox(17, 167, 273, 15, "Clear group logs", false, false, gui.my.ranks_.scroll) gui.my.ranks_.lbl_5 = guiCreateLabel(10, 182, 248, 17, "Group Ranks", false, gui.my.ranks_.scroll) guiSetFont(gui.my.ranks_.lbl_5, "default-bold-small") gui.my.ranks_['perm_ranks_create'] = guiCreateCheckBox(17, 199, 273, 15, "Create Ranks", false, false, gui.my.ranks_.scroll) gui.my.ranks_['perm_ranks_delete'] = guiCreateCheckBox(17, 214, 273, 15, "Delete Ranks", false, false, gui.my.ranks_.scroll) gui.my.ranks_.lbl_6 = guiCreateLabel(10, 229, 248, 17, "Group Settings", false, gui.my.ranks_.scroll) guiSetFont(gui.my.ranks_.lbl_6, "default-bold-small") gui.my.ranks_['perm_group_modify_color'] = guiCreateCheckBox(20, 246, 273, 15, "Modify Group MOTD", false, false, gui.my.ranks_.scroll) gui.my.ranks_['perm_group_modify_motd'] = guiCreateCheckBox(20, 261, 273, 15, "Modify Group Color", false, false, gui.my.ranks_.scroll) gui.my.ranks_.add = guiCreateButton(241, 341, 99, 28, "Add Rank", false, gui.my.ranks_.window) gui.my.ranks_.close = guiCreateButton(132, 341, 99, 28, "Cancel", false, gui.my.ranks_.window) -- my -> Members gui.my.members_.window = guiCreateWindow(345, 146, 640, 378, "My group members", false) guiWindowSetSizable(gui.my.members_.window, false) gui.my.members_.label = guiCreateLabel(38, 33, 504, 21, "My group members", false, gui.my.members_.window) gui.my.members_.list = guiCreateGridList(21, 54, 599, 267, false, gui.my.members_.window) guiGridListAddColumn(gui.my.members_.list, "Username", 0.3) guiGridListAddColumn(gui.my.members_.list, "Rank", 0.3) guiGridListAddColumn(gui.my.members_.list, "Online", 0.3) guiGridListSetSortingEnabled ( gui.my.members_.list, false ) gui.my.members_.log = guiCreateButton(21, 331, 117, 31, "This Players Log", false, gui.my.members_.window) gui.my.members_.srank = guiCreateButton(140, 331, 117, 31, "Set Rank", false, gui.my.members_.window) gui.my.members_.kick = guiCreateButton(259, 331, 117, 31, "Kick", false, gui.my.members_.window) gui.my.members_.invite = guiCreateButton(378, 331, 117, 31, "Invite", false, gui.my.members_.window) gui.my.members_.close = guiCreateButton(503, 331, 117, 31, "Close", false, gui.my.members_.window ) --> my -> Members -> Player Log gui.my.members_.lWindow = guiCreateWindow(341, 142, 634, 392, "Player Log", false) guiWindowSetSizable(gui.my.members_.window, false) gui.my.members_.lList = guiCreateGridList(9, 25, 615, 311, false, gui.my.members_.lWindow) guiGridListAddColumn(gui.my.members_.lList, "Time", 0.28) guiGridListAddColumn(gui.my.members_.lList, "Account", 0.2) guiGridListAddColumn(gui.my.members_.lList, "Log", 0.7) guiGridListSetSortingEnabled ( gui.my.members_.lList, false ) gui.my.members_.lClose = guiCreateButton(488, 346, 136, 33, "Close", false, gui.my.members_.lWindow) -- my -> Members -> Set rank gui.my.members_.rWindow = guiCreateWindow(502, 128, 266, 414, "Group Rank", false) guiWindowSetSizable(gui.my.members_.rWindow, false) gui.my.members_.rRanks = guiCreateComboBox(14, 66, 236, 304, "", false, gui.my.members_.rWindow) gui.my.members_.rUpdate = guiCreateButton(18, 35, 113, 25, "Update", false, gui.my.members_.rWindow) gui.my.members_.rClose = guiCreateButton(137, 35, 113, 25, "Cancel", false, gui.my.members_.rWindow) -- my -> Members -> Invite gui.my.members_.iWindow = guiCreateWindow(339, 162, 611, 296, "Invite Players", false) guiWindowSetSizable(gui.my.members_.iWindow, false) gui.my.members_.iList = guiCreateGridList(9, 22, 592, 223, false, gui.my.members_.iWindow) guiGridListAddColumn(gui.my.members_.iList, "Player", 0.9) gui.my.members_.iLabel = guiCreateLabel(16, 254, 102, 27, "Search Player:", false, gui.my.members_.iWindow) guiLabelSetVerticalAlign(gui.my.members_.iLabel, "center") gui.my.members_.iFilter = guiCreateEdit(118, 253, 184, 28, "", false, gui.my.members_.iWindow) gui.my.members_.iClose = guiCreateButton(531, 255, 70, 25, "Close", false, gui.my.members_.iWindow) gui.my.members_.iInvite = guiCreateButton(451, 256, 70, 25, "Invite", false, gui.my.members_.iWindow) -- my -> change motd gui.my.motd.window = guiCreateWindow(392, 169, 528, 410, "", false) guiWindowSetSizable(gui.my.motd.window, false) gui.my.motd.motd = guiCreateMemo(9, 26, 509, 340, "", false, gui.my.motd.window) gui.my.motd.update = guiCreateButton(374, 370, 144, 30, "Update", false, gui.my.motd.window) gui.my.motd.cancel = guiCreateButton(220, 370, 144, 30, "Cancel", false, gui.my.motd.window) -- Administration Panel (NG 1.1.4) gui.admin.window = guiCreateWindow(386, 123, 608, 421, "NG Group Manager (Staff)", false) guiWindowSetSizable(gui.admin.window, false) gui.admin.admin.groupList = guiCreateGridList(9, 21, 401, 390, false, gui.admin.window) guiGridListSetSortingEnabled ( gui.admin.admin.groupList, false ); guiGridListAddColumn ( gui.admin.admin.groupList, "Group", 0.5 ); guiGridListAddColumn ( gui.admin.admin.groupList, "Founder", 0.3 ); guiGridListAddColumn ( gui.admin.admin.groupList, "Members", 0.15 ); gui.admin.admin.groupInfo = guiCreateButton(412, 26, 186, 29, "Basic Information", false, gui.admin.window) gui.admin.admin.groupMembers = guiCreateButton(412, 65, 186, 29, "Members", false, gui.admin.window) gui.admin.admin.groupRanks = guiCreateButton(412, 104, 186, 29, "Ranks", false, gui.admin.window) gui.admin.admin.groupLogs = guiCreateButton(412, 143, 186, 29, "Logs", false, gui.admin.window) gui.admin.admin.closeWindow = guiCreateButton(412, 382, 186, 29, "Close", false, gui.admin.window) gui.admin.admin.deleteGroup = guiCreateButton(412, 182, 186, 29, "Delete Group", false, gui.admin.window) guiSetProperty(gui.admin.admin.deleteGroup, "NormalTextColour", "FFFF0000") -- manager->Basic Information gui.admin.info.window = guiCreateWindow(445, 148, 559, 399, "Group Information", false) guiWindowSetSizable(gui.admin.info.window, false) gui.admin.info.list = guiCreateGridList(9, 29, 540, 314, false, gui.admin.info.window) guiGridListAddColumn(gui.admin.info.list, "Data Set", 0.4) guiGridListAddColumn(gui.admin.info.list, "Value", 0.5) gui.admin.info.close = guiCreateButton(10, 353, 164, 36, "Close", false, gui.admin.info.window) -- manager->members gui.admin.members.window = guiCreateWindow(445, 148, 559, 399, "Group Members", false) guiWindowSetSizable(gui.admin.members.window, false) gui.admin.members.list = guiCreateGridList(9, 29, 540, 314, false, gui.admin.members.window) guiGridListAddColumn(gui.admin.members.list, "Account", 0.3) guiGridListAddColumn(gui.admin.members.list, "Rank", 0.3) guiGridListAddColumn(gui.admin.members.list, "Joined", 0.3) gui.admin.members.close = guiCreateButton(10, 353, 164, 36, "Close", false, gui.admin.members.window) -- manager->ranks gui.admin.ranks.window = guiCreateWindow(445, 148, 559, 399, "Group Members", false) guiWindowSetSizable(gui.admin.ranks.window, false) gui.admin.ranks.list = guiCreateGridList(9, 29, 540, 314, false, gui.admin.ranks.window) guiGridListAddColumn(gui.admin.ranks.list, "Permission", 0.5) guiGridListAddColumn(gui.admin.ranks.list, "Access", 0.4) gui.admin.ranks.close = guiCreateButton(10, 353, 164, 36, "Close", false, gui.admin.ranks.window) -- manager->logs gui.admin.logs.window = guiCreateWindow(445, 148, 559, 399, "Group Logs", false) guiWindowSetSizable(gui.admin.logs.window, false) gui.admin.logs.list = guiCreateGridList(9, 29, 540, 314, false, gui.admin.logs.window) guiGridListAddColumn(gui.admin.logs.list, "Account", 0.25) guiGridListAddColumn(gui.admin.logs.list, "Time", 0.25) guiGridListAddColumn(gui.admin.logs.list, "Log", 0.8) gui.admin.logs.close = guiCreateButton(10, 353, 164, 36, "Close", false, gui.admin.logs.window) local sx, sy = sx__, sy__ local doElements = { } for i, v in pairs ( gui ) do if ( type ( v ) ~= "table" ) then table.insert ( doElements, v ) else for i, v in pairs ( v ) do if ( type ( v ) ~= "table" ) then table.insert ( doElements, v ) else for i, v in pairs ( v ) do if ( type ( v ) ~= "table" ) then table.insert ( doElements, v ) end end end end end end -- Window Visibilities guiSetVisible ( gui.my.basic.window , false ) guiSetVisible ( gui.my.logs_.window, false ) guiSetVisible ( gui.info.create.window, false ) guiSetVisible ( gui.my.bank_.window, false ) guiSetVisible ( gui.my.members_.window, false ) gui.my.members_.lWindow.visible = false gui.my.members_.rWindow.visible = false gui.my.members_.iWindow.visible = false gui.info.invites.window.visible = false gui.my.ranks_.window.visible = false gui.my.motd.window.visible = false gui.info.motd.window.visible = false gui.admin.window.visible = false gui.admin.info.window.visible = false gui.admin.members.window.visible = false gui.admin.ranks.window.visible = false gui.admin.logs.window.visible = false -- reposition and resize for i, v in pairs ( doElements ) do local t = getElementType ( v ) local x, y = guiGetPosition ( v, false ) local w, h = guiGetSize ( v, false ) --guiSetSize ( v, sx*w, sx*h, false ) local w, h = guiGetSize ( v, false ) if ( t == "gui-window" ) then x, y = ( sx_/2-w/2 ), ( sy_/2-h/2 ) end guiSetPosition ( v, x, y, false ) x, y, w, h, t = nil, nil, nil, nil, nil end showCursor ( true ) doElements = nil triggerServerEvent ( "NGGroups->Events:onClientRequestGroupList", localPlayer ) guiSetInputMode ( "no_binds_when_editing" ) end function isset ( f ) if ( f ) then return true end return false end function loadGroupPage ( p, AllowElementsToStay, arg1 ) if ( not AllowElementsToStay ) then if ( not gui ) then return exports.ngmessages:sendClientMessage ( "Please allow the GUI to finish loading...", 255, 255, 0 ); end for i, t in pairs ( gui ) do for _, v in pairs ( t ) do if ( type ( v ) ~= "table" ) then if ( i ~= "main" and isElement ( v ) ) then guiSetVisible ( v, false ) end end end end end -- core features if ( p == "core.admin" ) then gui.admin.window.visible = true; gui.admin.window:bringToFront(); guiGridListClear ( gui.admin.admin.groupList ); for gName, info in pairs ( gList ) do local row = guiGridListAddRow ( gui.admin.admin.groupList ); if ( not r ) then r = 255; end if ( not g ) then g = 255; end if ( not b ) then b = 255; end guiGridListSetItemText ( gui.admin.admin.groupList, row, 1, tostring ( gName ), false, false ); guiGridListSetItemText ( gui.admin.admin.groupList, row, 2, tostring ( info.info.founder ), false, false ); guiGridListSetItemText ( gui.admin.admin.groupList, row, 3, table.len ( info.members ), false, false ); for i=1,3 do guiGridListSetItemColor ( gui.admin.admin.groupList, row, i, info.info.color.r, info.info.color.g, info.info.color.b ); end end elseif ( p == "core.info" ) then for i, v in pairs ( gui.info ) do if ( v and isElement ( v ) ) then guiSetVisible ( v, true ) end end local acc = tostring ( getElementData ( localPlayer, "AccountData:Username" ) or "none" ) guiSetText ( gui.info.account, "Your Account: "..acc ) guiSetText ( gui.info.group, "Your group: "..tostring ( group or "None" ) ) guiSetText ( gui.info.rank, "Your Rank: "..tostring ( rank or "None" ) ) local group = tostring ( group ) if ( group and gList and gList [ group ] ) then else if ( group and group:lower() ~= "none" ) then setElementData ( localPlayer, "Group", "None" ) setElementData ( localPlayer, "Group Rank", "None") group = nil rank = nil end end -- Button locked permissions guiSetEnabled ( gui.main.my, isset ( group ) ) gui.info.gMotd.enabled = isset ( group ) guiSetEnabled ( gui.info.create_, not isset ( group ) ) if ( group and group:lower() ~= "none" ) then guiSetEnabled ( gui.my.members_.kick, gList[group].ranks[rank].member_kick or false ) guiSetEnabled ( gui.my.members_.srank, gList[group].ranks[rank].member_setrank or false ) guiSetEnabled ( gui.my.members_.log, gList[group].ranks[rank].member_viewlog or false ) gui.my.members_.invite.enabled = gList[group].ranks[rank].member_invite or false gui.my.delete.enabled = ( rank == "Founder" ) gui.my.leave.enabled = ( rank ~= "Founder" ) gui.my.logs.enabled = gList[group].ranks[rank].logs_view or false gui.my.logs_.clear.enabled = gList[group].ranks[rank].logs_clear or false gui.my.modColor.enabled = gList[group].ranks[rank].group_modify_color or false gui.my.modMotd.enabled = gList[group].ranks[rank].group_modify_motd or false end elseif ( p == "core.list" ) then guiGridListClear ( gui.list.list ) guiSetVisible ( gui.list.list, true ) local total = 0 for name, v in pairs ( gList ) do if ( table.len ( v.members ) ~= 0 ) then local r, g, b = v.info.color.r, v.info.color.g, v.info.color.b local ro = guiGridListAddRow ( gui.list.list ) guiGridListSetItemText ( gui.list.list, ro, 1, tostring ( name ), false, false ) guiGridListSetItemText ( gui.list.list, ro, 2, tostring ( v.info.founder ), false, false ) guiGridListSetItemText ( gui.list.list, ro, 3, tostring ( v.info.type ), false, false ) guiGridListSetItemText ( gui.list.list, ro, 4, tostring ( table.len ( v.members ) ), false, false ) for i=1, 4 do guiGridListSetItemColor ( gui.list.list, ro, i, r, g, b ) end r, g, b, ro = nil, nil, nil, nil total = 1 else triggerServerEvent ( "NGGroups->Modules->Gangs->Force->DeleteGroup", resourceRoot, tostring ( name ) ) end end if ( total == 0 ) then guiGridListSetItemText ( gui.list.list, guiGridListAddRow ( gui.list.list ), 1, "There's currently no groups", true, true ) end elseif ( p == "core.my" ) then for i, v in pairs ( gui.my ) do if ( type ( v ) ~= "table" and isElement ( v ) ) then guiSetVisible ( v, true ) end end elseif ( p == "core.myInvites" ) then gui.info.invites.window.visible = true guiBringToFront( gui.info.invites.window ) guiGridListClear ( gui.info.invites.list ) for i, v in pairs ( gList ) do if ( #v.pendingInvites > 0 ) then for index, info in pairs ( v.pendingInvites ) do if ( info.to == getElementData ( localPlayer, "AccountData:Username" ) ) then local r = guiGridListAddRow ( gui.info.invites.list ) guiGridListSetItemText ( gui.info.invites.list, r, 1, tostring ( i ), false, false ) guiGridListSetItemText ( gui.info.invites.list, r, 2, tostring ( info.time ), false, false ) guiGridListSetItemText ( gui.info.invites.list, r, 3, tostring ( info.inviter ), false, false ) end end end end elseif ( p == "my.basicInfo" ) then guiSetVisible ( gui.my.basic.window, true ) guiBringToFront ( gui.my.basic.window ) guiSetText ( gui.my.basic.group, "Group: ".. tostring ( group or "none" ) ) if ( gList and group and gList[group] ) then guiSetText ( gui.my.basic.founder, "Original founder: "..tostring ( gList[group].info.founder or "none" ) ) guiSetText ( gui.my.basic.founded, "Founded on: "..tostring ( gList[group].info.founded_time or "unknown" )) else guiSetText ( gui.my.basic.founder, "Original founder: none" ) guiSetText ( gui.my.basic.founded, "Founded on: unknown") end elseif ( p == "my.logs" ) then guiSetVisible ( gui.my.logs_.window, true ) guiBringToFront ( gui.my.logs_.window ) guiGridListClear ( gui.my.logs_.list ) for i, v in ipairs ( gList[group].log ) do local r = guiGridListAddRow ( gui.my.logs_.list ) guiGridListSetItemText ( gui.my.logs_.list, r, 1, tostring ( v.time ), false, false ) guiGridListSetItemText ( gui.my.logs_.list, r, 2, tostring ( v.account ), false, false ) guiGridListSetItemText ( gui.my.logs_.list, r, 3, tostring ( v.log ), false, false ) end elseif ( p == "my.bank" ) then guiSetVisible ( gui.my.bank_.window, true ) guiSetEnabled ( gui.my.bank_.amount, false ) guiSetEnabled ( gui.my.bank_.go, false ) guiSetEnabled ( gui.my.bank_.with, false ) guiSetEnabled ( gui.my.bank_.dep, false ) guiSetText ( gui.my.bank_.balance, "Group Balance: Loading..." ) triggerServerEvent ( "NGGroups:Module->Bank:returnBankBalanceToClient", localPlayer, group ) guiBringToFront ( gui.my.bank_.window ) elseif ( p == "core.create" ) then guiSetVisible ( gui.info.create.window, true ) guiBringToFront ( gui.info.create.window ) elseif ( p == "my.members" ) then gui.my.members_.window.visible = true gui.my.members_.list.clear ( gui.my.members_.list ) for i, v in pairs ( gList [ group ].members ) do local r = guiGridListAddRow ( gui.my.members_.list ) gui.my.members_.list.setItemText ( gui.my.members_.list, r, 1, tostring ( i ), false, false ) gui.my.members_.list.setItemText ( gui.my.members_.list, r, 2, tostring ( v.rank ), false, false ) local online = "No" for _, k in pairs ( getElementsByType ( "player" ) ) do local acc = getElementData ( k, "AccountData:Username" ) if ( acc and acc == i ) then online = "Yes" break end end gui.my.members_.list.setItemText ( gui.my.members_.list, r, 3, tostring ( online ), false, false ) for k=1, 3 do local r, g, b = 0, 255, 0 if ( online == "No" ) then r, g, b = 255, 0, 0 end guiGridListSetItemColor ( gui.my.members_.list, r, k, r, g, b ) end end end end function onClientGuiClick ( ) -- core buttons if ( source == gui.main.info ) then loadGroupPage ( "core.info" ) elseif ( source == gui.main.list ) then loadGroupPage ( "core.list" ) elseif ( source == gui.main.my ) then loadGroupPage ( "core.my" ) elseif ( source == gui.main.admin ) then loadGroupPage ( "core.admin", true ); -- Group administration (Staff) elseif ( source == gui.admin.admin.closeWindow ) then gui.admin.window.visible = false; elseif ( source == gui.admin.info.close ) then gui.admin.info.window.visible = false; elseif ( source == gui.admin.members.close ) then gui.admin.members.window.visible = false; elseif ( source == gui.admin.ranks.close ) then gui.admin.ranks.window.visible = false; elseif ( source == gui.admin.logs.close ) then gui.admin.logs.window.visible = false; elseif ( source == gui.admin.admin.groupInfo ) then local r, c = guiGridListGetSelectedItem ( gui.admin.admin.groupList ); if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group is selected", 255, 255, 255 ); end gui.admin.info.window.visible = true; gui.admin.info.window:bringToFront ( ); guiGridListClear ( gui.admin.info.list ); for index, value in pairs ( gList [ guiGridListGetItemText ( gui.admin.admin.groupList, r, 1 ) ].info ) do local r = guiGridListAddRow ( gui.admin.info.list ); guiGridListSetItemText ( gui.admin.info.list, r, 1, tostring ( index ), false, false ) if ( index == "color" ) then value = table.concat ( { value.r, value.g, value.b }, ", " );end guiGridListSetItemText ( gui.admin.info.list, r, 2, tostring ( value ), false, false ) end elseif ( source == gui.admin.admin.groupMembers ) then local r, c = guiGridListGetSelectedItem ( gui.admin.admin.groupList ); if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group is selected", 255, 255, 255 ); end gui.admin.members.window.visible = true; gui.admin.members.window:bringToFront ( ); guiGridListClear ( gui.admin.members.list ); for member, info in pairs ( gList [ guiGridListGetItemText ( gui.admin.admin.groupList, r, 1 ) ].members ) do local r = guiGridListAddRow ( gui.admin.members.list ); guiGridListSetItemText ( gui.admin.members.list, r, 1, tostring ( member ), false, false ) guiGridListSetItemText ( gui.admin.members.list, r, 2, tostring ( info.rank ), false, false ) guiGridListSetItemText ( gui.admin.members.list, r, 3, tostring ( info.joined ), false, false ) end elseif ( source == gui.admin.admin.groupRanks ) then local r, c = guiGridListGetSelectedItem ( gui.admin.admin.groupList ); if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group is selected", 255, 255, 255 ); end gui.admin.ranks.window.visible = true; gui.admin.ranks.window:bringToFront ( ); guiGridListClear ( gui.admin.ranks.list ); for rank, permissions in pairs ( gList [ guiGridListGetItemText ( gui.admin.admin.groupList, r, 1 ) ].ranks ) do guiGridListSetItemText ( gui.admin.ranks.list, guiGridListAddRow ( gui.admin.ranks.list ), 1, tostring ( rank ), true, true ); for permission, access in pairs ( permissions ) do local r = guiGridListAddRow ( gui.admin.ranks.list ); local sAccess = ( access and "Yes" ) or "No"; guiGridListSetItemText ( gui.admin.ranks.list, r, 1, tostring ( permission ), false, false ); guiGridListSetItemText ( gui.admin.ranks.list, r, 2, sAccess, false, false ); if ( sAccess == "Yes" ) then guiGridListSetItemColor ( gui.admin.ranks.list, r, 1, 0, 255, 0 ); guiGridListSetItemColor ( gui.admin.ranks.list, r, 2, 0, 255, 0 ); else guiGridListSetItemColor ( gui.admin.ranks.list, r, 1, 255, 0, 0 ); guiGridListSetItemColor ( gui.admin.ranks.list, r, 2, 255, 0, 0 ); end end end elseif ( source == gui.admin.admin.groupLogs ) then local r, c = guiGridListGetSelectedItem ( gui.admin.admin.groupList ); if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group is selected", 255, 255, 255 ); end gui.admin.logs.window.visible = true; gui.admin.logs.window:bringToFront ( ); guiGridListClear ( gui.admin.logs.list ); for _, log in pairs ( gList [ guiGridListGetItemText ( gui.admin.admin.groupList, r, 1 ) ].log ) do local r = guiGridListAddRow ( gui.admin.logs.list ); guiGridListSetItemText ( gui.admin.logs.list, r, 1, tostring ( log.account ), false, false ); guiGridListSetItemText ( gui.admin.logs.list, r, 2, tostring ( log.time ), false, false ); guiGridListSetItemText ( gui.admin.logs.list, r, 3, tostring ( log.log ), false, false ); end elseif ( source == gui.admin.admin.deleteGroup ) then local r, c = guiGridListGetSelectedItem ( gui.admin.admin.groupList ); if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group is selected", 255, 255, 255 ); end local group = tostring ( guiGridListGetItemText ( gui.admin.admin.groupList, r, 1 ) ); askConfirm ( "Are you really sure you want to delete this group?", function ( done, group ) if ( not done )then return end triggerServerEvent ( "NGGroups->GroupStaff:OnAdminDeleteGroup", localPlayer, group ); end, group ) -- my buttons elseif ( source == gui.my.info ) then loadGroupPage ( "my.basicInfo", true ) elseif ( source == gui.my.basic.close ) then guiSetVisible ( gui.my.basic.window, false ) elseif ( source == gui.my.logs ) then loadGroupPage ( "my.logs", true ) elseif ( source == gui.my.logs_.close ) then guiSetVisible ( gui.my.logs_.window, false ) elseif ( source == gui.my.logs_.clear ) then askConfirm ( "Are you sure you would like to clear your group logs?", function ( v ) if ( not v ) then return end triggerServerEvent ( "NGGroups->GEvents:onPlayerClearGroupLog", localPlayer, group ) gui.my.logs_.window.visible = false end ) -- Create window elseif ( source == gui.info.create_ ) then loadGroupPage ( "core.create", true ) elseif ( source == gui.info.create.close ) then guiSetVisible ( gui.info.create.window, false ) elseif ( source == gui.info.create.cpick ) then exports.cpicker:openPicker ( "GroupColorPicker", { r=tonumber(guiGetText(gui.info.create.cr)), g=tonumber(guiGetText(gui.info.create.cg)), b=tonumber(guiGetText(gui.info.create.cb)), a=255 }, "Group Color Picker" ) elseif ( source == gui.info.create.create ) then local name = tostring ( guiGetText ( gui.info.create.name ) ) local r=tonumber(guiGetText(gui.info.create.cr)) local g=tonumber(guiGetText(gui.info.create.cg)) local b=tonumber(guiGetText(gui.info.create.cb)) local tp = tostring ( guiGetText ( gui.info.create.type ) ) if ( name:gsub ( " ", "" ) == "" ) then return exports.ngmessages:sendClientMessage ( "You need to enter a name", 255, 255, 0 ) end if ( tp:gsub ( " ", "" ) == "" ) then return exports.ngmessages:sendClientMessage ( "Please select a group type", 255, 255, 0 ) end if ( not r or not g or not b ) then return exports.ngmessages:sendClientMessage ( "Please select a group color", 255, 255, 0 ) end local color = { r = r, g = g, b = b } triggerServerEvent ( "NGGroups->GEvents:onPlayerAttemptGroupMake", localPlayer, { name=name, type = tp, color=color } ) -- invites elseif ( source == gui.info.mInvites ) then loadGroupPage ( "core.myInvites", true ) elseif ( source == gui.info.invites.close ) then gui.info.invites.window.visible = false elseif ( source == gui.info.invites.deny ) then local r, c = guiGridListGetSelectedItem ( gui.info.invites.list ) if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group selected", 255, 0, 0 ) end exports.ngmessages:sendClientMessage("You denied the invite to "..guiGridListGetItemText ( gui.info.invites.list, r, 1 ) ) triggerServerEvent ( "NGGroups->Modules->Groups->Invites->OnPlayerDeny", localPlayer, guiGridListGetItemText ( gui.info.invites.list, r, 1 ) ) elseif ( source == gui.info.invites.accept ) then local r, c = guiGridListGetSelectedItem ( gui.info.invites.list ) if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No group selected", 255, 0, 0 ) elseif ( group and group:lower() ~= "none" ) then return exports.ngmessages:sendClientMessage ( "You need to leave your group before joining another one.", 255, 255, 0 ) end triggerServerEvent ( "NGGroups->Modules->Groups->Invites->OnPlayerAccept", localPlayer, guiGridListGetItemText ( gui.info.invites.list, r, 1 ) ) -- bank elseif ( source == gui.my.bank ) then loadGroupPage ( "my.bank", true ); elseif ( source == gui.my.bank_.close ) then gui.my.bank_.window.visible = false elseif ( source == gui.my.bank_.go ) then local a = tonumber ( gui.my.bank_.amount.text ); if ( not a ) then return exports.ngmessages:sendClientMessage ( "Invalid cash amount", 255, 0, 0 ); end local a = math.floor ( a ) if ( a <= 0 ) then return exports.ngmessages:sendClientMessage ( "Please enter a number greater than 0", 255, 0, 0 ) end -- run this to check if they have access if ( gui.my.bank_.with.selected ) then triggerServerEvent ( "NGGroups:Modules->BankSys:onPlayerAttemptWithdawl", localPlayer, group, a ) gui.my.bank_.window.visible = false elseif ( gui.my.bank_.dep.selected ) then triggerServerEvent ( "NGGroups:Modules->BankSys:onPlayerAttemptDeposit", localPlayer, group, a ) gui.my.bank_.window.visible = false else return exports.ngmessages:sendClientMessage ( "Please select your method (Deposit/Withdraw)", 255, 255, 0 ) end -- delete elseif ( source == gui.my.delete ) then askConfirm ( "Are you sure you want to delete your gang? You will not be able to get it back.", function ( x ) if ( not x ) then return end triggerServerEvent ( "NGGroups->gEvents:onPlayerDeleteGroup", localPlayer, group, a ) end ) -- leave elseif ( source == gui.my.leave ) then askConfirm ( "Are you sure you want to leave "..tostring(group).."?", function ( x ) if ( not x ) then return end triggerServerEvent ( "NGGroups->Modules->Groups->OnPlayerLeave", localPlayer, group ) end ) -- Members window elseif ( source == gui.my.members ) then loadGroupPage ( "my.members", true ) gui.main.window.visible = false elseif ( source == gui.my.members_.close ) then gui.my.members_.window.visible = false gui.main.window.visible = true if ( gui.my.members_.lWindow.visible ) then gui.my.members_.lWindow.visible = false end if ( isElement( gui.my.members_.iWindow ) ) then destroyElement ( gui.my.members_.iWindow ) end elseif ( source == gui.my.members_.log ) then local r, c = guiGridListGetSelectedItem ( gui.my.members_.list ) if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "You need to select an account", 255, 0, 0 ) end guiGridListClear ( gui.my.members_.lList ) gui.my.members_.viewingPlayer = guiGridListGetItemText ( gui.my.members_.list, r, 1 ) gui.my.members_.lWindow.visible = true; gui.my.members_.lWindow.text = "Player Group Log - ".. tostring ( gui.my.members_.viewingPlayer ) gui.my.members_.lWindow.bringToFront ( gui.my.members_.lWindow ) local sum = 0 for i, v in ipairs ( gList [ group ].log ) do if ( v.account == gui.my.members_.viewingPlayer ) then sum = sum + 1 local r = guiGridListAddRow ( gui.my.members_.lList ) guiGridListSetItemText ( gui.my.members_.lList, r, 1, v.time, false, false ) guiGridListSetItemText ( gui.my.members_.lList, r, 2, v.account, false, false ) guiGridListSetItemText ( gui.my.members_.lList, r, 3, v.log, false, false ) end end if ( sum == 0 ) then guiGridListSetItemText ( gui.my.members_.lList, guiGridListAddRow ( gui.my.members_.lList ), 1, "This player has no logs", true, true ) end elseif ( source == gui.my.members_.lClose ) then gui.my.members_.viewingPlayer = nil gui.my.members_.lWindow.visible = false gui.my.members_.rWindow.visible = false elseif ( source == gui.my.members_.kick ) then local r, c = guiGridListGetSelectedItem ( gui.my.members_.list ) if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "You need to select an account", 255, 0, 0 ) end local a = guiGridListGetItemText ( gui.my.members_.list, r, 1 ) askConfirm ( "Are you sure you want to kick \"".. a .."\"?", function ( x ) if ( not x ) then return end if ( gList [ group ].members [ a ].rank == "Founder" ) then return exports.ngmessages:sendClientMessage ( "You cannot kick the gang founder", 255, 0, 0 ) elseif( a == getElementData ( localPlayer, "AccountData:Username" ) ) then return exports.ngmessages:sendClientMessage ( "You can't kick yourself from the gang", 255, 0, 0 ) end triggerServerEvent ( "NGGroups->Modules->Gangs->kickPlayer", localPlayer, group, a ) end ) elseif ( source == gui.my.members_.srank ) then local r, c = guiGridListGetSelectedItem ( gui.my.members_.list ) if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "You need to select an account", 255, 0, 0 ) end local a = guiGridListGetItemText ( gui.my.members_.list, r, 1 ) gui.my.members_.viewingPlayer1 = a gui.my.members_.rWindow.visible = true guiBringToFront ( gui.my.members_.rWindow ) guiComboBoxClear ( gui.my.members_.rRanks ) for i, v in pairs ( gList[group].ranks ) do local f = guiComboBoxAddItem ( gui.my.members_.rRanks, tostring ( i ) ) if ( tostring ( i ) == gList[group].members[a].rank ) then guiComboBoxSetSelected ( gui.my.members_.rRanks, f ) end end elseif ( source == gui.my.members_.rUpdate ) then local nrank = guiComboBoxGetItemText ( gui.my.members_.rRanks, guiComboBoxGetSelected ( gui.my.members_.rRanks ) ) askConfirm ( "Are you sure you want to change "..gui.my.members_.viewingPlayer1.."'s rank to from "..gList[group].members[gui.my.members_.viewingPlayer1].rank.." to "..nrank.."?", function ( x, nrank ) if ( not x ) then return end gui.my.members_.rWindow.visible = false if ( gui.my.members_.viewingPlayer1 == getElementData ( localPlayer, "AccountData:Username" ) ) then return exports.ngmessages:sendClientMessage ( "You cannot change your own rank.", 255, 0, 0 ) elseif ( gList[group].members[gui.my.members_.viewingPlayer1].rank == "Founder" ) then return exports.ngmessages:sendClientMessage ( "You cannot change the founders rank", 255, 0, 0 ) elseif ( nrank:lower ( ) == "founder" ) then return exports.ngmessages:sendClientMessage ( "You cannot set players rank to 'founder'", 255, 255, 0 ) end triggerServerEvent ( "NGGroups->Modules->Gangs->Ranks->UpdatePlayerrank", localPlayer, group, gui.my.members_.viewingPlayer1, nrank ); gui.my.members_.viewingPlayer1 = false end, nrank ) elseif ( source == gui.my.members_.rClose ) then gui.my.members_.rWindow.visible = false -- Invite Window elseif ( source == gui.my.members_.invite ) then gui.my.members_.iWindow.visible = true guiBringToFront ( gui.my.members_.iWindow ) guiGridListClear ( gui.my.members_.iList ) gui.my.members_.iFilter.text = ""; for i,v in ipairs ( getElementsByType ( "player" ) ) do guiGridListSetItemText ( gui.my.members_.iList, guiGridListAddRow ( gui.my.members_.iList ), 1, v.name, false, false ) end elseif ( source == gui.my.members_.iClose ) then gui.my.members_.iWindow.visible = false elseif ( source == gui.my.members_.iInvite ) then local r, c = guiGridListGetSelectedItem ( gui.my.members_.iList ) if ( r == -1 ) then return exports.ngmessages:sendClientMessage ( "No player selected", 255, 0, 0 ) end local name = guiGridListGetItemText ( gui.my.members_.iList, r, 1 ) if ( not getPlayerFromName ( name ) ) then return exports.ngmessages:sendClientMessage ( "Sorry, this player is no longer on the server, or has changed their nickname", 255, 0, 0 ) end local plr = getPlayerFromName ( name ) if ( tostring ( plr.getData ( plr, "Group" ) ):lower ( ) == group:lower ( ) ) then return exports.ngmessages:sendClientMessage ( "This player is already in your group", 255, 0, 0 ) end triggerServerEvent ( "NGGroups->Modules->Groups->InvitePlayer", localPlayer, group, plr ) gui.my.members_.iWindow.visible = false; -- Ranks elseif ( source == gui.my.ranks ) then gui.my.ranks_.window.visible = true guiBringToFront ( gui.my.ranks_.window ) guiSetInputMode ( "no_binds_when_editing" ) elseif ( source == gui.my.ranks_.close) then gui.my.ranks_.window.visible = false elseif ( source == gui.my.ranks_.add ) then local name = gui.my.ranks_.name.text; if ( name:gsub ( " ", "" ) == "") then return exports.ngmessages:sendClientMessage ( "Invalid rank name.", 255, 255, 0 ) end for i, v in pairs ( gList[group].ranks ) do if ( tostring ( i ):lower ( ) == name:lower ( ) ) then return exports.ngmessages:sendClientMessage ( "This rank already exists in your group", 255, 255, 0 ) end end askConfirm ( "Are you sure you want to add '"..name.."' to the group?", function ( x, name ) if ( not x ) then return end local permTable = { } for i, v in pairs ( gui.my.ranks_ ) do if ( tostring ( i ):sub ( 0, 5 ) == "perm_" ) then permTable [ tostring(i):sub(6,tostring(i):len()) ] = v.selected end end triggerServerEvent ( "NGGroups->Modules->Groups->Ranks->AddRank", localPlayer, group, name, permTable ) end, name ) -- change group color elseif ( source == gui.my.modColor ) then exports.cpicker:openPicker ( "changeGroupColorPicker", { r = 0, g = 0, b = 0, a = 0 }, "Group Color" ) elseif ( source == gui.my.modMotd ) then guiSetInputMode ( "no_binds_when_editing" ) gui.my.motd.window.visible = true gui.my.motd.motd.text = gList[group].info.desc or "" guiBringToFront( gui.my.motd.window ) guiSetInputMode( "no_binds_when_editing" ) elseif ( source == gui.my.motd.cancel ) then gui.my.motd.window.visible = false elseif( source == gui.my.motd.update ) then askConfirm ( "Are you sure you want to change the group MOTD?", function ( x ) if not x then return end local t = gui.my.motd.motd.text; triggerServerEvent ( "NGGroups->Modules->Groups->MOTD->Update", localPlayer, group, t ) end ) -- motd window elseif ( source == gui.info.gMotd ) then gui.info.motd.window.visible = true local desk = gList[group].info.desc if ( not desk or desk:gsub ( " ", "" ) == "" ) then desk = "None" end gui.info.motd.motd.text = tostring ( desk ) guiBringToFront ( gui.info.motd.window ) elseif ( source == gui.info.motd.cancel ) then gui.info.motd.window.visible = false end end function onClientGuiChanged ( ) if ( gui and gui.my and gui.my.members_ and gui.my.members_.iFilter and source == gui.my.members_.iFilter ) then local t = source.text:lower(); guiGridListClear ( gui.my.members_.iList ) for i, v in ipairs ( getElementsByType ( "player" ) ) do if ( v.name:lower():find ( t ) ) then guiGridListSetItemText ( gui.my.members_.iList, guiGridListAddRow ( gui.my.members_.iList ), 1, v.name, false, false ) end end elseif ( gui and gui.my and gui.my.name_ and gui.my.ranks_.name ) then local t = source.text(); if ( t ~= "" ) then local tmp = t tmp = tmp:gsub ( "%p", "" ); source.text = tmp end end end addEvent ( "onColorPickerOK", true ) addEventHandler ( "onColorPickerOK", root, function ( id, _, r, g, b ) if ( id == "GroupColorPicker" ) then guiSetText ( gui.info.create.cr, tostring ( r ) ) guiSetText ( gui.info.create.cg, tostring ( g ) ) guiSetText ( gui.info.create.cb, tostring ( b ) ) elseif ( id == "changeGroupColorPicker" ) then askConfirm ( "Are you sure you want to change the group color?", function ( x, r, g, b ) if ( not x ) then return x end triggerServerEvent ( "NGGroups->Modules->Groups->Colors->UpdateColor", localPlayer, group, r, g, b ) end, r, g, b ) end end ) function onPlayerOpenPanel ( ) if ( not exports.nglogin:isClientLoggedin ( ) ) then return end if ( gui and isElement ( gui.main.window ) ) then if ( isElement ( gui.my.members_.window ) and guiGetVisible ( gui.my.members_.window ) ) then return false end removeEventHandler ( "onClientGUIClick", root, onClientGuiClick ) removeEventHandler ( "onClientGUIChanged", root, onClientGuiChanged ) destroyElement ( gui.main.window ) if ( isElement ( gui.my.info_window ) ) then destroyElement ( gui.my.info_window ) end if ( isElement ( gui.my.basic.window ) ) then destroyElement ( gui.my.basic.window ) end if ( isElement ( gui.my.logs_.window )) then destroyElement ( gui.my.logs_.window ) end if ( isElement ( gui.info.create.window ) ) then destroyElement ( gui.info.create.window ) end if ( isElement ( gui.my.bank_.window ) ) then destroyElement ( gui.my.bank_.window ) end if ( isElement ( gui.my.members_.window ) ) then destroyElement ( gui.my.members_.window ) end if ( isElement ( gui.my.members_.rWindow ) ) then destroyElement ( gui.my.members_.rWindow ) end if ( isElement ( gui.my.members_.lWindow ) ) then destroyElement ( gui.my.members_.lWindow ) end if ( isElement ( gui.my.members_.iWindow ) ) then destroyElement ( gui.my.members_.iWindow ) end if ( isElement ( gui.info.invites.window ) ) then destroyElement ( gui.info.invites.window ) end if ( isElement ( gui.my.ranks_.window ) ) then destroyElement( gui.my.ranks_.window ) end if ( isElement ( gui.my.motd.window ) ) then destroyElement ( gui.my.motd.window ) end if ( isElement ( gui.info.motd.window ) ) then destroyElement ( gui.info.motd.window ) end if ( isElement ( gui.admin.window ) ) then destroyElement ( gui.admin.window ) end if ( isElement ( gui.admin.info.window ) ) then destroyElement ( gui.admin.info.window ) end if ( isElement ( gui.admin.members.window ) ) then destroyElement ( gui.admin.members.window ) end if ( isElement ( gui.admin.ranks.window ) ) then destroyElement ( gui.admin.ranks.window ) end if ( isElement ( gui.admin.logs.window ) ) then destroyElement ( gui.admin.logs.window ) end showCursor ( false ) gui = nil else group = getElementData ( localPlayer, "Group" ) or nil rank = getElementData ( localPlayer, "Group Rank" ) or nil if ( tostring ( group ):lower ( ) == "none" ) then group = nil rank = nil end createGroupGui ( ) end end bindKey ( "F2", "down", onPlayerOpenPanel ) -- List the group addEvent ( "NGGroups->onServerSendClientGroupList", true ) addEventHandler ( "NGGroups->onServerSendClientGroupList", root, function ( g ) gList = g loadGroupPage ( "core.info" ) addEventHandler ( "onClientGUIClick", root, onClientGuiClick ) addEventHandler ( "onClientGUIChanged", root, onClientGuiChanged ) -- Bugged, not sure why -- Removed NG 1.1.3 --[[ Make sure the users group is valid if ( group and not gList [ group ] ) then group = nil rank = nil setElementData ( localPlayer, "Group", "None" ) setElementData ( localPlayer, "Group Rank", "None") onPlayerOpenPanel ( ) onPlayerOpenPanel ( ) return false; elseif ( group and not gList [ group ].members [ getElementData(localPlayer,"AccountData:Username") ] ) then group = nil rank = nil setElementData ( localPlayer, "Group", "None" ) setElementData ( localPlayer, "Group Rank", "None") onPlayerOpenPanel ( ) onPlayerOpenPanel ( ) return false end ]] end ) function table.len ( t ) local c = 0 for i, v in pairs ( t ) do c = c + 1 end return c end addEvent ( "NGGroups->pEvents:onPlayerRefreshPanel", true ) addEventHandler ( "NGGroups->pEvents:onPlayerRefreshPanel", root, function ( ) if ( gui and isElement ( gui.main.window ) ) then gui.my.members_.window.visible = false onPlayerOpenPanel ( ) onPlayerOpenPanel ( ) end end ) addEvent ( "NGGroups:Module->Bank:onServerSendClientBankLevel", true ) addEventHandler ( "NGGroups:Module->Bank:onServerSendClientBankLevel", root, function ( m ) guiSetText ( gui.my.bank_.balance, "Group Balance: $"..tostring ( m ) ) guiSetEnabled ( gui.my.bank_.amount, true ) guiSetEnabled ( gui.my.bank_.go, true ) guiSetEnabled ( gui.my.bank_.with, gList[group].ranks[rank].bank_withdraw ) guiSetEnabled ( gui.my.bank_.dep, gList[group].ranks[rank].bank_deposit ) end )
local SP = SmoothyPlates local Utils = SP.Utils SP.hookOnInit( function() handleSharedMedia() SP.Ace.Console:RegisterChatCommand('smp', handleChatCommand) -- SP.Ace.Timer.ScheduleTimer({}, function() showLayoutGUI() end, 2) end ) function handleChatCommand(cmd) if cmd == 'config' then createOptionFrame() elseif cmd == 'defaults' then SP.setCharOptions(nil) ReloadUI() elseif cmd == 'layout' then showLayoutGUI() elseif cmd == 'exportluatable' then local Box = SP.Ace.GUI:Create('MultiLineEditBox') Box:SetNumLines(30) Box:SetWidth(800) Box:DisableButton(true) Box:SetLabel('Export Table') Box:SetPoint('CENTER', UIParent, 0, 0) Box:SetText(Utils.tableToString(SP.db)) Box:HighlightText() Box:SetFocus() Box.frame:Show() local close = SP.Ace.GUI:Create('Button') close:SetText('Close') close.frame:SetSize(70, 26) close:SetPoint('BOTTOMLEFT', Box.frame, 0, -26) close:SetCallback( 'OnClick', function() Box.frame:Hide() Box = nil close.frame:Hide() close = nil end ) close.frame:Show() else Utils.print('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -') Utils.print('Possible SmoothyPlates Commands:') Utils.print(' - /smp | Show all commands') Utils.print(' - /smp config | Show options') Utils.print(' - /smp layout | Show Layout configurator') Utils.print(' - /smp defaults | Clears all configuration for this character and uses the default configuration.') Utils.print('- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -') end end local sharedMedia function handleSharedMedia() sharedMedia = LibStub:GetLibrary('LibSharedMedia-3.0', true) LibStub:GetLibrary('AceGUISharedMediaWidgets-1.0') sharedMedia:Register( 'font', 'Designosaur Regular', 'Interface\\Addons\\SmoothyPlates\\Media\\Font\\Designosaur-Regular.ttf' ) sharedMedia:Register('font', 'ElvUI Mentium', 'Interface\\Addons\\SmoothyPlates\\Media\\Font\\ElvUI-Mentium.ttf') sharedMedia:Register('font', 'Purista Medium', SP.Vars.ui.FONT) sharedMedia:Register('statusbar', 'Blizzard Nameplate Bar', 'Interface\\TargetingFrame\\UI-TargetingFrame-BarFill') sharedMedia:Register('statusbar', 'Glaze', SP.Vars.ui.textures.BAR_TEX) sharedMedia:Register('statusbar', 'Gloss', SP.Vars.ui.textures.PRED_BAR_TEX) sharedMedia:Register('statusbar', 'Flat', 'Interface\\Addons\\SmoothyPlates\\Media\\TGA\\Flat') sharedMedia:Register('statusbar', 'Minimalist', 'Interface\\Addons\\SmoothyPlates\\Media\\TGA\\Minimalist') sharedMedia:Register('statusbar', 'Minimal', 'Interface\\Addons\\SmoothyPlates\\Media\\TGA\\Minimal') if SP.db then SP.Vars.ui.font = sharedMedia:Fetch('font', SP.db.media.FONT) SP.Vars.ui.textures.BAR_TEX = sharedMedia:Fetch('statusbar', SP.db.media.BAR) SP.Vars.ui.textures.PRED_BAR_TEX = sharedMedia:Fetch('statusbar', SP.db.media.PRED_BAR) end end function createOptionFrame() local optionsFrame = SP.Ace.GUI:Create('Frame') optionsFrame:SetTitle('SmoothyPlates Options') optionsFrame:SetLayout('Flow') optionsFrame:SetStatusText('Version: ' .. SP.Vars.currVersion) optionsFrame:SetWidth(290) optionsFrame:SetHeight(410) optionsFrame:EnableResize(false) local scrollFrame = SP.Ace.GUI:Create('ScrollFrame') scrollFrame:SetWidth(270) scrollFrame:SetHeight(330) scrollFrame:SetLayout('Flow') local defaultConfig = SP.getOptionsStructure() for _, category in ipairs(defaultConfig) do local key = category.key local categoryGroup = SP.Ace.GUI:Create('InlineGroup') categoryGroup:SetTitle(category.displayName) local dbOptions = SP.db[key] for optionKey, option in pairs(category.options) do local type = option.type local inlineGroup = SP.Ace.GUI:Create('SimpleGroup') inlineGroup:SetLayout('Flow') local widget local optionValue = dbOptions[optionKey] if category.valuePath then optionValue = optionValue[category.valuePath] end local setValue = function(newValue) if category.valuePath then dbOptions[optionKey][category.valuePath] = newValue else dbOptions[optionKey] = newValue end end if type == 'BOOL' then widget = SP.Ace.GUI:Create('CheckBox') widget:SetLabel(option.displayName) widget:SetValue(optionValue) widget:SetCallback( 'OnValueChanged', function(_, _, value) setValue(value) end ) elseif type == 'BAR' then widget = SP.Ace.GUI:Create('LSM30_Statusbar') widget.list = sharedMedia:HashTable('statusbar') widget.SetLabel(widget, option.displayName) widget.SetValue(widget, optionValue) widget:SetCallback( 'OnValueChanged', function(dropdown, _, value) dropdown.SetValue(dropdown, value) setValue(value) end ) elseif type == 'FONT' then widget = SP.Ace.GUI:Create('LSM30_Font') widget.list = sharedMedia:HashTable('font') widget.SetLabel(widget, option.displayName) widget.SetValue(widget, optionValue) widget:SetCallback( 'OnValueChanged', function(dropdown, _, value) dropdown.SetValue(dropdown, value) setValue(value) end ) end if widget then widget:SetWidth(200) inlineGroup:AddChild(widget) end if option.customOptions then local customOptions = SP.Ace.GUI:Create('Icon') customOptions:SetImageSize(14, 14) customOptions:SetWidth(14) local configIcon = 'Interface\\Buttons\\UI-OptionsButton' -- local checkIcon = "Interface\\Buttons\\UI-CheckBox-Check" customOptions:SetImage(configIcon) customOptions:SetCallback( 'OnClick', function() SP.Addon:GetModule(optionKey).customOptions() optionsFrame.frame:SetAlpha(0) end ) inlineGroup:AddChild(customOptions) end categoryGroup:AddChild(inlineGroup) end scrollFrame:AddChild(categoryGroup) end optionsFrame:AddChild(scrollFrame) optionsFrame:SetCallback( 'OnClose', function() ReloadUI() end ) end local lastLayout local anchorList = { TOP = 'TOP', BOTTOM = 'BOTTOM', CENTER = 'CENTER', LEFT = 'LEFT', RIGHT = 'RIGHT', TOPLEFT = 'TOPLEFT', TOPRIGHT = 'TOPRIGHT', BOTTOMLEFT = 'BOTTOMLEFT', BOTTOMRIGHT = 'BOTTOMRIGHT' } function showLayoutGUI() lastLayout = Utils.shallowCopy(SP.db.layout) local editorFrame = Utils.createSimpleFrame('fakePlateEditor', UIParent, true) editorFrame:SetSize(456, 480) editorFrame:SetPoint('CENTER', 0, 0) editorFrame:SetBackdrop( { bgFile = SP.Vars.ui.textures.EditorBackground, tile = false, edgeFile = SP.Vars.ui.textures.EDGE_TEX, edgeSize = 2 } ) editorFrame:SetFrameLevel(0) editorFrame:SetFrameStrata('BACKGROUND') local Portrait = CreateFrame('PlayerModel', nil, editorFrame) Portrait:SetPoint('CENTER', 0, -40) Portrait:SetSize(70, 70) Portrait:SetUnit('player') local bottomContainer = Utils.createSimpleFrame('$bottomContainer', editorFrame, true) bottomContainer:SetSize(440, 130) bottomContainer:SetPoint('BOTTOM', 0, 8) bottomContainer:SetBackdrop(SP.Vars.ui.backdrops.stdbd) bottomContainer:SetBackdropColor(0, 0, 0, 0.7) bottomContainer:SetFrameStrata('BACKGROUND') local scrollFrame = SP.Ace.GUI:Create('ScrollFrame') scrollFrame:SetWidth(422) scrollFrame:SetHeight(130) scrollFrame:SetLayout('Flow') scrollFrame.frame:SetPoint('CENTER', bottomContainer, 8, 0) local elements = {} for k, v in pairs(SP.SmoothyPlate.registeredFrameNames) do elements[v] = k end local updateLayoutSetting local elementsDD = SP.Ace.GUI:Create('Dropdown') elementsDD.frame:SetSize(170, 26) elementsDD:SetList(elements) elementsDD:SetLabel('Element') elementsDD:SetValue(nil) elementsDD:SetPoint('TOPLEFT', editorFrame, 10, -9) elementsDD:SetCallback( 'OnValueChanged', function(dropdown, _, value) dropdown.SetValue(dropdown, value) updateLayoutSetting(value) end ) local save = SP.Ace.GUI:Create('Button') save:SetText('Save') save.frame:SetSize(80, 26) save:SetPoint('TOPRIGHT', editorFrame, -10, -24) save:SetCallback( 'OnClick', function() ReloadUI() end ) save.frame:Show() local reset = SP.Ace.GUI:Create('Button') reset:SetText('x') reset.frame:SetSize(38, 22) reset:SetPoint('TOPRIGHT', editorFrame, -2, -2) reset:SetCallback( 'OnClick', function() SP.db.layout = lastLayout ReloadUI() end ) reset.frame:Show() local defaults = SP.Ace.GUI:Create('Button') defaults:SetText('Defaults') defaults.frame:SetSize(90, 26) defaults:SetPoint('TOPRIGHT', editorFrame, -90, -24) defaults:SetCallback( 'OnClick', function() SP.db.layout = SP.getDefaultConfig().layout ReloadUI() end ) defaults.frame:Show() local export = SP.Ace.GUI:Create('Button') export:SetText('Export') export.frame:SetSize(90, 26) export:SetPoint('TOPRIGHT', editorFrame, -10, -52) export:SetCallback( 'OnClick', function() local Box = SP.Ace.GUI:Create('MultiLineEditBox') Box:SetNumLines(30) Box:SetWidth(800) Box:DisableButton(true) Box:SetLabel('Export') Box:SetPoint('CENTER', editorFrame, 0, 0) Box:SetText(SP.Ace.Serializer:Serialize(SP.db)) Box:HighlightText() Box:SetFocus() Box.frame:Show() local close = SP.Ace.GUI:Create('Button') close:SetText('Ok') close.frame:SetSize(60, 26) close:SetPoint('BOTTOMLEFT', Box.frame, 0, -26) close:SetCallback( 'OnClick', function() Box.frame:Hide() Box = nil close.frame:Hide() close = nil end ) close.frame:Show() end ) export.frame:Show() local import = SP.Ace.GUI:Create('Button') import:SetText('Import') import.frame:SetSize(90, 26) import:SetPoint('TOPRIGHT', editorFrame, -100, -52) import:SetCallback( 'OnClick', function() local Box = SP.Ace.GUI:Create('MultiLineEditBox') Box:SetNumLines(30) Box:SetWidth(800) Box:DisableButton(true) Box:SetLabel('Import') Box:SetPoint('CENTER', editorFrame, 0, 0) Box:SetText('') Box:HighlightText() Box:SetFocus() Box.frame:Show() local parse = SP.Ace.GUI:Create('Button') parse:SetText('Import') parse.frame:SetSize(60, 26) parse:SetPoint('BOTTOMLEFT', Box.frame, 0, -26) parse:SetCallback( 'OnClick', function() Box.frame:Hide() parse.frame:Hide() parse = nil local success, table = SP.Ace.Serializer:Deserialize(Box:GetText()) Box = nil if success and table then SP.setCharOptions(table) updateTestLayout(editorFrame) end end ) parse.frame:Show() end ) import.frame:Show() updateLayoutSetting = function(frameName) scrollFrame:ReleaseChildren() local layoutValues = SP.db.layout[frameName] local function setValue(k, v) layoutValues[k] = v end for k, v in pairs(layoutValues) do local widget if type(v) == 'string' then local onValueChanged onValueChanged = function(dropdown, _, newValue) dropdown.SetValue(dropdown, newValue) setValue(k, newValue) updateTestLayout(editorFrame) end widget = SP.Ace.GUI:Create('Dropdown') local lists = { parent = SP.SmoothyPlate.elementsPlain, anchor = anchorList, direction = {TOP = 'TOP', BOTTOM = 'BOTTOM', LEFT = 'LEFT', RIGHT = 'RIGHT'}, ['hide border'] = {t = 'TOP', b = 'BOTTOM', l = 'LEFT', r = 'RIGHT', n = 'NONE'} } widget:SetList(lists[k]) widget:SetCallback('OnValueChanged', onValueChanged) elseif type(v) == 'boolean' then widget = SP.Ace.GUI:Create('CheckBox') widget:SetCallback( 'OnValueChanged', function(_, _, newValue) setValue(k, newValue) updateTestLayout(editorFrame) end ) else widget = SP.Ace.GUI:Create('Slider') local sliderValues = { scale = {min = 1, max = 4, step = 0.1}, width = {min = 1, max = 200}, height = {min = 1, max = 200}, size = {min = 1, max = 100}, level = {min = 1, max = 20}, opacity = {min = 0, max = 1, step = 0.1} } local sliderInfo = sliderValues[k] if not sliderInfo then sliderInfo = {min = -100, max = 100} end widget:SetSliderValues(sliderInfo.min, sliderInfo.max, sliderInfo.step or 1) widget:SetCallback( 'OnValueChanged', function(_, _, newValue) setValue(k, newValue) updateTestLayout(editorFrame) end ) end widget:SetLabel(k) widget:SetValue(v) scrollFrame:AddChild(widget) end end editorFrame.fakePlate = nil updateTestLayout(editorFrame) end function updateTestLayout(editorFrame) if editorFrame.fakePlate then editorFrame.fakePlate.SmoothyPlate:RemoveUnit() editorFrame.fakePlate.SmoothyPlate = nil editorFrame.fakePlate:Hide() editorFrame.fakePlate:SetParent(nil) editorFrame.fakePlate:ClearAllPoints() editorFrame.fakePlate = nil end local fakePlate = CreateFrame('Frame', '$fakePlate', editorFrame) fakePlate:SetSize(154, 64) fakePlate:SetPoint('CENTER', 0, 40) fakePlate:SetFrameStrata('BACKGROUND') fakePlate:SetScale(SP.Vars.perfectScale * 1.9737) local sp = SP.SmoothyPlate(fakePlate, true) SP.callbacks:Fire('AFTER_SP_CREATION', fakePlate) sp:AddUnit('player') SP.callbacks:Fire('AFTER_SP_UNIT_ADDED', fakePlate) editorFrame.fakePlate = fakePlate end
local path = (function () local i = 0 while arg[i] ~= nil do i = i - 1 end return arg[i + 1] :match("(.+)[/\\][%w_.-]+$") :match("(.+)[/\\][%w_.-]+$") :match("(.+)[/\\][%w_.-]+$") :match("(.+)[/\\][%w_.-]+$") end)() local function dofile(filename, ...) local load = _VERSION == "Lua 5.1" and loadstring or load local f = assert(io.open(filename)) local str = f:read "*a" f:close() return assert(load(str, "=(debugger.lua)"))(...) end local dbg = dofile(path.."/script/debugger.lua", path) dbg:set_wait("DBG", function(params) local pid = params[1] local cfg = { address = ("@%s/tmp/pid_%s"):format(path, pid), ansi = true } for i = 2, #params do local param = params[i] cfg[param] = true end dbg:start(cfg) end)
UIInfo = { } UIInfo.BottomMidUI = {path = "BottomMidUI",class = "Client.Scripts.Modulus.RootUI.UI.BottomMidUI",className = "BottomMidUI" ,UIEnum = UIEnum.BottomMidUI,UINode = UINode.UIRoot,isDestroy = false } UIInfo.JoyStickUI = {path = "JoyStickUI",class = "Client.Scripts.Modulus.RootUI.UI.JoyStickUI",className = "JoyStickUI" ,UIEnum = UIEnum.JoyStickUI,UINode = UINode.UIRoot,isDestroy = false } UIInfo.BottomSkillUI = {path = "BottomSkillUI",class = "Client.Scripts.Modulus.RootUI.UI.BottomSkillUI",className = "BottomSkillUI" ,UIEnum = UIEnum.BottomSkillUI,UINode = UINode.UIRoot,isDestroy = true } UIInfo.FaceBookUI = {path = "FaceBookUI",class = "Client.Scripts.Modulus.FaceBookUI.UI.FaceBookUI",className = "FaceBookUI" ,UIEnum = UIEnum.FaceBookUI,UINode = UINode.UIMain,isDestroy = false } UIInfo.UpDownAnimUI = {path = "UpDownAnimUI",class = "Client.Scripts.Modulus.UIUtils.UI.UpDownAnimUI",className = "UpDownAnimUI" ,UIEnum = UIEnum.UpDownAnimUI,UINode = UINode.UIAlert,isDestroy = true } UIInfo.GuildUI = {path = "GuildUI",class = "Client.Scripts.Modulus.Guild.UI.GuildUI",className = "GuildUI" ,UIEnum = UIEnum.GuildUI,UINode = UINode.UIMain,isDestroy = true }
local helpers = require "spec.helpers" local cjson = require "cjson" local utils = require "kong.tools.utils" local to_hex = require "resty.string".to_hex local fmt = string.format local ZIPKIN_HOST = os.getenv("ZIPKIN_HOST") or "127.0.0.1" local ZIPKIN_PORT = 9411 local GRPCBIN_HOST = "127.0.0.1" local GRPCBIN_PORT = 15002 -- Transform zipkin annotations into a hash of timestamps. It assumes no repeated values -- input: { { value = x, timestamp = y }, { value = x2, timestamp = y2 } } -- output: { x = y, x2 = y2 } local function annotations_to_hash(annotations) local hash = {} for _, a in ipairs(annotations) do assert(not hash[a.value], "duplicated annotation: " .. a.value) hash[a.value] = a.timestamp end return hash end local function assert_is_integer(number) assert.equals("number", type(number)) assert.equals(number, math.floor(number)) end local function gen_trace_id(traceid_byte_count) return to_hex(utils.get_rand_bytes(traceid_byte_count)) end local function gen_span_id() return to_hex(utils.get_rand_bytes(8)) end -- assumption: tests take less than this (usually they run in ~2 seconds) local MAX_TIMESTAMP_AGE = 5 * 60 -- 5 minutes local function assert_valid_timestamp(timestamp_mu, start_s) assert_is_integer(timestamp_mu) local age_s = timestamp_mu / 1000000 - start_s if age_s < 0 or age_s > MAX_TIMESTAMP_AGE then error("out of bounds timestamp: " .. timestamp_mu .. "mu (age: " .. age_s .. "s)") end end local function wait_for_spans(zipkin_client, number_of_spans, remoteServiceName, trace_id) local spans = {} helpers.wait_until(function() if trace_id then local res = assert(zipkin_client:get("/api/v2/trace/" .. trace_id)) spans = cjson.decode(assert.response(res).has.status(200)) return #spans == number_of_spans end local res = zipkin_client:get("/api/v2/traces", { query = { limit = 10, remoteServiceName = remoteServiceName, } }) local all_spans = cjson.decode(assert.response(res).has.status(200)) if #all_spans > 0 then spans = all_spans[1] return #spans == number_of_spans end end) return utils.unpack(spans) end -- the following assertions should be true on any span list, even in error mode local function assert_span_invariants(request_span, proxy_span, expected_name, traceid_len, start_s, service_name) -- request_span assert.same("table", type(request_span)) assert.same("string", type(request_span.id)) assert.same(expected_name, request_span.name) assert.same(request_span.id, proxy_span.parentId) assert.same("SERVER", request_span.kind) assert.same("string", type(request_span.traceId)) assert.equals(traceid_len, #request_span.traceId, request_span.traceId) assert_valid_timestamp(request_span.timestamp, start_s) if request_span.duration and proxy_span.duration then assert.truthy(request_span.duration >= proxy_span.duration) end if #request_span.annotations == 1 then error(require("inspect")(request_span)) end assert.equals(2, #request_span.annotations) local rann = annotations_to_hash(request_span.annotations) assert_valid_timestamp(rann["krs"], start_s) assert_valid_timestamp(rann["krf"], start_s) assert.truthy(rann["krs"] <= rann["krf"]) assert.same({ serviceName = service_name }, request_span.localEndpoint) -- proxy_span assert.same("table", type(proxy_span)) assert.same("string", type(proxy_span.id)) assert.same(request_span.name .. " (proxy)", proxy_span.name) assert.same(request_span.id, proxy_span.parentId) assert.same("CLIENT", proxy_span.kind) assert.same("string", type(proxy_span.traceId)) assert.equals(request_span.traceId, proxy_span.traceId) assert_valid_timestamp(proxy_span.timestamp, start_s) if request_span.duration and proxy_span.duration then assert.truthy(proxy_span.duration >= 0) end assert.equals(6, #proxy_span.annotations) local pann = annotations_to_hash(proxy_span.annotations) assert_valid_timestamp(pann["kas"], start_s) assert_valid_timestamp(pann["kaf"], start_s) assert_valid_timestamp(pann["khs"], start_s) assert_valid_timestamp(pann["khf"], start_s) assert_valid_timestamp(pann["kbs"], start_s) assert_valid_timestamp(pann["kbf"], start_s) assert.truthy(pann["kas"] <= pann["kaf"]) assert.truthy(pann["khs"] <= pann["khf"]) assert.truthy(pann["kbs"] <= pann["kbf"]) assert.truthy(pann["khs"] <= pann["kbs"]) end for _, strategy in helpers.each_strategy() do describe("plugin configuration", function() local proxy_client, zipkin_client, service setup(function() local bp = helpers.get_db_utils(strategy, { "services", "routes", "plugins" }) service = bp.services:insert { name = string.lower("http-" .. utils.random_string()), } -- kong (http) mock upstream bp.routes:insert({ name = string.lower("route-" .. utils.random_string()), service = service, hosts = { "http-route" }, preserve_host = true, }) -- enable zipkin plugin globally, with sample_ratio = 0 bp.plugins:insert({ name = "zipkin", config = { sample_ratio = 0, http_endpoint = fmt("http://%s:%d/api/v2/spans", ZIPKIN_HOST, ZIPKIN_PORT), default_header_type = "b3-single", } }) -- enable zipkin on the service, with sample_ratio = 1 -- this should generate traces, even if there is another plugin with sample_ratio = 0 bp.plugins:insert({ name = "zipkin", service = { id = service.id }, config = { sample_ratio = 1, http_endpoint = fmt("http://%s:%d/api/v2/spans", ZIPKIN_HOST, ZIPKIN_PORT), default_header_type = "b3-single", } }) helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", stream_listen = helpers.get_proxy_ip(false) .. ":19000", }) proxy_client = helpers.proxy_client() zipkin_client = helpers.http_client(ZIPKIN_HOST, ZIPKIN_PORT) end) teardown(function() helpers.stop_kong() end) it("#generates traces when several plugins exist and one of them has sample_ratio = 0 but not the other", function() local start_s = ngx.now() local r = proxy_client:get("/", { headers = { ["x-b3-sampled"] = "1", host = "http-route", ["zipkin-tags"] = "foo=bar; baz=qux" }, }) assert.response(r).has.status(200) local _, proxy_span, request_span = wait_for_spans(zipkin_client, 3, service.name) -- common assertions for request_span and proxy_span assert_span_invariants(request_span, proxy_span, "get", 16 * 2, start_s, "kong") end) end) end for _, strategy in helpers.each_strategy() do describe("serviceName configuration", function() local proxy_client, zipkin_client, service setup(function() local bp = helpers.get_db_utils(strategy, { "services", "routes", "plugins" }) service = bp.services:insert { name = string.lower("http-" .. utils.random_string()), } -- kong (http) mock upstream bp.routes:insert({ name = string.lower("route-" .. utils.random_string()), service = service, hosts = { "http-route" }, preserve_host = true, }) -- enable zipkin plugin globally, with sample_ratio = 1 bp.plugins:insert({ name = "zipkin", config = { sample_ratio = 1, http_endpoint = fmt("http://%s:%d/api/v2/spans", ZIPKIN_HOST, ZIPKIN_PORT), default_header_type = "b3-single", local_service_name = "custom-service-name", } }) helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", stream_listen = helpers.get_proxy_ip(false) .. ":19000", }) proxy_client = helpers.proxy_client() zipkin_client = helpers.http_client(ZIPKIN_HOST, ZIPKIN_PORT) end) teardown(function() helpers.stop_kong() end) it("#generates traces with configured serviceName if set", function() local start_s = ngx.now() local r = proxy_client:get("/", { headers = { ["x-b3-sampled"] = "1", host = "http-route", ["zipkin-tags"] = "foo=bar; baz=qux" }, }) assert.response(r).has.status(200) local _, proxy_span, request_span = wait_for_spans(zipkin_client, 3, service.name) -- common assertions for request_span and proxy_span assert_span_invariants(request_span, proxy_span, "get", 16 * 2, start_s, "custom-service-name") end) end) end for _, strategy in helpers.each_strategy() do describe("http_span_name configuration", function() local proxy_client, zipkin_client, service setup(function() local bp = helpers.get_db_utils(strategy, { "services", "routes", "plugins" }) service = bp.services:insert { name = string.lower("http-" .. utils.random_string()), } -- kong (http) mock upstream bp.routes:insert({ name = string.lower("route-" .. utils.random_string()), service = service, hosts = { "http-route" }, preserve_host = true, }) -- enable zipkin plugin globally, with sample_ratio = 1 bp.plugins:insert({ name = "zipkin", config = { sample_ratio = 1, http_endpoint = fmt("http://%s:%d/api/v2/spans", ZIPKIN_HOST, ZIPKIN_PORT), default_header_type = "b3-single", http_span_name = "method_path", } }) helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", stream_listen = helpers.get_proxy_ip(false) .. ":19000", }) proxy_client = helpers.proxy_client() zipkin_client = helpers.http_client(ZIPKIN_HOST, ZIPKIN_PORT) end) teardown(function() helpers.stop_kong() end) it("http_span_name = 'method_path' includes path to span name", function() local start_s = ngx.now() local r = proxy_client:get("/", { headers = { ["x-b3-sampled"] = "1", host = "http-route", ["zipkin-tags"] = "foo=bar; baz=qux" }, }) assert.response(r).has.status(200) local _, proxy_span, request_span = wait_for_spans(zipkin_client, 3, service.name) -- common assertions for request_span and proxy_span assert_span_invariants(request_span, proxy_span, "get /", 16 * 2, start_s, "kong") end) end) end for _, strategy in helpers.each_strategy() do for _, traceid_byte_count in ipairs({ 8, 16 }) do describe("http integration tests with zipkin server [#" .. strategy .. "] traceid_byte_count: " .. traceid_byte_count, function() local proxy_client_grpc local service, grpc_service, tcp_service local route, grpc_route, tcp_route local zipkin_client local proxy_client lazy_setup(function() local bp = helpers.get_db_utils(strategy, { "services", "routes", "plugins" }) -- enable zipkin plugin globally pointing to mock server bp.plugins:insert({ name = "zipkin", -- enable on TCP as well (by default it is only enabled on http, https, grpc, grpcs) protocols = { "http", "https", "tcp", "tls", "grpc", "grpcs" }, config = { sample_ratio = 1, http_endpoint = fmt("http://%s:%d/api/v2/spans", ZIPKIN_HOST, ZIPKIN_PORT), traceid_byte_count = traceid_byte_count, static_tags = { { name = "static", value = "ok" }, }, default_header_type = "b3-single", } }) service = bp.services:insert { name = string.lower("http-" .. utils.random_string()), } -- kong (http) mock upstream route = bp.routes:insert({ name = string.lower("route-" .. utils.random_string()), service = service, hosts = { "http-route" }, preserve_host = true, }) -- grpc upstream grpc_service = bp.services:insert { name = string.lower("grpc-" .. utils.random_string()), url = fmt("grpc://%s:%d", GRPCBIN_HOST, GRPCBIN_PORT), } grpc_route = bp.routes:insert { name = string.lower("grpc-route-" .. utils.random_string()), service = grpc_service, protocols = { "grpc" }, hosts = { "grpc-route" }, } -- tcp upstream tcp_service = bp.services:insert({ name = string.lower("tcp-" .. utils.random_string()), protocol = "tcp", host = helpers.mock_upstream_host, port = helpers.mock_upstream_stream_port, }) tcp_route = bp.routes:insert { name = string.lower("tcp-route-" .. utils.random_string()), destinations = { { port = 19000 } }, protocols = { "tcp" }, service = tcp_service, } helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", stream_listen = helpers.get_proxy_ip(false) .. ":19000", }) proxy_client = helpers.proxy_client() proxy_client_grpc = helpers.proxy_client_grpc() zipkin_client = helpers.http_client(ZIPKIN_HOST, ZIPKIN_PORT) end) teardown(function() helpers.stop_kong() end) it("generates spans, tags and annotations for regular requests", function() local start_s = ngx.now() local r = proxy_client:get("/", { headers = { ["x-b3-sampled"] = "1", host = "http-route", ["zipkin-tags"] = "foo=bar; baz=qux" }, }) assert.response(r).has.status(200) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, service.name) -- common assertions for request_span and proxy_span assert_span_invariants(request_span, proxy_span, "get", traceid_byte_count * 2, start_s, "kong") -- specific assertions for request_span local request_tags = request_span.tags assert.truthy(request_tags["kong.node.id"]:match("^[%x-]+$")) request_tags["kong.node.id"] = nil assert.same({ ["http.method"] = "GET", ["http.path"] = "/", ["http.status_code"] = "200", -- found (matches server status) ["http.protocol"] = "HTTP/1.1", ["http.host"] = "http-route", lc = "kong", static = "ok", foo = "bar", baz = "qux" }, request_tags) local consumer_port = request_span.remoteEndpoint.port assert_is_integer(consumer_port) assert.same({ ipv4 = "127.0.0.1", port = consumer_port, }, request_span.remoteEndpoint) -- specific assertions for proxy_span assert.same(proxy_span.tags["kong.route"], route.id) assert.same(proxy_span.tags["kong.route_name"], route.name) assert.same(proxy_span.tags["peer.hostname"], "127.0.0.1") assert.same({ ipv4 = helpers.mock_upstream_host, port = helpers.mock_upstream_port, serviceName = service.name, }, proxy_span.remoteEndpoint) -- specific assertions for balancer_span assert.equals(balancer_span.parentId, request_span.id) assert.equals(request_span.name .. " (balancer try 1)", balancer_span.name) assert.equals("number", type(balancer_span.timestamp)) if balancer_span.duration then assert.equals("number", type(balancer_span.duration)) end assert.same({ ipv4 = helpers.mock_upstream_host, port = helpers.mock_upstream_port, serviceName = service.name, }, balancer_span.remoteEndpoint) assert.same({ serviceName = "kong" }, balancer_span.localEndpoint) assert.same({ ["kong.balancer.try"] = "1", ["kong.route"] = route.id, ["kong.route_name"] = route.name, ["kong.service"] = service.id, ["kong.service_name"] = service.name, }, balancer_span.tags) end) it("generates spans, tags and annotations for regular requests (#grpc)", function() local start_s = ngx.now() local ok, resp = proxy_client_grpc({ service = "hello.HelloService.SayHello", body = { greeting = "world!" }, opts = { ["-H"] = "'x-b3-sampled: 1'", ["-authority"] = "grpc-route", } }) assert(ok, resp) assert.truthy(resp) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, grpc_service.name) -- common assertions for request_span and proxy_span assert_span_invariants(request_span, proxy_span, "post", traceid_byte_count * 2, start_s, "kong") -- specific assertions for request_span local request_tags = request_span.tags assert.truthy(request_tags["kong.node.id"]:match("^[%x-]+$")) request_tags["kong.node.id"] = nil assert.same({ ["http.method"] = "POST", ["http.path"] = "/hello.HelloService/SayHello", ["http.status_code"] = "200", -- found (matches server status) ["http.protocol"] = "HTTP/2", ["http.host"] = "grpc-route", lc = "kong", static = "ok", }, request_tags) local consumer_port = request_span.remoteEndpoint.port assert_is_integer(consumer_port) assert.same({ ipv4 = '127.0.0.1', port = consumer_port, }, request_span.remoteEndpoint) -- specific assertions for proxy_span assert.same(proxy_span.tags["kong.route"], grpc_route.id) assert.same(proxy_span.tags["kong.route_name"], grpc_route.name) assert.same(proxy_span.tags["peer.hostname"], GRPCBIN_HOST) -- random ip assigned by Docker to the grpcbin container local grpcbin_ip = proxy_span.remoteEndpoint.ipv4 assert.same({ ipv4 = grpcbin_ip, port = GRPCBIN_PORT, serviceName = grpc_service.name, }, proxy_span.remoteEndpoint) -- specific assertions for balancer_span assert.equals(balancer_span.parentId, request_span.id) assert.equals(request_span.name .. " (balancer try 1)", balancer_span.name) assert_valid_timestamp(balancer_span.timestamp, start_s) if balancer_span.duration then assert_is_integer(balancer_span.duration) end assert.same({ ipv4 = grpcbin_ip, port = GRPCBIN_PORT, serviceName = grpc_service.name, }, balancer_span.remoteEndpoint) assert.same({ serviceName = "kong" }, balancer_span.localEndpoint) assert.same({ ["kong.balancer.try"] = "1", ["kong.service"] = grpc_route.service.id, ["kong.service_name"] = grpc_service.name, ["kong.route"] = grpc_route.id, ["kong.route_name"] = grpc_route.name, }, balancer_span.tags) end) it("generates spans, tags and annotations for regular #stream requests", function() local start_s = ngx.now() local tcp = ngx.socket.tcp() assert(tcp:connect(helpers.get_proxy_ip(false), 19000)) assert(tcp:send("hello\n")) local body = assert(tcp:receive("*a")) assert.equal("hello\n", body) assert(tcp:close()) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, tcp_service.name) -- request span assert.same("table", type(request_span)) assert.same("string", type(request_span.id)) assert.same("stream", request_span.name) assert.same(request_span.id, proxy_span.parentId) assert.same("SERVER", request_span.kind) assert.same("string", type(request_span.traceId)) assert_valid_timestamp(request_span.timestamp, start_s) if request_span.duration and proxy_span.duration then assert.truthy(request_span.duration >= proxy_span.duration) end assert.is_nil(request_span.annotations) assert.same({ serviceName = "kong" }, request_span.localEndpoint) local request_tags = request_span.tags assert.truthy(request_tags["kong.node.id"]:match("^[%x-]+$")) request_tags["kong.node.id"] = nil assert.same({ lc = "kong", static = "ok", }, request_tags) local consumer_port = request_span.remoteEndpoint.port assert_is_integer(consumer_port) assert.same({ ipv4 = "127.0.0.1", port = consumer_port, }, request_span.remoteEndpoint) -- proxy span assert.same("table", type(proxy_span)) assert.same("string", type(proxy_span.id)) assert.same(request_span.name .. " (proxy)", proxy_span.name) assert.same(request_span.id, proxy_span.parentId) assert.same("CLIENT", proxy_span.kind) assert.same("string", type(proxy_span.traceId)) assert_valid_timestamp(proxy_span.timestamp, start_s) if proxy_span.duration then assert.truthy(proxy_span.duration >= 0) end assert.equals(2, #proxy_span.annotations) local pann = annotations_to_hash(proxy_span.annotations) assert_valid_timestamp(pann["kps"], start_s) assert_valid_timestamp(pann["kpf"], start_s) assert.truthy(pann["kps"] <= pann["kpf"]) assert.same({ ["kong.route"] = tcp_route.id, ["kong.route_name"] = tcp_route.name, ["kong.service"] = tcp_service.id, ["kong.service_name"] = tcp_service.name, ["peer.hostname"] = "127.0.0.1", }, proxy_span.tags) assert.same({ ipv4 = helpers.mock_upstream_host, port = helpers.mock_upstream_stream_port, serviceName = tcp_service.name, }, proxy_span.remoteEndpoint) -- specific assertions for balancer_span assert.equals(balancer_span.parentId, request_span.id) assert.equals(request_span.name .. " (balancer try 1)", balancer_span.name) assert.equals("number", type(balancer_span.timestamp)) if balancer_span.duration then assert.equals("number", type(balancer_span.duration)) end assert.same({ ipv4 = helpers.mock_upstream_host, port = helpers.mock_upstream_stream_port, serviceName = tcp_service.name, }, balancer_span.remoteEndpoint) assert.same({ serviceName = "kong" }, balancer_span.localEndpoint) assert.same({ ["kong.balancer.try"] = "1", ["kong.route"] = tcp_route.id, ["kong.route_name"] = tcp_route.name, ["kong.service"] = tcp_service.id, ["kong.service_name"] = tcp_service.name, }, balancer_span.tags) end) it("generates spans, tags and annotations for non-matched requests", function() local trace_id = gen_trace_id(traceid_byte_count) local start_s = ngx.now() local r = assert(proxy_client:send { method = "GET", path = "/foobar", headers = { ["x-b3-traceid"] = trace_id, ["x-b3-sampled"] = "1", ["zipkin-tags"] = "error = true" }, }) assert.response(r).has.status(404) local proxy_span, request_span = wait_for_spans(zipkin_client, 2, nil, trace_id) -- common assertions for request_span and proxy_span assert_span_invariants(request_span, proxy_span, "get", #trace_id, start_s, "kong") -- specific assertions for request_span local request_tags = request_span.tags assert.truthy(request_tags["kong.node.id"]:match("^[%x-]+$")) request_tags["kong.node.id"] = nil assert.same({ ["http.method"] = "GET", ["http.path"] = "/foobar", ["http.status_code"] = "404", -- note that this was "not found" ["http.protocol"] = 'HTTP/1.1', ["http.host"] = '0.0.0.0', lc = "kong", static = "ok", error = "true", }, request_tags) local consumer_port = request_span.remoteEndpoint.port assert_is_integer(consumer_port) assert.same({ ipv4 = "127.0.0.1", port = consumer_port }, request_span.remoteEndpoint) -- specific assertions for proxy_span assert.is_nil(proxy_span.tags) assert.is_nil(proxy_span.remoteEndpoint) assert.same({ serviceName = "kong" }, proxy_span.localEndpoint) end) it("propagates b3 headers for non-matched requests", function() local trace_id = gen_trace_id(traceid_byte_count) local r = assert(proxy_client:send { method = "GET", path = "/foobar", headers = { ["x-b3-traceid"] = trace_id, ["x-b3-sampled"] = "1", }, }) assert.response(r).has.status(404) local proxy_span, request_span = wait_for_spans(zipkin_client, 2, nil, trace_id) assert.equals(trace_id, proxy_span.traceId) assert.equals(trace_id, request_span.traceId) end) describe("b3 single header propagation", function() it("works on regular calls", function() local trace_id = gen_trace_id(traceid_byte_count) local span_id = gen_span_id() local parent_id = gen_span_id() local r = proxy_client:get("/", { headers = { b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "1", parent_id), host = "http-route", }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.matches(trace_id .. "%-%x+%-1%-%x+", json.headers.b3) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(span_id, request_span.id) assert.equals(parent_id, request_span.parentId) assert.equals(trace_id, proxy_span.traceId) assert.not_equals(span_id, proxy_span.id) assert.equals(span_id, proxy_span.parentId) assert.equals(trace_id, balancer_span.traceId) assert.not_equals(span_id, balancer_span.id) assert.equals(span_id, balancer_span.parentId) end) it("works without parent_id", function() local trace_id = gen_trace_id(traceid_byte_count) local span_id = gen_span_id() local r = proxy_client:get("/", { headers = { b3 = fmt("%s-%s-1", trace_id, span_id), host = "http-route", }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.matches(trace_id .. "%-%x+%-1%-%x+", json.headers.b3) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(span_id, request_span.id) assert.equals(trace_id, proxy_span.traceId) assert.not_equals(span_id, proxy_span.id) assert.equals(span_id, proxy_span.parentId) assert.equals(trace_id, balancer_span.traceId) assert.not_equals(span_id, balancer_span.id) assert.equals(span_id, balancer_span.parentId) end) it("works with only trace_id and span_id", function() local trace_id = gen_trace_id(traceid_byte_count) local span_id = gen_span_id() local r = proxy_client:get("/", { headers = { b3 = fmt("%s-%s", trace_id, span_id), ["x-b3-sampled"] = "1", host = "http-route", }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.matches(trace_id .. "%-%x+%-1%-%x+", json.headers.b3) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(span_id, request_span.id) assert.equals(trace_id, proxy_span.traceId) assert.not_equals(span_id, proxy_span.id) assert.equals(span_id, proxy_span.parentId) assert.equals(trace_id, balancer_span.traceId) assert.not_equals(span_id, balancer_span.id) assert.equals(span_id, balancer_span.parentId) end) it("works on non-matched requests", function() local trace_id = gen_trace_id(traceid_byte_count) local span_id = gen_span_id() local r = proxy_client:get("/foobar", { headers = { b3 = fmt("%s-%s-1", trace_id, span_id) }, }) assert.response(r).has.status(404) local proxy_span, request_span = wait_for_spans(zipkin_client, 2, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(span_id, request_span.id) assert.equals(trace_id, proxy_span.traceId) assert.not_equals(span_id, proxy_span.id) assert.equals(span_id, proxy_span.parentId) end) end) describe("w3c traceparent header propagation", function() it("works on regular calls", function() local trace_id = gen_trace_id(16) -- w3c only admits 16-byte trace_ids local parent_id = gen_span_id() local r = proxy_client:get("/", { headers = { traceparent = fmt("00-%s-%s-01", trace_id, parent_id), host = "http-route" }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.matches("00%-" .. trace_id .. "%-%x+-01", json.headers.traceparent) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(parent_id, request_span.parentId) assert.equals(trace_id, proxy_span.traceId) assert.equals(trace_id, balancer_span.traceId) end) it("works on non-matched requests", function() local trace_id = gen_trace_id(16) -- w3c only admits 16-bit trace_ids local parent_id = gen_span_id() local r = proxy_client:get("/foobar", { headers = { traceparent = fmt("00-%s-%s-01", trace_id, parent_id), }, }) assert.response(r).has.status(404) local proxy_span, request_span = wait_for_spans(zipkin_client, 2, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(parent_id, request_span.parentId) assert.equals(trace_id, proxy_span.traceId) end) end) describe("jaeger uber-trace-id header propagation", function() it("works on regular calls", function() local trace_id = gen_trace_id(traceid_byte_count) local span_id = gen_span_id() local parent_id = gen_span_id() local r = proxy_client:get("/", { headers = { ["uber-trace-id"] = fmt("%s:%s:%s:%s", trace_id, span_id, parent_id, "1"), host = "http-route" }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.matches(('0'):rep(32-#trace_id) .. trace_id .. ":%x+:" .. span_id .. ":01", json.headers["uber-trace-id"]) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(span_id, request_span.id) assert.equals(parent_id, request_span.parentId) assert.equals(trace_id, proxy_span.traceId) assert.not_equals(span_id, proxy_span.id) assert.equals(span_id, proxy_span.parentId) assert.equals(trace_id, balancer_span.traceId) assert.not_equals(span_id, balancer_span.id) assert.equals(span_id, balancer_span.parentId) end) it("works on non-matched requests", function() local trace_id = gen_trace_id(traceid_byte_count) local span_id = gen_span_id() local parent_id = gen_span_id() local r = proxy_client:get("/foobar", { headers = { ["uber-trace-id"] = fmt("%s:%s:%s:%s", trace_id, span_id, parent_id, "1"), }, }) assert.response(r).has.status(404) local proxy_span, request_span = wait_for_spans(zipkin_client, 2, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(span_id, request_span.id) assert.equals(parent_id, request_span.parentId) assert.equals(trace_id, proxy_span.traceId) assert.not_equals(span_id, proxy_span.id) assert.equals(span_id, proxy_span.parentId) end) end) describe("ot header propagation", function() it("works on regular calls", function() local trace_id = gen_trace_id(8) local span_id = gen_span_id() local r = proxy_client:get("/", { headers = { ["ot-tracer-traceid"] = trace_id, ["ot-tracer-spanid"] = span_id, ["ot-tracer-sampled"] = "1", host = "http-route", }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.equals(trace_id, json.headers["ot-tracer-traceid"]) local balancer_span, proxy_span, request_span = wait_for_spans(zipkin_client, 3, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(trace_id, proxy_span.traceId) assert.equals(trace_id, balancer_span.traceId) end) it("works on non-matched requests", function() local trace_id = gen_trace_id(8) local span_id = gen_span_id() local r = proxy_client:get("/foobar", { headers = { ["ot-tracer-traceid"] = trace_id, ["ot-tracer-spanid"] = span_id, ["ot-tracer-sampled"] = "1", }, }) assert.response(r).has.status(404) local proxy_span, request_span = wait_for_spans(zipkin_client, 2, nil, trace_id) assert.equals(trace_id, request_span.traceId) assert.equals(trace_id, proxy_span.traceId) end) end) describe("header type with 'preserve' config and no inbound headers", function() it("uses whatever is set in the plugin's config.default_header_type property", function() local r = proxy_client:get("/", { headers = { -- no tracing header host = "http-route" }, }) local body = assert.response(r).has.status(200) local json = cjson.decode(body) assert.not_nil(json.headers.b3) end) end) end) end end
local sti = require("lib/sti") local json = require("lib/json") local lurker = require("lib/lurker") require("classes/player") require("classes/enemy") require("classes/collectable") require("classes/dialog") require("classes/barrel") local windowHeight local windowWidth local map local world local backgroundSound local sparkleSound local enemies = {} local collectables = {} local spawnPoints = {} local hero local mute = false local elapsedTime = 0 local score = 0 function printTable(val) for k, v in pairs(val) do print(k) print(v) end print("-----------------------") end function reset() backgroundSound:stop() collectables = {} enemies = {} spawnPoints = {} mainDialog:clear() score = 0 end function love.load() -- Grab window size windowWidth = love.graphics.getWidth() windowHeight = love.graphics.getHeight() backgroundSound = love.audio.newSource("assets/sound/Kevin_MacLeod_-_Clean_Soul.mp3", "stream") backgroundSound:setLooping(true) backgroundSound:setVolume(0.3) sparkleSound = love.audio.newSource("assets/sound/sparkle.wav", "static") sparkleSound:setVolume(0.5) if(not mute) then backgroundSound:play() end math.randomseed(os.time()) -- Set world meter size (in pixels) love.physics.setMeter(64) mainDialog = dialog.new() -- Load a map exported to Lua from Tiled map = sti("assets/maps/firstmap.lua", { "box2d" }) world = love.physics.newWorld(0, 8.91 * 64, true) world:setCallbacks(beginContact, endContact, preSolve, postSolve) map:box2d_init(world) local startPosId = 0 for k,v in pairs(map.objects) do if(v.name == "StartPos") then startPosId = k end if(v.type == "enemy") then table.insert(enemies, enemy.new(v.x, v.y, world)) end if(v.type == "collectable") then table.insert(collectables, collectable.new(v.x, v.y, world, v.properties.value)) end if(v.type == "spawn") then table.insert(spawnPoints, { x = v.x, y = v.y, spawn = true, type = v.properties.type }) end end hero = player.new( map.objects[startPosId].x, map.objects[startPosId].y, world, windowWidth / 2, windowHeight / 2 ) lurker.preswap = function(f) reset() end lurker.postswap = function(f) print(f .. " was swapped") --if(f == 'assets/maps/firstmap.lua') then love:load() --end end end function love.update(dt) elapsedTime = elapsedTime + dt lurker.update() if(love.keyboard.isDown("left")) then hero:moveLeft() end if(love.keyboard.isDown("right")) then hero:moveRight() end hero:sprint(dt, love.keyboard.isDown("lshift")) world:update(dt) map:update(dt) hero:update(dt) local newEnemies = {} for k,v in pairs(enemies) do if(not v.destroyed()) then table.insert(newEnemies, v) end v:update(dt, map) end enemies = newEnemies if(elapsedTime > 10) then for k,v in pairs(spawnPoints) do table.insert(enemies, barrel.new(v.x, v.y, world)) end elapsedTime = 0 end mainDialog:update(dt) end function love.draw() if not map then love.load() end if(hero.gameOver) then love.graphics.setColor(255, 255, 255) love.graphics.print("Game over!", windowWidth / 2 - 150, windowHeight / 2 - 40, 0, 5, 5) return end love.graphics.setColor(255, 255, 255) map:draw(hero:getScreenX(), hero:getScreenY()) hero:draw() for k,v in pairs(collectables) do v:draw(hero:getScreenX(), hero:getScreenY()) end for k,v in pairs(enemies) do v:draw(hero:getScreenX(), hero:getScreenY()) end mainDialog:draw() --love.graphics.setColor(255, 0, 0) --map:box2d_draw(hero:getScreenX(), hero:getScreenY()) love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", 0, 0, windowWidth, 40) love.graphics.setColor(255, 255, 255) love.graphics.print("Score: " .. score, 20, 5, 0, 2, 2) love.graphics.setColor(0, 0, 255) love.graphics.rectangle("fill", 200, 10, hero:getSprintTimeLeft() * 100, 20) love.graphics.setColor(255, 255, 255) love.graphics.rectangle("line", 200, 10, 100, 20) love.graphics.setColor(255, 0, 0) love.graphics.rectangle("fill", 350, 10, hero:getHealthLeft() * 100, 20) love.graphics.setColor(255, 255, 255) love.graphics.rectangle("line", 350, 10, 100, 20) end function love.keypressed(key) if(key == "r") then reset() love:load() end if(key == "space") then mainDialog:sayNext() end if(key == "up") then hero:jump() end if(key == "down") then hero:stop() end if(key == "escape") then love.event.quit() end end function beginContact(a, b, coll) if(a:isSensor()) then if(a:getUserData().properties) then if(a:getUserData().properties.type == 'dialog' and b:getUserData():type() == 'player') then mainDialog:startScript(a:getUserData().properties.script) a:destroy() end if(a:getUserData().properties.type == 'despawn' and b:getUserData():type() == 'spawnable') then b:getUserData():destroy() end if(a:getUserData().properties.type == 'reveal' and b:getUserData():type() == 'player') then map.layers.hidden.opacity = 0 sparkleSound:play() for k,v in pairs(collectables) do v:showHidden() end end end if(a:getUserData().type) then if(a:getUserData():type() == "collectable" and b:getUserData():type() == 'player') then a:getUserData():collect() a:destroy() score = score + 20 end end end if(not b:isSensor() and a:getUserData().type and a:getUserData().type() == 'player') then if(b:getUserData().canHurt) then a:getUserData():hurt(coll, b:getUserData():canHurt(), true) end end if(not a:isSensor() and b:getUserData().type() == 'player') then if(a:getUserData().canHurt) then b:getUserData():hurt(coll, a:getUserData():canHurt(), false) else nx, ny = coll:getNormal() if(ny < 0) then b:getUserData():landed() end end end end function endContact(a, b, coll) if(a:isSensor() and a:getUserData().properties) then if(a:getUserData().properties.type == 'reveal' and b:getUserData():type() == 'player') then map.layers.hidden.opacity = 1 for k,v in pairs(collectables) do v:hideHidden() end end end end function preSolve(a, b, coll) end function postSolve(a, b, coll, normalimpulse, tangentimpulse) end
--made by Sander#2211 ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) RegisterServerEvent('sa_revive:Revive') AddEventHandler('sa_revive:Revive', function(id, target, health) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local MoneyX = xPlayer.getMoney() local xTarget = ESX.GetPlayerFromId(target) if tonumber(id) == tonumber(target) then if health < 1 then if MoneyX >= Config.Price then xPlayer.removeAccountMoney('money', Config.Price) TriggerClientEvent('esx:showAdvancedNotification', _source, 'Revive-station', 'Revive', 'you revived: ~g~' ..xTarget.getName().. '~w~', 'CHAR_CALL911', 1) TriggerClientEvent('esx:showAdvancedNotification', target, 'Revive-station', 'Revive', 'you were revived by: ~g~' ..xPlayer.getName().. '~w~', 'CHAR_CALL911', 1) xTarget.triggerEvent('esx_ambulancejob:revive') else TriggerClientEvent('esx:showAdvancedNotification', _source, 'Revive-station', 'Money', 'You dont have enough money with you', 'CHAR_CALL911', 1) end else TriggerClientEvent('esx:showAdvancedNotification', _source, 'Revive-station', 'Player', 'The player is not dead', 'CHAR_CALL911', 1) end else TriggerClientEvent('esx:showAdvancedNotification', _source, 'Revive-station', 'Player', 'The ID doesnt exists', 'CHAR_CALL911', 1) end end)
local AceConsole = LibStub("AceConsole-3.0") local LibDataBroker = LibStub("LibDataBroker-1.1") local LibDBIcon = LibStub("LibDBIcon-1.0") --- @type ClickedInternal local _, Addon = ... --- @type Localization local L = LibStub("AceLocale-3.0"):GetLocale("Clicked") --- @type Clicked Clicked = LibStub("AceAddon-3.0"):NewAddon("Clicked", "AceEvent-3.0") --- The current version of Clicked. --- @type string Clicked.VERSION = GetAddOnMetadata("Clicked", "Version") local isPlayerInCombat = false local isInitialized = false -- Local support functions local function RegisterMinimapIcon() local iconData = LibDataBroker:NewDataObject("Clicked", { type = "launcher", label = L["Clicked"], icon = "Interface\\Icons\\inv_misc_punchcards_yellow", OnClick = function() Addon:BindingConfig_Open() end, OnTooltipShow = function(tooltip) tooltip:AddLine(L["Clicked"]) end }) LibDBIcon:Register("Clicked", iconData, Addon.db.profile.options.minimap) end --- Parse a chat command input and handle it appropriately. --- --- @param input string The data of the chat command, excluding the first word local function HandleChatCommand(input) local args = {} local startpos = 1 while true do local arg, next = AceConsole:GetArgs(input, 1, startpos) table.insert(args, arg) if next == 1e9 then break end startpos = next end if #args == 0 then Addon:BindingConfig_Open() elseif #args == 1 then if args[1] == "profile" then Addon:ProfileOptions_Open() elseif args[1] == "blacklist" then Addon:BlacklistOptions_Open() elseif args[1] == "dump" then Addon:StatusOutput_Open() end end end -- Event handlers local function PLAYER_REGEN_DISABLED() isPlayerInCombat = true Addon:AbilityTooltips_Refresh() end local function PLAYER_REGEN_ENABLED() isPlayerInCombat = false Addon:ProcessFrameQueue() Addon:ReloadActiveBindingsIfPending() Addon:AbilityTooltips_Refresh() end local function PLAYER_ENTERING_WORLD() isInitialized = true Addon:ProcessFrameQueue() Addon:UpdateClickCastHeaderBlacklist() Clicked:ReloadActiveBindings() end local function ADDON_LOADED() Addon:ProcessFrameQueue() end local function GET_ITEM_INFO_RECEIVED(_, itemId, success) Addon:BindingConfig_ItemInfoReceived(itemId, success) end local function ZONE_CHANGED_NEW_AREA() Clicked:ReloadActiveBindings() end local function PLAYER_TALENT_UPDATE() Clicked:ReloadActiveBindings() end local function PLAYER_FLAGS_CHANGED(_, unit) if unit == "player" then Clicked:ReloadActiveBindings() end end local function PLAYER_FOCUS_CHANGED() Addon:AbilityTooltips_Refresh() end local function PLAYER_LEVEL_CHANGED() Clicked:ReloadActiveBindings() end local function PLAYER_EQUIPMENT_CHANGED() Clicked:ReloadActiveBindings() end local function GROUP_ROSTER_UPDATE() Clicked:ReloadActiveBindings() end local function MODIFIER_STATE_CHANGED() Addon:AbilityTooltips_Refresh() end local function UNIT_TARGET() Addon:AbilityTooltips_Refresh() end -- Public addon API function Clicked:OnInitialize() local defaultProfile = select(2, UnitClass("player")) --- @type Database Addon.db = LibStub("AceDB-3.0"):New("ClickedDB", self:GetDatabaseDefaults(), defaultProfile) Addon.db.RegisterCallback(self, "OnProfileChanged", "ReloadDatabase") Addon.db.RegisterCallback(self, "OnProfileCopied", "ReloadDatabase") Addon.db.RegisterCallback(self, "OnProfileReset", "ReloadDatabase") Addon:UpgradeDatabaseProfile(Addon.db.profile) RegisterMinimapIcon() Addon:RegisterClickCastHeader() Addon:RegisterBlizzardUnitFrames() Addon:GeneralOptions_Initialize() Addon:ProfileOptions_Initialize() Addon:BlacklistOptions_Initialize() Addon:BindingConfig_Initialize() Addon:StatusOutput_Initialize() Addon:AbilityTooltips_Initialize() AceConsole:RegisterChatCommand("clicked", HandleChatCommand) AceConsole:RegisterChatCommand("cc", HandleChatCommand) end function Clicked:OnEnable() self:RegisterEvent("PLAYER_REGEN_DISABLED", PLAYER_REGEN_DISABLED) self:RegisterEvent("PLAYER_REGEN_ENABLED", PLAYER_REGEN_ENABLED) self:RegisterEvent("PLAYER_ENTERING_WORLD", PLAYER_ENTERING_WORLD) if Addon:IsGameVersionAtleast("BC") then self:RegisterEvent("PLAYER_FOCUS_CHANGED", PLAYER_FOCUS_CHANGED) end if Addon:IsGameVersionAtleast("RETAIL") then self:RegisterEvent("PLAYER_TALENT_UPDATE", PLAYER_TALENT_UPDATE) self:RegisterEvent("PLAYER_FLAGS_CHANGED", PLAYER_FLAGS_CHANGED) end self:RegisterEvent("PLAYER_LEVEL_CHANGED", PLAYER_LEVEL_CHANGED); self:RegisterEvent("PLAYER_EQUIPMENT_CHANGED", PLAYER_EQUIPMENT_CHANGED) self:RegisterEvent("GROUP_ROSTER_UPDATE", GROUP_ROSTER_UPDATE) self:RegisterEvent("ADDON_LOADED", ADDON_LOADED) self:RegisterEvent("GET_ITEM_INFO_RECEIVED", GET_ITEM_INFO_RECEIVED) self:RegisterEvent("ZONE_CHANGED_NEW_AREA", ZONE_CHANGED_NEW_AREA) self:RegisterEvent("MODIFIER_STATE_CHANGED", MODIFIER_STATE_CHANGED) self:RegisterEvent("UNIT_TARGET", UNIT_TARGET) end function Clicked:OnDisable() self:UnregisterEvent("PLAYER_REGEN_DISABLED") self:UnregisterEvent("PLAYER_REGEN_ENABLED") self:UnregisterEvent("PLAYER_ENTERING_WORLD") if Addon:IsGameVersionAtleast("BC") then self:UnregisterEvent("PLAYER_FOCUS_CHANGED") end if Addon:IsGameVersionAtleast("RETAIL") then self:UnregisterEvent("PLAYER_TALENT_UPDATE") self:UnregisterEvent("PLAYER_FLAGS_CHANGED") end self:UnregisterEvent("PLAYER_LEVEL_CHANGED") self:UnregisterEvent("PLAYER_EQUIPMENT_CHANGED") self:UnregisterEvent("GROUP_ROSTER_UPDATE") self:UnregisterEvent("ADDON_LOADED") self:UnregisterEvent("GET_ITEM_INFO_RECEIVED") self:UnregisterEvent("ZONE_CHANGED_NEW_AREA") self:UnregisterEvent("MODIFIER_STATE_CHANGED") self:UnregisterEvent("UNIT_TARGET") end -- Private addon API --- Check if the addon is fully initialized. --- --- @return boolean @`true` if the addon is done initializing, `false` otherwise function Addon:IsInitialized() return isInitialized end --- Check if the player is currently in combat. --- @return boolean @`true` if the player is currently considered to be in combat, `false` otherwise. function Addon:IsPlayerInCombat() return isPlayerInCombat end
local Prop = {} Prop.Name = "J&M Glass CO" Prop.Cat = "Warehouse" Prop.Price = 3200 Prop.Doors = { Vector( -7043, -9828.91015625, 355 ), Vector( -7184, -9915, 347.64999389648 ), Vector( -6585.7299804688, -9760, 320 ), Vector( -6998.2900390625, -9760, 320 ), Vector( -5903.5, -10875, 347 ), Vector( -5903.5, -10781, 347 ), Vector( -5758, -11356, 374 ), Vector( -5216.5, -11685, 351 ), Vector( -5483, -10480.599609375, 347 ), Vector( -4735.5, -11723, 351 ), Vector( -3555, -10968.5, 391 ), Vector( -3856, -11143, 408 ), Vector( -4272, -11143, 408 ), } GM.Property:Register( Prop )
Talk(108, "何掌门说,若医不好夫人的病,就要将我杀了.可是这位夫人所患的病症实在太诡异了,我根本是无能为力.怎么办?我家还有八十岁高龄的母亲及不满十岁的儿女要靠我抚养.少侠请救救我.", "talkname108", 0); ModifyEvent(-2, 7, -2, -2, 138, -1, -1, -2, -2, -2, -2, -2, -2); ModifyEvent(-2, -2, -2, -2, 137, -1, -1, -2, -2, -2, -2, -2, -2); do return end;
---@class CS.FairyEditor.PluginManager ---@field public allPlugins CS.System.Collections.Generic.List_CS.FairyEditor.PluginManager.PluginInfo ---@field public userPluginFolder string ---@field public projectPluginFolder string ---@type CS.FairyEditor.PluginManager CS.FairyEditor.PluginManager = { } ---@return CS.FairyEditor.PluginManager function CS.FairyEditor.PluginManager.New() end function CS.FairyEditor.PluginManager:Dispose() end function CS.FairyEditor.PluginManager:Load() end ---@param filePath string function CS.FairyEditor.PluginManager:LoadUIPackage(filePath) end ---@param name string ---@param displayName string ---@param icon string ---@param desc string ---@param template string function CS.FairyEditor.PluginManager:CreateNewPlugin(name, displayName, icon, desc, template) end return CS.FairyEditor.PluginManager
#!/usr/bin/env lua -- This file drives valgrind test -- See .travis.yml for more detail. require "busted.runner"({ standalone = false })
-- update did and broker --- did="<your device id>" broker = "<the broker url e.g. sensor.mysite.com>" outpin=2 -- Select output pin - GPIO0 gpio.mode(outpin,gpio.OUTPUT) inpin=1 -- Select input pin - GPIO12 gpio.mode(inpin,gpio.INT,gpio.PULLUP) -- attach interrupt to inpin stat="OFF" connecting=true mbroking=true msgs="" vals="" -- init mqtt client with keepalive timer 120sec m = mqtt.Client(wifi.sta.getmac(), 120) m:lwt("/lwt", wifi.sta.getmac(), 0, 0) tmr_broker=0 tmr_motion=1 tmr_nomotion=2 motion_cnt=0 inInt=false last_read=gpio.LOW --nomotion_cnt=0 function isready() return ((not mbroking) and (not connecting)) end m:on("connect", function(conn) print("connected+++++++++++++++++++++++") mbroking=false end) -- on publish message receive event m:on("message", function(conn, topic, data) print(topic .. ":" ) if data ~= nil then print(data) end end) m:on("offline", function(con) print ("reconnecting...") print(node.heap()) mbroking=true tmr.alarm(1, 10000, 0, function() m:connect(broker, 1883, 0) end) end) function pub_stat(s) local data = string.format("{\"did\":\"%s\",\"v\":\"%s\",\"c\":%s}",did,s,tmr.now()) --table.insert(msgs, data) msgs=data print("gonna pub") print(node.heap()) pub_broker() end function motion() if not inInt then -- wait initialize return end last_read = gpio.read(inpin) if (last_read == gpio.HIGH) then stat = 1 gpio.write(outpin,gpio.HIGH) -- Led ON - Motion detected local s = string.format("%s:%s", stat, tmr.now()/1000) print(s) if vals~="" then vals = vals..","..s else vals = s end print(string.len(vals) ) if (string.len(vals) > 300) or (node.heap() < 5000) then pub_stat(vals) vals="" end else stat = 0 gpio.write(outpin,gpio.LOW) -- Led ON - Motion detected end end m:connect(broker, 1883, 0) function pub_broker() if(isready()) then msg = msgs msgs = "" print("msg publishing -------------" .. msg) m:publish("hello/office", msg,0,0, function(conn) print("sent") end) end end gpio.trig(inpin,"both", motion) tmr.alarm(tmr_motion, 10000,0, function() tmr.stop(tmr_motion) print("initialized in") last_read=gpio.read(inpin) inInt=true end)
--[[ © 2018 Thriving Ventures AB do not share, re-distribute or modify without permission of its author (gustaf@thrivingventures.com). ]] local plugin = plugin plugin.name = "Votes" plugin.author = "duck" plugin.version = "0.1" plugin.description = "Adds various commands for voting." plugin.permissions = {"Custom Vote"} serverguard.phrase:Add("english", "command_vote", {SERVERGUARD.NOTIFY.GREEN, "%s", SERVERGUARD.NOTIFY.WHITE, " has started a vote."}) serverguard.phrase:Add("english", "vote_winner", {SERVERGUARD.NOTIFY.WHITE, "Option ", SERVERGUARD.NOTIFY.GREEN, "%s", SERVERGUARD.NOTIFY.WHITE, " has won the vote (%d/", "%d)"}) serverguard.phrase:Add("english", "vote_tied", {SERVERGUARD.NOTIFY.WHITE, "The vote was inconclusive."}) serverguard.phrase:Add("english", "vote_tied_random", {SERVERGUARD.NOTIFY.WHITE, "The vote was inconclusive. Option ", SERVERGUARD.NOTIFY.GREEN, "%s", SERVERGUARD.NOTIFY.WHITE, " was randomly selected as the winner."}) serverguard.phrase:Add("english", "vote_in_progress", {SERVERGUARD.NOTIFY.RED, "There is already a vote in progress."})
-- Copyright (C) 2006-2018 Alexey Kopytov <akopytov@gmail.com> -- This program is free software; you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 2 of the License, or -- (at your option) any later version. -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA -- ----------------------------------------------------------------------------- -- Common code for OLTP benchmarks. -- ----------------------------------------------------------------------------- function init() assert(event ~= nil, "this script is meant to be included by other OLTP scripts and " .. "should not be called directly.") end if sysbench.cmdline.command == nil then error("Command is required. Supported commands: prepare, prewarm, run, " .. "cleanup, help") end function thread_init() drv = sysbench.sql.driver() con = drv:connect() -- Create global nested tables for prepared statements and their -- parameters. We need a statement and a parameter set for each combination -- of connection/table/query stmt = {} param = {} for t = 1, sysbench.opt.tables do stmt[t] = {} param[t] = {} end print_lock = 0 -- print('INIT THREAD') -- This function is a 'callback' defined by individual benchmark scripts prepare_statements() end function thread_done() close_statements() con:disconnect() end -- Re-prepare statements if we have reconnected, which is possible when some of -- the listed error codes are in the --mysql-ignore-errors list function sysbench.hooks.before_restart_event(errdesc) if errdesc.sql_errno == 2013 or -- CR_SERVER_LOST errdesc.sql_errno == 2055 or -- CR_SERVER_LOST_EXTENDED errdesc.sql_errno == 2006 or -- CR_SERVER_GONE_ERROR errdesc.sql_errno == 2011 -- CR_TCP_CONNECTION then close_statements() prepare_statements() end end -- Command line options sysbench.cmdline.options = { table_size = {"Number of rows per table", 10000}, range_size = {"Range size for range SELECT queries", 100}, tables = {"Number of tables", 1}, point_selects = {"Number of point SELECT queries per transaction", 10}, simple_ranges = {"Number of simple range SELECT queries per transaction", 1}, sum_ranges = {"Number of SELECT SUM() queries per transaction", 1}, order_ranges = {"Number of SELECT ORDER BY queries per transaction", 1}, distinct_ranges = {"Number of SELECT DISTINCT queries per transaction", 1}, index_updates = {"Number of UPDATE index queries per transaction", 1}, non_index_updates = {"Number of UPDATE non-index queries per transaction", 1}, delete_inserts = {"Number of DELETE/INSERT combinations per transaction", 1}, deletes = {"Number of DELETE queries per transaction", 1}, inserts = {"Number of INSERT queries per transaction", 1}, range_selects = {"Enable/disable all range SELECT queries", true}, range_insert = {"Range for parallel insert of current server", "0,1000000"}, auto_inc = {"Use AUTO_INCREMENT column as Primary Key (for MySQL), " .. "or its alternatives in other DBMS. When disabled, use " .. "client-generated IDs", true}, skip_trx = {"Don't start explicit transactions and execute all queries " .. "in the AUTOCOMMIT mode", false}, secondary = {"Use a secondary index in place of the PRIMARY KEY", false}, create_secondary = {"Create a secondary index in addition to the PRIMARY KEY", true}, mysql_storage_engine = {"Storage engine, if MySQL is used", "innodb"}, pgsql_variant = {"Use this PostgreSQL variant when running with the " .. "PostgreSQL driver. The only currently supported " .. "variant is 'redshift'. When enabled, " .. "create_secondary is automatically disabled, and " .. "delete_inserts is set to 0"} } -- Implement parallel prepare and prewarm commands sysbench.cmdline.commands = { prepare = {cmd_prepare, sysbench.cmdline.PARALLEL_COMMAND}, prewarm = {cmd_prewarm, sysbench.cmdline.PARALLEL_COMMAND}, } -- Template strings of random digits with 11-digit groups separated by dashes -- 10 groups, 119 characters local c_value_template = "###########-###########-###########-" .. "###########-###########-###########-" .. "###########-###########-###########-" .. "###########" -- 5 groups, 59 characters local pad_value_template = "###########-###########-###########-" .. "###########-###########" function get_c_value() return sysbench.rand.string(c_value_template) end function get_pad_value() return sysbench.rand.string(pad_value_template) end function get_int_value() local val = sysbench.rand.uniform(0, 2000000000) return val end local t = sysbench.sql.type local stmt_defs = { point_selects = { "SELECT * FROM sbtest%u WHERE id=?", {t.VARCHAR,255}}, simple_ranges = { "SELECT * FROM sbtest%u WHERE id BETWEEN ? AND ?", {t.VARCHAR,255}, {t.VARCHAR,255}}, sum_ranges = { "SELECT SUM(amount) FROM sbtest%u WHERE id BETWEEN ? AND ?", {t.VARCHAR,255}, {t.VARCHAR,255}}, order_ranges = { "SELECT * FROM sbtest%u WHERE id BETWEEN ? AND ? ORDER BY FIELD1", {t.VARCHAR,255}, {t.VARCHAR,255}}, distinct_ranges = { "SELECT DISTINCT FIELD1 FROM sbtest%u WHERE id BETWEEN ? AND ? ORDER BY FIELD2", {t.VARCHAR,255}, {t.VARCHAR,255}}, index_updates = { "UPDATE sbtest%u SET FIELD0=FIELD0+1 WHERE id=?", {t.VARCHAR,255}}, non_index_updates = { "UPDATE sbtest%u SET FIELD1=? WHERE id=?", {t.VARCHAR,255}, {t.VARCHAR,255}}, deletes = { "DELETE FROM sbtest%u WHERE id=?", {t.VARCHAR,255}}, inserts = { "INSERT INTO sbtest%u (id, amount, FIELD0, FIELD1, FIELD2, FIELD3, FIELD4, FIELD5, FIELD6, FIELD7, FIELD8) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", {t.VARCHAR,255}, t.INT, t.INT, {t.CHAR,120}, {t.CHAR,120}, {t.CHAR,120}, {t.CHAR,120}, {t.CHAR,120}, {t.CHAR,120}, {t.CHAR,120}, {t.CHAR,120}}, } function prepare_begin() stmt.begin = con:prepare("BEGIN") end function prepare_commit() stmt.commit = con:prepare("COMMIT") end function prepare_for_each_table(key) for t = 1, sysbench.opt.tables do -- print(string.format(stmt_defs[key][1], t)) stmt[t][key] = con:prepare(string.format(stmt_defs[key][1], t)) local nparam = #stmt_defs[key] - 1 if nparam > 0 then param[t][key] = {} end for p = 1, nparam do local btype = stmt_defs[key][p+1] local len if type(btype) == "table" then len = btype[2] btype = btype[1] end if btype == sysbench.sql.type.VARCHAR or btype == sysbench.sql.type.CHAR then param[t][key][p] = stmt[t][key]:bind_create(btype, len) else param[t][key][p] = stmt[t][key]:bind_create(btype) end end if nparam > 0 then stmt[t][key]:bind_param(unpack(param[t][key])) end end end function prepare_point_selects() prepare_for_each_table("point_selects") end function prepare_simple_ranges() prepare_for_each_table("simple_ranges") end function prepare_sum_ranges() prepare_for_each_table("sum_ranges") end function prepare_order_ranges() prepare_for_each_table("order_ranges") end function prepare_distinct_ranges() prepare_for_each_table("distinct_ranges") end function prepare_index_updates() prepare_for_each_table("index_updates") end function prepare_non_index_updates() prepare_for_each_table("non_index_updates") end function prepare_deletes() prepare_for_each_table("deletes") end function prepare_inserts() prepare_for_each_table("inserts") end function prepare_delete_inserts() prepare_for_each_table("deletes") prepare_for_each_table("inserts") end -- Close prepared statements function close_statements() for t = 1, sysbench.opt.tables do for k, s in pairs(stmt[t]) do stmt[t][k]:close() end end if (stmt.begin ~= nil) then stmt.begin:close() end if (stmt.commit ~= nil) then stmt.commit:close() end end local function get_table_num() return sysbench.rand.uniform(1, sysbench.opt.tables) end local function get_id() local id = "abc" .. sysbench.rand.default(1, sysbench.opt.table_size) -- print(id) return id end local function get_id_for_thread() local idx = 0 tmp = {} for val in string.gmatch(sysbench.opt.range_insert, "%d+") do tmp[idx] = val idx = idx + 1 end local size = (tonumber(tmp[1]) - tonumber(tmp[0])) local range = math.floor(size / sysbench.opt.threads) local start = sysbench.tid local id = sysbench.rand.default(start*range+tmp[0], (start+1)*range+tmp[0]) return "abc" .. id --- return "abc" .. (start * range + tmp[0]) end function begin() stmt.begin:execute() end function commit() stmt.commit:execute() end function execute_point_selects() -- print(sysbench.opt.point_selects) local tnum = get_table_num() local i for i = 1, sysbench.opt.point_selects do param[tnum].point_selects[1]:set(get_id()) stmt[tnum].point_selects:execute() end end local function execute_range(key) local tnum = get_table_num() for i = 1, sysbench.opt[key] do local id = get_id() local id_num = tonumber(string.sub(id, 4)) param[tnum][key][1]:set(id) -- param[tnum][key][2]:set(id + sysbench.opt.range_size - 1) param[tnum][key][2]:set("abc" .. (id_num + sysbench.opt.range_size - 1)) stmt[tnum][key]:execute() end end function execute_simple_ranges() execute_range("simple_ranges") end function execute_sum_ranges() execute_range("sum_ranges") end function execute_order_ranges() execute_range("order_ranges") end function execute_distinct_ranges() execute_range("distinct_ranges") end function execute_index_updates() local tnum = get_table_num() for i = 1, sysbench.opt.index_updates do param[tnum].index_updates[1]:set(get_id_for_thread()) stmt[tnum].index_updates:execute() end end function execute_non_index_updates() local tnum = get_table_num() for i = 1, sysbench.opt.non_index_updates do param[tnum].non_index_updates[1]:set_rand_str(c_value_template) param[tnum].non_index_updates[2]:set(get_id_for_thread()) stmt[tnum].non_index_updates:execute() end end function execute_delete_inserts() local tnum = get_table_num() local id = get_id_for_thread() for i = 1, sysbench.opt.delete_inserts do param[tnum].deletes[1]:set(id) local amount = get_int_value() local field0 = get_int_value() param[tnum].inserts[1]:set(id) param[tnum].inserts[2]:set(amount) param[tnum].inserts[3]:set(field0) for j = 4, 11 do param[tnum].inserts[j]:set(get_c_value()) end stmt[tnum].deletes:execute() stmt[tnum].inserts:execute() end end function execute_deletes() local tnum = get_table_num() for i = 1, sysbench.opt.deletes do local id = get_id_for_thread() param[tnum].deletes[1]:set(id) stmt[tnum].deletes:execute() end end function execute_inserts() local tnum = get_table_num() for i = 1, sysbench.opt.inserts do local id = get_id_for_thread() .. (sysbench.rand.unique() - 2147483648) local amount = get_int_value() local field0 = get_int_value() param[tnum].inserts[1]:set(id) param[tnum].inserts[2]:set(amount) param[tnum].inserts[3]:set(field0) for j = 4, 11 do param[tnum].inserts[j]:set(get_c_value()) end stmt[tnum].inserts:execute() end end function log_info(msg) prefix = os.date("%Y/%m/%d %H:%M:%S [info] ") while print_lock > 0 do end print_lock = 1 print(prefix .. msg) print_lock = 0 end function log_error(msg) prefix = os.date("%Y/%m/%d %H:%M:%S [error] ") while print_lock > 0 do end print_lock = 1 print(prefix .. msg) print_lock = 0 end
local template = require("resty.template") --是否缓存解析后的模板,默认true template.caching(true) --渲染模板需要的上下文 local context = {title = "title"} --渲染模板 template.render("t1.html",context) ngx.say("<br/>") --编译得到一个lua函数 local func = template.compile("t1.html") --执行函数 local content = func(context) --ngx api ngx.say(content)
-------------- -- Worldgen -- -------------- -- Uranium minetest.register_ore({ ore_type = "scatter", ore = "elepower_nuclear:stone_with_uranium", wherein = "default:stone", clust_scarcity = 16 * 16 * 16, clust_num_ores = 5, clust_size = 3, y_max = 846, y_min = 248, }) minetest.register_ore({ ore_type = "scatter", ore = "elepower_nuclear:stone_with_uranium", wherein = "default:stone", clust_scarcity = 16 * 16 * 16, clust_num_ores = 5, clust_size = 3, y_max = -248, y_min = -846, }) minetest.register_ore({ ore_type = "scatter", ore = "elepower_nuclear:stone_with_uranium", wherein = "default:stone", clust_scarcity = 16 * 16 * 16, clust_num_ores = 5, clust_size = 3, y_max = -1248, y_min = -1846, })
--[[ © 2020 TERRANOVA do not share, re-distribute or modify without permission of its author. --]] ITEM.base = "base_torso"; ITEM.name = "Olive Green, Winter Coat"; ITEM.model = "models/fty/items/wintercoat.mdl" ITEM.price = 21; ITEM.description = "An olive green winter coat that looks as warm as it feels. A tag of white fabric that reads CWU-Approved hangs on the inside of the collar."; ITEM.flag = "a" ITEM.bodyGroups = { ["torso"] = 12 }
local E, L, V, P, G = unpack(select(2, ...)); --Import: Engine, Locales, PrivateDB, ProfileDB, GlobalDB local DT = E:GetModule('DataTexts') local CH = E:GetModule('Chat') --Lua functions local next, pairs, select, type = next, pairs, select, type local format, strjoin, wipe = string.format, strjoin, wipe --WoW API / Variables local SocialQueueUtil_GetRelationshipInfo = SocialQueueUtil_GetRelationshipInfo local SocialQueueUtil_GetQueueName = SocialQueueUtil_GetQueueName local ToggleQuickJoinPanel = ToggleQuickJoinPanel local C_SocialQueue_GetAllGroups = C_SocialQueue.GetAllGroups local C_SocialQueue_GetGroupMembers = C_SocialQueue.GetGroupMembers local C_SocialQueue_GetGroupQueues = C_SocialQueue.GetGroupQueues local C_LFGList_GetSearchResultInfo = C_LFGList.GetSearchResultInfo local UNKNOWN, QUICK_JOIN = UNKNOWN, QUICK_JOIN local displayModifierString, lastPanel = '' local quickJoinGroups, quickJoin = nil, {} local function OnEnter(self) DT:SetupTooltip(self) if not next(quickJoin) then return end DT.tooltip:AddLine(QUICK_JOIN, nil, nil, nil, true); DT.tooltip:AddLine(" "); for name, activity in pairs(quickJoin) do DT.tooltip:AddDoubleLine(name, activity, nil, nil, nil, 1, 1, 1); end DT.tooltip:Show() end local function OnEvent(self) wipe(quickJoin) quickJoinGroups = C_SocialQueue_GetAllGroups() local coloredName, players, playerName, nameColor, firstMember, numMembers, extraCount, isLFGList, firstQueue, queues, numQueues, activityName, leaderName, isLeader, activity, output, queueCount, queueName, searchResultInfo for _, guid in pairs(quickJoinGroups) do players = C_SocialQueue_GetGroupMembers(guid) if players then firstMember, numMembers, extraCount = players[1], #players, '' playerName, nameColor = SocialQueueUtil_GetRelationshipInfo(firstMember.guid, nil, firstMember.clubId) if numMembers > 1 then extraCount = format(' +%s', numMembers - 1) end if playerName then coloredName = format('%s%s|r%s', nameColor, playerName, extraCount) else coloredName = format('{%s%s}', UNKNOWN, extraCount) end queues = C_SocialQueue_GetGroupQueues(guid) firstQueue, numQueues = queues and queues[1], queues and #queues or 0 isLFGList = firstQueue and firstQueue.queueData and firstQueue.queueData.queueType == 'lfglist' if isLFGList and firstQueue and firstQueue.eligible then if firstQueue.queueData.lfgListID then searchResultInfo = C_LFGList_GetSearchResultInfo(firstQueue.queueData.lfgListID) if searchResultInfo then activityName, leaderName = searchResultInfo.name, searchResultInfo.leaderName isLeader = CH:SocialQueueIsLeader(playerName, leaderName) end end if isLeader then coloredName = format("|TInterface\\GroupFrame\\UI-Group-LeaderIcon:16:16|t%s", coloredName) end activity = activityName or UNKNOWN if numQueues > 1 then activity = format("[+%s]%s", numQueues - 1, activity) end elseif firstQueue then output, queueCount = '', 0 for _, queue in pairs(queues) do if type(queue) == 'table' and queue.eligible then queueName = (queue.queueData and SocialQueueUtil_GetQueueName(queue.queueData)) or '' if queueName ~= '' then if output == '' then output = queueName:gsub('\n.+','') -- grab only the first queue name queueCount = queueCount + select(2, queueName:gsub('\n','')) -- collect additional on single queue else queueCount = queueCount + 1 + select(2, queueName:gsub('\n','')) -- collect additional on additional queues end end end end if output ~= '' then if queueCount > 0 then activity = format("%s[+%s]", output, queueCount) else activity = output end end end quickJoin[coloredName] = activity end end self.text:SetFormattedText(displayModifierString, QUICK_JOIN, #quickJoinGroups) lastPanel = self end local function ValueColorUpdate(hex) displayModifierString = strjoin("", "%s: ", hex, "%s|r") if lastPanel ~= nil then OnEvent(lastPanel) end end E.valueColorUpdateFuncs[ValueColorUpdate] = true DT:RegisterDatatext('Quick Join', {"SOCIAL_QUEUE_UPDATE", "PLAYER_ENTERING_WORLD"}, OnEvent, nil, ToggleQuickJoinPanel, OnEnter, nil, QUICK_JOIN)
local BulletDjensen = Thing:extend("BulletDjensen") function BulletDjensen:new(x, y, dir) BulletDjensen.super.new(self, x, y) self:setImage("bosses/emotilord/djensen") self.SFX.bounce = SFX("sfx/frog_bounce") self.velocity.x = _.signbool(dir) and -700 or 400 self.velocity.y = -_.random(400, 550) self.damaging = true self.angleTimer = step.new(0.5) self.bounce:set(1) end function BulletDjensen:done() BulletDjensen.super.done(self) end function BulletDjensen:update(dt) if self.angleTimer(dt) then self.angle = _.random(-.3, .3) end BulletDjensen.super.update(self, dt) end function BulletDjensen:draw() BulletDjensen.super.draw(self) end function BulletDjensen:onGrounding() BulletDjensen.super.onGrounding(self) self.scene:playSFX(self.SFX.bounce) end return BulletDjensen
return {'eddie','eddo','eddy','eddies','eddos','eddys'}
-- Copyright (c) 2019 Redfern, Trevor <trevorredfern@gmail.com> -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local csv = require("moonpie.ext.csv") local colors = { } function colors.convert_hex(hex) hex = hex:gsub("#","") if (string.len(hex) == 6) then return tonumber("0x"..hex:sub(1,2))/255, tonumber("0x"..hex:sub(3,4))/255, tonumber("0x"..hex:sub(5,6))/255 elseif (string.len(hex) == 3) then return tonumber("0x"..hex:sub(1,1)..hex:sub(1,1))/255, tonumber("0x"..hex:sub(2,2)..hex:sub(2,2))/255, tonumber("0x"..hex:sub(3,3)..hex:sub(3,3))/255 end end -- TODO: Remove hardcoded color directory local csv_file = love.filesystem.read("moonpie/assets/colors.csv") local contents = csv.openstring(csv_file) for fields in contents:lines() do local r,g,b = colors.convert_hex(fields[3]) colors[fields[1]]={ r, g, b, 1 } end colors.transparent = {0,0,0,0} function colors.redistribute_rgb(clr) local r, g, b, a = clr[1], clr[2], clr[3], clr[4] local m = math.max(r, g, b) if m <= 1.0 then return { r, g, b, a } end -- maxed out local total = r + g + b if total >= 3 then return { 1, 1, 1, a } end local x = (3 - total) / (3 * m - total) local gray = 1 - x * m return { gray + x * r, gray + x * g, gray + x * b, a } end function colors.lighten(clr, multiplier) return colors.redistribute_rgb({ clr[1] * multiplier, clr[2] * multiplier, clr[3] * multiplier, clr[4] }) end function colors.get_color(self, clr, opacity) if type(clr) == "table" then return { clr[1], clr[2], clr[3], opacity or clr[4] } elseif type(clr) == "string" then return self(self[clr], opacity) elseif type(clr) == "function" then return self(clr(self), opacity) end return nil end function colors.is_color(v) return type(v) == "table" and #v == 4 end function colors.all() local out = {} for _, v in pairs(colors) do if colors.is_color(v) then out[#out + 1] = v end end return out end setmetatable(colors, { __call = colors.get_color }) return colors
object_building_kashyyyk_thm_kash_south_bridge = object_building_kashyyyk_shared_thm_kash_south_bridge:new { } ObjectTemplates:addTemplate(object_building_kashyyyk_thm_kash_south_bridge, "object/building/kashyyyk/thm_kash_south_bridge.iff")
---------------------------------------------------------------------------------------------------- -- This is a class to set the layout of UIComponent. -- -- @author Makoto -- @release V3.0.0 ---------------------------------------------------------------------------------------------------- -- import local PropertyUtils = require 'candy.ui.PropertyUtils' ---@class UILayout local UILayout = CLASS: UILayout () --- -- Constructor. function UILayout:__init ( params ) self:_initInternal () self:setProperties ( params ) end --- -- Initialize the internal variables. function UILayout:_initInternal () end --- -- Update the layout. ---@param parent parent component. function UILayout:update ( parent ) end --- -- Sets the properties. ---@param properties properties function UILayout:setProperties ( properties ) if properties then PropertyUtils.setProperties ( self, properties, true ) end end return UILayout
for i = 1,10 do if i == 5 then i = 6 end print(i) end
local ffi = require("ffi") local lua = require "luajit_ffi" local function report_errors(L, status) if status ~= 0 then print("-- ", ffi.string(lua.lua_tostring(L, -1))) lua.lua_pop(L, 1); -- remove error message end end local LuaState = { Defaults = {} } setmetatable(LuaState, { __call = function(self, ...) return self:new(...); end, }); local LuaState_mt = { __index = LuaState; } -- Must at least load base library -- or 'require' and print won't work -- MUST load jit, or JIT won't work --[[ lua.luaopen_base(L) lua.luaopen_string(L); lua.luaopen_math(L); lua.luaopen_io(L); lua.luaopen_table(L); lua.luaopen_bit(L); lua.luaopen_jit(L); lua.luaopen_ffi(L); --]] LuaState.loadBaseLibraries = function(self, L) lua.luaL_openlibs(L); end LuaState.new = function(self, codechunk, autorun) local L = lua.luaL_newstate(); -- create state if L == nil then return nil, "cannot create state: not enough memory"; end local obj = { State = L; } setmetatable(obj, LuaState_mt); LuaState:loadBaseLibraries(L); if LuaState.Init then self.InitStatus = self:run(LuaState.Init); end if codechunk then self.CodeChunk = codechunk if autorun then self:run(codechunk) end end return obj; end function LuaState:loadChunk(s) local result = lua.luaL_loadstring(self.State, s) report_errors(self.State, result) return result end function LuaState:run(codechunk) local result if codechunk then result = self:LoadChunk(codechunk) end if result == 0 then result = lua.lua_pcall(self.State, 0, lua.LUA_MULTRET, 0) report_errors(self.State, result) else return result end return result end return LuaState;
-- -- @copyright (c) 2015 Upstart Illustration LLC. All rights reserved. -- local ConfigureRequest = Class() ConfigureRequest.implements("bridge.BridgeRequestProtocol") function ConfigureRequest.new(self) local service local config function self.init(_service, _config) service = _service config = _config end -- BridgeRequestProtocol function self.toDict() return {service=service, config=config} end end return ConfigureRequest
----------------------------------------------------------------------------- -- webThreads: Xavante resumable handlers framework -- -- Author: Javier Guerra -- Copyright (c) 2005 Kepler Project ----------------------------------------------------------------------------- local session = require "xavante.session" local unpack = table.unpack or unpack local coroWeb = {} -- original coroutine functions local o_resume, o_yield = coroutine.resume, coroutine.yield -- creates a resume/yield pair local function _ortoroutines (err) err = err or error local _tag = {} return function (co, ...) local arg = {...} local r,sts repeat r = { o_resume (co, unpack (arg)) } sts = coroutine.status (co) if not r[1] then err (r[2]) end table.remove (r,1) if r[1] ~= _tag and sts == "suspended" then arg = { o_yield (unpack (r)) } end until r[1] == _tag or sts == "dead" table.remove (r,1) return unpack (r) end, function (...) return o_yield (_tag, ...) end end local function _error (res, err) res:send_data ("<h1>error:"..err.."</h1>") end coroWeb.resume, coroWeb.yield = _ortoroutines () -- -- creates a xavante handler -- params: -- name (string) : session name to use -- h (function) : thread to handle -- function coroWeb.handler (name, h) return function (req, res) local sess = session.open (req, res, name) sess.coHandler = sess.coHandler or coroutine.create (h) coroWeb.resume (sess.coHandler, req, res) if coroutine.status (sess.coHandler) == "dead" then session.close (req, res, name) end return res end end -- -- gets user actions as events -- params: -- in_req (table) : 'req' parameter -- sh_t (table) : namesubhandlers function coroWeb.event (in_req, sh_t, get_all) local req, res local subH, ret repeat req, res = coroWeb.yield () subH = sh_t [req.relpath] if subH and type (subH) == "function" then ret = subH (req, res) end if ret then xavante.httpd.redirect (res, ret) elseif ret == "refresh" then xavante.httpd.redirect (res, in_req.parsed_url.path) req, res = coroWeb.yield () end until not subH or get_all or ret == "refresh" return req, res end
particles = {} function spawnParticle(type, x, y, args) local particle = {} particle.type = type particle.args = args particle.tag = "" -- used for finding related particles -- Function that sets the properties of the new particle local init = require("src/effects/particles/" .. type) particle = init(particle, x, y, args) -- This update function is the same for all particles, regardless of type function particle:genericUpdate(dt) if self.timer > 0 then self.timer = self.timer - dt else self.dead = true self.timer = 0 end end table.insert(particles, particle) end function particles:update(dt) -- Calls update functions on all particles for i,p in ipairs(self) do p:update(dt) p:genericUpdate(dt) end -- Iterate through all particles in reverse to remove the dead ones for i=#particles,1,-1 do if particles[i].dead then if particles[i].tween then particles[i].tween:stop() end if particles[i].physics then particles[i].physics:destroy() end table.remove(particles, i) end end end function particles:draw() -- Calls draw functions on all particles for i,p in ipairs(self) do p:draw() end end
-- Use Include 'prosody-ldap.cfg.lua' from prosody.cfg.lua to include this file authentication = 'ldap2' -- Indicate that we want to use LDAP for authentication --storage = 'ldap' -- Indicate that we want to use LDAP for roster/vcard storage storage = { roster = "ldap"; vcard = "ldap"; archive2 = "sql2"; muc_log = "sql2"; } ldap = { hostname = '{{LDAP_HOST}}', -- LDAP server location bind_dn = '{{LDAP_DN}}', -- Bind DN for LDAP authentication (optional if anonymous bind is supported) bind_password = '{{LDAP_PWD}}', -- Bind password (optional if anonymous bind is supported) user = { basedn = 'ou=users,{{LDAP_BASE}}', -- The base DN where user records can be found filter = '(&(objectClass=person)(!(uid=seven)))', -- Filter expression to find user records under basedn usernamefield = 'uid', -- The field that contains the user's ID (this will be the username portion of the JID) namefield = 'cn', -- The field that contains the user's full name (this will be the alias found in the roster) }, groups = { basedn = 'ou=groups,{{LDAP_BASE}}', -- The base DN where group records can be found memberfield = 'member', -- The field that contains user ID records for this group (each member must have a corresponding entry under the user basedn with the same value in usernamefield) namefield = 'cn', -- The field that contains the group's name (used for matching groups in LDAP to group definitions below) { name = 'GroupName', -- The group name that will be seen in users' rosters cn = 'groupname', -- This field's key *must* match ldap.groups.namefield! It's the name of the LDAP group this definition represents admin = false, -- (Optional) A boolean flag that indicates whether members of this group should be considered administrators. }, { name = 'admins', cn = 'admins', admin = true, }, }, vcard_format = { displayname = 'cn', -- Consult the vCard configuration section in the README nickname = 'uid', name = { family = 'sn', given = 'givenName', }, photo = { type = 'image/jpeg', binval = 'jpegPhoto', }, telephone = { work = { number = 'telephoneNumber', } }, address = { work = { street = 'street', -- street name pcode = 'postalCode', -- postal code locality = 'l', -- city name ctry = 'c', -- country name } }, email = { internet = { userid = 'mail', } }, }, }
local COMMAND = Clockwork.command:New("Announce"); COMMAND.tip = "Announce something to everyone on the server."; COMMAND.text = "<string Text>"; COMMAND.access = "o"; COMMAND.arguments = 1; -- Called when the command has been run. function COMMAND:OnRun(player, arguments) Clockwork.chatBox:Add(nil, nil, "cp_announce", arguments[1]); end; COMMAND:Register();
----------------------------------------- -- ID: 5016 -- Scroll of Shining Fantasia -- Teaches the song Shining Fantasia ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(408) end function onItemUse(target) target:addSpell(408) end
-- Helper Functions local function UpdateSelected(radioButtons, selected, silent) for i, radioButton in ipairs(radioButtons) do if radioButton ~= selected then radioButton:SetSelected(false, silent) end end end -- Public Functions local class = {} class.__index = class function class:GetName() return self.name end function class:AddRadioButton(radioButton) table.insert(self.radioButtons, radioButton) radioButton.group = self end function class:RemoveRadioButton(radioButton) assert(type(radioButton) == "number" or type(radioButton) == "table", "param 1 must be a number or a radiobutton frame!") radioButton.group = nil if type(radioButton) == "number" then table.remove(self.radioButtons, radioButton) else for i, v in ipairs(self.radioButtons) do if v == radioButton then table.remove(self.radioButtons, i) end end end end function class:GetRadioButton(index) assert(type(index) == "number", "param 1 must be a number!") return self.radioButtons[index] end function class:GetSelectedRadioButton() for i, radioButton in ipairs(self.radioButtons) do if radioButton:GetSelected() then return radioButton end end end function class:GetSelectedIndex() for i, radioButton in ipairs(self.radioButtons) do if radioButton:GetSelected() then return i end end end function class:SetSelectedIndex(index, silent) assert(type(index) == "number", "param 1 must be a number!") assert(silent == nil or type(silent) == "boolean", "param 2 must be a boolean!") local radioButton = self.radioButtons[index] radioButton:SetSelected(true, silent) end function class:SetEnabled(enabled) assert(type(enabled) == "boolean", "param 1 must be a boolean!") for i, radioButton in ipairs(self.radioButtons) do radioButton:SetEnabled(enabled) end end -- Internal Functions function class:RadioButtonSelected(radioButton, silent) UpdateSelected(self.radioButtons, radioButton, silent) if not silent and self.Event.RadioButtonChange then self.Event.RadioButtonChange(self) end end -- Constructor Function function Library.LibSimpleWidgets.RadioButtonGroup(name) assert(type(name) == "string", "param 1 must be a string!") local group = {} setmetatable(group, class) group.name = name group.radioButtons = {} Library.LibSimpleWidgets.EventProxy(group, { "RadioButtonChange" }) return group end
local t = require("aaaaa").mod local b = require("bbbbb") local c = require "ddddd" p("okwjgfiowjiofw").aa = 13
luapack = luapack or {} local green = {r = 0, g = 255, b = 0, a = 255} function luapack.LogMsg(...) MsgC(green, "[LuaPack] ") print(...) end local yellow = {r = 255, g = 255, b = 0, a = 255} function luapack.DebugMsg(...) MsgC(yellow, "[LuaPack] ") print(...) end function luapack.CanonicalizePath(path) path = string.lower(path) path = string.gsub(path, "\\", "/") path = string.gsub(path, "/+", "/") local t = {} for str in string.gmatch(path, "([^/]+)") do if str == ".." then table.remove(t) elseif str ~= "." and str ~= "" then table.insert(t, str) end end path = table.concat(t, "/") return string.match(path, "lua/(.+)$") or (string.match(path, "^gamemodes/(.+)$") or path) end
require("iuplua") require("iupluagl") require("luagl") require("luaglu") iup.key_open() cnv = iup.glcanvas{buffer="DOUBLE", rastersize = "640x480"} function cnv:resize_cb(width, height) iup.GLMakeCurrent(self) gl.Viewport(0, 0, width, height) gl.MatrixMode('PROJECTION') -- Select The Projection Matrix gl.LoadIdentity() -- Reset The Projection Matrix if height == 0 then height = 1 end -- Avoid division by zero glu.Perspective(80, width / height, 1, 5000) -- Calculate The Aspect Ratio And Set The Clipping Volume gl.MatrixMode('MODELVIEW') -- Select The Model View Matrix gl.LoadIdentity() -- Reset The Model View Matrix end function cnv:action(x, y) iup.GLMakeCurrent(self) gl.Clear('COLOR_BUFFER_BIT,DEPTH_BUFFER_BIT') -- Clear Screen And Depth Buffer iup.GLSwapBuffers(self) end function cnv:k_any(c) if c == iup.K_q or c == iup.K_ESC then return iup.CLOSE elseif c == iup.K_F1 then if fullscreen then fullscreen = false dlg.fullscreen = "No" else fullscreen = true dlg.fullscreen = "Yes" end end end function cnv:map_cb() iup.GLMakeCurrent(self) gl.ShadeModel('SMOOTH') -- Enable Smooth Shading gl.ClearColor(0, 0, 0, 0.5) -- Black Background gl.ClearDepth(1.0) -- Depth Buffer Setup gl.Enable('DEPTH_TEST') -- Enables Depth Testing gl.DepthFunc('LEQUAL') -- The Type Of Depth Testing To Do gl.Enable('COLOR_MATERIAL') gl.Hint('PERSPECTIVE_CORRECTION_HINT','NICEST') end dlg = iup.dialog{cnv; title="LuaGL Test Application 01"} dlg:show() cnv.rastersize = nil -- reset minimum limitation if (not iup.MainLoopLevel or iup.MainLoopLevel()==0) then iup.MainLoop() end
local function parse_args() local cmd = torch.CmdLine() cmd:option("-batch_size", 128, "") cmd:option("-alpha", 0.0001, "learning rate") cmd:option("-max_iter", 8, "max number of iteration") cmd:option("-gpu_index", 1, "the index of GPU to use") cmd:option("-params_file", "Atten/save_t_given_s/params", "load hyperparameters for a pre-trained generative model") cmd:option("-model_file", "Atten/save_t_given_s/model1", "path for loading the pre-trained generative model") cmd:option("-train_file", "data/t_given_s_train.txt", "") cmd:option("-dev_file", "data/t_given_s_dev.txt", "") cmd:option("-test_file", "data/t_given_s_test.txt", "") cmd:option("-save_model_path", "save", "path for saving the model") cmd:option("-readSequenceModel", true, "whether to read a pretrained seq2seq model. this variable has to be set to true when training the model") cmd:option("-readFutureModel", false, "whether to load a pretrained Soothsayer Model. this variable has to be set to false when training the model") cmd:option("-FuturePredictorModelFile", "", "path for load a pretrained Soothsayer Model. does not need it at model training time") local params = cmd:parse(arg) paths.mkdir(params.save_model_path) print(params) return params end return parse_args
include("plat/build.lua") local conly = { rpi = true } local softfp = { cpm = true, } local sourcefiles = filenamesof( "./hilo.b", "./hilo.bas", "./hilo.c", "./hilo.mod", "./hilo.p", "./mandelbrot.c", "./paranoia.c", "./startrek.c" ) local usesfp = { ["mandelbrot.c"] = true, ["startrek.c"] = true, } local installmap = {} for _, file in ipairs(sourcefiles) do local b = basename(file) local be = replace(b, "%.", "_") local _, _, e = b:find("%.(%w*)$") for _, plat in ipairs(vars.plats) do local flags = {} if softfp[plat] and usesfp[b] then flags[#flags+1] = "-fp" end if (e == "c") or not conly[plat] then local exe = ackprogram { name = be.."_"..plat, srcs = { file }, vars = { plat = plat, lang = e, ["+ackldflags"] = flags, } } installmap["$(PLATIND)/examples/"..be.."."..plat] = exe end end installmap["$(PLATIND)/examples/"..b] = file end installable { name = "pkg", map = installmap }
----------------------------------------- -- ID: 5006 -- Scroll of Valor Minuet V -- Teaches the song Valor Minuet V ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(398) end function onItemUse(target) target:addSpell(398) end
AmmoPackAbilityMixin = CreateMixin(AmmoPackAbilityMixin) AmmoPackAbilityMixin.type = "AmmoPackAbility" local kUseSound = PrecacheAsset("sound/NS2.fev/marine/common/pickup_ammo") AmmoPackAbilityMixin.networkVars = { timeLastAmmoPackUsed = "time", ammoPackAbilityEnabled = "boolean" } function AmmoPackAbilityMixin:__initmixin() self.timeLastAmmoPackUsed = 0 self.ammoPackAbilityEnabled = false end function AmmoPackAbilityMixin:GetIsAmmoPackAbilityEnabled() return self.ammoPackAbilityEnabled end function AmmoPackAbilityMixin:SetIsAmmoPackAbilityEnabled(isEnabled) self.ammoPackAbilityEnabled = isEnabled end local function GetRemainingCooldownTime(self) if self.timeLastAmmoPackUsed == 0 then return 0 end return math.max(0, self.timeLastAmmoPackUsed + kAmmoPackAbilityCooldown - Shared.GetTime()) end local function CheckNeedsAmmo(self) local needsAmmo = false if self:isa("Marine") then for i = 0, self:GetNumChildren() - 1 do local child = self:GetChildAtIndex(i) if child:isa("ClipWeapon") and child:GetNeedsAmmo(false) then needsAmmo = true break end end end return needsAmmo end function AmmoPackAbilityMixin:CanApplyAmmoPack() if Server then if not self:isa("Marine") then return false end local userId = Server.GetOwner(self):GetUserId() local coolDownTime = GetRemainingCooldownTime(self) local alive = self:GetIsAlive() local vortexed = GetIsVortexed() local hasAbility = GetGameMaster():GetMarinePersistData():GetHasAbility(userId, kTechId.AmmoPack) local needsAmmo = CheckNeedsAmmo(self) return hasAbility and self.ammoPackAbilityEnabled and coolDownTime == 0 and alive and not vortexed and needsAmmo end end function AmmoPackAbilityMixin:ApplyAmmoPack() local consumedPack = false local emptyClip = false if self:isa("Marine") then for i = 0, self:GetNumChildren() - 1 do local child = self:GetChildAtIndex(i) if child:isa("ClipWeapon") then if child:GetAmmo() == 0 then emptyClip = true end if child:GiveAmmo(AmmoPack.kNumClips, false) then consumedPack = true end end end if consumedPack then self.timeLastAmmoPackUsed = Shared.GetTime() StartSoundEffectAtOrigin(kUseSound, self:GetOrigin()) if emptyClip then self:Reload() end end end end function AmmoPackAbilityMixin:GetAmmoPackCooldownFraction() local timeRemaining = GetRemainingCooldownTime(self) return ConditionalValue(timeRemaining > 0, timeRemaining / kAmmoPackAbilityCooldown, 0) end
--- Functions for command-line scripts. module("luarocks.command_line", package.seeall) local util = require("luarocks.util") local cfg = require("luarocks.cfg") local path = require("luarocks.path") local dir = require("luarocks.dir") local deps = require("luarocks.deps") --- Display an error message and exit. -- @param message string: The error message. local function die(message) assert(type(message) == "string") local ok, err = pcall(util.run_scheduled_functions) if not ok then util.printerr("\nLuaRocks "..cfg.program_version.." internal bug (please report at luarocks-developers@lists.sourceforge.net):\n"..err) end util.printerr("\nError: "..message) os.exit(1) end --- Main command-line processor. -- Parses input arguments and calls the appropriate driver function -- to execute the action requested on the command-line, forwarding -- to it any additional arguments passed by the user. -- Uses the global table "commands", which contains -- the loaded modules representing commands. -- @param ... string: Arguments given on the command-line. function run_command(...) local args = {...} local cmdline_vars = {} for i = #args, 1, -1 do local arg = args[i] if arg:match("^[^-][^=]*=") then local var, val = arg:match("^([A-Z_][A-Z0-9_]*)=(.*)") if val then cmdline_vars[var] = val table.remove(args, i) else die("Invalid assignment: "..arg) end end end local nonflags = { util.parse_flags(unpack(args)) } local flags = table.remove(nonflags, 1) if flags["from"] then flags["server"] = flags["from"] end if flags["only-from"] then flags["only-server"] = flags["only-from"] end if flags["only-sources-from"] then flags["only-sources"] = flags["only-sources-from"] end if flags["to"] then flags["tree"] = flags["to"] end if flags["nodeps"] then flags["deps-mode"] = "none" table.insert(args, "--deps-mode=none") end cfg.flags = flags local command if flags["version"] then util.printout(program_name.." "..cfg.program_version) util.printout(program_description) util.printout() os.exit(0) elseif flags["help"] or #nonflags == 0 then command = "help" args = nonflags else command = nonflags[1] for i, arg in ipairs(args) do if arg == command then table.remove(args, i) break end end end command = command:gsub("-", "_") if flags["extensions"] then cfg.use_extensions = true local type_check = require("luarocks.type_check") type_check.load_extensions() end if cfg.local_by_default then flags["local"] = true end if flags["deps-mode"] and not deps.check_deps_mode_flag(flags["deps-mode"]) then die("Invalid entry for --deps-mode.") end if flags["tree"] then if flags["tree"] == true or flags["tree"] == "" then die("Argument error: use --tree=<path>") end local fs = require("luarocks.fs") local root_dir = fs.absolute_name(flags["tree"]) path.use_tree(root_dir) elseif flags["local"] then path.use_tree(cfg.home_tree) else local trees = cfg.rocks_trees path.use_tree(trees[#trees]) end if type(cfg.root_dir) == "string" then cfg.root_dir = cfg.root_dir:gsub("/+$", "") else cfg.root_dir.root = cfg.root_dir.root:gsub("/+$", "") end cfg.rocks_dir = cfg.rocks_dir:gsub("/+$", "") cfg.deploy_bin_dir = cfg.deploy_bin_dir:gsub("/+$", "") cfg.deploy_lua_dir = cfg.deploy_lua_dir:gsub("/+$", "") cfg.deploy_lib_dir = cfg.deploy_lib_dir:gsub("/+$", "") cfg.variables.ROCKS_TREE = cfg.rocks_dir cfg.variables.SCRIPTS_DIR = cfg.deploy_bin_dir if flags["server"] then if flags["server"] == true then die("Argument error: use --server=<url>") end local protocol, path = dir.split_url(flags["server"]) table.insert(cfg.rocks_servers, 1, protocol.."://"..path) end if flags["only-server"] then if flags["only-server"] == true then die("Argument error: use --only-server=<url>") end cfg.rocks_servers = { flags["only-server"] } end if flags["only-sources"] then cfg.only_sources_from = flags["only-sources"] end if command ~= "help" then for k, v in pairs(cmdline_vars) do cfg.variables[k] = v end end if commands[command] then -- TODO the interface of run should be modified, to receive the -- flags table and the (possibly unpacked) nonflags arguments. -- This would remove redundant parsing of arguments. -- I'm not changing this now to avoid messing with the run() -- interface, which I know some people use (even though -- I never published it as a public API...) local xp, ok, err = xpcall(function() return commands[command].run(unpack(args)) end, function(err) die(debug.traceback("LuaRocks "..cfg.program_version .." bug (please report at luarocks-developers@lists.sourceforge.net).\n" ..err, 2)) end) if xp and (not ok) then die(err) end else die("Unknown command: "..command) end util.run_scheduled_functions() end
-- Base16 PhD color -- Author: Hennig Hasemann (http://leetless.de/vim.html) -- to be use in your theme.lua -- symlink or copy to config folder `local color = require('color')` local M = {} M.base00 = "#061229" -- ---- M.base01 = "#2a3448" -- --- M.base02 = "#4d5666" -- -- M.base03 = "#717885" -- - M.base04 = "#9a99a3" -- + M.base05 = "#b8bbc2" -- ++ M.base06 = "#dbdde0" -- +++ M.base07 = "#ffffff" -- ++++ M.base08 = "#d07346" -- red M.base09 = "#f0a000" -- orange M.base0A = "#fbd461" -- yellow M.base0B = "#99bf52" -- green M.base0C = "#72b9bf" -- aqua/cyan M.base0D = "#5299bf" -- blue M.base0E = "#9989cc" -- purple M.base0F = "#b08060" -- brown return M
local entity local Fishing = false local WaterTypes = { [1] = {["name"] = "Sea of Coronado", ["waterhash"] = -247856387, ["watertype"] = "lake"}, [2] = {["name"] = "San Luis River", ["waterhash"] = -1504425495, ["watertype"] = "river"}, [3] = {["name"] = "Lake Don Julio", ["waterhash"] = -1369817450, ["watertype"] = "lake"}, [4] = {["name"] = "Flat Iron Lake", ["waterhash"] = -1356490953, ["watertype"] = "lake"}, [5] = {["name"] = "Upper Montana River", ["waterhash"] = -1781130443, ["watertype"] = "river"}, [6] = {["name"] = "Owanjila", ["waterhash"] = -1300497193, ["watertype"] = "river"}, [7] = {["name"] = "HawkEye Creek", ["waterhash"] = -1276586360, ["watertype"] = "river"}, [8] = {["name"] = "Little Creek River", ["waterhash"] = -1410384421, ["watertype"] = "river"}, [9] = {["name"] = "Dakota River", ["waterhash"] = 370072007, ["watertype"] = "river"}, [10] = {["name"] = "Beartooth Beck", ["waterhash"] = 650214731, ["watertype"] = "river"}, [11] = {["name"] = "Lake Isabella", ["waterhash"] = 592454541, ["watertype"] = "lake"}, [12] = {["name"] = "Cattail Pond", ["waterhash"] = -804804953, ["watertype"] = "lake"}, [13] = {["name"] = "Deadboot Creek", ["waterhash"] = 1245451421, ["watertype"] = "river"}, [14] = {["name"] = "Spider Gorge", ["waterhash"] = -218679770, ["watertype"] = "river"}, [15] = {["name"] = "O'Creagh's Run", ["waterhash"] = -1817904483, ["watertype"] = "lake"}, [16] = {["name"] = "Moonstone Pond", ["waterhash"] = -811730579, ["watertype"] = "lake"}, [17] = {["name"] = "Roanoke Valley", ["waterhash"] = -1229593481, ["watertype"] = "river"}, [18] = {["name"] = "Elysian Pool", ["waterhash"] = -105598602, ["watertype"] = "lake"}, [19] = {["name"] = "Heartland Overflow", ["waterhash"] = 1755369577, ["watertype"] = "swamp"}, [20] = {["name"] = "Lagras", ["waterhash"] = -557290573, ["watertype"] = "swamp"}, [21] = {["name"] = "Lannahechee River", ["waterhash"] = -2040708515, ["watertype"] = "river"}, [22] = {["name"] = "Dakota River", ["waterhash"] = 370072007, ["watertype"] = "river"}, [23] = {["name"] = "Random1", ["waterhash"] = 231313522, ["watertype"] = "river"}, [24] = {["name"] = "Random2", ["waterhash"] = 2005774838, ["watertype"] = "river"}, [25] = {["name"] = "Random3", ["waterhash"] = -1287619521, ["watertype"] = "river"}, [26] = {["name"] = "Random4", ["waterhash"] = -1308233316, ["watertype"] = "river"}, [27] = {["name"] = "Random5", ["waterhash"] = -196675805, ["watertype"] = "river"}, } RegisterNetEvent('scf_fishing:StartFishing') AddEventHandler('scf_fishing:StartFishing', function() if not Fishing then Fishing = true local ped = PlayerPedId() local coords = GetEntityCoords(ped) local Water = Citizen.InvokeNative(0x5BA7A68A346A5A91,coords.x, coords.y, coords.z) local foundwater = false local dic = "amb_work@world_human_stand_fishing@male_b@base" local boneIndex = GetEntityBoneIndexByName(playerPed, "SKEL_R_HAND") local modelHash = GetHashKey("p_fishingpole01x") local anim = "base" loadAnimDict(dic) local entity = CreateObject(modelHash, coords.x+0.3, coords.y,coords.z, true, false, false) AttachEntityToEntity(entity, ped, boneIndex, 0.1, -0.1, -0.0, -66.0, -0.2, -0.2, false, false, false, true, 2, true) TaskPlayAnim(ped, dic, anim, 1.0, 8.0, -1, 1, 0, false, false, false) for k,v in pairs(WaterTypes) do if Water == WaterTypes[k]["waterhash"] then foundwater = true w = math.random(12,28) local seconds = w/1 for i=1,seconds,1 do TriggerEvent("vorp:Tip", "Fishing.", 500) Wait(335) TriggerEvent("vorp:Tip", "Fishing..", 500) Wait(335) TriggerEvent("vorp:Tip", "Fishing...", 500) Wait(335) end -- Wait(w) ClearPedTasks(ped) DeleteObject(entity) DeleteEntity(entity) TriggerServerEvent("fishing") break end end Fishing = false if foundwater == false then TriggerEvent("vorp:TipBottom", "You cant fish here", 10000) end end end) function loadAnimDict(dict) RequestAnimDict(dict) while not HasAnimDictLoaded(dict) do Citizen.Wait(500) end end
local player_helper = require("/dynamic/helpers/player_helpers.lua") local angle_helpers = require("/dynamic/helpers/angle_helpers.lua") local floating_message = require("/dynamic/helpers/floating_message.lua") local shield_box = require("/dynamic/helpers/boxes/shield_box.lua") local cannon_box = require("/dynamic/helpers/boxes/cannon_box.lua") local blindness_boxes = require("/dynamic/blindness_boxes/blindness_boxes.lua") local set = require("/dynamic/timeout_helper.lua") local height = 1000fx local width = 750fx pewpew.set_level_size(width, height) local weapon_config = {frequency = pewpew.CannonFrequency.FREQ_10, cannon = pewpew.CannonType.DOUBLE} local player = player_helper.new_player_ship( 375fx, 150fx, 0) pewpew.configure_player(0, {camera_distance = 650fx, shield = 2}) pewpew.configure_player_ship_weapon(player, weapon_config) local function random_position() return fmath.random_fixedpoint(10fx, width-10fx), fmath.random_fixedpoint(10fx, height-10fx) end local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/outline.lua", 0) local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/outline.lua", 1) local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/outline.lua", 2) local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/outline.lua", 3) local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/outline.lua", 4) local background = pewpew.new_customizable_entity(0fx, 0fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/outline.lua", 5) local background = pewpew.new_customizable_entity(-220fx, -220fx) pewpew.customizable_entity_set_mesh(background, "/dynamic/background.lua", 0) local dots_background = pewpew.new_customizable_entity(width / 2fx, height / 2fx) pewpew.customizable_entity_set_mesh(dots_background, "/dynamic/cage_graphics.lua", 0) pewpew.add_wall(335fx, 400fx, 415fx, 400fx) pewpew.add_wall(275fx, 460fx, 275fx, 540fx) pewpew.add_wall(480fx, 460fx, 480fx, 540fx) pewpew.add_wall(335fx, 600fx, 415fx, 600fx) local text = pewpew.new_customizable_entity(375fx, 1085fx) pewpew.customizable_entity_set_string(text, "#ffffff05April fools? More like Blind fools!") local text2 = pewpew.new_customizable_entity(378fx, 1087fx) pewpew.customizable_entity_set_string(text2, "#ffffff04April fools? More like Blind fools!") local text3 = pewpew.new_customizable_entity(372fx, 1083fx) pewpew.customizable_entity_set_string(text3, "#ffffff03April fools? More like Blind fools!") local function toRad(x) return x * (22fx/7fx) / 180fx end local function toDeg(x) return x * 180fx / (22fx/7fx) end local function random_position() return fmath.random_fixedpoint(10fx, width-10fx), fmath.random_fixedpoint(10fx, height-10fx) end local angle = fmath.random_fixedpoint(0fx,fmath.tau()) local rx, ry = random_position() local shield = shield_box.new(375fx, 500fx, weapon_config) local time = 0 pewpew.add_update_callback( function() time = time + 1 local conf = pewpew.get_player_configuration(0) if conf["has_lost"] == true then pewpew.stop_game() end if time > 150 and time < 1150 and time % 295 == 0 then pewpew.new_wary(random_position()) end if time > 1150 and time < 2150 and time % 245 == 0 then pewpew.new_wary(random_position()) end if time > 2150 and time % 225 == 0 then pewpew.new_wary(random_position()) end if time > 250 and time < 1250 and time % 470 == 0 then pewpew.new_asteroid(random_position()) end if time > 1250 and time < 2250 and time % 425 == 0 then pewpew.new_asteroid(random_position()) end if time > 2250 and time % 380 == 0 then pewpew.new_asteroid(random_position()) end if time > 450 and time % 700 == 0 then pewpew.new_rolling_sphere(fmath.random_fixedpoint(25fx,725fx),fmath.random_fixedpoint(25fx,100fx), fmath.random_fixedpoint(0fx,fmath.tau()), 3fx) pewpew.new_rolling_sphere(fmath.random_fixedpoint(25fx,725fx),fmath.random_fixedpoint(900fx,975fx), fmath.random_fixedpoint(0fx,fmath.tau()), 3fx) end if time > 300 and time < 1300 and time % 400 == 0 then pewpew.new_mothership(rx, ry, pewpew.MothershipType.FIVE_CORNERS, fmath.random_fixedpoint(0fx,fmath.tau())) end if time > 1300 and time < 2300 and time % 355 == 0 then pewpew.new_mothership(rx, ry, pewpew.MothershipType.FIVE_CORNERS, fmath.random_fixedpoint(0fx,fmath.tau())) end if time > 2300 and time % 305 == 0 then pewpew.new_mothership(rx, ry, pewpew.MothershipType.FIVE_CORNERS, fmath.random_fixedpoint(0fx,fmath.tau())) end if time > 300 and time < 1700 % 650 == 0 then pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(1fx, 999fx) pewpew.new_crowder(1fx, 999fx) end if time > 1700 and time < 3100 and time % 645 == 0 then pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(1fx, 999fx) pewpew.new_crowder(1fx, 999fx) pewpew.new_crowder(1fx, 999fx) end if time > 3100 and time % 645 == 0 then pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(1fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 1fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(749fx, 999fx) pewpew.new_crowder(1fx, 999fx) pewpew.new_crowder(1fx, 999fx) pewpew.new_crowder(1fx, 999fx) pewpew.new_crowder(1fx, 999fx) end if time > 200 and time % 600 == 0 then shield_box.new(375fx, 500fx, weapon_config) end if time > 650 and time % 1200 == 0 then cannon_box.new(fmath.random_fixedpoint(10fx, 740fx), fmath.random_fixedpoint(10fx, 990fx), fmath.random_int(3, 3)) end if time > 600 and time % 675 == 0 then -- arguments (in order): x, y, expiration (in ticks), ship id, callback function blindness_boxes.create_box(fmath.random_fixedpoint(10fx, 740fx), fmath.random_fixedpoint(10fx, 990fx), 350, player, function(player_index, ship_id) pewpew.configure_player(player_index, {camera_distance = 300fx}) -- arguments (in order): duration of powerup, callback function set.timeout(200, function() pewpew.configure_player(player_index, {camera_distance = 650fx}) end) end) end if time % 30 == 0 then local x, y = pewpew.entity_get_position(player) pewpew.print(x .. " , " .. y) end end)
local TCP = require('tcp') local Request = require('request') local Response = require('response') local HTTP_Parser = require('http_parser') local HTTP = {} function HTTP.create_server(host, port, on_connection) local server = TCP.new() server:bind(host, port) server:listen(function (err) if err then return server:emit("error", err) end -- Accept the client and build request and response objects local client = TCP.new() server:accept(client) client:read_start() local request = Request.new(client) local response = Response.new(client) -- Convert TCP stream to HTTP stream local current_field local parser local headers parser = HTTP_Parser.new("request", { on_message_begin = function () headers = {} request.headers = headers end, on_url = function (url) request.url = url end, on_header_field = function (field) current_field = field end, on_header_value = function (value) headers[current_field:lower()] = value end, on_headers_complete = function (info) request.method = info.method request.upgrade = info.upgrade request.version_major = info.version_major request.version_minor = info.version_minor -- Give upgrade requests access to the raw client if they want it if info.upgrade then request.client = client end -- Handle 100-continue requests if request.headers.expect and info.version_major == 1 and info.version_minor == 1 and request.headers.expect:lower() == "100-continue" then if server.handlers and server.handlers.check_continue then server:emit("check_continue", request, response) else response:write_continue() on_connection(request, response) end else on_connection(request, response) end -- We're done with the parser once we hit an upgrade if request.upgrade then parser:finish() end end, on_body = function (chunk) request:emit('data', chunk, #chunk) end, on_message_complete = function () request:emit('end') end }) client:on("data", function (chunk, len) -- Ignore empty chunks if len == 0 then return end -- Once we're in "upgrade" mode, the protocol is no longer HTTP and we -- shouldn't send data to the HTTP parser if request.upgrade then request:emit("data", chunk, len) return end -- Parse the chunk of HTTP, this will syncronously emit several of the -- above events and return how many bytes were parsed. local nparsed = parser:execute(chunk, 0, len) -- If it wasn't all parsed then there was an error parsing if nparsed < len then -- If the error was caused by non-http protocol like in websockets -- then that's ok, just emit the rest directly to the request object if request.upgrade then len = len - nparsed chunk = chunk:sub(nparsed + 1) request:emit("data", chunk, len) else request:emit("error", "parse error") end end end) client:on("end", function () parser:finish() end) end) return server end return HTTP
-- ============================================================= -- Copyright Roaming Gamer, LLC. 2009-2015 -- ============================================================= -- License -- ============================================================= --[[ > SSK is free to use. > SSK is free to edit. > SSK is free to use in a free or commercial game. > SSK is free to use in a free or commercial non-game app. > SSK is free to use without crediting the author (credits are still appreciated). > SSK is free to use without crediting the project (credits are still appreciated). > SSK is NOT free to sell for anything. > SSK is NOT free to credit yourself with. ]] -- ============================================================= _G.lrequire = function( path ) local mod return setmetatable({}, { __index = function(_, k) mod = mod or require(path) return mod[k] end }) end
--this is included server side by the loader if the map is md_yard --return a function for wave generation, if nil is returned it will default to what is in the config
local FlagStandManager = {} -- ROBLOX Services local Players = game.Players -- Game Services local Configurations = require(game.ServerStorage.Configurations) -- Local Variables local FlagObjects = {} local FlagCarriers = {} local Events = game.ReplicatedStorage.Events local CaptureFlag = Events.CaptureFlag local ReturnFlag = Events.ReturnFlag -- Local Functions local MakeFlag local function DestroyFlag(flagObject) flagObject.Flag:Destroy() for player, object in pairs(FlagCarriers) do if object == flagObject then FlagCarriers[player] = nil end end end local function OnCarrierDied(player) local flagObject = FlagCarriers[player] if flagObject then local flagPole = flagObject.FlagPole local flagBanner = flagObject.FlagBanner flagPole.CanCollide = false flagBanner.CanCollide = false flagPole.Anchored = true flagBanner.Anchored = true flagObject.PickedUp = false FlagCarriers[player] = nil if Configurations.RETURN_FLAG_ON_DROP then wait(Configurations.FLAG_RESPAWN_TIME) if not flagObject.AtSpawn and not flagObject.PickedUp then DestroyFlag(flagObject) MakeFlag(flagObject) ReturnFlag:Fire(flagObject.FlagBanner.BrickColor) end end end end local function PickupFlag(player, flagObject) FlagCarriers[player] = flagObject flagObject.AtSpawn = false flagObject.PickedUp = true local torso if player.Character.Humanoid.RigType == Enum.HumanoidRigType.R6 then torso = player.Character:FindFirstChild('Torso') else torso = player.Character:FindFirstChild('UpperTorso') end local flagPole = flagObject.FlagPole local flagBanner = flagObject.FlagBanner flagPole.Anchored = false flagBanner.Anchored = false flagPole.CanCollide = false flagBanner.CanCollide = false local weld = Instance.new('Weld', flagPole) weld.Name = 'PlayerFlagWeld' weld.Part0 = flagPole weld.Part1 = torso weld.C0 = CFrame.new(0,0,-1) end local function BindFlagTouched(flagObject) local flagPole = flagObject.FlagPole local flagBanner = flagObject.FlagBanner flagPole.Touched:connect(function(otherPart) local player = Players:GetPlayerFromCharacter(otherPart.Parent) if not player then return end if not player.Character then return end local humanoid = player.Character:FindFirstChild('Humanoid') if not humanoid then return end if humanoid.Health <= 0 then return end if flagBanner.BrickColor ~= player.TeamColor and not flagObject.PickedUp then PickupFlag(player, flagObject) elseif flagBanner.BrickColor == player.TeamColor and not flagObject.AtSpawn and Configurations.FLAG_RETURN_ON_TOUCH then DestroyFlag(flagObject) MakeFlag(flagObject) ReturnFlag:Fire(flagObject.FlagBanner.BrickColor) end end) end function MakeFlag(flagObject) flagObject.Flag = flagObject.FlagCopy:Clone() flagObject.Flag.Parent = flagObject.FlagContainer flagObject.FlagPole = flagObject.Flag.FlagPole flagObject.FlagBanner = flagObject.Flag.FlagBanner flagObject.FlagBanner.CanCollide = false flagObject.AtSpawn = true flagObject.PickedUp = false BindFlagTouched(flagObject) end local function BindBaseTouched(flagObject) local flagBase = flagObject.FlagBase flagBase.Touched:connect(function(otherPart) local player = Players:GetPlayerFromCharacter(otherPart.Parent) if not player then return end if flagBase.BrickColor == player.TeamColor and FlagCarriers[player] then CaptureFlag:Fire(player) local otherFlag = FlagCarriers[player] DestroyFlag(otherFlag) MakeFlag(otherFlag) end end) end local function OnPlayerAdded(player) player.CharacterAdded:connect(function(character) character:WaitForChild('Humanoid').Died:connect(function() OnCarrierDied(player) end) end) player.CharacterRemoving:connect(function() OnCarrierDied(player) end) end -- Public Functions function FlagStandManager:Init(container) local flagObject = {} local success, message = pcall(function() flagObject.AtSpawn = true flagObject.PickedUp = false flagObject.TeamColor = container.FlagStand.BrickColor flagObject.Flag = container.Flag flagObject.FlagPole = container.Flag.FlagPole flagObject.FlagBanner = container.Flag.FlagBanner flagObject.FlagBase = container.FlagStand flagObject.FlagCopy = container.Flag:Clone() flagObject.FlagContainer = container end) if not success then warn("Flag object not built correctly. Please load fresh template to see how flag stand is expected to be made.") end BindBaseTouched(flagObject) DestroyFlag(flagObject) MakeFlag(flagObject) table.insert(FlagObjects, flagObject) end -- Event Bindings Players.PlayerAdded:connect(OnPlayerAdded) return FlagStandManager
local F = require("F") local u = "Hello" local function f() local w = "World" return function() local gobo = "GOBO" print(u .. " " .. w) print(F"{u} {w} of {gobo}") end end f()()
instrument { name = "RSI", icon="indicators:RSI" } input_group { "RSI", period = input (14, "front.period", input.integer, 1), source = input (1, "front.ind.source", input.string_selection, inputs.titles), fn = input (averages.ssma, "front.newind.average", input.string_selection, averages.titles), color = input { default = "#B42EFF", type = input.color }, width = input { default = 1, type = input.line_width} } input_group { "front.newind.supportlines", overbought = input (70, "front.overbought", input.double, 1, 100, 1, false), oversold = input (30, "front.oversold", input.double, 1, 100, 1, false), overbought_color = input { default = rgba(37,225,84,0.50), type = input.color }, oversold_color = input { default = rgba(255,108,88,0.50), type = input.color }, bg_color = input { default = rgba(255,255,255,0.05), type = input.color }, support_width = input { default = 1, type = input.line_width} } local sourceSeries = inputs [source] local averageFunction = averages [fn] delta = sourceSeries - sourceSeries [1] up = averageFunction (max (delta, 0), period) down = averageFunction (max (-delta, 0), period) rs = up / down res = 100 - 100 / (1 + rs) fill_area (overbought, oversold, "", bg_color) plot (res, "RSI", color, width) hline { value = overbought, color = overbought_color, width = support_width, style = style.dash_line } hline { value = oversold, color = oversold_color, width = support_width, style = style.dash_line } hline { value = 90, color = rgba(255,255,255,0), show_label = false } hline { value = 10, color = rgba(255,255,255,0), show_label = false }
--[[ Copyright (C) 2018 Google Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] -- Demonstration of modifying a texture in multiple ways. -- In the level there should be a blue picture on the wall. local game = require 'dmlab.system.game' local make_map = require 'common.make_map' local tensor = require 'dmlab.system.tensor' local api = {} function api:start(episode, seed) make_map.seedRng(1) api._count = 0 end function api:nextMap() if api._map then return api._map end api._map = make_map.makeMap{ mapName = 'demo_rectangle', mapEntityLayer = 'P ', useSkybox = true, } return api._map end local TEXTURE_NAME = 'textures/decal/lab_games/dec_img_style02_013' function api:replaceTextureName(textureName) if textureName == TEXTURE_NAME then textureName = textureName .. '%01' end return textureName end function api:loadTexture(textureName) if textureName == TEXTURE_NAME .. '%01' then return tensor.ByteTensor(8, 8, 4):fill(255) end end local colourIndex = 0 local columnIndex = 0 local function changeTexture(textureData) for i = 0, 2 do local c = (math.floor(colourIndex) == i) and 255 or 0 textureData:select(3, i + 1):fill(c) end textureData:select(2, math.floor(columnIndex) + 1):fill(255) colourIndex = (colourIndex + 0.01) % 3 columnIndex = (columnIndex + 0.01) % 8 end function api:modifyTexture(textureName, tensorData) if textureName == TEXTURE_NAME then assert(tensorData == tensor.ByteTensor(8, 8, 4):fill(255)) -- Make texture red. changeTexture(tensorData) return true end return false end local textureData = tensor.ByteTensor(8, 8, 4):fill(255) function api:modifyControl(actions) if actions.crouchJump > 0 then actions.crouchJump = 0 changeTexture(textureData) game:updateTexture(TEXTURE_NAME, textureData) end return actions end return api
local currentCell local collisionShapes = {} local drawCollisions = true AddRemoteEvent("mogzones:update_collision_shapes", function(receivedCollisionShapes) collisionShapes = json_decode(receivedCollisionShapes) end) AddRemoteEvent("mogzones:update_current_cell", function(cellData) currentCell = json_decode(cellData) end) AddRemoteEvent("mogzones:update_draw_collisions", function(status) drawCollisions = status end) AddEvent("OnRenderHUD", function () if not drawCollisions then return end if currentCell then SetDrawColor(RGB(0, 255, 0)) DrawLine3D(currentCell.x, currentCell.y, 0, currentCell.x, currentCell.y, 100000, 5) DrawLine3D(currentCell.x + currentCell.width, currentCell.y, 0, currentCell.x + currentCell.width, currentCell.y, 100000, 5) DrawLine3D(currentCell.x, currentCell.y + currentCell.height, 0, currentCell.x, currentCell.y + currentCell.height, 100000, 5) DrawLine3D(currentCell.x + currentCell.width, currentCell.y + currentCell.height, 0, currentCell.x, currentCell.y, 100000, 5) end SetDrawColor(RGB(255, 0, 0)) for key,shape in pairs(collisionShapes) do for i = 1,10 do if shape.type == 'circle' then DrawLine3D(shape.x, shape.y, 0, shape.x, shape.y, 100000, 5) DrawLine3D(shape.x - shape.radius, shape.y - shape.radius, 0, shape.x - shape.radius, shape.y - shape.radius, 100000, 5) DrawLine3D(shape.x - shape.radius, shape.y + shape.radius, 0, shape.x - shape.radius, shape.y + shape.radius, 100000, 5) DrawLine3D(shape.x + shape.radius, shape.y - shape.radius, 0, shape.x + shape.radius, shape.y - shape.radius, 100000, 5) DrawLine3D(shape.x + shape.radius, shape.y + shape.radius, 0, shape.x + shape.radius, shape.y + shape.radius, 100000, 5) elseif shape.type == 'polygon' then if #shape.vertices > 0 then local lastVertex for _, vertex in pairs(shape.vertices) do if lastVertex then DrawLine3D(vertex.x, vertex.y, 1000 + i * 100, lastVertex.x, lastVertex.y, 1000 + i * 100, 5) end lastVertex = vertex end DrawLine3D(lastVertex.x, lastVertex.y, 1000 + i * 100, shape.vertices[1].x, shape.vertices[1].y, 1000 + i * 100, 5) end end end end end)
--mobs_fallout v0.0.4 --maikerumine --made for Extreme Survival game --dofile(minetest.get_modpath("mobs_fallout").."/api.lua") --REFERENCE --function (mod_name_here):spawn_specific(name, nodes, neighbors, min_light, max_light, interval, chance, active_object_count, min_height, max_height) mobs:register_spawn("mobs_fallout:Bajan", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -20) mobs:register_mob("mobs_fallout:Bajan", { type = "monster", group_attack = true, pathfinding = true, hp_min = 35, hp_max = 75, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Bajancanadian_by_bajanhgk.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 3, damage = 3, drops = { {name = "default:jungletree", chance = 1, min = 0, max = 2,}, {name = "shooter:pistol", chance = 2, min = 0, max = 1,}, {name = "shooter:ammo", chance = 2, min = 0, max=3,}, }, armor = 100, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Calinou", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Calinou", { type = "monster", group_attack = true, pathfinding = true, hp_min = 49, hp_max = 83, collisionbox = {-0.3, -0.6, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Calinou_by_Calinou.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1.2, y=.7}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 2, damage = 3, drops = { {name = "default:duct_tape", chance = 7, min = 0, max = 5,}, {name = "shooter:pistol", chance = 1, min = 0, max = 1,}, {name = "default:apple", chance = 1, min = 1, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell2", death = "mobs_howl", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Castaway", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Castaway", { type = "monster", group_attack = true, pathfinding = true, hp_min = 37, hp_max = 82, collisionbox = {-0.3, -1.3, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Castaway_by_Gold.png", "3d_armor_trans.png", minetest.registered_items["shooter:rifle"].inventory_image, }}, visual_size = {x=1.2, y=1.3}, makes_footstep_sound = true, view_range = 19, walk_velocity = 1, run_velocity = 3, damage = 3, drops = { {name = "default:duct_tape", chance = 2, min =0, max = 1,}, {name = "shooter:rifle", chance = 4, min = 0, max = 1,}, {name = "default:steel_ingot", chance = 2, min = 1, max=3,}, }, armor = 100, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_rifle", }, }) mobs:register_spawn("mobs_fallout:cx384", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -100) mobs:register_mob("mobs_fallout:cx384", { type = "monster", group_attack = true, pathfinding = true, hp_min = 130, hp_max = 140, collisionbox = {-0.3, -0.8, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"cx384_by_cx3884.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=.9, y=.8}, makes_footstep_sound = true, view_range = 20, walk_velocity = 3, run_velocity = 4, damage = 3, drops = { {name = "shooter:pistol", chance = 3, min = 0, max = 1,}, {name = "default:gold_ingot", chance = 3, min = 0, max = 1,}, {name = "default:glue", chance = 2, min = 1, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:FloatingWraith", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:FloatingWraith", { type = "monster", group_attack = true, pathfinding = true, hp_min = 37, hp_max = 70, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"FloatingWraith_by_Skel_originalby_lovehart.png", "3d_armor_trans.png", minetest.registered_items["shooter:shotgun"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1.2, run_velocity = 3, damage = 3, drops = { {name = "shooter:shotgun", chance = 2, min = 0, max = 1,}, {name = "default:bronze_ingot", chance = 3, min = 0, max = 5,}, {name = "default:health_kit", chance = 1, min = 1, max=2,}, }, armor = 85, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_yeti_death", attack = "shooter_shotgun", }, }) mobs:register_spawn("mobs_fallout:Ghost", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -250) mobs:register_mob("mobs_fallout:Ghost", { type = "monster", group_attack = true, pathfinding = true, hp_min = 157, hp_max = 195, collisionbox = {-0.3, -0.8, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Ghost_by_sazonovpavlik73-nickli.png", "3d_armor_trans.png", minetest.registered_items["shooter:shotgun"].inventory_image, }}, visual_size = {x=0.6, y=0.8}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 1.5, damage = 3, drops = { {name = "default:duct_tape", chance = 1, min = 3, max = 33,}, {name = "shooter:grenade", chance = 2, min = 0, max = 1,}, {name = "default:ice", chance = 2, min = 13, max=30,}, }, armor = 100, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_barbarian_death", attack = "shooter_shotgun", }, }) mobs:register_spawn("mobs_fallout:Zombie_Rex", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -300) mobs:register_mob("mobs_fallout:Zombie_Rex", { type = "monster", group_attack = true, pathfinding = true, hp_min = 177, hp_max = 190, collisionbox = {-0.3, -0.8, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:shotgun"].inventory_image, }}, visual_size = {x=.9, y=.8}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 3, damage = 3, drops = { {name = "shooter:shotgun", chance = 2, min = 0, max = 1,}, {name = "default:stone_with_diamond", chance = 6, min = 0, max = 3,}, {name = "default:apple", chance = 1, min = 1, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_barbarian_death", attack = "shooter_shotgun", }, }) mobs:register_spawn("mobs_fallout:Lovehart", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -430) mobs:register_mob("mobs_fallout:Lovehart", { type = "monster", group_attack = true, pathfinding = true, hp_min = 157, hp_max = 200, collisionbox = {-0.3, -1.5, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"herobrines_blody_gost_by_lovehart.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1.3, y=1.5}, makes_footstep_sound = true, view_range = 10, walk_velocity = 4, run_velocity =15, damage = 4, drops = { {name = "default:cotton", chance = 1, min = 3, max = 5,}, {name = "shooter:pistol", chance = 3, min = 0, max = 1,}, {name = "shooter:pistol", chance = 2, min = 0, max=1,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_fireball", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Minetestian", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 100) mobs:register_mob("mobs_fallout:Minetestian", { type = "monster", group_attack = true, pathfinding = true, hp_min = 49, hp_max = 85, collisionbox = {-0.3, -1.3, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Hobo8Homeless_person_by_Minetestian.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1.3}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 2, damage = 3, drops = { {name = "default:sapling", chance = 1, min = 3, max = 5,}, {name = "shooter:pistol", chance = 6, min = 0, max = 1,}, {name = "default:glue", chance = 2, min = 13, max=30,}, }, armor = 100, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Andromeda", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Andromeda", { type = "monster", group_attack = true, pathfinding = true, hp_min = 57, hp_max = 85, collisionbox = {-0.3, -0.5, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Hunky_Simon_with_Jacket_by_Andromeda.png", "3d_armor_trans.png", minetest.registered_items["shooter:grenade"].inventory_image, }}, visual_size = {x=1, y=.5}, makes_footstep_sound = true, view_range = 25, walk_velocity = 0.3, run_velocity = 1.5, damage = 3, drops = { {name = "default:grass_1", chance = 1, min = 3, max = 5,}, {name = "default:bokken", chance = 2, min = 1, max = 1,}, {name = "default:sand", chance = 2, min = 13, max=30,}, }, armor = 100, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_throw", }, }) mobs:register_spawn("mobs_fallout:Phil", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Phil", { type = "monster", group_attack = true, pathfinding = true, hp_min = 47, hp_max = 85, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Infantry_man_by_philipbenr.png", "3d_armor_trans.png", minetest.registered_items["shooter:crossbow_loaded"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 1.4, damage = 3, drops = { {name = "default:pick_wood", chance = 1, min = 0, max = 1,}, {name = "default:duct_tape", chance = 1, min = 1, max = 1,}, {name = "shooter:ammo", chance = 2, min = 1, max=5,}, }, armor = 90, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_click", }, }) mobs:register_spawn("mobs_fallout:IvanbotXD", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:IvanbotXD", { type = "monster", group_attack = true, pathfinding = true, hp_min = 48, hp_max = 77, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"ivanbotXD_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:rifle"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 2, damage = 3, drops = { {name = "default:pick_stone", chance = 1, min = 1, max = 3,}, {name = "default:club_stone", chance = 5, min = 0, max = 1,}, {name = "default:stone_with_gold", chance = 2, min = 4, max=8,}, }, armor = 90, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_eerie", death = "mobs_yeti_death", attack = "shooter_rifle", }, }) mobs:register_spawn("mobs_fallout:Orc", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Orc", { type = "monster", group_attack = true, pathfinding = true, hp_min = 77, hp_max = 90, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"orc_from_lottmob_by_lovehart.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 3, run_velocity = 3, damage = 4, drops = { {name = "default:chest", chance = 1, min = 0, max = 1,}, {name = "shooter:pistol", chance = 1, min = 0, max = 1,}, {name = "default:book", chance = 4, min = 1, max=30,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_death2", attack = "shooter_pistol", }, attacks_monsters = true, peaceful = true, group_attack = true, step = 1, }) mobs:register_spawn("mobs_fallout:Luke", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -150) mobs:register_mob("mobs_fallout:Luke", { type = "monster", group_attack = true, pathfinding = true, hp_min = 127, hp_max = 152, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"RockerLuke_skin_by_RockerLuke.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 7, walk_velocity = 1.3, run_velocity = 3.5, damage = 3, drops = { {name = "default:steelblock", chance = 3, min = 0, max = 2,}, {name = "shooter:pistol", chance = 1, min = 0, max = 1,}, {name = "default:bronze_ingot", chance = 2, min = 1, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Seth_Rollins", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -400) mobs:register_mob("mobs_fallout:Seth_Rollins", { type = "monster", group_attack = true, pathfinding = true, hp_min = 137, hp_max = 159, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"Seth_Rollins_by_Ferdi_Napoli.png", "3d_armor_trans.png", minetest.registered_items["default:goldblock"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1.5, run_velocity = 3, damage = 2.5, drops = { {name = "default:goldblock", chance = 6, min = 1, max = 4,}, {name = "shooter:pistol", chance = 1, min = 0, max = 1,}, {name = "shooter:ammo", chance = 2, min = 0, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell2", death = "mobs_barbarian_death", attack = "shooter_flare_burn", }, }) mobs:register_spawn("mobs_fallout:Sgt_Prf", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -120) mobs:register_mob("mobs_fallout:Sgt_Prf", { type = "monster", group_attack = true, pathfinding = true, hp_min = 100, hp_max = 120, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"SgtPrf_by_Prf.png", "3d_armor_trans.png", minetest.registered_items["shooter:rifle"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 12, walk_velocity = 2, run_velocity = 3, damage = 5, drops = { {name = "shooter:rifle", chance = 2, min = 0, max = 1,}, {name = "shooter:shotgun", chance = 1, min = 0, max = 2,}, {name = "default:apple", chance = 2, min = 1, max=5,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "shooter_rifle", }, }) mobs:register_spawn("mobs_fallout:Willy_Rex", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Willy_Rex", { type = "monster", group_attack = true, pathfinding = true, hp_min = 73, hp_max = 80, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"thewillyrex_by_edwar_masterchieft.png", "3d_armor_trans.png", minetest.registered_items["default:axe_steel"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 2, damage = 3, drops = { {name = "default:axe_steel", chance = 1, min = 0, max = 2,}, {name = "farming:seed_cotton", chance = 1, min = 0, max = 1,}, {name = "shooter:ammo", chance = 2, min = 1, max=3,}, }, armor = 90, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_barbarian_yell1", death = "mobs_barbarian_death", attack = "mobs_slash_attack", }, }) mobs:register_spawn("mobs_fallout:Zombie_Drogado_A", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Zombie_Drogado_A", { type = "monster", group_attack = true, pathfinding = true, hp_min = 99, hp_max = 140, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:shotgun"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 10, walk_velocity = 2, run_velocity = 4, damage = 6, drops = { {name = "shooter:pistol", chance = 1, min = 0, max = 1,}, {name = "default:apple", chance = 1, min = 1, max = 7,}, {name = "shooter:ammo", chance = 1, min = 1, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_barbarian_death", attack = "shooter_shotgun", }, }) mobs:register_spawn("mobs_fallout:Zombie_Drogado_B", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Zombie_Drogado_B", { type = "monster", group_attack = true, pathfinding = true, hp_min = 77, hp_max = 90, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 25, walk_velocity = 0.5, run_velocity = 1.5, damage = 3, drops = { {name = "default:obsidian", chance = 2, min = 0, max = 2,}, {name = "shooter:pistol", chance = 1, min = 0, max = 1,}, {name = "default:apple", chance = 2, min = 1, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_barbarian_death", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Zombie_Drogado_C", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -50) mobs:register_mob("mobs_fallout:Zombie_Drogado_C", { type = "monster", group_attack = true, pathfinding = true, hp_min = 69, hp_max = 89, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:shotgun"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, run_velocity = 2, damage = 3, drops = { {name = "default:club_stone", chance = 1, min = 0, max = 2,}, {name = "default:glue", chance = 3, min = 0, max = 1,}, {name = "default:apple", chance = 2, min = 1, max=9,}, }, armor = 100, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_yeti_death", attack = "shooter_shotgun", }, }) mobs:register_spawn("mobs_fallout:Zombie_Drogado_D", {"default:dirt_with_grass","default:stone", "default:stonebrick","default:cobble","default:stone", "default:dry_dirt", "default:snow","default:dirt_with_dry_grass"}, 5, -1, 6000, 1, -50) mobs:register_mob("mobs_fallout:Zombie_Drogado_D", { type = "monster", group_attack = true, pathfinding = true, hp_min = 137, hp_max = 150, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 5, walk_velocity = 1, run_velocity = 5, damage = 4, drops = { {name = "default:diamondblock", chance = 4, min = 1, max = 3,}, {name = "shooter:pistol", chance = 2, min = 0, max = 1,}, {name = "default:apple", chance = 2, min = 2, max=7,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_howl", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Zombie_Drogado_E", {"default:dirt_with_grass","default:stone","meru:stone", "default:stonebrick","default:cobble"}, 5, -1, 6000, 1, 31000) mobs:register_mob("mobs_fallout:Zombie_Drogado_E", { type = "monster", group_attack = true, pathfinding = true, hp_min = 77, hp_max = 130, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 5, walk_velocity = 1, run_velocity = 5, damage = 4, drops = { {name = "default:cactus", chance = 5, min = 0, max = 3,}, {name = "shooter:pistol", chance = 2, min = 1, max = 1,}, {name = "default:dirt", chance = 2, min = 6, max=23,}, }, armor = 80, drawtype = "front", water_damage = 0, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_howl", attack = "shooter_pistol", }, }) mobs:register_spawn("mobs_fallout:Zombie_Drogado_F", {"default:sandstone","default:stone", "default:stonebrick","default:cobble","default:dirt"}, 9, -1, 6000, 1, -20) mobs:register_mob("mobs_fallout:Zombie_Drogado_F", { type = "monster", group_attack = true, pathfinding = true, hp_min = 35, hp_max = 75, collisionbox = {-0.3, -1.0, -0.3, 0.3, 0.8, 0.3}, visual = "mesh", mesh = "3d_armor_character.b3d", textures = {{"zombie_drogado_by_rexyGYM.png", "3d_armor_trans.png", minetest.registered_items["shooter:pistol"].inventory_image, }}, visual_size = {x=1, y=1}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1.9, run_velocity = 3.8, damage = 4, drops = { {name = "default:jungletree", chance = 1, min = 0, max = 2,}, {name = "shooter:pistol", chance = 2, min = 0, max = 1,}, {name = "shooter:ammo", chance = 2, min = 0, max=3,}, }, armor = 80, drawtype = "front", water_damage = 10, lava_damage = 50, light_damage = 1, on_rightclick = nil, attack_type = "dogfight", animation = { speed_normal = 30, speed_run = 30, stand_start = 0, stand_end = 79, walk_start = 168, walk_end = 187, run_start = 168, run_end = 187, punch_start = 200, punch_end = 219, }, sounds = { war_cry = "mobs_stonemonster", death = "mobs_barbarian_death", attack = "shooter_pistol", }, })
local AddonName, AddonTable = ... -- MoP Transmog AddonTable.transmog = { 81972, 81979, 82014, 82021, 82027, 82029, 82036, 82061, 82069, 82070, 82073, 82076, 82089, 82095, 82097, 82099, 82148, 82184, 82192, 82193, 82196, 82197, 82198, 82199, 82200, 82204, 82209, 82212, 82220, 82221, 82222, 82223, 82224, 82226, 82227, 82229, 82230, 82231, 82236, 82237, 82240, 82241, 82242, 82243, 82244, 82245, 82246, 82247, 82248, 82249, 82250, 82251, 82252, 82253, 82254, 82255, 82256, 82257, 82258, 82259, 82260, 82261, 82262, 82263, 82264, 82265, 82266, 82267, 82268, 82269, 82270, 82271, 82272, 82274, 82275, 82276, 82277, 82278, 82279, 82281, 82282, 82284, 82285, 82286, 82287, 82288, 82289, 82290, 82291, 82292, 82293, 82294, 82295, 86849, 87419, 87451, 87501, 87650, 90574, 94031, 94067, }
PLUGIN.name = "Quiz" PLUGIN.author = "Qemist & AleXXX_007 (NS 1.1)" PLUGIN.desc = "A quiz which will be shown the first time a player joins your server which they will have to answer correctly to gain access to the server." PLUGIN.players = {} nut.util.Include("sh_config.lua") nut.util.Include("sh_lang.lua") nut.util.Include("cl_quiz.lua") function PLUGIN:PlayerInitialSpawn(client) timer.Simple(5,function() local passed = client:getNutData("passedQuiz", false) if passed == nil then passed = false end if (!passed) then netstream.Start(client, "nut_Quiz") end end) end netstream.Hook("nut_QuizResult", function(client, result) if (result == true) then client:setNutData("passedQuiz", true) netstream.Start(client, "nut_Char") else client:Kick(nut.config.quiz.kickMessage) end end)
local bencode = require 'bencode' local encode = bencode.encode local uwrite = uart.write -- SENDING ---------------------------------------------------- local function send_message (spid, opcode, data) local s, err = encode({spid, opcode, data}) uwrite (0, s) end ---------------------------------------------------- -- POLLING ---------------------------------------------------- local poll_callbacks = {} local MAX_POLL_CALLBACKS = 1024 local function register_poll_callback(cb) if #poll_callbacks >= MAX_POLL_CALLBACKS then return -1 end poll_callbacks[#poll_callbacks+1] = cb return #poll_callbacks end local function unregister_poll_callback(n) if n<#poll_callbacks then poll_callbacks[n] = poll_callbacks[#poll_callbacks] end poll_callbacks[#poll_callbacks]=nil end local function call_poll_callbacks(n) for i = 1, #poll_callbacks do poll_callbacks[i]() end end ---------------------------------------------------- -- OPCODES ---------------------------------------------------- local opcode_callbacks = { [0] = { -- admin [0] = function() end, [1] = function(data) send_message(0, 1, data) end, } } local function register_opcode_callbacks(cbs) opcode_callbacks[#opcode_callbacks+1] = cbs return #opcode_callbacks --pid end local function unregister_opcode_callbacks(pid) opcode_callbacks[pid]=false end ---------------------------------------------------- return { -- polling tick = call_poll_callbacks, register_poll_callback = register_poll_callback, unregister_poll_callback = unregister_poll_callback, -- opcode opcode_callbacks = opcode_callbacks, register_opcode_callbacks = register_opcode_callbacks, unregister_opcode_callbacks = unregister_opcode_callbacks, -- sending send_message = send_message, }
local Command = VH_CommandLib.Command:new("Return", VH_CommandLib.UserTypes.Admin, "Return the player to last teleport position.", "") Command:addArg(VH_CommandLib.ArgTypes.Plr, {required = true}) Command:addAlias({Prefix = "!", Alias = "return"}) Command.Callback = function(Sender, Alias, Target) Target:PLForceTeleport(Target:PLGetLastPos()) VH_CommandLib.SendCommandMessage(Sender, "returned", {Target}, "to their last position") return "" end
function Server_Created(game, settings) settings.Commanders = false; end
local Namespace = require('vgit.core.Namespace') local Buffer = require('vgit.core.Buffer') local Window = require('vgit.core.Window') local console = require('vgit.core.console') local live_blame_setting = require('vgit.settings.live_blame') local loop = require('vgit.core.loop') local Feature = require('vgit.Feature') local LiveBlame = Feature:extend() function LiveBlame:new(git_store) return setmetatable({ id = 1, git_store = git_store, last_lnum = nil, namespace = Namespace:new(), }, LiveBlame) end function LiveBlame:display(lnum, buffer, config, blame) loop.await_fast_event() if buffer:is_valid() then local virt_text = live_blame_setting:get('format')(blame, config) if type(virt_text) == 'string' then loop.await_fast_event() self.namespace:transpose_virtual_text( buffer, virt_text, 'GitComment', lnum - 1, 0, 'eol' ) end end end function LiveBlame:hide(buffer) loop.await_fast_event() if buffer:is_valid() then self.namespace:clear(buffer) end end LiveBlame.sync = loop.brakecheck(loop.async(function(self) loop.await_fast_event() local window = Window:new(0) loop.await_fast_event() local buffer = self.git_store:current() if not buffer then return end loop.await_fast_event() if buffer:editing() then console.debug( string.format('Buffer %s is being edited right now', buffer.bufnr) ) return end loop.await_fast_event() if not self:is_buffer_valid(buffer) then return end loop.await_fast_event() if not self:is_buffer_tracked(buffer) then return end loop.await_fast_event() local lnum = window:get_lnum() if self.last_lnum and self.last_lnum == lnum then return end loop.await_fast_event() local blame_err, blame = buffer.git_object:blame_line(lnum) loop.await_fast_event() if not buffer:is_valid() then console.debug( 'Buffer on which blame was live blame was being synced is no longer valid' ) end loop.await_fast_event() if not window:is_valid() then console.debug( 'Window on which blame was live blame was being synced is no longer valid' ) return end loop.await_fast_event() local new_lnum = window:get_lnum() if lnum ~= new_lnum then console.debug( string.format( 'Suspending blame computation for %s user is currently on %s and not in %s', buffer.bufnr, new_lnum, lnum ) ) return end if blame_err then console.debug(blame_err, debug.traceback()) return end loop.await_fast_event() local config_err, config = buffer.git_object:config() if config_err then console.debug(config_err, debug.traceback()) return end if not buffer then return end self:hide(buffer) self:display(lnum, buffer, config, blame) self.last_lnum = lnum end)) function LiveBlame:desync(force) loop.await_fast_event() local window = Window:new(0) local buffer = self.git_store:current() if not buffer then return end loop.await_fast_event() buffer = self.git_store:get(buffer) loop.await_fast_event() local lnum = window:get_lnum() if not force and self.last_lnum and self.last_lnum == lnum then return end if not buffer then return end self:hide(buffer) end function LiveBlame:desync_all() local buffers = Buffer:list() for i = 1, #buffers do local buffer = buffers[i] if buffer then self:hide(buffer) end end end return LiveBlame
local S = aurum.get_translator() aurum.magic.register_spell("air_blast", { description = S"Air Blast", longdesc = S"Blasts air against whatever node the user is pointing at, sending the user flying backward.", max_level = 2, rod = function(level) return "aurum_magic:air_blast_rod_" .. level end, apply_requirements = function(thing) return thing.type == "node" end, apply = function(_, level, player) (aurum.wings.flying(player) or player):add_velocity(vector.multiply(player:get_look_dir(), -(5 + level * 2))) end, }) for i=1,3 do aurum.rods.register("aurum_magic:air_blast_rod_" .. i, { range = 5 + i * 2, liquids_pointable = true, }) end
--[[ Copyright 2012 Rackspace Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local fmt = require('string').format local async = require('async') local run = require('./run') local exports = {} function runTestFile(filePath, callback) print(filePath) local status, mod = pcall(require, filePath) if status ~= true then process.stdout:write(fmt('Error loading test module [%s]: %s\n\n', filePath, mod)) callback(err) return end process.stdout:write(fmt('Executing test module [%s]\n\n', filePath)) run(nil, mod, function(err, stats) process.stdout:write('\n') callback(err, stats) end) end function runTestFiles(testFiles, options, callback) local failed = 0 async.forEachSeries(testFiles, function(testFile, callback) runTestFile(testFile, function(err, stats) if err then callback(err) return end if stats then failed = failed + stats.failed end callback() end) end, function(err) if err then p(err) debugm.traceback(err) end callback(err, failed) end) end exports.runTestFile = runTestFile exports.runTestFiles = runTestFiles return exports
--[[ Copyright 2018 The Nakama Authors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local nk = require("nakama") local du = require("debug_utils") --[[ Test RPC function calls from client libraries. --]] local function rpc(_context, payload) nk.event("foo", {bar = "baz"}, 12345, false) return payload end nk.register_rpc(rpc, "clientrpc.rpc") local function rpc_error(_context, _payload) error("Some error occured.") end nk.register_rpc(rpc_error, "clientrpc.rpc_error") local function rpc_get(_context, _payload) local response = { message = "PONG" } return nk.json_encode(response) end nk.register_rpc(rpc_get, "clientrpc.rpc_get") local function send_notification(context, payload) local decoded = nk.json_decode(payload) local new_notifications = { { code = 1, content = { reward_coins = 1000 }, persistent = true, sender_id = context.user_id, subject = "You've unlocked level 100!", user_id = decoded.user_id } } nk.notifications_send(new_notifications) end nk.register_rpc(send_notification, "clientrpc.send_notification") local function send_stream_data(context, payload) local stream = { mode = 20, label = "Stream Data Test", } nk.stream_user_join(context.user_id, context.session_id, stream, false, false) nk.stream_send(stream, tostring(payload)) end nk.register_rpc(send_stream_data, "clientrpc.send_stream_data") local function create_authoritative_match(_context, payload) local decoded = nk.json_decode(payload) local params = { debug = (decoded and decoded.debug) or true, label = (decoded and decoded.label) } local match_id = nk.match_create("match", params) return nk.json_encode({ match_id = match_id }) end nk.register_rpc(create_authoritative_match, "clientrpc.create_authoritative_match") local function print_env(context, _) print("env:\n" .. du.print_r(context.env)) local response = { message = context.env } return nk.json_encode(response) end nk.register_rpc(print_env, "clientrpc.print_env") local function create_leaderboard(context, payload) local decoded = nk.json_decode(payload) local id = nk.uuid_v4() local status, result = pcall(nk.leaderboard_create, id, false, "desc", decoded.operator) if (not status) then nk.logger_error(result) end local response = { leaderboard_id = id } return nk.json_encode(response) end nk.register_rpc(create_leaderboard, "clientrpc.create_leaderboard")
local Tunnel = module('_core', 'lib/Tunnel') local Proxy = module('_core', 'lib/Proxy') cAPI = Proxy.getInterface('API') API = Tunnel.getInterface('API') local muggablePlayer Citizen.CreateThread( function() while true do Citizen.Wait(100) local nearestPlayer = cAPI.getNearestPlayer(1.5) if nearestPlayer ~= nil then if IsEntityPlayingAnim(GetPlayerPed(player), "script_proc@robberies@homestead@lonnies_shack@deception", "hands_up_loop", 3) then muggablePlayer = nearestPlayer else muggablePlayer = nil end else muggablePlayer = nil end end end ) Citizen.CreateThread( function() local prompt = PromptRegisterBegin() local promptGroup = GetRandomIntInRange(0, 0xffffff) PromptSetControlAction(prompt, 0xCEFD9220) local str = CreateVarString(10, 'LITERAL_STRING', 'Assaltar') PromptSetText(prompt, str) PromptSetEnabled(prompt, 1) PromptSetVisible(prompt, 1) PromptSetHoldMode(prompt, 1) PromptSetGroup(prompt, promptGroup) PromptRegisterEnd(prompt) while true do Citizen.Wait(0) if muggablePlayer ~= nil then local promptGroupName = CreateVarString(10, 'LITERAL_STRING', GetPlayerName(muggablePlayer)) PromptSetActiveGroupThisFrame(promptGroup, promptGroupName) if PromptHasHoldModeCompleted(prompt) then Citizen.Wait(1000) TriggerServerEvent('FRP:MUGGIN:TryToMug', GetPlayerServerId(muggablePlayer)) end end end end )