content
stringlengths
5
1.05M
--[[- This provides a pure Lua implementation of the builtin @{require} function and @{package} library. Generally you do not need to use this module - it is injected into the every program's environment. However, it may be useful when building a custom shell or when running programs yourself. @module cc.require @since 1.88.0 @see using_require For an introduction on how to use @{require}. @usage Construct the package and require function, and insert them into a custom environment. local r = require "cc.require" local env = setmetatable({}, { __index = _ENV }) env.require, env.package = r.make(env, "/") -- Now we have our own require function, separate to the original. local r2 = env.require "cc.require" print(r, r2) ]] local expect = require and require("cc.expect") or dofile("rom/modules/main/cc/expect.lua") local expect = expect.expect local function preload(package) return function(name) if package.preload[name] then return package.preload[name] else return nil, "no field package.preload['" .. name .. "']" end end end local function from_file(package, env) return function(name) local sPath, sError = package.searchpath(name, package.path) if not sPath then return nil, sError end local fnFile, sError = loadfile(sPath, nil, env) if fnFile then return fnFile, sPath else return nil, sError end end end local function make_searchpath(dir) return function(name, path, sep, rep) expect(1, name, "string") expect(2, path, "string") sep = expect(3, sep, "string", "nil") or "." rep = expect(4, rep, "string", "nil") or "/" local fname = string.gsub(name, sep:gsub("%.", "%%%."), rep) local sError = "" for pattern in string.gmatch(path, "[^;]+") do local sPath = string.gsub(pattern, "%?", fname) if sPath:sub(1, 1) ~= "/" then sPath = fs.combine(dir, sPath) end if fs.exists(sPath) and not fs.isDir(sPath) then return sPath else if #sError > 0 then sError = sError .. "\n " end sError = sError .. "no file '" .. sPath .. "'" end end return nil, sError end end local function make_require(package) local sentinel = {} return function(name) expect(1, name, "string") if package.loaded[name] == sentinel then error("loop or previous error loading module '" .. name .. "'", 0) end if package.loaded[name] then return package.loaded[name] end local sError = "module '" .. name .. "' not found:" for _, searcher in ipairs(package.loaders) do local loader = table.pack(searcher(name)) if loader[1] then package.loaded[name] = sentinel local result = loader[1](name, table.unpack(loader, 2, loader.n)) if result == nil then result = true end package.loaded[name] = result return result else sError = sError .. "\n " .. loader[2] end end error(sError, 2) end end --- Build an implementation of Lua's @{package} library, and a @{require} -- function to load modules within it. -- -- @tparam table env The environment to load packages into. -- @tparam string dir The directory that relative packages are loaded from. -- @treturn function The new @{require} function. -- @treturn table The new @{package} library. local function make_package(env, dir) expect(1, env, "table") expect(2, dir, "string") local package = {} package.loaded = { _G = _G, bit = bit, bit32 = bit32, coroutine = coroutine, ffi = ffi, jit = jit, math = math, package = package, string = string, table = table, } package.path = "?;?.lua;?/init.lua;/rom/modules/main/?;/rom/modules/main/?.lua;/rom/modules/main/?/init.lua" if turtle then package.path = package.path .. ";/rom/modules/turtle/?;/rom/modules/turtle/?.lua;/rom/modules/turtle/?/init.lua" elseif commands then package.path = package.path .. ";/rom/modules/command/?;/rom/modules/command/?.lua;/rom/modules/command/?/init.lua" end package.config = "/\n;\n?\n!\n-" package.preload = {} package.loaders = { preload(package), from_file(package, env) } package.searchpath = make_searchpath(dir) return make_require(package), package end return { make = make_package }
local RunService = game:GetService("RunService") if not game:GetService("RunService"):IsServer() then error("CloudCore_Client can be only loaded in client context!") end local Module = {} local _Wrappers = script.Parent.CloudCore_Function:InvokeServer("GetWrappersInfo") for serviceName, members in pairs(_Wrappers) do local serviceFunction = script.Parent._Wrappers:FindFirstChild(serviceName) Module[serviceName] = setmetatable({}, { __index = function(_, Index, ...) if members[Index] then if members[Index] == "function" then return function(...) serviceFunction:InvokeServer(Index, ...) end ekse return serviceFunction:InvokeServer(Index, ...) end end end }) end function Module:GetService(Service) return Module[Service] or game:GetService(Service) end return Module
do --- mat4mul !private_G function mat4mul(a11, a21, a31, a41, a12, a22, a32, a42, a13, a23, a33, a43, a14, a24, a34, a44, b11, b21, b31, b41, b12, b22, b32, b42, b13, b23, b33, b43, b14, b24, b34, b44) return a11*b11+a21*b12+a31*b13+a41*b14, a11*b21+a21*b22+a31*b23+a41*b24, a11*b31+a21*b32+a31*b33+a41*b34, a11*b41+a21*b42+a31*b43+a41*b44, a12*b11+a22*b12+a32*b13+a42*b14, a12*b21+a22*b22+a32*b23+a42*b24, a12*b31+a22*b32+a32*b33+a42*b34, a12*b41+a22*b42+a32*b43+a42*b44, a13*b11+a23*b12+a33*b13+a43*b14, a13*b21+a23*b22+a33*b23+a43*b24, a13*b31+a23*b32+a33*b33+a43*b34, a13*b41+a23*b42+a33*b43+a43*b44, a14*b11+a24*b12+a34*b13+a44*b14, a14*b21+a24*b22+a34*b23+a44*b24, a14*b31+a24*b32+a34*b33+a44*b34, a14*b41+a24*b42+a34*b43+a44*b44 end local a11, a21, a31, a41 = 1, 0, 0, 0 local a12, a22, a32, a42 = 0, 1, 0, 0 local a13, a23, a33, a43 = 0, 0, 1, 0 local a14, a24, a34, a44 = 0, 0, 0, 1 local b11, b21, b31, b41 = 0, 0, -1, 0 local b12, b22, b32, b42 = 0, 1, 0, 0 local b13, b23, b33, b43 = 1, 0, 0, 0 local b14, b24, b34, b44 = 0, 0, 0, 1 for i = 1, 1000 do a11, a21, a31, a41, a12, a22, a32, a42, a13, a23, a33, a43, a14, a24, a34, a44 = mat4mul(a11, a21, a31, a41, a12, a22, a32, a42, a13, a23, a33, a43, a14, a24, a34, a44, b11, b21, b31, b41, b12, b22, b32, b42, b13, b23, b33, b43, b14, b24, b34, b44) end assert(a11 == 1) assert(a31 == 0) end
-- Routine for NPC "Helena" outside of her inn. velocity = 40 loadRoutine = function(R, W) if (W:isConditionFulfilled("npc_helena2","talked")) then R:setTilePosition(28,51) R:goToTile(28,49) R:setDisposed() else R:setTalkingActiveForce(true) R:setReloadEnabled(true) R:setTilePosition(28,51) R:setFacingDown() end end
str = "abcdefghijklmnopqrstuvwxyz" n, m = 5, 15 print( string.sub( str, n, m ) ) -- efghijklmno print( string.sub( str, n, -1 ) ) -- efghijklmnopqrstuvwxyz print( string.sub( str, 1, -2 ) ) -- abcdefghijklmnopqrstuvwxy pos = string.find( str, "i" ) if pos ~= nil then print( string.sub( str, pos, pos+m ) ) end -- ijklmnopqrstuvwx pos = string.find( str, "ijk" ) if pos ~= nil then print( string.sub( str, pos, pos+m ) ) end-- ijklmnopqrstuvwx -- Alternative (more modern) notation print ( str:sub(n,m) ) -- efghijklmno print ( str:sub(n) ) -- efghijklmnopqrstuvwxyz print ( str:sub(1,-2) ) -- abcdefghijklmnopqrstuvwxy pos = str:find "i" if pos then print (str:sub(pos,pos+m)) end -- ijklmnopqrstuvwx pos = str:find "ijk" if pos then print (str:sub(pos,pos+m)) end d-- ijklmnopqrstuvwx
-- Mercurio server overrides -- log_action logs the provided message with 'action' level. local function log_action(msg) minetest.log("action", "[MOD]mercurio: "..msg) end -- format_pos formats the given position with no decimal places local function fmt_pos(pos) return minetest.pos_to_string(pos, 0) end local function to_json(val) if val == nil then return "null" end local str = minetest.write_json(val) if str == nil then return "null" end return str end log_action("Initializing server overrides ...") -- PvP area as defined by the server settings. local pvp_center = minetest.setting_get_pos("pvp_area_center") local pvp_size = minetest.settings:get("pvp_area_size") log_action("PvP area with center at " .. fmt_pos(pvp_center) .. ", and " .. pvp_size .. " blocks.") minetest.register_on_punchplayer(function(player, hitter, time_from_last_punch, tool_capabilities, dir, damage) if not hitter:is_player() or not player:is_player() then return end local pos = player:get_pos() local bound_x = pos.x <= (pvp_center.x-pvp_size) or pos.x >= (pvp_center.x+pvp_size) local bound_y = pos.y <= (pvp_center.y-pvp_size) or pos.y >= (pvp_center.y+pvp_size) local bound_z = pos.z <= (pvp_center.z-pvp_size) or pos.z >= (pvp_center.z+pvp_size) if bound_x or bound_y or bound_z then return true end return end) -- Fix remaining unknown nodes after adding moreblocks local function fix_nodes(from, to) log_action("Fixing unknown node using alias from "..from..", to "..to) minetest.register_alias(from, to) end fix_nodes("ethereal:redwood_wood_micropanel", "ethereal:panel_redwood_wood_1") fix_nodes("ethereal:redwood_wood_microslab", "ethereal:slab_redwood_wood_1") fix_nodes("stairs:stair_red", "bakedclay:stair_baked_clay_red") fix_nodes("stairs:stair_inner_red","bakedclay:stair_baked_clay_red_inner") fix_nodes("stairs:stair_outer_red","bakedclay:stair_baked_clay_red_outer") fix_nodes("stairs:stair_orange", "bakedclay:stair_baked_clay_orange") fix_nodes("stairs:stair_inner_orange","bakedclay:stair_baked_clay_orange_inner") fix_nodes("stairs:stair_outer_orange","bakedclay:stair_baked_clay_orange_outer") fix_nodes("stairs:stair_grey", "bakedclay:stair_baked_clay_grey") fix_nodes("stairs:stair_inner_grey","bakedclay:stair_baked_clay_grey_inner") fix_nodes("stairs:stair_outer_grey","bakedclay:stair_baked_clay_grey_outer") fix_nodes("stairs:slab_red", "bakedclay:slab_baked_clay_red") fix_nodes("bakedclay:red_microslab", "bakedclay:slab_baked_clay_red_1") fix_nodes("stairs:slab_orange", "bakedclay:slab_baked_clay_orange") fix_nodes("bakedclay:orange_microslab","bakedclay:slab_baked_clay_orange_1") fix_nodes("stairs:slab_grey", "bakedclay:slab_baked_clay_grey") fix_nodes("bakedclay:grey_microslab", "bakedclay:slab_baked_clay_grey_1") fix_nodes("stairs:stair_Adobe", "building_blocks:stair_Adobe") -- Removes surprise blocks replacing them with air fix_nodes("tsm_surprise:question", "air") -- Remove unknown entities local function remove_entity(name) log_action("Registering entities with name=" .. name .. " for removal.") minetest.register_entity(name, { on_activate = function(self, dtime, staticdata) local o = self.object local pos = fmt_pos(o:get_pos()) log_action("Removing entity " .. self.name .. " at " .. pos) o:remove() end }) end remove_entity(":dmobs:nyan") remove_entity(":loot_crates:common") remove_entity(":loot_crates:uncommon") remove_entity(":loot_crates:rare") -- Spawn overrides local _orig_spawn_check = mobs.spawn_abm_check local function mercurio_spawn_abm_check(self, pos, node, name) if name == "nether_mobs:netherman" then if pos.y >= -3000 then return true end end return _orig_spawn_check(pos, node, name) end mobs.spawn_abm_check = mercurio_spawn_abm_check -- Debug spawning mobs from mobs_redo: log_action("mobs.spawning_mobs = " .. minetest.write_json(mobs.spawning_mobs)) -- ABM to fix Nether unknown blocks already created minetest.register_abm({ label = "Fix unknown nodes bellow Nether", nodenames = {"nether:native_mapgen"}, interval = 1.0, chance = 1, catch_up = true, action = function(pos, node, active_object_count, active_object_count_wider) if pos.y >= -11000 then return end log_action("Fixing Nether node node at pos "..to_json(pos)) minetest.set_node(pos, {name="default:stone"}) end, }) log_action("Server overrides loaded!")
Locales['pl'] = { ['have_withdrawn'] = 'wyciągnąłeś/aś ~y~x%s~s~ ~b~%s~s~', ['have_deposited'] = 'zdeponowałeś/aś ~y~x%s~s~ ~b~%s~s~', ['free_prop'] = 'wolne mieszkanie', ['property'] = 'mieszkanie', ['enter'] = 'wejdz', ['move_out'] = 'move out from property', ['move_out_sold'] = 'sell property for <span style="color:green;">$%s</span>', ['moved_out'] = 'you moved out and do no longer rent the property.', ['moved_out_sold'] = 'you have sold the property for ~g~$%s~s~', ['buy'] = 'buy property for <span style="color:green;">$%s</span>', ['buy_for'] = 'kupiłeś/aś mieszkanie za ~g~$%s~s~', ['rent'] = 'rent property for <span style="color:green;">$%s</span> / week', ['rent_for'] = 'wynająłeś/aś mieszkanie za ~g~$%s~s~', ['press_to_menu'] = 'wciśnij ~INPUT_CONTEXT~ aby otworzyć menu', ['owned_properties'] = 'twoje mieszkania', ['available_properties'] = 'dostępne mieszkania', ['invite_player'] = 'zaproś gracza', ['you_invited'] = 'zaprosiłeś/aś ~y~%s~s~ do swojego mieszkania', ['player_clothes'] = 'ubrania', ['remove_cloth'] = 'usuń ubrania', ['removed_cloth'] = 'te ubrania zostały usunięte z twojej garderoby!', ['remove_object'] = 'usuń objekt', ['deposit_object'] = 'deponuj objekt', ['invite'] = 'zaproś', ['dirty_money'] = 'brudne pieniądze: <span style="color:red;">$%s</span>', ['inventory'] = 'ekwipunek', ['amount'] = 'suma?', ['amount_invalid'] = 'nieprawidłowa suma', ['press_to_exit'] = 'wciśnij ~INPUT_CONTEXT~ aby wyjść z mieszkania', ['not_enough'] = 'nie posiadasz wystarczająco pieniędzy', ['invalid_quantity'] = 'nieprawidłowa ilość', ['paid_rent'] = 'you paid your rent at ~g~$%s~s~ for ~y~%s~s~', ['paid_rent_evicted'] = 'you have been ~o~evicted~s~ from ~y~%s~s~ for not affording rent at ~g~$%s~s~', ['not_enough_in_property'] = 'nie ma wystarczająco ~r~tego przedmiotu~s~ w mieszkaniu!', ['player_cannot_hold'] = '~r~nie masz~s~ wystarczająco ~y~wolnego~s~ miejsca w ekwipunku!', }
--[[ This file is part of halimede. It is subject to the licence terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene/halimede/master/COPYRIGHT. No part of halimede, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. Copyright © 2015 The developers of halimede. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/pallene/halimede/master/COPYRIGHT. ]]-- local halimede = require('halimede') local assert = halimede.assert local Path = halimede.io.paths.Path local openBinaryFileForReading = halimede.io.FileHandleStream.openBinaryFileForReading local execute = halimede.luacode.execute assert.globalTableHasChieldFieldOfTypeFunctionOrCall('string', 'gsub') local function removeInitialShaBang(fileContents) return fileContents:gsub('^#![^\n]*\n', '') end local function executeFromFile(fileDescription, luaCodeFilePath, environment) assert.parameterTypeIsString('fileDescription', fileDescription) assert.parameterTypeIsInstanceOf('luaCodeFilePath', luaCodeFilePath, Path) assert.parameterTypeIsTable('environment', environment) luaCodeFilePath:assertIsFilePath('luaCodeFilePath') local luaCodeStringWithAnyLeadingShaBang = openBinaryFileForReading(luaCodeFilePath, fileDescription):readAllRemainingContentsAndClose() local luaCodeString = removeInitialShaBang(luaCodeStringWithAnyLeadingShaBang) return execute(luaCodeString, fileDescription, luaCodeFilePath:toString(true), environment) end halimede.modulefunction(executeFromFile)
local E, C, L = select(2, ...):unpack() if not C.actionbar.styles.cooldown.enable then return end ---------------------------------------------------------------------------------------- -- Cooldown count (modified from tullaCC) ---------------------------------------------------------------------------------------- local _G = _G local CreateFrame = CreateFrame local GetTime = GetTime local C_Timer_After = C_Timer.After local hooksecurefunc = hooksecurefunc local getmetatable = getmetatable local pairs = pairs local floor, max = math.floor, math.max local round = function(x) return floor(x + 0.5) end local UIParent = UIParent --sexy constants! local ICON_SIZE = 36 --the normal size for an icon (don't change this) local DAY, HOUR, MINUTE = 86400, 3600, 60 --used for formatting text local DAYISH, HOURISH, MINUTEISH = 3600 * 23.5, 60 * 59.5, 59.5 --used for formatting text at transition points local HALFDAYISH, HALFHOURISH, HALFMINUTEISH = DAY / 2 + 0.5, HOUR / 2 + 0.5, MINUTE / 2 + 0.5 --used for calculating next update times local MIN_DELAY = 0.01 local cfg = C.actionbar.styles.cooldown local Timer = {} local timers = {} --returns both what text to display, and how long until the next update local function getTimeText(s) --format text as seconds when at 90 seconds or below if s < MINUTEISH then --format text as minutes when below an hour local seconds = round(s) local formatString = seconds > cfg.expiringDuration and cfg.secondsFormat or cfg.expiringFormat return formatString, seconds, s - (seconds - 0.51) elseif s < HOURISH then --format text as hours when below a day local minutes = round(s / MINUTE) return cfg.minutesFormat, minutes, minutes > 1 and (s - (minutes * MINUTE - HALFMINUTEISH)) or (s - MINUTEISH) elseif s < DAYISH then --format text as days local hours = round(s / HOUR) return cfg.hoursFormat, hours, hours > 1 and (s - (hours * HOUR - HALFHOURISH)) or (s - HOURISH) else local days = round(s / DAY) return cfg.daysFormat, days, days > 1 and (s - (days * DAY - HALFDAYISH)) or (s - DAYISH) end end function Timer.SetNextUpdate(self, duration) C_Timer_After(max(duration, MIN_DELAY), self.OnTimerDone) end --stops the timer function Timer.Stop(self) self.enabled = nil self.start = nil self.duration = nil self:Hide() end function Timer.UpdateText(self) local remain = self.enabled and (self.duration - (GetTime() - self.start)) or 0 if round(remain) > 0 then if (self.fontScale * self:GetEffectiveScale() / UIParent:GetScale()) < cfg.minScale then self.text:SetText("") Timer.SetNextUpdate(self, 1) else local formatStr, time, timeUntilNextUpdate = getTimeText(remain) self.text:SetFormattedText(formatStr, time) Timer.SetNextUpdate(self, timeUntilNextUpdate) end else Timer.Stop(self) end end --forces the given timer to update on the next frame function Timer.ForceUpdate(self) Timer.UpdateText(self) self:Show() end --adjust font size whenever the timer's parent size changes --hide if it gets too tiny function Timer.OnSizeChanged(self, width, _) local fontScale = round(width) / ICON_SIZE if fontScale == self.fontScale then return end self.fontScale = fontScale if fontScale < cfg.minScale then self:Hide() else self.text:SetFont(cfg.fontFace, fontScale * cfg.fontSize, "OUTLINE") self.text:SetShadowColor(0, 0, 0, 0.8) self.text:SetShadowOffset(1, -1) if self.enabled then Timer.ForceUpdate(self) end end end --returns a new timer object function Timer.Create(cooldown) --a frame to watch for OnSizeChanged events --needed since OnSizeChanged has funny triggering if the frame with the handler is not shown local scaler = CreateFrame("Frame", nil, cooldown) scaler:SetAllPoints(cooldown) local timer = CreateFrame("Frame", nil, scaler) timer:Hide() timer:SetAllPoints(scaler) timer.OnTimerDone = function() Timer.UpdateText(timer) end local text = timer:CreateFontString(nil, "OVERLAY") text:SetPoint("CENTER", 0, 0) text:SetFont(cfg.fontFace, cfg.fontSize, "OUTLINE") timer.text = text Timer.OnSizeChanged(timer, scaler:GetSize()) scaler:SetScript("OnSizeChanged", function(_, ...) Timer.OnSizeChanged(timer, ...) end) -- prevent display of blizzard cooldown text cooldown:SetHideCountdownNumbers(true) timers[cooldown] = timer return timer end function Timer.Start(cooldown, start, duration, ...) --start timer if start > 0 and duration > cfg.minDuration and (not cooldown.noCooldownCount) then --stop timer cooldown:SetDrawBling(cfg.drawBling) cooldown:SetDrawSwipe(cfg.drawSwipe) cooldown:SetDrawEdge(cfg.drawEdge) local timer = timers[cooldown] or Timer.Create(cooldown) timer.enabled = true timer.start = start timer.duration = duration Timer.UpdateText(timer) if timer.fontScale >= cfg.minScale then timer:Show() end else local timer = timers[cooldown] if timer then Timer.Stop(timer) end end end local f = CreateFrame('Frame') f:RegisterEvent('PLAYER_ENTERING_WORLD') f:SetScript('OnEvent', function() for _, timer in pairs(timers) do Timer.ForceUpdate(timer) end end) hooksecurefunc(getmetatable(_G["ActionButton1Cooldown"]).__index, "SetCooldown", Timer.Start)
local state = require("loaded_state") local placementUtils = require("placement_utils") local layerHandlers = require("layer_handlers") local viewportHandler = require("viewport_handler") local keyboardHelper = require("keyboard_helper") local configs = require("configs") local utils = require("utils") local toolUtils = require("tool_utils") local history = require("history") local snapshotUtils = require("snapshot_utils") local tool = {} tool._type = "tool" tool.name = "placement" tool.group = "placement" tool.image = nil tool.layer = "entities" tool.validLayers = { "entities", "triggers", "decalsFg", "decalsBg" } local placementsAvailable = nil local placementTemplate = nil local placementCurrentX = 0 local placementCurrentY = 0 local placementDragStartX = 0 local placementDragStartY = 0 local placementRectangle = nil local placementDragCompleted = false local function getCurrentPlacementType() local placementInfo = placementTemplate and placementTemplate.placement local placementType = placementInfo and placementInfo.placementType return placementType end local function getCursorGridPosition(x, y) local precise = keyboardHelper.modifierHeld(configs.editor.precisionModifier) if precise then return x, y else return math.floor((x + 4) / 8) * 8, math.floor((y + 4) / 8) * 8 end end local function placeItemWithHistory(room) local snapshot = snapshotUtils.roomLayerSnapshot(function() placementUtils.placeItem(room, tool.layer, utils.deepcopy(placementTemplate.item)) end, room, tool.layer, "Placement") history.addSnapshot(snapshot) end local function dragStarted(x, y) x, y = getCursorGridPosition(x, y) placementRectangle = utils.rectangle(x, y, 0, 0) placementDragCompleted = false placementDragStartX = x placementDragStartY = y end local function dragChanged(x, y, width, height) if placementRectangle then x, y = getCursorGridPosition(x, y) width, height = getCursorGridPosition(width, height) -- Only update if needed if x ~= placementRectangle.x or y ~= placementRectangle.y or width ~= placementRectangle.width or height ~= placementRectangle.height then placementRectangle = utils.rectangle(x, y, width, height) end end end local function dragFinished() local room = state.getSelectedRoom() local placementType = getCurrentPlacementType() if placementType == "rectangle" or placementType == "line" then placeItemWithHistory(room) toolUtils.redrawTargetLayer(room, tool.layer) end placementDragCompleted = true end local function mouseMoved(x, y) placementCurrentX = x placementCurrentY = y end local function placePointPlacement() local room = state.getSelectedRoom() local placementType = getCurrentPlacementType() if placementType == "point" then placeItemWithHistory(room) toolUtils.redrawTargetLayer(room, tool.layer) end end -- TODO - Clean up local function getPlacementOffset() local precise = keyboardHelper.modifierHeld(configs.editor.precisionModifier) local placementType = getCurrentPlacementType() if placementType == "rectangle" or placementType == "line" then if placementRectangle and not placementDragCompleted then return placementRectangle.x, placementRectangle.y end end return getCursorGridPosition(placementCurrentX, placementCurrentY) end local function updatePlacementDrawable() if placementTemplate then local target = placementTemplate.item._name or placementTemplate.item.texture local drawable = placementUtils.getDrawable(tool.layer, target, state.getSelectedRoom(), placementTemplate.item) placementTemplate.drawable = drawable end end local function updatePointPlacement(template, item, itemX, itemY) if itemX ~= item.x or itemY ~= item.y then item.x = itemX item.y = itemY return true end return false end local function updateRectanglePlacement(template, item, itemX, itemY) local needsUpdate = false local dragging = placementRectangle and not placementDragCompleted local room = state.getSelectedRoom() local layer = tool.layer local resizeWidth, resizeHeight = placementUtils.canResize(room, layer, item) local minimumWidth, minimumHeight = placementUtils.minimumSize(room, layer, item) local itemWidth = math.max(dragging and placementRectangle.width or 8, minimumWidth or 8) local itemHeight = math.max(dragging and placementRectangle.height or 8, minimumHeight or 8) -- Always update when not dragging if not dragging then if itemX ~= item.x or itemY ~= item.y then item.x = itemX item.y = itemY needsUpdate = true end end -- When dragging only update the x position if we have width if resizeWidth and item.width then if dragging and itemX ~= item.x or itemWidth ~= item.width then item.x = itemX item.width = itemWidth needsUpdate = true end end -- When dragging only update the y position if we have height if resizeHeight and item.height then if not dragging and itemY ~= item.y or itemHeight ~= item.height then item.y = itemY item.height = itemHeight needsUpdate = true end end return needsUpdate end local function updateLinePlacement(template, item, itemX, itemY) local dragging = placementRectangle and not placementDragCompleted local node = item.nodes[1] or {} if not dragging then if itemX ~= item.x or itemY ~= item.y then item.x = itemX item.y = itemY node.x = itemX + 8 node.y = itemY + 8 return true end else local stopX, stopY = getCursorGridPosition(placementCurrentX, placementCurrentY) if stopX ~= node.x or stopY ~= node.y then node.x = stopX node.y = stopY return true end end return false end local placementUpdaters = { point = updatePointPlacement, rectangle = updateRectanglePlacement, line = updateLinePlacement } local function updatePlacementNodes() local room = state.room local item = placementTemplate.item local placementType = getCurrentPlacementType() local minimumNodes, maximumNodes = placementUtils.nodeLimits(room, tool.layer, item) if minimumNodes > 0 then -- Add nodes until placement has minimum amount of nodes if not item.nodes then item.nodes = {} end while #item.nodes < minimumNodes do local widthOffset = item.width or 0 local nodeOffset = (#item.nodes + 1) * 16 local node = { x = item.x + widthOffset + nodeOffset, y = item.y } table.insert(item.nodes, node) end -- Update node positions for point and rectangle placements if placementType ~= "line" then for i, node in ipairs(item.nodes) do local widthOffset = item.width or 0 local heightOffset = (item.height or 0) / 2 local nodeOffsetX = #item.nodes * 16 node.x = item.x + widthOffset + nodeOffsetX node.y = item.y + heightOffset end end end end local function updatePlacement() if placementTemplate and placementTemplate.item then local placementType = getCurrentPlacementType() local placementUpdater = placementUpdaters[placementType] local itemX, itemY = getPlacementOffset() local item = placementTemplate.item local needsUpdate = placementUpdater and placementUpdater(placementTemplate, item, itemX, itemY) if needsUpdate then updatePlacementNodes() updatePlacementDrawable() end end end local function selectPlacement(name, index) for i, placement in ipairs(placementsAvailable) do if i == index or placement.displayName == name or placement.name == name then placementTemplate = { item = utils.deepcopy(placement.itemTemplate), placement = placement, } updatePlacementNodes() updatePlacementDrawable() toolUtils.sendMaterialEvent(tool, tool.layer, placement.displayName) return true end end return false end local function drawPlacement(room) if room and placementTemplate and placementTemplate.drawable then viewportHandler.drawRelativeTo(room.x, room.y, function() if utils.typeof(placementTemplate.drawable) == "table" then for _, drawable in ipairs(placementTemplate.drawable) do if drawable.draw then drawable:draw() end end else if placementTemplate.drawable.draw then placementTemplate.drawable:draw() end end end) end end function tool.setLayer(layer) if layer ~= tool.layer or not placementsAvailable then tool.layer = layer placementsAvailable = placementUtils.getPlacements(layer) selectPlacement(nil, 1) toolUtils.sendLayerEvent(tool, layer) end end function tool.setMaterial(material) if type(material) == "number" then selectPlacement(nil, material) else selectPlacement(material, nil) end end function tool.getMaterials() return placementsAvailable end function tool.mousepressed(x, y, button, istouch, presses) local actionButton = configs.editor.toolActionButton if button == actionButton then local px, py = toolUtils.getCursorPositionInRoom(x, y) if px and py then dragStarted(px, py) placePointPlacement() end end end function tool.mousemoved(x, y, dx, dy, istouch) local actionButton = configs.editor.toolActionButton local px, py = toolUtils.getCursorPositionInRoom(x, y) mouseMoved(px, py) if not placementDragCompleted and love.mouse.isDown(actionButton) then if px and py and placementDragStartX and placementDragStartY then local width, height = px - placementDragStartX, py - placementDragStartY dragChanged(placementDragStartX, placementDragStartY, width, height) end end end function tool.mousereleased(x, y, button, istouch, presses) local actionButton = configs.editor.toolActionButton if button == actionButton then dragFinished() end end function tool.keypressed(key, scancode, isrepeat) local room = state.getSelectedRoom() end function tool.update(dt) updatePlacement() end function tool.draw() local room = state.getSelectedRoom() if room then drawPlacement(room) end end return tool
dofile("urlcode.lua") dofile("table_show.lua") local url_count = 0 local tries = 0 local item_type = os.getenv('item_type') local item_value = os.getenv('item_value') local downloaded = {} local addedtolist = {} for ignore in io.open("ignore-list", "r"):lines() do downloaded[ignore] = true end read_file = function(file) if file then local f = assert(io.open(file)) local data = f:read("*all") f:close() return data else return "" end end wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason) local url = urlpos["url"]["url"] local html = urlpos["link_expect_html"] if downloaded[url] == true or addedtolist[url] == true then return false end if (downloaded[url] ~= true or addedtolist[url] ~= true) then if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "[^0-9]"..item_value.."[0-9]") and not (string.match(url, "[^0-9]"..item_value.."[0-9][0-9]") or string.match(url, "/window%.open%('https?://"))) or html == 0) then addedtolist[url] = true return true else return false end end end wget.callbacks.get_urls = function(file, url, is_css, iri) local urls = {} local html = nil local function check(urla) local url = string.match(urla, "^([^#]+)") if (downloaded[url] ~= true and addedtolist[url] ~= true) and ((string.match(url, "[^0-9]"..item_value.."[0-9]") and not (string.match(url, "[^0-9]"..item_value.."[0-9][0-9]") or string.match(url, "/window%.open%('https?://") or string.match(url, "^https?://[^/]*google%.com/") or string.match(url, "^https?://[^/]*stumbleupon%.com/") or string.match(url, "^https?://[^/]*del.icio.us/") or string.match(url, "^https?://[^/]*twitter.com/") or string.match(url, "^https?://[^/]*digg.com/") or string.match(url, "^https?://[^/]*technorati.com/"))) or string.match(url, "media[0-9]+%.gamefront%.com") or string.match(url, "uploads%.gamefront%.com") or string.match(url, "%.jpg$") or string.match(url, "%.png$") or string.match(url, "%.gif$") or string.match(url, "%.jpeg$")) then if string.match(url, "&amp;") then table.insert(urls, { url=string.gsub(url, "&amp;", "&") }) addedtolist[url] = true addedtolist[string.gsub(url, "&amp;", "&")] = true else table.insert(urls, { url=url }) addedtolist[url] = true end end end local function checknewurl(newurl) if string.match(newurl, "^https?://") then check(newurl) elseif string.match(newurl, "^//") then check("http:"..newurl) elseif string.match(newurl, "^/") then check(string.match(url, "^(https?://[^/]+)")..newurl) end end if string.match(url, "[^0-9]"..item_value.."[0-9]") and not string.match(url, "[^0-9]"..item_value.."[0-9][0-9]") then html = read_file(file) for newurl in string.gmatch(html, '([^"]+)') do checknewurl(newurl) end for newurl in string.gmatch(html, "([^']+)") do checknewurl(newurl) end end return urls end wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if (status_code >= 200 and status_code <= 399) then if string.match(url.url, "https://") then local newurl = string.gsub(url.url, "https://", "http://") downloaded[newurl] = true else downloaded[url.url] = true end end if string.match(url["url"], "%?mode=threaded") or string.match(url["url"], "%?mode=linear") or string.match(url["url"], "%?mode=hybrid") or string.match(url["url"], "%-prev%-thread%.html") or string.match(url["url"], "%-next%-thread%.html") or string.match(url["url"], "%-post[0-9]+%.html") then return wget.actions.EXIT end if status_code >= 500 or (status_code >= 400 and status_code ~= 404 and status_code ~= 403) or status_code == 0 then if not string.match(url["url"], "^https?://[^/]*filefront%.com") then return wget.actions.EXIT end io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 5 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
local meta = FindMetaTable("Player") local cachedRunModifiers = {} function meta:getMaxRun() return self.maxRunspeed or 180 end function meta:getMaxWalk() return self.maxWalkspeed or 100 end function meta:setMaxRun(a) self.maxRunspeed = a end function meta:setMaxWalk(a) self.maxWalkspeed = a end function meta:runSpeed(amt) self:SetRunSpeed(amt) self:SprintDisable() self:SprintEnable() end function meta:walkSpeed(amt) self:SetWalkSpeed(amt) end function meta:resetMovespeed() self:SetWalkSpeed(self:getMaxWalk()) self:runSpeed(self:getMaxRun()) end function meta:deathMoveSpeed() self:SetWalkSpeed(120) self:runSpeed(230) end function doSlow(tar, dmg) local curHP = tar:Health() local newHP = math.Clamp(curHP-dmg, 0.4, tar:GetMaxHealth()) local perc = newHP/tar:GetMaxHealth() tar:setMaxRun(180 * perc) tar:setMaxWalk(100 * perc) end function meta:reduceSpeed(amt, len) cachedRunModifiers[self:id()] = cachedRunModifiers[self:id()] or {} table.insert(cachedRunModifiers[self:id()], {time = CurTime() + len, speed = amt}) local maxSlow = LSP.Config.RunSpeed for d,data in pairs(cachedRunModifiers[self:id()]) do if data.time > CurTime() then if data.speed < maxSlow then maxSlow = data.speed end else cachedRunModifiers[self:id()][d] = nil end end if maxSlow < LSP.Config.RunSpeed then self:runSpeed(maxSlow) self:walkSpeed(maxSlow) end end local lastRunThink = 0 hook.Add("Think", "runspeedMod", function() if lastRunThink <= CurTime() then for _,ply in pairs(player.GetAll()) do cachedRunModifiers[ply:id()] = cachedRunModifiers[ply:id()] or {} local maxSlow = LSP.Config.RunSpeed for d,data in pairs(cachedRunModifiers[ply:id()]) do if data.time > CurTime() then if data.speed < maxSlow then maxSlow = data.speed end else cachedRunModifiers[ply:id()][d] = nil end end if maxSlow < LSP.Config.RunSpeed then ply:runSpeed(maxSlow) ply:walkSpeed(maxSlow) else ply:runSpeed(LSP.Config.RunSpeed) ply:walkSpeed(LSP.Config.WalkSpeed) end end lastRunThink = CurTime() + 0.5 end end) local tootsies = { "npc/footsteps/hardboot_generic1.wav", "npc/footsteps/hardboot_generic2.wav", "npc/footsteps/hardboot_generic3.wav", "npc/footsteps/hardboot_generic4.wav", "npc/footsteps/hardboot_generic5.wav", "npc/footsteps/hardboot_generic6.wav", "npc/footsteps/hardboot_generic8.wav", } hook.Add( "PlayerFootstep", "CustomFootstep", function( ply, pos, foot, sound, volume, rf ) if LSP.Config.OptimizeFeet then local snd = tootsies[math.random(1, table.Count(tootsies))] ply:EmitSound(snd) return true end end) hook.Add("PlayerStepSoundTime", "omdisfgsdfg", function(ply, iType, bWalking) if LSP.Config.OptimizeFeet then local fStepTime = 350 local fMaxSpeed = ply:GetMaxSpeed() if ( iType == STEPSOUNDTIME_NORMAL || iType == STEPSOUNDTIME_WATER_FOOT ) then if ( fMaxSpeed <= 100 ) then fStepTime = 400 elseif ( fMaxSpeed <= 300 ) then fStepTime = 350 else fStepTime = 250 end elseif ( iType == STEPSOUNDTIME_ON_LADDER ) then fStepTime = 450 elseif ( iType == STEPSOUNDTIME_WATER_KNEE ) then fStepTime = 600 end -- Step slower if crouching if ( ply:Crouching() ) then fStepTime = fStepTime + 50 end if ( ply:IsSprinting() ) then fStepTime = fStepTime *0.65 end return fStepTime*1.5 end end)
--[[---------------------------------------------------------------------------- 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 NoBackprop,parent = torch.class('nn.NoBackprop','nn.Container') -- was lazy to finish CPU side function NoBackprop:__init(inner) parent.__init(self) assert(inner) self.modules = {inner} end function NoBackprop:updateOutput(input) self.output = self.modules[1]:updateOutput(input) return self.output end function NoBackprop:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input):zero() return self.gradInput end function NoBackprop:__tostring() return 'NoBackprop: ' .. tostring(self.modules[1]) end -- ugh, stupid temporary backwards-compatibility hack NoBackprop.__version = 2 function NoBackprop:__read(file, version) -- do the normal read local var = file:readObject() for k, v in pairs(var) do self[k] = v end -- fixup module if version < 2 then self.modules = {self.inner} self.inner = nil end end
----------------------------------- -- Area: Al'Taieu -- Mob: Om'aern ----------------------------------- mixins = {require("scripts/mixins/families/aern")} ----------------------------------- function onMobDeath(mob, player, isKiller) end
--- === cp.apple.finalcutpro.menu === --- --- Final Cut Pro Menu Helper Functions. local require = require --local log = require "hs.logger".new "fcpMenu" local axutils = require "cp.ui.axutils" local destinations = require "cp.apple.finalcutpro.export.destinations" local fcpApp = require "cp.apple.finalcutpro.app" local strings = require "cp.apple.finalcutpro.strings" local tools = require "cp.tools" local moses = require "moses" local childMatching = axutils.childMatching local childWith = axutils.childWith local isEqual = moses.isEqual local trim = tools.trim local menu = fcpApp.menu ---------------------------------------------------------------------------------------- -- Add a finder for Share Destinations: ---------------------------------------------------------------------------------------- menu:addMenuFinder(function(parentItem, path, childName) if isEqual(path, {"File", "Share"}) then ---------------------------------------------------------------------------------------- -- Note, that in German, there's a space between the '…", for example: -- 'Super DVD …' ---------------------------------------------------------------------------------------- local childNameClean = childName:match("(.*)…$") childName = childNameClean and trim(childNameClean) or childName local index = destinations.indexOf(childName) if index then local children = parentItem:attributeValue("AXChildren") return children[index] end end end) ---------------------------------------------------------------------------------------- -- Add a finder for missing menus: ---------------------------------------------------------------------------------------- local missingMenuMap = { { path = {"Final Cut Pro"}, child = "Commands", key = "CommandSubmenu" }, { path = {"Final Cut Pro", "Commands"}, child = "Customize…", key = "Customize" }, { path = {"Clip"}, child = "Open Clip", key = "FFOpenInTimeline" }, { path = {"Clip"}, child = "Open in Angle Editor", key = "FFOpenInAngleEditor" }, { path = {"Window", "Show in Workspace"}, child = "Sidebar", key = "PEEventsLibrary" }, { path = {"Window", "Show in Workspace"}, child = "Timeline", key = "PETimeline" }, { path = {"Window", "Show in Workspace"}, child = "Event Viewer", key = "PEEventViewer" }, { path = {"Window", "Show in Workspace"}, child = "Timeline Index", key = "PEDataList" }, { path = {"Window"}, child = "Extensions", key = "FFExternalProviderMenuItemTitle" }, { path = {"File"}, child = "Close Library.*", key = "FFCloseLibraryFormat" }, { path = {"Edit"}, child = "Undo", key = "Undo %@" }, { path = {"Edit"}, child = "Redo", key = "Redo %@" }, { path = {"Window", "Workspaces"}, child = "Update ‘.*’ Workspace", key = "PEWorkspacesMenuUpdateWithName" }, { path = {"Window", "Extensions"} }, { path = {"Final Cut Pro", "Commands"} }, { path = {"Window", "Workspaces"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language", "English"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language", "French"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language", "Portuguese"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language", "Spanish"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language", "Greek"} }, { path = {"Edit", "Captions", "Duplicate Captions to New Language", "German"} }, } menu:addMenuFinder(function(parentItem, path, childName, locale) for _,item in ipairs(missingMenuMap) do if item.child == nil and item.key == nil then ---------------------------------------------------------------------------------------- -- Only the path is supplied (in the missing menu map): ---------------------------------------------------------------------------------------- if isEqual(path, item.path) then return childWith(parentItem, "AXTitle", childName) end else ---------------------------------------------------------------------------------------- -- Perform Pattern Matching with Tokens: ---------------------------------------------------------------------------------------- local itemChild = item.child:gsub("%%@", ".*") if isEqual(path, item.path) and childName == itemChild then local keyWithPattern = strings:find(item.key, locale):gsub("%%@", ".*") return childMatching(parentItem, function(child) local title = child:title() return title and string.match(title, keyWithPattern) end) end end end end)
local args = {} DATA_DIR = paths.thisfile('data') print(DATA_DIR) function args.parse(arg) local cmd = torch.CmdLine() cmd:text() cmd:text('Options:') cmd:option('-test', 0, 'test mode (0 or 1)') cmd:option('-extract', 'test', 'extract features on indicated set') cmd:option('-backend', 'cudnn', '(nn|cunn|cudnn)') cmd:option('-seed', 4242, 'Manual random seed') -- Data cmd:option('-dataset', DATA_DIR..'/data.h5', '') cmd:option('-ingrW2V', DATA_DIR..'/text/vocab.bin') -- training params cmd:option('-mismatchFreq', 0.8, '') cmd:option('-nworkers', 4, 'number of data loading threads') cmd:option('-gpu', 1, 'gpu id') cmd:option('-ngpus', 4, 'multigpu') cmd:option('-batchSize', 150, 'mini-batch size') -- Vision model cmd:option('-imsize',224, 'size of image crop(square)') cmd:option('-imstore',256, 'size of images saved in disk') cmd:option('-net', 'resnet', 'resnet or vgg') cmd:option('-patience', 3, 'Number of validation steps to wait until swap, -1 means no swap - all trained at once') cmd:option('-iter_swap', -1, 'Fix number of iterations between freeze switches. -1 means no swap.') cmd:option('-dec_lr', 1, 'Divide learning rate by value every time we swap (value of 1 will leave as is)') cmd:option('-n_layer_trijoint', 7, 'Number of layers in trijoint model (5/7 for semantic=0/semantic=1)') cmd:option('-freeze_first', 'vision', 'Branch to freeze first (trijoint|vision)') --vgg16 model cmd:option('-proto',DATA_DIR..'/vision/VGG_ILSVRC_16_layers_deploy.prototxt', 'deploy file') cmd:option('-caffemodel',DATA_DIR..'/vision/VGG_ILSVRC_16_layers.caffemodel', 'caffe model file') cmd:option('-remove', 2, 'number of layers to remove after loading vgg') --resnet model cmd:option('-resnet_model',DATA_DIR..'/vision/resnet-50.t7', 'resnet torch model file') -- Trijoint model cmd:option('-embDim', 1024, '') cmd:option('-nRNNs', 1, '') cmd:option('-srnnDim', 1024, '') cmd:option('-irnnDim', 300, '') cmd:option('-imfeatDim', 2048, '') cmd:option('-stDim', 1024, '') cmd:option('-ingrW2VDim', 300) cmd:option('-maxSeqlen', 20, '') cmd:option('-maxIngrs', 20, '') cmd:option('-maxImgs',5,'max number of images per sample') -- Semantic regularization cmd:option('-semantic', 1, 'Bool to include semantic branch') cmd:option('-numClasses', 1048, 'Number of classes') cmd:option('-cosw', 0.98, 'Weight to cosine criterion loss') cmd:option('-clsw', 0.01, 'NLL weight (x2)') -- Training cmd:option('-lr', 0.0001, 'base learning rate') cmd:option('-optim', 'adam', 'optimizer (adam|sgd)') cmd:option('-niters', -1, 'number of iterations for which to run (-1 is forever)') cmd:option('-dispfreq', 1000, 'number of iterations between printing train loss') cmd:option('-valfreq', 10000, 'number of iterations between validations. Snapshot will be saved for all validations(if increases performance).') -- Saving & loading -- cmd:option('-snapfile', 'snaps/resnet_reg', 'snapshot file prefix') cmd:option('-loadsnap', '', 'file from which to load model') cmd:option('-rundesc', '', 'description of what is being tested') cmd:text() return cmd:parse(arg or {}) end return args
max_fov = 360 max_vfov = 180 lens_width = 2*pi onload = "f_cover" function lens_inverse(x,y) if abs(x) > pi then return nil end local lon = x local lat = atan(y) return latlon_to_ray(lat,lon) end function lens_forward(x,y,z) local lat,lon = ray_to_latlon(x,y,z) local x = lon local y = tan(lat) return x,y end
-- util.AddNetworkString("ClothingStorageSystem.OpenAddItemMenu") -- util.AddNetworkString("ClothingStorageSystem.SendToServerAddFile") -- util.AddNetworkString("ClothingStorageSystem.OpenStorageMenu") -- util.AddNetworkString("ClothingStorageSystem.EntitySpawner")
fprp.PLAYER.isInRoom = fprp.stub{ name = "isInRoom", description = "Whether the player is in the same room as the LocalPlayer.", parameters = {}, returns = { { name = "inRoom", description = "Whether the player is in the same room.", type = "boolean" } }, metatable = fprp.PLAYER } fprp.deLocalise = fprp.stub{ name = "deLocalise", description = "Makes sure the string will not be localised when drawn or printed.", parameters = { { name = "text", description = "The text to delocalise.", type = "string", optional = false } }, returns = { { name = "text", description = "The delocalised text.", type = "string" } }, metatable = fprp } fprp.textWrap = fprp.stub{ name = "textWrap", description = "Wrap a text around when reaching a certain width.", parameters = {}, returns = { { name = "text", description = "The text to wrap.", type = "string" }, { name = "font", description = "The font of the text.", type = "string" }, { name = "width", description = "The maximum width in pixels.", type = "number" } }, metatable = fprp } fprp.setPreferredJobModel = fprp.stub{ name = "setPreferredJobModel", description = "Set the model preferred by the player (if the job allows multiple models).", parameters = { { name = "teamNr", description = "The team number of the job.", type = "number", optional = false }, { name = "model", description = "The preferred model for the job.", type = "string", optional = false } }, returns = { }, metatable = fprp } fprp.getPreferredJobModel = fprp.stub{ name = "getPreferredJobModel", description = "Get the model preferred by the player (if the job allows multiple models).", parameters = { { name = "teamNr", description = "The team number of the job.", type = "number", optional = false } }, returns = { { name = "model", description = "The preferred model for the job.", type = "string" } }, metatable = fprp } fprp.hookStub{ name = "teamChanged", description = "When your team is changed.", parameters = { { name = "before", description = "The team before the change.", type = "number" }, { name = "after", description = "The team after the change.", type = "number" } }, returns = { } }
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") local maxPlates = 5 --Per table (No more than five can exist at a time per table) function ENT:Initialize() self:SetModel( "models/press-plates/workbench.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType(SIMPLE_USE) local phys = self:GetPhysicsObject() phys:EnableMotion(false) self.activePlates = {} end function ENT:Use(act , call) if not call:isArrested() then call:ChatPrint("This job is only for people who are arrested.") return end if table.Count(self.activePlates) < maxPlates then local p = ents.Create("plate_unpressed") p:SetPos(self:GetPos() + (self:GetAngles():Up() * 45)) local a = self:GetAngles() a:RotateAroundAxis(self:GetAngles():Right() , 180) p:SetAngles(a) p:Spawn() local id = -1 for i = 1 , maxPlates do if self.activePlates[i] == nil then id = i break end end p.owner = self p.id = id self.activePlates[id] = p else call:ChatPrint("There are to many plates around the area, Please use them first before getting more!") end end function ENT:PlateDestoyed(p) self.activePlates[p.id] = nil end
require("prototypes.entity.vbuck")
---@meta --=== time === ---@class time time = {} ---@class CalendarTable ---@field year integer ---@field mon integer ---@field day integer ---@field hour integer ---@field min integer ---@field sec integer ---Converts calendar table to a timestamp in Unix epoch ---@param calendar CalendarTable @Table containing calendar info. --- - **year** 1970 ~ 2038 --- - **mon** month 1 ~ 12 in current year --- - **day** day 1 ~ 31 in current month --- - **hour** --- - **min** --- - **sec** ---@return integer @number of seconds since the Epoch function time.cal2epoch(calendar) end ---Converts timestamp in Unix epoch to calendar format ---@param time integer @number of seconds since the Epoch ---@return { year:number, mon:number, day:number, hour:number, min:number, sec:number, yday:number, wday:number, dst:number } @A table containing the fields: --- - **year** 1970 ~ 2038 --- - **mon** month 1 ~ 12 in current year --- - **day** day 1 ~ 31 in current month --- - **hour** --- - **min** --- - **sec** --- - **yday** day 1 ~ 366 in current year --- - **wday** day 1 ~ 7 in current weak (Sunday is 1) --- - **dst** day time adjustment: --- - 1, (DST in effect, i.e. daylight time) --- - 0, (DST not in effect, i.e. standard time) --- - -1, (Unknown DST status) function time.epoch2cal(time) end ---Returns current system time in the Unix epoch\ ---(seconds from midnight 1970/01/01). ---@return integer sec @seconds since the Unix epoch ---@return integer usec @the microseconds part function time.get() end ---Returns current system time adjusted for\ ---the locale in calendar format. ---@return { year:number, mon:number, day:number, hour:number, min:number, sec:number, yday:number, wday:number, dst:number } @A table containing the fields: --- - **year** 1970 ~ 2038 --- - **mon** month 1 ~ 12 in current year --- - **day** day 1 ~ 31 in current month --- - **hour** --- - **min** --- - **sec** --- - **yday** day 1 ~ 366 in current year --- - **wday** day 1 ~ 7 in current weak (Sunday is 1) --- - **dst** day time adjustment: --- - 1, (DST in effect, i.e. daylight time) --- - 0, (DST not in effect, i.e. standard time) --- - -1, (Unknown DST status) function time.getlocal() end ---Initializes and starts NTP client ---@param ntpAddr? string @"(optional) address of a NTP server, \n defaults to 'pool.ntp.org' if none is specified" ---@return nil function time.initntp(ntpAddr) end ---Checks if NTP client is enabled. ---@return boolean @`true' if NTP client is enabled. function time.ntpenabled() end ---Stops NTP client. ---@return nil function time.ntpstop() end ---Sets system time to a given timestamp in the Unix epoch\ ---(seconds from midnight 1970/01/01). ---@param time integer @number of seconds since the Epoch ---@return nil function time.set(time) end ---Sets correct format for Time Zone locale ---@param timezone string @"a string representing timezone, \n can also include DST adjustment." ---For full syntax see [TZ variable documentation](http://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html). ---@return nil function time.settimezone(timezone) end
objectasteroid = {} objectasteroid_mt = { __index = objectasteroid } function objectasteroid:new(name, tex, x, y, w, h, u, v, nFrames, ang, rad) local entity = {} setmetatable(entity, objectasteroid_mt) entity.name = name entity.texture = tex entity.posx = x entity.posy = y entity.width = w entity.height = h entity.velx = 0 entity.vely = 0 entity.angle = ang entity.radius = rad entity.alpha = 0 entity.frames = {} entity.currentRow = 0 entity.currentFrame = 1 entity.numFrames = nFrames entity.thrust = 0 entity.destroy = false entity.health = 0 if w == 35 then entity.velx = love.math.random(20,85) entity.health = 2 else entity.velx = love.math.random(85,150) entity.health = 1 end return entity end function objectasteroid:update(dt) self.posx = self.posx - self.velx * dt if self.posx < 0 then self.destroy = true end end function objectasteroid:draw() love.graphics.draw(self.texture, self.posx,self.posy) end
--[[ TheNexusAvenger Tests the SurfaceGuiCrashTest class. --]] local NexusUnitTesting = require("NexusUnitTesting") local SurfaceGuiCrashTest = require(game:GetService("StarterGui"):WaitForChild("NexusVRCompatibilityTester"):WaitForChild("Tests"):WaitForChild("SurfaceGuiCrashTest")) local SurfaceGuiCrashTestTest = NexusUnitTesting.UnitTest:Extend() --[[ Sets up the test. --]] function SurfaceGuiCrashTestTest:Setup() self.CuT = SurfaceGuiCrashTest.new() end --[[ Tears down the test. --]] function SurfaceGuiCrashTestTest:Teardown() if self.SurfaceGui then self.SurfaceGui:Destroy() end end --[[ Tests the state updating. --]] NexusUnitTesting:RegisterUnitTest(SurfaceGuiCrashTestTest.new("StateUpdates"):SetRun(function(self) --Create a SurfaceGui and make sure the state didn't change. local SurfaceGui = Instance.new("SurfaceGui") SurfaceGui.Parent = game:GetService("Workspace") self.SurfaceGui = SurfaceGui --Add a frame and assert the state doesn't change. local Frame = Instance.new("Frame") Frame.Parent = SurfaceGui wait() self:AssertEquals(self.CuT.Icon,"NONE") --Add a button and assert the state changes. local Button = Instance.new("TextButton") Button.Parent = SurfaceGui wait() self:AssertEquals(self.CuT.Icon,"ERROR") --Reset the state, remove the button, make the frame selectable, and assert the state changes. Button:Destroy() self.CuT.Icon = "NONE" Frame.Selectable = true wait() self:AssertEquals(self.CuT.Icon,"ERROR") end)) return true
------------------------------------------------------------ -- OptionFrame.lua -- -- Abin -- 2010/10/16 ------------------------------------------------------------ local CreateFrame = CreateFrame local pairs = pairs local ipairs = ipairs local type = type local tostring = tostring local tonumber = tonumber local GetSpellInfo = GetSpellInfo local strtrim = strtrim local CloseDropDownMenus = CloseDropDownMenus local UIDropDownMenu_AddButton = UIDropDownMenu_AddButton local ToggleDropDownMenu = ToggleDropDownMenu local ColorPickerFrame = ColorPickerFrame local _ local L = CompactRaid:GetLocale("CornerIndicators") local module = CompactRaid:GetModule("CornerIndicators") if not module then return end local auraGroups = _G["LibBuffGroups-1.0"] module.optionData = {} local activeOptionKey, activeOptionDB local templates = CompactRaid.optionTemplates local page = module.optionPage local tabFrame = UICreateTabFrame(page:GetName().."TabFrame", page) page.tabFrame = tabFrame page:AnchorToTopLeft(tabFrame, 0, -24) tabFrame:SetWidth(556) tabFrame:SetHeight(420) do local i for i = 1, #module.INDICATOR_KEYS do local key = module.INDICATOR_KEYS[i] tabFrame:AddTab(L[key], key) module.optionData[key] = module:DecodeData() end activeOptionKey = "TOPLEFT" activeOptionDB = module.optionData.TOPLEFT end local scaleoffset = templates:CreateScaleOffsetGroup(page) scaleoffset:SetPoint("TOPLEFT", tabFrame, "TOPLEFT", 20, -20) function scaleoffset:OnScaleApply(scale) activeOptionDB.scale = scale module:SaveOptionData() module:UpdateAllIndicators(activeOptionKey, nil, nil, 1) end function scaleoffset:OnScaleCancel() return activeOptionDB.scale end function scaleoffset:OnOffsetApply(xoffset, yoffset) activeOptionDB.xoffset, activeOptionDB.yoffset = xoffset, yoffset module:SaveOptionData() module:UpdateAllIndicators(activeOptionKey, nil, nil, nil, 1) end function scaleoffset:OnOffsetCancel() return activeOptionDB.xoffset, activeOptionDB.yoffset end local styleGroup = page:CreateSingleSelectionGroup(L["indicator style"], 1) styleGroup:SetPoint("TOPLEFT", scaleoffset, "BOTTOMLEFT", 0, -20) styleGroup:AddButton(L["icon"], 0):ClearAllPoints() styleGroup[1]:SetPoint("LEFT", styleGroup, "LEFT", 48, 0) styleGroup:AddButton(L["color block"], 1) styleGroup:AddButton(L["numerical"], 2) styleGroup:AddButton(HIDE, 3) function styleGroup:OnCheckInit(value) return value == activeOptionDB.style end function styleGroup:OnSelectionChanged(value) activeOptionDB.style = value module:SaveOptionData() page:UpdateOptionStats() module:UpdateAllIndicators(activeOptionKey, 1) end local function CreateStageOption(text, key) local colorSwatch = templates:CreateColorSwatch(page:GetName().."Swatch"..key, page) colorSwatch.key = key local label = page:CreateFontString(nil, "ARTWORK", "GameFontHighlightLeft") colorSwatch.label = label label:SetPoint("LEFT", colorSwatch, "RIGHT") label:SetText(" - "..text) if key > 1 then local combo = page:CreateComboBox() colorSwatch.combo = combo combo.key = key combo:SetPoint("LEFT", label, "RIGHT", 7, 0) combo:SetWidth(100) if key == 2 then combo:AddLine("75%", 75) combo:AddLine("50%", 50) combo:AddLine("25%", 25) combo:AddLine(NONE, 0) else combo:AddLine(format(INT_SPELL_DURATION_SEC, 10), 10) combo:AddLine(format(INT_SPELL_DURATION_SEC, 7), 7) combo:AddLine(format(INT_SPELL_DURATION_SEC, 5), 5) combo:AddLine(format(INT_SPELL_DURATION_SEC, 3), 3) combo:AddLine(NONE, 0) end combo.OnComboChanged = function(self, value) activeOptionDB["threshold"..self.key] = value module:SaveOptionData() end end colorSwatch.OnColorChange = function(self, r, g, b) local key = self.key activeOptionDB["r"..key] = r activeOptionDB["g"..key] = g activeOptionDB["b"..key] = b module:SaveOptionData() end colorSwatch.OnEnable = function(self) self.label:SetTextColor(HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b) if self.combo then self.combo:Enable() end end colorSwatch.OnDisable = function(self) self.label:SetTextColor(GRAY_FONT_COLOR.r, GRAY_FONT_COLOR.g, GRAY_FONT_COLOR.b) if self.combo then self.combo:Disable() end end return colorSwatch end local auraEdit = page:CreateEditBox(L["aura name"], 1) auraEdit:SetWidth(210) auraEdit.text:ClearAllPoints() auraEdit.text:SetPoint("TOPLEFT", styleGroup, "BOTTOMLEFT", 0, -24) auraEdit:SetPoint("LEFT", auraEdit.text, "LEFT", 50, 0) templates:SetEditBoxAutoPrompt(auraEdit) function auraEdit:OnTextCommit(text) text = strtrim(text) if text == "" or text == L["type spell name"] then text = nil end local spellId = tonumber(text) if spellId then text = GetSpellInfo(spellId) self:SetText(text or L["type spell name"]) end activeOptionDB.aura = text module:SaveOptionData() page:UpdateSimilarPrompt() module:UpdateAllIndicators(activeOptionKey, nil, 1) if not text then self:SetText(L["type spell name"]) end end function auraEdit:OnTextCancel() return activeOptionDB.aura or L["type spell name"] end auraEdit:HookScript("OnEditFocusGained", function(self) CloseDropDownMenus() end) local similarButton = page:CreateSubControl("Button") similarButton.icon = similarButton:CreateTexture(nil, "BORDER") similarButton.icon:SetAllPoints(similarButton) similarButton.icon:SetTexture("Interface\\Icons\\Ability_Rogue_ShadowStrikes") similarButton.count = similarButton:CreateFontString(nil, "ARTWORK", "TextStatusBarText") similarButton.count:SetPoint("BOTTOMRIGHT", -1, 1) similarButton:SetSize(20, 20) similarButton:SetPoint("LEFT", auraEdit, "RIGHT", 4, 0) function page:UpdateSimilarPrompt() local aura = activeOptionDB.aura local list = auraGroups:GetGroupAuras(auraGroups:GetAuraGroup(aura)) if list then activeOptionDB.checkSimilar = 1 similarButton.tooltipTitle = aura local similar, text local count = 0 for similar in pairs(list) do if similar ~= aura then count = count + 1 if text then text = text.."\n"..similar else text = similar end end end similarButton.tooltipText = "\n"..L["similars/conflicts"].."\n|cffffffff"..(text or "").."|r" similarButton.icon:SetDesaturated(false) similarButton.count:SetText(count) else activeOptionDB.checkSimilar, similarButton.tooltipTitle, similarButton.tooltipText = nil similarButton.icon:SetDesaturated(true) similarButton.count:SetText() end if GameTooltip:IsOwned(similarButton) then similarButton:Hide() similarButton:Show() end end local spellButton = page:CreateSubControl("Button") spellButton:SetWidth("28") spellButton:SetHeight("58") spellButton:SetScale(0.7) spellButton:SetPoint("LEFT", similarButton, "RIGHT", 4, 11) LoadMicroButtonTextures(spellButton, "Spellbook") spellButton:SetHitRectInsets(0, 0, 22, 0) local BUILTIN_SPELLS = module.DEFAULT_SPELLS[select(2, UnitClass("player"))] if BUILTIN_SPELLS then local spellList = {} local spellid for _, spellid in ipairs(BUILTIN_SPELLS) do local name, _, icon = GetSpellInfo(spellid) if name then spellList[name] = icon end end local spellMenu = CreateFrame("Button", spellButton:GetName().."SpellMenu", spellButton, "UIDropDownMenuTemplate") spellMenu.point = "TOPRIGHT" spellMenu.relativeTo = spellButton spellMenu.relativePoint = "TOPLEFT" spellMenu.xOffset = 0 spellMenu.yOffset = -14 local function OnMenuClick(self, spell) if spell then auraEdit:SetText(spell) auraEdit:OnTextCommit(spell) auraEdit:ClearFocus() end end UIDropDownMenu_Initialize(spellMenu, function() local text = strtrim(auraEdit:GetText()) local name, icon for name, icon in pairs(spellList) do local sel = name == text UIDropDownMenu_AddButton({ text = name, icon = icon, arg1 = name, func = OnMenuClick, checked = sel }) end end, "MENU") spellButton:SetScript("OnClick", function() auraEdit:ClearFocus() ToggleDropDownMenu(nil, nil, spellMenu) end) else spellButton:Disable() end function page:UpdateOptionStats() local i for i = 1, 3 do local colorSwatch = self.stages[i] if activeOptionDB.style == 0 or activeOptionDB.showlacks then colorSwatch:Disable() else colorSwatch:Enable() end end end local spellGroup = page:CreateMultiSelectionGroup(CALENDAR_FILTERS, 1) spellGroup:SetPoint("TOPLEFT", auraEdit.text, "BOTTOMLEFT", 0, -20) spellGroup:AddButton(L["self cast"], "selfcast") spellGroup:AddButton(L["show lacks"], "showlacks"):ClearAllPoints() spellGroup:AddButton(L["ignore outranged"], "ignoreOutRanged"):ClearAllPoints() spellGroup:AddButton(L["ignore vehicles"], "ignoreVehicle"):ClearAllPoints() spellGroup:AddButton(L["ignore physical classes"], "ignorePhysical"):ClearAllPoints() spellGroup:AddButton(L["ignore magical classes"], "ignoreMagical"):ClearAllPoints() page.showLacksCheck = spellGroup[2] -- [aura name] [book] -- [1] selfcast [2] show misses -- [3] ignore outranged [4] ignore vehicle -- [5] ignore physical [6] ignore magical spellGroup[2]:SetPoint("LEFT", spellGroup[1], "LEFT", 210, 0) spellGroup[3]:SetPoint("TOPLEFT", spellGroup[1], "BOTTOMLEFT") spellGroup[4]:SetPoint("TOPLEFT", spellGroup[2], "BOTTOMLEFT") spellGroup[5]:SetPoint("TOPLEFT", spellGroup[3], "BOTTOMLEFT") spellGroup[6]:SetPoint("TOPLEFT", spellGroup[4], "BOTTOMLEFT") function spellGroup:OnCheckInit(value) return activeOptionDB[value] end function spellGroup:OnCheckChanged(value, checked) activeOptionDB[value] = checked module:SaveOptionData() module:UpdateAllIndicators(activeOptionKey, nil, 1) if value == "showlacks" then page:UpdateOptionStats() end end local colorLabel = page:CreateFontString(nil, "ARTWORK", "GameFontNormal") colorLabel:SetPoint("TOPLEFT", spellGroup[5], "BOTTOMLEFT", 0, -20) colorLabel:SetText(L["stage colors"]) page.stages = {} page.stages[1] = CreateStageOption(L["normal stage"], 1) page.stages[1]:SetPoint("TOPLEFT", colorLabel, "BOTTOMLEFT", 8, -10) --hooksecurefunc(page.stages[1], "SetColor", function(self, r, g, b) print("setcolor", r, g, b) end) page.stages[2] = CreateStageOption(L["remaining time"], 2) page.stages[2]:SetPoint("TOPLEFT", page.stages[1], "BOTTOMLEFT", 0, -8) page.stages[3] = CreateStageOption(L["remaining time"], 3) page.stages[3]:SetPoint("TOPLEFT", page.stages[2], "BOTTOMLEFT", 0, -8) local function LoadStageData(stage) local colorSwatch = page.stages[stage] colorSwatch:SetColor(activeOptionDB["r"..stage], activeOptionDB["g"..stage], activeOptionDB["b"..stage]) if stage > 1 then colorSwatch.combo:SetSelection(activeOptionDB["threshold"..stage], 1) end end function tabFrame:OnTabSelected(id, key) if not key or not module.talentdb then return -- Should never happen end activeOptionKey = key activeOptionDB = module.optionData[key] scaleoffset:ClearFocus() auraEdit:ClearFocus() ColorPickerFrame:Hide() CloseDropDownMenus() scaleoffset:SetValue("scale", activeOptionDB.scale) scaleoffset:SetValue("offset", activeOptionDB.xoffset, activeOptionDB.yoffset) styleGroup:SetSelection(activeOptionDB.style, 1) auraEdit:SetText(activeOptionDB.aura or L["type spell name"]) if not activeOptionDB.aura then auraEdit:HighlightText() end spellGroup:SetChecked("selfcast", activeOptionDB.selfcast, 1) spellGroup:SetChecked("showlacks", activeOptionDB.showlacks, 1) spellGroup:SetChecked("ignoreOutRanged", activeOptionDB.ignoreOutRanged, 1) spellGroup:SetChecked("ignoreVehicle", activeOptionDB.ignoreVehicle, 1) spellGroup:SetChecked("ignorePhysical", activeOptionDB.ignorePhysical, 1) spellGroup:SetChecked("ignoreMagical", activeOptionDB.ignoreMagical, 1) page:UpdateSimilarPrompt() LoadStageData(1) LoadStageData(2) LoadStageData(3) page:UpdateOptionStats() end function module:InitOptionData() local db = self.talentdb if not db then return end local key for _, key in ipairs(self.INDICATOR_KEYS) do self.optionData[key] = self:DecodeData(db[key]) end tabFrame:DeselectTab() tabFrame:SelectTab(1) local indicator for _, indicator in ipairs(self.indicators) do indicator.db = self.optionData[indicator.key] end end function module:SaveOptionData() if self.talentdb then self.talentdb[activeOptionKey] = self:EncodeData(activeOptionDB) end end
----------------------------------- -- Area: Northern San d'Oria -- NPC: Prerivon -- Type: Standard Dialogue NPC -- !pos 142.324 0.000 132.515 231 -- ----------------------------------- local ID = require("scripts/zones/Northern_San_dOria/IDs") ----------------------------------- function onTrade(player, npc, trade) end function onTrigger(player, npc) player:showText(npc, ID.text.PRERIVON_DIALOG) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
ProgramsLoc = "%{wks.location}/Source/Programs/" function Program() kind "ConsoleApp" language "C#" location (ProgramsLoc .. "%{prj.name}") targetdir "%{wks.location}/Binaries/%{prj.name}/%{cfg.configuration}/%{cfg.platform}/" files { ProgramsLoc .. "%{prj.name}/**.cs" } end group "Programs" include "LibTool.lua" group ""
do local protobuf_dissector = Dissector.get("protobuf") -- Get the value of a varint -- https://developers.google.com/protocol-buffers/docs/encoding#varints -- @param tvb - The packet buffer -- @param offset - The offset in the packet buffer local function get_varint(tvb, offset, maxlen) local value = 0 local cur_byte local varint_maxlen = 10 if maxlen < varint_maxlen then varint_maxlen = maxlen end local i for i = 0, varint_maxlen, 1 do cur_byte = tvb(offset+i, 1):uint() value = bit.bor(value, bit.lshift(bit.band(cur_byte, 0x7f), (i * 7))) if cur_byte < 0x80 then i = i+1 return i, value end end return 0, 0 end -- Get the byte length of a varint32 -- @param tvb - The packet buffer -- @param offset - The offset in the packet buffer local function varint32_size(tvb, offset) local length, value = get_varint(tvb, offset, 4) return length end -- Get the value of a varint32 -- @param tvb - The packet buffer -- @param offset - The offset in the packet buffer local function varint32_value(tvb, offset) local length, value = get_varint(tvb, offset, 4) return value end -- Decode the ybrpc call_id from the header -- This is a hack, instead of actually parsing the protobuf format, just do a basic -- validation and get the varint. I needed to do it manually because the protobuf_field -- dissector doesn't get called on varint fields. -- @param tvb - The packet buffer -- @param offset - The offset in the packet buffer local function get_call_id(tvb, offset) -- validate that this is the first field of the message, and the type is varint32 (0x08) -- https://developers.google.com/protocol-buffers/docs/encoding#structure local field_value = tvb(offset, 1):uint() if field_value ~= 0x08 then error("unexpected value for protobuf message header") end return varint32_size(tvb, offset+1)+1, varint32_value(tvb, offset+1) end -- Create a dissector for the yugabyte rpc protocol -- Loosely based on the example in this wireshark wiki: -- https://gitlab.com/wireshark/wireshark/-/wikis/Protobuf#write-your-own-protobuf-udp-or-tcp-dissectors -- @param name - The dissector name -- @param desc - The dissector description local function create_yugabyte_dissector(name, desc) local proto = Proto(name, desc) local f_call_id = ProtoField.uint32(name .. ".call_id", "Call ID", base.DEC) local f_message_service = ProtoField.string(name .. ".message_service", "Message Service") local f_message_method = ProtoField.string(name .. ".message_method", "Message Method") local f_length = ProtoField.uint32(name .. ".length", "Message Length", base.DEC) local f_protobuf_header_length = ProtoField.uint32(name .. ".protobuf_header_length", "Protobuf Header Length", base.DEC) local f_protobuf_message_length = ProtoField.uint32(name .. ".protobuf_message_length", "Protobuf Body Length", base.DEC) proto.fields = { f_call_id, f_message_service, f_message_method, f_length, f_protobuf_header_length, f_protobuf_message_length } -- Get the value of the tcp.stream in order to record response method local f_tcp_stream = Field.new("tcp.stream") --local f_tcp_seq = Field.new("tcp.seq") --local f_tcp_srcport = Field.new("tcp.srcport") -- Track the method for the RPC response -- TODO: While this seems to kind-of work, because every packet is dissected when you click a new packet -- sometimes this data isn't available for the response dissection... There needs to be a better -- way to accomplish this. Maybe a post dissector? local function register_call_with_stream(call_id, pinfo) if not f_tcp_stream() then return end streamno = f_tcp_stream().value if tcp_streams[streamno] == nil then tcp_streams[streamno] = {} end if pinfo.private["yb_service_string"] ~= "" and pinfo.private["yb_method_string"] ~= "" then if tcp_streams[streamno][call_id] == nil then tcp_streams[streamno][call_id] = {} end tcp_streams[streamno][call_id]["yb_service_string"] = pinfo.private["yb_service_string"] tcp_streams[streamno][call_id]["yb_method_string"] = pinfo.private["yb_method_string"] end end -- Get the method/service for the RPC request local function get_request_rpc_method(pinfo) return pinfo.private["yb_service_string"], pinfo.private["yb_method_string"] end -- Get the method for the RPC response local function get_response_rpc_method(call_id) if tcp_streams[streamno] ~= nil then if tcp_streams[streamno][call_id] ~= nil then return tcp_streams[streamno][call_id]["yb_service_string"], tcp_streams[streamno][call_id]["yb_method_string"] end end -- We don't know the message type, so just leave it blank return "", "" end proto.init = function() tcp_streams = {} end proto.dissector = function(tvb, pinfo, tree) local subtree = tree:add(proto, tvb()) local offset = 0 local remaining_len = tvb:len() local reported_len = tvb:reported_len() -- can't dissect because we don't have all the data if remaining_len ~= reported_len then return 0 end -- TODO: there has to be some better way of figuring this out local is_response = true if pinfo.dst_port == 7100 then is_response = false elseif pinfo.dst_port == 9100 then is_response = false end if remaining_len < 3 then -- head not enough pinfo.desegment_offset = offset pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT return -1 end -- Check for packet hello TODO: This should print something to the packet dump local hello = tvb(offset, 3):string() if hello == "YB\1" then offset = offset + 3 remaining_len = remaining_len - 3 end -- OK! Start decoding RPC messages while remaining_len > 0 do ::continue:: -- Reset these values, as they are going to be set by subdissectors called by the protobuf_field dissector (below) pinfo.private["yb_service_string"] = "" pinfo.private["yb_method_string"] = "" if remaining_len < 4 then -- head not enough pinfo.desegment_offset = offset pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT return -1 end -- message + header length local data_len = tvb(offset, 4):uint() if remaining_len - 4 < data_len then -- data not enough pinfo.desegment_offset = offset pinfo.desegment_len = data_len - (remaining_len - 4) return -1 end message_tree = subtree:add(tvb(offset, data_len + 4), "Message") -- YBRPC total message length message_tree:add(f_length, tvb(offset, 4)) offset = offset + 4 -- TODO: This is to skip zero length messages... Why do we have empty messages sometimes? Keepalives? if data_len == 0 then remaining_len = remaining_len - 4 offset = reported_len - remaining_len goto continue end -- PacketHeader Length local pheader_length = varint32_value(tvb, offset) message_header = message_tree:add(tvb(offset, pheader_length + varint32_size(tvb, offset)), "Header") message_header:add(f_protobuf_header_length, tvb(offset, varint32_size(tvb,offset)), varint32_value(tvb, offset)) offset = offset + varint32_size(tvb,offset) -- Set message type for the protobuf dissector if is_response then pinfo.private["pb_msg_type"] = "message," .. "yb.rpc.ResponseHeader" else -- TODO: get the sidecar addresses for the response packets pinfo.private["pb_msg_type"] = "message," .. "yb.rpc.RequestHeader" end -- Get the call_id local call_id_len, call_id = get_call_id(tvb, offset) message_header:add(f_call_id, tvb(offset, call_id_len), call_id) message_tree:append_text(" [ID=" .. call_id .. "]") -- Dissect the header -- TODO: why can't I just use a regular tvb here, why does it require an intermediate bytearray -- in order to avoid a C stack overflow? local protobuf_header_bytearray = tvb:bytes(offset, pheader_length) pcall(Dissector.call, protobuf_dissector, protobuf_header_bytearray:tvb(), pinfo, message_header) -- Try to record the message type for the response packet. This needs to be done after dissecting -- the header, because it uses a `protobuf_field` subdissector to intercept the method values from -- the protobuf dissector if is_response == false then register_call_with_stream(call_id, pinfo) end offset = offset + pheader_length -- Now we have everything we need to determine the message type if is_response then message_type = "response" message_service, message_method = get_response_rpc_method(call_id) else message_service, message_method = get_request_rpc_method(pinfo) message_type = "request" end if message_service ~= "" and message_method ~= "" then message_header:add(f_message_service, message_service):set_generated() message_header:add(f_message_method, message_method):set_generated() -- Append message type to top of message tree message_tree:append_text(" [" ..message_service .. "/" .. message_method .. "] [" .. string.upper(message_type) .. "]") -- Set message type for the protobuf dissector pinfo.private["pb_msg_type"] = "application/ybrpc," .. message_service .. "/" .. message_method .. "," .. message_type else pinfo.private["pb_msg_type"] = "message," end local varint_length, pb_message_length = get_varint(tvb, offset, 4) local message_body = message_tree:add(tvb(offset, varint_length + pb_message_length), "Message Body") message_body:add(f_protobuf_message_length, tvb(offset, varint_length), pb_message_length) offset = offset + varint_length local protobuf_message_bytearray = tvb:bytes(offset, pb_message_length) local message_service, message_method, message_type pcall(Dissector.call, protobuf_dissector, protobuf_message_bytearray:tvb(), pinfo, message_body) offset = offset + pb_message_length remaining_len = reported_len - offset end pinfo.columns.protocol:set(name) end DissectorTable.get("tcp.port"):add(0, proto) return proto end create_yugabyte_dissector("YBRPC", "Yugabyte RPC") -- Create a new subdissector - these will be called by the protobuf dissector, and will 'slurp' the field -- into a pinfo.private[] variable and made available to the dissector above. -- @param name - The dissector name -- @param desc - The dissector description local function create_protobuf_subdissector(name, desc, field_name, private_field, as_hex) local proto = Proto(name, desc) proto.dissector = function(tvb, pinfo, tree) -- TODO: To make this general purpose, select a function to execute via an argument to this function pinfo.private[private_field] = tvb:bytes(0, tvb:len()):raw() end local protobuf_field_table = DissectorTable.get("protobuf_field") protobuf_field_table:add(field_name, proto) return proto end create_protobuf_subdissector("ybservicesubdissector", "Yugabyte Service Subdissector", "yb.rpc.RemoteMethodPB.service_name", "yb_service_string") create_protobuf_subdissector("ybmethodsubdissector", "Yugabyte Method Subdissector", "yb.rpc.RemoteMethodPB.method_name", "yb_method_string") end
local gql_types = require('graphql.types') local vshard_utils = require('cartridge.vshard-utils') local _ = require('cartridge.lua-api.vshard') local module_name = 'cartridge.webui.api-vshard' local gql_type_vsgroup = gql_types.object({ name = 'VshardGroup', description = 'Group of replicasets sharding the same dataset', fields = { name = { kind = gql_types.string.nonNull, description = 'Group name', }, bucket_count = { kind = gql_types.int.nonNull, description = 'Virtual buckets count in the group', }, bootstrapped = { kind = gql_types.boolean.nonNull, description = 'Whether the group is ready to operate', }, rebalancer_max_receiving = { kind = gql_types.int.nonNull, description = 'The maximum number of buckets that can be received in parallel by a single replica set ' .. 'in the storage group' }, rebalancer_max_sending = { kind = gql_types.int.nonNull, description = 'The maximum number of buckets that can be sent in parallel by a single replica set ' .. 'in the storage group' }, collect_lua_garbage = { kind = gql_types.boolean.nonNull, description = 'If set to true, the Lua collectgarbage() function is called periodically' }, sync_timeout = { kind = gql_types.float.nonNull, description = 'Timeout to wait for synchronization of the old master with replicas before demotion' }, collect_bucket_garbage_interval = { kind = gql_types.float, deprecationReason = 'Has no effect anymore', description = 'The interval between garbage collector actions, in seconds' }, rebalancer_disbalance_threshold = { kind = gql_types.float.nonNull, description = 'A maximum bucket disbalance threshold, in percent' }, sched_ref_quota = { kind = gql_types.long.nonNull, description = 'Scheduler storage ref quota' }, sched_move_quota = { kind = gql_types.long.nonNull, description = 'Scheduler bucket move quota' }, } }) -- This function is used in frontend only, -- returned value is useless for any other purpose. -- It is to be refactored later. local function get_vshard_bucket_count() -- errors.deprecate( -- 'GraphQL query "vshard_bucket_count" is deprecated. ' .. -- 'Query "vshard_groups" instead.' -- ) local vshard_groups = vshard_utils.get_known_groups() local sum = 0 for _, g in pairs(vshard_groups) do sum = sum + g.bucket_count end return sum end local function get_vshard_known_groups() -- errors.deprecate( -- 'GraphQL query "vshard_known_groups" is deprecated. ' .. -- 'Query "vshard_groups" instead.' -- ) local vshard_groups = vshard_utils.get_known_groups() local ret = {} for name, _ in pairs(vshard_groups) do table.insert(ret, name) end table.sort(ret) return ret end local function get_vshard_groups() local vshard_groups = vshard_utils.get_known_groups() local ret = {} for name, g in pairs(vshard_groups) do g.name = name table.insert(ret, g) end table.sort(ret, function(l, r) return l.name < r.name end) return ret end local function edit_vshard_options(_, args) local group_name = args.name args.name = nil local _, err = vshard_utils.edit_vshard_options(group_name, args) if err ~= nil then return nil, err end local group = vshard_utils.get_known_groups()[group_name] group.name = group_name return group end local function init(graphql) graphql.add_mutation({ name = 'bootstrap_vshard', args = {}, kind = gql_types.boolean, callback = 'cartridge.lua-api.vshard.bootstrap_vshard', }) graphql.add_callback({ prefix = 'cluster', name = 'can_bootstrap_vshard', doc = 'Whether it is reasonble to call bootstrap_vshard mutation', args = {}, kind = gql_types.boolean.nonNull, callback = 'cartridge.vshard-utils.can_bootstrap', }) -- deprecated graphql.add_callback({ prefix = 'cluster', name = 'vshard_bucket_count', doc = 'Virtual buckets count in cluster', args = {}, kind = gql_types.int.nonNull, callback = module_name .. '.get_vshard_bucket_count', }) -- deprecated graphql.add_callback({ prefix = 'cluster', name = 'vshard_known_groups', doc = 'Get list of known vshard storage groups.', args = {}, kind = gql_types.list(gql_types.string.nonNull).nonNull, callback = module_name .. '.get_vshard_known_groups', }) graphql.add_callback({ prefix = 'cluster', name = 'vshard_groups', args = {}, kind = gql_types.list(gql_type_vsgroup.nonNull).nonNull, callback = module_name .. '.get_vshard_groups', }) graphql.add_mutation({ prefix = 'cluster', name = 'edit_vshard_options', args = { name = gql_types.string.nonNull, rebalancer_max_receiving = gql_types.int, rebalancer_max_sending = gql_types.int, collect_lua_garbage = gql_types.boolean, sync_timeout = gql_types.float, collect_bucket_garbage_interval = gql_types.float, rebalancer_disbalance_threshold = gql_types.float, sched_ref_quota = gql_types.long, sched_move_quota = gql_types.long, }, kind = gql_type_vsgroup.nonNull, callback = module_name .. '.edit_vshard_options', }) end return { init = init, get_vshard_bucket_count = get_vshard_bucket_count, get_vshard_known_groups = get_vshard_known_groups, get_vshard_groups = get_vshard_groups, edit_vshard_options = edit_vshard_options }
-- -- Paranoid Pirate queue -- -- Author: Robert G. Jakabosky <[email protected]> -- require"zmq" require"zmq.poller" require"zmsg" local MAX_WORKERS = 100 local HEARTBEAT_LIVENESS = 3 -- 3-5 is reasonable local HEARTBEAT_INTERVAL = 1000 -- msecs local tremove = table.remove -- Insert worker at end of queue, reset expiry -- Worker must not already be in queue local function s_worker_append(queue, identity) if queue[identity] then printf ("E: duplicate worker identity %s", identity) else assert (#queue < MAX_WORKERS) queue[identity] = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS queue[#queue + 1] = identity end end -- Remove worker from queue, if present local function s_worker_delete(queue, identity) for i=1,#queue do if queue[i] == identity then tremove(queue, i) break end end queue[identity] = nil end -- Reset worker expiry, worker must be present local function s_worker_refresh(queue, identity) if queue[identity] then queue[identity] = s_clock() + HEARTBEAT_INTERVAL * HEARTBEAT_LIVENESS else printf("E: worker %s not ready\n", identity) end end -- Pop next available worker off queue, return identity local function s_worker_dequeue(queue) assert (#queue > 0) local identity = tremove(queue, 1) queue[identity] = nil return identity end -- Look for & kill expired workers local function s_queue_purge(queue) local curr_clock = s_clock() -- Work backwards from end to simplify removal for i=#queue,1,-1 do local id = queue[i] if (curr_clock > queue[id]) then tremove(queue, i) queue[id] = nil end end end s_version_assert (2, 1) -- Prepare our context and sockets local context = zmq.init(1) local frontend = context:socket(zmq.ROUTER) local backend = context:socket(zmq.ROUTER) frontend:bind("tcp://*:5555"); -- For clients backend:bind("tcp://*:5556"); -- For workers -- Queue of available workers local queue = {} local is_accepting = false -- Send out heartbeats at regular intervals local heartbeat_at = s_clock() + HEARTBEAT_INTERVAL local poller = zmq.poller(2) local function frontend_cb() -- Now get next client request, route to next worker local msg = zmsg.recv(frontend) local identity = s_worker_dequeue (queue) msg:push(identity) msg:send(backend) if (#queue == 0) then -- stop accepting work from clients, when no workers are available. poller:remove(frontend) is_accepting = false end end -- Handle worker activity on backend poller:add(backend, zmq.POLLIN, function() local msg = zmsg.recv(backend) local identity = msg:unwrap() -- Return reply to client if it's not a control message if (msg:parts() == 1) then if (msg:address() == "READY") then s_worker_delete(queue, identity) s_worker_append(queue, identity) elseif (msg:address() == "HEARTBEAT") then s_worker_refresh(queue, identity) else printf("E: invalid message from %s\n", identity) msg:dump() end else -- reply for client. msg:send(frontend) s_worker_append(queue, identity) end -- start accepting client requests, if we are not already doing so. if not is_accepting and #queue > 0 then is_accepting = true poller:add(frontend, zmq.POLLIN, frontend_cb) end end) -- start poller's event loop while true do local cnt = assert(poller:poll(HEARTBEAT_INTERVAL * 1000)) -- Send heartbeats to idle workers if it's time if (s_clock() > heartbeat_at) then for i=1,#queue do local msg = zmsg.new("HEARTBEAT") msg:wrap(queue[i], nil) msg:send(backend) end heartbeat_at = s_clock() + HEARTBEAT_INTERVAL end s_queue_purge(queue) end -- We never exit the main loop -- But pretend to do the right shutdown anyhow while (#queue > 0) do s_worker_dequeue(queue) end frontend:close() backend:close()
if SERVER then else local panel = vgui.Create("DPanel") panel.Paint = function() end bsuMenu.addPage(4, "Commands", panel, "icon16/wand.png") end
local status_ok, lsp_installer = pcall(require, "nvim-lsp-installer") if not status_ok then return end -- Install servers local servers = { "bashls", "emmet_ls", "jedi_language_server", "solargraph", "sumneko_lua", "tailwindcss", "tsserver", "vimls", } for _, name in pairs(servers) do local server_is_found, server = lsp_installer.get_server(name) if server_is_found and not server:is_installed() then print("Installing " .. name) server:install() end end -- Config LSP lsp_installer.on_server_ready(function(server) local opts = server:get_default_options() opts.on_attach = require("user.lsp.handlers").on_attach opts.capabilities = require("user.lsp.handlers").capabilities -- Apply server settings if available local present, av_overrides = pcall(require, "user.lsp.server_settings." .. server.name) if present then opts = vim.tbl_deep_extend("force", av_overrides, opts) end server:setup(opts) end)
local function onSpectatePlayer(client, message) local spectatorPlayer = client:GetControllingPlayer() if spectatorPlayer then -- This only works for players on the spectator team. if spectatorPlayer:GetTeamNumber() == kSpectatorIndex then client:GetControllingPlayer():SelectEntity(message.entityId) if spectatorPlayer.specMode == kSpectatorMode.Overhead then if message.entityId == Entity.invalidId then spectatorPlayer:SetOverheadMoveEnabled(true) else spectatorPlayer:SetOverheadMoveEnabled(false) end end end end end Server.HookNetworkMessage("SpectatePlayer", onSpectatePlayer)
x = 4 y = 2 f = compiler.load('x,y = y,x') assert(f and type(f) == 'function') f() assert(x == 2) assert(y == 4) print 'Ok'
local dt = require "decisiontree._env" local bm = {} function bm.CartTrainer(opt) local timer = torch.Timer() local trainSet, validSet = dt.getSparseDummyData(opt) print(string.format("CartTrainer: sparse dataset create: %f samples/sec; %f sec", opt.nExample/timer:time().real, timer:time().real)) local cartTrainer = dt.CartTrainer(trainSet, opt.minLeafSize, opt.maxLeafNodes) local treeState = dt.GiniState(trainSet:getExampleIds()) timer:reset() local cartTree, nleaf = cartTrainer:train(treeState, trainSet.featureIds) print(string.format("CartTrainer: train single-thread : %f samples/sec; %f sec", opt.nExample/timer:time().real, timer:time().real)) timer:reset() cartTrainer:featureParallel(opt.nThread) print(string.format("CartTrainer: setup feature-parallel : %f samples/sec; %f sec", opt.nExample/timer:time().real, timer:time().real)) timer:reset() local cartTree, nleaf = cartTrainer:train(treeState, trainSet.featureIds) print(string.format("CartTrainer: train feature-parallel : %f samples/sec; %f sec", opt.nExample/timer:time().real, timer:time().real)) end function bm.GradientBoostState(opt) local trainSet, validSet = dt.getSparseDummyData(opt) trainSet:initScore() local treeState = dt.GradientBoostState(trainSet:getExampleIds(), nn.LogitBoostCriterion(false)) local timer = torch.Timer() -- first step also calls SparseTensor:buildIndex() treeState:findBestSplit(trainSet, trainSet.featureIds, 10, 1, 3) print(string.format("GradientBoostState: findBestSplit (first) : %f sec", timer:time().real)) timer:reset() treeState:findBestSplit(trainSet, trainSet.featureIds, 10, 1, 3) print(string.format("GradientBoostState: findBestSplit (second) : %f sec", timer:time().real)) end local function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function bm.GradientBoostTrainer(opt) local trainSet, validSet if file_exists("/tmp/train.bin") and file_exists("/tmp/valid.bin") then trainSet = torch.load("/tmp/train.bin") validSet = torch.load("/tmp/valid.bin") else if opt.sparse then trainSet, validSet = dt.getSparseDummyData(opt) else trainSet, validSet = dt.getDenseDummyData(opt) end torch.save("/tmp/train.bin", trainSet) torch.save("/tmp/valid.bin", validSet) end local cartTrainer = dt.CartTrainer(trainSet, opt.minLeafSize, opt.maxLeafNodes) opt.lossFunction = nn.LogitBoostCriterion(false) opt.treeTrainer = cartTrainer local forestTrainer = dt.GradientBoostTrainer(opt) local timer = torch.Timer() local decisionForest = forestTrainer:train(trainSet, trainSet.featureIds, validSet) local time = timer:time().real print(string.format("GradientBoostTrainer: train single-thread : %f samples/sec; %f sec/tree, %f sec", opt.nExample/time, time/opt.nTree, time)) cartTrainer:featureParallel(opt.nThread) timer:reset() local decisionForest = forestTrainer:train(trainSet, trainSet.featureIds, validSet) local time = timer:time().real print(string.format("GradientBoostTrainer: train feature-parallel : %f samples/sec; %f sec/tree, %f sec", opt.nExample/time, time/opt.nTree, time)) end function bm.RandomForestTrainer(opt) local trainSet, validSet = dt.getSparseDummyData(opt) local forestTrainer = dt.RandomForestTrainer(opt) local decisionForest = forestTrainer:train(trainSet, trainSet.featureIds) local timer = torch.Timer() local decisionForest = forestTrainer:train(trainSet, trainSet.featureIds) local time = timer:time().real print(string.format("RandomForestTrainer: train single-thread : %f samples/sec; %f sec/tree, %f sec", opt.nExample/time, time/opt.nTree, time)) timer:reset() forestTrainer:treeParallel(opt.nThread) print(string.format("RandomForestTrainer: setup tree-parallel : %f samples/sec; %f sec", opt.nExample/timer:time().real, timer:time().real)) timer:reset() local decisionForest = forestTrainer:train(trainSet, trainSet.featureIds) local time = timer:time().real print(string.format("RandomForestTrainer: train tree-parallel : %f samples/sec; %f sec/tree, %f sec", opt.nExample/time, time/opt.nTree, time)) end function bm.DFD(opt) local _ = require 'moses' local opt = _.clone(opt) opt.nExample = 200 local trainSet, validSet = dt.getDenseDummyData(opt) local forestTrainer = dt.RandomForestTrainer(opt) forestTrainer:treeParallel(opt.nThread) local timer = torch.Timer() local decisionForest = forestTrainer:train(trainSet, trainSet.featureIds) local time = timer:time().real print(string.format("DFD: train random forest in parallel : %f samples/sec; %f sec/tree, %f sec", opt.nExample/time, time/opt.nTree, time)) -- benchmark nn.DFD local input = trainSet.input:sub(1,opt.batchsize) local dfd = nn.DFD(decisionForest) dfd:forward(input) timer:reset() for i=1,opt.nloop do dfd:forward(input) end print(string.format("DFD: updateOutput : %f samples/sec; %f sec", opt.nloop*opt.batchsize/timer:time().real, timer:time().real)) end function bm.Sparse2Dense(opt) local _ = require 'moses' local opt = _.clone(opt) opt.nExample = opt.batchsize local trainSet = dt.getSparseDummyData(opt) local input = {{},{}} for i=1,opt.batchsize do input[1][i] = trainSet.input[i].keys input[2][i] = trainSet.input[i].values end assert(#input[1] == opt.batchsize) -- benchmark nn.Sparse2Dense local s2d = nn.Sparse2Dense(torch.LongTensor():range(1,opt.nFeature)) s2d:forward(input) local timer = torch.Timer() for i=1,opt.nloop do s2d:forward(input) end print(string.format("Sparse2Dense: updateOutput : %f samples/sec; %f sec", opt.nloop*opt.batchsize/timer:time().real, timer:time().real)) end function dt.benchmark(benchmarks, opt2) local opt = { nExample=10000, nCluster=2, nFeature=1000, overlap=0, nValid=100, -- getSparseDummyData nTree=20, featureBaggingSize=-1, sparse=true, -- GradientBoostTrainer and RandomForestTrainer nThread=2, shrinkage=0.1, downsampleRatio=0.1, evalFreq=5, earlyStop=0, -- GradientBoostTrainer activeRatio=0.5, -- RandomForestTrainer batchsize=32, nloop=10 } local _ = require 'moses' benchmarks = benchmarks or _.keys(bm) assert(torch.type(benchmarks) == 'table') for i,benchmark in ipairs(benchmarks) do local opt1 = _.clone(opt) for key, value in pairs(opt2 or {}) do opt1[key] = value end opt1.nActive = opt1.nActive or torch.round(opt1.nFeature/10) opt1.maxLeafNodes = opt1.maxLeafNodes or (opt1.nExample/10) opt1.minLeafSize = opt1.minLeafSize or (opt1.nExample/100) assert(torch.type(benchmark) == 'string', benchmark) assert(bm[benchmark], benchmark) bm[benchmark](opt1) end end
include("memorytable.lua"); include("memdatabase.lua"); include("bankitem.lua"); CBank = class( function (self) self.MaxSlots = 300; self.BagSlot = {}; local timeStart = getTime(); for slotNumber = 1, self.MaxSlots, 1 do self.BagSlot[slotNumber] = CBankItem( slotNumber ); end if( settings.profile.options.DEBUG_INV ) then printf( "Bank update took: %d\n", deltaTime( getTime(), timeStart ) ); end; end ); function CBank:update() local timeStart = getTime(); for slotNumber = 1, self.MaxSlots, 1 do self.BagSlot[ slotNumber ]:update(); end if( settings.profile.options.DEBUG_INV ) then printf( "Bank update took: %d\n", deltaTime( getTime(), timeStart ) ); end; end; function CBank:findItem( itemNameOrId, range) local first, last, location = getInventoryRange(range) -- get bag slot range if location ~= "bank" and location ~= nil then printf("You can only use bank ranges with 'bank:findItem'. You cannot use '%s' which is in %s\n", range, location) end if first == nil then first , last = 1, 300 -- default, search all end local smallestStack = nil local item for slot = first, last do item = self.BagSlot[slot] item:update() if item.Available and (item.Name == itemNameOrId or item.Id == itemNameOrId) then if (os.clock() - item.LastMovedTime) > ITEM_REUSE_DELAY then if item.ItemCount > 1 then -- find smallest stack if smallestStack == nil or smallestStack.ItemCount > item.ItemCount then smallestStack = item end else return item end end end; end; return smallestStack end function CBank:itemTotalCount(itemNameOrId, range) local first, last, location = getInventoryRange(range) -- get bag slot range if location and location ~= "bank" then print("bank:itemTotalCount() only supports ranges in the bank, eg. \"bank\",\"bank1\",\"bank2\",etc.") return end if first == nil then -- Default values - 1-300 for items, 1-200 for empties. first = 1 if itemNameOrId == "<EMPTY>" or itemNameOrId == 0 then last = 200 else last = 300 end end local item local totalCount = 0; for slot = first, last do item = bank.BagSlot[slot] item:update() if item.Available and (item.Id == itemNameOrId or item.Name == itemNameOrId) then if itemNameOrId == "<EMPTY>" or itemNameOrId == 0 then -- so you can count empty slots totalCount = totalCount + 1 else totalCount = totalCount + item.ItemCount; end end; end; return totalCount; end;
-- Zigbee Tuya Button -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local log = require "log" local capabilities = require "st.capabilities" local ZigbeeDriver = require "st.zigbee" local defaults = require "st.zigbee.defaults" local zcl_clusters = require "st.zigbee.zcl.clusters" local function get_ep_offset(device) return device.fingerprinted_endpoint_id - 1 end local button_handler_EF00 = function(driver, device, zb_rx) log.info("<<---- Moon ---->> multi / button_handler zb_rx.body.zcl_body.body_bytes", zb_rx.body.zcl_body.body_bytes) -- https://drive.google.com/file/d/1WaoM80xPi2TMsf-Z-itKLr2p7VKFZ5xh/view -- maybe battery... -- to do: battery handling if zb_rx.body.zcl_body.body_bytes:byte(3) == 10 then return end -- DTH -- buttonNumber = zigbee.convertHexToInt(descMap?.data[2]) -- buttonState = zigbee.convertHexToInt(descMap?.data[6]) -- Note: Groovy Array start 0, Lua Index start 1 local component_id = string.format("button%d", zb_rx.body.zcl_body.body_bytes:byte(3)) log.info("<<---- Moon ---->> multi / button_handler component_id", component_id) -- 00: click, 01: double click, 02: held local clickType = zb_rx.body.zcl_body.body_bytes:byte(7) local ev log.info("<<---- Moon ---->> multi / button_handler clickType", clickType) if clickType == 0 then log.info("<<---- Moon ---->> multi / button_handler clickType-0") ev = capabilities.button.button.pushed() elseif clickType == 1 then log.info("<<---- Moon ---->> multi / button_handler clickType-1") ev = capabilities.button.button.double() elseif clickType == 2 then log.info("<<---- Moon ---->> multi / button_handler clickType-2") ev = capabilities.button.button.held() end if ev ~= nil then ev.state_change = true device.profile.components[component_id]:emit_event(ev) end end local device_added = function(driver, device) log.info("<<---- Moon ---->> multi / device_added") for key, value in pairs(device.profile.components) do log.info("<<---- Moon ---->> multi / device_added - component : ", key) device.profile.components[key]:emit_event(capabilities.button.supportedButtonValues({ "pushed", "double", "held" })) device.profile.components[key]:emit_event(capabilities.button.button.pushed()) end end local configure_device = function(self, device) log.info("<<---- Moon ---->> multi / configure_device") -- todo: need to bind monitored attribute since this device don't have 0001 cluster -- so there might be no default reporting cluster. It can cause health check fail or button might need to wake up device:configure() end local ZIGBEE_TUYA_BUTTON_EF00_FINGERPRINTS = { { mfr = "_TZE200_zqtiam4u", model = "TS0601" }, } local is_tuya_ef00 = function(opts, driver, device) for _, fingerprint in ipairs(ZIGBEE_TUYA_BUTTON_EF00_FINGERPRINTS) do log.info("<<---- Moon ---->> multi / is_tuya_ef00 :", device:pretty_print()) if device:get_manufacturer() == fingerprint.mfr and device:get_model() == fingerprint.model then log.info("<<---- Moon ---->> multi / is_tuya_ef00 : true / device.fingerprinted_endpoint_id :", device.fingerprinted_endpoint_id) return true end end log.info("<<---- Moon ---->> multi / is_tuya_ef00 : false") return false end local tuya_ef00 = { NAME = "tuya ef00", zigbee_handlers = { cluster = { -- No Attr Data from zb_rx, so it should use cluster handler [0xEF00] = { -- ZCLCommandId [0x01] = button_handler_EF00 }, }, }, lifecycle_handlers = { added = device_added, doConfigure = configure_device, }, can_handle = is_tuya_ef00, } return tuya_ef00
-- import local AssetLibraryModule = require 'candy.AssetLibrary' -- module local RenderMaterialModule = {} -------------------------------------------------------------------- -- RenderMaterialInstance -------------------------------------------------------------------- ---@class RenderMaterialInstance local RenderMaterialInstance = CLASS: RenderMaterialInstance () :MODEL {} function RenderMaterialInstance:__init ( source, key ) self.source = source self.key = key self.shaders = {} self.materialBatch = false self.subMaterialBatches = false self:initMaterialBatch () end function RenderMaterialInstance:__tostring () return string.format ( "%s @ %s", self:__repr (), self.source:__tostring () ) end function RenderMaterialInstance:getMaterial () return self.source end function RenderMaterialInstance:initMaterialBatch () local batch = nil local source = self.source local branchInfo = source:getBranchInfo () if not branchInfo then batch = MOAIMaterialBatch.new () local context = source.parsedShaderContext local shaderConfig = source:getDefaultShaderConfig () if shaderConfig then local shader = shaderConfig:affirmShader ( self, context ) batch:setShader ( 1, shader:getMoaiShader () ) self.shaders.main = shader end else batch = MOAIMaterialBatchSwitch.new () local branchCount = table.len ( branchInfo ) local context = source.parsedShaderContext batch:reserveSubBatches ( branchCount ) local idx = 0 self.subMaterialBatches = {} for mask, info in pairs ( branchInfo ) do idx = idx + 1 local subBatch = MOAIMaterialBatch.new () if type ( mask ) == "string" then mask = getRenderManager ():getGlobalMaterialSwitchMask ( mask ) end batch:setSubBatch ( idx, subBatch, mask ) self.subMaterialBatches[ mask ] = subBatch local shaderConfig = info.shader if shaderConfig then local shader = shaderConfig:affirmShader ( self, context ) assert ( shader ) local shaderName = shaderConfig.name subBatch:setShader ( 1, shader:getMoaiShader () ) self.shaders[ shaderName ] = shader end end end batch:setParent ( source.sharedMaterialBatch ) batch.__source = self self.materialBatch = batch end function RenderMaterialInstance:getMaterialBatch () return self.materialBatch end function RenderMaterialInstance:getSubMaterialBatch ( batchMask ) if not self.subMaterialBatches then return false end if type ( batchMask ) == "string" then batchMask = getRenderManager():getGlobalMaterialSwitchMask ( batchMask ) end return batchMask and self.subMaterialBatches[ batchMask ] end function RenderMaterialInstance:update () local source = self.source end function RenderMaterialInstance:applyToMoaiProp ( prop ) local source = self.source source:update () prop:setParentMaterialBatch ( self.materialBatch ) source:applyBillboard ( prop ) source:applyPriority ( prop ) end function RenderMaterialInstance:getShader ( name ) name = name or "main" return self.shaders[ name ] end function RenderMaterialInstance:getShaders () return self.shaders end -------------------------------------------------------------------- -- RenderMaterial -------------------------------------------------------------------- ---@class RenderMaterial local RenderMaterial = CLASS: RenderMaterial () :MODEL { Field 'tag' :string(); '----'; Field 'blend' :enum( EnumBlendMode ); Field 'shader' :asset( 'shader;shader_script' ); Field 'shaderContext' :string(); '----'; Field 'depthMask' :boolean(); Field 'depthTest' :enum( EnumDepthTestMode ) ; '----'; Field 'billboard' :enum( EnumBillboard ); Field 'culling' :enum( EnumCullingMode ); '----'; Field 'priority' :int(); '----'; Field 'stencilTest' :enum( EnumStencilTestMode ); Field 'stencilTestRef' :int() :range(0,255); Field 'stencilTestMask' :int() :range(0,255) :widget( 'bitmask8' ); Field 'stencilMask' :int() :range(0,255) :widget( 'bitmask8' ); Field 'stencilOpSFail' :enum( EnumStencilOp ); Field 'stencilOpDPFail' :enum( EnumStencilOp ); Field 'stencilOpDPPass' :enum( EnumStencilOp ); '----'; Field 'colorMaskR' :boolean(); Field 'colorMaskG' :boolean(); Field 'colorMaskB' :boolean(); Field 'colorMaskA' :boolean(); } -------------------------------------------------------------------- local CULL_NONE = MOAIProp. CULL_NONE local DEPTH_TEST_DISABLE = MOAIProp. DEPTH_TEST_DISABLE local STENCIL_TEST_DISABLE = MOAIProp. STENCIL_TEST_DISABLE local STENCIL_OP_KEEP = MOAIProp. STENCIL_OP_KEEP local STENCIL_OP_KEEP = MOAIProp. STENCIL_OP_KEEP local STENCIL_OP_REPLACE = MOAIProp. STENCIL_OP_REPLACE local BILLBOARD_NONE = MOAIProp. BILLBOARD_NONE function RenderMaterial:__init () self.tag = '' self.blend = 'alpha' self.shader = false self.shaderContext = '' -- self.billboard = BILLBOARD_NONE self.culling = CULL_NONE --depth test self.depthMask = false self.depthTest = DEPTH_TEST_DISABLE --stencil self.stencilTest = STENCIL_TEST_DISABLE self.stencilTestRef = 0 self.stencilTestMask = 0xff self.stencilOpSFail = STENCIL_OP_KEEP self.stencilOpDPFail = STENCIL_OP_KEEP self.stencilOpDPPass = STENCIL_OP_REPLACE self.stencilMask = 0xff --priority self.priority = 0 --colorMask self.colorMaskR = true self.colorMaskG = true self.colorMaskB = true self.colorMaskA = true end function RenderMaterial:__tostring () return string.format ( "%s:%s", self:__repr (), self.assetPath or "???" ) end function RenderMaterial:createInstance ( key ) local instance = RenderMaterialInstance ( self, key ) return instance end function RenderMaterial:removeInstance ( key ) self.instances[ key ] = nil end function RenderMaterial:affirmDefaultInstance () local default = self.defaultInstance if not default then default = self:createInstance ( "__default" ) self.defaultInstance = default end return default end function RenderMaterial:affirmInstance ( key ) if not key or key == "__default" or self:isShared () then return self:affirmDefaultInstance () end local instance = self.instances[ key ] if not instance then instance = self:createInstance ( key ) self.instances[ key ] = instance end return instance end function RenderMaterial:isShared () return self.sharedShader end function RenderMaterial:getBranchInfo () return self.branchInfo end function RenderMaterial:getDefaultShaderConfig () return self.defaultShaderConfig end function RenderMaterial:init () local parsedShaderContext = parseSimpleNamedValueList ( self.shaderContext ) parsedShaderContext.material = self.assetPath self.parsedShaderContext = parsedShaderContext local branchInfo = self.branchInfo if not branchInfo then local branching = false branchInfo = {} local function addBranchInfo ( mask ) if not branchInfo[ mask ] then local entry = {} branchInfo[ mask ] = entry return entry end return branchInfo[ mask ] end if self.branchForShader then local shaderPath = nonWhiteSpaceString ( self.shader ) local shaderConfigGroup = candy.loadAsset ( shaderPath ) local branches = shaderConfigGroup and shaderConfigGroup.branches if branches and next ( branches ) then branching = true for mask, shaderSubConfig in pairs ( branches ) do local entry = addBranchInfo ( mask ) entry.shader = shaderSubConfig end end end if branching then self.branchInfo = branchInfo else self.branchInfo = false end end if not self.branchInfo then _stat ( "branching material", self ) local shaderConfig = false local shaderPath = nonWhiteSpaceString ( self.shader ) if shaderPath then local shaderName = self.shaderName if shaderName == "" then shaderName = "main" end local shaderConfigGroup = candy.loadAsset ( shaderPath ) if shaderConfigGroup then shaderConfig = shaderConfigGroup:getSubConfig ( shaderName ) if not shaderConfig then _warn ( "shader config not found:", shaderName, shaderPath ) end else _warn ( "shader asset not found:", shaderPath ) end end self.defaultShaderConfig = shaderConfig _stat ( "done branching material" ) else self.defaultShaderConfig = false end end function RenderMaterial:update () if not self.dirty then return end self:syncToMoaiMaterial ( self.sharedMaterialBatch ) for i, instance in ipairs ( self.instances ) do instance:update () end self.dirty = false end function RenderMaterial:syncToMoaiMaterial ( batch, ignoreFlags ) batch:setBlendMode ( 1, getMoaiBlendMode ( self.blend ) ) batch:setColorMask ( 1, self.colorMaskR, self.colorMaskG, self.colorMaskB, self.colorMaskA ) batch:setStencilMode ( 1, self.stencilMask, EnumStencilTestModeToMoai[self.stencilTest], self.stencilTestRef, self.stencilTestMask, EnumStencilOpToMoai[self.stencilOpSFail], EnumStencilOpToMoai[self.stencilOpDPFail], EnumStencilOpToMoai[self.stencilOpDPPass] ) batch:setCullMode ( 1, EnumCullingModeToMoai[self.culling] ) batch:setDepthMask ( 1, self.depthMask ) batch:setDepthTest ( 1, EnumDepthTestModeToMoai[self.depthTest] ) end function RenderMaterial:applyToMoaiProp ( prop ) self:applyCullMode ( prop ) self:applyBillboard ( prop ) self:applyBlendMode ( prop ) self:applyDepthMode ( prop ) self:applyShader ( prop ) self:applyPriority ( prop ) -- self:applyColorMask ( prop ) -- self:applyStencilMode ( prop ) end function RenderMaterial:applyColorMask ( prop ) -- prop:setColorMask ( self.colorMaskR, self.colorMaskG, self.colorMaskB, self.colorMaskA ) _warn ( "TODO: MOAIGraphicsProp::applyColorMask not impl." ) end function RenderMaterial:applyStencilMode ( prop ) -- prop:setStencilTest ( self.stencilTest, self.stencilTestRef, self.stencilTestMask ) -- prop:setStencilOp ( self.stencilOpSFail, self.stencilOpDPFail, self.stencilOpDPPass ) -- prop:setStencilMask ( self.stencilMask ) _warn ( "TODO: MOAIGraphicsProp::setStencilTest not impl." ) _warn ( "TODO: MOAIGraphicsProp::setStencilOp not impl." ) _warn ( "TODO: MOAIGraphicsProp::setStencilMask not impl." ) end function RenderMaterial:applyCullMode ( prop ) prop:setCullMode ( self.culling ) end function RenderMaterial:applyBillboard ( prop ) prop:setBillboard ( self.billboard ) end function RenderMaterial:applyBlendMode ( prop ) setPropBlend ( prop, self.blend ) end function RenderMaterial:applyDepthMode ( prop ) prop:setDepthMask ( self.depthMask ) prop:setDepthTest ( self.depthTest ) end function RenderMaterial:applyPriority ( prop ) prop:setPriority ( self.priority ) end function RenderMaterial:setBlend ( blend ) self.blend = blend self.dirty = true end function RenderMaterial:setDepthTest ( test ) self.depthTest = test self.dirty = true end function RenderMaterial:setDepthMask ( mask ) self.depthMask = mask self.dirty = true end function RenderMaterial:setStencilTest ( func, ref, mask ) self.stencilTest = func self.stencilTestRef = ref self.stencilTestMask = mask self.dirty = true end function RenderMaterial:setStencilMask ( mask ) self.stencilMask = mask self.dirty = true end function RenderMaterial:affirmShader () local shader = self.builtShader if shader then return shader end if shader == false then return false end shader = false local shaderPath = self.shader if shaderPath then local parsedContext = parseSimpleNamedValueList ( self.shaderContext ) parsedContext[ 'material' ] = self.assetPath shader = buildMasterShader ( shaderPath, self, parsedContext ) end self.builtShader = shader return shader end function RenderMaterial:applyShader ( prop ) local shader = self:affirmShader () if shader then local moaiShader = shader:getMoaiShader () return prop:setShader ( moaiShader ) else return prop:setShader ( nil ) end end function RenderMaterial:setColorMask ( r, g, b, a ) self.colorMaskR = r self.colorMaskG = g self.colorMaskB = b self.colorMaskA = a end function RenderMaterial:getColorMask () return self.colorMaskR, self.colorMaskG, self.colorMaskB, self.colorMaskA end -------------------------------------------------------------------- local DefaultMaterial = RenderMaterial () DefaultMaterial.tag = '__DEFAULT' DefaultMaterial:setBlend ( "alpha" ) function getDefaultRenderMaterial () return DefaultMaterial end -------------------------------------------------------------------- local legacyDepthTestEnum = { [0] = "disable", [37.0] = "never", [34.0] = "less_equal", [36.0] = "greater", [35.0] = "greater_equal", [31.0] = "always", [32.0] = "equal", [33.0] = "less" } local legacyStencilTestEnum = { [0] = "disable", [156.0] = "less_equal", [155.0] = "less", [153.0] = "always", [158.0] = "greater", [154.0] = "equal", [157.0] = "greater_equal", [159.0] = "never" } local legacyStencilOpEnum = { [148.0] = "incr_wrap", [149.0] = "invert", [145.0] = "decr", [150.0] = "keep", [146.0] = "decr_wrap", [151.0] = "replace", [147.0] = "incr", [152.0] = "zero" } local legacyCullingEnum = { [0] = "none", [29.0] = "back", [30.0] = "front", [28.0] = "all" } local function fixLegacyRenderMaterialData ( data ) local mapData = data.map local root = data.root if mapData then local objData = mapData[ root ] local bodyData = objData and objData.body if bodyData and type ( bodyData.depthTest ) == "number" then bodyData.depthTest = legacyDepthTestEnum[ bodyData.depthTest ] bodyData.culling = legacyCullingEnum[ bodyData.culling ] bodyData.stencilTest = legacyStencilTestEnum[ bodyData.stencilTest ] bodyData.stencilOpSFail = legacyStencilOpEnum[ bodyData.stencilOpSFail ] bodyData.stencilOpDPFail = legacyStencilOpEnum[ bodyData.stencilOpDPFail ] bodyData.stencilOpDPPass = legacyStencilOpEnum[ bodyData.stencilOpDPPass ] end end end local function loadRenderMaterial ( node ) local data = candy.loadAssetDataTable ( node:getObjectFile('def') ) local config = candy.deserialize ( nil, data ) config.assetPath = node:getPath () return config end AssetLibraryModule.registerAssetLoader ( 'material', loadRenderMaterial ) RenderMaterialModule.RenderMaterialInstance = RenderMaterialInstance RenderMaterialModule.RenderMaterial = RenderMaterial RenderMaterialModule.getDefaultRenderMaterial = getDefaultRenderMaterial return RenderMaterialModule
require('packer').use { 'neovim/nvim-lspconfig', config = function() vim.api.nvim_buf_set_option(0, 'omnifunc', 'v:lua.vim.lsp.omnifunc') -- set up global lsp integrations vim.g.capabilities = vim.lsp.protocol.make_client_capabilities() vim.g.capabilities.textDocument.completion.completionItem.snippetSupport = true vim.g.capabilities.textDocument.completion.completionItem.resolveSupport = { properties = { 'documentation', 'detail', 'additionalTextEdits', } } require('lspconfig').bashls.setup{capabilities = vim.g.capabilities} end }
local indent = 4 vim.opt.expandtab = true vim.opt.shiftwidth = indent vim.opt.tabstop = indent vim.opt.softtabstop = indent vim.opt.smartindent = true vim.wo.number = true vim.wo.relativenumber = true vim.wo.signcolumn = 'yes' vim.wo.colorcolumn = '120' vim.o.termguicolors = true vim.opt.wrap = false vim.opt.scrolloff = 8 vim.opt.ignorecase = true vim.opt.smartcase = true vim.opt.hlsearch = false vim.opt.incsearch = true vim.opt.errorbells = false vim.g.mapleader = ' ' -- AutoSave on exit vim.cmd[[autocmd TextChanged,FocusLost,BufEnter * silent update]]
SerializeDialogStateFunction(this, "{{Tale_NextFunctionName}}") {{Tale_NextFunctionName}}(this)
local SchemaElem = {} local M = {Config = {SignsConfig = {}, watch_index = {}, yadm = {}, }, } M.config = {} M.schema = { signs = { type = 'table', deep_extend = true, default = { add = { hl = 'GitSignsAdd', text = '│', numhl = 'GitSignsAddNr', linehl = 'GitSignsAddLn' }, change = { hl = 'GitSignsChange', text = '│', numhl = 'GitSignsChangeNr', linehl = 'GitSignsChangeLn' }, delete = { hl = 'GitSignsDelete', text = '_', numhl = 'GitSignsDeleteNr', linehl = 'GitSignsDeleteLn' }, topdelete = { hl = 'GitSignsDelete', text = '‾', numhl = 'GitSignsDeleteNr', linehl = 'GitSignsDeleteLn' }, changedelete = { hl = 'GitSignsChange', text = '~', numhl = 'GitSignsChangeNr', linehl = 'GitSignsChangeLn' }, }, description = [[ Configuration for signs: • `hl` specifies the highlight group to use for the sign. • `text` specifies the character to use for the sign. • `numhl` specifies the highlight group to use for the number column (see |gitsigns-config.numhl|). • `linehl` specifies the highlight group to use for the line (see |gitsigns-config.linehl|). • `show_count` to enable showing count of hunk, e.g. number of deleted lines. Note if `hl`, `numhl` or `linehl` use a `GitSigns*` highlight and it is not defined, it will be automatically derived by searching for other defined highlights in the following order: • `GitGutter*` • `Signify*` • `Diff*Gutter` • `diff*` • `Diff*` For example if `signs.add.hl = GitSignsAdd` and `GitSignsAdd` is not defined but `GitGutterAdd` is defined, then `GitSignsAdd` will be linked to `GitGutterAdd`. ]], }, keymaps = { type = 'table', default = { noremap = true, ['n ]c'] = { expr = true, "&diff ? ']c' : '<cmd>lua require\"gitsigns\".next_hunk()<CR>'" }, ['n [c'] = { expr = true, "&diff ? '[c' : '<cmd>lua require\"gitsigns\".prev_hunk()<CR>'" }, ['n <leader>hs'] = '<cmd>lua require"gitsigns".stage_hunk()<CR>', ['v <leader>hs'] = '<cmd>lua require"gitsigns".stage_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>', ['n <leader>hu'] = '<cmd>lua require"gitsigns".undo_stage_hunk()<CR>', ['n <leader>hr'] = '<cmd>lua require"gitsigns".reset_hunk()<CR>', ['v <leader>hr'] = '<cmd>lua require"gitsigns".reset_hunk({vim.fn.line("."), vim.fn.line("v")})<CR>', ['n <leader>hR'] = '<cmd>lua require"gitsigns".reset_buffer()<CR>', ['n <leader>hp'] = '<cmd>lua require"gitsigns".preview_hunk()<CR>', ['n <leader>hb'] = '<cmd>lua require"gitsigns".blame_line(true)<CR>', ['n <leader>hS'] = '<cmd>lua require"gitsigns".stage_buffer()<CR>', ['n <leader>hU'] = '<cmd>lua require"gitsigns".reset_buffer_index()<CR>', ['o ih'] = ':<C-U>lua require"gitsigns".select_hunk()<CR>', ['x ih'] = ':<C-U>lua require"gitsigns".select_hunk()<CR>', }, description = [[ Keymaps to set up when attaching to a buffer. Each key in the table defines the mode and key (whitespace delimited) for the mapping and the value defines what the key maps to. The value can be a table which can contain keys matching the options defined in |map-arguments| which are: `expr`, `noremap`, `nowait`, `script`, `silent`, `unique` and `buffer`. These options can also be used in the top level of the table to define default options for all mappings. Since this field is not extended (unlike |gitsigns-config-signs|), mappings defined in this field can be disabled by setting the whole field to `{}`, and |gitsigns-config-on_attach| can instead be used to define mappings. ]], }, on_attach = { type = 'function', default = nil, description = [[ Callback called when attaching to a buffer. Mainly used to setup keymaps when `config.keymaps` is empty. The buffer number is passed as the first argument. This callback can return `false` to prevent attaching to the buffer. Example: > on_attach = function(bufnr) if vim.api.nvim_buf_get_name(bufnr):match(<PATTERN>) then -- Don't attach to specific buffers whose name matches a pattern return false end -- Setup keymaps vim.api.nvim_buf_set_keymap(bufnr, 'n', 'hs', '<cmd>lua require"gitsigns".stage_hunk()<CR>', {}) ... -- More keymaps end < ]], }, watch_index = { type = 'table', default = { interval = 1000, follow_files = true, }, description = [[ When opening a file, a libuv watcher is placed on the respective `.git/index` file to detect when changes happen to use as a trigger to update signs. Fields: • `interval`: Interval the watcher waits between polls of `.git/index` is milliseconds. • `follow_files`: If a file is moved with `git mv`, switch the buffer to the new location. ]], }, sign_priority = { type = 'number', default = 6, description = [[ Priority to use for signs. ]], }, signcolumn = { type = 'boolean', default = true, description = [[ Enable/disable symbols in the sign column. When enabled the highlights defined in `signs.*.hl` and symbols defined in `signs.*.text` are used. ]], }, numhl = { type = 'boolean', default = false, description = [[ Enable/disable line number highlights. When enabled the highlights defined in `signs.*.numhl` are used. If the highlight group does not exist, then it is automatically defined and linked to the corresponding highlight group in `signs.*.hl`. ]], }, linehl = { type = 'boolean', default = false, description = [[ Enable/disable line highlights. When enabled the highlights defined in `signs.*.linehl` are used. If the highlight group does not exist, then it is automatically defined and linked to the corresponding highlight group in `signs.*.hl`. ]], }, diff_algorithm = { type = 'string', default = function() local algo = 'myers' for o in vim.gsplit(vim.o.diffopt, ',') do if vim.startswith(o, 'algorithm:') then algo = string.sub(o, 11) end end return algo end, default_help = "taken from 'diffopt'", description = [[ Diff algorithm to pass to `git diff` . ]], }, count_chars = { type = 'table', default = { [1] = '1', [2] = '2', [3] = '3', [4] = '4', [5] = '5', [6] = '6', [7] = '7', [8] = '8', [9] = '9', ['+'] = '>', }, description = [[ The count characters used when `signs.*.show_count` is enabled. The `+` entry is used as a fallback. With the default, any count outside of 1-9 uses the `>` character in the sign. Possible use cases for this field: • to specify unicode characters for the counts instead of 1-9. • to define characters to be used for counts greater than 9. ]], }, status_formatter = { type = 'function', default = function(status) local added, changed, removed = status.added, status.changed, status.removed local status_txt = {} if added and added > 0 then table.insert(status_txt, '+' .. added) end if changed and changed > 0 then table.insert(status_txt, '~' .. changed) end if removed and removed > 0 then table.insert(status_txt, '-' .. removed) end return table.concat(status_txt, ' ') end, default_help = [[function(status) local added, changed, removed = status.added, status.changed, status.removed local status_txt = {} if added and added > 0 then table.insert(status_txt, '+'..added ) end if changed and changed > 0 then table.insert(status_txt, '~'..changed) end if removed and removed > 0 then table.insert(status_txt, '-'..removed) end return table.concat(status_txt, ' ') end]], description = [[ Function used to format `b:gitsigns_status`. ]], }, max_file_length = { type = 'number', default = 40000, description = [[ Max file length to attach to. ]], }, preview_config = { type = 'table', deep_extend = true, default = { border = 'single', style = 'minimal', relative = 'cursor', row = 0, col = 1, }, description = [[ Option overrides for the Gitsigns preview window. Table is passed directly to `nvim_open_win`. ]], }, attach_to_untracked = { type = 'boolean', default = true, description = [[ Attach to untracked files. ]], }, update_debounce = { type = 'number', default = 100, description = [[ Debounce time for updates (in milliseconds). ]], }, use_internal_diff = { type = 'boolean', default = function() if not jit or jit.os == "Windows" then return false else return true end end, default_help = "`true` if luajit is present (windows unsupported)", description = [[ Use Neovim's built in xdiff library for running diffs. This uses LuaJIT's FFI interface. ]], }, use_decoration_api = { type = 'boolean', default = true, description = [[ Use Neovim's decoration API to apply signs. This should improve performance on large files since signs will only be applied to drawn lines as opposed to all lines in the buffer. ]], }, current_line_blame = { type = 'boolean', default = false, description = [[ Adds an unobtrusive and customisable blame annotation at the end of the current line. The highlight group used for the text is `GitSignsCurrentLineBlame`. ]], }, current_line_blame_position = { type = 'string', default = 'eol', description = [[ Blame annotation position. Available options: - eol: right after eol character (default). - overlay: display over the specified column, without shifting the underlying text. - right_align: display right aligned in the window. ]], }, current_line_blame_formatter = { type = 'function', default = function(name, blame_info) if blame_info.author == name then blame_info.author = 'You' end local text if blame_info.author == 'Not Committed Yet' then text = blame_info.author else text = string.format( '%s, %s - %s', blame_info.author, os.date('%Y-%m-%d', tonumber(blame_info['author_time'])), blame_info.summary) end return { { ' ' .. text, 'GitSignsCurrentLineBlame' } } end, default_help = [[function(name, blame_info) if blame_info.author == name then blame_info.author = 'You' end local text if blame_info.author == 'Not Committed Yet' then text = blame_info.author else text = string.format( '%s, %s - %s', blame_info.author, os.date('%Y-%m-%d', tonumber(blame_info['author_time'])), blame_info.summary ) end return {{' '..text, 'GitSignsCurrentLineBlame'}} end]], description = [[ Function used to format the virtual text of |gitsigns-config-current_line_blame|. The first argument {name} is the git user name returned from: > git config user.name < The second argument {blame_info} is a table with the following keys: - abbrev_sha: string - orig_lnum: integer - final_lnum: integer - author: string - author_mail: string - author_time: integer - author_tz: string - committer: string - committer_mail: string - committer_time: integer - committer_tz: string - summary: string - previous: string - filename: string Note that the keys map onto the output of: > git blame --line-porcelain < ]], }, current_line_blame_delay = { type = 'number', default = 1000, description = [[ Sets the delay before blame virtual text is displayed in milliseconds. ]], }, yadm = { type = 'table', default = { enable = false }, description = [[ yadm configuration. ]], }, _git_version = { type = 'string', default = 'auto', description = [[ Version of git available. Set to 'auto' to automatically detect. ]], }, word_diff = { type = 'boolean', default = false, description = [[ Highlight intra-line word differences in the buffer. Uses the highlights: • GitSignsAddLn • GitSignsChangeLn • GitSignsDeleteLn ]], }, _refresh_staged_on_update = { type = 'boolean', default = true, description = [[ Always refresh the staged file on each update. Disabling this will cause the staged file to only be refreshed when an update to the index is detected. ]], }, debug_mode = { type = 'boolean', default = false, description = [[ Print diagnostic messages. ]], }, } local function validate_config(config) for k, v in pairs(config) do if M.schema[k] == nil then print(("gitsigns: Ignoring invalid configuration field '%s'"):format(k)) else vim.validate({ [k] = { v, M.schema[k].type }, }) end end end local function resolve_default(v) if type(v.default) == 'function' and v.type ~= 'function' then return (v.default)() else return v.default end end function M.build(user_config) user_config = user_config or {} validate_config(user_config) local config = M.config for k, v in pairs(M.schema) do if user_config[k] ~= nil then if v.deep_extend then local d = resolve_default(v) config[k] = vim.tbl_deep_extend('force', d, user_config[k]) else config[k] = user_config[k] end else config[k] = resolve_default(v) end end end return M
DefineClass.SecurityStation = { __parents = { "ElectricityConsumer", "Workplace" }, properties = { { id = "negated_renegades", default = 5, name = T(726, "Neutralized Renegades"), modifiable = true, editor = "number"}, }, } function SecurityStation:GetNegatedRenegades() if not self.working then return 0 end return MulDivRound(self.performance, self.negated_renegades, 100) end function SecurityStation:GetAdjustedRenegades() return self.parent_dome and self.parent_dome:GetAdjustedRenegades() or self:GetNegatedRenegades() end function SecurityStation:GetRenegadesCount() return #(self.parent_dome.labels.Renegade or empty_table) end function SecurityStation:GetNotAdjustedRenegades() return T{727, "Renegades in the Dome <right><number>",number = #(self.parent_dome.labels.Renegade or empty_table)} end
local action = require "action" action.init() action.generate(true) action.clean() action.make()
local fs = filesystem local mainDriveID = nil local nic = nil local bcp = 9998 local rcp = 9997 local finalEEprom = '' local allFilesSent = false local t = computer.millis() starts_with = function(str, start) return str:sub(1, #start) == start end ends_with = function(str, ending) return ending == "" or str:sub(-#ending) == ending end lastIndexOfChar = function(str,char) return string.find(str, char.."[^"..char.."]*$") end --Wait for X seconds before starting function StartupPause(s) local wait = true local time = s * 1000 print(string.format("Waiting for %s seconds before contacting the central server.\nPLEASE CLOSE THIS INTERFACE BEFORE THAT TIME OR THE GAME IS LIKELY TO CRASH", s)) while wait do local ct = computer.millis() local tl = (time - ct) --If 10s on less left then beep the computer every second if tl <= 10000 and tl % 1000 == 0 then computer.beep() end if tl % 1000 == 0 then print(tl/1000) end if ct > t + time then t = ct wait = false end end end local function networkSetup() print("Setting up Network Connection") networkCard = component.proxy(component.findComponent("networkCard")) if not networkCard[1] then computer.panic("Please Install a network card and name it networkCard before continuing") else nic = networkCard[1] end if nic then event.listen(nic) nic:open(rcp) print("Network Configured and listening on port ", rcp) end end local function mountDrive() if fs.mount("/dev/" .. mainDriveID, "/") ~= true then return "Unable to mount FS `" .. mainDriveID .. "`" else return "Drive mounted" end end local function boot() --Set Wait timer to 60s --StartupPause(60) --Currently Breaks ENTIRE GAME print("Attempting to Boot Primary Drive") if fs.initFileSystem("/dev") ~= true then error("Failed to mount /dev") end for _, entry in ipairs(fs.childs("/dev")) do if entry ~= "serial" then mainDriveID = entry print("Primary Drive Found") print(mountDrive()) print("Boot Successful for Startup EEprom") end end networkSetup() end function Write(path, data) local fileData = fs.open(path,"w") if not fileData then panic("File system didn't open'") end fileData:write(data) end function CreateParentDir(path) print("Creating directory:", path) return fs.createDir(path) --Note: As of 080121 this will always return false end function VerifyParentDir(rootDir, path, createIfMissing) local dirPath = '' local sPath = string.sub(path,1,lastIndexOfChar(path,"/")) --File Path without the filename print(string.format("R:%s\tP:%s\tS:%s",rootDir,path, sPath)) --Assuming if the path ends with a / then its a dir if ends_with(rootDir,'/') then CreateParentDir(rootDir) --Remove the Leading / if starts_with(sPath, "/") then sPath = sPath:sub(2) end --Concat the current root dir to the sPath dirPath = rootDir..sPath else dirPath = sPath end --Iterates through local bpath = '' for p in dirPath:gmatch("[^/]+") do bpath = bpath.."/"..p if not fs.exists(bpath) and createIfMissing then CreateParentDir(bpath) end end end function Copy(path, data) local rootDir = '/' local sPath = path --Split the path and verify the dirs exist, if not create them VerifyParentDir(rootDir, path, true) --Write the data to the file if starts_with(sPath, "/") then sPath = string.sub(sPath,2) end rootDir = rootDir..sPath print("Writing:\t"..rootDir) Write(rootDir,data) end local function RewriteEEProm(prom) computer.setEEPROM(prom) computer.reset() computer.beep() end local function broadcast(mainDriveID) print("Broadcasting Request for deployment on port", bcp) nic:broadcast(bcp, "0x0011", mainDriveID) end --Startup boot() if not mainDriveID then computer.panic("Please Insert a hard drive and restart the computer") end if nic then broadcast(mainDriveID) end local continuousBroadcast = true while true do local ct = computer.millis() --60s rebroadcast if no ack received if ct > t + 60000 and continuousBroadcast then t = ct broadcast(mainDriveID) end if allFilesSent and allFilesSent ~= false and finalEEprom ~= '' then RewriteEEProm(finalEEprom) print("Write new EE") end e = table.pack(event.pull(0.1)) if e[1] == "NetworkMessage" and e[3] ~= nic.id and e[4]== rcp then local msg = e[1] local s = e[2] local sender = e[3] --Central core local port = e[4] local code = e[5] -- CODE local path = e[6] -- File path local data = e[7] -- File Data if code then if code == "0x0012" then --print(s,sender,port,message) continuousBroadcast = false print("Setup Msg Received. Waiting for instructions") elseif code == "0x0014" and path and data then --Write the Data to the drive Copy(path,data) elseif code == "0x0016" then --Code is file transmit complete allFilesSent = true nic:send(sender,port,"0x0015") print("Send All Files Received Response") elseif code == "0x0013" then --Receive last EEprom finalEEprom = fs.open(path,"r"):read("*all") print("Boot EEprom Read") end end end end
require('list') require('game.gameobject') require('game.game_objects.level') require('other') require('content') require('game.globals') require('quadtree') utils = require('utils') core = require('core') GameWorld = class(function(t) end) -- Draw function GameObject:draw() end -- Update function GameObject:update() end -- Init function GameObject:init() end
--[[----------------------------------------------------------------------------------------------------------------------- Run Lua on the server -----------------------------------------------------------------------------------------------------------------------]]-- local PLUGIN = {} PLUGIN.Title = "Lua" PLUGIN.Description = "Execute Lua on the server." PLUGIN.Author = "Overv" PLUGIN.ChatCommand = "lua" PLUGIN.Usage = "<code>" PLUGIN.Privileges = { "Lua" } local mt, mt2 = {}, {} EVERYONE, EVERYTHING = {}, {} function mt.__index( t, k ) return function( ply, ... ) for _, pl in ipairs( player.GetAll() ) do pl[ k ]( pl, ... ) end end end function mt2.__index( t, k ) return function( ply, ... ) for _, ent in ipairs( ents.GetAll() ) do if ( !ent:IsWorld() ) then ent[ k ]( ent, ... ) end end end end setmetatable( EVERYONE, mt ) setmetatable( EVERYTHING, mt2 ) function PLUGIN:Call( ply, args ) if ( ply:EV_HasPrivilege( "Lua" ) and IsValid( ply ) ) then local code = table.concat( args, " " ) if ( #code > 0 ) then ME = ply THIS = ply:GetEyeTrace().Entity PLAYER = function( nick ) return evolve:FindPlayer( nick )[1] end local f, a, b = CompileString( code, "" ) if ( !f ) then evolve:Notify( ply, evolve.colors.red, "Syntax error! Check your script!" ) return end local status, err = pcall( f ) if ( status ) then evolve:Notify( evolve.colors.blue, ply:Nick(), evolve.colors.white, " ran Lua code: ", evolve.colors.red, code ) else evolve:Notify( ply, evolve.colors.red, string.sub( err, 5 ) ) end THIS, ME, PLAYER = nil else evolve:Notify( ply, evolve.colors.red, "No code specified." ) end else evolve:Notify( ply, evolve.colors.red, evolve.constants.notallowed ) end end evolve:RegisterPlugin( PLUGIN )
-- mysql 的配置读取工具 -- 支持从配置读取或是串读取 local cfg = {} function cfg:get_mysql_cfg(config) if type(config) == 'string' then return require('config.mysql')[config] else return config end end function cfg:get_redis_cfg(config) if type(config) == "string" then return require('config.redis')[config] else return config end end return cfg
local infoview = require('lean.infoview') local fixtures = require('tests.fixtures') local helpers = require('tests.helpers') helpers.setup {} describe('infoview', function() describe("startup", function() it('cursor stays in source window on open', function(_) helpers.edit_lean_buffer(fixtures.lean3_project.some_existing_file) infoview.get_current_infoview():open() assert.win.stayed.tracked_pending() end) it('created valid infoview', function(_) assert.use_pendingwin.initopened.infoview() end) it('starts with the window position at the top', function(_) local cursor = vim.api.nvim_win_get_cursor(infoview.get_current_infoview().window) assert.is.same(1, cursor[1]) end) end) describe("new tab", function() it('cursor stays in source window on open', function(_) vim.api.nvim_command("tabnew") assert.buf.created.tracked() assert.win.created.tracked() helpers.edit_lean_buffer(fixtures.lean_project.some_existing_file) assert.initclosed.infoview() infoview.get_current_infoview():open() assert.win.stayed.tracked_pending() end) it('created valid infoview', function(_) assert.use_pendingwin.opened.infoview() end) it('starts with the window position at the top', function(_) local cursor = vim.api.nvim_win_get_cursor(infoview.get_current_infoview().window) assert.is.same(1, cursor[1]) end) end) end)
-- Plugin list require('plugins.plugins') -- LSP require('plugins.nvim-lspconfig') -- Autocompletion require('plugins.nvim-cmp') require('plugins.luasnip') -- Syntax highlighting require('plugins.nvim-treesitter') -- Python require('plugins.vim-pydocstring') -- Javascript / Typescript require('plugins.vim-jsdoc') -- General coding support require('plugins.trouble') require('plugins.kommentary') require('plugins.pear-tree') require('plugins.nvim-lightbulb') require('plugins.surround') require('plugins.todo-comments') require('plugins.indent-blankline') require('plugins.nvim-toggleterm') require('plugins.toolwindow') require('plugins.formatter') -- Themes and styling require('plugins.themes') require('plugins.lualine') -- Navigation require('plugins.nvim-tree') require('plugins.telescope') require('plugins.nvim-gps') -- Git support require('plugins.gitsigns') require('plugins.neogit') require('plugins.diffview') -- Spelling require('plugins.spelunker') -- Debugging require('plugins.nvim-dap') require('plugins.nvim-dap-virtual-text') require('plugins.nvim-dap-ui') -- Testing require('plugins.vim-ultest') -- General tools require('plugins.nvim-colorizer') require('plugins.neoscroll') require('plugins.tabout')
ikka_gesul_missions = { { missionType = "assassinate", primarySpawns = { { npcTemplate = "thug", npcName = "Orga Presari" } }, secondarySpawns = { { npcTemplate = "thug", npcName = "a Thug" }, { npcTemplate = "thug", npcName = "a Thug" } }, itemSpawns = {}, rewards = { { rewardType = "faction", faction = "rebel", amount = 100 } } }, { missionType = "deliver", primarySpawns = { { npcTemplate = "taln_solwind", npcName = "Taln Solwind" } }, secondarySpawns = { { npcTemplate = "thug", npcName = "a Thug" }, { npcTemplate = "thug", npcName = "a Thug" } }, itemSpawns = { { itemTemplate = "object/tangible/mission/quest_item/ikka_gesul_q2_needed.iff", itemName = "Datadisc" } }, rewards = { { rewardType = "faction", faction = "rebel", amount = 200 } } }, } npcMapIkkaGesul = { { spawnData = { npcTemplate = "ikka_gesul", x = 1499.45, z = 7, y = 3009.43, direction = 191.517, cellID = 0, position = STAND }, worldPosition = { x = 1500, y = 3010 }, npcNumber = 1, stfFile = "@static_npc/tatooine/ikka_gesul", missions = ikka_gesul_missions }, } IkkaGesul = ThemeParkLogic:new { npcMap = npcMapIkkaGesul, className = "IkkaGesul", screenPlayState = "ikka_gesul_quest", planetName = "tatooine", distance = 800 } registerScreenPlay("IkkaGesul", true) ikka_gesul_mission_giver_conv_handler = mission_giver_conv_handler:new { themePark = IkkaGesul } ikka_gesul_mission_target_conv_handler = mission_target_conv_handler:new { themePark = IkkaGesul }
modifier_nevermore_second_attack_debuff = class({}) function modifier_nevermore_second_attack_debuff:OnCreated(params) if IsServer() then self:SetStackCount(1) end end function modifier_nevermore_second_attack_debuff:OnRefresh(table) if IsServer() then self:IncrementStackCount() end end function modifier_nevermore_second_attack_debuff:GetEffectName() return "particles/units/heroes/hero_nevermore/nevermore_shadowraze_debuff.vpcf" end function modifier_nevermore_second_attack_debuff:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end function modifier_nevermore_second_attack_debuff:GetStatusLabel() return "Raze" end function modifier_nevermore_second_attack_debuff:GetStatusPriority() return 4 end function modifier_nevermore_second_attack_debuff:GetStatusStyle() return "Raze" end if IsClient() then require("wrappers/modifiers") end Modifiers.Status(modifier_nevermore_second_attack_debuff)
-- dep local sgsub = string.gsub local pairs = pairs local os_execute = os.execute local io_open = io.open local print = print local ansicolors = require 'vanilla.v.libs.ansicolors' -- vanilla local va_conf = require 'vanilla.sys.config' local utils = require 'vanilla.v.libs.utils' local gitignore = [[ # Vanilla client_body_temp fastcgi_temp logs proxy_temp tmp uwsgi_temp # Compiled Lua sources luac.out # luarocks build files *.src.rock *.zip *.tar.gz # Object files *.o *.os *.ko *.obj *.elf # Precompiled Headers *.gch *.pch # Libraries *.lib *.a *.la *.lo *.def *.exp # Shared objects (inc. Windows DLLs) *.dll *.so *.so.* *.dylib # Executables *.exe *.out *.app *.i*86 *.x86_64 *.hex ]] local base_controller = [[ local BaseController = Class('controllers.base') function BaseController:__construct() print_r('----------------BaseController:init----------------') local get = self:getRequest():getParams() self.d = '----------------base----------------' .. get.act end function BaseController:fff() self.aaa = 'dddddd' end return BaseController ]] local index_controller = [[ -- local IndexController = Class('controllers.index', LoadApplication('controllers.base')) -- local IndexController = Class('controllers.index') local IndexController = {} local user_service = LoadApplication('models.service.user') local aa = LoadLibrary('aa') -- function IndexController:__construct() -- -- self.parent:__construct() -- print_r('===============IndexController:init===============') -- -- -- -- self.aa = aa({info='ppppp'}) -- -- -- -- self.parent:__construct() -- local get = self:getRequest():getParams() -- self.d = '===============index===============' .. get.act -- end function IndexController:index() return 'hello vanilla.' end function IndexController:indext() -- self.parent:fff() -- do return user_service:get() -- .. sprint_r(aa:idevzDobb()) -- .. sprint_r(Registry['v_sysconf']['db.client.read']['port']) -- -- .. sprint_r(self.aa:idevzDobb()) -- -- .. sprint_r(self.parent.aaa) -- .. Registry['APP_NAME'] -- -- .. self.d -- end local view = self:getView() local p = {} p['vanilla'] = 'Welcome To Vanilla...' .. user_service:get() p['zhoujing'] = 'Power by Openresty' view:assign(p) return view:display() end function IndexController:buested() return 'hello buested.' end -- curl http://localhost:9110/get?ok=yes function IndexController:get() local get = self:getRequest():getParams() print_r(get) do return 'get' end end -- curl -X POST http://localhost:9110/post -d '{"ok"="yes"}' function IndexController:post() local _, post = self:getRequest():getParams() print_r(post) do return 'post' end end -- curl -H 'accept: application/vnd.YOUR_APP_NAME.v1.json' http://localhost:9110/api?ok=yes function IndexController:api_get() local api_get = self:getRequest():getParams() print_r(api_get) do return 'api_get' end end return IndexController ]] local idevz_controller = [[ local IdevzController = {} local user_service = LoadApplication 'models.service.user' local bb = LoadLibrary 'bb' function IdevzController:index() -- do return user_service:get() .. sprint_r(bb:idevzDo()) end local view = self:getView() local p = {} p['vanilla'] = 'Welcome To Vanilla...' .. user_service:get() p['zhoujing'] = 'Power by Openresty' -- view:assign(p) do return view:render('index/index.html', p) end return view:display() end -- curl http://localhost:9110/get?ok=yes function IdevzController:get() local get = self:getRequest():getParams() print_r(get) do return 'get' end end -- curl -X POST http://localhost:9110/post -d '{"ok"="yes"}' function IdevzController:post() local _, post = self:getRequest():getParams() print_r(post) do return 'post' end end -- curl -H 'accept: application/vnd.YOUR_APP_NAME.v1.json' http://localhost:9110/api?ok=yes function IdevzController:api_get() local api_get = self:getRequest():getParams() print_r(api_get) do return 'api_get' end end return IdevzController ]] local index_tpl = [[ <!DOCTYPE html> <html> <body> <img src="http://m1.sinaimg.cn/maxwidth.300/m1.sinaimg.cn/120d7329960e19cf073f264751e8d959_2043_2241.png"> <h1><a href = 'https://github.com/idevz/vanilla'>{{vanilla}}</a></h1><h5>{{zhoujing}}</h5> </body> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-71947507-1', 'auto'); ga('send', 'pageview'); </script> </html> ]] local error_controller = [[ local ErrorController = {} local ngx_log = ngx.log local ngx_redirect = ngx.redirect local os_getenv = os.getenv function ErrorController:error() local env = os_getenv('VA_ENV') or 'development' if env == 'development' then local view = self:getView() view:assign(self.err) return view:display() else local helpers = require 'vanilla.v.libs.utils' ngx_log(ngx.ERR, helpers.sprint_r(self.err)) -- return ngx_redirect("http://sina.cn?vt=4", ngx.HTTP_MOVED_TEMPORARILY) return helpers.sprint_r(self.err) end end return ErrorController ]] local error_tpl = [[ <!DOCTYPE html> <html> <body> <h1>{{status}}</h1> {% for k, v in pairs(body) do %} {% if k == 'message' then %} <h4><pre>{{k}} => {{v}}</pre></h4> {% else %} <h5><pre>{{k}} : {{v}}</pre></h5> {% end %} {% end %} </body> </html> ]] local lib_aa = [[ local LibAa = Class("aa", LoadLibrary('bb')) function LibAa:idevzDo(params) local params = params or { lib_aa = 'idevzDo LibAa'} return params end function LibAa:__construct( data ) print_r('===============init==aaa=======' .. data.info) -- self.parent:init() self.lib = 'LibAa----------------------------aaaa' end return LibAa ]] local lib_bb = [[ local LibBb = Class("bb") function LibBb:idevzDo(params) local params = params or { lib_bb = 'idevzDo LibBb'} return params end function LibBb:__construct( data ) print_r('===============init bbb=========') self.lib = 'LibBb---------------xxx' .. data.info -- self.a = 'ppp' end function LibBb:idevzDobb(params) local params = params or { lib_bb = 'idevzDo idevzDobb'} return params end return LibBb ]] local dao = [[ local TableDao = {} function TableDao:set(key, value) self.__cache[key] = value return true end function TableDao:new() local instance = { set = self.set, __cache = {} } setmetatable(instance, TableDao) return instance end function TableDao:__index(key) local out = rawget(rawget(self, '__cache'), key) if out then return out else return false end end return TableDao ]] local service = [[ local table_dao = LoadApplication('models.dao.table'):new() local UserService = {} function UserService:get() table_dao:set('zhou', 'UserService res') return table_dao.zhou end return UserService ]] local admin_plugin_tpl = [[ local AdminPlugin = LoadV('vanilla.v.plugin'):new() function AdminPlugin:routerStartup(request, response) print_r('<pre>') if request.method == 'GET' then print_r('-----------' .. sprint_r(request.headers) .. '----------') else print_r(request.headers) end end function AdminPlugin:routerShutdown(request, response) end function AdminPlugin:dispatchLoopStartup(request, response) end function AdminPlugin:preDispatch(request, response) end function AdminPlugin:postDispatch(request, response) end function AdminPlugin:dispatchLoopShutdown(request, response) end return AdminPlugin ]] local bootstrap = [[ local simple = LoadV 'vanilla.v.routes.simple' local restful = LoadV 'vanilla.v.routes.restful' local Bootstrap = Class('application.bootstrap') function Bootstrap:initWaf() LoadV('vanilla.sys.waf.acc'):check() end function Bootstrap:initErrorHandle() self.dispatcher:setErrorHandler({controller = 'error', action = 'error'}) end function Bootstrap:initRoute() local router = self.dispatcher:getRouter() local simple_route = simple:new(self.dispatcher:getRequest()) local restful_route = restful:new(self.dispatcher:getRequest()) router:addRoute(restful_route, true) router:addRoute(simple_route) -- print_r(router:getRoutes()) end function Bootstrap:initView() end function Bootstrap:initPlugin() local admin_plugin = LoadPlugin('admin'):new() self.dispatcher:registerPlugin(admin_plugin); end function Bootstrap:boot_list() return { -- Bootstrap.initWaf, -- Bootstrap.initErrorHandle, -- Bootstrap.initRoute, -- Bootstrap.initView, -- Bootstrap.initPlugin, } end function Bootstrap:__construct(dispatcher) self.dispatcher = dispatcher end return Bootstrap ]] local application_conf = [[ local APP_ROOT = Registry['APP_ROOT'] local Appconf={} Appconf.sysconf = { 'v_resource', 'cache' } Appconf.page_cache = {} Appconf.page_cache.cache_on = true -- Appconf.page_cache.cache_handle = 'lru' Appconf.page_cache.no_cache_cookie = 'va-no-cache' Appconf.page_cache.no_cache_uris = { 'uris' } Appconf.page_cache.build_cache_key_without_args = {'rd'} Appconf.vanilla_root = '{{VANILLA_ROOT}}' Appconf.vanilla_version = '{{VANILLA_VERSION_DIR_STR}}' Appconf.name = '{{APP_NAME}}' Appconf.route='vanilla.v.routes.simple' Appconf.bootstrap='application.bootstrap' Appconf.app={} Appconf.app.root=APP_ROOT Appconf.controller={} Appconf.controller.path=Appconf.app.root .. '/application/controllers/' Appconf.view={} Appconf.view.path=Appconf.app.root .. '/application/views/' Appconf.view.suffix='.html' Appconf.view.auto_render=true return Appconf ]] local errors_conf = [[ ------------------------------------------------------------------------------------------------------------------- -- Define all of your application errors in here. They should have the format: -- -- local Errors = { -- [1000] = { status = 500, message = "Controller Err." }, -- } -- -- where: -- '1000' is the error number that can be raised from controllers with `self:raise_error(1000) -- 'status' (required) is the http status code -- 'message' (required) is the error description ------------------------------------------------------------------------------------------------------------------- local Errors = {} return Errors ]] local waf_conf = [[ local waf_conf = {} waf_conf.ipBlocklist={"1.0.0.1"} -- waf_conf.html="<!DOCTYPE html><html><body><h1>Fu*k U...</h1><h4>=======</h4><h5>--K--</h5></body></html>" return waf_conf ]] local waf_conf_regs_args = [[ \.\./ \:\$ \$\{ select.+(from|limit) (?:(union(.*?)select)) having|rongjitest sleep\((\s*)(\d*)(\s*)\) benchmark\((.*)\,(.*)\) base64_decode\( (?:from\W+information_schema\W) (?:(?:current_)user|database|schema|connection_id)\s*\( (?:etc\/\W*passwd) into(\s+)+(?:dump|out)file\s* group\s+by.+\( xwork.MethodAccessor (?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\( xwork\.MethodAccessor (gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\/ java\.lang \$_(GET|post|cookie|files|session|env|phplib|GLOBALS|SERVER)\[ \<(iframe|script|body|img|layer|div|meta|style|base|object|input) (onmouseover|onerror|onload)\= ]] local waf_conf_regs_cookie = [[ \.\./ \:\$ \$\{ select.+(from|limit) (?:(union(.*?)select)) having|rongjitest sleep\((\s*)(\d*)(\s*)\) benchmark\((.*)\,(.*)\) base64_decode\( (?:from\W+information_schema\W) (?:(?:current_)user|database|schema|connection_id)\s*\( (?:etc\/\W*passwd) into(\s+)+(?:dump|out)file\s* group\s+by.+\( xwork.MethodAccessor (?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\( xwork\.MethodAccessor (gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\/ java\.lang \$_(GET|post|cookie|files|session|env|phplib|GLOBALS|SERVER)\[ ]] local waf_conf_regs_post = [[ select.+(from|limit) (?:(union(.*?)select)) having|rongjitest sleep\((\s*)(\d*)(\s*)\) benchmark\((.*)\,(.*)\) base64_decode\( (?:from\W+information_schema\W) (?:(?:current_)user|database|schema|connection_id)\s*\( (?:etc\/\W*passwd) into(\s+)+(?:dump|out)file\s* group\s+by.+\( xwork.MethodAccessor (?:define|eval|file_get_contents|include|require|require_once|shell_exec|phpinfo|system|passthru|preg_\w+|execute|echo|print|print_r|var_dump|(fp)open|alert|showmodaldialog)\( xwork\.MethodAccessor (gopher|doc|php|glob|file|phar|zlib|ftp|ldap|dict|ogg|data)\:\/ java\.lang \$_(GET|post|cookie|files|session|env|phplib|GLOBALS|SERVER)\[ \<(iframe|script|body|img|layer|div|meta|style|base|object|input) (onmouseover|onerror|onload)\= ]] local waf_conf_regs_url = [[ \.(svn|htaccess|bash_history) \.(bak|inc|old|mdb|sql|backup|java|class)$ (vhost|bbs|host|wwwroot|www|site|root|hytop|flashfxp).*\.rar (phpmyadmin|jmx-console|jmxinvokerservlet) java\.lang /(attachments|upimg|images|css|uploadfiles|html|uploads|templets|static|template|data|inc|forumdata|upload|includes|cache|avatar)/(\\w+).(php|jsp) ]] local waf_conf_regs_ua = [[ (HTTrack|harvest|audit|dirbuster|pangolin|nmap|sqln|-scan|hydra|Parser|libwww|BBBike|sqlmap|w3af|owasp|Nikto|fimap|havij|PycURL|zmeu|BabyKrokodil|netsparker|httperf|bench| SF/) ]] local waf_conf_regs_whiteurl = [[ ^/123/$ ]] local va_nginx_config_tpl = [[ #user zhoujing staff; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type text/html; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 60; gzip on; gzip_vary on; gzip_comp_level 6; gzip_buffers 16 8k; gzip_min_length 1000; gzip_proxied any; gzip_disable "msie6"; gzip_http_version 1.0; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml; lua_package_path "/?.lua;/?/init.lua;{{VANILLA_ROOT}}/?.lua;{{VANILLA_ROOT}}/?/init.lua;;"; lua_package_cpath "/?.so;{{VANILLA_ROOT}}/?.so;;"; #init_by_lua_file {{VANILLA_ROOT}}/init.lua; init_worker_by_lua_file {{VANILLA_ROOT}}/init.lua; include vhost/*.conf; } ]] local va_nginx_dev_config_tpl = [[ #user zhoujing staff; worker_processes 1; #error_log logs/error.log; #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid; events { worker_connections 1024; } http { include mime.types; default_type text/html; #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; #access_log logs/access.log main; sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 60; gzip on; gzip_vary on; gzip_comp_level 6; gzip_buffers 16 8k; gzip_min_length 1000; gzip_proxied any; gzip_disable "msie6"; gzip_http_version 1.0; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript application/javascript image/svg+xml; lua_package_path "/?.lua;/?/init.lua;{{VANILLA_ROOT}}/?.lua;{{VANILLA_ROOT}}/?/init.lua;;"; lua_package_cpath "/?.so;{{VANILLA_ROOT}}/?.so;;"; init_by_lua_file {{VANILLA_ROOT}}/init.lua; #init_worker_by_lua_file {{VANILLA_ROOT}}/init.lua; include dev_vhost/*.conf; } ]] local nginx_vhost_config_tpl = [[ lua_shared_dict idevz 20m; server { server_name {{APP_NAME}}.idevz.com 127.0.0.1; lua_code_cache on; root {{APP_ROOT}}; listen 80; set $APP_NAME '{{APP_NAME}}'; set $VANILLA_VERSION '{{VANILLA_VERSION_DIR_STR}}'; set $VANILLA_ROOT '{{VANILLA_ROOT}}'; set $template_root ''; set $va_cache_status ''; location /static { access_log off; alias {{APP_ROOT}}/pub/static; expires max; } location = /favicon.ico { access_log off; root {{APP_ROOT}}/pub/; expires max; } # Access log with buffer, or disable it completetely if unneeded access_log logs/vanilla-access.log combined buffer=16k; # access_log off; # Error log error_log logs/vanilla-error.log debug; # Va runtime location / { content_by_lua_file $document_root/pub/index.lua; } } ]] local dev_nginx_vhost_config_tpl = [[ lua_shared_dict idevz 20m; server { server_name {{APP_NAME}}.idevz.com 127.0.0.1; lua_code_cache off; root {{APP_ROOT}}; listen 9110; set $APP_NAME '{{APP_NAME}}'; set $VANILLA_VERSION '{{VANILLA_VERSION_DIR_STR}}'; set $VANILLA_ROOT '{{VANILLA_ROOT}}'; set $template_root ''; set $va_cache_status ''; set $VA_DEV on; location /static { access_log off; alias {{APP_ROOT}}/pub/static; expires max; } location = /favicon.ico { access_log off; root {{APP_ROOT}}/pub/; expires max; } # Access log with buffer, or disable it completetely if unneeded access_log logs/vanilla-access.log combined buffer=16k; # access_log off; # Error log error_log logs/vanilla-error.log debug; # Va runtime location / { content_by_lua_file $document_root/pub/index.lua; } } ]] local service_manage_sh = [[ #!/bin/sh ### BEGIN ### # Author: idevz # Since: 2016/03/12 # Description: Manage a Vanilla App Service ### END ### OPENRESTY_NGINX_ROOT={{OPENRESTY_NGINX_ROOT}} NGINX=$OPENRESTY_NGINX_ROOT/sbin/nginx NGINX_CONF_PATH=$OPENRESTY_NGINX_ROOT/conf VA_APP_PATH={{VA_APP_PATH}} VA_APP_NAME=`basename $VA_APP_PATH` NGINX_CONF_SRC_PATH=$VA_APP_PATH/nginx_conf TIME_MARK=`date "+%Y_%m_%d_%H_%M_%S"` NGINX_CONF_SRC_PATH=$VA_APP_PATH/nginx_conf DESC=va-{{APP_NAME}}-service DESC=va-ok-service IS_FORCE='' PLATFORM=`uname` ECHO_E=" -e " [ $PLATFORM = "Darwin" ] && ECHO_E="" ok() { MSG=$1 echo $ECHO_E"\033[35m$MSG \033[0m\n" } die() { MSG=$1 echo $ECHO_E"\033[31m$MSG \033[0m\n"; exit $?; } if [ -n "$2" -a "$2" = 'dev' ];then VA_ENV="development" IS_FORCE=$3 NGINX_CONF=$OPENRESTY_NGINX_ROOT/conf/va-nginx-$VA_ENV.conf NGINX_APP_CONF=$OPENRESTY_NGINX_ROOT/conf/dev_vhost/$VA_APP_NAME.conf NGINX_CONF_SRC=$NGINX_CONF_SRC_PATH/va-nginx-$VA_ENV.conf VA_APP_CONF_SRC=$NGINX_CONF_SRC_PATH/dev_vhost/$VA_APP_NAME.conf else NGINX_CONF=$OPENRESTY_NGINX_ROOT/conf/va-nginx.conf NGINX_APP_CONF=$OPENRESTY_NGINX_ROOT/conf/vhost/$VA_APP_NAME.conf NGINX_CONF_SRC=$NGINX_CONF_SRC_PATH/va-nginx.conf VA_APP_CONF_SRC=$NGINX_CONF_SRC_PATH/vhost/$VA_APP_NAME.conf IS_FORCE=$2 VA_ENV='' fi if [ ! -f $NGINX ]; then echo $ECHO_E"Didn't Find Nginx sbin."; exit 0 fi conf_move() { NGINX_CONF_SRC=$1 NGINX_CONF=$2 VA_APP_CONF_SRC=$3 NGINX_APP_CONF=$4 IS_FORCE=$5 NGINX_APP_CONF_DIR=`dirname $NGINX_APP_CONF` if [ -e "$NGINX_CONF" -a "$IS_FORCE" = "-f" ]; then mv -f $NGINX_CONF $NGINX_CONF".old."$TIME_MARK && cp -f $NGINX_CONF_SRC $NGINX_CONF echo $ECHO_E"Move And Copy \033[32m" $NGINX_CONF_SRC "\033[0m" to "\033[31m" $NGINX_CONF "\033[m"; elif [ ! -e "$NGINX_CONF" ]; then cp -f $NGINX_CONF_SRC $NGINX_CONF echo $ECHO_E"Copy \033[32m" $NGINX_CONF_SRC "\033[0m" to "\033[31m" $NGINX_CONF "\033[m"; else ok $NGINX_CONF" is already exist, Add param '-f' to Force move." fi if [ -e $NGINX_APP_CONF ]; then mv -f $NGINX_APP_CONF $NGINX_APP_CONF".old."$TIME_MARK && cp -f $VA_APP_CONF_SRC $NGINX_APP_CONF elif [ ! -d "$NGINX_APP_CONF_DIR" ]; then mkdir -p $NGINX_APP_CONF_DIR && cp -f $VA_APP_CONF_SRC $NGINX_APP_CONF else cp -f $VA_APP_CONF_SRC $NGINX_APP_CONF fi echo $ECHO_E"copy \033[32m" $VA_APP_CONF_SRC "\033[0m" to "\033[31m" $NGINX_APP_CONF "\033[m"; exit 0 } nginx_conf_test() { if $NGINX -t -c $1 >/dev/null 2>&1; then return 0 else $NGINX -t -c $1 return $? fi } case "$1" in start) echo $ECHO_E"Starting $DESC: " nginx_conf_test $NGINX_CONF $NGINX -c $NGINX_CONF || true ok "Succ." ;; stop) echo $ECHO_E"Stopping $DESC: " $NGINX -c $NGINX_CONF -s stop || true ok "Succ." ;; restart|force-reload) echo $ECHO_E"Restarting $DESC: " $NGINX -c $NGINX_CONF -s stop || true sleep 1 nginx_conf_test $NGINX_CONF $NGINX -c $NGINX_CONF || true ok "Succ." ;; reload) echo $ECHO_E"Reloading $DESC configuration: " nginx_conf_test $NGINX_CONF $NGINX -c $NGINX_CONF -s reload || true ok "Succ." ;; configtest) echo $ECHO_E"Testing $DESC configuration: " if nginx_conf_test $NGINX_CONF; then echo $ECHO_E"Config Test Succ." else die "Config Test Fail." fi ;; confinit|initconf) echo $ECHO_E"Initing $DESC configuration: " if conf_move $NGINX_CONF_SRC $NGINX_CONF $VA_APP_CONF_SRC $NGINX_APP_CONF $IS_FORCE; then if nginx_conf_test $NGINX_CONF; then tree $NGINX_CONF_PATH/vhost tree $NGINX_CONF_PATH/dev_vhost echo $ECHO_E"Config init Succ." fi die "Config Test Fail." fi ;; ltpl) echo $ECHO_E"Start using lemplate compile TT2 template ..." TT2_TEMPLATE_PATH=$VA_APP_PATH/application/views/ lemplate-{{VANILLA_VERSION}} --compile $TT2_TEMPLATE_PATH/*.html > $TT2_TEMPLATE_PATH/templates.lua ;; *) echo $ECHO_E"Usage: ./va-ok-service {start|stop|restart|reload|force-reload|confinit[-f]|configtest} [dev]" >&2 exit 1 ;; esac exit 0 ]] local nginx_conf = [[ local ngx_conf = {} ngx_conf.common = { INIT_BY_LUA = 'nginx.init', LUA_SHARED_DICT = 'nginx.sh_dict', -- LUA_PACKAGE_PATH = '', -- LUA_PACKAGE_CPATH = '', CONTENT_BY_LUA_FILE = './pub/index.lua' } ngx_conf.env = {} ngx_conf.env.development = { LUA_CODE_CACHE = false, PORT = 9110 } ngx_conf.env.test = { LUA_CODE_CACHE = true, PORT = 9111 } ngx_conf.env.production = { LUA_CODE_CACHE = true, PORT = 80 } return ngx_conf ]] local restful_route_conf = [[ local restful = { v1={}, v={} } restful.v.GET = { {pattern = '/get', controller = 'index', action = 'get'}, } restful.v.POST = { {pattern = '/post', controller = 'index', action = 'post'}, } restful.v1.GET = { {pattern = '/api', controller = 'index', action = 'api_get'}, } return restful ]] local nginx_init_by_lua_tpl = [[ local init_by_lua = {} function init_by_lua:run() local conf = LoadApplication 'nginx.init.config' ngx.zhou = conf end return init_by_lua ]] local nginx_init_config_tpl = [[ local config = LoadApp('config.application') return config ]] local vanilla_index = [[ init_vanilla() page_cache() --+--------------------------------------------------------------------------------+-- -- if Registry['VA_ENV'] == nil then local helpers = LoadV "vanilla.v.libs.utils" function sprint_r( ... ) return helpers.sprint_r(...) end function lprint_r( ... ) local rs = sprint_r(...) print(rs) end function print_r( ... ) local rs = sprint_r(...) ngx.say(rs) end function err_log(msg) ngx.log(ngx.ERR, "===zjdebug" .. msg .. "===") end -- end --+--------------------------------------------------------------------------------+-- Registry['VANILLA_APPLICATION']:new(ngx, Registry['APP_CONF']):bootstrap(Registry['APP_BOOTS']):run() ]] local vanilla_app_resource = [[ [mc] conf=127.0.0.1:7348 127.0.0.1:11211 [redis] conf=127.0.0.1:7348 127.0.0.1:7349 [redisq] conf=127.0.0.1:7348 127.0.0.1:7349 [db.user.write] host =127.0.0.1 port =3306 dbname =user.info user =idevz passwd =idevz [db.user.read] host =127.0.0.1 port =3306 dbname =user.info user =idevz passwd =idevz ]] local index_controller_spec = [[ require 'spec.spec_helper' describe("PagesController", function() describe("#root", function() it("responds with a welcome message", function() local response = cgi({ method = 'GET', path = "/" }) assert.are.same(200, response.status) assert.are.same("hello vanilla.", response.body_raw) end) end) describe("#buested", function() it("responds with a welcome message for buested", function() local response = cgi({ method = 'GET', path = "/index/buested" }) assert.are.same(200, response.status) assert.are.same("hello buested.", response.body_raw) end) end) end) ]] local spec_helper = [[ package.path = package.path .. ";/?.lua;/?/init.lua;{{VANILLA_ROOT}}/{{VANILLA_VERSION_DIR_STR}}/?.lua;{{VANILLA_ROOT}}/{{VANILLA_VERSION_DIR_STR}}/?/init.lua;;"; package.cpath = package.cpath .. ";/?.so;{{VANILLA_ROOT}}/{{VANILLA_VERSION_DIR_STR}}/?.so;;"; Registry={} Registry['APP_ROOT'] = '{{APP_ROOT}}' Registry['APP_NAME'] = '{{APP_NAME}}' LoadV = function ( ... ) return require(...) end LoadApp = function ( ... ) return require(Registry['APP_ROOT'] .. '/' .. ...) end LoadV 'vanilla.spec.runner' ]] local sys_cache = [[ [shared_dict] dict=idevz exptime=100 [memcached] instances=127.0.0.1:11211 127.0.0.1:11211 exptime=60 timeout=100 poolsize=100 idletimeout=10000 [redis] instances=127.0.0.1:6379 127.0.0.1:6379 exptime=60 timeout=100 poolsize=100 idletimeout=10000 [lrucache] items=200 exptime=60 useffi=false ]] local sys_v_resource = [[ [mc] conf=127.0.0.1:7348 127.0.0.1:11211 [redis] conf=127.0.0.1:7348 127.0.0.1:7349 [redisq] conf=127.0.0.1:7348 127.0.0.1:7349 [db.user.write] host =127.0.0.1 port =3306 dbname =user.info user =idevz passwd =idevz [db.user.read] host =127.0.0.1 port =3306 dbname =user.info user =idevz passwd =idevz ]] local VaApplication = {} VaApplication.files = { ['.gitignore'] = gitignore, ['application/controllers/base.lua'] = base_controller, ['application/controllers/index.lua'] = index_controller, ['application/controllers/idevz.lua'] = idevz_controller, ['application/controllers/error.lua'] = error_controller, ['application/library/aa.lua'] = lib_aa, ['application/library/bb.lua'] = lib_bb, ['application/models/dao/table.lua'] = dao, ['application/models/service/user.lua'] = service, ['application/plugins/admin.lua'] = admin_plugin_tpl, ['application/views/index-index.html'] = index_tpl, ['application/views/error-error.html'] = error_tpl, ['application/bootstrap.lua'] = bootstrap, ['application/nginx/init/init.lua'] = nginx_init_by_lua_tpl, ['application/nginx/init/config.lua'] = nginx_init_config_tpl, ['config/errors.lua'] = errors_conf, -- ['config/nginx.lua'] = nginx_conf, ['config/restful.lua'] = restful_route_conf, ['config/waf.lua'] = waf_conf, ['config/waf-regs/args'] = waf_conf_regs_args, ['config/waf-regs/cookie'] = waf_conf_regs_cookie, ['config/waf-regs/post'] = waf_conf_regs_post, ['config/waf-regs/url'] = waf_conf_regs_url, ['config/waf-regs/user-agent'] = waf_conf_regs_ua, ['config/waf-regs/whiteurl'] = waf_conf_regs_whiteurl, ['pub/index.lua'] = vanilla_index, ['sys/v_resource'] = vanilla_app_resource, ['logs/hack/.gitkeep'] = "", ['spec/controllers/index_controller_spec.lua'] = index_controller_spec, ['spec/models/.gitkeep'] = "", ['spec/spec_helper.lua'] = spec_helper, ['sys/cache'] = sys_cache, ['sys/v_resource'] = sys_v_resource, } function VaApplication.new(app_path) local app_name = utils.basename(app_path) print(ansicolors("Creating app %{blue}" .. app_name .. "%{reset}...")) VaApplication.files['nginx_conf/va-nginx.conf'] = sgsub(va_nginx_config_tpl, "{{VANILLA_ROOT}}", VANILLA_ROOT) VaApplication.files['nginx_conf/va-nginx-development.conf'] = sgsub(va_nginx_dev_config_tpl, "{{VANILLA_ROOT}}", VANILLA_ROOT) service_manage_sh = sgsub(service_manage_sh, "{{APP_NAME}}", app_name) service_manage_sh = sgsub(service_manage_sh, "{{OPENRESTY_NGINX_ROOT}}", VANILLA_NGX_PATH) service_manage_sh = sgsub(service_manage_sh, "{{VANILLA_VERSION}}", VANILLA_VERSION) VaApplication.files['va-' .. app_name .. '-service'] = sgsub(service_manage_sh, "{{VA_APP_PATH}}", app_path) dev_nginx_vhost_config_tpl = sgsub(dev_nginx_vhost_config_tpl, "{{APP_NAME}}", app_name) dev_nginx_vhost_config_tpl = sgsub(dev_nginx_vhost_config_tpl, "{{VANILLA_ROOT}}", VANILLA_ROOT) dev_nginx_vhost_config_tpl = sgsub(dev_nginx_vhost_config_tpl, "{{VANILLA_VERSION_DIR_STR}}", VANILLA_VERSION_DIR_STR) VaApplication.files['nginx_conf/dev_vhost/' .. app_name .. '.conf'] = sgsub(dev_nginx_vhost_config_tpl, "{{APP_ROOT}}", app_path) nginx_vhost_config_tpl = sgsub(nginx_vhost_config_tpl, "{{APP_NAME}}", app_name) nginx_vhost_config_tpl = sgsub(nginx_vhost_config_tpl, "{{VANILLA_ROOT}}", VANILLA_ROOT) nginx_vhost_config_tpl = sgsub(nginx_vhost_config_tpl, "{{VANILLA_VERSION_DIR_STR}}", VANILLA_VERSION_DIR_STR) VaApplication.files['nginx_conf/vhost/' .. app_name .. '.conf'] = sgsub(nginx_vhost_config_tpl, "{{APP_ROOT}}", app_path) application_conf = sgsub(application_conf, "{{APP_NAME}}", app_name) application_conf = sgsub(application_conf, "{{VANILLA_VERSION_DIR_STR}}", VANILLA_VERSION_DIR_STR) application_conf = sgsub(application_conf, "{{VANILLA_ROOT}}", VANILLA_ROOT) VaApplication.files['config/application.lua'] = application_conf spec_helper = sgsub(spec_helper, "{{VANILLA_ROOT}}", VANILLA_ROOT) spec_helper = sgsub(spec_helper, "{{VANILLA_VERSION_DIR_STR}}", VANILLA_VERSION_DIR_STR) spec_helper = sgsub(spec_helper, "{{APP_ROOT}}", app_path) spec_helper = sgsub(spec_helper, "{{APP_NAME}}", app_name) VaApplication.files['spec/spec_helper.lua'] = spec_helper -- vanilla_index = sgsub(vanilla_index, "{{VANILLA_VERSION_DIR_STR}}", VANILLA_VERSION_DIR_STR) -- vanilla_index = sgsub(vanilla_index, "{{APP_ROOT}}", app_path) -- VaApplication.files['pub/index.lua'] = sgsub(vanilla_index, "{{VANILLA_ROOT}}", VANILLA_ROOT) VaApplication.create_files(app_path) end function VaApplication.create_files(parent) for file_path, file_content in pairs(VaApplication.files) do local full_file_path = parent .. "/" .. file_path local full_file_dirname = utils.dirname(full_file_path) os_execute("mkdir -p " .. full_file_dirname .. " > /dev/null") local fw = io_open(full_file_path, "w") fw:write(file_content) fw:close() print(ansicolors(" %{blue}created file%{reset} " .. full_file_path)) end end return VaApplication
local plat = loader.GetPlatformName() if plat ~= "Unsupported" then loader.WindowedOnEdited() loader.SetWindowXOffset(10) loader.SetWindowYOffset(10) loader.SetWindowWidth(800) loader.SetWindowHeight(600) loader.SetToggleWindowCentered(1) --[[ At this point window is centered, so x & y should not have any effect. ]]-- loader.SetwindowrectangleOnEdited() loader.SetCounter(3) end
-- This is a generated file! Please edit source .ksy file and use kaitai-struct-compiler to rebuild -- -- This file is compatible with Lua 5.3 local class = require("class") require("kaitaistruct") local enum = require("enum") EnumDeepLiterals = class.class(KaitaiStruct) function EnumDeepLiterals:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function EnumDeepLiterals:_read() self.pet_1 = EnumDeepLiterals.Container1.Animal(self._io:read_u4le()) self.pet_2 = EnumDeepLiterals.Container1.Container2.Animal(self._io:read_u4le()) end EnumDeepLiterals.property.is_pet_1_ok = {} function EnumDeepLiterals.property.is_pet_1_ok:get() if self._m_is_pet_1_ok ~= nil then return self._m_is_pet_1_ok end self._m_is_pet_1_ok = self.pet_1 == EnumDeepLiterals.Container1.Animal.cat return self._m_is_pet_1_ok end EnumDeepLiterals.property.is_pet_2_ok = {} function EnumDeepLiterals.property.is_pet_2_ok:get() if self._m_is_pet_2_ok ~= nil then return self._m_is_pet_2_ok end self._m_is_pet_2_ok = self.pet_2 == EnumDeepLiterals.Container1.Container2.Animal.hare return self._m_is_pet_2_ok end EnumDeepLiterals.Container1 = class.class(KaitaiStruct) EnumDeepLiterals.Container1.Animal = enum.Enum { dog = 4, cat = 7, chicken = 12, } function EnumDeepLiterals.Container1:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function EnumDeepLiterals.Container1:_read() end EnumDeepLiterals.Container1.Container2 = class.class(KaitaiStruct) EnumDeepLiterals.Container1.Container2.Animal = enum.Enum { canary = 4, turtle = 7, hare = 12, } function EnumDeepLiterals.Container1.Container2:_init(io, parent, root) KaitaiStruct._init(self, io) self._parent = parent self._root = root or self self:_read() end function EnumDeepLiterals.Container1.Container2:_read() end
--空牙団の闘士 ブラーヴォ --Blavo, Fighter of the Skyfang Brigade --Script by nekrozar function c100408019.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(100408019,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetCountLimit(1,100408019) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c100408019.sptg) e1:SetOperation(c100408019.spop) c:RegisterEffect(e1) --atk up local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(100408019,1)) e2:SetCategory(CATEGORY_ATKCHANGE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetProperty(EFFECT_FLAG_DELAY) e2:SetCode(EVENT_SPSUMMON_SUCCESS) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1,100421119) e2:SetCondition(c100408019.atkcon) e2:SetTarget(c100408019.atktg) e2:SetOperation(c100408019.atkop) c:RegisterEffect(e2) end function c100408019.spfilter(c,e,tp) return c:IsSetCard(0x214) and not c:IsCode(100408019) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100408019.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c100408019.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c100408019.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c100408019.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function c100408019.cfilter(c,tp) return c:IsFaceup() and c:IsSetCard(0x214) and c:IsControler(tp) end function c100408019.atkcon(e,tp,eg,ep,ev,re,r,rp) return not eg:IsContains(e:GetHandler()) and eg:IsExists(c100408019.cfilter,1,nil,tp) end function c100408019.atkfilter(c) return c:IsFaceup() and c:IsSetCard(0x214) end function c100408019.atktg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100408019.atkfilter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end end function c100408019.atkop(e,tp,eg,ep,ev,re,r,rp) local tg=Duel.GetMatchingGroup(c100408019.atkfilter,tp,LOCATION_MZONE,LOCATION_MZONE,nil) if tg:GetCount()>0 then local sc=tg:GetFirst() while sc do local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(500) sc:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENSE) sc:RegisterEffect(e2) sc=tg:GetNext() end end end
ESX = nil local ItemsLabels = {} local ItemLabelsLicenses = {} TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) AddEventHandler('onMySQLReady', function() MySQL.Async.fetchAll( 'SELECT * FROM items', {}, function(result) for i=1, #result, 1 do ItemsLabels[result[i].name] = result[i].label end end ) TriggerEvent('esx_license:getLicensesList', function(licenses) for i=1, #licenses, 1 do ItemLabelsLicenses[licenses[i].type] = licenses[i].label end end) end) RegisterServerEvent('esx_shops:buyItem') AddEventHandler('esx_shops:buyItem', function(itemType, itemName, price) local _source = source local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= price then xPlayer.removeMoney(price) xPlayer.addInventoryItem(itemName, 1) TriggerClientEvent('esx:showNotification', _source, 'Vous avez acheté ~b~1x ' .. ItemsLabels[itemName]) elseif xPlayer.get('bank') >= price then xPlayer.removeAccountMoney('bank', price) xPlayer.addInventoryItem(itemName, 1) TriggerClientEvent('esx:showNotification', _source, 'Vous avez acheté ~b~1x ' .. ItemsLabels[itemName].. ' ~w~avec votre carte bancaire') else TriggerClientEvent('esx:showNotification', _source, 'Vous n\'avez pas assez d\'argent sur vous ni sur votre carte bancaire') end end) ESX.RegisterServerCallback('esx_shops:requestDBItems', function(source, cb) MySQL.Async.fetchAll( 'SELECT * FROM shops', {}, function(result) local shopItems = {} for i=1, #result, 1 do if shopItems[result[i].name] == nil then shopItems[result[i].name] = {} end local label = nil if result[i].type == 'item_standard' then label = ItemsLabels[result[i].item] elseif result[i].type == 'item_license' then label = ItemLabelsLicenses[result[i].item] end table.insert(shopItems[result[i].name], { name = result[i].item, price = result[i].price, label = label, type = result[i].type }) end cb(shopItems) end ) end)
-- mod_ipcheck.lua -- Implementation of XEP-0279: Server IP Check <http://xmpp.org/extensions/xep-0279.html> local st = require "util.stanza"; module:add_feature("urn:xmpp:sic:0"); module:hook("iq-get/bare/urn:xmpp:sic:0:ip", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.to then origin.send(st.error_reply(stanza, "auth", "forbidden", "You can only ask about your own IP address")); elseif origin.ip then origin.send(st.reply(stanza):tag("ip", {xmlns='urn:xmpp:sic:0'}):text(origin.ip)); else -- IP addresses should normally be available, but in case they are not origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "IP address for this session is not available")); end return true; end); module:add_feature("urn:xmpp:sic:1"); module:hook("iq-get/bare/urn:xmpp:sic:1:address", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.to then origin.send(st.error_reply(stanza, "auth", "forbidden", "You can only ask about your own IP address")); elseif origin.ip then local reply = st.reply(stanza):tag("address", {xmlns='urn:xmpp:sic:1'}) :tag("ip"):text(origin.ip):up() if origin.conn and origin.conn.port then -- server_event reply:tag("port"):text(tostring(origin.conn:port())) elseif origin.conn and origin.conn.clientport then -- server_select reply:tag("port"):text(tostring(origin.conn:clientport())) end origin.send(reply); else -- IP addresses should normally be available, but in case they are not origin.send(st.error_reply(stanza, "cancel", "service-unavailable", "IP address for this session is not available")); end return true; end);
object_mobile_angler_king = object_mobile_shared_angler_king:new { } ObjectTemplates:addTemplate(object_mobile_angler_king, "object/mobile/angler_king.iff")
local context = G.botContext -- callback(callbackType, callback) context.callback = function(callbackType, callback) if not context._callbacks[callbackType] then return error("Wrong callback type: " .. callbackType) end if callbackType == "onAddThing" or callbackType == "onRemoveThing" then g_game.enableTileThingLuaCallback(true) end local desc = "lua" local info = debug.getinfo(2, "Sl") if info then desc = info.short_src .. ":" .. info.currentline end local callbackData = {} table.insert(context._callbacks[callbackType], function(...) if not callbackData.delay or callbackData.delay < context.now then local prevExecution = context._currentExecution context._currentExecution = callbackData local start = g_clock.realMillis() callback(...) local executionTime = g_clock.realMillis() - start if executionTime > 100 then context.warning("Slow " .. callbackType .. " (" .. executionTime .. "ms): " .. desc) end context._currentExecution = prevExecution end end) local cb = context._callbacks[callbackType] return { remove = function() local index = nil for i, cb2 in ipairs(context._callbacks[callbackType]) do if cb == cb2 then index = i end end if index then table.remove(context._callbacks[callbackType], index) end end } end -- onKeyDown(callback) -- callback = function(keys) context.onKeyDown = function(callback) return context.callback("onKeyDown", callback) end -- onKeyPress(callback) -- callback = function(keys) context.onKeyPress = function(callback) return context.callback("onKeyPress", callback) end -- onKeyUp(callback) -- callback = function(keys) context.onKeyUp = function(callback) return context.callback("onKeyUp", callback) end -- onTalk(callback) -- callback = function(name, level, mode, text, channelId, pos) context.onTalk = function(callback) return context.callback("onTalk", callback) end -- onTextMessage(callback) -- callback = function(mode, text) context.onTextMessage = function(callback) return context.callback("onTextMessage", callback) end -- onAddThing(callback) -- callback = function(tile, thing) context.onAddThing = function(callback) return context.callback("onAddThing", callback) end -- onRemoveThing(callback) -- callback = function(tile, thing) context.onRemoveThing = function(callback) return context.callback("onRemoveThing", callback) end -- onCreatureAppear(callback) -- callback = function(creature) context.onCreatureAppear = function(callback) return context.callback("onCreatureAppear", callback) end -- onCreatureDisappear(callback) -- callback = function(creature) context.onCreatureDisappear = function(callback) return context.callback("onCreatureDisappear", callback) end -- onCreaturePositionChange(callback) -- callback = function(creature, newPos, oldPos) context.onCreaturePositionChange = function(callback) return context.callback("onCreaturePositionChange", callback) end -- onCreatureHealthPercentChange(callback) -- callback = function(creature, healthPercent) context.onCreatureHealthPercentChange = function(callback) return context.callback("onCreatureHealthPercentChange", callback) end -- onUse(callback) -- callback = function(pos, itemId, stackPos, subType) context.onUse = function(callback) return context.callback("onUse", callback) end -- onUseWith(callback) -- callback = function(pos, itemId, target, subType) context.onUseWith = function(callback) return context.callback("onUseWith", callback) end -- onContainerOpen -- callback = function(container, previousContainer) context.onContainerOpen = function(callback) return context.callback("onContainerOpen", callback) end -- onContainerClose -- callback = function(container) context.onContainerClose = function(callback) return context.callback("onContainerClose", callback) end -- onContainerUpdateItem -- callback = function(container, slot, item) context.onContainerUpdateItem = function(callback) return context.callback("onContainerUpdateItem", callback) end -- onMissle -- callback = function(missle) context.onMissle = function(callback) return context.callback("onMissle", callback) end -- onAnimatedText -- callback = function(thing, text) context.onAnimatedText = function(callback) return context.callback("onAnimatedText", callback) end -- onStaticText -- callback = function(thing, text) context.onStaticText = function(callback) return context.callback("onStaticText", callback) end -- onChannelList -- callback = function(channels) context.onChannelList = function(callback) return context.callback("onChannelList", callback) end -- onOpenChannel -- callback = function(channelId, name) context.onOpenChannel = function(callback) return context.callback("onOpenChannel", callback) end -- onCloseChannel -- callback = function(channelId) context.onCloseChannel = function(callback) return context.callback("onCloseChannel", callback) end -- onChannelEvent -- callback = function(channelId, name, event) context.onChannelEvent = function(callback) return context.callback("onChannelEvent", callback) end -- onTurn -- callback = function(creature, direction) context.onTurn = function(callback) return context.callback("onTurn", callback) end -- CUSTOM CALLBACKS -- listen(name, callback) -- callback = function(text, channelId, pos) context.listen = function(name, callback) if not name then return context.error("listen: invalid name") end name = name:lower() return context.onTalk(function(name2, level, mode, text, channelId, pos) if name == name2:lower() then callback(text, channelId, pos) end end) end -- onPlayerPositionChange(callback) -- callback = function(newPos, oldPos) context.onPlayerPositionChange = function(callback) return context.onCreaturePositionChange(function(creature, newPos, oldPos) if creature == context.player then callback(newPos, oldPos) end end) end -- onPlayerHealthChange(callback) -- callback = function(healthPercent) context.onPlayerHealthChange = function(callback) return context.onCreatureHealthPercentChange(function(creature, healthPercent) if creature == context.player then callback(healthPercent) end end) end
----------------------------------------------------------------------------- -- Copyright (c) 2015 Intel Research and Development Ireland Ltd. -- -- 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. ----------------------------------------------------------------------------- ------------------------------- ----- RFC-2544 throughput ----- ------------------------------- package.path = package.path ..";?.lua;test/?.lua;app/?.lua;../?.lua" require "Pktgen"; ----- Packet Gen Configuration local sendport = "0"; local recvport = "1"; pktgen.set(recvport, "rate", 1); pktgen.vlan(sendport, "on"); pktgen.ping4("all"); pktgen.icmp_echo("all", "on"); pktgen.process("all", "on"); ----- RFC2544 Configuration local traffic_delay = 60; -- Time in seconds to delay. local multicast_delay = 15; -- Time in seconds to delay. local starting_rate = 100; -- Initial Rate in % local step = 100; -- Initial Step in % local down_limit = 0; local up_limit = 100; -- Creation of a module --local rfc2544 = {} function start_traffic(rate) local endStats, diff, prev, iteration, flag, found; flag = false; found = false; print("PACKET GENERATION - " .. rate .. "%\n"); -- Send packet to join the multicast group print("Join Multicast Group"); pktgen.start(recvport); sleep(multicast_delay); pktgen.stop(recvport); pktgen.clr(); -- Send traffic at the specified rate print("Start Generation"); pktgen.set(sendport, "rate", rate); sleep(1); pktgen.start(sendport); sleep(traffic_delay); pktgen.stop(sendport); print("Stop Generation"); sleep(5); -- Collect statistics about the experiment endStats = pktgen.portStats("all", "port"); diff = endStats[0].opackets - endStats[1].ipackets; if ( endStats[0].opackets <= 0) then diff = 0; else diff = diff / endStats[0].opackets; end pktgen.clr(); print("Missing packets: " .. (diff * 100)); -- Adjust variable for the next race prev_rate = rate; step = step/2; if ( diff > 0.01) then if(endStats[0].opackets > 0) then up_limit = rate; rate = math.floor(rate - (step)); end else down_limit = rate; rate = math.floor(rate + (step)); print("\nRATE: " .. rate .. " RECEIVED PACKETS: " .. endStats[1].ipackets .. " "); found = true; end printf("DOWN LIMIT: %d\n", down_limit); printf("UP LIMIT: %d\n", up_limit); if ( rate >= 100 ) then rate = 100; end if ( prev ~= rate and rate < up_limit and rate >= down_limit and step >= 1 ) then if (step < 1 and not found ) or (step >= 1 ) then return start_traffic(rate); end end sleep(3); return down_limit; end local out_file = ""; local starting_rate = 100; pktgen.clr(); print("RFC 2544 THROUGHPUT CALCULATION"); -- Write output on log file file = io.open(out_file, "w"); -- Start experiment --rate = rfc2544.start_traffic(starting_rate) rate = start_traffic(starting_rate); print("RATE: " .. rate); file:write(rate); -- Close the log file file:close(); -- Quit the environment os.exit(1);
--- -- @classmod Circle local middleclass = require("middleclass") local typeutils = require("typeutils") --- -- @table instance -- @tfield number x -- @tfield number y -- @tfield number radius [0, ∞) local Circle = middleclass("Circle") --- -- @function new -- @tparam number x -- @tparam number y -- @tparam number radius [0, ∞) -- @treturn Circle function Circle:initialize(x, y, radius) assert(typeutils.is_number(x)) assert(typeutils.is_number(y)) assert(typeutils.is_positive_number(radius)) self.x = x self.y = y self.radius = radius end return Circle
local unique = {} -- List of Database Unique IDs (SQL) by Server ID local fivem = {} -- List of FiveM License IDs by Server ID local scores = {} -- Scores of players (KEYS: 'cop' and 'civ') local positions = {} -- List of positions being saved local zone = { timer = 300, -- Time in minutes between zone changes count = 4, -- Number of zones to use active = 1, -- The currently active zone pick = 18000000, -- The next time to pick a zone (in ms) } local reduce = { -- Reduction of wanted level points = 0.25, -- Points each tick tickTime = 1 -- Time in seconds between reductions } --[[ -------------------------------------------------------------------------- ~ BEGIN POSITION AQUISITION SCRIPTS 1) Players, when loaded, will submit their position every 12 seconds 2) The server, every 30 seconds, loops through the positions table 3) For each entry found, it will update their last known position in SQL 4) When the update succeeds, it will remove the position entry 5) When a player drops, it will send and immediate update. ]]----------------------------------------------------------------------------- local positions = {} RegisterServerEvent('cnr:save_pos') AddEventHandler('cnr:save_pos', function(pos) local ply = source local uid = unique[ply] if uid then print("DEBUG - Preserved position for Unique ID #"..uid) positions[uid] = pos end end) function SavePlayerPos(uid,pos) if uid then if not pos then pos = positions[uid] end if pos then exports['ghmattimysql']:execute( "UPDATE characters SET position = @p WHERE idUnique = @uid", {['p'] = pos, ['uid'] = uid}, function() -- Once updated, remove entry print("DEBUG - Position ("..positions[uid]..") saved for UID #"..uid) positions[uid] = nil end ) end end end AddEventHandler('playerDropped', function(reason) local ply = source local uid = unique[ply] local plyInfo = GetPlayerName(ply) if uid then SavePlayerPos(uid, positions[uid]) end ConsolePrint( "^1"..tostring(plyInfo).." disconnected. ^7("..tostring(reason)..")" ) exports['cnr_chat']:DiscordMessage( 16711680, tostring(plyInfo).." Disconnected", tostring(reason), "" ) end) --[[--------------------------------------------------------------------------- ~ END OF POSITION ACQUISITION SCRIPTS --]] --- ConsolePrint() -- Nicely formatted console print with timestamp -- @param msg The message to be displayed function ConsolePrint(msg) if msg then local dt = os.date("%H:%M", os.time()) print("[CNR "..dt.."] ^7"..(msg).."^7") end end AddEventHandler('cnr:print', ConsolePrint) --- EXPORT: UniqueId() -- Assigns / Retrieves player's Unique ID (SQL Database ID Number) -- @param ply The player (server ID) to get the UID for -- @param uid If provided, sets player's UID. If nil, returns UID -- @return Returns the Unique ID, or 0 if not found function UniqueId(ply, uid) if ply then -- If UID is given, assign it. if uid then unique[ply] = uid -- Otherwise, find it. else local idFound = nil -- If unique ID doesn't exist, find it for _,id in pairs(GetPlayerIdentifiers(ply)) do if string.sub(id, 1, string.len("steam:")) == "steam:" then idFound = id print("DEBUG - Found Steam ID ["..id.."]") elseif string.sub(id, 1, string.len("license:")) == "license:" then if not idFound then -- Prefer the SteamID versus the FiveM ID idFound = id print("DEBUG - Found FiveM ID ["..id.."]") end end end if idFound then local idNumber = exports['ghmattimysql']:scalarSync( "SELECT idUnique FROM players ".. "WHERE idSteam = @idNum OR idFiveM = @idNum LIMIT 1", {['idNum'] = idFound} ) unique[ply] = idNumber else unique[ply] = 0 end end else print("DEBUG - ERROR; 'ply' not given to 'UniqueId()' (sv_cnrobbers.lua)") return 0 -- No 'ply' given, return 0 end return (unique[ply]) end --- EXPORT: CurrentZone() -- Returns the current zone value -- @return The current zone (always int) function CurrentZone() return (zone.active) end --- EXPORT: GetFullZoneName() -- Returns the name found for the zone in shared.lua -- If one isn't found, returns "San Andreas" -- @param abbrv The abbreviation of the zone name given by runtime -- @return A string containing the proper zone name ("LS Airport") function GetFullZoneName(abbrv) if not zoneByName[abbrv] then return "San Andreas" end return (zoneByName[abbrv]) end --- EXPORT: ZoneNotification() -- Called when the zone is changing / has changed / will be changed function ZoneNotification(i, t, s, m) TriggerClientEvent('cnr:chat_notify', (-1), i, t, s, m) end --- EXPORT: GetUniqueId() -- Returns the player's Unique ID. If not found, attempts to find it (SQL) -- DEBUG - OBSOLETE; Use 'UniqueId(ply, uid)' instead -- @return The player's UID, or 0 if not found (always int) function GetUniqueId(ply) if not unique[ply] then -- If unique ID doesn't exist, find it -- We know they have one because of deferral check upon joining. local sid = nil for _,id in pairs(GetPlayerIdentifiers(ply)) do if string.sub(id, 1, string.len("steam:")) == "steam:" then sid = id end end -- If Steam ID was found, retrieve player's UID. if sid then local steam = exports['ghmattimysql']:scalarSync( "SELECT idUnique FROM players WHERE idSteam = @steam LIMIT 1", {['steam'] = sid} ) unique[ply] = steam else unique[ply] = 0 end end return unique[ply] end --- ZoneChange() -- Handles changing over the zone. No params, no return. function ZoneChange() local newZone = math.random(zone.count) while newZone == zone.active do newZone = math.random(zone.count); Wait(1) end local n = 300 -- 5 Minutes, in seconds ConsolePrint("^3Zone "..(newZone).." will unlock in 5 minutes.") while n > 30 do if n % 60 == 0 then local mins = (n/60).." minutes" if n/60 == 1 then mins = "1 minute" elseif n/60 < 1 then mins = n.." seconds" end TriggerClientEvent('chat:addMessage', (-1), {args = {"ZONE CHANGE", "^3"..mins.."^1 until zone change!"} }) ZoneNotification("CHAR_SOCIAL_CLUB", "Zone Change", "~r~"..mins, "Active zone is changing soon!" ) end n = n - 1 Wait(1000) end Citizen.Wait(20000) for i = 0, 9 do TriggerClientEvent('chat:addMessage', (-1), {args = {"^1Zone ^3#"..newZone.." ^1activates in ^3"..(10-i).." Second(s)^1!!"}} ) Citizen.Wait(1000) end zone.active = newZone ConsolePrint("^2Zone "..(newZone).." is now active.") TriggerClientEvent('chat:addMessage', (-1), {args = {"^2Zone ^7#"..(newZone).." ^2is now the active Zone! (^7/zones^2)"}} ) ZoneNotification("CHAR_SOCIAL_CLUB", "Zone Change", "~g~New Zone Active", "Zone #"..newZone.." is active." ) -- Tell clients and server the zone has changed -- This gives the option to use exports['cnrobbers']:CurrentZone(), or to wait for event -- DO NOT MAKE THIS EVENT SAFE FOR NETWORKING TriggerClientEvent('cnr:zone_change', (-1), newZone) TriggerEvent('cnr:zone_change', newZone) end -- Runs the zone change timer for choosing which zone is being played function ZoneLoop() while true do if GetGameTimer() > zone.pick then zone.pick = GetGameTimer() + (zone.timer * 60 * 1000) --[[ Threaded to ensure the (zone.timer) is consistent, and doesn't add 5 minutes of tick every time the script decides to change the zone. ]] Citizen.CreateThread(ZoneChange) end Citizen.Wait(1000) end end Citizen.CreateThread(ZoneLoop) -- When a client has loaded in the game, send them relevant script details RegisterServerEvent('cnr:client_loaded') AddEventHandler('cnr:client_loaded', function() TriggerClientEvent('cnr:active_zone', source, zone.active) end) SetGameType('5M Cops and Robbers')
local system = require "coutil.system" newtest "address" -------------------------------------------------------------- do case "empty ipv4" local a = system.address("ipv4") assert(tostring(a) == "0.0.0.0:0") assert(a.type == "ipv4") assert(a.port == 0) assert(a.literal == "0.0.0.0") assert(a.binary == "\0\0\0\0") assert(a == system.address("ipv4")) done() end do case "empty ipv6" local a = system.address("ipv6") assert(tostring(a) == "[::]:0") assert(a.type == "ipv6") assert(a.port == 0) assert(a.literal == "::") assert(a.binary == string.rep("\0", 16)) assert(a == system.address("ipv6")) done() end local cases = { ipv4 = { port = 8080, literal = "192.168.0.1", binary = "\192\168\000\001", uri = "192.168.0.1:8080", changes = { port = 54321, literal = "127.0.0.1", binary = "byte", }, equivalents = { ["10.20.30.40"] = "\10\20\30\40", ["40.30.20.10"] = "\40\30\20\10", }, invalid = "291.168.0.1", }, ipv6 = { port = 8888, literal = "::ffff:192.168.0.1", binary = "\0\0\0\0\0\0\0\0\0\0\xff\xff\192\168\000\001", uri = "[::ffff:192.168.0.1]:8888", changes = { port = 12345, literal = "::1", binary = "bytebytebytebyte", }, equivalents = { ["1::f"] = "\0\1\0\0\0\0\0\0\0\0\0\0\0\0\0\x0f", ["1:203:405:607:809:a0b:c0d:e0f"] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f", ["123:4567:89ab:cdef:fedc:ba98:7654:3210"] = "\x01\x23\x45\x67\x89\xab\xcd\xef\xfe\xdc\xba\x98\x76\x54\x32\x10", }, invalid = "[291:168:0:1]", }, } for type, expected in pairs(cases) do local addr = system.address(type, expected.uri) local function checkaddr(a) --assert(system.type(a) == "address") assert(tostring(a) == expected.uri) assert(a.type == type) assert(a.port == expected.port) assert(a.literal == expected.literal) assert(a.binary == expected.binary) assert(a == addr) end do case("create "..type) checkaddr(addr) checkaddr(system.address(type, expected.literal, expected.port)) checkaddr(system.address(type, expected.literal, expected.port, "t")) checkaddr(system.address(type, expected.binary, expected.port, "b")) done() end do case("change "..type) for field, newval in pairs(expected.changes) do local oldval = addr[field] addr[field] = newval assert(addr[field] == newval) addr[field] = oldval checkaddr(addr) end for literal, binary in pairs(expected.equivalents) do addr.literal = literal assert(addr.binary == binary) end for literal, binary in pairs(expected.equivalents) do addr.binary = binary assert(addr.literal == literal) end done() end do case("bad field "..type) local a = system.address(type) asserterr("bad argument #2 to 'index' (invalid option 'wrongfield')", pcall(function () return a.wrongfield end)) asserterr("bad argument #2 to 'newindex' (invalid option 'wrongfield')", pcall(function () a.wrongfield = true end)) asserterr("bad argument #2 to 'newindex' (invalid option 'type')", pcall(function () a.type = true end)) if type == "file" then asserterr("bad argument #2 to 'newindex' (invalid option 'port')", pcall(function () a.port = 1234 end)) end done() end do case("errors "..type) asserterr("bad argument #1 to 'coutil.system.address' (invalid option 'ip')", pcall(system.address, "ip")) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got boolean)", pcall(system.address, type, true)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got boolean)", pcall(system.address, type, true, expected.port)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got boolean)", pcall(system.address, type, true, expected.port, "t")) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got boolean)", pcall(system.address, type, true, expected.port, "b")) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, nil)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, nil, nil)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, expected.port)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, expected.port, "t")) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, expected.port, "b")) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, nil)) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, nil, "t")) asserterr("bad argument #2 to 'coutil.system.address' (string or memory expected, got nil)", pcall(system.address, type, nil, nil, "b")) asserterr("bad argument #3 to 'coutil.system.address' (number expected, got nil)", pcall(system.address, type, expected.uri, nil)) asserterr("bad argument #3 to 'coutil.system.address' (number expected, got nil)", pcall(system.address, type, expected.literal, nil, "t")) asserterr("bad argument #3 to 'coutil.system.address' (number expected, got nil)", pcall(system.address, type, expected.binary, nil, "b")) asserterr("bad argument #3 to 'coutil.system.address' (number expected, got string)", pcall(system.address, type, expected.literal, "port")) asserterr("bad argument #3 to 'coutil.system.address' (number expected, got string)", pcall(system.address, type, expected.literal, "port", "t")) asserterr("bad argument #3 to 'coutil.system.address' (number expected, got string)", pcall(system.address, type, expected.literal, "port", "b")) asserterr("bad argument #4 to 'coutil.system.address' (invalid mode)", pcall(system.address, type, 3232235776, expected.port, "n")) asserterr("bad argument #2 to 'coutil.system.address' (invalid URI format)", pcall(system.address, type, expected.literal)) asserterr("invalid argument", pcall(system.address, type, type == "ipv4" and "localhost:8080" or "[ip6-localhost]:8080")) asserterr("invalid argument", pcall(system.address, type, expected.invalid..":8080")) asserterr("bad argument #2 to 'coutil.system.address' (invalid port)", pcall(system.address, type, (string.gsub(expected.uri, expected.port.."$", "65536")))) asserterr("bad argument #2 to 'coutil.system.address' (invalid port)", pcall(system.address, type, (string.gsub(expected.uri, expected.port.."$", "-"..expected.port)))) asserterr("bad argument #2 to 'coutil.system.address' (invalid port)", pcall(system.address, type, (string.gsub(expected.uri, expected.port.."$", "0x1f90")))) asserterr("invalid argument", pcall(system.address, type, "localhost", expected.port, "t")) asserterr("invalid argument", pcall(system.address, type, expected.invalid, expected.port, "t")) asserterr("bad argument #3 to 'coutil.system.address' (invalid port)", pcall(system.address, type, expected.literal, 65536, "t")) asserterr("bad argument #3 to 'coutil.system.address' (invalid port)", pcall(system.address, type, expected.literal, -1, "t")) asserterr("bad argument #3 to 'coutil.system.address' (invalid port)", pcall(system.address, type, expected.binary, 65536, "b")) asserterr("bad argument #3 to 'coutil.system.address' (invalid port)", pcall(system.address, type, expected.binary, -1, "b")) done() end end newtest "findaddr" ------------------------------------------------------------- local hosts = { localhost = { ["127.0.0.1"] = "ipv4", ["::1"] = "ipv6", }, --["ip6-localhost"] = { ["::1"] = "ipv6" }, ["*"] = { ["0.0.0.0"] = "ipv4", ["::"] = "ipv6", }, } hosts[false] = hosts.localhost local servs = { ssh = 22, http = 80, [false] = 0, [54321] = 54321, } local scktypes = { datagram = true, stream = true, passive = true, } local addrtypes = { ipv4 = system.address("ipv4"), ipv6 = system.address("ipv6"), } local function allexpected(ips, hostname, servport) local stream = hostname == "*" and "passive" or "stream" local missing = {} for literal, domain in pairs(ips) do missing[literal.." "..servport.." datagram"] = true missing[literal.." "..servport.." "..stream] = true end return missing end local function clearexpected(missing, found, scktype) if standard == "win32" and scktype == nil then missing[found.literal.." "..found.port.." datagram"] = nil missing[found.literal.." "..found.port.." stream"] = nil missing[found.literal.." "..found.port.." passive"] = nil else missing[found.literal.." "..found.port.." "..scktype] = nil end end do case "reusing addresses" spawn(function () for hostname, ips in pairs(hosts) do for servname, servport in pairs(servs) do if servname or (hostname and hostname ~= "*") then local addrlist = assert(system.findaddr(hostname or nil, servname or nil)) for i = 1, 2 do local missing = allexpected(ips, hostname, servport) local addr, domain, scktype repeat domain = addrlist:getdomain() addr = assert(addrtypes[domain]) local other = domain == "ipv4" and addrtypes.ipv6 or addrtypes.ipv4 asserterr("wrong domain", pcall(addrlist.getaddress, addrlist, other)) local found = addrlist:getaddress(addr) assert(rawequal(found, addr)) assert(ips[found.literal] == domain) assert(found.port == servport) scktype = addrlist:getsocktype() assert(domain == nil or addrtypes[domain] ~= nil) assert(standard == "win32" and scktype == nil or scktypes[scktype] == true) clearexpected(missing, found, scktype) until not addrlist:next() assert(domain == addrlist:getdomain()) assert(addr == addrlist:getaddress()) assert(scktype == addrlist:getsocktype()) addrlist:reset() end end end end end) assert(system.run() == false) done() end do case "create addresses" spawn(function () for hostname, ips in pairs(hosts) do for servname, servport in pairs(servs) do if servname or (hostname and hostname ~= "*") then local missing = allexpected(ips, hostname, servport) local addrlist = assert(system.findaddr(hostname or nil, servname or nil)) repeat local found = addrlist:getaddress() local scktype = addrlist:getsocktype() assert(addrlist:getdomain() == found.type) assert(ips[found.literal] ~= nil) assert(found.port == servport) assert(standard == "win32" and scktype == nil or scktypes[scktype] == true) clearexpected(missing, found, scktype) until not addrlist:next() end end end end) assert(system.run() == false) done() end do case "error messages" spawn(function () asserterr("name or service must be provided", pcall(system.findaddr)) asserterr("name or service must be provided", pcall(system.findaddr, nil)) asserterr("name or service must be provided", pcall(system.findaddr, nil, nil)) asserterr("service must be provided for '*'", pcall(system.findaddr, "*")) asserterr("service must be provided for '*'", pcall(system.findaddr, "*")) asserterr("service must be provided for '*'", pcall(system.findaddr, "*", nil)) asserterr("'m' is invalid for IPv4", pcall(system.findaddr, "localhost", 0, "m4")) asserterr("unknown mode char (got 'i')", pcall(system.findaddr, "localhost", 0, "ipv6")) end) assert(system.run() == false) done() end newtest "nameaddr" ------------------------------------------------------------- local hosts = { localhost = { ipv4 = "127.0.0.1", ipv6 = "::1", }, } local servs = { ssh = 22, http = 80, } local names = { ["www.github.com"] = "github.com", } do case "host and service" spawn(function () for servname, port in pairs(servs) do assert(system.nameaddr(port) == servname) for hostname, ips in pairs(hosts) do for domain, ip in pairs(ips) do local addr = system.address(domain, ip, port) local name, service = system.nameaddr(addr) assert(name == standard == "win32" and system.procinfo("n") or hostname) assert(service == servname) end end end end) assert(system.run() == false) done() end do case "cannonical name" spawn(function () for name, cannonical in pairs(names) do assert(system.nameaddr(name) == cannonical) end end) assert(system.run() == false) done() end
GM.MingeSENTS = GAMEMODE.MingeSENTS or {} GM.MingeIcons = GAMEMODE.MingeIcons or {} --local variables local destructing_keys = { DrawIconModels = true, DrawIconWeaponModels = true, IconCamera = true, ReleaseIconModels = true, SetupIconModels = true } local render_size = 128 --local function local function draw_models(ENT, lighting) --automtically light up the entity with good settings if lighting then local lighting_side = lighting.Sides or {} render.SuppressEngineLighting(true) render.SetLightingOrigin(lighting.Position or vector_origin) if lighting.Default then render.ResetModelLighting(unpack(lighting.Default)) else render.ResetModelLighting(1, 1, 1) end end ENT:DrawIconModels() if ENT.DrawIconWeaponModels then ENT:DrawIconWeaponModels() end if lighting then render.SuppressEngineLighting(false) end end --gamemode functions function GM:MingeIconsGenerate(class, ENT, outline, outline_step, outline_minimum) local camera_data = ENT.IconCamera local existing_material = self.MingeIcons[class] local lighting = camera_data.AutoLighting local outline_minimum = outline_minimum or outline and -outline local outline_step = outline_step or 1 local render_target = GetRenderTargetEx("mdicons/" .. class, render_size, render_size, RT_SIZE_OFFSCREEN, MATERIAL_RT_DEPTH_SEPARATE, 256, 0, IMAGE_FORMAT_BGRA8888) local render_target_background = GetRenderTargetEx("mdicon_backgrounds/" .. class, render_size, render_size, RT_SIZE_OFFSCREEN, MATERIAL_RT_DEPTH_SEPARATE, 256, 0, IMAGE_FORMAT_BGRA8888) local render_target_background_material = CreateMaterial("mdicon_background_materials/" .. class, "UnlitGeneric", { ["$basetexture"] = render_target_background:GetName(), ["$translucent"] = 1, --we could also try $alphatest as it makes the model transparent not translucent ["$vertexcolor"] = 1 }) local camera_parameters = { camera_data.Position, camera_data.Angles or (camera_data.TargetPosition - camera_data.Position):Angle(), camera_data.FOV, 0, 0, render_size, render_size, camera_data.Near, camera_data.Far } --create the models and prepare for DrawIconModels to be called several times ENT:SetupIconModels() --create a silhouette of the models render.PushRenderTarget(render_target_background) --the depth buffer NEEDS to be cleared, but the stencil buffer probably doesn't matter render.Clear(0, 0, 0, 0, true, true) cam.Start3D(unpack(camera_parameters)) render.OverrideColorWriteEnable(true, false) draw_models(ENT, false) render.OverrideColorWriteEnable(false) cam.End3D() render.PopRenderTarget() --create the texture itself render.PushRenderTarget(render_target) render.Clear(0, 0, 0, 0, true, true) if outline then --draw an outline using the silhouette cam.Start2D() surface.SetDrawColor(255, 255, 255, 255) surface.SetMaterial(render_target_background_material) for x = outline_minimum, outline, outline_step do for y = outline_minimum, outline, outline_step do if x == 0 and y == 0 then continue end surface.DrawTexturedRect(x, y, 512, 512) end end cam.End2D() end --draw the model itself cam.Start3D(unpack(camera_parameters)) --more? draw_models(ENT, lighting) cam.End3D() render.PopRenderTarget() --delete models created by SetupIconModels ENT:ReleaseIconModels() if existing_material then existing_material:SetTexture("$basetexture", render_target) else existing_material = CreateMaterial("mdicon_" .. class, "UnlitGeneric", { ["$basetexture"] = render_target:GetName(), ["$translucent"] = 1, --we could also try $alphatest as it makes the model transparent not translucent ["$vertexcolor"] = 1 }) end return existing_material end function GM:MingeIconsScanSENTS() for class, data in pairs(scripted_ents.GetList()) do local ENT = scripted_ents.Get(class) --local overrides = data.t if ENT.GenerateIcon then --debugging! only do the first one right now local material = hook.Call("MingeIconsGenerate", self, class, ENT, 2) local stored = scripted_ents.GetStored(class) ENT.IconOverride = material:GetName() ENT.IconMaterial = material self.MingeIcons[class] = material self.MingeSENTS[class] = ENT --probably not good for reload... --for key, value in pairs(stored) do if destructing_keys[key] then stored[key] = nil end end elseif ENT.IsMinge then self.MingeSENTS[class] = ENT end end end function GM:MingeIconsTestIcons() local count = 0 local frame = vgui.Create("DFrame") frame:SetSize(1038, 1062) ----icon layout local layout = vgui.Create("DIconLayout", frame) layout:Dock(FILL) layout:SetSpaceX(4, 4) layout:SetSpaceY(4, 4) for class, icon in pairs(self.MingeIcons) do count = count + 1 local panel = layout:Add("DPanel") panel:SetSize(512, 512) function test:Paint(width, height) surface.SetDrawColor(255, 255, 255) surface.SetMaterial(icon) surface.DrawTexturedRect(0, 0, width, height) surface.SetDrawColor(0, 0, 0, 64) surface.DrawRect(0, 0, width, height) end do local label = vgui.Create("DLabel", panel) label:Dock(FILL) label:SetContentAlignment(2) label:SetText(class) end end frame:Center() frame:MakePopup() frame:SetTitle("Icon test with " .. count .. " icons") end
--to contain all debug actions in on table local debug = {} debug.myDebug = true if not hudebug then --make sure that hudebug is made hudebug = require("Libraries.hudebug.hudebug") end hudebug.toggle() --my own variable for tracking info debug.info = {} --set position to far right of screen hudebug.setPosition(love.graphics.getWidth() - 128 * 2, 0) function debug.setupGeneralPage() debug.setupNewPage("General", { {"page-count", function() return "Debug Pages: "..hudebug.pageCount end}, {"fps", function() return "FPS: "..love.timer.getFPS() end}, }) end --info is passed. info contain a name and a function to use function debug.setupNewPage(pageName, info) hudebug.pageName(hudebug.pageCount + 1, pageName) debug.info[hudebug.pageCount] = info return hudebug.pageCount end --Add info example: --[[ debug.addInfo(self.debugPage, {"physics-position", function() local x, y = self.physicsHandle.body:getPosition() return "Physics Position: ("..math.floor(x)..", "..math.floor(y)..")" end} ) ]] function debug.addInfo(pageNum, info) table.insert(debug.info[pageNum], info) end function debug.updateCurrentPage() for i,v in ipairs(debug.info[hudebug.page]) do --update each line in current page hudebug.updateMsg( hudebug.page, v[1], v[2]() ) end end function debug.draw() hudebug.draw() --draw hudebug love.graphics.setColor(255, 255, 255) -- set color to default white end function debug.toggleHUDebug() hudebug.toggle() end function debug.togglePage() hudebug.nextPage() end return debug
require("layouts/default") require("layouts/interleaved") require("layouts/chests") black_list = { "extractor", "underground", "factory.port.marker","vehicle.miner.*attachment", "splitter", "loader", "pumpjack", "water", "factory.connection", "dummy", "proxy"} buttons = {} mode_buttons = {} layout_buttons = {} entity_selections = { belt = "transport-belt", miner = "electric-mining-drill", pole = "small-electric-pole", chest = "iron-chest" } new_selections = { belt = "transport-belt", miner = "electric-mining-drill", pole = "small-electric-pole", chest = "iron-chest" } deconstruction = true research_only = false ghosts = true active_direction = "left" spacing_mode = "tight" layout_strategy = "default" function remote_on_player_selected_area(event, alt) if (event.item == "remote-control") then local player = game.players[event.player_index] -- select remote_deselect_units(player) local area = event.area -- non-zero area.left_top.x = area.left_top.x - 0.01 area.left_top.y = area.left_top.y - 0.01 area.right_bottom.x = area.right_bottom.x + 0.01 area.right_bottom.y = area.right_bottom.y + 0.01 local select_entities = player.surface.find_entities_filtered{ area = area, type = "resource", fores = player.force } local data = {} global.player_selected_units[player.index] = data data["all"] = { amount = 0, entities = {}} local item_found = false for _, entity in pairs(select_entities) do if not string.match(entity.name, "oil") and not string.match(entity.name, "water") then --skip oil and water patches item_found = true if not data[entity.name] then data[entity.name] = {amount = 0, entities={}} end data[entity.name].amount = data[entity.name].amount + entity.amount data["all"].amount = data["all"].amount + entity.amount table.insert(data[entity.name].entities,entity) table.insert(data["all"].entities, entity) end end for name, itemdata in pairs(data) do local boudingbox = {{2000000,2000000},{-2000000,-2000000}} -- lefttop, rightbottom itemdata.area = boudingbox for _, entity in pairs(itemdata.entities) do extend_bounding_box(entity.position, boudingbox) end end if item_found then remote_show_gui(player) end end end function extend_bounding_box(point, box) if point.x < box[1][1] then box[1][1] = math.floor(point.x) end if point.y < box[1][2] then box[1][2] = math.floor(point.y) end if point.x > box[2][1] then box[2][1] = math.ceil(point.x) end if point.y > box[2][2] then box[2][2] = math.ceil(point.y) end end function remote_on_player_cursor_stack_changed(event) local player = game.players[event.player_index] if player.cursor_stack and player.cursor_stack.valid and player.cursor_stack.valid_for_read then if player.cursor_stack.name == "remote-control" then -- else remote_deselect_units(player) end else remote_deselect_units(player) end end function remote_deselect_units(player) remote_hide_gui(player) if not global.player_selected_units then global.player_selected_units = {} end end function remote_on_init() global.player_selected_units = {} end function is_item_researched(player,item) for _, recipe in pairs(player.force.recipes) do for _2, product in pairs(recipe.products) do if (product.name == item.name) then return recipe.enabled end end end return false end function is_entity_researched(player, entity) for key, proto in pairs(entity.items_to_place_this ) do if is_item_researched(player , proto) then return true end end return false end function show_picker(key, player, items) if player.gui.center[key .. "_picker"] == nil then new_selections[key] = entity_selections[key] local frame = player.gui.center.add { type = "frame", name = key .. "_picker" , direction=vertical} local vflow = frame.add { type="flow", direction = "vertical", name="container" } local selection_flow = vflow.add { type="flow", direction = "horizontal", name = "selection" } local selected_belt = selection_flow.add { type= "sprite-button", style = "square-button", name = "selected_" .. key, sprite = get_icon( entity_selections[key]) } local pick = selection_flow.add { type = "button", caption = "Pick", name ="pick_"..key.."_button" } local grid = vflow.add { type="table", column_count = #items + 1, name= key .. "-table" } grid.add { type= "sprite-button", style= "square-button", name = key .. "type_none" , sprite = get_icon("none"), tooltip = "do not place" } for i = 1, #items do grid.add { type= "sprite-button", style= "square-button", name = key .. "type_" .. items[i], sprite = get_icon(items[i]), tooltip = items[i] } end end end function is_blacklisted(key) for i=1, #black_list do local filter = black_list[i] if string.match(key, filter) then return true end end return false end function show_belt_picker(player) local items = {} for key, proto in pairs(game.entity_prototypes) do if proto.belt_speed then if not is_blacklisted(key) and (not research_only or is_entity_researched(player, proto)) then table.insert(items, key) end end end show_picker("belt", player, items) end function show_miner_picker(player) local items = {} for key, proto in pairs(game.entity_prototypes) do if proto.mining_drill_radius then if not is_blacklisted(key) and ( not research_only or is_entity_researched(player, proto)) then table.insert(items, key) end end end show_picker("miner", player, items) end function show_chest_picker(player) local items = {} for key, proto in pairs(game.entity_prototypes) do if string.match(key, "chest") then if not is_blacklisted(key) and ( not research_only or is_entity_researched(player, proto)) then table.insert(items, key) end end end show_picker("chest", player, items) end function show_pole_picker(player) local items = {} local metaRep = player.force.recipes["mp-meta"] for _, item in pairs(metaRep.ingredients) do local iname = item["name"] if not is_blacklisted(iname) and (not research_only or is_entity_researched(player, game.entity_prototypes[iname])) then table.insert(items, iname) end end show_picker("pole", player, items) end function get_icon(key) if key == "none" then return "virtual-signal/signal-red" end return "item/" .. key end function update_selections(player) local ui = player.gui.left.remote_selected_units if ui then ui.entity_type_picker.change_belt_button.sprite = get_icon ( entity_selections.belt ) ui.entity_type_picker.change_belt_button.tooltip = entity_selections.belt ui.entity_type_picker.change_pole_button.sprite = get_icon ( entity_selections.pole ) ui.entity_type_picker.change_pole_button.tooltip = entity_selections.pole ui.entity_type_picker.change_miner_button.sprite = get_icon ( entity_selections.miner ) ui.entity_type_picker.change_miner_button.tooltip = entity_selections.miner ui.entity_type_picker.change_chest_button.sprite = get_icon ( entity_selections.chest ) ui.entity_type_picker.change_chest_button.tooltip = entity_selections.chest end end function remote_show_gui(player) if player.gui.left.remote_selected_units == nil then local remote_selected_units = player.gui.left.add{type = "frame", name = "remote_selected_units", caption = {"text-remote-selected-units"}, direction = "vertical"} remote_selected_units.add { type = "checkbox", caption = "Deconstruct selection", state = deconstruction , name="deconstruction_button" } local mode_picker = remote_selected_units.add { type="flow", direction="horizontal", name="mode_picker" } mode_picker.add { type = "label", caption = "Positioning" } local tight = mode_picker.add { type = "radiobutton", name = "mode_tight", caption = "Tight", state = spacing_mode == "tight" } local optimal = mode_picker.add { type = "radiobutton", name = "mode_optimal", caption = "Spread out", state = spacing_mode == "optimal" } mode_buttons = {} table.insert(mode_buttons, tight) table.insert(mode_buttons, optimal) local layout_picker = remote_selected_units.add { type="flow", direction="horizontal", name="layout_picker" } layout_picker.add { type = "label", caption = "Layout" } local default = layout_picker.add { type = "radiobutton", name = "layout_default", caption = "Default", state = layout_strategy == "default" } local interleaved = layout_picker.add { type = "radiobutton", name = "layout_interleaved", caption = "Interleaved", state = layout_strategy == "interleaved" } local chests = layout_picker.add { type = "radiobutton", name = "layout_chests", caption = "Chests", state = layout_strategy == "chests" } layout_buttons = {} table.insert(layout_buttons, interleaved) table.insert(layout_buttons, default) table.insert(layout_buttons, chests) local direction_picker = remote_selected_units.add { type="flow", direction="horizontal", name="directionpicker" } buttons = {} local topButton = direction_picker.add { type = "radiobutton", name = "top", caption = "Top", state = active_direction == "top" } table.insert(buttons,topButton) local leftButton = direction_picker.add { type = "radiobutton", name = "left", caption = "Left", state = active_direction == "left" } table.insert(buttons, leftButton) local rightButton = direction_picker.add { type = "radiobutton", name = "right", caption = "Right", state = active_direction == "right" } table.insert(buttons, rightButton) local bottomButton = direction_picker.add { type = "radiobutton", name = "bottom", caption = "Bottom", state = active_direction == "bottom" } table.insert(buttons, bottomButton) local entity_type_picker = remote_selected_units.add { type="flow", direction="horizontal", name="entity_type_picker" } local pick = entity_type_picker.add { type = "sprite-button", name = "change_belt_button", style = "square-button" } local pick = entity_type_picker.add { type = "sprite-button", name = "change_miner_button", style = "square-button" } local pick = entity_type_picker.add { type = "sprite-button", name = "change_pole_button", style = "square-button" } local pick = entity_type_picker.add { type = "sprite-button", name = "change_chest_button", style = "square-button" } update_selections(player) for resource_name, selected_unit in pairs(global.player_selected_units[player.index]) do local amount = selected_unit.amount local unit_button = remote_selected_units.add{ type = "button", name = resource_name, style = "resource-button-fixed"} local unit_button_flow = unit_button.add{ type = "flow", name = "flow", direction = "horizontal"} local icon_name = resource_name local infinite = false if (string.find( resource_name, "infinite")) then icon_name = string.gsub(resource_name, "infinite." , "") infinite = true end if icon_name == "all" then unit_button_flow.add { type = "label", caption="all", style="button-label" } else unit_button_flow.add{ type = "sprite", sprite = "item/".. icon_name} end if infinite then amount = "infinite" end unit_button_flow.add { type = "label", name = "resource-amount", caption=amount, style="button-label" } end end end function resource_in_area(surface, position, entity_bounds, type) if type == "all" then local result = surface.find_entities_filtered { area = { { position[1] + entity_bounds.left_top.x , position[2] + entity_bounds.left_top.y }, { position[1] + entity_bounds.right_bottom.x , position[2] + entity_bounds.right_bottom.y }, }, type = "resource" } return #result > 0 end local result = surface.find_entities_filtered { area = { { position[1] + entity_bounds.left_top.x , position[2] + entity_bounds.left_top.y }, { position[1] + entity_bounds.right_bottom.x , position[2] + entity_bounds.right_bottom.y }, }, name = type } return #result > 0 end function create_entity(entity_type, resource_type, position, direction, bbox, player) return create_entity(entity_type, resource_type, position, direction, bbox, player, nil) end function create_entity(entity_type, resource_type, position, direction, bbox, player, type) if entity_type == "none" then return end local surface = player.surface local entity if ghosts then entity = { name = "entity-ghost", inner_name = entity_type, expires = false, position = position, direction = direction, force = player.force, type = type } else entity = { name = entity_type, position = position, direction = direction, force = player.force , type = type} end -- if not surface.can_place_entity(entity) then -- game.print ("cannot place " .. entity_type .." at " .. position[1] .. "x" .. position[2]) -- end -- and surface.can_place_entity (entity) if resource_in_area(surface, position, bbox, resource_type) then return surface.create_entity (entity) end end function create_miners(direction, area, type, player) local surface = player.surface if deconstruction then surface.deconstruct_area { area = area, force = player.force} end local drill_type = entity_selections.miner local belt_type = entity_selections.belt local pole_type = entity_selections.pole local chest_type = entity_selections.chest if (layout_strategy == "default") then layout_default(player, direction, drill_type, belt_type, pole_type, type, area) end if (layout_strategy == "interleaved") then layout_interleaved(player, direction, drill_type, belt_type, pole_type, type, area) end if (layout_strategy == "chests") then layout_chests(player, direction, drill_type, belt_type, pole_type, type, chest_type, area) end end function remote_on_gui_click(event) local player_index = event.player_index local ui = game.players[player_index].gui.left.remote_selected_units if ui ~= nil then -- avoid looping if menu is closed local player = game.players[player_index] if event.element.parent.name == "mode_picker" then active_mode = event.element.name for n,item in pairs(mode_buttons) do item.state = item == event.element end spacing_mode = string.gsub(event.element.name, "mode_", "") end if event.element.parent.name == "layout_picker" then active_mode = event.element.name for n,item in pairs(layout_buttons) do item.state = item == event.element end layout_strategy = string.gsub(event.element.name, "layout_", "") end if event.element.name == "deconstruction_button" then deconstruction = not deconstruction ui.deconstruction_button.state = deconstruction end if event.element.name == "change_belt_button" then hide_picker_guis(player) show_belt_picker(player) end if event.element.name == "change_pole_button" then hide_picker_guis(player) show_pole_picker(player) end if event.element.name == "change_miner_button" then hide_picker_guis(player) show_miner_picker(player) end if event.element.name == "change_chest_button" then hide_picker_guis(player) show_chest_picker(player) end local types = { "belt", "pole", "miner", "chest"} for i = 1, #types do local type = types[i] if string.match( event.element.name, type .. "type_") then local selection = player.gui.center[type .. "_picker"].container.selection new_selections[type] = string.gsub(event.element.name, type .. "type_" ,"") selection["selected_" .. type].sprite = get_icon(new_selections[type]) end if event.element.name == "pick_" .. type .. "_button" then entity_selections[type] = new_selections[type] update_selections(player) player.gui.center[type .. "_picker"].destroy() return end end if event.element.parent.name == "directionpicker" then active_direction = event.element.name for n,item in pairs(buttons) do item.state = item == event.element end end if event.element.parent.name == "remote_selected_units" then local item_type = event.element.name if (event.element.type == "button") then create_miners( active_direction, global.player_selected_units[player.index][item_type].area, item_type, player) end end end end function remote_hide_gui(player) if player.gui.left.remote_selected_units ~= nil then player.gui.left.remote_selected_units.destroy() end hide_picker_guis(player) end function hide_picker_guis(player) if player.gui.center.belt_picker ~= nil then player.gui.center.belt_picker.destroy() end if player.gui.center.pole_picker ~= nil then player.gui.center.pole_picker.destroy() end if player.gui.center.miner_picker ~= nil then player.gui.center.miner_picker.destroy() end end local function on_player_selected_area(event) remote_on_player_selected_area(event, false) end local function on_player_alt_selected_area(event) remote_on_player_selected_area(event, true) end local function on_player_cursor_stack_changed(event) remote_on_player_cursor_stack_changed(event, true) end local function on_init() remote_on_init() end local function on_gui_click(event) remote_on_gui_click(event) end script.on_event(defines.events.on_player_selected_area, on_player_selected_area) script.on_event(defines.events.on_player_alt_selected_area, on_player_alt_selected_area) script.on_event(defines.events.on_player_cursor_stack_changed, on_player_cursor_stack_changed) script.on_event(defines.events.on_gui_click, on_gui_click) script.on_init(on_init)
mobs = {} function mobs:register_mob(name, def) minetest.register_entity(name, { hp_max = 100+def.hp_max, physical = true, collisionbox = def.collisionbox, visual = def.visual, visual_size = def.visual_size, mesh = def.mesh, textures = def.textures, makes_footstep_sound = def.makes_footstep_sound, view_range = def.view_range, walk_velocity = def.walk_velocity, run_velocity = def.run_velocity, damage = def.damage, light_damage = def.light_damage, water_damage = def.water_damage, lava_damage = def.lava_damage, disable_fall_damage = def.disable_fall_damage, drops = def.drops, armor = def.armor, drawtype = def.drawtype, on_rightclick = def.on_rightclick, type = def.type, attack_type = def.attack_type, arrow = def.arrow, shoot_interval = def.shoot_interval, sounds = def.sounds, animation = nil,--def.animation, follow = def.follow, jump = def.jump or true, timer = 0, env_damage_timer = 0, -- only if state = "attack" attack = {player=nil, dist=nil}, state = "stand", v_start = false, old_y = nil, lifetimer = 600, tamed = false, set_velocity = function(self, v) local yaw = self.object:getyaw() if v ~= nil and yaw ~= nil then if self.drawtype == "side" then yaw = yaw+(math.pi/2) end local x = math.sin(yaw) * -v local z = math.cos(yaw) * v self.object:setvelocity({x=self.object:getvelocity().x, y=self.object:getvelocity().y, z=self.object:getvelocity().z}) end end, get_velocity = function(self) local v = self.object:getvelocity() if v ~= nil then return (v.x^2 + v.z^2)^(0.5) end end, set_animation = function(self, type) if not self.animation then return end if not self.animation.current then self.animation.current = "" end if type == "stand" and self.animation.current ~= "stand" then if self.animation.stand_start and self.animation.stand_end and self.animation.speed_normal then self.object:set_animation( {x=self.animation.stand_start,y=self.animation.stand_end}, self.animation.speed_normal, 0 ) self.animation.current = "stand" end elseif type == "walk" and self.animation.current ~= "walk" then if self.animation.walk_start and self.animation.walk_end and self.animation.speed_normal then self.object:set_animation( {x=self.animation.walk_start,y=self.animation.walk_end}, self.animation.speed_normal, 0 ) self.animation.current = "walk" end elseif type == "run" and self.animation.current ~= "run" then if self.animation.run_start and self.animation.run_end and self.animation.speed_run then self.object:set_animation( {x=self.animation.run_start,y=self.animation.run_end}, self.animation.speed_run, 0 ) self.animation.current = "run" end elseif type == "punch" and self.animation.current ~= "punch" then if self.animation.punch_start and self.animation.punch_end and self.animation.speed_normal then self.object:set_animation( {x=self.animation.punch_start,y=self.animation.punch_end}, self.animation.speed_normal, 0 ) self.animation.current = "punch" end end end, on_step = function(self, dtime) if self.type == "monster" and minetest.setting_getbool("only_peaceful_mobs") then self.object:remove() end self.lifetimer = self.lifetimer - dtime if self.lifetimer <= 0 and not self.tamed then local player_count = 0 for _,obj in ipairs(minetest.env:get_objects_inside_radius(self.object:getpos(), 20)) do if obj:is_player() then player_count = player_count+1 end end if player_count == 0 and self.state ~= "attack" then self.object:remove() return end end if self.object:getvelocity().y > 0.1 then local yaw = self.object:getyaw() if self.drawtype == "side" then yaw = yaw+(math.pi/2) end local x = math.sin(yaw) * -2 local z = math.cos(yaw) * 2 self.object:setacceleration({x=x, y=-10, z=z}) else self.object:setacceleration({x=0, y=-10, z=0}) end if self.object:getpos() ~= nil then if self.disable_fall_damage and self.object:getvelocity().y == 0 then if not self.old_y then self.old_y = self.object:getpos().y else local d = self.old_y - self.object:getpos().y if d > 5 then local damage = d-5 self.object:set_hp(self.object:get_hp()-damage) if self.object:get_hp() == 0 then self.object:remove() end end if self.object:getpos() ~= nil then self.old_y = self.object:getpos().y end end end end self.timer = self.timer+dtime if self.state ~= "attack" then if self.timer < 1 then return end self.timer = 0 end if self.sounds and self.sounds.random and math.random(1, 100) <= 1 then minetest.sound_play(self.sounds.random, {object = self.object}) end local do_env_damage = function(self) local pos = self.object:getpos() local n = minetest.env:get_node(pos) if self.light_damage and self.light_damage ~= 0 and pos.y>0 and minetest.env:get_node_light(pos) and minetest.env:get_node_light(pos) > 4 and minetest.env:get_timeofday() > 0.2 and minetest.env:get_timeofday() < 0.8 then self.object:set_hp(self.object:get_hp()-self.light_damage) if self.object:get_hp() == 0 then self.object:remove() end end if self.water_damage and self.water_damage ~= 0 and minetest.get_item_group(n.name, "water") ~= 0 then self.object:set_hp(self.object:get_hp()-self.water_damage) if self.object:get_hp() == 0 then self.object:remove() end end if self.lava_damage and self.lava_damage ~= 0 and minetest.get_item_group(n.name, "lava") ~= 0 then self.object:set_hp(self.object:get_hp()-self.lava_damage) if self.object:get_hp() == 0 then self.object:remove() end end end self.env_damage_timer = self.env_damage_timer + dtime if self.state == "attack" and self.env_damage_timer > 1 then self.env_damage_timer = 0 do_env_damage(self) elseif self.state ~= "attack" then do_env_damage(self) end if self.type == "monster" and minetest.setting_getbool("enable_damage") then for _,player in pairs(minetest.get_connected_players()) do local s = self.object:getpos() local p = player:getpos() if s ~= nil and p ~= nil then local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5 if dist < self.view_range then if self.attack.dist then if self.attack.dist < dist then self.state = "attack" self.attack.player = player self.attack.dist = dist end else self.state = "attack" self.attack.player = player self.attack.dist = dist end end end end end if self.follow ~= "" and not self.following then for _,player in pairs(minetest.get_connected_players()) do local s = self.object:getpos() local p = player:getpos() if s ~= nil and p ~= nil then local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5 if self.view_range and dist < self.view_range then self.following = player end end end end if self.following and self.following:is_player() then if self.following:get_wielded_item():get_name() ~= self.follow then self.following = nil self.v_start = false else local s = self.object:getpos() local p = self.following:getpos() local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5 if dist > self.view_range then self.following = nil self.v_start = false else local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z} local yaw = math.atan(vec.z/vec.x)+math.pi/2 if self.drawtype == "side" then yaw = yaw+(math.pi/2) end if p.x > s.x then yaw = yaw+math.pi end self.object:setyaw(yaw) if dist > 2 then if not self.v_start then self.v_start = true self.set_velocity(self, self.walk_velocity) else if self.jump and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y == 0 then local v = self.object:getvelocity() v.y = 5 self.object:setvelocity(v) end self.set_velocity(self, self.walk_velocity) end self:set_animation("walk") else self.v_start = false self.set_velocity(self, 0) self:set_animation("stand") end return end end end if self.object:getyaw() ~= nil then if self.state == "stand" then if math.random(1, 4) == 1 then self.object:setyaw(self.object:getyaw()+((math.random(0,360)-180)/180*math.pi)) end self.set_velocity(self, 0) self.set_animation(self, "stand") if math.random(1, 100) <= 50 then self.set_velocity(self, self.walk_velocity) self.state = "walk" self.set_animation(self, "walk") end elseif self.state == "walk" then if math.random(1, 100) <= 30 then self.object:setyaw(self.object:getyaw()+((math.random(0,360)-180)/180*math.pi)) end if self.jump and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y == 0 then local v = self.object:getvelocity() v.y = 5 self.object:setvelocity(v) end self:set_animation("walk") self.set_velocity(self, self.walk_velocity) if math.random(1, 100) <= 10 then self.set_velocity(self, 0) self.state = "stand" self:set_animation("stand") end elseif self.state == "attack" and self.attack_type == "dogfight" then if not self.attack.player or not self.attack.player:is_player() then self.state = "stand" self:set_animation("stand") return end local s = self.object:getpos() local p = self.attack.player:getpos() local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5 if dist > self.view_range or self.attack.player:get_hp() <= 0 then self.state = "stand" self.v_start = false self.set_velocity(self, 0) self.attack = {player=nil, dist=nil} self:set_animation("stand") return else self.attack.dist = dist end local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z} local yaw = math.atan(vec.z/vec.x)+math.pi/2 if self.drawtype == "side" then yaw = yaw+(math.pi/2) end if p.x > s.x then yaw = yaw+math.pi end self.object:setyaw(yaw) if self.attack.dist > 2 then if not self.v_start then self.v_start = true self.set_velocity(self, self.run_velocity) else if self.jump and self.get_velocity(self) <= 0.5 and self.object:getvelocity().y == 0 then local v = self.object:getvelocity() v.y = 5 self.object:setvelocity(v) end self.set_velocity(self, self.run_velocity) end self:set_animation("run") else self.set_velocity(self, 0) self:set_animation("punch") self.v_start = false if self.timer > 1 then self.timer = 0 if self.sounds and self.sounds.attack then minetest.sound_play(self.sounds.attack, {object = self.object}) end self.attack.player:punch(self.object, 1.0, { full_punch_interval=1.0, damage_groups = {fleshy=self.damage} }, vec) end end elseif self.state == "attack" and self.attack_type == "shoot" then if not self.attack.player or not self.attack.player:is_player() then self.state = "stand" self:set_animation("stand") return end local s = self.object:getpos() local p = self.attack.player:getpos() local dist = ((p.x-s.x)^2 + (p.y-s.y)^2 + (p.z-s.z)^2)^0.5 if dist > self.view_range or self.attack.player:get_hp() <= 0 then self.state = "stand" self.v_start = false self.set_velocity(self, 0) self.attack = {player=nil, dist=nil} self:set_animation("stand") return else self.attack.dist = dist end local vec = {x=p.x-s.x, y=p.y-s.y, z=p.z-s.z} local yaw = math.atan(vec.z/vec.x)+math.pi/2 if self.drawtype == "side" then yaw = yaw+(math.pi/2) end if p.x > s.x then yaw = yaw+math.pi end self.object:setyaw(yaw) self.set_velocity(self, 0) if self.timer > self.shoot_interval and math.random(1, 100) <= 60 then self.timer = 0 self:set_animation("punch") if self.sounds and self.sounds.attack then minetest.sound_play(self.sounds.attack, {object = self.object}) end local p = self.object:getpos() p.y = p.y + (self.collisionbox[2]+self.collisionbox[5])/2 local obj = minetest.env:add_entity(p, self.arrow) local amount = (vec.x^2+vec.y^2+vec.z^2)^0.5 local v = obj:get_luaentity().velocity vec.y = vec.y+1 vec.x = vec.x*v/amount vec.y = vec.y*v/amount vec.z = vec.z*v/amount obj:setvelocity(vec) end end end end, on_activate = function(self, staticdata, dtime_s) self.object:set_armor_groups({fleshy=self.armor}) self.object:setacceleration({x=0, y=-10, z=0}) self.state = "stand" self.object:setvelocity({x=0, y=self.object:getvelocity().y, z=0}) self.object:setyaw(math.random(1, 360)/180*math.pi) if self.type == "monster" and minetest.setting_getbool("only_peaceful_mobs") then self.object:remove() end self.lifetimer = 600 - dtime_s if staticdata then local tmp = minetest.deserialize(staticdata) if tmp and tmp.lifetimer then self.lifetimer = tmp.lifetimer - dtime_s end if tmp and tmp.tamed then self.tamed = tmp.tamed end end if self.lifetimer <= 0 and not self.tamed then self.object:remove() end end, get_staticdata = function(self) local tmp = { lifetimer = self.lifetimer, tamed = self.tamed, } return minetest.serialize(tmp) end, on_punch = function(self, hitter) if self.object:get_hp() <= 100 then if hitter and hitter:is_player() and hitter:get_inventory() then for _,drop in ipairs(self.drops) do if math.random(1, drop.chance) == 1 then hitter:get_inventory():add_item("main", ItemStack(drop.name.." "..math.random(drop.min, drop.max))) end end end self.object:remove() end end, }) end mobs.spawning_mobs = {} function mobs:register_spawn(name, nodes, max_light, min_light, chance, active_object_count, max_height, spawn_func) mobs.spawning_mobs[name] = true minetest.register_abm({ nodenames = nodes, neighbors = {"air"}, interval = 30, chance = chance * mob_spawn_chance_multiplier, action = function(pos, node, _, active_object_count_wider) if active_object_count_wider > active_object_count then return end if not mobs.spawning_mobs[name] then return end pos.y = pos.y+1 if not minetest.env:get_node_light(pos) then return end if minetest.env:get_node_light(pos) > max_light then return end if minetest.env:get_node_light(pos) < min_light then return end if pos.y > max_height then return end if minetest.env:get_node(pos).name ~= "air" then return end pos.y = pos.y+1 if minetest.env:get_node(pos).name ~= "air" then return end if spawn_func and not spawn_func(pos, node) then return end if minetest.setting_getbool("display_mob_spawn") then minetest.chat_send_all("[mobs] Add "..name.." at "..minetest.pos_to_string(pos)) end minetest.env:add_entity(pos, name) end }) end function mobs:register_arrow(name, def) minetest.register_entity(name, { physical = false, visual = def.visual, visual_size = def.visual_size, textures = def.textures, velocity = def.velocity, hit_player = def.hit_player, hit_node = def.hit_node, on_step = function(self, dtime) local pos = self.object:getpos() if minetest.env:get_node(self.object:getpos()).name ~= "air" then self.hit_node(self, pos, node) self.object:remove() return end pos.y = pos.y-1 for _,player in pairs(minetest.env:get_objects_inside_radius(pos, 1)) do if player:is_player() then self.hit_player(self, player) self.object:remove() return end end end }) end
require "system" require "extensions.timer" AudioManager = class { __name = "AudioManager", bgm = { fading = nil, current = nil, memory = nil }, bgs = { fading = nil, current = nil, memory = nil }, me = { current = nil }, se = { cache = {} }, onTitleScreen = function(self) self:reset() end, onSceneDrawn = function(self, scene) self:update() end } function AudioManager:load(data) end function AudioManager:save() end function AudioManager:reset() end function AudioManager:update() -- get milliseconds passed since last update local dt = Timer:getTimeDelta() if dt == 0 then -- no sense to continue return end -- update bgm fading if self.bgm.fading then local fade = self.bgm.fading -- for brevity fade.time_left = fade.time_left - dt if fade.time_left > 0 then -- decrease volume fade.sound.volume = fade.orig_volume * (fade.time_left / fade.time_total) else -- finished fading fade.sound:stop() self.bgm.fading = nil end end -- update bgs fading if self.bgs.fading then local fade = self.bgs.fading -- for brevity fade.time_left = fade.time_left - dt if fade.time_left > 0 then -- decrease volume fade.sound.volume = fade.orig_volume * (fade.time_left / fade.time_total) else -- finished fading fade.sound:stop() self.bgs.fading = nil end end -- update me fading if self.me.fading then local fade = self.me.fading -- for brevity fade.time_left = fade.time_left - dt if fade.time_left > 0 then -- decrease volume fade.sound.volume = fade.orig_volume * (fade.time_left / fade.time_total) else -- me fading finished fade.sound:stop() self.me.fading = nil -- resume bgm self:resumeBgm() end end -- check if we need to resume bgm after me stopped if self.me.current then if not self.me.current.sound.isPlaying then -- me stopped, clear it and resume bgm self.me.current = nil self:resumeBgm() end end end function AudioManager:playBgm(filename, volume, pitch) -- sanity checks assert(type(filename) == "string", "filename must be a string") -- init optional arguments to defaults, if omitted volume = volume or 1.0 pitch = pitch or 1.0 -- if filename is empty, clear bgm if #filename == 0 then if self.bgm.current then self.bgm.current.sound:stop() end self.bgm.current = nil return end -- stop current bgm if self.bgm.current then self.bgm.current.sound:stop() end -- play new bgm local bgm = { sound = audio.openSound(filename) or error("could not open sound '"..filename.."'"), filename = filename, volume = volume, pitch = pitch } bgm.sound.loop = true bgm.sound.volume = volume bgm.sound.pitch = pitch bgm.sound:play() self.bgm.current = bgm end function AudioManager:stopBgm() if self.bgm.current then self.bgm.current.sound:stop() end end function AudioManager:resumeBgm() if self.bgm.current then self.bgm.current.sound:play() end end function AudioManager:fadeBgm(time) -- sanity checks assert(type(time) == "number" and time > 0, "time must be a positive number") if self.bgm.current then -- if there is already a fading bgm, stop it if self.bgm.fading then self.bgm.fading.sound:stop() end -- init fading bgm self.bgm.fading = { sound = self.bgm.current.sound, orig_volume = self.bgm.current.sound.volume, time_total = time, time_left = time } -- clear current bgm self.bgm.current = nil end end function AudioManager:memorizeBgm() if self.bgm.current then self.bgm.memory = { filename = self.bgm.current.filename, volume = self.bgm.current.volume, pitch = self.bgm.current.pitch } else self.bgm.memory = nil end end function AudioManager:restoreBgm() if self.bgm.memory then self:playBgm( self.bgm.memory.filename, self.bgm.memory.volume, self.bgm.memory.pitch ) end end function AudioManager:getBgm() if self.bgm.current then return self.bgm.current.sound else return nil end end function AudioManager:playBgs(filename, volume, pitch) -- sanity checks assert(type(filename) == "string", "filename must be a string") -- init optional arguments to defaults, if omitted volume = volume or 1.0 pitch = pitch or 1.0 -- if filename is empty, clear bgs if #filename == 0 then if self.bgs.current then self.bgs.current.sound:stop() end self.bgs.current = nil return end -- stop current bgs if self.bgs.current then self.bgs.current.sound:stop() end -- play new bgs local bgs = { sound = audio.openSound(filename) or error("could not open sound '"..filename.."'"), filename = filename, volume = volume, pitch = pitch } bgs.sound.loop = true bgs.sound.volume = volume bgs.sound.pitch = pitch bgs.sound:play() self.bgs.current = bgs end function AudioManager:stopBgs() if self.bgs.current then self.bgs.current.sound:stop() end end function AudioManager:resumeBgs() if self.bgs.current then self.bgs.current.sound:play() end end function AudioManager:fadeBgs(time) -- sanity checks assert(type(time) == "number" and time > 0, "time must be a positive number") if self.bgs.current then -- if there is already a fading bgs, stop it if self.bgs.fading then self.bgs.fading.sound:stop() end -- init fading bgs self.bgs.fading = { sound = self.bgs.current.sound, orig_volume = self.bgs.current.sound.volume, time_total = time, time_left = time } -- clear current bgs self.bgs.current = nil end end function AudioManager:memorizeBgs() if self.bgs.current then self.bgs.memory = { filename = self.bgs.current.filename, volume = self.bgs.current.volume, pitch = self.bgs.current.pitch } else self.bgs.memory = nil end end function AudioManager:restoreBgs() if self.bgs.memory then self:playBgs( self.bgs.memory.filename, self.bgs.memory.volume, self.bgs.memory.pitch ) end end function AudioManager:getBgs() if self.bgs.current then return self.bgs.current.sound else return nil end end function AudioManager:playMe(filename, volume, pitch) -- sanity checks assert(type(filename) == "string", "filename must be a string") -- init optional arguments to defaults, if omitted volume = volume or 1.0 pitch = pitch or 1.0 -- if filename is empty, clear me if #filename == 0 then self:stopMe() return end -- stop current bgm self:stopBgm() -- stop current me if self.me.current then self.me.current.sound:stop() end -- play new me local me = { sound = audio.openSound(filename) or error("could not open sound '"..filename.."'") } me.sound.volume = volume me.sound.pitch = pitch me.sound:play() self.me.current = me end function AudioManager:stopMe() if self.me.current then -- stop me self.me.current.sound:stop() -- clear me self.me.current = nil -- resume bgm self:resumeBgm() end end function AudioManager:fadeMe(time) -- sanity checks assert(type(time) == "number" and time > 0, "time must be a positive number") if self.me.current then -- if there is already a fading me, stop it if self.me.fading then self.me.fading.sound:stop() end -- init fading me self.me.fading = { sound = self.me.current.sound, orig_volume = self.me.current.sound.volume, time_total = time, time_left = time } -- clear current me self.me.current = nil end end function AudioManager:playSe(filename) -- sanity checks assert(type(filename) == "string" and #filename > 0) -- get cached sound effect local se = self.se.cache[filename] -- if sound effect is not cached yet, -- open and cache the sound effect if se == nil then se = audio.openSoundEffect(filename) -- make sure openSoundEffect succeeded assert(se, "could not open sound effect '"..filename.."'") self.se.cache[filename] = se end -- play sound effect se:play() end function AudioManager:stopSe() -- multiple sound effects could be playing, -- so iterate over all sound effects in the -- sound effect cache and stop them for _, se in pairs(self.se.cache) do se:stop() end end -- register in callback manager CallbackManager:addListener("AudioManager", 1, AudioManager)
local hex = require "hex" --[[ send_0x00_S1发送参数(用于升级 导轨节数的变化) a = 时间戳 (一般发送当前时间戳) b = 版本号 (更新时所要发送的版本号) c = 0o r 1 (1代表着强制更新 也就是开启更新) d = 升级版本的字节数 e = 导轨拼接节数 ]] function send_0x00_S1(a, b, c, d, e, f) local info = string.pack(">HbLbbIbb",0xaaaf, 0x00, a, b, c, d, e, f) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 手动模式 u16 data[3-4] 导轨速度 v*10+500 u8 data[10] 1 ]] function send_0x01_S1(a,b) local info = string.pack(">HbHbIbL", 0xaaaf, 0x01,a,0, 0,b, 0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 0 1 2 3 4 5 u32 data[4-7]时间戳高32 u32 data[8-11]时间戳低32 ms u8 data[18] 是否循环运行 1循环 ]] function send_0x02_S1(a,b,c) local info = string.pack(">HbbLIHb", 0xaaaf, 0x02,a,b,0, 0,c) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u16 data[3-4] Interval u16 data[5-6] Exposure u32 data[7-10] Frames u8 data[11] Mode u8 data[12] NumBezier u16 data[13-14] Buffer_second ]] function send_0x03_S1(a,b,c,d,e,f) local info = string.pack(">HbHHIbbHI", 0xaaaf, 0x03,a,b,c,d, e, f,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[u32 data[3-6] Time u8 data[12] NumBezier ]] function send_0x04_S1(a,b) local info = string.pack(">HbIIbbIH", 0xaaaf, 0x04,a,0,0,b, 0, 0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 0 1 2 3 4 u32 data[4-7]时间戳高32 u32 data[8-11]时间戳低32 ms u32 data[12-15] Frame_Need u16 data[16-17] 单次时间-ms ]] function send_0x05_S1(a,b,c,d) local info = string.pack(">HbbLIHb", 0xaaaf, 0x05,a,b,c,d,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 功能 1预览 0待机 float data[4-7] slider位置 保留到0.1mm ]] function send_0x06_S1(a,b) local info = string.pack(">HbbILHb", 0xaaaf, 0x06,a,b, 0, 0, 0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[u8 data[3] 0 1 5 6 7 u16 data[4-5]Slider速度*100+5000 u32 data[6-9] Slider位置mm*100(A) u32 data[10-13] Slider位置mm*100(B) u16 data[17-18] 总运行时间 秒]] function send_0x09_S1(a,b,c,d,e) local info = string.pack(">HbbHIIHbh", 0xaaaf, 0x09,a,b,c,d,0,0,e) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 0 1 2 3 4 u8 data[4] 方向 1.向左 2.向右 3 自处理方向 u8 data[5] 0 1 循环标志 1循环 u16 data[6-7] 总运行时间 秒 u8 data[8] 淡入淡出等级 0 1 2 3 u64 data[11-18] 时间戳 64位 ms ]] function send_0x0A_S1(a,b,c,d,e,f) local info = string.pack(">HbbbbHbHL", 0xaaaf, 0x0a,a,b,c,d,e,0,f) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u64 data[3-10] 时间戳 ms64位 ]] function send_0x0B_S1(a) local info = string.pack(">HbLL", 0xaaaf, 0x0B,a,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[u8 data[3] 0 1 2 3 4 u16 data[7-8]导轨速度 v+500 mm/s]] function send_0x0C_S1(a,b) local info = string.pack(">HbbHbHLH", 0xaaaf, 0x0C,a,0,0,b,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u64 data[3-10] 时间戳 ms64位 ]] function send_0x24_S1(a) local info = string.pack(">HbLL", 0xaaaf, 0x24,a,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 发送导轨贝塞尔曲线参数 ]] function send_0xAx_S1(a,b,c,d,e) local info if (a== 0) then info = string.pack(">HBIIII", 0xaaaf, 0xa0,b,c,d,e) elseif(a == 1) then info = string.pack(">HBIIII", 0xaaaf, 0xa1,b,c,d,e) elseif(a == 2) then info = string.pack(">HBIIII", 0xaaaf, 0xa2,b,c,d,e) elseif(a == 3) then info = string.pack(">HBIIII", 0xaaaf, 0xa3,b,c,d,e) elseif(a == 4) then info = string.pack(">HBIIII", 0xaaaf, 0xa4,b,c,d,e) elseif(a == 5) then info = string.pack(">HBIIII", 0xaaaf, 0xa5,b,c,d,e) elseif(a == 6) then info = string.pack(">HBIIII", 0xaaaf, 0xa6,b,c,d,e) elseif(a == 7) then info = string.pack(">HBIIII", 0xaaaf, 0xa7,b,c,d,e) elseif(a == 8) then info = string.pack(">HBIIII", 0xaaaf, 0xa8,b,c,d,e) elseif(a == 9) then info = string.pack(">HBIIII", 0xaaaf, 0xa9,b,c,d,e) elseif(a == 10) then info = string.pack(">HBIIII", 0xaaaf, 0xaA,b,c,d,e) elseif(a == 11) then info = string.pack(">HBIIII", 0xaaaf, 0xab,b,c,d,e) elseif(a == 12) then info = string.pack(">HBIIII", 0xaaaf, 0xac,b,c,d,e) elseif(a == 13) then info = string.pack(">HBIIII", 0xaaaf, 0xad,b,c,d,e) elseif(a == 14) then info = string.pack(">HBIIII", 0xaaaf, 0xae,b,c,d,e) elseif(a == 15) then info = string.pack(">HBIIII", 0xaaaf, 0xaf,b,c,d,e) end local sum = hex.checksum(info) return info .. string.char(sum) end -- hex.dump(send_0xAx_S1(0x0f,2,3,4,5)) -- function send_0xAx_S1(a,b,c,d,e) -- -- if(a == 0) -- local info = string.pack(">HbLL", 0xaaaf, 0xa0,b,c,d,e) -- local sum = hex.checksum(info) -- return info .. string.char(sum) -- -- else if (a == 1) -- -- local info = string.pack(">HbLL", 0xaaaf, 0xa1,b,c,d,e) -- -- local sum = hex.checksum(info) -- -- return info .. string.char(sum) -- end --===========================================-- --[[ 0x00_SharkMini_X2发送参数 a = 时间戳 (一般发送当前时间戳) b = 版本号 (更新时所要发送的版本号) c = 0o r 1 (1代表着强制更新 也就是开启更新) d = 升级版本的字节数 e = nil ]] function send_0x00_X2(a,b,c,d,e) local info = string.pack(">HbLbbIbb",0x555f, 0x00, a, b, c, d, 0,e) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x01_SharkMini_X2发送参数 a = pan速度 0.1°/s *10 +300 b = tilt 速度 0.1°/s *10 +300 c = pan lock 标志 0x01) d = tilt lock 标志 0x01 e = 回零点标志 为1 回零点 为1 时 云台回零点位置,若中途拨动摇杆,回零动作停止,并响应摇杆速度 ]] function send_0x01_X2(a,b,c,d,e) local info = string.pack(">Hb>H>HbbbbL", 0x555f, 0x01,a,b,c,d,0,e,0) print("len:" ,#info) local sum = hex.checksum(info) return info .. string.char(sum) end hex.dump(send_0x01_X2(300, 300, 0,0,0)) -- -- function AAAA(a,b,c) -- local info = string.pack(">Hb>H>Hb", 0x555f, 0x01,a,b,c) -- -- local sum = hex.checksum(info) -- return info .. string.char(sum) -- end -- hex.dump(AAAA(1,2,3)) --[[ 0x01_SharkMini_X2发送运行指令 a = 0 回起点 1 时间戳校准 2 开始时间的时间戳 3 暂停运行(配合时间戳,何时暂停) 4 停止运行(导轨停止,清零参数) 5 恢复运行(配合时间戳,何时恢复) b = 开始时间戳 64位 c = 是否循环运行 1循环 ]] function send_0x02_X2(a,b,c) local info = string.pack(">HbbIIIHb", 0x555f, 0x02,a,b,0,0,0,c) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x03_SharkMini_x2延时摄影参数设置 a = Interval b = Exposure c = Frames d = Mode e = NumBezier.Pan—Tilt f = Buffer_second (Interval 1-60 second Exposure 1-60 second Frames 照片总张数 Mode 0 SMS/ 1 Continue MS_Running SMS中一段运动的最大时间) ]] function send_0x03_X2(a,b,c,d,e,f) local info = string.pack(">HbHHIbHHHb", 0x555f, 0x03,a,b,c,d, e, f,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x04_SharkMini_X2Video参数设置 a = time 运行总时间 b = pan 和 tilt的贝塞尔曲线数量 ]] function send_0x04_X2(a,b) local info = string.pack(">HbIIbHIb", 0x555f, 0x04,a,0,0,b,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x05_Shark_Mini StopMotion set a = mode 0 回起点 1 时间戳校准 2 当前帧的时间戳 3 配合Frame_Need移动到相应位置 4 停止运行(云台停止,清零参数) b = 时间戳 c = frame_Need 当前帧 d = time单次运行的时间 ]] function send_0x05_X2(a,b,c,d) local info = string.pack(">HbbLIHb", 0x555f, 0x05,a,b,c,d,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x06_Shark_Mini 预览preview a = mode 功能 1预览 0待机 b = pan的位置精度0.1 c = tilt的位置精度0.1 ]] function send_0x06_X2(a,b,c) local info = string.pack(">HbbIIIHb", 0x555f, 0x06,a,b,c,0,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x07_Shark_Mini Panorama 环形矩阵 a = mode ( 0 回起始点命令 1 预览起点 2 开始拍摄 3 暂停 6恢复 4 放弃运行(云台停止,清零参数) 5 Tilt设置) b = 单张照片的宽角度 * 100 c = 起始角度*10(0-3600) d = 终止角度*10 e = tilt速度 0.1°/s *10+300 f = Interval 秒 ]] function send_0x07_X2(a,b,c,d,e,f) local info = string.pack(">HbbhhhhhIb", 0x555f, 0x07,a,b,c,d, 0,e, 0,f) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 0x08_Shark_Mini 方形矩阵 a = data[3] 0 1 2 3 4 5 6 7 b = data[4-5]单张宽角度*100 c = data[6-7] 单张高角度*100 d = data[8-9] Pan速度*100+3000 e = data[10-11] Tilt速度*100+3000 f = data[18] Interval 秒 ]] function send_0x08_X2(a,b,c,d,e,f) local info = string.pack(">HbbHHHHHIb", 0x555f, 0x08,a,b,c,d, e,0,0,f) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 0 1 5 6 7 u16 data[4-5]pan速度*100+3000 u16 data[6-7] tilt速度*100+3000 u16 data[8-9] Pan角度*10+3600(A) u16 data[10-11] Tilt角度*10+350(A) u16 data[12-13] Pan角度*10+3600(B点) u16 data[14-15] Tilt角度*10+350(B点) u16 data[17-18] 总运行时间 秒 ]] function send_0x09_X2(a,b,c,d,e,f,g,h) local info = string.pack(">HbbHHHHHHbH", 0x555f, 0x09,a,b,c,d,e,f,g,0,h) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 0 1 2 3 4 u8 data[4] 方向 1.向左 2.向右 3 自处理方向 u8 data[5] 0 1 循环标志 1循环 u16 data[6-7] 总运行时间 秒 u8 data[8] 淡入淡出等级 0 1 2 3 u8 data[9] 聚焦、离散标志(1聚焦 0离散) u64 data[11-18] 时间戳 64位 ms ]] function send_0x0A_X2(a,b,c,d,e,f,g) local info = string.pack(">HbbbbHbbbL", 0x555f, 0x0a,a,b,c,d, e, f,0,g) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u64 data[3-10] 时间戳 ms64位 ]] function send_0x0B_X2(a) local info = string.pack(">HbLL", 0x555f, 0x0b,a,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u8 data[3] 0 1 2 3 4 ]] function send_0x0C_X2(a) local info = string.pack(">HbbHLIb", 0x555f, 0x0c,a,0,0,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ u64 data[3-10] 时间戳 ms64位 ]] function send_0x24_X2(a) local info = string.pack(">HbLL", 0x555f, 0x24,a,0,0) local sum = hex.checksum(info) return info .. string.char(sum) end --[[ 发送pan的贝塞尔曲线 ]] function send_0x5x_S1(a,b,c,d,e) local info if (a== 0) then info = string.pack(">HBIIII", 0x555f, 0x50,b,c,d,e) elseif(a == 1) then info = string.pack(">HBIIII", 0x555f, 0x51,b,c,d,e) elseif(a == 2) then info = string.pack(">HBIIII", 0x555f, 0x52,b,c,d,e) elseif(a == 3) then info = string.pack(">HBIIII", 0x555f, 0x53,b,c,d,e) elseif(a == 4) then info = string.pack(">HBIIII", 0x555f, 0x54,b,c,d,e) elseif(a == 5) then info = string.pack(">HBIIII", 0x555f, 0x55,b,c,d,e) elseif(a == 6) then info = string.pack(">HBIIII", 0x555f, 0x56,b,c,d,e) elseif(a == 7) then info = string.pack(">HBIIII", 0x555f, 0x57,b,c,d,e) elseif(a == 8) then info = string.pack(">HBIIII", 0x555f, 0x58,b,c,d,e) elseif(a == 9) then info = string.pack(">HBIIII", 0x555f, 0x59,b,c,d,e) elseif(a == 10) then info = string.pack(">HBIIII", 0x555f, 0x5A,b,c,d,e) elseif(a == 11) then info = string.pack(">HBIIII", 0x555f, 0x5b,b,c,d,e) elseif(a == 12) then info = string.pack(">HBIIII", 0x555f, 0x5c,b,c,d,e) elseif(a == 13) then info = string.pack(">HBIIII", 0x555f, 0x5d,b,c,d,e) elseif(a == 14) then info = string.pack(">HBIIII", 0x555f, 0x5e,b,c,d,e) elseif(a == 15) then info = string.pack(">HBIIII", 0x555f, 0x5f,b,c,d,e) end local sum = hex.checksum(info) return info .. string.char(sum) end --[[发送Tilt的贝塞尔曲线]] function send_0x6x_S1(a,b,c,d,e) local info if (a== 0) then info = string.pack(">HBIIII", 0x555f, 0x60,b,c,d,e) elseif(a == 1) then info = string.pack(">HBIIII", 0x555f, 0x61,b,c,d,e) elseif(a == 2) then info = string.pack(">HBIIII", 0x555f, 0x62,b,c,d,e) elseif(a == 3) then info = string.pack(">HBIIII", 0x555f, 0x63,b,c,d,e) elseif(a == 4) then info = string.pack(">HBIIII", 0x555f, 0x64,b,c,d,e) elseif(a == 5) then info = string.pack(">HBIIII", 0x555f, 0x65,b,c,d,e) elseif(a == 6) then info = string.pack(">HBIIII", 0x555f, 0x66,b,c,d,e) elseif(a == 7) then info = string.pack(">HBIIII", 0x555f, 0x67,b,c,d,e) elseif(a == 8) then info = string.pack(">HBIIII", 0x555f, 0x68,b,c,d,e) elseif(a == 9) then info = string.pack(">HBIIII", 0x555f, 0x69,b,c,d,e) elseif(a == 10) then info = string.pack(">HBIIII", 0x555f, 0x6A,b,c,d,e) elseif(a == 11) then info = string.pack(">HBIIII", 0x555f, 0x6b,b,c,d,e) elseif(a == 12) then info = string.pack(">HBIIII", 0x555f, 0x6c,b,c,d,e) elseif(a == 13) then info = string.pack(">HBIIII", 0x555f, 0x6d,b,c,d,e) elseif(a == 14) then info = string.pack(">HBIIII", 0x555f, 0x6e,b,c,d,e) elseif(a == 15) then info = string.pack(">HBIIII", 0x555f, 0x6f,b,c,d,e) end local sum = hex.checksum(info) return info .. string.char(sum) end
--[[ _ ( ) _| | __ _ __ ___ ___ _ _ /'_` | /'__`\( '__)/' _ ` _ `\ /'_` ) ( (_| |( ___/| | | ( ) ( ) |( (_| | `\__,_)`\____)(_) (_) (_) (_)`\__,_) DButton --]] local PANEL = {} AccessorFunc( PANEL, "m_bBorder", "DrawBorder", FORCE_BOOL ) function PANEL:Init() self:SetContentAlignment( 5 ) -- -- These are Lua side commands -- Defined above using AccessorFunc -- self:SetDrawBorder( true ) self:SetDrawBackground( true ) self:SetTall( 22 ) self:SetMouseInputEnabled( true ) self:SetKeyboardInputEnabled( true ) self:SetCursor( "hand" ) self:SetFont( "DermaDefault" ) end --[[--------------------------------------------------------- IsDown -----------------------------------------------------------]] function PANEL:IsDown() return self.Depressed end --[[--------------------------------------------------------- SetImage -----------------------------------------------------------]] function PANEL:SetImage( img ) if ( !img ) then if ( IsValid( self.m_Image ) ) then self.m_Image:Remove() end return end if ( !IsValid( self.m_Image ) ) then self.m_Image = vgui.Create( "DImage", self ) end self.m_Image:SetImage( img ) self.m_Image:SizeToContents() self:InvalidateLayout() end PANEL.SetIcon = PANEL.SetImage function PANEL:Paint( w, h ) if self.Depressed or self.m_bSelected or self.Hovered then draw.RoundedBox( 0, 0, 0, self:GetWide(), self:GetTall(), Color( 0, 180, 255 ) ) else draw.RoundedBox( 0, 0, 0, self:GetWide(), self:GetTall(), Color( 175, 175, 175 ) ) end return false end --[[--------------------------------------------------------- UpdateColours -----------------------------------------------------------]] function PANEL:UpdateColours( skin ) if self.Depressed or self.m_bSelected then return self:SetTextStyleColor( Color( 255, 255, 255 ) ) else return self:SetTextStyleColor( Color( 0, 0, 0 ) ) end end --[[--------------------------------------------------------- Name: PerformLayout -----------------------------------------------------------]] function PANEL:PerformLayout() -- -- If we have an image we have to place the image on the left -- and make the text align to the left, then set the inset -- so the text will be to the right of the icon. -- if ( IsValid( self.m_Image ) ) then self.m_Image:SetPos( 4, ( self:GetTall() - self.m_Image:GetTall() ) * 0.5 ) self:SetTextInset( self.m_Image:GetWide() + 16, 0 ) end DLabel.PerformLayout( self ) end --[[--------------------------------------------------------- SetDisabled -----------------------------------------------------------]] function PANEL:SetDisabled( bDisabled ) self.m_bDisabled = bDisabled self:InvalidateLayout() end -- Override the default engine method, so it actually does something for DButton function PANEL:SetEnabled( bEnabled ) self.m_bDisabled = !bEnabled self:InvalidateLayout() end --[[--------------------------------------------------------- Name: SetConsoleCommand -----------------------------------------------------------]] function PANEL:SetConsoleCommand( strName, strArgs ) self.DoClick = function( self, val ) RunConsoleCommand( strName, strArgs ) end end --[[--------------------------------------------------------- Name: GenerateExample -----------------------------------------------------------]] function PANEL:GenerateExample( ClassName, PropertySheet, Width, Height ) local ctrl = vgui.Create( ClassName ) ctrl:SetText( "Example Button" ) ctrl:SetWide( 200 ) PropertySheet:AddSheet( ClassName, ctrl, nil, true, true ) end --[[--------------------------------------------------------- OnMousePressed -----------------------------------------------------------]] function PANEL:OnMousePressed( mousecode ) return DLabel.OnMousePressed( self, mousecode ) end --[[--------------------------------------------------------- OnMouseReleased -----------------------------------------------------------]] function PANEL:OnMouseReleased( mousecode ) return DLabel.OnMouseReleased( self, mousecode ) end local PANEL = derma.DefineControl( "ULogs_GDButton", "A standard Button", PANEL, "DLabel" ) PANEL = table.Copy( PANEL ) --[[--------------------------------------------------------- Name: SetActionFunction -----------------------------------------------------------]] function PANEL:SetActionFunction( func ) self.DoClick = function( self, val ) func( self, "Command", 0, 0 ) end end -- No example for this control. Should we remove this completely? function PANEL:GenerateExample( class, tabs, w, h ) end derma.DefineControl( "Button", "Backwards Compatibility", PANEL, "DLabel" )
--- Low-level and high-level filesystem manipulation library. module "nixio.fs" --- Check user's permission on a file. -- @class function -- @name nixio.fs.access -- @param path Path -- @param mode1 First Mode to check ["f", "r", "w", "x"] -- @param ... More Modes to check [-"-] -- @return true --- Strip the directory part from a path. -- @class function -- @name nixio.fs.basename -- @usage This function cannot fail and will never return nil. -- @param path Path -- @return basename --- Strip the base from a path. -- @class function -- @name nixio.fs.dirname -- @usage This function cannot fail and will never return nil. -- @param path Path -- @return dirname --- Return the cannonicalized absolute pathname. -- @class function -- @name nixio.fs.realpath -- @param path Path -- @return absolute path --- Remove a file or directory. -- @class function -- @name nixio.fs.remove -- @param path Path -- @return true --- Delete a name and - if no links are left - the associated file. -- @class function -- @name nixio.fs.unlink -- @param path Path -- @return true --- Renames a file or directory. -- @class function -- @name nixio.fs.rename -- @param src Source path -- @param dest Destination path -- @usage It is normally not possible to rename files across filesystems. -- @return true --- Remove an empty directory. -- @class function -- @name nixio.fs.rmdir -- @param path Path -- @return true --- Create a new directory. -- @class function -- @name nixio.fs.mkdir -- @param path Path -- @param mode File mode (optional, see chmod and umask) -- @see nixio.fs.chmod -- @see nixio.umask -- @return true --- Change the file mode. -- @class function -- @name nixio.fs.chmod -- @usage Windows only supports setting the write-protection through the -- "Writable to others" bit. -- @usage <strong>Notice:</strong> The mode-flag for the functions -- open, mkdir, mkfifo are affected by the umask. -- @param path Path -- @param mode File mode -- [decimal mode number, "[-r][-w][-xsS][-r][-w][-xsS][-r][-w][-xtT]"] -- @see nixio.umask -- @return true --- Iterate over the entries of a directory. -- @class function -- @name nixio.fs.dir -- @usage The special entries "." and ".." are omitted. -- @param path Path -- @return directory iterator returning one entry per call --- Create a hard link. -- @class function -- @name nixio.fs.link -- @usage This function calls link() on POSIX and CreateHardLink() on Windows. -- @param oldpath Path -- @param newpath Path -- @return true --- Change file last access and last modification time. -- @class function -- @name nixio.fs.utimes -- @param path Path -- @param actime Last access timestamp (optional, default: current time) -- @param mtime Last modification timestamp (optional, default: actime) -- @return true --- Get file status and attributes. -- @class function -- @name nixio.fs.stat -- @param path Path -- @param field Only return a specific field, not the whole table (optional) -- @return Table containing: <ul> -- <li>atime = Last access timestamp</li> -- <li>blksize = Blocksize (POSIX only)</li> -- <li>blocks = Blocks used (POSIX only)</li> -- <li>ctime = Creation timestamp</li> -- <li>dev = Device ID</li> -- <li>gid = Group ID</li> -- <li>ino = Inode</li> -- <li>modedec = Mode converted into a decimal number</li> -- <li>modestr = Mode as string as returned by `ls -l`</li> -- <li>mtime = Last modification timestamp</li> -- <li>nlink = Number of links</li> -- <li>rdev = Device ID (if special file)</li> -- <li>size = Size in bytes</li> -- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li> -- <li>uid = User ID</li> -- </ul> --- Get file status and attributes and do not resolve if target is a symlink. -- @class function -- @name nixio.fs.lstat -- @param path Path -- @param field Only return a specific field, not the whole table (optional) -- @see nixio.fs.stat -- @return Table containing attributes (see stat for a detailed description) --- (POSIX) Change owner and group of a file. -- @class function -- @name nixio.fs.chown -- @param path Path -- @param user User ID or Username (optional) -- @param group Group ID or Groupname (optional) -- @return true --- (POSIX) Change owner and group of a file and do not resolve -- if target is a symlink. -- @class function -- @name nixio.fs.lchown -- @param path Path -- @param user User ID or Username (optional) -- @param group Group ID or Groupname (optional) -- @return true --- (POSIX) Create a FIFO (named pipe). -- @class function -- @name nixio.fs.mkfifo -- @param path Path -- @param mode File mode (optional, see chmod and umask) -- @see nixio.fs.chmod -- @see nixio.umask -- @return true --- (POSIX) Create a symbolic link. -- @class function -- @name nixio.fs.symlink -- @param oldpath Path -- @param newpath Path -- @return true --- (POSIX) Read the target of a symbolic link. -- @class function -- @name nixio.fs.readlink -- @param path Path -- @return target path --- (POSIX) Find pathnames matching a pattern. -- @class function -- @name nixio.fs.glob -- @param pattern Pattern -- @return path iterator -- @return number of matches --- (POSIX) Get filesystem statistics. -- @class function -- @name nixio.fs.statvfs -- @param path Path to any file within the filesystem. -- @return Table containing: <ul> -- <li>bavail = available blocks</li> -- <li>bfree = free blocks</li> -- <li>blocks = number of fragments</li> -- <li>frsize = fragment size</li> -- <li>favail = available inodes</li> -- <li>ffree = free inodes</li> -- <li>files = inodes</li> -- <li>flag = flags</li> -- <li>fsid = filesystem ID</li> -- <li>namemax = maximum filename length</li> -- </ul> --- Read the contents of a file into a buffer. -- @class function -- @name nixio.fs.readfile -- @param path Path -- @param limit Maximum bytes to read (optional) -- @return file contents --- Write a buffer into a file truncating the file first. -- @class function -- @name nixio.fs.writefile -- @param path Path -- @param data Data to write -- @return true --- Copy data between files. -- @class function -- @name nixio.fs.datacopy -- @param src Source file path -- @param dest Destination file path -- @param limit Maximum bytes to copy (optional) -- @return true --- Copy a file, directory or symlink non-recursively preserving file mode, -- timestamps, owner and group. -- @class function -- @name nixio.fs.copy -- @usage The destination must always be a full destination path e.g. do not -- omit the basename even if source and destination basename are equal. -- @param src Source path -- @param dest Destination path -- @return true --- Rename a file, directory or symlink non-recursively across filesystems. -- @class function -- @name nixio.fs.move -- @usage The destination must always be a full destination path e.g. do not -- omit the basename even if source and destination basename are equal. -- @param src Source path -- @param dest Destination path -- @return true --- Create a directory and all needed parent directories recursively. -- @class function -- @name nixio.fs.mkdirr -- @param dest Destination path -- @param mode File mode (optional, see chmod and umask) -- @see nixio.fs.chmod -- @see nixio.umask -- @return true --- Rename a file, directory or symlink recursively across filesystems. -- @class function -- @name nixio.fs.mover -- @usage The destination must always be a full destination path e.g. do not -- omit the basename even if source and destination basename are equal. -- @param src Source path -- @param dest Destination path -- @return true --- Copy a file, directory or symlink recursively preserving file mode, -- timestamps, owner and group. -- @class function -- @name nixio.fs.copyr -- @usage The destination must always be a full destination path e.g. do not -- omit the basename even if source and destination basename are equal. -- @param src Source path -- @param dest Destination path -- @return true
local L = Grid2Options.L local options = {} Grid2Options:MakeTitleOptions( options, Grid2.versionstring, L["GRID2_WELCOME"], nil, "Interface\\Addons\\Grid2\\media\\icon" ) options.description = { type = "description", order = 1, fontSize = "medium", name = L["GRID2_DESC"] .. "\n" } options.debug = { type = "header", order = 2, name = L["Debug"] } do local function AddModuleDebugMenu(name, module, options) options[name]= { type = "toggle", order = 10, name = name, desc = L["Toggle debugging for %s."]:format(name), get = function () return module.db.global.debug end, set = function () local v = not module.db.global.debug module.db.global.debug = v or nil module.debugging = v end, } end AddModuleDebugMenu("Grid2", Grid2, options ) for name, module in Grid2:IterateModules() do AddModuleDebugMenu(name, module, options) end end options.separator = { type = "description", order = 100, name = "" } options.resetpost = { type = "execute", order = 110, name = L["Reset Position"], desc = L["Resets the Grid2 main window position and anchor."], func = function () Grid2Layout:ResetPosition() end, } Grid2Options:AddGeneralOptions( "About", nil, options, 500 )
--空气质量 --请用自己的token local token = "737aa093c7d9c16b7c6fdc1b70af2fb02bf01e11" local function getInfo(id) local html = asyncHttpGet("http://api.waqi.info/feed/@"..tostring(id).."/","token="..token) local d,r,e = jsonDecode(html) if not r then return "加载失败" end return d.data.city.name.."的空气质量如下:".. (d.data.aqi and "\r\n空气质量指数:"..d.data.aqi or "").. (d.data.iaqi.pm25 and "\r\npm2.5:"..d.data.iaqi.pm25.v or "").. (d.data.iaqi.pm10 and "\r\npm2.5:"..d.data.iaqi.pm10.v or "").. (d.data.iaqi.co and "\r\npm2.5:"..d.data.iaqi.co.v or "").. (d.data.iaqi.no2 and "\r\npm2.5:"..d.data.iaqi.no2.v or "").. (d.data.iaqi.o3 and "\r\npm2.5:"..d.data.iaqi.o3.v or "").. (d.data.iaqi.so2 and "\r\npm2.5:"..d.data.iaqi.so2.v or "").. (d.data.attributions[1].name and "\r\n数据来源:"..d.data.attributions[1].name or "").. (d.data.time.s and "\r\n数据更新时间:"..d.data.time.s or "") end local function search(name) for i=1,name:len() do if name:byte(i) > 127 then return "城市名称不能用中文!" end end local html = asyncHttpGet("http://api.waqi.info/search/","keyword="..name.."&token="..token) local d,r,e = jsonDecode(html) if not r then return "加载失败" end local result = {} for i=1,#d.data do table.insert(result, d.data[i].uid..":"..d.data[i].station.name) end return "共找到"..tostring(#result).."个监测站:".. "\r\n"..table.concat(result,"\r\n").. "\r\n使用指令“空气质量”加监测站编号查看数据" end local function air(message) if message == "空气质量" then return "使用帮助:\r\n发送空气质量加城市英文(拼音),即可查询\r\n如:空气质量harbin" elseif message:find("空气质量") == 1 then message = message:gsub("空气质量 *","") if tonumber(message) then return getInfo(message) else return search(message) end end end return {--空气质量 check = function (data) return data.msg:find("空气质量") == 1 end, run = function (data,sendMessage) sys.taskInit(function()--用到了异步http,必须新开个任务 sendMessage(Utils.CQCode_At(data.qq).."\r\n"..air(data.msg)) end) return true end, explain = function () return "[CQ:emoji,id=128168]空气质量" end }
AntiCheat.Locales['nl'] = { ['checking'] = '👮 𝗧𝗶𝗴𝗼𝗔𝗻𝘁𝗶𝗖𝗵𝗲𝗮𝘁 | U wordt momenteel gecontroleerd...', ['empty_reason'] = 'Geen reden was opgegeven', ['resource_starting'] = '👮 𝗧𝗶𝗴𝗼𝗔𝗻𝘁𝗶𝗖𝗵𝗲𝗮𝘁 | Is momenteel bezig met opstarten, even geduld aub....', ['unknown_error'] = '🛑 𝗧𝗶𝗴𝗼𝗔𝗻𝘁𝗶𝗖𝗵𝗲𝗮𝘁 | U kunt niet joinen door een onbekende fout, probeer het opnieuw', ['country_not_allowed'] = '🛑 𝗧𝗶𝗴𝗼𝗔𝗻𝘁𝗶𝗖𝗵𝗲𝗮𝘁 | Uw land {{{country}}} is niet toegestaan om deze server te joinen', ['blocked_ip'] = '🛑 𝗧𝗶𝗴𝗼𝗔𝗻𝘁𝗶𝗖𝗵𝗲𝗮𝘁 | Uw IP staat op een blacklist, dit kan komen omdat u gebruik maakt van een VPN of uw IP betrokken is bij verdachten activiteiten', ['banned'] = '🛑 𝗧𝗶𝗴𝗼𝗔𝗻𝘁𝗶𝗖𝗵𝗲𝗮𝘁 | U bent verbannen van deze server ( 𝗚𝗲𝗯𝗿𝘂𝗶𝗸𝗲𝗿𝘀𝗻𝗮𝗮𝗺: {{{username}}} )', ['new_identifiers'] = 'Nieuwe identifiers gevonden', ['ban_type_godmode'] = 'Godmode gedetecteerd op speler', ['ban_type_injection'] = 'Speler heeft commando\'s geïnjecteerd (Injection)', ['ban_type_blacklisted_weapon'] = 'Speler had een wapen van de zwarte lijst: {{{item}}}', ['ban_type_blacklisted_key'] = 'Speler had op een key gedrukt die op de zwarte lijst staat: {{{item}}}', ['ban_type_hash'] = 'Speler had een hash aangepast', ['ban_type_esx_shared'] = 'Speler heeft een esx:getSharedObject getriggerd', ['ban_type_superjump'] = 'De speler had zijn spronghoogte aangepast', ['ban_type_client_files_blocked'] = 'Speler reageerde niet na 5 keer vragen of hij nog leefde (Client Files Blocked)', ['ban_type_event'] = 'De speler heeft geprobeerd om \'{{{event}}}\' aan te roepen', ['none'] = 'Geen', -- Discord ['discord_title'] = '[TigoAntiCheat] Heeft een speler verbannen', ['discord_description'] = '**Naam:** {{{name}}}\n **Reden:** {{{reason}}}\n **Identifiers:**\n {{{identifiers}}}\n **Matching Identifiers:**\n {{{matchingIdentifiers}}}' }
#!/usr/bin/env lua -- A semaphore (traffic light) with a simple GUI. -- Requires: - MoonSC to define the behavior of the semaphore, -- - MoonNuklear to draw the GUI, -- - MoonGLFW for window creation and input handling, -- - MoonGL for rendering. local glfw = require("moonglfw") local gl = require("moongl") local nk = require("moonnuklear") local backend = require("moonnuklear.glbackend") local moonsc = require("moonsc") moonsc.import_tags() local now = moonsc.now local TITLE = "Semaphore" -- GLFW window title local FPS = 20 -- minimum frames per seconds local X, Y, W, H = 100, 200, 160, 500 -- window position and size local BGCOLOR = {0.10, 0.18, 0.24, 1.0} -- background color local R, G, B, A = table.unpack(BGCOLOR) local DEFAULT_FONT_PATH = nil -- full path filename of a ttf file (optional) ------------------------------------------------------------------------------- -- Statechart ------------------------------------------------------------------------------- -- This statechart defines the behavior of the semaphore: -- initially red, switches to green after 5s, then to yellow after 3s, -- then back to red after 2s. Repeats this cycle indefinitely. -- Expects a global set_light() function to be defined in its environment -- to switch on one light and off the other ones. local statechart = _scxml{ name='semaphore', initial='red', _state{ id='red', _onentry{ _script{ text=[[set_light('red')]] }, _log{ expr="'Semaphore is red'" }, _send{ event='timeout', delay='5s' }, }, _transition{ event='timeout', target='green' }, }, _state{ id='green', _onentry{ _script{ text=[[set_light('green')]] }, _log{ expr="'Semaphore is green'" }, _send{ event='timeout', delay='3s' }, }, _transition{ event='timeout', target='yellow' }, }, _state{ id='yellow', _onentry{ _script{ text=[[set_light('yellow')]] }, _log{ expr="'Semaphore is yellow'" }, _send{ event='timeout', delay='2s' }, }, _transition{ event='timeout', target='red' }, } } ------------------------------------------------------------------------------- -- GUI ------------------------------------------------------------------------------- local RED, DARK_RED = {1, 0, 0, 1}, {.3, 0, 0, 1} local GREEN, DARK_GREEN = {0, 1, 0, 1}, {0, .3, 0, 1} local YELLOW, DARK_YELLOW = {1, 1, 0, 1}, {.3, .3, 0, 1} local red_light, green_light, yellow_light -- color of the 3 lights local function set_light(on) -- The statechart will call this to switch one light on and the others off red_light = on=='red' and RED or DARK_RED green_light = on=='green' and GREEN or DARK_GREEN yellow_light = on=='yellow' and YELLOW or DARK_YELLOW end local function draw_gui(ctx) if nk.window_begin(ctx, "GUI", {0, 0, W, H}, nk.WINDOW_NO_SCROLLBAR) then local canvas = nk.window_get_canvas(ctx) canvas:fill_circle({10, 20, 140, 140}, red_light) canvas:fill_circle({10, 180, 140, 140}, yellow_light) canvas:fill_circle({10, 340, 140, 140}, green_light) end nk.window_end(ctx) end ------------------------------------------------------------------------------- -- Main ------------------------------------------------------------------------------- -- GL/GLFW inits glfw.version_hint(3, 3, 'core') glfw.window_hint('resizable', false) local window = glfw.create_window(W, H, TITLE) glfw.make_context_current(window) glfw.set_window_pos(window, X, Y) gl.init() -- Initialize the backend local ctx = backend.init(window, { vbo_size = 512*1024, ebo_size = 128*1024, anti_aliasing = true, clipboard = false, callbacks = true, circle_segment_count = 48, }) -- Load fonts local atlas = backend.font_stash_begin() local default_font = atlas:add(13, DEFAULT_FONT_PATH) backend.font_stash_end(ctx, default_font) -- Set callbacks glfw.set_key_callback(window, function (window, key, scancode, action, shift, control, alt, super) if key == 'escape' and action == 'press' then glfw.set_window_should_close(window, true) end backend.key_callback(window, key, scancode, action, shift, control, alt, super) end) moonsc.set_log_callback(function(sessionid, label, expr) print(expr) end) -- Create a running instance of the statechart (i.e. a session): local sessionid = moonsc.generate_sessionid() moonsc.create(sessionid, statechart) -- Add the set_light() function to the session's dedicated environment, -- so that we can change the GUI aspect from the statechart: moonsc.get_env(sessionid)['set_light'] = set_light -- Start the statechart: moonsc.start(sessionid) local tnext = now() -- next time moonsc.trigger() must be called local dtmax = 1/FPS -- max wait interval (for responsiveness) local function limit(dt) -- limits a time interval between 0 and dtmax return dt < 0 and 0 or (dt > dtmax and dtmax or dt) end collectgarbage() collectgarbage('stop') while not glfw.window_should_close(window) do -- Wait for input events: local dt = limit(tnext-now()) glfw.wait_events_timeout(dt) -- Execute the logic tnext = moonsc.trigger() if not tnext then break end -- no more sessions running in the system -- Start a new frame: backend.new_frame() -- Draw the GUI: draw_gui(ctx) -- Render: W, H = glfw.get_window_size(window) gl.viewport(0, 0, W, H) gl.clear_color(R, G, B, A) gl.clear('color') backend.render() glfw.swap_buffers(window) collectgarbage() end backend.shutdown()
local data = require("core.data") data.define_prototype("activity") data.add( "core.activity", { eat = { integer_id = 1, }, read = { integer_id = 2, }, travel = { integer_id = 3, }, sleep = { integer_id = 4, }, dig_wall = { integer_id = 5, }, perform = { integer_id = 6, }, fish = { integer_id = 7, }, search_material = { integer_id = 8, }, dig_around = { integer_id = 9, }, -- Activity `integer_id` 10 is used for several purposes in vanilla. In foobar, it is separated to each activity. sleep = { -- integer_id = 10, gdata(91) = 100 }, build_shelter = { -- integer_id = 10, gdata(91) = 101 }, enter_shelter = { -- integer_id = 10, gdata(91) = 102 }, harvest = { -- integer_id = 10, gdata(91) = 103 }, study = { -- integer_id = 10, gdata(91) = 104 }, steal = { -- integer_id = 10, gdata(91) = 105 }, sex = { integer_id = 11, }, blend = { integer_id = 12, }, } )
local Utils = { generateQuads = function (atlas, tileWidth, tileHeight) local quads = {} local width, height = atlas:getDimensions() local sheetWidth = width / tileWidth local sheetHeight = height / tileHeight local spriteCount = 1 for y = 0, sheetHeight - 1 do for x = 0, sheetWidth - 1 do quads[spriteCount] = love.graphics.newQuad(x * tileWidth, y * tileHeight, tileWidth, tileHeight, width, height) spriteCount = spriteCount + 1 end end return quads end, generateQuadsFromTo = function(atlas, tileWidth, tileHeight, from, total, offset) from = from or { x = 0, y = 0 } total = total or -1 offset = offset or { x = 0, y = 0 } local quads = {} local width, height = atlas:getDimensions() local sheetWidth = width / tileWidth local sheetHeight = height / tileHeight local spriteCount = 0 (function() for y = from.y, sheetHeight - 1 do for x = from.x, sheetWidth - 1 do spriteCount = spriteCount + 1 quads[spriteCount] = love.graphics.newQuad(x * (tileWidth + offset.x), y * (tileHeight + offset.y), tileWidth, tileHeight, width, height) if spriteCount >= total then return end end end end)() return quads end } return Utils
--[[ Copyright (c) 2015 深圳市辉游科技有限公司. --]] require 'consts' local RoleImages = {} RoleImages[ddz.PlayerRoles.Farmer] = {} RoleImages[ddz.PlayerRoles.Farmer][ddz.Gender.Male] = { win = 'NewRes/paint/paint_farmer_v.png', lose = 'NewRes/paint/paint_farmer_f.png', left = 'NewRes/paint/paint_farmer_default_left.png', right = 'NewRes/paint/paint_farmer_default_right.png' } RoleImages[ddz.PlayerRoles.Farmer][ddz.Gender.Female] = { win = 'NewRes/paint/paint_farmeress_v.png', lose = 'NewRes/paint/paint_farmeress_f.png', left = 'NewRes/paint/paint_farmeress_default_left.png', right = 'NewRes/paint/paint_farmeress_default_right.png' } RoleImages[ddz.PlayerRoles.Lord] = {} RoleImages[ddz.PlayerRoles.Lord][ddz.Gender.Male] = { win = 'NewRes/paint/paint_lord_v.png', lose = 'NewRes/paint/paint_lord_f.png' , left = 'NewRes/paint/paint_lord_default_left.png', right = 'NewRes/paint/paint_lord_default_right.png' } RoleImages[ddz.PlayerRoles.Lord][ddz.Gender.Female] = { win = 'NewRes/paint/paint_lordress_v.png', lose = 'NewRes/paint/paint_lordress_f.png' , left = 'NewRes/paint/paint_lordress_default_left.png', right = 'NewRes/paint/paint_lordress_default_right.png' } return RoleImages
local lspconfig = require "lspconfig" local on_attach = function(client) -- require "completion".on_attach(client) print("'" .. client.name .. "' server attached") end lspconfig.elixirls.setup { cmd = {"/usr/local/bin/elixir-ls/language_server.sh"}, on_attach = on_attach, }
-- Lua functions accept any number of arguments; missing arguments are nil-padded, extras are dropped. function fixed (a, b, c) print(a, b, c) end fixed() --> nil nil nil fixed(1, 2, 3, 4, 5) --> 1 2 3 -- True vararg functions include a trailing ... parameter, which captures all additional arguments as a group of values. function vararg (...) print(...) end vararg(1, 2, 3, 4, 5) -- 1 2 3 4 5 -- Lua also allows dropping the parentheses if table or string literals are used as the sole argument print "some string" print { foo = "bar" } -- also serves as a form of named arguments -- First-class functions in expression context print(("this is backwards uppercase"):gsub("%w+", function (s) return s:upper():reverse() end)) -- Functions can return multiple values (including none), which can be counted via select() local iter, obj, start = ipairs { 1, 2, 3 } print(select("#", (function () end)())) --> 0 print(select("#", unpack { 1, 2, 3, 4 })) --> 4 -- Partial application function prefix (pre) return function (suf) return pre .. suf end end local prefixed = prefix "foo" print(prefixed "bar", prefixed "baz", prefixed "quux") -- nil, booleans, and numbers are always passed by value. Everything else is always passed by reference. -- There is no separate notion of subroutines -- Built-in functions are not easily distinguishable from user-defined functions
fx_version 'cerulean' game 'gta5' lua54 'yes' ui_page 'index.html' files { "index.html", "scripts.js", "css/style.css" } client_script { "client.lua", } export "taskBar" export "closeGuiFail"
local allowCountdown = false function onStartCountdown() if not allowCountdown and isStoryMode and not seenCutscene then --Block the first countdown setProperty('camGame.visible', false) setProperty('camHUD.visible', false) runtimer('lowEnd',1,1) allowCountdown = true; return Function_Stop; end setProperty('camGame.visible', true) setProperty('camHUD.visible', true) return Function_Continue; end function onTimerCompleted(tags, Loops, LoopsLeft) if tag == 'lowEnd' then startVideo('lofight'); end end
local M = {} -- M.my_theme = { -- bg = "#3A3845", -- fg = "#FAF5E4", -- -- black = "#3A3845", -- blue = "#9ADCFF", -- cyan = "#D1E8E4", -- darkblue = "#9ADCFF", -- green = "#BEDBBB", -- oceanblue = "#9ADCFF", -- orange = "#FFA299", -- magenta = "#FFC7C7", -- red = "#FF7878", -- skyblue = "#9ADCFF", -- violet = "#C3AED6", -- white = "#FAF5E4", -- yellow = "#FEE2B3", -- } -- M.my_theme = { bg = "#3c3836", fg = "#fbf1c7", black = "#282828", blue = "#83a598", cyan = "#689d6a", darkblue = "#83a598", green = "#98971a", oceanblue = "#83a598", skyblue = "#83a598", orange = "#d79921", magenta = "#b16286", red = "#cc241d", white = "#fbf1c7", yellow = "#fabd2f", } return M
require("games/common2/module/layerShowTypeData"); require("games/common2/onlooker/data/onlookerPlayerManager"); local OnlookerSocketCmd = require("games/common2/onlooker/socket/onlookerSocketCmd"); local OnlookerController = class(); OnlookerController.initOnlookerRoom = function(self) Log.d("OnlookerController.initOnlookerRoom"); local showType = LayerShowTypeData.getInstance():getOnlookerType(); LayerShowTypeData.getInstance():setCurShowType(showType); self:updateView(self.m_view.s_cmds.InitOnlookerRoom); self:_addOnlookerSocketTools(); if GameInfoIsolater.getInstance():isInMatchRoom() then self:initMatchRoom(); end end OnlookerController.releaseOnlookerRoom = function(self) Log.d("OnlookerController.releaseOnlookerRoom"); self:_stopLoginOnlookerTimer(); self:_removeOnlookerSocketTools(); end -------------------------------------------------------------------------------------------- OnlookerController.resume = function(self) CommonController.resume(self); CommunityLogic.getInstance(); end OnlookerController.requestEnterRoom = function(self) --请求进围观 Log.d("OnlookerController.requestEnterRoom"); local uid = UserBaseInfoIsolater.getInstance():getUserId(); MechineManage.getInstance():receiveAction(GameMechineConfig.ACTION_ENTER_ONLOOKER,uid); if GameInfoIsolater.getInstance():isInMatchRoom() then local _,onlookerdId = self.m_state:getBundleData(); local info = {}; info.userId = onlookerdId; MatchMechine.getInstance():receiveAction(MatchMechineConfig.ACTION_ENTER_ONLOOKER,info); end self:_startLoginOnlookerTimer(); self:requestLoginOnlooker(); end OnlookerController.onBackPressed = function(self) if DialogLogic.getInstance():popDialog() then return; end if IBaseDialog.isDialogShowing() then IBaseDialog.onBackHidden(); return; end self:requestLogoutOnlooker(); end OnlookerController.startReconnect = function(self) LoadingView.getInstance():showText("正在连接网络"); self.m_isDuringReconnect = true; self:_startLoginOnlookerTimer(); self:requestLoginOnlooker(); end OnlookerController.checkIsExitRoom = function(self) end -------------------------------------------------------------------------------------------- OnlookerController.requestLoginOnlooker = function(self) local param,onlookerdId = self.m_state:getBundleData(); param = table.verify(param); local curGameId = GameInfoIsolater.getInstance():getCurGameId(); local info = {}; info.userInfo = CommonPlayerInfoHandler2.getInstance():getUserLoginJsonInfo(curGameId); info.tmid = onlookerdId; info.keepOnlooker = 0;--是否一直围观,1:持续围观,0:看完被围观者正在打的那桌就被server踢出 info.extend = param.enterOnlookerExtendParam or "";--扩展字段(json) SocketIsolater.getInstance():sendMsg(OnlookerSocketCmd.C_REQUEST_LOGIN_ONLOOKER,info); end OnlookerController.requestLogoutOnlooker = function(self) local _,onlookerdId = self.m_state:getBundleData(); local info = {}; info.tmid = onlookerdId; SocketIsolater.getInstance():sendMsg(OnlookerSocketCmd.C_REQUEST_LOGOUT_ONLOOKER,info); end OnlookerController.onEnterOnlookerSuc = function(self) self:_stopLoginOnlookerTimer(); LoadingView.getInstance():hidden(); OnlookerPlayerManager.getInstance():removeAllOnlooker(); self.m_isDuringReconnect = nil; end OnlookerController.onExitOnlookerSuc = function(self) LayerShowTypeData.getInstance():setCurShowType(nil); OnlookerPlayerManager.getInstance():removeAllOnlooker(); if GameInfoIsolater.getInstance():isInMatchRoom() then self:releaseMatchRoom(); end local info = self.m_state:getBundleData(); info = table.verify(info); local hallGameType = GameInfoIsolater.getInstance():getHallGameType(); local stateId = info.jumpStateId or hallGameType; local data = {}; data.viewJumpParam = info.viewJumpParam; GameInfoIsolater.getInstance():startGame(stateId,nil,data); end -------------------------------------------------------------------------------------------- OnlookerController._startLoginOnlookerTimer = function(self) self.m_loginOnlookerTimer = Clock.instance():schedule_once(function() self:requestLogoutOnlooker(); self:onExitOnlookerSuc(); LoadingView.getInstance():hidden(); end, 10); end OnlookerController._stopLoginOnlookerTimer = function(self) if self.m_loginOnlookerTimer then self.m_loginOnlookerTimer:cancel(); end self.m_loginOnlookerTimer = nil; end OnlookerController._addOnlookerSocketTools = function(self) self.m_socket = SocketIsolater.getInstance(); local OnlookerSocketReader = require("games/common2/onlooker/socket/onlookerSocketReader"); self.m_onlookerSocketReader = new(OnlookerSocketReader); self.m_socket:addSocketReader(self.m_onlookerSocketReader); local OnlookerSocketWriter = require("games/common2/onlooker/socket/onlookerSocketWriter"); self.m_onlookerSocketWriter = new(OnlookerSocketWriter); self.m_socket:addSocketWriter(self.m_onlookerSocketWriter); local OnlookerSocketProcesser = require("games/common2/onlooker/socket/onlookerSocketProcesser"); self.m_onlookerSocketProcesser = new(OnlookerSocketProcesser,self); end OnlookerController._removeOnlookerSocketTools = function(self) self.m_socket:removeSocketReader(self.m_onlookerSocketReader); self.m_socket:removeSocketWriter(self.m_onlookerSocketWriter); delete(self.m_onlookerSocketReader); self.m_onlookerSocketReader = nil; delete(self.m_onlookerSocketWriter); self.m_onlookerSocketWriter = nil; delete(self.m_onlookerSocketProcesser); self.m_onlookerSocketProcesser = nil; end -------------------------------------------------------------------------------------------- OnlookerController._joinMatchRoom = function(self) end -------------------------------------------------------------------------------------------- OnlookerController.s_stateFuncMap = {}; OnlookerController.s_actionFuncMap = { [GameMechineConfig.ACTION_ENTER_ONLOOKER_SUC] = "onEnterOnlookerSuc"; [GameMechineConfig.ACTION_EXIT_ONLOOKER_SUC] = "onExitOnlookerSuc"; [GameMechineConfig.ACTION_REQUEST_EXIT_ONLOOKER] = "requestLogoutOnlooker"; }; return OnlookerController;
if not modules then modules = { } end modules ['lpdf-tag'] = { version = 1.001, comment = "companion to lpdf-tag.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local next = next local format, match, concat = string.format, string.match, table.concat local lpegmatch, P, S, C = lpeg.match, lpeg.P, lpeg.S, lpeg.C local settings_to_hash = utilities.parsers.settings_to_hash local sortedhash = table.sortedhash local formatters = string.formatters local trace_tags = false trackers.register("structures.tags", function(v) trace_tags = v end) local report_tags = logs.reporter("backend","tags") local backends = backends local lpdf = lpdf local nodes = nodes local nodeinjections = backends.pdf.nodeinjections local codeinjections = backends.pdf.codeinjections local enableaction = nodes.tasks.enableaction local pdfdictionary = lpdf.dictionary local pdfarray = lpdf.array local pdfboolean = lpdf.boolean local pdfconstant = lpdf.constant local pdfreference = lpdf.reference local pdfunicode = lpdf.unicode local pdfflushobject = lpdf.flushobject local pdfreserveobject = lpdf.reserveobject local pdfpagereference = lpdf.pagereference local addtocatalog = lpdf.addtocatalog local addtopageattributes = lpdf.addtopageattributes local texgetcount = tex.getcount local nodecodes = nodes.nodecodes local hlist_code = nodecodes.hlist local vlist_code = nodecodes.vlist local glyph_code = nodecodes.glyph local a_tagged = attributes.private('tagged') local a_image = attributes.private('image') local nuts = nodes.nuts local tonut = nuts.tonut local tonode = nuts.tonode local nodepool = nuts.pool local pdfpageliteral = nodepool.pdfpageliteral local register = nodepool.register local getid = nuts.getid local getattr = nuts.getattr local getprev = nuts.getprev local getnext = nuts.getnext local getlist = nuts.getlist local setlink = nuts.setlink local setlist = nuts.setlist local copy_node = nuts.copy local traverse_nodes = nuts.traverse local tosequence = nuts.tosequence local structure_stack = { } local structure_kids = pdfarray() local structure_ref = pdfreserveobject() local parent_ref = pdfreserveobject() local root = { pref = pdfreference(structure_ref), kids = structure_kids } local tree = { } local elements = { } local names = pdfarray() local structurestags = structures.tags local taglist = structurestags.taglist local specifications = structurestags.specifications local usedlabels = structurestags.labels local properties = structurestags.properties local usewithcare = structurestags.usewithcare local usedmapping = { } ----- tagsplitter = structurestags.patterns.splitter -- local embeddedtags = false -- true will id all, for tracing -- local f_tagid = formatters["%s-%04i"] -- local embeddedfilelist = pdfarray() -- /AF crap -- -- directives.register("structures.tags.embedmath",function(v) -- if not v then -- -- only enable -- elseif embeddedtags == true then -- -- already all tagged -- elseif embeddedtags then -- embeddedtags.math = true -- else -- embeddedtags = { math = true } -- end -- end) -- function codeinjections.maptag(original,target,kind) -- mapping[original] = { target, kind or "inline" } -- end local function finishstructure() if #structure_kids > 0 then local nums, n = pdfarray(), 0 for i=1,#tree do n = n + 1 ; nums[n] = i - 1 n = n + 1 ; nums[n] = pdfreference(pdfflushobject(tree[i])) end local parenttree = pdfdictionary { Nums = nums } -- we need to split names into smaller parts (e.g. alphabetic or so) -- we already have code for that somewhere if #names > 0 then local kids = pdfdictionary { Limits = pdfarray { names[1], names[#names-1] }, Names = names, } local idtree = pdfdictionary { Kids = pdfarray { pdfreference(pdfflushobject(kids)) }, } end -- local rolemap = pdfdictionary() for k, v in next, usedmapping do k = usedlabels[k] or k local p = properties[k] rolemap[k] = pdfconstant(p and p.pdf or "Span") -- or "Div" end local structuretree = pdfdictionary { Type = pdfconstant("StructTreeRoot"), K = pdfreference(pdfflushobject(structure_kids)), ParentTree = pdfreference(pdfflushobject(parent_ref,parenttree)), IDTree = #names > 0 and pdfreference(pdfflushobject(idtree)) or nil, RoleMap = rolemap, -- sorted ? } pdfflushobject(structure_ref,structuretree) addtocatalog("StructTreeRoot",pdfreference(structure_ref)) -- if lpdf.majorversion() == 1 then local markinfo = pdfdictionary { Marked = pdfboolean(true) or nil, -- UserProperties = pdfboolean(true), -- maybe some day -- Suspects = pdfboolean(true) or nil, -- AF = #embeddedfilelist > 0 and pdfreference(pdfflushobject(embeddedfilelist)) or nil, } addtocatalog("MarkInfo",pdfreference(pdfflushobject(markinfo))) end -- for fulltag, element in sortedhash(elements) do -- sorting is easier on comparing pdf pdfflushobject(element.knum,element.kids) end end end lpdf.registerdocumentfinalizer(finishstructure,"document structure") local index, pageref, pagenum, list = 0, nil, 0, nil local pdf_mcr = pdfconstant("MCR") local pdf_struct_element = pdfconstant("StructElem") local function initializepage() index = 0 pagenum = texgetcount("realpageno") pageref = pdfreference(pdfpagereference(pagenum)) list = pdfarray() tree[pagenum] = list -- we can flush after done, todo end local function finishpage() -- flush what can be flushed addtopageattributes("StructParents",pagenum-1) end -- here we can flush and free elements that are finished local pdf_userproperties = pdfconstant("UserProperties") local function makeattribute(t) if t and next(t) then local properties = pdfarray() for k, v in sortedhash(t) do -- easier on comparing pdf properties[#properties+1] = pdfdictionary { N = pdfunicode(k), V = pdfunicode(v), } end return pdfdictionary { O = pdf_userproperties, P = properties, } end end local function makeelement(fulltag,parent) local specification = specifications[fulltag] local tag = specification.tagname if tag == "ignore" then return false elseif tag == "mstackertop" or tag == "mstackerbot" or tag == "mstackermid"then -- TODO return true end -- local detail = specification.detail local userdata = specification.userdata -- usedmapping[tag] = true -- -- specification.attribute is unique -- local id = nil -- local af = nil -- if embeddedtags then -- local tagname = specification.tagname -- local tagindex = specification.tagindex -- if embeddedtags == true or embeddedtags[tagname] then -- id = f_tagid(tagname,tagindex) -- af = job.fileobjreferences.collected[id] -- if af then -- local r = pdfreference(af) -- af = pdfarray { r } -- -- embeddedfilelist[#embeddedfilelist+1] = r -- end -- end -- end -- local k = pdfarray() local r = pdfreserveobject() local t = usedlabels[tag] or tag local d = pdfdictionary { Type = pdf_struct_element, S = pdfconstant(t), ID = id, T = detail and detail or nil, P = parent.pref, Pg = pageref, K = pdfreference(r), A = a and makeattribute(a) or nil, -- Alt = " Who cares ", -- ActualText = " Hi Hans ", AF = af, } local s = pdfreference(pdfflushobject(d)) if id then names[#names+1] = id names[#names+1] = s end local kids = parent.kids kids[#kids+1] = s local e = { tag = t, pref = s, kids = k, knum = r, pnum = pagenum } elements[fulltag] = e return e end local f_BDC = formatters["/%s <</MCID %s>> BDC"] local function makecontent(parent,id,specification) local tag = parent.tag local kids = parent.kids local last = index if id == "image" then local list = specification.taglist local data = usewithcare.images[list[#list]] local label = data and data.label local d = pdfdictionary { Type = pdf_mcr, Pg = pageref, MCID = last, Alt = pdfunicode(label ~= "" and label or "image"), } kids[#kids+1] = d elseif pagenum == parent.pnum then kids[#kids+1] = last else local d = pdfdictionary { Type = pdf_mcr, Pg = pageref, MCID = last, } -- kids[#kids+1] = pdfreference(pdfflushobject(d)) kids[#kids+1] = d end -- index = index + 1 list[index] = parent.pref -- page related list -- return f_BDC(tag,last) end local function makeignore(specification) return "/Artifact BMC" end -- no need to adapt head, as we always operate on lists local EMCliteral = nil function nodeinjections.addtags(head) if not EMCliteral then EMCliteral = register(pdfpageliteral("EMC")) end local last = nil local ranges = { } local range = nil local head = tonut(head) local function collectranges(head,list) for n, id in traverse_nodes(head) do if id == glyph_code then -- maybe also disc local at = getattr(n,a_tagged) if not at then range = nil elseif last ~= at then range = { at, "glyph", n, n, list } -- attr id start stop list ranges[#ranges+1] = range last = at elseif range then range[4] = n -- stop end elseif id == hlist_code or id == vlist_code then local at = getattr(n,a_image) if at then local at = getattr(n,a_tagged) if not at then range = nil else ranges[#ranges+1] = { at, "image", n, n, list } -- attr id start stop list end last = nil else collectranges(getlist(n),n) end end end end initializepage() collectranges(head) if trace_tags then for i=1,#ranges do local range = ranges[i] local attr = range[1] local id = range[2] local start = range[3] local stop = range[4] local tags = taglist[attr] if tags then -- not ok ... only first lines report_tags("%s => %s : %05i % t",tosequence(start,start),tosequence(stop,stop),attr,tags.taglist) end end end local top = nil local noftop = 0 for i=1,#ranges do local range = ranges[i] local attr = range[1] local id = range[2] local start = range[3] local stop = range[4] local list = range[5] local specification = taglist[attr] local taglist = specification.taglist local noftags = #taglist local common = 0 if top then for i=1,noftags >= noftop and noftop or noftags do if top[i] == taglist[i] then common = i else break end end end local prev = common > 0 and elements[taglist[common]] or root local ignore = false local literal = nil for j=common+1,noftags do local tag = taglist[j] local prv = elements[tag] or makeelement(tag,prev) if prv == false then -- ignore this one prev = false ignore = true break elseif prv == true then -- skip this one else prev = prv end end if prev then literal = pdfpageliteral(makecontent(prev,id,specification)) elseif ignore then literal = pdfpageliteral(makeignore(specification)) end if literal then local prev = getprev(start) if prev then setlink(prev,literal) end setlink(literal,start) if list and getlist(list) == start then setlist(list,literal) end local literal = copy_node(EMCliteral) -- use insert instead: local next = getnext(stop) if next then setlink(literal,next) end setlink(stop,literal) end -- if literal then -- if list and getlist(list) == start then -- setlink(literal,start) -- setlist(list,literal) -- else -- setlink(getprev(start),literal,start) -- end -- -- use insert instead: -- local literal = copy_node(EMCliteral) -- setlink(stop,literal,getnext(stop)) -- end top = taglist noftop = noftags end finishpage() head = tonode(head) return head, true end -- variant: more structure but funny collapsing in viewer -- function nodeinjections.addtags(head) -- -- local last, ranges, range = nil, { }, nil -- -- local function collectranges(head,list) -- for n, id in traverse_nodes(head) do -- if id == glyph_code then -- local at = getattr(n,a_tagged) -- if not at then -- range = nil -- elseif last ~= at then -- range = { at, "glyph", n, n, list } -- attr id start stop list -- ranges[#ranges+1] = range -- last = at -- elseif range then -- range[4] = n -- stop -- end -- elseif id == hlist_code or id == vlist_code then -- local at = getattr(n,a_image) -- if at then -- local at = getattr(n,a_tagged) -- if not at then -- range = nil -- else -- ranges[#ranges+1] = { at, "image", n, n, list } -- attr id start stop list -- end -- last = nil -- else -- local nl = getlist(n) -- collectranges(nl,n) -- end -- end -- end -- end -- -- initializepage() -- -- head = tonut(head) -- collectranges(head) -- -- if trace_tags then -- for i=1,#ranges do -- local range = ranges[i] -- local attr = range[1] -- local id = range[2] -- local start = range[3] -- local stop = range[4] -- local tags = taglist[attr] -- if tags then -- not ok ... only first lines -- report_tags("%s => %s : %05i % t",tosequence(start,start),tosequence(stop,stop),attr,tags.taglist) -- end -- end -- end -- -- local top = nil -- local noftop = 0 -- local last = nil -- -- for i=1,#ranges do -- local range = ranges[i] -- local attr = range[1] -- local id = range[2] -- local start = range[3] -- local stop = range[4] -- local list = range[5] -- local specification = taglist[attr] -- local taglist = specification.taglist -- local noftags = #taglist -- local tag = nil -- local common = 0 -- -- local prev = root -- -- if top then -- for i=1,noftags >= noftop and noftop or noftags do -- if top[i] == taglist[i] then -- common = i -- else -- break -- end -- end -- end -- -- local result = { } -- local r = noftop - common -- if r > 0 then -- for i=1,r do -- result[i] = "EMC" -- end -- end -- -- local prev = common > 0 and elements[taglist[common]] or root -- -- for j=common+1,noftags do -- local tag = taglist[j] -- local prv = elements[tag] or makeelement(tag,prev) -- -- if prv == false then -- -- -- ignore this one -- -- prev = false -- -- break -- -- elseif prv == true then -- -- -- skip this one -- -- else -- prev = prv -- r = r + 1 -- result[r] = makecontent(prev,id) -- -- end -- end -- -- if r > 0 then -- local literal = pdfpageliteral(concat(result,"\n")) -- -- use insert instead: -- local literal = pdfpageliteral(result) -- local prev = getprev(start) -- if prev then -- setlink(prev,literal) -- end -- setlink(literal,start) -- if list and getlist(list) == start then -- setlist(list,literal) -- end -- end -- -- top = taglist -- noftop = noftags -- last = stop -- -- end -- -- if last and noftop > 0 then -- local result = { } -- for i=1,noftop do -- result[i] = "EMC" -- end -- local literal = pdfpageliteral(concat(result,"\n")) -- -- use insert instead: -- local next = getnext(last) -- if next then -- setlink(literal,next) -- end -- setlink(last,literal) -- end -- -- finishpage() -- -- head = tonode(head) -- return head, true -- -- end -- this belongs elsewhere (export is not pdf related) function codeinjections.enabletags(tg,lb) structures.tags.handler = nodeinjections.addtags enableaction("shipouts","structures.tags.handler") enableaction("shipouts","nodes.handlers.accessibility") enableaction("math","noads.handlers.tags") -- maybe also textblock if trace_tags then report_tags("enabling structure tags") end end
--gist:2cf8d094009635fe9c42 ----------------------------------------------------------------------------- -- Module declaration ----------------------------------------------------------------------------- local nibutil = {} ----------------------------------------------------------------------------- -- Public functions ----------------------------------------------------------------------------- --- Generates a table from an existing table with the key/value pairs reversed -- @param t The table to fetch key/value pairs from -- a clone of t with the key/value pairs reversed function nibutil.reverseKeysValues(t) local reverse = {} for k,v in pairs(t) do reverse[v] = k end return reverse end return nibutil
data:extend({ { type = "movement-bonus-equipment", name = "repair-module", take_result = "repair-module", sprite = { filename = "__PocketRepair__/graphics/equip-repair-module.png", width = 64, height = 64, priority = "medium" }, shape = { width = 2, height = 2, type = "full" }, energy_source = { type = "electric", buffer_capacity = "1MJ", input_flow_limit = "100KW", usage_priority = "secondary-input" }, energy_consumption = "10kW", movement_bonus = 0.0 } })
local TestEZ = require(game:GetService("ReplicatedStorage").TestEz) TestEZ.TestBootstrap:run({ script.Parent }) -- DEBUGGING ---[[ local express: Express = require(game:GetService("ReplicatedStorage").express) local App = express.App local app: App = App.new() app:get("/Test", function(_, res) res:send("Hello World!") end) app:Listen("Debug") wait(10) print("From Client:") print(express.Request.new("Debug://Test", "GET", game.Players.HawDevelopment, "Server")) --]]
--------------------------------------------- -- Earth Pounder -- -- Description: Deals Earth damage to enemies within area of effect. Additional effect: Dexterity Down -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 15' radial -- Notes: --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local typeEffect = tpz.effect.DEX_DOWN MobStatusEffectMove(mob, target, typeEffect, 10, 3, 120) local dmgmod = 1 local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*4,tpz.magic.ele.EARTH,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,tpz.attackType.MAGICAL,tpz.damageType.EARTH,MOBPARAM_WIPE_SHADOWS) target:takeDamage(dmg, mob, tpz.attackType.MAGICAL, tpz.damageType.EARTH) return dmg end
-- Copyright (C) Mashape, Inc. local BasePlugin = require "kong.plugins.base_plugin" local responses = require "kong.tools.responses" local cache = require "kong.tools.database_cache" local check_https = require("kong.tools.utils").check_https local SSLHandler = BasePlugin:extend() SSLHandler.PRIORITY = 3000 function SSLHandler:new() SSLHandler.super.new(self, "ssl") end function SSLHandler:certificate(conf) SSLHandler.super.certificate(self) local ssl = require "ngx.ssl" ssl.clear_certs() local data = cache.get_or_set(cache.ssl_data(ngx.ctx.api.id), function() local result = { cert_der = ngx.decode_base64(conf._cert_der_cache), key_der = ngx.decode_base64(conf._key_der_cache) } return result end) local ok, err = ssl.set_der_cert(data.cert_der) if not ok then ngx.log(ngx.ERR, "failed to set DER cert: ", err) return end ok, err = ssl.set_der_priv_key(data.key_der) if not ok then ngx.log(ngx.ERR, "failed to set DER private key: ", err) return end end function SSLHandler:access(conf) SSLHandler.super.access(self) if conf.only_https and not check_https(conf.accept_http_if_already_terminated) then ngx.header["connection"] = { "Upgrade" } ngx.header["upgrade"] = "TLS/1.0, HTTP/1.1" return responses.send(426, {message="Please use HTTPS protocol"}) end end return SSLHandler
require("constants") local StaticLayout = require("map/static_layout") local ruins_areas = { rubble = function(area) return nil end, debris = function(area) return PickSomeWithDups( 0.25 * area , {"rocks"}) end, } local function GetLayoutsForType( name ) local layouts = { ["SINGLE_NORTH"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/one", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.NORTH}), ["SINGLE_EAST"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/one", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.EAST}), ["L_NORTH"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/two", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.NORTH}), ["SINGLE_SOUTH"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/one", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.SOUTH}), ["TUNNEL_NS"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/long", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.NORTH}), ["L_EAST"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/two", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.EAST}), ["THREE_WAY_N"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/three", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.NORTH}), ["SINGLE_WEST"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/one", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.WEST}), ["L_WEST"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/two", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.WEST}), ["TUNNEL_EW"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/long", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.EAST}), ["THREE_WAY_W"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/three", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.WEST}), ["L_SOUTH"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/two", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.SOUTH}), ["THREE_WAY_S"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/three", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.SOUTH}), ["THREE_WAY_E"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/three", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.EAST}), ["FOUR_WAY"] = StaticLayout.Get("map/static_layouts/rooms/"..name.."/four", { areas = ruins_areas, force_rotation = LAYOUT_ROTATION.NORTH}), } return layouts end return { Layouts = GetLayoutsForType("room"), AllLayouts = { ["default"] = GetLayoutsForType("room"), ["hallway"] = GetLayoutsForType("hallway"), ["hallway_armoury"] = GetLayoutsForType("hallway_armoury"), ["hallway_residential"] = GetLayoutsForType("hallway_residential"), ["hallway_residential_two"] = GetLayoutsForType("hallway_residential_two"), --["hallway_shop"] = GetLayoutsForType("hallway_shop"), -- ["default"] = GetLayoutsForType("room_shop"), ["room_armoury"] = GetLayoutsForType("room_armoury"), ["room_armoury_two"] = GetLayoutsForType("room_armoury_two"), ["room_residential"] = GetLayoutsForType("room_residential"), ["room_residential_two"] = GetLayoutsForType("room_residential_two"), ["room_open"] = GetLayoutsForType("room_open"), }, }
local helpers = require "spec.helpers" describe("without host set", function() local proxy_client setup(function() local bp = helpers.get_db_utils('postgres', nil, { "redirecting" }) local route = bp.routes:insert({ hosts = { "example.com" }, }) bp.plugins:insert { name = "redirecting", route = { id = route.id }, config = {} } assert(helpers.start_kong({ database = "postgres", plugins = "bundled, redirecting", custom_plugins = "redirecting", nginx_conf = "spec/fixtures/custom_nginx.template" })) proxy_client = helpers.proxy_client() end) it('is not redirected', function() local res = proxy_client:get("/", { headers = { Host = "example.com" }, }) assert.res_status(200, res) end) teardown(function() if proxy_client then proxy_client:close() end helpers.stop_kong(nil, true) end) end) describe("with host set", function() local proxy_client setup(function() local bp = helpers.get_db_utils('postgres', nil, { "redirecting" }) local route = bp.routes:insert({ hosts = { "example.com" }, }) bp.plugins:insert { name = "redirecting", route = { id = route.id }, config = { host = 'redirected.com' } } assert(helpers.start_kong({ database = "postgres", plugins = "bundled, redirecting", custom_plugins = "redirecting", nginx_conf = "spec/fixtures/custom_nginx.template" })) proxy_client = helpers.proxy_client() end) describe("GET", function() it("is redirected", function() local res = proxy_client:get("/", { headers = { Host = "example.com" }, }) assert.res_status(301, res) assert.equal("http://redirected.com/", res.headers["Location"]) end) end) describe("POST", function() it("is redirected", function() local res = proxy_client:post("/create", { headers = { Host = "example.com" }, }) assert.res_status(301, res) assert.equal("http://redirected.com/create", res.headers["Location"]) end) end) teardown(function() if proxy_client then proxy_client:close() end helpers.stop_kong(nil, true) end) end)
resource.AddFile("materials/terranova/ui/books/blankbook.png") -- If markerOnly is true, then only change marker position, not text. netstream.Hook("ixSaveBookChanges", function(client, itemID, text, markerOnly, markerPos) markerOnly = markerOnly and markerOnly or false markerPos = markerPos and markerPos or "none" local character = client:GetCharacter() local item = ix.item.instances[itemID] -- we don't check for entity since data can be changed in the player's inventory if (character and item and item.base == "base_writablebook") then if markerOnly then local numberMarkerPos = tonumber(markerPos) if numberMarkerPos ~= nil then item:SetMarker(numberMarkerPos) return end end local owner = item:GetData("owner", 0) if (owner == 0 or owner == character:GetID()) then item:SetText(text, character) end end end)
--(C) 2015 Steven Byrnes --This is the lua script that S4 runs. Generally you don't run this yourself, you let Python call it --(see grating.py) pi = math.pi degree = pi / 180 math.randomseed(os.time()) function almost_equal(a,b,tol) return math.abs(a-b) <= tol * (math.abs(a) + math.abs(b)) end function str_from_complex(a) return string.format('%.4f + %.4f i', a[1], a[2]) end function polar_str_from_complex(a) local phase = math.atan2(a[1], a[2]) if phase < 0 then phase = phase + 2*pi end return string.format('amp:%.4f, phase:%.4fdeg', math.sqrt(a[1]^2 + a[2]^2), phase/deg) end function mergeTables(t1, t2) --for hash tables. With duplicate entries, t2 will overwrite. local out = {} for k,v in pairs(t1) do out[k] = v end for k,v in pairs(t2) do out[k] = v end return out end -- read parameters from configuration files (hopefully just now outputted by Python) -- all lengths in microns f = assert(io.open("temp/grating_setup.txt", "r")) what_to_do = f:read("*line") assert(what_to_do == '1' or what_to_do == '2') if what_to_do == '1' then what_to_do = 'fom' end if what_to_do == '2' then what_to_do = 'characterize' end if what_to_do == 'fom' then grating_period = tonumber(f:read("*line")) * 1e6 lateral_period = tonumber(f:read("*line")) * 1e6 angle_in_air = tonumber(f:read("*line")) n_glass = tonumber(f:read("*line")) nTiO2 = tonumber(f:read("*line")) cyl_height = tonumber(f:read("*line")) * 1e6 --num_G is the number of modes to include. Higher = slower but more accurate num_G = tonumber(f:read("*line")) elseif what_to_do == 'characterize' then grating_period = tonumber(f:read("*line")) * 1e6 lateral_period = tonumber(f:read("*line")) * 1e6 n_glass = tonumber(f:read("*line")) nTiO2 = tonumber(f:read("*line")) cyl_height = tonumber(f:read("*line")) * 1e6 num_G = tonumber(f:read("*line")) --ux,uy is direction cosine ux_min = tonumber(f:read("*line")) ux_max = tonumber(f:read("*line")) uy_min = tonumber(f:read("*line")) uy_max = tonumber(f:read("*line")) u_steps = tonumber(f:read("*line")) wavelength = tonumber(f:read("*line")) end --setting either nTiO2 or n_glass to 0 means "use tabulated data". -- this table is generated by refractive_index.py if nTiO2 == 0 then nTiO2_data = {[450]=2.5, [500]=2.433, [525]=2.41, [550]=2.391, [575]=2.375, [580]=2.372, [600]=2.362, [625]=2.351, [650]=2.341} end if n_glass == 0 then nSiO2_data = {[450]=1.466, [500]=1.462, [525]=1.461, [550]=1.46, [575]=1.459, [580]=1.459, [600]=1.458, [625]=1.457, [650]=1.457} end f = assert(io.open("temp/grating_xyrra_list.txt", "r")) xyrra_list = {} while f:read(0) == '' do local line = f:read("*line") --print('line' .. line) local t={} local i=1 for str in string.gmatch(line, "([^%s]+)") do t[i] = tonumber(str) i = i + 1 end if #t > 0 then xyrra_list[#xyrra_list+1] = t end end function set_up() --initial setup of a simulation local S = S4.NewSimulation() S:SetLattice({grating_period,0}, {0, lateral_period}) S:SetNumG(num_G) ------- Materials ------- --S:AddMaterial(name, {real part of epsilon, imag part of epsilon}) --if nTiO2 or n_glass is 0, don't worry, we'll set it later in --set_wavelength_angle() when we know the wavelength. S:AddMaterial("Air", {1,0}) S:AddMaterial("TiO2", {nTiO2^2,0}) S:AddMaterial("Glass", {n_glass^2,0}) ------- Layers ------- -- S:AddLayer(name, thickness, default material) S:AddLayer('Air', 0, 'Air') S:AddLayer('Cylinders', cyl_height, 'Air') S:AddLayer('Substrate', 0, 'Glass') for _,xyrra in ipairs(xyrra_list) do x,y,rx,ry,angle = unpack(xyrra) --print(x,y,rx,ry,angle) --S:SetLayerPatternEllipse(layer, material, center, angle (CCW, in degrees), halfwidths) S:SetLayerPatternEllipse('Cylinders', 'TiO2', {x,y}, angle, {rx,ry}) end return S end function set_wavelength_angle(arg) --set the wavelength and angle of incoming light --S is the result of set_up() local S = arg.S local pol = arg.pol assert((pol == 's') or (pol == 'p')) local wavelength = arg.wavelength local incident_theta = arg.incident_theta local incident_phi = arg.incident_phi if nTiO2 == 0 then local nTiO2_now = nTiO2_data[math.floor(wavelength*1000+0.5)] assert(nTiO2_now > 0) S:SetMaterial("TiO2", {nTiO2_now^2,0}) end local n_glass_now if n_glass == 0 then n_glass_now = nSiO2_data[math.floor(wavelength*1000+0.5)] assert(n_glass_now > 0) S:SetMaterial("Glass", {n_glass_now^2,0}) else n_glass_now = n_glass end local sAmplitude, pAmplitude if pol == 's' then sAmplitude = {1,0} -- amplitude and phase pAmplitude = {0,0} else sAmplitude = {0,0} pAmplitude = {1,0} end S:SetFrequency(1/wavelength) -- we set it up so that the incoming wave is the (0,0) diffraction order S:SetExcitationPlanewave( {incident_theta/degree,incident_phi/degree}, -- incidence angles (spherical coordinates: phi in [0,180], theta in [0,360]) sAmplitude, -- s-polarization amplitude and phase (in degrees) pAmplitude) -- p-polarization amplitude and phase --futz with these settings to make it more accurate for a given num_G S:UsePolarizationDecomposition() S:UseNormalVectorBasis() --S:UseJonesVectorBasis() --S:UseSubpixelSmoothing() --S:SetResolution(4) return {S, n_glass_now} end function fom(arg) -- Calculate a figure-of-merit, basically the amount of power going into the desired diffraction order. -- This is used for optimizing the gratings. --S is output from set_up() local S = arg.S local target_diffraction_order = arg.target_diffraction_order local incident_theta = arg.incident_theta local pol = arg.pol local wavelength = arg.wavelength local inphase = arg.inphase local S, n_glass_now = unpack(set_wavelength_angle{pol=pol, S=S, wavelength=wavelength, incident_theta=incident_theta, incident_phi=0}) local outgoing_order_index = S:GetDiffractionOrder(target_diffraction_order,0) local forw,_ = S:GetAmplitudes('Substrate',0) local complex_output_amplitude if pol == 's' then complex_output_amplitude = forw[outgoing_order_index] --at normal incidence (i.e. center of lens), it seems that s and p wind up with opposite phases due to some weird convention --(I think ... I still need to check explicitly). To keep --everything adding in phase, we need to keep the same s-vs-p phase relation throughout the lens complex_output_amplitude = {-complex_output_amplitude[1], -complex_output_amplitude[2]} else complex_output_amplitude = forw[outgoing_order_index + S:GetNumG()] end -- End result: Power in desired diffraction order if inphase then return math.abs(complex_output_amplitude[2]) * complex_output_amplitude[2] / n_glass_now / math.cos(incident_theta) else return (complex_output_amplitude[1]^2 + complex_output_amplitude[2]^2) / n_glass_now / math.cos(incident_theta) end -- We are looking at the imaginary part complex_output_amplitude[2], rather than the absolute -- value complex_output_amplitude[1]^2 + complex_output_amplitude[2]^2, because we want the -- output phases of different parts of the lens to agree. -- We are looking at the imaginary part complex_output_amplitude[2], rather than the real -- part complex_output_amplitude[1], for no particular reason, they would each work equally -- well as an optimization target. -- We are looking at math.abs(complex_output_amplitude[2]) * complex_output_amplitude[2], rather -- than complex_output_amplitude[2]^2, because we want to have consistent phase, no possible -- sign-flip. -- We are using S:GetAmplitudes() rather than S:GetPowerFluxByOrder() because the latter -- is calculated in the region where the different modes are all overlapping. Also, we want -- just the s --> s and p --> p polarization-conserved power because it's easier to think -- about that than the phases of two different polarizations at once. That means it's -- perhaps an underestimate of collimated power. --consistency check: The following two should match (at least approximately --return (complex_output_amplitude[1]^2 + complex_output_amplitude[2]^2) / n_glass_now / math.cos(incident_theta) -- ..... VS ..... --[[ local incident_power, total_reflected_power = S:GetPowerFlux('Air', 0) local total_transmitted_power, temp = S:GetPowerFlux('Substrate', 0) assert(temp==0) local transmitted_normal_power, back_r, forw_i, back_i = unpack(S:GetPowerFluxByOrder('Substrate',0)[outgoing_order_index]) assert(almost_equal(-total_reflected_power + total_transmitted_power, incident_power, 1e-3)) assert(back_i == 0 and back_r == 0 and forw_i == 0) return (transmitted_normal_power / incident_power) --]] -- This is the formula I was using earlier --local phase = math.atan2(complex_output_amplitude[1], complex_output_amplitude[2]) -- note: I got the atan2 arguments backwards, so that's really 90 degrees minus the phase. Doesn't matter. --return (transmitted_normal_power / incident_power) * math.cos(phase) end function print_orders(arg) -- This function will print the complex amplitude for the requested diffraction -- orders. This is used for far-field calculations. local S = arg.S local pol = arg.pol assert((pol == 's') or (pol == 'p')) local wavelength = arg.wavelength -- orders should be an array like {{0,0},{1,0},...} -- diffraction orders to calculate local orders=arg.orders assert(orders ~= nil) --ux,uy are direction cosines. They are outputted to make the results easier to parse, -- but otherwise are not used local ux = arg.ux local uy = arg.uy local forw,_ = S:GetAmplitudes('Substrate',0) local _,back = S:GetAmplitudes('Air',0) for _,order in ipairs(orders) do local ox,oy = unpack(order) local index = S:GetDiffractionOrder(ox,oy) local G = S:GetNumG() local complex_output_amplitude_fy = forw[index] local complex_output_amplitude_fx = forw[index + G] local complex_output_amplitude_ry = back[index] local complex_output_amplitude_rx = back[index + G] print(math.floor(wavelength*1000+0.5), pol, arg.ux, arg.uy, ox, oy, complex_output_amplitude_fy[1], complex_output_amplitude_fy[2], complex_output_amplitude_fx[1], complex_output_amplitude_fx[2], complex_output_amplitude_ry[1], complex_output_amplitude_ry[2], complex_output_amplitude_rx[1], complex_output_amplitude_rx[2]) end end function display_fom() --display figure of merit for optimizing gratings --order (short for target_diffraction_order) should be -1 for lens, 0 for light passing right through --inphase is whether or not we demand that the outgoing waves have consistent complex phase --[[ wavelengths_weights_orders_inphase = {{0.580, 1, -1, true}} --]] ---[[ wavelengths_weights_orders_inphase = {{0.580, 0.5, -1, true}, {0.450, 0.5, 0, true}} --]] --[[ wavelengths_weights_orders_inphase = {{0.500, 1, -1, false}, {0.580, 1, -1, true}, {0.650, 1, -1, false}} --]] score_so_far = 0 weight_so_far = 0 for i=1,#wavelengths_weights_orders_inphase,1 do local wavelength, weight, target_diffraction_order, inphase = unpack(wavelengths_weights_orders_inphase[i]) --right now I'm assuming that if we want light to pass through, we only care about normal incidence if target_diffraction_order ~= 0 then incident_theta = angle_in_air else incident_theta=0 end local S = set_up() local s = fom{pol='s', S=S, wavelength=wavelength,target_diffraction_order=target_diffraction_order, incident_theta=incident_theta, inphase=inphase} local p = fom{pol='p', S=S, wavelength=wavelength, target_diffraction_order=target_diffraction_order, incident_theta=incident_theta, inphase=inphase} --print('lam:', wavelength, 's:', s, 'p:', p) score_so_far = score_so_far + (s+p)/2 * weight weight_so_far = weight_so_far + weight end print(score_so_far / weight_so_far) --S:OutputLayerPatternDescription('Cylinders', 'temp/grating_img.ps') end if what_to_do == 'fom' then display_fom() do return end end function epsilon_map(S) local f = assert(io.open('temp/grating_eps.txt', 'w')) local z = cyl_height/2 for x = -grating_period/2,grating_period/2,grating_period/100 do for y = -lateral_period/2,lateral_period/2,lateral_period/100 do local eps_r, eps_i = S:GetEpsilon({x,y,z}) f:write(x,' ',y,' ',z,' ',eps_r,' ',eps_i,'\n') end end end --epsilon_map(S) function print_fields(S, z) local num_x = 20 local num_y = 20 for ix=1,num_x,1 do local x = -grating_period/2 + (ix / num_x) * grating_period for iy=1,num_y,1 do local y = -lateral_period/2 + (iy / num_y) * lateral_period Exr, Eyr, Ezr, Hxr, Hyr, Hzr, Exi, Eyi, Ezi, Hxi, Hyi, Hzi = S:GetFields({x, y, z}) print(x, y, z, Exr, Eyr, Ezr, Hxr, Hyr, Hzr, Exi, Eyi, Ezi, Hxi, Hyi, Hzi) end end end function characterize(arg) --characterize a grating by calculating all the complex output amplitudes as a --function of incoming angle local S = set_up() local wavelength = arg.wavelength local kvac = 2*pi / wavelength local grating_kx = 2*pi / grating_period local grating_ky = 2*pi / lateral_period --ux,uy are the direction cosines, i.e. the x and y components of the unit vector in the direction of the incoming light local ux_min = arg.ux_min local ux_max = arg.ux_max local uy_min = arg.uy_min local uy_max = arg.uy_max num_steps = arg.num_steps for ix=0,num_steps-1,1 do local ux if num_steps == 1 then ux = (ux_min + ux_max)/2 else ux = ux_min + ix * (ux_max - ux_min) / (num_steps-1) end local kx = kvac * ux for iy=0, num_steps-1,1 do local uy if num_steps == 1 then uy = (uy_min + uy_max)/2 else uy = uy_min + iy * (uy_max - uy_min) / (num_steps-1) end local ky = kvac * uy if ux^2+uy^2 < 1 then local theta = math.acos((1-ux^2-uy^2)^0.5) local phi = math.atan2(uy,ux) --find the propagating diffraction orders (ox,oy), where (0,0) is by definition the --incoming wave. Exclude the light that propagates but --totally-internally-reflects, unless include_tir flag is true. For calculating the --far-field, we really don't need that stuff, but for near-field consistency checks --we do. local k_cutoff if arg.include_tir == true then if n_glass > 0 then k_cutoff = kvac * n_glass else k_cutoff = kvac * nSiO2_data[math.floor(wavelength*1000+0.5)] end else k_cutoff = kvac end local orders = {} for ox=-5,5,1 do for oy=-5,5,1 do if (kx + ox*grating_kx)^2 + (ky + oy*grating_ky)^2 < k_cutoff^2 then table.insert(orders, {ox,oy}) end end end for _, pol in ipairs({'s', 'p'}) do set_wavelength_angle{pol=pol, S=S, wavelength=wavelength, incident_theta=theta, incident_phi=phi} --ux and uy are sent only for display purposes, not used in the calculation print_orders{pol=pol, S=S, wavelength=wavelength, orders=orders, ux=ux, uy=uy} end end end end end -- UNCOMMENT THESE LINES FOR S4conventions.py, where I'm figuring out the relation -- that S4 uses to translate between complex amplitudes and real-space fields --[[ num_G = 50 pol = 's' theta = math.asin((ux_min^2 + uy_min^2)^0.5) phi = math.atan2(uy_min, ux_min) characterize{num_G=num_G, ux_min=ux_min, ux_max=ux_max, uy_min=uy_min, uy_max=uy_max, num_steps=u_steps, wavelength=wavelength, include_tir=true} print('Fields') S = set_up() set_wavelength_angle{S=S, pol=pol, wavelength=wavelength, incident_theta=theta, incident_phi=phi} print_fields(S,-10.0) do return end --]] if what_to_do == 'characterize' then characterize{ux_min=ux_min, ux_max=ux_max, uy_min=uy_min, uy_max=uy_max, num_steps=u_steps, wavelength=wavelength} do return end end
local super = require("bt.composite") local states = super.states return class { typename = "顺序节点", super = super, ctor = function (self, repeats, ...) super.ctor(self, ...) self.repeats = repeats or 0 end, enter = function (self) local child self.repeated = 0 self.index = 0 while true do self.index = self.index + 1 child = self.children[self.index] if not child then self.repeated = self.repeated + 1 if self.repeats > 0 and self.repeated >= self.repeats then return false end self.index = 0 else if child:enter() then return true end end end end, update = function (self, dt) local child = self.children[self.index] if child then local ret = child:update(dt) if ret == states.END then while true do self.index = self.index + 1 child = self.children[self.index] if not child then self.repeated = self.repeated + 1 if self.repeats > 0 and self.repeated >= self.repeats then break end self.index = 0 else if child:enter() then return states.RUN end end end return states.END end return states.RUN end return states.END end, clone = function (self) local inst = self.class.new(self.repeats) for _, child in ipairs(self.children) do inst:add(child:clone()) end return inst end, }
return { uiEffect = "", name = "莱茵演习", cd = 0, focus_duration = 1, picture = "1", aniEffect = "", desc = "序章俾斯麦秒杀技能", painting = 1, id = 7000, effect_list = {} }
----------------------------------- -- Area: Ghelsba Outpost (140) -- NM: Thousandarm Deshglesh ----------------------------------- mixins = {require("scripts/mixins/job_special")}; ----------------------------------- function onMobDeath(mob, player, isKiller) end;
local _VERSION = "1.4a" if _HOST and fs then return fs end local lfs = require("lfs") local _check _check = function(f) return function(...) local args = { ... } for i, arg in ipairs(args) do assert(("string" == type(arg)), "argument #" .. tostring(i) .. " is not a string") end return f(...) end end local currentDir currentDir = function() return lfs.currentdir() end local changeDir = _check(function(path) lfs.chdir(path) currentDir = path end) local getDevice = _check(function(path) return lfs.attributes(path, "dev") end) local getInode = _check(function(path) return lfs.attributes(path, "ino") end) local getMode = _check(function(path) return lfs.attributes(path, "mode") end) local getLinks = _check(function(path) return lfs.attributes(path, "nlinks") end) local getUID = _check(function(path) return lfs.attributes(path, "uid") end) local getGID = _check(function(path) return lfs.attributes(path, "gid") end) local getDeviceType = _check(function(path) return lfs.attributes(path, "rdev") end) local getLastAccess = _check(function(path) return lfs.attributes(path, "access") end) local getLastModification = _check(function(path) return lfs.attributes(path, "modification") end) local getLastChange = _check(function(path) return lfs.attributes(path, "change") end) local getPermissions = _check(function(path) local permstring = lfs.attributes(path, "permissions") local permissions = { owner = { read = false, write = false, execute = false }, group = { read = false, write = false, execute = false }, world = { read = false, write = false, execute = false } } if permstring:match("r........") then permissions.owner.read = true end if permstring:match(".w.......") then permissions.owner.write = true end if permstring:match("..x......") then permissions.owner.execute = true end if permstring:match("...r.....") then permissions.group.read = true end if permstring:match("....w....") then permissions.group.write = true end if permstring:match(".....x...") then permissions.group.execute = true end if permstring:match("......r..") then permissions.world.read = true end if permstring:match(".......w.") then permissions.world.write = true end if permstring:match("........x") then permissions.world.execute = true end return permissions end) local getOctalPermissions = _check(function(path) local permnum = 000 local permstring = lfs.attributes(path, "permissions") if permstring:match("r........") then permnum = permnum + 400 end if permstring:match(".w.......") then permnum = permnum + 200 end if permstring:match("..x......") then permnum = permnum + 100 end if permstring:match("...r.....") then permnum = permnum + 040 end if permstring:match("....w....") then permnum = permnum + 020 end if permstring:match(".....x...") then permnum = permnum + 010 end if permstring:match("......r..") then permnum = permnum + 004 end if permstring:match(".......w.") then permnum = permnum + 002 end if permstring:match("........x") then permnum = permnum + 001 end return permnum end) local getBlocks = _check(function(path) return lfs.attributes(path, "blocks") end) local getBlockSize = _check(function(path) return lfs.attributes(path, "blksize") end) local getLinkDevice = _check(function(path) return lfs.symlinkattributes(path, "dev") end) local getLinkInode = _check(function(path) return lfs.symlinkattributes(path, "ino") end) local getLinkMode = _check(function(path) return lfs.symlinkattributes(path, "mode") end) local getLinkLinks = _check(function(path) return lfs.symlinkattributes(path, "nlinks") end) local getLinkUID = _check(function(path) return lfs.symlinkattributes(path, "uid") end) local getLinkGID = _check(function(path) return lfs.symlinkattributes(path, "gid") end) local getLinkDeviceType = _check(function(path) return lfs.symlinkattributes(path, "rdev") end) local getLinkLastAccess = _check(function(path) return lfs.symlinkattributes(path, "access") end) local getLinkLastModification = _check(function(path) return lfs.symlinkattributes(path, "modification") end) local getLinkLastChange = _check(function(path) return lfs.symlinkattributes(path, "change") end) local getLinkPermissions = _check(function(path) local permstring = lfs.symlinkattributes(path, "permissions") local permissions = { owner = { read = false, write = false, execute = false }, group = { read = false, write = false, execute = false }, world = { read = false, write = false, execute = false } } if permstring:match("r........") then permissions.owner.read = true end if permstring:match(".w.......") then permissions.owner.write = true end if permstring:match("..x......") then permissions.owner.execute = true end if permstring:match("...r.....") then permissions.group.read = true end if permstring:match("....w....") then permissions.group.write = true end if permstring:match(".....x...") then permissions.group.execute = true end if permstring:match("......r..") then permissions.world.read = true end if permstring:match(".......w.") then permissions.world.write = true end if permstring:match("........x") then permissions.world.execute = true end end) local getLinkOctalPermissions = _check(function(path) local permnum = 000 local permstring = lfs.symlinkattributes(path, "permissions") if permstring:match("r........") then permnum = permnum + 400 end if permstring:match(".w.......") then permnum = permnum + 200 end if permstring:match("..x......") then permnum = permnum + 100 end if permstring:match("...r.....") then permnum = permnum + 040 end if permstring:match("....w....") then permnum = permnum + 020 end if permstring:match(".....x...") then permnum = permnum + 010 end if permstring:match("......r..") then permnum = permnum + 004 end if permstring:match(".......w.") then permnum = permnum + 002 end if permstring:match("........x") then permnum = permnum + 001 end return permnum end) local getLinkBlocks = _check(function(path) return lfs.symlinkattributes(path, "blocks") end) local getLinkBlockSize = _check(function(path) return lfs.symlinkattributes(path, "blksize") end) local list = _check(function(path) return (function() local _accum_0 = { } local _len_0 = 1 for v in lfs.dir(path) do _accum_0[_len_0] = v _len_0 = _len_0 + 1 end return _accum_0 end)() end) local ilist = _check(function(path) local files = list(path) local i = 0 local n = #files return function() i = i + 1 if i <= n then return files[i] end end end) local list1 = _check(function(path) local _accum_0 = { } local _len_0 = 1 local _list_0 = list(path) for _index_0 = 1, #_list_0 do local file = _list_0[_index_0] if (file ~= "..") and (file ~= ".") then _accum_0[_len_0] = file _len_0 = _len_0 + 1 end end return _accum_0 end) local ilist1 = _check(function(path) local files = list1(path) local i = 0 local n = #files return function() i = i + 1 if i <= n then return files[i] end end end) local safeOpen safeOpen = function(path, mode) local a, b = io.open(path, mode) return a and a or { error = b } end local exists = _check(function(path) do local _with_0 = safeOpen(path, "rb") if _with_0.close then _with_0:close() return true else return false, _with_0.error end return _with_0 end end) local isDir = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "directory" end) local isFile = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "file" end) local isLink = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "link" end) local isSocket = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "socket" end) local isPipe = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "pipe" end) local isCharDevice = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "char device" end) local isBlockDevice = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "block device" end) local isOther = _check(function(path) if not (exists(path)) then local _ = false end return (lfs.attributes(path, "mode")) == "other" end) local isReadOnly = _check(function(path) if not (exists(path)) then error("isReadOnly $ " .. tostring(path) .. " does not exist") end return (lfs.attributes(path, "permissions")):match("w") and false or true end) local getName = _check(function(path) return path:match("/([^/]-)$") end) local getDrive = _check(function(path) return nil end) local getSize = _check(function(path) return lfs.attributes(path, "size") end) local getLinkSize = _check(function(path) return lfs.symlinkattributes(path, "size") end) local getFreeSpace = _check(function(path) return 0 end) local makeDir = lfs.mkdir local move = os.rename local combine = _check(function(basePath, localPath) do local _with_0 = basePath .. localPath if (not basePath:match("/$")) and (not localPath:match("^/")) then _with_0 = basePath .. "/" .. localPath else _with_0 = _with_0:gsub("//", "/") end return _with_0 end end) local filecopy = _check(function(fr, to) if not (exists(fr)) then error("copy $ " .. tostring(fr) .. " does not exist") end do local _with_0 = assert((io.open(fr, "rb")), "copy $ could not open " .. tostring(fr) .. " in 'rb' mode") local contents = _with_0:read("*a") do local _with_1 = assert((io.open(to, "wb")), "copy $ could not create " .. tostring(to) .. " in 'wb' mode") _with_1:write(contents) _with_1:close() end _with_0:close() return _with_0 end end) local copy copy = _check(function(fr, to) if not (exists(fr)) then error("copy $ " .. tostring(fr) .. " does not exist") end if isDir(fr) then if exists(to) then error("copy $ " .. tostring(to) .. " already exists") end makeDir(to) for node in ilist1(fr) do copy((combine(fr, node)), (combine(to, node))) end elseif isFile(fr) then return filecopy(fr, to) end end) local isEmpty isEmpty = function(path) if not (exists(path)) then error("isEmpty $ " .. tostring(path) .. " does not exist") end if not (isDir(path)) then return false end return 0 == #(list1(path)) end local delete delete = function(path) if not (exists(path)) then return end if isFile(path or isEmpty(path)) then return os.remove(path) else for node in ilist1(path) do delete(combine(path, node)) end return os.remove(path) end end local remove = delete local open = io.open local listAll listAll = function(path, all) if all == nil then all = { } end for node in ilist1(path) do local fullnode = combine(path, node) table.insert(all, fullnode) if isDir(fullnode) then listAll(fullnode, all) end end return all end local find find = function(wildcard, base, results) if base == nil then base = "" end if results == nil then results = { } end wildcard = wildcard:gsub("%*", "(.-)") local listing = list1(currentDir()) for _index_0 = 1, #listing do local item = listing[_index_0] if (base .. item):match(wildcard) then table.insert(results, base .. item) end if isDir(item) then local subresults = find(wildcard, base .. item, results) for _index_1 = 1, #subresults do local subitem = subresults[_index_1] table.insert(results, subitem) end end end return results end local getDir = _check(function(path) return path:match("^.+/") end) local link link = function(fr, to) return lfs.link(fr, to, false) end local symlink symlink = function(fr, to) return lfs.link(fr, to, true) end local touch touch = function(path, atime, mtime) if atime == nil then atime = os.time() end if mtime == nil then mtime = (atime or os.time()) end return lfs.touch(path, atime, mtime) end local lockDir lockDir = function(path, stale) return lfs.lock_dir(path, stale) end local lock lock = function(file, exclusive, start, length) if exclusive == nil then exclusive = false end return lfs.lock(file, exclusive, start, length) end local unlock unlock = function(file, start, length) return lfs.unlock(file, start, length) end local setMode setMode = function(file, mode) return lfs.setmode(file, mode) end local reduce reduce = function(path) local isroot, isdir = (path:match("^/")), (path:match("/$")) local parts do local _accum_0 = { } local _len_0 = 1 for part in path:gmatch("[^/]+") do _accum_0[_len_0] = part _len_0 = _len_0 + 1 end parts = _accum_0 end if #parts == 1 then return path end local final = { } for _index_0 = 1, #parts do local _continue_0 = false repeat local part = parts[_index_0] if part == "." then _continue_0 = true break elseif part == ".." then if final[#final] then final[#final] = nil end else final[#final + 1] = part end _continue_0 = true until true if not _continue_0 then break end end local f = table.concat(final, "/") if isroot then f = "/" .. f end if isdir then f = f .. "/" end return f end local fromGlob fromGlob = function(glob) local sanitize sanitize = function(pattern) if pattern then return pattern:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%0") end end local saglob = sanitize(glob) do local _with_0 = saglob local mid = _with_0:gsub("%%%*%%%*", ".*") mid = mid:gsub("%%%*", "[^/]*") mid = mid:gsub("%%%?", ".") return tostring(mid) .. "$" end end local matchGlob matchGlob = function(glob, path) return nil ~= path:match(glob) end local glob glob = function(path, all) if all == nil then all = { } end if not (path:match("%*")) then return path end local currentpath = currentDir() local fullpath = reduce(combine(currentpath, path)) local correctpath = "" for i = 1, #fullpath do if (fullpath:sub(i, i)) == (currentpath:sub(i, i)) then correctpath = correctpath .. currentpath:sub(i, i) end end local toglob = fromGlob(fullpath) local _list_0 = listAll(correctpath) for _index_0 = 1, #_list_0 do local node = _list_0[_index_0] if node:match(toglob) then table.insert(all, node) end end return all end local iglob iglob = function(path) local globbed = glob(path) local i = 0 local n = #globbed return function() i = i + 1 if i <= n then return globbed[i] end end end return { currentDir = currentDir, changeDir = changeDir, getDir = getDir, getBlockSize = getBlockSize, getBlocks = getBlocks, getOctalPermissions = getOctalPermissions, getDevice = getDevice, getDeviceType = getDeviceType, getDrive = getDrive, getFreeSpace = getFreeSpace, getUID = getUID, getGID = getGID, getInode = getInode, getLastAccess = getLastAccess, getLastChange = getLastChange, getLastModification = getLastModification, getLinks = getLinks, getMode = getMode, getName = getName, getPermissions = getPermissions, getSize = getSize, exists = exists, list = list, isReadOnly = isReadOnly, ilist = ilist, list1 = list1, ilist1 = ilist1, listAll = listAll, fromGlob = fromGlob, matchGlob = matchGlob, glob = glob, iglob = iglob, reduce = reduce, isDir = isDir, isFile = isFile, isEmpty = isEmpty, isBlockDevice = isBlockDevice, isCharDevice = isCharDevice, isSocket = isSocket, isPipe = isPipe, isLink = isLink, isOther = isOther, makeDir = makeDir, move = move, copy = copy, remove = remove, delete = delete, combine = combine, open = open, find = find, link = link, symlink = symlink, touch = touch, lockDir = lockDir, lock = lock, unlock = unlock, setMode = setMode, getLinkBlockSize = getLinkBlockSize, getLinkBlocks = getLinkBlocks, getLinkOctalPermissions = getLinkOctalPermissions, getLinkDevice = getLinkDevice, getLinkDeviceType = getLinkDeviceType, getLinkUID = getLinkUID, getLinkGID = getLinkGID, getLinkInode = getLinkInode, getLinkLastAccess = getLinkLastAccess, getLinkLastChange = getLinkLastChange, getLinkLastModification = getLinkLastModification, getLinkLinks = getLinkLinks, getLinkMode = getLinkMode, getLinkPermissions = getLinkPermissions, getLinkSize = getLinkSize, safeOpen = safeOpen, _VERSION = _VERSION }
---------------------------------------------- -----Contra III hitbox viewer script SNES----- ---------------------------------------------- --Player Colors: --Gold = Invuln --Blue = Vulnerable --Enemy colors: --Red = Can be touched and hit with projectiles --Green = Can be hit with projectiles but has no collision --Yellow = Can touch you, cannot be hit with player projectiles --White Axis in middle of box = Box is invulnerable local xm local ym function findbit(p) return 2 ^ (p - 1) end function hasbit(x, p) return x % (p + p) >= p end local function check_offscreen(pos,val) if val ~= 0 then if val == 1 then pos = 255 + pos elseif val == 255 then pos = 0 -(255 - pos) end end return pos end local function draw_invuln(x,y,xrad,yrad) gui.drawLine(x + (xrad / 2), y, x + (xrad / 2), y + yrad,0xFFFFFFFF) gui.drawLine(x, y + (yrad / 2), x + xrad, y + (yrad / 2),0xFFFFFFFF) end local function Player() local pbase = 0x200 for i = 0,1,1 do pbase = pbase + (i * 0x40) local x = mainmemory.read_u8(pbase + 6) local y = mainmemory.read_u8(pbase + 0x10) local x2 = mainmemory.read_u8(pbase + 0x28) local y2 = mainmemory.read_u8(pbase + 0x2A) local x_offscreen = mainmemory.read_u8(pbase + 0x7) local y_offscreen = mainmemory.read_u8(pbase + 0x11) local x2_offscreen = mainmemory.read_u8(pbase + 0x29) local y2_offscreen = mainmemory.read_u8(pbase + 0x2B) local active = mainmemory.read_u8(pbase + 0x16) -- Checks if the box went off screen and adjusts x = check_offscreen(x,x_offscreen) x2 = check_offscreen(x2,x2_offscreen) y = check_offscreen(y,y_offscreen) y2 = check_offscreen(y2,y2_offscreen) if active > 0 then if hasbit(active,findbit(2)) == true or mainmemory.read_u16_le(0x1F88 + (i * 0x40)) > 0 then gui.drawBox(x,y,x2,y2,0xFFFDD017,0x35FDD017) else gui.drawBox(x,y,x2,y2,0xFF0000FF,0x350000FF) end end end end local function Enemies() local start = 0x280 local base = 0 local oend = 32 local x local x_offscreen local y local y_offscreen local xrad local yrad local active local touch local projectile local invuln local hp for i = 0,oend,1 do base = start + (i * 0x40) active = mainmemory.read_u8(base + 0x16) hp = mainmemory.read_s16_le(base + 6) if active > 0 then touch = hasbit(active,findbit(4)) projectile = hasbit(active,findbit(5)) invuln = hasbit(active,findbit(6)) x = mainmemory.read_u8(base + 0xa) x_offscreen = mainmemory.read_u8(base + 0xb) y = mainmemory.read_u8(base + 0xe) y_offscreen = mainmemory.read_u8(base + 0xf) xrad = mainmemory.read_s16_le(base+0x28) yrad = mainmemory.read_s16_le(base+0x2A) -- Checks if the box went off screen and adjusts x = check_offscreen(x,x_offscreen) y = check_offscreen(y,y_offscreen) if projectile and touch then gui.drawBox(x,y,x+ xrad,y+yrad,0xFFFF0000,0x35FF0000) elseif projectile then gui.drawBox(x,y,x + xrad,y+yrad,0xFF00FF00,0x3500FF00) elseif touch then gui.drawBox(x,y,x + xrad,y + yrad,0xFFFFFF00,0x35FFFF00) end if hp > 0 and invuln == false then gui.text((x-5) * xm,(y-5) * ym,"HP: " .. hp) end if invuln then draw_invuln(x,y,xrad,yrad) end end end end local function scaler() xm = client.screenwidth() / 256 ym = client.screenheight() / 224 end while true do scaler() local stage = mainmemory.read_u8(0x7E0086) if stage ~= 2 and stage ~= 5 then Player() Enemies() end emu.frameadvance() end