content
stringlengths
5
1.05M
----------------------------------- -- Area: Windurst Woods -- NPC: Shih Tayuun -- Guild Merchant NPC: Bonecrafting Guild -- !pos -3.064 -6.25 -131.374 241 ----------------------------------- local ID = require("scripts/zones/Windurst_Woods/IDs") require("scripts/globals/shop") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) if player:sendGuild(514,8,23,3) then player:showText(npc,ID.text.SHIH_TAYUUN_DIALOG) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
local rt_dap = require('rust-tools.dap') local config = require('rust-tools.config') local M = {} local function get_params() return { textDocument = vim.lsp.util.make_text_document_params(), position = nil -- get em all } end local function build_label(args) local ret = "" for _, value in ipairs(args.cargoArgs) do ret = ret .. value .. " " end for _, value in ipairs(args.cargoExtraArgs) do ret = ret .. value .. " " end if not vim.tbl_isempty(args.executableArgs) then ret = ret .. "-- " for _, value in ipairs(args.executableArgs) do ret = ret .. value .. " " end end return ret end local function getOptions(result, withTitle, withIndex) local option_strings = withTitle and {"Debuggables: "} or {} for i, debuggable in ipairs(result) do local label = build_label(debuggable.args) local str = withIndex and string.format("%d: %s", i, label) or label table.insert(option_strings, str) end return option_strings end local function is_valid_test(args) local is_not_cargo_check = args.cargoArgs[1] ~= "check" return is_not_cargo_check end -- rust-analyzer doesn't actually support giving a list of debuggable targets, -- so work around that by manually removing non debuggable targets (only cargo -- check for now). -- This function also makes it so that the debuggable commands are more -- debugging friendly. For example, we move cargo run to cargo build, and cargo -- test to cargo test --no-run. local function sanitize_results_for_debugging(result) local ret = {} ret = vim.tbl_filter(function(value) return is_valid_test(value.args) end, result) for i, value in ipairs(ret) do if value.args.cargoArgs[1] == "run" then ret[i].args.cargoArgs[1] = "build" elseif value.args.cargoArgs[1] == "test" then table.insert(ret[i].args.cargoArgs, 2, "--no-run") end end return ret end local function handler(...) local _args = { ... } local result if vim.fn.has 'nvim-0.5.1' == 1 then result = _args[2] else result = _args[3] end result = sanitize_results_for_debugging(result) -- get the choice from the user local choice = vim.fn.inputlist(getOptions(result, true, true)) local args = result[choice].args rt_dap.start(args) end local function get_telescope_handler(opts) local pickers = require('telescope.pickers') local finders = require('telescope.finders') local sorters = require('telescope.sorters') local actions = require('telescope.actions') local action_state = require('telescope.actions.state') return function(_, _, results) results = sanitize_results_for_debugging(results) local choices = getOptions(results, false, false) local function attach_mappings(bufnr, map) local function on_select() local choice = action_state.get_selected_entry().index actions.close(bufnr) local args = results[choice].args rt_dap.start(args) end map('n', '<CR>', on_select) map('i', '<CR>', on_select) -- Additional mappings don't push the item to the tagstack. return true end pickers.new(opts or {}, { prompt_title = "Debuggables", finder = finders.new_table({results = choices}), sorter = sorters.get_generic_fuzzy_sorter(), previewer = nil, attach_mappings = attach_mappings }):find() end end -- Sends the request to rust-analyzer to get the runnables and handles them -- The opts provided here are forwarded to telescope, other than use_telescope -- which is used to check whether we want to use telescope or the vanilla vim -- way for input function M.debuggables() local opts = config.options.tools.debuggables -- this is the handler which is actually used, hence its the used handler local used_handler = handler -- if the user has both telescope installed and option set to use telescope if pcall(require, 'telescope') and opts.use_telescope then used_handler = get_telescope_handler(opts) end -- fallback to the vanilla method incase telescope is not installed or the -- user doesn't want to use it vim.lsp.buf_request(0, "experimental/runnables", get_params(), used_handler) end return M
require 'Coat' local CodeGen = require 'CodeGen' singleton 'Smc.Groovy' extends 'Smc.Language' has.id = { '+', default = 'GROOVY' } has.name = { '+', default = 'Groovy' } has.option = { '+', default = '-groovy' } has.suffix = { '+', default = 'Context' } has.generator = { '+', isa = 'Smc.Groovy.Generator', default = function () return require 'Smc.Groovy.Generator' end } has.reflectFlag = { '+', default = true } has.serialFlag = { '+', default = true } has.syncFlag = { '+', default = true } class 'Smc.Groovy.Generator' extends 'Smc.Generator' has.suffix = { '+', default = 'groovy' } function method:_build_template () return CodeGen{ TOP = [[ // ex: set ro: // DO NOT EDIT. // generated by smc (http://github.com/fperrad/lua-Smc) // from file : ${fsm.filename} ${_preamble()} ${_context()} ${_base_state()} ${fsm.maps/_map()} // Local variables: // buffer-read-only: t // End: ]], _preamble = [[ ${fsm.source} ${fsm._package?__package()} ${fsm.importList/_import()} ]], __package = [[ package ${fsm._package; format=scoped} ]], _import = [[ import ${it} ]], _context = [[ class ${fsm.fsmClassname} extends statemap.FSMContext${generator.serialFlag?_serializable()} { def owner def ${fsm.fsmClassname} (owner) { super(${fsm.startState; format=scoped}) this.owner = owner } def ${fsm.fsmClassname} (owner, initState) { super(initState) this.owner = owner } def enterStartState () { state.Entry(this) } ${fsm.transitions/_transition_context()} ${generator.reflectFlag?_context_reflect()} } ]], scoped = function (str) return str:gsub('::','.') end, ucfirst = function (str) return str:sub(1,1):upper() .. str:sub(2) end, _serializable = " implements Serializable", _transition_context = "${isntDefault?_transition_context_if()}\n", _transition_context_if = [[ ${generator.syncFlag?_def_synchronized()!_def()} ${name} (${parameters/_parameter_proto_context(); separator=", "}) { transition = '${name}' state.${name}(this${parameters/_parameter_call_context()}) transition = '' } ]], _def_synchronized = "synchronized void", _def = "def", _parameter_proto_context = "${_type?_parameter_type()}${name}", _parameter_type = "${_type} ", _parameter_call_context = ", ${name}", _context_reflect = [[ final states = [ ${fsm.maps/_map_context_reflect(); separator=",\n"} ] final transitions = [ ${fsm.transitions/_transition_context_reflect(); separator=",\n"} ] ]], _map_context_reflect = '${states/_state_context_reflect(); separator=",\\n"}', _state_context_reflect = [[ ${map.name}.${name; format=ucfirst} ]], _transition_context_reflect = [[ '${name}' ]], _base_state = [[ private class ${fsm.context}State extends statemap.State { def Entry (${fsm.fsmClassname} context) {} def Exit (${fsm.fsmClassname} context) {} ${fsm.transitions/_transition_base_state()} def Default (${fsm.fsmClassname} context) { ${generator.debugLevel0?_base_state_debug()} throw new statemap.TransitionUndefinedException( 'State: ' + context.state.name + ', Transition: ' + context.transition) } } ]], _transition_base_state = "${isntDefault?_transition_base_state_if()}\n", _transition_base_state_if = [[ def ${name} (${fsm.fsmClassname} context${parameters/_parameter_proto()}) { Default(context) } ]], _parameter_proto = ", ${_type?_parameter_type()}${name}", _base_state_debug = [[ if (context.debugFlag) context.debugStream.println 'TRANSITION : Default()' ]], _map = [[ private class ${name}_DefaultState extends ${fsm.context}State { ${defaultState?_map_default_state()} ${generator.reflectFlag?_default_state_reflect()} } ${states/_state()} class ${name} { ${states/_state_init()} static final Default = new ${name}_DefaultState(name:'${fullName}::DefaultState', id:-1) } ]], _map_default_state = "${defaultState.transitions/_transition()}", _default_state_reflect = [[ def transitions = [ ${reflect/_reflect(); separator=",\n"} ] ]], _state_init = [[ static final ${name} = new ${map.name}_${name; format=ucfirst}(name:'${fullName}', id:${map.nextStateId}) ]], _state = [[ private class ${map.name}_${name; format=ucfirst} extends ${map.name}_DefaultState { ${entryActions?_state_entry()} ${exitActions?_state_exit()} ${transitions/_transition()} ${generator.reflectFlag?_state_reflect()} } ]], _state_entry = [[ def Entry (${map.fsm.fsmClassname} context) { def ctxt = context.owner ${entryActions/_action()} } ]], _state_exit = [[ def Exit (${map.fsm.fsmClassname} context) { def ctxt = context.owner ${exitActions/_action()} } ]], _state_reflect = [[ final transitions = [ ${reflect/_reflect(); separator=",\n"} ] ]], _reflect = [[ ${name}:${def} ]], _transition = [[ def ${name}(${fsm.fsmClassname} context${parameters/_parameter_proto()}) { ${hasCtxtReference?_transition_ctxt()} ${generator.debugLevel0?_transition_debug()} ${guards/_guard()} ${needFinalElse?_transition_else()} } ]], _transition_ctxt = [[ def ctxt = context.owner ]], _transition_debug = [[ if (context.debugFlag) context.debugStream.println('LEAVING STATE : ${state.fullName}') ]], _transition_else = [[ else { super.${name}(context${parameters/_parameter_call()}) } ]], _parameter_call = ", ${name}", _guard = "${isConditional?_guard_conditional()!_guard_unconditional()}", _guard_conditional = "${ifCondition?_guard_if()!_guard_no_if()}", _guard_no_if = "${elseifCondition?_guard_elseif()!_guard_else()}", _guard_unconditional = [[ ${_guard_core()} ]], _guard_if = [[ if (${condition}) { ${_guard_core()} } ]], _guard_elseif = [[ else if (${condition}) { ${_guard_core()} } ]], _guard_else = [[ else { ${_guard_core()} } ]], _guard_core = [[ ${needVarEndState?_guard_end_state()} ${doesExit?_guard_exit()} ${generator.debugLevel0?_guard_debug_enter()} ${hasActions?_guard_actions()!_guard_no_action()} ${doesEndPop?_guard_end_pop()} ]], _guard_end_state = [[ def endState = context.state ]], _guard_exit = [[ ${generator.debugLevel1?_guard_debug_before_exit()} context.state.Exit(context) ${generator.debugLevel1?_guard_debug_after_exit()} ]], _guard_debug_before_exit = [[ if (context.debugFlag) context.debugStream.println('BEFORE EXIT : ${transition.state.fullName}.Exit()') ]], _guard_debug_after_exit = [[ if (context.debugFlag) context.debugStream.println('AFTER EXIT : ${transition.state.fullName}.Exit()') ]], _guard_debug_enter = [[ if (context.debugFlag) context.debugStream.println('ENTER TRANSITION: ${transition.state.fullName}.${transition.name}(${transition.parameters/_parameter_proto_context(); separator=', '})') ]], _guard_no_action = [[ ${isConditional?_guard_no_action_if()} ${_guard_final()} ]], _guard_no_action_if = [[ // No actions. ]], _guard_actions = [[ context.clearState() ${generator.catchFlag?_guard_actions_protected()!_guard_actions_not_protected()} ]], _guard_actions_protected = [[ try { ${actions/_action()} } finally { ${_guard_final()} } ]], _guard_actions_not_protected = [[ ${actions/_action()} ${_guard_final()} ]], _guard_final = [[ ${generator.debugLevel0?_guard_debug_exit()} ${doesSet?_guard_set()} ${doesPush?_guard_push()} ${doesPop?_guard_pop()} ${doesEntry?_guard_entry()} ]], _guard_debug_exit = [[ if (context.debugFlag) context.debugStream.println('EXIT TRANSITION : ${transition.state.fullName}.${transition.name}(${transition.parameters/_parameter_proto_context(); separator=', '})') ]], _guard_set = [[ context.setState(${needVarEndState?_end_state_var()!_end_state_no_var()}) ]], _end_state_var = "endState", _end_state_no_var = "${endStateName; format=scoped}", _guard_push = [[ ${doesPushSet?_guard_set()} ${doesPushEntry?_guard_entry()} context.pushState(${pushStateName; format=scoped}) ]], _guard_pop = [[ context.popState() ]], _guard_entry = [[ ${generator.debugLevel1?_guard_debug_before_entry()} context.state.Entry(context) ${generator.debugLevel1?_guard_debug_after_entry()} ]], _guard_debug_before_entry = [[ if (context.debugFlag) context.debugStream.println('BEFORE ENTRY : ${transition.state.fullName}.Exit()') ]], _guard_debug_after_entry = [[ if (context.debugFlag) context.debugStream.println('AFTER ENTRY : ${transition.state.fullName}.Exit()') ]], _guard_end_pop = [[ context.${endStateName}(${popArgs}) ]], _action = "${propertyFlag?_action_prop()!_action_no_prop()}\n", _action_no_prop = "${isEmptyStateStack?_action_ess()!_action_no_ess()}", _action_prop = [[ ctxt.${name} = ${arguments} ]], _action_ess = [[ context.emptyStateStack() ]], _action_no_ess = [[ ctxt.${name}(${arguments; separator=', '}) ]], } end
local llpSender=TcpSender:extends { } llpSender.__name='LLP Sender' function llpSender:__init(data, channelName, logger) llpSender.super.__init(self, data, channelName, logger) self._startMessageChars=self._configTable.startMessageChars or DEFAULT_LLP_START_OF_MESSAGE self._endMessageChars =self._configTable.endMessageChars or DEFAULT_LLP_END_OF_MESSAGE end function llpSender:send(message) local SOM =self._startMessageChars local EOM =self._endMessageChars LOGGER:debug("Building LLP payload") local llpPayload=SOM..tostring(message)..EOM local response=llpSender.super.send(self, llpPayload, EOM) if response then if not response:match(SOM) then self:_catch(nil, START_OF_MESSAGE_ACK_ERR) end if not response:match(EOM) then self:_catch(nil, END_OF_MESSAGE_ACK_ERR) end response=response:match(SOM..'(.*)'..EOM) end return response end return llpSender
return{ name = "greendale", description = "Greendale", type = "key", info = "a key that is rumored to open a secret door to a place named 'Greendale'", MAX_ITEMS = 1, }
local ffi = require "ffi" local bit = require("bit") local band = bit.band local bnot = bit.bnot local lshift = bit.lshift local rshift = bit.rshift local GDILib = ffi.load("gdi32") local gdi_ffi = require ("gdi32_ffi") --[[ DeviceContext The Drawing Context for good ol' GDI drawing --]] DeviceContext = {} setmetatable(DeviceContext, { __call = function(self, ...) return self:create(...) end, }) DeviceContext_mt = { __index = DeviceContext, __tostring = function(self) return string.format("DeviceContext(0x%s)", tostring(self.Handle)) end, } DeviceContext.init = function(self, rawhandle) local obj = { Handle = rawhandle; } setmetatable(obj, DeviceContext_mt) return obj; end DeviceContext.create = function(self, lpszDriver, lpszDevice, lpszOutput, lpInitData) lpszDriver = lpszDriver or "DISPLAY" local rawhandle = GDILib.CreateDCA(lpszDriver, lpszDevice, lpszOutput, lpInitData); if rawhandle == nil then return nil, "could not create Device Context as specified" end -- default to advanced graphics mode instead of GM_COMPATIBLE gdi_ffi.SetGraphicsMode(rawhandle, "GM_ADVANCED") return self:init(rawhandle) end DeviceContext.CreateForMemory = function(self, hDC) hDC = hDC or GDILib.CreateDCA("DISPLAY", nil, nil, nil) local rawhandle = GDILib.CreateCompatibleDC(hDC) return self:init(rawhandle) end DeviceContext.clone = function(self) local hDC = GDILib.CreateCompatibleDC(self.Handle); local ctxt = DeviceContext:init(hDC) return ctxt; end DeviceContext.createCompatibleBitmap = function(self, width, height) local bm, err = GDIBitmap:createCompatible(width, height, self); return bm, err end -- Coordinates and Transforms DeviceContext.setGraphicsMode = function(self, mode) gdi_ffi.SetGraphicsMode(self.Handle, mode) return true; end DeviceContext.setMapMode = function(self, mode) gdi_ffi.SetMapMode(self.Handle, mode) return true; end -- Device Context State DeviceContext.flush = function(self) return GDILib.GdiFlush() end DeviceContext.restore = function(self, nSavedDC) nSavedDC = nSavedDC or -1; return GDILib.RestoreDC(self.Handle, nSavedDC); end DeviceContext.save = function(self) local stateIndex = GDILib.SaveDC(self.Handle); if stateIndex == 0 then return false, "failed to save GDI state" end return stateIndex; end -- Object Management DeviceContext.SelectObject = function(self, gdiobj) GDILib.SelectObject(self.Handle, gdiobj.Handle) end DeviceContext.SelectStockObject = function(self, objectIndex) -- First get a handle on the object local objHandle = GDILib.GetStockObject(objectIndex); -- Then select it into the device context return GDILib.SelectObject(self.Handle, objHandle); end -- Drawing Attributes DeviceContext.UseDCBrush = function(self) self:SelectStockObject(gdi_ffi.DC_BRUSH) end DeviceContext.UseDCPen = function(self) self:SelectStockObject(gdi_ffi.DC_PEN) end DeviceContext.SetDCBrushColor = function(self, color) return GDILib.SetDCBrushColor(self.Handle, color) end DeviceContext.SetDCPenColor = function(self, color) return GDILib.SetDCPenColor(self.Handle, color) end -- Drawing routines DeviceContext.MoveTo = function(self, x, y) local result = GDILib.MoveToEx(self.Handle, x, y, nil); return result end DeviceContext.MoveToEx = function(self, x, y, lpPoint) return GDILib.MoveToEx(self.Handle, X, Y, lpPoint); end DeviceContext.SetPixel = function(self, x, y, color) return GDILib.SetPixel(self.Handle, x, y, color); end DeviceContext.SetPixelV = function(self, x, y, crColor) return GDILib.SetPixelV(self.Handle, X, Y, crColor); end DeviceContext.LineTo = function(self, xend, yend) local result = GDILib.LineTo(self.Handle, xend, yend); return result end DeviceContext.Ellipse = function(self, nLeftRect, nTopRect, nRightRect, nBottomRect) return GDILib.Ellipse(self.Handle,nLeftRect,nTopRect,nRightRect,nBottomRect); end DeviceContext.Polygon = function(self, lpPoints, nCount) local res = gdi_ffi.Polygon(self.Handle,lpPoints, nCount); return true; end DeviceContext.Rectangle = function(self, left, top, right, bottom) return GDILib.Rectangle(self.Handle, left, top, right, bottom); end DeviceContext.RoundRect = function(self, left, top, right, bottom, width, height) return GDILib.RoundRect(self.Handle, left, top, right, bottom, width, height); end -- Text Drawing DeviceContext.Text = function(self, txt, x, y) x = x or 0 y = y or 0 return GDILib.TextOutA(self.Handle, x, y, txt, string.len(txt)); end -- Bitmap drawing DeviceContext.BitBlt = function(self, nXDest, nYDest, nWidth, nHeight, hdcSrc, nXSrc, nYSrc, dwRop) nXSrc = nXSrc or 0 nYSrc = nYSrc or 0 dwRop = dwRop or gdi_ffi.SRCCOPY return GDILib.BitBlt(self.Handle,nXDest,nYDest,nWidth,nHeight,hdcSrc,nXSrc,nYSrc,dwRop); end DeviceContext.StretchDIBits = function(self, XDest, YDest, nDestWidth, nDestHeight, XSrc, YSrc, nSrcWidth, nSrcHeight, lpBits, lpBitsInfo, iUsage, dwRop) XDest = XDest or 0 YDest = YDest or 0 iUsage = iUsage or 0 dwRop = dwRop or gdi_ffi.SRCCOPY; return GDILib.StretchDIBits(hdc,XDest,YDest,nDestWidth,nDestHeight,XSrc,YSrc,nSrcWidth,nSrcHeight,lpBits,lpBitsInfo,iUsage,dwRop); end DeviceContext.GetDIBits = function(self, hbmp, uStartScan, cScanLines, lpvBits, lpbi, uUsage) return GDILib.GetDIBits(self.Handle,hbmp,uStartScan,cScanLines,lpvBits,lpbi,uUsage); end DeviceContext.StretchBlt = function(self, img, XDest, YDest,DestWidth,DestHeight) XDest = XDest or 0 YDest = YDest or 0 DestWidth = DestWidth or img.Width DestHeight = DestHeight or img.Height -- Draw a pixel buffer local bmInfo = BITMAPINFO(); bmInfo.bmiHeader.biWidth = img.Width; bmInfo.bmiHeader.biHeight = img.Height; bmInfo.bmiHeader.biPlanes = 1; bmInfo.bmiHeader.biBitCount = img.BitsPerElement; bmInfo.bmiHeader.biClrImportant = 0; bmInfo.bmiHeader.biClrUsed = 0; bmInfo.bmiHeader.biCompression = 0; self:StretchDIBits(XDest,YDest,DestWidth,DestHeight, 0,0,img.Width, img.Height, img.Data, bmInfo); end -- For Color -- 0x00bbggrr local function RGB(byRed, byGreen, byBlue) local acolor = lshift(byBlue,16) + lshift(byGreen,8) + byRed; return acolor; end local function GetRValue(c) return band(c, 0xff) end local function GetGValue(c) return band(rshift(c,8), 0xff) end local function GetBValue(c) return band(rshift(c,16), 0xff) end -- -- This function answers the question: -- Given: -- We know the size of the byte boundary we want -- to align to. -- Question: -- How many bytes need to be allocated to ensure we -- will align to that boundary. -- Discussion: -- This comes up in cases where you're allocating a bitmap image -- for example. It may be a 24-bit image, but you need to ensure -- that each row can align to a 32-bit boundary. So, we need to -- essentially scale up the number of bits to match the alignment. -- local GetAlignedByteCount = function(width, bitsperpixel, alignment) local bytesperpixel = bitsperpixel / 8; return band((width * bytesperpixel + (alignment - 1)), bnot(alignment - 1)); end GDIBitmap = {} setmetatable(GDIBitmap, { __call = function(self, ...) return self:create(...) end, }) GDIBitmap_mt = { __index = GDIBitmap, __tostring = function(self) return string.format("GDIBitmap(0x%s)", tostring(self.Handle)) end, } GDIBitmap.init = function(self, rawhandle, deviceContext) --print("GDIBitmap.init - BEGIN: ", rawhandle, deviceContext) local obj = { Handle = rawhandle; DeviceContext = deviceContext; } setmetatable(obj, GDIBitmap_mt) if deviceContext ~= nil then deviceContext:SelectObject(obj) end return obj; end GDIBitmap.create = function(self, width, height, deviceContext) local rawhandle = GDILib.CreateCompatibleBitmap(deviceContext.Handle, width, height) if rawhandle == nil then return nil, "failed to create bitmap handle" end return self:init(rawhandle) end GDIBitmap.createCompatible = function(self, width, height, deviceContext) --print("GDIBitmap.createCompatible - BEGIN: ", width, height, deviceContext) local rawhandle = GDILib.CreateCompatibleBitmap(deviceContext.Handle, width, height) --print("GDIBitmap.createCompatible, rawhandle: ", rawhandle) if rawhandle == nil then return nil, "failed to create bitmap handle" end return self:init(rawhandle, deviceContext:clone()) end GDIBitmap.getDeviceContext = function(self) if not self.DeviceContext then -- create a memory device context self.DeviceContext = DeviceContext:CreateForMemory() self.DeviceContext:SelectObject(self) end return self.DeviceContext end GDIBitmap.getNativeInfo = function(self) if not self.Info then self.Info = ffi.new("BITMAP") local infosize = ffi.sizeof("BITMAP"); GDILib.GetObjectA(self.Handle, infosize, self.Info) end return self.Info end GDIBitmap.Print = function(self) local info = self:getNativeInfo(); if not info then print("No bitmap info available") return false; end print(string.format("== Bitmap ==")) print(string.format(" type: %d", info.bmType)) print(string.format(" width: %d", info.bmWidth)) print(string.format(" height: %d", info.bmHeight)) print(string.format(" Width Bytes: %d", info.bmWidthBytes)) print(string.format(" Planes: %d", info.bmPlanes)) print(string.format("BitsPerPixel: %d", info.bmBitsPixel)); print(string.format(" Pixels: %s", tostring(info.bmBits))) return true; end GDIDIBSection = {} setmetatable(GDIDIBSection, { __call = function(self, ...) return self:create(...) end, }) GDIDIBSection_mt = { __index = GDIDIBSection, } GDIDIBSection.init = function(rawhandle, pixels, info, deviceContext) local obj = { Handle = rawhandle; Width = info.bmiHeader.biWidth; Height = info.bmiHeader.biHeight; BitsPerPixel = info.bmiHeader.biBitCount; Pixels = pixels; Info = info; DeviceContext = deviceContext; } setmetatable(obj, GDIDIBSection_mt) -- Select the dib section into the device context -- so that drawing can occur. deviceContext:SelectObject(obj) return obj; end GDIDIBSection.create = function(self, width, height, bitsperpixel, alignment) bitsperpixel = bitsperpixel or 32 alignment = alignment or 4 -- Need to construct a BITMAPINFO structure -- to describe the image we'll be creating local bytesPerRow = GetAlignedByteCount(width, bitsperpixel, alignment) local info = BITMAPINFO(); info.bmiHeader.biWidth = width; info.bmiHeader.biHeight = height; info.bmiHeader.biPlanes = 1; info.bmiHeader.biBitCount = bitsperpixel; info.bmiHeader.biSizeImage = bytesPerRow * math.abs(height); info.bmiHeader.biClrImportant = 0; info.bmiHeader.biClrUsed = 0; info.bmiHeader.biCompression = 0; -- GDI32.BI_RGB -- Create the DIBSection, using the screen as -- the source DC local ddc = DeviceContext(); local DIB_RGB_COLORS = 0 local pPixels = ffi.new("void *[1]") local rawhandle = GDILib.CreateDIBSection(ddc.Handle, info, DIB_RGB_COLORS, pPixels, nil, 0); return self:init(rawhandle, pPixels[0], info, ddc) end GDIDIBSection.getDeviceContext = function(self) if not self.DeviceContext then self.DeviceContext = DeviceContext:CreateForMemory(); self.DeviceContext:SelectObject(self); end return self.DeviceContext; end GDIDIBSection.Print = function(self) print("Bits Per Pixel: ", self.BitsPerPixel) print("Size: ", self.Width, self.Height) print("Pixels: ", self.Pixels) end return { FFI = gdi_ffi, Lib = GDILib, DeviceContext = DeviceContext, GDIBitmap = GDIBitmap, GDIDIBSection = GDIDIBSection, -- Some helper functions GetAlignedByteCount = GetAlignedByteCount, GetBValue = GetBValue, GetGValue = GetGValue, GetRValue = GetRValue, RGB = RGB, }
-- module local SceneAssetWalkerModule = {} -------------------------------------------------------------------- --[[ ]] -------------------------------------------------------------------- local function _defaultCollector ( obj, field, value, collected ) collected[ value ] = true end local function _collectAssetFromObject ( obj, collected, collector ) collector = collector or _defaultCollector local model = Model.fromObject ( obj ) if not model then return end local fields = model:getFieldList ( true ) for i, field in ipairs ( fields ) do if field.__type == '@asset' then local value = field:getValue ( obj ) if value then collector ( obj, field, value, collected ) end end end end local function _collectAssetFromEntity ( ent, collected, collector ) _collectAssetFromObject ( ent, collected, collector ) for com in pairs ( ent.components ) do _collectAssetFromObject ( com, collected, collector ) end for child in pairs ( ent.children ) do _collectAssetFromEntity ( child, collected, collector ) end end -------------------------------------------------------------------- function collectAssetFromObject ( obj, collected, collector ) collected = collected or {} _collectAssetFromObject ( obj, collected, collector or _defaultCollector ) return collected end function collectAssetFromEntity ( ent, collected, collector ) collected = collected or {} _collectAssetFromEntity ( ent, collected, collector or _defaultCollector ) return collected end function collectAssetFromGroup ( group, collected, collector ) collected = collected or {} collector = collector or _defaultCollector for ent in pairs ( group.entities ) do _collectAssetFromEntity ( ent, collected, collector ) end for childGroup in pairs ( group.childGroups ) do collectAssetFromGroup ( childGroup, collected, collector ) end return collected end function collectAssetFromScene ( scn, collected, collector ) collected = collected or {} collector = collector or _defaultCollector for ent in pairs ( scn.entities ) do if not ent.parent then _collectAssetFromEntity ( ent, collected, collector ) end end return collected end -------------------------------------------------------------------- local function _dependencyCollector ( obj, field, value, collected ) local meta = field.__meta local preloadMeta = meta and meta[ 'preload' ] local v0 = collected[ value ] local v1 = preloadMeta and 'preload' or 'dep' if v1 == v0 then return end if v0 == 'preload' then --do nothing else collected[ value ] = v1 end end function collectGroupAssetDependency ( group, collected ) return collectAssetFromGroup ( group, collected, _dependencyCollector ) end SceneAssetWalkerModule.collectAssetFromObject = collectAssetFromObject SceneAssetWalkerModule.collectAssetFromEntity = collectAssetFromEntity SceneAssetWalkerModule.collectAssetFromGroup = collectAssetFromGroup SceneAssetWalkerModule.collectAssetFromScene = collectAssetFromScene SceneAssetWalkerModule.collectGroupAssetDependency = collectGroupAssetDependency return SceneAssetWalkerModule
local _, addon = ...; -- https://onlinetexttools.com/split-text?input=&split-by-char=false&char=%20&split-by-regex=false&regex=%2F%5Cs%2B%2F&split-by-length=true&length=110&separator=%2C%5Cn&symbol-before-chunk=%22&symbol-after-chunk=%22 table.insert(addon.officialCourses, table.concat({ "!WOP:2!0x96DD5638!1r1VVXrruyLymXSoHyhjBKIOyuefbe3zF2NxFNBISnwYwaHiNdfHsrU5M5T7(KNDNHzM1Nox6w6Cb1i3sdkvud)dmcjA", "rr0Ngen0XB27meHWDJM389EF)4T7n(2rcDT1bFu6fcDPrbEqwSrnk)X5w8pV9Hp63u)0pl)Hrh(Ox9RlB(UB8n)b3AXt5kj688kbm)fcUsnIlo", "XLE(vxMylXkSKBsoES2QKjxAaRJkcv(IWTg(lcfWTx96vo2JEfyFIgR8So7LzjIS0ZIaz6m2t42tikAUxtROM(cuOREHdpJqkS8ZMm0S8S59gL", "clmCVcQHMN)up36zCpZxaScmVaCEwMsZ9yvoZQfNW4J0Ncn1hartio3diufTzFLUMngvkwfasMxtiNWQnScWcTtd3Sim3mR6vR6)(fCKv97L9V", "B35oi8wZhMpn82jHBLewij8orPhswjS4mPUr4oH3nC3vclnmSCKWH7zE9Gc0Xmn1PdZyDUvxxjzk4uqXit0g9Tij)FP8rvmEfdYY0KUjgxP9SC", "KeiFmFsdekoYaHNeFThIpzw2hneFKaIckvHQC4Jzhnv(uI1yreJi1tqMORBNKShMZI28oSb2jmj4eqLCABaIpKt7q51s1xgbyrJh1vM)Qr6txh", "Notl811OfyasGTmoX38AcE8O0slPShki(q6S8djUmi6uAUkACebl5NamSXbIZEK271LxdtO55liZGjNqKN61XF5NDWt3j5Xn5nDv8uUcLZoYhH", "k0JGBQJySuYqjwg5AmjVKNdj7R4o3vpOiAEwqwlOLO34vrQ(fF6dqP5d63jTRy90TA1RRiTv3ED70QF)o9ATr3017X3sc92gmlrn1xQLygcsj3", "dMLxFZ12SZAB0H1z7D2S3oD388sWZPA8uZQuoA5cpypqIX0D)g39MM3)Fk4EgP8PxVRBxHN2tsUeD7p7NbfxsZkdf1k)KrFoiX6YWIM7)j)Bq)", "FCYlhRhFA8RDD1X9BVE7TSclW9AR59oItF(B5kcvRbOOqxjTyT7V)d" }))
local local0 = 0.4 local local1 = 0.5 - local0 local local2 = 5.2 - local0 local local3 = 0.5 - local0 local local4 = 6 - local0 local local5 = 0.5 - local0 local local6 = 5.6 - local0 local local7 = 0.5 - local0 local local8 = 5.8 - local0 local local9 = 0.5 - local0 local local10 = 5.7 - local0 local local11 = 0.5 - local0 local local12 = 11 - local0 local local13 = 0.5 - local0 local local14 = 9.4 - local0 local local15 = 0.5 - local0 local local16 = 2.7 - local0 local local17 = 0.5 - local0 local local18 = 0.5 - local0 local local19 = 6 - local0 local local20 = 0.5 - local0 local local21 = 5 - local0 local local22 = 0.5 - local0 local local23 = 6 - local0 local local24 = 0.5 - local0 local local25 = 4.8 - local0 local local26 = 0.5 - local0 local local27 = 6.6 - local0 local local28 = 0.5 - local0 local local29 = 0.5 - local0 local local30 = 6 - local0 local local31 = 0.5 - local0 local local32 = 6.7 - local0 local local33 = 0.5 - local0 local local34 = 6.4 - local0 local local35 = 0.5 - local0 local local36 = 6.3 - local0 local local37 = 0.5 - local0 local local38 = 6.5 - local0 local local39 = 0.5 - local0 local local40 = 12.1 - local0 local local41 = 0.5 - local0 local local42 = 10.5 - local0 local local43 = 0.5 - local0 local local44 = 0.5 - local0 local local45 = 0.5 - local0 local local46 = 6.8 - local0 local local47 = 0.5 - local0 local local48 = 5.9 - local0 function OnIf_231000(arg0, arg1, arg2) if arg2 == 0 then KingInBlue231000_ActAfter_RealTime(arg0, arg1) end if arg2 == 1 then KingInBlue231000_BackStepCombo(arg0, arg1) end return end function KingInBlue231000Battle_Activate(arg0, arg1) local local0 = {} local local1 = {} local local2 = {} Common_Clear_Param(local0, local1, local2) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetEventRequest() local local5 = arg0:GetRandam_Int(1, 100) if arg0:GetHpRate(TARGET_SELF) <= 0.5 and arg0:HasSpecialEffectId(TARGET_SELF, 5401) == false then local0[6] = 100 elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 200) then local0[10] = 100 elseif arg0:HasSpecialEffectId(TARGET_SELF, 5401) == true then if 12 <= local3 then local0[1] = 0 local0[2] = 0 local0[3] = 70 local0[5] = 0 local0[7] = 0 local0[8] = 0 local0[9] = 30 if arg0:GetNumber(1) == 0 then local0[1] = 20 local0[2] = 20 local0[3] = 0 local0[5] = 20 local0[7] = 20 local0[8] = 20 local0[9] = 0 end elseif 8 <= local3 then local0[1] = 0 local0[2] = 0 local0[3] = 30 local0[5] = 0 local0[7] = 20 local0[8] = 20 local0[9] = 30 elseif 5.5 <= local3 then local0[1] = 20 local0[2] = 10 local0[3] = 10 local0[5] = 15 local0[7] = 20 local0[8] = 15 local0[9] = 10 elseif 5.5 <= local3 then local0[1] = 15 local0[2] = 10 local0[4] = 10 local0[5] = 15 local0[7] = 25 local0[8] = 25 if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 120) then local0[1] = 0 local0[2] = 25 local0[4] = 15 local0[5] = 0 local0[7] = 35 local0[8] = 25 end if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 120) then local0[1] = 35 local0[2] = 15 local0[4] = 0 local0[5] = 35 local0[7] = 0 local0[8] = 15 end else local0[1] = 15 local0[2] = 25 local0[4] = 30 local0[5] = 15 local0[7] = 15 local0[8] = 0 if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 120) then local0[1] = 0 local0[2] = 30 local0[4] = 30 local0[5] = 0 local0[7] = 40 end if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 120) then local0[1] = 35 local0[2] = 15 local0[4] = 15 local0[5] = 35 local0[7] = 0 end end elseif 11 <= local3 then local0[1] = 0 local0[2] = 0 local0[3] = 100 local0[5] = 0 if arg0:GetNumber(1) == 0 then local0[1] = 33 local0[2] = 33 local0[3] = 0 local0[5] = 33 end elseif 8 <= local3 then local0[1] = 20 local0[2] = 15 local0[3] = 35 local0[5] = 30 elseif 4.5 <= local3 then local0[1] = 30 local0[2] = 20 local0[3] = 20 local0[5] = 30 elseif 2.5 <= local3 then local0[1] = 20 local0[2] = 35 local0[4] = 25 local0[5] = 20 if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 120) then local0[1] = 20 local0[2] = 35 local0[4] = 25 local0[5] = 20 end if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 120) then local0[1] = 35 local0[2] = 15 local0[4] = 20 local0[5] = 35 end else local0[1] = 15 local0[2] = 15 local0[4] = 40 local0[5] = 15 if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 120) then local0[1] = 15 local0[2] = 35 local0[4] = 35 local0[5] = 15 end if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 120) then local0[1] = 40 local0[2] = 0 local0[4] = 20 local0[5] = 40 end end local1[1] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act01) local1[2] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act02) local1[3] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act03) local1[4] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act04) local1[5] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act05) local1[6] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act06) local1[7] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act07) local1[8] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act08) local1[9] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act09) local1[10] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act10) local1[11] = REGIST_FUNC(arg0, arg1, KingInBlue231000_Act11) Common_Battle_Activate(arg0, arg1, local0, local1, REGIST_FUNC(arg0, arg1, KingInBlue231000_ActAfter_AdjustSpace), local2) return end local0 = local2 local0 = local4 local0 = local6 local0 = local30 local0 = local32 local0 = local34 function KingInBlue231000_Act01(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 + 1 local local2 = UPVAL1 + 1 local local3 = UPVAL2 + 1 local local4 = UPVAL0 if arg0:GetNumber(0) == 1 then local1 = UPVAL3 + 1 local2 = UPVAL4 + 1 local3 = UPVAL5 + 1 local4 = UPVAL3 end if local4 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local4, 999, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, local1, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, local2, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, local3, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local8 local0 = local10 local0 = local36 local0 = local38 function KingInBlue231000_Act02(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 + 1 local local2 = UPVAL1 + 1 local local3 = UPVAL0 if arg0:GetNumber(0) == 1 then local1 = UPVAL2 + 1 local2 = UPVAL3 + 1 local3 = UPVAL2 end if local3 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local3, 999, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, local1, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, local2, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local12 local0 = local14 local0 = local40 local0 = local42 function KingInBlue231000_Act03(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 + 1 local local3 = UPVAL1 + 1 local local4 = UPVAL0 if arg0:GetNumber(0) == 1 then local2 = UPVAL2 + 1 local3 = UPVAL3 + 1 local4 = UPVAL2 end if local0 <= 8 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5) end if local4 <= local0 then Approach_Act(arg0, arg1, local4, 0, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, local2, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, local3, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local16 local0 = 4.2 - local0 local0 = 2.7 - local0 local0 = 4.9 - local0 function KingInBlue231000_Act04(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 + 1 local local2 = UPVAL1 + 1 local local3 = UPVAL0 if arg0:GetNumber(0) == 1 then local1 = UPVAL2 + 1 local2 = UPVAL3 + 1 local3 = UPVAL2 end if local3 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local3, 999, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3007, TARGET_ENE_0, local1, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3008, TARGET_ENE_0, local2, 0, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local19 local0 = local21 local0 = local46 local0 = local48 function KingInBlue231000_Act05(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 + 1 local local3 = UPVAL1 + 1 local local4 = UPVAL0 if arg0:GetNumber(0) == 1 then local2 = UPVAL2 + 1 local3 = UPVAL3 + 1 local4 = UPVAL2 end if local4 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local4, 999, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3009, TARGET_ENE_0, local2, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3010, TARGET_ENE_0, local3, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function KingInBlue231000_Act06(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) if arg0:GetDist(TARGET_ENE_0) <= 5 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3011, TARGET_ENE_0, DIST_None, 0, 0) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3011, TARGET_ENE_0, DIST_None, 0, 0) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end local0 = local23 local0 = local25 function KingInBlue231000_Act07(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 999, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3012, TARGET_ENE_0, UPVAL0 + 1, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3013, TARGET_ENE_0, UPVAL1 + 1, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local27 function KingInBlue231000_Act08(arg0, arg1, arg2) local local0 = arg0:GetRandam_Int(1, 100) local local1 = UPVAL0 if local1 <= arg0:GetDist(TARGET_ENE_0) then Approach_Act(arg0, arg1, local1, 999, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3014, TARGET_ENE_0, UPVAL0 + 1, 0, 0) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local27 function KingInBlue231000_Act09(arg0, arg1, arg2) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = UPVAL0 if local0 <= 8 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5) end if local2 <= local0 then Approach_Act(arg0, arg1, local2, 0, 0, 3) end arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3015, TARGET_ENE_0, UPVAL0 + 1, 0, -1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end function KingInBlue231000_Act10(arg0, arg1, arg2) if arg0:GetDist(TARGET_ENE_0) <= 1.5 and arg0:GetRandam_Int(1, 100) <= 30 then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 4) else arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 4) end elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, 0, arg0:GetRandam_Int(30, 45), false, true, -1) else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, 3, TARGET_ENE_0, 1, arg0:GetRandam_Int(30, 45), false, true, -1) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function KingInBlue231000_Act11(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 701, TARGET_ENE_0, 0, AI_DIR_TYPE_B, 5) arg1:AddSubGoal(GOAL_COMMON_If, 10, 1) GetWellSpace_Odds = 100 return GetWellSpace_Odds end local0 = local12 local0 = 8.1 - local0 local0 = local40 local0 = local42 local0 = local30 local0 = local32 local0 = local34 local0 = local36 local0 = local38 local0 = local46 local0 = local48 local0 = local23 local0 = local25 local0 = local27 local0 = local14 local0 = local2 local0 = local4 local0 = local6 local0 = local8 local0 = local10 local0 = local19 local0 = local21 function KingInBlue231000_BackStepCombo(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) if arg0:HasSpecialEffectId(TARGET_SELF, 5401) == true then if 6 <= local0 then local local2 = UPVAL0 if 50 <= local1 then local2 = UPVAL1 end if local2 <= local0 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 3, TARGET_ENE_0, local2, TARGET_ENE_0, false, -1) end if local1 <= 50 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL2, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, UPVAL3, 0) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3015, TARGET_ENE_0, UPVAL1, 0, -1) end elseif local1 <= 20 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL4, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, UPVAL5, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, UPVAL6, 0) elseif local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL7, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, UPVAL8, 0) elseif local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3009, TARGET_ENE_0, UPVAL9, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3010, TARGET_ENE_0, UPVAL10, 0) elseif local1 <= 80 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3012, TARGET_ENE_0, UPVAL11, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3013, TARGET_ENE_0, UPVAL12, 0) else arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3014, TARGET_ENE_0, UPVAL13, 0, 0) end elseif 6 <= local0 then if UPVAL0 <= local0 then arg1:AddSubGoal(GOAL_COMMON_ApproachTarget, 3, TARGET_ENE_0, UPVAL0, TARGET_ENE_0, false, -1) end arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, UPVAL0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, UPVAL14, 0) elseif local1 <= 33 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3000, TARGET_ENE_0, UPVAL15, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboRepeat, 10, 3001, TARGET_ENE_0, UPVAL16, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3002, TARGET_ENE_0, UPVAL17, 0) elseif local1 <= 66 then arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, UPVAL18, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, UPVAL19, 0) else arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3009, TARGET_ENE_0, UPVAL20, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3010, TARGET_ENE_0, UPVAL21, 0) end GetWellSpace_Odds = 0 return GetWellSpace_Odds end function KingInBlue231000_ActAfter_AdjustSpace(arg0, arg1, arg2) arg1:AddSubGoal(GOAL_COMMON_If, 10, 0) return end function KingInBlue231000_ActAfter_RealTime(arg0, arg1) local local0 = arg0:GetDist(TARGET_ENE_0) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Float(2.5, 3.5) arg0:SetNumber(1, 1) if local0 <= 2 then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 60) then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) and local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local2, TARGET_ENE_0, 1, arg0:GetRandam_Int(30, 45), true, true, -1) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) and local1 <= 40 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local2, TARGET_ENE_0, 0, arg0:GetRandam_Int(30, 45), true, true, -1) end end elseif local0 <= 6 then if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 60) and local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_LeaveTarget, arg0:GetRandam_Float(1.5, 2.5), TARGET_ENE_0, 6, TARGET_ENE_0, true, -1) arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local2, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) and local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local2, TARGET_ENE_0, 1, arg0:GetRandam_Int(30, 45), true, true, -1) elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_L, 180) and local1 <= 60 then arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local2, TARGET_ENE_0, 0, arg0:GetRandam_Int(30, 45), true, true, -1) end else arg1:AddSubGoal(GOAL_COMMON_SidewayMove, local2, TARGET_ENE_0, arg0:GetRandam_Int(0, 1), arg0:GetRandam_Int(30, 45), true, true, -1) end return end function KingInBlue231000Battle_Update(arg0, arg1) return GOAL_RESULT_Continue end function KingInBlue231000Battle_Terminate(arg0, arg1) return end local0 = local8 local0 = local10 local0 = local36 local0 = local38 local0 = local12 local0 = local14 local0 = local40 local0 = local42 local0 = local16 local0 = local19 local0 = local46 local0 = local23 function KingInBlue231000Battle_Interupt(arg0, arg1) if arg0:IsLadderAct(TARGET_SELF) then return false end local local0 = arg0:GetRandam_Int(1, 100) local local1 = arg0:GetRandam_Int(1, 100) local local2 = arg0:GetRandam_Int(1, 100) local local3 = arg0:GetDist(TARGET_ENE_0) local local4 = arg0:GetHpRate(TARGET_SELF) if arg0:IsInterupt(INTERUPT_UseItem) and local0 <= 65 then if local3 <= 5 then local local5 = UPVAL0 + 1 local local6 = UPVAL1 + 1 if arg0:GetNumber(0) == 1 then local5 = UPVAL2 + 1 local6 = UPVAL3 + 1 end arg1:ClearSubGoal() arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3003, TARGET_ENE_0, AttDist1, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3004, TARGET_ENE_0, local6, 0) else local local5 = UPVAL4 + 1 local local6 = UPVAL5 + 1 local local7 = UPVAL4 - 1 if arg0:GetNumber(0) == 1 then local5 = UPVAL6 + 1 local6 = UPVAL7 + 1 local7 = UPVAL6 - 1 end arg1:ClearSubGoal() Approach_Act(arg0, arg1, local7, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboAttackTunableSpin, 10, 3005, TARGET_ENE_0, AttDist1, 0, 0) arg1:AddSubGoal(GOAL_COMMON_ComboFinal, 10, 3006, TARGET_ENE_0, local6, 0) end return true elseif arg0:GetNumber(1) == 1 and 13 <= local3 then local local5 = UPVAL4 - 4 local local6 = UPVAL4 + 2 if arg0:GetNumber(0) == 1 then local5 = UPVAL4 - 4 local6 = UPVAL4 + 2 end arg1:ClearSubGoal() Approach_Act(arg0, arg1, local5, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local6, 0, -1) return true elseif arg0:IsInterupt(INTERUPT_Damaged) and local0 <= 40 then local local5 = 0 local local6 = 0 local local7 = 0 local local8 = 0 local local9 = 0 if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_F, 90) then local7 = 701 local8 = AI_DIR_TYPE_B if local1 <= 40 then local9 = 20 local5 = 3007 local6 = UPVAL8 else local9 = 100 local5 = 3009 local6 = UPVAL9 end if arg0:HasSpecialEffectId(TARGET_SELF, 5401) == true then local6 = UPVAL10 end elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_B, 90) then local9 = 0 if arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 180) then local7 = 702 local8 = AI_DIR_TYPE_L else local7 = 703 local8 = AI_DIR_TYPE_R end elseif arg0:IsInsideTarget(TARGET_ENE_0, AI_DIR_TYPE_R, 90) then local5 = 3009 local6 = UPVAL9 local9 = 70 local7 = 702 local8 = AI_DIR_TYPE_L if arg0:HasSpecialEffectId(TARGET_SELF, 5401) == true then local6 = UPVAL10 end else local5 = 3012 local6 = UPVAL11 local7 = 703 local8 = AI_DIR_TYPE_R local9 = 0 if arg0:HasSpecialEffectId(TARGET_SELF, 5401) == true then local9 = 80 end end if local1 <= local9 then arg1:ClearSubGoal() arg1:AddSubGoal(GOAL_COMMON_Wait, 0.1, TARGET_ENE_0, 0, 0, 0) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, local5, TARGET_ENE_0, local6, 0, 0) else arg1:ClearSubGoal() arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, local7, TARGET_ENE_0, 0, local8, 5) arg1:AddSubGoal(GOAL_COMMON_If, 10, 1) end return true end local local9 = arg0:GetRandam_Int(1, 100) local local10 = arg0:GetRandam_Int(1, 100) local local11 = arg0:GetDist(TARGET_ENE_0) local local12 = Shoot_2dist(arg0, arg1, 6, 20, 50, 80) if local12 == 1 then if local10 <= 50 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 4) else arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 4) end elseif local12 == 2 then local local13 = UPVAL4 + 1 local local14 = UPVAL4 if arg0:GetNumber(0) == 1 then local13 = UPVAL6 + 1 local14 = UPVAL6 end local local15 = 0 local local16 = 0 if local10 <= 50 then arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 702, TARGET_ENE_0, 0, AI_DIR_TYPE_L, 4) Approach_Act(arg0, arg1, local14, local15, local16) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local13, 0, -1) else arg1:AddSubGoal(GOAL_COMMON_SpinStep, 5, 703, TARGET_ENE_0, 0, AI_DIR_TYPE_R, 4) Approach_Act(arg0, arg1, local14, local15, local16) arg1:AddSubGoal(GOAL_COMMON_AttackTunableSpin, 10, 3005, TARGET_ENE_0, local13, 0, -1) end return true end return false end return
function onCreate() makeLuaSprite('robo', 'robo', -800, -500); setScrollFactor('robo', 0.9, 0.9); makeLuaSprite('grassm', 'grassm', -800, -500); setScrollFactor('grassm', 0.9, 0.9); scaleObject('grassm', 1.1, 1.1); makeLuaSprite('back_sticks', 'back_sticks', -800, -500); setScrollFactor('back_sticks', 0.9, 0.9); scaleObject('back_sticks', 1.1, 1.1); makeLuaSprite('Front Sticks', 'Front Sticks', -800, -500); setScrollFactor('Front Sticks', 0.9, 0.9); scaleObject('Front Sticks', 1.1, 1.1); addLuaSprite('robo', false); addLuaSprite('back_sticks', false); addLuaSprite('Front Sticks', false); addLuaSprite('grassm', false); close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end
-- $Id$ -- -- All rights reserved. Part of the ALua project. -- Detailed information regarding ALua's license can be found -- in the LICENSE file. -- module("alua.daemon.auth", package.seeall) -- Standard modules require("table") require("string") -- Internal modules require("alua.event") require("alua.daemon.context") -- Alias local context = alua.daemon.context -- -- -- local function auth_process(msg, reply, conn) -- Save the context local id = tostring(context.nextidx()) .. "@" .. alua.id -- Use the idx in order to guarantee the sequencial number context.prc_save(id, conn) -- Set the allowed events alua.event.flush(conn) alua.event.add(conn, context.events.process) reply({status = "ok", id = id, daemon = alua.id}) end -- -- -- local function auth_daemon(msg, reply, conn) -- Save the context context.dmn_save(msg.daemon, conn) -- Set the allowed events alua.event.flush(conn) alua.event.add(conn, context.events.daemon) reply({status = "ok", daemon = alua.id}) end -- -- Register the authentication mode for processes and daemons -- context.auth["daemon"] = auth_daemon context.auth["process"] = auth_process
while true do wait(0.5) mouse1click() wait(0.5) mouse1click() wait(0.5) mouse1click() wait(0.5) mouse1click() wait(0.5) mouse1click() wait(0.5) mouse1click() wait(0.5) mouse1click() wait(0.5) mouse1click() end
function model.getAvailableConveyors() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.CONVEYOR) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getAvailableInputBoxes() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.INPUTBOX) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getAvailableOutputBoxes() local l=sim.getObjectsInTree(sim.handle_scene,sim.handle_all,0) local retL={} for i=1,#l,1 do local data=sim.readCustomDataBlock(l[i],simBWF.modelTags.OUTPUTBOX) if data then retL[#retL+1]={simBWF.getObjectAltName(l[i]),l[i]} end end return retL end function model.getModelInputOutputConnectionIndex(modelHandle,input) -- returns the connection index (1-6) if yes, otherwise -1: if modelHandle~=-1 then for i=1,8,1 do if input then if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.INPUT1+i-1)==modelHandle then return i end else if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.OUTPUT1+i-1)==modelHandle then return i end end end end return -1 end function model.disconnectInputOrOutputBoxConnection(modelHandle,input) local refreshDlg=false if modelHandle~=-1 then for i=1,8,1 do if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.INPUT1+i-1)==modelHandle then simBWF.setReferencedObjectHandle(model.handle,model.objRefIdx.INPUT1+i-1,-1) refreshDlg=true break end if simBWF.getReferencedObjectHandle(model.handle,model.objRefIdx.OUTPUT1+i-1)==modelHandle then simBWF.setReferencedObjectHandle(model.handle,model.objRefIdx.OUTPUT1+i-1,-1) refreshDlg=true break end end end if refreshDlg then model.dlg.refresh() end end function sysCall_init() model.codeVersion=1 model.dlg.init() model.handleJobConsistency(simBWF.isModelACopy_ifYesRemoveCopyTag(model.handle)) model.updatePluginRepresentation() end function sysCall_nonSimulation() model.dlg.showOrHideDlgIfNeeded() model.updatePluginRepresentation() end function sysCall_beforeSimulation() local c=model.readInfo() if sim.boolAnd32(c.bitCoded,1)>0 then sim.setObjectInt32Parameter(model.handles.body,sim.objintparam_visibility_layer,0) end model.simJustStarted=true model.ext.outputBrSetupMessages() model.ext.outputPluginSetupMessages() model.dlg.removeDlg() end --[[ function sysCall_sensing() if model.simJustStarted then model.dlg.updateEnabledDisabledItems() end model.simJustStarted=nil model.ext.outputPluginRuntimeMessages() end --]] function sysCall_afterSimulation() sim.setObjectInt32Parameter(model.handles.body,sim.objintparam_visibility_layer,1) model.dlg.showOrHideDlgIfNeeded() model.dlg.updateEnabledDisabledItems() model.updatePluginRepresentation() end function sysCall_beforeInstanceSwitch() model.dlg.removeDlg() model.removeFromPluginRepresentation() end function sysCall_afterInstanceSwitch() model.updatePluginRepresentation() end function sysCall_cleanup() model.dlg.removeDlg() model.removeFromPluginRepresentation() model.dlg.cleanup() end
--- --- DrawLine.lua --- --- Copyright (C) 2018 Xrysnow. All rights reserved. --- _LoadImageFromFile('draw.pixel', ASSETS.tex.pixel, true, 0, 0, true, 0) local line_color = Color(255, 255, 255, 255) function DrawLine(x1, y1, x2, y2, width, color) width = width or 0.5 color = color or line_color SetImageState('draw.pixel', '', color) local l = hypot(x1 - x2, y1 - y2) local r = atan2(y1 - y2, x1 - x2) Render('draw.pixel', (x1 + x2) / 2, (y1 + y2) / 2, r, l, width) end
-- require 'busted.runner'() local pkey = require "openssl.pkey" local x509 = require "openssl.x509" local name = require "openssl.x509.name" local altname = require "openssl.x509.altname" local x509 = require "openssl.x509" local luajwtossl = require "luajwtossl" local base64 = require "base64" local utl = require "luajwtossl.utils" local log = print local standalone = true if pcall(debug.getlocal, 4, 1) then -- we'running with test framework, disable logging log = function (x) end standalone = false end local function t2s(o) if type(o) == 'table' then local s = '{ ' for k,v in pairs(o) do if type(k) ~= 'number' then k = '"'..k..'"' end s = s .. '['..k..'] = ' .. t2s(v) .. ',' end return s .. '} ' else return tostring(o) end end local function readfile(filename) local fd,err = io.open(filename, "rb"); if not fd then return nil,"Failed to open "..filename..": "..tostring(err); end local content,err = fd:read("*all"); if not content then err = "Failed to read from "..filename..": "..tostring(err) end fd:close(); return content, err end local function gen_test_rsa_cert() -- make self-signed certificate local key = pkey.new{ type = "rsa"} local dn = name.new () dn:add("C", "US") dn:add("ST", "California") dn:add("L", "San Francisco ") dn:add("O", "Acme , Inc") dn:add("CN", "acme.inc") -- build our certificate local crt = x509.new () crt:setVersion (3) crt:setSerial (42) crt:setSubject (dn) crt:setIssuer(crt: getSubject()) local issued , expires = crt:getLifetime () crt:setLifetime(issued , expires + 600) -- good for 600 seconds crt:setBasicConstraints { CA = true , pathLen = 2 } crt:setBasicConstraintsCritical (true) crt: setPublicKey (key) crt:sign(key) return tostring(crt), crt:toPEM("DER"), key:toPEM("privateKey"), key:toPEM("publicKey") end local hmac_key = "example_key" local rsa_cert, rsa_cert_der, rsa_priv_key, rsa_pub_key = gen_test_rsa_cert() local claim = { iss = "12345678", nbf = os.time(), exp = os.time() + 3600, } -- test for unencrypted tokens local function ptest_none_jwt(extra) local alg = 'none' local jwt = luajwtossl.new { allow_algs={ ['none']=true } } log("alg=".. tostring(alg)) local token, err = jwt.encode(claim, nil, alg, extra) log("Token:", token) assert(token, err) assert(err == nil) local validate = true -- validate exp and nbf (default: true) local decoded, err = jwt.decode(token, nil, validate) assert(decoded, err) assert(err == nil) log("Claim:", t2s(decoded) ) return true end -- test for HMAC digest based tokens local function ptest_hmac_jwt(alg, extra) log("alg=".. tostring(alg)) local jwt = luajwtossl.new { allow_algs="^"..alg.."$" } local token, err = jwt.encode(claim, hmac_key, alg, extra) log("Token:", token) assert(token, err) assert(err == nil) local validate = false log("decode without validation") local decoded, err = jwt.decode(token, nil, false) assert(decoded,err) assert(err == nil) log("Claim:", t2s(decoded) ) validate = true log("decode using secret key") local decoded, err = jwt.decode(token, hmac_key, validate) assert(decoded,err) assert(err == nil) log("Claim:", t2s(decoded) ) log("decode using function to fetch secret key") local decoded, err = jwt.decode(token, function(token_alg, header) assert(header, "header must be provided") assert(token_alg == alg, "invalid alg requested: "..tostring(alg)) return tostring(hmac_key) end, validate) return true end -- test fetch function error handling local function ptest_fetch_error_handling() local alg = "HS256" local token, err = jwt.encode(claim, hmac_key, alg) log("Token:", token) assert(token, err) assert(err == nil) local validate = false log("decode without validation") local decoded, err = jwt.decode(token, function () error("must not be called") end, false) assert(decoded,err) assert(err == nil) log("Claim:", t2s(decoded) ) validate = true log("fetch function returns error") local decoded, err = jwt.decode(token, function() return nil, "err1" end, validate) assert(not decoded) assert(err) assert(err:find("err1",1,true)) log("fetch function faild") local decoded, err = jwt.decode(token, function() error("err2") end, validate) assert(not decoded) assert(err) assert(err:find("err2",1,true)) return true end local function ptest_rsa_jwt(alg, extra) log("alg=".. tostring(alg)) local jwt = luajwtossl.new { allow_algs={ [alg]=true } } assert(rsa_cert) assert(rsa_priv_key) assert(rsa_pub_key) local keystr = rsa_priv_key assert(keystr) log ("KEYSTR=" .. keystr) local token, err = jwt.encode(claim, keystr, alg, extra) log("Token:", token) assert(token, err) assert(err == nil) local validate = false -- validate exp and nbf (default: true) log("decode w/o validation") local decoded0, err = jwt.decode(token, nil, validate) assert(decoded0, err) assert(err == nil) log("Claim:", t2s(decoded) ) validate = true log("decode using cert in PEM format") local decoded, err = jwt.decode(token, tostring(rsa_cert), validate) assert(decoded, err) assert(err == nil) log("Claim:", t2s(decoded) ) log("decode using public key in PEM format") local decoded, err = jwt.decode(token, tostring(rsa_pub_key), validate) assert(decoded, err) assert(err == nil) log("Claim:", t2s(decoded) ) log("decode using function to fetch public key in PEM format") local decoded, err = jwt.decode(token, function(token_alg, header) assert(header, "header must be provided") assert(token_alg == alg, "invalid alg requested: "..tostring(alg)) return tostring(rsa_pub_key) end, validate) assert(decoded, err) assert(err == nil) log("Claim:", t2s(decoded) ) log("decode corrupted token (wrong signature), must fail") local decoded, err = jwt.decode(token .. "M" , tostring(rsa_pub_key), validate) assert("not decoded", "verify should have failed") assert(err == "Invalid signature", err) return token end local function get_header(token) local cjson = require("cjson") log("TOKEN="..token) local part = utl.b64urldecode(token:sub(1,token:find(".",1,true) - 1)) log("PART="..part) return cjson.decode(part) end if (standalone) then -- simple busted emulator, we do not use many features it = function(desc, test_fun) print("\n** RUNNING TEST: "..desc) test_fun() end describe = function (desc, tests_fun) print("\n* RUNNING TESTS GROUP: ".. desc) tests_fun() end end describe("test Utilities methods", function() it("tohex", function() local data = "ABCD"; local hex = utl.tohex(data) assert(hex == "41424344") end) end) describe("test JWT encoding/decoding", function() it("test unencrypted jwt", function() assert(ptest_none_jwt()) end) it("test hmac jwt", function() local algs = { 'HS256', 'HS384', 'HS512' } for _,alg in ipairs(algs) do assert(ptest_hmac_jwt(alg)) end end) it("test RSA jwt", function() for _,alg in ipairs{ 'RS256', 'RS384', 'RS512' } do token = assert(ptest_rsa_jwt(alg)) end end) end) describe("test JWT attack mitigation", function() it("test mitigation on RSA decode", function() local alg = "HS256" local jwt = luajwtossl.new() local token, err = jwt.encode(claim, rsa_pub_key, "HS256") assert(token, err) assert(err == nil) local jw2 = luajwtossl.new { allow_algs="^RS256$" } local validate = true log("attack - pass JWT HMAC - signed with RSA public key") local decoded, err = jwt.decode(token, rsa_pub_key, validate) assert(not decoded, "must have failed for wrong encryption type") assert(string.find(err,"Algorithm not allowed")) end) end) describe("test JWT header fields handling/generation in encoder", function() it("test header fields specification", function() local extra = { header = {typ = "JWT", bar="baz", alg="junk", x5t="" }} token = assert(ptest_rsa_jwt("RS256", extra)) header = get_header(token) assert(header.bar == "baz") assert(header.x5t == nil) end) it("test x5t pass-through", function() local extra = { header = {typ = "JWT", bar="baz", alg="junk", x5t="fooo" }} token = assert(ptest_rsa_jwt("RS256", extra)) header = get_header(token) assert(header.bar == "baz") assert(header.x5t == "fooo") end) it("test x5t computation", function() local extra = { header = {typ = "JWT", bar="baz", alg="junk", x5t="" , ['x5t#S256'] = "" , x5c = ""}, certs = { rsa_cert } } token = assert(ptest_rsa_jwt("RS256", extra)) header = get_header(token) assert(header.bar == "baz") assert(header.x5t) assert(header.x5t ~= "") assert(header['x5t#S256']) assert(header['x5t#S256'] ~= "") assert(header['x5c']) assert(header['x5c'] ~= "") end) end)
local awful = require("awful") local ws = require("awesome-launch.workspace") local rofi = {} rofi.workspace = {} rofi.workspace.dirs = {'~/code'} function rofi.workspace.new() local dirs = table.concat(rofi.workspace.dirs, ' ') local cmd = string.format("find %s -maxdepth 2 -name %s", dirs, ws.filename) cmd = cmd.." -printf '%h\n' | rofi -dmenu -p 'workspace'" awful.spawn.easy_async_with_shell(cmd, function (out) out = string.gsub(out, '\n', '') if out == '' then return end local t = ws.new(out:match("([^/]+)$"), { props = {layout = awful.layout.layouts[1]}, load_workspace = out, }) t:view_only() end) end return rofi
---@class CS.UnityEngine.Cache : CS.System.ValueType ---@field public valid boolean ---@field public ready boolean ---@field public readOnly boolean ---@field public path string ---@field public index number ---@field public spaceFree number ---@field public maximumAvailableStorageSpace number ---@field public spaceOccupied number ---@field public expirationDelay number ---@type CS.UnityEngine.Cache CS.UnityEngine.Cache = { } ---@return boolean ---@param lhs CS.UnityEngine.Cache ---@param rhs CS.UnityEngine.Cache function CS.UnityEngine.Cache.op_Equality(lhs, rhs) end ---@return boolean ---@param lhs CS.UnityEngine.Cache ---@param rhs CS.UnityEngine.Cache function CS.UnityEngine.Cache.op_Inequality(lhs, rhs) end ---@return number function CS.UnityEngine.Cache:GetHashCode() end ---@overload fun(other:CS.System.Object): boolean ---@return boolean ---@param other CS.UnityEngine.Cache function CS.UnityEngine.Cache:Equals(other) end ---@overload fun(): boolean ---@return boolean ---@param optional expiration number function CS.UnityEngine.Cache:ClearCache(expiration) end return CS.UnityEngine.Cache
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- M I D I C O N T R O L S -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === plugins.finalcutpro.midi.controls.zoom === --- --- Final Cut Pro MIDI Zoom Control. -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Logger: -------------------------------------------------------------------------------- local log = require("hs.logger").new("zoomMIDI") -------------------------------------------------------------------------------- -- CommandPost Extensions: -------------------------------------------------------------------------------- local fcp = require("cp.apple.finalcutpro") -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} --- plugins.finalcutpro.midi.controls.zoom.control() -> nil --- Function --- Final Cut Pro MIDI Zoom Control --- --- Parameters: --- * metadata - table of metadata from the MIDI callback --- --- Returns: --- * None function mod.control(metadata) local value if metadata.pitchChange then value = metadata.pitchChange else value = metadata.fourteenBitValue end if type(value) == "number" then local appearance = fcp:timeline():toolbar():appearance() if appearance then -------------------------------------------------------------------------------- -- MIDI Controller Value (7bit): 0 to 127 -- MIDI Controller Value (14bit): 0 to 16383 -- Zoom Slider: 0 to 10 -------------------------------------------------------------------------------- appearance:show():zoomAmount():setValue(value / (16383/10)) end else log.ef("Unexpected Value: %s %s", value, value and type(value)) end end --- plugins.finalcutpro.midi.controls.zoom.init() -> nil --- Function --- Initialise the module. --- --- Parameters: --- * None --- --- Returns: --- * None function mod.init() local params = { group = "fcpx", text = string.upper(i18n("midi")) .. ": " .. i18n("timelineZoom"), subText = i18n("midiTimelineZoomDescription"), fn = mod.control, } mod._manager.controls:new("zoomSlider", params) return mod end -------------------------------------------------------------------------------- -- -- THE PLUGIN: -- -------------------------------------------------------------------------------- local plugin = { id = "finalcutpro.midi.controls.zoom", group = "finalcutpro", dependencies = { ["core.midi.manager"] = "manager", } } -------------------------------------------------------------------------------- -- INITIALISE PLUGIN: -------------------------------------------------------------------------------- function plugin.init(deps) mod._manager = deps.manager return mod.init() end return plugin
player_manager.AddValidModel( "PMC5_03", "models/player/PMC_5/PMC__03.mdl" ) list.Set( "PlayerOptionsModel", "PMC5_03", "models/player/PMC_5/PMC__03.mdl" )
-- @author : aero (2254228017@qq.com) -- @file : init -- @created : 星期二 3月 01, 2022 17:18:52 CST -- @github : https://github.com/denstiny -- @blog : https://denstiny.github.io local M = require("OverVirTool.OverVirTualChara") function M.initVirTool() if M.fileRules() == true then return end local cur_line = vim.fn.line('.') local max_line = vim.fn.line('$') local count = 0 for line_num = cur_line-M.scope, cur_line+M.scope,1 do if line_num > 0 and line_num <= max_line then count = count + 1 -- id local mrk = M.StartVisible(line_num,-1,M.OverVirTualChara_c,count) -- 创建虚拟文本 if mrk ~= nil and M.filterVirsiBle(line_num) == false then -- 清理空行虚拟文本 -- clear blank line M.delVirTool(mrk) end end end end function M.initVirTool_() if M.fileRules() == true then return end local cur_line = vim.fn.line('.') local max_line = vim.fn.line('$') local count = 0 for line = 1, M.scope,1 do count = count+1 if M.filterVirsiBle(cur_line-line) then M.StartVisible(cur_line-line,-1,M.OverVirTualChara_c,count) end count = count+1 if M.filterVirsiBle(cur_line+line) then M.StartVisible(cur_line+line,-1,M.OverVirTualChara_c,count) end end M.StartVisible(cur_line,-1,M.OverVirTualChara_c,count+1) end local opts = { overlay_start = true, OverVirTualChara_c = ' .-||>', rules_file = {'startify','NvimTree','Trouble','Outline','packer','lsp-installer','toggleterm','CompetiTest','markdown'}, scope = 35 } function M.setup(opts) M.overlay_start = opts.overlay_start M.rules_file = opts.rules_file M.OverVirTualChara_c = opts.OverVirTualChara_c M.scope = opts.scope -- 初始化id组 M.table_id = {} M.ns_id = vim.api.nvim_create_namespace('OverVirTualChara') if M.overlay_start then vim.cmd[[ augroup MyFunVirReturnText au! au TextChanged,InsertLeave * lua require('overvir').initVirTool_() au BufEnter,InsertLeave,CursorMovedI,TextChanged,CursorMoved * lua require('overvir').initVirTool_() augroup END ]] end end return M
local trouble = require("trouble.providers.telescope") local telescope = require("telescope") telescope.setup({ extensions = { -- fzy_native = { -- override_generic_sorter = false, -- override_file_sorter = true, --}, }, defaults = { mappings = { i = { ["<c-t>"] = trouble.open_with_trouble } }, prompt_prefix = "❯ ", selection_caret = " ", winblend = 5, layout_strategy = "flex", }, }) -- telescope.load_extension("fzy_native") require("telescope").load_extension("fzf") telescope.load_extension("gh") local M = {} M.project_files = function(opts) opts = opts or {} local _git_pwd = vim.fn.systemlist("git rev-parse --show-toplevel")[1] if vim.v.shell_error ~= 0 then local client = vim.lsp.get_active_clients()[1] if client then opts.cwd = client.config.root_dir end require("telescope.builtin").find_files(opts) return end require("telescope.builtin").git_files(opts) end local util = require("util") util.nnoremap("<Leader><Space>", M.project_files) util.nnoremap("<Leader>fd", function() require("telescope.builtin").git_files({ cwd = "~/.config/nvim", }) end) return M
local bit32 = require("bit") local band = bit32.band function apply(opcodes, opcode_cycles) local function add_to_a (reg, flags, value) local a = reg[3] -- half-carry flags[3] = band(a, 0xF) + band(value, 0xF) > 0xF local sum = a + value -- carry (and overflow correction) flags[4] = sum > 0xFF reg[3] = band(sum, 0xFF) flags[1] = reg[3] == 0 flags[2] = false end local function adc_to_a (reg, flags, value) local a = reg[3] -- half-carry local carry = 0 if flags[4] then carry = 1 end flags[3] = band(a, 0xF) + band(value, 0xF) + carry > 0xF local sum = a + value + carry -- carry (and overflow correction) flags[4] = sum > 0xFF reg[3] = band(sum, 0xFF) flags[1] = reg[3] == 0 flags[2] = false end -- add A, r opcodes[0x80] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[4]) end opcodes[0x81] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[5]) end opcodes[0x82] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[6]) end opcodes[0x83] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[7]) end opcodes[0x84] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[9]) end opcodes[0x85] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[10]) end opcode_cycles[0x86] = 8 opcodes[0x86] = function(self, reg, flags, mem) add_to_a(reg, flags, self.read_at_hl()) end opcodes[0x87] = function(self, reg, flags, mem) add_to_a(reg, flags, reg[3]) end -- add A, nn opcode_cycles[0xC6] = 8 opcodes[0xC6] = function(self, reg, flags, mem) add_to_a(reg, flags, self.read_nn()) end -- adc A, r opcodes[0x88] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[4]) end opcodes[0x89] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[5]) end opcodes[0x8A] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[6]) end opcodes[0x8B] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[7]) end opcodes[0x8C] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[9]) end opcodes[0x8D] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[10]) end opcode_cycles[0x8E] = 8 opcodes[0x8E] = function(self, reg, flags, mem) adc_to_a(reg, flags, self.read_at_hl()) end opcodes[0x8F] = function(self, reg, flags, mem) adc_to_a(reg, flags, reg[3]) end -- adc A, nn opcode_cycles[0xCE] = 8 opcodes[0xCE] = function(self, reg, flags, mem) adc_to_a(reg, flags, self.read_nn()) end local function sub_from_a (reg, flags, value) local a = reg[3] -- half-carry flags[3] = band(a, 0xF) - band(value, 0xF) < 0 a = a - value -- carry (and overflow correction) flags[4] = a < 0 or a > 0xFF a = band(a, 0xFF) reg[3] = a flags[1] = a == 0 flags[2] = true end local function sbc_from_a (reg, flags, value) local a = reg[3] local carry = 0 if flags[4] then carry = 1 end -- half-carry flags[3] = band(a, 0xF) - band(value, 0xF) - carry < 0 local difference = a - value - carry -- carry (and overflow correction) flags[4] = difference < 0 or difference > 0xFF a = band(difference, 0xFF) reg[3] = a flags[1] = a == 0 flags[2] = true end -- sub A, r opcodes[0x90] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[4]) end opcodes[0x91] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[5]) end opcodes[0x92] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[6]) end opcodes[0x93] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[7]) end opcodes[0x94] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[9]) end opcodes[0x95] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[10]) end opcode_cycles[0x96] = 8 opcodes[0x96] = function(self, reg, flags, mem) sub_from_a(reg, flags, self.read_at_hl()) end opcodes[0x97] = function(self, reg, flags, mem) sub_from_a(reg, flags, reg[3]) end -- sub A, nn opcode_cycles[0xD6] = 8 opcodes[0xD6] = function(self, reg, flags, mem) sub_from_a(reg, flags, self.read_nn()) end -- sbc A, r opcodes[0x98] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[4]) end opcodes[0x99] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[5]) end opcodes[0x9A] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[6]) end opcodes[0x9B] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[7]) end opcodes[0x9C] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[9]) end opcodes[0x9D] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[10]) end opcode_cycles[0x9E] = 8 opcodes[0x9E] = function(self, reg, flags, mem) sbc_from_a(reg, flags, self.read_at_hl()) end opcodes[0x9F] = function(self, reg, flags, mem) sbc_from_a(reg, flags, reg[3]) end -- sbc A, nn opcode_cycles[0xDE] = 8 opcodes[0xDE] = function(self, reg, flags, mem) sbc_from_a(reg, flags, self.read_nn()) end -- daa -- BCD adjustment, correct implementation details located here: -- http://www.z80.info/z80syntx.htm#DAA opcodes[0x27] = function(self, reg, flags, mem) local a = reg[3] if not flags[2] then -- Addition Mode, adjust BCD for previous addition-like instruction if band(0xF, a) > 0x9 or flags[3] then a = a + 0x6 end if a > 0x9F or flags[4] then a = a + 0x60 end else -- Subtraction mode! Adjust BCD for previous subtraction-like instruction if flags[3] then a = band(a - 0x6, 0xFF) end if flags[4] then a = a - 0x60 end end -- Always reset H and Z flags[3] = false flags[1] = false -- If a is greater than 0xFF, set the carry flag if band(0x100, a) == 0x100 then flags[4] = true end -- Note: Do NOT clear the carry flag otherwise. This is how hardware -- behaves, yes it's weird. a = band(a, 0xFF) reg[3] = a -- Update zero flag based on A's contents flags[1] = a == 0 end local function add_to_hl (reg, flags, value) -- half carry flags[3] = band(reg.hl(), 0xFFF) + band(value, 0xFFF) > 0xFFF local sum = reg.hl() + value -- carry flags[4] = sum > 0xFFFF or sum < 0x0000 reg.set_hl(band(sum, 0xFFFF)) flags[2] = false end -- add HL, rr opcode_cycles[0x09] = 8 opcode_cycles[0x19] = 8 opcode_cycles[0x29] = 8 opcode_cycles[0x39] = 8 opcodes[0x09] = function(self, reg, flags, mem) add_to_hl(reg, flags, reg.bc()) end opcodes[0x19] = function(self, reg, flags, mem) add_to_hl(reg, flags, reg.de()) end opcodes[0x29] = function(self, reg, flags, mem) add_to_hl(reg, flags, reg.hl()) end opcodes[0x39] = function(self, reg, flags, mem) add_to_hl(reg, flags, reg[2]) end -- inc rr opcode_cycles[0x03] = 8 opcodes[0x03] = function(self, reg, flags, mem) reg.set_bc(band(reg.bc() + 1, 0xFFFF)) end opcode_cycles[0x13] = 8 opcodes[0x13] = function(self, reg, flags, mem) reg.set_de(band(reg.de() + 1, 0xFFFF)) end opcode_cycles[0x23] = 8 opcodes[0x23] = function(self, reg, flags, mem) reg.set_hl(band(reg.hl() + 1, 0xFFFF)) end opcode_cycles[0x33] = 8 opcodes[0x33] = function(self, reg, flags, mem) reg[2] = band(reg[2] + 1, 0xFFFF) end -- dec rr opcode_cycles[0x0B] = 8 opcodes[0x0B] = function(self, reg, flags, mem) reg.set_bc(band(reg.bc() - 1, 0xFFFF)) end opcode_cycles[0x1B] = 8 opcodes[0x1B] = function(self, reg, flags, mem) reg.set_de(band(reg.de() - 1, 0xFFFF)) end opcode_cycles[0x2B] = 8 opcodes[0x2B] = function(self, reg, flags, mem) reg.set_hl(band(reg.hl() - 1, 0xFFFF)) end opcode_cycles[0x3B] = 8 opcodes[0x3B] = function(self, reg, flags, mem) reg[2] = band(reg[2] - 1, 0xFFFF) end -- add SP, dd opcode_cycles[0xE8] = 16 opcodes[0xE8] = function(self, reg, flags, mem) local offset = self.read_nn() -- offset comes in as unsigned 0-255, so convert it to signed -128 - 127 if band(offset, 0x80) ~= 0 then offset = offset + 0xFF00 end -- half carry --if band(reg[2], 0xFFF) + offset > 0xFFF or band(reg[2], 0xFFF) + offset < 0 then flags[3] = band(reg[2], 0xF) + band(offset, 0xF) > 0xF -- carry flags[4] = band(reg[2], 0xFF) + band(offset, 0xFF) > 0xFF reg[2] = reg[2] + offset reg[2] = band(reg[2], 0xFFFF) flags[1] = false flags[2] = false end end return apply
--[[ Name: "sh_attributes.lua". Product: "kuroScript". --]] kuroScript.attributes = {}; -- A function to get the default attributes. function kuroScript.attributes.GetDefault(player, character) local attributes = {}; local default = {}; local k, v; -- Loop through each value in a table. for k, v in pairs(kuroScript.attribute.stored) do if (v.default) then attributes[k] = v.default; end; end; -- Check if a statement is true. if (player) then hook.Call("GetPlayerDefaultAttributes", kuroScript.frame, player, character or player._Character, attributes); end; -- Loop through each value in a table. for k, v in pairs(attributes) do local attributeTable = kuroScript.attribute.Get(k); -- Check if a statement is true. if (attributeTable) then local attribute = attributeTable.uniqueID; -- Set some information. if ( !default[attribute] ) then default[attribute] = { amount = math.min(v, attributeTable.maximum), progress = 0 }; else default[attribute].amount = math.min(default[attribute].amount + v, attributeTable.maximum); end; end; end; -- Return the default attributes. return default; end; -- Check if a statement is true. if (SERVER) then function kuroScript.attributes.Progress(player, attribute, amount, gradual) local attributeTable = kuroScript.attribute.Get(attribute); local attributes = player:QueryCharacter("attributes"); -- Check if a statement is true. if (attributeTable) then attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( gradual and attributes[attribute] ) then if (amount > 0) then amount = math.max(amount - ( (amount / attributeTable.maximum) * attributes[attribute].amount ), amount / attributeTable.maximum); else amount = math.min( (amount / attributeTable.maximum) * attributes[attribute].amount, amount / attributeTable.maximum ); end; end; -- Set some information. amount = amount * kuroScript.config.Get("scale_attribute_progress"):Get(); -- Check if a statement is true. if ( !attributes[attribute] ) then local defaultAttributes = kuroScript.attributes.GetDefault(player); -- Check if a statement is true. if ( defaultAttributes[attribute] ) then attributes[attribute] = defaultAttributes[attribute]; else attributes[attribute] = {amount = 0, progress = 0}; end; elseif (attributes[attribute].amount == attributeTable.maximum) then if (amount > 0) then return false, "You have reached this attribute's maximum!"; end; end; -- Set some information. local progress = attributes[attribute].progress + amount; -- Check if a statement is true. if (progress >= 100) then attributes[attribute].progress = 0; -- Update the player's attribute status. kuroScript.attributes.Update(player, attribute, 1); -- Set some information. local remaining = math.max(progress - 100, 0); -- Check if a statement is true. if (remaining > 0) then return kuroScript.attributes.Progress(player, attribute, remaining); end; elseif (progress < 0) then attributes[attribute].progress = 100; -- Update the player's attribute status. kuroScript.attributes.Update(player, attribute, -1); -- Check if a statement is true. if (progress < 0) then return kuroScript.attributes.Progress(player, attribute, progress); end; else attributes[attribute].progress = progress; end; -- Check if a statement is true. if (attributes[attribute].amount == 0 and attributes[attribute].progress == 0) then attributes[attribute] = nil; end; -- Check if a statement is true. if ( player:HasInitialized() ) then if ( attributes[attribute] ) then player._AttributeProgress[attribute] = math.floor(attributes[attribute].progress); else player._AttributeProgress[attribute] = 0; end; end; else return false, "That is not a valid attribute!"; end; end; -- A function to update a player's attribute status. function kuroScript.attributes.Update(player, attribute, amount) local attributeTable = kuroScript.attribute.Get(attribute); local attributes = player:QueryCharacter("attributes"); -- Check if a statement is true. if (attributeTable) then attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( !attributes[attribute] ) then local defaultAttributes = kuroScript.attributes.GetDefault(player); -- Check if a statement is true. if ( defaultAttributes[attribute] ) then attributes[attribute] = defaultAttributes[attribute]; else attributes[attribute] = {amount = 0, progress = 0}; end; elseif (attributes[attribute].amount == attributeTable.maximum) then if (amount and amount > 0) then return false, "You have reached this attribute's maximum!"; end; end; -- Set some information. attributes[attribute].amount = math.max(attributes[attribute].amount + (amount or 0), 0); -- Check if a statement is true. if (amount) then if (amount < 0) then kuroScript.player.Alert( player, "- "..math.abs(amount).." "..attributeTable.name, Color(0, 100, 255, 255) ); -- Print a debug message. kuroScript.frame:PrintDebug(player:Name().." has lost "..math.abs(amount).." "..attributeTable.name.."."); elseif (amount > 0) then kuroScript.player.Alert( player, "+ "..math.abs(amount).." "..attributeTable.name, Color(255, 150, 0, 255) ); -- Print a debug message. kuroScript.frame:PrintDebug(player:Name().." has gained "..math.abs(amount).." "..attributeTable.name.."."); end; -- Check if a statement is true. if (amount > 0) then attributes[attribute].progress = 0; -- Check if a statement is true. if ( player:HasInitialized() ) then player._AttributeProgress[attribute] = 0; player._AttributeProgressTime = 0; end; end; end; -- Start a user message. umsg.Start("ks_AttributesUpdate", player); umsg.Long(attributeTable.index); umsg.Long(attributes[attribute].amount); umsg.End(); -- Check if a statement is true. if (attributes[attribute].amount == 0 and attributes[attribute].progress == 0) then attributes[attribute] = nil; end; -- Call a gamemode hook. hook.Call("PlayerAttributeUpdated", kuroScript.frame, player, attributeTable, amount); -- Return true to break the function. return true; else return false, "That is not a valid attribute!"; end; end; -- A function to clear a player's attribute boosts. function kuroScript.attributes.ClearBoosts(player) umsg.Start("ks_AttributesBoostClear", player); umsg.End(); -- Set some information. player._AttributeBoosts = {}; end; --- A function to get whether a boost is active for a player. function kuroScript.attributes.IsBoostActive(player, identifier, attribute, amount, expire) if (player._AttributeBoosts) then local attributeTable = kuroScript.attribute.Get(attribute); -- Check if a statement is true. if (attributeTable) then attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( player._AttributeBoosts[attribute] ) then local attributeBoost = player._AttributeBoosts[attribute][identifier]; -- Check if a statement is true. if (attributeBoost) then if (amount and expire) then return attributeBoost.amount == amount and attributeBoost.expire == expire; elseif (amount) then return attributeBoost.amount == amount; elseif (expire) then return attributeBoost.expire == expire; else return true; end; end; end; end; end; end; -- A function to boost a player's attribute status. function kuroScript.attributes.Boost(player, identifier, attribute, amount, expire, silent) local attributeTable = kuroScript.attribute.Get(attribute); -- Check if a statement is true. if (attributeTable) then attribute = attributeTable.uniqueID; -- Check if a statement is true. if (amount) then if (!identifier) then identifier = tostring( {} ); end; -- Check if a statement is true. if ( !player._AttributeBoosts[attribute] ) then player._AttributeBoosts[attribute] = {}; end; -- Check if a statement is true. if ( !kuroScript.attributes.IsBoostActive(player, identifier, attribute, amount, expire) ) then if (expire) then player._AttributeBoosts[attribute][identifier] = { amount = amount, expire = expire, finish = CurTime() + expire }; else player._AttributeBoosts[attribute][identifier] = { amount = amount }; end; -- Check if a statement is true. if (!silent) then if (amount > 0) then kuroScript.player.Alert( player, "+ "..math.abs(amount).." Temporary "..attributeTable.name, Color(255, 0, 255, 255) ); elseif (amount < 0) then kuroScript.player.Alert( player, "- "..math.abs(amount).." Temporary "..attributeTable.name, Color(0, 255, 255, 255) ); end; end; -- Start a user message. umsg.Start("ks_AttributesBoost", player); umsg.Long(attributeTable.index); umsg.Long(player._AttributeBoosts[attribute][identifier].amount); umsg.Long(player._AttributeBoosts[attribute][identifier].expire); umsg.Long(player._AttributeBoosts[attribute][identifier].finish); umsg.String(identifier); umsg.End(); end; -- Return the identifier. return identifier; elseif (identifier) then if ( kuroScript.attributes.IsBoostActive(player, identifier, attribute) ) then if ( player._AttributeBoosts[attribute] ) then player._AttributeBoosts[attribute][identifier] = nil; end; -- Start a user message. umsg.Start("ks_AttributesBoostClear", player); umsg.Long(attributeTable.index); umsg.String(identifier); umsg.End(); end; -- Return true to break the function. return true; elseif ( player._AttributeBoosts[attribute] ) then umsg.Start("ks_AttributesBoostClear", player); umsg.Long(attributeTable.index); umsg.End(); -- Set some information. player._AttributeBoosts[attribute] = {}; -- Return true to break the function. return true; end; else kuroScript.attributes.ClearBoosts(player); -- Return true to break the function. return true; end; end; -- A function to get whether a player has an attribute. function kuroScript.attributes.Get(player, attribute, boostless) local attributeTable = kuroScript.attribute.Get(attribute); -- Check if a statement is true. if (attributeTable) then attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( kuroScript.frame:HasObjectAccess(player, attributeTable) ) then local default = player:QueryCharacter("attributes")[attribute]; local boosts = player._AttributeBoosts[attribute]; -- Check if a statement is true. if (boostless) then if (default) then return default.amount, default.progress; end; else local progress = 0; local amount = 0; local k, v; -- Check if a statement is true. if (default) then amount = amount + default.amount; progress = progress + default.progress; end; -- Check if a statement is true. if (boosts) then for k, v in pairs(boosts) do amount = amount + v.amount; end; end; -- Set some information. amount = math.Clamp(amount, 0, attributeTable.maximum); -- Check if a statement is true. if (amount > 0) then return amount, progress; end; end; end; end; end; -- Add a hook. hook.Add("PlayerSetSharedVars", "kuroScript.attributes.PlayerSetSharedVars", function(player, curTime) local k, v; -- Check if a statement is true. if (curTime >= player._AttributeProgressTime) then player._AttributeProgressTime = curTime + 10; -- Loop through each value in a table. for k, v in pairs(player._AttributeProgress) do local attributeTable = kuroScript.attribute.Get(k); -- Check if a statement is true. if (attributeTable) then umsg.Start("ks_AttributeProgress", player); umsg.Long(attributeTable.index); umsg.Short(v); umsg.End(); end; end; end; end); -- Add a hook. hook.Add("PlayerThink", "kuroScript.attributes.PlayerThink", function(player, curTime, infoTable) local k, v; -- Loop through each value in a table. for k, v in pairs(player._AttributeBoosts) do for k2, v2 in pairs(v) do if (v2.expire and v2.finish) then if (curTime >= v2.finish) then kuroScript.attributes.Boost(player, k2, k, false); else local timeLeft = v2.finish - curTime; -- Check if a statement is true. if (timeLeft >= 0) then if (!v2.default) then v2.default = v2.amount; end; -- Check if a statement is true. if (v2.amount < 0) then v2.amount = math.max( (math.abs(v2.default) / v2.expire) * timeLeft, 0 ); else v2.amount = math.max( (v2.default / v2.expire) * timeLeft, 0 ); end; end; end; end; end; end; end); -- Add a hook. hook.Add("PlayerInitialized", "kuroScript.attributes.PlayerInitialized", function(player) local k, v; -- Set some information. player._AttributeProgress = {}; player._AttributeProgressTime = 0; -- Loop through each value in a table. for k, v in pairs(kuroScript.attribute.stored) do kuroScript.attributes.Update(player, k); end; -- Loop through each value in a table. for k, v in pairs( player:QueryCharacter("attributes") ) do player._AttributeProgress[k] = math.floor(v.progress); end; end); else kuroScript.attributes.stored = {}; kuroScript.attributes.boosts = {}; -- A function to get whether the local player has an attribute. function kuroScript.attributes.Get(attribute, boostless) local attributeTable = kuroScript.attribute.Get(attribute); -- Check if a statement is true. if (attributeTable) then attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( kuroScript.frame:HasObjectAccess(g_LocalPlayer, attributeTable) ) then local default = kuroScript.attributes.stored[attribute]; local boosts = kuroScript.attributes.boosts[attribute]; -- Check if a statement is true. if (boostless) then if (default) then return default.amount, default.progress; end; else local progress = 0; local amount = 0; local k, v; -- Check if a statement is true. if (default) then amount = amount + default.amount; progress = progress + default.progress; end; -- Check if a statement is true. if (boosts) then for k, v in pairs(boosts) do amount = amount + v.amount; end; end; -- Set some information. amount = math.Clamp(amount, 0, attributeTable.maximum); -- Check if a statement is true. if (amount > 0) then return amount, progress; end; end; end; end; end; -- Hook a user message. usermessage.Hook("ks_AttributesBoostClear", function(msg) local index = msg:ReadLong(); local identifier = msg:ReadString(); local attributeTable = kuroScript.attribute.Get(index); -- Check if a statement is true. if (attributeTable) then local attribute = attributeTable.uniqueID; -- Check if a statement is true. if (identifier and identifier != "") then if ( kuroScript.attributes.boosts[attribute] ) then kuroScript.attributes.boosts[attribute][identifier] = nil; end; else kuroScript.attributes.boosts[attribute] = nil; end; else kuroScript.attributes.boosts = {}; end; -- Check if a statement is true. if (kuroScript.menu.GetOpen() and kuroScript.attributes.panel) then if (kuroScript.menu.GetActiveTab() == kuroScript.attributes.panel) then kuroScript.attributes.panel:Rebuild(); end; end; end); -- Hook a user message. usermessage.Hook("ks_AttributesBoost", function(msg) local index = msg:ReadLong(); local amount = msg:ReadLong(); local expire = msg:ReadLong(); local finish = msg:ReadLong(); local identifier = msg:ReadString(); local attributeTable = kuroScript.attribute.Get(index); -- Check if a statement is true. if (attributeTable) then local attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( !kuroScript.attributes.boosts[attribute] ) then kuroScript.attributes.boosts[attribute] = {}; end; -- Set some information. if (amount == 0) then kuroScript.attributes.boosts[attribute][identifier] = nil; elseif (expire > 0 and finish > 0) then kuroScript.attributes.boosts[attribute][identifier] = { amount = amount, expire = expire, finish = finish }; else kuroScript.attributes.boosts[attribute][identifier] = { amount = amount }; end; -- Check if a statement is true. if (kuroScript.menu.GetOpen() and kuroScript.attributes.panel) then if (kuroScript.menu.GetActiveTab() == kuroScript.attributes.panel) then kuroScript.attributes.panel:Rebuild(); end; end; end; end); -- Hook a user message. usermessage.Hook("ks_AttributeProgress", function(msg) local index = msg:ReadLong(); local amount = msg:ReadShort(); local attributeTable = kuroScript.attribute.Get(index); -- Check if a statement is true. if (attributeTable) then local attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( kuroScript.attributes.stored[attribute] ) then kuroScript.attributes.stored[attribute].progress = amount; else kuroScript.attributes.stored[attribute] = {amount = 0, progress = amount}; end; end; end); -- Hook a user message. usermessage.Hook("ks_AttributesUpdate", function(msg) local index = msg:ReadLong(); local amount = msg:ReadLong(); local attributeTable = kuroScript.attribute.Get(index); -- Check if a statement is true. if (attributeTable) then local attribute = attributeTable.uniqueID; -- Check if a statement is true. if ( kuroScript.attributes.stored[attribute] ) then kuroScript.attributes.stored[attribute].amount = amount; else kuroScript.attributes.stored[attribute] = {amount = amount, progress = 0}; end; end; end); end;
local exec = vim.api.nvim_command vim.cmd [[ nnoremap <SPACE> <Nop> let mapleader = "\<Space>" au FocusGained,BufEnter * :checktime command! BufOnly execute '%bdelete|edit #|normal `"' ]] vim.o.encoding = 'utf-8' vim.wo.number = true vim.o.hidden = true vim.o.termguicolors = true vim.o.mouse = 'a' vim.o.cmdheight = 1 vim.o.updatetime = 100 vim.o.clipboard = 'unnamedplus' vim.o.tabstop = 2 vim.o.softtabstop = 2 vim.o.shiftwidth = 2 vim.o.expandtab = true vim.o.completeopt = 'menuone,noselect' vim.opt.splitbelow = true
return function() local cb = require("diffview.config").diffview_callback local M = {} require("diffview").setup { diff_binaries = false, enhanced_diff_hl = true, use_icons = true, icons = { folder_closed = "", folder_open = "", }, signs = { fold_closed = "", fold_open = "", }, file_panel = { position = "left", width = 35, height = 10, listing_style = "tree", -- One of 'list' or 'tree' tree_options = { -- Only applies when listing_style is 'tree' flatten_dirs = true, folder_statuses = "only_folded", -- One of 'never', 'only_folded' or 'always'. }, }, default_args = { DiffviewOpen = {}, DiffviewFileHistory = {}, }, hooks = {}, key_bindings = { disable_defaults = false, view = { ["<tab>"] = cb "select_next_entry", ["<s-tab>"] = cb "select_prev_entry", ["gf"] = cb "goto_file_edit", ["<C-w><C-f>"] = cb "goto_file_split", ["<C-w>gf"] = cb "goto_file_tab", ["<leader>e"] = cb "focus_files", ["<leader>b"] = cb "toggle_files", }, file_panel = { ["j"] = cb "next_entry", ["<down>"] = cb "next_entry", ["k"] = cb "prev_entry", ["<up>"] = cb "prev_entry", ["<cr>"] = cb "focus_entry", ["o"] = cb "select_entry", ["<2-LeftMouse>"] = cb "select_entry", ["-"] = cb "toggle_stage_entry", ["s"] = cb "toggle_stage_entry", ["S"] = cb "stage_all", ["U"] = cb "unstage_all", ["R"] = cb "refresh_files", ["<tab>"] = cb "select_next_entry", ["<s-tab>"] = cb "select_prev_entry", ["gf"] = cb "goto_file_edit", ["<C-w><C-f>"] = cb "goto_file_split", ["<C-w>gf"] = cb "goto_file_tab", ["<leader>e"] = cb "focus_files", ["<leader>b"] = cb "toggle_files", }, file_history_panel = { ["g!"] = cb "options", -- Open the option panel ["<C-A-d>"] = cb "open_in_diffview", -- Open the entry under the cursor in a diffview ["y"] = cb "copy_hash", -- Copy the commit hash of the entry under the cursor ["zR"] = cb "open_all_folds", ["zM"] = cb "close_all_folds", ["j"] = cb "next_entry", ["<down>"] = cb "next_entry", ["k"] = cb "prev_entry", ["<up>"] = cb "prev_entry", ["<cr>"] = cb "focus_entry", ["o"] = cb "select_entry", ["<2-LeftMouse>"] = cb "select_entry", ["<tab>"] = cb "select_next_entry", ["<s-tab>"] = cb "select_prev_entry", ["gf"] = cb "goto_file_edit", ["<C-w><C-f>"] = cb "goto_file_split", ["<C-w>gf"] = cb "goto_file_tab", ["<leader>e"] = cb "focus_files", ["<leader>b"] = cb "toggle_files", }, option_panel = { ["<tab>"] = cb "select", ["q"] = cb "close", }, }, } _G.Config.diffview = M end
-- @file cache_lua_libs.lua Some Lua globals cached as locals -- This file is part of Godot Lua PluginScript: https://github.com/gilzoide/godot-lua-pluginscript -- -- Copyright (C) 2021 Gil Barbosa Reis. -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the “Software”), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -- sell copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING -- FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS -- IN THE SOFTWARE. -- Lua globals local assert, getmetatable, ipairs, pairs, rawget, select, setmetatable, tonumber, tostring, type = assert, getmetatable, ipairs, pairs, rawget, select, setmetatable, tonumber, tostring, type -- Lua globals with fallback for 5.1 local loadstring = loadstring or load table.unpack = table.unpack or unpack table.pack = table.pack or function(...) return { ..., n = select('#', ...) } end -- Bitwise operations for LuaJIT or 5.2 or 5.3+ operators local bor = bit.bor or bit32.bor or load[[function(a,b)return a|b end]] -- Lua library functions local coroutine_resume, coroutine_running, coroutine_status, coroutine_yield = coroutine.resume, coroutine.running, coroutine.status, coroutine.yield local debug_getinfo, debug_traceback = debug.getinfo, debug.traceback local package_loadlib = package.loadlib local string_byte, string_find, string_format, string_gmatch, string_gsub, string_lower, string_match, string_replace, string_rep, string_reverse, string_sub, string_upper = string.byte, string.find, string.format, string.gmatch, string.gsub, string.lower, string.match, string.replace, string.rep, string.reverse, string.sub, string.upper local table_concat, table_insert, table_remove, table_unpack = table.concat, table.insert, table.remove, table.unpack -- custom globals from `src/language_gdnative.c` local setthreadfunc, touserdata = setthreadfunc, touserdata -- FFI local ffi_cast, ffi_copy, ffi_gc, ffi_istype, ffi_metatype, ffi_new, ffi_sizeof, ffi_string, ffi_typeof = ffi.cast, ffi.copy, ffi.gc, ffi.istype, ffi.metatype, ffi.new, ffi.sizeof, ffi.string, ffi.typeof -- Weak tables local weak_k = { __mode = 'k' } -- Some useful patterns local ERROR_LINE_MESSAGE_PATT = ':(%d+):%s*(.*)' local ERROR_PATH_LINE_MESSAGE_PATT = '"([^"]+)"[^:]*:(%d*):%s*(.*)' -- Some useful functions local function string_quote(s) return string_format('%q', s) end
------------------------------------------------------------------------------- -- Module Declaration -- local mod, CL = BigWigs:NewBoss("Zanzil", 859, 184) if not mod then return end mod:RegisterEnableMob(52053) --mod.engageId = 1181 -- no boss frames, also he consistently fires ENCOUNTER_END when his Graveyard Gas ends, without despawning --mod.respawnTime = 30 ------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { 96914, -- Zanzili Fire {96316, "ICON", "FLASH"}, -- Zanzil's (Blue) Resurrection Elixir 96338, -- Zanzil's Graveyard Gas } end function mod:OnBossEnable() self:Log("SPELL_CAST_START", "ZanziliFire", 96914) self:Log("SPELL_AURA_APPLIED", "BlueResurrectionElixir", 96316) self:Log("SPELL_CAST_START", "PursuitCastStart", 96342) self:Log("SPELL_CAST_SUCCESS", "PursuitCastSuccess", 96342) self:Log("SPELL_AURA_REMOVED", "PursuitRemoved", 96306) -- this is applied to the mob, there are no SPELL_AURA_* events for the debuff his target gets self:Death("AddDied", 52054) self:Log("SPELL_AURA_APPLIED", "GraveyardGasCast", 96338) self:Log("SPELL_AURA_REMOVED", "GraveyardGasCastOver", 96338) self:RegisterEvent("PLAYER_REGEN_DISABLED", "CheckForEngage") self:Death("Win", 52053) end function mod:OnEngage() self:RegisterEvent("PLAYER_REGEN_ENABLED", "CheckForWipe") end ------------------------------------------------------------------------------- -- Event Handlers -- function mod:ZanziliFire(args) self:Message(args.spellId, "yellow", "Info", CL.casting:format(args.spellName)) end function mod:BlueResurrectionElixir(args) self:Message(args.spellId, "yellow", "Alert") end function mod:GraveyardGasCast(args) self:Message(args.spellId, "yellow", "Alert", CL.casting:format(args.spellName)) self:CastBar(args.spellId, 7) end function mod:GraveyardGasCastOver(args) self:Bar(args.spellId, 12) -- duration end do local targetFound, scheduled = nil, nil local function printTarget(self, player, guid) targetFound = true if self:Me(guid) then self:Flash(96316, 96342) end self:TargetMessage(96316, player, "red", "Alert", 96342) self:PrimaryIcon(96316, player) end function mod:PursuitCastStart(args) scheduled = self:ScheduleTimer("GetUnitTarget", 0.1, printTarget, 0.4, args.sourceGUID) -- the add recasts this the same moment he dies, I don't have a better idea end function mod:PursuitCastSuccess(args) if not targetFound then if self:Me(args.destGUID) then self:Flash(96316, args.spellId) end self:TargetMessage(96316, args.destName, "red", "Alert", args.spellId) self:PrimaryIcon(96316, args.destName) else targetFound = nil end end function mod:PursuitRemoved() self:PrimaryIcon(96316) end function mod:AddDied() if scheduled then self:CancelTimer(scheduled) end end end
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local item_thread = os.getenv('item_thread') local downloaded = {} local addedtolist = {} local replyids = {} for ignore in io.open("ignore-list", "r"):lines() do downloaded[ignore] = true end read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if downloaded[url] ~= true and addedtolist[url] ~= true then if (string.match(url, "^https?://[^/]*"..item_value) and ((item_type == "10threads" and string.match(url, "[^0-9]"..item_thread.."[0-9]") and not string.match(url, "[^0-9]"..item_thread.."[0-9][0-9]")) or (item_type == "thread" and string.match(url, "[^0-9]"..item_thread) and not string.match(url, "[^0-9]"..item_thread.."[0-9]")))) or html == 0 then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil downloaded[url] = true local function check(urla, origurl) local url = string.match(urla, "^([^#]+)") if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "^https?://[^/]*"..item_value) and ((item_type == "10threads" and string.match(url, "[^0-9]"..item_thread.."[0-9]") and not string.match(url, "[^0-9]"..item_thread.."[0-9][0-9]")) or (item_type == "thread" and string.match(url, "[^0-9]"..item_thread) and not string.match(url, "[^0-9]"..item_thread.."[0-9]")) or string.match(url, "https?://[^/]+/forum/[^/]+/id/") or string.match(url, "https?://[^/]+/s?reply/"))) or string.match(url, "^https?://[^/]*amazonaws%.com") or string.match(url, "^https?://[^/]*images%.yuku%.com")) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end local function checknewurl(newurl) if string.match(newurl, "^https?://") then check(newurl, url) elseif string.match(newurl, "^//") then check("http:"..newurl, url) elseif string.match(newurl, "^/") then check(string.match(url, "^(https?://[^/]+)")..newurl, url) elseif string.match(newurl, "^"..item_value.."%.yuku%.com") then check("http://"..newurl, url) end end if string.match(url, "^https?://[^/]*"..item_value) and ((item_type == "10threads" and string.match(url, "[^0-9]"..item_thread.."[0-9]") and not string.match(url, "[^0-9]"..item_thread.."[0-9][0-9]")) or (item_type == "thread" and string.match(url, "[^0-9]"..item_thread) and not string.match(url, "[^0-9]"..item_thread.."[0-9]")) or string.match(url, "https?://[^/]+/forum/[^/]+/id/") or string.match(url, "https?://[^/]+/s?reply/")) then html = read_file(file) for newurl in string.gmatch(html, '([^"]+)') do checknewurl(newurl) end for newurl in string.gmatch(html, "([^']+)") do checknewurl(newurl) end for newurl in string.gmatch(html, ">([^<]+)") do checknewurl(newurl) end if string.match(url, "%?") then check(string.match(url, "^(https?://[^%?]+)%?")) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() local function check_loop(part_) for part in part_ do part = string.gsub(part, '(['..("%^$().[]*+-?"):gsub("(.)", "%%%1")..'])', "%%%1") if string.find(url["url"], "/"..part.."/"..part.."/"..part.."/") or string.find(url["url"], "%%"..part.."%%"..part.."%%"..part.."%%") then return wget.actions.EXIT end end end if downloaded[url["url"]] == true and status_code >= 200 and status_code < 400 then return wget.actions.EXIT end if (status_code >= 200 and status_code < 400) then downloaded[url["url"]] = true end check_loop(string.gmatch(url["url"], "([^/]*)")) check_loop(string.gmatch(url["url"], "([^/]+/[^/]*)")) check_loop(string.gmatch(url["url"], "([^%%]*)")) check_loop(string.gmatch(url["url"], "([^%%]+%%[^%%]*)")) if string.match(url["url"], "^https?://[^/]+/forum/previous/topic/") or string.match(url["url"], "^https?://[^/]+/forum/next/topic/") then return wget.actions.EXIT end if status_code == 301 and (string.match(url["url"], "^https?://[^%.]+%.yuku%.com/forum/.....reply/id/[0-9]+")) then return wget.actions.EXIT end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 if string.match(url["url"], "^https?://[^/]*"..item_value) then return wget.actions.ABORT else return wget.actions.EXIT end else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 if string.match(url["url"], "^https?://[^/]*"..item_value) then return wget.actions.ABORT else return wget.actions.EXIT end else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
test_run = require('test_run').new() fiber = require 'fiber' fio = require 'fio' xlog = require 'xlog' s = box.schema.space.create('test', {engine='vinyl'}) _ = s:create_index('pk') -- Start a few fibers populating the space in the background. n_workers = 3 c = fiber.channel(n_workers) test_run:cmd("setopt delimiter ';'") for i=1,n_workers do fiber.create(function() for j=i,1000,n_workers do s:insert{j} end c:put(true) end) end test_run:cmd("setopt delimiter ''"); -- Let the background fibers run. fiber.sleep(0.001) -- Concurrent checkpoint. box.snapshot() -- Join background fibers. for i=1,n_workers do c:get() end -- Get list of files from the last checkpoint. files = box.backup.start() -- Extract the last checkpoint LSN and find -- max LSN stored in run files. snap_lsn = -1 run_lsn = -1 test_run:cmd("setopt delimiter ';'") for _, path in ipairs(files) do suffix = string.gsub(path, '.*%.', '') if suffix == 'snap' then snap_lsn = tonumber(fio.basename(path, '.snap')) end if suffix == 'run' then for lsn, _ in xlog.pairs(path) do if run_lsn < lsn then run_lsn = lsn end end end end test_run:cmd("setopt delimiter ''"); snap_lsn >= 0 run_lsn >= 0 box.backup.stop() -- Check that run files only contain statements -- inserted before checkpoint. snap_lsn == run_lsn or {snap_lsn, run_lsn} s:drop() -- -- gh-2614 about broken vy_run_iterator_start_from. -- s = box.schema.space.create('test', {engine = 'vinyl'}) p = s:create_index('pk') s:replace{100} s:replace{101} s:replace{102} s:replace{103} box.snapshot() s:select({99}, {iterator = box.index.LE, limit = 10}) s:drop()
-- Global ban modul for ULX --by Andrew Mensky! local CATEGORY_NAME = "Utility"; -- Simple convert from ulx to ugb bans. local function Convert( calling_ply ) if not ULib.fileExists( ULib.BANS_FILE ) then return ulx.fancyLogAdmin( calling_ply, "Nothing to convert" ); end; local bans, err = ULib.parseKeyValues( ULib.fileRead( ULib.BANS_FILE ) ); if ( err ) then return ulx.fancyLogAdmin( calling_ply, err ); end; local os_time = os.time(); local c_fine = 0; local c_err = 0; for k, v in pairs( bans ) do if type( v ) == "table" and type( k ) == "string" then local time = ( v.unban - os_time ) / 60; if ( time > 0 or math.floor( v.unban ) == 0 ) then -- We floor it because GM10 has floating point errors that might make it be 0.1e-20 or something dumb. -- Create fake admin :) local admin = {}; local name, sid = UGB:NameIDSplit( v.admin ); function admin:IsValid() return name and sid and name != "(Console)"; end; function admin:Name() return name; end; function admin:Nick() return name; end; function admin:SteamID() return sid; end; -- Convert ban ULib.addBan( k, time, v.reason, v.name, admin ); c_fine = c_fine + 1; end; else ulx.fancyLogAdmin( calling_ply, "Warning: Bad ban data is being ignored, key = " .. tostring( k ) .. "\n" ); c_err = c_err + 1; end; end; ulx.fancyLogAdmin( calling_ply, "Converted bans: #s, Errors: #s.", tostring(c_fine), tostring(c_err) ); end; local cmd = ulx.command( CATEGORY_NAME, "ugb convert_ulx", Convert ); cmd:defaultAccess( ULib.ACCESS_SUPERADMIN ); cmd:help( "Convert from ulx bans to ugb" ); -- Convert from bcool1 global bans to ugb. local forewarned = false; local function Convert2( calling_ply ) local tableName = UDB:Prefixer( UGB_TABLE ); local queryObj = UDB:Select( "bans" ); queryObj:SetCallback( function( result ) if not UDB:IsResult( result ) then return ULib.tsayError( calling_ply, "There is nothing to convert." ); end; local count = #result; for i=1, count do local queryObj = UDB:Select( tableName ); queryObj:AddWhere( "_SteamID = ?", result[i]["OSteamID"] ); queryObj:AddWhere( "_Cluster = ?", UGB_CLUSTER ); queryObj:SetCallback( function( result2 ) local bExists = UDB:IsResult( result2 ); local queryObj = bExists and UDB:Update( tableName ) or UDB:Insert( tableName ); if ( bExists ) then queryObj:AddWhere( "_SteamID = ?", result[i]["OSteamID"] ); queryObj:AddWhere( "_Cluster = ?", UGB_CLUSTER ); else queryObj:SetValue( "_SteamID", result[i]["OSteamID"] ); queryObj:SetValue( "_Cluster", UGB_CLUSTER ); end; queryObj:SetValue( "_SteamID", result[i]["OSteamID"] ); queryObj:SetValue( "_Cluster", UGB_CLUSTER ); queryObj:SetValue( "_SteamName", result[i]["OName"], true ); queryObj:SetValue( "_Length", result[i]["Length"], true ); queryObj:SetValue( "_Time", result[i]["Time"], true ); queryObj:SetValue( "_ASteamName", result[i]["AName"], true ); queryObj:SetValue( "_ASteamID", result[i]["ASteamID"], true ); queryObj:SetValue( "_Reason", result[i]["Reason"] ); queryObj:SetValue( "_ServerID", UDB_SERVERID ); queryObj:SetValue( "_MSteamName", result[i]["MAdmin"], true ); queryObj:SetValue( "_MTime", result[i]["MTime"], true ); if ( i == count ) then queryObj:SetCallback( function() ULib.queueFunctionCall( function() ULib.refreshBans(); ulx.fancyLogAdmin( calling_ply, "Imported "..count.." bcool bans.\n" ); end); end); end; queryObj:Push(); end); queryObj:Pull(); end; end); queryObj:Pull(); end; local cmd = ulx.command( CATEGORY_NAME, "ugb convert_bcool", Convert2 ); cmd:defaultAccess( ULib.ACCESS_SUPERADMIN ); cmd:help( "Convert bcool bans to ugb." ); -- Forced refresh. local function Refresh( calling_ply ) ULib.refreshBans() end; local cmd = ulx.command( CATEGORY_NAME, "ugb refresh", Refresh ); cmd:defaultAccess( ULib.ACCESS_SUPERADMIN ); cmd:help( "Convert ulx bans to global bans." );
local luadev_inspect = require'luadev.inspect' local a = vim.api if _G._luadev_mod == nil then _G._luadev_mod = {execount = 0} end local s = _G._luadev_mod local function create_buf() if s.buf ~= nil then return end local buf = a.nvim_create_buf(true,true) a.nvim_buf_set_name(buf, "[nvim-lua]") s.buf = buf end local function open_win() if s.win and a.nvim_win_is_valid(s.win) and a.nvim_win_get_buf(s.win) == s.buf then return end create_buf() local w0 = a.nvim_get_current_win() a.nvim_command("new") local w = a.nvim_get_current_win() a.nvim_win_set_buf(w,s.buf) a.nvim_set_current_win(w0) s.win = w end local function dosplit(str, delimiter) local result = { } local from = 1 local delim_from, delim_to = string.find( str, delimiter, from ) while delim_from do table.insert( result, string.sub( str, from , delim_from-1 ) ) from = delim_to + 1 delim_from, delim_to = string.find( str, delimiter, from ) end table.insert( result, string.sub( str, from ) ) return result end local function splitlines(str) return vim.split(str, "\n", true) end local function append_buf(lines, hl) if s.buf == nil then create_buf() end local l0 = a.nvim_buf_line_count(s.buf) if type(lines) == type("") then lines = splitlines(lines) end a.nvim_buf_set_lines(s.buf, l0, l0, true, lines) local l1 = a.nvim_buf_line_count(s.buf) if hl ~= nil then for i = l0, l1-1 do a.nvim_buf_add_highlight(s.buf, -1, hl, i, 0, -1) end end local curwin = a.nvim_get_current_win() for _,win in ipairs(a.nvim_list_wins()) do if a.nvim_win_get_buf(win) == s.buf and win ~= curwin then a.nvim_win_set_cursor(win, {l1, 1e9}) end end return l0 end local function luadev_print(...) local strs = {} local args = {...} for i = 1,select('#', ...) do strs[i] = tostring(args[i]) end append_buf(table.concat(strs, ' ')) end local function dedent(str, leave_indent) -- find minimum common indent across lines local indent = nil for line in str:gmatch('[^\n]+') do local line_indent = line:match('^%s+') or '' if indent == nil or #line_indent < #indent then indent = line_indent end end if indent == nil or #indent == 0 then -- no minimum common indent return str end local left_indent = (' '):rep(leave_indent or 0) -- create a pattern for the indent indent = indent:gsub('%s', '[ \t]') -- strip it from the first line str = str:gsub('^'..indent, left_indent) -- strip it from the remaining lines str = str:gsub('[\n]'..indent, '\n' .. left_indent) return str end local function ld_pcall(chunk, ...) local coro = coroutine.create(chunk) local res = {coroutine.resume(coro, ...)} if not res[1] then _G._errstack = coro -- if the only frame on the traceback is the chunk itself, skip the traceback if debug.getinfo(coro, 0,"f").func ~= chunk then res[2] = debug.traceback(coro, res[2], 0) end end return unpack(res) end local function default_reader(str, count) local name = "@[luadev "..count.."]" local chunk, err = loadstring("return \n"..str, name) if chunk == nil then chunk, err = loadstring(str, name) end return chunk, err end local function exec(str) local count = s.execount + 1 s.execount = count local reader = s.reader or default_reader local chunk, err = reader(str, count) local inlines = splitlines(dedent(str)) if inlines[#inlines] == "" then inlines[#inlines] = nil end firstmark = tostring(count)..">" contmark = string.rep(".", string.len(firstmark)) for i,l in ipairs(inlines) do local marker = ((i == 1) and firstmark) or contmark inlines[i] = marker.." "..l end local start = append_buf(inlines) for i,_ in ipairs(inlines) do a.nvim_buf_add_highlight(s.buf, -1, "Question", start+i-1, 0, 2) end if chunk == nil then append_buf(err,"WarningMsg") else local oldprint = _G.print _G.print = luadev_print local st, res = ld_pcall(chunk) _G.print = oldprint if st == false then append_buf(res,"WarningMsg") elseif doeval or res ~= nil then append_buf(luadev_inspect(res)) end end append_buf({""}) end local function start() open_win() end local function err_wrap(cb) return (function (...) local res = {ld_pcall(cb, ...)} if not res[1] then open_win() append_buf(res[2],"WarningMsg") return nil else table.remove(res, 1) return unpack(res) end end) end local function schedule_wrap(cb) return vim.schedule_wrap(err_wrap(cb)) end local funcs = { create_buf=create_buf, start=start, exec=exec, print=luadev_print, append_buf=append_buf, err_wrap = err_wrap, schedule_wrap = schedule_wrap, } -- TODO: export abstraction for autoreload for k,v in pairs(funcs) do s[k] = v end return s
solution "Engine" configurations {"debug", "release"} language ("c++") platforms {"x64"} location ("build") debugdir ("build") targetdir ("bin") flags {"ExtraWarnings"} project ("engine") kind ("ConsoleApp") includedirs {"include", "src/deps/glfw"} files {"src/*.cpp", "src/*.h", "include/**.h", "src/deps/glfw/context.c", "src/deps/glfw/init.c", "src/deps/glfw/input.c", "src/deps/glfw/monitor.c", "src/deps/glfw/window.c", "src/deps/glfw/vulkan.c", "src/deps/glfw/osmesa_context.c" } -- defines {} vpaths{ ["Headers"] = "include/*.h", ["Source"] = "src/*.cpp", ["Dependency Headers"] = { "include/dxc/*", "include/glfw/*", "include/glm/**", "include/glslang/**", "include/shaderc/*", "include/spirv_cross/*", "include/spirv-headers/*", "include/spirv-tools/*", "include/vk_video/*", "include/vulkan/*" }, ["Dependency Source"] = { "src/deps/glfw/**" }, } configuration {"debug"} flags {"Symbols"} targetsuffix ("_d") configuration {"release"} flags {"Optimize"} targetsuffix ("_r") configuration {"windows"} libdirs {"lib/vulkan"} files {"src/deps/glfw/egl_context.c", "src/deps/glfw/win32*", "src/deps/glfw/wgl_*", "src/deps/glfw/winmm_*"} links {"vulkan-1"} defines {"_GLFW_WIN32", "_GLFW_WGL"} flags {"NoEditAndContinue"} windowstargetplatformversion "10.0.18362.0"
if GetBot():IsInvulnerable() or not GetBot():IsHero() or not string.find(GetBot():GetUnitName(), "hero") or GetBot():IsIllusion() then return; end local ability_item_usage_generic = dofile( GetScriptDirectory().."/ability_item_usage_generic" ) local utils = require(GetScriptDirectory() .. "/util") local mutil = require(GetScriptDirectory() .. "/MyUtility") function AbilityLevelUpThink() ability_item_usage_generic.AbilityLevelUpThink(); end function BuybackUsageThink() ability_item_usage_generic.BuybackUsageThink(); end function CourierUsageThink() ability_item_usage_generic.CourierUsageThink(); end function ItemUsageThink() ability_item_usage_generic.ItemUsageThink() end local castESDesire = 0; local castOPDesire = 0; local castERDesire = 0; local abilityES = nil; local abilityOP = nil; local abilityER = nil; local npcBot = nil; function AbilityUsageThink() if npcBot == nil then npcBot = GetBot(); end -- Check if we're already using an ability if mutil.CanNotUseAbility(npcBot) then return end if abilityES == nil then abilityES = npcBot:GetAbilityByName( "ursa_earthshock" ) end if abilityOP == nil then abilityOP = npcBot:GetAbilityByName( "ursa_overpower" ) end if abilityER == nil then abilityER = npcBot:GetAbilityByName( "ursa_enrage" ) end -- Consider using each ability castESDesire = ConsiderEarthshock(); castOPDesire = ConsiderOverpower(); castERDesire = ConsiderEnrage(); if ( castERDesire > castESDesire and castERDesire > castESDesire ) then npcBot:Action_UseAbility( abilityER ); return; end if ( castESDesire > 0 ) then npcBot:Action_UseAbility( abilityES ); return; end if ( castOPDesire > 0 ) then npcBot:Action_UseAbility( abilityOP ); return; end end function ConsiderEarthshock() -- Make sure it's castable if ( not abilityES:IsFullyCastable() ) then return BOT_ACTION_DESIRE_NONE; end -- Get some of its values local nRadius = abilityES:GetSpecialValueInt( "shock_radius" ); local nCastRange = 0; local nDamage = abilityES:GetAbilityDamage(); -------------------------------------- -- Mode based usage -------------------------------------- -- If we're seriously retreating, see if we can land a stun on someone who's damaged us recently if mutil.IsRetreating(npcBot) then local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( nRadius, true, BOT_MODE_NONE ); for _,npcEnemy in pairs( tableNearbyEnemyHeroes ) do if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) and mutil.CanCastOnNonMagicImmune(npcEnemy) ) then return BOT_ACTION_DESIRE_MODERATE; end end end -- If we're going after someone if mutil.IsGoingOnSomeone(npcBot) then local npcTarget = npcBot:GetTarget(); if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnNonMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, nRadius - 150) then return BOT_ACTION_DESIRE_MODERATE; end end return BOT_ACTION_DESIRE_NONE; end function ConsiderOverpower() -- Make sure it's castable if ( not abilityOP:IsFullyCastable() ) then return BOT_ACTION_DESIRE_NONE; end -- If we're pushing a lane if mutil.IsPushing(npcBot) and npcBot:GetMana() / npcBot:GetMaxMana() >= 0.65 then local tableNearbyEnemyTowers = npcBot:GetNearbyTowers( 800, true ); if tableNearbyEnemyTowers ~= nil and #tableNearbyEnemyTowers >= 1 and tableNearbyEnemyTowers[1] ~= nil and mutil.IsInRange(tableNearbyEnemyTowers[1], npcBot, 300) then return BOT_ACTION_DESIRE_MODERATE; end end if npcBot:GetActiveMode() == BOT_MODE_FARM then local npcTarget = npcBot:GetAttackTarget(); if npcTarget ~= nil then return BOT_ACTION_DESIRE_LOW; end end if ( npcBot:GetActiveMode() == BOT_MODE_ROSHAN ) then local npcTarget = npcBot:GetAttackTarget(); if ( mutil.IsRoshan(npcTarget) and mutil.CanCastOnMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, 300) ) then return BOT_ACTION_DESIRE_LOW; end end -- If we're going after someone if mutil.IsGoingOnSomeone(npcBot) then local npcTarget = npcBot:GetTarget(); if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, 400) then return BOT_ACTION_DESIRE_MODERATE; end end return BOT_ACTION_DESIRE_NONE; end function ConsiderEnrage() -- Make sure it's castable if ( not abilityER:IsFullyCastable() ) then return BOT_ACTION_DESIRE_NONE; end -- If we're seriously retreating, see if we can land a stun on someone who's damaged us recently if mutil.IsRetreating(npcBot) then local tableNearbyEnemyHeroes = npcBot:GetNearbyHeroes( 800, true, BOT_MODE_NONE ); for _,npcEnemy in pairs( tableNearbyEnemyHeroes ) do if ( npcBot:WasRecentlyDamagedByHero( npcEnemy, 2.0 ) ) then return BOT_ACTION_DESIRE_MODERATE; end end end if npcBot:GetActiveMode() == BOT_MODE_FARM and npcBot:GetHealth()/npcBot:GetMaxHealth() < 0.20 then local npcTarget = npcBot:GetAttackTarget(); if npcTarget ~= nil then return BOT_ACTION_DESIRE_LOW; end end if ( npcBot:GetActiveMode() == BOT_MODE_ROSHAN ) then local npcTarget = npcBot:GetAttackTarget(); if ( mutil.IsRoshan(npcTarget) and mutil.CanCastOnMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, 300) ) then return BOT_ACTION_DESIRE_LOW; end end -- If we're going after someone if mutil.IsGoingOnSomeone(npcBot) then local npcTarget = npcBot:GetTarget(); if mutil.IsValidTarget(npcTarget) and mutil.CanCastOnMagicImmune(npcTarget) and mutil.IsInRange(npcTarget, npcBot, 300) then return BOT_ACTION_DESIRE_MODERATE; end end return BOT_ACTION_DESIRE_NONE; end
----------------------------------- -- Ability: Reverse Flourish -- Converts remaining finishing moves into TP. Requires at least one Finishing Move. -- Obtained: Dancer Level 40 -- Finishing Moves Used: 1-5 -- Recast Time: 00:30 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_1)) then return 0,0 elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_2)) then return 0,0 elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_3)) then return 0,0 elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_4)) then return 0,0 elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_5)) then return 0,0 else return tpz.msg.basic.NO_FINISHINGMOVES,0 end end function onUseAbility(player,target,ability) local TPGain = 0 local STM = 0.5 + (0.1 * player:getMod(tpz.mod.REVERSE_FLOURISH_EFFECT)) local Merits = player:getMerit(tpz.merit.REVERSE_FLOURISH_EFFECT) if (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_1)) then TPGain = 9.5 * 1 + STM * 1 ^ 2 + Merits elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_2)) then TPGain = 9.5 * 2 + STM * 2 ^ 2 + Merits elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_3)) then TPGain = 9.5 * 3 + STM * 3 ^ 2 + Merits elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_4)) then TPGain = 9.5 * 4 + STM * 4 ^ 2 + Merits elseif (player:hasStatusEffect(tpz.effect.FINISHING_MOVE_5)) then TPGain = 9.5 * 5 + STM * 5 ^ 2 + Merits end TPGain = TPGain * 10 player:addTP(TPGain) player:delStatusEffect(tpz.effect.FINISHING_MOVE_1) player:delStatusEffect(tpz.effect.FINISHING_MOVE_2) player:delStatusEffect(tpz.effect.FINISHING_MOVE_3) player:delStatusEffect(tpz.effect.FINISHING_MOVE_4) player:delStatusEffect(tpz.effect.FINISHING_MOVE_5) return TPGain end
-- AUDIO function playSfx(xbool) local sound local channel if xbool then sound = Sound.new("audio/selecton.wav") channel = sound:play() channel:setVolume(0.25) else sound = Sound.new("audio/selectoff.wav") channel = sound:play() channel:setVolume(0.75) end end -- scene manager scenemanager = SceneManager.new( { ["menu"] = Menu, ["levels"] = Levels, } ) stage:addChild(scenemanager) scenemanager:changeScene("menu") --scenemanager:changeScene("levels")
local lsp = vim.lsp local api = vim.api local all_diag = lsp.diagnostic.get_all() vim.cmd [[ 10new ]] vim.cmd [[ hi StuffWarning gui=bold guifg=#d79921 ]] local result_bufnr = api.nvim_get_current_buf() local ns = api.nvim_create_namespace("stuff") api.nvim_buf_set_keymap(result_bufnr, "n", "<C-c>", "<CMD>bd!<CR>", { silent = true }) api.nvim_buf_set_keymap(result_bufnr, "n", "q", "<CMD>bd!<CR>", { silent = true }) local i = 0 for bufnr, diag in pairs(all_diag) do if #diag ~= 0 then local filename = vim.fn.fnamemodify(api.nvim_buf_get_name(bufnr), ":t") local icon, hl_group = require("nvim-web-devicons").get_icon(filename, vim.fn.fnamemodify(filename, ":e"), { default = true }) P(i) api.nvim_buf_set_lines(0, i, -1, false, {icon.." "..filename}) api.nvim_buf_add_highlight(result_bufnr, ns, hl_group, i, 0, 3) -- api.nvim_buf_add_highlight(result_bufnr, ns, "StuffFilename", i, 3, -1) for k, v in ipairs(diag) do i = i + k + 1 api.nvim_buf_set_lines(0, i, -1, false, { string.format("  [%s] %s", v.code, v.message) }) api.nvim_buf_add_highlight( result_bufnr, ns, "StuffWarning", k + i - 2, 5, #v.code + 9 ) end end end api.nvim_buf_set_option(result_bufnr, "modifiable", false)
Locales['en'] = { ['valid_purchase'] = 'Cela vous coûtera 250$?', ['yes'] = 'Oui', ['no'] = 'Non', ['press_access'] = 'Appuyez sur ~INPUT_CONTEXT~ pour faire de la ~r~Chirurgie', ['not_enough_money'] = 'Vous n\'avez pas assez d\'argent !', ['you_paid'] = 'Vous avez payé $%s', ['blip_plastic_surgery'] = 'Chirurgie', }
module 'mock' -------------------------------------------------------------------- CLASS: EditorEntity ( mock.Entity ) function EditorEntity:__init() self.layer = '_GII_EDITOR_LAYER' self.FLAG_EDITOR_OBJECT = true end -------------------------------------------------------------------- CLASS: ComponentPreviewer () :MODEL{} function ComponentPreviewer:onStart() end function ComponentPreviewer:onUpdate( dt ) end function ComponentPreviewer:onDestroy() end function ComponentPreviewer:onReset() --?? end -------------------------------------------------------------------- function resetFieldDefaultValue( obj, fid ) local model = Model.fromObject( obj ) if not model then return false end local field = model:getField( fid ) if not field then return false end field:resetDefaultValue( obj ) return true end
local core = require('cmp.core') local source = require('cmp.source') local config = require('cmp.config') local feedkeys = require('cmp.utils.feedkeys') local autocmd = require('cmp.utils.autocmd') local keymap = require('cmp.utils.keymap') local misc = require('cmp.utils.misc') local cmp = {} cmp.core = core.new() ---Expose types for k, v in pairs(require('cmp.types.cmp')) do cmp[k] = v end cmp.lsp = require('cmp.types.lsp') cmp.vim = require('cmp.types.vim') ---Expose event cmp.event = cmp.core.event ---Export mapping for special case cmp.mapping = require('cmp.config.mapping') ---Export default config presets cmp.config = {} cmp.config.disable = misc.none cmp.config.compare = require('cmp.config.compare') cmp.config.sources = require('cmp.config.sources') cmp.config.mapping = require('cmp.config.mapping') ---Sync asynchronous process. cmp.sync = function(callback) return function(...) cmp.core.filter:sync(1000) if callback then return callback(...) end end end ---Suspend completion. cmp.suspend = function() return cmp.core:suspend() end ---Register completion sources ---@param name string ---@param s cmp.Source ---@return number cmp.register_source = function(name, s) local src = source.new(name, s) cmp.core:register_source(src) return src.id end ---Unregister completion source ---@param id number cmp.unregister_source = function(id) cmp.core:unregister_source(id) end ---Get current configuration. ---@return cmp.ConfigSchema cmp.get_config = function() return require('cmp.config').get() end ---Invoke completion manually ---@param option cmp.CompleteParams cmp.complete = cmp.sync(function(option) option = option or {} config.set_onetime(option.config) cmp.core:complete(cmp.core:get_context({ reason = option.reason or cmp.ContextReason.Manual })) return true end) ---Complete common string in current entries. cmp.complete_common_string = cmp.sync(function() return cmp.core:complete_common_string() end) ---Return view is visible or not. cmp.visible = cmp.sync(function() return cmp.core.view:visible() or vim.fn.pumvisible() == 1 end) ---Get current selected entry or nil cmp.get_selected_entry = cmp.sync(function() return cmp.core.view:get_selected_entry() end) ---Get current active entry or nil cmp.get_active_entry = cmp.sync(function() return cmp.core.view:get_active_entry() end) ---Get current all entries cmp.get_entries = cmp.sync(function() return cmp.core.view:get_entries() end) ---Close current completion cmp.close = cmp.sync(function() if cmp.core.view:visible() then local release = cmp.core:suspend() cmp.core.view:close() cmp.core:reset() vim.schedule(release) return true else return false end end) ---Abort current completion cmp.abort = cmp.sync(function() if cmp.core.view:visible() then local release = cmp.core:suspend() cmp.core.view:abort() vim.schedule(release) return true else return false end end) ---Select next item if possible cmp.select_next_item = cmp.sync(function(option) option = option or {} if cmp.core.view:visible() then local release = cmp.core:suspend() cmp.core.view:select_next_item(option) vim.schedule(release) return true elseif vim.fn.pumvisible() == 1 then -- Special handling for native pum. Required to facilitate key mapping processing. if (option.behavior or cmp.SelectBehavior.Insert) == cmp.SelectBehavior.Insert then feedkeys.call(keymap.t('<C-n>'), 'in') else feedkeys.call(keymap.t('<Down>'), 'in') end return true end return false end) ---Select prev item if possible cmp.select_prev_item = cmp.sync(function(option) option = option or {} if cmp.core.view:visible() then local release = cmp.core:suspend() cmp.core.view:select_prev_item(option) vim.schedule(release) return true elseif vim.fn.pumvisible() == 1 then -- Special handling for native pum. Required to facilitate key mapping processing. if (option.behavior or cmp.SelectBehavior.Insert) == cmp.SelectBehavior.Insert then feedkeys.call(keymap.t('<C-p>'), 'in') else feedkeys.call(keymap.t('<Up>'), 'in') end return true end return false end) ---Scrolling documentation window if possible cmp.scroll_docs = cmp.sync(function(delta) if cmp.core.view:visible() then cmp.core.view:scroll_docs(delta) return true else return false end end) ---Confirm completion cmp.confirm = cmp.sync(function(option, callback) option = option or {} callback = callback or function() end local e = cmp.core.view:get_selected_entry() or (option.select and cmp.core.view:get_first_entry() or nil) if e then cmp.core:confirm(e, { behavior = option.behavior, }, function() callback() cmp.core:complete(cmp.core:get_context({ reason = cmp.ContextReason.TriggerOnly })) end) return true else -- Special handling for native puma. Required to facilitate key mapping processing. if vim.fn.complete_info({ 'selected' }).selected ~= -1 then feedkeys.call(keymap.t('<C-y>'), 'in') return true end return false end end) ---Show status cmp.status = function() local kinds = {} kinds.available = {} kinds.unavailable = {} kinds.installed = {} kinds.invalid = {} local names = {} for _, s in pairs(cmp.core.sources) do names[s.name] = true if config.get_source_config(s.name) then if s:is_available() then table.insert(kinds.available, s:get_debug_name()) else table.insert(kinds.unavailable, s:get_debug_name()) end else table.insert(kinds.installed, s:get_debug_name()) end end for _, s in ipairs(config.get().sources) do if not names[s.name] then table.insert(kinds.invalid, s.name) end end if #kinds.available > 0 then vim.api.nvim_echo({ { '\n', 'Normal' } }, false, {}) vim.api.nvim_echo({ { '# ready source names\n', 'Special' } }, false, {}) for _, name in ipairs(kinds.available) do vim.api.nvim_echo({ { ('- %s\n'):format(name), 'Normal' } }, false, {}) end end if #kinds.unavailable > 0 then vim.api.nvim_echo({ { '\n', 'Normal' } }, false, {}) vim.api.nvim_echo({ { '# unavailable source names\n', 'Comment' } }, false, {}) for _, name in ipairs(kinds.unavailable) do vim.api.nvim_echo({ { ('- %s\n'):format(name), 'Normal' } }, false, {}) end end if #kinds.installed > 0 then vim.api.nvim_echo({ { '\n', 'Normal' } }, false, {}) vim.api.nvim_echo({ { '# unused source names\n', 'WarningMsg' } }, false, {}) for _, name in ipairs(kinds.installed) do vim.api.nvim_echo({ { ('- %s\n'):format(name), 'Normal' } }, false, {}) end end if #kinds.invalid > 0 then vim.api.nvim_echo({ { '\n', 'Normal' } }, false, {}) vim.api.nvim_echo({ { '# unknown source names\n', 'ErrorMsg' } }, false, {}) for _, name in ipairs(kinds.invalid) do vim.api.nvim_echo({ { ('- %s\n'):format(name), 'Normal' } }, false, {}) end end end ---@type cmp.Setup cmp.setup = setmetatable({ global = function(c) config.set_global(c) end, filetype = function(filetype, c) config.set_filetype(c, filetype) end, buffer = function(c) config.set_buffer(c, vim.api.nvim_get_current_buf()) end, cmdline = function(type, c) config.set_cmdline(c, type) end, }, { __call = function(self, c) self.global(c) end, }) autocmd.subscribe('InsertEnter', function() feedkeys.call('', 'i', function() if config.enabled() then cmp.core:prepare() cmp.core:on_change('InsertEnter') end end) end) autocmd.subscribe('InsertLeave', function() cmp.core:reset() cmp.core.view:close() end) autocmd.subscribe('CmdlineEnter', function() if config.enabled() then cmp.core:prepare() cmp.core:on_change('InsertEnter') end end) autocmd.subscribe('CmdlineLeave', function() cmp.core:reset() cmp.core.view:close() end) autocmd.subscribe('TextChanged', function() if config.enabled() then cmp.core:on_change('TextChanged') end end) autocmd.subscribe('CursorMoved', function() if config.enabled() then cmp.core:on_moved() else cmp.core:reset() cmp.core.view:close() end end) autocmd.subscribe('InsertEnter', function() cmp.config.compare.scopes:update() cmp.config.compare.locality:update() end) cmp.event:on('complete_done', function(evt) if evt.entry then cmp.config.compare.recently_used:add_entry(evt.entry) end cmp.config.compare.scopes:update() cmp.config.compare.locality:update() end) cmp.event:on('confirm_done', function(evt) if evt.entry then cmp.config.compare.recently_used:add_entry(evt.entry) end end) return cmp
-- This module contains configuration related to the native language server require("utils") -- AUTOCOMMANDS ------------------------------------------------------------------------------- vim.api.nvim_define_augroup("Lsp", true) -- Show diagnostic information on CursorHold vim.api.nvim_define_autocmd("CursorHold", "<buffer>", "lua vim.lsp.diagnostic.show_line_diagnostics()", "Lsp") -- Format on write vim.api.nvim_define_autocmd("BufWritePre", "<buffer>", "lua vim.lsp.buf.formatting_sync(nil, 200)", "Lsp") -- LANGUAGE SERVER CONFIGURATION -------------------------------------------------------------------------------- local lspconfig = require("lspconfig") local capabilities = require("cmp_nvim_lsp").update_capabilities(vim.lsp.protocol.make_client_capabilities()) -- Rust require("rust-tools").setup { capabilities = capabilities, tools = { autoSetHints = true, hover_with_actions = true, inlay_hints = { show_parameter_hints = false, parameter_hints_prefix = "", other_hints_prefix = "", }, }, server = { settings = { ["rust-analyzer"] = { checkOnSave = { command = "clippy", }, }, }, }, } -- Golang lspconfig.gopls.setup { cmd = { "gopls" }, capabilities = capabilities, filetypes = { "go", "gomod" }, } -- Lua lspconfig.sumneko_lua.setup { cmd = { "/usr/bin/lua-language-server" }, capabilities = capabilities, settings = { Lua = { runtime = { version = "LuaJIT", }, diagnostics = { globals = { "vim" }, }, workspace = { library = vim.api.nvim_get_runtime_file("", true), }, telemetry = { enable = false, }, }, }, } -- Terraform lspconfig.terraformls.setup { cmd = { "terraform-ls", "serve" }, capabilities = capabilities, }
-- colorbuddy.vim -- @author: TJ DeVries -- Inspired HEAVILY by @tweekmonster's colorpal.vim vim.fn = vim.fn or setmetatable({}, { __index = function(t, key) local function _fn(...) return vim.api.nvim_call_function(key, {...}) end t[key] = _fn return _fn end }) local groups = require('colorbuddy.group').groups local colors = require('colorbuddy.color').colors local M = { groups = groups, Group = require('colorbuddy.group').Group, colors = colors, Color = require('colorbuddy.color').Color, styles = require('colorbuddy.style').styles, } --- Exports globals so you can use them in a script. --- Optionally returns them if you'd prefer to use them that way. function M.setup() Color = M.Color c = M.colors colors = M.colors Group = M.Group g = M.groups groups = M.groups s = M.styles styles = M.styles return Color, c, Group, g, s end function M.colorscheme(name, light) local bg if light then bg = 'light' else bg = 'dark' end vim.api.nvim_command('set termguicolors') vim.api.nvim_command(string.format('let g:colors_name = "%s"', name)) vim.api.nvim_command(string.format('set background=%s', bg)) require(name) end return M
local SpellCaster = Class(function(self, inst) self.inst = inst self.spell = nil self.spelltest = nil self.onspellcast = nil self.canusefrominventory = true self.canuseontargets = false self.canuseonpoint = false end) function SpellCaster:SetSpellFn(fn) self.spell = fn end function SpellCaster:SetSpellTestFn(fn) self.spelltest = fn end function SpellCaster:SetOnSpellCastFn(fn) self.onspellcast = fn end function SpellCaster:CastSpell(target, pos) if self.spell then self.spell(self.inst, target, pos) if self.onspellcast then self.onspellcast(self.inst, target, pos) end end end function SpellCaster:CanCast(doer, target, pos) if self.spelltest then return self.spelltest(self.inst, doer, target, pos) and self.spell ~= nil end return self.spell ~= nil end function SpellCaster:CollectInventoryActions(doer, actions) if self:CanCast(doer) and self.canusefrominventory then table.insert(actions, ACTIONS.CASTSPELL) end end function SpellCaster:CollectEquippedActions(doer, target, actions, right) if right and self:CanCast(doer, target) and self.canuseontargets then table.insert(actions, ACTIONS.CASTSPELL) end end function SpellCaster:CollectPointActions(doer, pos, actions, right) if right and self:CanCast(doer, nil, pos) and self.canuseonpoint then table.insert(actions, ACTIONS.CASTSPELL) end end return SpellCaster
-- This config example file is released into the Public Domain. -- This is a generic configuration that is a good starting point for -- real-world projects. Data is split into tables according to geometry type -- and most tags are stored in jsonb columns. -- Set this to the projection you want to use local srid = 3857 local tables = {} tables.points = osm2pgsql.define_node_table('points', { { column = 'id', type = 'int8'}, { column = 'id_type', type = 'text'}, { column = 'power', type = 'text'}, { column = 'tags', type = 'jsonb' }, { column = 'geom', type = 'point', projection = srid }, }) tables.lines = osm2pgsql.define_way_table('lines', { { column = 'id', type = 'int8'}, { column = 'id_type', type = 'text'}, { column = 'power', type = 'text'}, { column = 'tags', type = 'jsonb' }, { column = 'members_nodes', sql_type = 'int8[]'}, { column = 'members_ways', sql_type = 'int8[]'}, { column = 'members_relations', sql_type = 'int8[]'}, { column = 'geom', type = 'linestring', projection = srid }, }) tables.polygons = osm2pgsql.define_area_table('polygons', { { column = 'id', type = 'int8'}, { column = 'id_type', type = 'text'}, { column = 'power', type = 'text'}, { column = 'tags', type = 'jsonb' }, { column = 'members_nodes', sql_type = 'int8[]'}, { column = 'members_ways', sql_type = 'int8[]'}, { column = 'members_relations', sql_type = 'int8[]'}, { column = 'geom', type = 'geometry', projection = srid }, { column = 'area', type = 'area' }, }) tables.routes = osm2pgsql.define_relation_table('routes', { { column = 'tags', type = 'jsonb' }, { column = 'members_nodes', sql_type = 'int8[]'}, { column = 'members_ways', sql_type = 'int8[]'}, { column = 'members_relations', sql_type = 'int8[]'}, { column = 'geom', type = 'multilinestring', projection = srid }, }) -- These tag keys are generally regarded as useless for most rendering. Most -- of them are from imports or intended as internal information for mappers. -- -- If a key ends in '*' it will match all keys with the specified prefix. -- -- If you want some of these keys, perhaps for a debugging layer, just -- delete the corresponding lines. local delete_keys = { -- "mapper" keys 'attribution', 'comment', 'created_by', 'fixme', 'note', 'note:*', 'odbl', 'odbl:note', 'source', 'source:*', 'source_ref', -- "import" keys -- Corine Land Cover (CLC) (Europe) 'CLC:*', -- Geobase (CA) 'geobase:*', -- CanVec (CA) 'canvec:*', -- osak (DK) 'osak:*', -- kms (DK) 'kms:*', -- ngbe (ES) -- See also note:es and source:file above 'ngbe:*', -- Friuli Venezia Giulia (IT) 'it:fvg:*', -- KSJ2 (JA) -- See also note:ja and source_ref above 'KSJ2:*', -- Yahoo/ALPS (JA) 'yh:*', -- LINZ (NZ) 'LINZ2OSM:*', 'linz2osm:*', 'LINZ:*', 'ref:linz:*', -- WroclawGIS (PL) 'WroclawGIS:*', -- Naptan (UK) 'naptan:*', -- TIGER (US) 'tiger:*', -- GNIS (US) 'gnis:*', -- National Hydrography Dataset (US) 'NHD:*', 'nhd:*', -- mvdgis (Montevideo, UY) 'mvdgis:*', -- EUROSHA (Various countries) 'project:eurosha_2012', -- UrbIS (Brussels, BE) 'ref:UrbIS', -- NHN (CA) 'accuracy:meters', 'sub_sea:type', 'waterway:type', -- StatsCan (CA) 'statscan:rbuid', -- RUIAN (CZ) 'ref:ruian:addr', 'ref:ruian', 'building:ruian:type', -- DIBAVOD (CZ) 'dibavod:id', -- UIR-ADR (CZ) 'uir_adr:ADRESA_KOD', -- GST (DK) 'gst:feat_id', -- Maa-amet (EE) 'maaamet:ETAK', -- FANTOIR (FR) 'ref:FR:FANTOIR', -- 3dshapes (NL) '3dshapes:ggmodelk', -- AND (NL) 'AND_nosr_r', -- OPPDATERIN (NO) 'OPPDATERIN', -- Various imports (PL) 'addr:city:simc', 'addr:street:sym_ul', 'building:usage:pl', 'building:use:pl', -- TERYT (PL) 'teryt:simc', -- RABA (SK) 'raba:id', -- DCGIS (Washington DC, US) 'dcgis:gis_id', -- Building Identification Number (New York, US) 'nycdoitt:bin', -- Chicago Building Inport (US) 'chicago:building_id', -- Louisville, Kentucky/Building Outlines Import (US) 'lojic:bgnum', -- MassGIS (Massachusetts, US) 'massgis:way_id', -- Los Angeles County building ID (US) 'lacounty:*', -- Address import from Bundesamt für Eich- und Vermessungswesen (AT) 'at_bev:addr_date', -- misc 'import', 'import_uuid', 'OBJTYPE', 'SK53_bulk:load', 'mml:class' } -- The osm2pgsql.make_clean_tags_func() function takes the list of keys -- and key prefixes defined above and returns a function that can be used -- to clean those tags out of a Lua table. The clean_tags function will -- return true if it removed all tags from the table. local clean_tags = osm2pgsql.make_clean_tags_func(delete_keys) -- Helper function that looks at the tags and decides if this is possibly -- an area. function has_area_tags(tags) if tags.area == 'yes' then return true end if tags.area == 'no' then return false end return tags.aeroway or tags.amenity or tags.building or tags.harbour or tags.historic or tags.landuse or tags.leisure or tags.man_made or tags.military or tags.natural or tags.office or tags.place or tags.power or tags.public_transport or tags.shop or tags.sport or tags.tourism or tags.water or tags.waterway or tags.wetland or tags['abandoned:aeroway'] or tags['abandoned:amenity'] or tags['abandoned:building'] or tags['abandoned:landuse'] or tags['abandoned:power'] or tags['area:highway'] or tags['building:part'] end function osm2pgsql.process_node(object) if clean_tags(object.tags) then return end tables.points:add_row({ id = object.id, id_type = 'n', power = object.tags.power, tags = object.tags, geom = { create = "point" } }) end function way_member_nodes(way) local ids = {} for _, member in ipairs(way.nodes) do ids[#ids + 1] = member end return ids end function rel_member_ids(relation) local node_ids = {} local way_ids = {} local relation_ids = {} for _, member in ipairs(relation.members) do if member.type == 'w' then way_ids[#way_ids + 1] = member.ref end if member.type == 'n' then node_ids[#node_ids + 1] = member.ref end if member.type == 'r' then relation_ids[#relation_ids + 1] = member.ref end end return node_ids, way_ids, relation_ids end function osm2pgsql.process_way(object) if clean_tags(object.tags) then return end if object.is_closed and has_area_tags(object.tags) then tables.polygons:add_row({ id = object.id, id_type = 'w', power = object.tags.power, tags = object.tags, members_nodes = '{' .. table.concat(way_member_nodes(object), ',') .. '}', geom = { create = 'area', multi = False } }) else tables.lines:add_row({ id = object.id, id_type = 'w', power = object.tags.power, tags = object.tags, members_nodes = '{' .. table.concat(way_member_nodes(object), ',') .. '}', geom = { create = 'line' } }) end end function osm2pgsql.process_relation(object) local type = object:grab_tag('type') if clean_tags(object.tags) then return end nodes, ways, relations = rel_member_ids(object) if type == 'route' then tables.routes:add_row({ id = object.id, id_type = 'r', power = object.tags.power, tags = object.tags, member_nodes = '{' .. table.concat(nodes, ',') .. '}', member_ways = '{' .. table.concat(ways, ',') .. '}', member_relations = '{' .. table.concat(relations, ',') .. '}', geom = { create = 'line' } }) return end if type == 'multipolygon' then tables.polygons:add_row({ id = object.id, id_type = 'r', power = object.tags.power, tags = object.tags, member_nodes = '{' .. table.concat(nodes, ',') .. '}', member_ways = '{' .. table.concat(ways, ',') .. '}', member_relations = '{' .. table.concat(relations, ',') .. '}', geom = { create = 'area', multi = False } }) end end
local coq = require('coq') local lsp_installer = require("nvim-lsp-installer") -- keymaps local on_attach = function(client, bufnr) local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') require('bindings.lsp').Set_Keymaps(client) -- Set autocommands conditional on server_capabilities if client.resolved_capabilities.document_highlight then vim.api.nvim_exec([[ augroup lsp_document_highlight autocmd! * <buffer> autocmd CursorHold <buffer> lua vim.lsp.buf.document_highlight() autocmd CursorMoved <buffer> lua vim.lsp.buf.clear_references() augroup END ]], false) end end -- config that activates keymaps and enables snippet support local function make_config() local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true capabilities.textDocument.completion.completionItem.resolveSupport = { properties = { 'documentation', 'detail', 'additionalTextEdits' } } return { -- enable snippet support capabilities = capabilities, -- map buffer local keybindings when the language server attaches on_attach = on_attach, } end lsp_installer.on_server_ready(function(server) local config = make_config() if server.name == "lua" then config = require("lua-dev").setup({ lspconfig = make_config() }) end server:setup(coq.lsp_ensure_capabilities(config)) end)
object_tangible_npe_npe_elevator_down_b = object_tangible_npe_shared_npe_elevator_down_b:new { } ObjectTemplates:addTemplate(object_tangible_npe_npe_elevator_down_b, "object/tangible/npe/npe_elevator_down_b.iff")
----------------------------------------------------------------------------------------------- -- Grasses - More Tall Grass 0.0.2 ----------------------------------------------------------------------------------------------- -- by Mossmanikin -- License (everything): WTFPL -- Contains code from: biome_lib -- Looked at code from: default ----------------------------------------------------------------------------------------------- abstract_dryplants.grow_grass = function(pos) local right_here = {x=pos.x, y=pos.y+1, z=pos.z} local grass_size = math.random(1,5) if minetest.get_node(right_here).name == "air" -- instead of check_air = true, or minetest.get_node(right_here).name == "default:junglegrass" then minetest.set_node(right_here, {name="default:grass_"..grass_size}) end end biome_lib:register_generate_plant({ surface = { "default:dirt_with_grass", "stoneage:grass_with_silex", "sumpf:peat", "sumpf:sumpf" }, max_count = TALL_GRASS_PER_MAPBLOCK, rarity = 101 - TALL_GRASS_RARITY, min_elevation = 1, -- above sea level plantlife_limit = -0.9, }, abstract_dryplants.grow_grass )
local lastKey local clientResourceCount local keepAlive = {} local registerResource = {} local dbg = rdebug() --Thanks nit34byte <3 function generateKey() local chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ' local a = '' math.randomseed(os.time()) b = {} for c in chars:gmatch "." do table.insert(b, c) end for i = 1, 10 do a = a .. b[math.random(1, #b)] end return a end RegisterNetEvent('rcore:retrieveKey') AddEventHandler('rcore:retrieveKey', function() local _source = source if GetCurrentResourceName() == "rcore" then if lastKey == nil then lastKey = generateKey() dbg.security(string.format('[rcore] generating key %s',lastKey)) end TriggerClientEvent('rcore:updateKey', _source, lastKey) else TriggerEvent('rcore:logCheater',nil,'rcore:updateKey') end end) RegisterNetEvent('rcore:registerCheck') AddEventHandler('rcore:registerCheck',function(resName) dbg.security('Register resource for checking %s',resName) registerResource[resName] = resName end) AddEventHandler(EventConfig.Common.playerDropped,function(source) keepAlive[source] = nil end) function getServerKey() return lastKey end function isProtected(key) if Config.Debug then dbg.securitySpam(string.format('[rcore] checking keys %s:%s',lastKey,key)) end if key == nil then return false end if key == lastKey then return true else return false end end exports('isProtected', isProtected)
----------------------------------------- -- Spell: Cura -- Restores hp in area of effect. Self target only -- From what I understand, Cura's base potency is the same as Cure's. -- With Afflatus Misery Bonus, it can be as potent as a Curaga II -- Modeled after our Cure.lua, which was modeled after the below reference -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) if (caster:getID() ~= target:getID()) then return tpz.msg.basic.CANNOT_PERFORM_TARG else return 0 end end function onSpellCast(caster,target,spell) local divisor = 0 local constant = 0 local basepower = 0 local power = 0 local basecure = 0 local final = 0 local minCure = 10 if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster) divisor = 1 constant = -10 if (power > 100) then divisor = 57 constant = 29.125 elseif (power > 60) then divisor = 2 constant = 5 end else power = getCurePower(caster) if (power < 20) then divisor = 4 constant = 10 basepower = 0 elseif (power < 40) then divisor = 1.3333 constant = 15 basepower = 20 elseif (power < 125) then divisor = 8.5 constant = 30 basepower = 40 elseif (power < 200) then divisor = 15 constant = 40 basepower = 125 elseif (power < 600) then divisor = 20 constant = 40 basepower = 200 else divisor = 999999 constant = 65 basepower = 0 end end if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant) else basecure = getBaseCure(power,divisor,constant,basepower) end --Apply Afflatus Misery Bonus to Final Result if (caster:hasStatusEffect(tpz.effect.AFFLATUS_MISERY)) then if (caster:getID() == target:getID()) then -- Let's use a local var to hold the power of Misery so the boost is applied to all targets, caster:setLocalVar("Misery_Power", caster:getMod(tpz.mod.AFFLATUS_MISERY)) end local misery = caster:getLocalVar("Misery_Power") -- print(caster:getLocalVar("Misery_Power")) --THIS IS LARELY SEMI-EDUCATED GUESSWORK. THERE IS NOT A --LOT OF CONCRETE INFO OUT THERE ON CURA THAT I COULD FIND --If the target max affluent misery bonus --according to tests I found seems to cap out at most --people about 125 misery. With that in mind, if you --were hitting the Cure I cap of 65hp, then each misery --point would boost your Cura by about 1hp, capping at ~175hp --So with lack of available formula documentation, I'll go with that. --printf("BEFORE AFFLATUS MISERY BONUS: %d", basecure) basecure = basecure + misery if (basecure > 175) then basecure = 175 end --printf("AFTER AFFLATUS MISERY BONUS: %d", basecure) --Afflatus Misery Mod Gets Used Up caster:setMod(tpz.mod.AFFLATUS_MISERY, 0) end final = getCureFinal(caster,spell,basecure,minCure,false) final = final + (final * (target:getMod(tpz.mod.CURE_POTENCY_RCVD)/100)) --Applying server mods.... final = final * CURE_POWER target:addHP(final) target:wakeUp() --Enmity for Cura is fixed, so its CE/VE is set in the SQL and not calculated with updateEnmityFromCure spell:setMsg(tpz.msg.basic.AOE_HP_RECOVERY) local mpBonusPercent = (final*caster:getMod(tpz.mod.CURE2MP_PERCENT))/100 if (mpBonusPercent > 0) then caster:addMP(mpBonusPercent) end return final end
-- The text interpreter. Loaded after everything. interpreter = {} -- Load modules dofile("script/interpmodules/itemmodule.lua") dofile("script/interpmodules/movemodule.lua") -- Load command definitions function interpreter.loadDefs () interpreter.def = {} local defsToLoad = table.load("assets/interpdefs/commands.ldef") for i,v in pairs(defsToLoad) do if string.sub(v, -5) == ".idef" then interpreter.def[i] = table.load("assets/interpdefs/"..v) else -- Assume we are defining a command in-line. interpreter.def[i] = { v } end end end -- Compare a text string with a defined command. function interpreter.resolveCommand ( sText, command ) if type(command) ~= "table" then if command == sText then return true else return false end end for i,v in pairs(command) do if v == sText then return true end end return false end -- Check if the user wants to quit function interpreter.checkExit ( sText ) sText = string.lower(sText) return interpreter.resolveCommand(sText, interpreter.def.exit) end -- Remove articles from input. function interpreter.catchArticles ( tCommand ) for i,v in pairs(tCommand) do if v == "the" then table.remove(tCommand, i) elseif v == "a" then table.remove(tCommand, i) elseif v == "an" then table.remove(tCommand, i) end end return tCommand end -- Figure out what command the user inputted function interpreter.resolveInput ( sInput ) local words = {} sInput = string.lower(sInput) for word in string.gmatch(sInput, "%g+") do table.insert(words, word) end -- Remove "the", "a", and "an" words = interpreter.catchArticles(words) -- Show help if interpreter.resolveCommand(words[1], interpreter.def.help) then game.showHelpScreen() return end -- Examine something if interpreter.resolveCommand(words[1], interpreter.def.examine) then if not words[2] then -- Examine the room game.printRoomDescription() return elseif words[2] == "me" then -- You talkin' about ME? player.printDescription() return else -- Examine an item local itemID = interpreter.getItemIDByCommand(words) game.examineItem(itemID) return end end -- Take an item from the room if interpreter.resolveCommand(words[1], interpreter.def.take) then if not words[2] then print("Take what?") return end local itemID = interpreter.getItemIDByCommand(words) game.takeItem(itemID) return end -- Take inventory if interpreter.resolveCommand(words[1], interpreter.def.inventory) then player.printInventory() return end -- Move to another room if interpreter.resolveCommand(words[1], interpreter.def.move) then if not words[2] then print("Move where?") return end interpreter.resolveMovement(words[2]) return end -- Also move to another room. if interpreter.resolveCommand(words[1], interpreter.def.directions) then if not words[2] then interpreter.resolveMovement(words[1]) return end end -- Doesn't match up to anything. print("I did not understand that command.") end -- Interpret user-input function interpreter.run ( input ) if input == "" then return end -- No command. Equivalent to typing wait. if interpreter.checkExit(input) then game.quit() return end -- Quit. interpreter.resolveInput(input) return 0 end
--data.lua mod = "Realistic_Electric_Trains" path = "__" .. mod .. "__/" graphics = path .. "graphics/" require("config") require("prototypes.items") require("prototypes.entities") require("prototypes.recipes") require("prototypes.research")
cpuid = require 'luacpuid' print(cpuid.valid()) print(cpuid.vendor()) b = cpuid.New() --print(b.eax) print(b) --b.eax = 0xe cpuid.cpuid(b) print(b)
return { summary = 'Set the position of the Source.', description = [[ Sets the position of the Source, in meters. Setting the position will cause the Source to be distorted and attenuated based on its position relative to the listener. Only mono sources can be positioned. Setting the position of a stereo Source will cause an error. ]], arguments = { { name = 'x', type = 'number', description = 'The x coordinate.' }, { name = 'y', type = 'number', description = 'The y coordinate.' }, { name = 'z', type = 'number', description = 'The z coordinate.' } }, returns = {} }
-- MT-specific implementations of various dependencies of the loader logic. -- will trigger an error early if not run under MT local getmodpath = minetest.get_modpath -- FIXME: I *still* don't know if this varies across OSes or if lua handles it. local dirsep = "/" -- io implementation for the reservation manager to read the relevant files from mod directories. local modopen = function(self, modname, relpath) local sep = self.dirsep local path = self.mp(modname) if path == nil then return nil end return io.open(path..sep..relpath, "r") end local ioimpl = { dirsep=dirsep, mp=getmodpath, open=modopen, } -- getmodpath wrapper for the main loader object local mp = function(self, modname) return getmodpath(modname) end local modfinder = { get=mp } return ioimpl, modfinder
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-2020, TBOOX Open Source Group. -- -- @author ruki -- @file find_android_sdk.lua -- -- imports import("lib.detect.cache") import("core.base.semver") import("core.base.option") import("core.base.global") import("core.project.config") import("lib.detect.find_directory") -- find sdk directory function _find_android_sdkdir(sdkdir) -- get sdk directory if not sdkdir then sdkdir = os.getenv("ANDROID_SDK_HOME") or os.getenv("ANDROID_SDK_ROOT") if not sdkdir and is_host("macosx") then sdkdir = "~/Library/Android/sdk" end end -- get sdk directory if sdkdir and os.isdir(sdkdir) then return sdkdir end end -- find the build-tools version of sdk function _find_sdk_build_toolver(sdkdir) -- find the max version local toolver_max = "0" for _, dir in ipairs(os.dirs(path.join(sdkdir, "build-tools", "*"))) do local toolver = path.filename(dir) if semver.is_valid(toolver) and semver.compare(toolver, toolver_max) > 0 then toolver_max = toolver end end -- get the max sdk version return toolver_max ~= "0" and tostring(toolver_max) or nil end -- find the android sdk function _find_android_sdk(sdkdir, build_toolver) -- find sdk root directory sdkdir = _find_android_sdkdir(sdkdir) if not sdkdir then return {} end -- find the build-tools version of sdk build_toolver = build_toolver or _find_sdk_build_toolver(sdkdir) -- ok? return {sdkdir = sdkdir, build_toolver = build_toolver} end -- find android sdk directory -- -- @param sdkdir the android sdk directory -- @param opt the argument options, e.g. {force = true, build_toolver = "28.0.3"} -- -- @return the sdk toolchains. e.g. {sdkdir = .., build_toolver = "28.0.3"} -- -- @code -- -- local sdk = find_android_sdk("~/Library/Android/sdk") -- -- @endcode -- function main(sdkdir, opt) -- init arguments opt = opt or {} -- attempt to load cache first local key = "detect.sdks.find_android_sdk" local cacheinfo = cache.load(key) if not opt.force and cacheinfo.sdk and cacheinfo.sdk.sdkdir and os.isdir(cacheinfo.sdk.sdkdir) then return cacheinfo.sdk end -- find sdk local sdk = _find_android_sdk(sdkdir or config.get("android_sdk") or global.get("android_sdk"), opt.build_toolver or config.get("build_toolver")) if sdk and sdk.sdkdir then -- save to config config.set("android_sdk", sdk.sdkdir, {force = true, readonly = true}) config.set("build_toolver", sdk.build_toolver, {force = true, readonly = true}) -- trace if opt.verbose or option.get("verbose") then cprint("checking for the Android SDK directory ... ${color.success}%s", sdk.sdkdir) cprint("checking for the Build Tools Version of Android SDK ... ${color.success}%s", sdk.build_toolver) end else -- trace if opt.verbose or option.get("verbose") then cprint("checking for the Android SDK directory ... ${color.nothing}${text.nothing}") end end -- save to cache cacheinfo.sdk = sdk or false cache.save(key, cacheinfo) -- ok? return sdk end
local ffi = require'ffi' local ljarray = require'ljarray' ---------------------------------------------------------------------------- -- simple integer array ---------------------------------------------------------------------------- local a = ljarray.int(100) for i=1,5 do a:insert(i) --insert behaves like the default lua insert end a:remove(1) for i=1,#a do io.write(tostring(a[i])) end io.write'\n' ---------------------------------------------------------------------------- -- nested array ---------------------------------------------------------------------------- ffi.cdef('typedef $ intarray;', ljarray.int) -- 2nd parameter is a function that gets called on each element when the -- array itself is cleared or garbage collected. -- Passing the element type by string results in nicer tostring-output. -- Avoid passing the element type as ctype, and if you do, always pass the -- exact same value (!!) otherwise a unique array-type (plus methods -- and metatable) will be generated on *every* call of ljarray(<ctype>), -- instead of just once. local a = ljarray('intarray', ljarray.int.clear)() a[1] = ljarray.int() a[1][6] = 5 --a[0] is implicitly initialized a[0][0] = 42 print(a) print(a[1][6]) print(a[0][0]) ---------------------------------------------------------------------------- -- 'Point'-struct with pointless finalizer. ---------------------------------------------------------------------------- ffi.cdef'typedef struct { double x, y; } Point;' local Point = ffi.typeof('Point') local free_point = function(p) print('point destructor', p) end local new_point = function(ct) local p = ffi.new(ct) print('point constructor', p) return p end ffi.metatype(Point, {__new = new_point, __gc = free_point}) local v = ljarray(Point, free_point)() -- ljarrays with the ability to free their elements disable -- the finalizer on elements that they aquire. -- If this were not the case, array elements might be finalized -- multiple times, or array content might be finalized even before -- the array is garbage collected. -- Thus, 'el' will *not* be finalized when it goes out of scope (because -- we copied its contents into our array, and those contents *are* -- finalizede.g. when 'clear'-ing the array or when the array itself is -- garbage-collected). local el = Point() -- implicit initialization of v[0] triggers point-constructor call: v[1] = el print'clear' -- point-destructor gets called twice: v:clear() print'cleared' v[0] = el -- point-destructor gets called once (v cleans up its last remaining -- element when garbage-collected):
local setmetatable = setmetatable local tonumber = tonumber local aes = require "resty.aes" local cip = aes.cipher local hashes = aes.hash local ceil = math.ceil local var = ngx.var local sub = string.sub local rep = string.rep local CIPHER_MODES = { ecb = "ecb", cbc = "cbc", cfb1 = "cfb1", cfb8 = "cfb8", cfb128 = "cfb128", ofb = "ofb", ctr = "ctr" } local CIPHER_SIZES = { ["128"] = 128, ["192"] = 192, ["256"] = 256 } local defaults = { size = CIPHER_SIZES[var.session_aes_size] or 256, mode = CIPHER_MODES[var.session_aes_mode] or "cbc", hash = hashes[var.session_aes_hash] or "sha512", rounds = tonumber(var.session_aes_rounds) or 1 } local function salt(s) if s then local z = #s if z < 8 then return sub(rep(s, ceil(8 / z)), 1, 8) end if z > 8 then return sub(s, 1, 8) end return s end end local cipher = {} cipher.__index = cipher function cipher.new(config) local a = config.aes or defaults return setmetatable({ size = CIPHER_SIZES[a.size or defaults.size] or 256, mode = CIPHER_MODES[a.mode or defaults.mode] or "cbc", hash = hashes[a.hash or defaults.hash] or hashes.sha512, rounds = tonumber(a.rounds or defaults.rounds) or 1 }, cipher) end function cipher:encrypt(d, k, s) return aes:new(k, salt(s), cip(self.size, self.mode), self.hash, self.rounds):encrypt(d) end function cipher:decrypt(d, k, s) return aes:new(k, salt(s), cip(self.size, self.mode), self.hash, self.rounds):decrypt(d) end return cipher
PANEL.Base = "Panel" function PANEL:Init() self.Icon = vgui.Create("DImage", self) self.Shadow = vgui.Create("DImage", self) self.Shadow:SetImage("gui/legs") if math.random(0, 30) == 1 then self.Overlay = vgui.Create("DImage", self) self.Overlay:SetImage("gui/legs"..math.random(1, 2)) -- Random this end end function PANEL:SetUp(Icon, Speed) self.Icon:SetImage(Icon) local Distance = math.Rand(0, 30) self.BaseY = self:GetParent():GetTall() -64 - Distance self:SetPos(-62, self.BaseY) self:SetZPos(20 - Distance) self.Speed = Speed * math.Rand(0.8, 1.0) * 0.5 self.StartTime = SysTime() self.EndTime = SysTime() + self.Speed * 0.5 end function PANEL:PerformLayout() self:SetSize(64, 64) self.Icon:SetSize(16, 16) self.Icon:SetPos(24, 32) if IsValid(self.Overlay) then self.Overlay:SetPos(0, 0) self.Overlay:SetSize(64, 64) self.Overlay:SetZPos(1) end self.Shadow:SetPos(0, 0) self.Shadow:SetSize(64, 64) self.Shadow:SetZPos(1) end function PANEL:Think() if not self.StartTime then return end local delta = (SysTime() - self.StartTime) / (self.EndTime - self.StartTime) local x = Lerp(delta, -62, ScrW()) local y = self.BaseY - 64 + math.sin(x * 0.01) * 32 self:SetPos(x, y) if x >= ScrW() then if not self.Repeat then self:Remove() else -- Go around again.. self.EndTime = SysTime() + (self.EndTime - self.StartTime) self.StartTime = SysTime() self.x = -62 end end -- Up/Down motion. I don't like it. -- self.Icon:SetPos(24, 32 + math.sin((SysTime() * self.Speed) * 0.2) * 3) end function PANEL:SetRepeat(shouldrepeat) self.Repeat = shouldrepeat end
return { config = { option = { elona = { item_shortcuts_respect_curse_state = { name = "Shortcut", doc = [[ Normal: Separate shortcuts by item type only. Expansion: Separate item shortcuts for item congratulatory spells. ]], yes = "Expansion", no = "Normal" }, } } } }
nut.command.add("charsetclass", { adminOnly = true, syntax = "<string name> <string class>", onRun = function(client, args) local Target = nut.command.findPlayer(client, args[1]) if not IsValid(Target) then return end local TargetClass = table.concat(args," ", 2) for ClassID,Class in ipairs(nut.class.list) do if Class.uniqueID == TargetClass then local Char = Target:getChar() local OldClass = Char:getClass() Char:setClass(ClassID) hook.Run("OnPlayerJoinClass", client, ClassID, OldClass) client:notify("Class changed", L(Class.name, Target)) return true end end client:notify("Non existant class") end }) nut.command.add("charkickclass", { adminOnly = true, syntax = "<string name>", onRun = function(client, args) local Target = nut.command.findPlayer(client, args[1]) if not IsValid(Target) then return end local char = Target:getChar() char:setClass() client:notify("You kicked", L(Target)) local client = char:getPlayer() hook.Run("OnPlayerJoinClass", client, class) end }) nut.command.add("promote", { adminOnly = false, syntax = "< Look at target player >", onRun = function(client, args) local Target = client:GetEyeTraceNoCursor().Entity if not IsValid(Target) then client:notify("Not a valid target") return end local char = client:getChar() local ply = char:getPlayer() if char:hasFlags("T") then if Target:getChar():getFaction() == FACTION_REC then Target:setFaction(FACTION_PRIMUS) else client:notify("Character is not a recruit") end else client:notify("You are not a qualified trainer") end end }) nut.command.add("playintro", { adminOnly = true, syntax = "<string name>", onRun = function(client, args) local Target = client or nut.command.findPlayer(client, args[1]) if not IsValid(Target) then return end local char = Target:getChar() local client = char:getPlayer() net.Start( "playIntro" ) net.Send( Target ) end }) nut.command.add("traitgive", { adminOnly = true, syntax = "<string name> [string traits]", onRun = function(client, arguments) local target = nut.command.findPlayer(client, arguments[1]) if (IsValid(target) and target:getChar()) then local traits = arguments[2] if (!traits) then local available = "" -- Aesthetics~~ for k, v in SortedPairs(nut.trait.list) do if (!target:getChar():hasTraits(k)) then available = available..k end end return client:requestString("@traitGiveTitle", "@traitGiveDesc", function(text) nut.command.run(client, "traitgive", {target:Name(), text}) end, available) end target:getChar():giveTraits(traits) nut.util.notifyLocalized("Gave Traits", nil, client:Name(), target:Name(), traits) end end }) nut.command.add("traittake", { adminOnly = true, syntax = "<string name> [string traits]", onRun = function(client, arguments) local target = nut.command.findPlayer(client, arguments[1]) if (IsValid(target) and target:getChar()) then local traits = arguments[2] if (!traits) then return client:requestString("@traitTakeTitle", "@traitTakeDesc", function(text) nut.command.run(client, "traittake", {target:Name(), text}) end, target:getChar():getTraits()) end target:getChar():takeTraits(traits) nut.util.notifyLocalized("Removed Traits", nil, client:Name(), traits, target:Name()) end end }) nut.command.add("checkattrib", { adminOnly = true, syntax = "<string name> [string attribute]", onRun = function(client, arguments) local target = nut.command.findPlayer(client, arguments[1]) if (IsValid(target) and target:getChar()) then local attrib = arguments[2] if !attrib then client:notifyLocalized("FalseAttrib") return end for k, v in pairs(nut.attribs.list) do if (nut.util.stringMatches(v.name, attrib) or nut.util.stringMatches(k, attribName) or nut.util.stringMatches("*", attrib)) then client:ChatPrint(target:Name().." has ".. target:getChar():getAttrib(k, 0).. " in "..v.name) end end end end }) nut.chat.register("gmroll", { format = "(Admin Roll) %s has rolled %s.", color = Color(0, 255, 0), filter = "actions", font = "nutChatFontItalics", onCanHear = function(speaker, listener) local players = player.GetAll() for k, v in pairs(players) do if v:IsAdmin() then Admin = v end end return admin end, deadCanChat = true }) nut.command.add("gmroll", { adminOnly = true, syntax = "<string name> [number maximum]", onRun = function(client, arguments) local target = nut.command.findPlayer(client, arguments[1]) if (IsValid(target) and target:getChar()) then print(target) local number = math.random(0, math.min(tonumber(arguments[2]) or 100, 100)) nut.chat.send(target, "gmroll", number) nut.chat.send(target, "roll", number) end end })
--!A cross-platform build utility based on Lua -- -- 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. -- -- Copyright (C) 2015-present, TBOOX Open Source Group. -- -- @author ruki -- @file vs.lua -- -- imports import("impl.vs200x") import("impl.vs201x") import("impl.vsinfo") import("core.project.config") -- make factory function make(version) if not version then version = tonumber(config.get("vs")) if not version then return function(outputdir) raise("invalid vs version, run `xmake f --vs=201x`") end end end -- get vs version info local info = vsinfo(version) if version < 2010 then return function(outputdir) vprint("using project kind vs%d", version) vs200x.make(outputdir, info) end else return function(outputdir) utils.warning("please use the new vs project generator, .e.g xmake project -k vsxmake") vprint("using project kind vs%d", version) vs201x.make(outputdir, info) end end end
local json = require "json" function hive.start() names = json.array {} end local function hello(req) local name = req.params.name or "world" table.insert(names, name) return { greeting = "Hello, " .. name .. "!" } end local function list(req) return names end hive.register("/", hello) hive.register("/list", list) hive.register("/:name", hello)
require 'pl' require 'image' require 'trepl' local gm = require 'graphicsmagick' torch.setdefaulttensortype("torch.FloatTensor") local function color(black) local r, g, b if torch.uniform() > 0.8 then if black then return {0, 0, 0} else return {1, 1, 1} end else if torch.uniform() > 0.7 then r = torch.random(0, 1) else r = torch.uniform(0, 1) end if torch.uniform() > 0.7 then g = torch.random(0, 1) else g = torch.uniform(0, 1) end if torch.uniform() > 0.7 then b = torch.random(0, 1) else b = torch.uniform(0, 1) end end return {r,g,b} end local function gen_mod() local f = function() local xm = torch.random(2, 4) local ym = torch.random(2, 4) return function(x, y) return x % xm == 0 and y % ym == 0 end end return f() end local function dot() local sp = 1 local blocks = {} local n = 64 local s = 24 for i = 1, n do local block = torch.Tensor(3, s, s) local margin = torch.random(1, 3) local size = torch.random(1, 5) local mod = gen_mod() local swap_color = torch.uniform() > 0.5 local fg, bg if swap_color then fg = color() bg = color(true) else fg = color(true) bg = color() end local use_cross_and_skip = torch.uniform() > 0.5 for j = 1, 3 do block[j]:fill(bg[j]) end for y = margin, s - margin do local b = 0 if use_cross_and_skip and torch.random(0, 1) == 1 then b = torch.random(0, 1) end for x = margin, s - margin do local yc = math.floor(y / size) local xc = math.floor(x / size) if use_corss_and_skip then if torch.uniform() > 0.25 and mod(yc + b, xc + b) then block[1][y][x] = fg[1] block[2][y][x] = fg[2] block[3][y][x] = fg[3] end else if mod(yc + b, xc + b) then block[1][y][x] = fg[1] block[2][y][x] = fg[2] block[3][y][x] = fg[3] end end end end block = image.scale(block, s * 2, s * 2, "simple") if (not use_corss_and_skip) and size >= 3 and torch.uniform() > 0.5 then block = image.rotate(block, math.pi / 4, "bilinear") end blocks[i] = block end local img = torch.Tensor(#blocks, 3, s * 2, s * 2) for i = 1, #blocks do img[i]:copy(blocks[i]) end img = image.toDisplayTensor({input = img, padding = 0, nrow = math.pow(n, 0.5), min = 0, max = 1}) return img end local function gen() return dot() end local cmd = torch.CmdLine() cmd:text() cmd:text("dot image generator") cmd:text("Options:") cmd:option("-o", "", 'output directory') cmd:option("-n", 64, 'number of images') local opt = cmd:parse(arg) if opt.o:len() == 0 then cmd:help() os.exit(1) end for i = 1, opt.n do local img = gen() image.save(path.join(opt.o, i .. ".png"), img) end
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local rand = require("lib.lpm.random").u32 local bit = require("bit") local lib = require("core.lib") local lpm = require("lib.lpm.lpm").LPM local ip4 = require("lib.lpm.ip4") LPM4 = setmetatable({}, { __index = lpm }) entry = ffi.typeof([[ struct { uint32_t ip; int32_t key; int32_t length; } ]]) local verify_ip_count = 2000000 function LPM4:print_entry (e) print(string.format("%s/%d %d", ip4.tostring(e.ip), e.length, e.key)) end function LPM4:print_entries () for e in self:entries() do self:print_entry(e) end end function LPM4:search_bytes (bytes) local ip = ffi.cast("uint32_t*", bytes)[0] return self:search(lib.ntohl(ip)) end function LPM4:search_entry (ip) error("Must be implemented in a subclass") end function LPM4:search_entry_exact (ip, len) error("Must be implemented in a subclass") end function LPM4:search_entry_string (ip) return self:search_entry(ip4.parse(ip)) end function LPM4:search (ip) return self:search_entry(ip).key end function LPM4:search_string (str) return self:search(ip4.parse(str)) end function LPM4:search_cidr (cidr) return self:search_entry_exact(ip4.parse_cidr(cidr)) end function LPM4:add (ip, len, key) error("Must be implemented in a subclass") end function LPM4:add_string (cidr, key) local net, len = ip4.parse_cidr(cidr) self:add(net, len, key) end function LPM4:add_from_file (pfxfile) for line in io.lines(pfxfile) do local cidr, key = string.match(line, "(%g*)%s*(%g*)") self:add_string(cidr, tonumber(key)) end return self end function LPM4:remove (ip, len) error("Must be implemented in a subclass") end function LPM4:remove_string (cidr) local net, len = ip4.parse_cidr(cidr) self:remove(net, len) end function LPM4:build () return self end function LPM4:benchmark (million) local million = million or 100000000 local pmu = require("lib.pmu") local ip self:build() local funcs = { ["data dependency"] = function() for i = 1, million do ip = rand(ip) + self:search(ip) end end, ["no lookup"] = function() for i = 1, million do ip = rand(ip) + 1 end end, ["no dependency"] = function() for i = 1, million do ip = rand(ip) + 1 self:search(ip) end end } for n,f in pairs(funcs) do print(n) ip = rand(314159) pmu.profile( f, { "mem_load_uops_retired.llc_hit", "mem_load_uops_retired.llc_miss", "mem_load_uops_retired.l2_miss", "mem_load_uops_retired.l2_hit" }, { lookup = million } ) print() end end function LPM4:verify (trusted) local ip = rand(271828) for i = 0,verify_ip_count do local ipstr = ip4.tostring(ip) local expected = trusted:search(ip) local key = self:search(ip) assert(expected == key, string.format("%s got %d expected %d", ipstr, key, expected)) ip = rand(ip) end end function LPM4:verify_against_fixtures (pfxfile, verifyfile) self:add_from_file(pfxfile) self:build() local count = 0 for line in io.lines(verifyfile) do local ip, tcidr, key = string.match(line, "(%g*) (%g*) (%g*)") local found = self:search_entry_string(ip) assert(found.key == tonumber(key), string.format("Search %d for %s found (%s/%d) %s expected (%s) %d ", count, ip, ip4.tostring(found.ip), found.length, found.key, tcidr, key)) count = count + 1 end end function LPM4:build_verify_fixtures (pfxfile, ipfile) local f = LPM4:new() local out = assert(io.open(pfxfile, "w", "unable to open " .. pfxfile .. " for writing")) f.add = function (self,ip,len,key) out:write(string.format("%s/%d %d\n", ip4.tostring(ip), len, key)) end f:add_random_entries() local out = assert(io.open(ipfile, "w", "unable to open " .. pfxfile .. " for writing")) local ip = rand(271828) for i = 0, verify_ip_count do out:write(ip4.tostring(ip) .. "\n") ip = rand(ip) end end function LPM4:remove_random_entries () local count = self.entry_count - 1 local ents = self.lpm4_ents local removen = math.floor(count * 0.1) -- Set a random seed so that remove_random_entries -- removes the same entries if run across different objects math.randomseed(9847261856) for i = 1,removen do local remove = math.random(1, count) ents[remove].ip, ents[count].ip = ents[count].ip, ents[remove].ip ents[remove].length, ents[count].length = ents[count].length, ents[remove].length ents[remove].key, ents[count].key = ents[count].key, ents[remove].key self:remove(ents[count].ip, ents[count].length) count = count - 1 end self.entry_count = count end function LPM4:verify_entries_method () local against = {} print("Verifying " .. tostring(self.entry_count) .. " entries") for e in self:entries() do local cidr = ip4.tostring(e.ip) .. "/" .. e.length against[cidr] = e.key end for i = 0, self.entry_count - 1 do local cidr = ip4.tostring(self.lpm4_ents[i].ip) .. "/" .. self.lpm4_ents[i].length assert(against[cidr] and against[cidr] == self.lpm4_ents[i].key, cidr .. " not found") end end function LPM4:add_random_entries (tab) local tab = tab or { [0] = 1, [10] = 50, [11] = 100, [12] = 250, [13] = 500, [14] = 1000, [15] = 1750, [16] = 12000, [17] = 8000, [18] = 13500, [19] = 26250, [20] = 40000, [21] = 43000, [22] = 75000, [23] = 65000, [24] = 350000, [25] = 1250, [26] = 1000, [27] = 500, [28] = 500, [29] = 1250, [30] = 150, [31] = 50, [32] = 1500 } local count = 0 for k,v in pairs(tab) do count = count + v end self:alloc("lpm4_ents", entry, count) local ents = self.lpm4_ents local r = rand(314159) local eoff = 0 local addrs = {} for k,v in pairs(tab) do local mask = bit.bnot(2^(32-k)-1) local i = 0 while i < v do r = rand(r) local ip = bit.band(r, mask) r = rand(r) ents[eoff].ip = ip ents[eoff].length = k ents[eoff].key = bit.band(r,0x7fff) if not addrs[ip * 64 + k] and ents[eoff].key ~= 0 then eoff = eoff + 1 i = i + 1 end addrs[ip * 64 + k] = true end end print("Adding " .. tostring(count) .. " random entries") self.entry_count = count for i=0, count-1 do self:add(ents[i].ip, ents[i].length, ents[i].key) end return self end function selftest () local s = require("lib.lpm.lpm4_trie").LPM4_trie:new() s:add_string("10.0.0.0/24", 10) s:add_string("0.0.0.10/32", 11) assert(10 == s:search_bytes(ffi.new("uint8_t[4]", {10,0,0,0}))) assert(11 == s:search_bytes(ffi.new("uint8_t[4]", {0,0,0,10}))) end function LPM4:selftest (cfg, millions) assert(self, "selftest must be called with : ") if not os.getenv("SNABB_LPM4_TEST_INTENSIVE") then print("Skipping LPM4:selfest (very specific / excessive runtime)") print("In case you are hacking on lib.lpm you might want to enable") print("these tests by setting SNABB_LPM4_TEST_INTENSIVE in your") print("environment.") return end local trusted = require("lib.lpm.lpm4_trie").LPM4_trie:new() trusted:add_random_entries() local f = self:new(cfg) f:add_random_entries() for i = 1,5 do f:build():verify(trusted:build()) f:verify_entries_method() f:remove_random_entries() trusted:remove_random_entries() end local ptr = C.malloc(256*1024*1024) local f = self:new(cfg) local g = self:new(cfg) f:add_random_entries() f:build() f:alloc_store(ptr) g:alloc_load(ptr) g:verify(f) C.free(ptr) local avail, err = require('lib.pmu').is_available() if not avail then print("PMU not available:") print(" "..err) print("Skipping benchmark.") else self:new(cfg):add_random_entries():benchmark(millions) end print("selftest complete") end
tokenizer=require 'simple_tokenizer' --comment out to have debugging autostart started_debugging=true if not started_debugging then started_debugging = true require('mobdebug').start() end --local serpent = require("serpent") --require 'class' --forward references local strip_tokens_from_list,apply_macros,add_macro,nullp,cdr,car,cadr,cddr,caddr,cdddr,macros,validate_params local optional_read_match_to,read_match_to,read_match_to_no_commas,sublist_to_list,concat_cons,scan_head_forward,add_token_keys,nthcar local my_err,cons,list_to_array,copy_list, copy_list_and_object,simple_copy,render,output_render, last_cell,reverse_list_in_place,reverse_list,cons_tostring,Nil,list_append_in_place,process,list_to_stripped_array,add_tokens local token_metatable = {__tostring= function(self) if self.token and self.macro_token~=self.token.value then if self.type == 'String' then return self.token.value end return self.token.value .. '-as-' .. self.macro_token end return self.macro_token end } local filename2sections = {} local function insure_subtable_exists(original_table,field) if not original_table[field] then original_table[field]={} end end -- table_path_get(t,'a','b','c') is t.a.b.c returning nil if any level does not exist local function table_path_get(r, ...) local len=select('#',...) for i = 1, len do if not r then return nil end local selector=select(i,...) r=r[selector] end return r end codemap = {} local function fill_codemap(filename, tokens,m) filename='@'..filename insure_subtable_exists(codemap,filename) local t=tokens local ti=1 local di=1 local cmap=codemap[filename] while not nullp(t) do local token = car(t) if token.token and token.token.from_line then di=(token.token.from_line+1)*m end while #cmap<ti do table.insert(cmap,di) end -- cmap[ti]=di if cmap[ti]<di then cmap[ti]=di end ti=ti+1 t=cdr(t) end end local function my_loadstring(string, filename,tokens,output_string) output_string=output_string or string fill_codemap(filename,tokens,1) if not filename then filename = 'macro_temp.lua' end local output_filename = filename .. '.temp.lua' local file=io.open(output_filename,"w") -- file:write('return((') file:write(output_string ) --output_render(tokens)) -- file:write(')())') file:close() local function my_hander(err) print('in handler '..tostring(err)) local token_number,error_text=string.match(tostring(err),":(%d+):(.*)") if not token_number then my_err(nil,"can't determine token for error \""..tostring(err)..'"') else token_number = tonumber(token_number) print ('error at token '..token_number.. ' error message: "'..error_text..'"') if tokens then my_err(nthcar( token_number,tokens), error_text) else my_err(nil,"can't determine token for error \""..tostring(err)..'"') end end end local ret local status --= xpcall(my_do,my_hander) local function my_do(...) local s=table.pack(pcall(status,...)) if not s[1] then my_hander(s[2]) end table.remove(s,1) return table.unpack(s,s.n-1) end if not started_debugging then started_debugging = true require('mobdebug').start() end --editor.autoactivate=true status,ret=loadstring(string,"@"..filename) if not status then my_hander(ret) end -- print ('the status is "' .. tostring(status) ..'"') return my_do end local function my_dostring(string, filename, tokens) --print('my_dostring 「', string,'」') if not filename then filename = 'macro_temp.lua' end fill_codemap(filename,tokens,-1) -- local file=io.open(filename,"w") -- file:write(string) -- file:close() local function my_hander(err) -- print('in handler '..tostring(err)) local token_number,error_text=string.match(tostring(err),":(%d+):(.*)") if not token_number then my_err(nil,"can't determine token for error \""..tostring(err)..'"') else token_number = tonumber(token_number) -- print ('error at token '..token_number.. ' error message: "'..error_text..'"') if tokens then my_err(nthcar(tokens, token_number), error_text) else my_err(nil,"can't determine token for error \""..tostring(err)..'"') end end return true end local ret local function my_do() -- ret=dofile(filename) ret=assert(loadstring(string,'@'..filename))() end local status = xpcall(my_do,my_hander) -- print ('the status is "' .. tostring(status) ..'"') return ret end local function array_to_set_table(a) if type(a)~='table' then return a end local t={} for _,v in ipairs(a) do t[v]=true end return t end simple_translate = setmetatable( { ['[|']='function (', ['{|']='coroutine.wrap(function (', ['|']=')', ['@']='return', ['y@']='coroutine.yield', ['Y@']='coroutine.yield', ['|]']='end', ['|}']='end)', ['$#']='select("#",...)', ['$1']='select(1,...)', ['$2']='select(2,...)', ['$3']='select(3,...)', ['$4']='select(4,...)', ['$5']='select(5,...)', ['$6']='select(6,...)', }, { __index = function(_,v) return v end }) local function pp_null_fn(lines, line_number) return line_number+1 end local function file_path(mtoken) return table_path_get(mtoken,'token','filename') or '¯\\_(ツ)_/¯' end my_err= function (mtoken,err) local line=' ' err=err or 'error' if not nullp(mtoken) then if mtoken.token then print('token '.. mtoken.macro_token .. ' filename ' .. tostring(mtoken.token.filename) .. ' line '.. tostring(mtoken.token.from_line) ) else print('macro token '.. tostring(mtoken) ) end end if mtoken and mtoken.token then line= ':'..tostring(mtoken.token.from_line+1)..':'..tostring(mtoken.token.from_x+1)..':' end io.stderr:write(file_path(mtoken).. line .. err .. '\n') os.exit(1) end --from is cut, to is cut local function cut_out_lines(lines,from_line,to_line) -- print ("delete lines from "..from_line.." to "..to_line) while lines[1+from_line]==0 do from_line=from_line+1 end while lines[2+to_line]==0 do to_line=to_line+1 end if to_line<from_line or not lines[1+from_line] then return end --print ("adjusted delete lines from "..from_line.." to "..to_line) local at_start=lines[from_line+1] local before_start=at_start[1] local after_end=lines[to_line+2] local at_end if after_end then at_end=after_end[1] else after_end=Nil end if before_start ~= 'Cons' then before_start[3]=after_end if after_end~= Nil then after_end[1]=before_start end else at_start[3]=after_end if after_end~= Nil then after_end[1]=at_start end at_start[2].macro_token='' end for j=from_line+1,to_line+1 do lines[j]=0 end end local function cut_out_lines_saved(lines,saved) cut_out_lines(lines,saved[1],saved[2]) return saved; end local cut_out_if_lines = {} local if_state = {} local function redo_if_statements(lines) while #cut_out_if_lines>0 do cut_out_lines_saved(lines,table.remove(cut_out_if_lines)) end end local if_special_lines = { ['@endif']=true, ['@else']=true, ['@elseif']=true, ['@if']=true } local if_skip_lines = { ['@endif']=true, ['@if']=true } local function skip_if(lines, curline, line_number) ::search_more:: repeat curline=curline+1 until not lines[1+curline] or if_skip_lines[car(lines[1+curline]).macro_token] if not lines[1+curline] then my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number)) end if token == '@if' then curline=skip_if(lines, curline, line_number) goto search_more end -- token == '@endif' return curline end local function pp_endif(lines,line_number,filename, skipping) if skipping then my_err(cadr(start),'internal error. @endifs should be culled before second pass') end if #if_state==0 then my_err(cadr(start),'@endif without matching @if') end table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,line_number})) table.remove(if_state) return line_number+1 end local function pp_else(lines,line_number,filename, skipping) local start = lines[line_number+1] if #if_state==0 then my_err(cadr(start),'@else without matching @if') end table.remove(if_state) local curline=line_number ::search_more:: repeat curline=curline+1 until not lines[1+curline] or (lines[1+curline]~=0 and if_special_lines[car(lines[1+curline]).macro_token]) if not lines[1+curline] then my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number)) end local token = car(lines[1+curline]).macro_token if token == '@if' then curline=skip_if(lines, curline, line_number) goto search_more elseif token == '@endif' then table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline})) return curline+1 elseif token == '@else' then my_err(cadr(start),'second @else ' ) elseif token == '@elseif' then my_err(cadr(start),'@elseif after @else ' ) end end local function pp_elseif(lines,line_number,filename, skipping) local start = lines[line_number+1] if #if_state==0 then my_err(cadr(start),'@elseif without matching @if') end local curline=line_number ::search_more:: repeat curline=curline+1 until not lines[1+curline] or (lines[1+curline]~=0 and if_special_lines[car(lines[1+curline]).macro_token]) if not lines[1+curline] then my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number)) end local token = car(lines[1+curline]).macro_token if token == '@if' then curline=skip_if(lines, curline, line_number) goto search_more elseif token == '@endif' then table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline})) return curline+1 elseif token == '@else' then table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline-1})) return pp_else(lines,curline,filename, skipping) elseif token == '@elseif' then goto search_more end table.remove(if_state) end local function pp_if(lines,line_number,filename, skipping) local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1 if skipping then my_err(cadr(start),'internal error. @ifs should be culled before second pass') end local function my_handler(err) local token_number,error_text=string.match(tostring(err),":(%d+):(.*)") if not token_number then my_err(nil,"can't determine token for error \""..tostring(err)..'"') else token_number = tonumber(token_number)+2 if not nullp(cdr(start)) then my_err(nthcar( token_number,cdr(start)), error_text) else my_err(nil,"can't determine token for error \""..tostring(err)..'"') end end end local function do_conditional_expression(line_number) local start = lines[line_number+1] local exp_start=cdr(lines[line_number+1]) local exp_end=exp_start while not nullp(cadr(exp_end)) and cadr(exp_end).token.from_line == line_number do exp_end=cdr(exp_end) end local ret= sublist_to_list({exp_start,exp_end},0) if not filename and car(start).token then filename = car(start).token.filename end if not skipping then if ret then ret=process(ret,filename,'no render') end local cond = my_dostring('return ('.. render(ret).. ')', filename, cdr(start)); -- if not cond then my_err(car(start), 'syntax error in @if or @elseif conditional expression') end -- local _success,_err,result= xpcall(cond,my_handler) -- print('if result',_success,_err,result) return cond end end if do_conditional_expression(line_number) then -- print('if succeeded') table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,line_number})) table.insert(if_state, 'if') return line_number+1 else -- print('if failed') local curline=line_number ::search_more:: repeat curline=curline+1 until not lines[1+curline] or (lines[1+curline]~=0 and if_special_lines[car(lines[1+curline]).macro_token]) if not lines[1+curline] then my_err(cadr(start),'unfinished @if, from line ' .. tostring(line_number)) end local token = car(lines[1+curline]).macro_token if token == '@if' then curline=skip_if(lines, curline, line_number) goto search_more elseif token == '@endif' then table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline})) return curline+1 elseif token == '@else' then table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline})) table.insert(if_state, 'else') return curline+1 elseif token == '@elseif' then table.insert(cut_out_if_lines,cut_out_lines_saved(lines,{line_number,curline-1})) return pp_if(lines,curline, filename, skipping) end end end local function pp_section(lines,line_number,filename, skipping) local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1 if not filename and car(start).token then filename = car(start).token.filename end local splice_first = start[1] -- can be 'Cons' on the first element if cadr(start).type ~= 'String' then my_err(cadr(start),'name of a section expected after @section, " or \' expected') end--{}{}{} local nl = cdr(start) car(start).macro_token='' cadr(start).macro_token='' if skipping then insure_subtable_exists(filename2sections,filename) if filename2sections[filename][cadr(start).token.processed] then my_err(cadr(start),'section '..cadr(start).token.processed..' in file '..filename..' already exists.') end filename2sections[filename][cadr(start).token.processed]= {insertion_point = start} end -- car(start).section = { filename=filename, section_name=cadr(start).token.processed } --table.insert(filename2sections[filename],cadr(start).token.processed) return car(nl).token.from_line+1 end local function process_sections(filename) local empty if not filename2sections[filename] then return end repeat empty = true for k,v in pairs(filename2sections[filename]) do macro_list = Nil for i=1,#v do if not nullp(v[i]) then macro_list = list_append_in_place(v[i],macro_list) end empty=false end for i=1,#v do table.remove(v) end if macro_list then macro_list=process(macro_list,filename,'no render') end if v.processed_macros then v.processed_macros = list_append_in_place(v.processed_macros,macro_list) else v.processed_macros = macro_list end end until empty for k,v in pairs(filename2sections[filename]) do --insert processed now if not nullp(v.processed_macros) then v.insertion_point[3] = list_append_in_place(v.processed_macros,v.insertion_point[3]) end end end local function section_object_from_token(token) if not token.section then return nil end return filename2sections[token.section.filename][token.section.section_name] end local function pp_require(lines,line_number,filename,skipping) local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1 local splice_first = start[1] -- can be 'Cons' on the first element if cadr(start).type ~= 'String' then my_err(cadr(start),'name of a file expected after @require, " or \' expected') end--{}{}{} local nl = cdr(start) if not skipping then require(cadr(start).token.processed) end if splice_first~= 'Cons' then splice_first[3]=cdr(nl) cdr(nl)[1]=splice_first else start[3]=cdr(nl) cdr(nl)[1]=start car(start).macro_token='' end return car(nl).token.from_line+1 end local function pp_macro(lines,line_number,filename,skipping) local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1 local splice_first = start[1] -- can be 'Cons' on the first element if cadr(start).macro_token ~= '{' then my_err(cadr(start),'struct of macro expected after @macro, { expected') end local s,nl s,nl=optional_read_match_to(cddr(start),'}') if not s or nullp(nl) or car(nl).macro_token ~='}' then my_err(start,'struct of macro expected after @macro, } expected') end local ret = sublist_to_list( {cdr(start),nl} ) -- local filename = nil if not filename and car(start).token then filename = car(start).token.filename end local macro = my_dostring('return('..render(ret)..')', filename, cdr(start)); if not macro then my_err(car(start), 'syntax error in table definition for macro') end if not skipping then print("adding macro:",macro.head) print(macro.new_tokens) add_macro(macro,macros, filename,car(start).token.from_line) end if splice_first~= 'Cons' then splice_first[3]=cdr(nl) cdr(nl)[1]=splice_first else start[3]=cdr(nl) cdr(nl)[1]=start car(start).macro_token='' end return car(nl).token.from_line+1 end local function pp_start(lines,line_number,filename,skipping) local start = lines[line_number+1] --lines are counted from 0 but lua arrays from 1 local splice_first = start[1] -- can be 'Cons' on the first element local s,nl s,nl=optional_read_match_to(cddr(start),'@end') if not s or nullp(nl) or car(nl).macro_token ~='@end' then my_err(start,'@end expected after @start') end local ret = sublist_to_list( {cdr(start),nl},1 ) -- local filename = nil if not filename and car(start).token then filename = car(start).token.filename end if not skipping then if ret then ret=process(ret,filename,'no render') end local macro = my_dostring('return function () '.. render(ret)..' end', filename, cdr(start)); if not macro then my_err(car(start), 'syntax error @start/@end block') end local function my_handler(err) local token_number,error_text=string.match(tostring(err),":(%d+):(.*)") if not token_number then my_err(nil,"can't determine token for error \""..tostring(err)..'"') else token_number = tonumber(token_number)+2 if not nullp(cdr(start)) then my_err(nthcar( token_number,cdr(start)), error_text) else my_err(nil,"can't determine token for error \""..tostring(err)..'"') end end end xpcall(macro,my_handler) end if splice_first~= 'Cons' then splice_first[3]=cdr(nl) cdr(nl)[1]=splice_first else start[3]=cdr(nl) cdr(nl)[1]=start car(start).macro_token='' end return car(nl).token.from_line+1 end --turn list back to normal cons cells after first stage of preprocessing local function strip_back_links(list) local n=list while not nullp(n) do n[1]='Cons' n=n[3] end while list.macro_token == '' do list=list[3] end return list end preprocessor_tokens = setmetatable({ ['@start']=pp_start, -- ['@end']=pp_null_fn, --['@define']=pp_null_fn, ['@if']=pp_if, ['@elseif']=pp_elseif, ['@else']=pp_else, ['@endif']=pp_endif, ['@section']=pp_section, --['@fileout']=pp_null_fn, ['@require']=pp_require, ['@macro']=pp_macro, }, { __index = function (_,v) return pp_null_fn end}) --macros as first class at expand time --[==[ @macro{ new_tokens={'WHILE','DO','END','BREAK','CONTINUE'}, head='WHILE ?()...exp DO ?,...statements END', body=[[ local function %loop() if ?exp then @apply({{head='BREAK',body='return("__*done*__")'}, {head='CONTINUE',body='return %loop()'},}, ?statements) return %loop() end return '__*done*__' end local %save=table.pack(%loop()) if %save[1]~='__*done*__' then return table.unpack(%save,%save.n) end local fn,err= loadstring(process([[ local i,j i=1 WHILE i<=6 DO j=10 if i==3 then CONTINUE end if i==5 then BREAK end WHILE j<=60 DO if j==30 then CONTINUE end if j==50 then BREAK end print(i,j) --I should test return too j=j+10 END i=i+1 END ]])) fn() } --]==] add_token_keys= function(t) for k,_ in pairs(t) do tokenizer.add_special_token(k) end end add_tokens= function(t) if not t then return end for _,v in ipairs(t) do tokenizer.add_special_token(v) end end add_token_keys(simple_translate) local function no_source_token(t) return setmetatable({macro_token=t},token_metatable) end local function string_to_source_array(str,filename,err_handler) local error_pos, source, meaningful =tokenizer.tokenize_all(str,filename,err_handler) --{}{}{} process needs to ignore token errors on the first pass -- but the rest of the program??? -- if not error_pos then local flatten={} local prevx,prevy,indent=0,0,0 for a = 1,#meaningful do local ttype = source[meaningful[a]].type local value local token=source[meaningful[a]] -- if ttype=='String' then --we don't want to find escape sequences in our strings, so we use the processed version -- value='[=======['..source[meaningful[a]].processed..']=======]' -- else value=source[meaningful[a]].value -- end local dy=token.from_line-prevy prevy=token.to_line local dx,first if dy ~= 0 then dx=token.from_x indent = dx first=true else dx=token.from_x-prevx first=false end prevx=token.to_x table.insert(flatten, setmetatable( {first = first,macro_token=simple_translate[value],type=ttype,token=token,dx=dx,dy=dy,indent=indent, splice=false, indent_delta=0},token_metatable)) -- print('y = '..tostring( flatten[#flatten].token.from_line )..'\t x = '.. tostring( flatten[#flatten].token.from_x)) end return flatten -- end end local function splice_simple(original_head_list, new_head_array, concat_list) if not new_head_array then error("internal") end if #new_head_array == 0 then return concat_list end local indent local indent_delta if nullp(original_head_list) then indent = (new_head_array[1].indent or car(concat_list).indent or 0) indent_delta = 0 else indent =car(original_head_list).indent+car(original_head_list).indent_delta indent_delta = indent-((new_head_array[1].indent or 0) + (new_head_array[1].indent_delta or 0)) end local l=concat_list or Nil if new_head_array then for i=#new_head_array,1,-1 do -- if not new_head_array[i].indent then -- print 'wat' -- end assert (new_head_array[i].indent) new_head_array[i].indent_delta=(new_head_array[i].indent_delta or 0)+indent_delta l=cons(new_head_array[i],l) end car(l).splice=true car(l).first=true car(l).dy=1 car(l).dx=car(l).indent if concat_list and not concat_list[1].first then car(concat_list).splice=true car(concat_list).first=true car(concat_list).dy=1 car(concat_list).dx=car(concat_list).indent end end return l end local function splice(original_head_list, new_head_array, section, filename) --Note, in the first case "section" is the concat list not the section if not filename then return splice_simple(original_head_list, new_head_array, section) end if not filename2sections[filename] then my_err(Nil,'No sections in file '..filename..' have been found.') end local section_table = filename2sections[filename][section] if not section_table then my_err(Nil,'no section '..section..' in file '..filename..' found.') end local sp= splice_simple(original_head_list, new_head_array) table.insert(section_table,sp) return sp end simple_copy = function (obj) if type(obj) ~= 'table' then return obj end local copy={} for i,v in pairs(obj) do copy[i]=v end return setmetatable(copy,getmetatable(obj)) end --[[ New syntax ?name ?...name ?,...name ?()...name ]] local macro_params={ --input paramsk ['?1']='param', --input matches till ['?...']='param until', --input matches till next, also matches () {} [] - stops for comma --if the expected next is a comma then that matches --if the expected next is not a comma and it finds one, that's a failure ['?']='param match until', --in matches any number of elements including commas ['?,']='params', ['??,']='optional params',--generate var ['%']='generate var', -- ['%external-load:']='global load', -- also need a 4th entry for saving ['@apply']='apply macros', } add_token_keys(preprocessor_tokens) tokenizer.add_special_token('@apply') tokenizer.add_special_token('@@') --needs a global macro with a function body tokenizer.add_special_token('@tostring') --needs a global macro with a function body tokenizer.add_special_token('@end') local function skip_one(l) if not nullp(l) then return cdr(l) end return l end local function skip_apply(l, store, filename) l=cdr(l) if car(l).macro_token ~='(' then my_err(car(l), '( expected after @apply ') end l=cdr(l) local ret local where_struct_goes = l if (store) then if car(l).macro_token ~='{' or cadr(l).macro_token ~='{' then my_err(car(l), 'array of macros expected after @apply ( got: '..car(l).macro_token .." ".. cadr(l).macro_token) end local s,nl s,nl=optional_read_match_to(l,',') if not s then my_err(car(l), 'array of macros expected after @apply (') end if nullp(nl) then my_err(car(l) ', expected after @apply({macros...} ') end if car(nl).macro_token ~=',' then my_err(car(nl) ', expected after @apply({macros...} ') end --{}{}{} could use formatting ret = sublist_to_list( {l,nl},1 ) local tokens = l l=cdr(nl); --concat_cons(ret,' '); where_struct_goes[2]={} local filename=nil if l.token then filename=l.token.filename end local temp_macros = my_dostring('return('..render(ret)..')', filename, tokens); if not temp_macros then my_err(car(nl), 'syntax error in table definition for macro for @apply') end for i = 1,#temp_macros do add_macro(temp_macros[i],where_struct_goes[2],filename) -- end where_struct_goes[3]=l else l=cdr(l) end if nullp(l) or not macro_params[car(l).macro_token] then my_err(car(l),'parameter expected after @apply({macros...}, got '.. car(l).macro_token ..' instead') end l=cdr(l) if nullp(l) or car(l).type~='Id' then my_err (car(l),'Id expected after @apply({macros...}, got '.. car(l).macro_token..' type = "'.. tostring( car(l).type) ..'" instead') end l=cdr(l) if nullp(l) or car(l).macro_token ~=')' then my_err(car(l), ') expected after @apply({macros...},?Id') end return cdr(l),where_struct_goes[2],caddr(where_struct_goes) end local skip_param_tokens={ ['param']=skip_one, --input matches till ['param until']=skip_one, --input matches till next, also matches () {} [] - stops for comma --if the expected next is a comma then that matches --if the expected next is not a comma and it finds one, that's a failure ['param match until']=skip_one, --in matches any number of elements including commas ['params']=skip_one, ['optional params']=skip_one, --generate var ['generate var']=skip_one, -- ['%external-load:']='global load', -- also need a 4th entry for saving ['apply macros']=skip_apply, } add_token_keys(macro_params) local match= { ['(']=')', ['{']='}', ['[']=']', ['do']='end', ['for']='do', --special cased to go for 'end' after 'do' ['while']='do', --special cased to go for 'end' after 'do' ['if']='end', ['function']='end', ['repeat']='until', --really needs to be until exp } local starts= { ['for']=true, ['while']=true, ['if']=true, ['function']=true, ['repeat']=true, ['local']=true, ['return']=true, } local separators= { [',']=true, [';']=true, } local ends={ ['end']=true } --[[ so here, car is [2] cdr is [3] --]] nullp= function(l) return l==Nil end local function listp(n) return type(n)=='table' and 'Cons' == n[1] end local function pairp(n) return (not nullp(n)) and listp(n) end last_cell=function(l) while pairp(cdr(l)) do l=cdr(l) end return l end car=function(n) if n==nil then error('car on lua nil') end return n[2] end cadr=function(n) if n==nil then error('cadr on lua nil') end return n[3][2] end caddr=function(n) if n==nil then error('caddr on lua nil') end return n[3][3][2] end cdddr=function(n) if n==nil then error('cdddr on lua nil') end return n[3][3][3] end cddr=function(n) if n==nil then error('cddr on lua nil') end return n[3][3] end cdr= function(n) if n==nil then error('cdr on lua nil') end return n[3] end cons = function (first, rest) return setmetatable({'Cons',first,rest}, {__tostring = cons_tostring, __concat= function(op1,op2) return tostring(op1) .. tostring(op2) end, __len=function(self) if nullp(self) then return 0 elseif nullp(self[3]) then return 1 elseif not listp(self[3]) then return 1.5 end return 1+ #(self[3]) end }) end local function reverse_transfer_one_in_place(dest,source) if source==nil then print 'wat' end if not nullp(source) then dest,source,source[3] = source,source[3],dest end return dest,source end reverse_list_in_place= function (l,concat) local d=concat or Nil while not nullp(l) do l,d,l[3]=l[3],l,d end return d end --otherwise known as nconc list_append_in_place = function(l,concat) local r=l while r[3]~=Nil do r=r[3] end r[3]=concat return l end reverse_list= function (l,concat) local d=concat or Nil while not nullp(l) do d=cons(l[2],d) l=l[3] end return d end local function array_to_list(a, concat) local l=concat or Nil if a then for i=#a,1,-1 do l=cons(a[i],l) end end return l end local function append_list_to_array(a,l) while not nullp(l) do table.insert(a,car(l)) l=cdr(l) end return a end local function array_to_reversed_list(a, concat) local l=concat or Nil if a then for i=1,#a do l=cons(a[i],l) end end return l end nthcar = function (n,l) repeat if nullp(l) then return Nil end if n>1 then n=n-1 l=cdr(l) else break end until false return car(l) end local function quoted_tostring(q) return tostring(q) -- if type(q)~='string' then return tostring(q) end -- if q:find("'",1,true) then -- if q:find('"',1,true) then -- return '[['..q..']]' -- else -- return '"'..q..'"' -- end -- else -- return "'"..q.."'" -- end end local function cons_rest_tostring(self) if (nullp(self[3])) then return ' ' .. quoted_tostring(self[2]) .. ' 」' elseif (listp(self[3])) then return ' ' .. quoted_tostring(self[2]) .. cons_rest_tostring(self[3]) else return ' ' .. quoted_tostring(self[2]) .. ' . ' .. quoted_tostring(self[3]) ..' 」' end end; cons_tostring = function(self) if nullp(self) then return '「」' elseif nullp(self[3]) then return '「 ' .. quoted_tostring(self[2]) .. ' 」' elseif listp(self[3]) then return '「 ' .. quoted_tostring(self[2]) .. cons_rest_tostring(self[3]) else return '「 ' .. quoted_tostring(self[2]) .. ' . ' .. quoted_tostring(self[3]) ..' 」' end end concat_cons= function(l,v) local dest = {} while not nullp(l) do table.insert(dest,l[2]) l=l[3] end return table.concat(dest,v) end output_render= function (l) --local d={} --while not nullp(l) do -- table.insert(d, car(l).macro_token) -- l=cdr(l) -- end local d={} -- local render_line,render_x = 0,0 local next_line = true while not nullp(l) do local t=car(l) local i,p i=t.indent+t.indent_delta if i<0 then i=0 end if t.first then next_line = true end if next_line then table.insert(d,'\n') p=i else p=t.dx if not p or p<1 then p=1 end end table.insert(d, string.rep(' ',p)) table.insert(d, t.macro_token) local k=t.token ---[[ while k and k.source[k.source_index+1] and not k.source[k.source_index+1].meaningful do local n = k.source[k.source_index+1] if n.type == "Comment" then if n.from_line ~= k.to_line then table.insert(d,'\n') table.insert(d,string.rep(' ',i)) else p=n.from_line-k.to_line if p<1 then p=1 end table.insert(d,string.rep(' ',p)) end table.insert(d,n.value) -- table.insert(d,'\n') end k=n end --]] l=cdr(l) next_line=l.dy end return table.concat(d,'') end --]=] render= function (l) local d={} while not nullp(l) do table.insert(d, car(l).macro_token) l=cdr(l) end return table.concat(d,'\n') end Nil = cons() Nil[2]=Nil Nil[3]=Nil assert(Nil==Nil[2]) local function read_to(token_clist,end_token) --print('read to "', tostring(strip_tokens_from_list(token_clist)),'" to',end_token ) local len =0; local r=token_clist while not nullp(r) and car(r).macro_token~=end_token do r=cdr(r) len=len+1 end if len~=0 and (car(r) or end_token=='@end') then -- print('succeeded') return true,r,len end -- print('failed') return false,token_clist,0 end optional_read_match_to = function(token_clist,end_token) -- print('read match to "', tostring(strip_tokens_from_list(token_clist)),'" to',end_token ) local r=token_clist local len=0 while not nullp(r) and car(r).macro_token~=end_token do local m= match[car(r).macro_token] if m then local succ,inc -- print('found new match '..car(r).macro_token ..' to ' .. match[car(r).macro_token]) succ,r,inc= optional_read_match_to(cdr(r),m) if not succ then -- print('failed inner match') return false,token_clist,0 end len=len+inc+1 if m=='do' then if nullp(r) then break end succ,r,inc= optional_read_match_to(cdr(r),'end') end end r=cdr(r) len=len+1 end if not nullp(r) or end_token=='@end' then -- print('succeeded') return true,r,len end -- print('failed') return false,token_clist,0 end read_match_to = function(token_clist,end_token) -- print('read match to "', tostring(strip_tokens_from_list(token_clist)),'" to',end_token ) local r=token_clist local len=0 while not nullp(r) and car(r).macro_token~=end_token do local m= match[car(r).macro_token] if m then local succ,inc -- print('found new match '..car(r).macro_token ..' to ' .. match[car(r).macro_token]) succ,r,inc= optional_read_match_to(cdr(r),m) if not succ then -- print('failed inner match') return false,token_clist,0 end len=len+inc+1 if m=='do' then if nullp(r) then break end succ,r,inc= optional_read_match_to(cdr(r),'end') end end r=cdr(r) len=len+1 end if len~=0 and (not nullp(r) or end_token=='@end') then -- print('succeeded') return true,r,len end -- print('failed') return false,token_clist,0 end read_match_to_no_commas= function(token_clist,end_token) --print('read match to no commas"', tostring(strip_tokens_from_list(token_clist)),'" to',end_token ) local r=token_clist local len=0 while not nullp(r) and car(r).macro_token~=end_token and car(r).macro_token~=','and car(r).macro_token~=';' do if match[car(r).macro_token] then local succ,inc -- print('found new match '..car(r).macro_token ..' to ' .. match[car(r).macro_token]) succ,r,inc= optional_read_match_to(cdr(r),match[car(r).macro_token]) if not succ then -- print('failed inner match') return false,token_clist,0 end len=len+inc+1 end r=cdr(r) len=len+1 end if len~=0 and ((nullp(r) and end_token=='@end') or car(r).macro_token==end_token) then -- print('succeeded') return true,r,len end -- print('failed') return false,token_clist,0 end local function sublist_end(a,p) return p==a[2] end local function list_append_to_reverse(r,e) while not nullp(e) do r=cons(car(e),r) e=cdr(e) end return r end local function list_append(l,e) if nullp(l) then return e end local d=cons(car(l)) local r1,r2=d,cdr(l) while not nullp(r2) do r1[3]=cons(car(r2)) r1=cdr(r1) r2=cdr(r2) end r1[3]=e return d end local gen_var_counter = 10000 local function gensym() gen_var_counter=gen_var_counter+1 return '__GENVAR_'.. tostring(gen_var_counter) .. '__' end --sublists are dangerious {pos-in-list, later-pos-in-same-list} --as long as that invariant holds, we're ok --not inclusive of second element local function sublist_equal(a,b) local ra=a[1] local rb=b[1] while not sublist_end(a,ra) and not sublist_end(b,rb) do if car(ra)~=car(rb) then return false end ra=cdr(ra) rb=cdr(rb) end return sublist_end(a,ra) == sublist_end(b,rb) end list_to_array = function(l) local d={} while not nullp(l) do table.insert(d,car(l)) l=cdr(l) end return d end local function sublist_to_array(s,endoff) local d = {} local r=s[1] endoff=endoff or 0 repeat table.insert(d,car(r)) if r==s[2] then break end r=cdr(r) until false while endoff>0 do table.remove(d) endoff=endoff-1 end return d end sublist_to_list= function (s,endoff) return array_to_list(sublist_to_array(s,endoff)) end list_to_stripped_array = function(l) local d={} while not nullp(l) do table.insert(d,car(l).macro_token) l=cdr(l) end return d end strip_tokens_from_list= function(l) return array_to_list(list_to_stripped_array(d)) end local function stripped_sublist_equal(a,b) return sublist_equal(strip_tokens_from_list(a),strip_tokens_from_list(b)) end local function sublist_to_stripped_string(s) return tostring(strip_tokens_from_list(sublist_to_list(s))) end local function sublist_to_string(s) return tostring(sublist_to_list(s)) end macros= { } copy_list = function (l) assert(l[1]=='Cons') local d=cons(Nil,Nil) local r=d local p=Nil while not nullp(l) do r[2]=car(l) l=cdr(l) r[3]=cons(Nil,Nil) p=r r=r[3] end p[3]=Nil return d end copy_list_and_object = function (l) local d=cons(Nil,Nil) local r=d local p=Nil while not nullp(l) do r[2]=simple_copy(car(l)) l=cdr(l) r[3]=cons(Nil,Nil) p=r r=r[3] end p[3]=Nil return d end local function apply_inner_macros(macros_dest,params,params_info,filename) local function replace_params(l) l=copy_list(l) local d=l local p=Nil while not nullp(l) do if car(l).macro_token and macro_params[car(l).macro_token] and cadr(l).macro_token and params_info[cadr(l).macro_token] and params_info[cadr(l).macro_token].value then local t if params_info[cadr(l).macro_token].value[1]=='Cons' then t = splice(l,list_to_array(params_info[cadr(l).macro_token].value),cddr(l)) else if macro_params[car(l).macro_token] == 'generate var' then if not params_info[cadr(l).macro_token].value then gen_var_counter=gen_var_counter+1 params_info[cadr(l).macro_token].value = setmetatable({ macro_token= '__GENVAR_'.. tostring(gen_var_counter) ..'__', type='Id'},token_metatable) end local k=simple_copy(car(l)) k.macro_token = params_info[cadr(l).macro_token].value.macro_token k.type = 'Id' --l[2]=k; l[3]=l[3][3] t= splice(p,{ k },cddr(l)) else t= splice(p,{ params_info[cadr(l).macro_token].value},cddr(l)) end if not nullp(p) then p[3]=t end end if p==Nil then d=t end p=l l=cddr(l) else p=l l=cdr(l) end end return d end local dest = {} if not params.head then error 'inner macros have to have a head' end if not params.body then error 'inner macros have to have a body' end dest.head=replace_params(params.head)--replace_params(array_to_list(string_to_token_array(params.head))) if params.body then if type(params.body) == 'function' then dest.body = params.body else; dest.body=replace_params(params.body or {})--replace_params(array_to_list(string_to_token_array(params.body or {}))) end end if params.semantic_function and type(params.semantic_function)~='function' then error 'semantic_function has to be a function' end dest.semantic_function = params.semantic_function dest.new_tokens = params.new_tokens dest.sections = params.section validate_params(dest.head,true) dest.handle, dest.handle_offset = scan_head_forward(dest.head) -- print('handle == '..dest.handle,'handle offset == '..dest.handle_offset) --you know what, there's no reason for a limit on how far forward a macro --can match, it just means the rescan has to go that far. -- scan_head_backward(dest.head) validate_params(dest.body) if params.sections then dest.sections={} for k,v in pairs(params.sections) do dest.sections[k]=replace_params(array_to_list(string_to_source_array(v))) validate_params(dest.sections[k]) end end -- print ('inner macro: offset ='..dest.handle_offset..' handle = '..dest.handle) while not macros_dest[dest.handle_offset] do table.insert( macros_dest,{} ) end if not macros_dest[dest.handle_offset][dest.handle] then macros_dest[dest.handle_offset][dest.handle]={} end table.insert(macros_dest[dest.handle_offset][dest.handle],dest) end validate_params= function (head, is_head,filename) if not head then print 'wat' end --head=array_to_list(head) while not nullp(head) do local c = car(head) if not c or not c.macro_token then print 'wat' end local is_param = macro_params[c.macro_token] if is_param == 'apply macros' then if is_head then error '@apply can not appear in the head' end elseif is_param and (nullp(cdr(head)) or cadr(head).type ~= 'Id') then my_err (car(head),"identifier missing after match specifier "..c.macro_token .." in head") end local apply_struct if is_param then local apply_struct head,apply_struct=skip_param_tokens[is_param](head,true,filename) -- if apply_struct then -- print('@apply on these macros:',apply_struct) -- end else head=cdr(head) end end end scan_head_forward= function(head) --head=array_to_list(head) i=1 while not nullp(head) do local c = car(head) local is_param = macro_params[c.macro_token] if is_param then if is_param~= 'param' then my_err(car(head),'macro must start with a constant token or constant preceded by single token params:'.. head) end else return c.macro_token,i end i=i+1 if is_param then head=cddr(head) else head=cdr(head) end end my_err (car(head),'macro must have a constant token:'.. head) end local function set_token_list_line(l,line) while not nullp(l) do local t=car(l) t.token.from_line=line t.token.from_x=0 t.token.to_line=line t.token.to_x=0 l=cdr(l) end end --[[Possibly params new_tokens, head (required) semantic_function body / (can be a function) sections = {section_name (can be functions)...}} macros_dest is optional ]] add_macro= function (params, macros_dest,filename,line) add_tokens(params.new_tokens) local dest = {} if not params.head then error 'macros have to have a head' end dest.head=array_to_list(string_to_source_array(params.head,filename,my_err)) if line then set_token_list_line(dest.head,line) end dest.internal_function_body=params.internal_function_body if params.body then if type(params.body) == 'function' then dest.body = params.body else dest.body=array_to_list(string_to_source_array(params.body or {},filename,my_err)) if line then set_token_list_line(dest.body,line) end end end if params.semantic_function and type(params.semantic_function)~='function' then error 'semantic_function has to be a function' end dest.semantic_function = params.semantic_function dest.new_tokens = params.new_tokens dest.sections = params.section validate_params(dest.head,true,filename) dest.handle, dest.handle_offset = scan_head_forward(dest.head) -- print('handle == '..dest.handle,'handle offset == '..dest.handle_offset) --you know what, there's no reason for a limit on how far forward a macro --can match, it just means the rescan has to go that far. -- scan_head_backward(dest.head) if dest.body and type(dest.body) ~= 'function' then validate_params(dest.body,false,filename) end if params.sections then dest.sections={} for k,v in pairs(params.sections) do dest.sections[k]=array_to_list( string_to_source_array(v)) if line then set_token_list_line(dest.sections[k],line) end validate_params(dest.sections[k],false,filename) end end macros_dest = macros_dest or macros while not macros_dest[dest.handle_offset] do table.insert(macros_dest,{}) end if not macros_dest[dest.handle_offset][dest.handle] then macros_dest[dest.handle_offset][dest.handle]={} end --print('macro on handle '..dest.handle..' defined') table.insert(macros_dest[dest.handle_offset][dest.handle],dest) end local function token_copy(token) local t=simple_copy(token) t.token=simple_copy(t.token) return t end local splice_body = array_to_list(string_to_source_array('?a ?b')) add_macro({ head='?1a @@ ?1b', internal_function_body= function(param_info,c,do_body) local ok,s,ret,n = do_body(splice_body,c) if ok then ret[2]=token_copy(ret[2]) car(ret).macro_token = car(ret).macro_token .. cadr(ret).macro_token ret[3]=ret[3][3] car(ret).type = 'Id' end return ok,s,ret,n end, }) local tostring_body = array_to_list(string_to_source_array('"dummy" ?a')) tostring_list={ '=', '==', '===', '====', '=====', '======', '=======', '========', '==========', '===========', '============', '=============', '==============', '===============', } to_string_counter=0 local function next_to_string_delimiters() local n=to_string_counter+1 to_string_counter=(to_string_counter+1)%(#tostring_list) return '['.. tostring_list[n]..'[' ,']'.. tostring_list[n]..']' end add_macro({ head='@tostring(?,a)', internal_function_body= function(param_info,c,do_body) local ok,s,ret,n = do_body(tostring_body,c) local open_del,close_del = next_to_string_delimiters() local dest = {open_del} if ok then ret[2]=token_copy(ret[2]) local l = param_info['a'].value local e = ret[3] local first=true while not nullp(l) do e=e[3] if not first then table.insert(dest,' ') end first = false table.insert(dest,car(l).macro_token) l=cdr(l) end table.insert(dest,close_del) car(ret).macro_token = table.concat(dest,'') car(ret).token.processed = cadr(ret).macro_token car(ret).token.value = car(ret).macro_token ret[3]=e end return ok,s,ret,n end }) local function add_simple_translate(m,t) simple_translate[m]=t end for i,v in ipairs(macros) do add_tokens(v.new_tokens) v.head=string_to_source_array(v.head) if v.body then v.body=string_to_source_array(v.body) end end -- processed,replaced_tokens_list,last_replaced_token_list_element =macro_match(flatten,pos,v) -- needs to return a sublist -- returns processed/didn't followed by first element replace followed by last element of macro local function macro_match(datac,macro,filename) local head=macro.head --array_to_list(macro.head) local c,pos=datac,head local param_info={} --type=, value= if macro.match_debug then print('match debug') end local sanitized, tagged_sanitized,matched_to,functional_macros,sanitized_param_info,simple_param_info,functional_macro_data functional_macros = macro.semantic_function~=nil or type(macro.body)=='function' if functional_macros then sanitized = {} tagged_sanitized={} end --reading into parameters in the head --if they already have values, then verifying that they match local match = function(match_fn) -- read_to, read_match_to or read_match_to_no_commas --pos must point at the parameter specifier ie ? --caddr(pos) will be what we stop at if nullp(caddr(pos)) then my_err (cadr(pos), "match until must have a token after it") end if macro_params[caddr(pos).macro_token] then my_err (caddr(pos), "match until must end with a constant token") end --success, end token (the one targetted), number of tokens matched including final matched_to = caddr(pos).macro_token local succ, nc, inc = match_fn(c,caddr(pos).macro_token) if not succ then return false end -- print("match succeeded, inc =",inc) -- if the parameter you're matching into already has a value, that's ok if the text matched has the same -- tokens as what it already holds if param_info[cadr(pos).macro_token].value then -- prolog style equality matching if not (stripped_sublist_equal(param_info[cadr(pos).macro_token].value,{c,nc})) then -- print('reusing parameter match failed on', cadr(pos).macro_token ) return false else -- print(cadr(pos).macro_token, "= a previous match", sublist_to_stripped_string(param_info[cadr(pos).macro_token])) end else --copy match into the parameter, cutting off the stop character param_info[cadr(pos).macro_token].value = sublist_to_list({c,nc},1) --if nothing was matched, that's a failure --we could make a match type that accepts empty matchesS --{}{}{} maybe we should allow this or make it an option maybe ?? instead of ? -- if #(param_info[cadr(pos).macro_token].value) == 0 then -- print("empty parameter") -- return false -- end -- print(cadr(pos).macro_token,"set to",tostring(strip_tokens_from_list(param_info[cadr(pos).macro_token].value))) end c=nc pos=cdddr(pos) return true end while not nullp(pos) do --head if car(pos).macro_token==car(c).macro_token then if functional_macros then table.insert(sanitized,car(c).macro_token) table.insert(tagged_sanitized,{tag='literal',car(c).macro_token}) end pos=cdr(pos) c=cdr(c) elseif car(pos).macro_token=='@end' and nullp(c) then --???{}{}{} pos=cdr(pos) elseif macro_params[car(pos).macro_token] then local param_type = macro_params[car(pos).macro_token] local param_name=cadr(pos).macro_token -- @apply doesn't appear in the head if not param_info[param_name] then param_info[param_name]={type=param_type} end -- Already checked that the next is an Id if param_type=='param' then if functional_macros then table.insert(sanitized,car(c).macro_token) table.insert(tagged_sanitized,{tag=param_type,name=param_name,car(c).macro_token}) end if param_info[param_name].value then -- prolog style equality matching if param_info[param_name].value.macro_token~=car(c).macro_token then return false,datac else -- print(cadr(pos).macro_token, "= a previous match", car(c).macro_token) end else param_info[param_name].value=car(c) -- print(cadr(pos).macro_token,"set to",car(c).macro_token) end pos=cddr(pos) else if macro_params[car(pos).macro_token]=='param until' then if not match(read_to) then return false,datac end elseif macro_params[car(pos).macro_token]=='params' then if not match(read_match_to) then return false,datac end elseif macro_params[car(pos).macro_token]=='optional params' then if not match(optional_read_match_to) then return false,datac end elseif macro_params[car(pos).macro_token]=='param match until' then if not match(read_match_to_no_commas) then return false,datac end elseif macro_params[car(pos).macro_token]=='generate var' then my_err (car(pos), "can't have a generate variable in a macro head") else --unused so far end if functional_macros then local r=param_info[param_name].value local tagged={tag=param_type,name=param_name} while not nullp(r) do table.insert(sanitized,car(r).macro_token) table.insert(tagged,car(r).macro_token) r=cdr(r) end table.insert(tagged_sanitized,tagged) table.insert(sanitized,matched_to) table.insert(tagged_sanitized,{tag='literal', matched_to}) end end c=cdr(c) else return false,datac end end local do_body= function (body,tc,f) local dest={} --splices c on after local bi=body -- print("Scanning Body", strip_tokens_from_list( body)) while not nullp(bi) do -- if not bi or not body or not body[bi] or not body[bi].macro_token then -- print 'breakpoint' -- end local param_type_text=macro_params[car(bi).macro_token] local param_type=nil if param_type_text=='apply macros' then local inner_macros,p bi,inner_macros,p= skip_param_tokens[param_type_text](bi) -- print('++++++++++++++++++++++++++++', inner_macros) local temp={} for _,i in ipairs(inner_macros) do for _,j in pairs(i) do --ordered by handle offset for _,k in ipairs(j) do if k.head then apply_inner_macros(temp,k,param_info,filename) end end end end temp=apply_macros(temp,param_info[p.macro_token].value,filename) dest=append_list_to_array(dest,temp) else if param_type_text then bi= skip_param_tokens[param_type_text](bi) if param_type_text=='generate var' then if not param_info[car(bi).macro_token] then param_info[car(bi).macro_token]={type='generate var'} end end if not param_info[car(bi).macro_token] then my_err(car(bi), "body contains a parameter that isn't in the head") end param_type = param_info[car(bi).macro_token].type -- print('param type = '..param_type) end -- if param_type_text=='generate var' if not param_type_text then table.insert(dest,car(bi)) -- dest=cons(body[bi],dest) -- print('>>',car(bi).macro_token) elseif not param_type then my_err (car(bi),' unmatched parameter '..car(bi).macro_token) elseif param_type=='param' then table.insert(dest,param_info[car(bi).macro_token].value) -- dest=cons(param_info[body[bi].macro_token].value,dest) -- print('>>',param_info[car(bi).macro_token].value) elseif param_type=='param until' or param_type=='param match until' or param_type=='params' or param_type=='optional params' then dest=append_list_to_array(dest,param_info[car(bi).macro_token].value) -- print('>>',param_info[car(bi).macro_token].value) elseif param_type=='generate var' then if not param_info[car(bi).macro_token].value then gen_var_counter=gen_var_counter+1 param_info[car(bi).macro_token].value = setmetatable({ macro_token= '__GENVAR_'.. tostring(gen_var_counter) ..'__', type='Id'},token_metatable) -- print('generating variable',car(bi).macro_token, 'as',param_info[car(bi).macro_token].value ) end -- dest=cons(param_info[body[bi].macro_token].value,dest) local t = simple_copy(car(bi)) t.macro_token = param_info[car(bi).macro_token].value.macro_token t.type = dest,param_info[car(bi).macro_token].value.type table.insert(dest,t) -- print('>>',param_info[car(bi).macro_token].value) else --unused so far end bi=cdr(bi) end --~= apply macro end --while -- return true,tc,splice(datac,dest,tc,f) end --function do_body if functional_macros then sanitized_param_info = { } simple_param_info = {} for k,v in pairs(param_info) do if v.type == 'param' then sanitized_param_info[k]={v.value.macro_token} simple_param_info[k]=v.value.macro_token else sanitized_param_info[k]= list_to_stripped_array(v.value) simple_param_info[k]= table.concat(sanitized_param_info[k],' ') end end functional_macro_data = {params = simple_param_info, param_lists = sanitized_param_info, source = sanitized, tagged_source = tagged_sanitized } end if macro.semantic_function then local sem_return = macro.semantic_function(functional_macro_data) if not sem_return then return false,datac end end function do_sections() if macro.sections then --{}{}{} ignore sections for now for section,m in pairs(macro.sections) do if type(m) == 'function' then if not filename2sections[filename] then my_err(cadr(start),'No sections in file '..filename..' have been found.') end local sublist = filename2sections[filename][section] if not sublist then my_err(cadr(start),'no section '..cadr(start).token.processed..' in file '..filename..' found.') end local body_ret_s = m(functional_macro_data) if body_ret_s then --return true, dest, start splice_simple(datac,string_to_source_array(body_ret_s,filename,my_err),sublist[2][3]) --return true,array_to_list(string_to_source_array(body_ret,filename,my_err),c),c end else do_body(m,section,filename) end end end end if macro.internal_function_body then local body_ret,b,c = macro.internal_function_body(param_info,c,do_body) if body_ret then return body_ret,b,c end return false,datac elseif macro.body then if type(macro.body) == 'function' then --{}{}{} sanitize local body_ret = macro.body(functional_macro_data) if body_ret then --return true, dest, start do_sections() return true,c,splice_simple(datac,string_to_source_array(body_ret,filename,my_err),c) --return true,array_to_list(string_to_source_array(body_ret,filename,my_err),c),c end return false,datac else do_sections() return do_body(macro.body,c) end end end -- this could be written differently if 'list' is always a double linked list apply_macros = function(macros, flatten,filename) flatten=reverse_list_in_place(flatten) -- we keep the active portion of the expansion by transfering between a reversed and a forward list -- instead of having a double linked list. local dest = Nil -- dest is the forward list, we will move forward as we expand while not nullp(flatten) do dest,flatten = reverse_transfer_one_in_place(dest,flatten) -- move one token from the beginning of the reversed list to the beginning of the forward list -- dest = cons(car(flatten),dest) -- flatten=cdr(flatten) local done -- we are done at a token when we've tried all macros and none expanded -- eventually we should optimize this, but we have to keep the macros in order so it won't be simple repeat done = true for nth,macros_per_offset in ipairs(macros) do local t=macros_per_offset[nthcar(nth,dest).macro_token] if t then for i,v in ipairs(t) do local processed,start --a bit of optimization --if I can table drive this more it could be more optimized, but --how to maintain macro order then? assert(nth == v.handle_offset) assert( v.handle == nthcar(nth,dest).macro_token) -- have we found a macro with the right handle? processed,dest,start=macro_match(dest,v,filename) -- if so process the macro if processed then -- if the macro expanded, it did so at the beginning of dest -- dump the whole processed portion back into the reverse list to rescan done = false --set rescan back by the whole macro --is it possible that it sets up less than a whole macro? --rescan from the end of the new substitution while start~=dest do flatten, start = reverse_transfer_one_in_place(flatten,start) -- flatten=cons(car(start),flatten) -- start=cdr(start) end break -- should always scan macros in order! end end end end until done end return dest end local function token_error_handler(token) my_err(setmetatable({macro_token=simple_translate[token.value], type = token.type, token=token},token_metatable),'illegal token') end --process as used by process sections just processes a list and returns a list --no preprocessing, no rendering to a string --this is signaled by no_render not being nil process = function(str,filename, no_render,skipping) local source_array local source_list if no_render then source_list = str else if skipping then source_array = string_to_source_array(str,filename,token_error_handler) -- stores simple translated names in macro_token, and the whole token in token else source_array = string_to_source_array(str,filename) -- stores simple translated end source_list=array_to_list(source_array) -- convert to sexpr so that it's more end end local lines = {} -- make array of lines in order to handle preprocessor directives that only appear at the beginning of lines -- 'lines[]' contains pointers into the continuous sexpr in source_list local function add_line(i,v) if not lines[i+1] then --plus 1 because I count lines from 0 while #lines <= i do table.insert(lines,0) end lines[i+1]=v end end local p,prev=source_list,'Cons' -- the first element of the double linked list remains a cons cell, It would be better to have a root cell -- I currently have to fake changing the first element, and that might not work in all cases. if not no_render then while not nullp(p) do -- turn source_list into a double linked list add_line(car(p).token.from_line,p) p[1]=prev prev=p p=cdr(p) end if skipping then redo_if_statements(lines) end local i=0 --line numbers and x positions count from 0 while i < #lines do -- handle preprocessor directives that only appear as the first token of lines -- if lines[i] == 0 then -- print('line '..i..' is blank') -- else -- print('line '..i.. 'is at ' .. car(lines[i]).token.from_line .. ' is a '.. car(lines[i]).macro_token) -- if lines[i][1]=='Cons' then print ('is first token') else print('prev token at line '..car(lines[i][1]).token.from_line .. ' is a '.. car(lines[i][1]).macro_token) end -- end if lines[i+1] ~= 0 then -- local fn = preprocessor_tokens[car(lines[i+1]).macro_token] -- if fn~= pp_null_fn then -- print ('preprocess', car(lines[i+1]).macro_token) -- end i = preprocessor_tokens[car(lines[i+1]).macro_token](lines,i,filename, skipping) -- returns the next line to process else i=i+1 end end --kludge so that special tokens will be added if not skipping then print 'phase 2' return process(str,filename, no_render,true) end end -- print('after preprocess statements are removed, file is [' .. strip_tokens_from_list(source_list) .. ']') local dest= apply_macros(macros,strip_back_links(source_list), filename) -- apply global macros. I strip the back links and nulified intial links just so that -- there can't be any bugs caused by using the back links when they're no longer valid --{}{}{} could use formatting if no_render then return dest end process_sections(filename) local ret=render(dest,'\n') -- print(strip_tokens_from_list( dest)) return ret,dest,output_render(dest) end local macro_path = string.gsub(package.path,'%.lua','.pp.lua') -- Install the loader so that it's callled just before the normal Lua loader local function load(modulename) local errmsg = "" -- Find source local modulepath = string.gsub(modulename, "%.", "/") for path in string.gmatch(macro_path, "([^;]+)") do local filename = string.gsub(path, "%?", modulepath) local file = io.open(filename, "rb") if file then -- Compile and return the module print('here!') local string, tokens,output_string = process(assert(file:read("*a")),filename) return assert(my_loadstring(string, filename,tokens,output_string)) end errmsg = errmsg.."\n\tno file '"..filename.."' (checked with custom loader)" end return errmsg end table.insert(package.loaders, 2, load) local function scriptload(modulename) local errmsg = "" -- Find source local modulepath = string.gsub(modulename, "%.", "/") for path in string.gmatch(macro_path, "([^;]+)") do local filename = modulename local file = io.open(filename, "rb") if file then -- Compile and return the module print('here!') local string, tokens,output_string = process(assert(file:read("*a")),filename) return assert(my_loadstring(string, filename,tokens,output_string)) end errmsg = errmsg.."\n\tno file '"..filename.."' (checked with custom loader)" end return errmsg end macro_system = { gensym=gensym, add = add_macro, add_simple=add_simple_translate, load=load, scriptload=scriptload, } return macro_system
local F, C, L = unpack(select(2, ...)) local UNITFRAME = F:GetModule('Unitframe') local format, floor = string.format, math.floor local cfg = C.unitframe local tags = FreeUI.oUF.Tags.Methods local tagEvents = FreeUI.oUF.Tags.Events local tagSharedEvents = FreeUI.oUF.Tags.SharedEvents local function usub(str, len) local i = 1 local n = 0 while true do local b,e = string.find(str, '([%z\1-\127\194-\244][\128-\191]*)', i) if(b == nil) then return str end i = e + 1 n = n + 1 if(n > len) then local r = string.sub(str, 1, b-1) return r end end end local function ShortenName(unit, len) if not UnitIsConnected(unit) then return end local name = UnitName(unit) if name and name:len() > len then name = usub(name, len) end return name end tags['free:dead'] = function(unit) if UnitIsDead(unit) then return '|cffd84343Dead|r' elseif UnitIsGhost(unit) then return '|cffbd69beGhost|r' end end tagEvents['free:dead'] = 'UNIT_HEALTH' tags['free:offline'] = function(unit) if not UnitIsConnected(unit) then return '|cffccccccOff|r' end end tagEvents['free:offline'] = 'UNIT_HEALTH UNIT_CONNECTION' tags['free:name'] = function(unit) if (unit == 'targettarget' and UnitIsUnit('targettarget', 'player')) then return '|cffff0000> YOU <|r' else return ShortenName(unit, 6) end end tagEvents['free:name'] = 'UNIT_NAME_UPDATE UNIT_TARGET PLAYER_TARGET_CHANGED' tags['free:health'] = function(unit) if not UnitIsConnected(unit) or UnitIsDead(unit) or UnitIsGhost(unit) then return end local cur = UnitHealth(unit) local r, g, b = unpack(FreeUI.oUF.colors.reaction[UnitReaction(unit, 'player') or 5]) return format('|cff%02x%02x%02x%s|r', r * 255, g * 255, b * 255, F.Numb(cur)) end tagEvents['free:health'] = 'UNIT_CONNECTION UNIT_HEALTH_FREQUENT UNIT_MAXHEALTH' tags['free:percentage'] = function(unit) if not UnitIsConnected(unit) or UnitIsDead(unit) or UnitIsGhost(unit) then return end local cur, max = UnitHealth(unit), UnitHealthMax(unit) local r, g, b = ColorGradient(cur, max, 0.69, 0.31, 0.31, 0.65, 0.63, 0.35, 0.33, 0.59, 0.33) r, g, b = r * 255, g * 255, b * 255 if cur ~= max then return format('|cff%02x%02x%02x%d%%|r', r, g, b, floor(cur / max * 100 + 0.5)) end end tagEvents['free:percentage'] = 'UNIT_CONNECTION UNIT_HEALTH_FREQUENT UNIT_MAXHEALTH' tags['free:power'] = function(unit) local cur, max = UnitPower(unit), UnitPowerMax(unit) if(cur == 0 or max == 0 or not UnitIsConnected(unit) or UnitIsDead(unit) or UnitIsGhost(unit)) then return end return F.Numb(cur) end tagEvents['free:power'] = 'UNIT_POWER_FREQUENT UNIT_MAXPOWER UNIT_DISPLAYPOWER' tags['free:groupname'] = function(unit) if not UnitIsConnected(unit) then return 'Off' elseif cfg.groupNames then if UnitInRaid('player') then return ShortenName(unit, 2) else return ShortenName(unit, 4) end else if UnitIsDead(unit) then return 'Dead' elseif UnitIsGhost(unit) then return 'Ghost' else return '' end end end tagEvents['free:groupname'] = 'UNIT_HEALTH GROUP_ROSTER_UPDATE UNIT_CONNECTION' local function UpdateUnitNameColour(self) if self.unitStyle == 'party' or self.unitStyle == 'raid' or self.unitStyle == 'boss' then if (UnitIsUnit(self.unit, 'target')) then self.Name:SetTextColor(95/255, 222/255, 215/255) elseif UnitIsDead(self.unit) then self.Name:SetTextColor(216/255, 67/255, 67/255) elseif UnitIsGhost(self.unit) then self.Name:SetTextColor(189/255, 105/255, 190/255) elseif not UnitIsConnected(self.unit) then self.Name:SetTextColor(204/255, 204/255, 204/255) else self.Name:SetTextColor(1, 1, 1) end end end function UNITFRAME:AddNameText(self) local name if self.unitStyle == 'party' or self.unitStyle == 'raid' then name = F.CreateFS(self.Health, (C.isCNClient and {C.font.normal, 11}) or 'pixel', '', nil, (C.isCNClient and {0, 0, 0, 1, 0, -2}) or true) self:Tag(name, '[free:groupname]') else name = F.CreateFS(self.Health, (C.isCNClient and {C.font.normal, 11}) or 'pixel', '', nil, (C.isCNClient and {0, 0, 0, 1, 0, -2}) or true) if self.unitStyle == 'target' then name:SetPoint('BOTTOMRIGHT', self, 'TOPRIGHT', 0, 3) elseif self.unitStyle == 'boss' then name:SetPoint('BOTTOMLEFT', self, 'TOPLEFT', 0, 3) else name:SetPoint('BOTTOM', self, 'TOP', 0, 3) end self:Tag(name, '[free:name]') end self.Name = name if self.unitStyle == 'party' or self.unitStyle == 'raid' or self.unitStyle == 'boss' then self:RegisterEvent('UNIT_HEALTH_FREQUENT', UpdateUnitNameColour, true) self:RegisterEvent('PLAYER_TARGET_CHANGED', UpdateUnitNameColour, true) self:RegisterEvent('UNIT_CONNECTION', UpdateUnitNameColour, true) end end function UNITFRAME:AddHealthValue(self) local healthValue = F.CreateFS(self.Health, 'pixel', '', nil, true) healthValue:SetPoint('BOTTOMLEFT', self, 'TOPLEFT', 0, 3) if self.unitStyle == 'player' then self:Tag(healthValue, '[free:dead][free:health]') elseif self.unitStyle == 'target' then self:Tag(healthValue, '[free:dead][free:offline][free:health] [free:percentage]') elseif self.unitStyle == 'boss' then healthValue:ClearAllPoints() healthValue:SetPoint('BOTTOMRIGHT', self, 'TOPRIGHT', 0, 3) healthValue:SetJustifyH('RIGHT') self:Tag(healthValue, '[free:dead][free:health]') elseif self.unitStyle == 'arena' then healthValue:ClearAllPoints() healthValue:SetPoint('BOTTOMRIGHT', self, 'TOPRIGHT', 0, 3) healthValue:SetJustifyH('RIGHT') self:Tag(healthValue, '[free:dead][free:offline][free:health]') end self.HealthValue = healthValue end function UNITFRAME:AddHealthPercentage(self) local healthPercentage = F.CreateFS(self.Health, 'pixel', '', nil, true) healthPercentage:SetPoint('LEFT', self, 'RIGHT', 4, 0) self:Tag(healthPercentage, '[free:percentage]') self.HealthPercentage = healthPercentage self.HealthPercentage = healthPercentage end function UNITFRAME:AddPowerValue(self) local powerValue = F.CreateFS(self.Health, 'pixel', '', nil, true) powerValue:SetPoint('BOTTOMRIGHT', self, 'TOPRIGHT', 0, 3) if self.unitStyle == 'target' then powerValue:ClearAllPoints() powerValue:SetPoint('BOTTOMLEFT', self.HealthValue, 'BOTTOMRIGHT', 4, 0) elseif self.unitStyle == 'boss' then powerValue:ClearAllPoints() powerValue:SetPoint('BOTTOMRIGHT', self.HealthValue, 'BOTTOMLEFT', -4, 0) end self:Tag(powerValue, '[powercolor][free:power]') powerValue.frequentUpdates = true self.PowerValue = powerValue end tags['free:level'] = function(unit) local level = UnitLevel(unit) local color = GetCreatureDifficultyColor(level) local r, g, b = color.r, color.g, color.b if(level > 0) then return format('|cff%02x%02x%02x%s|r', r * 255, g * 255, b * 255, level) else return '|cffff2735??|r' end end tagEvents['free:level'] = 'UNIT_LEVEL PLAYER_LEVEL_UP' tags['free:classification'] = function(unit) local class = UnitClassification(unit) if(class == 'elite') then return '|cffCC3300+|r' elseif(class == 'rare') then return '|cffFF99FFRare|r' elseif(class == 'rareelite') then return '|cffFF0099Rare+|r' elseif(class == 'worldboss') then --return '|cffff2735Boss|r' return '' elseif(class == 'minus') then return '|cff888888-|r' end end tagEvents['free:classification'] = 'UNIT_CLASSIFICATION_CHANGED' function UNITFRAME:AddLevelText(self) local levelText = F.CreateFS(self.Health, 'pixel', '', nil, true) levelText:SetPoint('BOTTOMRIGHT', self.Name, 'BOTTOMLEFT', -4, 0) self:Tag(levelText, '[free:level][free:classification]') self.Level = levelText end tags['free:pvp'] = function(unit) if(UnitIsPVP(unit)) then return '|cffff2735P|r' end end tagEvents['free:pvp'] = 'UNIT_FACTION' function UNITFRAME:AddPVPText(self) local PVPText = F.CreateFS(self.Health, 'pixel', nil, nil, true) PVPText:SetPoint('BOTTOMRIGHT', self.PowerValue, 'BOTTOMLEFT', -4, 0) self:Tag(PVPText, '[free:pvp]') self.PVP = PVPText end function UNITFRAME:AddLeaderText(self) local leaderText = F.CreateFS(self.Health, 'pixel', 'L', nil, true) leaderText:SetPoint('TOPLEFT', self.Health, 2, -2) self:Tag(leaderText, '[leader]') self.Leader = leaderText end
hs.alert.show("Spacehammer config loaded") -- Support upcoming 5.4 release and also use luarocks' local path package.path = package.path .. ";" .. os.getenv("HOME") .. "/.luarocks/share/lua/5.4/?.lua;" .. os.getenv("HOME") .. "/.luarocks/share/lua/5.4/?/init.lua" package.cpath = package.cpath .. ";" .. os.getenv("HOME") .. "/.luarocks/lib/lua/5.4/?.so" package.path = package.path .. ";" .. os.getenv("HOME") .. "/.luarocks/share/lua/5.3/?.lua;" .. os.getenv("HOME") .. "/.luarocks/share/lua/5.3/?/init.lua" package.cpath = package.cpath .. ";" .. os.getenv("HOME") .. "/.luarocks/lib/lua/5.3/?.so" fennel = require("fennel") table.insert(package.loaders or package.searchers, fennel.searcher) require "core"
Lists = { --Custom Pedestals Pedestals = { PEDESTAL_DEFAULT = 0, NUM_PEDESTALS = 1, ANIMFILE = "gfx/Items/Pick Ups/Pedestals/animation.anm2", }, --Enemy Subtypes EnemySubTypes = { }, --Tear subs TearSubTypes = { }, --Helper Callbacks Callbacks = { ENTITY_SPAWN = 1 }, --Default unlockflags DefUnlockFlags = { Satan = false, Isaac = false, Lamb = false, BlueBaby = false, Greed = false, Greedier = false, BossRush = false, Mom = false, Heart = false, Delirium = false, MegaSatan = false, Hush = false, Ezekiel = false, }, --Eternal jumping workaround JumpVariant = { }, --functiontypes fnTypes = { UPDATE = "updateFns", INIT = "initFns", ANIM = "animFns", EVENT = "eventFns" } } return Lists
local bin = require "bin" local coroutine = require "coroutine" local nmap = require "nmap" local os = require "os" local stdnse = require "stdnse" local table = require "table" description = [[ Discovers PC-DUO remote control hosts and gateways running on a LAN by sending a special broadcast UDP probe. ]] --- -- @usage -- nmap --script broadcast-pc-duo -- -- @output -- Pre-scan script results: -- | broadcast-pc-duo: -- | PC-Duo Gateway Server -- | 10.0.200.113 - WIN2K3SRV-1 -- | PC-Duo Hosts -- |_ 10.0.200.113 - WIN2K3SRV-1 -- -- @args broadcast-pc-duo.timeout specifies the amount of seconds to sniff -- the network interface. (default varies according to timing. -T3 = 5s) author = "Patrik Karlsson" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = { "broadcast", "safe" } local TIMEOUT = stdnse.parse_timespec(stdnse.get_script_args("broadcast-pc-duo.timeout")) prerule = function() return ( nmap.address_family() == "inet") end -- Sends a UDP probe to the server and processes the response -- @param probe table contaning a pc-duo probe -- @param responses table containing the responses local function udpProbe(probe, responses) local condvar = nmap.condvar(responses) local socket = nmap.new_socket("udp") socket:set_timeout(500) for i=1,2 do local status = socket:sendto(probe.host, probe.port, probe.data) if ( not(status) ) then return "\n ERROR: Failed to send broadcast request" end end local timeout = TIMEOUT or ( 20 / ( nmap.timing_level() + 1 ) ) local stime = os.time() local hosts = {} repeat local status, data = socket:receive() if ( status ) then local srvname = data:match(probe.match) if ( srvname ) then local status, _, _, rhost, _ = socket:get_info() if ( not(status) ) then socket:close() return false, "Failed to get socket information" end -- avoid duplicates hosts[rhost] = srvname end end until( os.time() - stime > timeout ) socket:close() local result = {} for ip, name in pairs(hosts) do table.insert(result, ("%s - %s"):format(ip,name)) end if ( #result > 0 ) then result.name = probe.topic table.insert(responses, result) end condvar "signal" end action = function() -- PC-Duo UDP probes local probes = { -- PC-Duo Host probe { host = { ip = "255.255.255.255" }, port = { number = 1505, protocol = "udp" }, data = bin.pack("H", "00808008ff00"), match= "^.........(%w*)\0", topic= "PC-Duo Hosts" }, -- PC-Duo Gateway Server probe { host = { ip = "255.255.255.255" }, port = { number = 2303, protocol = "udp" }, data = bin.pack("H", "20908008ff00"), match= "^.........(%w*)\0", topic= "PC-Duo Gateway Server" }, } local threads, responses = {}, {} local condvar = nmap.condvar(responses) -- start a thread for each probe for _, p in ipairs(probes) do local th = stdnse.new_thread( udpProbe, p, responses ) threads[th] = true end -- wait until the probes are all done repeat for thread in pairs(threads) do if coroutine.status(thread) == "dead" then threads[thread] = nil end end if ( next(threads) ) then condvar "wait" end until next(threads) == nil table.sort(responses, function(a,b) return a.name < b.name end) -- did we get any responses if ( #responses > 0 ) then return stdnse.format_output(true, responses) end end
--- The game module. -- @module Game -- @usage local Game = require('__stdlib__/stdlib/game') local Game = { __class = 'Game', __index = require('__stdlib__/stdlib/core') } setmetatable(Game, Game) local Is = require('__stdlib__/stdlib/utils/is') --- Return a valid player object from event, index, string, or userdata -- @tparam string|number|LuaPlayer|event mixed -- @treturn LuaPlayer a valid player or nil function Game.get_player(mixed) if type(mixed) == 'table' then if mixed.player_index then return game.get_player(mixed.player_index) elseif mixed.__self then return mixed.valid and mixed end elseif mixed then return game.get_player(mixed) end end --- Return a valid force object from event, string, or userdata -- @tparam string|LuaForce|event mixed -- @treturn LuaForce a valid force or nil function Game.get_force(mixed) if type(mixed) == 'table' then if mixed.__self then return mixed and mixed.valid and mixed elseif mixed.force then return Game.get_force(mixed.force) end elseif type(mixed) == 'string' then local force = game.forces[mixed] return (force and force.valid) and force end end function Game.get_surface(mixed) if type(mixed) == 'table' then if mixed.__self then return mixed.valid and mixed elseif mixed.surface then return Game.get_surface(mixed.surface) end elseif mixed then local surface = game.surfaces[mixed] return surface and surface.valid and surface end end --- Messages all players currently connected to the game. --> Offline players are not counted as having received the message. -- If no players exist msg is stored in the `global._print_queue` table. -- @tparam string msg the message to send to players -- @tparam[opt] ?|nil|boolean condition the condition to be true for a player to be messaged -- @treturn uint the number of players who received the message. function Game.print_all(msg, condition) local num = 0 if #game.players > 0 then for _, player in pairs(game.players) do if condition == nil or select(2, pcall(condition, player)) then player.print(msg) num = num + 1 end end return num else global._print_queue = global._print_queue or {} global._print_queue[#global._print_queue + 1] = msg end end --- Gets or sets data in the global variable. -- @tparam string sub_table the name of the table to use to store data. -- @tparam[opt] mixed index an optional index to use for the sub_table -- @tparam mixed key the key to store the data in -- @tparam[opt] boolean set store the contents of value, when true return previously stored data -- @tparam[opt] mixed value when set is true set key to this value, if not set and key is empty store this -- @treturn mixed the chunk value stored at the key or the previous value function Game.get_or_set_data(sub_table, index, key, set, value) Is.Assert.String(sub_table, 'sub_table must be a string') global[sub_table] = global[sub_table] or {} local this if index then global[sub_table][index] = global[sub_table][index] or {} this = global[sub_table][index] else this = global[sub_table] end local previous if set then previous = this[key] this[key] = value return previous elseif not this[key] and value then this[key] = value return this[key] end return this[key] end function Game.write_mods() game.write_file('Mods.lua', 'return ' .. inspect(game.active_mods)) end function Game.write_statistics() local pre = 'Statistics/' .. game.tick .. '/' for _, force in pairs(game.forces) do local folder = pre .. force.name .. '/' for _, count_type in pairs {'input_counts', 'output_counts'} do game.write_file(folder .. 'pollution-' .. count_type .. '.json', game.table_to_json(game.pollution_statistics[count_type])) game.write_file(folder .. 'item-' .. count_type .. '.json', game.table_to_json(force.item_production_statistics[count_type])) game.write_file(folder .. 'fluid-' .. count_type .. '.json',game.table_to_json( force.fluid_production_statistics[count_type])) game.write_file(folder .. 'kill-' .. count_type .. '.json', game.table_to_json(force.kill_count_statistics[count_type])) game.write_file(folder .. 'build-' .. count_type .. '.json',game.table_to_json( force.entity_build_count_statistics[count_type])) end end end function Game.write_surfaces() game.remove_path('surfaces') for _, surface in pairs(game.surfaces) do game.write_file('surfaces/' .. (surface.name or surface.index) .. '.lua', 'return ' .. inspect(surface.map_gen_settings)) end end return Game
PowerSwitch = {}; ColorButton = {}; Import("Core.Light"); Import("Core.World"); Import("Core.Utils.Math"); Import("Core.Animation.Animator"); GetHook("World"); UseLocalTrigger("Init"); function Local.Init() switchKey = Require("switchKey"); buttonKey = Require("buttonKey"); UseCustomTrigger(switchKey, "Switch", "*", "PowerSwitch"); UseCustomTrigger(buttonKey, "Button", "Click", "ColorButton"); This:Animator():setKey("Off"); state = false; light = Core.Light.PointLight.new("light", 1920, 1080, 400, 200, 20, 255, 255, 50, 255, false); light:setOffset(25, 25); light:hide(); incLight = 0.0 Hook.World:addLight(light); end function PowerSwitch.Off() state = false; light:hide(); This:Animator():setKey("Off"); end function PowerSwitch.On(param) print("RCV:",param.lolz); for k, v in pairs( param.lolz ) do print(k, v) end state = true; light:show(); This:Animator():setKey("On"); end function ColorButton.Click() local randR = Core.Utils.Math.randint(0, 255); local randG = Core.Utils.Math.randint(0, 255); local randB = Core.Utils.Math.randint(0, 255); light:setColor(randR, randG, randB, 255); end
local encodings = require "util.encodings"; local utf8 = assert(encodings.utf8, "no encodings.utf8 module"); describe("util.encodings", function () describe("#encode()", function() it("should work", function () assert.is.equal(encodings.base64.encode(""), ""); assert.is.equal(encodings.base64.encode('coucou'), "Y291Y291"); assert.is.equal(encodings.base64.encode("\0\0\0"), "AAAA"); assert.is.equal(encodings.base64.encode("\255\255\255"), "////"); end); end); describe("#decode()", function() it("should work", function () assert.is.equal(encodings.base64.decode(""), ""); assert.is.equal(encodings.base64.decode("="), ""); assert.is.equal(encodings.base64.decode('Y291Y291'), "coucou"); assert.is.equal(encodings.base64.decode("AAAA"), "\0\0\0"); assert.is.equal(encodings.base64.decode("////"), "\255\255\255"); end); end); end); describe("util.encodings.utf8", function() describe("#valid()", function() it("should work", function() for line in io.lines("spec/utf8_sequences.txt") do local data = line:match(":%s*([^#]+)"):gsub("%s+", ""):gsub("..", function (c) return string.char(tonumber(c, 16)); end) local expect = line:match("(%S+):"); assert(expect == "pass" or expect == "fail", "unknown expectation: "..line:match("^[^:]+")); local valid = utf8.valid(data); assert.is.equal(valid, utf8.valid(data.." ")); assert.is.equal(valid, expect == "pass", line); end end); end); end);
------------------------------------------------------------ -- Experiencer by Sonaza (https://sonaza.com) -- Licensed under MIT License -- See attached license text in file LICENSE ------------------------------------------------------------ local ADDON_NAME, Addon = ...; local _; local module = Addon:RegisterModule("experience", { label = "Experience", order = 1, savedvars = { char = { session = { Exists = false, Time = 0, TotalXP = 0, AverageQuestXP = 0, }, }, global = { ShowRemaining = true, ShowGainedXP = true, ShowHourlyXP = true, ShowTimeToLevel = true, ShowQuestsToLevel = true, KeepSessionData = true, QuestXP = { ShowText = true, AddIncomplete = false, IncludeAccountWide = false, ShowVisualizer = true, }, }, }, }); module.session = { LoginTime = time(), GainedXP = 0, LastXP = UnitXP("player"), MaxXP = UnitXPMax("player"), QuestsToLevel = -1, AverageQuestXP = 0, Paused = false, PausedTime = 0, }; -- Required data for experience module local HEIRLOOM_ITEMXP = { ["INVTYPE_HEAD"] = 0.1, ["INVTYPE_SHOULDER"] = 0.1, ["INVTYPE_CHEST"] = 0.1, ["INVTYPE_ROBE"] = 0.1, ["INVTYPE_LEGS"] = 0.1, ["INVTYPE_FINGER"] = 0.05, ["INVTYPE_CLOAK"] = 0.05, -- Rings with battleground xp bonus instead [126948] = 0.0, [126949] = 0.0, }; local HEIRLOOM_SLOTS = { 1, 3, 5, 7, 11, 12, 15, }; local BUFF_MULTIPLIERS = { [46668] = { multiplier = 0.1, }, -- Darkmoon Carousel Buff [178119] = { multiplier = 0.2, }, -- Excess Potion of Accelerated Learning [127250] = { multiplier = 3.0, maxlevel = 84, }, -- Elixir of Ancient Knowledge [189375] = { multiplier = 3.0, maxlevel = 99, }, -- Elixir of the Rapid Mind }; local GROUP_TYPE = { SOLO = 0x1, PARTY = 0x2, RAID = 0x3, }; local QUEST_COMPLETED_PATTERN = "^" .. string.gsub(ERR_QUEST_COMPLETE_S, "%%s", "(.-)") .. "$"; local QUEST_EXPERIENCE_PATTERN = "^" .. string.gsub(ERR_QUEST_REWARD_EXP_I, "%%d", "(%%d+)") .. "$"; function module:Initialize() self:RegisterEvent("CHAT_MSG_SYSTEM"); self:RegisterEvent("PLAYER_XP_UPDATE"); self:RegisterEvent("PLAYER_LEVEL_UP"); self:RegisterEvent("QUEST_LOG_UPDATE"); self:RegisterEvent("UNIT_INVENTORY_CHANGED"); self:RegisterEvent("UPDATE_EXPANSION_LEVEL"); module.playerCanLevel = not module:IsPlayerMaxLevel(); module:RestoreSession(); end function module:IsDisabled() return module:IsPlayerMaxLevel() or IsXPUserDisabled(); end function module:AllowedToBufferUpdate() return true; end function module:Update(elapsed) local lastPaused = self.session.Paused; self.session.Paused = UnitIsAFK("player"); if (self.session.Paused and lastPaused ~= self.session.Paused) then self:Refresh(); elseif (not self.session.Paused and lastPaused ~= self.session.Paused) then self.session.LoginTime = self.session.LoginTime + math.floor(self.session.PausedTime); self.session.PausedTime = 0; end if (self.session.Paused) then self.session.PausedTime = self.session.PausedTime + elapsed; end if (self.db == nil) then return; end if (self.db.global.KeepSessionData) then self.db.char.session.Exists = true; self.db.char.session.Time = time() - (self.session.LoginTime + math.floor(self.session.PausedTime)); self.db.char.session.TotalXP = self.session.GainedXP; self.db.char.session.AverageQuestXP = self.session.AverageQuestXP; end end function module:GetText() local primaryText = {}; local secondaryText = {}; local current_xp, max_xp = UnitXP("player"), UnitXPMax("player"); local rested_xp = GetXPExhaustion() or 0; local remaining_xp = max_xp - current_xp; local progress = current_xp / (max_xp > 0 and max_xp or 1); local progressColor = Addon:GetProgressColor(progress); if (self.db.global.ShowRemaining) then tinsert(primaryText, string.format("%s%s|r (%s%.1f|r%%)", progressColor, BreakUpLargeNumbers(remaining_xp), progressColor, 100 - progress * 100) ); else tinsert(primaryText, string.format("%s%s|r / %s (%s%.1f|r%%)", progressColor, BreakUpLargeNumbers(current_xp), BreakUpLargeNumbers(max_xp), progressColor, progress * 100) ); end if (rested_xp > 0) then tinsert(primaryText, string.format("%d%% |cff6fafdfrested|r", math.ceil(rested_xp / max_xp * 100)) ); end if (module.session.GainedXP > 0) then local hourlyXP, timeToLevel = module:CalculateHourlyXP(); if (self.db.global.ShowGainedXP) then tinsert(secondaryText, string.format("+%s |cffffcc00xp|r", BreakUpLargeNumbers(module.session.GainedXP)) ); end if (self.db.global.ShowHourlyXP) then tinsert(primaryText, string.format("%s |cffffcc00xp/h|r", BreakUpLargeNumbers(hourlyXP)) ); end if (self.db.global.ShowTimeToLevel) then tinsert(primaryText, string.format("%s |cff80e916until level|r", Addon:FormatTime(timeToLevel)) ); end end if (self.db.global.ShowQuestsToLevel) then if (module.session.QuestsToLevel > 0 and module.session.QuestsToLevel ~= math.huge) then tinsert(secondaryText, string.format("~%s |cff80e916quests|r", module.session.QuestsToLevel) ); end end if (self.db.global.QuestXP.ShowText) then local completeXP, incompleteXP, totalXP = module:CalculateQuestLogXP(); local levelUpAlert = ""; if (current_xp + completeXP >= max_xp) then levelUpAlert = " (|cfff1e229enough to level|r)"; end if (not self.db.global.QuestXP.AddIncomplete) then tinsert(secondaryText, string.format("%s |cff80e916xp from quests|r%s", BreakUpLargeNumbers(math.floor(completeXP)), levelUpAlert) ); elseif (self.db.global.QuestXP.AddIncomplete) then tinsert(secondaryText, string.format("%s |cffffdd00+|r %s |cff80e916xp from quests|r%s", BreakUpLargeNumbers(math.floor(completeXP)), BreakUpLargeNumbers(math.floor(incompleteXP)), levelUpAlert) ); end end return table.concat(primaryText, " "), table.concat(secondaryText, " "); end function module:HasChatMessage() return not module:IsPlayerMaxLevel() and not IsXPUserDisabled(), "Max level reached."; end function module:GetChatMessage() local current_xp, max_xp = UnitXP("player"), UnitXPMax("player"); local remaining_xp = max_xp - current_xp; local rested_xp = GetXPExhaustion() or 0; local rested_xp_percent = floor(((rested_xp / max_xp) * 100) + 0.5); local max_xp_text = Addon:FormatNumber(max_xp); local current_xp_text = Addon:FormatNumber(current_xp); local remaining_xp_text = Addon:FormatNumber(remaining_xp); return string.format("Currently level %d at %s/%s (%d%%) with %s xp to go (%d%% rested)", UnitLevel("player"), current_xp_text, max_xp_text, math.ceil((current_xp / max_xp) * 100), remaining_xp_text, rested_xp_percent ); end function module:GetBarData() local data = {}; data.id = nil; data.level = UnitLevel("player"); data.min = 0; data.max = UnitXPMax("player"); data.current = UnitXP("player"); data.rested = (GetXPExhaustion() or 0); if (self.db.global.QuestXP.ShowVisualizer) then local completeXP, incompleteXP, totalXP = module:CalculateQuestLogXP(); data.visual = completeXP; if (self.db.global.QuestXP.AddIncomplete) then data.visual = { completeXP, totalXP }; end end return data; end function module:GetOptionsMenu() local menudata = { { text = "Experience Options", isTitle = true, notCheckable = true, }, { text = "Show remaining XP", func = function() self.db.global.ShowRemaining = true; module:RefreshText(); end, checked = function() return self.db.global.ShowRemaining == true; end, }, { text = "Show current and max XP", func = function() self.db.global.ShowRemaining = false; module:RefreshText(); end, checked = function() return self.db.global.ShowRemaining == false; end, }, { text = " ", isTitle = true, notCheckable = true, }, { text = "Show gained XP", func = function() self.db.global.ShowGainedXP = not self.db.global.ShowGainedXP; module:RefreshText(); end, checked = function() return self.db.global.ShowGainedXP; end, isNotRadio = true, }, { text = "Show XP per hour", func = function() self.db.global.ShowHourlyXP = not self.db.global.ShowHourlyXP; module:RefreshText(); end, checked = function() return self.db.global.ShowHourlyXP; end, isNotRadio = true, }, { text = "Show time to level", func = function() self.db.global.ShowTimeToLevel = not self.db.global.ShowTimeToLevel; module:RefreshText(); end, checked = function() return self.db.global.ShowTimeToLevel; end, isNotRadio = true, }, { text = "Show quests to level", func = function() self.db.global.ShowQuestsToLevel = not self.db.global.ShowQuestsToLevel; module:RefreshText(); end, checked = function() return self.db.global.ShowQuestsToLevel; end, isNotRadio = true, }, { text = " ", isTitle = true, notCheckable = true, }, { text = "Remember session data", func = function() self.db.global.KeepSessionData = not self.db.global.KeepSessionData; end, checked = function() return self.db.global.KeepSessionData; end, isNotRadio = true, }, { text = "Reset session", func = function() module:ResetSession(); end, notCheckable = true, }, { text = " ", isTitle = true, notCheckable = true, }, { text = "Quest XP Visualizer", isTitle = true, notCheckable = true, }, { text = "Show completed quest XP", func = function() self.db.global.QuestXP.ShowText = not self.db.global.QuestXP.ShowText; module:Refresh(); end, checked = function() return self.db.global.QuestXP.ShowText; end, isNotRadio = true, }, { text = "Also show XP from incomplete quests", func = function() self.db.global.QuestXP.AddIncomplete = not self.db.global.QuestXP.AddIncomplete; module:Refresh(); end, checked = function() return self.db.global.QuestXP.AddIncomplete; end, isNotRadio = true, }, { text = "Include XP from account wide quests (pet battles)", func = function() self.db.global.QuestXP.IncludeAccountWide = not self.db.global.QuestXP.IncludeAccountWide; module:Refresh(); end, checked = function() return self.db.global.QuestXP.IncludeAccountWide; end, isNotRadio = true, }, { text = "Display visualizer bar", func = function() self.db.global.QuestXP.ShowVisualizer = not self.db.global.QuestXP.ShowVisualizer; module:Refresh(); end, checked = function() return self.db.global.QuestXP.ShowVisualizer; end, isNotRadio = true, }, }; return menudata; end ------------------------------------------ function module:RestoreSession() if (not self.db.char.session.Exists) then return end if (not self.db.global.KeepSessionData) then return end if (module:IsPlayerMaxLevel()) then return end local data = self.db.char.session; module.session.LoginTime = module.session.LoginTime - data.Time; module.session.GainedXP = data.TotalXP; module.session.AverageQuestXP = module.session.AverageQuestXP; if (module.session.AverageQuestXP > 0) then local remaining_xp = UnitXPMax("player") - UnitXP("player"); module.session.QuestsToLevel = ceil(remaining_xp / module.session.AverageQuestXP); end end function module:ResetSession() module.session = { LoginTime = time(), GainedXP = 0, LastXP = UnitXP("player"), MaxXP = UnitXPMax("player"), AverageQuestXP = 0, QuestsToLevel = -1, Paused = false, PausedTime = 0, }; self.db.char.session = { Exists = false, Time = 0, TotalXP = 0, AverageQuestXP = 0, }; module:RefreshText(); end function module:IsPlayerMaxLevel(level) return GetMaxLevelForPlayerExpansion() == (level or UnitLevel("player")); end function module:CalculateHourlyXP() local hourlyXP, timeToLevel = 0, 0; local logged_time = time() - (module.session.LoginTime + math.floor(module.session.PausedTime)); local coeff = logged_time / 3600; if (coeff > 0 and module.session.GainedXP > 0) then hourlyXP = math.ceil(module.session.GainedXP / coeff); timeToLevel = (UnitXPMax("player") - UnitXP("player")) / hourlyXP * 3600; end return hourlyXP, timeToLevel; end function module:GetGroupType() if (IsInRaid()) then return GROUP_TYPE.RAID; elseif (IsInGroup()) then return GROUP_TYPE.PARTY; end return GROUP_TYPE.SOLO; end local partyUnitID = { "player", "party1", "party2", "party3", "party4" }; function module:GetUnitID(group_type, index) if (group_type == GROUP_TYPE.SOLO or group_type == GROUP_TYPE.PARTY) then return partyUnitID[index]; elseif (group_type == GROUP_TYPE.RAID) then return string.format("raid%d", index); end return nil; end local function GroupIterator() local index = 0; local groupType = module:GetGroupType(); local numGroupMembers = GetNumGroupMembers(); if (groupType == GROUP_TYPE.SOLO) then numGroupMembers = 1 end return function() index = index + 1; if (index <= numGroupMembers) then return index, module:GetUnitID(groupType, index); end end end function module:HasRecruitingBonus() local playerLevel = UnitLevel("player"); for index, unit in GroupIterator() do if (not UnitIsUnit("player", unit) and UnitIsVisible(unit) and IsRecruitAFriendLinked(unit)) then local unitLevel = UnitLevel(unit); if (math.abs(playerLevel - unitLevel) <= 4 and playerLevel < 120) then return true; end end end return false; end function module:CalculateXPMultiplier() local multiplier = 1.0; -- Heirloom xp bonus is now factored in quest log --for _, slotID in ipairs(HEIRLOOM_SLOTS) do -- local link = GetInventoryItemLink("player", slotID); -- if (link) then -- local _, _, itemRarity, _, _, _, _, _, itemEquipLoc = GetItemInfo(link); -- if (itemRarity == 7) then -- local itemID = tonumber(strmatch(link, "item:(%d*)")) or 0; -- local itemMultiplier = HEIRLOOM_ITEMXP[itemID] or HEIRLOOM_ITEMXP[itemEquipLoc]; -- multiplier = multiplier + itemMultiplier; -- end -- end --end if (module:HasRecruitingBonus()) then multiplier = math.max(1.5, multiplier); end local playerLevel = UnitLevel("player"); for buffSpellID, buffMultiplier in pairs(BUFF_MULTIPLIERS) do if (Addon:PlayerHasBuff(buffSpellID)) then if (not buffMultiplier.maxlevel or (buffMultiplier.maxlevel and playerLevel <= buffMultiplier.maxlevel)) then multiplier = multiplier + buffMultiplier.multiplier; end end end return multiplier; end function module:CalculateQuestLogXP() local completeXP, incompleteXP = 0, 0; local numEntries, _ = C_QuestLog.GetNumQuestLogEntries(); if (numEntries == 0) then return 0, 0, 0; end for index = 1, numEntries do repeat local qinfo = C_QuestLog.GetInfo(index) local questID = qinfo["questID"] if (questID == 0 or qinfo["isHeader"] or qinfo["isHidden"]) then break end if (not self.db.global.QuestXP.IncludeAccountWide and C_QuestLog.IsAccountQuest(questID)) then break end if (C_QuestLog.ReadyForTurnIn(questID)) then completeXP = completeXP + GetQuestLogRewardXP(questID); else incompleteXP = incompleteXP + GetQuestLogRewardXP(questID); end until true end local multiplier = module:CalculateXPMultiplier(); return completeXP * multiplier, incompleteXP * multiplier, (completeXP + incompleteXP) * multiplier; end function module:UPDATE_EXPANSION_LEVEL() if (not playerCanLevel and not module:IsPlayerMaxLevel()) then DEFAULT_CHAT_FRAME:AddMessage(("|cfffaad07Experiencer|r %s"):format("Expansion level upgraded, you are able to gain experience again.")); end module.playerCanLevel = not module:IsPlayerMaxLevel(); end function module:QUEST_LOG_UPDATE() module:Refresh(true); end function module:UNIT_INVENTORY_CHANGED(event, unit) if (unit ~= "player") then return end module:Refresh(); end function module:CHAT_MSG_SYSTEM(event, msg) if (msg:match(QUEST_COMPLETED_PATTERN) ~= nil) then module.QuestCompleted = true; return; end if (not module.QuestCompleted) then return end module.QuestCompleted = false; local xp_amount = msg:match(QUEST_EXPERIENCE_PATTERN); if (xp_amount ~= nil) then xp_amount = tonumber(xp_amount); local weigth = 0.5; if (module.session.AverageQuestXP > 0) then weigth = math.min(xp_amount / module.session.AverageQuestXP, 0.9); module.session.AverageQuestXP = module.session.AverageQuestXP * (1.0 - weigth) + xp_amount * weigth; else module.session.AverageQuestXP = xp_amount; end if (module.session.AverageQuestXP ~= 0) then local remaining_xp = UnitXPMax("player") - UnitXP("player"); module.session.QuestsToLevel = math.floor(remaining_xp / module.session.AverageQuestXP); if (module.session.QuestsToLevel > 0 and xp_amount > 0) then local quests_text = string.format("%d more quests to level", module.session.QuestsToLevel); DEFAULT_CHAT_FRAME:AddMessage("|cffffff00" .. quests_text .. ".|r"); if (Parrot) then Parrot:ShowMessage(quests_text, "Errors", false, 1.0, 1.0, 0.1); end end end end end function module:PLAYER_XP_UPDATE(event) local current_xp = UnitXP("player"); local max_xp = UnitXPMax("player"); local gained = current_xp - module.session.LastXP; if (gained < 0) then gained = module.session.MaxXP - module.session.LastXP + current_xp; end module.session.GainedXP = module.session.GainedXP + gained; module.session.LastXP = current_xp; module.session.MaxXP = max_xp; if (module.session.AverageQuestXP > 0) then local remaining_xp = max_xp - current_xp; module.session.QuestsToLevel = ceil(remaining_xp / module.session.AverageQuestXP); end module:Refresh(); end function module:UPDATE_EXHAUSTION() module:Refresh(); end function module:PLAYER_LEVEL_UP(event, level) if (module:IsPlayerMaxLevel(level)) then Addon:CheckDisabledStatus(); else module.session.MaxXP = UnitXPMax("player"); local remaining_xp = module.session.MaxXP - UnitXP("player"); module.session.QuestsToLevel = ceil(remaining_xp / module.session.AverageQuestXP) - 1; end module.playerCanLevel = not module:IsPlayerMaxLevel(level); end
require("lab1.z1") function moveinto(tab1,i1,j1,tab2,i2) if i2 == nil then tab2, i2 = tab1, tab2 end local padding = j1-i1+1 new_tab = {} for k, v in pairs(tab2) do if type(k) ~= "number" or k < i2 or k<1 then new_tab[k] = v end if type(k) == "number" and k>=i2 then new_tab[k+padding]=v end end for k1, v1 in pairs(tab1) do print(k1,v1,i1,j1) if k1 >= i1 and k1 <= j1 then new_tab[i2+k1-2]=v1 end end for k,v in pairs(tab2) do tab2[k] = nil end for k, v in pairs(new_tab) do --tab2 = new_tab --print(tab1,i1,j1,tab2,i2) tab2[k] = v end end tab2 = {1, nil , 3, 7, nil , 8} moveinto ({3, 4, nil , 6, 7}, 2, 4 ,tab2, 4) printf(tab2) printfk(tab2) --tab2 --> {1, nil , 3, 4, nil , 6, 7, nil , 8}
-- Generated by github.com/davyxu/tabtoy -- Version: 2.8.10 local tab = { ItemBaseData = { { Id = 10001, Name = "钻石", Desc = "", Sort = 0, Type = 10, Sold = 0, RealPrice = 100 }, { Id = 10002, Name = "钻石券", Desc = "", Sort = 0, Type = 10, Sold = 0, RealPrice = 10 }, { Id = 8001, Name = "广告联盟", Desc = "", Sort = 0, Type = 8, Sold = 0, RealPrice = 0 }, { Id = 7001, Name = "PAPAGO记录仪", Desc = "名称:PAPAGO行车记录仪 特征:超高清 描述:迷你隐藏式 类型:固定发货", Sort = 12, Type = 7, Sold = 289, RealPrice = 2890 }, { Id = 7002, Name = "小米记录仪", Desc = "名称:70迈小米行车记录仪 特征:高清夜视 描述:后视镜 类型:固定发货", Sort = 23, Type = 7, Sold = 1299, RealPrice = 12990 }, { Id = 7003, Name = "家用洗车机", Desc = "名称:家用洗车机 特征:高压 描述:高压清洗机 类型:固定发货", Sort = 31, Type = 7, Sold = 299, RealPrice = 2990 }, { Id = 7004, Name = "汽车腰靠垫", Desc = "名称:汽车腰靠垫 特征:倍逸舒 描述:人体工学 类型:固定发货", Sort = 34, Type = 7, Sold = 189, RealPrice = 1890 }, { Id = 7005, Name = "车载手机支架", Desc = "名称:车载手机支架 特征:塑料 描述:风口式支架 类型:固定发货", Sort = 38, Type = 7, Sold = 10, RealPrice = 100 }, { Id = 7006, Name = "车载充电器", Desc = "名称:车载充电器 特征:银色 描述:全金属 类型:固定发货", Sort = 44, Type = 7, Sold = 26, RealPrice = 260 }, { Id = 7007, Name = "汽车香水", Desc = "名称:汽车香水 特征:黑色 描述:香水夹 类型:固定发货", Sort = 46, Type = 7, Sold = 68, RealPrice = 680 }, { Id = 7008, Name = "汽车车载香水", Desc = "名称:汽车车载香水 特征:白色 描述:香水夹 类型:固定发货", Sort = 49, Type = 7, Sold = 39, RealPrice = 390 }, { Id = 7009, Name = "汽车头枕腰靠", Desc = "名称:汽车腰靠垫 特征:织物 描述:人体工学 类型:固定发货", Sort = 53, Type = 7, Sold = 179, RealPrice = 1790 }, { Id = 7010, Name = "车载充电器", Desc = "名称:飞利浦车载充电器 特征:双USB输出 描述:黑色 类型:固定发货", Sort = 54, Type = 7, Sold = 129, RealPrice = 1290 }, { Id = 7011, Name = "小米净化器", Desc = "名称:小米净化器 特征:小米 描述:便携式 类型:固定发货", Sort = 63, Type = 7, Sold = 389, RealPrice = 3890 }, { Id = 7012, Name = "海尔净化器", Desc = "名称:车载空气净化器 特征:CJ05A 描述:便携式 类型:固定发货", Sort = 66, Type = 7, Sold = 199, RealPrice = 1990 }, { Id = 7013, Name = "车载吸尘器", Desc = "名称:车载吸尘器 特征:12V 描述:黑金色 类型:固定发货", Sort = 70, Type = 7, Sold = 79, RealPrice = 790 }, { Id = 7014, Name = "车载灭火器", Desc = "名称:车载灭火器 特征:金属 描述:小型灭火器 类型:固定发货", Sort = 72, Type = 7, Sold = 39, RealPrice = 390 }, { Id = 7015, Name = "对讲机", Desc = "名称:对讲机 特征:无线电 描述:自驾游对讲机 类型:固定发货", Sort = 75, Type = 7, Sold = 158, RealPrice = 1580 }, { Id = 7016, Name = "汽车安全锤", Desc = "名称:汽车安全锤 特征:消防锤 描述:钨钢锤尖 类型:固定发货", Sort = 80, Type = 7, Sold = 58, RealPrice = 580 }, { Id = 7017, Name = "保平安符", Desc = "名称:车载保平安符 特征:织物 描述:平安符 类型:随机发货", Sort = 81, Type = 7, Sold = 89, RealPrice = 890 }, { Id = 7018, Name = "汽车U盘带音乐", Desc = "名称:车载mp3汽车U盘带音乐 特征:32g 描述:金色 类型:固定发货", Sort = 85, Type = 7, Sold = 59, RealPrice = 590 }, { Id = 7019, Name = "汽车收纳箱", Desc = "名称:汽车收纳箱储物箱 特征:40升 描述:PP树脂 类型:固定发货", Sort = 90, Type = 7, Sold = 129, RealPrice = 1290 }, { Id = 6001, Name = "元宝", Desc = "", Sort = 0, Type = 6, Sold = 0, RealPrice = 0 }, { Id = 6002, Name = "金券", Desc = "", Sort = 0, Type = 6, Sold = 0, RealPrice = 0 }, { Id = 6003, Name = "代金券(作废,不要使用)", Desc = "", Sort = 0, Type = 6, Sold = 0, RealPrice = 0 }, { Id = 6004, Name = "金币", Desc = "", Sort = 0, Type = 6, Sold = 0, RealPrice = 0 }, { Id = 6005, Name = "免费次数", Desc = "", Sort = 0, Type = 6, Sold = 0, RealPrice = 0 }, { Id = 5001, Name = "100元话费", Desc = "名称:话费直充 特征:100元 描述:虚拟卡 类型:固定发货", Sort = 59, Type = 5, Sold = 100, RealPrice = 1000 }, { Id = 5002, Name = "50元话费", Desc = "名称:话费直充 特征:50 描述:虚拟卡 类型:固定发货", Sort = 76, Type = 5, Sold = 50, RealPrice = 500 }, { Id = 5003, Name = "30元话费", Desc = "名称:话费直充 特征:30 描述:虚拟卡 类型:固定发货", Sort = 84, Type = 5, Sold = 30, RealPrice = 300 }, { Id = 5004, Name = "10元话费", Desc = "名称:话费直充 特征:10元 描述:虚拟卡 类型:固定发货", Sort = 91, Type = 5, Sold = 10, RealPrice = 100 }, { Id = 4001, Name = "毛怪苏利文", Desc = "名称:正版迪士尼-毛怪苏利文 特征:95cm 描述:PP棉 类型:固定发货", Sort = 9, Type = 4, Sold = 350, RealPrice = 3500 }, { Id = 4002, Name = "Disney维尼熊", Desc = "名称:小熊维尼公仔 特征:高约52cm 描述:PP棉 类型:固定发货", Sort = 18, Type = 4, Sold = 198, RealPrice = 1980 }, { Id = 4003, Name = "迪士尼基本款套装", Desc = "名称:迪士尼米奇&米妮套装 特征:43*50cm 描述:PP棉-超柔短毛绒 类型:固定发货", Sort = 24, Type = 4, Sold = 119, RealPrice = 1190 }, { Id = 4004, Name = "创意十二萌犬礼盒", Desc = "名称:创意十二萌犬礼盒 特征:树脂 描述:饰物 类型:固定发货", Sort = 25, Type = 4, Sold = 49, RealPrice = 490 }, { Id = 4005, Name = "正版迪士尼布鲁托", Desc = "名称:正版迪士尼布鲁托 特征:30-35cm 描述:PP棉 类型:固定发货", Sort = 27, Type = 4, Sold = 40, RealPrice = 400 }, { Id = 4006, Name = "瘫倒仓鼠坐垫", Desc = "名称:瘫倒仓鼠坐垫 特征:45x90cm 描述:灰色/浅棕/深棕/粉色 类型:随机发货", Sort = 29, Type = 4, Sold = 34, RealPrice = 340 }, { Id = 4007, Name = "初音ミク抱枕", Desc = "名称:初音ミク抱枕 特征:高约20cm 描述:超柔PP棉 类型:固定发货", Sort = 32, Type = 4, Sold = 23, RealPrice = 230 }, { Id = 4008, Name = "旅かえる公仔", Desc = "名称:旅行青蛙公仔(旅かえる) 特征:高约20cm 描述:PP棉-超柔短毛绒 类型:固定发货", Sort = 33, Type = 4, Sold = 20, RealPrice = 200 }, { Id = 4009, Name = "小丁丁", Desc = "名称:小丁丁 特征:高约20cm 描述:毛绒 类型:随机发货", Sort = 39, Type = 4, Sold = 10, RealPrice = 100 }, { Id = 4010, Name = "仿真狗boo", Desc = "名称:仿真狗boo 特征:60cm 描述:PP棉 类型:固定发货", Sort = 42, Type = 4, Sold = 199, RealPrice = 1990 }, { Id = 4011, Name = "大脸猫玩偶", Desc = "名称:白色泪眼猫 特征:60cm 描述:PP棉 类型:固定发货", Sort = 47, Type = 4, Sold = 59, RealPrice = 590 }, { Id = 4012, Name = "变身蜡笔小新", Desc = "名称:变身蜡笔小新 特征:95cm 描述:PP棉 类型:固定发货", Sort = 48, Type = 4, Sold = 348, RealPrice = 3480 }, { Id = 4013, Name = "冰雪奇缘艾莎", Desc = "名称:冰雪奇缘-艾莎 特征:28cm 描述:玩偶 类型:固定发货", Sort = 55, Type = 4, Sold = 99, RealPrice = 990 }, { Id = 4014, Name = "大型抱抱熊公仔", Desc = "名称:大型抱抱熊公仔 特征:3.4米 描述:PP棉 类型:固定发货", Sort = 58, Type = 4, Sold = 768, RealPrice = 7680 }, { Id = 4015, Name = "节日版维尼熊", Desc = "名称:正版迪士尼维尼熊 特征:41cm 描述:PP棉 类型:固定发货", Sort = 60, Type = 4, Sold = 129, RealPrice = 1290 }, { Id = 4016, Name = "唐老鸭包包", Desc = "名称:大型抱抱熊公仔 特征:3.4米 描述:PP棉 类型:固定发货", Sort = 61, Type = 4, Sold = 88, RealPrice = 880 }, { Id = 4017, Name = "粉红豹公仔", Desc = "名称:粉红顽皮豹 特征:55cm 描述:PP棉 类型:固定发货", Sort = 64, Type = 4, Sold = 178, RealPrice = 1780 }, { Id = 4018, Name = "哈姆太郎", Desc = "名称:哈姆太郎 特征:40cm 描述:毛绒 类型:固定发货", Sort = 71, Type = 4, Sold = 68, RealPrice = 680 }, { Id = 4019, Name = "雪儿公主", Desc = "名称:正版芭比婚纱娃娃 特征:60cm 描述:镶钻长拖尾款 类型:固定发货", Sort = 73, Type = 4, Sold = 1499, RealPrice = 14990 }, { Id = 4020, Name = "长颈鹿公仔", Desc = "名称:可骑的长颈鹿公仔 特征:1.3米 描述:PP棉 类型:固定发货", Sort = 78, Type = 4, Sold = 386, RealPrice = 3860 }, { Id = 4021, Name = "白虎背包", Desc = "名称:欧美个性潮白虎背包 特征:1.0kg 描述:PP棉 类型:随机发货", Sort = 79, Type = 4, Sold = 309, RealPrice = 3090 }, { Id = 4022, Name = "皮卡丘玩偶", Desc = "名称:大型抱抱熊公仔 特征:90cm 描述:PP棉 类型:固定发货", Sort = 83, Type = 4, Sold = 100, RealPrice = 1000 }, { Id = 4023, Name = "音乐泰迪熊", Desc = "名称:七彩发光音乐泰迪熊 特征:100cm 描述:PP棉 类型:固定发货", Sort = 87, Type = 4, Sold = 178, RealPrice = 1780 }, { Id = 4024, Name = "索尼子人形抱枕", Desc = "名称:索尼子人形抱枕 特征:160*50cm 描述:PP棉 类型:固定发货", Sort = 88, Type = 4, Sold = 298, RealPrice = 2980 }, { Id = 4025, Name = "巡音人形抱枕", Desc = "名称:巡音人形抱枕 特征:160*50cm 描述:PP棉 类型:固定发货", Sort = 92, Type = 4, Sold = 298, RealPrice = 2980 }, { Id = 4026, Name = "小礼品", Desc = "名称:小礼品 特征:时尚小挂件一个 描述:多种款式 类型:随机发货", Sort = 94, Type = 9, Sold = 3, RealPrice = 30 }, { Id = 4027, Name = "贱贱猫", Desc = "名称:贱贱猫 特征:30-40cm 描述:毛绒 类型:随机发货", Sort = 0, Type = 4, Sold = 11, RealPrice = 110 }, { Id = 3001, Name = "CL萝卜丁口红", Desc = "名称:萝卜丁丝绒口红唇膏 特征:丝滑缎光系列 描述:505M 001M 类型:固定发货", Sort = 4, Type = 3, Sold = 898, RealPrice = 8980 }, { Id = 3002, Name = "莫杰小雏菊女士香水", Desc = "名称:莫杰小雏菊女士香水 特征:50ml 描述:花果香调 类型:固定发货", Sort = 13, Type = 3, Sold = 315, RealPrice = 3150 }, { Id = 3003, Name = "DIOR魅惑润唇蜜", Desc = "名称:迪奥魅惑润唇蜜 特征:40g 描述:粉红色 类型:固定发货", Sort = 16, Type = 3, Sold = 283, RealPrice = 2830 }, { Id = 3004, Name = "花王蒸汽眼罩", Desc = "名称:花王蒸汽眼罩(无香) 特征:170g 描述:14片 类型:固定发货", Sort = 17, Type = 3, Sold = 78, RealPrice = 780 }, { Id = 3005, Name = "小甘菊护手霜", Desc = "名称:小甘菊 经典护手霜) 特征:75ml 描述:护手霜 类型:固定发货", Sort = 20, Type = 3, Sold = 59, RealPrice = 590 }, { Id = 3006, Name = "吸盘牙刷架套装", Desc = "名称:吸盘牙刷架套装 特征:458.00g 描述:收纳 类型:固定发货", Sort = 28, Type = 3, Sold = 39, RealPrice = 390 }, { Id = 3007, Name = "星球大战吸管杯带盖", Desc = "名称:创意十二萌犬礼盒 特征:480ml 描述:风暴兵/暗黑原力 类型:随机发货", Sort = 35, Type = 3, Sold = 26, RealPrice = 260 }, { Id = 3008, Name = "施耐福四件套", Desc = "名称:施耐福 黑色四件套 特征: 黑色四件套 描述:不锈钢钢 类型:固定发货", Sort = 36, Type = 3, Sold = 248, RealPrice = 2480 }, { Id = 3009, Name = "镁离子净水壶", Desc = "名称:镁离子净水壶 特征:1.5升 描述:PP树脂 类型:固定发货", Sort = 40, Type = 3, Sold = 189, RealPrice = 1890 }, { Id = 3010, Name = "德尔玛加湿器", Desc = "名称:德尔玛加湿器 特征:5升 描述:PP树脂 类型:固定发货", Sort = 45, Type = 3, Sold = 80, RealPrice = 800 }, { Id = 3011, Name = "飞利浦剃须刀", Desc = "名称:飞利浦剃须刀 特征:电动剃须刀 描述:环保材料 类型:固定发货", Sort = 50, Type = 3, Sold = 1199, RealPrice = 11990 }, { Id = 3012, Name = "小熊咖啡机", Desc = "名称:小熊机 美式家用咖啡壶 特征:0.7L 描述:滴滤机 类型:固定发货", Sort = 56, Type = 3, Sold = 129, RealPrice = 1290 }, { Id = 3013, Name = "忠臣电陶炉", Desc = "名称:忠臣电陶炉 特征:电陶炉 描述:黑色 类型:固定发货", Sort = 57, Type = 3, Sold = 199, RealPrice = 1990 }, { Id = 3014, Name = "金正养生壶", Desc = "名称:金正养生壶 特征:1.5L 描述:养生壶 类型:固定发货", Sort = 62, Type = 3, Sold = 99, RealPrice = 990 }, { Id = 3015, Name = "九洲鹿床垫", Desc = "名称:九洲鹿床垫 特征:床垫 描述:棉 类型:固定发货", Sort = 65, Type = 3, Sold = 78, RealPrice = 780 }, { Id = 3016, Name = "悠佳脏衣篮", Desc = "名称:悠佳脏衣篮 特征:40升 描述:PP树脂 类型:固定发货", Sort = 67, Type = 3, Sold = 79, RealPrice = 790 }, { Id = 3017, Name = "黄金金条10g", Desc = "名称:【中国黄金】黄金金条 特征:9999金砖10g黄金金条 描述:10克 类型:固定发货", Sort = 68, Type = 3, Sold = 2893, RealPrice = 28930 }, { Id = 3018, Name = "黄金吊坠", Desc = "名称:黄金吊坠 特征:9999金黄金吊坠 描述:2克 类型:固定发货", Sort = 69, Type = 3, Sold = 840, RealPrice = 8400 }, { Id = 3019, Name = "南极人四件套", Desc = "名称:南极人四件套 特征:四件套 描述:棉 类型:固定发货", Sort = 74, Type = 3, Sold = 149, RealPrice = 1490 }, { Id = 3020, Name = "小米空气净化器", Desc = "名称:小米净化器 特征:小米 描述:立式 类型:固定发货", Sort = 82, Type = 3, Sold = 529, RealPrice = 5290 }, { Id = 3021, Name = "小熊养生壶", Desc = "名称:小熊养生壶 特征:1.5L 描述:养生壶 类型:固定发货", Sort = 86, Type = 3, Sold = 129, RealPrice = 1290 }, { Id = 2001, Name = "京东e卡1000元", Desc = "名称:京东卡 特征:1000 描述:虚拟卡 类型:固定发货", Sort = 15, Type = 2, Sold = 1000, RealPrice = 10000 }, { Id = 2002, Name = "京东e卡500元", Desc = "名称:京东卡 特征:500 描述:虚拟卡 类型:固定发货", Sort = 22, Type = 2, Sold = 500, RealPrice = 5000 }, { Id = 2003, Name = "京东e卡300元", Desc = "名称:京东卡 特征:300 描述:虚拟卡 类型:固定发货", Sort = 30, Type = 2, Sold = 300, RealPrice = 3000 }, { Id = 2004, Name = "京东e卡200元", Desc = "名称:京东卡 特征:200 描述:虚拟卡 类型:固定发货", Sort = 37, Type = 2, Sold = 200, RealPrice = 2000 }, { Id = 2005, Name = "爱奇艺VIP会员年卡", Desc = "名称:爱奇艺VIP会员卡 特征:1年 描述:虚拟卡 类型:固定发货", Sort = 43, Type = 2, Sold = 190, RealPrice = 1900 }, { Id = 2006, Name = "京东e卡50元", Desc = "名称:京东卡 特征:50 描述:虚拟卡 类型:固定发货", Sort = 77, Type = 2, Sold = 50, RealPrice = 500 }, { Id = 2007, Name = "爱奇艺1个月会员卡", Desc = "名称:爱奇艺VIP会员卡 特征:1个月 描述:虚拟卡 类型:固定发货", Sort = 89, Type = 2, Sold = 20, RealPrice = 200 }, { Id = 2008, Name = "斗鱼直播充值10鱼翅", Desc = "名称:斗鱼TV 特征:10鱼翅 描述:虚拟卡 类型:固定发货", Sort = 93, Type = 2, Sold = 10, RealPrice = 100 }, { Id = 1001, Name = "苹果iPhoneX", Desc = "名称:Apple/苹果 iPhone X 特征:64GB 描述:银色,深空灰色 类型:随机发货", Sort = 1, Type = 1, Sold = 8488, RealPrice = 84880 }, { Id = 1002, Name = "PS4家用游戏机", Desc = "名称:PS4家用游戏机 特征:500G 描述:标配 类型:固定发货", Sort = 2, Type = 1, Sold = 1960, RealPrice = 19600 }, { Id = 1003, Name = "小米5X美颜手机", Desc = "名称:小米5X美颜双摄拍照手机 特征:4GB+64GB 描述:金色 类型:固定发货", Sort = 3, Type = 1, Sold = 1399, RealPrice = 13990 }, { Id = 1004, Name = "Beauty美容棒", Desc = "名称:Beauty BAR美容棒 特征:90g 描述:美容仪 类型:固定发货", Sort = 5, Type = 1, Sold = 529, RealPrice = 5290 }, { Id = 1005, Name = "kindle", Desc = "名称:Kindle X咪咕 电纸书阅读器 特征:6英寸屏 描述:白色 类型:固定发货", Sort = 6, Type = 1, Sold = 658, RealPrice = 6580 }, { Id = 1006, Name = "switch游戏机", Desc = "名称:任天堂NS switch 特征:32GB 描述:玫瑰金 类型:固定发货", Sort = 7, Type = 1, Sold = 2300, RealPrice = 23000 }, { Id = 1007, Name = "oppoR11S手机", Desc = "名称:OPPO R11s 星幕新年版 特征:4GB+64GB 描述:新年红 类型:固定发货", Sort = 8, Type = 1, Sold = 3099, RealPrice = 30990 }, { Id = 1008, Name = "vivoX9S", Desc = "名称:vivo X9s 全网通手机 特征:4GB+64GB 描述:玫瑰金 类型:固定发货", Sort = 10, Type = 1, Sold = 1998, RealPrice = 19980 }, { Id = 1009, Name = "VIVOX20", Desc = "名称:vivo X20 王者荣耀限量版 特征:6GB+64GB 描述:定制 类型:固定发货", Sort = 11, Type = 1, Sold = 3498, RealPrice = 34980 }, { Id = 1010, Name = "荣耀9", Desc = "名称:荣耀9青春版 全网通 标配版 特征:3GB+32GB 描述:幻海蓝 类型:固定发货", Sort = 14, Type = 1, Sold = 1199, RealPrice = 11990 }, { Id = 1011, Name = "荣耀V10", Desc = "名称:荣耀 V10全网通 标配版 特征:4GB+64GB 描述:极光蓝 类型:固定发货", Sort = 19, Type = 1, Sold = 2699, RealPrice = 26990 }, { Id = 1012, Name = "荣耀体脂称", Desc = "名称:荣耀蓝牙APP智能电子秤 特征:智能体脂秤 描述:适配ios&安卓 类型:固定发货", Sort = 21, Type = 1, Sold = 199, RealPrice = 1990 }, { Id = 1013, Name = "小方智能摄像机", Desc = "名称:小方智能摄像机 特征:1080p 描述:白色 类型:固定发货", Sort = 26, Type = 1, Sold = 139, RealPrice = 1390 }, { Id = 1014, Name = "小米充电宝", Desc = "名称:小米充电宝 特征:移动电源 描述:10000毫安 类型:随机发货", Sort = 41, Type = 1, Sold = 1399, RealPrice = 13990 }, { Id = 1015, Name = "小米手环", Desc = "名称:小米手环 特征:手环 描述:京东自营店 类型:随机发货", Sort = 51, Type = 1, Sold = 149, RealPrice = 1490 }, { Id = 1016, Name = "智能水杯", Desc = "名称:麦开智能水杯 特征:智能水杯 描述:环保材料 类型:固定发货", Sort = 52, Type = 1, Sold = 349, RealPrice = 3490 } } } -- Id tab.ItemBaseDataById = {} for _, rec in pairs(tab.ItemBaseData) do tab.ItemBaseDataById[rec.Id] = rec end tab.Enum = { } return tab
-- -- Load a resizable 1-d frame. p contains an odd number of parts. -- Even parts are resized; odd parts are not (unless the requested -- width is too small). The frame is centered on the midway part -- of p; parts to the left and right are anchored on the inside. -- -- A 3-part frame; the center third is dynamic, expanding outwards -- in both directions: -- p = { 1/3, 1/3, 1/3 }; -- --oo-- -- --oooooooooo-- -- -- A 2-part frame. The left half is static, the right side dynamic; -- the left part stays in place as the right half expands to the right, -- with the frame centered on the boundary: -- <<-- -- <<----------- -- p = { 1/2, 0, 0, 1/2, 0 }; -- -- A 5-part frame, with an anchored center and static caps on each -- end, expanding outwards: -- <<--oo-->> -- <<----------oo---------->> -- p = { 1/5, 1/5, 1/10, 0, 1/10, 1/5, 1/5 }; -- local p, a = ... assert((#p % 2) == 1) local t = Def.ActorFrame {} local Widths = {} local TextureXPos = 0 for i = 1, #p do t[i] = a .. { Name = tostring(i), InitCommand = function(self) if i < math.ceil(#p / 2) then self:horizalign("HorizAlign_Right") elseif i == math.ceil(#p / 2) then self:horizalign("HorizAlign_Center") else self:horizalign("HorizAlign_Left") end Widths[i] = self:GetWidth() end, SetPartSizeCommand = function(self, params) self:x(params.XPos[i]) self:zoomtowidth(params.Zooms[i]) end } local Width = p[i] t[i].Frames = { { -- state 0 {x = TextureXPos, y = 0}, -- top-left {x = (TextureXPos + Width), y = 1} -- bottom-right } } TextureXPos = TextureXPos + Width end t.InitCommand = function(self, params) local Child = self:GetChild("1") local Height = Child:GetHeight() self:SetHeight(Height) end t.SetPartSizeCommand = function(self, params) self:zoomx(params.FrameZoom) end t.SetSizeCommand = function(self, params) local Width = params.Width assert(Width) self:SetWidth(Width) if params.tween then params.tween(self) self:RunCommandsOnChildren(params.tween) end local UnscaledPartWidth = 0 local ScaledPartWidth = 0 for i = 1, #p do if (i % 2) == 0 then ScaledPartWidth = ScaledPartWidth + Widths[i] else UnscaledPartWidth = UnscaledPartWidth + Widths[i] end end local WidthToScale = Width - UnscaledPartWidth local CurrentScaledPartWidth = math.max(WidthToScale, 0) params.Zooms = {} params.XPos = {} local pos = 0 for i = math.ceil(#p / 2), 1, -1 do local ThisScaledPartWidth = Widths[i] if (i % 2) == 0 then ThisScaledPartWidth = scale(CurrentScaledPartWidth, 0, ScaledPartWidth, 0, Widths[i]) end params.XPos[i] = pos if i == math.ceil(#p / 2) then pos = pos - ThisScaledPartWidth / 2 else pos = pos - ThisScaledPartWidth end params.Zooms[i] = ThisScaledPartWidth end pos = 0 for i = math.ceil(#p / 2), #p do local ThisScaledPartWidth = Widths[i] if (i % 2) == 0 then ThisScaledPartWidth = scale(CurrentScaledPartWidth, 0, ScaledPartWidth, 0, Widths[i]) end params.XPos[i] = pos if i == math.ceil(#p / 2) then pos = pos + ThisScaledPartWidth / 2 else pos = pos + ThisScaledPartWidth end params.Zooms[i] = ThisScaledPartWidth end params.FrameZoom = math.min(Width / UnscaledPartWidth, 1) self:playcommand("SetPartSize", params) end return t -- -- (c) 2007 Glenn Maynard -- All rights reserved. -- -- Permission is hereby granted, free of charge, to any person obtaining a -- copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, and/or sell copies of the Software, and to permit persons to -- whom the Software is furnished to do so, provided that the above -- copyright notice(s) and this permission notice appear in all copies of -- the Software and that both the above copyright notice(s) and this -- permission notice appear in supporting documentation. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF -- THIRD PARTY RIGHTS. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR HOLDERS -- INCLUDED IN THIS NOTICE BE LIABLE FOR ANY CLAIM, OR ANY SPECIAL INDIRECT -- OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS -- OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -- PERFORMANCE OF THIS SOFTWARE. --
-- -- List of messages to be used by MUDpp -- messages = { welcome = "Welcome to Mud++\n\r" .. "****************\n\r\n\r" .. "Copyright 2020 Joel FALCOU" , motd = "Message Of The Day (MOTD)\n\r\n\r" .. "Here is where you place announcements to be given to people " .. "once they have joined the game.\n\r\n\r" , new_player = "Welcome to @rMUDpp##!\n\r" .. "Please read the help files to become familiar with our rules. :)\n\r\n\r" , returning_player = "Welcome back! We hope you enjoy playing today.\n\r" }
description 'chat management stuff' ui_page 'html/chat.html' client_script 'chat_client.lua' server_script 'chat_server.lua' export 'printChatLine' files { 'html/chat.html', 'html/chat.css', 'html/chat.js', 'html/jquery.faketextbox.js', "Roboto-Bold.ttf", }
//________________________________ // // NS2 Single-Player Mod // Made by JimWest, 2012 // //________________________________ // base class for spawning npcs Script.Load("lua/ExtraEntitiesMod/npc/NpcSpawner.lua") class 'NpcSpawnerMarine' (NpcSpawner) NpcSpawnerMarine.kMapName = "npc_spawner_marine" local networkVars = { } if Server then function NpcSpawnerMarine:OnCreate() NpcSpawner.OnCreate(self) end function NpcSpawnerMarine:OnInitialized() NpcSpawner.OnInitialized(self) end function NpcSpawnerMarine:GetTechId() return kTechId.Marine end function NpcSpawnerMarine:Spawn() local values = self:GetValues() local entity = Server.CreateEntity(Marine.kMapName, values) InitMixin(entity, NpcMixin) // destroy all weapons and give them our weapons entity:DestroyWeapons() local items = {} // always include builder table.insert(items, Builder.kMapName) if self.weapons == 0 then table.insert(items, Pistol.kMapName) table.insert(items, Axe.kMapName) table.insert(items, Rifle.kMapName) elseif self.weapons == 1 then table.insert(items, Axe.kMapName) table.insert(items, Pistol.kMapName) elseif self.weapons == 2 then table.insert(items, Axe.kMapName) elseif self.weapons == 3 then table.insert(items, GrenadeLauncher.kMapName) elseif self.weapons == 4 then table.insert(items, Flamethrower.kMapName) end for i, item in ipairs(items) do entity:GiveItem(item) end self:SetWayPoint(entity) end end Shared.LinkClassToMap("NpcSpawnerMarine", NpcSpawnerMarine.kMapName, networkVars)
--- @TODO Create German translations
--[[ --re-implimation of the linear module for debug. You can use this module to debug your code, e.g. observe the output or the inteval varibles. -- --]] local Linear_ForDebug, parent = torch.class('nn.Linear_ForDebug', 'nn.Module') function Linear_ForDebug:__init(inputSize, outputSize,orth_flag,isBias) parent.__init(self) if isBias ~= nil then assert(type(isBias) == 'boolean', 'isBias has to be true/false') self.isBias = isBias else self.isBias = true end self.weight = torch.Tensor(outputSize, inputSize) if self.isBias then self.bias = torch.Tensor(outputSize) self.gradBias = torch.Tensor(outputSize) end self.gradWeight = torch.Tensor(outputSize, inputSize) self.FIM=torch.Tensor() self.conditionNumber={} self.epcilo=10^-100 self.counter=0 self.FIM_updateInterval=100 --for debug self.printDetail=false self.debug=false self.debug_detailInfo=false self.printInterval=1 self.count=0 if orth_flag ~= nil then assert(type(orth_flag) == 'boolean', 'orth_flag has to be true/false') if orth_flag then self:reset_orthogonal() else self:reset() end else self:reset() end end function Linear_ForDebug:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) if self.isBias then self.bias[i] = torch.uniform(-stdv, stdv) end end else self.weight:uniform(-stdv, stdv) if self.isBias then self.bias:uniform(-stdv, stdv) end end return self end function Linear_ForDebug:reset_orthogonal() local initScale = 1.1 -- math.sqrt(2) -- local initScale = math.sqrt(2) local M1 = torch.randn(self.weight:size(1), self.weight:size(1)) local M2 = torch.randn(self.weight:size(2), self.weight:size(2)) local n_min = math.min(self.weight:size(1), self.weight:size(2)) -- QR decomposition of random matrices ~ N(0, 1) local Q1, R1 = torch.qr(M1) local Q2, R2 = torch.qr(M2) self.weight:copy(Q1:narrow(2,1,n_min) * Q2:narrow(1,1,n_min)):mul(initScale) self.bias:zero() end function Linear_ForDebug:updateOutput(input) --self.bias:fill(0) if input:dim() == 1 then self.output:resize(self.bias:size(1)) self.output:copy(self.bias) self.output:addmv(1, self.weight, input) elseif input:dim() == 2 then local nframe = input:size(1) local nElement = self.output:nElement() self.output:resize(nframe, self.weight:size(1)) if self.output:nElement() ~= nElement then self.output:zero() end self.addBuffer = self.addBuffer or input.new() if self.addBuffer:nElement() ~= nframe then self.addBuffer:resize(nframe):fill(1) end self.output:addmm(0, self.output, 1, input, self.weight:t()) if self.isBias then self.output:addr(1, self.addBuffer, self.bias) end else error('input must be vector or matrix') end if self.printDetail then print("Linear_ForDebug: activation, number fo example=20") print(self.output[{{1,20},{}}]) end if self.debug and (self.count % self.printInterval==0)then -- local input_norm=torch.norm(input,1)/input:numel() local input_norm=torch.norm(input,1) local output_norm=torch.norm(self.output,1) -- print('debug_LinearModule--input_norm_elementWise:'..input_norm..' --output_norm_elementWise:'..output_norm) end if self.debug_detailInfo and (self.count % self.printInterval==0)then local input_mean=input:mean(1) local input_normPerDim=torch.norm(input,1,1)/input:size(1) local output_mean=self.output:mean(1) local output_normPerDim=torch.norm(self.output,1,1)/self.output:size(1) print('debug_LinearModule--input_mean:') print(input_mean) print('debug_LinearModule--input_normPerDim:') print(input_normPerDim) print('debug_LinearModule--output_mean:') print(output_mean) print('debug_LinearModule--output_normPerDim:') print(output_normPerDim) end return self.output end function Linear_ForDebug:updateGradInput(input, gradOutput) if self.gradInput then local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if input:dim() == 1 then self.gradInput:addmv(0, 1, self.weight:t(), gradOutput) elseif input:dim() == 2 then self.gradInput:addmm(0, 1, gradOutput, self.weight) end if self.printDetail then print("Linear_ForDebug: gradOutput, number fo example=20") print(gradOutput[{{1,20},{}}]) end if self.debug and (self.count % self.printInterval==0)then local gradOutput_norm=torch.norm(gradOutput,1) local gradInput_norm=torch.norm(self.gradInput,1) end if self.debug_detailInfo and (self.count % self.printInterval==0)then local gradInput_mean=self.gradInput:mean(1) local gradInput_normPerDim=torch.norm(self.gradInput,1,1)/self.gradInput:size(1) local gradOutput_mean=gradOutput:mean(1) local gradOutput_normPerDim=torch.norm(gradOutput,1,1)/gradOutput:size(1) print('debug_LinearModule--gradInput_mean:') print(gradInput_mean) print('debug_LinearModule--gradInput_normPerDim:') print(gradInput_normPerDim) print('debug_LinearModule--gradOutput_mean:') print(gradOutput_mean) print('debug_LinearModule--gradOutput_normPerDim:') print(gradOutput_normPerDim) end return self.gradInput end end function Linear_ForDebug:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 1 then self.gradWeight:addr(scale, gradOutput, input) self.gradBias:add(scale, gradOutput) elseif input:dim() == 2 then self.gradWeight:addmm(scale, gradOutput:t(), input) if self.isBias then self.gradBias:addmv(scale, gradOutput:t(), self.addBuffer) end end if self.debug and (self.count % self.printInterval==0) then local weight_norm=torch.norm(self.weight,1) local bias_norm=torch.norm(self.bias,1) local gradWeight_norm=torch.norm(self.gradWeight,1) local gradBias_norm=torch.norm(self.gradBias,1) print('debug_LinearModule:--weight_norm_elementWise:'..weight_norm..' --bias_norm_elementWise:'..bias_norm) print(' --gradWeight_norm_elementWise:'..gradWeight_norm..' --gradBias_norm_elementWise:'..gradBias_norm) end if self.debug_detailInfo and (self.count % self.printInterval==0)then local gradWeight_mean_rowWise=self.gradWeight:mean(1) local gradWeight_mean_columnWise=self.gradWeight:mean(2) local gradWeight_normPerDim_rowWise=torch.norm(self.gradWeight,1,1)/self.gradWeight:size(1) local gradWeight_normPerDim_columnWise=torch.norm(self.gradWeight,1,2)/self.gradWeight:size(2) local weight_mean_rowWise=self.weight:mean(1) local weight_mean_columnWise=self.weight:mean(2) local weight_normPerDim_rowWise=torch.norm(self.weight,1,1)/self.weight:size(1) local weight_normPerDim_columnWise=torch.norm(self.weight,1,2)/self.weight:size(2) print('debug_LinearModule--gradWeight_mean_rowWise:') print(gradWeight_mean_rowWise) print('debug_LinearModule--gradWeight_mean_columnWise:') print(gradWeight_mean_columnWise) print('debug_LinearModule--gradWeight_normPerDim_rowWise:') print(gradWeight_normPerDim_rowWise) print('debug_LinearModule--gradWeight_normPerDim_columnWise:') print(gradWeight_normPerDim_columnWise) print('debug_LinearModule--weight_mean_rowWise:') print(weight_mean_rowWise) print('debug_LinearModule--weight_mean_columnWise:') print(weight_mean_columnWise) print('debug_LinearModule--weight_normPerDim_rowWise:') print(weight_normPerDim_rowWise) print('debug_LinearModule--weight_normPerDim_columnWise:') print(weight_normPerDim_columnWise) end self.count=self.count+1 --the ending of all the operation in this module end -- we do not need to accumulate parameters when sharing Linear_ForDebug.sharedAccUpdateGradParameters = Linear_ForDebug.accUpdateGradParameters function Linear_ForDebug:__tostring__() return torch.type(self) .. string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1)) end
require 'torch' require 'hdf5' require 'shortcut' require 'NCEDataGenerator' local BidTreeLM_NCE_Dataset = torch.class('BidTreeLM_NCE_Dataset') function BidTreeLM_NCE_Dataset:__init(datasetPath, nneg, power, normalizeUNK) self.vocab = torch.load(datasetPath:sub(1, -3) .. 'vocab.t7') xprintln('load vocab done!') self.h5in = hdf5.open(datasetPath, 'r') local function getLength(label) local index = self.h5in:read(string.format('/%s/index', label)) return index:dataspaceSize()[1] end self.trainSize = getLength('train') self.validSize = getLength('valid') self.testSize = getLength('test') xprintln('train size %d, valid size %d, test size %d', self.trainSize, self.validSize, self.testSize) xprintln('vocab size %d', self.vocab.nvocab) self.UNK = self.vocab.UNK xprintln('unknown word token is %d', self.UNK) self.ncedata = NCEDataGenerator(self.vocab, nneg, power, normalizeUNK) end function BidTreeLM_NCE_Dataset:getVocabSize() return self.vocab.nvocab end function BidTreeLM_NCE_Dataset:getTrainSize() return self.trainSize end function BidTreeLM_NCE_Dataset:getValidSize() return self.validSize end function BidTreeLM_NCE_Dataset:getTestSize() return self.testSize end function BidTreeLM_NCE_Dataset:toBatch(xs, ys, lcs, batchSize) local dtype = 'torch.LongTensor' local maxn = 0 for _, y_ in ipairs(ys) do if y_:size(1) > maxn then maxn = y_:size(1) end end local x = torch.ones(maxn, batchSize, 5):type(dtype) x:mul(self.UNK) x[{ {}, {}, 4 }] = torch.linspace(2, maxn + 1, maxn):resize(maxn, 1):expand(maxn, batchSize) x[{ {}, {}, 5 }] = 0 -- in default, I don't want them to have local nsent = #ys local y = torch.zeros(maxn, batchSize):type(dtype) for i = 1, nsent do local sx, sy = xs[i], ys[i] x[{ {1, sx:size(1)}, i, {} }] = sx y[{ {1, sy:size(1)}, i }] = sy end -- for left children assert(#lcs == #xs, 'should be the same!') local lcBatchSize = 0 local maxLcSeqLen = 0 for _, lc in ipairs(lcs) do if lc:dim() ~= 0 then lcBatchSize = lcBatchSize + 1 maxLcSeqLen = math.max(maxLcSeqLen, lc:size(1)) end end local lchild = torch.Tensor():type(dtype) local lc_mask = torch.FloatTensor() if lcBatchSize ~= 0 then lchild:resize(maxLcSeqLen, lcBatchSize):fill(self.UNK) lc_mask:resize(maxLcSeqLen, lcBatchSize):fill(0) local j = 0 for i, lc in ipairs(lcs) do if lc:dim() ~= 0 then j = j + 1 lchild[{ {1, lc:size(1)}, j }] = lc[{ {}, 1 }] lc_mask[{ {1, lc:size(1)}, j }] = lc[{ {}, 2 }] + 1 local xcol = x[{ {}, i, 5 }] local idxs = xcol:ne(0) xcol[idxs] = (xcol[idxs] - 1) * lcBatchSize + j end end end return x, y, lchild, lc_mask end function BidTreeLM_NCE_Dataset:createBatch(label, batchSize, useNCE) local h5in = self.h5in local x_data = h5in:read(string.format('/%s/x_data', label)) local y_data = h5in:read(string.format('/%s/y_data', label)) local index = h5in:read(string.format('/%s/index', label)) local l_data = h5in:read( string.format('/%s/l_data', label) ) local lindex = h5in:read( string.format('/%s/lindex', label) ) local N = index:dataspaceSize()[1] local istart = 1 return function() if istart <= N then local iend = math.min(istart + batchSize - 1, N) local xs = {} local ys = {} local lcs = {} for i = istart, iend do local idx = index:partial({i, i}, {1, 2}) local start, len = idx[1][1], idx[1][2] local x = x_data:partial({start, start + len - 1}, {1, 5}) local y = y_data:partial({start, start + len - 1}) table.insert(xs, x) table.insert(ys, y) local lidx = lindex:partial({i, i}, {1, 2}) local lstart, llen = lidx[1][1], lidx[1][2] local lc if llen == 0 then lc = torch.IntTensor() -- to be the same type as l_data else lc = l_data:partial({lstart, lstart + llen - 1}, {1, 2}) end table.insert(lcs, lc) end istart = iend + 1 local x, y, lchild, lc_mask = self:toBatch(xs, ys, lcs, batchSize) if useNCE then local mask = y:ne(0):float() y[y:eq(0)] = 1 local y_neg, y_prob, y_neg_prob = self.ncedata:getYNegProbs(y) return x, y, lchild, lc_mask, y_neg, y_prob, y_neg_prob, mask else return x, y, lchild, lc_mask end end end end function BidTreeLM_NCE_Dataset:close() self.h5in:close() end
return { shopTitle = "Hidden Valley General Store", shopId = "hiddenValley", items = { "cookie", "healthPotion", "rake", "axe" } }
if nil ~= require then require "fritomod/basic"; require "fritomod/currying"; require "fritomod/Metatables"; require "fritomod/Functions"; require "fritomod/OOP"; require "fritomod/OOP-Class"; require "fritomod/Metatables"; require "fritomod/Lists"; require "fritomod/Iterators"; require "fritomod/Tests"; end; TestSuite = OOP.Class("TestSuite"); local TestSuite = TestSuite; function TestSuite:Constructor(name) self.listener = Metatables.Multicast(); self.name = name or ""; if name then if require then require("fritomod/AllTests"); end; AllTests[name] = self; end; end; function TestSuite:GetName() if self.name == "" then return; end; return self.name; end; function TestSuite:ToString() local name = self:GetName() or Reference(self); return ("TestSuite(%s)"):format(name); end; function TestSuite:AddListener(listener) return self.listener:Add(listener); end; function TestSuite:AddRecursiveListener(listener, ...) local removers = {}; Lists.Insert(removers, self:AddListener(listener)); local testGenerator = self:TestGenerator(...); while true do local test, testName = testGenerator(); if not test then break; end; -- We don't use OOP.InstanceOf here because it's possible we'll encounter -- TestSuites that are from a different global environment than the one -- this TestSuite was created in. For example, if AllTests is created in a -- global environment, but we run our test suites in a pristine environment -- (with only a reference to AllTests), this will never be true since the -- children have different "TestSuite" classes. if type(test)=="table" and IsCallable(test.AddRecursiveListener) then Lists.Insert(removers, test:AddRecursiveListener(listener)); end; end; return Curry(Lists.CallEach, removers); end; local function CoerceTest(test) assert(test, "Test is falsy"); if IsCallable(test) then return test; end; if type(test) == "table" then return CurryMethod(test, "Run"); end; if type(test) == "string" then local testfunc, err = loadstring(test); if testFunc then return testFunc; end; error(err); end; error("Test is not a callable, table, or string: " .. type(test)); end; function TestSuite:TestGenerator(...) local testGenerator = self:GetTests(...); if type(testGenerator) ~= "function" then testGenerator = Iterators.IterateMap(testGenerator); end; return function() local testName, test = testGenerator(); if testName == nil then return; end; if not test and testName then test, testName = testName, testName; end; return test, tostring(testName); end; end; local function WrapTestRunner(testRunner) return function() local result, reason = testRunner(); assert(result ~= false, reason or "Test returned false"); end; end; local function InterpretTestResult(testRanSuccessfully, result, reason) if testRanSuccessfully and result ~= false then return "Successful"; end; if result == false then return "Failed", tostring(reason or "Test failed because it returned false"); end; return "Failed", tostring(result); end; local function RunTest(self, test, testName) local function ErrorHandler(msg) local trace = Strings.Join("\n\t", Strings.Split("\n", Tests.FormattedPartialStackTrace(2, 10, 0))); return msg .. "\n\t" .. trace; end; local success, result = xpcall(Curry(CoerceTest, test), ErrorHandler); if not success then self.listener:InternalError(self, testName, result); return false; end; local testRunner = result; self.listener:TestStarted(self, testName, testRunner); local testState, reason = InterpretTestResult(xpcall(testRunner, ErrorHandler)); testRunner = WrapTestRunner(testRunner); self.listener["Test" .. testState](self.listener, self, testName, testRunner, reason); self.listener:TestFinished(self, testName, testRunner, testState, reason); return testState; end; -- Runs tests from this test suite. Every test returned by GetTests() is invoked. Their -- results are sent to this test suite's listeners. -- -- Tests are called in protected mode, so failed tests do not stop execution of subsequent -- tests. -- -- ... -- Optional. These arguments are forwarded to GetTests, so they may be used to configure -- either the number of tests or the way tests are run. Semantics of these arguments -- are defined by subclasses. If a suite does not have any filtering or customizing -- abilitiy, these arguments are silently ignored. -- returns -- false if this test suite failed -- returns -- a string describing the reason of the failure function TestSuite:Run(...) self.listener:StartAllTests(self, ...); local testResults = { All = Tests.Counter(), Successful = Tests.Counter(), Failed = Tests.Counter(), Crashed = Tests.Counter() }; for test, testName in self:TestGenerator(...) do testResults.All:Hit(); local result = RunTest(self, test, testName); testResults[result].Hit(); end; local successful = testResults.All:Get() == testResults.Successful:Get(); local report; if successful then report = ("All %d tests ran successfully."):format(testResults.All:Get()); else report = ("%d of %d tests ran successfully, %d failed, %d crashed"):format( testResults.Successful:Get(), testResults.All:Get(), testResults.Failed:Get(), testResults.Crashed:Get()); end; self.listener:FinishAllTests(self, successful, report); return successful, report; end; -- Returns all tests that this test suite contains. A test may be one of the following: -- -- * A function or callable table. The function is called with no arguments, and its -- returned value is ignored. -- * A table with a Run function. The Run function is called like a regular function with -- the proper self argument. -- * A string that represents executable code. The code is compiled and executed. -- -- The returned list is expected to be a map or list. The map's keys will be used as test names, -- and their values will be the runnable tests. -- -- ... -- Optional. These arguments may be used to configure which tests are ran, or how they -- are executed. Subclasses are expected to either define the semantics of these arguments -- or silently ignore them. -- returns -- a list, or a function that iterates over a list, of tests to be executed function TestSuite:GetTests(...) error("This method must be overridden by a subclass."); end; function TestSuite:GetCount(...) return Iterators.Size(self, "GetTests", ...); end;
--- Eva IAPs module -- Can process all in-apps in your application -- @submodule eva local app = require("eva.app") local log = require("eva.log") local luax = require("eva.luax") local const = require("eva.const") local fun = require("eva.libs.fun") local db = require("eva.modules.db") local game = require("eva.modules.game") local saver = require("eva.modules.saver") local proto = require("eva.modules.proto") local token = require("eva.modules.token") local device = require("eva.modules.device") local events = require("eva.modules.events") local wallet = require("eva.modules.wallet") local logger = log.get_logger("eva.iaps") local M = {} local function get_iaps_config() local settings = app.settings.iaps local is_ios = device.is_ios() local config_name = is_ios and settings.config_ios or settings.config_android local config = db.get(config_name) return config and config.iaps or {} end local function load_config() app.iap_products = {} local iaps = get_iaps_config() for iap_id, info in pairs(iaps) do app.iap_products[iap_id] = { is_available = false, category = info.category, price = info.price, ident = info.ident, reward_id = info.token_group_id, price_string = info.price .. " $", currency_code = "USD", title = "", description = "", } end end local function get_id_by_ident(ident) for iap_id, value in pairs(app.iap_products) do if value.ident == ident then return iap_id end end return false end local function list_callback(self, products, error) if not error then local products_string = table.concat(luax.table.list(products, "ident"), ", ") logger:info("Get product list", { products = products_string }) for k, v in pairs(products) do local iap_id = get_id_by_ident(v.ident) local iap_info = app.iap_products[iap_id] iap_info.is_available = true iap_info.currency_code = v.currency_code iap_info.title = v.title iap_info.description = v.description iap_info.price_string = v.price_string iap_info.price = v.price end else logger:warn("IAP update products error", { error = error }) end events.event(const.EVENT.IAP_UPDATE) end local function fake_transaction(iap_id, state) return { ident = iap_id, state = state or const.IAP.STATE.PURCHASED, date = game.get_current_time_string(), trans_ident = device.get_uuid(), is_fake = true, } end local function get_fake_products() local products = {} for iap_id, value in pairs(app.iap_products) do products[value.ident] = { currency_code = "USD", ident = value.ident, title = "Fake title", description = "Fake description", price_string = "$" .. value.price, price = value.price } end return products end local function save_iap(iap_id, transaction) local purchased = app[const.EVA.IAPS].purchased_iaps local iap_data = proto.get(const.EVA.IAP_INFO) iap_data.transaction_id = transaction.trans_ident iap_data.ident = transaction.ident iap_data.iap_id = iap_id iap_data.state = transaction.state iap_data.date = transaction.date table.insert(purchased, iap_data) end local function consume(iap_id, transaction) local item = M.get_iap(iap_id) if not item then logger:error("The iap_id is not exist", { iap_id = iap_id }) return end if item.reward_id then wallet.add_group(item.reward_id, const.REASON.IAP) end save_iap(iap_id, transaction) if iap and (not item.forever or device.is_ios()) then iap.finish(transaction) end events.event(const.EVENT.IAP_PURCHASE, { iap_id = iap_id, ident = item.ident }) end local function iap_listener(self, transaction, error) if not error then if luax.math.is(transaction.state, const.IAP.STATE.PURCHASED, const.IAP.STATE.RESTORED) then local iap_id = get_id_by_ident(transaction.ident) consume(iap_id, transaction) end else if error.reason == const.IAP.REASON.CANCELED then local ident = transaction and transaction.ident or "n/a" local iap_id = get_id_by_ident(ident) events.event(const.EVENT.IAP_CANCEL, { ident = ident, iap_id = iap_id }) else logger:warn("Error while IAP processing", transaction) end end end --- Buy the inapp -- @function eva.iaps.buy -- @tparam string iap_id In-game inapp ID from iaps settings function M.buy(iap_id) local products = app.iap_products local item = products[iap_id] if not item then logger:error("The IAP is not exist", { iap_id = iap_id }) return end events.event(const.EVENT.IAP_START, { ident = item.ident, iap_id = iap_id }) if iap then logger:info("Start process IAP", { iap_id = iap_id }) iap.buy(item.ident) else M.test_buy_with_fake_state(iap_id, const.IAP.STATE.PURCHASED) end return true end function M.test_buy_with_fake_state(iap_id, state, is_canceled) local products = app.iap_products local item = products[iap_id] if not item then logger:error("The IAP is not exist", { iap_id = iap_id }) return end logger:info("No IAP module, fake free transaction", { iap_id = iap_id }) local ident = products[iap_id].ident local iap_error = nil if is_canceled then iap_error = { reason = const.IAP.REASON.CANCELED } end iap_listener(nil, fake_transaction(ident, state), iap_error) return true end --- Get reward from iap_id -- @function eva.iaps.get_reward -- @tparam string iap_id the inapp id function M.get_reward(iap_id) local iap_data = get_iaps_config()[iap_id] if not iap_data then logger:error("No iap with id", { iap_id = iap_id }) end return token.get_token_group(iap_data.token_group_id) end --- Get iap info by iap_id -- @function eva.iaps.get_iap -- @tparam string iap_id the inapp id function M.get_iap(iap_id) return app.iap_products[iap_id] end --- Get all iaps. Can be selected by category -- @function eva.iaps.get_iaps -- @tparam string category Category of iap -- @treturn list of iap products function M.get_iaps(category) if not category then return app.iap_products else return fun.filter(function(id, iap_data) return iap_data.category == category end, app.iap_products):tomap() end end --- Check is iap is available -- @function eva.iaps.is_available -- @tparam string iap_id the inapp id -- @treturn bool Is available function M.is_available(iap_id) local data = M.get_iap(iap_id) if not data then logger:warn("No iap with id to check available", { iap_id = iap_id }) return false end return data.is_available end --- Get price from iap_id -- @function eva.iaps.get_price -- @tparam string iap_id the inapp id -- @treturn number Price of iap function M.get_price(iap_id) return app.iap_products[iap_id].price end --- Get price_string from iap_id -- @function eva.iaps.get_price_string -- @tparam string iap_id the inapp id -- @treturn string The iap price string function M.get_price_string(iap_id) return app.iap_products[iap_id].price_string end --- Refresh iap list. -- It make request to stores to get new info -- Throw EVENT.IAP_UPDATE at end -- @function eva.iaps.refresh_iap_list function M.refresh_iap_list() if not iap or device.is_web() then logger:debug("No iap on current platform. Fake iap module") list_callback(nil, get_fake_products()) return end iap.set_listener(iap_listener) iap.list(luax.table.list(app.iap_products, "ident"), list_callback) end --- Get total lifetime value (from iaps) -- @function eva.iaps.get_ltv -- @treturn number Player's LTV function M.get_ltv() if not app[const.EVA.IAPS] then return 0 end local ltv = 0 local purchased = app[const.EVA.IAPS].purchased_iaps for i = 1, #purchased do local info = purchased[i] local price = M.get_price(info.iap_id) or 0 ltv = ltv + price end return ltv end --- Get player max payment -- @function eva.iaps.get_max_payment -- @treturn number Max player payment function M.get_max_payment() if not app[const.EVA.IAPS] then return 0 end local max_pay = 0 local purchased = app[const.EVA.IAPS].purchased_iaps for i = 1, #purchased do local info = purchased[i] local price = M.get_price(info.iap_id) or 0 max_pay = math.max(max_pay, price) end return max_pay end function M.before_eva_init() app.iap_products = {} end function M.on_eva_init() app[const.EVA.IAPS] = proto.get(const.EVA.IAPS) saver.add_save_part(const.EVA.IAPS, app[const.EVA.IAPS]) load_config() end function M.after_eva_init() M.refresh_iap_list() end return M
do (nil)({ _1 = nil, _2 = nil }) end
local awful = require("awful") local wibox = require("wibox") local gears = require("gears") local utils = require("utils") local icons = require("icons") local BaseWidget = require("widgets.base").BaseWidget local BrightWidget = BaseWidget.derive() function BrightWidget:update() utils.async(self.getcmd, function(out) self._brightness_perc = math.ceil(out) self.widget:set_text(tostring(self._brightness_perc) .. "%") self:set_icon(icons.get_3level("brightness", self._brightness_perc)) end) end function BrightWidget:create(args) args = args or {} self.widget = wibox.widget.textbox() -- self.device = "/sys/class/backlight/" .. (args.device or "intel_backlight") self.addcmd = args.addcmd or "light -A" self.subcmd = args.subcmd or "light -U" self.getcmd = args.subcmd or "light" self._brightness_perc = 0 local box = self:init(self.widget, icons.brightness_high) box:buttons(awful.util.table.join( awful.button({}, 4, function() self:incBrightness(5) end), awful.button({}, 5, function() self:incBrightness(-5) end) )) self.timer = gears.timer({ timeout = args.timeout or 11 }) self.timer:connect_signal("timeout", function() self:update() end) self.timer:start() self:update() end function BrightWidget:getBrightness() return self._brightness_perc end function BrightWidget:incBrightness(val) local cmd = val < 0 and self.subcmd or self.addcmd utils.async(string.format("%s %s", cmd, tostring(math.abs(val))), function(out) self:update() end) end return BrightWidget
local composer = require( "composer" ) display.setStatusBar( display.HiddenStatusBar ) math.randomseed( os.time() ) composer.setVariable( "finalScore", 0 ) composer.gotoScene( "menu" )
resource_manifest_version "77731fab-63ca-442c-a67b-abc70f28dfa5" client_script "RealisticAirControl_cl.lua"
local util = {} --[[Get a random value of the chance table formatted like this: { { value = <any type>, chance = <float> }, ... } ]] function util.TableRandomChance(chanceTable) local range = 0 for _, chanceData in pairs(chanceTable) do range = range + chanceData.chance end local randomNumber = RandomInt(0, range) local top = 0 for _, chanceData in pairs(chanceTable) do top = top + chanceData.chance if randomNumber <= top then return chanceData.value end end end --Clamp a number between a minimum and a maximum function util.Clamp(value, min, max) return math.min(math.max(value, min), max) end function util.Trim(s) return string.gsub(s, "^%s*(.-)%s*$", "%1") end --Convert a comma seperated string with equal signs into a table function util.StringDataToTable(input) local output = {} for _, keyValue in pairs(vlua.split(input, ",")) do keyValue = vlua.split(keyValue, "=") keyValue[1] = util.Trim(keyValue[1]) keyValue[2] = util.Trim(keyValue[2]) output[keyValue[1]] = tonumber(keyValue[2]) or keyValue[2] end return output end return util
--# selene: allow(unused_variable) ---@diagnostic disable: unused-local -- This module provides a basic ping function which can test host availability. Ping is a network diagnostic tool commonly found in most operating systems which can be used to test if a route to a specified host exists and if that host is responding to network traffic. ---@class hs.network.ping local M = {} hs.network.ping = M -- Returns a string containing the resolved IPv4 or IPv6 address this pingObject is sending echo requests to. -- -- Parameters: -- * None -- -- Returns: -- * A string containing the IPv4 or IPv6 address this pingObject is sending echo requests to or "<unresolved address>" if the address cannot be resolved. ---@return string function M:address() end -- Cancels an in progress ping process, terminating it immediately -- -- Parameters: -- * None -- -- Returns: -- * None -- -- Notes: -- * the `didFinish` message will be sent to the callback function as its final message. function M:cancel() end -- Get or set the number of ICMP Echo Requests that will be sent by the ping process -- -- Parameters: -- * `count` - an optional integer specifying the total number of echo requests that the ping process should send. If specified, this number must be greater than the number of requests already sent. -- -- Returns: -- * if no argument is specified, returns the current number of echo requests the ping process will send; if an argument is specified and the ping process has not completed, returns the pingObject; if the ping process has already completed, then this method returns nil. function M:count(count, ...) end -- Returns whether or not the ping process is currently paused. -- -- Parameters: -- * None -- -- Returns: -- * A boolean indicating if the ping process is paused (true) or not (false) ---@return boolean function M:isPaused() end -- Returns whether or not the ping process is currently active. -- -- Parameters: -- * None -- -- Returns: -- * A boolean indicating if the ping process is active (true) or not (false) -- -- Notes: -- * This method will return false only if the ping process has finished sending all echo requests or if it has been cancelled with [hs.network.ping:cancel](#cancel). To determine if the process is currently sending out echo requests, see [hs.network.ping:isPaused](#isPaused). ---@return boolean function M:isRunning() end -- Returns a table containing information about the ICMP Echo packets sent by this pingObject. -- -- Parameters: -- * `sequenceNumber` - an optional integer specifying the sequence number of the ICMP Echo packet to return information about. -- -- Returns: -- * If `sequenceNumber` is specified, returns a table with key-value pairs containing information about the specific ICMP Echo packet with that sequence number, or an empty table if no packet with that sequence number has been sent yet. If no sequence number is specified, returns an array table of all ICMP Echo packets this object has sent. -- -- Notes: -- * Sequence numbers start at 0 while Lua array tables are indexed starting at 1. If you do not specify a `sequenceNumber` to this method, index 1 of the array table returned will contain a table describing the ICMP Echo packet with sequence number 0, index 2 will describe the ICMP Echo packet with sequence number 1, etc. -- -- * An ICMP Echo packet table will have the following key-value pairs: -- * `sent` - a number specifying the time at which the echo request for this packet was sent. This number is the number of seconds since January 1, 1970 at midnight, GMT, and is a floating point number, so you should use `math.floor` on this number before using it as an argument to Lua's `os.date` function. -- * `recv` - a number specifying the time at which the echo reply for this packet was received. This number is the number of seconds since January 1, 1970 at midnight, GMT, and is a floating point number, so you should use `math.floor` on this number before using it as an argument to Lua's `os.date` function. -- * `icmp` - a table provided by the `hs.network.ping.echoRequest` object which contains the details about the specific ICMP packet this entry corresponds to. It will contain the following keys: -- * `checksum` - The ICMP packet checksum used to ensure data integrity. -- * `code` - ICMP Control Message Code. Should always be 0. -- * `identifier` - The ICMP Identifier generated internally for matching request and reply packets. -- * `payload` - A string containing the ICMP payload for this packet. This has been constructed to cause the ICMP packet to be exactly 64 bytes to match the convention for ICMP Echo Requests. -- * `sequenceNumber` - The ICMP Sequence Number for this packet. -- * `type` - ICMP Control Message Type. For ICMPv4, this will be 0 if a reply has been received or 8 no reply has been received yet. For ICMPv6, this will be 129 if a reply has been received or 128 if no reply has been received yet. -- * `_raw` - A string containing the ICMP packet as raw data. function M:packets(sequenceNumber, ...) end -- Pause an in progress ping process. -- -- Parameters: -- * None -- -- Returns: -- * if the ping process is currently active, returns the pingObject; if the process has already completed, returns nil. function M:pause() end -- Test server availability by pinging it with ICMP Echo Requests. -- -- Parameters: -- * `server` - a string containing the hostname or ip address of the server to test. Both IPv4 and IPv6 addresses are supported. -- * `count` - an optional integer, default 5, specifying the number of ICMP Echo Requests to send to the server. -- * `interval` - an optional number, default 1.0, in seconds specifying the delay between the sending of each echo request. To set this parameter, you must supply `count` as well. -- * `timeout` - an optional number, default 2.0, in seconds specifying how long before an echo reply is considered to have timed-out. To set this parameter, you must supply `count` and `interval` as well. -- * `class` - an optional string, default "any", specifying whether IPv4 or IPv6 should be used to send the ICMP packets. The string must be one of the following: -- * `any` - uses the IP version which corresponds to the first address the `server` resolves to -- * `IPv4` - use IPv4; if `server` cannot resolve to an IPv4 address, or if IPv4 traffic is not supported on the network, the ping will fail with an error. -- * `IPv6` - use IPv6; if `server` cannot resolve to an IPv6 address, or if IPv6 traffic is not supported on the network, the ping will fail with an error. -- * `fn` - the callback function which receives update messages for the ping process. See the Notes for details regarding the callback function. -- -- Returns: -- * a pingObject -- -- Notes: -- * For convenience, you can call this constructor as `hs.network.ping(server, ...)` -- * the full ping process will take at most `count` * `interval` + `timeout` seconds from `didStart` to `didFinish`. -- -- * the default callback function, if `fn` is not specified, prints the results of each echo reply as they are received to the Hammerspoon console and a summary once completed. The output should be familiar to anyone who has used `ping` from the command line. -- -- * If you provide your own callback function, it should expect between 2 and 4 arguments and return none. The possible arguments which are sent will be one of the following: -- -- * "didStart" - indicates that address resolution has completed and the ping will begin sending ICMP Echo Requests. -- * `object` - the ping object the callback is for -- * `message` - the message to the callback, in this case "didStart" -- -- * "didFail" - indicates that the ping process has failed, most likely due to a failure in address resolution or because the network connection has dropped. -- * `object` - the ping object the callback is for -- * `message` - the message to the callback, in this case "didFail" -- * `error` - a string containing the error message that has occurred -- -- * "sendPacketFailed" - indicates that a specific ICMP Echo Request has failed for some reason. -- * `object` - the ping object the callback is for -- * `message` - the message to the callback, in this case "sendPacketFailed" -- * `sequenceNumber` - the sequence number of the ICMP packet which has failed to send -- * `error` - a string containing the error message that has occurred -- -- * "receivedPacket" - indicates that an ICMP Echo Request has received the expected ICMP Echo Reply -- * `object` - the ping object the callback is for -- * `message` - the message to the callback, in this case "receivedPacket" -- * `sequenceNumber` - the sequence number of the ICMP packet received -- -- * "didFinish" - indicates that the ping has finished sending all ICMP Echo Requests or has been cancelled -- * `object` - the ping object the callback is for -- * `message` - the message to the callback, in this case "didFinish" function M.ping(server, count, interval, timeout, class, fn, ...) end -- Resume an in progress ping process, if it has been paused. -- -- Parameters: -- * None -- -- Returns: -- * if the ping process is currently active, returns the pingObject; if the process has already completed, returns nil. function M:resume() end -- Returns the number of ICMP Echo Requests which have been sent. -- -- Parameters: -- * None -- -- Returns: -- * The number of echo requests which have been sent so far. ---@return number function M:sent() end -- Returns the hostname or ip address string given to the [hs.network.ping.ping](#ping) constructor. -- -- Parameters: -- * None -- -- Returns: -- * A string matching the hostname or ip address given to the [hs.network.ping.ping](#ping) constructor for this object. ---@return string function M:server() end -- Set or remoce the callback function for the pingObject. -- -- Parameters: -- * `fn` - the function to set as the callback, or nil if you wish use the default callback. -- -- Returns: -- * the pingObject -- -- Notes: -- * Because the ping process begins immediately upon creation with the [hs.network.ping.ping](#ping) constructor, it is preferable to assign the callback with the constructor itself. -- * This method is provided as a means of changing the callback based on other events (a change in the current network or location, perhaps.) -- * If you truly wish to create a pingObject with no callback, you will need to do something like `hs.network.ping.ping(...):setCallback(function() end)`. function M:setCallback(fn) end -- Returns a string containing summary information about the ping process. -- -- Parameters: -- * None -- -- Returns: -- * a summary string for the current state of the ping process -- -- Notes: -- * The summary string will look similar to the following: -- ~~~ -- --- hostname ping statistics -- 5 packets transmitted, 5 packets received, 0.0 packet loss -- round-trip min/avg/max = 2.282/4.133/4.926 ms -- ~~~ -- * The numer of packets received will match the number that has currently been sent, not necessarily the value returned by [hs.network.ping:count](#count). ---@return string function M:summary() end
local tiny = require('lib.tiny') local class = require('lib.middleclass') local System = tiny.processingSystem(class('system.input.keyboard')) function System:initialize() self.filter = tiny.requireAll('isPlayer', 'left', 'right', 'space') end function System:process(e, dt) e.left = love.keyboard.isDown('a') or love.keyboard.isDown('left') e.right = love.keyboard.isDown('d') or love.keyboard.isDown('right') e.space = love.keyboard.isDown('space') end return System
local storages = {} local storageBusy = {} function findStorageWithSameName(name) for k, v in pairs(storages) do if v.name == name then return k end end end function removeStorage(id) storages[id] = nil TriggerEvent('rcore:updateStorages') end exports('removeStorage',removeStorage) function setStorageBusy(id,state) if Config.Debug then print(string.format('[rcore] Setting storage with id %s to busy state %s',id,state)) end TriggerServerEvent('rcore:setStorageBusy',id,state) end exports('setStorageBusy',setStorageBusy) function isStorageBusy(id) return storageBusy[id] or false end exports('isStorageBusy',isStorageBusy) function updateStorage(id,title,name,datastore,coords,options) storages[id] = { id = id, title = title, name = name, datastore = datastore, coords = coords, options = options, distance = options.distance or 100, updated = true } if Config.Debug then print(string.format('[rcore] Updating storage with id %s',id)) end return id end exports('updateStorage',updateStorage) function addStorage(title, name, datastore, coords, options) local findId = findStorageWithSameName(name) if findId then updateStorage(findId,title,name,datastore,coords,options) TriggerEvent('rcore:updateStorages') return findId else local id = tableLastIterator(storages)+1 table.insert(storages,{ id = id, title = title, name = name, datastore = datastore, coords = coords, options = options, distance = options.distance or 100 }) if Config.Debug then print(string.format('[rcore] Creating storage with id %s',id)) end TriggerEvent('rcore:updateStorages') return id end end exports('addStorage',addStorage) function closeStorageMenu(id) local storage = storages[id] if storage ~= nil then local idName = string.format('storage-%s-%s-',id,storage.name) closeMenu(idName) closeMenu(idName..'store_weapon') closeMenu(idName..'get_weapon') closeMenu(idName..'store_item') closeMenu(idName..'get_item') closeMenu(idName..'store_money') closeMenu(idName..'get_money') closeDialog(idName..'get_money_count') closeDialog(idName..'store_money_count') closeDialog(idName..'store_item_count') closeDialog(idName..'get_item_count') end end function openStorageMenu(id, title, name, datastore, menuContext) local menuOptions = {} if menuContext == nil then menuOptions = { { label = 'Uschovat zbran', value = 'store_weapon' }, { label = 'Vybrat zbran', value = 'get_weapon' }, { label = 'Uschovat predmet', value = 'store_item' }, { label = 'Vybrat predmet', value = 'get_item' }, { label = 'Uschovat penize', value = 'store_money' }, { label = 'Vybrat penize', value = 'get_money' }, } else for k, v in pairs(menuContext) do if v == "store_weapon" then table.insert(menuOptions,{ label = 'Uschovat zbran', value = 'store_weapon' }) elseif v == "get_weapon" then table.insert(menuOptions,{ label = 'Vybrat zbran', value = 'get_weapon' }) elseif v == "store_item" then table.insert(menuOptions,{ label = 'Uschovat predmet', value = 'store_item' }) elseif v == "get_item" then table.insert(menuOptions,{ label = 'Vybrat predmet', value = 'get_item' }) elseif v == "store_money" then table.insert(menuOptions,{ label = 'Uschovat penize', value = 'store_money' }) elseif v == "get_money" then table.insert(menuOptions,{ label = 'Vybrat penize', value = 'get_money' }) end end end local idName = string.format('storage-%s-%s-',id,name) createMenu(title, idName, menuOptions, { submit = function(data, menu) local value = data.current.value if value == "store_weapon" then ESX.TriggerServerCallback('rcore:getWeapons', function(weapons) createMenu(title, idName..'store_weapon', weapons, { submit = function(data, menu2) menu2.close() ESX.TriggerServerCallback('rcore:storeWeapon', function(stored) showNotification('~g~Uspesne jste ulozili zbran do trezoru!') end,getClientKey(GetCurrentResourceName()), data.current.value, datastore) end }) end) elseif value == "get_weapon" then ESX.TriggerServerCallback('rcore:getStoredWeapons', function(weapons) createMenu(title, idName..'get_weapon', weapons, { submit = function(data, menu2) menu2.close() ESX.TriggerServerCallback('rcore:getStoredWeapon', function(get) if get then showNotification('~g~Uspesne jste si vybral zbran z trezoru!') else showNotification('~r~Tak tuto zbran tu opravdu nemame!') end end,getClientKey(GetCurrentResourceName()), datastore, data.current.value) end }) end,getClientKey(GetCurrentResourceName()), datastore) elseif value == "store_item" then ESX.TriggerServerCallback('rcore:getInventory', function(inv) createMenu(title, idName..'store_item', inv, { submit = function(data, menu2) createDialog('Pocet k ulozeni?',idName..'store_item_count',function(data2,menu3) menu3.close() menu2.close() local count = tonumber(data2.value) if count ~= nil and count > 0 then ESX.TriggerServerCallback('rcore:storeInventoryItem',function(state) if state then showNotification('~g~Uspesne~w~ si uschoval predmet') else showNotification('~r~Nepodarilo~w~ se ti to tam narvat!') end end,getClientKey(GetCurrentResourceName()),datastore,data.current.value,count) else showNotification('Neplatna castka') end end) end }) end) elseif value == "get_item" then ESX.TriggerServerCallback('rcore:getStoredItems', function(items) createMenu(title, idName..'get_item', items, { submit = function(data, menu2) createDialog('Pocet k vybrani?',idName..'get_item_count',function(data2,menu3) menu3.close() menu2.close() local count = tonumber(data2.value) if count ~= nil and count > 0 then ESX.TriggerServerCallback('rcore:getStoredInventoryItem', function(get) if get == true then showNotification('~g~Uspesne~w~ jste vybrali ze skladu!') elseif get == false then showNotification('~r~Tak takto asi ne!') else showNotification('~w~Tolik toho opravdu ~r~neuneses!') end end,getClientKey(GetCurrentResourceName()), datastore, data.current.value,count) else showNotification('~r~Neplatny~w~ pocet!') end end) end }) end,getClientKey(GetCurrentResourceName()), datastore) elseif value == "store_money" then createMenu(title, idName..'store_money', { {label = 'Spinave penize', value = 'black_money'}, {label = 'Ciste penize', value = 'cash'} }, { submit = function(data, menu2) createDialog('Pocet k ulozeni?', idName..'store_money_count',function(data2,menu3) menu3.close() menu2.close() local count = tonumber(data2.value) if count ~= nil and count > 0 then ESX.TriggerServerCallback('rcore:putStoredMoney',function(is) if is then if data.current.value == "cash" then showNotification(string.format('Vyborne, prave jste ~g~ulozili %s$',ESX.Math.GroupDigits(count))) else showNotification(string.format('Vyborne, prave jste ~g~ulozili %s$~w~ spinavych penez',ESX.Math.GroupDigits(count))) end else showNotification('~w~Takto to nepujde, ~r~nemuzete~w~ dat vice nez mate') end end,getClientKey(GetCurrentResourceName()),datastore,data.current.value,count) else showNotification('~r~Neplatny~w~ pocet!') end end) end }) elseif value == "get_money" then ESX.TriggerServerCallback('rcore:getStoredMoney',function(options) createMenu(title, idName..'get_money', options, { submit = function(data, menu2) createDialog('Pocet k ulozeni?', idName..'get_money_count',function(data2,menu3) menu3.close() menu2.close() local count = tonumber(data2.value) if count ~= nil and count > 0 then ESX.TriggerServerCallback('rcore:takeStoredMoney',function(is) if is then if data.current.value == "cash" then showNotification(string.format('Vyborne, prave jste ~g~vybrali %s$',ESX.Math.GroupDigits(count))) else showNotification(string.format('Vyborne, prave jste ~g~vybrali %s$~w~ spinavych penez',ESX.Math.GroupDigits(count))) end else showNotification('~w~Takto to nepujde, ~r~nemuzete~w~ vzit vice nez tam je') end end,getClientKey(GetCurrentResourceName()),datastore,data.current.value,count) else showNotification('~r~Neplatny~w~ pocet!') end end) end }) end,getClientKey(GetCurrentResourceName()),datastore) end end }) end function getStorages() return storages end exports('getStorages',getStorages) RegisterNetEvent('rcore:updateStorageBusy') AddEventHandler('rcore:updateStorageBusy',function(storages) storageBusy = storages end)
----------------------------------- -- Ability: Overdrive -- Augments the fighting ability of your automaton to its maximum level. -- Obtained: Puppetmaster Level 1 -- Recast Time: 1:00:00 -- Duration: 1:00 ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/pets") require("scripts/globals/msg") ----------------------------------- function onAbilityCheck(player,target,ability) if not player:getPet() then return tpz.msg.basic.REQUIRES_A_PET, 0 elseif not player:getPetID() or not (player:getPetID() >= 69 and player:getPetID() <= 72) then return tpz.msg.basic.NO_EFFECT_ON_PET, 0 else return 0, 0 end end function onUseAbility(player,target,ability) player:addStatusEffect(tpz.effect.OVERDRIVE, 0, 0, 60) return tpz.effect.OVERDRIVE end
--[[============================================================================= Properties Code Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] -- This macro is utilized to identify the version string of the driver template version used. if (TEMPLATE_VERSION ~= nil) then TEMPLATE_VERSION.properties = "2014.10.31" end function ON_PROPERTY_CHANGED.System(propertyValue) AddDriverToCarrier() end function ON_PROPERTY_CHANGED.Zone(propertyValue) AddDriverToCarrier() end
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:27' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ZO_Repair = ZO_InitializingObject:Subclass() local DATA_TYPE_REPAIR_ITEM = 1 function ZO_Repair:Initialize(control) self.control = control control.owner = self REPAIR_FRAGMENT = ZO_FadeSceneFragment:New(control) self.list = self.control:GetNamedChild("List") self.activeTab = self.control:GetNamedChild("TabsActive") self.tabs = self.control:GetNamedChild("Tabs") self.freeSlotsLabel = self.control:GetNamedChild("InfoBarFreeSlots") self.money = self.control:GetNamedChild("InfoBarMoney") self:InitializeList() self:InitializeFilterBar() self:InitializeSortHeader() self:InitializeEvents() end function ZO_Repair:InitializeList() ZO_ScrollList_AddDataType(self.list, DATA_TYPE_REPAIR_ITEM, "ZO_PlayerInventorySlot", 52, function(control, data) self:SetupRepairItem(control, data) end, nil, nil, ZO_InventorySlot_OnPoolReset) end function ZO_Repair:InitializeFilterBar() local menuBarData = { initialButtonAnchorPoint = RIGHT, buttonTemplate = "ZO_StoreTab", normalSize = 51, downSize = 64, buttonPadding = -15, animationDuration = 180, } ZO_MenuBar_SetData(self.tabs, menuBarData) local repairFilter = { tooltipText = GetString("SI_ITEMFILTERTYPE", ITEMFILTERTYPE_DAMAGED), filterType = ITEMFILTERTYPE_DAMAGED, descriptor = ITEMFILTERTYPE_DAMAGED, normal = "EsoUI/Art/Repair/inventory_tabIcon_repair_up.dds", pressed = "EsoUI/Art/Repair/inventory_tabIcon_repair_down.dds", highlight = "EsoUI/Art/Repair/inventory_tabIcon_repair_over.dds", } ZO_MenuBar_AddButton(self.tabs, repairFilter) ZO_MenuBar_SelectDescriptor(self.tabs, ITEMFILTERTYPE_DAMAGED) self.activeTab:SetText(GetString("SI_ITEMFILTERTYPE", ITEMFILTERTYPE_DAMAGED)) end function ZO_Repair:InitializeSortHeader() self.sortHeaders = ZO_SortHeaderGroup:New(self.control:GetNamedChild("SortBy"), true) self.sortOrder = ZO_SORT_ORDER_UP self.sortKey = "name" local function OnSortHeaderClicked(key, order) self.sortKey = key self.sortOrder = order self:ApplySort() end self.sortHeaders:RegisterCallback(ZO_SortHeaderGroup.HEADER_CLICKED, OnSortHeaderClicked) self.sortHeaders:AddHeadersFromContainer() self.sortHeaders:SelectHeaderByKey("name", ZO_SortHeaderGroup.SUPPRESS_CALLBACKS) self.searchBox = self.control:GetNamedChild("SearchFiltersTextSearchBox") local function OnTextSearchTextChanged(editBox) ZO_EditDefaultText_OnTextChanged(editBox) TEXT_SEARCH_MANAGER:SetSearchText("storeTextSearch", editBox:GetText()) end self.searchBox:SetHandler("OnTextChanged", OnTextSearchTextChanged) local SUPPRESS_TEXT_CHANGED_CALLBACK = true local function OnListTextFilterComplete() if REPAIR_FRAGMENT:IsShowing() then self.searchBox:SetText(TEXT_SEARCH_MANAGER:GetSearchText("storeTextSearch"), SUPPRESS_TEXT_CHANGED_CALLBACK) self:RefreshAll() end end TEXT_SEARCH_MANAGER:RegisterCallback("UpdateSearchResults", OnListTextFilterComplete) end function ZO_Repair:InitializeEvents() local function RefreshAll() if not self.control:IsControlHidden() then self:RefreshAll() end end self.control:RegisterForEvent(EVENT_MONEY_UPDATE, function() self:UpdateMoney() end) self.control:RegisterForEvent(EVENT_INVENTORY_SINGLE_SLOT_UPDATE, RefreshAll) self.control:RegisterForEvent(EVENT_INVENTORY_FULL_UPDATE, RefreshAll) end function ZO_Repair:RefreshAll() self:UpdateList() self:UpdateFreeSlots() end function ZO_Repair:UpdateMoney() if not self.control:IsControlHidden() then ZO_CurrencyControl_SetSimpleCurrency(self.money, CURT_MONEY, GetCurrencyAmount(CURT_MONEY, CURRENCY_LOCATION_CHARACTER), ZO_KEYBOARD_CURRENCY_OPTIONS) end end function ZO_Repair:UpdateFreeSlots() if not self.control:IsControlHidden() then local numUsedSlots, numSlots = PLAYER_INVENTORY:GetNumSlots(INVENTORY_BACKPACK) if numUsedSlots < numSlots then self.freeSlotsLabel:SetText(zo_strformat(SI_INVENTORY_BACKPACK_REMAINING_SPACES, numUsedSlots, numSlots)) else self.freeSlotsLabel:SetText(zo_strformat(SI_INVENTORY_BACKPACK_COMPLETELY_FULL, numUsedSlots, numSlots)) end end end do local function GatherDamagedEquipmentFromBag(bagId, dataTable) for slotIndex in ZO_IterateBagSlots(bagId) do if TEXT_SEARCH_MANAGER:IsItemInSearchTextResults("storeTextSearch", BACKGROUND_LIST_FILTER_TARGET_BAG_SLOT, bagId, slotIndex) then local condition = GetItemCondition(bagId, slotIndex) if condition < 100 and not IsItemStolen(bagId, slotIndex) then local icon, stackCount, _, _, _, _, _, functionalQuality, displayQuality = GetItemInfo(bagId, slotIndex) if stackCount > 0 then local repairCost = GetItemRepairCost(bagId, slotIndex) if repairCost > 0 then local name = zo_strformat(SI_TOOLTIP_ITEM_NAME, GetItemName(bagId, slotIndex)) local data = { bagId = bagId, slotIndex = slotIndex, name = name, icon = icon, stackCount = stackCount, functionalQuality = functionalQuality, displayQuality = displayQuality, -- quality is deprecated, included here for addon backwards compatibility quality = displayQuality, condition = condition, repairCost = repairCost } dataTable[#dataTable + 1] = ZO_ScrollList_CreateDataEntry(DATA_TYPE_REPAIR_ITEM, data) end end end end end end function ZO_Repair:UpdateList() if not self.control:IsControlHidden() then ZO_ScrollList_Clear(self.list) ZO_ScrollList_ResetToTop(self.list) local scrollData = ZO_ScrollList_GetDataList(self.list) GatherDamagedEquipmentFromBag(BAG_WORN, scrollData) GatherDamagedEquipmentFromBag(BAG_BACKPACK, scrollData) self:ApplySort() end end end local REPAIR_COST_CURRENCY_OPTIONS = { showTooltips = false, font = "ZoFontGameShadow", iconSide = RIGHT, } function ZO_Repair:SetupRepairItem(control, data) local statusControl = GetControl(control, "Status") local slotControl = GetControl(control, "Button") local nameControl = GetControl(control, "Name") local repairCostControl = GetControl(control, "SellPrice") local itemConditionControl = GetControl(control, "ItemCondition") statusControl:SetHidden(true) ZO_Inventory_BindSlot(slotControl, SLOT_TYPE_REPAIR, data.slotIndex, data.bagId) ZO_Inventory_BindSlot(control, SLOT_TYPE_REPAIR, data.slotIndex, data.bagId) ZO_Inventory_SetupSlot(slotControl, data.stackCount, data.icon) nameControl:SetText(data.name) -- already formatted -- data.quality is deprecated, included here for addon backwards compatibility local displayQuality = data.displayQuality or data.quality nameControl:SetColor(GetInterfaceColor(INTERFACE_COLOR_TYPE_ITEM_QUALITY_COLORS, displayQuality)) repairCostControl:SetHidden(false) ZO_CurrencyControl_SetSimpleCurrency(repairCostControl, CURT_MONEY, data.repairCost, REPAIR_COST_CURRENCY_OPTIONS) itemConditionControl:SetText(zo_strformat(SI_ITEM_CONDITION_PERCENT, data.condition)) end do local sortKeys = { name = { }, condition = { tiebreaker = "name", isNumeric = true }, repairCost = { tiebreaker = "name", isNumeric = true }, } function ZO_Repair:ApplySort() local function Comparator(left, right) return ZO_TableOrderingFunction(left.data, right.data, self.sortKey, sortKeys, self.sortOrder) end local scrollData = ZO_ScrollList_GetDataList(self.list) table.sort(scrollData, Comparator) ZO_ScrollList_Commit(self.list) end end function ZO_Repair:OnShown() self.searchBox:SetText(TEXT_SEARCH_MANAGER:GetSearchText("storeTextSearch")) self:UpdateList() self:UpdateMoney() self:UpdateFreeSlots() end function ZO_Repair_OnInitialize(control) REPAIR_WINDOW = ZO_Repair:New(control) end
local F, C = unpack(select(2, ...)) tinsert(C.themes["FreeUI"], function() if C.isClassic then return end _G.LossOfControlFrame.RedLineTop:SetTexture(nil) _G.LossOfControlFrame.RedLineBottom:SetTexture(nil) _G.LossOfControlFrame.blackBg:SetTexture(nil) local styled hooksecurefunc("LossOfControlFrame_SetUpDisplay", function(self) if not styled then self.Icon:SetTexCoord(unpack(C.TexCoord)) local bg = F.CreateBDFrame(self.Icon) F.CreateSD(bg) styled = true end end) end)
local _, private = ... local L = private.L --[[ Lua Globals ]] -- luacheck: globals tinsert wipe select next --[[ Core ]] local Aurora = private.Aurora local Hook, Skin = Aurora.Hook, Aurora.Skin local checkboxes = {} local function RemoveCheckedItem(mailIndex) private.debug("RemoveCheckedItem", mailIndex, checkboxes[mailIndex]) checkboxes[mailIndex]:SetChecked(false) checkboxes[mailIndex] = nil end local function UpdateCheckedItems() private.debug("UpdateCheckedItems") local numItems = _G.GetInboxNumItems() local index = ((_G.InboxFrame.pageNum - 1) * _G.INBOXITEMS_TO_DISPLAY) + 1 for i = 1, _G.INBOXITEMS_TO_DISPLAY do local mailItem = _G["MailItem"..i] if index <= numItems then if checkboxes[index] then private.debug("checkbox", i, index, checkboxes[index]) mailItem.checkbox:SetChecked(true) else mailItem.checkbox:SetChecked(false) end else mailItem.checkbox:SetChecked(false) end index = index + 1 end private.debug("next", next(checkboxes)) if next(checkboxes) then _G.OpenAllMail:Hide() _G.InboxFrameOpenChecked:Show() else _G.OpenAllMail:Show() _G.InboxFrameOpenChecked:Hide() end end local function ResetCheckedItems() wipe(checkboxes) UpdateCheckedItems() end local OPEN_ALL_MAIL_MIN_DELAY = 0.15 local OpenCheckedMailMixin = _G.Mixin({}, _G.OpenAllMailMixin) function OpenCheckedMailMixin:StopOpening() private.debug("StopOpening") ResetCheckedItems() self:Reset() self:Enable() self:SetText(L.MailFrame_OpenChecked) self:UnregisterEvent("MAIL_INBOX_UPDATE") self:UnregisterEvent("MAIL_FAILED") end function OpenCheckedMailMixin:AdvanceToNextItem() local foundAttachment = false private.debug("AdvanceToNextItem", self.mailIndex, self.attachmentIndex) if checkboxes[self.mailIndex] then while ( not foundAttachment ) do local _, _, _, _, _, CODAmount = _G.GetInboxHeaderInfo(self.mailIndex) local itemID = select(2, _G.GetInboxItem(self.mailIndex, self.attachmentIndex)) local hasBlacklistedItem = self:IsItemBlacklisted(itemID) local hasCOD = CODAmount and CODAmount > 0 local hasMoneyOrItem = _G.C_Mail.HasInboxMoney(self.mailIndex) or _G.HasInboxItem(self.mailIndex, self.attachmentIndex) if ( not hasBlacklistedItem and not hasCOD and hasMoneyOrItem ) then foundAttachment = true else self.attachmentIndex = self.attachmentIndex - 1 if ( self.attachmentIndex == 0 ) then RemoveCheckedItem(self.mailIndex) break end end end end private.debug("foundAttachment", foundAttachment, self.attachmentIndex) if ( not foundAttachment ) then self.mailIndex = self.mailIndex + 1 self.attachmentIndex = _G.ATTACHMENTS_MAX if ( self.mailIndex > _G.GetInboxNumItems() ) then return false end return self:AdvanceToNextItem() end return true end function OpenCheckedMailMixin:ProcessNextItem() private.debug("ProcessNextItem") local _, _, _, _, money, CODAmount, _, itemCount, _, _, _, _, isGM = _G.GetInboxHeaderInfo(self.mailIndex) if ( isGM or (CODAmount and CODAmount > 0) ) then self:AdvanceAndProcessNextItem() return end private.debug("NextItem", money, itemCount) if ( money > 0 ) then if not itemCount then RemoveCheckedItem(self.mailIndex) end self.timeUntilNextRetrieval = OPEN_ALL_MAIL_MIN_DELAY _G.TakeInboxMoney(self.mailIndex) elseif ( itemCount and itemCount > 0 ) then if itemCount == 1 then RemoveCheckedItem(self.mailIndex) end self.timeUntilNextRetrieval = OPEN_ALL_MAIL_MIN_DELAY _G.TakeInboxItem(self.mailIndex, self.attachmentIndex) else RemoveCheckedItem(self.mailIndex) self:AdvanceAndProcessNextItem() end private.debug("timeUntilNextRetrieval", self.timeUntilNextRetrieval) end do --[[ FrameXML\MailFrame.lua ]] local numItems _G.hooksecurefunc(Hook, "InboxFrame_Update", function() local newNumItems = _G.GetInboxNumItems() private.debug("InboxFrame_Update", numItems, newNumItems) if numItems ~= newNumItems then numItems = newNumItems local index = ((_G.InboxFrame.pageNum - 1) * _G.INBOXITEMS_TO_DISPLAY) + 1 for i = 1, _G.INBOXITEMS_TO_DISPLAY do local mailItem = _G["MailItem"..i] if index <= numItems then private.debug("checkbox", i, index, checkboxes[index]) if checkboxes[index + 1] then -- mailIndexes changed, we need to increment down the checkboxes -- to ensure that the correct mail items get taken. checkboxes[index + 1] = nil checkboxes[index] = mailItem.checkbox end end index = index + 1 end end UpdateCheckedItems() end) end do --[[ FrameXML\MailFrame.xml ]] local function OnClick(self) local mailItem = self:GetParent() if self:GetChecked() then _G.PlaySound(_G.SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON) checkboxes[mailItem.Button.index] = mailItem.checkbox else _G.PlaySound(_G.SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_OFF) checkboxes[mailItem.Button.index] = nil end UpdateCheckedItems() end _G.hooksecurefunc(Skin, "MailItemTemplate", function(Frame) Frame:SetSize(295, 45) local check = _G.CreateFrame("CheckButton", "$parentCheck", Frame, "UICheckButtonTemplate") Skin.UICheckButtonTemplate(check) check:SetPoint("RIGHT", Frame.Button, "LEFT", -3, 0) check:SetScript("OnClick", OnClick) Frame.checkbox = check end) end _G.hooksecurefunc(private.FrameXML, "MailFrame", function() _G.MailItem1:SetPoint("TOPLEFT", 33, -(private.FRAME_TITLE_HEIGHT + 5)) local openChecked = _G.CreateFrame("Button", "$parentOpenChecked", _G.InboxFrame, "UIPanelButtonTemplate") Skin.UIPanelButtonTemplate(openChecked) openChecked:SetText(L.MailFrame_OpenChecked) openChecked:SetPoint("BOTTOM", 0, 14) openChecked:SetSize(120, 24) openChecked:Hide() _G.Mixin(openChecked, OpenCheckedMailMixin) openChecked:SetScript("OnEvent", openChecked.OnEvent) openChecked:SetScript("OnClick", openChecked.OnClick) openChecked:SetScript("OnUpdate", openChecked.OnUpdate) openChecked:SetScript("OnHide", openChecked.OnHide) openChecked:OnLoad() ------------- -- Section -- ------------- --[[ Scale ]]-- end)
-------------------------------------------------------------------------------- -- Module declaration -- local mod, CL = BigWigs:NewBoss("Wing Leader Ner'onok", 1011, 727) if not mod then return end mod:RegisterEnableMob(62205) mod.engageId = 1464 mod.respawnTime = 30 -------------------------------------------------------------------------------- -- Locals -- local nextWindsWarning = 75 -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { "stages", 121443, -- Caustic Pitch -6205, -- Quick-Dry Resin (EJ entry mentions Invigorated) 121284, -- Gusting Winds } end function mod:OnBossEnable() self:Log("SPELL_AURA_APPLIED", "CausticPitch", 121443) self:Log("SPELL_PERIODIC_DAMAGE", "CausticPitch", 121443) self:Log("SPELL_PERIODIC_MISSED", "CausticPitch", 121443) self:Log("SPELL_AURA_APPLIED", "QuickDryResin", 121447) self:Log("SPELL_AURA_APPLIED", "Invigorated", 121449) self:Log("SPELL_AURA_APPLIED", "GustingWinds", 121282, 121284) self:Log("SPELL_INTERRUPT", "GustingWindsInterrupted", "*") self:RegisterUnitEvent("UNIT_HEALTH_FREQUENT", nil, "boss1") end function mod:OnEngage() nextWindsWarning = 75 -- casts it at 70% and 40% end -------------------------------------------------------------------------------- -- Event Handlers -- do local prev = 0 function mod:CausticPitch(args) if self:Me(args.destGUID) then local t = GetTime() if t-prev > 1.5 then prev = t self:Message(args.spellId, "blue", "Alert", CL.underyou:format(args.spellName)) end end end end function mod:QuickDryResin(args) if self:Me(args.destGUID) then self:Message(-6205, "blue", "Alarm", CL.you:format(args.spellName)) end end function mod:Invigorated(args) if self:Me(args.destGUID) then self:Message(-6205, "green", "Info", CL.you:format(args.spellName), args.spellId) end end do local scheduledCooldownTimer = nil function mod:GustingWinds(args) self:Message(121284, "orange", self:Interrupter() and "Warning" or "Long", CL.casting:format(args.spellName)) self:CastBar(121284, 4) scheduledCooldownTimer = self:ScheduleTimer("CDBar", 4.1, 121284, 3.2) -- 7.3s CD end function mod:GustingWindsInterrupted(args) if args.extraSpellId == 121282 or args.extraSpellId == 121284 then -- Gusting Winds self:Message(121284, "green", nil, CL.interrupted_by:format(args.extraSpellName, self:ColorName(args.sourceName))) self:StopBar(CL.cast:format(args.extraSpellName)) if scheduledCooldownTimer then self:CancelTimer(scheduledCooldownTimer) scheduledCooldownTimer = nil end end end end function mod:UNIT_HEALTH_FREQUENT(event, unit) local hp = UnitHealth(unit) / UnitHealthMax(unit) * 100 if hp < nextWindsWarning then nextWindsWarning = nextWindsWarning - 30 self:Message("stages", "yellow", nil, CL.soon:format(self:SpellName(-6297)), false) -- -6297 = Treacherous Winds if nextWindsWarning < 40 then self:UnregisterUnitEvent(event, unit) end end end
if not _G.plugin_loaded("nvim-scrollview") then do return end end vim.g.scrollview_base = "buffer" vim.g.scrollview_column = 80
function create(dialogObject, bindings) print(bindings) print(dialogObject) dSysClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogSystem" ); dSysFactoryClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogStateMachineFactory" ); dSysEntryClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogStateMachineFactoryEntry" ); hookClass = luajava.bindClass( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua" ); dSys = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogSystem", dialogObject ); print(dSys); factory = dSys:getFactory(bindings); hook = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogTextEntryHookLua", "hookFunc", {} ); entry = luajava.newInstance( "org.schema.game.common.data.player.dialog.TextEntry", "Check this cool contraption I made. You can pretty much do anything with the logic blocks, as they\n".. "work just like electrical circuits." , 2000 ); factory:setRootEntry(entry); dSys:add(factory) return dSys --frame = luajava.newInstance( "org.schema.game.common.data.player.dialog.DialogSystem", "Texts" ); --frame:test() end