content
stringlengths
5
1.05M
-- Zytharian (roblox: Legend26) -- Description: -- Quick and dirty Jumper compatibility shim local NAME = "BOUNDARY_VALUE_SYNC" local model = script.Parent.Parent local remoteFn = Instance.new("RemoteFunction") remoteFn.Name = NAME remoteFn.Parent = model remoteFn.OnServerInvoke = (function (player, valueObject, value, childClass) -- Get the target, make sure it's a *Value object local target = type(valueObject) == "string" and model:FindFirstChild(valueObject) or nil if (not target) or (not target:IsA("ValueBase")) then return end -- Update the value pcall(function() if (not childClass) then if (target.Value == value) then return end target.Value = value else local child = Instance.new(childClass) if (not child:IsA("ValueBase")) then return end child.Name = "DO_NOT_REPLICATE" child.Value = value child.Parent = target end end) end)
local Plugin = script.Parent.Parent.Parent.Parent local Libs = Plugin.Libs local Roact = require(Libs.Roact) local RoactRodux = require(Libs.RoactRodux) local Utility = require(Plugin.Core.Util.Utility) local Constants = require(Plugin.Core.Util.Constants) local ContextGetter = require(Plugin.Core.Util.ContextGetter) local ContextHelper = require(Plugin.Core.Util.ContextHelper) local withTheme = ContextHelper.withTheme local withModal = ContextHelper.withModal local getModal = ContextGetter.getModal local Components = Plugin.Core.Components local Foundation = Components.Foundation local PreciseFrame = require(Foundation.PreciseFrame) local PreciseButton = require(Foundation.PreciseButton) local LabeledFieldTemplate = Roact.PureComponent:extend("LabeledFieldTemplate") function LabeledFieldTemplate:init() end function LabeledFieldTemplate:render() local props = self.props local LayoutOrder = props.LayoutOrder local ZIndex = props.ZIndex local label = props.label local indentLevel = props.indentLevel or 0 local labelWidth = props.labelWidth or 120 local Visible = props.Visible local collapsible = not not props.collapsible local collapsed = not not props.collapsed local onCollapseToggled = props.onCollapseToggled local enabled = props.enabled ~= false local rowHeight = props.rowHeight or 1 local modal = getModal(self) return withTheme(function(theme) local fieldTheme = theme.labeledField local fieldHeight = Constants.INPUT_FIELD_HEIGHT*rowHeight local perLevelIndent = Constants.INPUT_FIELD_INDENT_PER_LEVEL local labelPadding = Constants.INPUT_FIELD_LABEL_PADDING local fontSize = Constants.FONT_SIZE_MEDIUM local font = Constants.FONT local labelColor = enabled and fieldTheme.textColor.Enabled or fieldTheme.textColor.Disabled local arrowColor = fieldTheme.arrowColor local totalIndent = perLevelIndent*(indentLevel) local width = labelWidth-totalIndent local arrowRight = Constants.COLLAPSIBLE_ARROW_RIGHT_IMAGE local arrowDown = Constants.COLLAPSIBLE_ARROW_DOWN_IMAGE local arrowSize = Constants.COLLAPSIBLE_ARROW_SIZE local arrowPosition = Constants.COLLAPSIBLE_ARROW_POSITION local finalLabelWidth = width-labelPadding local textFits = Utility.GetTextSize(label, fontSize, font, Vector2.new(9999, 9999)).X <= finalLabelWidth return Roact.createElement( PreciseFrame, { Size = UDim2.new(1, 0, 0, fieldHeight), BackgroundTransparency = 1, LayoutOrder = LayoutOrder, ZIndex = ZIndex, Visible = Visible }, { -- ArrowLines = indentLevel > 0 and Roact.createElement( -- "TextLabel", -- { -- Size = UDim2.new(0, 20, 1, 0), -- BackgroundTransparency = 1, -- TextColor3 = arrowColor, -- TextSize = 15, -- Font = Enum.Font.SourceSans, -- Text = "└─", -- AnchorPoint = Vector2.new(1, 0), -- Position = UDim2.new(0, totalIndent-3, 0, -1), -- TextXAlignment = Enum.TextXAlignment.Right, -- ZIndex = 2 -- } -- ), -- ArrowHead = indentLevel > 0 and Roact.createElement( -- "TextLabel", -- { -- Size = UDim2.new(0, 20, 1, 0), -- BackgroundTransparency = 1, -- TextColor3 = arrowColor, -- TextSize = 15, -- Font = Enum.Font.SourceSans, -- Text = ">", -- AnchorPoint = Vector2.new(1, 0), -- Position = UDim2.new(0, totalIndent-3, 0, -1), -- TextXAlignment = Enum.TextXAlignment.Right, -- ZIndex = 2 -- } -- ), Label = Roact.createElement( "TextLabel", { Size = UDim2.new(0, finalLabelWidth, 0, Constants.INPUT_FIELD_HEIGHT), BackgroundTransparency = 1, TextColor3 = labelColor, TextSize = fontSize, TextTruncate = textFits and Enum.TextTruncate.None or Enum.TextTruncate.AtEnd, Font = font, Text = label, TextXAlignment = Enum.TextXAlignment.Left, Position = UDim2.new(0, totalIndent+labelPadding, 0, 0), ZIndex = 2 } ), FieldContainer = Roact.createElement( "Frame", { BackgroundTransparency = 1, Size = UDim2.new(1, -labelWidth, 0, fieldHeight), Position = UDim2.new(0, labelWidth, 0, 0), ZIndex = 2 }, props[Roact.Children] ), CollapseArrowButton = collapsible and Roact.createElement( PreciseButton, { Size = UDim2.new(0, totalIndent, 0, fieldHeight), BackgroundTransparency = 1, [Roact.Event.MouseButton1Down] = collapsible and onCollapseToggled and function() onCollapseToggled() end }, { Arrow = Roact.createElement( "ImageLabel", { Size = UDim2.new(0, arrowSize, 0, arrowSize), Position = arrowPosition, Image = collapsed and arrowRight or arrowDown, BackgroundTransparency = 1 } ) } ) } ) end) end return LabeledFieldTemplate
package.path = 'C:/Develop/projects/tetris/lua/src/?.lua;' .. package.path --package.path = './src/?.lua;' .. package.path local Dimension = require 'util'.dimension local TetrisGame = require 'tetrisgame' local function Color(r, g, b) return {r = r / 255.0, g = g / 255.0, b = b / 255.0} end local config = { grid_size = Dimension(11, 16), square_size = 30, falling_speed = 0.7, controls = { w = 'ROTATE', a = 'MOVE_LEFT', s = 'MOVE_DOWN', d = 'MOVE_RIGHT', space = 'DROP' }, background_color = Color(23, 23, 23), tetromino_colors = { Color(0, 200, 100), Color(70, 130, 0), Color(160, 220, 0), Color(250, 230, 60), Color(250, 180, 50), Color(230, 100, 0), Color(200, 0, 0) } } local game = TetrisGame(config.grid_size) local falling_timer = config.falling_speed local game_width = config.square_size * config.grid_size.width local game_height = config.square_size * config.grid_size.height local function draw_square(color, x, y, width, height) width = width or config.square_size height = height or width local top = top or y * height local left = left or x * width local s = config.square_size love.graphics.setColor(color.r, color.g, color.b) love.graphics.rectangle('fill', left, top, width, height) end function love.load() game.start() end function love.keypressed(key) local command = config.controls[key] if command ~= nil then game.handle_command(command) if command == 'MOVE_DOWN' or command == 'DROP' then falling_timer = config.falling_speed end end end function love.update(dt) if game.is_running then falling_timer = falling_timer - dt if falling_timer <= 0 then game.handle_command('FALL') falling_timer = config.falling_speed end end end function love.draw() draw_square(config.background_color, 0, 0, game_width, game_height) if game.is_running then local board = game.board for x = 0, board.size.width - 1 do for y = 0, board.size.height - 1 do local cell = board.grid[x][y] if not (type(cell) == 'boolean' and not cell) then local color = config.tetromino_colors[cell] draw_square(color, x, y) end end end local tetromino = game.falling_tetromino for _, part_offset in pairs(tetromino.parts) do local p = tetromino.position + part_offset local color = config.tetromino_colors[tetromino.shape_type] draw_square(color, p.x, p.y) end else local font = love.graphics.newFont(24) local message = 'Game over!' local msg_width = font:getWidth(message) local msg_height = font:getHeight(message) love.graphics.setFont(font) love.graphics.setColor(1, 1, 1) love.graphics.print(message, (game_width - msg_width) / 2, (game_height - msg_height) / 2) end end
local boot = require 'radish.mswindows.boot' boot.main_loop()
local M = function() end return M
co = coroutine.create( function() print("co", coroutine.yield()) end ) coroutine.resume(co) print("-------------") coroutine.resume(co, 4, 5) --> co 4 5
local AddonName, AddonTable = ... AddonTable.cooking = { -- Materials 52340, 62779, 62791, }
local solidown=Class{} solidown:include(gt_widget) function solidown:init(editor, x, y, id) gt_widget.init(self, editor, x, y, id, "make a layer more transparent") self.weight=5 self:add_button(editor, "solidown.png") end function solidown:mouse_pressed(editor) editor.sys.map.layers[editor.selected.layer].opacity=editor.sys.map.layers[editor.selected.layer].opacity-10 self.button.active=true if(editor.sys.map.layers[editor.selected.layer].opacity<1) then editor.sys.map.layers[editor.selected.layer].opacity=0 end return editor end function solidown:draw(editor) gt_widget.draw(self, editor) self.button.active=false end return solidown
local function indexed(arr) local result = {} for i = 1, #arr do result[i] = {i, arr[i]} end return result end return indexed
---@type string local string = string string.whitespace = ' \t\n\r\v\f' string.ascii_lowercase = 'abcdefghijklmnopqrstuvwxyz' string.ascii_uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' string.ascii_letters = string.ascii_lowercase .. string.ascii_uppercase string.digits = '0123456789' string.hexdigits = string.digits .. 'abcdef' .. 'ABCDEF' string.octdigits = '01234567' string.punctuation = [[!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~]] string.printable = string.digits .. string.ascii_letters .. string.punctuation .. string.whitespace function string.is_whitespace(s) return string.whitespace:find(s) ~= nil end function string.is_ascii_lowercase(s) return string.ascii_lowercase:find(s) ~= nil end function string.is_ascii_uppercase(s) return string.ascii_uppercase:find(s) ~= nil end function string.is_ascii_letter(s) return string.ascii_letters:find(s) ~= nil end function string.is_digit(s) return string.digits:find(s) ~= nil end function string.is_hexdigit(s) return string.hexdigits:find(s) ~= nil end function string.is_octdigit(s) return string.octdigits:find(s) ~= nil end function string.is_punctuation(s) return string.punctuation:find(s) ~= nil end function string.is_printable(s) return string.printable:find(s) ~= nil end local insert = table.insert local concat = table.concat ---@param s string ---@param sep string --function string.split(s, sep) -- local ret = {} -- if not sep or sep == '' then -- local len = #s -- for i = 1, len do -- insert(ret, s:sub(i, i)) -- end -- else -- while true do -- local p = string.find(s, sep) -- if not p then -- insert(ret, s) -- break -- end -- local ss = s:sub(1, p - 1) -- insert(ret, ss) -- s = s:sub(p + 1, #s) -- end -- end -- return ret --end ---@param s string function string.remove(s, pattern) return concat(string.split(s, pattern)) end ---@param s string function string.capitalize(s) if s == '' then return '' end return string.upper(s:sub(1, 1)) .. s:sub(2) end function string.capwords(s, sep) sep = sep or ' ' local w = string.split(s, sep) local c = {} for _, v in ipairs(w) do insert(c, string.capitalize(v)) end return concat(c, sep) end -------------------------------------------------- -- filename and path -------------------------------------------------- --- filename from path ---@param s string ---@param with_ext boolean ---@return string function string.filename(s, with_ext) s = s:gsub('\\', '/'):gsub('/+', '/') if with_ext then return s:match(".*/([^/]*)$") or s else return s:match(".*/([^/]*)%.%w+$") or s:match(".*/([^/]*)$") or s:match("(.*)%.%w+") or s end end --- file extention from path ---@param s string ---@return string function string.fileext(s) s = s:gsub('\\', '/'):gsub('/+', '/') return s:match(".*%.(%w+)$") or '' end --- file folder from path ---@param s string ---@return string function string.filefolder(s) s = s:gsub('\\', '/'):gsub('/+', '/') return s:match("(.+)/[^/]*%w+$") or '' end --- ---@param s string ---@return string function string.path_uniform(s) return s:gsub('\\', '/'):gsub('/+', '/') end -------------------------------------------------- --- ---@param s string ---@param str string function string.starts_with(s, str) return s:sub(1, #str) == str end --- ---@param s string ---@param str string function string.ends_with(s, str) return s:sub(-#str, -1) == str end
-- 自定义函数指针 local type = type local s_find = string.find local c_json = require("cjson.safe") local r_cache = require("app.store.redis") local u_each = require("app.utils.each") local s_cache = require("app.store.cache.base_cache") ----------------------------------------------------------------------------------------------------------------- local _obj = s_cache:extend() ------------------------------------------ 通用配置信息,使它分离出多个区域 ----------------------------------- --[[ ---> RDS 选区 --]] function _obj:new(conf) self._VERSION = '0.02' self._name = "cache-redis-store" self.config = conf _obj.super.new(self, conf, self._name) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------- REDIS 缓存设置 -------------------------------------------------- --[[ ---> RDS 连接器 --]] function _obj:_get_connect( timeout ) local config = self.config if timeout then config.timeout = timeout end return r_cache:new(config) end -- 设置 REDIS 缓存值 function _obj:set_by_json(json, timeout) local json_obj = c_json.decode(json) -- 获取缓存连接器 local redis = self:_get_connect() local effect_len = 0 redis:init_pipeline() u_each.json_action(json_obj, function(key,value) -- 设置缓存 redis:set(key, value) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) if not err then effect_len = effect_len + 1 end end) local ok,err = redis:commit_pipeline() return ok,err,effect_len end -- 设置 REDIS 缓存值 function _obj:set(key, value, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:set(key, value) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err end -- 设置 REDIS 缓存值 function _obj:hmset_by_array_text(key, array_text, timeout) local value = c_json.decode(array_text) return self:hmset(key, value, timeout) end -- 设置 REDIS 缓存值 function _obj:hmset(key, value, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:hmset(key, unpack(value)) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err,#(value) / 2 end -- 设置 REDIS 缓存值 依据 function function _obj:set_by_func(key, func, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:set(key, func()) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err end -- 获取 REDIS 缓存值 function _obj:get(key) -- 获取缓存连接器 local redis = self:_get_connect() local status,value,effect_len = "OK",nil,0 local value,err = redis:get(key) if not value then status = "FAILURE" else effect_len = 1 end return value,err,effect_len,status end -- 获取 REDIS 缓存值 function _obj:hmget(key, element_key) -- 获取缓存连接器 local redis = self:_get_connect() local status,value,effect_len = "OK",nil,0 local value,err = redis:hmget(key, element_key) if not value then status = "FAILURE" else effect_len = 1 end return value,err,effect_len,status end -- 获取 REDIS 缓存值 function _obj:hmget_array_text(key, element_key) local value,err,effect_len,status = _obj:hmget(key, element_key) return c_json.encode(value),err,effect_len,status end function _obj:delete(key) -- 获取缓存连接器 local redis = self:_get_connect() return redis:del(key) end function _obj:delete_all() -- 获取缓存连接器 local redis = self:_get_connect() redis:flush_all() redis:flush_expired() end ----------------------------------------------------------------------------------------------------------------- -- 推送 REDIS 缓存值 function _obj:lpush(key, value, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:lpush(key, value) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err end -- 推送 REDIS 缓存值 function _obj:llen(key) -- 获取缓存连接器 local redis = self:_get_connect() return redis:llen(key) end -- 推送 REDIS 缓存值 function _obj:rpush(key, value, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:rpush(key, value) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err end -- 推送 REDIS 缓存值 function _obj:lpop(key, value, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:lpop(key, value) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err end -- 推送 REDIS 缓存值 function _obj:rpop(key, value, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:rpop(key, value) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, timeout) end) return ok,err end -- 设置 REDIS 缓存值 function _obj:incr(key, step, timeout) -- 获取缓存连接器 local redis = self:_get_connect() local ok,err = redis:incr(key) timeout = _obj.filter_timeout(timeout, function () -- 设置当前KEY的过期时间,-s 秒为 redis:expire(key, step, timeout) end) return ok,err end -- 同一连接,执行命令 function _obj:pipeline_command(action) -- 获取缓存连接器 local redis = self:_get_connect() redis:init_pipeline() action(redis) return redis:commit_pipeline() end function _obj:keys(pattern) -- 获取缓存连接器 local redis = self:_get_connect() return redis:keys(pattern) end ----------------------------------------------------------------------------------------------------------------- return _obj
local PLETHORA_SCANNER = "plethora:scanner" local AIR_BLOCK = "minecraft:air" function new() return { priority = 10, isAvailable = function() return peripheral.find(PLETHORA_SCANNER) end, execute = function(currentPosition, updateSessionMap, updateServerMap) local scanner = peripheral.find(PLETHORA_SCANNER) if not scanner then return end -- throw error? -- get block data from scan and add to temporary map local rawBlockInfo = scanner.scan() local sortedBlockInfo = aStar.newMap() for _, blockInfo in ipairs(rawBlockInfo) do sortedBlockInfo:set(currentPosition + vector.new(blockInfo.x, blockInfo.y, blockInfo.z), blockInfo) end -- add adjacent blocks to initial toCheck queue local toCheckQueue = {} for _, pos in ipairs(aStar.adjacent(currentPosition)) do local blockInfo = sortedBlockInfo:get(pos) if blockInfo then table.insert(toCheckQueue, pos) blockInfo.queued = true end end -- flag position of turtle as checked to prevent updating map incorrectly updateSessionMap(currentPosition, false) updateServerMap(currentPosition, false) sortedBlockInfo:get(currentPosition).queued = true -- process all blocks from the scan while toCheckQueue[1] do local pos = table.remove(toCheckQueue, 1) local blockInfo = sortedBlockInfo:get(pos) if blockInfo.name == AIR_BLOCK then for _, pos2 in ipairs(aStar.adjacent(pos)) do local blockInfo2 = sortedBlockInfo:get(pos2) if blockInfo2 and not blockInfo2.queued then -- only add air blocks to the toCheck queue to prevent overscanning the area and bloating the map data size table.insert(toCheckQueue, pos2) blockInfo2.queued = true end end updateSessionMap(pos, false) updateServerMap(pos, false) else updateSessionMap(pos, true) updateServerMap(pos, true) end end -- go through list again and add all block data to session map for _, blockInfo in ipairs(rawBlockInfo) do local pos = currentPosition + vector.new(blockInfo.x, blockInfo.y, blockInfo.z) if not blockInfo.queued then updateSessionMap(pos, blockInfo.name ~= AIR_BLOCK) end end end, } end
components = require "components" grid = require "grid" function love.load() love.window.setTitle("salms: Software Architecture Live Diagrams") love.window.setMode(1280, 750, {resizable=true,centered=true,minwidth=800,minheight=600}) love.window.maximize() wh = love.graphics.getHeight() ww = love.graphics.getWidth() x_offset = 0 y_offset = 0 draw_timer = 0 beat_timer = 0 beat_interval = 0.1 beat_counter = 0 step_size = 15 -- Fine tuning: -- TODO: load these from somewhere else grid_w = 170 grid_h = 90 beat_debounce = false grid_space_w = math.floor(grid_w / 3) grid_space_h = math.floor(grid_h / 2) cell_w = grid_w + grid_space_w cell_h = grid_h + grid_space_h love.graphics.setLineWidth(2) should_draw_grid = false highlighted_rectangle = nil love.graphics.setNewFont(12) love.graphics.setColor(0,0,0) love.graphics.setBackgroundColor(255,255,255) -- Load desired schema: schema_path = arg[2] if schema_path == nil then schema_path = "schema.lua" end schema = dofile(schema_path) -- Initialize the schema: schema.init() end function love.draw() if should_draw_grid then draw_grid() end draw_legend() love.graphics.setColor(0, 0, 0) love.graphics.print(beat_counter, 5, 5) if highlighted_rectangle then rx, ry = coords_from_grid(unpack(highlighted_rectangle)) love.graphics.setColor(0.5, 0.5, 0.5) love.graphics.rectangle("fill", rx, ry, grid_w, grid_h) end for idx, c in ipairs(components_list) do rx, ry = coords_from_grid(unpack(c["coordinates"])) -- Draw only VISIBLE components if not (rx < -grid_w or ry < -grid_h or rx > ww or ry > wh) then love.graphics.setColor(0.2, 0.2, 0.2) love.graphics.rectangle("line", rx, ry, grid_w, grid_h) c:draw(rx, ry) -- Connect to neighbours: for direction_name, connector_data in pairs(c.connectors) do if connector_data then connector, redness = unpack(connector_data) cx1, cy1, cx2, cy2 = unpack(connector) love.graphics.setColor(redness, 0.5, 0.5) love.graphics.line( cx1 + rx, cy1 + ry, cx2 + rx, cy2 + ry ) end end end end end function draw_legend() x = 5 size = 12 space = 4 y = wh - size - 5 for name, color in pairs(status_colors) do love.graphics.setColor(0, 0, 0) love.graphics.print(name, x + size + space, y) love.graphics.setColor(unpack(color)) love.graphics.rectangle("fill", x, y, size, size) y = y - size - space end end function love.update(dt) draw_timer = draw_timer + dt if draw_timer < 0.1 then -- diff = draw_timer - 0.1 love.timer.sleep(0.05) return end draw_timer = 0 wh = love.graphics.getHeight() ww = love.graphics.getWidth() if love.keyboard.isDown("q") then love.window.close() os.exit() elseif love.keyboard.isDown("space") then if not beat_debounce then beat() beat_debounce = true end end if beat_debounce then beat_timer = beat_timer + dt if beat_timer > beat_interval then beat_timer = 0 beat_debounce = false end end if love.keyboard.isDown("left") then x_offset = x_offset + step_size elseif love.keyboard.isDown("right") then x_offset = x_offset - step_size end if love.keyboard.isDown("up") then y_offset = y_offset + step_size elseif love.keyboard.isDown("down") then y_offset = y_offset - step_size end if love.keyboard.isDown("x") then c = components_list[1] if c then c:do_call_action() end end end function love.mousepressed(x, y, button, istouch) if button == 1 then highlight_cell(x, y) elseif button == 2 then components.run_action(x, y) end end ------------------------------------------------ function beat() beat_counter = (beat_counter + 1) % 1000 for idx, c in ipairs(components_list) do c:beat() end end
--[[ Name: unipolar_full_step.lua Desc: This example script was written as part of LabJack's "Stepper Motor Controller" App-Note. Note: There is an accompanying python script as well as a (Windows Only) LabVIEW example application that should be run in conjunction with this script: https://labjack.com/support/app-notes/digital-IO/stepper-motor-controller --]] print("Use the following registers:") print("46080: Target Position (steps)") print("46082: Current Position (steps)") print("46180: enable, 1:enable, 0: disable") print("46181: estop, 1: estop, 0: run") print("46182: hold, 1: hold position of motor, 0: release motor (after movement)") print("46183: sethome, (sethome)") -- Enable/disable control local enable = false -- Target location local targ = 0 -- Position relative to the target local pos = 0 -- Value read before setting I/O line states to immediately disengage motor local estop = 0 -- Enable hold mode by default at end of a movement sequence local hold = 1 -- Set new "zero" or "home" local sethome = 0 local channela = "EIO0" local channelb = "EIO1" local channelc = "EIO4" local channeld = "EIO5" MB.writeName(channela, 0) MB.writeName(channelb, 0) MB.writeName(channelc, 0) MB.writeName(channeld, 0) -- Define the Full Step Sequence local a = {1,0,0,0} -- This is the control logic for line A local b = {0,0,1,0} -- This is the control logic for line A' local c = {0,1,0,0} -- This is the control logic for line B local d = {0,0,0,1} -- This is the control logic for line B' local numSteps =table.getn(a) local i = 0 local m0, m1, m2, m3 = 0 -- Set initial USER_RAM values. MB.writeName("USER_RAM1_I32", targ) MB.writeName("USER_RAM0_I32", pos) MB.writeName("USER_RAM0_U16", enable) MB.writeName("USER_RAM1_U16", estop) MB.writeName("USER_RAM2_U16", hold) MB.writeName("USER_RAM3_U16", sethome) -- Configure an interval for stepper motor control LJ.IntervalConfig(0, 4) -- Configure an interval for printing the current state LJ.IntervalConfig(1, 1000) while true do -- If a print interval is done if LJ.CheckInterval(1) then print("Current State", enable, target, pos, estop) end -- If a stepper interval is done if LJ.CheckInterval(0) then -- Read USER_RAM to determine if we should start moving enable = (MB.readName("USER_RAM0_U16") == 1) -- Read USER_RAM to get the desired target targ = MB.readName("USER_RAM1_I32") -- If the motor is allowed to move if enable then -- If we have reached the new position if pos == targ then -- Set enable to 0 to signal that the movement is finished enable = false MB.writeName("USER_RAM0_U16", 0) print("reached new pos") -- Determine if the motor should be "held in place" hold = MB.readName("USER_RAM1_U16") if hold == 0 then -- Set all low to allow free movement m0 = 0 m1 = 0 m2 = 0 m3 = 0 end -- Else if the motor should be held keep the same position activated -- If behind the target, go forward elseif pos < targ then pos = pos+1 -- Lua is 1-indexed, so add a 1 i = pos%numSteps+1 -- Write the new positions m0 = a[i] m1 = b[i] m2 = c[i] m3 = d[i] -- If ahead of the target, move back elseif pos > targ then pos = pos-1 i = pos%numSteps+1 m0 = a[i] m1 = b[i] m2 = c[i] m3 = d[i] end -- If the motor is not enabled to move else -- Check again if the motor is enabled to move hold = MB.readName("USER_RAM2_U16") sethome = MB.readName("USER_RAM3_U16") -- If the home register is set to make a new home if sethome == 1 then print("New home created") MB.writeName("USER_RAM3_U16", 0) -- Make a new home pos = 0; end if hold == 0 then m0 = 0 m1 = 0 m2 = 0 m3 = 0 end end -- Save the current position to USER_RAM MB.writeName("USER_RAM0_I32", pos) estop = MB.readName("USER_RAM1_U16") if estop == 1 then m0 = 0; m1 = 0; m2 = 0; m3 = 0 end MB.writeName(channela, m0) MB.writeName(channelb, m1) MB.writeName(channelc, m2) MB.writeName(channeld, m3) end end
--- The Dungeon-style map Prototype. -- This class is extended by ROT.Map.Digger and ROT.Map.Uniform -- @module ROT.Map.Dungeon local ROT = require((...):gsub(('.[^./\\]*'):rep(2) .. '$', '')) local Dungeon = ROT.Map:extend("Dungeon") --- Constructor. -- Called with ROT.Map.Cellular:new() -- @tparam int width Width in cells of the map -- @tparam int height Height in cells of the map function Dungeon:init(width, height) Dungeon.super.init(self, width, height) self._rooms = {} self._corridors = {} end --- Get rooms -- Get a table of rooms on the map -- @treturn table A table containing objects of the type ROT.Map.Room function Dungeon:getRooms() return self._rooms end --- Get doors -- Get a table of doors on the map -- @treturn table A table {{x=int, y=int},...} for doors. -- FIXME: This could be problematic; it accesses an internal member of another -- class (room._doors). Will break if underlying implementation changes. -- Should probably take a callback instead like Room:getDoors(). function Dungeon:getDoors() local result = {} for _, room in ipairs(self._rooms) do for _, x, y in room._doors:each() do result[#result + 1] = { x = x, y = y } end end return result end --- Get corridors -- Get a table of corridors on the map -- @treturn table A table containing objects of the type ROT.Map.Corridor function Dungeon:getCorridors() return self._corridors end function Dungeon:_getDetail(name, x, y) local t = self[name] for i = 1, #t do if t[i].x == x and t[i].y == y then return t[i], i end end end function Dungeon:_setDetail(name, x, y, value) local detail, i = self:_getDetail(name, x, y) if detail then if value then detail.value = value else table.remove(self[name], i) end elseif value then local t = self[name] detail = { x = x, y = y, value = value } t[#t + 1] = detail end return detail end function Dungeon:getWall(x, y) return self:_getDetail('_walls', x, y) end function Dungeon:setWall(x, y, value) return self:_setDetail('_walls', x, y, value) end return Dungeon
-- Plugin configuration mapper. -- -- Each plugin entry consists of the following keys: -- -- - "rename": rename the plugin so that it’s exposed a the given name. -- - "branch": specify the branch to checkout this plugin at. -- - "enable": state whether or not we should be using this plugin. -- - "depends": list of other plugins this plugin depends on. -- - "after": runs some Vim commands after installation. -- - "global_setup": global configuration. -- - "config": configuration of the plugin — the plugin most expose a public -- Lua "setup" function accepting the configuration object. -- -- In the case where the plugin doesn’t support the "setup" + "config" situation, some local overrides might be provided -- to still allow configuring those plugins via this mechanism. local M = {} local plugin_exists = require'poesie.plugin'.plugin_exists local function setup_override_nvim_tree(c) local bindings = {} local tree_cb = require'nvim-tree.config'.nvim_tree_callback if c.keybindings ~= nil then for key, value in pairs(c.keybindings) do bindings[key] = tree_cb(value) end vim.g.nvim_tree_bindings = bindings end end local function setup_override_lsp_extensions(c) if c.rust_analyzer_inlay_hints ~= nil then local rust_conf = c.rust_analyzer_inlay_hints local au_groups = rust_conf.au_groups or { 'BufEnter', 'BufWinEnter', 'BufWritePost', 'InsertLeave', 'TabEnter' } local au_string = 'au ' for i, au_group in ipairs(au_groups) do if i == 1 then au_string = au_string .. au_group else au_string = au_string .. ',' .. au_group end end au_string = au_string .. " *.rs :lua require'lsp_extensions'.inlay_hints { " au_string = au_string .. 'highlight = ' .. (rust_conf.highlight or 'Comment') .. ',' au_string = au_string .. 'prefix = ' .. (rust_conf.prefix or ' » ') .. ',' au_string = au_string .. 'aligned = ' .. (rust_conf.aligned or 'false') .. ',' au_string = au_string .. 'only_current_line = ' .. (rust_conf.only_current_line or 'false') .. ',' au_string = au_string .. 'enabled = { ' for _, enabled in pairs(rust_conf.enabled or { 'ChainingHint' }) do au_string = au_string .. enabled end au_string = au_string .. ' }' vim.cmd(au_string) end end local function setup_override_telescope(c) local sorters = { get_fuzzy_file = require'telescope.sorters'.get_fuzzy_file, get_generic_fuzzy_sorter = require'telescope.sorters'.get_generic_fuzzy_sorter, get_levenshtein_sorter = require'telescope.sorters'.get_levenshtein_sorter, get_fzy_sorter = require'telescope.sorters'.get_fzy_sorter, fuzzy_with_index_bias = require'telescope.sorters'.fuzzy_with_index_bias, } local previewers = { vim_buffer_cat = require'telescope.previewers'.vim_buffer_cat.new, vim_buffer_vimgrep = require'telescope.previewers'.vim_buffer_vimgrep.new, vim_buffer_qflist = require'telescope.previewers'.vim_buffer_qflist.new, cat = require'telescope.previewers'.cat.new, vimgrep = require'telescope.previewers'.vimgrep.new, qflist = require'telescope.previewers'.qflist.new, } local config = {} if c.defaults.file_sorter ~= nil then config.file_sorter = sorters[c.defaults.file_sorter] end if c.defaults.generic_sorter ~= nil then config.generic_sorter = sorters[c.defaults.generic_sorter] end if c.defaults.file_previewer ~= nil then config.file_previewer = previewers[c.defaults.file_previewer] end if c.defaults.grep_previewer ~= nil then config.grep_previewer = previewers[c.defaults.grep_previewer] end if c.defaults.qflist_previewer ~= nil then config.qflist_previewer = previewers[c.defaults.qflist_previewer] end if c.defaults.mappings ~= nil then local overriden_mappings = {} for mode, mappings in pairs(c.defaults.mappings) do local maps = {} for key, action in pairs(mappings) do maps[key] = require'telescope.actions'[action] end overriden_mappings[mode] = maps end config.mappings = overriden_mappings end require'telescope'.setup({ defaults = config }) end -- FIXME: we need to allow passing configuration to telescope.setup; we should probably remove those overrides and move -- them in the override of telescope; it’s ugly but that extension system is by itself very annoying so meh meh meh -- FIXME: ensure the overrides are made _after_ the override of telescope… hard? local function setup_override_telescope_fzy_native() require'telescope'.load_extension('fzy_native') end local function setup_override_telescope_fzf_native() require'telescope'.load_extension('fzf') end local function setup_override_octo(c) require'telescope'.load_extension('octo') require'octo'.setup(c) end local setup_overrides = { ['kyazdani42/nvim-tree.lua'] = setup_override_nvim_tree, ['nvim-lua/lsp_extensions.nvim'] = setup_override_lsp_extensions, ['nvim-telescope/telescope.nvim'] = setup_override_telescope, ['nvim-telescope/telescope-fzy-native.nvim'] = setup_override_telescope_fzy_native, ['nvim-telescope/telescope-fzf-native.nvim'] = setup_override_telescope_fzf_native, ['pwntester/octo.nvim'] = setup_override_octo, } local function packer_interpret(plugins) if not plugin_exists('packer') then return end error('packer doesn’t work as expected and hence support is not complete; sorry, have a hug') vim.cmd [[packadd packer.nvim]] require('packer').startup(function(use) -- the first plugin needed is obviously packer, so that we can bootstrap it once and have it automatically updated -- etc.; however, if it’s already present in the user configuration, we authorize specific configuration to be -- passed, because we are cool if plugins["wbthomason/packer.nvim"] == nil then plugins["wbthomason/packer.nvim"] = {{}} end for plug_name, plug_conf in pairs(plugins) do local original_plug_name = plug_name local conf = { plug_name } if plug_conf.rename ~= nil and type(plug_conf.rename) == 'string' then conf.as = plug_conf.rename -- used later for configuration purposes plug_name = plug_conf.rename else plug_name = plug_name:match(".*/(.*)") end if plug_conf.branch ~= nil and type(plug_conf.branch) == 'string' then conf.branch = plug_conf.branch end if plug_conf.enable ~= nil and type(plug_conf.enable) == 'boolean' then conf.disable = not plug_conf.enable end if plug_conf.depends ~= nil and type(plug_conf.depends) == 'table' then local requires = {} for _, dependency in pairs(plug_conf.depends) do requires[#requires + 1] = { dependency } end conf.requires = requires end if plug_conf.after ~= nil and type(plug_conf.after) == 'string' then conf.run = plug_conf.after end if plug_conf.global_setup ~= nil and type(plug_conf.global_setup) == 'table' then for key, value in pairs(plug_conf.global_setup) do vim.g[key] = value end end if plug_conf.config ~= nil and type(plug_conf.config) == 'table' then conf.config = function() local plugin = require(plug_name) -- look for setup overrides first -- -- otherwise, if the plugin exposes a setup function, configure it by passing the local configuration -- otherwise, check if we have local override for it if setup_overrides[original_plug_name] ~= nil then setup_overrides[original_plug_name](plug_conf.config) elseif plugin.setup ~= nil then plugin.setup(plug_conf.config) end end end use(conf) end end) end local function paq_interpret(plugins) vim.cmd [[packadd paq-nvim]] if not plugin_exists('paq-nvim') then error('paq not installed ffs') return end local paq = require'paq-nvim'.paq if plugins['savq/paq-nvm'] == nil then paq { 'savq/paq-nvim', opt = true } end for plug_name, plug_conf in pairs(plugins) do if plug_conf.enable == nil or plug_conf.enable then local original_plug_name = plug_name local conf = { plug_name } if plug_conf.rename ~= nil and type(plug_conf.rename) == 'string' then conf.as = plug_conf.rename -- used later for configuration purposes plug_name = plug_conf.rename else plug_name = plug_name:match(".*/(.*)") local plug_name_alt = plug_name:match('(.*)%.') if plug_name_alt ~= nil then plug_name = plug_name_alt end end if plug_conf.branch ~= nil and type(plug_conf.branch) == 'string' then conf.branch = plug_conf.branch end if plug_conf.after ~= nil and type(plug_conf.after) == 'string' then conf.run = plug_conf.after end if plug_conf.global_setup ~= nil and type(plug_conf.global_setup) == 'table' then for key, value in pairs(plug_conf.global_setup) do vim.g[key] = value end end paq(conf) if plug_conf.config ~= nil and type(plug_conf.config) == 'table' then -- look for setup overrides first -- -- otherwise, if the plugin exposes a setup function, configure it by passing the local configuration -- otherwise, check if we have local override for it if setup_overrides[original_plug_name] ~= nil then setup_overrides[original_plug_name](plug_conf.config) elseif plugin_exists(plug_name) then local plugin = require(plug_name) if plugin.setup ~= nil then plugin.setup(plug_conf.config) end end end end end end local packagers = { packer = packer_interpret, paq = paq_interpret, } local function is_valid_packager(name) return packagers[name] ~= nil end function M.interpret(c) -- Get the package manager to use. if c.packager == nil or not is_valid_packager(c.packager) then error('you must specify a valid package manager to use') return end local packager = c.packager local plugins = c.plugins or {} packagers[packager](plugins) end return M
--[[ Victory Screen - README 1.0.0 - 2020/10/15 by Waffle (Manticore) (META) (Programming) (https://www.coregames.com/user/581ff579fd864966aec56450754db1fb) + Nicholas Foreman (META) (Programming) (https://www.coregames.com/user/f9df3457225741c89209f6d484d0eba8) + WitcherSilver (META) (Art) (https://www.coregames.com/user/e730c40ae54d4c588658667927acc6d8) Victory Screen allows creators to end rounds on a special note, showing off the skins, emotes, and stats of the top players each round. Simple and easy to customize, creators have the ability to show any environment with any arrangement for the players. 1. Setup 1) Navigate to: Project Content > Imported Content > Victory Screen > Dependencies. 2) Drag-and-drop a VictoryScreen into the hierarchy. 3) Set its position somewhere hidden, such as under the map or far, far into the distance. 4) Alter custom properties as you wish! 2. Usage • If the AutomaticActivation custom property is set to true, the victory Screen will activate upon Game.roundEndEvent and will deactivate after the Duration custom property (in seconds). If AutomaticActivation is set to false, then it can be manually activated and deactivated using the ActivateEvent and DeactivateEvent custom properties: Events.Broadcast("VictoryScreen_Activate", winnerList) -- "VictoryScreen_Activate" would be what you put in the custom property Events.Broadcast("VictoryScreen_Deactivate") -- "VictoryScreen_Deactivate" would be what you put in the custom property • Winners can be chosen manually. This would require AutomaticActivation to be false and the event to be fired with the list of winners to be an argument of the event broadcast. • If winners are not chosen manually, then they will be chosen by the value given in WinnerSortType custom property (KILL_DEATH or RESOURCE). If it is KILL_DEATH, then it will first try to get the player with more kills, then the one with less deaths, then, if their kills/deaths are the same, their username alphabetically. If it is RESOURCE, it will use the highest value for the resource given in WinnerSortResource custom property, or if they are the same, their username alphabetically. 3. Additional Notes • The ClientContext inside the template contains the camera, fog(s), and user interface. • The name of each spawn in the Spawns group does not matter; it works from top-down in the hierarchy. • The lighting in the VictoryScreen area does not affect the global lighting; any additions you make should always try to use adjustment volumes whenever possible to maintain such. 4. Discord If you have any questions, feel free to join the Core Hub Discord server: discord.gg/core-creators We are a friendly group of creators and players interested in the games and community on Core. Open to everyone, regardless of your level of experience or interests. --]]
-- Copyright (C) Yichun Zhang (agentzh) -- Copyright (C) cuiweixie -- I hereby assign copyright in this code to the lua-resty-core project, -- to be licensed under the same terms as the rest of the code. local ffi = require 'ffi' local base = require "resty.core.base" local FFI_OK = base.FFI_OK local FFI_ERROR = base.FFI_ERROR local FFI_DECLINED = base.FFI_DECLINED local ffi_new = ffi.new local ffi_str = ffi.string local ffi_gc = ffi.gc local C = ffi.C local type = type local error = error local tonumber = tonumber local getfenv = getfenv local get_string_buf = base.get_string_buf local get_size_ptr = base.get_size_ptr local setmetatable = setmetatable local co_yield = coroutine._yield local ERR_BUF_SIZE = 128 local errmsg = base.get_errmsg_ptr() ffi.cdef[[ struct ngx_http_lua_semaphore_s; typedef struct ngx_http_lua_semaphore_s ngx_http_lua_semaphore_t; int ngx_http_lua_ffi_semaphore_new(ngx_http_lua_semaphore_t **psem, int n, char **errmsg); int ngx_http_lua_ffi_semaphore_post(ngx_http_lua_semaphore_t *sem, int n); int ngx_http_lua_ffi_semaphore_count(ngx_http_lua_semaphore_t *sem); int ngx_http_lua_ffi_semaphore_wait(ngx_http_request_t *r, ngx_http_lua_semaphore_t *sem, int wait_ms, unsigned char *errstr, size_t *errlen); void ngx_http_lua_ffi_semaphore_gc(ngx_http_lua_semaphore_t *sem); ]] local psem = ffi_new("ngx_http_lua_semaphore_t *[1]") local _M = { version = base.version } local mt = { __index = _M } function _M.new(n) n = tonumber(n) or 0 if n < 0 then return error("no negative number") end local ret = C.ngx_http_lua_ffi_semaphore_new(psem, n, errmsg) if ret == FFI_ERROR then return nil, ffi_str(errmsg[0]) end local sem = psem[0] ffi_gc(sem, C.ngx_http_lua_ffi_semaphore_gc) return setmetatable({ sem = sem }, mt) end function _M.wait(self, seconds) if type(self) ~= "table" or type(self.sem) ~= "cdata" then return error("not a semaphore instance") end local r = getfenv(0).__ngx_req if not r then return error("no request found") end local milliseconds = tonumber(seconds) * 1000 if milliseconds < 0 then return error("no negative number") end local cdata_sem = self.sem local err = get_string_buf(ERR_BUF_SIZE) local errlen = get_size_ptr() errlen[0] = ERR_BUF_SIZE local ret = C.ngx_http_lua_ffi_semaphore_wait(r, cdata_sem, milliseconds, err, errlen) if ret == FFI_ERROR then return nil, ffi_str(err, errlen[0]) end if ret == FFI_OK then return true end if ret == FFI_DECLINED then return nil, "timeout" end return co_yield() end function _M.post(self, n) if type(self) ~= "table" or type(self.sem) ~= "cdata" then return error("not a semaphore instance") end local cdata_sem = self.sem local num = n and tonumber(n) or 1 if num < 1 then return error("no negative number") end -- always return NGX_OK C.ngx_http_lua_ffi_semaphore_post(cdata_sem, num) return true end function _M.count(self) if type(self) ~= "table" or type(self.sem) ~= "cdata" then return error("not a semaphore instance") end return C.ngx_http_lua_ffi_semaphore_count(self.sem) end return _M
slot0 = require((string.match(..., ".*%.") or "") .. "dis_x86") return { create = slot0.create64, disass = slot0.disass64, regname = slot0.regname64 }
-- Button.lua require "gui/box" require "gui/text" Button = {} Button.__index = Button setmetatable(Button, { __call = function (cls, ...) local self = setmetatable({}, cls) self:_init(...) return self end, }) function Button:_init(text, x, y, font, scale, textColor, cam) self.x = x self.y = y self.color = color or {255, 255, 255, 255} self.scale = scale or 5 self.cam = cam self.text = Text(text, x, y, font, self.scale) self.box = Box(x,y,self.text.text:getWidth(), self.text.text:getHeight(), self.scale) end function Button:draw () offsetX, offsetY = 0,0 if self.cam then offsetX, offsetY = cam:getVisibleCorners() end self.box:draw() self.text:draw() end function Button:update (text) self.text:update(text) end function Button:touchpressed(id, x, y) if (x > self.box.x) and (x <= self.box.x + self.box.width) then if (y > self.box.y) and (y <= self.box.y + self.box.height) then return true end end end
-------------------------------------------------------------------------------- -- Let's Raid (c) 2019 by Siarkowy <http://siarkowy.net/letsraid> -- Released under the terms of BSD 3-Clause "New" license (see LICENSE file). -------------------------------------------------------------------------------- local abs = abs local date = date local format = string.format local modf = math.modf local time = time local GetQuestResetTime = GetQuestResetTime local wipe = LetsRaid.wipe local MINUTE = 60 local HOUR = 60 * MINUTE local DAY = 24 * HOUR local WEEK = 7 * DAY local function toHHMM(t) -- from http://lua-users.org/wiki/TimeZone if not t then return end local h, m = modf(t / 3600) return format("%+.4d", 100 * h + 60 * m) end LetsRaid.toHHMM = toHHMM local function toISO8601(utc_t, utc_dt) if not utc_t then return end utc_dt = utc_dt or 0 local date_str = date("!%Y-%m-%dT%X", utc_t + utc_dt) local offset = toHHMM(utc_dt) local stamp = format("%s%s", date_str, offset):gsub("+0000","Z") return stamp end LetsRaid.toISO8601 = toISO8601 --- Returns true if automatic time calibration is enabled. function LetsRaid:IsAutomaticTime() return self.db.realm.time.automatic end --- Toggles automatic time calibration on/off. function LetsRaid:SetAutomaticTime(enabled) self.db.realm.time.automatic = not not enabled end --- Returns a guessed local to UTC (client) time difference in seconds. -- Negative for time zones west of Greenwich, positive otherwise. function LetsRaid:GuessClientTimeOffset(loc_hh, loc_mm, utc_hh, utc_mm) local now_t = time() loc_hh = loc_hh or date("%H", now_t) loc_mm = loc_mm or date("%M", now_t) utc_hh = utc_hh or date("!%H", now_t) utc_mm = utc_mm or date("!%M", now_t) local loc_now_t = loc_hh * HOUR + loc_mm * MINUTE local utc_now_t = utc_hh * HOUR + utc_mm * MINUTE local offset_dt = loc_now_t - utc_now_t if offset_dt < -9 * HOUR then offset_dt = offset_dt + DAY elseif offset_dt > 13 * HOUR then offset_dt = offset_dt - DAY end if self.debug then self:Trace("GuessClientTimeOffset", offset_dt, "->", toHHMM(offset_dt)) end return offset_dt end function LetsRaid:GuessAndStoreClientTimeOffset(...) local offset_dt = self:GuessClientTimeOffset(...) self:SetClientTimeOffset(offset_dt) return offset_dt end --- Returns local to UTC (client) time difference in seconds. function LetsRaid:GetClientTimeOffset() return self.db.realm.time.client_dt or self:GuessAndStoreClientTimeOffset() end --- Saves local to UTC (client) time difference in seconds. function LetsRaid:SetClientTimeOffset(dt) self.db.realm.time.client_dt = tonumber(dt) end --- Returns time to server-side quest reset in seconds. function LetsRaid:GetServerQuestResetOffset() -- GetQuestResetTime() returns a value of `-time()` during first -- UPDATE_INSTANCE_INFO after restarting the game client local reset_dt = GetQuestResetTime() if reset_dt > 0 then if self.debug then self:Trace("GetServerQuestResetOffset", reset_dt, "->", toHHMM(reset_dt)) end return reset_dt end self:Trace("GetServerQuestResetOffset", nil) end --- Returns time to server-side raid reset in seconds if player has an active lockout. -- It is assumed that all raid instance types reset at the same time. function LetsRaid:GetServerRaidResetOffset() for i = 1, GetNumSavedInstances() do local name, _, reset_dt = GetSavedInstanceInfo(i) reset_dt = reset_dt % DAY if self:GetInstanceKeyForMap(name) then if self.debug then self:Trace("GetServerRaidResetOffset", reset_dt, "->", toHHMM(reset_dt)) end return reset_dt end end self:Trace("GetServerRaidResetOffset", nil) end --- Returns UTC timestamp of next server-side quest reset. function LetsRaid:GetServerNextQuestReset() local reset_dt = self:GetServerQuestResetOffset() if not reset_dt then self:Debug("GetServerNextQuestReset", nil) return end local reset_t = time() + reset_dt if self.debug then self:Debug("GetServerNextQuestReset", reset_t, "->", toISO8601(reset_t)) end return reset_t end --- Returns UTC timestamp of next server-side raid reset. -- Only correct right after UPDATE_INSTANCE_INFO event. function LetsRaid:GetServerNextRaidReset() local reset_dt = self:GetServerRaidResetOffset() if not reset_dt then self:Debug("GetServerNextRaidReset", nil) return end local reset_t = time() + reset_dt if self.debug then self:Debug("GetServerNextRaidReset", reset_t, "->", toISO8601(reset_t)) end return reset_t end --- Returns number of seconds past UTC midnight at which lockouts reset. -- Infers the value from available lockouts & quest reset timer. function LetsRaid:GuessServerResetOffset(use_quest) local raid_t = self:GetServerNextRaidReset() local quest_t = self:GetServerNextQuestReset() local raid_dt = raid_t and (raid_t % DAY) local quest_dt = quest_t and (quest_t % DAY) local cur_dt = self:GetServerResetOffset() local reset_dt = use_quest and quest_dt or raid_dt or cur_dt or quest_dt if self.debug then self:Trace("GuessServerResetOffset", raid_dt, quest_dt, cur_dt, reset_dt, "->", toHHMM(raid_dt), toHHMM(quest_dt), toHHMM(cur_dt), toHHMM(reset_dt)) end return reset_dt end function LetsRaid:GuessAndStoreServerResetOffset(...) local reset_dt = self:GuessServerResetOffset(...) if reset_dt then self:SetServerResetOffset(reset_dt) end return reset_dt end --- Returns number of seconds past UTC midnight at which lockouts reset. function LetsRaid:GetServerResetOffset() local reset_dt = self.db.realm.time.reset_dt if reset_dt then return reset_dt end end --- Saves number of seconds past UTC midnight at which lockouts reset. function LetsRaid:SetServerResetOffset(dt) self.db.realm.time.reset_dt = (tonumber(dt) or 0) % DAY end --- Returns UTC timestamp of next server-side lockout reset, either raid or quest. function LetsRaid:GetServerNextInstanceReset() local now_t = time() local midnight_t = now_t - now_t % DAY local reset_dt = self:GetServerResetOffset() if not reset_dt then self:Debug("GetServerNextInstanceReset", "unknown") return end local reset_t = midnight_t + reset_dt if reset_t < now_t then reset_t = reset_t + DAY end if self.debug then self:Debug("GetServerNextInstanceReset", reset_t, "->", toISO8601(reset_t)) end return reset_t end --- Adjusts time settings from available lockout timers. -- Raid lockout timers are always the preferred source of information. -- Daily quests reset timer is used only if there was no information collected yet, -- otherwise the existing time settings are kept intact. This can be overridden -- with `use_quest` flag to force a refresh when there's no raid lockout timers. function LetsRaid:CalibrateTime(use_quest) local client_dt = self:GuessAndStoreClientTimeOffset() self:GuessAndStoreServerResetOffset(use_quest) if self.debug then local reset_t = self:GetServerNextInstanceReset() self:Debug("CalibrateTime", use_quest, reset_t, client_dt, "->", toISO8601(reset_t, client_dt)) end end --- Throws an error if argument under test in not a readable date in YYYYMMDD format. function LetsRaid:AssertReadable(arg) if type(arg) ~= "number" then error(("Arg should be a number, got %q"):format(type(arg)), 2) end if arg <= 20000101 or arg >= 30000101 then error(("Arg should be a readable date, got %q"):format(arg), 2) end end --- Returns a readable date in YYYYMMDD format for specified timestamp. function LetsRaid:GetReadableDateFromTimestamp(stamp) if not stamp then return nil end return tonumber(date("!%Y%m%d", stamp)) end --- Returns a readable date/hour in YYYYMMDD.P format for specified timestamp. -- The P stands for fractional part of whole day, with minute resolution. function LetsRaid:GetReadableDateHourFromTimestamp(stamp) if not stamp then return nil end return tonumber(date("!%Y%m%d", stamp)) + (date("!%H", stamp) * HOUR + date("!%M", stamp) * MINUTE) / DAY end do local temp_date = {} local dt = LetsRaid:GuessClientTimeOffset() local t = date("*t") --- Returns a timestamp for specified YYYYMMDD readable date. function LetsRaid:GetTimestampFromReadableDate(readable) if not readable then return nil end temp_date.year = tonumber(string.sub(readable, 1, 4)) temp_date.month = tonumber(string.sub(readable, 5, 6)) temp_date.day = tonumber(string.sub(readable, 7, 8)) temp_date.hour = dt / HOUR temp_date.min = 0 temp_date.sec = 0 temp_date.isdst = t.isdst return time(temp_date) end end --- Returns server daily reset timestamp for specified YYYYMMDD readable date. function LetsRaid:GetResetTimestampFromReadableDate(readable, reset_dt) local reset_tstmp = self:GetTimestampFromReadableDate(readable) if not reset_tstmp then return nil end reset_dt = reset_dt or self:GetServerResetOffset() return reset_tstmp + reset_dt end --- Returns a short date in MMDD format for specified timestamp. function LetsRaid:GetShortDateFromTimestamp(stamp) if not stamp then return nil end return date("!%m%d", stamp) end --- Returns a short date in MMDD format for specified YYYYMMDD readable date. function LetsRaid:GetShortDateFromReadable(readable) if not readable then return nil end return string.sub(readable, 5, 8) end --- Recovers a timestamp from specified MMDD short date. -- Tries both current and neighbour year and returns the closer one. -- Neighbour year is either (1) previous year for `now` before Jun 01 -- or (2) next year otherwise. function LetsRaid:GetTimestampFromShort(short, now_readable) local now_readable = now_readable or self:GetReadableDateFromTimestamp(time()) self:AssertReadable(now_readable) local now_short = self:GetShortDateFromReadable(now_readable) local now_stamp = self:GetTimestampFromReadableDate(now_readable) local padded_short = format("%04d", short) local current_year = tostring(now_readable):sub(1, 4) local neighbour_year = current_year + (now_short >= "0601" and 1 or -1) local a = self:GetTimestampFromReadableDate(current_year .. padded_short) local b = self:GetTimestampFromReadableDate(neighbour_year .. padded_short) local da, db = abs(a - now_stamp), abs(b - now_stamp) return da < db and a or b end --- Returns a readable date in YYYYMMDD format for specified MMDD short date. -- Limitations of GetTimestampFromShort apply. function LetsRaid:GetReadableDateFromShort(short, now_readable) return self:GetReadableDateFromTimestamp(self:GetTimestampFromShort(short, now_readable)) end do local assertEqual = LetsRaid.assertEqual assertEqual(toHHMM(), nil) assertEqual(toHHMM(0), "+0000") assertEqual(toHHMM(3600), "+0100") assertEqual(toHHMM(7260), "+0201") assertEqual(toHHMM(-3600), "-0100") assertEqual(toHHMM(-7260), "-0201") assertEqual(toISO8601(), nil) assertEqual(toISO8601(0), "1970-01-01T00:00:00Z") assertEqual(toISO8601(0, 0), "1970-01-01T00:00:00Z") assertEqual(toISO8601(7200, 0), "1970-01-01T02:00:00Z") assertEqual(toISO8601(0, 3600), "1970-01-01T01:00:00+0100") assertEqual(toISO8601(7200, 3600), "1970-01-01T03:00:00+0100") assertEqual(toISO8601(0, 7200), "1970-01-01T02:00:00+0200") assertEqual(toISO8601(3600, 7200), "1970-01-01T03:00:00+0200") assertEqual(LetsRaid:GuessClientTimeOffset(00, 00, 00, 00), 0 * HOUR) -- UTC+0 / GMT assertEqual(LetsRaid:GuessClientTimeOffset(23, 00, 23, 00), 0 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(01, 00, 00, 00), 1 * HOUR) -- UTC+1 / CET assertEqual(LetsRaid:GuessClientTimeOffset(23, 00, 22, 00), 1 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(00, 00, 23, 00), 1 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(13, 00, 00, 00), 13 * HOUR) -- UTC+13 / NZDT assertEqual(LetsRaid:GuessClientTimeOffset(23, 00, 10, 00), 13 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(00, 00, 11, 00), 13 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(12, 00, 23, 00), 13 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(00, 00, 09, 00), -9 * HOUR) -- UTC-9 / AKST assertEqual(LetsRaid:GuessClientTimeOffset(14, 00, 23, 00), -9 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(15, 00, 00, 00), -9 * HOUR) assertEqual(LetsRaid:GuessClientTimeOffset(23, 00, 08, 00), -9 * HOUR) assertEqual(LetsRaid:GetReadableDateFromTimestamp(), nil) assertEqual(LetsRaid:GetReadableDateFromTimestamp(0), 19700101) assertEqual(LetsRaid:GetReadableDateFromTimestamp(DAY), 19700102) assertEqual(LetsRaid:GetReadableDateFromTimestamp(DAY-1), 19700101) assertEqual(LetsRaid:GetReadableDateHourFromTimestamp(), nil) assertEqual(LetsRaid:GetReadableDateHourFromTimestamp(0), 19700101) assertEqual(LetsRaid:GetReadableDateHourFromTimestamp(12 * HOUR), 19700101.5) assertEqual(LetsRaid:GetReadableDateHourFromTimestamp(DAY), 19700102) assertEqual(LetsRaid:GetShortDateFromTimestamp(), nil) assertEqual(LetsRaid:GetShortDateFromTimestamp(0), "0101") assertEqual(LetsRaid:GetShortDateFromTimestamp(DAY), "0102") assertEqual(LetsRaid:GetShortDateFromTimestamp(DAY-1), "0101") assertEqual(LetsRaid:GetShortDateFromReadable(), nil) assertEqual(LetsRaid:GetShortDateFromReadable(19700101), "0101") assertEqual(LetsRaid:GetShortDateFromReadable(19700102), "0102") assertEqual(LetsRaid:GetTimestampFromReadableDate(), nil) assertEqual(LetsRaid:GetTimestampFromReadableDate(19700101), 0) assertEqual(LetsRaid:GetTimestampFromReadableDate("19700101"), 0) assertEqual(LetsRaid:GetTimestampFromReadableDate(19700102), DAY) assertEqual(LetsRaid:GetTimestampFromReadableDate("19700102"), DAY) assertEqual(LetsRaid:GetReadableDateFromShort("0722", 20190722), 20190722) assertEqual(LetsRaid:GetReadableDateFromShort("722", 20190722), 20190722) assertEqual(LetsRaid:GetReadableDateFromShort("0122", 20190715), 20190122) assertEqual(LetsRaid:GetReadableDateFromShort("0122", 20190722), 20190122) assertEqual(LetsRaid:GetReadableDateFromShort("0122", 20190729), 20200122) assertEqual(LetsRaid:GetReadableDateFromShort("0722", 20190115), 20180722) assertEqual(LetsRaid:GetReadableDateFromShort("0722", 20190122), 20190722) assertEqual(LetsRaid:GetReadableDateFromShort("0722", 20190129), 20190722) assertEqual(LetsRaid:GetResetTimestampFromReadableDate(19700101, 10 * HOUR), 0 * DAY + 10 * HOUR) assertEqual(LetsRaid:GetResetTimestampFromReadableDate(19700102, 10 * HOUR), 1 * DAY + 10 * HOUR) local now_t = time() local hour = (now_t % DAY - now_t % HOUR) / HOUR assertEqual(hour, 0 + date("!%H", now_t)) -- time() is modulo friendly end
local thisActor = ... local thisContainer = scaleform.Actor.container(thisActor) local thisPos = scaleform.Actor.local_position(thisActor) scaleform.Actor.set_mouse_enabled_for_children(thisActor, false) local SCALE_FACTOR = 1.25 local function highlightButton() -- Increase size of buttons local iconActor = scaleform.ContainerComponent.actor_by_name(thisContainer, "icon") local iDim = scaleform.Actor.dimensions(thisActor) local iPos = scaleform.Actor.local_position(thisActor) local iIconPos = scaleform.Actor.local_position(iconActor) local iIconDim = scaleform.Actor.dimensions(iconActor) scaleform.Actor.set_local_scale(thisActor, {x = SCALE_FACTOR, y = SCALE_FACTOR}) -- And center them to their original icon position local fDim = scaleform.Actor.dimensions(thisActor) local fPos = scaleform.Actor.local_position(thisActor) local fIconPos = scaleform.Actor.local_position(iconActor) local fIconDim = scaleform.Actor.dimensions(iconActor) fPos.x = iPos.x + (iDim.width - fDim.width) + ((fIconPos.x + fIconDim.width * 0.5 * SCALE_FACTOR) - (iIconPos.x + iIconDim.width * 0.5)) fPos.y = iPos.y + (iDim.height - fDim.height) * 0.5 scaleform.Actor.set_local_position(thisActor, fPos) end local function emitEvent( evt_name ) local evt = { eventId = scaleform.EventTypes.Custom, name = evt_name, data = { buttonActor = thisActor } } scaleform.Stage.dispatch_event(evt) end mouseDownEventListener = scaleform.EventListener.create(mouseDownEventListener, function(e) if not scaleform.Actor.property(thisActor, "Selected") then scaleform.AnimationComponent.play_label(thisContainer, "pressed") end end ) mouseClickEventListener = scaleform.EventListener.create(mouseClickEventListener, function(e) if e.currentTarget == thisActor and not scaleform.Actor.property(thisActor, "Selected") then -- Update this button status scaleform.AnimationComponent.goto_label(thisContainer, "selected") scaleform.Actor.set_property(thisActor, "Selected", true) -- Highlight buttons highlightButton() -- Call for an update of the other buttons in this button's group emitEvent("ButtonSelected") end end ) mouseOverEventListener = scaleform.EventListener.create(mouseOverEventListener, function(e) if not scaleform.Actor.property(thisActor, "Selected") then scaleform.AnimationComponent.play_label(thisContainer, "hovered") end end ) mouseOutEventListener = scaleform.EventListener.create(mouseOutEventListener, function(e) if not scaleform.Actor.property(thisActor, "Selected") then scaleform.AnimationComponent.play_label(thisContainer, "default") end end ) mouseReleaseOutsideEventListener = scaleform.EventListener.create(mouseReleaseOutsideEventListener, function(e) if not scaleform.Actor.property(thisActor, "Selected") then scaleform.AnimationComponent.play_label(thisContainer, "default") end end ) local custom_listener = scaleform.EventListener.create(custom_listener, function(e) -- Callback for button group handling if e.name == "HighlightButton" and e.data then if e.data.buttonActor then if e.data.buttonActor == thisActor then -- Update this button status scaleform.AnimationComponent.goto_label(thisContainer, "selected") scaleform.Actor.set_property(thisActor, "Selected", true) -- Highlight buttons highlightButton() end end end end ) scaleform.EventListener.connect(mouseDownEventListener, thisActor, scaleform.EventTypes.MouseDown) scaleform.EventListener.connect(mouseClickEventListener, thisActor, scaleform.EventTypes.MouseUp) scaleform.EventListener.connect(mouseOverEventListener, thisActor, scaleform.EventTypes.MouseOver) scaleform.EventListener.connect(mouseOutEventListener, thisActor, scaleform.EventTypes.MouseOut) scaleform.EventListener.connect(mouseReleaseOutsideEventListener, thisActor, scaleform.EventTypes.MouseUpOutside) scaleform.EventListener.connect(custom_listener, thisActor, scaleform.EventTypes.Custom) return thisActor
require("ts3init") require("ts3defs") require("ts3errors") local MODULE_NAME = "acjc" function tableReverse(t) local revT = {} for k, v in pairs(t) do revT[v] = k end return revT end function sortedPairsByKeys(t, comp) local sortedKeys = {} for k, _ in pairs(t) do table.insert(sortedKeys, k) end table.sort(sortedKeys, comp) local i = 0 local iter = function () i = i + 1 if sortedKeys[i] == nil then return nil else return sortedKeys[i], t[sortedKeys[i]] end end return iter end function sortedPairsByValues(t, comp) return sortedPairsByKeys(t, function(a, b) if comp ~= nil then return comp(t[a], t[b]) else return t[a] < t[b] end end) end local ts3errorsReverse = tableReverse(ts3errors) local serverChannels = {} local function logRaw(msg) print(msg) ts3.printMessageToCurrentTab(msg) end local function logMsg(msg) logRaw("[color=red][" .. MODULE_NAME .. "][/color] " .. tostring(msg)) end local function logError(msg, error) local errorMsg, errorB = ts3.getErrorMessage(error) if errorB ~= ts3errors.ERROR_ok then errorMsg = "Error getting Error Message: " .. errorB .. " for Error Code" end logMsg(msg .. ": " .. errorMsg .. " (" .. error .. ": " .. tostring(ts3errorsReverse[error]) .. ")") end logMsg("Loading " .. MODULE_NAME .. "...") local function logDefs(serverConnectionHandlerID) logMsg("Defs:") for name, category in sortedPairsByKeys(ts3defs) do for def, id in sortedPairsByValues(category) do logMsg(name .. "." .. def .. " = " .. id) end end logMsg(string.rep("#", 64)) logMsg("Errors:") for error, id in sortedPairsByValues(ts3errors) do logMsg(error .. " = " .. id) end end local function createOrJoinChannel(serverConnectionHandlerID) local serverUID, error = ts3.getServerVariableAsString(serverConnectionHandlerID, ts3defs.VirtualServerProperties.VIRTUALSERVER_UNIQUE_IDENTIFIER) if error == ts3errors.ERROR_not_connected then logError("You are not connected to a Server", error) return elseif error ~= ts3errors.ERROR_ok then logError("Failed to get Server UID", error) return end local clientID, error = ts3.getClientID(serverConnectionHandlerID) if error ~= ts3errors.ERROR_ok then logError("Failed to get Client ID", error) return end local data = serverChannels[serverUID] if data == nil then logMsg("There is no predefined Channel for this Server (Server UID: " .. serverUID .. "). Define one in the config file.") return end local channelName = data.name local channelPassword = data.password local channelTopic = data.topic local channelCodec = data.codec local channelCodecQuality = data.codecQuality local channelAutoJoin = data.autoJoin local channelAutoCreate = data.autoCreate local parentChannelPath = {"User Channels", ""} if channelAutoJoin == "0" and channelAutoCreate == "0" then logMsg("Your predefined Channel for this Server (Server UID: " .. serverUID .. ") is faulty: Auto joining and creating are both disabled. Cannot create or join Channel.") return end local joinMatchProperty = data.joinMatchProperty local joinMatchChannelProperty if channelAutoJoin == "1" then local error = false, req if joinMatchProperty == "name" then if channelName ~= nil and channelName ~= "" then joinMatchChannelProperty = ts3defs.ChannelProperties.CHANNEL_NAME else error = true req = joinMatchProperty end elseif joinMatchProperty == "topic" then if channelTopic ~= nil then joinMatchChannelProperty = ts3defs.ChannelProperties.CHANNEL_TOPIC else error = true req = joinMatchProperty end else error = true end if error then local msg = "Your predefined Channel for this Server (Server UID: " .. serverUID .. ") is faulty: Missing/Invalid required field" if req then msg = msg .. "s 'joinMatchProperty', '" .. req .. "'" else msg = msg .. " 'joinMatchProperty'" end logMsg(msg .. " for auto joining. Cannot create or join Channel.") return end end if channelAutoCreate == "1" and (channelName == nil or channelName == "" or channelCodec == nil or channelCodecQuality == nil) then logMsg("Your predefined Channel for this Server (Server UID: " .. serverUID .. ") is faulty: Missing/Invalid required field 'name', 'codec', 'quality' for auto joining. Cannot create or join Channel.") return end -- Try to find and join the Channel if channelAutoJoin == "1" then local channelList, error = ts3.getChannelList(serverConnectionHandlerID) if error ~= ts3errors.ERROR_ok then logError("Failed to get Channel-List", error) return end local channelID = 0 for _, id in ipairs(channelList) do local matchValue = ts3.getChannelVariableAsString(serverConnectionHandlerID, id, joinMatchChannelProperty) if matchValue == channelMatchValue then channelID = id break end end if channelID ~= 0 then local error = ts3.requestClientMove(serverConnectionHandlerID, clientID, channelID, channelPassword) if error ~= ts3errors.ERROR_ok then logError("Failed to join Channel", error) end return end end -- Create the Channel if channelAutoCreate == "1" then local parentChannelID, error = ts3.getChannelIDFromChannelNames(serverConnectionHandlerID, parentChannelPath) if error ~= ts3errors.ERROR_ok then logError("Failed to get parent Channel ID", error) return end ts3.setChannelVariableAsString(serverConnectionHandlerID, 0, ts3defs.ChannelProperties.CHANNEL_NAME, channelName) if channelPassword ~= nil and channelPassword ~= "" then ts3.setChannelVariableAsString(serverConnectionHandlerID, 0, ts3defs.ChannelProperties.CHANNEL_PASSWORD, channelPassword) end if channelTopic ~= nil and channelTopic ~= "" then ts3.setChannelVariableAsString(serverConnectionHandlerID, 0, ts3defs.ChannelProperties.CHANNEL_TOPIC, channelTopic) end if channelCodec ~= nil and channelCodec ~= "" then ts3.setChannelVariableAsString(serverConnectionHandlerID, 0, ts3defs.ChannelProperties.CHANNEL_CODEC, channelCodec) end if channelCodec ~= nil and channelCodec ~= "" then ts3.setChannelVariableAsString(serverConnectionHandlerID, 0, ts3defs.ChannelProperties.CHANNEL_CODEC_QUALITY, channelCodecQuality) end local error = ts3.flushChannelCreation(serverConnectionHandlerID, parentChannelID) if error ~= ts3errors.ERROR_ok then logError("Failed to create channel", error) return end end end local function onConnectStatusChangeEvent(serverConnectionHandlerID, status, errorNumber) if status == ts3defs.ConnectStatus.STATUS_CONNECTION_ESTABLISHED then createOrJoinChannel(serverConnectionHandlerID) end end local function onMenuItemEvent(serverConnectionHandlerID, menuType, menuItemID, selectedItemID) createOrJoinChannel(serverConnectionHandlerID) end local function createMenus(moduleMenuItemID) return { { ts3defs.PluginMenuType.PLUGIN_MENU_TYPE_GLOBAL, 0, "Create or join predefined Channel", "" } } end local function loadServerChannels() local serverFileName = "config/" .. MODULE_NAME .. "/servers.txt" logMsg("Loading Server Config from <AppPath>/" .. serverFileName) local file, msg, id = io.open(serverFileName) if file then for serverUID in file:lines() do if serverUID ~= nil and serverUID ~= "" then serverChannels[serverUID] = {} end end file:close() else logMsg("Could not load Server Config: " .. tostring(msg) .. " (" .. tostring(id) .. ")") end for serverUID, dataTable in pairs(serverChannels) do local channelFileName = "config/" .. MODULE_NAME .. "/" .. serverUID .. ".txt" logMsg("Loading Channel Config from <AppPath>/" .. channelFileName) local file, msg, id = io.open(channelFileName) if file then for line in io.lines(channelFileName) do if line ~= nil and line ~= "" then local i = string.find(line, "=") if i ~= nil then local key = string.sub(line, 1, i - 1) local value = string.sub(line, i + 1) if key ~= nil and key ~= "" then dataTable[key] = value end end end end file:close() else logMsg("Could not load Channel Config: " .. tostring(msg) .. " (" .. tostring(id) .. ")") end end end loadServerChannels() acjc = { logDefs = logDefs, createOrJoinChannel = createOrJoinChannel, cjc = createOrJoinChannel } local registeredEvents = { onConnectStatusChangeEvent = onConnectStatusChangeEvent, createMenus = createMenus, onMenuItemEvent = onMenuItemEvent } ts3RegisterModule(MODULE_NAME, registeredEvents) logMsg("Successfully loaded " .. MODULE_NAME) local commands = {} for cmd, _ in pairs(acjc) do table.insert(commands, cmd) end table.sort(commands) logMsg(#commands .. " Commands available:") for _, cmd in ipairs(commands) do logMsg(" [color=green]" .. cmd .. "[/color]") end logMsg("Run with '/lua run " .. MODULE_NAME .. ".<command>'")
--[[ Simple fizz buzz implementation --]] local function is_multiple_of(divisor, number) return number % divisor == 0 end local function check_that_number_is_greater_than_zero(number) if number <= 0 then error('Error: number must be > 0') end end local function figure_out_result(number) local result = number if is_multiple_of(3, number) and is_multiple_of(5, number) then result = 'fizz buzz' elseif is_multiple_of(3, number) then result = 'fizz' elseif is_multiple_of(5, number) then result = 'buzz' end return result end return function(number) check_that_number_is_greater_than_zero(number) return figure_out_result(number) end
local _, private = ... --[[ Lua Globals ]] -- luacheck: globals --[[ Core ]] local Aurora = private.Aurora local Base = Aurora.Base local Skin = Aurora.Skin local Color = Aurora.Color --do --[[ FrameXML\MainMenuBarBagButtons.lua ]] --end do --[[ FrameXML\MainMenuBarBagButtons.xml ]] function Skin.BagSlotButtonTemplate(ItemButton) Skin.FrameTypeItemButton(ItemButton) if private.isRetail then Base.CropIcon(ItemButton.SlotHighlightTexture) else Base.CropIcon(ItemButton:GetCheckedTexture()) end end end function private.FrameXML.MainMenuBarBagButtons() if private.disabled.mainmenubar then return end Skin.FrameTypeItemButton(_G.MainMenuBarBackpackButton) if private.isRetail then Base.CropIcon(_G.MainMenuBarBackpackButton.SlotHighlightTexture) else Base.CropIcon(_G.MainMenuBarBackpackButton:GetCheckedTexture()) end Skin.BagSlotButtonTemplate(_G.CharacterBag0Slot) Skin.BagSlotButtonTemplate(_G.CharacterBag1Slot) Skin.BagSlotButtonTemplate(_G.CharacterBag2Slot) Skin.BagSlotButtonTemplate(_G.CharacterBag3Slot) if private.isRetail then _G.CharacterBag0Slot:SetPoint("RIGHT", _G.MainMenuBarBackpackButton, "LEFT", -4, -5) _G.CharacterBag1Slot:SetPoint("RIGHT", _G.CharacterBag0Slot, "LEFT", -4, 0) _G.CharacterBag2Slot:SetPoint("RIGHT", _G.CharacterBag1Slot, "LEFT", -4, 0) _G.CharacterBag3Slot:SetPoint("RIGHT", _G.CharacterBag2Slot, "LEFT", -4, 0) if not private.isPatch then Skin.GlowBoxFrame(_G.AzeriteInBagsHelpBox) end else local KeyRingButton = _G.KeyRingButton Base.SetBackdrop(KeyRingButton, Color.frame) Base.SetHighlight(KeyRingButton, "backdrop") local normal = KeyRingButton:GetNormalTexture() normal:SetTexture([[Interface\Icons\Inv_Misc_Key_13]]) --normal:SetTexCoord(0.1875, 0.8125, 0.0625, 0.9375) --normal:SetTexCoord(ULx, ULy, LLx, LLy, URx, URy, LRx, LRy) normal:SetTexCoord(0.625, 0.03125, 0.03125, 0.84375, 0.921875, 0.171875, 0.34375, 0.984375) normal:ClearAllPoints() normal:SetPoint("TOPLEFT", 1, -1) normal:SetPoint("BOTTOMRIGHT", -1, 1) local pushed = KeyRingButton:GetPushedTexture() pushed:SetTexture([[Interface\Icons\Inv_Misc_Key_13]]) --pushed:SetTexCoord(0.09375, 0.46875, 0.046875, 0.5625) pushed:SetTexCoord(0.625, 0.03125, 0.03125, 0.84375, 0.921875, 0.171875, 0.34375, 0.984375) pushed:SetAllPoints(normal) KeyRingButton:GetHighlightTexture():SetTexture("") end end
-------------------------------------------------------------------------------- -- Module declaration -- local mod, CL = BigWigs:NewBoss("Loken", 602, 600) if not mod then return end mod:RegisterEnableMob(28923) -------------------------------------------------------------------------------- -- Initialization -- function mod:GetOptions() return { 59835, -- Lightning Nova } end function mod:OnBossEnable() self:Log("SPELL_CAST_START", "LightningNova", 52960, 59835) -- normal, heroic self:Death("Win", 28923) end -------------------------------------------------------------------------------- -- Event Handlers -- function mod:LightningNova(args) self:Message(59835, "orange", "Alert") self:Bar(59835, args.spellId == 59835 and 4 or 5) end
local localization = { ATT_STR_BUYER = "Покупатель", ATT_STR_SELLER = "Продавец", ATT_STR_GUILD = "Гильдия", ATT_STR_ITEM = "Предмет", ATT_STR_UNIT_PRICE = "шт.", ATT_STR_PRICE = "Цена", ATT_STR_TIME = "Время", ATT_STR_PURCHASES = "Покупки", ATT_STR_SALES = "Продажи", ATT_STR_ITEMS = "Предметы", ATT_STR_DAYS = "дней", ATT_STR_NOW = "сейчас", ATT_STR_TODAY = "Сегодня", ATT_STR_YESTERDAY = "Вчера", ATT_STR_TWO_DAYS_AGO = "Два дня назад", ATT_STR_THIS_WEEK = "Текущая неделя", ATT_STR_LAST_WEEK = "Прошлая неделя", ATT_STR_PRIOR_WEEK = "Предыдущая неделя", ATT_STR_7_DAYS = "7 дней", ATT_STR_10_DAYS = "10 дней", ATT_STR_14_DAYS = "14 дней", ATT_STR_30_DAYS = "30 дней", ATT_STR_NO_PRICE = "Нет цены", ATT_STR_AVERAGE_PRICE = "Средняя цена", ATT_STR_TOTAL = "Cуммарный", ATT_STR_OTHER_QUALITIES = "В другом качестве", ATT_STR_NOTHING_FOUND = "<Ничего не найдено>", ATT_STR_STATS_TO_CHAT = "Статистику в чат", ATT_STR_OPEN_POPUP_TOOLTIP = "Открыть всплывающую подсказку", ATT_FMTSTR_STATS_ITEM = "ATT цена для %s: %s (%s продаж / %s предметов / %s дней)", ATT_FMTSTR_STATS_NO_QUANTITY = "ATT цена для %s: %s (%s продаж / %s дней)", ATT_FMTSTR_STATS_MASTER_WRIT = "ATT цена для %s: %s (%s продаж / %s ваучеров / %s за ваучер / %s дней)", ATT_FMTSTR_STATS_NO_SALES = "ATT цена для %s: Нет продаж за последние %s дней.", ATT_FMTSTR_TOOLTIP_STATS_ITEM = "%s продаж, %s предметов", ATT_FMTSTR_TOOLTIP_STATS_MASTER_WRIT = "%s продаж, %s ваучеров", ATT_FMTSTR_TOOLTIP_PRICE_ITEM = "%s", ATT_FMTSTR_TOOLTIP_PRICE_MASTER_WRIT = "%s (%s за один ваучер)", ATT_FMTSTR_TOOLTIP_NO_SALES = "Нет данных", ATT_FMTSTR_ANNOUNCE_SALE = "Вы продали %sx %s за %s в %s", ATT_STR_ENABLE_GUILD_ROSTER_EXTENSIONS = "Включить Расширения для состава гильдии", ATT_STR_ENABLE_TRADING_HOUSE_EXTENSIONS = "Включить Расширения для магазина", ATT_STR_ENABLE_TOOLTIP_EXTENSIONS = "Включить Расширения для всплывающих подсказок", ATT_STR_ENABLE_TOOLTIP_EXTENSIONS_GRAPH = "Показывать график", ATT_STR_ENABLE_TOOLTIP_EXTENSIONS_CRAFTING = "Show crafting costs", ATT_STR_ENABLE_TOOLTIP_EXTENSIONS_CRAFTING_TOOLTIP = "Only supported for a subset of master writs", ATT_STR_ENABLE_INVENTORY_PRICES = "Enable prices in inventories", ATT_STR_ENABLE_INVENTORY_PRICES_WARNING = "Can cause frame skips upon first open", ATT_STR_KEEP_SALES_FOR_DAYS = "Хранить историю продаж x дней", ATT_STR_BASE_PROFIT_MARGIN_CALC_ON = "Расчёт прибыли основан на", ATT_STR_DEFAULT_DEAL_LEVEL = "Default deal level", ATT_STR_DEFAULT_DEAL_LEVEL_TOOLTIP = "Sets the default deal level when there is no sales data for an item", ATT_STR_DEAL_LEVEL_1 = "Bad", ATT_STR_DEAL_LEVEL_2 = "OK", ATT_STR_DEAL_LEVEL_3 = "Good", ATT_STR_DEAL_LEVEL_4 = "Great", ATT_STR_DEAL_LEVEL_5 = "Fantastic", ATT_STR_DEAL_LEVEL_6 = "Mind-blowing!", ATT_STR_ENABLE_TRADING_HOUSE_AUTO_PRICING = 'Enable auto pricing for guild trader listings', ATT_STR_ENABLE_TRADING_HOUSE_AUTO_PRICING_TOOLTIP = 'Default UI only', ATT_STR_FILTER_TEXT_TOOLTIP = "Поиск по игрокам-, гильдиям- или предметам, трейтам предметов (например, presice) или качеству предметов (например, легендарный)", ATT_STR_FILTER_SUBSTRING_TOOLTIP = "Переключение между поиском по слову целиком или по части слова. Заглавные буквы игнорируются в обоих случаях.", ATT_STR_FILTER_COLUMN_TOOLTIP = "Включить/Исключить эту колонку в/из поиск(а)", } localization["en"] = { ATT_STR_STATS_TO_CHAT = localization["ATT_STR_STATS_TO_CHAT"], ATT_FMTSTR_STATS_ITEM = localization["ATT_FMTSTR_STATS_ITEM"], ATT_FMTSTR_STATS_NO_QUANTITY = localization["ATT_FMTSTR_STATS_NO_QUANTITY"], ATT_FMTSTR_STATS_MASTER_WRIT = localization["ATT_FMTSTR_STATS_MASTER_WRIT"], ATT_FMTSTR_STATS_NO_SALES = localization["ATT_FMTSTR_STATS_NO_SALES"], } ZO_ShallowTableCopy(localization, ArkadiusTradeTools.Modules.Sales.Localization)
local increasing = {[416] = 417, [426] = 425, [446] = 447, [3216] = 3217, [3202] = 3215, [11062] = 11063} local decreasing = {[417] = 416, [425] = 426, [447] = 446, [3217] = 3216, [3215] = 3202, [11063] = 11062} function onStepIn(creature, item, position, fromPosition) if not increasing[item.itemid] then return true end if not creature:isPlayer() or creature:isInGhostMode() then return true end item:transform(increasing[item.itemid]) if item.actionid >= 1000 then if creature:getLevel() < item.actionid - 1000 then creature:teleportTo(fromPosition, false) position:sendMagicEffect(CONST_ME_MAGIC_BLUE) creature:sendTextMessage(MESSAGE_INFO_DESCR, "The tile seems to be protected against unwanted intruders.") end return true end if Tile(position):hasFlag(TILESTATE_PROTECTIONZONE) then local lookPosition = creature:getPosition() lookPosition:getNextPosition(creature:getDirection()) local depotItem = Tile(lookPosition):getItemByType(ITEM_TYPE_DEPOT) if depotItem then local depotItems = creature:getDepotChest(getDepotId(depotItem:getUniqueId()), true):getItemHoldingCount() creature:sendTextMessage(MESSAGE_STATUS_DEFAULT, "Your depot contains " .. depotItems .. " item" .. (depotItems > 1 and "s." or ".")) return true end end if item.actionid ~= 0 and creature:getStorageValue(item.actionid) <= 0 then creature:teleportTo(fromPosition, false) position:sendMagicEffect(CONST_ME_MAGIC_BLUE) creature:sendTextMessage(MESSAGE_INFO_DESCR, "The tile seems to be protected against unwanted intruders.") return true end return true end function onStepOut(creature, item, position, fromPosition) if not decreasing[item.itemid] then return true end if creature:isPlayer() and creature:isInGhostMode() then return true end item:transform(decreasing[item.itemid]) return true end
-- aes256.lua -- This file is part of AES-everywhere project (https://github.com/mervick/aes-everywhere) -- -- This is an implementation of the AES algorithm, specifically CBC mode, -- with 256 bits key length and PKCS7 padding. -- -- Copyright Andrey Izman (c) 2018-2019 <izmanw@gmail.com> -- Copyright Philip Mayer (c) 2020 <philip.mayer@shadowsith.de> -- Licensed under the MIT license -- -- 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. -- Requires lua-openssl (luarocks install openssl) local openssl = require "openssl" local md5 = openssl.digest.get('md5') -- private local function deriveKeyAndIv(passphrase, salt) local di = "" local dx = "" for i = 1, 4 do di = md5:digest(di .. passphrase .. salt) dx = dx .. di end return string.sub(dx, 0, 32), string.sub(dx, 33, 48) end -- public AES256 = {} AES256.encrypt = function(input, passphrase) local salt = openssl.random(8) local key, iv = deriveKeyAndIv(passphrase, salt) local aes = openssl.cipher.new('aes-256-cbc', true, key, iv, true, openssl.engine('pkcs7')) local crypted = aes:update(input) .. aes:final() return openssl.base64("Salted__" .. salt .. crypted, true) end AES256.decrypt = function(crypted, passphrase) local data = openssl.base64(crypted, false) local salted = string.sub(data, 0, 8) if salted ~= "Salted__" then error("Invalid data") end local salt = string.sub(data, 9, 16) crypted = string.sub(data, 17, string.len(data)) local key, iv = deriveKeyAndIv(passphrase, salt) local aes = openssl.cipher.new('aes-256-cbc', false, key, iv, true, openssl.engine('pkcs7')) crypted = aes:update(crypted) .. aes:final() return crypted end return AES256;
local t = Def.ActorFrame{ Def.Quad{ InitCommand=cmd(FullScreen;diffuse,color("0,0,0,1")); }; }; t[#t+1] = Def.ActorFrame { InitCommand=cmd(Center;blend,Blend.Add;;); LoadActor(THEME:GetPathB("","ScreenLogo background/bg"))..{ OnCommand=cmd(diffusealpha,1;sleep,5;linear,0.165;diffusealpha,0); }; Def.Quad{ InitCommand=cmd(setsize,SCREEN_WIDTH,SCREEN_HEIGHT;diffuse,color("0,0,0,0.6")); OnCommand=cmd(diffusealpha,0.6;sleep,5;linear,0.165;diffusealpha,0); }; }; t[#t+1] = Def.ActorFrame { InitCommand=cmd(Center); LoadActor("werds")..{ OnCommand=cmd(diffusealpha,1); OffCommand=cmd(sleep,5;linear,0.165;diffusealpha,0) }; LoadActor("bemani")..{ OnCommand=cmd(diffusealpha,0;sleep,5.165;linear,0.165;diffusealpha,1); OffCommand=cmd(sleep,10.165;linear,0.165;diffusealpha,0); }; }; return t;
//----------------Silent Raid---------------------- // //Silently notifies admins of the starting of a raid // // //commit 07-19-17 //by Mikomi Hooves //------------------------------------------------- //------------------------------------------------- // BLogs Setup //------------------------------------------------- function SR_initalize( ) bLogs.CreateCategory("Silent Raid", Color(165, 0, 55, 255)) bLogs.DefineLogger("Raid Start", "Silent Raid") bLogs.DefineLogger("Raid Over", "Silent Raid") end if (bLogsInit) then SR_initalize() else hook.Add("bLogsInit","SR_initalize",SR_initalize) end //------------------------------------------------- // ULib Setup //------------------------------------------------- ULib.ucl.registerAccess( "Silent Raid", ULib.ACCESS_ADMIN, "Allows player to see raid notifications", "Other" )-- Create ULX catagory for easy assignemnt of who can see this shit notification //------------------------------------------------- // Network stuff //------------------------------------------------- util.AddNetworkString( "SR_RaidOver_admin" ) util.AddNetworkString( "SR_RaidStart_admin" ) util.AddNetworkString( "SR_RaidOver_player" ) util.AddNetworkString( "SR_RaidStart_player" ) util.AddNetworkString( "SR_NoRaid" ) util.AddNetworkString( "SR_AlreadyRaid" ) util.AddNetworkString( "SR_Timeup" ) util.AddNetworkString( "SR_Timer_End" ) util.AddNetworkString( "SR_RaidOver_adminnet" ) util.AddNetworkString( "SR_RemoveTimer" ) util.AddNetworkString( "SR_SelfRaid" ) util.AddNetworkString( "SR_WrongJob" ) util.AddNetworkString( "SR_FunnyJoke" ) //------------------------------------------------- // Silent Raid Functions //------------------------------------------------- srTable = {} srTable.raider = {} srTable.target = {} srTable.raidAllowed = { "Mane-iac","Mane-iac's Sergeant", "Mane-iac's Goon", "The Mysterious Mare Do Well" } //This is shouldnt have to change much to make things work as all its doing is getting a list of admins and notifying them when a raid starts/ends function SR_AdminNotify_start( srRaider, srVictim, ply ) local srAdmins = {} //Find players with the ulx perm for seeing the notification for k, v in pairs( player.GetAll() ) do if ULib.ucl.query( v, "Silent Raid", true ) then srAdmins[ #srAdmins + 1 ] = v end end net.Start("SR_RaidStart_admin") net.WriteEntity(srRaider) net.WriteEntity(srTarget) net.Send(srAdmins) bLogs.Log({ module = "Raid Start", log = bLogs.GetName(srRaider) .. " Has began a raid on " .. bLogs.GetName(srTarget) .. ".", involved = {srRaider, srTarget}, }) end function SR_AdminNotify_end( srRaider, ply ) local srAdmins = {} //Find players with the ulx perm for seeing the notification for k, v in pairs( player.GetAll() ) do if ULib.ucl.query( v, "Silent Raid", true ) then srAdmins[ #srAdmins + 1 ] = v end end net.Start("SR_RaidOver_admin") net.WriteEntity(srPlayer) net.WriteEntity(srVictim) net.Send(srAdmins) bLogs.Log({ module = "Raid Over", log = "A Raid by " .. bLogs.GetName(srPlayer) .. " on " .. bLogs.GetName(srVictim) .. " has ended.", involved = {srPlayer, srVictim}, }) end function SR_AdminNotify_endnet( srRaider, srVictim, ply ) local srAdmins = {} local srNetRaider = net.ReadEntity(raider) local srNetTarget = net.ReadEntity(target) //Find players with the ulx perm for seeing the notification for k, v in pairs( player.GetAll() ) do if ULib.ucl.query( v, "Silent Raid", true ) then srAdmins[ #srAdmins + 1 ] = v end end net.Start("SR_RaidOver_adminnet") net.WriteEntity(srNetRaider) net.WriteEntity(srNetTarget) net.Send(srAdmins) table.RemoveByValue(srTable.raider, srNetRaider) table.RemoveByValue(srTable.target, srNetTarget) bLogs.Log({ module = "Raid Over", log = "A Raid by " .. bLogs.GetName(srNetRaider) .. " on " .. bLogs.GetName(srNetTarget) .. " has ended.", involved = {srNetRaider, srNetTarget}, }) end net.Receive("SR_Timer_End", SR_AdminNotify_endnet) //Need to begin writing values to a table for current raiders and targets and matching them up by pairs //Most likely will just do this by comparing keys for the two tables, as long as they are added and removed at the same time then life should be good function SR_RaidStart( ply, text, team, args ) sr_activeRaid = false srRaider = ply if IsValid( ply ) and ply:IsPlayer() then -- Check for player beacuse console and all that jazz can chat, mind you it would be neat to see the console raid someone... anyway... local target = string.lower(text) local text = string.lower( string.Left( text, 5 ) ) // This will check for the player saying the command, this will likely be changed for a more indepth command // with auto complete of player names, and a req for a player name to be entered or it will error // ... ill do it later if text == "/raid" then local match = nil for k,v in pairs( srTable.raidAllowed ) do if ply:getJobTable().name == v then match = 1 end end if !match then net.Start("SR_WrongJob") net.Send(srRaider) return "" end if table.HasValue(srTable.raider, ply) then net.Start("SR_AlreadyRaid") net.Send(srRaider) return "" end //local srPossTargets = {} I think this is depreciated I cant remember but it doesnt seem im using it, might have been planning to though //Ill leave it for now //This is going to have to be overhauled to write the target and raider to a table rather than a veriable, while being careful to match keys for k, v in pairs(player.GetAll()) do local vSM = string.lower(v:Nick()) local vCheck = string.Explode(" ", vSM) local targExp = string.Explode(" ", target) if targExp[2] == nil then break end srTarget = string.match(targExp[2], vCheck[1]) if !srTarget then srTarget = string.match(vCheck[1], targExp[2]) end if srTarget then sr_activeRaid = true srTarget = v if v == ply then net.Start("SR_SelfRaid") net.Send(srRaider) return "" end srTable.target[ #srTable.target +1 ] = v srTable.raider[ #srTable.raider +1 ] = ply hook.Add( "PlayerDeath", tostring(srRaider), SR_RaiderDead) net.Start("SR_RaidStart_player") net.WriteEntity(srRaider) net.WriteEntity(srTarget) net.Send(srRaider) SR_AdminNotify_start( ply ) break end end return "" end end end hook.Add( "PlayerSay", "SR_RaidStart", SR_RaidStart) //To be used if the raider calls /over //Ill fix this up once I have the tables ready and then this can just check them and remove the value when a raid is over //Might acutally redo all the ending functions so that the various outcomes just call a singal function as to make things //abit cleaner... in short ignore this for now... All of it function SR_RaidOver( ply, text, team ) if IsValid( ply ) and ply:IsPlayer() then -- Check for player beacuse console and all that jazz can chat, mind you it would be neat to see the console raid someone... anyway... local text = string.lower( string.Left( text, 5 ) ) if text == "/over" and !table.HasValue(srTable.raider, ply) then //For safety if there is no raid we dont let the user end the raid beacuse there will be no information for the CL chat print net.Start("SR_NoRaid") net.Send(ply) return "" elseif text == "/over" and table.HasValue(srTable.raider, ply) then srPlayer = nil srPlayer = ply for k,v in pairs(srTable.raider) do if ply == v then srKey = k end end for k,v in pairs(srTable.target) do if srKey == k then srVictim = v end end net.Start("SR_RaidOver_player") net.WriteEntity(srPlayer) net.WriteEntity(srVictim) net.Send(ply) table.RemoveByValue(srTable.raider, srPlayer) table.RemoveByValue(srTable.target, srVictim) net.Start("SR_RemoveTimer") net.Send(ply) SR_AdminNotify_end( ) return "" end end end hook.Add( "PlayerSay", "SR_RaidOver", SR_RaidOver) //End the raid if the raider is dead function SR_RaiderDead( ply ) if table.HasValue(srTable.raider, ply) then srPlayer = nil srPlayer = ply for k,v in pairs(srTable.raider) do if ply == v then srKey = k end end for k,v in pairs(srTable.target) do if srKey == k then srVictim = v end end hook.Remove(tostring(ply)) net.Start("SR_RaidOver_player") net.WriteEntity(srPlayer) net.WriteEntity(srVictim) net.Send(ply) table.RemoveByValue(srTable.raider, srPlayer) table.RemoveByValue(srTable.target, srVictim) net.Start("SR_RemoveTimer") net.Send(ply) SR_AdminNotify_end( ) end end //for the lols function SR_FunnyJoke( ) local srjokekill = net.ReadEntity(srjoke) srjokekill:Kill() end net.Receive("SR_FunnyJoke", SR_FunnyJoke)
vim.g.scnvim_postwin_orientation = "h" vim.g.scnvim_postwin_size = 7 vim.g.scnvim_scdoc = 0 vim.g.scnvim_scdoc_render_prg = "f:\\devel\\Scripts\\pandoc.exe" vim.g.scnvim_snippet_format = "luasnip" --vim.g.scnvim_no_mappings = 1 vim.keymap.set("n", "<M-e>", "<Plug>(scnvim-send-block)", { remap = true }) vim.keymap.set("i", "<M-e>", "<C-o><Plug>(scnvim-send-block)", { remap = true }) vim.keymap.set("v", "<M-e>", "<Plug>(scnvim-send-selection)", { remap = true }) vim.keymap.set("n", "<C-e>", "<Plug>(scnvim-send-line)", { remap = true }) vim.keymap.set("i", "<C-e>", "<C-o><Plug>(scnvim-send-line)", { remap = true }) vim.keymap.set("n", "<F12>", "<Plug>(scnvim-hard-stop)", { remap = true }) vim.keymap.set("i", "<F12>", "<C-o><Plug>(scnvim-hard-stop)", { remap = true }) -- does this work? vim.keymap.set("n", "<M-k>", "<Plug>(scnvim-show-signature)", { remap = true }) vim.keymap.set("i", "<M-k>", "<C-o><Plug>(scnvim-show-signature)", { remap = true })
--- === plugins.finalcutpro.timeline.playback === --- --- Playback Plugin. local require = require local fcp = require "cp.apple.finalcutpro" local i18n = require "cp.i18n" local tools = require "cp.tools" local playErrorSound = tools.playErrorSound local mod = {} --- plugins.finalcutpro.timeline.playback.play() -> none --- Function --- 'Play' in Final Cut Pro --- --- Parameters: --- * None --- --- Returns: --- * None function mod.play() if not fcp.viewer:isPlaying() and not fcp.eventViewer:isPlaying() then fcp:doShortcut("PlayPause"):Now() else playErrorSound() end end --- plugins.finalcutpro.timeline.playback.pause() -> none --- Function --- 'Pause' in Final Cut Pro --- --- Parameters: --- * None --- --- Returns: --- * None function mod.pause() if fcp.viewer:isPlaying() or fcp.eventViewer:isPlaying() then fcp:doShortcut("PlayPause"):Now() else playErrorSound() end end local plugin = { id = "finalcutpro.timeline.playback", group = "finalcutpro", dependencies = { ["finalcutpro.commands"] = "fcpxCmds", } } function plugin.init(deps) -------------------------------------------------------------------------------- -- Only load plugin if Final Cut Pro is supported: -------------------------------------------------------------------------------- if not fcp:isSupported() then return end local cmds = deps.fcpxCmds cmds :add("cpPlay") :subtitled(i18n("thisWillOnlyTriggerThePlayShortcutKeyIfAlreadyStopped")) :whenActivated(mod.play) cmds :add("cpPause") :subtitled(i18n("thisWillOnlyTriggerThePauseShortcutKeyIfAlreadyPlaying")) :whenActivated(mod.pause) end return plugin
return {'tbc'}
---------------------------------------------------------------- -- Copyright © 2019 by Guy Shefer -- Made By: Guy293 -- GitHub: https://github.com/Guy293 -- Fivem Forum: https://forum.fivem.net/u/guy293/ -- Tweaked by Campinchris (Added ESX only Diff animation for Police and Non Police) ---------------------------------------------------------------- Config = {} Config.CooldownPolice = 700 Config.cooldown = 1700 -- Add/remove weapon hashes here to be added for holster checks. Config.Weapons = { "WEAPON_PISTOL", "WEAPON_COMBATPISTOL", "WEAPON_APPISTOL", "WEAPON_PISTOL50", "WEAPON_SNSPISTOL", "WEAPON_HEAVYPISTOL", "WEAPON_VINTAGEPISTOL", "WEAPON_MARKSMANPISTOL", "WEAPON_MACHINEPISTOL", "WEAPON_VINTAGEPISTOL", "WEAPON_PISTOL_MK2", "WEAPON_SNSPISTOL_MK2", "WEAPON_FLAREGUN", "WEAPON_STUNGUN", "WEAPON_REVOLVER", }
local class = function() local c = {} c.__index = c c.class = c c.new = function(...) local obj = {} setmetatable(obj,c) obj:init(...) return obj end setmetatable(c, {__call = function(t, ...) return c.new(...) end }) return c end return class
--estudos sobre lua --[[ comentario ]] print("Hello World with lua ")
--- 验证spi flash驱动接口 目前该驱动兼容w25q32 bh25q32 require"spiFlash" require "pm" pm.wake("testSpiFlash") local flashlist = { [0xEF15] = 'w25q32', [0xEF16] = 'w25q64', [0xEF17] = 'w25q128', [0x6815] = 'bh25q32', } sys.taskInit(function() local spi_flash = spiFlash.setup(spi.SPI_1) while true do local manufacutreID, deviceID = spi_flash:readFlashID() print('spi flash id', manufacutreID, deviceID) local flashName = (manufacutreID and deviceID) and flashlist[manufacutreID*256 + deviceID] log.info('testSPIFlash', 'flash name', flashName or 'unknown') print('spi flash erase 4K', spi_flash:erase4K(0x1000)) print('spi flash write', spi_flash:write(0x1000, '123456')) print('spi flash read', spi_flash:read(0x1000, 6)) -- '123456' sys.wait(1000) end end)
local key = ModPath .. ' ' .. RequiredScript if _G[key] then return else _G[key] = true end for character, tweaks in pairs(tweak_data.character) do if type(tweaks) == "table" and tweaks.move_speed and character ~= "presets" then tweaks.hostage_move_speed = tweaks.surrender and tweaks.surrender ~= tweak_data.character.presets.surrender.special and tweak_data.character.civilian.hostage_move_speed or 1 end end HuskCopBrain._ENABLE_LASER_TIME = 0.1 HuskCopBrain._NET_EVENTS.hostage_on = 3 HuskCopBrain._NET_EVENTS.hostage_off = 4 local fs_original_huskcopbrain_syncnetevent = HuskCopBrain.sync_net_event function HuskCopBrain:sync_net_event(event_id) if event_id == self._NET_EVENTS.hostage_on then self._unit:movement().move_speed_multiplier = tweak_data.character[self._unit:base()._tweak_table].hostage_move_speed elseif event_id == self._NET_EVENTS.hostage_off then self._unit:movement().move_speed_multiplier = 1 else fs_original_huskcopbrain_syncnetevent(self, event_id) end end
local Class = require'libs.hump.class' local Trigger = require'trigger' EnemyCollision = Class{ __includes = Trigger } function EnemyCollision:init(x,y,w,h,properties) Trigger:init(self,x,y,w,h) self.name = "EnemyCollision" self.x = x self.y = y self.w = w self.h = h self.map = map self.properties = properties self.img = love.graphics.newImage( 'assets/entity_stub.png' ) self.pressable = true self.active = false return self end function EnemyCollision:handleCollisions() print("am i being called?") end
-- -- Created by IntelliJ IDEA. -- User: chen0 -- Date: 29/6/2017 -- Time: 4:55 PM -- To change this template use File | Settings | File Templates. -- describe("Union Find", function() it("should connect points union together", function() local unionfind = require('lualgorithms.unionfind').create() unionfind:union(1, 2) unionfind:union(4, 6) unionfind:union(7, 4) assert.equal(unionfind:connected(6, 7), true) assert.equal(unionfind:connected(4, 7), true) assert.equal(unionfind:connected(6, 4), true) assert.equal(unionfind:connected(6, 1), false) assert.equal(unionfind:connected(7, 2), false) end) end)
require("import") -- the import fn import("cpp_namespace") -- import lib into global cn=cpp_namespace --alias -- catching undefined variables local env = _ENV -- Lua 5.2 if not env then env = getfenv () end -- Lua 5.1 setmetatable(env, {__index=function (t,i) error("undefined global variable `"..i.."'",2) end}) assert(cn.fact(4) == 24) assert(cn.Foo == 42) t1 = cn.Test() assert(t1:method() == "Test::method") cn.weird("t1", 4) assert(cn.do_method(t1) == "Test::method") assert(cn.do_method2(t1) == "Test::method") t2 = cn.Test2() assert(t2:method() == "Test2::method") assert(cn.foo3(5) == 5) assert(cn.do_method3(t2, 7) == "Test2::method")
--- -- @author wesen -- @copyright 2019-2020 wesen <wesen-ac@web.de> -- @release 0.1 -- @license MIT -- local Object = require "classic" --- -- Provides methods to read a file. -- -- @type File -- local File = Object:extend() --- -- The file path of the file -- -- @tfield string path -- File.path = nil --- -- File constructor. -- -- @tparam string _path The file path of the file -- function File:new(_path) self.path = _path end -- Public Methods --- -- Returns the contents of the File. -- -- @treturn string The File's contents -- function File:getContents() local fileContents = "" for line in io.lines(self.path) do fileContents = fileContents .. "\n" .. line end return fileContents end return File
local WEAPON = FindMetaTable("Weapon") function WEAPON:GetPrimaryAmmoName() return game.GetAmmoName(self:GetPrimaryAmmoType()) end function WEAPON:GetSecondaryAmmoName() return game.GetAmmoName(self:GetSecondaryAmmoType()) end -- FIXME function WEAPON:GetDefaultClip1() return self:IsScripted() and self.Primary.DefaultClip or -1 end function WEAPON:GetDefaultClip2() return self:IsScripted() and self.Secondary.DefaultClip -1 end -- https://github.com/Facepunch/garrysmod-issues/issues/2543 function WEAPON:GetActivityBySequence(iIndex) local pOwner = self:GetOwner() if (pOwner:IsValid()) then local pViewModel = pOwner:GetViewModel(iIndex) if (pViewModel:IsValid()) then return pViewModel:GetSequenceActivity(pViewModel:GetSequence()) end end return ACT_INVALID end -- https://github.com/Facepunch/garrysmod-requests/issues/703 function WEAPON:GetPrimaryAmmoCount() return 1 end function WEAPON:GetSecondaryAmmoCount() return 1 end --[[function WEAPON:HasAmmo() return self:HasPrimaryAmmo() or self:HasSecondaryAmmo() end]] function WEAPON:HasPrimaryAmmo() -- Melee/utility weapons always have ammo if (self:GetMaxClip1() == -1 and self:GetMaxClip2() == -1) then return true end // If I use a clip, and have some ammo in it, then I have ammo if (self:Clip1() ~= 0) then return true end // Otherwise, I have ammo if I have some in my ammo counts local pPlayer = self:GetOwner() if (pPlayer:IsValid()) then return pPlayer:GetAmmoCount(self:GetPrimaryAmmoType()) > 0 end // No owner, so return how much primary ammo I have along with me if (self:GetPrimaryAmmoCount() > 0) then return true end return false end function WEAPON:HasSecondaryAmmo() if (self:GetMaxClip2() == -1 and self:GetMaxClip1() == -1) then return true end if (self:Clip2() ~= 0) then return true end local pPlayer = self:GetOwner() if (pPlayer:IsValid()) then return pPlayer:GetAmmoCount(self:GetSecondaryAmmoType()) > 0 end if (self:GetSecondaryAmmoCount() > 0) then return true end return false end function WEAPON:IsActiveWeapon() local pPlayer = self:GetOwner() return pPlayer:IsValid() and pPlayer:GetActiveWeapon() == self end function WEAPON:IsViewModelSequenceFinished(iIndex) local pPlayer = self:GetOwner() if (pPlayer:IsValid()) then local pViewModel = pPlayer:GetViewModel(iIndex) if (pViewModel:IsValid()) then if (pViewModel:GetSaveValue("m_bSequenceFinished")) then return true end local iActivity = self:GetActivityBySequence(iIndex) // These are not valid activities and always complete immediately return iActivity == ACT_INVALID or iActivity == ACT_RESET end end -- https://github.com/Facepunch/garrysmod-requests/issues/704 return false end
--[[ Tester for LinearNet Copyright 2016 Xiang Zhang --]] local class = require('pl.class') local math = require('math') local torch = require('torch') local Test = class() -- Constructor -- data: the data instance -- model: the model instance -- loss: the loss instance -- config: configuration table function Test:_init(data, model, loss, config) self.data = data self.model = model self.loss = loss self.type = model:type() end -- Run the tester -- callback: a function to execute after each step function Test:run(callback) self.total_objective = 0 self.total_error = 1 self.step = 0 for sample, label in self.data:iterator() do self:runStep(sample, label) self.step = self.step + 1 if callback then callback(self, self.step) end end end -- Run for one step function Test:runStep(sample, label) -- Get sample self.sample, self.label = sample, label -- Forward propagation self.output = self.model:forward(self.sample) self.objective = self.loss:forward(self.output, self.label) -- Compute decision self.max, self.decision = self.output:max(1) self.error = (self.decision[1] == self.label[1]) and 0 or 1 -- Accumulate errors self.total_objective = (self.total_objective * self.step + self.objective) / (self.step + 1) self.total_error = (self.total_error * self.step + self.error) / (self.step + 1) end return Test
TestEnums = { modulesEnums = {"MODULES_4"}, arrays = {111,222}, moduelsEnums2 = {"MODULES_2","MODULES_1"}, integer = 0 }
--[[ Copyright (c) 2018, Vsevolod Stakhov <vsevolod@highsecure.ru> 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. ]]-- --[[[ -- @module lua_scanners -- This module contains external scanners functions --]] local fun = require "fun" local exports = { } local function require_scanner(name) local sc = require ("lua_scanners/" .. name) exports[sc.name or name] = sc end -- Antiviruses require_scanner('clamav') require_scanner('fprot') require_scanner('kaspersky_av') require_scanner('savapi') require_scanner('sophos') -- Other scanners require_scanner('dcc') require_scanner('oletools') require_scanner('icap') require_scanner('vadesecure') require_scanner('spamassassin') exports.add_scanner = function(name, t, conf_func, check_func) assert(type(conf_func) == 'function' and type(check_func) == 'function', 'bad arguments') exports[name] = { type = t, configure = conf_func, check = check_func, } end exports.filter = function(t) return fun.tomap(fun.filter(function(_, elt) return type(elt) == 'table' and elt.type and ( (type(elt.type) == 'string' and elt.type == t) or (type(elt.type) == 'table' and fun.any(function(tt) return tt == t end, elt.type)) ) end, exports)) end return exports
local branch_id = ARGV[1]; local mh_id = ARGV[2]; local assigned_pss_for_branch = redis.call("HGET", "{BAMH}:MH_BRANCH_ASSIGNATIONS", branch_id); if assigned_pss_for_branch == mh_id or assigned_pss_for_branch == "UNAVAILABLE" .. mh_id or assigned_pss_for_branch == "SHUTTINGDOWN" .. mh_id then redis.call("HDEL", "{BAMH}:MH_BRANCH_ASSIGNATIONS", branch_id) end
local cmp_status_ok, cmp = pcall(require, 'cmp') if not cmp_status_ok then vim.notify('Not able to load in cmp', 'error') return end local tabnine_status_ok, tabnine = pcall(require, 'cmp_tabnine.config') if not tabnine_status_ok then vim.notify('Not able to load in tabnine', 'error') return end local lspkind_status_ok, lspkind = pcall(require, 'lspkind') if not lspkind_status_ok then vim.notify('Not able to load in lspkind', 'error') return end require('utils/setmapping') local source_mapping = { buffer = "[Buffer]", nvim_lsp = "[LSP]", nvim_lua = "[Lua]", cmp_tabnine = "[TN]", path = "[Path]", } local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match("%s") == nil end local feedkey = function(key, mode) vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes(key, true, true, true), mode, true) end -- Set completion menu options setOption('global', 'completeopt', 'menuone,noselect') tabnine:setup({ max_lines = 1000; max_num_results = 20; sort = true; run_on_every_keystroke = true; snippet_placeholder = '..'; ignored_file_types = { -- default is not to ignore -- uncomment to ignore in lua: -- lua = true }; }) cmp.setup({ snippet = { expand = function(args) vim.fn["vsnip#anonymous"](args.body) end, }, mapping = { ['<C-b>'] = cmp.mapping(cmp.mapping.scroll_docs(-4), { 'i', 'c' }), ['<C-f>'] = cmp.mapping(cmp.mapping.scroll_docs(4), { 'i', 'c' }), ['<C-Space>'] = cmp.mapping(cmp.mapping.complete(), { 'i', 'c' }), ['<C-y>'] = cmp.config.disable, -- Specify `cmp.config.disable` if you want to remove the default `<C-y>` mapping. ['<C-e>'] = cmp.mapping({ i = cmp.mapping.abort(), c = cmp.mapping.close(), }), ['<CR>'] = cmp.mapping.confirm({ select = true }), ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif vim.fn["vsnip#available"](1) == 1 then feedkey("<Plug>(vsnip-expand-or-jump)", "") elseif has_words_before() then cmp.complete() else fallback() -- The fallback function sends a already mapped key. In this case, it's probably `<Tab>`. end end, { "i", "s" }), ["<S-Tab>"] = cmp.mapping(function() if cmp.visible() then cmp.select_prev_item() elseif vim.fn["vsnip#jumpable"](-1) == 1 then feedkey("<Plug>(vsnip-jump-prev)", "") end end, { "i", "s" }), }, formatting = { format = function(entry, vim_item) vim_item.kind = lspkind.presets.default[vim_item.kind] local menu = source_mapping[entry.source.name] if entry.source.name == 'cmp_tabnine' then if entry.completion_item.data ~= nil and entry.completion_item.data.detail ~= nil then menu = entry.completion_item.data.detail .. ' ' .. menu end vim_item.kind = '' end vim_item.menu = menu return vim_item end }, sources = cmp.config.sources({ { name = 'cmp_tabnine' }, { name = 'nvim_lsp' } }, { { name = 'buffer' }, }) })
--Copyright 2019 Control4 Corporation. All rights reserved. do --Globals Timer = Timer or {} end function OnDriverDestroyed () DlnaStopDiscovery () KillAllTimers () end function OnDriverLateInit () KillAllTimers () -- run here in case of driver update to stop timers from running but being out of scope if (C4.AllowExecute) then C4:AllowExecute (true) end C4:urlSetTimeout (20) if (not PersistData) then PersistData = {} end DlnaLocations = {} DlnaDevices = {} for property, _ in pairs (Properties) do OnPropertyChanged (property) end -- UPNP server if (CALLBACK == nil) then SetCallbackServer () end C4:CreateNetworkConnection (6999, '239.255.255.250') DlnaSendDiscoveryPacket () -- listen for servers coming online end function OnPropertyChanged (strProperty) local value = Properties [strProperty] if (value == nil) then print ('OnPropertyChanged, nil value for Property: ', strProperty) return end if (strProperty == 'Driver Version') then C4:UpdateProperty ('Driver Version', C4:GetDriverConfigInfo ('version')) elseif (strProperty == 'Device Selector') then if (value ~= '') then for uuid, device in pairs (DlnaDevices or {}) do if (value == device.friendlyName) then if (CURRENT_DEVICE ~= uuid) then CURRENT_DEVICE = uuid PersistData.CURRENT_DEVICE = CURRENT_DEVICE C4:UpdateProperty ('Device Selector', '') C4:UpdateProperty ('Selected Device', device.friendlyName) -- XXX this is where we would trigger setting up of the device, connecting to the control protocol, etc end end end end end end ----------------------------------------------- -- url Functions ----------------------------------------------- GlobalTicketHandlers = GlobalTicketHandlers or {} function ReceivedAsync (ticketId, strData, responseCode, tHeaders, strError) for k, info in pairs (GlobalTicketHandlers) do if (info.TICKET == ticketId) then table.remove (GlobalTicketHandlers, k) if (ETag) then local url = info.URL local hit = false local tag = tHeaders.ETag for k, v in pairs (ETag) do if (v.url == url) then hit = k end end if (responseCode == 200 and strError == nil) then if (strData == nil and tonumber (tHeaders ['Content-Length']) == 0) then strData = '' end if (hit) then table.remove (ETag, hit) end if (tag and info.METHOD ~= 'DELETE') then table.insert (ETag, 1, {url = url, strData = strData, tHeaders = tHeaders, tag = tag}) end elseif (tag and responseCode == 304 and strError == nil) then if (hit) then strData = ETag [hit].strData tHeaders = ETag [hit].tHeaders table.remove (ETag, hit) table.insert (ETag, 1, {url = url, strData = strData, tHeaders = tHeaders, tag = tag}) responseCode = 200 end end while (#ETag > MAX_CACHE) do table.remove (ETag, #ETag) end end local data, js, len for k, v in pairs (tHeaders) do if (string.upper (k) == 'CONTENT-TYPE') then if (string.find (v, 'application/json')) then js = true end end if (string.upper (k) == 'CONTENT-LENGTH') then len = tonumber (v) or 0 end end if (js) then data = JSON:decode (strData) if (data == nil and len ~= 0) then print ('ERROR parsing json data: ') strError = 'Error parsing response' end else data = strData end if (info.CALLBACK) then info.CALLBACK (strError, responseCode, tHeaders, data, info.CONTEXT, info.URL) else print (responseCode, info.URL) Print (data) end return end end end function urlDo (method, url, data, headers, callback, context) local info = {} if (type (callback) == 'function') then info.CALLBACK = callback end info.CONTEXT = context info.URL = url info.METHOD = method data = data or '' headers = headers or {} for _, etag in pairs (ETag or {}) do if (etag.url == url) then headers ['If-None-Match'] = etag.tag end end if (method == 'GET') then info.TICKET = C4:urlGet (url, headers, false) elseif (method == 'POST') then info.TICKET = C4:urlPost (url, data, headers, false) elseif (method == 'PUT') then info.TICKET = C4:urlPut (url, data, headers, false) elseif (method == 'DELETE') then info.TICKET = C4:urlDelete (url, headers, false) else info.TICKET = C4:urlCustom (url, method, data, headers, false) end if (info.TICKET and info.TICKET ~= 0) then table.insert (GlobalTicketHandlers, info) else print ('C4.Curl error: ' .. info.METHOD .. ' ' .. url) if (callback) then callback ('No ticket', nil, nil, '', context, url) end end end function urlGet (url, headers, callback, context) urlDo ('GET', url, data, headers, callback, context) end function urlPost (url, data, headers, callback, context) urlDo ('POST', url, data, headers, callback, context) end function urlPut (url, data, headers, callback, context) urlDo ('PUT', url, data, headers, callback, context) end function urlDelete (url, headers, callback, context) urlDo ('DELETE', url, data, headers, callback, context) end function urlCustom (url, method, data, headers, callback, context) urlDo (method, url, data, headers, callback, context) end ----------------------------------------------- -- useful functions ----------------------------------------------- function KillAllTimers () for k,v in pairs (Timer or {}) do if (type (timer) == 'userdata') then timer:Cancel () Timer [k] = nil end end end function Print (data) if (type (data) == 'table') then local p = {} for k, v in pairs (data) do table.insert (p, tostring (k) .. ' :-: ' .. tostring (v)) end print (table.concat (p, '\r\n')) elseif (type (data) ~= 'nil') then print (type (data), data) else print ('nil value') end end function XMLDecode (s) if (s == nil) then return end s = string.gsub (s, '%<%!%[CDATA%[(.-)%]%]%>', function (a) return (a) end) s = string.gsub (s, '&quot;' , '"') s = string.gsub (s, '&lt;' , '<') s = string.gsub (s, '&gt;' , '>') s = string.gsub (s, '&apos;' , '\'') s = string.gsub (s, '&#x(.-);', function (a) return string.char (tonumber (a, 16) % 256) end ) s = string.gsub (s, '&#(.-);', function (a) return string.char (tonumber (a) % 256) end ) s = string.gsub (s, '&amp;' , '&') return s end function XMLEncode (s) if (s == nil) then return end s = string.gsub (s, '&', '&amp;') s = string.gsub (s, '"', '&quot;') s = string.gsub (s, '<', '&lt;') s = string.gsub (s, '>', '&gt;') s = string.gsub (s, '\'', '&apos;') return s end function XMLTag (strName, tParams, tagSubTables, xmlEncodeElements) local retXML = {} if (type (strName) == 'table' and tParams == nil) then tParams = strName strName = nil end if (strName) then table.insert (retXML, '<') table.insert (retXML, tostring (strName)) table.insert (retXML, '>') end if (type (tParams) == 'table') then for k, v in pairs (tParams) do if (v == nil) then v = '' end if (type (v) == 'table') then if (tagSubTables == true) then table.insert (retXML, XMLTag (k, v)) end else if (v == nil) then v = '' end table.insert (retXML, '<') table.insert (retXML, tostring (k)) table.insert (retXML, '>') if (xmlEncodeElements ~= false) then table.insert (retXML, XMLEncode (tostring (v))) else table.insert (retXML, tostring (v)) end table.insert (retXML, '</') table.insert (retXML, tostring (k)) table.insert (retXML, '>') end end elseif (tParams) then if (xmlEncodeElements ~= false) then table.insert (retXML, XMLEncode (tostring (tParams))) else table.insert (retXML, tostring (tParams)) end end if (strName) then table.insert (retXML, '</') table.insert (retXML, tostring (strName)) table.insert (retXML, '>') end return (table.concat (retXML)) end ----------------------------------------------- ----------------------------------------------- -- UPNP functions ----------------------------------------------- ----------------------------------------------- do -- static service values AVTRANSPORT_SERVICE = 'urn:upnp-org:serviceId:AVTransport' UPNPEvent = {} UPNPEvent [AVTRANSPORT_SERVICE] = {} end function SetCallbackServer () local serverport = math.random (49152, 65535) local ip = C4:GetControllerNetworkAddress () if (ip and ip ~= '') then C4:CreateServer (serverport) CALLBACK = 'http://' .. ip .. ':' .. serverport .. '/notify/' else CALLBACK = nil if (Timer.SetCallbackServer) then Timer.SetCallbackServer = Timer.SetCallbackServer:Cancel () end Timer.SetCallbackServer = C4:SetTimer (15 * 1000, function (timer) if (CALLBACK == nil) then SetCallbackServer () end end) end end function UPNPInvoke (serviceId, actionName, actionData, callback, context) if (not CURRENT_DEVICE) then print ('Invoke Error: Device not set') return end local serviceURN = UPNPServices [CURRENT_DEVICE][serviceId].serviceType local controlURL = UPNPServices [CURRENT_DEVICE][serviceId].controlURL local args if (type (actionData) == 'table') then args = XMLTag (nil, actionData) elseif (type (actionData) == 'string') then args = actionData end local content = '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">' .. '<s:Body><u:' .. actionName .. ' xmlns:u="' .. serviceURN .. '">' .. args .. '</u:' .. actionName .. '></s:Body></s:Envelope>' local headers = {['Content-Type'] = 'text/xml; charset="utf-8"', SOAPACTION = '"' .. serviceURN .. '#' .. actionName.. '"'} urlPost (controlURL, content, headers, callback, context) end ----------------------------------------------- -- Discovery functions ----------------------------------------------- function OnConnectionStatusChanged (idBinding, nPort, strStatus) if (idBinding == 6999) then DlnaSSDPServerOnline = (strStatus == 'ONLINE') if (DlnaSSDPServerOnline) then print ('SSDP discovery socket online') DlnaSendDiscoveryPacket () else print ('SSDP discovery socket offline') if (PersistData and PersistData.CURRENT_DEVICE and not (CURRENT_DEVICE and DlnaDevices [PersistData.CURRENT_DEVICE])) then -- if device has been selected but is not currently found if (Timer.DlnaRescan) then Timer.DlnaRescan = Timer.DlnaRescan:Cancel () end Timer.DlnaRescan = C4:SetTimer (math.random (20, 40) * 1000, function (timer) DlnaSendDiscoveryPacket () end) end end end end function ReceivedFromNetwork (idBinding, nPort, strData) if (idBinding == 6999) then DlnaParseSSDPResponse (strData) end end function DlnaOpenDiscoveryConnection () DlnaStopDiscovery () if (Timer.DlnaCloseConnection) then Timer.DlnaCloseConnection = Timer.DlnaCloseConnection:Cancel () end Timer.DlnaCloseConnection = C4:SetTimer (10 * 1000, function (timer) C4:NetDisconnect (6999, 1900, 'UDP') Timer.DlnaCloseConnection = Timer.DlnaCloseConnection:Cancel () end) C4:NetConnect (6999, 1900, 'UDP') end function DlnaSendDiscoveryPacket () if (Timer.DlnaRescan) then Timer.DlnaRescan = Timer.DlnaRescan:Cancel () end Timer.DlnaRescan = C4:SetTimer (math.random (180, 300) * 1000, function (timer) DlnaSendDiscoveryPacket () end) -- XXX this timer period is set for Sonos. It should be no more than half (and ideally less than a third) of the interval expiry time from the SSDP packet to avoid -- invalid offline calls if (DlnaSSDPServerOnline) then local content = 'M-SEARCH * HTTP/1.1\r\n' .. 'HOST: 239.255.255.250:1900\r\n' .. 'MAN: "ssdp:discover"\r\n' .. 'MX: 5\r\n' .. 'ST: ' .. 'ssdp:all' .. '\r\n\r\n' -- XXX you should change ssdp:all to whichever is the tightest search pattern for your UPNP device you can use C4:SendToNetwork (6999, 1900, content) C4:SendToNetwork (6999, 1900, content) C4:SendToNetwork (6999, 1900, content) C4:SendToNetwork (6999, 1900, content) C4:SendToNetwork (6999, 1900, content) else DlnaOpenDiscoveryConnection () end end function DlnaStopDiscovery () for location, timer in pairs (DlnaLocations or {}) do DlnaLocations [location] = timer:Cancel () end DlnaLocations = {} C4:NetDisconnect (6999, 1900) end function DlnaParseSSDPResponse (data) if (string.find (data, 'M-SEARCH')) then return end if (string.find (data, 'c4:')) then return end local headers = {} for line in string.gmatch (data, '(.-)\r\n') do local k, v = string.match (line, '%s*(.-)%s*[:/*]%s*(.+)') if (k and v) then k = string.upper (k) headers [k] = v end end -- XXX you can change YOUR SEARCH TYPE HERE to whatever your correct value is and uncomment this line to not parse unnecessary SSDP responses -- if (not (headers.ST and headers.ST == 'YOUR SEARCH TYPE HERE')) then return end local alive, byebye if (headers.HTTP and headers.HTTP == '1.1 200 OK') then alive = true elseif (headers.NOTIFY and headers.NTS and headers.NTS == 'ssdp:alive') then -- we can't currently receive these alive = true elseif (headers.NOTIFY and headers.NTS and headers.NTS == 'ssdp:byebye') then -- we can't currently receive these byebye = true end if (alive) then local interval if (headers ['CACHE-CONTROL']) then interval = string.match (headers ['CACHE-CONTROL'], 'max-age = (%d+)') end interval = tonumber (interval) or 1800 if (headers.LOCATION) then local location = headers.LOCATION local server, path = string.match (location, 'http://(.-)(/.*)') local ip, port = string.match (server, '(.-):(.+)') if (not port) then ip = server port = 80 end DlnaDevices = DlnaDevices or {} local uuid = string.match (headers.USN, 'uuid:(.-):') if (not uuid) then return end DlnaDevices [uuid] = DlnaDevices [uuid] or {} for k, v in pairs (headers) do DlnaDevices [uuid] [k] = v end DlnaDevices [uuid].ip = ip DlnaDevices [uuid].port = port if (DlnaLocations [location]) then DlnaLocations [location]:Cancel () else urlGet (location, nil, DlnaParseXML, {uuid = uuid}) end DlnaLocations [location] = C4:SetTimer (interval * 1005, function (timer) DlnaLocations [location] = nil for uuid, device in pairs (DlnaDevices or {}) do if (device.LOCATION == location) then DlnaDeviceOffline (uuid) end end end) end elseif (byebye) then if (headers.USN) then local uuid = string.match (headers.USN, 'uuid:(.+)') DlnaDeviceOffline (uuid) end end end function DlnaDeviceOffline (uuid) -- if a device doesn't respond to an M-SEARCH within it's interval, it'll "go offline" -- we can't continuously listen for bye-bye messages. local location = DlnaDevices [uuid].LOCATION local timer = DlnaLocations [location] if (timer) then DlnaLocations [location] = timer:Cancel () end DlnaDevices [uuid] = nil if (Timer.UpdateServerList) then Timer.UpdateServerList:Cancel () end Timer.UpdateServerList = C4:SetTimer (1000, function (timer) UpdateServerList () end) if (uuid == CURRENT_DEVICE) then -- XXX may want to implement a counter here if device doesn't reliably respond to most M-SEARCH messages CURRENT_DEVICE = nil end if (CURRENT_DEVICE == nil) then if (Timer.DlnaRescan) then Timer.DlnaRescan:Cancel () end Timer.DlnaRescan = C4:SetTimer (math.random (5, 10) * 1000, function (timer) DlnaSendDiscoveryPacket () end) end end function DlnaParseXML (strError, responseCode, tHeaders, data, context, url) if (strError == nil and responseCode == 200) then local friendlyName = XMLDecode (string.match (data, '<friendlyName>(.-)</friendlyName>')) local uuid = string.match (data, '<UDN>uuid:(.-)</UDN>') -- UPNP functions require this local server, path = string.match (url, 'http://(.-)(/.*)') local URLBase = string.match (data, '<URLBase>(.-)</URLBase>') or string.match (path, '(.*/)') UPNPServices = UPNPServices or {} UPNPServices [uuid] = UPNPServices [uuid] or {} for service in string.gfind (data, '<service>(.-)</service>') do local serviceId = string.match (service, '<serviceId>(.-)</serviceId>') local serviceType = string.match (service, '<serviceType>(.-)</serviceType>') local controlURL = string.match (service, '<controlURL>(.-)</controlURL>') local eventSubURL = string.match (service, '<eventSubURL>(.-)</eventSubURL>') local SCPDURL = string.match (service, '<SCPDURL>(.-)</SCPDURL>') if (string.sub (controlURL, 1, 1) ~= '/') then controlURL = URLBase .. controlURL end if (string.sub (eventSubURL, 1, 1) ~= '/') then eventSubURL = URLBase .. eventSubURL end if (string.sub (SCPDURL, 1, 1) ~= '/') then SCPDURL = URLBase .. SCPDURL end controlURL = 'http://' .. server .. controlURL eventSubURL = 'http://' .. server .. eventSubURL SCPDURL = 'http://' .. server .. SCPDURL UPNPServices [uuid][serviceId] = {serviceType = serviceType, controlURL = controlURL, eventSubURL = eventSubURL, SCPDURL = SCPDURL} end DlnaDevices [uuid].friendlyName = friendlyName if (Timer.UpdateServerList) then Timer.UpdateServerList:Cancel () end Timer.UpdateServerList = C4:SetTimer (1000, function (timer) UpdateServerList () end) if (CURRENT_DEVICE == nil and PersistData.CURRENT_DEVICE == uuid) then -- this happens on startup of C4 when we've previously selected this device and this is the first time being discovered -- this also happens if a device was offline for a period of time and is being rediscovered after going offline -- XXX note that we cannot generically detect a device rebooting and coming back online on the same IP address within it's timeout -- XXX you will need to either see if there is an SSDP response value that you can parse to detect this (uptime counter or similar) -- XXX or resubscribe to the device on EVERY SSDP response for CURRENT_DEVICE in the DlnaParseSSDPResponse function C4:UpdateProperty ('Device Selector', friendlyName) OnPropertyChanged ('Device Selector') end end end function UpdateServerList () local names = {[1] = ''} for uuid, device in pairs (DlnaDevices or {}) do table.insert (names, device.friendlyName) end table.sort (names) names = table.concat (names, ',') C4:UpdatePropertyList ('Device Selector', names) end ----------------------------------------------- --UPNP server functions ----------------------------------------------- function OnServerConnectionStatusChanged (nHandle, nPort, strStatus) if (strStatus == 'ONLINE') then if (not ServerBuffer) then ServerBuffer = {} end ServerBuffer [nHandle] = '' elseif (strStatus == 'OFFLINE') then C4:ServerCloseClient (nHandle) ServerBuffer [nHandle] = nil end end function OnServerDataIn (nHandle, strData) if (ServerBuffer and ServerBuffer [nHandle]) then ServerBuffer [nHandle] = ServerBuffer [nHandle] .. strData local content, headers = ProcessHTTP (nHandle, true) if (headers and content) then if (headers.NOTIFY) then C4:ServerSend (nHandle, 'HTTP/1.1 200 OK\r\n\r\n') local deviceUuid, serviceId = string.match (headers.NOTIFY, '/notify/(.-)/(.-) HTTP/') for property in string.gfind (content, '<e:property>(.-)</e:property>') do local variable, data = string.match (property, '<(.-)>(.-)</.->') data = XMLDecode (data) if (UPNPEvent and UPNPEvent [serviceId] and UPNPEvent [serviceId] [variable]) then UPNPEvent [serviceId] [variable] (data) else print (serviceId, variable, data) end end end if (not (headers.CONNECTION and headers.CONNECTION == 'Keep-Alive')) then C4:ServerCloseClient (nHandle) end end end end function ProcessHTTP (idBinding, isServer) local Buffer = Buffer if (isServer) then Buffer = ServerBuffer end local i, _, HTTP_Header, HTTP_Content = string.find (Buffer [idBinding], '(.-\r\n)\r\n(.*)') if (i == nil) then -- no <cr><lf><cr><lf> received yet return end local rcvHeaders = {} string.gsub (HTTP_Header, '([^%s:]+):?%s?([^\r\n]*)\r\n', function (a, b) rcvHeaders [string.upper (a)] = b return '' end) if (rcvHeaders ['CONTENT-LENGTH'] and HTTP_Content:len() < tonumber (rcvHeaders ['CONTENT-LENGTH'])) then -- Packet not complete yet, still waiting for content to arrive return end if (rcvHeaders ['TRANSFER-ENCODING'] and string.find (rcvHeaders ['TRANSFER-ENCODING'], 'chunked')) then --what about a stream? Do we need to deal with that? local result = '' local lastChunk = false while (not lastChunk) do local _, chunkStart, chunkLen = string.find (HTTP_Content, '^%W-(%x+).-\r\n') --allow for chunk extensions between HEX and crlf if (not chunkLen) then return end --waiting for more HTTP chunks --waiting for more to come in? chunkLen = tonumber (chunkLen, 16) if (chunkLen == 0 or chunkLen == nil) then lastChunk = true else result = result .. string.sub (HTTP_Content, chunkStart + 1, chunkStart + chunkLen) HTTP_Content = string.sub (HTTP_Content, chunkStart + chunkLen + 1) end end HTTP_Content = result end Buffer [idBinding] = '' if (HTTP_Content == nil) then HTTP_Content = '' end return HTTP_Content, rcvHeaders end ----------------------------------------------- --UPNP subscribe ----------------------------------------------- function UPNPServiceSubscribe (serviceId) if (not CALLBACK) then print ('Callback server not initialized, waiting') return end if (not CURRENT_DEVICE) then print ('Subscribe Error: Device not set') return end local sId, path for id, info in pairs (Subscriptions or {}) do if (info and info.deviceUuid == CURRENT_DEVICE and info.serviceId == serviceId) then sId = id path = info.path break end end local device = DlnaDevices [CURRENT_DEVICE] local service = UPNPServices [CURRENT_DEVICE][serviceId] if (sId and path) then if (Subscriptions [sId].TIMER) then Subscriptions [sId].TIMER = Subscriptions [sId].TIMER:Cancel () end else path = service.eventSubURL end if (sId) then print ('Resubscribing ', device.friendlyName, serviceId) else print ('Subscribing ', device.friendlyName, serviceId) end if (not path) then print ('service not found') return end local headers = {TIMEOUT = 'Second-3600'} if (sId) then headers.SID = sId else headers.CALLBACK = '<' .. CALLBACK .. CURRENT_DEVICE .. '/' .. serviceId .. '>' headers.NT = 'upnp:event' end urlCustom (path, 'SUBSCRIBE', '', headers, UPNPServiceSubscribeResponse, {deviceUuid = CURRENT_DEVICE, serviceId = serviceId, path = path, sId = sId}) end function UPNPServiceSubscribeResponse (strError, responseCode, tHeaders, data, context, url) if (strError == nil and responseCode == 200) then local timeout = 3600 if (tHeaders and tHeaders.SID) then local sId = tHeaders.SID if (not Subscriptions) then Subscriptions = {} end Subscriptions [sId] = context timeout = tonumber (string.sub ((tHeaders.TIMEOUT or ''), 8)) or timeout local deviceName = DlnaDevices [CURRENT_DEVICE].friendlyName if (context.sId) then print ('Resubscribed ', deviceName, context.serviceId, timeout) else print ('Subscribed ', deviceName, context.serviceId, timeout) end if (Subscriptions [sId].TIMER) then Subscriptions [sId].TIMER = Subscriptions [sId].TIMER:Cancel () end Subscriptions [sId].TIMER = C4:SetTimer ((timeout - 10) * 1000, function (timer) UPNPServiceSubscribe (context.serviceId) end) end elseif (strError == nil and responseCode == 412) then if (context.sId and Subscriptions [context.sId]) then if (Subscriptions [context.sId].TIMER) then Subscriptions [context.sId].TIMER = Subscriptions [context.sId].TIMER:Cancel () end Subscriptions [context.sId] = nil end local sub repeat sub = 'EVSUB' .. math.random (1000000, 9999999) until (not Subscriptions [sub]) Subscriptions [sub] = context if (Subscriptions [sub].TIMER) then Subscriptions [sub].TIMER = Subscriptions [sub].TIMER:Cancel () end Subscriptions [sub].TIMER = C4:SetTimer (5 * 1000, function (timer) Subscriptions [sub] = nil UPNPServiceSubscribe (context.serviceId) end) else print ('Error subscribing:' .. strError or '') if (context.sId and Subscriptions [context.sId]) then if (Subscriptions [context.sId].TIMER) then Subscriptions [context.sId].TIMER = Subscriptions [context.sId].TIMER:Cancel () end Subscriptions [context.sId] = nil end end end function UPNPServiceUnsubscribe (serviceId) if (not CURRENT_DEVICE) then print ('Unsubscribe Error: Device not set') return end local device = DlnaDevices [CURRENT_DEVICE] local service = UPNPServices [CURRENT_DEVICE][serviceId] local sId, path for id, info in pairs (Subscriptions or {}) do if (info and info.deviceUuid == CURRENT_DEVICE and info.serviceId == serviceId) then sId = id path = info.path break end end print ('Unsubscribing ', device.friendlyName, serviceId) if (not path) then print ('Service not subscribed, cannot unsubscribe') return end if (Subscriptions [sId].TIMER) then Subscriptions [sId].TIMER = Subscriptions [sId].TIMER:Cancel () end Subscriptions [sId] = nil urlCustom (path, 'UNSUBSCRIBE', '', {SID = sId}, UPNPServiceUnsubscribeResponse, {deviceUuid = CURRENT_DEVICE, serviceId = serviceId, path = path, sId = sId}) end function UPNPServiceUnsubscribeResponse (strError, responseCode, tHeaders, data, context, url) if (strError == nil and responseCode == 200) then local deviceName = DlnaDevices [CURRENT_DEVICE].friendlyName print ('Unsubscribed ', deviceName, context.serviceId) end end
local class = require 'middleclass' local lume = require 'lume' -- 基底クラス local Entity = require 'Entity' -- シーン クラス local Scene = class('Scene', Entity) -- 初期化 function Scene:initialize() Entity.initialize(self) end -- シーンの追加 function Scene:addScene(scene) if self.parent then lume.call(self.parent.add, self.parent, scene) end end -- シーンの削除 function Scene:removeScene(scene) if self.parent then lume.call(self.parent.remove, self.parent, scene) end end -- シーンのプッシュ function Scene:pushScene(scene) if self.parent then lume.call(self.parent.push, self.parent, scene) end end -- シーンのポップ function Scene:popScene() if self.parent then lume.call(self.parent.pop, self.parent) end end -- シーンのスワップ function Scene:swapScene(scene) if self.parent then lume.call(self.parent.swap, self.parent, scene) end end return Scene
EtcdClientOpGet = EtcdClientOpGet or class("EtcdClientOpGet", EtcdClientOpBase) function EtcdClientOpGet:ctor() EtcdClientOpSet.super.ctor(self) self[EtcdConst.Key] = nil self[EtcdConst.Wait] = nil self[EtcdConst.Recursive] = nil self[EtcdConst.WaitIndex] = nil self[EtcdConst.PrevExist] = nil self[EtcdConst.PrevIndex] = nil self[EtcdConst.PrevValue] = nil end function EtcdClientOpGet:get_http_url() if not self[EtcdConst.Key] then return false, "" end local keys = { EtcdConst.Wait, EtcdConst.Recursive, EtcdConst.WaitIndex, EtcdConst.PrevExist, EtcdConst.PrevIndex, EtcdConst.PrevValue, } local query_str = self:concat_values(keys, "%s=%s", "&") local ret_str = "" if #query_str > 0 then ret_str = string.format("%s?%s", self[EtcdConst.Key], query_str) else ret_str = self[EtcdConst.Key] end return true, ret_str end function EtcdClientOpGet:execute(etcd_client) local ret, sub_url = self:get_http_url() if not ret then return 0 end local url = string.format(self.host_format, etcd_client:get_host(), sub_url) local op_id = HttpClient.get(url, Functional.make_closure(self._handle_result_cb, self), Functional.make_closure(self._handle_event_cb, self), self.http_heads) return op_id; end --[[ function EtcdClientOpGet._handle_result_cb(op, op_id, url_str, heads_map, body_str, body_len) log_debug("EtcdClientOpGet._handle_result_cb %s %s %s %s %s", op_id or "null", url_str or "null", heads_map or "null", body_str or "", body_len or "null") end ]]
--[[ 公共状态机,处理游戏开始后的状态逻辑 ]] local PlayIngMechineBase = class(); function PlayIngMechineBase:ctor() self.m_lastState = GameMechineConfig.STATUS_PLAYING; -- 记录上一次的状态 self.m_curState = GameMechineConfig.STATUS_PLAYING; -- 当前状态 self:getActionListenMap(); end function PlayIngMechineBase:getActionListenMap() local curObj = self; while curObj do if curObj.actionConfig then self.actionConfig = CombineTables(curObj.actionConfig or {}, self.actionConfig); end if curObj.stateChangeConfig then self.stateChangeConfig = CombineTables(curObj.stateChangeConfig or {}, self.stateChangeConfig); end curObj = curObj.super; end end function PlayIngMechineBase:dtor() self.actionConfig = {}; self.stateChangeConfig = {}; end function PlayIngMechineBase:checkAction(action) if self.actionConfig[action] then return true; end return false; end function PlayIngMechineBase:getStates() return self.m_curState, self.m_lastState; end -- 重置 function PlayIngMechineBase:reset() self.m_lastState = GameMechineConfig.STATUS_PLAYING; self.m_curState = GameMechineConfig.STATUS_PLAYING; end function PlayIngMechineBase:resetState() self:reset(); end function PlayIngMechineBase:checkStateValid(uid, action, info, isFast, tag) if not self:checkAction(action) then return true; end self.m_from = tag; Log.d("PlayIngMechineBase.checkStateValid", "uid=",uid , "-----self.m_curState=", self.m_curState,"---self.m_lastState=",self.m_lastState,"---action=",action); local result = true; if self.stateChangeConfig and self.stateChangeConfig[action] == self.m_curState then -- a动作会导致状态修改为A,当前已经是A状态,又接收到动作a时,直接返回 self:sthrowErro(uid,info,"状态错误,当前状态已经是" ..(self.m_curState or "")..",action = "..(action or "")..",tag = "..(tag or "")); return true, self.m_curState, self.m_lastState, result; end local checkValid = false; local state = self.m_curState; local config = self.stateCheckConfig[self.m_curState]; if config then for k, v in pairs(config) do if v[1] == action then state = v[2] or state; checkValid = true; break; end end end self:_recordLog(uid,tag,info); if checkValid then self.m_lastState = self.m_curState; self.m_curState = state; self.m_action = action; result = self:onUpdatePlayerInfo(action,uid,info,isFast); end if (not result) or (not checkValid) then -- 状态错误,需要上报 local msg = "状态错误:" ..(self.m_curState or "")..",action = "..(action or "")..",tag = "..(tag or ""); self:sthrowErro(uid,info,msg); end return checkValid, self.m_curState, self.m_lastState, result; end -- 更新数据 function PlayIngMechineBase:onUpdatePlayerInfo(action, uid, info, isFast) local func = self.actionConfig[action]; local result = true; if type(func) == "string" then local funcSelf = self[func]; if funcSelf then result = funcSelf(self,action,uid,info,isFast); end elseif type(func) == "function" then local msg = "状态机配置表,需要修改为string类型:" ..(self.m_curState or "")..",action = "..(action or "")..",tag = "..(self.m_from or ""); self:sthrowErro(uid,info,msg); result = func(self,action,uid,info,isFast); end return result; end -- 广播通知状态变化 function PlayIngMechineBase:sendBroadCastMsg(uid, info, isFast) if number.valueOf(uid) == 0 then if _DEBUG then self:showToast("PlayIngMechineBase.sendBroadCastMsg:广播通知的uid参数不对,请检查代码。uid=" .. uid); end return false; end local simpleInfo = GamePlayerManager2.getInstance():getSimpleInfo(uid); if simpleInfo and simpleInfo.seatId then if not PlayerSeat.getInstance():isSeatLegal(simpleInfo.seatId) then return false; end EventDispatcher.getInstance():breadthDispatch(GameMechineConfig.BROADCAST_STATE, self.m_curState, self.m_lastState, self.m_action, simpleInfo.seatId, uid, info, isFast); return true; end return false; end -- 不改变当前状态的事件,触发动作监听消息 function PlayIngMechineBase:sendActionBroadCastMsg(uid, info, isFast) if number.valueOf(uid) == 0 then if _DEBUG then self:showToast("PlayIngMechineBase.sendActionBroadCastMsg:广播通知的uid参数不对,前检查代码。uid=" .. uid); end return false; end local simpleInfo = GamePlayerManager2.getInstance():getSimpleInfo(uid); if simpleInfo and simpleInfo.seatId then if not PlayerSeat.getInstance():isSeatLegal(simpleInfo.seatId) then return false; end EventDispatcher.getInstance():breadthDispatch(GameMechineConfig.BROADCAST_ACTION,self.m_action,simpleInfo.seatId,uid,info,isFast); return true; end return false; end function PlayIngMechineBase:showToast(msg) if type(msg) == "string" and msg ~= "" then Toast.getInstance():showText(msg,50,30,kAlignLeft,"",24,200,175,110); end end -- 上报错误 function PlayIngMechineBase:_recordLog(uid,tag,info) local data = {}; data.action = self.m_action; data.curState = self.m_curState; data.lastState = self.m_lastState; data.time = os.date(); data.uid = uid; data.tag = tag; data.info = info; data.mainState = self.m_mainState; MechineLog.getInstance():d("PlayIngMechineBase",uid,data); end function PlayIngMechineBase:sthrowErro(uid,info,msg) if _DEBUG and uid then self:_recordLog(uid,self.m_from,info); MechineLog.getInstance():reportLog("PlayIngMechineBase",uid); debug.traceback(); --error(msg); end end ---------------------------------------------------------------------------------------------------------------- -- 状态配置表 PlayIngMechineBase.stateCheckConfig = { -- [curStatus] = { -- { action1, lastStatus1}, -- { action2, lastStatus2}, -- }; }; -- 会引起状态变化的动作配置表 PlayIngMechineBase.stateChangeConfig = { -- [action] = status; }; -- 事件响应 PlayIngMechineBase.actionConfig = { -- [action] = "function"; }; return PlayIngMechineBase;
local WindowedScrollingFrame = require(script.WindowedScrollingFrame) return { WindowedScrollingFrame = WindowedScrollingFrame, }
function NewPIDController(p, i, d) local p = { kp = p, ki = i, kd = d, integral = 0, previousError = nil, dt = 0, shouldRunIntegral = false, clear = function(self, time) self.dt = 0 previousTime = time integral = 0 previousError = nil shouldRunIntegral = false end, pid = function(self, input, setpoint, thresh) local threshold = thresh or 0 local error = setpoint - input local p = error * self.kp local i = 0 if shouldRunIntegral then if threshold == 0 or (input < (threshold + setpoint) and input > (setpoint - threshold)) then integral = integral + dt * error else integral = 0 end else shouldRunIntegral = true end local d if previousError == nil or dt == 0 then d = 0 else d = ((error - previousError) / dt) * kd end previousError = error return p + i + d end, updateTime = function(self, time) self.dt = time - previousTime previousTime = time end } return p end
FACTION.name = "Одиночки" FACTION.desc = "Одиночки" FACTION.color = Color(210, 105, 30) FACTION.models = { "models/hdmodels/kek1ch/stalker_neutral_1_face_2.mdl", "models/hdmodels/kek1ch/stalker_neutral_1_hq.mdl", "models/hdmodels/kek1ch/stalker_neutral_1_mask.mdl", "models/hdmodels/kek1ch/stalker_neutral_1_mas2.mdl", "models/hdmodels/kek1ch/stalker_neutrala4.mdl", "models/hdmodels/kek1ch/stalker_neutrala5.mdl" } FACTION.isDefault = true FACTION.isPublic = true FACTION_LONER = FACTION.index
local m,s,o local uci = luci.model.uci.cursor() m = Map("xlnetacc") m.title = translate("XLNetAcc - Settings") m.description = translate("XLNetAcc is a Thunder joint broadband operators launched a commitment to help users solve the low broadband, slow Internet access, poor Internet experience of professional-grade broadband upgrade software.") m:section(SimpleSection).template = "xlnetacc/xlnetacc_status" s = m:section(NamedSection, "general", "general") s.title = translate("General Settings") s.anonymous = true s.addremove = false o = s:option(Flag, "enabled", translate("Enabled")) o.rmempty = false o = s:option(Flag, "down_acc", translate("Enable DownLink Upgrade")) o = s:option(Flag, "up_acc", translate("Enable UpLink Upgrade")) o = s:option(Flag, "logging", translate("Enable Logging")) o.default = 1 o = s:option(Flag, "verbose", translate("Enable verbose logging")) o:depends("logging",1) o = s:option(ListValue, "network", translate("Upgrade interface")) uci:foreach("network","interface",function(section) if section[".name"]~="loopback" then o:value(section[".name"]) end end) o = s:option(Value, "keepalive", translate("Keepalive interval")) o.description = translate("5 ~ 60 minutes") for _,v in ipairs({5,10,20,30,60}) do o:value(v,v.." "..translate("minutes")) end o.datatype = "range(5,60)" o.default = 10 o = s:option(Value, "relogin", translate("Account relogin")) o.description = translate("1 ~ 48 hours") o:value(0, translate("Not enabled")) for _,v in ipairs({3,12,18,24,30}) do o:value(v,v.." "..translate("hours")) end o.datatype = "max(48)" o.default = 0 o = s:option(Value, "account", translate("XLNetAcc account")) o = s:option(Value, "password", translate("XLNetAcc password")) o.password = true return m
local Filter = require('sre_filter') local patterns = { [[\d+]], [[\W+]], [[^(a|b|c|d)+$]] } local ids = { 1, 2, 3 } filter = Filter:new() filter:init_multi(patterns, ids) print(filter:scan('test')) print(filter:scan('10000')) print(filter:scan('abcdabcd')) print(filter:scan('abcdeabcd')) print(filter:scan('+=-#%'))
Config = {} Config.Descriptions = { "I dont have a description", "I have a description", "idk, i have it or no?", } Config.ServerName = { "Your cool server name", "Your cool server name but more COOL" } Config.UpdateCooldown = 10 -- Time in seconds (s)
------------------------------------------------------------------------------- -- $$\ $$\ $$\ $$\ -- \__| \__| $$ | $$ | -- $$\ $$$$$$$\ $$\ $$$$$$\ $$ |$$\ $$\ $$$$$$\ -- $$ |$$ __$$\ $$ |\_$$ _| $$ |$$ | $$ | \____$$\ -- $$ |$$ | $$ |$$ | $$ | $$ |$$ | $$ | $$$$$$$ | -- $$ |$$ | $$ |$$ | $$ |$$\ $$ |$$ | $$ |$$ __$$ | -- $$ |$$ | $$ |$$ | \$$$$ |$$\ $$ |\$$$$$$ |\$$$$$$$ | -- \__|\__| \__|\__| \____/ \__|\__| \______/ \_______| -------------------------------------------------------------------------------- require("config.impatient") require("user.options") require("user.keymaps") require("user.plugins") require("themes.colorscheme") require("lsp") require("config.cmp") require("config.cmp-tabnine") require("config.web-devicons") require("config.telescope") require("config.treesitter") require("config.autopairs") require("config.hop") require("config.comment") require("config.todo-comments") require("config.pretty-fold") require("config.sniprun") require("config.gitsigns") require("config.nvim-tree") require("config.bufferline") require("config.lualine") require("config.toggleterm") require("config.project") require("config.indentline") require("config.colorizer") require("config.alpha") require("config.whichkey") require("config.autocommands") require("config.notify")
--[[ Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. ]]-- local argcheck = require 'argcheck' local unn = {} local function isz(okw, odw, kw, dw, pw) dw = dw or 1 pw = pw or 0 okw = okw*dw + kw-dw-pw*2 odw = odw*dw return okw, odw end -- in specs, list of {kw=,dw=,pw=} (dw and pw optionals) -- kw (kernel width) -- dw (kernel stride) -- pw (padding) unn.inferinputsize = argcheck{ {name="specs", type="table"}, {name="size", type="number", default=1}, {name="verbose", type="boolean", default=false}, call = function(specs, size, verbose) local okw, odw = size, 1 for i=#specs,1,-1 do if specs[i].kw then okw, odw = isz(okw, odw, specs[i].kw, specs[i].dw, specs[i].pw) end if verbose then print(string.format( "|| layer %d: size=%d stride=%d", i, okw, odw)) end end return okw, odw end } local function iszr(okw, odw, kw, dw, pw) dw = dw or 1 pw = pw or 0 okw = math.floor((okw+2*pw-kw)/dw)+1 odw = odw * dw return okw, odw end unn.inferoutputsize = argcheck{ {name="specs", type="table"}, {name="size", type="number"}, {name="verbose", type="boolean", default=false}, call = function(specs, size, verbose) local okw, odw = size, 1 for i=1,#specs do okw, odw = iszr(okw, odw, specs[i].kw, specs[i].dw, specs[i].pw) if verbose then print(string.format("|| layer %d: size=%dx stride=%d", okw, odw)) end end return okw, odw end } return unn
local server = require "nvim-lsp-installer.server" local path = require "nvim-lsp-installer.path" local std = require "nvim-lsp-installer.installers.std" local root_dir = server.get_server_root_path "groovyls" return server.Server:new { name = "groovyls", root_dir = root_dir, installer = { std.ensure_executables { { "javac", "javac was not found in path." } }, std.git_clone "https://github.com/GroovyLanguageServer/groovy-language-server", std.gradlew { args = { "build" }, }, }, default_options = { cmd = { "java", "-jar", path.concat { root_dir, "build", "libs", "groovyls-all.jar" } }, }, }
game_name = "<GAME_NAME>" game = {} AUTO_UPDATE = true function _addGameObject(type, obj) obj.uuid = uuid() if obj.update then obj.auto_update = true end game[type] = ifndef(game[type],{}) table.insert(game[type], obj) end function _iterateGameGroup(group, func) for i, obj in ipairs(game[group]) do func(obj) end end require "plugins.json.json" uuid = require("plugins.uuid") Class = require 'plugins.hump.class' require 'plugins.blanke.Globals' require 'plugins.blanke.Util' require 'plugins.blanke.Debug' Input = require 'plugins.blanke.Input' Signal = require 'plugins.hump.signal' Gamestate = require 'plugins.hump.gamestate' Timer = require 'plugins.hump.timer' Vector = require 'plugins.hump.vector' Camera = require 'plugins.hump.camera' anim8 = require 'plugins.anim8' HC = require 'plugins.HC' Draw = require 'plugins.blanke.Draw' Image = require 'plugins.blanke.Image' Net = require 'plugins.blanke.Net' Save = require 'plugins.blanke.Save' Hitbox = require('plugins.blanke.Hitbox') Entity = require 'plugins.blanke.Entity' Map = require 'plugins.blanke.Map' View = require 'plugins.blanke.View' Effect = require 'plugins.blanke.Effect' Dialog = require 'plugins.blanke.Dialog' Tween = require 'plugins.blanke.Tween' Scene = require 'plugins.blanke.Scene' assets = require 'assets' <INCLUDES> function love.load() uuid.randomseed(love.timer.getTime()*10000) Gamestate.registerEvents() -- register gamestates updateGlobals(0) if "<FIRST_STATE>" ~= "" then Gamestate.switch(<FIRST_STATE>) end end -- prevents updating while window is being moved (would mess up collisions) max_fps = 120 min_dt = 1/max_fps next_time = love.timer.getTime() function love.update(dt) dt = math.min(dt, min_dt) next_time = next_time + min_dt updateGlobals(dt) Net.update(dt, false) for i_arr, arr in pairs(game) do for i_e, e in ipairs(arr) do if e.auto_update then e:update(dt) end end end end function love.draw() local cur_time = love.timer.getTime() if next_time <= cur_time then next_time = cur_time return end love.timer.sleep(next_time - cur_time) end function love.keypressed(key) _iterateGameGroup("input", function(input) input:keypressed(key) end) end function love.keyreleased(key) _iterateGameGroup("input", function(input) input:keyreleased(key) end) end function love.mousepressed(x, y, button) _iterateGameGroup("input", function(input) input:mousepressed(x, y, button) end) end function love.mousereleased(x, y, button) _iterateGameGroup("input", function(input) input:mousereleased(x, y, button) end) end function love.quit() Net.disconnect() end
-- maths.lua lerp = {} function lerp.lerp(current, target, speed) return current * (1 - speed) + target * speed end return lerp
local r = require("restructure") local VoidPointer = r.VoidPointer describe('Pointer', function() describe('decode', function() it('should handle null pointers', function() local stream = r.DecodeStream.new(string.char(0)) local pointer = r.Pointer.new(r.uint8, r.uint8) assert.is_nil(pointer:decode(stream, {_startOffset = 50})) end) it('should use local offsets from start of parent by default', function() local stream = r.DecodeStream.new(string.char(1, 53)) local pointer = r.Pointer.new(r.uint8, r.uint8) assert.are_equal(53,pointer:decode(stream, {_startOffset = 0})) end) it('should support immediate offsets', function() local stream = r.DecodeStream.new(string.char(1, 53)) local pointer = r.Pointer.new(r.uint8, r.uint8, {type = 'immediate'}) assert.are_equal(53,pointer:decode(stream)) end) it('should support offsets relative to the parent', function() local stream = r.DecodeStream.new(string.char(0, 0, 1, 53)) stream.buffer.pos = 2 local pointer = r.Pointer.new(r.uint8, r.uint8, {type = 'parent'}) assert.are_equal(53,pointer:decode(stream, {parent = { _startOffset = 2}})) end) it('should support global offsets', function() local stream = r.DecodeStream.new(string.char(1, 2, 4, 0, 0, 0, 53)) local pointer = r.Pointer.new(r.uint8, r.uint8, {type = 'global'}) stream.buffer.pos = 2 assert.are_equal(53,pointer:decode(stream, { parent = { parent = {_startOffset = 2 } } })) end) it('should support offsets relative to a property on the parent', function() local stream = r.DecodeStream.new(string.char(1, 0, 0, 0, 0, 53)) local pointer = r.Pointer.new(r.uint8, r.uint8, {relativeTo = 'parent.ptr'}) assert.are_equal(53,pointer:decode(stream, {_startOffset = 0, parent = { ptr = 4 }})) end) it('should support returning pointer if there is no decode type', function() local stream = r.DecodeStream.new(string.char(4)) local pointer = r.Pointer.new(r.uint8, 'void') assert.are_equal(4,pointer:decode(stream, { _startOffset = 0 })) end) it('should support decoding pointers lazily #debug', function() local stream = r.DecodeStream.new(string.char(1, 53)) local struct = r.Struct.new({ { ptr = r.Pointer.new(r.uint8, r.uint8, {lazy = true}) } }) local res = struct:decode(stream) -- Object.getOwnPropertyDescriptor(res, 'ptr').get.should.be.a('function') -- Object.getOwnPropertyDescriptor(res, 'ptr').enumerable.should.equal(true) assert.are_equal(53,res.ptr) end) end) describe('size', function() it('should add to local pointerSize', function() local pointer = r.Pointer.new(r.uint8, r.uint8) local ctx = { pointerSize = 0} assert.are_equal(1,pointer:size(10, ctx)) assert.are_equal(1,ctx.pointerSize) end) it('should add to immediate pointerSize', function() local pointer = r.Pointer.new(r.uint8, r.uint8, {type = 'immediate'}) local ctx = {pointerSize = 0} assert.are_equal(1,pointer:size(10, ctx)) assert.are_equal(1,ctx.pointerSize) end) it('should add to parent pointerSize', function() local pointer = r.Pointer.new(r.uint8, r.uint8, {type = 'parent'}) local ctx = { parent = { pointerSize = 0 } } assert.are_equal(1,pointer:size(10, ctx)) assert.are_equal(1,ctx.parent.pointerSize) end) it('should add to global pointerSize', function() local pointer = r.Pointer.new(r.uint8, r.uint8, {type = 'global'}) local ctx = { parent = { parent = { parent = { pointerSize = 0 }}}} assert.are_equal(1,pointer:size(10, ctx)) assert.are_equal(1,ctx.parent.parent.parent.pointerSize) end) it('should handle void pointers', function() local pointer = r.Pointer.new(r.uint8, 'void') local ctx = { pointerSize = 0 } assert.are_equal(1,pointer:size(VoidPointer.new(r.uint8, 50), ctx)) assert.are_equal(1,ctx.pointerSize) end) it('should throw if no type and not a void pointer', function() local pointer = r.Pointer.new(r.uint8, 'void') local ctx = {pointerSize = 0} assert.has_error(function() pointer:size(30, ctx) end, "Must be a VoidPointer") end) it('should return a fixed size without a value', function() local pointer = r.Pointer.new(r.uint8, r.uint8) assert.are_equal(1,pointer:size()) end) end) describe('encode', function() it('should handle null pointers', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8) local ctx = { pointerSize = 0, startOffset = 0, pointerOffset = 0, pointers = {} } ptr:encode(stream, nil, ctx) assert.are_equal(string.char(0), stream:getContents()) assert.are_equal(0,ctx.pointerSize) end) it('should handle local offsets', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8) local ctx = { pointerSize = 0, startOffset = 0, pointerOffset = 1, pointers = {} } ptr:encode(stream, 10, ctx) assert.are_equal(2,ctx.pointerOffset) assert.are_equal(string.char(1), stream:getContents()) assert.are.same({ { type = r.uint8, val = 10, parent = ctx } }, ctx.pointers) end) it('should handle immediate offsets', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8, {type = 'immediate'}) local ctx = { pointerSize = 0, startOffset = 0, pointerOffset = 1, pointers = {} } ptr:encode(stream, 10, ctx) assert.are_equal(2,ctx.pointerOffset) assert.are.same({ { type = r.uint8, val = 10, parent = ctx } }, ctx.pointers) assert.are_equal(string.char(0), stream:getContents()) end) it('should handle immediate offsets', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8, {type = 'immediate'}) local ctx = { pointerSize= 0, startOffset= 0, pointerOffset= 1, pointers= {} } ptr:encode(stream, 10, ctx) assert.are_equal(2,ctx.pointerOffset) assert.are_same({ { type = r.uint8, val = 10, parent = ctx } },ctx.pointers) assert.are_equal(string.char(0),stream:getContents()) end) it('should handle offsets relative to parent', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8, {type = 'parent'}) local ctx = { parent = { pointerSize = 0, startOffset = 3, pointerOffset = 5, pointers = {} } } ptr:encode(stream, 10, ctx) assert.are_equal(6,ctx.parent.pointerOffset) assert.are.same(ctx.parent.pointers, { { type = r.uint8, val = 10, parent = ctx } }) assert.are_equal(string.char(2), stream:getContents()) end) it('should handle global offsets', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8, {type = 'global'}) local ctx = { parent = { parent = { parent = { pointerSize = 0, startOffset = 3, pointerOffset = 5, pointers = {} } } } } ptr:encode(stream, 10, ctx) assert.are_equal(6,ctx.parent.parent.parent.pointerOffset) assert.are.same({ { type = r.uint8, val = 10, parent = ctx } },ctx.parent.parent.parent.pointers) assert.are_equal(string.char(5), stream:getContents()) end) it('should support offsets relative to a property on the parent', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, r.uint8, {relativeTo = 'ptr'}) local ctx = { pointerSize = 0, startOffset = 0, pointerOffset = 10, pointers = {}, val = { ptr = 4 } } ptr:encode(stream, 10, ctx) assert.are_equal(11,ctx.pointerOffset) assert.are.same({ { type = r.uint8, val = 10, parent = ctx } },ctx.pointers) assert.are_equal(string.char(6), stream:getContents()) end) it('should support void pointers', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, 'void') local ctx = { pointerSize = 0, startOffset = 0, pointerOffset = 1, pointers = {} } ptr:encode(stream, VoidPointer.new(r.uint8, 55), ctx) assert.are_equal(2,ctx.pointerOffset) assert.are.same({ { type = r.uint8, val = 55, parent = ctx } },ctx.pointers) assert.are_equal(string.char(1), stream:getContents()) end) it('should throw if not a void pointer instance', function() local stream = r.EncodeStream.new() local ptr = r.Pointer.new(r.uint8, 'void') local ctx = { pointerSize = 0, startOffset = 0, pointerOffset = 1, pointers = {} } assert.has_error(function() ptr:encode(stream, 44, ctx) end, "Must be a VoidPointer") end) end) end)
---@class RDSGunmanInBathroom : zombie.randomizedWorld.randomizedDeadSurvivor.RDSGunmanInBathroom RDSGunmanInBathroom = {} ---@public ---@param arg0 BuildingDef ---@return void function RDSGunmanInBathroom:randomizeDeadSurvivor(arg0) end
collision = {} function collision.rect2(x1, y1, w1, h1, x2, y2, w2, h2) return (x1 <= x2 + w2) and (x1 + x2 >= x2) and (y1 <= y2 + h2) and (y2 + h2 > y2) end
hs.hotkey.alertDuration=0 hs.window.animationDuration = 0 white = hs.drawing.color.white black = hs.drawing.color.black blue = hs.drawing.color.blue osx_red = hs.drawing.color.osx_red osx_green = hs.drawing.color.osx_green osx_yellow = hs.drawing.color.osx_yellow tomato = hs.drawing.color.x11.tomato dodgerblue = hs.drawing.color.x11.dodgerblue firebrick = hs.drawing.color.x11.firebrick lawngreen = hs.drawing.color.x11.lawngreen lightseagreen = hs.drawing.color.x11.lightseagreen purple = hs.drawing.color.x11.purple royalblue = hs.drawing.color.x11.royalblue sandybrown = hs.drawing.color.x11.sandybrown black50 = {red=0,blue=0,green=0,alpha=0.5} hs.hotkey.bind({"alt", "shift"}, "R", "Reload Hammerspoon Configuration", function() hs.notify.new({title="Hammerspoon", informativeText="Config loaded"}):send() hs.reload() end) function reloadConfig(files) doReload = false for _,file in pairs(files) do if file:sub(-4) == ".lua" then doReload = true end end if doReload then hs.reload() end end hs.hotkey.bind({"alt", "shift"}, "L", function() hs.caffeinate.lockScreen() end) modal_list = {} module_list = { "modes/showhotkey", "modes/clipshow", "modes/hsearch", "modes/time", } applist = { {shortcut = 'i',appname = 'iTerm'}, {shortcut = 'l',appname = 'Sublime Text'}, {shortcut = 'f',appname = 'Finder'}, {shortcut = 's',appname = 'Safari'}, {shortcut = 'y',appname = 'YoMail'}, {shortcut = 't',appname = 'Telegram'}, {shortcut = 'a',appname = 'Android Studio'}, {shortcut = 'c',appname = 'IntelliJ IDEA CE'}, } for i=1,#module_list do require(module_list[i]) end if #modal_list > 0 then require("modalmgr") end
gpio.mode(4, gpio.OUTPUT) gpio.write(4, gpio.LOW) clientactive = false clientdns = false counter = 0 usefile = "" createap = function() wifi.setmode(wifi.SOFTAP) wifi.ap.config({ssid="open_internet",pwd=nil}) srv=net.createServer(net.TCP) srv:listen(80,function(conn) conn:on("receive", function(client,request) local current = tmr.time() while clientactive do if tmr.time()-current>2 then clientactive = false end end counter = counter + 1 clientactive = true gpio.write(4, gpio.HIGH) local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP"); if(method == nil)then _, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP"); end local _GET = {} if (vars ~= nil)then for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do _GET[k] = v end end if _GET.file == nil then _GET.file = "web.html" _GET.type = "html" end usefile = _GET.file print ("FILE: ".._GET.file) local header = "HTTP/1.1 200 OK\r\nContent-Type: text/".._GET.type.."\r\n\r\n" client:send(header) file.open(_GET.file, "r") local linesize = 1024 local linedata = file.read(linesize) local linecounter = 0 while linedata ~= nil do client:send(linedata) linecounter = linecounter + 1 file.seek("set", linesize*linecounter) linedata = file.read(linesize) print("Linecounter: ", linecounter) tmr.delay(10000) end file.close() collectgarbage() if _GET.type == "html" then local secs = tmr.now()/1000000 local minutes = secs / 60 client:send("<br /><strong>This gadget has served "..counter.." pages since reboot. Free RAM: "..node.heap().." bytes, uptime: "..minutes.." minutes and "..(secs-minutes*60).." seconds. Serving ".._GET.file..".</strong>") end tmr.delay(1000000) client:close() gpio.write(4, gpio.LOW) clientactive = false linedata = nil collectgarbage() --print ("Free: ", node.heap()) end) end) end function unhex(str) str = string.gsub (str, "(%x%x) ?", function(h) return string.char(tonumber(h,16)) end) return str end s=net.createServer(net.UDP) s:on("receive",function(s,c) local transaction_id=string.sub(c,1,2) local flags=string.sub(c,3,4) local questions=string.sub(c,5,6) local query = "" local raw_query = "" local j=13 while true do local byte = string.sub(c,j,j) j=j+1 raw_query = raw_query .. byte if byte:byte(1)==0x00 then break end for i=1,byte:byte(1) do byte = string.sub(c,j,j) j=j+1 raw_query = raw_query .. byte query = query .. byte end query = query .. '.' end query=query:sub(1,query:len()-1) local q_type = string.sub(c,j,j+1) j=j+2 if q_type == unhex("00 01") then local class = string.sub(c,j,j+1) local ip=unhex("C0 A8 04 01") local answers = unhex("00 01") flags = unhex("81 80") local resp=transaction_id..flags..questions..answers..unhex("00 00")..unhex("00 00")..raw_query..q_type..class resp=resp..unhex("c0 0c")..q_type..class..unhex("00 00 00 da")..unhex("00 04")..ip s:send(resp) collectgarbage() print("DNS, free:", node.heap()) end collectgarbage() end) s:listen(53) createap() print("listening, free:", node.heap())
RegisterNetEvent('wk:velocidade') AddEventHandler('wk:velocidade', function(carro) Citizen.InvokeNative( 0xB59E4BD37AE292DB, carro, 5.0) end)
function IncludeScanning() IncludePackage("scanning") local directory = path.join(_GARRYSMOD_COMMON_DIRECTORY, "include", "scanning") local _project = project() local _workspace = _project.workspace sysincludedirs(path.join(_GARRYSMOD_COMMON_DIRECTORY, "include")) links("scanning") filter("system:macosx") links("CoreServices.framework") group("garrysmod_common") project("scanning") kind("StaticLib") location(path.join(_GARRYSMOD_COMMON_DIRECTORY, "projects", os.target(), _ACTION)) targetdir(path.join("%{prj.location}", "%{cfg.architecture}", "%{cfg.buildcfg}")) debugdir(path.join("%{prj.location}", "%{cfg.architecture}", "%{cfg.buildcfg}")) objdir(path.join("!%{prj.location}", "%{cfg.architecture}", "%{cfg.buildcfg}", "intermediate", "%{prj.name}")) includedirs(directory) files({ path.join(directory, "*.hpp"), path.join(directory, "*.cpp") }) vpaths({ ["Header files/*"] = path.join(directory, "*.hpp"), ["Source files/*"] = path.join(directory, "*.cpp") }) filter("system:linux or macosx") links("dl") group("") project(_project.name) end
object_tangible_dungeon_mustafar_working_droid_factory_inhibitor_storage = object_tangible_dungeon_mustafar_working_droid_factory_shared_inhibitor_storage:new { } ObjectTemplates:addTemplate(object_tangible_dungeon_mustafar_working_droid_factory_inhibitor_storage, "object/tangible/dungeon/mustafar/working_droid_factory/inhibitor_storage.iff")
return function() local PromptInfo = require(script.Parent.PromptInfo) local AvatarEditorPrompts = script.Parent.Parent local Actions = AvatarEditorPrompts.Actions local CloseOpenPrompt = require(Actions.CloseOpenPrompt) local OpenPrompt = require(Actions.OpenPrompt) local PromptType = require(AvatarEditorPrompts.PromptType) local function countValues(t) local c = 0 for _, _ in pairs(t) do c = c + 1 end return c end it("should have the correct default values", function() local defaultState = PromptInfo(nil, {}) expect(type(defaultState)).to.equal("table") expect(type(defaultState.queue)).to.equal("table") expect(type(defaultState.infoQueue)).to.equal("table") expect(countValues(defaultState)).to.equal(2) expect(countValues(defaultState.queue)).to.equal(0) expect(countValues(defaultState.infoQueue)).to.equal(0) end) describe("OpenPrompt", function() it("should correctly open PromptType.SaveAvatar", function() local humanoidDescription = Instance.new("HumanoidDescription") local oldState = PromptInfo(nil, {}) local newState = PromptInfo(oldState, OpenPrompt( PromptType.SaveAvatar, { humanoidDescription = humanoidDescription, rigType = Enum.HumanoidRigType.R15, } )) expect(oldState).to.never.equal(newState) expect(countValues(newState.queue)).to.equal(0) expect(countValues(newState.infoQueue)).to.equal(0) expect(newState.promptType).to.equal(PromptType.SaveAvatar) expect(newState.humanoidDescription).to.equal(humanoidDescription) expect(newState.rigType).to.equal(Enum.HumanoidRigType.R15) end) it("should correctly open PromptType.CreateOutfit", function() local humanoidDescription = Instance.new("HumanoidDescription") local oldState = PromptInfo(nil, {}) local newState = PromptInfo(oldState, OpenPrompt( PromptType.CreateOutfit, { humanoidDescription = humanoidDescription, rigType = Enum.HumanoidRigType.R15, } )) expect(oldState).to.never.equal(newState) expect(countValues(newState.queue)).to.equal(0) expect(countValues(newState.infoQueue)).to.equal(0) expect(newState.promptType).to.equal(PromptType.CreateOutfit) expect(newState.humanoidDescription).to.equal(humanoidDescription) expect(newState.rigType).to.equal(Enum.HumanoidRigType.R15) end) it("should correctly open PromptType.AllowInventoryReadAccess", function() local oldState = PromptInfo(nil, {}) local newState = PromptInfo(oldState, OpenPrompt( PromptType.AllowInventoryReadAccess, {} )) expect(oldState).to.never.equal(newState) expect(countValues(newState)).to.equal(3) expect(countValues(newState.queue)).to.equal(0) expect(countValues(newState.infoQueue)).to.equal(0) expect(newState.promptType).to.equal(PromptType.AllowInventoryReadAccess) end) it("should correctly open PromptType.SetFavorite", function() local oldState = PromptInfo(nil, {}) local newState = PromptInfo(oldState, OpenPrompt( PromptType.SetFavorite, { itemId = 1337, itemType = Enum.AvatarItemType.Bundle, itemName = "Cool Bundle", isFavorited = true, } )) expect(oldState).to.never.equal(newState) expect(countValues(newState.queue)).to.equal(0) expect(countValues(newState.infoQueue)).to.equal(0) expect(newState.promptType).to.equal(PromptType.SetFavorite) expect(newState.itemId).to.equal(1337) expect(newState.itemType).to.equal(Enum.AvatarItemType.Bundle) expect(newState.itemName).to.equal("Cool Bundle") expect(newState.isFavorited).to.equal(true) end) it("should add a prompt to the queue if a prompt is already open", function() local oldState = PromptInfo(nil, {}) oldState = PromptInfo(oldState, OpenPrompt( PromptType.SetFavorite, { itemId = 1337, itemType = Enum.AvatarItemType.Bundle, itemName = "Cool Bundle", isFavorited = true, } )) local humanoidDescription = Instance.new("HumanoidDescription") local newState = PromptInfo(oldState, OpenPrompt( PromptType.CreateOutfit, { humanoidDescription = humanoidDescription, rigType = Enum.HumanoidRigType.R15, } )) expect(oldState).to.never.equal(newState) expect(countValues(newState.queue)).to.equal(1) expect(countValues(newState.infoQueue)).to.equal(1) expect(newState.queue[1]).to.equal(PromptType.CreateOutfit) expect(newState.infoQueue[1].humanoidDescription).to.equal(humanoidDescription) expect(newState.infoQueue[1].rigType).to.equal(Enum.HumanoidRigType.R15) end) end) describe("CloseOpenPrompt", function() it("should revert back to the default values if the queue is empty", function() local oldState = PromptInfo(nil, {}) local newState = PromptInfo(oldState, OpenPrompt( PromptType.SaveAvatar, { humanoidDescription = Instance.new("HumanoidDescription"), rigType = Enum.HumanoidRigType.R15, } )) expect(oldState).to.never.equal(newState) newState = PromptInfo(newState, CloseOpenPrompt()) expect(type(newState.queue)).to.equal("table") expect(type(newState.infoQueue)).to.equal("table") expect(countValues(newState)).to.equal(2) expect(countValues(newState.queue)).to.equal(0) expect(countValues(newState.infoQueue)).to.equal(0) end) it("should switch to the next prompt info in the queue if the queue isn't empty", function() local oldState = PromptInfo(nil, {}) oldState = PromptInfo(oldState, OpenPrompt( PromptType.SaveAvatar, { humanoidDescription = Instance.new("HumanoidDescription"), rigType = Enum.HumanoidRigType.R15, } )) local newState = PromptInfo(oldState, OpenPrompt( PromptType.SetFavorite, { itemId = 1337, itemType = Enum.AvatarItemType.Bundle, itemName = "Cool Bundle", isFavorited = true, } )) expect(oldState).to.never.equal(newState) expect(countValues(newState.queue)).to.equal(1) expect(countValues(newState.infoQueue)).to.equal(1) newState = PromptInfo(newState, CloseOpenPrompt()) expect(type(newState.queue)).to.equal("table") expect(type(newState.infoQueue)).to.equal("table") expect(countValues(newState.queue)).to.equal(0) expect(countValues(newState.infoQueue)).to.equal(0) expect(newState.promptType).to.equal(PromptType.SetFavorite) expect(newState.itemId).to.equal(1337) expect(newState.itemType).to.equal(Enum.AvatarItemType.Bundle) expect(newState.itemName).to.equal("Cool Bundle") expect(newState.isFavorited).to.equal(true) end) end) end
-- _ _ _ _ _ -- / \ | | | | | __ ___ _(_) -- / _ \ | | |_ | |/ _` \ \ / / | -- / ___ \| | | |_| | (_| |\ V /| | -- /_/ \_\_|_|\___/ \__,_| \_/ |_| -- -- github: @AllJavi -- -- Tags configuration local awful = require('awful') local gears = require('gears') local beautiful = require('beautiful') local icons = require('theme.icons') local sharedtags = require('sharedtags') local tags = { { icon = icons.ball_1, }, { icon = icons.ball_2, }, { icon = icons.ball_3, }, { icon = icons.ball_4, }, { icon = icons.ball_5, }, { icon = icons.ball_6, }, { icon = icons.ball_7, } } -- Set tags layout tag.connect_signal( 'request::default_layouts', function() awful.layout.append_default_layouts({ awful.layout.suit.tile, awful.layout.suit.spiral.dwindle, awful.layout.suit.floating, awful.layout.suit.max }) end ) -- Create tags for each screen screen.connect_signal( 'request::desktop_decoration', function(s) for i, tag in pairs(tags) do awful.tag.add( i, { icon = tag.icon, icon_only = true, layout = tag.layout or awful.layout.suit.spiral.dwindle, gap_single_client = true, gap = beautiful.useless_gap, screen = s, selected = i == 1 } ) end end )
-------------------------------------------------------------------------------- -- single-DEPRECATED-unstrict-mode-suite.lua: suite used for full suite tests -- This file is a part of lua-nucleo library -- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license) -------------------------------------------------------------------------------- local make_suite = select(1, ...) local test = make_suite( "single-DEPRECATED-unstrict-mode-suite", { to_test = true } ) test:set_strict_mode(false) test:DEPRECATED "to_test"
class "Logger" function Logger:__init() print("[Zombies] Logger Init") end function Logger:Write(p_Message) print("[Zombies] : " .. p_Message) end return Logger
object_tangible_furniture_flooring_tile_frn_flooring_tile_s45 = object_tangible_furniture_flooring_tile_shared_frn_flooring_tile_s45:new { } ObjectTemplates:addTemplate(object_tangible_furniture_flooring_tile_frn_flooring_tile_s45, "object/tangible/furniture/flooring/tile/frn_flooring_tile_s45.iff")
--- LUA wrapper for moveit planning environment -- dependency to tourch.ros -- @classmod Plan local ffi = require 'ffi' local torch = require 'torch' local ros = require 'ros' local moveit = require 'moveit.env' local utils = require 'moveit.utils' local gnuplot = require 'gnuplot' local Plan = torch.class('moveit.Plan', moveit) local f function init() local Plan_method_names = { "new", "delete", "release", "getStartStateMsg", "setStartStateMsg", "getTrajectoryMsg", "setTrajectoryMsg", "getPlanningTime", "plot", "convertTrajectoyMsgToTable", "convertStartStateMsgToTensor" } f = utils.create_method_table("moveit_Plan_", Plan_method_names) end init() function Plan:__init() self.o = f.new() self.moveit_msgs_RobotStateSpec = ros.get_msgspec('moveit_msgs/RobotState') self.moveit_msgs_RobotTrajectory = ros.get_msgspec('moveit_msgs/RobotTrajectory') end function Plan:cdata() return self.o end function Plan:release() f.release(self.o) end ---Create a ros message for the robot state: moveit_msgs/RobotState --@tparam[opt] ros.Message result --@treturn ros.Message function Plan:getStartStateMsg(result) local msg_bytes = torch.ByteStorage() f.getStartStateMsg(self.o, msg_bytes:cdata()) local msg = result or ros.Message(self.moveit_msgs_RobotStateSpec, true) msg:deserialize(msg_bytes) return msg end ---Set a ros message for the robot state: moveit_msgs/RobotState --@tparam[opt] ros.Message result function Plan:setStartStateMsg(input) if torch.isTypeOf(input, ros.Message) then local msg_bytes = input:serialize() msg_bytes:shrinkToFit() f.setStartStateMsg(self.o, msg_bytes.storage:cdata()) end end ---Create a ros message for the robot trajectory: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message result --@treturn ros.Message function Plan:getTrajectoryMsg(result) local msg_bytes = torch.ByteStorage() f.getTrajectoryMsg(self.o, msg_bytes:cdata()) local msg = result or ros.Message(self.moveit_msgs_RobotTrajectory, true) msg:deserialize(msg_bytes) return msg end ---Set a ros message for the robot trajectory: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message input function Plan:setTrajectoryMsg(input) if torch.isTypeOf(input, ros.Message) then local msg_bytes = input:serialize() msg_bytes:shrinkToFit() f.setTrajectoryMsg(self.o, msg_bytes.storage:cdata()) end end ---Get the number of seconds --@treturn number function Plan:getPlanningTime() return f.getPlannigTime(self.o) end ---Convert a ros message: moveit_msgs/RobotTrajectory --@tparam[opt] ros.Message trajectory_msg --@return Positions, Velocities and Labels (name of each joint) function Plan:convertTrajectoyMsgToTable(trajectory_msg) -- expect a Utils object local positions = {} local velocities = {} local accelerations = {} local efforts = {} local points = trajectory_msg.joint_trajectory.points for i=1,#points do positions[i] = points[i].positions velocities[i] = points[i].velocities accelerations[i] = points[i].accelerations efforts[i] = points[i].effort end return positions,velocities,accelerations,efforts end ---Convert a ros message: moveit_msgs/RobotState --@tparam[opt] ros.Message start_state --@return current position, velocity and labels (name of each joint) function Plan:convertStartStateMsgToTensor(start_state) -- expect a Utils object local position = start_state.joint_state.position local velocity = start_state.joint_state.velocity local labels = start_state.joint_state.names return position, velocity, labels end local function plot6DTrajectory(trajectory) if trajectory[1]:nDimension()==0 then return false end local history_size = #trajectory local q1={} local q2={} local q3={} local q4={} local q5={} local q6={} for i=1,history_size do q1[#q1+1] = trajectory[i][1] q2[#q2+1] = trajectory[i][2] q3[#q3+1] = trajectory[i][3] q4[#q4+1] = trajectory[i][4] q5[#q5+1] = trajectory[i][5] q6[#q6+1] = trajectory[i][6] end local q1_tensor = torch.Tensor(q1) local q2_tensor = torch.Tensor(q2) local q3_tensor = torch.Tensor(q3) local q4_tensor = torch.Tensor(q4) local q5_tensor = torch.Tensor(q5) local q6_tensor = torch.Tensor(q6) gnuplot.plot({'q1',q1_tensor}, {'q2',q2_tensor}, {'q3',q3_tensor},{'q4',q4_tensor},{'q5',q5_tensor},{'q6',q6_tensor}) --gnuplot.axis{0, history_size, -100, 100} gnuplot.grid(true) return true end ---Creates gnu plot for either position, velocity, acceleration and speed depending input --@tparam int type if 1: Positions are plotted, 2: velocities are plotted,3: accelarations are plotted,4: speed is plotted --@treturn boolean is true if the requested type of the plot is know. function Plan:plot(type) local msg msg= self:getTrajectoryMsg()--Position local positions,velocities,accelerations,efforts= self:convertTrajectoyMsgToTable(msg) gnuplot.figure(type) if type == 1 then if plot6DTrajectory(positions)then gnuplot.title('Trajectory position Data') else return false end elseif type == 2 then if plot6DTrajectory(velocities) then gnuplot.title('Trajectory velocity Data') else return false end elseif type == 3 then if plot6DTrajectory(accelerations) then gnuplot.title('Trajectory accelaration Data') else return false end elseif type ==4 then if velocities[1]:nDimension()==0 then return false end history_size = #velocities local q = {} for i=1,#velocities do q[#q+1] = torch.norm(velocities[i]) end local q_tensor = torch.Tensor(q) gnuplot.plot({'speed',q_tensor}) --gnuplot.axis{0, history_size, -100, 100} gnuplot.grid(true) gnuplot.title('Trajectory speed Data') else print("plot type not yet implemented") return false end return true end
function RequestExtraIntegerData(dataType, whichPlayer, param1, param2, param3, param4, param5, param6) end function RequestExtraBooleanData(dataType, whichPlayer, param1, param2, param3, param4, param5, param6) end function RequestExtraStringData(dataType, whichPlayer, param1, param2, param3, param4, param5, param6) end function RequestExtraRealData(dataType, whichPlayer, param1, param2, param3, param4, param5, param6) end function DzAPI_Map_MissionComplete(whichPlayer, key, value) end function DzAPI_Map_GetActivityData() end function DzAPI_Map_GetMapLevel(whichPlayer) end function DzAPI_Map_SaveServerValue(whichPlayer, key, value) end function DzAPI_Map_GetServerValue(whichPlayer, key) end function DzAPI_Map_GetServerValueErrorCode(whichPlayer) end function DzAPI_Map_Stat_SetStat(whichPlayer, key, value) end function DzAPI_Map_Ladder_SetStat(whichPlayer, key, value) end function DzAPI_Map_Ladder_SetPlayerStat(whichPlayer, key, value) end function DzAPI_Map_IsRPGLobby() end function DzAPI_Map_GetGameStartTime() end function DzAPI_Map_IsRPGLadder() end function DzAPI_Map_GetMatchType() end function DzAPI_Map_GetLadderLevel(whichPlayer) end function DzAPI_Map_IsRedVIP(whichPlayer) end function DzAPI_Map_IsBlueVIP(whichPlayer) end function DzAPI_Map_GetLadderRank(whichPlayer) end function DzAPI_Map_GetMapLevelRank(whichPlayer) end function DzAPI_Map_GetGuildName(whichPlayer) end function DzAPI_Map_GetGuildRole(whichPlayer) end function DzAPI_Map_GetMapConfig(key) end function DzAPI_Map_HasMallItem(whichPlayer, key) end function DzAPI_Map_ChangeStoreItemCount(team, itemId, count) end function DzAPI_Map_ChangeStoreItemCoolDown(team, itemId, seconds) end function DzAPI_Map_ToggleStore(whichPlayer, show) end function DzAPI_Map_GetServerArchiveEquip(whichPlayer, key) end function DzAPI_Map_GetServerArchiveDrop(whichPlayer, key) end function DzAPI_Map_OrpgTrigger(whichPlayer, key) end function DzAPI_Map_GetUserID(whichPlayer) end function DzAPI_Map_GetPlatformVIP(whichPlayer) end function DzAPI_Map_SavePublicArchive(whichPlayer, key, value) end function DzAPI_Map_GetPublicArchive(whichPlayer, key) end function DzAPI_Map_UseConsumablesItem(whichPlayer, key) end function DzAPI_Map_Statistics(whichPlayer, category, label) end function DzAPI_Map_SystemArchive(whichPlayer, key) end function DzAPI_Map_GlobalArchive(key) end function DzAPI_Map_SaveGlobalArchive(whichPlayer, key, value) end function DzAPI_Map_ServerArchive(whichPlayer, key) end function DzAPI_Map_SaveServerArchive(whichPlayer, key, value) end function DzAPI_Map_IsRPGQuickMatch() end function DzAPI_Map_GetMallItemCount(whichPlayer, key) end function DzAPI_Map_ConsumeMallItem(whichPlayer, key, count) end function DzAPI_Map_EnablePlatformSettings(whichPlayer, option, enable) end function DzAPI_Map_IsBuyReforged(whichPlayer) end function DzAPI_Map_PlayedGames(whichPlayer) end function DzAPI_Map_CommentCount(whichPlayer) end function DzAPI_Map_FriendCount(whichPlayer) end function DzAPI_Map_IsConnoisseur(whichPlayer) end function DzAPI_Map_IsBattleNetAccount(whichPlayer) end function DzAPI_Map_IsAuthor(whichPlayer) end function DzAPI_Map_CommentTotalCount() end
local GUI = require("GUI") ------------------------------------------------------------------------------------------ local workspace = GUI.workspace() workspace:addChild(GUI.panel(1, 1, workspace.width, workspace.height, 0x1E1E1E)) -- Add a palette window to workspace local palette = workspace:addChild(GUI.palette(3, 2, 0x9900FF)) -- Specify an .onTouch() callback-function to submit button palette.submitButton.onTouch = function() GUI.alert("You've been selected a color: " .. string.format("0x%X", palette.color.integer)) end ------------------------------------------------------------------------------------------ workspace:draw() workspace:start()
ENT.Type = "anim" ENT.Base = "cw_ammo_ent_base" ENT.PrintName = "Ammo crate" ENT.Author = "Spy" ENT.Spawnable = true ENT.AdminSpawnable = true ENT.Category = "CW 2.0 Ammo" ENT.ResupplyMultiplier = 12 -- max amount of mags the player can take from the ammo entity before it considers him as 'full' ENT.AmmoCapacity = 36 -- max amount of resupplies before this entity dissapears ENT.HealthAmount = 100 -- the health of this entity ENT.ExplodeRadius = 512 ENT.ExplodeDamage = 100 ENT.ResupplyTime = 0.4 -- time in seconds between resupply sessions ENT.Model = "models/Items/ammocrate_smg1.mdl"
pdata = {} tile = { AIR = 0, ROCK = 1, GRASS = 2, DIRT = 3, STONE = 4, WOOD = 5, SHRUB = 6, BLACKROCK = 7, WATER = 8, WATERSTILL = 9, LAVA = 10, LAVASTILL = 11, SAND = 12, GRAVEL = 13, GOLD = 14, IRON = 15, COAL = 16, TRUNK = 17, LEAF = 18, SPONGE = 19, GLASS = 20, RED = 21, ORANGE = 22, YELLOW = 23, LIGHTGREEN = 24, GREEN = 25, AQUAGREEN = 26, CYAN = 27, BLUE = 28, PURPLE = 29, INDIGO = 30, VIOLET = 31, MAGENTA = 32, PINK = 33, DARKGREY = 34, LIGHTGREY = 35, WHITE = 36, YELLOWFLOWER = 37, REDFLOWER = 38, MUSHROOM = 39, REDMUSHROOM = 40, SOLIDGOLD = 41, IRON = 42, BLOCKF = 43, BLOCKH = 44, BRICK = 45, TNT = 46, BOOKCASE = 47, MOSSY = 48, VERYBLACK = 49 } isclear = {} isclear[tile.AIR] = true isclear[tile.WATER] = true isclear[tile.WATERSTILL] = true isclear[tile.LEAF] = true isclear[tile.GLASS] = true isclear[tile.SHRUB] = true isclear[tile.YELLOWFLOWER] = true isclear[tile.REDFLOWER] = true isclear[tile.MUSHROOM] = true isclear[tile.REDMUSHROOM] = true print("const.lua initialised")
local component = require("component") local fs = require("filesystem") local shell = require("shell") local dirs, options = shell.parse(...) if #dirs == 0 then table.insert(dirs, ".") end io.output():setvbuf("line") for i = 1, #dirs do local path = shell.resolve(dirs[i]) if #dirs > 1 then if i > 1 then io.write("\n") end io.write(path, ":\n") end local list, reason = fs.list(path) if not list then io.write(reason .. "\n") else local function setColor(c) if component.gpu.getForeground() ~= c then io.stdout:flush() component.gpu.setForeground(c) end end local lsd = {} local lsf = {} for f in list do if f:sub(-1) == "/" then if options.p then table.insert(lsd, f) else table.insert(lsd, f:sub(1, -2)) end else table.insert(lsf, f) end end table.sort(lsd) table.sort(lsf) setColor(0x66CCFF) for _, d in ipairs(lsd) do if options.a or d:sub(1, 1) ~= "." then io.write(d .. "\t") if options.l or io.output() ~= io.stdout then io.write("\n") end end end for _, f in ipairs(lsf) do if fs.isLink(fs.concat(path, f)) then setColor(0xFFAA00) elseif f:sub(-4) == ".lua" then setColor(0x00FF00) else setColor(0xFFFFFF) end if options.a or f:sub(1, 1) ~= "." then io.write(f .. "\t") if options.l then setColor(0xFFFFFF) io.write(fs.size(fs.concat(path, f)), "\n") elseif io.output() ~= io.stdout then io.write("\n") end end end setColor(0xFFFFFF) if options.M then io.write("\n" .. tostring(#lsf) .. " File(s)") io.write("\n" .. tostring(#lsd) .. " Dir(s)") end if not options.l then io.write("\n") end end end io.output():setvbuf("no") io.output():flush()
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- local require = require local local_conf = require('apisix.core.config_local').local_conf() local http = require('resty.http') local core = require('apisix.core') local ipairs = ipairs local type = type local math = math local math_random = math.random local error = error local ngx = ngx local ngx_re = require('ngx.re') local ngx_timer_at = ngx.timer.at local ngx_timer_every = ngx.timer.every local string = string local string_sub = string.sub local str_byte = string.byte local str_find = core.string.find local log = core.log local default_weight local applications local auth_path = 'auth/login' local instance_list_path = 'ns/instance/list?healthyOnly=true&serviceName=' local host_pattern = [[^http(s)?:\/\/[a-zA-Z0-9-_.:\@]+$]] local prefix_pattern = [[^[\/a-zA-Z0-9-_.]+$]] local schema = { type = 'object', properties = { host = { type = 'array', minItems = 1, items = { type = 'string', pattern = host_pattern, minLength = 2, maxLength = 100, }, }, fetch_interval = {type = 'integer', minimum = 1, default = 30}, prefix = { type = 'string', pattern = prefix_pattern, maxLength = 100, default = '/nacos/v1/' }, weight = {type = 'integer', minimum = 1, default = 100}, timeout = { type = 'object', properties = { connect = {type = 'integer', minimum = 1, default = 2000}, send = {type = 'integer', minimum = 1, default = 2000}, read = {type = 'integer', minimum = 1, default = 5000}, }, default = { connect = 2000, send = 2000, read = 5000, } }, }, required = {'host'} } local _M = {} local function request(request_uri, path, body, method, basic_auth) local url = request_uri .. path log.info('request url:', url) local headers = {} headers['Accept'] = 'application/json' if basic_auth then headers['Authorization'] = basic_auth end if body and 'table' == type(body) then local err body, err = core.json.encode(body) if not body then return nil, 'invalid body : ' .. err end headers['Content-Type'] = 'application/json' end local httpc = http.new() local timeout = local_conf.discovery.nacos.timeout local connect_timeout = timeout.connect local send_timeout = timeout.send local read_timeout = timeout.read log.info('connect_timeout:', connect_timeout, ', send_timeout:', send_timeout, ', read_timeout:', read_timeout) httpc:set_timeouts(connect_timeout, send_timeout, read_timeout) local res, err = httpc:request_uri(url, { method = method, headers = headers, body = body, ssl_verify = true, }) if not res then return nil, err end if not res.body or res.status ~= 200 then return nil, 'status = ' .. res.status end local json_str = res.body local data, err = core.json.decode(json_str) if not data then return nil, err end return data end local function get_url(request_uri, path) return request(request_uri, path, nil, 'GET', nil) end local function post_url(request_uri, path, body) return request(request_uri, path, body, 'POST', nil) end local function get_token_param(base_uri, username, password) if not username or not password then return '' end local args = { username = username, password = password} local data, err = post_url(base_uri, auth_path .. '?' .. ngx.encode_args(args), nil) if err then log.error('nacos login fail:', username, ' ', password, ' desc:', err) return nil, err end return '&accessToken=' .. data.accessToken end local function get_group_and_namespace_param(service_info) if not service_info then return '' end local param = '' local namespace_id = service_info.namespace_id if namespace_id then param = '&namespaceId=' .. namespace_id end local group_name = service_info.group_name if group_name then param = param .. '&groupName=' .. group_name end return param end local function get_base_uri(host) -- TODO Add health check to get healthy nodes. local url = host[math_random(#host)] local auth_idx = str_find(url, '@') local username, password if auth_idx then local protocol_idx = str_find(url, '://') local protocol = string_sub(url, 1, protocol_idx + 2) local user_and_password = string_sub(url, protocol_idx + 3, auth_idx - 1) local arr = ngx_re.split(user_and_password, ':') if #arr == 2 then username = arr[1] password = arr[2] end local other = string_sub(url, auth_idx + 1) url = protocol .. other end if local_conf.discovery.nacos.prefix then url = url .. local_conf.discovery.nacos.prefix end if str_byte(url, #url) ~= str_byte('/') then url = url .. '/' end return url, username, password end local function iter_and_add_service(services, values) if not values then return end for _, value in core.config_util.iterate_values(values) do local conf = value.value if not conf then goto CONTINUE end local up if conf.upstream then up = conf.upstream else up = conf end if up.discovery_type == 'nacos' then core.table.insert(services, { service_name=up.service_name, namespace_id=up.namespace_id, group_name=up.group_name, discovery_host=up.discovery_host }) end ::CONTINUE:: end end local function get_nacos_services() local services = {} -- here we use lazy load to work around circle dependency local get_upstreams = require('apisix.upstream').upstreams local get_routes = require('apisix.router').http_routes local get_services = require('apisix.http.service').services local values = get_upstreams() iter_and_add_service(services, values) values = get_routes() iter_and_add_service(services, values) values = get_services() iter_and_add_service(services, values) return services end local function fetch_full_registry(premature) if premature then return end local up_apps = {} local infos = get_nacos_services() if #infos == 0 then applications = up_apps return end local token_param_map = {} local data, err for _, service_info in ipairs(infos) do local group_and_namespace_param = get_group_and_namespace_param(service_info); local md5_sum = ngx.md5(core.table.concat(service_info.discovery_host)) if not token_param_map[md5_sum] then if not service_info.discovery_host then service_info.discovery_host = local_conf.discovery.nacos.host end local base_uri, username, password = get_base_uri(service_info.discovery_host) local token_param, err = get_token_param(base_uri, username, password) if err then log.error('get_token_param error:', err) if not applications then applications = up_apps end return end token_param_map[md5_sum] = { base_uri = base_uri, token_param = token_param} end data, err = get_url(token_param_map[md5_sum].base_uri, instance_list_path .. service_info.service_name .. group_and_namespace_param .. token_param_map[md5_sum].token_param) if err then log.error('get_url:', instance_list_path, ' err:', err) if not applications then applications = up_apps end return end for _, host in ipairs(data.hosts) do local nodes = up_apps[service_info.service_name] if not nodes then nodes = {} up_apps[service_info.service_name] = nodes end core.table.insert(nodes, { host = host.ip, port = host.port, weight = host.weight or default_weight, }) end end applications = up_apps end function _M.nodes(service_name) local logged = false -- maximum waiting time: 5 seconds local waiting_time = 5 local step = 0.1 while not applications and waiting_time > 0 do if not logged then log.warn('wait init') logged = true end ngx.sleep(step) waiting_time = waiting_time - step end return applications[service_name] end function _M.init_worker() if not local_conf.discovery.nacos or not local_conf.discovery.nacos.host or #local_conf.discovery.nacos.host == 0 then error('do not set default nacos.host') return end local ok, err = core.schema.check(schema, local_conf.discovery.nacos) if not ok then error('invalid nacos configuration: ' .. err) return end default_weight = local_conf.discovery.nacos.weight log.info('default_weight:', default_weight) local fetch_interval = local_conf.discovery.nacos.fetch_interval log.info('fetch_interval:', fetch_interval) ngx_timer_at(0, fetch_full_registry) ngx_timer_every(fetch_interval, fetch_full_registry) end function _M.dump_data() return {config = local_conf.discovery.nacos, services = applications or {}} end return _M
if SERVER then AddCSLuaFile() end fw.dep(SHARED, "hook") fw.printers = fw.printers or {} fw.include_sh "printers_sh.lua" concommand.Add("fw_reloadprinters", function(ply, cmd, args) if IsValid(ply) and not ply:IsSuperAdmin() then pl:ChatPrint("insufficient privliages") return end fw.hook.GetTable().Initialize.LoadPrinters() end)
local piranhas = {} -- Written by Arturo Deza, 2016. -- set everything to zero at beginning before initialization -- Still have to configure an init.lua file. -- That seems the right way to do it. -- Will update it for next release. param = {pixel_res_width=0, pixel_res_height = 0, mon_width = 0, mon_height = 0, view_dist = 0, gamma_c = 0, psi_c = 0, cm_per_pixel = 0, deg_per_pixel = 0, orien = 0, wave_num = 0, freq_zero = 0, bandwidth = 0, visual_field_radius_in_deg = 0, fovea = 0, scale = 0, e0_in_deg = 0, visual = 0, visual_mask = 0 } function param:param_init_all(o) o = o or {} setmetatable(o, self) self.__index = self -- Computer parameters: self.pixel_res_width = 800 -- in pixels self.pixel_res_height = 800 -- in pixels self.mon_width = 37.5 -- in cm self.mon_height = 30 -- in cm self.view_dist = 64 -- in cm -- Computed from above: self.cm_per_pixel = (self.mon_width)/(self.pixel_res_width) self.deg_per_pixel = 2*math.deg(math.atan(self.cm_per_pixel/2/self.view_dist)) -- Gabor Filter parameters self.orien = 8 self.wave_num = 3 self.freq_zero = 1.0 self.bandwidth = 1.0 self.gamma_c = 1 -- gabor parameter self.psi_c = 0 -- gabor parameter -- Human parameters: -- Field of View Model Parameters: self.visual_field_radius_in_deg = 10.0 self.fovea = 1.0 self.scale = 0.5 -- e_0 set to 0.25 self.e0_in_deg = 0.25 -- visualization toggles self.visual = 1 self.visual_mask = 1 return o end -- Ouput of functions will be regions array function create_regions_vector_smooth(e0_in_deg,e_max,visual_field_width,deg_per_pixel,N_theta,N_e) --e0_in_deg = 0.25 --e_max = 10 --visual_field_width = 477 --deg_per_pixel = 0.042 --N_theta = 25 --N_e = 8 --require 'torch' --require 'gnuplot' -- Visual flag on? visual = 0 center_r = math.floor(0.5 + visual_field_width/2) center_c = center_r -- This is where the magic happens: regions = torch.zeros(torch.LongStorage{visual_field_width,visual_field_width,N_theta,N_e}) visual_field_width_half = math.floor(0.5 + visual_field_width*1.0/2) visual_field_max = math.sqrt(2*visual_field_width_half^2) x_vec = torch.linspace(-1,1,visual_field_width) y_vec = torch.zeros(visual_field_width) for i=1,visual_field_width do if (x_vec[i]>=-0.75) and (x_vec[i]<-0.25) then y_vec[i] = math.cos((math.pi/2)*(x_vec[i]+0.25)*2)^2 elseif (x_vec[i]>=-0.25) and (x_vec[i]<0.25) then y_vec[i] = 1.0 elseif (x_vec[i]>=0.25) and (x_vec[i]<0.75) then y_vec[i] = -(math.cos((math.pi/2)*(x_vec[i]+0.75)*2))^2 else -- Do Nothing end end -- Initalize hyperparameters for the h function: w_theta = 2*math.pi/N_theta t = 0.5 -- Creating the h function h = torch.zeros(visual_field_width) arg_h = torch.zeros(N_theta+1,visual_field_width + 1 + visual_field_width) h_vec = torch.zeros(N_theta+1,visual_field_width + 1 + visual_field_width) -- Trying to tie MATLAB implementation: -- for j=0,N_theta-1 do for j=0,N_theta do for i=1,visual_field_width + 1 + visual_field_width do arg_h[j+1][i] = (((i-1)*1.0/visual_field_width)*2*math.pi - ((w_theta*j)+(w_theta)*(1-t)/2))/w_theta if (arg_h[j+1][i]<-0.75) then h_vec[j+1][i] = 0 elseif (arg_h[j+1][i]>=-0.75) and (arg_h[j+1][i]<-0.25) then h_vec[j+1][i] = math.cos((math.pi/2)*((arg_h[j+1][i]+0.25)*2))^2 elseif (arg_h[j+1][i]>=-0.25) and (arg_h[j+1][i]<0.25) then h_vec[j+1][i] = 1 elseif (arg_h[j+1][i]>=0.25) and (arg_h[j+1][i]<0.75) then h_vec[j+1][i] = 1 - (math.cos((math.pi/2)*((arg_h[j+1][i]-0.75)*2)))^2 elseif (arg_h[j+1][i]>0.75) then h_vec[j+1][i] = 0 end end end -- Visualize the h_vec piranha function: if (visual==1) then -- Multiplot option/flag? To do! gnuplot.raw("set multiplot") for i=1,N_theta do gnuplot.plot(h_vec:select(1,i)) end gnuplot.raw("unset multiplot") end -- Initialize hyperparameters for g function e_0 = e0_in_deg e_r = visual_field_width*math.sqrt(2)/2*deg_per_pixel N_ecc = N_e w_ecc = (math.log(e_r)-math.log(e_0))/N_ecc arg_g = torch.zeros(N_ecc,visual_field_width+1+visual_field_width) g_vec = torch.zeros(N_ecc,visual_field_width+1+visual_field_width) -- Trying to match MATLAB version for j=0,N_ecc-1 do for i=1,visual_field_width + 1 + visual_field_width do -- The extra math.sqrt(2) is something you can play with depending if you want your FoV to be diagonal or horizontal. -- Controlling this is critical if you wish to tile/overflow the entire visual field (have no holes) --arg_g[j+1][i] = (math.log((i-1)*e_r/(visual_field_width*math.sqrt(2))) - (math.log(e_0)+w_ecc*(j+1)))/w_ecc arg_g[j+1][i] = (math.log((i-1)*e_r/(visual_field_width)) - (math.log(e_0)+w_ecc*(j+1)))/w_ecc if arg_g[j+1][i] < -0.75 then g_vec[j+1][i] = 0 elseif arg_g[j+1][i] >=0 -0.75 and arg_g[j+1][i]<-0.25 then g_vec[j+1][i] = (math.cos((math.pi/2)*((arg_g[j+1][i]+0.25)*2)))^2 elseif arg_g[j+1][i] >= -0.25 and arg_g[j+1][i] < 0.25 then g_vec[j+1][i] = 1 elseif arg_g[j+1][i] >= 0.25 and arg_g[j+1][i] < 0.75 then g_vec[j+1][i] = 1 - (math.cos((math.pi/2)*((arg_g[j+1][i]-0.75)*2)))^2 elseif arg_g[j+1][i] >= 0.75 then g_vec[j+1][i] = 0 end end end if visual == 1 then gnuplot.raw("set multiplot") for i=1,N_ecc do gnuplot.plot(g_vec:select(1,i)) end gnuplot.raw("unset multiplot") end -- Now get the x,y coordinates from the polar coordinates map = torch.zeros(visual_field_width,visual_field_width) map2 = torch.zeros(visual_field_width,visual_field_width) theta_temp_matrix = torch.zeros(visual_field_width,visual_field_width) ang_sign = 1 map_hybrid = torch.zeros(torch.LongStorage{visual_field_width,visual_field_width,N_theta+1,N_e}) map_hybrid2 = torch.zeros(torch.LongStorage{visual_field_width,visual_field_width,N_theta+1,N_e}) ang_hybrid = torch.zeros(visual_field_width,visual_field_width) ecc_hybrid = torch.zeros(visual_field_width,visual_field_width) true_ang_matrix = torch.zeros(visual_field_width,visual_field_width) ang_theta_matrix = torch.zeros(visual_field_width,visual_field_width) ecc_matrix = torch.zeros(visual_field_width,visual_field_width) theta_matrix = torch.zeros(visual_field_width,visual_field_width) for i=1,visual_field_width do for j=1,visual_field_width do --for i=232,232 do -- for j=238,238 do -- Optimized Implementation. -- Get Distance from center: dist = math.sqrt((visual_field_width_half-i)^2 + (visual_field_width_half-j)^2) -- Get Angle from center: if i~=visual_field_width_half and j~= visual_field_width_half then ang = torch.atan2(visual_field_width_half-i,j-visual_field_width_half) true_ang = ang if i < visual_field_width_half and j < visual_field_width_half then true_ang = math.pi + ang end if i>=visual_field_width_half and j >= visual_field_width_half then true_ang = math.pi + ang end if i<=visual_field_width_half and j > visual_field_width_half then true_ang = math.pi + ang end if i>visual_field_width_half and j <= visual_field_width_half then true_ang = math.pi + ang end else ang = 0 true_ang = ang end if i <= visual_field_width_half and j == visual_field_width_half then true_ang = torch.atan2(visual_field_width_half-i,1) + math.pi end if j > visual_field_width_half and i==visual_field_width_half then true_ang = torch.atan2(visual_field_width_half-i,1) + math.pi end if j == visual_field_width_half and i > visual_field_width_half then true_ang = torch.atan2(visual_field_width_half-i,1) + math.pi end -- Find Closest Angle match: ang_match = math.floor(0.5 + true_ang/(2*math.pi)*visual_field_width) -- Find Closest Eccentricity match: dist_match = math.floor(0.5 + dist/(visual_field_width/2)*visual_field_width) if ang_match<=0 then ang_match = 1 end if dist_match<=0 then dist_match = 1 end -- Get Hybrid Computations ang_hybrid[i][j] = math.ceil(true_ang/(2*math.pi)*N_theta) if ang_hybrid[i][j] <= 0 then ang_hybrid[i][j] = 1 end ecc_hybrid[i][j] = math.ceil(dist_match/visual_field_max/2*N_ecc) if ecc_hybrid[i][j]>N_ecc then ecc_hybrid[i][j] = N_ecc end -- Also find the theta value and eccentricity: theta_temp = math.ceil(ang_match/(visual_field_width/N_theta)) true_ang_matrix[i][j] = true_ang ang_theta_matrix[i][j] = math.floor(true_ang*N_theta/(2*math.pi)) + 1 temp_ecc = torch.nonzero(torch.eq(g_vec:select(2,dist_match),torch.max(g_vec:select(2,dist_match)))) if temp_ecc[1]:storage():size() > 1 then ecc_matrix[i][j] = 1 else ecc_matrix[i][j] = temp_ecc[1][1] end if ecc_matrix[i][j] == (N_theta+1) then ecc_matrix[i][j] = N_theta end --temp_theta = torch.nonzero(math.max(h_vec:select(2,ang_match))==h_vec:select(2,ang_match)) temp_theta = torch.nonzero(torch.eq(h_vec:select(2,ang_match),torch.max(h_vec:select(2,ang_match)))) if temp_theta[1]:storage():size() > 1 then theta_matrix[i][j] = 1 else theta_matrix[i][j] = temp_theta[1][1] end if theta_matrix[i][j] == (N_theta + 1) then theta_matrix[i][j] = 1 end h_buffer_indx = torch.nonzero(torch.gt(h_vec:select(2,ang_match),0)) g_buffer_indx = torch.nonzero(torch.gt(g_vec:select(2,dist_match),0)) -- Get Smooth shadow tones for every region: if h_buffer_indx:nDimension()>=1 and g_buffer_indx:nDimension()>=1 then for z1=1,h_buffer_indx[1]:storage():size() do for z2=1,g_buffer_indx[1]:storage():size() do map_hybrid2[i][j][h_buffer_indx[z1][1]][g_buffer_indx[z2][1]] = h_vec[h_buffer_indx[z1][1]][ang_match] * g_vec[g_buffer_indx[z2][1]][dist_match] end end end hybrid_buffer = map_hybrid2[{i,j,{},{}}] map2[i][j] = torch.max(hybrid_buffer:view(hybrid_buffer:nElement())) --print(i) end end --if visual then gnuplot.imagesc(map2,'color') regions = map_hybrid2 return regions end -- Output of function will be N_e and N_theta function get_pooling_parameters(scale,e0_in_deg,visual_field_radius_in_deg,deg_per_pixel) w_theta = scale/2 N_theta = math.floor(2*math.pi/w_theta) e_0 = e0_in_deg visual_field_width = math.floor(0.5+2*(visual_field_radius_in_deg/deg_per_pixel)) e_r = visual_field_width/2*deg_per_pixel w_ecc = scale N_e = math.ceil((math.log(e_r)-math.log(e_0))/w_ecc) -- Holding this computation from the MATLAB implementation return N_e, N_theta end return piranhas
--------------------------------------------------------------------------------------------------- ---player_bullet_prefab.lua ---author: Karl ---date: 2021.5.30 ---desc: ---modifier: --- Karl, 2021.7.16, split from player_shot_prefabs.lua --------------------------------------------------------------------------------------------------- local Prefab = require("core.prefab") ---@class Prefab.PlayerBullet:Prefab.Object ---@desc an object of this class is a player bullet that does damage and gets cancelled when the enemy is hit local M = Prefab.NewX(Prefab.Object) --------------------------------------------------------------------------------------------------- ---overridden in sub-classes function M:createCancelEffect() end function M:kill() self:createCancelEffect() end --------------------------------------------------------------------------------------------------- ---init ---@param attack number numeric value of the damage towards enemies ---@param del_on_colli boolean function M:init(attack, del_on_colli) self.attack = attack -- damage to the enemies on hit self.layer = LAYER_PLAYER_BULLET self.group = GROUP_PLAYER_BULLET self.del_on_colli = del_on_colli self.has_collided = false -- deal with multiple collisions in a single frame; set to true at the first collision end --------------------------------------------------------------------------------------------------- ---collision events function M:colli(other) local on_player_bullet_collision = other.onPlayerBulletCollision if on_player_bullet_collision then on_player_bullet_collision(other, self) end end function M:playNormalHitSound() PlaySound("se:damage00", 0.07, 0, true) end function M:playLowHpHitSound() PlaySound("se:damage01", 0.07, 0, true) end function M:onEnemyCollision(other) if self.has_collided == false then other:receiveDamage(self.attack) if self.del_on_colli then Kill(self) self.has_collided = true end end end Prefab.Register(M) return M
--========================================================== -- Re-written by bc1 using Notepad++ -- Caches stuff and defines AddSerialEventGameMessagePopup --========================================================== --print( "Lua memory in use: ", Locale.ToNumber( collectgarbage("count") * 1024, "#,###,###,###" ), "ContextID", ContextPtr:GetID(), "isHotLoad", ContextPtr:IsHotLoad() ) local GameInfo = GameInfoCache or GameInfo include "FLuaVector" local Color = Color local ColorWhite = Color( 1, 1, 1, 1 ) --========================================================== -- Minor lua optimizations --========================================================== local floor = math.floor local print = print local IsCiv5 = InStrategicView ~= nil local GameInfoIconTextureAtlases = GameInfo.IconTextureAtlases local GameInfoCivilizations = GameInfo.Civilizations local GameInfoPlayerColors = GameInfo.PlayerColors local GameInfoColors = GameInfo.Colors local GetCivilization = PreGame.GetCivilization local GetCivilizationColor = PreGame.GetCivilizationColor local IconTextureAtlasCache = setmetatable( {}, { __index = function( IconTextureAtlasCache, name ) local atlas = {} if name then for row in GameInfoIconTextureAtlases{ Atlas=name } do atlas[ row.IconSize ] = { row.Filename, row.IconsPerRow, row.IconsPerColumn } end IconTextureAtlasCache[ name ] = atlas end return atlas end}) -- cache only ingame, pregame player slots can change local Cache = Game and function( value, table, key ) table[ key ] = value return value end or function( value ) return value end local PlayerCivilizationInfo = setmetatable( {}, { __index = function( table, playerID ) return Cache( GameInfoCivilizations[ GetCivilization( playerID ) ], table, playerID ) end}) local function GetPlayerColor( playerID, RGB ) local playerCivilizationInfo = PlayerCivilizationInfo[ playerID ] local color = playerCivilizationInfo and ( GameInfoPlayerColors[ GetCivilizationColor( playerID ) ] or GameInfoPlayerColors[ playerCivilizationInfo.DefaultPlayerColor ] ) color = color and GameInfoColors[ color[ (playerCivilizationInfo.Type ~= "CIVILIZATION_MINOR")==(RGB==1) and "PrimaryColor" or "SecondaryColor" ] ] return color and Color( color.Red, color.Green, color.Blue, color.Alpha ) or Color( RGB, RGB, RGB, 1 ) end local IsPlayerUsingCustomColor = setmetatable( {}, { __index = function( table, playerID ) local playerCivilizationInfo = PlayerCivilizationInfo[ playerID ] local defaultColorSet = playerCivilizationInfo and GameInfoPlayerColors[ playerCivilizationInfo.DefaultPlayerColor ] return Cache( not defaultColorSet or playerCivilizationInfo.Type == "CIVILIZATION_MINOR" or defaultColorSet.ID ~= GetCivilizationColor( playerID ), table, playerID ) end}) PrimaryColors = setmetatable( {}, { __index = function( table, playerID ) return Cache( GetPlayerColor( playerID, 1 ), table, playerID ) end}) local PrimaryColors = PrimaryColors BackgroundColors = setmetatable( {}, { __index = function( table, playerID ) return Cache( GetPlayerColor( playerID, 0 ), table, playerID ) end}) local BackgroundColors = BackgroundColors --========================================================== -- AddSerialEventGameMessagePopup is a more efficient EUI -- substitute for Events.SerialEventGameMessagePopup.Add --========================================================== function AddSerialEventGameMessagePopup( handler, ... ) for _, popupType in pairs{...} do LuaEvents[popupType].Add( handler ) end LuaEvents.AddSerialEventGameMessagePopup( ... ) end --========================================================== function IconLookup( index, size, atlas ) local entry = (index or -1) >= 0 and IconTextureAtlasCache[ atlas ][ size ] if entry then local filename = entry[1] local numRows = entry[3] local numCols = entry[2] if filename and index < numRows * numCols then return { x=(index % numCols) * size, y = floor(index / numCols) * size }, filename end end end local IconLookup = IconLookup --========================================================== function IconHookup( index, size, atlas, control ) local entry = control and (index or -1) >= 0 and IconTextureAtlasCache[ atlas ][ size ] if entry then local filename = entry[1] local numRows = entry[3] local numCols = entry[2] if filename and index < numRows * numCols then control:SetTextureOffsetVal( (index % numCols) * size, floor(index / numCols) * size ) control:SetTexture( filename ) return true end print( "Could not hookup icon index:", index, "from atlas:", filename, "numRows:", numRows, "numCols:", numCols, "to control:", control, control:GetID() ) end print( "Could not hookup icon index:", index, "size:", size, "atlas:", atlas, "to control:", control, control and control:GetID() ) end local IconHookup = IconHookup --========================================================== -- This is a special case hookup for civilization icons -- that will take into account the fact that player colors -- are dynamically handed out --========================================================== local downSizes = { [80] = 64, [64] = 48, [57] = 45, [45] = 32, [32] = 24 } local textureOffsets = IsCiv5 and { [64] = 141, [48] = 77, [32] = 32, [24] = 0 } or { [64] = 200, [48] = 137, [45] = 80, [32] = 32, [24] = 0 } local unmetCiv = { PortraitIndex = IsCiv5 and 23 or 24, IconAtlas = "CIV_COLOR_ATLAS", AlphaIconAtlas = IsCiv5 and "CIV_COLOR_ATLAS" or "CIV_ALPHA_ATLAS" } function CivIconHookup( playerID, size, iconControl, backgroundControl, shadowIconControl, alwaysUseComposite, shadowedWhoCares, highlightControl ) -- eg backgroundControl 32, shadowIconControl 24, iconControl 24, highlightControl 32 local playerCivilizationInfo = PlayerCivilizationInfo[ playerID ] if playerCivilizationInfo then if alwaysUseComposite or IsPlayerUsingCustomColor[ playerID ] or not playerCivilizationInfo.IconAtlas then -- use the ugly composite version size = downSizes[ size ] or size if backgroundControl then backgroundControl:SetTexture( "CivIconBGSizes.dds" ) backgroundControl:SetTextureOffsetVal( textureOffsets[ size ] or 0, 0 ) backgroundControl:SetColor( BackgroundColors[ playerID ] ) end if highlightControl then highlightControl:SetTexture( "CivIconBGSizes_Highlight.dds" ) highlightControl:SetTextureOffsetVal( textureOffsets[ size ] or 0, 0 ) highlightControl:SetColor( PrimaryColors[ playerID ] ) highlightControl:SetHide( false ) end local textureOffset, textureAtlas = IconLookup( playerCivilizationInfo.PortraitIndex, size, playerCivilizationInfo.AlphaIconAtlas ) if iconControl then if textureAtlas then iconControl:SetTexture( textureAtlas ) iconControl:SetTextureOffset( textureOffset ) iconControl:SetColor( PrimaryColors[ playerID ] ) iconControl:SetHide( false ) else iconControl:SetHide( true ) end end if shadowIconControl then if textureAtlas then shadowIconControl:SetTexture( textureAtlas ) shadowIconControl:SetTextureOffset( textureOffset ) return shadowIconControl:SetHide( false ) else return shadowIconControl:SetHide( true ) end end return end else playerCivilizationInfo = unmetCiv end -- use the one-piece pretty color version if iconControl then iconControl:SetHide( true ) end if shadowIconControl then shadowIconControl:SetHide( true ) end if highlightControl then highlightControl:SetHide( true ) end if backgroundControl then backgroundControl:SetColor( ColorWhite ) return IconHookup( playerCivilizationInfo.PortraitIndex, size, playerCivilizationInfo.IconAtlas, backgroundControl ) end end --========================================================== -- This is a special case hookup for civilization icons -- that always uses the one-piece pretty color version --========================================================== function SimpleCivIconHookup( playerID, size, control ) local playerCivilizationInfo = PlayerCivilizationInfo[ playerID ] or unmetCiv return IconHookup( playerCivilizationInfo.PortraitIndex, size, playerCivilizationInfo.IconAtlas, control ) end
---@class RDSCorpsePsycho : zombie.randomizedWorld.randomizedDeadSurvivor.RDSCorpsePsycho RDSCorpsePsycho = {} ---@public ---@param arg0 BuildingDef ---@return void function RDSCorpsePsycho:randomizeDeadSurvivor(arg0) end
function exemplo() print("--------------------------") print("Lado positivo é que ainda retorna os valores que você quer passar") print("--------------------------") coroutine.yield(420) print("--------------------------") print("Isso retornou 420, ") print("você não teve nem q filtrar o primeiro retorno, ") print("ou seja, ") print("não precisou fazer retorno1, retorno2 = couritine.resume(threadExemplo)") print("--------------------------") end function love.load() threadExemplo = coroutine.wrap(exemplo) print("EXEMPLO 10") retorno = threadExemplo() print(retorno) print("RODANDOD NOVAMENTE") threadExemplo() print("FIM") end function love.update() end function love.draw() end
-- Zwave Metering Plug ver 1.1 -- Copyright 2021 jido1517 --F -- 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 ofF the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local capabilities = require "st.capabilities" --- @type st.zwave.defaults local defaults = require "st.zwave.defaults" --- @type st.zwave.Driver local ZwaveDriver = require "st.zwave.driver" --- @type st.zwave.CommandClass.Meter local Meter = (require "st.zwave.CommandClass.Meter")({ version=3 }) --- @type st.zwave.CommandClass local cc = require "st.zwave.CommandClass" local POWER_UNIT_WATT = "W" local ENERGY_UNIT_KWH = "kWh" local Notification = (require "st.zwave.CommandClass.Notification")({ version = 3 }) -------------------------------------------------------------------------------------------- -- Register message handlers and run driver -------------------------------------------------------------------------------------------- local function meter_report_handler(self, device, cmd) local event_arguments = nil if cmd.args.scale == Meter.scale.electric_meter.KILOWATT_HOURS then event_arguments = { value = cmd.args.meter_value, unit = ENERGY_UNIT_KWH } device:emit_event(capabilities.energyMeter.energy(event_arguments)) local cEnergy = cmd.args.meter_value * 1000 local pEnergy = cmd.args.previous_meter_value * 1000 local delta = cEnergy - pEnergy local delta_arguments = {deltaEnergy = delta, energy = cEnergy} device:emit_event(capabilities.powerConsumptionReport.powerConsumption(delta_arguments)) elseif cmd.args.scale == Meter.scale.electric_meter.WATTS then local event_arguments = { value = cmd.args.meter_value, unit = POWER_UNIT_WATT } device:emit_event(capabilities.powerMeter.power(event_arguments)) end end local function notification_report_handler(self, device, cmd) if cmd.args.notification_type == Notification.notification_type.POWER_MANAGEMENT then if cmd.args.event == Notification.event.power_management.AC_MAINS_DISCONNECTED then device:emit_event(capabilities.switch.switch.off()) elseif cmd.args.event == Notification.event.power_management.AC_MAINS_RE_CONNECTED then device:emit_event(capabilities.switch.switch.on()) end end end local function momentary_reset_handler(driver, device, command) device:send(Meter:Reset({})) device:refresh() end local device_added = function (self, device) device:refresh() end local driver_template = { zwave_handlers = { [cc.METER] = { [Meter.REPORT] = meter_report_handler }, [cc.NOTIFICATION] = { [Notification.REPORT] = notification_report_handler } }, supported_capabilities = { capabilities.switch, capabilities.powerMeter, capabilities.energyMeter, capabilities.refresh, capabilities.momentary, capabilities.powerConsumptionReport }, lifecycle_handlers = { added = device_added }, capability_handlers = { [capabilities.momentary.ID] = { [capabilities.momentary.commands.push.NAME] = momentary_reset_handler } }, sub_drivers = { require("dawon-plug") } } defaults.register_for_default_handlers(driver_template, driver_template.supported_capabilities) --- @type st.zwave.Driver local zwavedevice = ZwaveDriver("zwave_metering_plug_report", driver_template) zwavedevice:run()
-- Author: Hua Liang[Stupid ET] <et@everet.org> local TileMapScene = class("TileMapScene", function() local scene = cc.Scene:create() scene.name = "TileMapScene" return scene end) function TileMapScene:ctor() local visibleSize = cc.Director:getInstance():getVisibleSize() local origin = cc.Director:getInstance():getVisibleOrigin() local layer = cc.LayerColor:create(cc.c4b(100, 100, 100, 255)) local kTagTileMap = 100 local kRectBoy = 101 local boy = nil local map = nil local function createRectBoy() local textureBoy = cc.Director:getInstance():getTextureCache():addImage("boy.png") local rect = cc.rect(0, 0, 40, 40) local frame0 = cc.SpriteFrame:createWithTexture(textureBoy, rect) rect = cc.rect(40, 0, 40, 40) local frame1 = cc.SpriteFrame:createWithTexture(textureBoy, rect) local spriteBoy = cc.Sprite:createWithSpriteFrame(frame0) local size = spriteBoy:getContentSize() local animation = cc.Animation:createWithSpriteFrames({frame0,frame1}, 0.1) local animate = cc.Animate:create(animation) spriteBoy:setScale(32/40, 32/40) spriteBoy:runAction(cc.RepeatForever:create(animate)) spriteBoy:setTag(kRectBoy) spriteBoy:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height / 4 * 3) spriteBoy.speed = 0 return spriteBoy end local function getTilePos(pt) local x, y = pt.x, pt.y mapX, mapY = map:getPosition() local offsetX, offsetY = mapX - origin.x, mapY - origin.y -- offsetX, offsetY = 0, 0 x = (x - offsetX) / map:getTileSize().width y = (map:getMapSize().height * map:getTileSize().height - (y - offsetY)) / map:getTileSize().height return math.floor(x), math.ceil(y) end local stop = false local function update(delta) local g = 9.8 local x, y = boy:getPosition() boy.speed = boy.speed + g * delta x, y = x, y - boy.speed * delta local boyX, boyY = x, y local mapOffsetY = 0 if stop then return end -- x, y = x - boy:getContentSize().width / 2, y - boy:getContentSize().height / 2 tileX, tileY = getTilePos(cc.p(x, y)) log.debug("x,y (%s, %s)", x, y) log.debug("pos (%s, %s)", tileX, tileY) log.debug("map (%s, %s)", map:getPositionX(), map:getPositionY()) if boyY < 200 then mapOffsetY = boy:getPositionY() - boyY boyY = 200 end if 0 <= tileX and tileX < map:getMapSize().width and 0 <= tileY and tileY < map:getMapSize().height then local metaLayer = map:getLayer("Meta") local GID = metaLayer:getTileGIDAt(cc.p(tileX, tileY)) if GID and GID ~= 0 then log.debug("GID: %s", GID) local prop = map:getPropertiesForGID(GID) if prop and prop ~= 0 then collision = prop["Collidable"] log.debug("collision: %s", collision) if collision then boy.speed = 0 stop = true return end end end end map:setPositionY(map:getPositionY() + mapOffsetY) boy:setPosition(cc.p(boyX, boyY)) end local function onEnter() boy = createRectBoy() layer:addChild(boy, 2) map = cc.TMXTiledMap:create("desert.tmx") local metaLayer = map:getLayer("Meta") -- metaLayer:setVisible(false) map:setPosition(origin.x - (map:getMapSize().width * map:getTileSize().width - visibleSize.width) / 2 + boy:getContentSize().width / 2, origin.y - (map:getMapSize().height * map:getTileSize().height - visibleSize.height) / 2) layer:addChild(map, 0, kTagTileMap) -- map:runAction(cc.Sequence:create(cc.MoveBy:create(10, cc.p(0, -1200)), cc.MoveBy:create(10, cc.p(0, 1200)))) local schedulerID = cc.Director:getInstance():getScheduler():scheduleScriptFunc(update, 0, false) end local function onNodeEvent(event) if "enter" == event then onEnter() end end layer:registerScriptHandler(onNodeEvent) self:addChild(layer) end return TileMapScene
return function (names) local enum = {} for _, name in ipairs(names) do enum[name] = "CoreEnum (" .. name .. ")" end return enum end
local present, cursorword = pcall(require, "mini.cursorword") if not present then return end cursorword.setup({ delay = 10, })
require('nis.message_window') function silent_print(text) local current_window = vis.win vis:message(tostring(text)) if current_window ~= nil then vis.win = current_window end end function register_colors(window) local holes = {} local existant = {} local lexer = vis.lexers.load("nim", nil, true) for i = 0, 64, 1 do holes[i] = true end for name, id in pairs(lexer._TOKENSTYLES) do local style = vis.lexers['STYLE_'..name:upper()] or "" window:style_define(id, style) existant[style] = id holes[id] = nil end return lexer, setmetatable(existant, {__index = function(t, k) local free for freeid in pairs(holes) do free = freeid break end if window:style_define(free, k) then holes[free] = nil t[k] = free return free else return 65 -- UI_STYLE_DEFAULT end end}) end local function stylize(window, data) local start, finish, style, lexer, existent local result = data if not window.existent then lexer, existent = register_colors(window) else existent = window.existent lexer = vis.lexers.load("nim", nil, true) end local styles = lexer._TOKENSTYLES local paints = {} local tokenstart = 0 local currenttoken = "reset" repeat start, finish, style = result:find("\\e%[([^%]]+)%]", start) if start == nil then start = #result style = "reset" else result = result:sub(1, start-1)..result:sub(finish+1) end if currenttoken ~= "reset" then if currenttoken == "syntax" then --do syntax highlighting local tokens = lexer:lex(result:sub(tokenstart,start), 1) local tstart = tokenstart for i = 1, #tokens, 2 do local tend = tokenstart + tokens[i+1] - 1 if tend >= tstart then local name = tokens[i] local tstyle = styles[name] if tstyle ~= nil then table.insert(paints, {start = tstart-1, finish = tend-1, style = tstyle}) end end tstart = tend end elseif tokenstart == start and style ~= "syntax" then currenttoken = currenttoken..","..style else --do colorizing according the style table.insert(paints, {start = tokenstart-1, finish = start-2, style = existent[currenttoken]}) end end tokenstart = start currenttoken = style until start == #result window.existent = existent return result, paints end function stylized_print(notifier, text, append) local lastwin = vis.win notifier:show() -- the order matters! stylize needs to have window that it is stylizing in -- focus local curwin = notifier.win local cleantext, paints = stylize(curwin, text) if append then if not curwin.paints then curwin.paints = {} end local shift = #notifier.text for i, paint in pairs(paints) do table.insert(curwin.paints, { style = paint.style, start = paint.start + shift, finish = paint.finish + shift }) end else curwin.paints = paints end notifier:setText(cleantext, append) curwin.triggers.error_highlighter = function(win) for _, task in pairs(win.paints) do win:style(task.style, task.start, task.finish) end end if lastwin and vis.win ~= lastwin then vis.win = lastwin end end local colors = require('nis.graphic').colors function convertTermColors(line) local replacer = function(a) if a == "0" then return "\\e[reset]" end for i, v in pairs(colors) do if v.id == a then return "\\e["..v.description.."]" end end return "" end return line:gsub("%c", function (a) local code = a:byte() if code == 27 then return "{"..code.."}" else return a end end) :gsub("{27}%[([0-9]+)m", replacer) end
display.setStatusBar(display.HiddenStatusBar) local json = require('json') local widget = require('widget') local admob = require('plugin.admob') display.setDefault('background', 1) local xl, xr, y = display.contentWidth * .25, display.contentWidth * .75, display.contentCenterY local w, h = display.contentWidth * 0.4, 50 local admob_ids = { ios = { --banner = 'ca-app-pub-***', interstitial = 'ca-app-pub-***', rewarded = 'ca-app-pub-***' }, android = { --banner ='ca-app-pub-***', interstitial = 'ca-app-pub-***', rewarded = 'ca-app-pub-***' } } -- Leave only current system ids admob_ids = admob_ids[system.getInfo('platform')] or {} widget.newButton{ x = xl, y = y - 200, width = w, height = h, label = 'Init', onRelease = function() print('init') admob.init{ test = true, listener = function(event) print(json.prettify(event)) end } end} widget.newButton{ x = xr, y = y - 200, width = w, height = h, label = 'Load interstitial', onRelease = function() print('Load interstitial') admob.load{ type = 'interstitial', id = admob_ids.interstitial, keywords = {'puzzle', 'game'} } end} widget.newButton{ x = xl, y = y - 120, width = w, height = h, label = 'Load rewarded', onRelease = function() print('Load rewarded') admob.load{ type = 'rewarded', id = admob_ids.rewarded, keywords = {'puzzle', 'game'} } end} widget.newButton{ x = xr, y = y - 120, width = w, height = h, label = 'Show interstitial', onRelease = function() print('Show interstitial') admob.show('interstitial') end} widget.newButton{ x = xl, y = y - 40, width = w, height = h, label = 'Show rewarded', onRelease = function() print('Show rewarded') admob.show('rewarded') end} widget.newButton{ x = xr, y = y - 40, width = w, height = h, label = 'Is loaded interstitial?', onRelease = function() native.showAlert('admob', admob.is_loaded('interstitial') and 'Yes' or 'No', {'OK'}) end} widget.newButton{ x = xl, y = y + 40, width = w, height = h, label = 'Is loaded rewarded?', onRelease = function() native.showAlert('admob', admob.is_loaded('rewarded') and 'Yes' or 'No', {'OK'}) 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 requirekey.lua -- -- get require key from requireinfo function main(requireinfo, opt) opt = opt or {} local key = "" if opt.name then key = key .. "/" .. opt.name end if opt.plat then key = key .. "/" .. opt.plat end if opt.arch then key = key .. "/" .. opt.arch end if opt.version then key = key .. "/" .. opt.version end if requireinfo.label then key = key .. "/" .. requireinfo.label end if key:startswith("/") then key = key:sub(2) end local configs = requireinfo.configs if configs then local configs_order = {} for k, v in pairs(configs) do table.insert(configs_order, k .. "=" .. tostring(v)) end table.sort(configs_order) key = key .. ":" .. string.serialize(configs_order, true) end if opt.hash then if key == "" then key = "_" -- we need generate a fixed hash value end return hash.uuid(key):split("-", {plain = true})[1]:lower() else return key end end
local M = {} local skynet = require "skynet" local cur_dbs_id = 1 local db_service_cnt = tonumber(skynet.getenv "db_service_cnt") function M.call(cmd, ...) if cur_dbs_id > db_service_cnt then cur_dbs_id = 1 end local service_name = string.format(".db_service_%d", cur_dbs_id) local res = {pcall(skynet.call, service_name, "lua", cmd, ...)} if not res[1] then -- TODO: args to json print(string.format("new_dao call fail, cmd=%s, args=%s", cmd, {...})) return false, res[2] end cur_dbs_id = cur_dbs_id + 1 return true, table.unpack(res, 2) end return M
include("shared.lua") function ENT:Draw() self:DrawModel() end language.Add("ent_frisbee_sentient","Sentient Frisbee");
local Signal = require 'pong.vendor.hump.signal' local Timer = require 'pong.vendor.hump.timer' local Constants = require 'pong.constants' local Court = require 'pong.court' local Utils = require 'pong.utils' local BallBlur = require 'pong.entities.ball_blur' -- The ball that bounces back and forth. local Ball = {} Ball.__index = Ball Ball.RADIUS = 16 Ball.DIAMETER = Ball.RADIUS * 2 -- For bounding box calculation Ball.BLUR_SPAWN_FREQUENCY = 3 Ball.BOUNCE_COOLDOWN = 5 local SPEED = 512 -- Use a set of angles to keep the game interesting. -- No one wants to play pong when the angle is 89 degrees. -- The trig functions expect radian so use ratios of the unit circle. local ANGLES = { 1 / 12, -- 15 1 / 6, -- 30 1 / 4, -- 45 1 / 3, -- 60 } local function construct(cls, scene) local self = setmetatable({}, Ball) self.scene = scene self.state = Ball.READY_STATE -- Start the ball in the middle of the court. self.x = love.graphics.getWidth() / 2 self.y = love.graphics.getHeight() / 2 self.x_direction = Constants.RIGHT self.x_speed = 0 self.y_direction = Constants.DOWN self.y_speed = 0 -- Extra state is needed for a bounce cooldown. -- When the ball collides with a wall, the direction is flipped. -- Without any buffer, two collisions can occur back to back. -- This leads to a cycle where the ball starts toggling back -- and forth in direction and gets "stuck." self.just_x_bounced = false self.blur_counter = 0 return self end setmetatable(Ball, {__call = construct}) -- READY_STATE is the start of the game where the ball is waiting in the center. function Ball.READY_STATE(self, dt, key_state) if key_state['start'] then self.state = Ball.MOVING_STATE self.x_direction = Constants.X_DIRECTIONS[math.random(#Constants.X_DIRECTIONS)] self:set_speeds() end end -- MOVING_STATE is when the ball is in play. function Ball.MOVING_STATE(self, dt, key_state) self:update_collide_x(dt) self:update_collide_y(dt) self:spawn_blur() self.x = self.x + self.x_speed * self.x_direction * dt self.y = self.y + self.y_speed * self.y_direction * dt end -- SCORING_STATE is after the ball reached a goal. function Ball.SCORING_STATE(self, dt, key_state) self:update_collide_y(dt) self:spawn_blur() self.x = self.x + self.x_speed * self.x_direction * dt self.y = self.y + self.y_speed * self.y_direction * dt end function Ball:update(dt, key_state) self.state(self, dt, key_state) end -- Create a new ball blur periodically. function Ball:spawn_blur() if self.blur_counter == 0 then self.scene:add_entity(BallBlur(self.x, self.y, Ball.RADIUS)) end self.blur_counter = (self.blur_counter + 1 ) % Ball.BLUR_SPAWN_FREQUENCY end -- Update if the ball collides with the paddles or goals. function Ball:update_collide_x(dt) if self.just_x_bounced then return end self.just_x_bounced = Utils.has_any_collision(self, self.scene.paddles) if self.just_x_bounced then self.x_direction = self.x_direction * Constants.REVERSE Signal.emit('bounce') Timer.after(Ball.BOUNCE_COOLDOWN * dt, function() self.just_x_bounced = false end) elseif Utils.has_any_collision(self, self.scene.goals) then self.state = Ball.SCORING_STATE end end -- Update if the ball collides with the top or bottom. function Ball:update_collide_y(dt) local bounced = false local bbox = self:get_bbox() -- On collision, immediately adjust y so that there isn't any double -- collision stuff going on that will cause direction flipping. if bbox.y < Court.TOP then bounced = true self.y = Court.TOP + Ball.RADIUS elseif bbox.y + bbox.h > Court.BOTTOM then bounced = true self.y = Court.BOTTOM - Ball.RADIUS end if bounced then self.y_direction = self.y_direction * Constants.REVERSE Signal.emit('bounce') end end -- Get the bounding box. function Ball:get_bbox() return { x = self.x - Ball.RADIUS, y = self.y - Ball.RADIUS, h = Ball.DIAMETER, w = Ball.DIAMETER, } end -- Set x and y speeds to produce a given angle for the ball. function Ball:set_speeds() local angle = ANGLES[math.random(#ANGLES)] self.x_speed = SPEED * math.cos(math.pi * angle) self.y_speed = SPEED * math.sin(math.pi * angle) end function Ball:draw() love.graphics.circle('fill', self.x, self.y, Ball.RADIUS) end return Ball