content
stringlengths
5
1.05M
local stringUtils = require("lib/utils/string_utils") describe("stringUtils", function() describe("#findPrevIndex", function() it("should find the prev occurrence of a character", function() local str = "12345" local index = stringUtils.findPrevIndex(str, "2", 5) assert.are.equals(2, index) end) it("should return nil if it doesn't find it", function() local str = "12345" local index = stringUtils.findPrevIndex(str, "a") assert.are.equals(nil, index) end) end) describe("#findNextIndex", function() it("should find the next occurrence of a character", function() local str = "12345" local index = stringUtils.findNextIndex(str, "5") assert.are.equals(5, index) end) it("should return nil if it doesn't find it", function() local str = "12345" local index = stringUtils.findNextIndex(str, "6") assert.are.equals(nil, index) end) end) end)
local PRODUCT = {} local config = require "luci.config" PRODUCT.MENU = { UPPERCASE = 0, HELP = 0, LOGOUT = 1, SAVE = 1, LICENSE = 0, } PRODUCT.SNMP = { TRAP = 0, THRESHOLD = 0, } PRODUCT.STATUS = { RESOURCE = 0, MODULE = 0, } PRODUCT.SYSTEM = { IPSEC = 1, IPTABLE = 1, KEYCERT = 1, PHONEHOME = 0, HALT = 0, } PRODUCT.SYSTEM_MGMT = { INTERFACE = 0, INTERFACE_LIST = 1, CLI_SESSION = 1, VRF_LIST = 1, VRF_PROCESS_LIST = 1, ROUTE_LIST = 1, ADDRESS_LIST = 1, PERMIT_LIST = 0, DNS = 1 } PRODUCT.SNMP_AGENT = { STATE = 0, COMMUNITIES = 0, USERS = 0, } PRODUCT.SYSTEM_SERVICE = { HTTP = 1, HTTPS = 1, } PRODUCT.SYSTEM_MISC = { LOGIN_BANNER = 1 } PRODUCT.NAVIGATION = { ALARM = 0 } local function verifyFeature(name, subname) if config[name] ~= nil and config[name][subname] ~= nil then return config[name][subname] == '1' end return PRODUCT[name][subname] == 1 end PRODUCT.verifyFeature = verifyFeature return PRODUCT
return function(busted) local handler = { successes = {}, successesCount = 0, pendings = {}, pendingsCount = 0, failures = {}, failuresCount = 0, errors = {}, errorsCount = 0, inProgress = {} } handler.cancelOnPending = function(element) return not (element.descriptor == 'pending' and handler.options.suppressPending) end handler.subscribe = function(handler, options) require('busted.languages.en') handler.options = options if options.language ~= 'en' then require('busted.languages.' .. options.language) end busted.subscribe({ 'suite', 'start' }, handler.baseSuiteStart) busted.subscribe({ 'suite', 'end' }, handler.baseSuiteEnd) busted.subscribe({ 'test', 'start' }, handler.baseTestStart, { predicate = handler.cancelOnPending }) busted.subscribe({ 'test', 'end' }, handler.baseTestEnd, { predicate = handler.cancelOnPending }) busted.subscribe({ 'error' }, handler.baseError) end handler.getFullName = function(context) local parent = busted.context.parent(context) local names = { (context.name or context.descriptor) } while parent and (parent.name or parent.descriptor) and parent.descriptor ~= 'file' do current_context = context.parent table.insert(names, 1, parent.name or parent.descriptor) parent = busted.context.parent(parent) end return table.concat(names, ' ') end handler.format = function(element, parent, message, debug, isError) local formatted = { trace = element.trace or debug, name = handler.getFullName(element), message = message, isError = isError } return formatted end handler.getDuration = function() if not handler.endTime or not handler.startTime then return 0 end return handler.endTime - handler.startTime end handler.baseSuiteStart = function(name, parent) handler.startTime = os.clock() return nil, true end handler.baseSuiteEnd = function(name, parent) handler.endTime = os.clock() return nil, true end handler.baseTestStart = function(element, parent) if element.descriptor == 'pending' and handler.options.suppressPending then return nil, false end handler.inProgress[tostring(element)] = {} return nil, true end handler.baseTestEnd = function(element, parent, status, debug) local insertTable local id = tostring(element) if status == 'success' then insertTable = handler.successes handler.successesCount = handler.successesCount + 1 elseif status == 'pending' then insertTable = handler.pendings handler.pendingsCount = handler.pendingsCount + 1 elseif status == 'failure' then insertTable = handler.failures handler.failuresCount = handler.failuresCount + 1 end insertTable[id] = handler.format(element, parent, nil, debug) if handler.inProgress[id] then for k, v in pairs(handler.inProgress[id]) do insertTable[id][k] = v end handler.inProgress[id] = nil end return nil, true end handler.baseError = function(element, parent, message, debug) if element.descriptor == 'it' then handler.inProgress[tostring(element)].message = message else handler.errorsCount = handler.errorsCount + 1 table.insert(handler.errors, handler.format(element, parent, message, debug, true)) end return nil, true end return handler end
----------------------------------------- -- ID: 5440 -- Dusty Wing -- Increases TP of the user by 300 ----------------------------------------- function onItemCheck(target) return 0 end function onItemUse(target) target:addTP(3000) end
Chill = Enemy:extend("Chill") Chill:implement(Locator) Chill.green = {51/255, 219/255, 53/255, .5} Chill.red = {228/255, 59/255, 68/255, .5} function Chill:new(...) Chill.super.new(self, ...) self:setImage("enemies/lekker_chill", 2) self.anim:add("mad", 2) self.anim:add("chill", 1) self.solid = 0 self.speed = 100 self.floating = true self.jumpToKill = true self.timer = 0 self.chill = true self.radiation = 0 self.radiationAlpha = 1 self.radiationChill = true self:radiate() self.autoFlip.x = false end function Chill:update(dt) -- print(self.madTimer.timer) -- if self.madTimer(dt) then -- self.chill = true -- self.anim:set("chill") -- end self:stopMoving() if not self.dead then self:findTarget(Player, 400) self:findTargets(Player) end self.timer = self.timer + dt -- self.offset.y = math.sin(self.timer * PI * .4) * 10 Chill.super.update(self, dt) end function Chill:draw() local r, g, b = unpack(self.radiationChill and Chill.green or Chill.red) love.graphics.setColor(r, g, b, self.radiationAlpha) love.graphics.circle("fill", self:centerX(), self:centerY(), self.radiation, 50) love.graphics.setColor(r, g, b, self.radiationAlpha * 10) love.graphics.circle("line", self:centerX(), self:centerY(), self.radiation, 50) Chill.super.draw(self) end function Chill:radiate() self.radiation = 0 self.radiationAlpha = 1 if self.chill then self.radiationChill = true else if not self.radiationChill then self.radiationChill = true self:goChill() else self.radiationChill = false end end self.flux:to(self, self.chill and 1 or .5, {radiation = 100, radiationAlpha = 0}) :oncomplete(self.wrap:radiate()) :delay(self.chill and 1 or .2) end function Chill:onFindingTarget(target, distance) if self.radiation == 0 then self:moveToEntity(target) end end function Chill:onFindingTargets(targets, distance) for i,v in ipairs(targets) do if self.radiation > 0 and self.radiationAlpha > 0.1 then if v.distance < self.radiation then if self.radiationChill then self:goMad() v.target:slowDown(1) else v.target:hit() v.target:stopSlowDown() end end end end end function Chill:goChill() self.chill = true self.anim:set("chill") end function Chill:goMad() self.chill = false self.anim:set("mad") end
dofile("cc_Assist.lua"); askText = "Automatically runs many charcoal hearths or ovens simultaneously.\n\nMake sure this window is in the TOP-RIGHT corner of the screen.\n\nTap Shift (while hovering ATITD window) to continue."; BEGIN = 1; WOOD = 2; WATER = 3; CLOSE = 4; OPEN = 5; FULL = 6; woodAddedTotal = 0; waterAddedTotal = 0; -- Standard mode, teh default, where each oven runs independently -- Synchronous mode, where one oven is watched, and all receive the same commands synchronousMode = 0; function ccMenu() local passCount = 1; local done = false; while not done do lsPrint(5, 5, 5, 0.7, 0.7, 0xffffffff, "How many passes?"); done, passCount = lsEditBox("pass_count", 5, 35, z, 100, 30, 0.7, 0.7, 0x000000ff, passCount); synchronousMode = CheckBox(5, 65, 10, 0xd0d0d0ff, " Synchronous Mode", synchronousMode, 0.7, 0.7); lsPrint(5, 80, 10, 0.6, 0.6, 0xd0d0d0ff, " Runs all ovens identically"); if lsButtonText(5, 110, z, 50, 0xffffffff, "OK") then done = true; end lsDoFrame(); lsSleep(25); checkBreak(); end askForFocus(); startTime = lsGetTimer(); for i = 1, passCount do woodAdded = 0; waterAdded = 0; woodx1Click = 0; drawWater(1); -- Refill Jugs. The parameter of 1 means don't do the animation countdown. Since we won't be running somewhere, not needed lsSleep(100); Do_Take_All_Click(); -- Make sure ovens are empty. If a previous run didn't complete and has wood leftover, will cause a popup 'Your oven already has wood' and throw macro off runCommand(buttons[1]); lsSleep(1500); ccRun(i, passCount); end Do_Take_All_Click(); -- All done, empty ovens lsPlaySound("Complete.wav"); lsMessageBox("Elapsed Time:", getElapsedTime(startTime), 1); end function findOvens() local result = findAllImages("ThisIs.png"); for i=1,#result do local corner = findImageInWindow("charcoal/mm-corner.png", result[i][0], result[i][1], 100); if not corner then error("Failed to find corner of cc window."); end result[i][0] = corner[0]; result[i][1] = corner[1]; end return result; end function setupVents(ovens) local result = {}; for i = 1, #ovens do result[i] = 0; end return result; end function findButton(pos, index) return findImageInWindow(buttons[index].image, pos[0], pos[1]); end function clickButton(pos, index, counter) local count = nil; if synchronousMode then count = runCommand(buttons[index]); else local buttonPos = findButton(pos, index); if buttonPos then safeClick(buttonPos[0] + buttons[index].offset[0], buttonPos[1] + buttons[index].offset[1]); count = 1; end end if counter ~= nil and count ~= nil then if index == 3 then -- Water waterAdded = waterAdded + count; waterAddedTotal = waterAddedTotal + count; end if index == 2 then -- Wood woodAdded = woodAdded + count; woodAddedTotal = woodAddedTotal + count; end end end function ccRun(pass, passCount) local ovens = findOvens(); local vents = setupVents(ovens); local done = false; while not done do sleepWithStatus(500, "Waiting on next tick ...\n\n" .. "[" .. pass .. "/" .. passCount .. "] Passes\n\n" .. "Totals: [This Pass/All Passes]\n\n" .. "[".. woodAdded*3 .. "/" .. woodAddedTotal * 3 .. "] Wood Used - Actual\n" .. "[" .. woodAdded .. "/" .. woodAddedTotal .. "] 'Add Wood' Button Clicked (x1)\n\n".. "[" .. waterAdded .. "/" .. waterAddedTotal .."] Water Used\n" .. " (Excluding cooldown water)\n\n\n" .. "Elapsed Time: " .. getElapsedTime(startTime), nil, 0.7); done = true; srReadScreen(); local count = #ovens; if synchronousMode then count = 1; end for i = 1, count do if not findButton(ovens[i], BEGIN) then vents[i] = processOven(ovens[i], vents[i]); done = false; end end end end -- 0% = 56, 100% = 249, each % = 1.94 minHeat = makePoint(199, 15); --80% minHeatProgress = makePoint(152, 15); --60% minOxy = makePoint(80, 33); --32% maxOxy = makePoint(116, 33); --47% maxOxyLowHeat = makePoint(160, 33); --64% minWood = makePoint(108, 50); --43% minWater = makePoint(61, 70); --24% minWaterGreen = makePoint(96, 70); --39% maxDangerGreen = makePoint(205, 90); --82% maxDanger = makePoint(219, 90); --88% uberDanger = makePoint(228, 90); --92% progressGreen = makePoint(62, 110); --25% greenColor = 0x01F901; barColor = 0x0101F9; function processOven(oven, vent) local newVent = vent; if pixelMatch(oven, progressGreen, greenColor, 4) then if not pixelMatch(oven, minWaterGreen, barColor, 8) then clickButton(oven, WATER); clickButton(oven, WATER); end if pixelMatch(oven, maxDangerGreen, barColor, 4) then clickButton(oven, WATER); elseif vent ~= 3 then newVent = 3; clickButton(oven, FULL); end else if not pixelMatch(oven, minHeat, barColor, 8) then if not pixelMatch(oven, minWood, barColor, 8) then clickButton(oven, WOOD, 1); end end if not pixelMatch(oven, minOxy, barColor , 8) then if vent ~= 3 then newVent = 3; clickButton(oven, FULL); end else local point = maxOxy; if not pixelMatch(oven, minHeatProgress, barColor, 8) then point = maxOxyLowHeat; end if pixelMatch(oven, point, barColor, 8) then if vent ~= 1 then newVent = 1; clickButton(oven, CLOSE); end else if vent ~= 2 then newVent = 2; clickButton(oven, OPEN); end end end if pixelMatch(oven, maxDanger, barColor, 8) then if not pixelMatch(oven, minWater, barColor, 8) then clickButton(oven, WATER, 1); if pixelMatch(oven, uberDanger, barColor, 8) then clickButton(oven, WATER, 1); end end end end return newVent; end function Do_Take_All_Click() statusScreen("Checking / Emptying Ovens ...",nil, 0.7); -- refresh windows clickAll("ThisIs.png", 1); lsSleep(100); clickAll("take.png", 1); lsSleep(100); clickAll("everything.png", 1); lsSleep(100); -- refresh windows, one last time so we know for sure the machine is empty (Take menu disappears) clickAll("ThisIs.png", 1); lsSleep(100); end function clickAll(image_name) -- Find buttons and click them! srReadScreen(); xyWindowSize = srGetWindowSize(); local buttons = findAllImages(image_name); if #buttons == 0 then -- statusScreen("Could not find specified buttons..."); -- lsSleep(1500); else -- statusScreen("Clicking " .. #buttons .. "button(s)..."); if up then for i=#buttons, 1, -1 do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3); lsSleep(per_click_delay); end else for i=1, #buttons do srClickMouseNoMove(buttons[i][0]+5, buttons[i][1]+3); lsSleep(per_click_delay); end end -- statusScreen("Done clicking (" .. #buttons .. " clicks)."); -- lsSleep(100); end end
--[[ - Synapse, unlike ScriptWare, has not implemented a feature into syn.protect_gui where it protects from this type of attack; thus making it vulnerable. You can easily patch this though. How does this work? GetFocusedTextBox allows you to get the current focused textbox, so if you are modifying the Name attribute of a Remote, for example. This can detect that and see whether that is legitimate or not, and therefore detect Synapse-made GUIs --]] -- // Services local UserInputService = game:GetService("UserInputService") local RunService = game:GetService("RunService") -- // RunService:BindToRenderStep("DetectGUI", 0, function() -- // Vars local FocusedTextBox = UserInputService:GetFocusedTextBox() -- // Make sure there actually is one if not (FocusedTextBox) then return end -- // Get the descendant - e.g. CoreGui.DarkDex.Whatever -> {CoreGui, DarkDex, Whatever} local Path = FocusedTextBox:GetFullName():split(".") local Descendant = Path[1] -- // Check if descendant of CoreGui and if not a ROBLOX GUI if (Descendant == "CoreGui" and Path[2] ~= "RobloxGui") then print("Detected:", FocusedTextBox:GetFullName()) end end)
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Plug" ENT.Author = "Divran" ENT.Purpose = "Links with a socket" ENT.Instructions = "Move a plug close to a socket to link them, and data will be transferred through the link." ENT.WireDebugName = "Plug" function ENT:GetSocketClass() return "gmod_wire_socket" end function ENT:GetClosestSocket() local sockets = ents.FindInSphere( self:GetPos(), 100 ) local ClosestDist local Closest for k,v in pairs( sockets ) do if (v:GetClass() == self:GetSocketClass() and not v:GetNWBool( "Linked", false )) then local pos, _ = v:GetLinkPos() local Dist = self:GetPos():Distance( pos ) if (ClosestDist == nil or ClosestDist > Dist) then ClosestDist = Dist Closest = v end end end return Closest end if CLIENT then function ENT:DrawEntityOutline() if (GetConVar("wire_plug_drawoutline"):GetBool()) then BaseClass.DrawEntityOutline( self ) end end return -- No more client end ------------------------------------------------------------ -- Helper functions & variables ------------------------------------------------------------ local LETTERS = { "A", "B", "C", "D", "E", "F", "G", "H" } local LETTERS_INV = {} for k,v in pairs( LETTERS ) do LETTERS_INV[v] = k end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetNWBool( "Linked", false ) self.Memory = {} end function ENT:Setup( ArrayInput ) local old = self.ArrayInput self.ArrayInput = ArrayInput or false if not (self.Inputs and self.Outputs and self.ArrayInput == old) then if (self.ArrayInput) then self.Inputs = WireLib.CreateInputs( self, { "In [ARRAY]" } ) self.Outputs = WireLib.CreateOutputs( self, { "Out [ARRAY]" } ) else self.Inputs = WireLib.CreateInputs( self, LETTERS ) self.Outputs = WireLib.CreateOutputs( self, LETTERS ) end end self:ShowOutput() end function ENT:TriggerInput( name, value ) if (self.Socket and self.Socket:IsValid()) then self.Socket:SetValue( name, value ) end self:ShowOutput() end function ENT:SetValue( name, value ) if not (self.Socket and self.Socket:IsValid()) then return end if (name == "In") then if (self.ArrayInput) then -- Both have array WireLib.TriggerOutput( self, "Out", table.Copy( value ) ) else -- Target has array, this does not for i=1,#LETTERS do local val = (value or {})[i] if isnumber(val) then WireLib.TriggerOutput( self, LETTERS[i], val ) end end end else if (self.ArrayInput) then -- Target does not have array, this does if (value ~= nil) then local data = table.Copy( self.Outputs.Out.Value ) data[LETTERS_INV[name]] = value WireLib.TriggerOutput( self, "Out", data ) end else -- Niether have array if (value ~= nil) then WireLib.TriggerOutput( self, name, value ) end end end self:ShowOutput() end ------------------------------------------------------------ -- WriteCell -- Hi-speed support ------------------------------------------------------------ function ENT:WriteCell( Address, Value, WriteToMe ) Address = math.floor(Address) if (WriteToMe) then self.Memory[Address or 1] = Value or 0 return true else if (self.Socket and self.Socket:IsValid()) then self.Socket:WriteCell( Address, Value, true ) return true else return false end end end ------------------------------------------------------------ -- ReadCell -- Hi-speed support ------------------------------------------------------------ function ENT:ReadCell( Address ) Address = math.floor(Address) return self.Memory[Address or 1] or 0 end function ENT:Think() BaseClass.Think( self ) self:SetNWBool( "PlayerHolding", self:IsPlayerHolding() ) end function ENT:ResetValues() if (self.ArrayInput) then WireLib.TriggerOutput( self, "Out", {} ) else for i=1,#LETTERS do WireLib.TriggerOutput( self, LETTERS[i], 0 ) end end self.Memory = {} self:ShowOutput() end ------------------------------------------------------------ -- ResendValues -- Resends the values when plugging in ------------------------------------------------------------ function ENT:ResendValues() if (not self.Socket) then return end if (self.ArrayInput) then self.Socket:SetValue( "In", self.Inputs.In.Value ) else for i=1,#LETTERS do self.Socket:SetValue( LETTERS[i], self.Inputs[LETTERS[i]].Value ) end end end function ENT:ShowOutput() local OutText = "Plug [" .. self:EntIndex() .. "]\n" if (self.ArrayInput) then OutText = OutText .. "Array input/outputs." else OutText = OutText .. "Number input/outputs." end if (self.Socket and self.Socket:IsValid()) then OutText = OutText .. "\nLinked to socket [" .. self.Socket:EntIndex() .. "]" end self:SetOverlayText(OutText) end duplicator.RegisterEntityClass( "gmod_wire_plug", WireLib.MakeWireEnt, "Data", "ArrayInput" ) function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID) if (info.Plug ~= nil) then ent:Setup( info.Plug.ArrayInput ) end BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID) end
require'rooter'.setup { echo = false, patterns = { -- the patterns to find '.git/', -- same as patterns passed to nvim_lsp.util.root_pattern(patterns...) '.git', -- same as patterns passed to nvim_lsp.util.root_pattern(patterns...) 'package.json', 'init.lua', '.env', }, non_project_files = "current" }
local stringx = require('pl.stringx') local cmd = torch.CmdLine() cmd:option("-beam_size",7,"beam_size") cmd:option("-batch_size",128,"decoding batch_size") cmd:option("-params_file","","") cmd:option("-model_file","","") cmd:option("-setting","BS","setting for decoding, sampling, BS, DiverseBS,StochasticGreedy") cmd:option("-DiverseRate",0,"") cmd:option("-InputFile","../data/t_given_s_test.txt","") cmd:option("-OutputFile","output.txt","") cmd:option("-max_length",20,"") cmd:option("-min_length",0,"") cmd:option("-NBest",false,"output N-best list or just a simple output") cmd:option("-gpu_index",1,"the index of GPU to use") cmd:option("-allowUNK",false,"whether allowing to generate UNK") cmd:option("-MMI",false,"") cmd:option("-onlyPred",true,"") cmd:option("-MMI_params_file","../atten/save_s_given_t/params","") cmd:option("-MMI_model_file","","") cmd:option("-max_decoded_num",0,"") cmd:option("-output_source_target_side_by_side",true,"") cmd:option("-StochasticGreedyNum",1,"") cmd:option("-target_length",0,"force the length of the generated target, 0 means there is no such constraints") cmd:option("-dictPath","../data/movie_25000","") cmd:option("-PrintOutIllustrationSample",false,"") local params= cmd:parse(arg) print(params) return params;
----------------------------------------------------------------------------------------------- -- Client Lua Script for ForgeUI -- -- name: welcome_module.lua -- author: Winty Badass@Jabbit -- about: ForgeUI welcome module ----------------------------------------------------------------------------------------------- local F = _G["ForgeLibs"]["ForgeUI"] -- ForgeUI API local G = _G["ForgeLibs"]["ForgeGUI"] -- ForgeGUI ----------------------------------------------------------------------------------------------- -- ForgeUI Module Definition ----------------------------------------------------------------------------------------------- local CreditsModule = { _NAME = "welcome_module", _API_VERSION = 3, _VERSION = "1.0", } ----------------------------------------------------------------------------------------------- -- Local variables ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -- Module functions ----------------------------------------------------------------------------------------------- function CreditsModule:ForgeAPI_Init() F:API_AddMenuItem(self, "Home", "Home", { strPriority = "shigh", bDefault = true }) self.tTmpSettings = { crColor = "FFFF9900" } end function CreditsModule:ForgeAPI_PopulateOptions() local wndHome = self.tOptionHolders["Home"] G:API_AddText(self, wndHome, string.format("<T TextColor=\"%s\" Font=\"%s\">%s</T>", "FFFFFFFF", "Nameplates", "Welcome to ") .. string.format("<T TextColor=\"%s\" Font=\"%s\">%s</T>", "FFFF0000", "Nameplates", "ForgeUI"), { tMove = { 235, 30 } }) G:API_AddText(self, wndHome, "- To move and resize elements of ForgeUI, press 'Unlock elements'.", { tMove = { 0, 90 } }) G:API_AddText(self, wndHome, "- To change mounts, recalls, potions, ... use right-click.", { tMove = { 0, 120 } }) G:API_AddText(self, wndHome, "- To cycle between mounts, use scroll-wheel.", { tMove = { 0, 150 } }) G:API_AddText(self, wndHome, "- /reloadui fixes most of the problems :)", { tMove = { 0, 180 } }) G:API_AddText(self, wndHome, "- Click on these color-boxes to bring up color picker: ", { tMove = { 0, 210 } }) G:API_AddColorBox(self, wndHome, "", self.tTmpSettings, "crColor", { tMove = { 310, 205 } }) G:API_AddText(self, wndHome, "Because ForgeUI is still in beta, please report any bugs here:", { tMove = { 0, 365 } }) self.wndEditBox = G:API_EditBox(self, wndHome, "", nil, nil, { tMove = { 0, 390 }, tWidths = { 300, 0 }, fnCallback = (function() self.wndEditBox:SetText('https://github.com/ForgeUI/ForgeUI/issues') end) }):FindChild("EditBox") self.wndEditBox:SetText('https://github.com/ForgeUI/ForgeUI/issues') end CreditsModule = F:API_NewModule(CreditsModule)
-- This file is subject to copyright - contact [email protected] for more information. -- INSTALL: CINEMA local PANEL = {} local CloseTexture = Material("theater/close.png") --local TitleBackground = Material("theater/bannernew2.png") function PANEL:Init() self:SetFocusTopLevel(true) self.titleHeight = 36 self.title = vgui.Create("DLabel", self) self.title:SetFont("ScoreboardTitleSmall") self.title:SetColor(Color(255, 255, 255)) self.title:SetText("Window") self.closeButton = vgui.Create("DButton", self) self.closeButton:SetZPos(5) self.closeButton:NoClipping(true) self.closeButton:SetText("") self.closeButton.DoClick = function(btn) self:Remove() end self.closeButton.Paint = function(btn, w, h) DisableClipping(true) surface.SetDrawColor(48, 55, 71) surface.DrawRect(2, 2, w - 4, h - 4) surface.SetDrawColor(26, 30, 38) surface.SetMaterial(CloseTexture) surface.DrawTexturedRect(0, 0, w, h) DisableClipping(false) end end function PANEL:SetTitle(title) self.title:SetText(title) end function PANEL:PerformLayout() self.title:SizeToContents() self.title:SetTall(self.titleHeight) self.title:SetPos(1, 1) self.title:CenterHorizontal() self.closeButton:SetSize(32, 32) self.closeButton:SetPos(self:GetWide() - 34, 2) end function PANEL:Paint(w, h) surface.SetDrawColor(26, 30, 38, 255) surface.DrawRect(0, 0, w, h) surface.SetDrawColor(141, 38, 33, 255) surface.DrawRect(0, 0, w, self.title:GetTall()) surface.SetDrawColor(141, 38, 33, 255) --surface.SetMaterial(TitleBackground) surface.DrawRect(0, -1, 512, self.title:GetTall() + 1) if w > 512 then surface.DrawRect(460, -1, 512, self.title:GetTall() + 1) end end vgui.Register("CinemaRentalsWindow", PANEL, "Panel")
-- Nibble Shell -- Audio local SQUARE = 0 local TRI = 1 local SAW = 2 local SIN = 3 local PSIN = 4 function makeaudio(w, v, o, n) return string.char(w)..string.char(v)..string.char(o)..string.char(n) end function audio_tick(c) if audio_enable then kernel.write(154448+c*4, makeaudio(SQUARE, 0, 0, 0)) end end
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = { PlaceObj('AddTrait', { 'Trait', "Guru", }), PlaceObj('AddTrait', { 'Trait', "Religious", }), PlaceObj('AddTrait', { 'Trait', "Saint", }), }, Comment = "using ForEachExecuteEffects >> Colonist, HasTrait >> Religious (negative), AddTrait >> Religious", Effects = { PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", 'Negate', true, }), }, 'RandomPercent', "<new_religious>", 'Effects', { PlaceObj('AddTrait', { 'Trait', "Religious", }), }, }), }, Image = "UI/Messages/Events/05_mysterious_stranger.tga", Prerequisites = {}, ScriptDone = true, Text = T(561444202705, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] 'Mike, the person who has been found as a child roaming the Mars surface without any protective equipment, has grown into a young man. He has learned several languages, but he still claims he lacks the words needed to explain how he survived and what is his connection with some "old ones" he mentions every once and again. Some say he has been raised by aliens, but he disagrees. All the questions, he says, can be answered only in the tongue of the Old Ones, as the language shapes the thought and the thought can change space and time.\n\nEventually, Mike decided that the humankind is hopelessly confused and unhappy, and he tried to establish a new religion which would change the very human nature by teaching the language of the Old Ones. His cult which promotes social libertarianism and some non-mainstream family structures, quickly gathered followers in our colony.\n\nNeedless to say, these ideas put pressure on our community.\n<effect>Some of our Colonists became Religious.'), TextReadyForValidation = true, TextsDone = true, Title = T(900575952837, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Title]] "Foreigner in a Foreign Land"), Trigger = "ColonistBecameYouth", group = "Expeditions", id = "ForeignerInAForeignLand_FollowUp2", PlaceObj('StoryBitParamPercent', { 'Name', "new_religious", 'Value', 25, }), PlaceObj('StoryBitParamNumber', { 'Name', "new_saints", 'Value', 2, }), PlaceObj('StoryBitParamNumber', { 'Name', "morale_loss", 'Value', -40, }), PlaceObj('StoryBitParamPercent', { 'Name', "colonists_pissed_1", 'Value', 25, }), PlaceObj('StoryBitParamPercent', { 'Name', "colonists_pissed_2", 'Value', 50, }), PlaceObj('StoryBitParamSols', { 'Name', "pissed_time", 'Value', 14400000, }), PlaceObj('StoryBitParamNumber', { 'Name', "morale_gain", 'Value', 10, }), PlaceObj('StoryBitParamPercent', { 'Name', "security_happy", 'Value', 25, }), PlaceObj('StoryBitParamSols', { 'Name', "happy_time", 'Value', 14400000, }), PlaceObj('StoryBitReply', { 'Text', T(143767476908, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "Mike means only good. Let him do whatever he deems necessary."), 'OutcomeText', "custom", 'CustomOutcomeText', T(170229833355, --[[StoryBit ForeignerInAForeignLand_FollowUp2 CustomOutcomeText]] "many Religious Colonists lose Morale, a few become Saints"), 'Comment', "using ForEachExecuteEffects >> Colonist, HasTrait >> Religious, ModifyObject >> base_morale, Parameters", }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Weight', 50, 'Text', T(764262105297, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "With your permission, Mike establishes the Church of Two Worlds as an official religion. This introduces immense social tension within our colony. Some insist that he and his people should be burned as witches, and others fiercely support him. However, the Old Ones' language really provides some unexplored psycho-kinetic abilities and even though modern science can't explain them, Mike and his people use their powers to help our community.\n\n<effect><colonists_pissed_2>% of Religious Colonists lose <morale_loss> Morale for <sols(pissed_time)> Sols.\n<new_saints> more Colonists have become Saints."), 'Image', "UI/Messages/Events/10_protest.tga", 'Effects', { PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", }), }, 'RandomPercent', "<colonists_pissed_2>", 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', "<morale_loss>", 'Sols', "<pissed_time>", }), }, }), PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", }), }, 'RandomCount', "<new_saints>", 'Effects', { PlaceObj('AddTrait', { 'Trait', "Saint", }), }, }), }, }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Weight', 50, 'Text', T(675735846271, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "With your permission, Mike establishes the Church of Two Worlds as an official religion. The Old Ones' language really provides some unexplored psycho-kinetic abilities and even though modern science can't explain them, Mike and his people use their powers to help our community.\n\nHowever, this introduces immense social tension within our colony. Some insist that he and his people should be burned as witches, and others fiercely support him. One day, a mob of angry and confused people attacks him at his house and Mike dies as a martyr. Strangely, the shock of what's done makes everybody sober down and the peace is finally restored.\n\n<effect>Mike is dead.\n<colonists_pissed_1>% of Religious Colonists lose <morale_loss> Morale for <sols(pissed_time)> Sols.\n<new_saints> more Colonists have become Saints."), 'Image', "UI/Messages/Events/10_protest.tga", 'Effects', { PlaceObj('KillColonist', nil), PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", }), }, 'RandomPercent', "<colonists_pissed_2>", 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', "<morale_loss>", 'Sols', "<pissed_time>", }), }, }), PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", }), }, 'RandomCount', "<new_saints>", 'Effects', { PlaceObj('AddTrait', { 'Trait', "Saint", }), }, }), }, }), PlaceObj('StoryBitReply', { 'Text', T(744628162387, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "Forbid his new religion, but secretly support him."), 'OutcomeText', "custom", 'CustomOutcomeText', T(466568906613, --[[StoryBit ForeignerInAForeignLand_FollowUp2 CustomOutcomeText]] "some Religious Colonists lose Morale, a few become Saints"), 'Prerequisite', PlaceObj('IsCommander2', { 'CommanderProfile1', "politician", 'CommanderProfile2', "author", }), 'Comment', "", }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Text', T(144154828670, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "Mike establishes the Church of Two Worlds as a secret cult and this creates some social tension between his followers and the other members of society. However, the Old Ones' language really provides some unexplored psycho-kinetic abilities and even though modern science can't explain them, Mike and his people use their powers to help our community.\n\n<effect><colonists_pissed_1>% of Religious Colonists lose <morale_loss> Morale for <sols(pissed_time)> Sols.\n<new_saints> more Colonists have become Saints."), 'Image', "UI/Messages/Events/10_protest.tga", 'Effects', { PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", }), }, 'RandomPercent', "<colonists_pissed_1>", 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', "<morale_loss>", 'Sols', "<pissed_time>", }), }, }), PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "Religious", }), }, 'RandomCount', "<new_saints>", 'Effects', { PlaceObj('AddTrait', { 'Trait', "Saint", }), }, }), }, }), PlaceObj('StoryBitReply', { 'Text', T(193275236198, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "The road to hell is paved with good intentions. Banish Mike to keep the peace."), 'OutcomeText', "custom", 'CustomOutcomeText', T(880040340421, --[[StoryBit ForeignerInAForeignLand_FollowUp2 CustomOutcomeText]] "Mike is sent to Earth, some Security Officers gain Morale"), 'Comment', "", }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Text', T(465260621163, --[[StoryBit ForeignerInAForeignLand_FollowUp2 Text]] "Mike creates a turmoil back on Earth and saves us the trouble. He introduces whole new concepts and thinking patterns, eventually provoking a social revolution.\n\nHe never finds the time to visit again his home planet Mars.\n\n<effect>Mike leaves Mars.\n<security_happy>% of Security Officers gain <morale_gain> Morale for <sols(happy_time)> Sols."), 'Effects', { PlaceObj('EraseColonist', nil), PlaceObj('ForEachExecuteEffects', { 'Label', "Colonist", 'Filters', { PlaceObj('HasTrait', { 'Trait', "security", }), }, 'RandomPercent', "<security_happy>", 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', "<morale_gain>", 'Sols', "<happy_time>", }), }, }), }, }), })
local state = { variables = {} } -- | 667 | -- Телепорты к врагам -- Телепортирует объект к врагу по заданному типу на заданное расстояние -- TYPES: -- 1 - Ближайший враг -- 2 - Дальний враг -- 3 - Средний враг -- 4 - Случайный враг --------------------------------------------------------------------- function state:Processing(object,s) if s.type then local distances_list = {} for i = 1, #battle.chars do local char = battle.chars[i] if entities.isEnemy(object,char) then local dist = math.sqrt((object.x - char.x)^2 + (object.y - char.y)^2 + (object.z - char.z)^2) local temp = { character = char, distance = dist } table.insert(distances_list,temp) end end end end return state
--- === hs.wifi === --- --- Inspect WiFi networks local USERDATA_TAG = "hs.wifi" local module = require("hs.libwifi") module.watcher = require("hs.libwifiwatcher") local watcherMT = hs.getObjectMetatable(USERDATA_TAG..".watcher") -- private variables and methods ----------------------------------------- -- Public interface ------------------------------------------------------ local originalEventTypes = module.watcher.eventTypes module.watcher.eventTypes = ls.makeConstantsTable(originalEventTypes) local originalWatchingFor = watcherMT.watchingFor watcherMT.watchingFor = function(self, ...) local args = table.pack(...) -- print(args[1]) if args.n == 0 or (args.n == 1 and type(args[1]) == "table") then return originalWatchingFor(self, ...) elseif args.n == 1 and args[1] == "all" then return originalWatchingFor(self, originalEventTypes) else args.n = nil return originalWatchingFor(self, args) end end -- Return Module Object -------------------------------------------------- return module
local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(25, 1, 25) -- This is the size to which you want to change your brick brick.Position = Vector3.new(5, 0.1, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(25, 9, 1) -- This is the size to which you want to change your brick brick.Position = Vector3.new(5, 2, 13) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(25, 9, 1) -- This is the size to which you want to change your brick brick.Position = Vector3.new(5, 2, 37) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 9, 9) -- This is the size to which you want to change your brick brick.Position = Vector3.new(17, 2, 18) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 9, 9) -- This is the size to which you want to change your brick brick.Position = Vector3.new(17, 2, 32) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Reddish brown") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 9, 5) -- This is the size to which you want to change your brick brick.Position = Vector3.new(17, 2, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = false -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 9, 23) -- This is the size to which you want to change your brick brick.Position = Vector3.new(-7, 2, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(25, 1, 25) -- This is the size to which you want to change your brick brick.Position = Vector3.new(5, 2, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Reddish brown") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(2, 2, 2) -- This is the size to which you want to change your brick brick.Position = Vector3.new(1, 2, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Reddish brown") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(5, 1, 8) -- This is the size to which you want to change your brick brick.Position = Vector3.new(1, 2, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Bright blue") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Shape = 0 brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 2, 1) -- This is the size to which you want to change your brick brick.Position = Vector3.new(1, 5, 23) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Bright blue") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Shape = 0 brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 2, 1) -- This is the size to which you want to change your brick brick.Position = Vector3.new(2, 5, 23) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Bright blue") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Shape = 0 brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(1, 2, 1) -- This is the size to which you want to change your brick brick.Position = Vector3.new(1.5, 5, 23) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("Black") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(9, 1, 7) -- This is the size to which you want to change your brick brick.Position = Vector3.new(-2, 1, 17) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Part") brick.BrickColor=BrickColor.new("White") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(2, 1, 7) -- This is the size to which you want to change your brick brick.Position = Vector3.new(-5.5, 1, 17) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = true -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Seat") brick.BrickColor=BrickColor.new("Reddish brown") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(2, 1, 2) -- This is the size to which you want to change your brick brick.Position = Vector3.new(5.5, 1, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = false -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1 local brick = Instance.new("Seat") brick.BrickColor=BrickColor.new("Reddish brown") brick.Parent = game.Workspace -- This is the "parent container" of your brick. brick.Name = "NewBrick" -- This name has to correspond with the name of your brick on the map brick.Size = Vector3.new(2, 1, 2) -- This is the size to which you want to change your brick brick.Position = Vector3.new(-3.5, 1, 25) -- This is where the bricks Position will be at brick.Anchored = true -- makes it stay in one place even in air. brick.CanCollide = false -- makes it so you can hit the object. brick.Locked = true -- makes it stay so you cant select it with a tool. brick.Transparency = 0 -- makes it visible to invisible 0 - 1 brick.Reflectance = 0 -- makes it non-shiny to shiny 0 - 1
-- ---------------------------------------------- -- Copyright (c) 2018, CounterFlow AI, Inc. All Rights Reserved. -- author: Andrew Fast <[email protected]> -- -- Use of this source code is governed by a BSD-style -- license that can be found in the LICENSE.txt file. -- ---------------------------------------------- -- Combine indicators from multiple sources into an overall score require 'math' require 'analyzer/utils' local analyzer_name = 'Overall Priority' function setup() conn = hiredis.connect() if conn:command('PING') ~= hiredis.status.PONG then dragonfly.log_event(analyzer_name..': Could not connect to redis') dragonfly.log_event(analyzer_name..': exiting') os.exit() end starttime = 0 --mle.epoch() print (">>>>>>>> Overall Priority") end function get_bytes_rank(eve) -- Analyzer 5: Bytes Rank Percentile -- Threshold: 0.95 bytes_rank = {} threshold = 0.95 -- 95% percentile bytes_rank['threshold'] = threshold dest_percentile = 0 local cmd = 'ZRANK total_bytes_rank:dest '..eve.dest_ip local reply = conn:command_line(cmd) if type(reply) == 'table' and reply.name ~= 'OK' then dragonfly.log_event(analyzer_name..': '..cmd..' : '..reply.name) dragonfly.analyze_event(default_analyzer, msg) return elseif not tonumber(reply) then dragonfly.log_event(analyzer_name..': Could not convert to number: '..reply) dragonfly.analyze_event(default_analyzer, msg) return end local dest_rank = reply local cmd = 'ZCARD total_bytes_rank:dest' local reply = conn:command_line(cmd) if type(reply) == 'table' and reply.name ~= 'OK' then dragonfly.log_event(analyzer_name..': '..cmd..' : '..reply.name) dragonfly.analyze_event(default_analyzer, msg) return elseif not tonumber(reply) then dragonfly.log_event(analyzer_name..': Could not convert to number: '..reply) dragonfly.analyze_event(default_analyzer, msg) return end local dest_size = reply src_percentile = 0 local cmd = 'ZRANK total_bytes_rank:src '..eve.src_ip local reply = conn:command_line(cmd) if type(reply) == 'table' and reply.name ~= 'OK' then dragonfly.log_event(analyzer_name..': '..cmd..' : '..reply.name) dragonfly.analyze_event(default_analyzer, msg) return elseif not tonumber(reply) then dragonfly.log_event(analyzer_name..': Could not convert to number: '..reply) dragonfly.analyze_event(default_analyzer, msg) return end local src_rank = reply local cmd = 'ZCARD total_bytes_rank:src' local reply = conn:command_line(cmd) if type(reply) == 'table' and reply.name ~= 'OK' then dragonfly.log_event(analyzer_name..': '..cmd..' : '..reply.name) dragonfly.analyze_event(default_analyzer, msg) return elseif not tonumber(reply) then dragonfly.log_event(analyzer_name..': Could not convert to number: '..reply) dragonfly.analyze_event(default_analyzer, msg) return end local src_size = reply dest_percentile = tonumber(dest_rank) / tonumber(dest_size) src_percentile = tonumber(src_rank) / tonumber(src_size) score = math.max(dest_percentile, src_percentile) bytes_rank["score"] = score bytes_rank["threshold"] = threshold bytes_rank["src_percentile"] = src_percentile bytes_rank["dest_percentile"] = dest_percentile return bytes_rank end function loop(msg) local start = os.clock() local eve = msg local fields = { ["event_type"] = "alert"} if not check_fields(eve, fields) then dragonfly.log_event(analyzer_name..': Required fields missing') dragonfly.analyze_event(default_analyzer, msg) return end analytics = eve.analytics details = {} max_score = 0 score = 0 num_over_threshold = 0 num_analyzers = 0 -- Add in individual analyzers -- Aggregation function: MAX of analyzers over the threshold + count of analyzers over the threshold -- Analyzer 1: Domain Generation Algorithm (DGA) -- Threshold: 0.98 if analytics.dga then dga = {} score_str = analytics.dga.score dga_score = tonumber(score_str) dga["score"] = dga_score dga["domain"] = analytics.dga.domain if dga_score > 0.98 then num_over_threshold = num_over_threshold + 1 end if dga_score > max_score then max_score = dga_score end num_analyzers = num_analyzers + 1 details["dga"] = dga end -- Analyzer 2: IP Blacklist -- Threshold: 0, any non-NONE value = 1 if analytics.ip_rep and analytics.ip_rep.ip_rep then blacklist = {} reputation = analytics.ip_rep.ip_rep -- dragonfly.output_event("debug", "Score Rep: " .. reputation) blacklist["blacklist"] = reputation if reputation and reputation ~= "NONE" then num_over_threshold = num_over_threshold + 1 max_score = 1 end num_analyzers = num_analyzers + 1 details["blacklist"] = blacklist end -- Analyzer 3: Time Anomaly -- Threshold: Uniform (but set by the analyzer) if analytics.time then time = {} threshold = analytics.time.threshold score = analytics.time.score -- dragonfly.output_event("debug", "Score Rep: " .. reputation) time["score"] = score time["threshold"] = threshold time["hour"] = analytics.time.hour time["timezone"] = analytics.time.timezone if score > threshold then num_over_threshold = num_over_threshold + 1 end if score > max_score then max_score = score end num_analyzers = num_analyzers + 1 details["time"] = time end -- Analyzer 4: Country Anomaly -- Threshold: Uniform (but set by the analyzer) if analytics.country then country = {} threshold = analytics.country.threshold score = analytics.country.score -- dragonfly.output_event("debug", "Score Rep: " .. reputation) country["score"] = score country["threshold"] = threshold country["country"] = analytics.country.country_code if score > threshold then num_over_threshold = num_over_threshold + 1 end if score > max_score then max_score = score end num_analyzers = num_analyzers + 1 details["country"] = country end local bytes_rank = get_bytes_rank(eve) if bytes_rank then if bytes_rank.score > bytes_rank.threshold then num_over_threshold = num_over_threshold + 1 end if bytes_rank.score > max_score then max_score = score end num_analyzers = num_analyzers + 1 details["bytes_rank"] = bytes_rank end -- Analyzer 6: Signature Anomaly if analytics.signature then signature = {} threshold = analytics.signature.threshold score = analytics.signature.score -- dragonfly.output_event("debug", "Score Rep: " .. reputation) signature["score"] = score signature["threshold"] = threshold if score > threshold then num_over_threshold = num_over_threshold + 1 end if score > max_score then max_score = score end num_analyzers = num_analyzers + 1 details["signature"] = signature end priority = {} -- Priority is max score, boosted if an analyzer crossed a threshold priority["priority"] = max_score + (max_score * num_over_threshold / num_analyzers) priority["details"] = details eve["priority"] = priority dragonfly.analyze_event(default_analyzer, eve) local now = os.clock() local delta = now - start dragonfly.log_event(analyzer_name..': time: '..delta) end
-- -- Autogenerated by Thrift -- -- DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING -- @generated -- local Thrift = require 'Thrift' local TType = Thrift.TType local __TObject = Thrift.__TObject local TException = Thrift.TException local ErrorCode = { SE_CONNPOOL_TIMEOUT = 0, SE_THRIFT_CONN_ERROR = 1, SE_UNAUTHORIZED = 2, SE_MEMCACHED_ERROR = 3, SE_MONGODB_ERROR = 4, SE_REDIS_ERROR = 5, SE_THRIFT_HANDLER_ERROR = 6, SE_RABBITMQ_CONN_ERROR = 7 } local PostType = { POST = 0, REPOST = 1, REPLY = 2, DM = 3 } local User = __TObject:new{ user_id, first_name, last_name, username, password_hashed, salt } function User:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.user_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRING then self.first_name = iprot:readString() else iprot:skip(ftype) end elseif fid == 3 then if ftype == TType.STRING then self.last_name = iprot:readString() else iprot:skip(ftype) end elseif fid == 4 then if ftype == TType.STRING then self.username = iprot:readString() else iprot:skip(ftype) end elseif fid == 5 then if ftype == TType.STRING then self.password_hashed = iprot:readString() else iprot:skip(ftype) end elseif fid == 6 then if ftype == TType.STRING then self.salt = iprot:readString() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function User:write(oprot) oprot:writeStructBegin('User') if self.user_id ~= nil then oprot:writeFieldBegin('user_id', TType.I64, 1) oprot:writeI64(self.user_id) oprot:writeFieldEnd() end if self.first_name ~= nil then oprot:writeFieldBegin('first_name', TType.STRING, 2) oprot:writeString(self.first_name) oprot:writeFieldEnd() end if self.last_name ~= nil then oprot:writeFieldBegin('last_name', TType.STRING, 3) oprot:writeString(self.last_name) oprot:writeFieldEnd() end if self.username ~= nil then oprot:writeFieldBegin('username', TType.STRING, 4) oprot:writeString(self.username) oprot:writeFieldEnd() end if self.password_hashed ~= nil then oprot:writeFieldBegin('password_hashed', TType.STRING, 5) oprot:writeString(self.password_hashed) oprot:writeFieldEnd() end if self.salt ~= nil then oprot:writeFieldBegin('salt', TType.STRING, 6) oprot:writeString(self.salt) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local ServiceException = TException:new{ __type = 'ServiceException', errorCode, message } function ServiceException:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I32 then self.errorCode = iprot:readI32() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRING then self.message = iprot:readString() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function ServiceException:write(oprot) oprot:writeStructBegin('ServiceException') if self.errorCode ~= nil then oprot:writeFieldBegin('errorCode', TType.I32, 1) oprot:writeI32(self.errorCode) oprot:writeFieldEnd() end if self.message ~= nil then oprot:writeFieldBegin('message', TType.STRING, 2) oprot:writeString(self.message) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local Media = __TObject:new{ media_id, media_type } function Media:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.media_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRING then self.media_type = iprot:readString() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function Media:write(oprot) oprot:writeStructBegin('Media') if self.media_id ~= nil then oprot:writeFieldBegin('media_id', TType.I64, 1) oprot:writeI64(self.media_id) oprot:writeFieldEnd() end if self.media_type ~= nil then oprot:writeFieldBegin('media_type', TType.STRING, 2) oprot:writeString(self.media_type) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local Url = __TObject:new{ shortened_url, expanded_url } function Url:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.STRING then self.shortened_url = iprot:readString() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRING then self.expanded_url = iprot:readString() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function Url:write(oprot) oprot:writeStructBegin('Url') if self.shortened_url ~= nil then oprot:writeFieldBegin('shortened_url', TType.STRING, 1) oprot:writeString(self.shortened_url) oprot:writeFieldEnd() end if self.expanded_url ~= nil then oprot:writeFieldBegin('expanded_url', TType.STRING, 2) oprot:writeString(self.expanded_url) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local UserMention = __TObject:new{ user_id, username } function UserMention:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.user_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRING then self.username = iprot:readString() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function UserMention:write(oprot) oprot:writeStructBegin('UserMention') if self.user_id ~= nil then oprot:writeFieldBegin('user_id', TType.I64, 1) oprot:writeI64(self.user_id) oprot:writeFieldEnd() end if self.username ~= nil then oprot:writeFieldBegin('username', TType.STRING, 2) oprot:writeString(self.username) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local Creator = __TObject:new{ user_id, username } function Creator:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.user_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRING then self.username = iprot:readString() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function Creator:write(oprot) oprot:writeStructBegin('Creator') if self.user_id ~= nil then oprot:writeFieldBegin('user_id', TType.I64, 1) oprot:writeI64(self.user_id) oprot:writeFieldEnd() end if self.username ~= nil then oprot:writeFieldBegin('username', TType.STRING, 2) oprot:writeString(self.username) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end local Post = __TObject:new{ post_id, creator, req_id, text, user_mentions, media, urls, timestamp, post_type } function Post:read(iprot) iprot:readStructBegin() while true do local fname, ftype, fid = iprot:readFieldBegin() if ftype == TType.STOP then break elseif fid == 1 then if ftype == TType.I64 then self.post_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 2 then if ftype == TType.STRUCT then self.creator = Creator:new{} self.creator:read(iprot) else iprot:skip(ftype) end elseif fid == 3 then if ftype == TType.I64 then self.req_id = iprot:readI64() else iprot:skip(ftype) end elseif fid == 4 then if ftype == TType.STRING then self.text = iprot:readString() else iprot:skip(ftype) end elseif fid == 5 then if ftype == TType.LIST then self.user_mentions = {} local _etype3, _size0 = iprot:readListBegin() for _i=1,_size0 do local _elem4 = UserMention:new{} _elem4:read(iprot) table.insert(self.user_mentions, _elem4) end iprot:readListEnd() else iprot:skip(ftype) end elseif fid == 6 then if ftype == TType.LIST then self.media = {} local _etype8, _size5 = iprot:readListBegin() for _i=1,_size5 do local _elem9 = Media:new{} _elem9:read(iprot) table.insert(self.media, _elem9) end iprot:readListEnd() else iprot:skip(ftype) end elseif fid == 7 then if ftype == TType.LIST then self.urls = {} local _etype13, _size10 = iprot:readListBegin() for _i=1,_size10 do local _elem14 = Url:new{} _elem14:read(iprot) table.insert(self.urls, _elem14) end iprot:readListEnd() else iprot:skip(ftype) end elseif fid == 8 then if ftype == TType.I64 then self.timestamp = iprot:readI64() else iprot:skip(ftype) end elseif fid == 9 then if ftype == TType.I32 then self.post_type = iprot:readI32() else iprot:skip(ftype) end else iprot:skip(ftype) end iprot:readFieldEnd() end iprot:readStructEnd() end function Post:write(oprot) oprot:writeStructBegin('Post') if self.post_id ~= nil then oprot:writeFieldBegin('post_id', TType.I64, 1) oprot:writeI64(self.post_id) oprot:writeFieldEnd() end if self.creator ~= nil then oprot:writeFieldBegin('creator', TType.STRUCT, 2) self.creator:write(oprot) oprot:writeFieldEnd() end if self.req_id ~= nil then oprot:writeFieldBegin('req_id', TType.I64, 3) oprot:writeI64(self.req_id) oprot:writeFieldEnd() end if self.text ~= nil then oprot:writeFieldBegin('text', TType.STRING, 4) oprot:writeString(self.text) oprot:writeFieldEnd() end if self.user_mentions ~= nil then oprot:writeFieldBegin('user_mentions', TType.LIST, 5) oprot:writeListBegin(TType.STRUCT, #self.user_mentions) for _,iter15 in ipairs(self.user_mentions) do iter15:write(oprot) end oprot:writeListEnd() oprot:writeFieldEnd() end if self.media ~= nil then oprot:writeFieldBegin('media', TType.LIST, 6) oprot:writeListBegin(TType.STRUCT, #self.media) for _,iter16 in ipairs(self.media) do iter16:write(oprot) end oprot:writeListEnd() oprot:writeFieldEnd() end if self.urls ~= nil then oprot:writeFieldBegin('urls', TType.LIST, 7) oprot:writeListBegin(TType.STRUCT, #self.urls) for _,iter17 in ipairs(self.urls) do iter17:write(oprot) end oprot:writeListEnd() oprot:writeFieldEnd() end if self.timestamp ~= nil then oprot:writeFieldBegin('timestamp', TType.I64, 8) oprot:writeI64(self.timestamp) oprot:writeFieldEnd() end if self.post_type ~= nil then oprot:writeFieldBegin('post_type', TType.I32, 9) oprot:writeI32(self.post_type) oprot:writeFieldEnd() end oprot:writeFieldStop() oprot:writeStructEnd() end return { ErrorCode=ErrorCode, PostType=PostType, User=User, ServiceException=ServiceException, Media=Media, Url=Url, UserMention=UserMention, Creator=Creator, Post=Post }
-- Assorted global functions that don't belong in their own file. -- 5.3 compatibility local unpack = unpack or table.unpack local loadstring = loadstring or load -- "safe require", returns nil,error if require fails rather than -- throwing an error function srequire(...) local s,r = pcall(require, ...) if s then return r end return nil,r end -- fast one-liner lambda creation function f(src) return assert(loadstring( "return function(" .. src:gsub(" => ", ") return ") .. " end" ))() end -- bind args into function function partial(f, ...) if select('#', ...) == 0 then return f end local head = (...) return partial(function(...) return f(head, ...) end, select(2, ...)) end -- New versions of pairs, ipairs, and type that respect the corresponding -- metamethods. do local function metamethod_wrap(f, name) return function(v) local mm = getmetafield(v, name) if mm then return mm(v) end return f(v) end end rawtype = type type = metamethod_wrap(type, "__type") -- We only need this on Lua 5.1 (5.2+ have it built in). But LuaJIT may also -- have it built in, depending on compilation option. -- If jit is defined, we're running in luajit. If 5.2 extensions are enabled, -- table.pack will be defined. if _VERSION:match("Lua 5.1") or (jit and not table.pack) then pairs = metamethod_wrap(pairs, "__pairs") ipairs = metamethod_wrap(ipairs, "__ipairs") end end -- formatting-aware versions of assert and error do -- We call it 'assertf' because things like assert(call()) are common, and -- if call() returns a bunch of stuff format() will get confused. -- This is more for 'assert(precondition, error, ...)' style usage. -- Maybe it should be called check() instead? function assertf(exp, err, ...) return assert(exp, err:format(...)) end local _error = error function error(err, ...) if select('#', ...) > 0 then return _error(err:format(...)) end return _error(err) end end -- Get field from metatable, return nil if no metatable function getmetafield(v, k) local mt = getmetatable(v) return mt and rawget(mt, k) end -- As tonumber/tostring, but casts to bool function toboolean(v) return not not v end
local spy = require "luassert.spy" local stub = require "luassert.stub" local _M = { --- @type busted_resty _VERSION = "0.5.0", _unmocked_ngx = nil, } --- create a metatable which return a mock string in its `__index` metamethod --- @return table a table for being a metatable local function create_new_var_metatable(prefix) return { __index = function(tbl, key) tbl[key] = "mock_var" return tbl[key] end } end --- create a metatable which return stubbed function in its `__index` metamethod --- @return table a table for being a metatable local function create_new_func_metatable(prefix) return { __index = function(tbl, key) tbl[key] = function() end tbl[key] = stub(tbl, key) return tbl[key] end } end --- create a new ngx object for further mocking --- @return table new partially mocked ngx object local function create_mock_ngx() return { status = 0, -- vars arg = setmetatable({}, create_new_var_metatable()), var = setmetatable({}, create_new_var_metatable()), header = setmetatable({}, create_new_var_metatable()), -- functions location = setmetatable({}, create_new_func_metatable()), req = setmetatable({}, create_new_func_metatable()), resp = setmetatable({}, create_new_func_metatable()), } end --- init the mock objects for the target table --- @param _ngx table local function init_mocks(_ngx) if type(_ngx) ~= "table" then error("[busted_resty:init_mocks] _ngx is not a table") end stub(_ngx, "exit") stub(_ngx, "exec") stub(_ngx, "redirect") stub(_ngx, "send_headers") stub(_ngx, "headers_sent") stub(_ngx, "print") stub(_ngx, "say") stub(_ngx, "flush") stub(_ngx, "eof") stub(_ngx, "is_subrequest") stub(_ngx, "on_abort") stub(_ngx.req, "get_headers", {}) stub(_ngx.req, "get_uri_args", {}) stub(_ngx.req, "get_method", "GET") stub(_ngx.req, "http_version", 1.1) end --- clear all the calling traces for spy objects in a table, recursively --- @param tbl table target table (i.e. ngx) --- @return boolean cleared for true, tbl is not a table for false local function clear_spy_calls(tbl) if type(tbl) ~= "table" then return false end for k, v in pairs(tbl) do if spy.is_spy(v) then v:clear() elseif type(v) == "table" then clear_spy_calls(tbl[k]) end end return true end --- clear all calling traces if the `ngx` is mocked by this module. function _M.clear() if not _M._unmocked_ngx then return end clear_spy_calls(_G.ngx) end --- restore `ngx` global object if mocked before function _M.restore() if _M._unmocked_ngx then _G.ngx = _M._unmocked_ngx end end --- init the busted_resty --- restore `ngx` global variable if mocked before. --- create new mocked `ngx` with `__index` metamethod. function _M.init() if not _M._unmocked_ngx then _M._unmocked_ngx = _G.ngx else _M.restore() end local new_ngx = create_mock_ngx() init_mocks(new_ngx) _G.ngx = setmetatable(new_ngx, { __index = _G.ngx }) end -- create a callable module -- init this module by `require "busted_resty"()` return setmetatable(_M, { __call = function(self) self.init() end })
return Def.Actor { BeginCommand = SL.IsEtterna and function() SCREENMAN:GetTopScreen():AddInputCallback(MPinput) end or nil }
local kOuterRangeScalar = 0.65 local function CustomAttackMeleeCapsule(weapon, player, damage, range, optionalCoords, traceRealAttack, scale, priorityFunc, filter, mask) scale = scale or 1 local eyePoint = player:GetEyePos() -- if not teamNumber then -- teamNumber = GetEnemyTeamNumber( player:GetTeamNumber() ) -- end mask = mask or PhysicsMask.Melee local coords = optionalCoords or player:GetViewAngles():GetCoords() local axis = coords.zAxis local forwardDirection = Vector(coords.zAxis) forwardDirection.y = 0 if forwardDirection:GetLength() ~= 0 then forwardDirection:Normalize() end local width, height = weapon:GetMeleeBase() width = scale * width height = scale * height --[[ if Client then Client.DebugCapsule(eyePoint, eyePoint + axis * range, width, 0, 3) end --]] -- extents defines a world-axis aligned box, so x and z must be the same. local extents = Vector(width / 6, height / 6, width / 6) if not filter then filter = EntityFilterOne(player) end local middleTrace,middleStart local target,endPoint,surface,startPoint if not priorityFunc then priorityFunc = IsBetterMeleeTarget end local selectedTrace local boxRange local outerBoxRange = range * kOuterRangeScalar for _, pointIndex in ipairs(kTraceOrder) do local dx = pointIndex % 3 - 1 local dy = math.floor(pointIndex / 3) - 1 local point = eyePoint + coords.xAxis * (dx * width / 3) + coords.yAxis * (dy * height / 3) if dx == 0 and dy == 0 then boxRange = range else boxRange = outerBoxRange end local trace, sp, ep = TraceMeleeBox(weapon, point, axis, extents, boxRange, mask, filter) if dx == 0 and dy == 0 then middleTrace, middleStart = trace, sp selectedTrace = trace end if trace.entity and priorityFunc(weapon, player, trace.entity, target) and IsNotBehind(eyePoint, trace.endPoint, forwardDirection) then selectedTrace = trace target = trace.entity startPoint = sp endPoint = trace.endPoint surface = trace.surface surface = GetIsAlienUnit(target) and "organic" or "metal" if GetAreEnemies(player, target) then if target:isa("Alien") then surface = "organic" elseif target:isa("Marine") then surface = "flesh" else if HasMixin(target, "Team") then if target:GetTeamType() == kAlienTeamType then surface = "organic" else surface = "metal" end end end end end end -- if we have not found a target, we use the middleTrace to possibly bite a wall (or when cheats are on, teammates) target = target or middleTrace.entity endPoint = endPoint or middleTrace.endPoint surface = surface or middleTrace.surface startPoint = startPoint or middleStart local direction = target and (endPoint - startPoint):GetUnit() or coords.zAxis return target ~= nil or middleTrace.fraction < 1, target, endPoint, direction, surface, startPoint, selectedTrace end function BiteLeap:OnTag(tagName) PROFILE("BiteLeap:OnTag") if tagName == "hit" then local player = self:GetParent() if player then local range = (player.GetIsEnzymed and player:GetIsEnzymed()) and kEnzymedRange or kRange local didHit, target, endPoint = CustomAttackMeleeCapsule(self, player, kBiteDamage, range, nil, false, EntityFilterOneAndIsa(player, "Babbler")) if Client and didHit then self:TriggerFirstPersonHitEffects(player, target) end if target and HasMixin(target, "Live") and not target:GetIsAlive() then self:TriggerEffects("bite_kill") elseif Server and target and target.TriggerEffects and GetReceivesStructuralDamage(target) and (not HasMixin(target, "Live") or target:GetCanTakeDamage()) then target:TriggerEffects("bite_structure", {effecthostcoords = Coords.GetTranslation(endPoint), isalien = GetIsAlienUnit(target)}) end self:OnAttack(player) self:TriggerEffects("bite_attack") end end end
doRockHover = false; function onCreate() -- -- background shit makeLuaSprite('hall', 'entity/nikusa/NikusaBG', -1000, -425); addLuaSprite('hall', false); -- addLuaSprite('stagefront', false); -- addLuaSprite('stagelight_left', false); -- addLuaSprite('stagelight_right', false); -- addLuaSprite('stagecurtains', false); -- close(true); --For performance reasons, close this script once the stage is fully loaded, as this script won't be used anymore after loading the stage end -- -350 + Math.sin((Conductor.songPosition / 1000) * (Conductor.bpm / 60) * 1.5) * 12.5; function onUpdate(elapsed) -- getSongPosition(); end
local Native = require('lib.native.native') ---@class ItemIntegerField local ItemIntegerField = { Level = Native.ConvertItemIntegerField(0x696C6576), --ITEM_IF_LEVEL NumberOfCharges = Native.ConvertItemIntegerField(0x69757365), --ITEM_IF_NUMBER_OF_CHARGES CooldownGroup = Native.ConvertItemIntegerField(0x69636964), --ITEM_IF_COOLDOWN_GROUP MaxHitPoints = Native.ConvertItemIntegerField(0x69687470), --ITEM_IF_MAX_HIT_POINTS HitPoints = Native.ConvertItemIntegerField(0x69687063), --ITEM_IF_HIT_POINTS Priority = Native.ConvertItemIntegerField(0x69707269), --ITEM_IF_PRIORITY ArmorType = Native.ConvertItemIntegerField(0x6961726D), --ITEM_IF_ARMOR_TYPE TintingColorRed = Native.ConvertItemIntegerField(0x69636C72), --ITEM_IF_TINTING_COLOR_RED TintingColorGreen = Native.ConvertItemIntegerField(0x69636C67), --ITEM_IF_TINTING_COLOR_GREEN TintingColorBlue = Native.ConvertItemIntegerField(0x69636C62), --ITEM_IF_TINTING_COLOR_BLUE TintingColorAlpha = Native.ConvertItemIntegerField(0x6963616C), --ITEM_IF_TINTING_COLOR_ALPHA } return ItemIntegerField
local loadString = load require("wx") require("turtle") local common = require("common") local complex = require("complex") local chartmap = require("chartmap") local colormap = require("colormap") io.stdout:setvbuf("no") local nFunc = 1 local tFunc = { {"(z^2 - 1)*(z - 2 - i)^2/(z^2 + 2 + 2*i)",4}, {"(z^3 - 1)", 1.3}, {"(1/(1+z))", 5}, {"(1/(1+z^2))", 5}, {"(1/(1-(z:getReal()+i*z:getImag())^2))", 5} } -- Tinker stuff local nAlp = 0.6 local dX, dY = 1,1 local W, H = 500, 500 -- Automatic stuff local nRan = tFunc[nFunc][2] local cI = complex.getNew(0,1) -- 0+i local intX = chartmap.New("interval","WinX", -nRan, nRan, 0, W) local intY = chartmap.New("interval","WinY", -nRan, nRan, H, 0) local scOpe = chartmap.New("scope"):setInterval(intX, intY):setSize():setBorder() scOpe:setColor():setDelta(dX, dY):Draw(true, true, true):setSizeVtx(0) local fFoo, sErr = loadString("return function(z, i) return "..tFunc[nFunc][1].." end") if(not fFoo) then print("Load("..tostring(fFoo).."): "..sErr); return end bSuc , fFoo = pcall(fFoo) if(not bSuc) then print("Make("..tostring(bSuc).."): "..fFoo); return end open("Complex domain coloring") size(W, H); zero(0, 0) updt(false) -- disable auto updates scOpe:Draw(false, false, false) local function getComplexColor(i,j) local nI = intX:Convert(i,true):getValue() local nJ = intY:Convert(j,true):getValue() local vC = complex.getNew(nI,nJ) local vF = fFoo(vC, cI) local nM, nP = vF:getPolar() local hslH = complex.toDeg(nP) hslM = ((hslH < 0) and (hslH+360) or hslH) local hslS, hslL = 1, (1-nAlp^nM) local r, g, b = colormap.getColorHSL(hslM, hslS, hslL) if(vF:isNan()) then -- Interpolate {0,0} as up-down-left-right local vC1, vF1, r1, g1, b1 = getComplexColor(i-1,j) local vC2, vF2, r2, g2, b2 = getComplexColor(i+1,j) local vC3, vF3, r3, g3, b3 = getComplexColor(i,j-1) local vC4, vF4, r4, g4, b4 = getComplexColor(i,j+1) r = (r1 + r2 + r3 + r4) / 4 g = (g1 + g2 + g3 + g4) / 4 b = (b1 + b2 + b3 + b4) / 4 end; return vC, vF, r, g, b end for j = 0, H do for i = 0, W do -- Convert coordinates to complex mapping local vC, vF, r, g, b = getComplexColor(i, j) scOpe:drawPointXY(vC:getReal(),vC:getImag(),colr(r, g, b)) end; updt() end wait()
-- 'Clan Administration' tab local settings = {id = 2.3, title = "Clan Administration"} local content = nil local items = { ["button_goback"] = {type = "button", text = "Return", x = 5, y = 5, width = 100, height = 35}, ["button_destroyclan"] = {type = "button", text = "Destroy", x = panel.width - 105, y = 5, width = 100, height = 35}, ["custom_infoblock"] = {type = "custom", x = panel.width * 0.1, y = panel.height * 0.15, width = panel.width * 0.8, height = panel.height * 0.2}, ["label_clanname"] = {type = "label", text = "Rename your clan ($50K)", x = panel.width * 0.1, y = panel.height * 0.3, width = panel.width * 0.2, height = 40, verticalAlign = "center"}, ["input_clanname"] = {type = "input", text = "How will be your clan called?", x = panel.width * 0.3, y = panel.height * 0.3, width = panel.width * 0.6, height = 40, maxLength = 36, backgroundColor = {0, 0, 0, 0}}, ["rectangle_clannameseperator"] = {type = "rectangle", x = panel.width * 0.1, y = panel.height * 0.3 + 39, width = panel.width * 0.8, height = 1, color = tocolor(255, 255, 255, 55)}, ["label_clancolor"] = {type = "label", text = "Re-colorize ($50K)", x = panel.width * 0.1, y = panel.height * 0.3 + 45, width = panel.width * 0.2, height = 40, verticalAlign = "center"}, ["input_clancolor"] = {type = "input", text = "#FFFFFF", x = panel.width * 0.3, y = panel.height * 0.3 + 45, width = panel.width * 0.6, height = 40, maxLength = 7, backgroundColor = {0, 0, 0, 0}}, ["rectangle_clancolorseperator"] = {type = "rectangle", x = panel.width * 0.1, y = panel.height * 0.3 + 84, width = panel.width * 0.8, height = 1, color = tocolor(255, 255, 255, 55)}, ["label_clandescription"] = {type = "label", text = "Change the description ($50K)", x = panel.width * 0.1, y = panel.height * 0.3 + 90, width = panel.width * 0.2, height = 40, verticalAlign = "center"}, ["input_clandescription"] = {type = "input", text = "#FFFFFF", x = panel.width * 0.3, y = panel.height * 0.3 + 90, width = panel.width * 0.6, height = 40, maxLength = 75, backgroundColor = {0, 0, 0, 0}}, ["button_update"] = {type = "button", text = "Update", x = panel.width * 0.5 - 100, y = panel.height - 40, width = 200, height = 35}, ["custom_colorpreview"] = {type = "custom", x = panel.width * 0.1 - 35, y = panel.height * 0.3 + 55, width = 20, height = 20} } -- Optimization local dxCreateRenderTarget = dxCreateRenderTarget local dxSetRenderTarget = dxSetRenderTarget local dxSetBlendMode = dxSetBlendMode local dxDrawRectangle = dxDrawRectangle local dxDrawText = dxDrawText local dxDrawImage = dxDrawImage local dxDrawImageSection = dxDrawImageSection local unpack = unpack local tocolor = tocolor local math_min = math.min local math_max = math.max local math_floor = math.floor local tableInsert = table.insert local tableRemove = table.remove local pairs = pairs local interpolateBetween = interpolateBetween -- Info text local infoText = [[ Welcome to your clan admin control panel, in this panel you can reconfigure your clan's important settings such as its name, color and update its description. Enter new configuration in the field which is required to be updated, and hit the update button to update. Important: Destroying the clan cannot be cancelled later. So please think twice before doing it. ]] -- Initialization local function initTab() -- Tab registration content = panel.initTab(settings.id, settings, items) -- Customization items["custom_infoblock"].renderingFunction = function(x, y, item) dxDrawText(infoText, x, y, x + item.width, y + item.height, tocolor(255, 255, 255, 255), item.fontScale, item.font, "center", "top", true, true) end items["custom_colorpreview"].renderingFunction = function(x, y, item) local color = content.previewColor or {255, 255, 255} dxDrawImage(x, y, item.width, item.height, "img/circle.png", 0, 0, 0, tocolor(color[1], color[2], color[3], 255)) end -- Functions -- 'return' items["button_goback"].onClick = function() panel.switch(2.1) end -- 'input' items["input_clancolor"].onTextChange = function(text) local r, g, b = hexToRGB(text) if r and g and b then content.previewColor = {r, g, b} else content.previewColor = nil end updateConfiguration() end items["input_clanname"].onTextChange = function() updateConfiguration() end items["input_clandescription"].onTextChange = function() updateConfiguration() end -- 'update' items["button_update"].onClick = function() if content.lastAttemptTick and getTickCount() - content.lastAttemptTick < 2000 then return triggerEvent("notification:create", "Clan", "You can't make too many attempts in a row, please wait") end if not content.configuration then return triggerEvent("notification:create", localPlayer, "Clan", "You didn't change anything") end if content.configuration.ClanName and #content.configuration.ClanName:gsub(" ", "") < 3 then return triggerEvent("notification:create", localPlayer, "Clan", "Clan name should contain minimum 3 letters") end if content.configuration.description and #content.configuration.description:gsub(" ", "") < 8 then return triggerEvent("notification:create", localPlayer, "Clan", "Your description is too short") end triggerServerEvent("Clan:onClanUpdateConfig", localPlayer, content.clan.id, content.configuration) content.lastAttemptTick = getTickCount() end -- 'destroy' items["button_destroyclan"].onClick = function() triggerServerEvent("Clan:onClanDestroy", localPlayer, content.clan.id) end end addEventHandler("onClientResourceStart", resourceRoot, initTab) -- Update cache function updateAdministrationCache(clan) if clan then content.clan = clan else return end items["input_clanname"].text = content.clan.name items["input_clancolor"].text = content.clan.colorHex items["input_clandescription"].text = content.clan.data.description end -- Config function updateConfiguration() local name = items["input_clanname"].text local color = content.previewColor local description = items["input_clandescription"].text if name or color or description then if not content.configuration then content.configuration = {} end if name and name ~= "" then content.configuration.ClanName = name else content.configuration.ClanName = nil end if color then local hex = string.format("#%.2X%.2X%.2X", unpack(color)) content.configuration.ClanColor = hex else content.configuration.ClanColor = nil end if description and description ~= "" then content.configuration.description = description else content.configuration.description = nil end else content.configuration = nil end end
-- rFilter_Zork: debuff -- zork, 2016 ----------------------------- -- Variables ----------------------------- local A, L = ... ----------------------------- -- Debuff Config ----------------------------- if L.C.playerName == "Zörk" then rFilter:CreateDebuff(115767,"target",36,{"CENTER"},"[spec:3,combat]show;hide",{0.2,1},true,nil) --deep wounds end if L.C.playerClass == "ROGUE" then rFilter:CreateDebuff(1833,"target",36,{"CENTER"},"[combat]show;hide",{0.2,1},true,"player") --deep wounds end
-- Tiled maps loading library -- This library has basic, but sufficent support of Tiled lua format. -- Adjust it according to your usage of Tiled, for example extra layer properties. local physics = require('physics') local bit = require('plugin.bit') local eachframe = require('libs.eachframe') local relayout = require('libs.relayout') local FlippedHorizontallyFlag = 0x80000000 local FlippedVerticallyFlag = 0x40000000 local FlippedGiagonallyFlag = 0x20000000 local ClearFlag = 0x1FFFFFFF -- Break full path string into path and filename local function extractPath(p) local c for i = p:len(), 1, -1 do c = p:sub(i, i) if c == '/' then return p:sub(1, i - 1), p:sub(i + 1) end end end -- Keep a value in boundaries local function clamp(value, low, high) if value < low then value = low elseif high and value > high then value = high end return value end local function load(self, params) local _W, _H = relayout._W, relayout._H self.map = require(params.filename) -- Actual Tiled data package.loaded[params.filename] = nil -- Remove from memory in case it's updated during runtime self.specs = params.specs or {} self:prepareTilesets() self.snapshot = display.newSnapshot(params.g, _W, _H) -- All tiles go into this snapshot self.snapshot.x, self.snapshot.y = 0, 0 self.group = self.snapshot.group self.snapshot.anchorX, self.snapshot.anchorY = 0, 0 self.group.x, self.group.y = -self.snapshot.width / 2, -self.snapshot.height / 2 local super = self function self.snapshot:relayout() self.width, self.height = relayout._W, relayout._H super.camera.high = {x = super.map.tilewidth * super.map.width - relayout._W, y = super.map.tilewidth * super.map.height - relayout._H} super:moveCamera(super.camera.x, super.camera.y) end relayout.add(self.snapshot) self.layers = {} -- Each Tiled layer has it's own group and they are stored here self.physicsGroup = display.newGroup() -- A separate group for physics objects params.g:insert(self.physicsGroup) self.physicsGroup.x, self.physicsGroup.y = self.snapshot.x, self.snapshot.y -- A set of properties for the camera self.camera = { x = 0, y = 0, xIncrement = 0, yIncrement = 0, low = {x = 0, y = 0}, high = {x = self.map.tilewidth * self.map.width - _W, y = self.map.tilewidth * self.map.height - _H} } -- Tiled provides a background color local color = self.map.backgroundcolor self.map.backgroundcolor = {color[1] / 255, color[2] / 255, color[3] / 255} eachframe.add(self) function self.snapshot:finalize() eachframe.remove(super) relayout.remove(self) end self.snapshot:addEventListener('finalize') end -- Load all spritesheers into memory local function prepareTilesets(self) self.tilesets = {} self.tileProperties = {} local map = self.map for i = 1, #map.tilesets do local t = map.tilesets[i] if t.image then local dir, filename = extractPath(t.image:sub(4)) local spritesheet = graphics.newImageSheet(dir .. filename, { width = t.tilewidth, height = t.tileheight, sheetContentWidth = t.imagewidth, sheetContentHeight = t.imageheight, numFrames = (t.imagewidth / t.tilewidth) * (t.imageheight / t.tileheight)}) table.insert(self.tilesets, spritesheet) end if t.tiles then self.tileProperties[t.name] = {} for j = 1, #t.tiles do local p = t.tiles[j] if p.properties then self.tileProperties[t.name][p.id + 1] = p.properties else self.tileProperties[t.name][p.id + 1] = {image = p.image:sub(4, p.image:len()), width = p.width, height = p.height} end end end end end local function getSpriteSheetByGid(self, gid) local map_tilesets = self.map.tilesets for i = #map_tilesets, 1, -1 do if map_tilesets[i].firstgid <= gid then return map_tilesets[i].name, self.tilesets[i], gid - map_tilesets[i].firstgid + 1 end end end local function newTile(self, params) local map = self.map local gid = params.gid local flip = {} if gid > 1000 or gid < -1000 then flip.x = bit.band(gid, FlippedHorizontallyFlag) ~= 0 flip.y = bit.band(gid, FlippedVerticallyFlag) ~= 0 flip.xy = bit.band(gid, FlippedGiagonallyFlag) ~= 0 gid = bit.band(gid, ClearFlag) end local sheetName, sheet, frameIndex = self:getSpriteSheetByGid(gid) local properties = self.tileProperties[sheetName] and self.tileProperties[sheetName][frameIndex] or {} local tile if sheet then tile = display.newImage(params.g, sheet, frameIndex) tile.x, tile.y = (params.x + 0.5) * map.tilewidth, (params.y + 0.5) * map.tileheight else tile = display.newImageRect(params.g, properties.image, properties.width, properties.height) _conditional_breakpoint(tile == nil) tile.x, tile.y = params.x * map.tilewidth + properties.width / 2, (params.y + 1) * map.tileheight - properties.height / 2 end if params.tint then tile:setFillColor(unpack(params.tint)) end tile.flip = flip if flip.xy then if flip.x == flip.y then print('tiled: unsupported rotation x,y:', params.x, params.y, flip.x, flip.y) end if flip.x then tile.rotation = 90 elseif flip.y then tile.rotation = -90 end else if flip.x then tile.xScale = -1 end if flip.y then tile.yScale = -1 end end return tile end -- Objects are rectangles and other polygons from Tiled local function newObject(self, params) if params.shape == 'rectangle' then local rect = display.newRect(params.g, params.x, params.y, params.width, params.height) rect.anchorX, rect.anchorY = 0, 0 rect.isVisible = false physics.addBody(rect, 'static', {density = 1, friction = 0.5, bounce = 0}) elseif params.shape == 'polygon' then local vertices = {} for i = 1, #params.polygon do table.insert(vertices, params.polygon[i].x) table.insert(vertices, params.polygon[i].y) end local polygon = display.newPolygon(params.g, params.x, params.y, vertices) polygon.anchorX, polygon.anchorY = 0, 1 polygon.isVisible = false physics.addBody(polygon, 'static', {density = 1, friction = 0.5, bounce = 0}) end end -- Iterate each Tiled layer and create all tiles and objects local function draw(self) local map = self.map local w, h = map.width, map.height for i = 1, #map.layers do local l = map.layers[i] if l.type == 'tilelayer' then local groupLayer = display.newGroup() self.group:insert(groupLayer) table.insert(self.layers, groupLayer) if l.properties.ratio then groupLayer.ratio = tonumber(l.properties.ratio) end if l.properties.speed then groupLayer.speed = tonumber(l.properties.speed) groupLayer.xOffset = 0 end if l.properties.yFactor then groupLayer.yFactor = tonumber(l.properties.yFactor) end local tint if l.properties.tintR and l.properties.tintG and l.properties.tintB then tint = {tonumber(l.properties.tintR), tonumber(l.properties.tintG), tonumber(l.properties.tintB)} end local d = l.data local gid for y = 0, h - 1 do for x = 0, w - 1 do gid = d[x + y * w + 1] if gid > 0 then self:newTile{ gid = gid, g = groupLayer, x = x, y = y, tint = tint } end end end elseif l.type == 'objectgroup' then for j = 1, #l.objects do local o = l.objects[j] self:newObject{g = self.physicsGroup, shape = o.shape, x = o.x, y = o.y, width = o.width, height = o.height, polygon = o.polygon } end end end end local function moveCamera(self, x, y) self.camera.x = clamp(x, self.camera.low.x, self.camera.high.x) self.camera.y = clamp(y, self.camera.low.y, self.camera.high.y) end local function moveCameraSmoothly(self, params) self.smoothMovementTransition = transition.to(self.camera, { x = clamp(params.x, self.camera.low.x, self.camera.high.x), y = clamp(params.y, self.camera.low.y, self.camera.high.y), time = params.time or 1000, delay = params.delay or 0, transition = easing.inOutExpo }) end local function snapCameraTo(self, object) self.camera.snappedObject = object if self.smoothMovementTransition then transition.cancel(self.smoothMovementTransition) self.smoothMovementTransition = nil end end local function eachFrame(self) -- Modify camera position local _W, _H, _CX, _CY = relayout._W, relayout._H, relayout._CX, relayout._CY local step = 30 local damping = 0.98 if self.camera.xIncrement ~= 0 or self.camera.yIncrement ~= 0 then self.camera.xIncrement = self.camera.xIncrement * damping if math.abs(self.camera.xIncrement) < 0.02 then self.camera.xIncrement = 0 end self.camera.yIncrement = self.camera.yIncrement * damping if math.abs(self.camera.yIncrement) < 0.02 then self.camera.yIncrement = 0 end self:moveCamera(self.camera.x + self.camera.xIncrement * step, self.camera.y + self.camera.yIncrement * step) elseif self.camera.snappedObject then if self.camera.snappedObject.x then local w, h = _W * 0.33 / 2, _H * 0.33 / 2 -- Object tracking window local oX, oY = self.camera.snappedObject.x, self.camera.snappedObject.y local x, y = self.camera.x + _CX, self.camera.y + _CY x = clamp(x, oX - w, oX + w) y = clamp(y, oY - h, oY + h) self:moveCamera(x - _CX, y - _CY) else self.camera.snappedObject = nil end end -- Adjust layers positions according to the camera self.group.x, self.group.y = -self.camera.x - _CX, -self.camera.y - _CY self.physicsGroup.x, self.physicsGroup.y = -self.camera.x, -self.camera.y for i = 1, #self.layers do local l = self.layers[i] if l.ratio then l.x = self.camera.x - self.camera.x * l.ratio if l.speed then for j = 1, l.numChildren do local object = l[j] local speed = l.speed if l.yFactor then speed = speed / (l.yFactor * object.y / self.map.tileheight) end object.x = object.x + speed if object.x > self.map.width * self.map.tilewidth + object.width then object.x = object.x - self.map.width * self.map.tilewidth - 2 * object.width elseif object.x < -object.width then object.x = object.x + self.map.width * self.map.tilewidth + object.width end end end end end self.snapshot:invalidate() end local function mapXYToPixels(self, x, y) return x * self.map.tilewidth, y * self.map.tileheight end local _M = {} function _M.newTiledMap(params) local tiledMap = { load = load, prepareTilesets = prepareTilesets, getSpriteSheetByGid = getSpriteSheetByGid, newTile = newTile, newObject = newObject, draw = draw, moveCamera = moveCamera, moveCameraSmoothly = moveCameraSmoothly, snapCameraTo = snapCameraTo, eachFrame = eachFrame, mapXYToPixels = mapXYToPixels } tiledMap:load(params) return tiledMap end return _M
local currentPath = debug.getinfo(1, 'S').source:sub(2) local rootPath = currentPath:gsub('[/\\]*[^/\\]-$', '') rootPath = (rootPath == '' and '.' or rootPath) loadfile(rootPath .. '/platform.lua')('script') local fs = require 'bee.filesystem' local function expanduser(path) if path:sub(1, 1) == '~' then local home = os.getenv('HOME') if not home then -- has to be Windows home = os.getenv 'USERPROFILE' or (os.getenv 'HOMEDRIVE' .. os.getenv 'HOMEPATH') end return home .. path:sub(2) else return path end end local function loadArgs() for _, v in ipairs(arg) do local key, value = v:match '^%-%-([%w_]+)%=(.+)' if not key then goto CONTINUE end if value == 'true' then value = true elseif value == 'false' then value = false elseif tonumber(value) then value = tonumber(value) elseif value:sub(1, 1) == '"' and value:sub(-1, -1) == '"' then value = value:sub(2, -2) end _G[key:upper()] = value ::CONTINUE:: end end loadArgs() ROOT = fs.path(expanduser(rootPath)) LOGPATH = LOGPATH and expanduser(LOGPATH) or (ROOT:string() .. '/log') METAPATH = METAPATH and expanduser(METAPATH) or (ROOT:string() .. '/meta') debug.setcstacklimit(200) collectgarbage('generational', 10, 50) -- collectgarbage('incremental', 120, 120, 0) output = function(...) return require('output')(...) end log = require 'log' log.init(ROOT, fs.path(LOGPATH) / 'service.log') log.info('Lua Lsp startup, root: ', ROOT) log.debug('ROOT:', ROOT:string()) log.debug('LOGPATH:', LOGPATH) log.debug('METAPATH:', METAPATH) require 'tracy' xpcall(dofile, log.debug, rootPath .. '/debugger.lua') local service = require 'service' service.start()
return {[1]={["stats"]={[1]="buff_effect_duration"},["name"]="buff_duration",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},["text"]="Banner lasts %1% seconds after being placed",["limit"]={[1]={[1]=1,[2]="#"}}}}}},[2]={["stats"]={[1]="banner_add_stage_on_impale"},["name"]="banner_add_stage_on_impale",["lang"]={["English"]={[1]={["limit"]={[1]={[1]="#",[2]="#"}},["text"]="Gain 1 Stage when you Impale an Enemy while carrying the Banner, up to 5 per second"}}}},[3]={["stats"]={[1]="banner_add_stage_on_kill"},["name"]="banner_add_stage_on_kill",["lang"]={["English"]={[1]={["limit"]={[1]={[1]="#",[2]="#"}},["text"]="Gain 1 Stage when you Kill an Enemy while carrying the Banner"}}}},[4]={["stats"]={[1]="banner_additional_base_duration_per_stage_ms"},["name"]="banner_stage_duration",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds",["v"]=1},["text"]="%1$+d second to Base Placed Banner Duration per Stage",["limit"]={[1]={[1]=1000,[2]=1000}}},[2]={[1]={["k"]="milliseconds_to_seconds",["v"]=1},["text"]="%1$+d seconds to Base Placed Banner Duration per Stage",["limit"]={[1]={[1]="#",[2]="#"}}}}}},[5]={["stats"]={[1]="banner_area_of_effect_+%_per_stage"},["name"]="banner_stage_aoe",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="When placed, %1%%% increased Area of Effect per Stage"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="When placed, %1%%% reduced Area of Effect per Stage",["limit"]={[1]={[1]="#",[2]=-1}}}}}},[6]={["stats"]={[1]="banner_buff_effect_+%_per_stage"},["name"]="banner_stage_aura_effect",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="When placed, %1%%% increased Aura effect per Stage"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="When placed, %1%%% reduced Aura effect per Stage",["limit"]={[1]={[1]="#",[2]=-1}}}}}},[7]={["stats"]={[1]="base_skill_effect_duration"},["name"]="base_duration_identifier",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},["text"]="Base Duration of %1% seconds after being Placed",["limit"]={[1]={[1]="#",[2]="#"}}}}}},[8]={["stats"]={[1]="bloodstained_banner_adrenaline_duration_per_stage_ms"},["name"]="war_banner_adrenaline",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextAdrenaline"},["text"]="Gain Adrenaline for %1% second per Stage on Placing the Banner",["limit"]={[1]={[1]=1000,[2]=1000}}},[2]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextAdrenaline"},["text"]="Gain Adrenaline for %1% seconds per Stage on Placing the Banner",["limit"]={[1]={[1]="#",[2]="#"}}}}}},["puresteel_banner_accuracy_rating_+%_final"]=9,["puresteel_banner_fortify_effect_+%_per_stage"]=11,["puresteel_banner_fortify_duration_per_stage_ms"]=10,[11]={["stats"]={[1]="puresteel_banner_fortify_effect_+%_per_stage"},["name"]="dread_banner_fortify_effect",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="%1%%% increased Fortify effect per Stage"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="%1%%% reduced Fortify effect per Stage",["limit"]={[1]={[1]="#",[2]=-1}}}}}},["banner_add_stage_on_kill"]=3,["base_skill_effect_duration"]=7,[9]={["stats"]={[1]="puresteel_banner_accuracy_rating_+%_final"},["name"]="dread_banner_accuracy_final",["lang"]={["English"]={[1]={["limit"]={[1]={[1]=1,[2]="#"}},["text"]="Nearby Enemies have %1%%% more Accuracy Rating"},[2]={[1]={["k"]="negate",["v"]=1},["text"]="Nearby Enemies have %1%%% less Accuracy Rating",["limit"]={[1]={[1]="#",[2]=-1}}}}}},[10]={["stats"]={[1]="puresteel_banner_fortify_duration_per_stage_ms"},["name"]="dread_banner_fortify",["lang"]={["English"]={[1]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextFortify"},["text"]="Gain Fortify for %1% second per Stage on Placing the Banner",["limit"]={[1]={[1]=1000,[2]=1000}}},[2]={[1]={["k"]="milliseconds_to_seconds_2dp",["v"]=1},[2]={["k"]="reminderstring",["v"]="ReminderTextFortify"},["text"]="Gain Fortify for %1% seconds per Stage on Placing the Banner",["limit"]={[1]={[1]="#",[2]="#"}}}}}},["banner_additional_base_duration_per_stage_ms"]=4,["bloodstained_banner_adrenaline_duration_per_stage_ms"]=8,["banner_buff_effect_+%_per_stage"]=6,["buff_effect_duration"]=1,["parent"]="aura_skill_stat_descriptions",["banner_add_stage_on_impale"]=2,["banner_area_of_effect_+%_per_stage"]=5}
return { cmd = {'gopls'}, -- for postfix snippets and analyzers capabilities = capabilities, settings = { gopls = { experimentalPostfixCompletions = true, analyses = { unusedparams = true, shadow = true, }, staticcheck = true, }, }, on_attach = on_attach, }
return function() local ComponentRoot = script.Parent local UIBloxRoot = ComponentRoot.Parent local Roact = require(UIBloxRoot.Parent.Roact) local mockStyleComponent = require(UIBloxRoot.Utility.mockStyleComponent) local Images = require(UIBloxRoot.App.ImageSet.Images) local ModalBottomSheet = require(script.Parent.ModalBottomSheet) describe("lifecycle", function() it("should mount and unmount without issue", function() local element = mockStyleComponent({ ModalBottomSheet = Roact.createElement(ModalBottomSheet, { buttonModels = {}, screenWidth = 100, onDismiss = function() end, }), }) local folder = Instance.new("Folder") local instance = Roact.mount(element, folder) Roact.unmount(instance) folder:Destroy() end) it("should correctly hold what it's given", function() local instanceRef = Roact.createRef() local folder = Instance.new("Folder") local element = mockStyleComponent({ Frame = Roact.createElement("Frame", { [Roact.Ref] = instanceRef, }, { ModalBottomSheet = Roact.createElement(ModalBottomSheet, { onDismiss = function() end, screenWidth = 1000, buttonModels = { { icon = Images["component_assets/circle_17"], text = "someSampleText", }, }, }), }), }) local instance = Roact.mount(element, folder) local modalBottomSheet = instanceRef.current.ModalBottomSheet local button = modalBottomSheet.SheetContent["button 1"] local icon = button.buttonContents:FindFirstChildWhichIsA("ImageLabel") expect(icon.ImageRectOffset).to.equal(Images["component_assets/circle_17"].ImageRectOffset) local text = button.buttonContents:FindFirstChildWhichIsA("TextLabel") expect(text.Text).to.equal("someSampleText") Roact.unmount(instance) end) it("should work correctly when renderRightElement is present", function() local element = mockStyleComponent({ ModalBottomSheet = Roact.createElement(ModalBottomSheet, { onDismiss = function() end, screenWidth = 1000, buttonModels = { { icon = Images["component_assets/circle_17"], text = "someSampleText", renderRightElement = function() return Roact.createElement("Frame", { Size = UDim2.new(1, 0, 1, 0), }) end, }, }, }), }) local folder = Instance.new("Folder") local instance = Roact.mount(element, folder) Roact.unmount(instance) folder:Destroy() end) end) end
SWEP.Cam_Offset_Ang = Angle(0, 0, 0) function SWEP:SelectAnimation(anim) if self:GetState() == ArcCW.STATE_SIGHTS and self.Animations[anim .. "_iron"] then anim = anim .. "_iron" end if self:GetState() == ArcCW.STATE_SIGHTS and self.Animations[anim .. "_sights"] then anim = anim .. "_sights" end if self:GetState() == ArcCW.STATE_SIGHTS and self.Animations[anim .. "_sight"] then anim = anim .. "_sight" end if self:GetState() == ArcCW.STATE_SPRINT and self.Animations[anim .. "_sprint"] then anim = anim .. "_sprint" end if self:InBipod() and self.Animations[anim .. "_bipod"] then anim = anim .. "_bipod" end if self:Clip1() == 0 and self.Animations[anim .. "_empty"] then anim = anim .. "_empty" end if self:GetMalfunctionJam() and self.Animations[anim .. "_jammed"] then anim = anim .. "_jammed" end if !self.Animations[anim] then return end return anim end SWEP.LastAnimStartTime = 0 SWEP.LastAnimFinishTime = 0 function SWEP:PlayAnimationEZ(key, mult, ignorereload) self:PlayAnimation(key, mult, true, 0, false, false, ignorereload, false) end function SWEP:PlayAnimation(key, mult, pred, startfrom, tt, skipholster, ignorereload, absolute) mult = mult or 1 pred = pred or false startfrom = startfrom or 0 tt = tt or false --skipholster = skipholster or false Unused ignorereload = ignorereload or false absolute = absolute or false if !key then return end local ct = CurTime() --pred and CurTime() or UnPredictedCurTime() if self:GetReloading() and !ignorereload then return end if game.SinglePlayer() and SERVER and pred then net.Start("arccw_sp_anim") net.WriteString(key) net.WriteFloat(mult) net.WriteFloat(startfrom) net.WriteBool(tt) --net.WriteBool(skipholster) Unused net.WriteBool(ignorereload) net.Send(self:GetOwner()) end local anim = self.Animations[key] if !anim then return end local tranim = self:GetBuff_Hook("Hook_TranslateAnimation", key) if self.Animations[tranim] then key = tranim anim = self.Animations[tranim] --[[elseif self.Animations[key] then -- Can't do due to backwards compatibility... unless you have a better idea? anim = self.Animations[key] else return]] end if anim.ViewPunchTable and CLIENT then for k, v in pairs(anim.ViewPunchTable) do if !v.t then continue end local st = (v.t * mult) - startfrom if isnumber(v.t) and st >= 0 and self:GetOwner():IsPlayer() and (game.SinglePlayer() or IsFirstTimePredicted()) then self:SetTimer(st, function() self:OurViewPunch(v.p or Vector(0, 0, 0)) end, id) end end end if isnumber(anim.ShellEjectAt) then self:SetTimer(anim.ShellEjectAt * mult, function() local num = 1 if self.RevolverReload then num = self.Primary.ClipSize - self:Clip1() end for i = 1,num do self:DoShellEject() end end) end if !self:GetOwner() then return end if !self:GetOwner().GetViewModel then return end local vm = self:GetOwner():GetViewModel() if !vm then return end if !IsValid(vm) then return end local seq = anim.Source if anim.RareSource and util.SharedRandom("raresource", 1, anim.RareSourceChance or 100, CurTime()/13) <= 1 then seq = anim.RareSource end seq = self:GetBuff_Hook("Hook_TranslateSequence", seq) if istable(seq) then seq["BaseClass"] = nil seq = seq[math.Round(util.SharedRandom("randomseq" .. CurTime(), 1, #seq))] end if isstring(seq) then seq = vm:LookupSequence(seq) end local time = absolute and 1 or self:GetAnimKeyTime(key) --if time == 0 then return end local ttime = (time * mult) - startfrom if startfrom > (time * mult) then return end if tt then self:SetNextPrimaryFire(ct + ((anim.MinProgress or time) * mult) - startfrom) end if anim.LHIK then self.LHIKStartTime = ct self.LHIKEndTime = ct + ttime if anim.LHIKTimeline then self.LHIKTimeline = {} for i, k in pairs(anim.LHIKTimeline) do table.Add(self.LHIKTimeline, {t = (k.t or 0) * mult, lhik = k.lhik or 1}) end else self.LHIKTimeline = { {t = -math.huge, lhik = 1}, {t = ((anim.LHIKIn or 0.1) - (anim.LHIKEaseIn or anim.LHIKIn or 0.1)) * mult, lhik = 1}, {t = (anim.LHIKIn or 0.1) * mult, lhik = 0}, {t = ttime - ((anim.LHIKOut or 0.1) * mult), lhik = 0}, {t = ttime - (((anim.LHIKOut or 0.1) - (anim.LHIKEaseOut or anim.LHIKOut or 0.1)) * mult), lhik = 1}, {t = math.huge, lhik = 1} } if anim.LHIKIn == 0 then self.LHIKTimeline[1].lhik = -math.huge self.LHIKTimeline[2].lhik = -math.huge end if anim.LHIKOut == 0 then self.LHIKTimeline[#self.LHIKTimeline - 1].lhik = math.huge self.LHIKTimeline[#self.LHIKTimeline].lhik = math.huge end end else self.LHIKTimeline = nil end if anim.LastClip1OutTime then self.LastClipOutTime = ct + ((anim.LastClip1OutTime * mult) - startfrom) end if anim.TPAnim then local aseq = self:GetOwner():SelectWeightedSequence(anim.TPAnim) if aseq then self:GetOwner():AddVCDSequenceToGestureSlot( GESTURE_SLOT_ATTACK_AND_RELOAD, aseq, anim.TPAnimStartTime or 0, true ) if !game.SinglePlayer() and SERVER then net.Start("arccw_networktpanim") net.WriteEntity(self:GetOwner()) net.WriteUInt(aseq, 16) net.WriteFloat(anim.TPAnimStartTime or 0) net.SendPVS(self:GetOwner():GetPos()) end end end if !(game.SinglePlayer() and CLIENT) then self:PlaySoundTable(anim.SoundTable or {}, 1 / mult, startfrom) end if seq then vm:SendViewModelMatchingSequence(seq) local dur = vm:SequenceDuration() vm:SetPlaybackRate(math.Clamp(dur / (ttime + startfrom), -4, 12)) self.LastAnimStartTime = ct self.LastAnimFinishTime = ct + (dur) end local att = self:GetBuff_Override("Override_CamAttachment") or self.CamAttachment -- why is this here if we just... do cool stuff elsewhere? if att and vm:GetAttachment(att) then local ang = vm:GetAttachment(att).Ang ang = vm:WorldToLocalAngles(ang) self.Cam_Offset_Ang = Angle(ang) end self:SetNextIdle(CurTime() + ttime) end function SWEP:PlayIdleAnimation(pred) local ianim local s = self:GetBuff_Override("Override_ShootWhileSprint") or self.ShootWhileSprint if self:GetState() == ArcCW.STATE_SPRINT and !s then ianim = self:SelectAnimation("idle_sprint") or ianim end if self:InBipod() then ianim = self:SelectAnimation("idle_bipod") or ianim end if (self.Sighted or self:GetState() == ArcCW.STATE_SIGHTS) then ianim = self:SelectAnimation("idle_sight") or self:SelectAnimation("idle_sights") or ianim end if self:GetState() == ArcCW.STATE_CUSTOMIZE then ianim = self:SelectAnimation("idle_inspect") or ianim end -- (key, mult, pred, startfrom, tt, skipholster, ignorereload) if self:GetBuff_Override("UBGL_BaseAnims") and self:GetInUBGL() and self.Animations.idle_ubgl_empty and self:Clip2() <= 0 then ianim = "idle_ubgl_empty" elseif self:GetBuff_Override("UBGL_BaseAnims") and self:GetInUBGL() and self.Animations.idle_ubgl then ianim = "idle_ubgl" elseif (self:Clip1() == 0 or self:GetNeedCycle()) and self.Animations.idle_empty then ianim = ianim or "idle_empty" else ianim = ianim or "idle" end self:PlayAnimation(ianim, 1, pred, nil, nil, nil, true) end function SWEP:GetAnimKeyTime(key, min) if !self:GetOwner() then return 1 end local anim = self.Animations[key] if !anim then return 1 end if self:GetOwner():IsNPC() then return anim.Time or 1 end local vm = self:GetOwner():GetViewModel() if !vm or !IsValid(vm) then return 1 end local t = anim.Time if !t then local tseq = anim.Source if istable(tseq) then tseq["BaseClass"] = nil -- god I hate Lua inheritance tseq = tseq[1] end if !tseq then return 1 end tseq = vm:LookupSequence(tseq) -- to hell with it, just spits wrong on draw sometimes t = vm:SequenceDuration(tseq) or 1 end if min and anim.MinProgress then t = anim.MinProgress end if anim.Mult then t = t * anim.Mult end return t end if CLIENT then net.Receive("arccw_networktpanim", function() local ent = net.ReadEntity() local aseq = net.ReadUInt(16) local starttime = net.ReadFloat() if ent ~= LocalPlayer() then ent:AddVCDSequenceToGestureSlot( GESTURE_SLOT_ATTACK_AND_RELOAD, aseq, starttime, true ) end end) end function SWEP:QueueAnimation() end function SWEP:NextAnimation() end
print(8 * 9, 9 / 8) a = math.sin(3) + math.cos(10) print(os.date())
-- Unit Handler Server Script -- -- Retrieve Unit Data RegisterServerEvent("getUnitData") RegisterServerEvent("returnUnitData") AddEventHandler("getUnitData", function(playerId) local steamHex = nil local unitId; local unitType; local identifiers = GetPlayerIdentifiers(playerId) for _, identifier in next, identifiers do if string.find(identifier, "steam:") then steamHex = identifier break end end steamHex = steamHex MySQL.Async.fetchAll("SELECT 1 FROM FiveM_UnitHandler.unit_data WHERE steam_hex = @steamHex;", {["@steamHex"] = steamHex}, function(result) if result[1] == nil then MySQL.Async.fetchAll("INSERT INTO FiveM_UnitHandler.unit_data (steam_hex, unit_id, unit_type) VALUES (@steamHex, @uid, @utype);", {["@steamHex"] = steamHex, ["@uid"] = "000", ["@utype"] = "leo"}, function(result) unitId = "000" unitType = "leo" TriggerClientEvent("returnUnitData", playerId, unitId, unitType) end) else MySQL.Async.fetchAll("SELECT * FROM FiveM_UnitHandler.unit_data WHERE steam_hex = @steamHex;", {["@steamHex"] = steamHex}, function(result) unitId = result[1].unit_id unitType = result[1].unit_type TriggerClientEvent("returnUnitData", playerId, unitId, unitType) end) end end) end) -- Update Unit Id RegisterServerEvent("updateUnitId") RegisterServerEvent("returnUnitId") AddEventHandler("updateUnitId", function(playerId, unitId) local steamHex = nil local unitId; local unitType; local identifiers = GetPlayerIdentifiers(playerId) for _, identifier in next, identifiers do if string.find(identifier, "steam:") then steamHex = identifier break end end steamHex = steamHex MySQL.Async.fetchAll("FiveM_UnitHandler.unit_data SET unit_id = @uid WHERE steam_hex = @steamHex;", {["uid"] = unitId, ["@steamHex"] = steamHex}, function(result) TriggerClientEvent("returnUnitId", playerId, unitId) end) end) -- Update Unit Type RegisterServerEvent("updateUnitType") RegisterServerEvent("returnUnitType") AddEventHandler("updateUnitType", function(playerId, unitType) local steamHex = nil local unitId; local unitType; local identifiers = GetPlayerIdentifiers(playerId) for _, identifier in next, identifiers do if string.find(identifier, "steam:") then steamHex = identifier break end end steamHex = steamHex MySQL.Async.fetchAll("FiveM_UnitHandler.unit_data SET unit_id = @uid WHERE steam_hex = @steamHex;", {["uid"] = unitId, ["@steamHex"] = steamHex}, function(result) TriggerClientEvent("returnUnitId", playerId, unitId) end) end)
local status, telescope = pcall(require, 'telescope') if not status then return end local actions = require('telescope.actions') local map = vim.api.nvim_set_keymap local N = { noremap = true, silent= true } telescope.setup{ defaults = { prompt_prefix = "", mappings = { n = { ["q"] = actions.close }, }, file_ignore_patterns = { "node_modules" } } } _G.telescope_live_grep_in_path = function(path) local _path = path or vim.fn.input("Dir: ", "", "dir") require("telescope.builtin").live_grep({search_dirs = {_path}}) end map('n', '<leader>ff', ':lua require("telescope.builtin").find_files()<cr>', N) map('n', '<leader>fg', ':lua require("telescope.builtin").live_grep()<cr>', N) map('n', '<leader>fh', ':lua require("telescope.builtin").help_tags()<cr>', N)
function CreateTexturedCircle(image) segments = segments or 40 local vertices = {} -- The first vertex is at the center, and has a red tint. We're centering the circle around the origin (0, 0). table.insert(vertices, {0, 0, 0.5, 0.5, 255, 255, 255}) -- Create the vertices at the edge of the circle. for i=0, segments do local angle = (i / segments) * math.pi * 2 -- Unit-circle. local x = math.cos(angle) local y = math.sin(angle) -- Our position is in the range of [-1, 1] but we want the texture coordinate to be in the range of [0, 1]. local u = (x + 1) * 0.5 local v = (y + 1) * 0.5 -- The per-vertex color defaults to white. table.insert(vertices, {x, y, u, v}) end -- The "fan" draw mode is perfect for our circle. local mesh = love.graphics.newMesh(vertices, "fan", "dynamic") mesh:setTexture(image) return mesh end -- Creation du canevas de l'explosion function initExplosionCanvas (width, height) local c = love.graphics.newCanvas(width, height) love.graphics.setCanvas(c) -- Switch to drawing on canvas 'c' love.graphics.setBlendMode("alpha") love.graphics.setColor(255, 64, 64, 255) love.graphics.circle("fill", width / 2, height / 2, 10, 100) love.graphics.setCanvas() -- Switch back to drawing on main screen return c end -- Systeme de particules de l'explosion function initPartSys (image, maxParticles) local ps = love.graphics.newParticleSystem(image, maxParticles) ps:setParticleLifetime(0.1, 0.5) -- (min, max) ps:setSizeVariation(1) ps:setLinearAcceleration(-400, -400, 400, 400) -- (minX, minY, maxX, maxY) ps:setColors(255, 64, 64, 255, 255, 0, 0, 255) -- (r1, g1, b1, a1, r2, g2, b2, a2 ...) return ps end function love.load() -- Chargement des éléments du jeu playerShip = love.graphics.newImage("resources/player.png") asteroidTexture = love.graphics.newImage("resources/asteroid.png") asteroidMesh = CreateTexturedCircle(asteroidTexture) -- Definition des variables globales version = 0.001 screenWidth, screenHeight = love.graphics.getDimensions( ) playerX = screenWidth / 2 playerY = screenHeight / 2 playerSpeedX = 0 playerSpeedY = 0 playerR = math.pi / 2 playerSize = 64 vitesseR = 10 vitesseMax = 100 vitesseTir = 500 dureeTir = 4 currVies = -1 tirs = {} love.graphics.setFont(love.graphics.newFont(32)) score = 0 nbTirMax = 8 -- Definition des asteroides asteroids = { } asteroidRadius = 120 tailleTir = 5 -- Configuration des asteroides configAsteroides = { { vitesse = 120, rayon = 30, score = 800 }, { vitesse = 70, rayon = 50, score = 400 }, { vitesse = 50, rayon = 70, score = 200 }, { vitesse = 20, rayon = 120, score = 100 } } -- Initialisation des directions for asteroidIndex, asteroid in ipairs(asteroids) do asteroid.angle = love.math.random() * (2 * math.pi) asteroid.niveau = #configAsteroides end -- Gestion du joystick local joysticks = love.joystick.getJoysticks() if #joysticks > 0 then joystick = joysticks[1] else joystick = false end lastbutton = "none" -- Canevas de l'explosion canvas = initExplosionCanvas(20, 40) explosions = {} end function love.draw() if currVies >= 0 then for y = -1, 1 do for x = -1, 1 do love.graphics.origin() love.graphics.translate(x * screenWidth, y * screenHeight) -- RAZ des couleurs love.graphics.setColor(255, 255, 255, 255) -- Dessiner la vaisseau love.graphics.draw(playerShip, playerX, playerY, playerR, 1, 1, playerSize, playerSize) -- Tirs for tirIndex, tir in ipairs(tirs) do love.graphics.setColor(0, 1, 0) love.graphics.circle('fill', tir.x, tir.y, tailleTir) end -- Asteroides for asteroidIndex, asteroid in ipairs(asteroids) do love.graphics.setColor(1, 1, 0) love.graphics.draw(asteroidMesh, asteroid.x, asteroid.y, asteroid.r, configAsteroides[asteroid.niveau].rayon, configAsteroides[asteroid.niveau].rayon) --love.graphics.circle(asteroidMesh, asteroid.x, asteroid.y, configAsteroides[asteroid.niveau].rayon) end -- nombre de vies for nbVies = 0, currVies do -- RAZ des couleurs love.graphics.setColor(255, 255, 255, 255) -- Dessiner la vaisseau our les vies love.graphics.draw(playerShip, nbVies * playerSize, screenHeight, (1.5 * math.pi), 0.25, 0.25, - (playerSize), -(playerSize)) end -- Explosions for expIndex, explosion in ipairs(explosions) do -- Try different blend modes out - https://love2d.org/wiki/BlendMode love.graphics.setBlendMode("add") -- Redraw particle system every frame love.graphics.draw(explosion.ps) end -- Score love.graphics.print("Score : " .. score, screenWidth, screenHeight, 0, 1, 1, screenWidth / 4, 50) end end else --local joysticks = love.joystick.getJoysticks() --for i, joystick in ipairs(joysticks) do -- love.graphics.print(joystick:getName(), 10, (i + 1) * 20) --end --love.graphics.print("Last gamepad button pressed: "..lastbutton, 10, 10) -- Texte love.graphics.print("Appuyer sur Espace pour commencer", screenWidth / 4, screenHeight / 2, 0, 1, 1, 0, 0) -- Score love.graphics.print("Score : " .. score, screenWidth, screenHeight, 0, 1, 1, screenWidth / 4, 50) end end function love.update(dt) -- Animation des explosions for expIndex, explosion in ipairs(explosions) do -- MAJ du système explosion.ps:update(dt) explosion.lt = explosion.lt - dt if explosion.lt < 0 then table.remove(explosions, expIndex) end end -- Contrôle des collisions - Merci Pythagore local function checkCollision(aX, aY, aRadius, bX, bY, bRadius) return (aX - bX)^2 + (aY - bY)^2 <= (aRadius + bRadius)^2 end -- Rotation vers la droite if love.keyboard.isDown('right') or (joystick and joystick:isGamepadDown("dpright")) then playerR = playerR + vitesseR * dt end -- Idem vers la gauche if love.keyboard.isDown('left') or (joystick and joystick:isGamepadDown("dpleft")) then playerR = playerR - vitesseR * dt end -- Limiter entre 0 et 2Pi (Radians) playerR = playerR % (2 * math.pi) -- Déplacement vaisseau -- Calul de la vitesse if love.keyboard.isDown('up') or (joystick and joystick:isGamepadDown("dpup")) then local vitesseMax = 100 playerSpeedX = playerSpeedX + math.cos(playerR) * vitesseMax * dt playerSpeedY = playerSpeedY + math.sin(playerR) * vitesseMax * dt end -- Calcul de la nouvelle position du vaisseau playerX = (playerX + playerSpeedX * dt) % screenWidth playerY = (playerY + playerSpeedY * dt) % screenHeight -- Calcul du déplacement des tirs for tirIndex, tir in ipairs(tirs) do -- On retire du temps de vie au tir tir.duree = tir.duree - dt -- Si temps de tir = 0, suppression if tir.duree <= 0 then table.remove(tirs, tirIndex) else -- Sinon déplacement tir.x = (tir.x + math.cos(tir.r) * vitesseTir * dt) % screenWidth tir.y = (tir.y + math.sin(tir.r) * vitesseTir * dt) % screenHeight end end -- Calcul du déplacement des asteroides for asteroidIndex, asteroid in ipairs(asteroids) do asteroid.x = (asteroid.x + math.cos(asteroid.angle) * configAsteroides[asteroid.niveau].vitesse * dt) % screenWidth asteroid.y = (asteroid.y + math.sin(asteroid.angle) * configAsteroides[asteroid.niveau].vitesse * dt) % screenHeight -- Rotation asteroid asteroid.r = asteroid.r + dt -- Contrôle collisions avec le vaisseau if checkCollision( playerX, playerY, playerSize, asteroid.x, asteroid.y, configAsteroides[asteroid.niveau].rayon ) then newLife() break end -- Contrôle collisions avec les tirs for tirIndex, tir in ipairs(tirs) do if checkCollision( tir.x, tir.y, tailleTir, asteroid.x, asteroid.y, configAsteroides[asteroid.niveau].rayon ) then -- Metttre à jour le score score = score + configAsteroides[asteroid.niveau].score --Son de l'explision local explosionSound = love.audio.newSource("resources/explosion.mp3", "static") explosionSound:play() -- Effet explision currentExplosion = initPartSys (canvas, 1500) currentExplosion:setPosition(asteroid.x, asteroid.y) currentExplosion:setEmitterLifetime(0.25) currentExplosion:setEmissionRate(3000) table.insert(explosions, {ps = currentExplosion, lt = 2}) -- Retirer le Tir table.remove(tirs, tirIndex) -- Générer de nouveaux asteroides if asteroid.niveau > 1 then local angle1 = love.math.random() * (2 * math.pi) local angle2 = (angle1 - 2*math.pi/3) % (2 * math.pi) local angle3 = (angle1 + 2*math.pi/3) % (2 * math.pi) table.insert(asteroids, { x = asteroid.x, y = asteroid.y, angle = angle1, r = angle1, niveau = asteroid.niveau - 1 }) table.insert(asteroids, { x = asteroid.x, y = asteroid.y, angle = angle2, r = angle2, niveau = asteroid.niveau - 1 }) table.insert(asteroids, { x = asteroid.x, y = asteroid.y, angle = angle3, r = angle3, niveau = asteroid.niveau - 1 }) end -- Retirer l'asteroid table.remove(asteroids, asteroidIndex) break end end end end -- Fonction de détection des touches function love.keypressed(key) -- ECHAP => Fermeture programme if key == 'escape' then love.event.quit() end -- ESPACE => Tir if key == 'space' and currVies >= 0 and #tirs < nbTirMax then fireLaser() end -- ESPACE => lancement partie if key == 'space' and currVies < 0 then resetGame() end end -- Idem pour le Joystick function love.gamepadpressed(joystick, button) lastbutton = button -- ESPACE => Tir if button == 'a' and currVies >= 0 and #tirs < nbTirMax then fireLaser() end -- ESPACE => lancement partie if button == 'a' and currVies < 0 then resetGame() end end function fireLaser() local laserSound = love.audio.newSource("resources/laser.ogg", "static") table.insert(tirs, { x = playerX + math.cos(playerR) * playerSize, y = playerY + math.sin(playerR) * playerSize, r = playerR, duree = dureeTir }) laserSound:play() end -- Fonction pour relancer la partie function resetGame() currVies = 3 score = 0 newLife() end -- Fonction pour relancer la partie function newLife() currVies = currVies - 1 -- Definition des variables globales playerX = screenWidth / 2 playerY = screenHeight / 2 playerSpeedX = 0 playerSpeedY = 0 playerR = math.pi / 2 tirs = {} -- Definition des asteroides asteroids = { { x = 150, y = 150, r = 0 }, { x = screenWidth - 150, y = 150, r = 0 }, { x = screenWidth / 2, y = screenHeight - 150, r = 0 }, } -- Initialisation des directions for asteroidIndex, asteroid in ipairs(asteroids) do asteroid.angle = love.math.random() * (2 * math.pi) asteroid.niveau = #configAsteroides end end
object_draft_schematic_weapon_component_new_weapon_comp_scope = object_draft_schematic_weapon_component_shared_new_weapon_comp_scope:new { } ObjectTemplates:addTemplate(object_draft_schematic_weapon_component_new_weapon_comp_scope, "object/draft_schematic/weapon/component/new_weapon_comp_scope.iff")
-- -- Copyright (c) 2018 Milos Tosic. All rights reserved. -- License: http://www.opensource.org/licenses/BSD-2-Clause -- function projectDependencies_MTuner() return { "rmem", "rdebug", "rqt" } end function projectExtraConfig_MTuner() configuration { "*-gcc* or osx" } buildoptions { "-fopenmp", } configuration {} end function projectExtraConfigExecutable_MTuner() if getTargetOS() == "linux" or getTargetOS() == "osx" then links { "gomp", } end configuration {} end function projectAdd_MTuner() addProject_qt("MTuner") end
--[[ Copyright (C) 2018 Kubos Corporation 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 uv = require 'uv' local dump = require('pretty-print').dump local Editor = require('readline').Editor local cbor = require 'cbor' local byte = string.byte local usage = [[ Kubos CBOR Client This is a tiny tool that provides a line interface to CBOR-UDP services. It can talk to local services or remote services through the communications bridge. Type messages in lua syntax and they will be parsed as lua, encoded as cbor and sent over the wire. Responses will be parsed as cbor and printed as lua. Usage: kubos-cbor-client $service_port ]] local port = args[1] port = port and tonumber(port) if not port then print(usage) return -1 end local editor = Editor.new {} local prompt = 'udp:' .. port .. '> ' local udp = uv.new_udp() assert(udp:bind('127.0.0.1', 0)) local function on_line(err, line, reason) assert(not err, err) if reason == 'EOF in readLine' then print 'Exiting...' udp:recv_stop() udp:close() return end local fn, error = loadstring('return ' .. line) if not fn then editor:insertAbove(error) else setfenv(fn, {}) local success, value = pcall(fn) if success then editor:insertAbove('Client: ' .. dump(value)) udp:send('\x00' .. cbor.encode(value), '127.0.0.1', port) else editor:insertAbove(value) end end editor:readLine(prompt, on_line) end udp:recv_start(function (err, data) assert(not err, err) if not data then return end if byte(data, 1) == 0 then local value = cbor.decode(data, 2) editor:insertAbove('Server: ' .. dump(value)) end end) editor:readLine(prompt, on_line) uv.run()
Script.Load("lua/CPPGUIDamageXPNotifier.lua") GUINotifications.kScoreDisplayFontNameLarge = Fonts.kAgencyFB_Large GUINotifications.kScoreDisplayPrimaryTextColor = Color(0.2, 0.71, 0.86, 1) GUINotifications.kScoreDisplayBuildTextColor = Color(0, 1, 0, 1) GUINotifications.kScoreDisplayWeldTextColor = Color(0.73, 0.22, 0.84, 1) GUINotifications.kScoreDisplayHealTextColor = Color(0.84, 0.18, 0.49, 1) GUINotifications.kScoreDisplayFontHeight = 100 GUINotifications.kScoreDisplayMinFontHeight = 80 GUINotifications.kScoreDisplayPopTimer = 0.35 GUINotifications.kScoreDisplayFadeoutTimer = 3 GUINotifications.kScoreDisplayFontHeightDmg = 60 GUINotifications.kScoreDisplayMinFontHeightDmg = 40 GUINotifications.kTimeToDisplayFinalAccumulatedValue = 2 local kResetSourceTypes = { [kXPSourceType.Kill] = true, [kXPSourceType.Assist] = true, [kXPSourceType.Nearby] = true, [kXPSourceType.Build] = true, } local kAccumulatingSourceTypes = { [kXPSourceType.Weld] = true, [kXPSourceType.Heal] = true } local ns2_GUINotifications_Initialize = GUINotifications.Initialize function GUINotifications:Initialize() self.damageXPNotifiers = { CreateDamageXPNotifier(), CreateDamageXPNotifier(), CreateDamageXPNotifier(), CreateDamageXPNotifier(), CreateDamageXPNotifier(), CreateDamageXPNotifier() } self.isAnimating = false self.xpSinceReset = 0 self.lastSourceType = kXPSourceType.Kill self.timeLastAccumulated = 0 ns2_GUINotifications_Initialize(self) end local ns2_GUINotifications_Uninitialize = GUINotifications.Uninitialize function GUINotifications:Uninitialize() for index, value in pairs(self.damageXPNotifiers) do value:Uninitialize() end ns2_GUINotifications_Uninitialize(self) end function GUINotifications:GetAvailableDmgXPNotifier() local dmgXPNotifier = nil for index, value in ipairs(self.damageXPNotifiers) do if dmgXPNotifier == nil then dmgXPNotifier = value elseif value.timeLastUsed < dmgXPNotifier.timeLastUsed then dmgXPNotifier = value end end return dmgXPNotifier end function GUINotifications:UpdateCombatScoreDisplay(deltaTime) PROFILE("GUINotifications:UpdateScoreDisplay") self.updateInterval = kUpdateIntervalFull if self.scoreDisplayFadeoutTime > 0 then self.scoreDisplayFadeoutTime = math.max(0, self.scoreDisplayFadeoutTime - deltaTime) local fadeRate = 1 - (self.scoreDisplayFadeoutTime / GUINotifications.kScoreDisplayFadeoutTimer) local fadeColor = self.scoreDisplay:GetColor() fadeColor.a = 1 fadeColor.a = fadeColor.a - (fadeColor.a * fadeRate) self.scoreDisplay:SetColor(fadeColor) if self.scoreDisplayFadeoutTime == 0 then self.scoreDisplay:SetIsVisible(false) self.isAnimating = false end end if self.scoreDisplayPopdownTime > 0 then self.scoreDisplayPopdownTime = math.max(0, self.scoreDisplayPopdownTime - deltaTime) local popRate = self.scoreDisplayPopdownTime / GUINotifications.kScoreDisplayPopTimer local fontSize = GUINotifications.kScoreDisplayMinFontHeight + ((GUINotifications.kScoreDisplayFontHeight - GUINotifications.kScoreDisplayMinFontHeight) * popRate) local scale = GUIScale(fontSize / GUINotifications.kScoreDisplayFontHeight) self.scoreDisplay:SetScale(Vector(scale, scale, scale)) if self.scoreDisplayPopdownTime == 0 then self.scoreDisplayFadeoutTime = GUINotifications.kScoreDisplayFadeoutTimer end end if self.scoreDisplayPopupTime > 0 then self.scoreDisplayPopupTime = math.max(0, self.scoreDisplayPopupTime - deltaTime) local popRate = 1 - (self.scoreDisplayPopupTime / GUINotifications.kScoreDisplayPopTimer) local fontSize = GUINotifications.kScoreDisplayMinFontHeight + ((GUINotifications.kScoreDisplayFontHeight - GUINotifications.kScoreDisplayMinFontHeight) * popRate) local scale = GUIScale(fontSize / GUINotifications.kScoreDisplayFontHeight) self.scoreDisplay:SetScale(Vector(scale, scale, scale)) if self.scoreDisplayPopupTime == 0 then self.scoreDisplayPopdownTime = GUINotifications.kScoreDisplayPopTimer end end local xp, source, targetId = CombatScoreDisplayUI_GetNewXPAward() if xp > 0 then if source == kXPSourceType.Damage then self:GetAvailableDmgXPNotifier():SetDisplayXP(xp) else if self.isAnimating ~= true then -- Restart the animation sequence. self:ResetAnimationSequence() end -- We want to see the the exact xp for certain source types (not accumulated) if kResetSourceTypes[source] or kResetSourceTypes[self.lastSourceType] then self:ResetAnimationSequence() end if kAccumulatingSourceTypes[source] then self.xpSinceReset = self.xpSinceReset + xp self.timeLastAccumulated = Shared.GetTime() -- earned more xp while numbers are on screen.. keep them there if self.scoreDisplayPopupTime == 0 then self.scoreDisplayPopdownTime = GUINotifications.kScoreDisplayPopTimer end else self.xpSinceReset = xp end self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayPrimaryTextColor) self.scoreDisplay:SetText(string.format("+%s XP", self.xpSinceReset)) if source == kXPSourceType.Damage then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayTextColor) self.scoreDisplay:SetText(string.format("+%s XP", self.xpSinceReset)) elseif source == kXPSourceType.Weld then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayWeldTextColor) self.scoreDisplay:SetText(string.format("+%s XP", self.xpSinceReset)) elseif source == kXPSourceType.Heal then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayHealTextColor) self.scoreDisplay:SetText(string.format("+%s XP", self.xpSinceReset)) elseif source == kXPSourceType.Build then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayBuildTextColor) self.scoreDisplay:SetText(string.format("Built Structure +%s XP", self.xpSinceReset)) elseif source == kXPSourceType.Kill then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayPrimaryTextColor) self.scoreDisplay:SetText(string.format("Kill +%s XP", self.xpSinceReset)) elseif source == kXPSourceType.Assist then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayPrimaryTextColor) self.scoreDisplay:SetText(string.format("Assist +%s XP", self.xpSinceReset)) elseif source == kXPSourceType.Nearby then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayPrimaryTextColor) self.scoreDisplay:SetText(string.format("Nearby Kill +%s XP", self.xpSinceReset)) end self.scoreDisplay:SetScale(GUIScale(Vector(0.7, 0.7, 0.7))) self.scoreDisplay:SetIsVisible(self.visible) self.lastSourceType = source end elseif kAccumulatingSourceTypes[self.lastSourceType] and self.timeLastAccumulated ~= 0 and (Shared.GetTime() - self.timeLastAccumulated) >= GUINotifications.kTimeToDisplayFinalAccumulatedValue then local totalXp = self.xpSinceReset self:ResetAnimationSequence() if self.lastSourceType == kXPSourceType.Weld then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayPrimaryTextColor) self.scoreDisplay:SetText(string.format("Welded Target +%s XP", totalXp)) elseif self.lastSourceType == kXPSourceType.Heal then self.scoreDisplay:SetColor(GUINotifications.kScoreDisplayPrimaryTextColor) self.scoreDisplay:SetText(string.format("Healed Target +%s XP", totalXp)) end self.scoreDisplay:SetScale(GUIScale(Vector(0.7, 0.7, 0.7))) self.scoreDisplay:SetIsVisible(self.visible) self.timeLastAccumulated = 0 end end function GUINotifications:ResetAnimationSequence() -- Restart the animation sequence. self.scoreDisplayPopupTime = GUINotifications.kScoreDisplayPopTimer self.isAnimating = true self.scoreDisplayPopdownTime = 0 self.scoreDisplayFadeoutTime = 0 self.xpSinceReset = 0 end function GUINotifications:Update(deltaTime) PROFILE("GUINotifications:Update") GUIAnimatedScript.Update(self, deltaTime) -- The commander has their own location text. if PlayerUI_IsACommander() or PlayerUI_IsOnMarineTeam() then self.locationText:SetIsVisible(false) else self.locationText:SetIsVisible(self.visible) self.locationText:SetText(PlayerUI_GetLocationName()) end self:UpdateCombatScoreDisplay(deltaTime) for index, value in ipairs(self.damageXPNotifiers) do value:Update(deltaTime) end end
-- -- RemDebug 1.0 Beta -- Copyright Kepler Project 2005 (http://www.keplerproject.org/remdebug) -- local socket = require"socket" local lfs = require"lfs" local debug = require"debug" module("remdebug.engine", package.seeall) _COPYRIGHT = "2006 - Kepler Project" _DESCRIPTION = "Remote Debugger for the Lua programming language" _VERSION = "1.0" local coro_debugger local events = { BREAK = 1, WATCH = 2 } local breakpoints = {} local watches = {} local step_into = false local step_over = false local step_level = 0 local stack_level = 0 local controller_host = "localhost" local controller_port = 8171 local function set_breakpoint(file, line) if not breakpoints[file] then breakpoints[file] = {} end breakpoints[file][line] = true end local function remove_breakpoint(file, line) if breakpoints[file] then breakpoints[file][line] = nil end end local function has_breakpoint(file, line) return breakpoints[file] and breakpoints[file][line] end local function restore_vars(vars) if type(vars) ~= 'table' then return end local func = debug.getinfo(3, "f").func local i = 1 local written_vars = {} while true do local name = debug.getlocal(3, i) if not name then break end debug.setlocal(3, i, vars[name]) written_vars[name] = true i = i + 1 end i = 1 while true do local name = debug.getupvalue(func, i) if not name then break end if not written_vars[name] then debug.setupvalue(func, i, vars[name]) written_vars[name] = true end i = i + 1 end end local function capture_vars() local vars = {} local func = debug.getinfo(3, "f").func local i = 1 while true do local name, value = debug.getupvalue(func, i) if not name then break end vars[name] = value i = i + 1 end i = 1 while true do local name, value = debug.getlocal(3, i) if not name then break end vars[name] = value i = i + 1 end setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) }) return vars end local function break_dir(path) local paths = {} path = string.gsub(path, "\\", "/") for w in string.gfind(path, "[^\/]+") do table.insert(paths, w) end return paths end local function merge_paths(path1, path2) local paths1 = break_dir(path1) local paths2 = break_dir(path2) for i, path in ipairs(paths2) do if path == ".." then table.remove(paths1, table.getn(paths1)) elseif path ~= "." then table.insert(paths1, path) end end return table.concat(paths1, "/") end local function debug_hook(event, line) if event == "call" then stack_level = stack_level + 1 elseif event == "return" then stack_level = stack_level - 1 else local file = debug.getinfo(2, "S").source if string.find(file, "@") == 1 then file = string.sub(file, 2) end file = merge_paths(lfs.currentdir(), file) local vars = capture_vars() table.foreach(watches, function (index, value) setfenv(value, vars) local status, res = pcall(value) if status and res then coroutine.resume(coro_debugger, events.WATCH, vars, file, line, index) end end) if step_into or (step_over and stack_level <= step_level) or has_breakpoint(file, line) then step_into = false step_over = false coroutine.resume(coro_debugger, events.BREAK, vars, file, line) restore_vars(vars) end end end local function debugger_loop(server) local command local eval_env = {} while true do local line, status = server:receive() command = string.sub(line, string.find(line, "^[A-Z]+")) if command == "SETB" then local _, _, _, filename, line = string.find(line, "^([A-Z]+)%s+([%w%p]+)%s+(%d+)$") if filename and line then set_breakpoint(filename, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "DELB" then local _, _, _, filename, line = string.find(line, "^([A-Z]+)%s+([%w%p]+)%s+(%d+)$") if filename and line then remove_breakpoint(filename, tonumber(line)) server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "EXEC" then local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$") if chunk then local func = loadstring(chunk) local status, res if func then setfenv(func, eval_env) status, res = xpcall(func, debug.traceback) end res = tostring(res) if status then server:send("200 OK " .. string.len(res) .. "\n") server:send(res) else server:send("401 Error in Expression " .. string.len(res) .. "\n") server:send(res) end else server:send("400 Bad Request\n") end elseif command == "SETW" then local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)$") if exp then local func = loadstring("return(" .. exp .. ")") local newidx = table.getn(watches) + 1 watches[newidx] = func table.setn(watches, newidx) server:send("200 OK " .. newidx .. "\n") else server:send("400 Bad Request\n") end elseif command == "DELW" then local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)$") index = tonumber(index) if index then watches[index] = nil server:send("200 OK\n") else server:send("400 Bad Request\n") end elseif command == "RUN" then server:send("200 OK\n") local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. line .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") else server:send("401 Error in Execution " .. string.len(file) .. "\n") server:send(file) end elseif command == "STEP" then server:send("200 OK\n") step_into = true local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. line .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") else server:send("401 Error in Execution " .. string.len(file) .. "\n") server:send(file) end elseif command == "OVER" then server:send("200 OK\n") step_over = true step_level = stack_level local ev, vars, file, line, idx_watch = coroutine.yield() eval_env = vars if ev == events.BREAK then server:send("202 Paused " .. file .. " " .. line .. "\n") elseif ev == events.WATCH then server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n") else server:send("401 Error in Execution " .. string.len(file) .. "\n") server:send(file) end else server:send("400 Bad Request\n") end end end coro_debugger = coroutine.create(debugger_loop) -- -- remdebug.engine.config(tab) -- Configures the engine -- function config(tab) if tab.host then controller_host = tab.host end if tab.port then controller_port = tab.port end end -- -- remdebug.engine.start() -- Tries to start the debug session by connecting with a controller -- function start() pcall(require, "remdebug.config") local server = socket.connect(controller_host, controller_port) if server then _TRACEBACK = function (message) local err = debug.traceback(message) server:send("401 Error in Execution " .. string.len(err) .. "\n") server:send(err) server:close() return err end debug.sethook(debug_hook, "lcr") return coroutine.resume(coro_debugger, server) end end
local socket = require "socket" local host, port = "127.0.0.1", "5462" assert(socket.bind(host, port)):close() local sock = socket.tcp() sock:settimeout(0) local ok, err = sock:connect(host, port) assert(not ok) assert('timeout' == err) for i = 1, 10 do -- select pass even if socket has error local _, rec, err = socket.select(nil, {sock}, 1) local _, ss = next(rec) if ss then assert(ss == sock) else assert('timeout' == err, 'unexpected error :' .. tostring(err)) end err = sock:getoption("error") -- i get 'connection refused' on WinXP if err then print("Passed! Error is '" .. err .. "'.") os.exit(0) end end print("Fail! No error detected!") os.exit(1)
local rng = _radiant.math.get_default_rng() local constants = require 'stonehearth.constants' local PopulationFaction = class() function PopulationFaction:get_kingdom_id() return self._data and self._data.kingdom_id end function PopulationFaction:get_kingdom_level_costs() local cache = self._cached_kingdom_level_costs if not cache then cache = radiant.resources.load_json(self._data.kingdom_level_costs or 'tower_defense:data:kingdom_level_costs:default') self._cached_kingdom_level_costs = cache end return cache end function PopulationFaction:get_role_entity_uris(role, gender) return self:_get_citizen_uris_from_role(role, self:get_role_data(role), gender) end function PopulationFaction:_get_citizen_uris_from_role(role, role_data, gender) --If there is no gender, default to male if not role_data[gender] then gender = constants.population.DEFAULT_GENDER end local entities = role_data[gender].uri if not self._sv.is_npc and role_data[gender].uri_pc then entities = role_data[gender].uri_pc end if not entities then error(string.format('role %s in population has no gender table for %s', role, gender)) end return entities end function PopulationFaction:_generate_citizen_from_role(role, role_data, gender) local uris = self:_get_citizen_uris_from_role(role, role_data, gender) local uri = uris[rng:get_int(1, #uris)] return self:create_entity(uri) end return PopulationFaction
local disPlayerNames = 80 local playerDistances = {} local show_id = false RegisterCommand("ids", function(source, args, rawCommand) if args[1] == "papagaiodebotas" then show_id = not show_id end end) local function DrawText3D(x,y,z, text, r,g,b) local onScreen,_x,_y=World3dToScreen2d(x,y,z) local px,py,pz=table.unpack(GetGameplayCamCoords()) local dist = #(vector3(px,py,pz)-vector3(x,y,z)) local scale = 0.3 local fov = (1/GetGameplayCamFov())*100 local scale = scale*fov if onScreen then if not useCustomScale then SetTextScale(0.0*scale, 0.55*scale) else SetTextScale(0.0*scale, customScale) end SetTextFont(0) SetTextProportional(1) SetTextColour(r, g, b, 255) SetTextDropshadow(0, 0, 0, 0, 255) SetTextEdge(2, 0, 0, 0, 150) SetTextDropShadow() SetTextOutline() SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) end end Citizen.CreateThread(function() Wait(500) while true do if show_id then for _, id in ipairs(GetActivePlayers()) do if GetPlayerPed(id) ~= GetPlayerPed(-1) then if playerDistances[id] then if (playerDistances[id] < disPlayerNames) then x2, y2, z2 = table.unpack(GetEntityCoords(GetPlayerPed(id), true)) if NetworkIsPlayerTalking(id) then DrawText3D(x2, y2, z2+1, ""..GetPlayerName(id).."\n (HP:"..GetEntityHealth(GetPlayerPed(id))..")", 247,124,24) DrawMarker(27, x2, y2, z2-0.97, 0, 0, 0, 0, 0, 0, 1.001, 1.0001, 0.5001, 173, 216, 230, 100, 0, 0, 0, 0) else DrawText3D(x2, y2, z2+1, ""..GetPlayerName(id).."\n (HP:"..GetEntityHealth(GetPlayerPed(id))..")", 247,124,24) end elseif (playerDistances[id] < 25) then x2, y2, z2 = table.unpack(GetEntityCoords(GetPlayerPed(id), true)) if NetworkIsPlayerTalking(id) then DrawMarker(27, x2, y2, z2-0.97, 0, 0, 0, 0, 0, 0, 1.001, 1.0001, 0.5001, 173, 216, 230, 100, 0, 0, 0, 0) end end end end end end Citizen.Wait(1) end end) Citizen.CreateThread(function() while true do for _, id in ipairs(GetActivePlayers()) do if GetPlayerPed(id) ~= GetPlayerPed(-1) then x1, y1, z1 = table.unpack(GetEntityCoords(GetPlayerPed(-1), true)) x2, y2, z2 = table.unpack(GetEntityCoords(GetPlayerPed(id), true)) distance = math.floor(#(vector3(x1, y1, z1)-vector3(x2, y2, z2))) playerDistances[id] = distance end end Citizen.Wait(1000) end end)
#!/usr/bin/env lua print(type("Hello world")) --> string print(type(10.4*3)) --> number print(type(print)) --> function print(type(type)) --> function print(type(true)) --> boolean print(type(nil)) --> nil print(type(type(X))) --> string print("---------------------table type-------------------") tab1 = { key1 = "val1", key2 = "val2", "val3" } for k, v in pairs(tab1) do print(k .. " - " .. v) end tab1.key1 = nil for k, v in pairs(tab1) do print(k .. " - " .. v) end --boolean print("---------------------boolean type-------------------") print(type(true)) print(type(false)) print(type(nil)) if false or nil then print("至少有一个是 true") else print("false 和 nil 都为 false") end if 0 then print("数字 0 是 true") else print("数字 0 为 false") end print("---------------------number type-------------------") print(type(2)) print(type(2.2)) print(type(0.2)) print(type(2e+1)) print(type(0.2e-1)) print(type(7.8263692594256e-06)) print("---------------------string type-------------------") string1 = "this is string1" string2 = 'this is string2' html = [[ <html> <head></head> <body> <a href="http://www.runoob.com/">菜鸟教程</a> </body> </html> ]] print(html) a = {} a["key"] = "value" key = 10 a[key] = 22 a[key] = a[key] + 11 for k, v in pairs(a) do print(k .. " : " .. v) end local tbl = {"apple", "pear", "orange", "grape"} for key, val in pairs(tbl) do print(key, val) end a3 = {} for i = 1, 10 do a3[i] = i end a3["key"] = "val" print(a3["key"]) print(a3["none"]) function factorial1(n) if n == 0 then return 1 else return n * factorial1(n - 1) end end print(factorial1(5)) factorial2 = factorial1 print(factorial2(5))
-- loading C library require 'libcudafft' local ComBiPooling, parent = torch.class('nn.ComBiPooling', 'nn.Module') function ComBiPooling:__init(output_size, sum_pool, homo) assert(output_size and output_size >= 1, 'missing outputSize...') self.output_size = output_size -- add option for one input -- mainly for testJacobian. self.sum_pool = sum_pool ~= false self.homo = homo or false self:initVar() end function ComBiPooling:initVar() self.flat_input = torch.Tensor() self.hash_input = torch.Tensor() self.rand_h_1 = torch.Tensor() self.rand_h_2 = torch.Tensor() self.rand_s_1 = torch.Tensor() self.rand_s_2 = torch.Tensor() end -- generate random vectors h1, h2, s1, s2. function ComBiPooling:genRand(size_1, size_2) self.rand_h_1 = self.rand_h_1:resize(size_1):uniform(0,self.output_size):ceil():long() self.rand_h_2 = self.rand_h_2:resize(size_2):uniform(0,self.output_size):ceil():long() self.rand_s_1 = self.rand_s_1:resize(size_1):uniform(0,2):floor():mul(2):add(-1) self.rand_s_2 = self.rand_s_2:resize(size_2):uniform(0,2):floor():mul(2):add(-1) end -- psi function in Algorithm 2. function ComBiPooling:getHashInput() self.hash_input:zero() self.hash_input[1]:indexAdd(2,self.rand_h_1, torch.cmul(self.rand_s_1:repeatTensor(self.flat_size,1),self.flat_input[1])) self.hash_input[2]:indexAdd(2,self.rand_h_2, torch.cmul(self.rand_s_2:repeatTensor(self.flat_size,1),self.flat_input[2])) end function ComBiPooling:checkInput(input) if self.homo then -- if only one input assert(1 == #input, string.format("expect 1 input but get %d...", #input)) assert(4 == input[1]:nDimension(), string.format("wrong input dimensions, required 4, but get %d", input[1]:nDimension())) else -- if there are two inputs, #dim and size of each dim is examined. assert(2 == #input, string.format("expect 2 inputs but get %d...", #input)) assert(4 == input[1]:nDimension() and 4 == input[2]:nDimension(), string.format("wrong input dimensions, required (4, 4), but get (%d, %d)", input[1]:nDimension(), input[2]:nDimension())) for dim = 1, 4 do if dim ~= 2 then assert(input[1]:size(dim) == input[2]:size(dim), string.format("input size mismatch, dim %d: %d vs %d", dim, input[1]:size(dim), input[2]:size(dim))) end end end end -- complex number element wise product function ComBiPooling:fftMul(x, y) local prod = torch.zeros(x:size()):cuda() for i = 1, x:size(1) do local x1 = x[i][1][1]:select(2,1) local x2 = x[i][1][1]:select(2,2) local y1 = y[i][1][1]:select(2,1) local y2 = y[i][1][1]:select(2,2) local real = torch.cmul(x1, y1) - torch.cmul(x2, y2) local imag = torch.cmul(x1, y2) + torch.cmul(x2, y1) prod[i]:copy(torch.cat(real, imag, 2)) end return prod end -- batch fft function ComBiPooling:fft1d(input, output) local nSamples = input:size(1) local nPlanes = input:size(2) local N = input:size(3) local M = input:size(4) input:resize(nSamples*nPlanes*N, M) output:resize(nSamples*nPlanes*N, M/2+1, 2) -- calling C function cudafft.fft1d_r2c(input, output) input:resize(nSamples, nPlanes, N, M) output:resize(nSamples, nPlanes, N, M/2+1, 2) end -- batch ifft function ComBiPooling:ifft1d(input, output) local nSamples = output:size(1) local nPlanes = output:size(2) local N = output:size(3) local M = output:size(4) input:resize(nSamples*nPlanes*N, M/2+1, 2) output:resize(nSamples*nPlanes*N, M) -- calling C function cudafft.fft1d_c2r(input,output) output:div(M) input:resize(nSamples, nPlanes, N, M/2+1, 2) output:resize(nSamples, nPlanes, N, M) end -- ifft( fft(x) .* fft(y) ) function ComBiPooling:conv(x,y) local batchSize = x:size(1) local dim = x:size(2) local function makeComplex(x,y) self.x_ = self.x_ or torch.CudaTensor() self.x_:resize(x:size(1),1,1,x:size(2),2):zero() self.x_[{{},{1},{1},{},{1}}]:copy(x) self.y_ = self.y_ or torch.CudaTensor() self.y_:resize(y:size(1),1,1,y:size(2),2):zero() self.y_[{{},{1},{1},{},{1}}]:copy(y) end makeComplex(x,y) self.fft_x = self.fft_x or torch.CudaTensor(batchSize,1,1,dim,2) self.fft_y = self.fft_y or torch.CudaTensor(batchSize,1,1,dim,2) local output = output or torch.CudaTensor() output:resize(batchSize,1,1,dim*2) self:fft1d(self.x_:view(x:size(1),1,1,-1), self.fft_x) self:fft1d(self.y_:view(y:size(1),1,1,-1), self.fft_y) local prod = self:fftMul(self.fft_x, self.fft_y) self:ifft1d(prod, output) return output:resize(batchSize,1,1,dim,2):select(2,1):select(2,1):select(3,1) end function ComBiPooling:updateOutput(input) -- wrap the input into a table if it's homo if self.homo then self.input = type(input)=='table' and input or {input} else self.input = input end self:checkInput(self.input) -- step 1. See Compact Bilinear Pooling paper -- "Algorithm 2 Tensor Sketch Projection". -- only generate new random vector at the very beginning. if 0 == self.rand_h_1:nElement() then if self.homo then self:genRand(self.input[1]:size(2), self.input[1]:size(2)) else self:genRand(self.input[1]:size(2), self.input[2]:size(2)) end end -- convert the input from 4D to 2D and expose dimension 2 outside. self.flat_size = self.input[1]:size(1) * self.input[1]:size(3) * self.input[1]:size(4) self.flat_input:resize(2, self.flat_size, self.input[1]:size(2)) for i = 1, #self.input do local new_input = self.input[i]:permute(1,3,4,2):contiguous() self.flat_input[i] = new_input:view(-1, self.input[i]:size(2)) end if self.homo then self.flat_input[2] = self.flat_input[1]:clone() end -- get hash input as step 2 self.hash_input:resize(2, self.flat_size, self.output_size) self:getHashInput() -- generate several constant values for later user self.flat_output = self:conv(self.hash_input[1], self.hash_input[2]) self.height = self.input[1]:size(3) self.width = self.input[1]:size(4) self.hw_size = self.input[1]:size(3) * self.input[1]:size(4) self.batch_size = self.input[1]:size(1) self.channel = self.input[1]:size(2) -- step 3 -- reshape output and sum pooling over dimension 2 and 3. self.output = self.flat_output:reshape(self.batch_size, self.hw_size, self.output_size) if self.sum_pool then self.output = self.output:sum(2):squeeze():reshape(self.batch_size, self.output_size) else self.output = self.output:transpose(2, 3):contiguous() self.output = self.output:reshape(self.batch_size, self.output_size, self.height, self.width) end return self.output end function ComBiPooling:updateGradInput(input, gradOutput) -- input: batch x channel x height x width -- if used sum pooling over dimension 2 and 3 -- gradOutput: batch x output_size -- else -- gradOutput: batch x output_size x height x width -- repeatGradOut: flat_size x output_size local repeatGradOut if self.sum_pool then repeatGradOut = gradOutput:view(self.batch_size, self.output_size, 1):repeatTensor(1, 1, self.hw_size) else repeatGradOut = gradOutput:view(self.batch_size, self.output_size, self.hw_size) end repeatGradOut = repeatGradOut:permute(1,3,2):reshape(self.flat_size, self.output_size) self.gradInputTable = self.gradInputTable or {} self.convResult = self.convResult or {} -- this part is derivative of ifft(fft().*fft()) for k = 1, 2 do self.gradInputTable[k] = self.gradInputTable[k] or self.hash_input.new() -- self.gradInputTable[k]: flat_size x output_size self.gradInputTable[k]:resizeAs(self.flat_input[k]):zero() self.convResult[k] = self.convResult[k] or repeatGradOut.new() -- self.convResult: flat_size x output_size self.convResult[k]:resizeAs(repeatGradOut) local index = torch.cat(torch.LongTensor{1}, torch.linspace(self.output_size,2,self.output_size-1):long()) -- self.hash_input: flat_size x output_size local reverse_input = self.hash_input[k]:index( 2 ,index) -- self.convResult: flat_size x output_size self.convResult[k] = self:conv(repeatGradOut, reverse_input) end -- this part is derivative of psi function for k = 1, 2 do -- self.rand_h_1: 1 x channel, range: [1, output_size] -- self.rand_s_1: 1 x channel, range: {1, -1} -- self.gradInputTable[k]: flat_size, channel local k_bar = 3-k self.gradInputTable[k_bar]:index(self.convResult[k], 2, self['rand_h_' .. k_bar]) self.gradInputTable[k_bar]:cmul(self['rand_s_' .. k_bar]:repeatTensor(self.flat_size,1)) self.gradInputTable[k_bar] = self.gradInputTable[k_bar]:view( self.batch_size,self.height,self.width,-1):permute(1,4,2,3):contiguous() end if type(input)=='table' then self.gradInput = self.gradInputTable return self.gradInput else self.gradInput = self.gradInputTable[1] + self.gradInputTable[2] return self.gradInput end end
local InGameInfoPanel = {} function InGameInfoPanel:new(x,y,layer,context, count, icon, text, iconAspect) local newIngameInfo = {}; -- set meta tables so lookups will work setmetatable(newIngameInfo, self) self.__index = self --newIngameInfo.uiUtils = require("ui.uiUtils"); --print("InGameInfoPanel:new(x,y,layer,context, count, icon, text)"); newIngameInfo:init(x,y,layer,context, count, icon, text, iconAspect) return newIngameInfo; end function InGameInfoPanel:init(x,y,layer,context, count, icon, text, iconAspect) local uiConst = context.uiConst; local fontSize = uiConst.bigFontSize; local iconHeight = fontSize+20; local iconWidth = iconHeight * (iconAspect or 1); local margin = uiConst.defaultMargin; local backH; if(icon) then backH= iconHeight+2*margin; --1.3*fontSize; else backH= fontSize+2*margin; --1.3*fontSize; end local w =0; -- width is unknown util all texts are created local g = display.newGroup(); layer:insert(g); self.g = g; -- add backround local back = display.newRoundedRect(g, x, y, 100, backH, 5) back:setFillColor(0.3,0.3,0.3,0.75); back.stroke = {type="image", filename= "img/comm/fuzy_stroke.png"}; back.strokeWidth = 4; --back:setStrokeColor(unpack(uiConst.highlightedFontColor)); back:setStrokeColor(0,0,0); back.blendMOde = "multiply"; if(count) then self.countLabel = display.newText{ -- contracted or tips label text= tostring(count), parent = g, x = x, y = y, height = 0, font= uiConst.fontName, fontSize = fontSize, align = "center" } self.countLabel.blendMode = "add"; self.countLabel:setFillColor(unpack(uiConst.highlightedFontColor)); g:insert(self.countLabel); w = w +self.countLabel.width + margin; end if(icon) then --local iconSize = fontSize; self.icon = display.newImageRect(g, icon, iconWidth, iconHeight); self.icon.y =y; w = w + self.icon.width+ margin; end if(text) then -- add label self.label = display.newText{ -- contracted or tips label text= text, parent = self.g, x = x, y = y, --width = w, height = 0, font= uiConst.fontName, fontSize = fontSize, align = "center" } self.label.blendMode = "add"; self.label:setFillColor(unpack(uiConst.highlightedFontColor)); g:insert(self.label); w = w +self.label.width+ margin; end -- now the width is known, so position elements properly -- it cluld be done as array of compnets, but m'I lazy now local xx = x - 0.5*w + margin; if(count) then self.countLabel.x = xx + 0.5*self.countLabel.width; xx = xx + self.countLabel.width+margin; end if(icon) then self.icon.x = xx + 0.5*self.icon.width; xx = xx + self.icon.width + margin; end if(text) then self.label.x = xx+ 0.5*self.label.width; --xx = end back.width = w + margin; g.alpha = 0; transition.to(self.g,{alpha=1, time = 250, transition = easing.inOutSine}); end function InGameInfoPanel:fadeOut() if(self.g== nil) then return; end; local time = 850; transition.to(self.g, {alpha=0, delay=4*time, time = time, onComplete = function() self:destroy(); end }) end function InGameInfoPanel:destroy() if(self.g) then self.g:removeSelf(); self.g = nil; end end return InGameInfoPanel;
CLASS.name = "Fourth Reich" CLASS.desc = "An army ruled by a facist dictator." CLASS.faction = FACTION_DWELLER CLASS.color = Color(0, 155, 0) CLASS.flag = "F" CLASS.pay = 7 CLASS.payTime = 3600 --1 hour in seconds function CLASS:onCanBe(client) local character = client:getChar() local inventory = character:getInv() if inventory:hasItem("reichpassport") and character:hasFlags("F") then return true else return false end end CLASS_REICH = CLASS.index
local replicating_ultra_fast_belt = { type = "recipe", name = "replicating-ultra-fast-belt", localised_name = {"replicating-belts.prefix", {[1] = "replicating-belts.ultra-fast-belt-lower"}}, enabled = false, ingredients ={ {'ultra-fast-belt', 1}, {'electronic-circuit', 1}, }, result = "replicating-ultra-fast-belt", } local replicating_extreme_fast_belt = { type = "recipe", name = "replicating-extreme-fast-belt", localised_name = {"replicating-belts.prefix", {[1] = "replicating-belts.extreme-fast-belt-lower"}}, enabled = false, ingredients = { {'extreme-fast-belt', 1}, {'electronic-circuit', 1}, }, result = "replicating-extreme-fast-belt", } local replicating_ultra_express_belt = { type = "recipe", name = "replicating-ultra-express-belt", localised_name = {"replicating-belts.prefix", {[1] = "replicating-belts.ultra-express-belt-lower"}}, enabled = false, ingredients = { {'ultra-express-belt', 1}, {'electronic-circuit', 1}, }, result = "replicating-ultra-express-belt", } local replicating_extreme_express_belt = { type = "recipe", name = "replicating-extreme-express-belt", localised_name = {"replicating-belts.prefix", {[1] = "replicating-belts.extreme-express-belt-lower"}}, enabled = false, ingredients = { {'extreme-express-belt', 1}, {'electronic-circuit', 1}, }, result = "replicating-extreme-express-belt", } local replicating_ultimate_transport_belt = { type = "recipe", name = "replicating-ultimate-transport-belt", localised_name = {"replicating-belts.prefix", {[1] = "replicating-belts.ultimate-belt-lower"}}, enabled = false, ingredients = { {'ultimate-belt', 1}, {'electronic-circuit', 1}, }, result = "replicating-ultimate-transport-belt", } data:extend{replicating_ultra_fast_belt, replicating_extreme_fast_belt, replicating_ultra_express_belt, replicating_extreme_express_belt, replicating_ultimate_transport_belt}
local example = {} example.title = "Menu" example.category = "Object Demonstrations" function example.func(loveframes, centerarea) local frame = loveframes.create("frame") frame:setName("Menu") frame:centerWithinArea(unpack(centerarea)) local text = loveframes.create("text", frame) text:setText("Right click this frame to see an \n example of the menu object") text:center() local submenu3 = loveframes.create("menu") submenu3:addOption("Option 1", false, function() end) submenu3:addOption("Option 2", false, function() end) local submenu2 = loveframes.create("menu") submenu2:addOption("Option 1", "resources/food/FishFillet.png", function() end) submenu2:addOption("Option 2", "resources/food/FishSteak.png", function() end) submenu2:addOption("Option 3", "resources/food/Shrimp.png", function() end) submenu2:addOption("Option 4", "resources/food/Sushi.png", function() end) local submenu1 = loveframes.create("menu") submenu1:addSubMenu("Option 1", "resources/food/Cookie.png", submenu3) submenu1:addSubMenu("Option 2", "resources/food/Fish.png", submenu2) local menu = loveframes.create("menu") menu:addOption("Option A", "resources/food/Eggplant.png", function() end) menu:addOption("Option B", "resources/food/Eggs.png", function() end) menu:addDivider() menu:addOption("Option C", "resources/food/Cherry.png", function() end) menu:addOption("Option D", "resources/food/Honey.png", function() end) menu:addDivider() menu:addSubMenu("Option E", false, submenu1) menu:setVisible(false) frame.menu_example = menu text.menu_example = menu end return example
local mbedtls = require("mbedtls") for k,v in pairs(mbedtls) do print(k, v) end
-- 草莓Dâu Tây 's Type Fx Vert -- Code by Effector Cmy include("karaskel.lua") local tr = aegisub.gettext script_name = tr"Cmy - Remember 1.5" script_description = "Cmy's Tool Remember" script_author = "Cmy草莓" script_version = "1.5" link1 = aegisub.decode_path("?user") .. "/RememberCmy.lua" link2 = aegisub.decode_path("?data") .. "/RememberCmy.lua" if (io.open(link1, "a+")) then link = link1 else link = link2 end Credit = function(r) return string.rep("-", r) .. " CODE BY CMY - 草莓 Dâu Tây " .. string.rep("-", r) end SaveKey = tr"Save" OpenKey = tr"Open File" DelKey = tr"Delete" DelAllKey = DelKey .. " " .. tr"All" AddRmb = tr"Add" AppKey = tr"Apply" CloseKey = tr"Close" function SaveFile(text, fname) local file = io.open(fname,"w") file : write(text) file : close() end function ApplyText(subs, sel, applytext) for z, i in ipairs(sel) do local l = subs[i] if l.text:match("`") then l.text = l.text:gsub("`", applytext) : gsub("}{","") else l.text = (applytext .. l.text) : gsub("}{","") end subs[i] = l end end function ReadFile() local file = io.open(link,"a+") rtext = file : read("*a") file : close() return rtext end function Remember(subs, sel) local file = io.open(link) setfile = (file and true or false) if file then file:close() end if not setfile then SaveFile("Rmb = {}", link) end rfile = ReadFile() or "" if not (rfile : match("Rmb = {}")) then rfile = "Rmb = {}\n" .. rfile end Rmb = loadstring(rfile .. " return Rmb")() repeat local RmbName = {} local i = 0 for name, _ in pairs(Rmb) do i = i + 1 RmbName[i] = name end table.sort(RmbName) if #RmbName < 1 then menu = { {x = 0, y = 0, width = 10, height = 2, class = "label", label = Credit(20)}; {x = 0, y = 2, width = 2, height = 1, class = "label", label = tr"Name" .. ": "}; {x = 2, y = 2, width = 8, height = 1, class = "edit", name = "remember_name", value = Name_n or "", hint = "Nhập tên khay nhớ tại đây"}; {x = 0, y = 3, width = 2, height = 1, class = "label", label = tr"Value" .. ": "}; {x = 2, y = 3, width = 8, height = 1, class = "edit", name = "remember_text", value = Value_n or "", hint = "Nhập giá trị cần ghi nhớ"} } P, res = ADD(menu, {AddRmb, OpenKey, CloseKey}, {ok = AddRmb, cancel = CloseKey}) if not P then stop = true else stop = false end else menu = { {x = 0, y = 0, width = 18, height = 2, class = "label", label = Credit(45)}; {x = 0, y = 2, width = 3, height = 1, class = "label", label = tr"Name" .. ": "}; {x = 3, y = 2, width = 7, height = 1, class = "edit", name = "remember_name", value = Name_n or "", hint = "Nhập tên khay nhớ tại đây"}; {x = 10, y = 2, width = 7, height = 1, class = "dropdown", items = RmbName, name = "remember_type", value = RmbName[1], hint = "Chọn khay nhớ cần chạy"}; {x = 17, y = 2, width = 1, height = 1, class = "label", label = " -- " .. #RmbName .. " --"}; {x = 0, y = 3, width = 3, height = 1, class = "label", label = tr"Value" .. ": "}; {x = 3, y = 3, width = 15, height = 1, class = "edit", name = "remember_text", value = Value_n or "", hint = "Nhập giá trị cần ghi nhớ"} } P, res = ADD(menu, {AppKey, AddRmb, SaveKey, DelKey, DelAllKey, OpenKey, CloseKey}, {ok = AppKey, cancel = CloseKey}) if not P or (P == AppKey) then stop = true else stop = false end end Name_n, Value_n = res.remember_name, res.remember_text if P == AddRmb and (Value_n ~= "" and Name_n ~= "") then Rmb[Name_n] = Value_n Name_n, Value_n = "", "" elseif P == DelKey then ttRmb = {} for i = 1, #RmbName do if RmbName[i] ~= res.remember_type then ttRmb[RmbName[i]] = Rmb[RmbName[i]] end end Rmb = ttRmb elseif P == DelAllKey then Rmb = {} elseif P == OpenKey then local filename = OPEN('Chọn File', '', '', '(.lua)|*.lua', false, true) if filename then file = assert(io.open(filename)) filetext = file:read("*a") file:close() f, err = loadstring(filetext) if not err then ttrmb = loadstring(filetext .. " return ttrmb ")() for name, vl in pairs(ttrmb) do Rmb[name] = vl end end end elseif P == SaveKey then local sfile = "ttrmb = {\n" for name, vl in pairs(Rmb) do sfile = sfile .. "\t[\"" .. name .. "\"] = \"" .. vl .. "\";\n" end sfile = sfile:gsub("\\","\\\\") .. "}" local file_name = SAVE('Nhập tên', 'File-Remember', '', '(.lua)|*.lua', true) if file_name then SaveFile(sfile, file_name) end end until stop if P == AppKey then ApplyText(subs, sel, Rmb[res.remember_type]) end local savermb = "Rmb = {\n" for name, vl in pairs(Rmb) do savermb = savermb .. "\t[\"" .. name .. "\"] = \"" .. vl .. "\";\n" end savermb = savermb : gsub("\\","\\\\") .. "}" SaveFile(savermb, link) end function apply_remember(subs,sel) ADD=aegisub.dialog.display ADP=aegisub.decode_path SAVE=aegisub.dialog.save OPEN=aegisub.dialog.open ak=aegisub.cancel Remember(subs, sel) aegisub.set_undo_point(script_name) end aegisub.register_macro(script_name, script_description, apply_remember)
function DrawTextShadow(Txt, Fnt, x, y, col, Align, scol, sdis) DrawText(Txt, Fnt, x-sdis, y+sdis, scol, Align) DrawText(Txt, Fnt, x, y, col, Align) end
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ========== PlaceObj('StoryBit', { ActivationEffects = {}, Category = "Tick_FounderStageDone", Effects = {}, Enabled = true, Image = "UI/Messages/Events/13_renegades.tga", Prerequisites = { PlaceObj('CheckObjectCount', { 'Label', "FactoryBuildings", 'Filters', {}, 'Condition', ">", 'Amount', 1, }), PlaceObj('PickFromLabel', { 'Label', "Colonist", 'Conditions', { PlaceObj('HasTrait', { 'Trait', "Youth", }), PlaceObj('HasTrait', { 'Trait', "Renegade", }), }, }), }, ScriptDone = true, Text = T(796006225278, --[[StoryBit Vandals Text]] "Albeit the biggest such incident lately, it is not the first. We suspect a gang of renegades led by a self-declared Street King named <DisplayName> to be responsible.\n\nSo far they have always smartly evaded our attempts to catch them in the act."), TextReadyForValidation = true, TextsDone = true, Title = T(633068112353, --[[StoryBit Vandals Title]] "Renegades: Street King"), VoicedText = T(842725828714, --[[voice:narrator]] "Vandals have sprayed obscene signs and drawings on several factories this night."), group = "Renegades", id = "Vandals", qa_info = PlaceObj('PresetQAInfo', { data = { { action = "Modified", time = 1625147987, }, }, }), PlaceObj('StoryBitParamNumber', { 'Name', "morale_penalty", 'Value', -15, }), PlaceObj('StoryBitParamSols', { 'Name', "penalty_sols", 'Value', 7200000, }), PlaceObj('StoryBitReply', { 'Text', T(827569042931, --[[StoryBit Vandals Text]] "Clean up the factories and make sure this doesn't happen again."), 'OutcomeText', "custom", 'CustomOutcomeText', T(558574066840, --[[StoryBit Vandals CustomOutcomeText]] "emergency maintenance for all Factories"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('AddTrait', { 'Trait', "Guru", }), PlaceObj('ForEachExecuteEffects', { 'Label', "FactoryBuildings", 'Filters', {}, 'Effects', { PlaceObj('SetBuildingBreakdownState', { 'RepairAmount', 3000, }), }, }), }, }), PlaceObj('StoryBitReply', { 'Text', T(568368955260, --[[StoryBit Vandals Text]] "We can't stop the factories right now. The workers will have to tolerate the drawings."), 'OutcomeText', "custom", 'CustomOutcomeText', T(755181016807, --[[StoryBit Vandals CustomOutcomeText]] "all factory workers lose Morale"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Effects', { PlaceObj('AddTrait', { 'Trait', "Guru", }), PlaceObj('ForEachExecuteEffects', { 'Label', "FactoryBuildings", 'Filters', {}, 'Effects', { PlaceObj('ForEachWorker', { 'Filters', {}, 'Effects', { PlaceObj('ModifyObject', { 'Prop', "base_morale", 'Amount', "<morale_penalty>", 'Sols', "<penalty_sols>", }), }, }), }, }), }, }), PlaceObj('StoryBitReply', { 'Text', T(260925240976, --[[StoryBit Vandals Text]] "Use a Rover as a trap and attempt to catch the leader."), 'OutcomeText', "custom", 'CustomOutcomeText', T(563737516480, --[[StoryBit Vandals CustomOutcomeText]] "lose one Rover"), }), PlaceObj('StoryBitOutcome', { 'Prerequisites', {}, 'Enables', { "Vandals_FollowUp_1", }, 'Disables', {}, 'Effects', { PlaceObj('AddTrait', nil), PlaceObj('ForEachExecuteEffects', { 'Label', "Rover", 'Filters', {}, 'RandomCount', 1, 'Effects', { PlaceObj('DestroyVehicle', nil), }, }), }, }), })
local Template = require "oil.dtests.Template" local template = Template{"Client"} -- master process name Server = [=====================================================================[ impl = { called = false } function impl:doit() self.called = true end orb = oil.dtests.init{ port = 2809 } if oil.dtests.flavor.corba then impl.__type = orb:loadidl[[ interface SomeIface { readonly attribute boolean called; oneway void doit(); }; ]] end orb:newservant(impl, "object") orb:run() --[Server]=====================================================================] Client = [=====================================================================[ orb = oil.dtests.init() obj = oil.dtests.resolve("Server", 2809, "object") obj:doit() assert(obj:_get_called()) oil.sleep(.1) orb:shutdown() --[Client]=====================================================================] return template:newsuite{ corba = true }
for i,v in pairs(game.Players:GetChildren()) do game:GetService("Chat"):Chat(v.Character.Head,"FUCK \n CUNT \n WHORE \n SHIT \n BITCH \n CUM \n JIZZ \n NIGGER") end
local Skada = Skada local L = LibStub("AceLocale-3.0"):GetLocale("Skada") local name = L["Data Text"] local mod = Skada:NewModule(name) mod.name = name mod.description = L["Data text acts as an LDB data feed. It can be integrated in any LDB display such as Titan Panel or ChocolateBar. It also has an optional internal frame."] Skada:AddDisplaySystem("broker", mod) local ldb = LibStub:GetLibrary("LibDataBroker-1.1") local LibWindow = LibStub("LibWindow-1.1") local media = LibStub("LibSharedMedia-3.0") local tsort, format = table.sort, string.format local CloseDropDownMenus = L_CloseDropDownMenus or CloseDropDownMenus local WrapTextInColorCode = Skada.WrapTextInColorCode local RGBPercToHex = Skada.RGBPercToHex local function sortDataset(win) tsort(win.dataset, function(a, b) if not a or a.value == nil then return false elseif not b or b.value == nil then return true else return a.value > b.value end end) end local function formatLabel(win, data) if win.db.isusingclasscolors and data.class then return WrapTextInColorCode(data.text or data.label or L.Unknown, Skada.classcolors[data.class].colorStr) elseif data.color and data.color.colorStr then return WrapTextInColorCode(data.text or data.label or L.Unknown, data.color.colorStr) elseif data.color then return WrapTextInColorCode(data.text or data.label or L.Unknown, RGBPercToHex(data.color.r or 1, data.color.g or 1, data.color.b or 1, data.color.a or 1, true)) else return data.text or data.label or L.Unknown end end local function formatValue(win, data) return data.valuetext end local function clickHandler(win, frame, button) if not win.obj then return end if button == "LeftButton" and IsShiftKeyDown() then Skada:OpenMenu(win) elseif button == "LeftButton" then Skada:ModeMenu(win) elseif button == "RightButton" then Skada:SegmentMenu(win) end CloseDropDownMenus() -- always close end local function tooltipHandler(win, tooltip) if win.db.useframe then Skada:SetTooltipPosition(tooltip, win.frame, nil, win) end -- Default color. local color = win.db.textcolor or {r = 1, g = 1, b = 1} tooltip:AddLine(win.metadata.title) sortDataset(win) if #win.dataset > 0 then tooltip:AddLine(" ") local n = 0 -- used to fix spots starting from 2 for i, data in ipairs(win.dataset) do if data.id and not data.ignore and i < 30 then n = n + 1 local label = formatLabel(win, data) local value = formatValue(win, data) if win.metadata.showspots and Skada.db.profile.showranks then label = format("%s. %s", n, label) end tooltip:AddDoubleLine(label or "", value or "", color.r, color.g, color.b, color.r, color.g, color.b) end end end tooltip:AddLine(" ") tooltip:AddLine(L["Hint: Left-Click to set active mode."], 0, 1, 0) tooltip:AddLine(L["Right-Click to set active set."], 0, 1, 0) tooltip:AddLine(L["Shift+Left-Click to open menu."], 0, 1, 0) tooltip:Show() end local ttactive = false function mod:Create(win, isnew) -- Optional internal frame if not win.frame then win.frame = CreateFrame("Frame", win.db.name .. "BrokerFrame", UIParent) win.frame:SetHeight(win.db.height or 30) win.frame:SetWidth(win.db.width or 200) win.frame:SetPoint("CENTER", 0, 0) -- Register with LibWindow-1.1. LibWindow.RegisterConfig(win.frame, win.db) -- Restore window position. if isnew then LibWindow.SavePosition(win.frame) else LibWindow.RestorePosition(win.frame) end local title = win.frame:CreateFontString("frameTitle", 6) title:SetPoint("CENTER", 0, 0) win.frame.title = title win.frame:EnableMouse(true) win.frame:SetMovable(true) win.frame:RegisterForDrag("LeftButton") win.frame:SetScript("OnMouseUp", function(frame, button) clickHandler(win, frame, button) end) win.frame:SetScript("OnEnter", function(frame) tooltipHandler(win, GameTooltip) end) win.frame:SetScript("OnLeave", function(frame) GameTooltip:Hide() end) win.frame:SetScript("OnDragStart", function(frame) if not win.db.barslocked then GameTooltip:Hide() frame.isDragging = true frame:StartMoving() end end) win.frame:SetScript("OnDragStop", function(frame) frame:StopMovingOrSizing() frame.isDragging = false LibWindow.SavePosition(frame) end) end -- LDB object if not win.obj then win.obj = ldb:NewDataObject("Skada: " .. win.db.name, { type = "data source", text = "", OnTooltipShow = function(tooltip) tooltipHandler(win, tooltip) end, OnClick = function(frame, button) clickHandler(win, frame, button) end }) end mod:ApplySettings(win) end function mod:IsShown(win) return win.frame:IsShown() end function mod:Show(win) if win.db.useframe then win.frame:Show() end end function mod:Hide(win) if win.db.useframe then win.frame:Hide() end end function mod:Destroy(win) if win and win.frame then if win.obj then if win.obj.text then win.obj.text = " " end win.obj = nil end win.frame:Hide() win.frame = nil end end function mod:Wipe(win) win.text = " " end function mod:SetTitle(win, title) end function mod:Update(win) if win.obj then win.obj.text = "" end sortDataset(win) if #win.dataset > 0 then local data = win.dataset[1] if data.id then local label = (formatLabel(win, data) or "") .. " - " .. (formatValue(win, data) or "") if win.obj then win.obj.text = label end if win.db.useframe then win.frame.title:SetText(label) end end end end function mod:OnInitialize() end function mod:ApplySettings(win) if win.db.useframe then local title = win.frame.title local db = win.db win.frame:SetMovable(not win.db.barslocked) win.frame:SetHeight(win.db.height or 30) win.frame:SetWidth(win.db.width or 200) local fbackdrop = {} fbackdrop.bgFile = media:Fetch("background", db.background.texture) fbackdrop.tile = db.background.tile fbackdrop.tileSize = db.background.tilesize win.frame:SetBackdrop(fbackdrop) win.frame:SetBackdropColor( db.background.color.r, db.background.color.g, db.background.color.b, db.background.color.a ) Skada:ApplyBorder( win.frame, db.background.bordertexture, db.background.bordercolor, db.background.borderthickness ) local color = db.textcolor or {r = 1, g = 1, b = 1, a = 1} title:SetTextColor(color.r, color.g, color.b, color.a) title:SetFont(media:Fetch("font", db.barfont), db.barfontsize, db.barfontflags) title:SetText(win.metadata.title or "Skada") title:SetWordWrap(false) title:SetJustifyH("CENTER") title:SetJustifyV("MIDDLE") title:SetHeight(win.db.height or 30) win.frame:SetScale(db.scale) win.frame:SetFrameStrata(db.strata) if db.hidden and win.frame:IsShown() then win.frame:Hide() elseif not db.hidden and not win.frame:IsShown() then win.frame:Show() end else win.frame:Hide() end self:Update(win) end function mod:AddDisplayOptions(win, options) local db = win.db options.main = { type = "group", name = L["Data Text"], desc = format(L["Options for %s."], L["Data Text"]), order = 10, get = function(i) return db[i[#i]] end, set = function(i, val) db[i[#i]] = val Skada:ApplySettings(db.name) end, args = { useframe = { type = "toggle", name = L["Use frame"], desc = L["Shows a standalone frame. Not needed if you are using an LDB display provider such as Titan Panel or ChocolateBar."], order = 10, width = "double" }, barfont = { type = "select", dialogControl = "LSM30_Font", name = L["Font"], desc = format(L["The font used by %s."], L["Bars"]), values = AceGUIWidgetLSMlists.font, order = 20 }, barfontflags = { type = "select", name = L["Font Outline"], desc = L["Sets the font outline."], values = Skada.fontFlags, order = 30 }, barfontsize = { type = "range", name = L["Font Size"], desc = format(L["The font size of %s."], L["Bars"]), min = 5, max = 32, step = 1, order = 40, width = "double" }, color = { type = "color", name = L["Text Color"], desc = L["Choose the default color."], hasAlpha = true, get = function(i) local c = db.textcolor or {r = 1, g = 1, b = 1, a = 1} return c.r, c.g, c.b, c.a end, set = function(i, r, g, b, a) db.textcolor = {["r"] = r, ["g"] = g, ["b"] = b, ["a"] = a} Skada:ApplySettings(db.name) end, disabled = function() return db.isusingclasscolors end, order = 50, }, isusingclasscolors = { type = "toggle", name = L["Class Colors"], desc = L["When possible, bar text will be colored according to player class."], order = 60 }, } } options.window = Skada:FrameSettings(db, true) end
--This is an example that uses the LSM303DLHC Accelerometer & Magnetometer on the I2C Bus on EIO4(SCL) and EIO5(SDA) --Outputs data to Registers: --X accel = 46006 --Y accel = 46008 --Z accel = 46010 fwver = MB.R(60004, 3) devType = MB.R(60000, 3) if (fwver < 1.0224 and devType == 7) or (fwver < 0.2037 and devType == 4) then print("This lua script requires a higher firmware version (T7 Requires 1.0224 or higher, T4 requires 0.2037 or higher). Program Stopping") MB.W(6000, 1, 0) end function convert_16_bit(msb, lsb, conv)--Returns a number, adjusted using the conversion factor. Use 1 if not desired res = 0 if msb >= 128 then res = (-0x7FFF+((msb-128)*256+lsb))/conv else res = (msb*256+lsb)/conv end return res end SLAVE_ADDRESS = 0x19 I2C.config(13, 12, 65516, 0, SLAVE_ADDRESS, 0)--configure the I2C Bus addrs = I2C.search(0, 127) addrsLen = table.getn(addrs) found = 0 for i=1, addrsLen do--verify that the target device was found if addrs[i] == SLAVE_ADDRESS then print("I2C Slave Detected") found = 1 break end end if found == 0 then print("No I2C Slave detected, program stopping") MB.W(6000, 1, 0) end --init slave I2C.write({0x20, 0x27})--Data Rate: 10Hz, disable low-power, enable all axes I2C.write({0x23, 0x49})--continuous update, LSB at lower addr, +- 2g, Hi-Res disable LJ.IntervalConfig(0, 500) while true do if LJ.CheckInterval(0) then dataRaw = {} for i=0, 5 do --sequentially read the addresses containing the accel data I2C.write({0x28+i}) dataIn, errorIn = I2C.read(2) table.insert(dataRaw, dataIn[1]) end data = {} for i=0, 2 do--convert the data into Gs table.insert(data, convert_16_bit(dataRaw[1+i*2], dataRaw[2+i*2], (0x7FFF/2))) MB.W(46006+i*2, 3, data[i+1]) end MB.W(46006, 3, data[1])--add X value, in Gs, to the user_ram register MB.W(46008, 3, data[2])--add Y MB.W(46010, 3, data[3])--add Z print("X: "..data[1]) print("Y: "..data[2]) print("Z: "..data[3]) print("------") end end
---@meta --=== ws2801 === ---@class ws2801 ws2801 = {} ---Initializes the module and sets the pin configuration. ---@param pin_clk integer @pin for the clock. Supported are GPIO 0, 2, 4, 5. ---@param pin_data integer @pin for the data. Supported are GPIO 0, 2, 4, 5. ---@return nil function ws2801.init(pin_clk, pin_data) end ---Sends data of RGB Data in 24 bits to WS2801. ---@param data any @"payload to be sent to one or more WS2801. \n Payload type could be:" ---- `string` representing bytes to send --- It should be composed from an RGB triplet per element. --- - `R1` the first pixel's red channel value (0-255) --- - `G1` the first pixel's green channel value (0-255) --- - `B1` the first pixel's blue channel value (0-255) \ --- ... You can connect a lot of WS2801... --- - `R2`, `G2`, `B2` are the next WS2801's Red, Green, and Blue channel values ---- a `pixbuf` object containing the bytes to send. The pixbuf's type is not checked! ---@return nil function ws2801.write(data) end
require("stringutil") require("vue/src") require("@vue/shared") describe('compiler + runtime integration', function() mockWarn() it('should support runtime template compilation', function() local container = document:createElement('div') local App = {template=, data=function() return {count=0} end } createApp(App):mount(container) expect(container.innerHTML):toBe() end ) it('should support runtime template via CSS ID selector', function() local container = document:createElement('div') local template = document:createElement('div') template.id = 'template' template.innerHTML = '{{ count }}' document.body:appendChild(template) local App = {template=, data=function() return {count=0} end } createApp(App):mount(container) expect(container.innerHTML):toBe() end ) it('should support runtime template via direct DOM node', function() local container = document:createElement('div') local template = document:createElement('div') template.id = 'template' template.innerHTML = '{{ count }}' local App = {template=template, data=function() return {count=0} end } createApp(App):mount(container) expect(container.innerHTML):toBe() end ) it('should warn template compilation errors with codeframe', function() local container = document:createElement('div') local App = {template=} createApp(App):mount(container) expect():toHaveBeenWarned() expect(():trim()):toHaveBeenWarned() expect():toHaveBeenWarned() expect(():trim()):toHaveBeenWarned() end ) it('should support custom element', function() local app = createApp({template='<custom></custom>'}) local container = document:createElement('div') app.config.isCustomElement = function(tag) tag == 'custom' end app:mount(container) expect(container.innerHTML):toBe('<custom></custom>') end ) it('should support using element innerHTML as template', function() local app = createApp({data=function() {msg='hello'} end }) local container = document:createElement('div') container.innerHTML = '{{msg}}' app:mount(container) expect(container.innerHTML):toBe('hello') end ) it('should support selector of rootContainer', function() local container = document:createElement('div') local origin = document.querySelector document.querySelector = jest:fn():mockReturnValue(container) local App = {template=, data=function() return {count=0} end } createApp(App):mount('#app') expect(container.innerHTML):toBe() document.querySelector = origin end ) it('should warn when template is not avaiable', function() local app = createApp({template={}}) local container = document:createElement('div') app:mount(container) expect('[Vue warn]: invalid template option:'):toHaveBeenWarned() end ) it('should warn when template is is not found', function() local app = createApp({template='#not-exist-id'}) local container = document:createElement('div') app:mount(container) expect('[Vue warn]: Template element not found or is empty: #not-exist-id'):toHaveBeenWarned() end ) it('should warn when container is not found', function() local origin = document.querySelector document.querySelector = jest:fn():mockReturnValue(nil) local App = {template=, data=function() return {count=0} end } createApp(App):mount('#not-exist-id') expect('[Vue warn]: Failed to mount app: mount target selector returned null.'):toHaveBeenWarned() document.querySelector = origin end ) end )
function Client_PresentConfigureUI(rootParent) local limit = Mod.Settings.Limit; if limit == nil then limit = 3; end local vert = UI.CreateVerticalLayoutGroup(rootParent); local horz = UI.CreateHorizontalLayoutGroup(vert); UI.CreateLabel(horz).SetText('Attack/transfer limit'); numberInputField = UI.CreateNumberInputField(horz) .SetSliderMinValue(0) .SetSliderMaxValue(15) .SetValue(limit); end
local pkg = {} -- Metadata pkg.name = "HotCorners" pkg.version = "1.0" pkg.author = "Joao Rietra <[email protected]>" pkg.github = "@jhlr" pkg.license = "MIT - https://opensource.org/licenses/MIT" -- Error messages local functionOrNil = "Callback has to be a function or nil." local numberOrNil = "Delay has to be nil or a number >= 0." -- Properties -- Delta is in pixels -- area to be considered as a corner pkg.delta = 10 -- Delay is in seconds -- avoid triggering repeatedly pkg.delay = 1 -- Local variables local sframe local mouseWatcher local screenWatcher -- Local booleans local moved = false local middle = true -- Corners local ul, ll, ur, lr function newCorner() local corner = { one = nil, two = nil, hold = nil, busy = false, delay = nil, timer = nil } corner.timer = hs.timer.new(0, function() if corner.hold and not moved then -- Stayed inside the corner since the trigger corner.hold() elseif (corner.two or corner.hold) and corner.one and corner.busy then -- Left but did not enter again corner.one() end corner.busy = false end) return corner end function trigger(corner) local delay = pkg.delay if corner.delay ~= nil then delay = corner.delay end if not corner.hold and not corner.two then -- Only single tap if not corner.one or corner.busy then return end if delay >= 0 then corner.busy = true end corner.one() if delay >= 0 then corner.timer:setNextTrigger(delay) end elseif corner.two and corner.busy then -- Second tap -- dont trigger corner.one corner.timer:stop() corner.two() corner.busy = false elseif not corner.busy then -- moved will stay false if cursor stays inside moved = false corner.busy = true corner.timer:setNextTrigger(delay) end end function updateScreen() sframe = hs.screen.primaryScreen():fullFrame() middle = false end function pkg:init() ul = newCorner() ur = newCorner() ll = newCorner() lr = newCorner() screenWatcher = hs.screen.watcher.new(updateScreen) mouseWatcher = hs.eventtap.new({ hs.eventtap.event.types.mouseMoved }, function(e) local p = e:location() -- Inside the main screen ? if p.x >= sframe.x and p.x < (sframe.x + sframe.w) and p.y >= sframe.y and p.y < (sframe.y + sframe.h) then p.x = p.x - sframe.x p.y = p.y - sframe.y else -- outside the screen is not corner moved = true middle = true return end -- Check corners if p.x < pkg.delta and p.y < pkg.delta then if middle then trigger(ul) end middle = false elseif p.x < pkg.delta and p.y > (sframe.h - pkg.delta) then if middle then trigger(ll) end middle = false elseif p.x > (sframe.w - pkg.delta) and p.y < pkg.delta then if middle then trigger(ur) end middle = false elseif p.x > (sframe.w - pkg.delta) and p.y > (sframe.h - pkg.delta) then if middle then trigger(lr) end middle = false else moved = true middle = true end end) end function pkg:start() updateScreen() mouseWatcher:start() screenWatcher:start() return self end function pkg:stop() mouseWatcher:stop() screenWatcher:stop() return self end function setCorner(corner, one, two, hold, delay) assert(one == nil or type(one) == "function", functionOrNil) assert(two == nil or type(two) == "function", functionOrNil) assert(hold == nil or type(hold) == "function", functionOrNil) assert(delay == nil or (type(delay) == "number" and delay >= 0), numberOrNil) corner.one = one corner.two = two corner.hold = hold corner.busy = false corner.delay = delay end function pkg:setUpperLeft(one, two, hold, delay) setCorner(ul, one, two, hold, delay) return self end function pkg:getULO() return ul.one end function pkg:getULT() return ul.two end function pkg:getULH() return ul.hold end function pkg:setLowerLeft(one, two, hold, delay) setCorner(ll, one, two, hold, delay) return self end function pkg:getLLO() return ll.one end function pkg:getLLT() return ll.two end function pkg:getLLH() return ll.hold end function pkg:setUpperRight(one, two, hold, delay) setCorner(ur, one, two, hold, delay) return self end function pkg:getURO() return ur.one end function pkg:getURT() return ur.two end function pkg:getURH() return ur.hold end function pkg:setLowerRight(one, two, hold, delay) setCorner(lr, one, two, hold, delay) return self end function pkg:getLRO() return lr.one end function pkg:getLRT() return lr.two end function pkg:getLRH() return lr.hold end return pkg
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You under the Apache License, Version 2.0 -- (the "License"); you may not use this file except in compliance with -- the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- local lfs = require("lfs") local log = require("apisix.core.log") local ngx = ngx local get_headers = ngx.req.get_headers local clear_header = ngx.req.clear_header local tonumber = tonumber local error = error local type = type local str_fmt = string.format local str_lower = string.lower local io_open = io.open local req_read_body = ngx.req.read_body local req_get_body_data = ngx.req.get_body_data local req_get_body_file = ngx.req.get_body_file local req_get_post_args = ngx.req.get_post_args local req_get_uri_args = ngx.req.get_uri_args local req_set_uri_args = ngx.req.set_uri_args local _M = {} local function _headers(ctx) if not ctx then ctx = ngx.ctx.api_ctx end local headers = ctx.headers if not headers then headers = get_headers() ctx.headers = headers end return headers end local function _validate_header_name(name) local tname = type(name) if tname ~= "string" then return nil, str_fmt("invalid header name %q: got %s, " .. "expected string", name, tname) end return name end _M.headers = _headers function _M.header(ctx, name) if not ctx then ctx = ngx.ctx.api_ctx end return _headers(ctx)[name] end function _M.set_header(ctx, header_name, header_value) if type(ctx) == "string" then -- It would be simpler to keep compatibility if we put 'ctx' -- after 'header_value', but the style is too ugly! header_value = header_name header_name = ctx ctx = nil log.warn("DEPRECATED: use set_header(ctx, header_name, header_value) instead") end local err header_name, err = _validate_header_name(header_name) if err then error(err) end if ctx and ctx.headers then ctx.headers[header_name] = header_value end ngx.req.set_header(header_name, header_value) end -- return the remote address of client which directly connecting to APISIX. -- so if there is a load balancer between downstream client and APISIX, -- this function will return the ip of load balancer. function _M.get_ip(ctx) if not ctx then ctx = ngx.ctx.api_ctx end return ctx.var.realip_remote_addr or ctx.var.remote_addr or '' end -- get remote address of downstream client, -- in cases there is a load balancer between downstream client and APISIX. function _M.get_remote_client_ip(ctx) if not ctx then ctx = ngx.ctx.api_ctx end return ctx.var.remote_addr or '' end function _M.get_remote_client_port(ctx) if not ctx then ctx = ngx.ctx.api_ctx end return tonumber(ctx.var.remote_port) end function _M.get_uri_args(ctx) if not ctx then ctx = ngx.ctx.api_ctx end if not ctx.req_uri_args then -- use 0 to avoid truncated result and keep the behavior as the -- same as other platforms local args = req_get_uri_args(0) ctx.req_uri_args = args end return ctx.req_uri_args end function _M.set_uri_args(ctx, args) if not ctx then ctx = ngx.ctx.api_ctx end ctx.req_uri_args = nil return req_set_uri_args(args) end function _M.get_post_args(ctx) if not ctx then ctx = ngx.ctx.api_ctx end if not ctx.req_post_args then req_read_body() -- use 0 to avoid truncated result and keep the behavior as the -- same as other platforms local args = req_get_post_args(0) ctx.req_post_args = args end return ctx.req_post_args end local function get_file(file_name) local f, err = io_open(file_name, 'r') if not f then return nil, err end local req_body = f:read("*all") f:close() return req_body end local function check_size(size, max_size) if max_size and size > max_size then return nil, "request size " .. size .. " is greater than the " .. "maximum size " .. max_size .. " allowed" end return true end local function test_expect(var) local expect = var.http_expect return expect and str_lower(expect) == "100-continue" end function _M.get_body(max_size, ctx) if max_size then local var = ctx and ctx.var or ngx.var local content_length = tonumber(var.http_content_length) if content_length then local ok, err = check_size(content_length, max_size) if not ok then -- When client_max_body_size is exceeded, Nginx will set r->expect_tested = 1 to -- avoid sending the 100 CONTINUE. -- We use trick below to imitate this behavior. if test_expect(var) then clear_header("expect") end return nil, err end end end req_read_body() local req_body = req_get_body_data() if req_body then local ok, err = check_size(#req_body, max_size) if not ok then return nil, err end return req_body end local file_name = req_get_body_file() if not file_name then return nil end log.info("attempt to read body from file: ", file_name) if max_size then local size, err = lfs.attributes (file_name, "size") if not size then return nil, err end local ok, err = check_size(size, max_size) if not ok then return nil, err end end local req_body, err = get_file(file_name) return req_body, err end function _M.get_scheme(ctx) if not ctx then ctx = ngx.ctx.api_ctx end return ctx.var.scheme or '' end function _M.get_host(ctx) if not ctx then ctx = ngx.ctx.api_ctx end return ctx.var.host or '' end function _M.get_port(ctx) if not ctx then ctx = ngx.ctx.api_ctx end return tonumber(ctx.var.server_port) end function _M.get_http_version() return ngx.req.http_version() end return _M
--- Proxy module which is responsible for handling JSON -- -- For additional information about current module functionality look at modules described in dependencies section. -- -- *Dependencies:* `json4lua.json.json` -- -- *Globals:* none -- @module json -- @copyright [Ford Motor Company](https://smartdevicelink.com/partners/ford/) and [SmartDeviceLink Consortium](https://smartdevicelink.com/consortium/) -- @license <https://github.com/smartdevicelink/sdl_core/blob/master/LICENSE> return require("json4lua.json.json")
local PlayerAccount = { CurrentlyOpened = nil; Properties = { MainMenu = {default = EntityId()}, SignIn = {default = EntityId()}, CreateAccount = {default = EntityId()}, ChangePassword = {default = EntityId()}, ConfirmSignUp = {default = EntityId()}, EditAccount = {default = EntityId()}, ForgotPassword = {default = EntityId()}, MainMenuSignedIn = {default = EntityId()}, }, } function PlayerAccount:OnActivate() self.tickBusHandler = TickBus.Connect(self) self.canvasNotificationHandler = nil self.CurrentlyOpened = self.Properties.MainMenu end function PlayerAccount:OnTick(deltaTime, timePoint) --self.tickBusHandler:Disconnect() self.CanvasEntityId = self.CanvasEntityId or UiElementBus.Event.GetCanvas(self.entityId) if self.CanvasEntityId ~= nil then if self.canvasNotificationHandler then self.canvasNotificationHandler:Disconnect() self.canvasNotificationHandler = nil end self.canvasNotificationHandler = UiCanvasNotificationBus.Connect(self, self.CanvasEntityId) end end function PlayerAccount:OnDeactivate() self.tickBusHandler:Disconnect() if self.canvasNotificationHandler then self.canvasNotificationHandler:Disconnect() end end function PlayerAccount:OnAction(entityId, actionName) if actionName == "SignIn" then UiElementBus.Event.SetIsEnabled(self.Properties.MainMenu, false) UiElementBus.Event.SetIsEnabled(self.Properties.SignIn, true) self.CurrentlyOpened = self.Properties.SignIn end if actionName == "CreateNewAccount" then UiElementBus.Event.SetIsEnabled(self.Properties.MainMenu, false) UiElementBus.Event.SetIsEnabled(self.Properties.CreateAccount, true) self.CurrentlyOpened = self.Properties.CreateAccount end if actionName == "EditAccount" then UiElementBus.Event.SetIsEnabled(self.Properties.MainMenuSignedIn, false) UiElementBus.Event.SetIsEnabled(self.Properties.EditAccount, true) self.CurrentlyOpened = self.Properties.EditAccount end if actionName == "ManagerChangePassword" then UiElementBus.Event.SetIsEnabled(self.Properties.MainMenuSignedIn, false) UiElementBus.Event.SetIsEnabled(self.Properties.ChangePassword, true) self.CurrentlyOpened = self.Properties.ChangePassword end if actionName == "SignOut" then UiElementBus.Event.SetIsEnabled(self.Properties.MainMenuSignedIn, false) UiElementBus.Event.SetIsEnabled(self.Properties.MainMenu, true) self.CurrentlyOpened = self.Properties.MainMenu end if actionName == "Exit" then end if actionName == "ForgotPassword" then UiElementBus.Event.SetIsEnabled(self.Properties.SignIn, false) UiElementBus.Event.SetIsEnabled(self.Properties.ForgotPassword, true) self.CurrentlyOpened = self.Properties.ForgotPassword end if actionName == "VerifyAccount" then UiElementBus.Event.SetIsEnabled(self.Properties.CreateAccount, false) UiElementBus.Event.SetIsEnabled(self.Properties.ConfirmSignUp, true) self.CurrentlyOpened = self.Properties.ConfirmSignUp end end return PlayerAccount
-- Copyright (C) 2018 Jérôme Leclercq -- This file is part of the "Not a Bot" application -- For conditions of distribution and use, see copyright notice in LICENSE local enums = discordia.enums local fs = require("coro-fs") local wrap = coroutine.wrap local isReady = false local function code(str) return string.format('```\n%s```', str) end -- Maps event name to function to retrieve its guild local discordiaEvents = { ["channelCreate"] = function (channel) return channel.guild end, ["channelDelete"] = function (channel) return channel.guild end, ["channelUpdate"] = function (channel) return channel.guild end, ["debug"] = function (message) end, ["emojisUpdate"] = function (guild) return guild end, ["error"] = function (message) end, ["guildAvailable"] = function (guild) return guild end, ["guildCreate"] = function (guild) return guild end, ["guildDelete"] = function (guild) return guild end, ["guildUnavailable"] = function (guild) return guild end, ["guildUpdate"] = function (guild) return guild end, ["heartbeat"] = function (shardId, latency) end, ["info"] = function (message) end, ["memberJoin"] = function (member) return member.guild end, ["memberLeave"] = function (member) return member.guild end, ["memberUpdate"] = function (member) return member.guild end, ["messageCreate"] = function (message) return message.guild end, ["messageDelete"] = function (message) return message.guild end, ["messageDeleteUncached"] = function (channel, messageId) return channel.guild end, ["messageUpdate"] = function (message) return message.guild end, ["messageUpdateUncached"] = function (channel, messageId) return channel.guild end, ["pinsUpdate"] = function (channel) return channel.guild end, ["presenceUpdate"] = function (member) return member.guild end, ["raw"] = function (string) end, ["reactionAdd"] = function (reaction, userId) return reaction.message.guild end, ["reactionAddUncached"] = function (channel, messageId, hash, userId) return channel.guild end, ["reactionRemove"] = function (reaction, userId) return reaction.message.guild end, ["reactionRemoveUncached"] = function (channel, messageId, hash, userId) return channel.guild end, ["ready"] = function () end, ["recipientAdd"] = function (relationship) end, ["recipientRemove"] = function (relationship) end, ["relationshipAdd"] = function (relationship) end, ["relationshipRemove"] = function (relationship) end, ["relationshipUpdate"] = function (relationship) end, ["roleCreate"] = function (role) return role.guild end, ["roleDelete"] = function (role) return role.guild end, ["roleUpdate"] = function (role) return role.guild end, ["shardReady"] = function (shardId) end, ["shardResumed"] = function (shardId) end, ["typingStart"] = function (userId, channelId, timestamp, client) local channel = client:getChannel(channelId) if (not channel) then return end return channel.guild end, ["userBan"] = function (user, guild) return guild end, ["userUnban"] = function (user, guild) return guild end, ["userUpdate"] = function (user) end, ["voiceChannelJoin"] = function (member, channel) return channel.guild end, ["voiceChannelLeave"] = function (member, channel) return channel.guild end, ["voiceConnect"] = function (member) return member.guild end, ["voiceDisconnect"] = function (member) return member.guild end, ["voiceUpdate"] = function (member) return member.guild end, ["warning"] = function (message) end, ["webhooksUpdate"] = function (channel) return channel.guild end } local botModuleEvents = { ["disable"] = true, ["enable"] = true, ["loaded"] = true, ["ready"] = true, ["unload"] = true } local ConfigMetatable = {} function ConfigMetatable:__newindex(key, value) print(debug.traceback()) error("Invalid config key " .. tostring(key) .. " for writing") end local ModuleMetatable = {} ModuleMetatable["__index"] = ModuleMetatable -- Config validation local validateSnowflake = function (snowflake) if (type(snowflake) ~= "string") then return false end return string.match(snowflake, "%d+") end local configTypeValidation = { [Bot.ConfigType.Boolean] = function (value) return type(value) == "boolean" end, [Bot.ConfigType.Category] = validateSnowflake, [Bot.ConfigType.Channel] = validateSnowflake, [Bot.ConfigType.Custom] = function (value) return true end, [Bot.ConfigType.Duration] = function (value) return type(value) == "number" end, [Bot.ConfigType.Emoji] = function (value) return type(value) == "string" end, [Bot.ConfigType.Integer] = function (value) return type(value) == "number" and math.floor(value) == value end, [Bot.ConfigType.Number] = function (value) return type(value) == "number" end, [Bot.ConfigType.Role] = validateSnowflake, [Bot.ConfigType.String] = function (value) return type(value) == "string" end, [Bot.ConfigType.User] = validateSnowflake, } local validateConfigType = function (configTable, value) local validator = configTypeValidation[configTable.Type] assert(validator) if (configTable.Array) then if (type(value) ~= "table") then return false end for _, arrayValue in pairs(value) do if (not validator(arrayValue)) then return false end end return true else return validator(value) end end function ModuleMetatable:_PrepareConfig(context, config, values, global) for optionIndex, configTable in pairs(config) do local reset = false local value = rawget(values, configTable.Name) if (value == nil) then reset = true elseif (not validateConfigType(configTable, value)) then self:LogWarning("%s has invalid value for option %s, resetting...", context, configTable.Name) reset = true end if (reset) then local default = configTable.Default if (type(default) == "table") then rawset(values, configTable.Name, table.deepcopy(default)) else rawset(values, configTable.Name, default) end end end end function ModuleMetatable:_PrepareGlobalConfig() if (not self.GlobalConfig) then self.GlobalConfig = {} end setmetatable(self.GlobalConfig, ConfigMetatable) return self:_PrepareConfig("Global config", self._GlobalConfig, self.GlobalConfig, true) end function ModuleMetatable:_PrepareGuildConfig(guildId, guildConfig) setmetatable(guildConfig, ConfigMetatable) return self:_PrepareConfig("Guild " .. guildId, self._GuildConfig, guildConfig, false) end function ModuleMetatable:DisableForGuild(guild, dontSave) if (not self:IsEnabledForGuild(guild)) then return true end local success, err if (self.OnDisable) then success, err = Bot:CallModuleFunction(self, "OnDisable", guild) else success = true end if (success) then local config = self:GetConfig(guild) config._Enabled = false if (not dontSave) then self:SaveGuildConfig(guild) end self:LogInfo(guild, "Module disabled") return true else return false, err end end function ModuleMetatable:EnableForGuild(guild, ignoreCheck, dontSave) if (not ignoreCheck and self:IsEnabledForGuild(guild)) then return true end local stopwatch = discordia.Stopwatch() local success, ret if (self.OnEnable) then local success, retOrErr, err = Bot:CallModuleFunction(self, "OnEnable", guild) if (not success) then return false, retOrErr end if (not retOrErr) then return false, err or "OnEnable hook returned false" end end local guildData = self:GetGuildData(guild.id) guildData._Ready = true guildData.Config._Enabled = true if (not dontSave) then self:SaveGuildConfig(guild) end self:LogInfo(guild, "Module enabled (%.3fs)", stopwatch.milliseconds / 1000) return true end function ModuleMetatable:ForEachGuild(callback, evenDisabled, evenNonReady, evenNonLoaded) for guildId, data in pairs(self._Guilds) do local guild = Bot.Client:getGuild(guildId) if ((guild or evenNonLoaded) and (evenNonReady or data._Ready) and (evenDisabled or data.Config._Enabled)) then callback(guildId, data.Config, data.Data, data.PersistentData, guild) end end end function ModuleMetatable:GetConfig(guild, noCreate) local guildData = self:GetGuildData(guild.id, noCreate) if (not guildData) then return nil end return guildData.Config end function ModuleMetatable:GetData(guild, noCreate) local guildData = self:GetGuildData(guild.id, noCreate) if (not guildData) then return nil end return guildData.Data end function ModuleMetatable:GetGuildData(guildId, noCreate) local guildData = self._Guilds[guildId] if (not guildData and not noCreate) then guildData = {} guildData.Config = { _Enabled = false } guildData.Data = {} guildData.PersistentData = {} guildData._Ready = false self:_PrepareGuildConfig(guildId, guildData.Config) self._Guilds[guildId] = guildData end return guildData end function ModuleMetatable:GetPersistentData(guild, noCreate) if (not guild) then if (not self.GlobalPersistentData) then self.GlobalPersistentData = {} end return self.GlobalPersistentData end local guildData = self:GetGuildData(guild.id, noCreate) if (not guildData) then return nil end return guildData.PersistentData end function ModuleMetatable:IsEnabledForGuild(guild) local config = self:GetConfig(guild, true) return config and config._Enabled or false end -- Log functions (LogError, LogInfo, LogWarning) for k, func in pairs({"error", "info", "warning"}) do ModuleMetatable["Log" .. string.UpperizeFirst(func)] = function (moduleTable, guild, ...) if (type(guild) == "string") then Bot.Client[func](Bot.Client, "[%s][%s] %s", "<*>", moduleTable.Name, string.format(guild, ...)) else Bot.Client[func](Bot.Client, "[%s][%s] %s", guild and guild.name or "<Invalid guild>", moduleTable.Name, string.format(...)) end end end function ModuleMetatable:RegisterCommand(values) local privilegeCheck = values.PrivilegeCheck if (privilegeCheck) then values.PrivilegeCheck = function (member) if (not self:IsEnabledForGuild(member.guild)) then return false end return privilegeCheck(member) end else values.PrivilegeCheck = function (member) return self:IsEnabledForGuild(member.guild) end end table.insert(self._Commands, values.Name) return Bot:RegisterCommand(values) end function ModuleMetatable:Save(guild) self:SaveGuildConfig(guild) self:SavePersistentData(guild) end function ModuleMetatable:SaveGlobalConfig() local filepath = string.format("data/module_%s/global_config.json", self.Name) local success, err = Bot:SerializeToFile(filepath, self.GlobalConfig, true) if (not success) then self:LogWarning(nil, "Failed to save global config: %s", err) end end function ModuleMetatable:SaveGlobalPersistentData() if (not self.GlobalPersistentData) then return end local filepath = string.format("data/module_%s/global_data.json", self.Name) local success, err = Bot:SerializeToFile(filepath, self.GlobalPersistentData, true) if (not success) then self:LogWarning(nil, "Failed to save global data: %s", err) end end function ModuleMetatable:LoadGuildConfig(guild) local guildData = self:GetGuildData(guild.id) local config, err = Bot:UnserializeFromFile(string.format("data/module_%s/guild_%s/config.json", self.Name, guild.id)) if (config) then self:_PrepareGuildConfig(guild.id, config) guildData.Config = config return true else self:LogError(guild, "Failed to load config: %s", err) return false, err end end function ModuleMetatable:SaveGuildConfig(guild) local save = function (guildId, guildConfig) local filepath = string.format("data/module_%s/guild_%s/config.json", self.Name, guildId) local success, err = Bot:SerializeToFile(filepath, guildConfig, true) if (not success) then self:LogWarning(guild, "Failed to save persistent data: %s", err) end end if (guild) then local guildConfig = self:GetConfig(guild, true) if (guildConfig) then save(guild.id, guildConfig) end else self:ForEachGuild(function (guildId, config, data, persistentData) save(guildId, config) end) end end function ModuleMetatable:SavePersistentData(guild) local save = function (guildId, persistentData) local filepath = string.format("data/module_%s/guild_%s/persistentdata.json", self.Name, guildId) local success, err = Bot:SerializeToFile(filepath, persistentData) if (not success) then self:LogWarning(guild, "Failed to save persistent data: %s", err) end end if (guild) then local guildData = self:GetPersistentData(guild, true) if (guildData) then save(guild.id, guildData) end else self:SaveGlobalPersistentData() self:ForEachGuild(function (guildId, config, data, persistentData) save(guildId, persistentData) end) end end function Bot:CallModuleFunction(moduleTable, functionName, ...) return self:ProtectedCall(string.format("Module (%s) function (%s)", moduleTable.Name, functionName), moduleTable[functionName], moduleTable, ...) end function Bot:CallOnReady(moduleTable) if (moduleTable.OnReady) then wrap(function () self:CallModuleFunction(moduleTable, "OnReady") end)() end end function Bot:DisableModule(moduleName, guild) local moduleTable = self.Modules[moduleName] if (moduleTable) then if (not moduleTable:IsEnabledForGuild(guild)) then return false, "Module is already disabled on this server" end return moduleTable:DisableForGuild(guild) end return false, "Module not loaded" end function Bot:EnableModule(moduleName, guild) local moduleTable = self.Modules[moduleName] if (moduleTable) then if (moduleTable:IsEnabledForGuild(guild)) then return false, "Module is already enabled on this server" end return moduleTable:EnableForGuild(guild) end return false, "Module not loaded" end function Bot:LoadModule(moduleTable) self:UnloadModule(moduleTable.Name) local stopwatch = discordia.Stopwatch() -- Load config local guildConfig = {} local globalConfig = {} if (moduleTable.GetConfigTable) then local success, ret = self:CallModuleFunction(moduleTable, "GetConfigTable") if (not success) then return false, "Failed to load config: " .. ret end if (type(ret) ~= "table") then return false, "Invalid config" end local config = ret -- Validate config local validConfigOptions = { -- Field = {type, mandatory, default} ["Array"] = {"boolean", false, false}, ["Default"] = {"any", false}, ["Description"] = {"string", true}, ["Global"] = {"boolean", false, false}, ["Optional"] = {"boolean", false, false}, ["Name"] = {"string", true}, ["Sensitive"] = {"boolean", false, false}, ["Type"] = {"number", true} } for optionIndex, configTable in pairs(config) do for configName, configValue in pairs(configTable) do local expectedType = validConfigOptions[configName][1] if (not expectedType) then return false, string.format("[%s] Option #%s has invalid key \"%s\"", configTable.Name, optionIndex, configName) end if (expectedType ~= "any" and type(configValue) ~= expectedType) then return false, string.format("[%s] Option #%s has key \"%s\" which has invalid type %s (expected %s)", configTable.Name, optionIndex, configName, type(configValue), expectedType) end end for key, value in pairs(validConfigOptions) do local mandatory = value[2] if (mandatory) then if (not configTable[key]) then return false, string.format("Option #%s has no \"%s\" key", optionIndex, key) end else if (configTable[key] == nil) then local defaultValue = value[3] configTable[key] = defaultValue end end end if (configTable.Default == nil and not configTable.Optional) then return false, string.format("[%s] Option #%s is not optional and has no default value", configTable.Name, optionIndex) end if (configTable.Global) then table.insert(globalConfig, configTable) else table.insert(guildConfig, configTable) end end end moduleTable._GlobalConfig = globalConfig moduleTable._GuildConfig = guildConfig -- Parse events local moduleEvents = {} for key,func in pairs(moduleTable) do if (key:startswith("On") and type(func) == "function") then local eventName = key:sub(3, 3):lower() .. key:sub(4) if (not botModuleEvents[eventName]) then if (not discordiaEvents[eventName]) then return false, "Module tried to bind hook \"" .. eventName .. "\" which doesn't exist" end moduleEvents[eventName] = {Module = moduleTable, Callback = function (moduleTable, ...) self:CallModuleFunction(moduleTable, key, ...) end} end end end moduleTable._Events = moduleEvents moduleTable._Commands = {} moduleTable._Guilds = {} setmetatable(moduleTable, ModuleMetatable) -- Load module persistent data from disk self:LoadModuleData(moduleTable) moduleTable:_PrepareGlobalConfig() -- Loading finished, call callback self.Modules[moduleTable.Name] = moduleTable if (moduleTable.OnLoaded) then local success, err = self:CallModuleFunction(moduleTable, "OnLoaded") if (not success or not err) then self.Modules[moduleTable.Name] = nil err = err or "OnLoaded hook returned false" return false, err end end local loadTime = stopwatch.milliseconds / 1000 self.Client:info("[<*>][%s] Loaded module (%.3fs)", moduleTable.Name, stopwatch.milliseconds / 1000) if (isReady) then self:CallOnReady(moduleTable) self:MakeModuleReady(moduleTable) end return moduleTable end function Bot:LoadModuleFile(fileName) local sandbox = setmetatable({ }, { __index = _G }) sandbox.Bot = self sandbox.Client = self.Client sandbox.Config = Config sandbox.Discordia = discordia sandbox.Module = {} sandbox.require = require -- I still don't understand why we have to do this local func, err = loadfile(fileName, "bt", sandbox) if (not func) then return false, "Failed to load module:", err end local ret, err = pcall(func) if (not ret) then return false, "Failed to call module:", err end local moduleName = sandbox.Module.Name if (not moduleName or type(moduleName) ~= "string") then return false, "Module has an invalid name" end return self:LoadModule(sandbox.Module) end function Bot:LoadModuleData(moduleTable) -- Must be called from within a coroutine local dataFolder = string.format("data/module_%s", moduleTable.Name) local dataIt = fs.scandir(dataFolder) if (dataIt) then for entry in assert(dataIt) do local path = dataFolder .. "/" .. entry.name if (entry.type == "directory") then local guildId = entry.name:match("guild_(%d+)") if (guildId) then local guildData = moduleTable:GetGuildData(guildId) local config, err = self:UnserializeFromFile(path .. "/config.json") if (config) then guildData.Config = config moduleTable:_PrepareGuildConfig(guildId, guildData.Config) else self.Client:error("Failed to load config of guild %s (%s module): %s", guildId, moduleTable.Name, err) end local persistentData, err = self:UnserializeFromFile(path .. "/persistentdata.json") if (persistentData) then guildData.PersistentData = persistentData else self.Client:error("Failed to load persistent data of guild %s (%s module): %s", guildId, moduleTable.Name, err) end end elseif (entry.type == "file") then if (entry.name == "global_config.json") then local config, err = self:UnserializeFromFile(path) if (config) then moduleTable.GlobalConfig = config self.Client:info("Global config of module %s has been loaded", moduleTable.Name) else self.Client:error("Failed to load global config module %s: %s", moduleTable.Name, err) end elseif (entry.name == "global_data.json") then local data, err = self:UnserializeFromFile(path) if (data) then moduleTable.GlobalPersistentData = data self.Client:info("Global data of module %s has been loaded", moduleTable.Name) else self.Client:error("Failed to load global config module %s: %s", moduleTable.Name, err) end end end end end end function Bot:MakeModuleReady(moduleTable) moduleTable:ForEachGuild(function (guildId, config, data, persistentData, guild) moduleTable:EnableForGuild(guild, true, true) end, false, true) for eventName,eventData in pairs(moduleTable._Events) do local eventTable = self.Events[eventName] if (not eventTable) then eventTable = {} self.Client:onSync(eventName, function (...) local parameters = {...} table.insert(parameters, self.Client) local eventGuild = discordiaEvents[eventName](table.unpack(parameters)) for _, eventData in pairs(eventTable) do if (not eventGuild or eventData.Module:IsEnabledForGuild(eventGuild)) then wrap(eventData.Callback)(eventData.Module, ...) end end end) self.Events[eventName] = eventTable end table.insert(eventTable, eventData) end end function Bot:UnloadModule(moduleName) local moduleTable = self.Modules[moduleName] if (moduleTable) then moduleTable:ForEachGuild(function (guildId, config, data, persistentData, guild) moduleTable:DisableForGuild(guild, true) end, false, true) if (isReady and moduleTable.OnUnload) then moduleTable:OnUnload() end moduleTable:SavePersistentData() for eventName,func in pairs(moduleTable._Events) do local eventTable = self.Events[eventName] assert(eventTable) local i = table.search(eventTable, func) assert(i) table.remove(eventTable, i) end for _, commandName in pairs(moduleTable._Commands) do Bot:UnregisterCommand(commandName) end self.Modules[moduleName] = nil self.Client:info("[<*>][%s] Unloaded module", moduleTable.Name) return true end return false end Bot.Client:onSync("ready", function () if (isReady) then for moduleName,moduleTable in pairs(Bot.Modules) do Bot:CallOnReady(moduleTable) end else for moduleName,moduleTable in pairs(Bot.Modules) do Bot:CallOnReady(moduleTable) Bot:MakeModuleReady(moduleTable) end end isReady = true end) Bot:RegisterCommand({ Name = "modulelist", Args = {}, PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end, Help = "Configures a module", Func = function (message) local moduleList = {} for moduleName, moduleTable in pairs(Bot.Modules) do table.insert(moduleList, moduleTable) end table.sort(moduleList, function (a, b) return a.Name < b.Name end) local moduleListStr = {} for _, moduleTable in pairs(moduleList) do local enabledEmoji if (moduleTable.Global) then enabledEmoji = ":globe_with_meridians:" elseif (moduleTable:IsEnabledForGuild(message.guild)) then enabledEmoji = ":white_check_mark:" else enabledEmoji = ":x:" end table.insert(moduleListStr, string.format("%s **%s**", enabledEmoji, moduleTable.Name)) end message:reply({ embed = { title = "Module list", fields = { {name = "Loaded modules", value = table.concat(moduleListStr, '\n')}, }, timestamp = discordia.Date():toISO('T', 'Z') } }) end }) Bot:RegisterCommand({ Name = "config", Args = { {Name = "module", Type = Bot.ConfigType.String}, {Name = "action", Type = Bot.ConfigType.String, Optional = true}, {Name = "key", Type = Bot.ConfigType.String, Optional = true}, {Name = "value", Type = Bot.ConfigType.String, Optional = true} }, PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end, Help = "Configures a module", Func = function (message, moduleName, action, key, value) moduleName = moduleName:lower() local moduleTable = Bot.Modules[moduleName] if (not moduleTable) then message:reply("Invalid module \"" .. moduleName .. "\"") return end action = action and action:lower() or "list" local globalConfig = moduleTable.GlobalConfig local guild = message.guild local guildConfig = moduleTable:GetConfig(guild) local StringifyConfigValue = function (configTable, value) if (value ~= nil) then local valueToString = Bot.ConfigTypeToString[configTable.Type] if (configTable.Array) then local valueStr = {} for _, value in pairs(value) do table.insert(valueStr, valueToString(value, guild)) end return table.concat(valueStr, ", ") else return valueToString(value, guild) end else if (not configTable.Optional) then error("Config " .. configTable.Name .. " has no value but is not optional") end return "<None>" end end local GenerateField = function (configTable, value, allowSensitive, wasModified) local valueStr if (not configTable.Sensitive or allowSensitive) then valueStr = StringifyConfigValue(configTable, value) else valueStr = "*<sensitive>*" end local fieldType = Bot.ConfigTypeString[configTable.Type] if (configTable.Array) then fieldType = fieldType .. " array" end return { name = string.format("%s:gear: %s", configTable.Global and ":globe_with_meridians: " or "", configTable.Name), value = string.format("**Description:** %s\n**Value (%s):** %s", configTable.Description, fieldType, valueStr) } end local GetConfigByKey = function (key) for k,configData in pairs(moduleTable._GuildConfig) do if (configData.Name == key) then return configData end end if (message.member.id == Config.OwnerUserId) then for k,configData in pairs(moduleTable._GlobalConfig) do if (configData.Name == key) then return configData end end end end if (action == "list") then local fields = {} local globalFields = {} for k,configTable in pairs(moduleTable._GuildConfig) do table.insert(fields, GenerateField(configTable, rawget(guildConfig, configTable.Name))) end if (message.member.id == Config.OwnerUserId) then for k,configTable in pairs(moduleTable._GlobalConfig) do table.insert(fields, GenerateField(configTable, rawget(moduleTable.GlobalConfig, configTable.Name))) end end local enabledText if (moduleTable.Global) then enabledText = ":globe_with_meridians: This module is global and cannot be enabled nor disabled on a guild basis" elseif (moduleTable:IsEnabledForGuild(guild)) then enabledText = ":white_check_mark: Module **enabled** (use `!disable " .. moduleTable.Name .. "` to disable it)" else enabledText = ":x: Module **disabled** (use `!enable " .. moduleTable.Name .. "` to enable it)" end message:reply({ embed = { title = "Configuration for " .. moduleTable.Name .. " module", description = string.format("%s\n\nConfiguration list:", enabledText, moduleTable.Name), fields = fields, footer = {text = string.format("Use `!config %s add/remove/reset/set/show ConfigName <value>` to change configuration settings.", moduleTable.Name)} } }) elseif (action == "show") then local configTable = GetConfigByKey(key) if (not configTable) then message:reply(string.format("Module %s has no config key \"%s\"", moduleTable.Name, key)) return end local config = configTable.Global and globalConfig or guildConfig message:reply({ embed = { title = "Configuration of " .. moduleTable.Name .. " module", fields = { GenerateField(configTable, rawget(config, configTable.Name), true) }, timestamp = discordia.Date():toISO('T', 'Z') } }) elseif (action == "add" or action == "remove" or action == "reset" or action == "set") then if (not key) then message:reply("Missing config key name") return end local configTable = GetConfigByKey(key) if (not configTable) then message:reply(string.format("Module %s has no config key \"%s\"", moduleTable.Name, key)) return end if (not configTable.Array and (action == "add" or action == "remove")) then message:reply("Configuration **" .. configTable.Name .. "** is not an array, use the *set* action to change its value") return end local newValue if (action ~= "reset") then if (not value or #value == 0) then if (configTable.Optional and action == "set") then value = nil else message:reply("Missing config value") return end end if (value) then local valueParser = Bot.ConfigTypeParser[configTable.Type] newValue = valueParser(value, guild) if (newValue == nil) then message:reply("Failed to parse new value (type: " .. Bot.ConfigTypeString[configTable.Type] .. ")") return end end else local default = configTable.Default if (type(default) == "table") then newValue = table.deepcopy(default) else newValue = default end end local wasModified = false local config = configTable.Global and globalConfig or guildConfig if (action == "add") then assert(configTable.Array) -- Insert value (if not present) local found = false local values = rawget(config, configTable.Name) if (not values) then assert(configTable.Optional) values = {} rawset(config, configTable.Name, values) end for _, value in pairs(values) do if (value == newValue) then found = true break end end if (not found) then table.insert(values, newValue) wasModified = true end elseif (action == "remove") then assert(configTable.Array) -- Remove value (if present) local values = rawget(config, configTable.Name) if (values) then for i = 1, #values do if (values[i] == newValue) then table.remove(values, i) wasModified = true break end end else assert(configTable.Optional) end elseif (action == "reset" or action == "set") then -- Replace value if (configTable.Array and action ~= "reset") then rawset(config, configTable.Name, {newValue}) else rawset(config, configTable.Name, newValue) end wasModified = true end if (wasModified) then if (configTable.Global) then moduleTable:SaveGlobalConfig() else moduleTable:SaveGuildConfig(guild) end end message:reply({ embed = { title = "Configuration update for " .. moduleTable.Name .. " module", fields = { GenerateField(configTable, config[configTable.Name], false, wasModified) }, timestamp = discordia.Date():toISO('T', 'Z') } }) else message:reply("Invalid action \"" .. action .. "\" (valid actions are *add*, *remove*, *reset*, *set* or *show*)") end end }) Bot:RegisterCommand({ Name = "load", Args = { {Name = "modulefile", Type = Bot.ConfigType.String} }, PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end, Help = "(Re)loads a module", Func = function (message, moduleFile) local moduleTable, err, codeErr = Bot:LoadModuleFile(moduleFile) if (moduleTable) then message:reply("Module **" .. moduleTable.Name .. "** loaded") else local errorMessage = err if (codeErr) then errorMessage = errorMessage .. "\n" .. code(codeErr) end message:reply("Failed to load module: " .. errorMessage) end end }) Bot:RegisterCommand({ Name = "disable", Args = { {Name = "module", Type = Bot.ConfigType.String} }, PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end, Help = "Disables a module", Func = function (message, moduleName) local success, err = Bot:DisableModule(moduleName, message.guild) if (success) then message:reply("Module **" .. moduleName .. "** disabled") else message:reply("Failed to disable **" .. moduleName .. "** module: " .. err) end end }) Bot:RegisterCommand({ Name = "enable", Args = { {Name = "module", Type = Bot.ConfigType.String} }, PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end, Help = "Enables a module", Func = function (message, moduleName) local success, err = Bot:EnableModule(moduleName, message.guild) if (success) then message:reply("Module **" .. moduleName .. "** enabled") else message:reply("Failed to enable **" .. moduleName .. "** module: " .. tostring(err)) end end }) Bot:RegisterCommand({ Name = "reload", Args = { {Name = "module", Type = Bot.ConfigType.String} }, PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end, Help = "Reloads a module (as disable/enable would do)", Func = function (message, moduleName) local moduleTable = Bot.Modules[moduleName] if (not moduleTable) then message:reply("Module **" .. moduleName .. "** doesn't exist") return end if (not moduleTable:IsEnabledForGuild(message.guild)) then message:reply("Module **" .. moduleName .. "** is not enabled") return end local success, err = moduleTable:DisableForGuild(message.guild, true) if (success) then local success, err = moduleTable:EnableForGuild(message.guild, false, true) if (success) then message:reply("Module **" .. moduleName .. "** reloaded") else message:reply("Failed to re-enable **" .. moduleName .. "** module: " .. err) end else message:reply("Failed to disable **" .. moduleName .. "** module: " .. err) end end }) Bot:RegisterCommand({ Name = "unload", Args = { {Name = "module", Type = Bot.ConfigType.String} }, PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end, Help = "Unloads a module", Func = function (message, moduleName) if (Bot:UnloadModule(moduleName)) then message:reply("Module **" .. moduleName .. "** unloaded.") else message:reply("Module **" .. moduleName .. "** not found.") end end }) Bot:RegisterCommand({ Name = "reloadconfig", Args = { {Name = "modulename", Type = Bot.ConfigType.String} }, PrivilegeCheck = function (member) return member.id == Config.OwnerUserId end, Help = "(Re)loads a module's config from file on a guild", Func = function (message, moduleName) local moduleTable = Bot.Modules[moduleName] if (not moduleTable) then message:reply("Module **" .. moduleName .. "** doesn't exist") return end local success, err = moduleTable:LoadGuildConfig(message.guild) if (success) then message:reply("Module **" .. moduleName .. "** configuration reloaded") else message:reply("Failed to reload **" .. moduleName .. "** configuration: " .. err) end end })
local createSignal = require(script.Parent.createSignal) local Symbol = require(script.Parent.Symbol) local Type = require(script.Parent.Type) local config = require(script.Parent.GlobalConfig).get() --[[ Default mapping function used for non-mapped bindings ]] local function identity(value) return value end local Binding = {} --[[ Set of keys for fields that are internal to Bindings ]] local InternalData = Symbol.named("InternalData") local bindingPrototype = {} bindingPrototype.__index = bindingPrototype bindingPrototype.__tostring = function(self) return ("RoactBinding(%s)"):format(tostring(self[InternalData].value)) end --[[ Get the current value from a binding ]] function bindingPrototype:getValue() local internalData = self[InternalData] --[[ If our source is another binding but we're not subscribed, we'll return the mapped value from our upstream binding. This allows us to avoid subscribing to our source until someone has subscribed to us, and avoid creating dangling connections. ]] if internalData.upstreamBinding ~= nil and internalData.upstreamDisconnect == nil then return internalData.valueTransform(internalData.upstreamBinding:getValue()) end return internalData.value end --[[ Creates a new binding from this one with the given mapping. ]] function bindingPrototype:map(valueTransform) if config.typeChecks then assert(typeof(valueTransform) == "function", "Bad arg #1 to binding:map: expected function") end local binding = Binding.create(valueTransform(self:getValue())) binding[InternalData].valueTransform = valueTransform binding[InternalData].upstreamBinding = self return binding end --[[ Update a binding's value. This is only accessible by Roact. ]] function Binding.update(binding, newValue) local internalData = binding[InternalData] newValue = internalData.valueTransform(newValue) internalData.value = newValue internalData.changeSignal:fire(newValue) end --[[ Subscribe to a binding's change signal. This is only accessible by Roact. ]] function Binding.subscribe(binding, handler) local internalData = binding[InternalData] --[[ If this binding is mapped to another and does not have any subscribers, we need to create a subscription to our source binding so that updates get passed along to us ]] if internalData.upstreamBinding ~= nil and internalData.subscriberCount == 0 then internalData.upstreamDisconnect = Binding.subscribe(internalData.upstreamBinding, function(value) Binding.update(binding, value) end) end local disconnect = internalData.changeSignal:subscribe(handler) internalData.subscriberCount = internalData.subscriberCount + 1 local disconnected = false --[[ We wrap the disconnect function so that we can manage our subscriptions when the disconnect is triggered ]] return function() if disconnected then return end disconnected = true disconnect() internalData.subscriberCount = internalData.subscriberCount - 1 --[[ If our subscribers count drops to 0, we can safely unsubscribe from our source binding ]] if internalData.subscriberCount == 0 and internalData.upstreamDisconnect ~= nil then internalData.upstreamDisconnect() internalData.upstreamDisconnect = nil end end end --[[ Create a new binding object with the given starting value. This function will be exposed to users of Roact. ]] function Binding.create(initialValue) local binding = { [Type] = Type.Binding, [InternalData] = { value = initialValue, changeSignal = createSignal(), subscriberCount = 0, valueTransform = identity, upstreamBinding = nil, upstreamDisconnect = nil, }, } setmetatable(binding, bindingPrototype) local setter = function(newValue) Binding.update(binding, newValue) end return binding, setter end return Binding
local cutils = require 'libcutils' local Reducer = require 'Q/RUNTIME/RDCR/lua/Reducer' local qconsts = require 'Q/UTILS/lua/qconsts' local qc = require 'Q/UTILS/lua/qcore' local qmem = require 'Q/UTILS/lua/qmem' local get_ptr = require 'Q/UTILS/lua/get_ptr' local record_time = require 'Q/UTILS/lua/record_time' local csz = qmem.chunk_size return function (a, x, optargs) -- Return early if you have cached the result of a previous call if ( x:is_eov() ) then -- Note that reserved keywords are prefixed by __ -- For example, minval is stored with key = "__min" local rslt = x:get_meta("__" .. a) if ( rslt ) then assert(type(rslt) == "table") local extractor = function (tbl) return unpack(tbl) end return Reducer ({value = rslt, func = extractor}) end end local sp_fn_name = "Q/OPERATORS/F_TO_S/lua/" .. a .. "_specialize" local spfn = assert(require(sp_fn_name)) local subs = assert(spfn(x, optargs)) -- subs must return (1) args (2) getter (3) cst_in_as local func_name = assert(subs.fn) qc.q_add(subs) local cargs = assert(subs.cargs) local cst_cargs = assert(get_ptr(cargs, subs.cst_cargs_as)) local getter = assert(subs.getter) assert(type(getter) == "function") --================== local is_eor = false -- eor = End Of Reducer local l_chunk_num = 0 --================== local lgen = function(chunk_num) assert(chunk_num == l_chunk_num) local offset = l_chunk_num * csz local x_len, x_chunk, nn_x_chunk = x:get_chunk(l_chunk_num) if ( ( not x_len ) or ( x_len == 0 ) ) then return nil end local inx = get_ptr(x_chunk, subs.cst_in_as) local start_time = cutils.rdtsc() qc[func_name](inx, x_len, cst_cargs, offset) record_time(start_time, func_name) x:unget_chunk(l_chunk_num) l_chunk_num = l_chunk_num + 1 if ( x_len < csz ) then is_eor = true end return cargs, is_eor end local s = Reducer ( { gen = lgen, func = getter, value = cargs} ) return s end
--- --- Generated by EmmyLua(https://github.com/EmmyLua) --- Created by heyqule. --- DateTime: 7/3/2021 12:16 PM --- if mods['space-exploration'] or mods['alien-biomes'] then -- Handle space exploration / alien-biomes collision layer local collision_mask_util_extended = require("__alien-biomes__/collision-mask-util-extended/data/collision-mask-util-extended") collision_mask_util_extended.get_make_named_collision_mask('flying-layer') elseif mods['combat-mechanics-overhaul'] then local collision_mask_util_extended = require("__combat-mechanics-overhaul__/collision-mask-util-extended/data/collision-mask-util-extended") collision_mask_util_extended.get_make_named_collision_mask('flying-layer') else -- Handle vanilla collision layer local collision_mask_util = require("__core__/lualib/collision-mask-util") local flying_layer = collision_mask_util.get_first_unused_layer() data:extend({ { type = "arrow", name = "collision-mask-flying-layer", collision_mask = {flying_layer}, flags = {"placeable-off-grid", "not-on-map"}, circle_picture = { filename = "__core__/graphics/empty.png", priority = "low", width = 1, height = 1}, arrow_picture = { filename = "__core__/graphics/empty.png", priority = "low", width = 1, height = 1} } }) end
{data={name="Ulmatcitidel", author="Magnus siiftun1857 Frankline"}, blocks={ {0x12f390, {-50.06, 40.804}, command={faction=1242}}, {0x12f39a, {-70.06, 160.804}}, {0x12f394, {-80.06, 50.804}}, {0x12f394, {-120.06, 50.804}}, {0x12f399, {-200.06, 60.804}, -1.571}, {0x12f3a0, {-156.06, 60.804}, 3.142}, {0x12f399, {-10.06, -169.196}}, {0x12f3a0, {-10.06, -125.196}, -1.571}, {0x12f3a3, {-170.06, -89.196}}, {0x12f394, {-20.06, 10.804}}, {0x12f3a4, {-150.06, -129.196}}, {0x12f39f, {-20.06, -99.196}}, {0x12f394, {-100.06, 10.804}}, {0x12f39e, {-140.06, 10.804}}, {0x12f3a0, {-164.06, -19.196}}, {0x12f6b1, {-60.06, 10.804}}, {0x12f394, {-20.06, -29.196}}, {0x12f394, {-60.06, -29.196}}, {0x12f3a2, {5.94, -73.196}}, {0x12f3a1, {-54.06, -85.196}}, {0x12f39f, {-60.06, -59.196}}, {0x12f394, {-100.06, -29.196}}, {0x12f3a3, {-140.06, -39.196}, -1.571}, {0x12f3a3, {-100.06, -119.196}, -1.571}, {0x12f3a4, {-110.06, -89.196}}, {0x12f3a4, {-130.06, -69.196}}, {0x12f392, {-45.06, 60.804}}, {0x12f392, {-35.06, 40.804}}, {0x12f392, {-25.06, 40.804}}, {0x12f392, {-15.06, 40.804}}, {0x12f392, {-5.06, 40.804}}, {0x12f392, {4.94, 40.804}}, {0x12f392, {14.94, 40.804}}, {0x12f392, {24.94, 40.804}}, {0x12f392, {34.94, 40.804}}, {0x12f392, {44.94, 40.804}}, {0x12f392, {54.94, 40.804}}, {0x12f392, {64.94, 40.804}}, {0x12f392, {74.94, 40.804}}, {0x12f392, {84.94, 40.804}}, {0x12f392, {94.94, 40.804}}, {0x12f392, {104.94, 40.804}}, {0x12f393, {9.94, 180.804}}, {0x12f394, {59.94, 10.804}}, {0x12f392, {-55.06, 60.804}}, {0x12f394, {-20.06, 70.804}}, {0x12f392, {-45.06, 80.804}}, {0x12f392, {-55.06, 80.804}}, {0x12f394, {-120.06, 90.804}}, {0x12f394, {19.94, -9.196}}, {0x12f39a, {9.94, 20.804}}, {0x12f39a, {29.94, 20.804}}, {0x12f393, {9.94, -139.196}}, {0x12f393, {-30.06, -139.196}}, {0x12f393, {-170.06, 40.804}}, {0x12f393, {-170.06, 80.804}}, {0x12f391, {-195.06, 35.804}}, {0x12f391, {-185.06, 35.804}}, {0x12f391, {-185.06, 25.804}}, {0x12f391, {-185.06, 85.804}}, {0x12f391, {-195.06, 85.804}}, {0x12f391, {-185.06, 95.804}}, {0x12f391, {-35.06, -154.196}}, {0x12f391, {-35.06, -164.196}}, {0x12f391, {-45.06, -154.196}}, {0x12f391, {14.94, -154.196}}, {0x12f391, {24.94, -154.196}}, {0x12f391, {14.94, -164.196}}, {0x12f52c, {59.94, -29.196}}, {0x12f394, {-120.06, 130.804}}, {0x12f3a0, {-156.06, 120.804}, 3.142}, {0x12f3a4, {-170.06, 150.804}}, {0x12f3a1, {-136.06, 184.804}, -1.571}, {0x12f394, {-100.06, 170.804}}, {0x12f3a3, {-110.06, 210.804}}, {0x12f394, {-80.06, 130.804}}, {0x12f392, {-55.06, 100.804}}, {0x12f392, {-45.06, 100.804}}, {0x12f392, {-55.06, 120.804}}, {0x12f392, {-45.06, 120.804}}, {0x12f392, {-55.06, 140.804}}, {0x12f392, {-45.06, 140.804}}, {0x12f392, {-45.06, 160.804}}, {0x12f392, {-55.06, 160.804}}, {0x12f392, {-55.06, 180.804}}, {0x12f392, {-45.06, 180.804}}, {0x12f392, {-65.06, 180.804}}, {0x12f6b4, {-80.06, 90.804}}, {0x12f52a, {19.94, -49.196}}, {0x12f392, {-75.06, 180.804}}, {0x12f394, {-20.06, 110.804}}, {0x12f394, {19.94, 70.804}}, {0x12f394, {59.94, -69.196}}, {0x12f394, {99.94, 10.804}}, {0x12f394, {99.94, -69.196}}, {0x12f394, {99.94, -29.196}}, {0x12f394, {-60.06, 210.804}}, {0x12f394, {59.94, 70.804}}, {0x12f394, {-20.06, 150.804}}, {0x12f392, {114.94, 40.804}}, {0x12f3a2, {53.94, -105.196}, 3.142}, {0x12f3a2, {95.94, -115.196}, -1.571}, {0x12f39e, {139.94, -89.196}}, {0x12f3a3, {129.94, -129.196}}, {0x12f394, {99.94, 70.804}}, {0x12f394, {139.94, 70.804}}, {0x12f392, {154.94, 40.804}}, {0x12f394, {139.94, 10.804}}, {0x12f392, {124.94, 40.804}}, {0x12f392, {134.94, 40.804}}, {0x12f392, {144.94, 40.804}}, {0x12f392, {-35.06, 180.804}}, {0x12f392, {-25.06, 180.804}}, {0x12f392, {-15.06, 180.804}}, {0x12f392, {-5.06, 180.804}}, {0x12f394, {-20.06, 210.804}}, {0x12f391, {4.94, 95.804}}, {0x12f391, {14.94, 95.804}}, {0x12f391, {24.94, 95.804}}, {0x12f391, {54.94, 95.804}}, {0x12f391, {44.94, 95.804}}, {0x12f391, {34.94, 95.804}}, {0x12f391, {84.94, 95.804}}, {0x12f391, {74.94, 95.804}}, {0x12f391, {64.94, 95.804}}, {0x12f391, {114.94, 95.804}}, {0x12f391, {104.94, 95.804}}, {0x12f391, {94.94, 95.804}}, {0x12f391, {134.94, 95.804}}, {0x12f391, {144.94, 95.804}}, {0x12f391, {154.94, 95.804}}, {0x12f391, {124.94, 95.804}}, {0x12f391, {4.94, 105.804}}, {0x12f391, {4.94, 125.804}}, {0x12f391, {4.94, 115.804}}, {0x12f391, {4.94, 135.804}}, {0x12f391, {4.94, 145.804}}, {0x12f391, {4.94, 205.804}}, {0x12f391, {4.94, 195.804}}, {0x12f393, {129.94, -19.196}}, {0x12f393, {149.94, -19.196}}, {0x12f391, {4.94, 165.804}}, {0x12f391, {4.94, 155.804}}, {0x12f391, {4.94, 215.804}}, {0x12f391, {4.94, 225.804}}, {0x12f393, {129.94, -59.196}}, {0x12f39f, {159.94, -39.196}}, {0x12f39f, {179.94, -59.196}}, {0x12f39f, {239.94, -39.196}}, {0x12f39f, {259.94, -59.196}}, {0x12f39f, {319.94, -39.196}}, {0x12f39f, {399.94, -39.196}}, {0x12f39f, {419.94, -59.196}}, {0x12f39f, {339.94, -59.196}}, {0x12f39f, {-90.06, 250.804}, -1.571}, {0x12f39f, {-110.06, 270.804}, -1.571}, {0x12f39f, {-90.06, 330.804}, -1.571}, {0x12f39f, {-110.06, 350.804}, -1.571}}}
-- Copyright (c) 2021, Eisa AlAwadhi -- License: BSD 2-Clause License -- Creator: Eisa AlAwadhi -- Project: UndoRedo -- Version: 2.2 local utils = require 'mp.utils' local msg = require 'mp.msg' local seconds = 0 local countTimer = -1 local seekTime = 0 local seekNumber = 0 local currentIndex = 0 local seekTable = {} local seeking = 0 local undoRedo = 0 local pause = false seekTable[0] = 0 ----------------------------USER CUSTOMIZATION SETTINGS----------------------------------- --These settings are for users to manually change some options in the script. --Keybinds can be defined in the bottom of the script. local osd_messages = true --true is for displaying osd messages when actions occur, Change to false will disable all osd messages generated from this script ---------------------------END OF USER CUSTOMIZATION SETTINGS--------------------- local function prepareUndoRedo() if (pause == true) then seconds = seconds else seconds = seconds - 0.5 end seekTable[currentIndex] = seekTable[currentIndex] + seconds seconds = 0 end local function getUndoRedo() if (seeking == 0) then prepareUndoRedo() seekNumber = currentIndex + 1 currentIndex = seekNumber seekTime = math.floor(mp.get_property_number('time-pos')) table.insert(seekTable, seekNumber, seekTime) undoRedo = 0 elseif (seeking == 1) then seeking = 0 end end mp.register_event('file-loaded', function() filePath = mp.get_property('path') timer = mp.add_periodic_timer(0.1, function() seconds = seconds + 0.1 end) if (pause == true) then timer:stop() else timer:resume() end timer2 = mp.add_periodic_timer(0.1, function() countTimer = countTimer + 0.1 if (countTimer == 0.6) then timer:resume() getUndoRedo() end end) timer2:stop() end) mp.register_event('seek', function() countTimer = 0 timer2:resume() timer:stop() end) mp.observe_property('pause', 'bool', function(name, value) if value then if timer ~= nil then timer:stop() end pause = true else if timer ~= nil then timer:resume() end pause = false end end) mp.register_event('end-file', function() if timer ~= nil then timer:kill() end if timer2 ~= nil then timer2:kill() end seekNumber = 0 currentIndex = 0 undoRedo = 0 seconds = 0 countTimer = -1 seekTable[0] = 0 end) local function undo() if (filePath ~= nil) and (countTimer >= 0) and (countTimer < 0.6) and (seeking == 0) then timer2:stop() getUndoRedo() currentIndex = currentIndex - 1 if (currentIndex < 0) then if (osd_messages == true) then mp.osd_message('No Undo Found') end currentIndex = 0 msg.info('No undo found') else if (seekTable[currentIndex] < 0) then seekTable[currentIndex] = 0 end seeking = 1 mp.commandv('seek', seekTable[currentIndex], 'absolute', 'exact') undoRedo = 1 if (osd_messages == true) then mp.osd_message('Undo') end msg.info('Seeked using undo') end elseif (filePath ~= nil) and (currentIndex > 0) then prepareUndoRedo() currentIndex = currentIndex - 1 if (seekTable[currentIndex] < 0) then seekTable[currentIndex] = 0 end seeking = 1 mp.commandv('seek', seekTable[currentIndex], 'absolute', 'exact') undoRedo = 1 if (osd_messages == true) then mp.osd_message('Undo') end msg.info('Seeked using undo') elseif (filePath ~= nil) and (currentIndex == 0) then if (osd_messages == true) then mp.osd_message('No Undo Found') end msg.info('No undo found') end end local function redo() if (filePath ~= nil) and (currentIndex < seekNumber) then prepareUndoRedo() currentIndex = currentIndex + 1 if (seekTable[currentIndex] < 0) then seekTable[currentIndex] = 0 end seeking = 1 mp.commandv('seek', seekTable[currentIndex], 'absolute', 'exact') undoRedo = 0 if (osd_messages == true) then mp.osd_message('Redo') end msg.info('Seeked using redo') elseif (filePath ~= nil) and (currentIndex == seekNumber) then if (osd_messages == true) then mp.osd_message('No Redo Found') end msg.info('No redo found') end end local function undoLoop() if (filePath ~= nil) and (undoRedo == 0) then undo() elseif (filePath ~= nil) and (undoRedo == 1) then redo() elseif (filePath ~= nil) and (countTimer == -1) then if (osd_messages == true) then mp.osd_message('No Undo Found') end msg.info('No undo found') end end mp.add_key_binding("ctrl+z", "undo", undo) mp.add_key_binding("ctrl+Z", "undoCaps", undo) mp.add_key_binding("ctrl+y", "redo", redo) mp.add_key_binding("ctrl+Y", "redoCaps", redo) mp.add_key_binding("ctrl+alt+z", "undoLoop", undoLoop) mp.add_key_binding("ctrl+alt+Z", "undoLoopCaps", undoLoop)
local M = { } local TK = require("PackageToolkit") local tail = (TK.module.import(..., '_tail')).tail M.append = function(list, ...) local items = { ... } if #items == 0 then return list end if (type(list)) ~= "table" and #items ~= 0 then return items end if (type(list)) == "table" and #items == 0 then return table end if (type(list)) ~= "table" and #items == 0 then return { } end local output do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #list do local x = list[_index_0] _accum_0[_len_0] = x _len_0 = _len_0 + 1 end output = _accum_0 end for _index_0 = 1, #items do local item = items[_index_0] output[#output + 1] = item end return output end return M
--[[ @file options.lua @license The MIT License (MIT) @author Alex <[email protected]> @copyright 2016 Alex --]] --- @module options local options = {} require "alt_getopt" local clfile = _G.arg[0] local long_opts, optarg, optind if clfile == "cli.lua" then long_opts = { help = "h", config = "f", set = "n", } optarg, optind = alt_getopt.get_opts (_G.arg, "hf:lc:m:p:sn:d", long_opts) if optarg.h or not (optarg.l or optarg.c or optarg.s or optarg.n or optarg.d) then print("Welcome to transitd CLI tool.\n\ Program arguments: \ -f, --config <path/to/config> Load configuration file \ -l List available gateways \ -c <ip> Connect to a gateway \ -m <suite> Use a specific suite \ -d Disconnect from the current gateway \ -p <port> Use a specific gateway port \ -n, --set <section.x=value> Set a configuration value \ -s Start a scan for gateways \ ") os.exit() end else long_opts = { help = "h", config = "f", } optarg, optind = alt_getopt.get_opts (_G.arg, "hf:", long_opts) if optarg.h then print("Program arguments: \ -f, --config <path/to/config> Load configuration file \ ") os.exit() end end function options.getArguments() return optarg end return options
-- LOVE 11.0 screenshot implementation -- Part of Live Simulator: 2 -- See copyright notice in main.lua local love = require("love") local Util = require("util") local screenshot = { list = {} } local function screenshotUpdateImpl() end local function cleanListStartFrom(i, len) for j = i, len do screenshot.list[j] = nil end end function screenshot.update() return screenshotUpdateImpl() end if love._version <= "11.0" then function screenshotUpdateImpl() local len = #screenshot.list if len > 0 then local ss = love.graphics.newScreenshot() for i = 1, len do local obj = screenshot.list[i] local tobj = type(obj) if tobj == "string" then local ext = Util.getExtension(obj):lower() ext = #ext > 0 and ext or "png" ss:encode(ext, obj) elseif tobj == "function" then local s, m = pcall(obj, ss) if not(s) then cleanListStartFrom(i, len) error(m) end elseif tobj == "userdata" and tobj.typeOf and tobj:typeOf("Channel") then obj:push(ss) end screenshot.list[i] = nil end end end function love.graphics.captureScreenshot(obj) local tobj = type(obj) if tobj == "string" or tobj == "function" or (tobj == "userdata" and tobj:typeOf("Channel")) then screenshot.list[#screenshot.list + 1] = obj end end end return screenshot
object_tangible_loot_creature_loot_generic_generic_eye = object_tangible_loot_creature_loot_generic_shared_generic_eye:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_generic_generic_eye, "object/tangible/loot/creature/loot/generic/generic_eye.iff")
// Generated by github.com/davyxu/tabtoy // Version: 2.8.10 module table { export var TBall : table.ITBallDefine[] = [ { Id : 1, Atk : 1, Price : 1 }, { Id : 2, Atk : 1, Price : 1 } ] // Id export var TBallById : game.Dictionary<table.ITBallDefine> = {} function readTBallById(){ for(let rec of TBall) { TBallById[rec.Id] = rec; } } readTBallById(); }
require('user/utils') local status_ok, nvim_web_devicons = pcall(require, 'nvim-web-devicons') if not status_ok then print('Could not load nvim-web-devicons') return end nvim_web_devicons.setup({ default = true, })
require "/scripts/vec2.lua" function init() self.controlForce = config.getParameter("controlForce") self.maxSpeed = config.getParameter("maxSpeed") end function update(dt) if self.target and world.entityExists(self.target) then self.targetPosition = world.entityPosition(self.target) else setTarget(nil) end if self.targetPosition then mcontroller.applyParameters({ gravityEnabled = false }) local toTarget = world.distance(self.targetPosition, mcontroller.position()) toTarget = vec2.norm(toTarget) mcontroller.approachVelocity(vec2.mul(toTarget, self.maxSpeed), self.controlForce) end mcontroller.setRotation(math.atan(mcontroller.velocity()[2], mcontroller.velocity()[1])) end function setTarget(targetId) self.target = targetId if self.target then self.targetPosition = world.entityPosition(targetId) else self.targetPosition = nil end end
ITEM.name = "Рем. комплект средне/крупнокалиб. винтовок" ITEM.desc = "Данный комплект содержит масла, растворители, основное оборудования для чистки и специальные инструменты, используемые для обслуживания различных оружейных материалов. \n\nХАРАКТЕРИСТИКИ: \n-технологическое приспособление \n-высокая ценность" ITEM.price = 5683 ITEM.exRender = false ITEM.weight = 2.01 ITEM.model = "models/kek1ch/toolkit_r.mdl" ITEM.width = 2 ITEM.height = 1 ITEM.iconCam = { pos = Vector(151.5, 126.59999847412, 94.267456054688), ang = Angle(25, 220, 2.2929935455322), fov = 6.5 } --[[ITEM.model = "models/kek1ch/toolkit_s.mdl" ITEM.width = 2 ITEM.height = 1 ITEM.iconCam = { pos = Vector(162, 136, 100.69999694824,) ang = Angle(25, 220, 0,) fov = 6, } ]]
server_shop = {} local ss = server_shop ss.modname = core.get_current_modname() ss.modpath = core.get_modpath(ss.modname) function ss.log(lvl, msg) if not msg then msg = lvl lvl = nil end msg = "[" .. ss.modname .. "] " .. msg if not lvl then core.log(msg) else core.log(lvl, msg) end end local scripts = { "settings", "api", "deposit", "formspec", "node", "command", } for _, script in ipairs(scripts) do dofile(ss.modpath .. "/" .. script .. ".lua") end ss.file_load() core.register_on_mods_loaded(ss.prune_shops)
-- https://github.com/kyazdani42/nvim-tree.lua local M = {} function M.get(spec, config, opts) local c = spec.palette -- stylua: ignore return { NvimTreeNormal = { fg = spec.fg1, bg = config.transparent and "NONE" or spec.bg0 }, NvimTreeVertSplit = { link = "VertSplit" }, NvimTreeIndentMarker = { fg = spec.bg4 }, NvimTreeRootFolder = { fg = c.orange.base, style = "bold" }, NvimTreeFolderName = { fg = c.blue.base }, NvimTreeFolderIcon = { fg = c.blue.base }, NvimTreeOpenedFolderName = { fg = c.blue:harsh() }, NvimTreeEmptyFolderName = { fg = spec.syntax.dep }, NvimTreeSymlink = { fg = c.pink:subtle() }, NvimTreeSpecialFile = { fg = c.cyan.base }, NvimTreeImageFile = { fg = c.white:subtle() }, NvimTreeOpenedFile = { fg = c.pink:harsh() }, -- TODO: not working NvimTreeGitDeleted = { fg = spec.git.removed }, NvimTreeGitDirty = { fg = spec.git.changed}, NvimTreeGitMerge = { fg = spec.git.conflict, }, NvimTreeGitNew = { fg = spec.git.add }, NvimTreeGitRenamed = { link = "NvimTreeGitDeleted" }, NvimTreeGitStaged = { link = "NvimTreeGitStaged" }, } end return M
local Roact = require(game.ReplicatedStorage.Roact) local RoactAnimate = require(game.ReplicatedStorage.RoactAnimate) local BouncingButton = Roact.PureComponent:extend("BouncingButton") function BouncingButton:init() self._position = RoactAnimate.Value.new( -- Use the Position property if it's given... self.props.Position -- ...or default to this position. or UDim2.new(0, 0, 0, 0) ) end function BouncingButton:render() return Roact.createElement(RoactAnimate.TextButton, { -- Use a Value to make the property animateable. Position = self._position, -- Everything else can't be animated! BackgroundColor3 = Color3.new(1, 1, 1), Font = Enum.Font.SourceSans, Size = UDim2.new(0, 120, 0, 40), Text = "Bounce!", TextColor3 = Color3.new(0, 0, 0), TextSize = 18, [Roact.Event.MouseButton1Click] = function() RoactAnimate.Sequence({ RoactAnimate(self._position, TweenInfo.new(0.125), self.props.Position - UDim2.new(0, 0, 0, 10)), RoactAnimate(self._position, TweenInfo.new( 0.5, Enum.EasingStyle.Bounce ), self.props.Position) }):Start() end, }) end local testTree = Roact.createElement("ScreenGui", {}, { Roact.createElement(BouncingButton, { Position = UDim2.new(0.5, 0, 0.5, 0), }) }) Roact.mount(testTree, game.Players.LocalPlayer:WaitForChild("PlayerGui"), "Bouncing")
--[[ Jericho's time script -- https://github.com/Jericho1060 Display IRL time in game https://github.com/Jericho1060/DualUniverse/blob/master/TimeScript/IRLHourScript.lua ]]-- summer_time = false --export function getTimeTable(time) local additionnal_hour = 0 if summer_time then additionnal_hour = 1 end local T = math.floor(time) % (3600*24) return {math.floor(T/3600+additionnal_hour)%24, math.floor(T%3600/60), math.floor(T%60)} end function getTimeString(time) local timeTable = getTimeTable(time) return string.format("%02d:%02d:%02d",timeTable[1],timeTable[2],timeTable[3]) end --[[ USAGE Copy the full script in Library > Start local timeTable = getTimeTable(system.getTime()) -- return a table with 3 values : {hour, minutes, seconds} local timeString = getTimeString(system.getTime()) -- return a formated string : "HH:mm:ss" you can add a timer every seconds to display the time ]]--
-- Author: Divran local Obj = EGP:NewObject( "3DTracker" ) Obj.material = nil Obj.w = nil Obj.h = nil Obj.target_x = 0 Obj.target_y = 0 Obj.target_z = 0 Obj.r = nil Obj.g = nil Obj.b = nil Obj.a = nil Obj.parententity = NULL Obj.NeedsConstantUpdate = true Obj.angle = 0 Obj.directionality = 0 function Obj:Draw(egp) local objectPosition if self.parententity and self.parententity:IsValid() then objectPosition = self.parententity:LocalToWorld(Vector(self.target_x,self.target_y,self.target_z)) else objectPosition = Vector(self.target_x,self.target_y,self.target_z) end if egp.gmod_wire_egp_hud then local pos = objectPosition:ToScreen() self.x = pos.x self.y = pos.y return end local eyePosition = EyePos() local direction = objectPosition-eyePosition local ratioX, ratioY if egp.gmod_wire_egp_emitter then ratioX = 4 ratioY = 4 -- localise the positions eyePosition = egp:WorldToLocal(eyePosition) - Vector( -64, 0, 135 ) direction = egp:WorldToLocal(direction + egp:GetPos()) elseif egp.gmod_wire_egp then local monitor = WireGPU_Monitors[ egp:GetModel() ] if not monitor then self.x = math.huge self.y = math.huge return end local Ang = egp:LocalToWorldAngles( monitor.rot ) local Pos = egp:LocalToWorld( monitor.offset ) ratioY = 1 / monitor.RS ratioX = monitor.RatioX * ratioY eyePosition = WorldToLocal(eyePosition, Angle(), Pos, Ang) eyePosition:Rotate(Angle(0,0,90)) eyePosition = eyePosition + Vector(256/ratioX, 0, -256/ratioY) direction = WorldToLocal(direction, Angle(), Vector(), Ang) direction:Rotate(Angle(0,0,90)) end -- plane/ray intersection: --[[ screenPosition = eyePosition+direction*fraction | screenPosition.y = 0 0 = eyePosition.y+direction.y*fraction | - eyePosition.y -eyePosition.y = direction.y*fraction | / direction.y -eyePosition.y / direction.y = fraction | swap sides ]] local fraction = -eyePosition.y / direction.y local screenPosition = eyePosition+direction*fraction if fraction < 0 then -- hide for fraction < 0 self.x = math.huge self.y = math.huge elseif (fraction - 1) * self.directionality < 0 then -- hide for fraction > 1 if directionality < 0 and for fraction < 1 if directionality > 0 self.x = math.huge self.y = math.huge else self.x = screenPosition.x * ratioX self.y = -screenPosition.z * ratioY end -- fraction < 0: object-player-screen: player is between object and screen; object is not seen at all when facing the screen -- fraction 0-1: object-screen-player: screen is between object and player; object is seen behind the screen -- fraction > 1: screen-object-player: object is between screen and player; object is seen in front of the screen end function Obj:Transmit() net.WriteFloat( self.target_x ) net.WriteFloat( self.target_y ) net.WriteFloat( self.target_z ) net.WriteEntity( self.parententity ) net.WriteInt((self.angle%360)*64, 16) net.WriteInt( self.directionality, 2 ) end function Obj:Receive() local tbl = {} tbl.target_x = net.ReadFloat() tbl.target_y = net.ReadFloat() tbl.target_z = net.ReadFloat() local parententity = net.ReadEntity() if parententity and parententity:IsValid() then tbl.parententity = parententity end tbl.angle = net.ReadInt(16)/64 tbl.directionality = net.ReadInt(2) return tbl end function Obj:DataStreamInfo() return { target_x = self.target_x, target_y = self.target_y, target_z = self.target_z, parententity = self.parententity, directionality = self.directionality } end
package.path = package.path .. ";/libs/?.lua" local Pretty = require "cc.pretty" local Utils = {} function Utils.concat(a, b) for i = 1, #b do a[#a + 1] = b[i] end return a end -- https://stackoverflow.com/a/26367080/1611592 function Utils.copy(obj, seen) if type(obj) ~= "table" then return obj end if seen and seen[obj] then return seen[obj] end local s = seen or {} local res = setmetatable({}, getmetatable(obj)) s[obj] = res for k, v in pairs(obj) do res[Utils.copy(k, s)] = Utils.copy(v, s) end return res end function Utils.isEmpty(t) for _, _ in pairs(t) do return false end return true end function Utils.prettyPrint(value) Pretty.print(Pretty.pretty(value)) end function Utils.count(table) local size = 0 for _ in pairs(table) do size = size + 1 end return size end function Utils.waitForUserToHitEnter() while true do local _, key = os.pullEvent("key") if (key == keys.enter) then break end end end function Utils.writeAutorunFile(args) local file = fs.open("startup/" .. args[1] .. ".autorun.lua", "w") file.write("shell.run(\"" .. table.concat(args, " ") .. "\")") file.close() end function Utils.noop() -- intentionally do nothing end function Utils.timestamp() return os.time() * 60 * 60 / 100 end return Utils
local hello = yeah.hello local hello, world do local _table_0 = table["cool"] hello = _table_0.hello world = _table_0.world end local a, b, c = items.a, moon.bind(items.b, items), items.c local master, ghost do local _table_0 = find("mytable") master = _table_0.master ghost = moon.bind(_table_0.ghost, _table_0) end local yumm a, yumm = 3434, "hello" local _table_0 = 232 local something do local _table_1 = a(table) something = _table_1.something end if indent then local okay, well do local _table_1 = tables[100] okay = _table_1.okay well = moon.bind(_table_1.well, _table_1) end end
return { type = "TEX"; file = "default_specular.jpg"; }
--[[ module oo (object orientation) --]] local util = require 'util' local M = { } local function construct(cls, ...) local self = { } setmetatable(self, cls) return self, util.callopt(self.__init, self, ...) end local id = debug.id or util.rawtostring function M.objectToString(obj) local name = getmetatable(obj).clsName if not name then return "Object: " .. id(obj) end return name .. ": " .. id(obj) end function M.classToString(cls) return "class: " .. cls.clsName or id(cls) end -- class([name, [env]], [super]) -- class([super]) function M.class(name, env, super) if name and not super and type(name) ~= 'string' then super, name = name, nil end local cls = {super = super, clsName = name, __tostring = M.objectToString} cls.__index = cls setmetatable(cls, { __index = super, __call = construct, __tostring = M.classToString }) if name and env then env[name] = cls end return cls end function M.isInstance(obj, cls, orDerived) local mt = getmetatable(cls) if not mt then return false end if mt == cls or mt.clsName == cls then return true end return orDerived and M.isInstance(obj, cls.super) end M.lclass = M.class -- alias for consistence with pseudo keyword M.mustOverride = util.failMsg "must override this method" -- cppclass(name, [env], super) function M.cppclass(name, env, super) if type(env) == 'userdata' then super, env = env, _ENV elseif not env then env = _ENV end assert( type(super) == 'userdata', "Only use cppclass for deriving from C++ classes! Use lclass instead.") assert(env[name] == nil, "oo.cppclass: name conflict") local oldval = _G[name] class(name)(super) -- create the actual class local classobj = _G[name] if env ~= _G then env[name], _G[name] = classobj, oldval end function classobj:__init() super.__init(self) end return classobj end if not OO_NO_KEYWORDS then (require 'tabutil').copyEntry(_G, 'lclass', M) end return M
return { Name = "", Description = "", SubDescription = "", Image = "rbxassetid://1297757230", SellPrice = 10, Rarity = 0, Color = Color3.fromRGB(118, 118, 118), Attributes = {} }
include "fw_init_sh.lua"
if not morescience.tech then morescience.tech = {} end --[[ Code edit and replacements with usage of functions below to fix issues with previous version's "explicit effect-declaration" overriding other mod code and breaking compatability with any other mods that attempt to utilize technologies in vanilla to unlock recipes that this mod also attempts to utilize. step one in conflict resolution: remove all explicit-effect-declaration that overriding other mod's effects that may be added without requiring numerous updates. we will, instead, add recipe unlocks for each of our science packs into data-final-updates.lua morescience.tech.add_recipe_unlock(technology, recipe) morescience.tech.add_science_pack_range(techList, first, last, amount) table.insert(data.raw.technology[technology].unit.ingredients,{pack, amount} impact: compressed 7000 lines of code into 200, and fixed issues where other mods prevented science packs from having a recipe unlock or the reverse happening, where this mod was preventing other recipe-unlocks other mods try to add to vanilla technology. --]] if not settings.startup["moresciencepack-GameProgressionFix"].value == true then --morescience.tech.add_science_pack_range(techList, first, last, amount) --morescience.tech.add_science_pack_range(techList, 1, last, 1) --EARLY PACKS morescience.tech.add_science_pack_range({"logistics", "optics", "stone-walls"}, 1, 1, 1) morescience.tech.add_science_pack_range({"turrets"}, 1, 2, 1) morescience.tech.add_science_pack_range({"automation","electronics","military","military-2"}, 1, 3, 1) morescience.tech.add_science_pack_range({"steel-processing", "automation-2"}, 1, 4, 1) morescience.tech.add_science_pack_range({"circuit-network", "heavy-armor", "research-speed-1", "electric-energy-distribution-1", "advanced-material-processing", "toolbelt", "landfill", "shotgun-shell-damage-1", "shotgun-shell-speed-1", "gun-turret-damage-1", "bullet-damage-1", "bullet-speed-1", "fluid-handling", "oil-processing"}, 1, 5, 1) morescience.tech.add_science_pack_range({"gates", "concrete", "engine", "shotgun-shell-damage-2", "shotgun-shell-speed-2", "gun-turret-damage-2", "bullet-damage-2", "bullet-speed-2"}, 1, 7, 1) morescience.tech.add_science_pack_range({"flammables", "railway", "automated-rail-transportation", "rail-signals", "automobilism", "solar-energy", "laser", "logistics-2", "research-speed-2", "electric-energy-accumulators", "electric-engine", "battery", "shotgun-shell-speed-3", "bullet-speed-3", "sulfur-processing", "plastics", "modules"}, 1, 8, 1) if not mods["omnimatter_science"] then morescience.tech.add_science_pack_range({"logistics-2"}, 9, 10, 1) --omniscience fix involving omnipack being added to vanilla techs and it requiring items from Logistics 2. So long as it is not enabled, MSP 9 and 10 can be added (as originally done) end morescience.tech.add_science_pack_range({"stack-inserter", "inserter-capacity-bonus-1", "inserter-capacity-bonus-2", "advanced-electronics", "fluid-wagon", "modular-armor", "flying", "robotics", "construction-robotics", "shotgun-shell-damage-3", "night-vision-equipment", "battery-equipment", "solar-panel-equipment", "cliff-explosives", "advanced-oil-processing", "electric-energy-distribution-2"}, 1, 10, 1) --Handle specificially for the case of anytime either bob's modules or custom modules is enabled if not mods["bobmodules"] and not mods["CustomModules"] then morescience.tech.add_science_pack_range({"speed-module", "productivity-module", "effectivity-module"}, 1, 10, 1) morescience.tech.add_science_pack_range({"speed-module-2", "productivity-module-2", "effectivity-module-2","speed-module-3", "productivity-module-3", "effectivity-module-3"}, 1, 12, 1) morescience.tech.add_science_pack_range({"speed-module-2", "productivity-module-2", "effectivity-module-2","speed-module-3", "productivity-module-3", "effectivity-module-3"}, 17, 17, 1) morescience.tech.add_science_pack_range({"speed-module-3", "productivity-module-3", "effectivity-module-3"}, 18, 27, 1) end --ADD pack 11 --table.insert(data.raw.technology["cliff-explosives"].unit.ingredients,{refPacks[tostring(11)], 1}) --add pack 11 to cliff explosives. morescience.tech.add_science_pack_range({"cliff-explosives", "electric-energy-distribution-2"}, 11, 11, 1) --MAIN PACKS 1-12 morescience.tech.add_science_pack_range({"flamethrower", "logistic-robotics", "character-logistic-slots-1", "character-logistic-slots-2", "character-logistic-trash-slots-1", "inserter-capacity-bonus-3", "advanced-electronics-2", "braking-force-1", "power-armor", "research-speed-3", "advanced-material-processing-2", "worker-robots-speed-1", "worker-robots-storage-1", "character-logistic-slots-3", "character-logistic-trash-slots-2", "battery-mk2-equipment", "exoskeleton-equipment", "personal-roboport-equipment", "automation-3", "braking-force-2", "research-speed-4", "worker-robots-speed-2", "auto-character-logistic-trash-slots", "inserter-capacity-bonus-4", "logistics-3", "research-speed-5", "effect-transmission", "worker-robots-speed-3", "worker-robots-storage-2", "character-logistic-slots-4", "coal-liquefaction", "inserter-capacity-bonus-5", "inserter-capacity-bonus-6", "inserter-capacity-bonus-7", "braking-force-3", "braking-force-4", "braking-force-5", "braking-force-6", "braking-force-7","research-speed-6", "logistic-system", "fusion-reactor-equipment", "worker-robots-speed-4", "worker-robots-speed-5", "worker-robots-storage-3", "character-logistic-slots-5", "character-logistic-slots-6", "personal-roboport-equipment-2", "worker-robots-speed-6"}, 1, 12, 1) --MAIN PACKS 1-13 morescience.tech.add_science_pack_range({"grenade-damage-1", "grenade-damage-2", "explosives", "land-mine", "rocketry", "laser-turrets", "shotgun-shell-damage-4", "shotgun-shell-speed-4", "gun-turret-damage-3", "gun-turret-damage-4", "flamethrower-damage-1", "energy-shield-equipment", "bullet-damage-3", "bullet-damage-4", "bullet-speed-4", "combat-robotics", "military-3", "grenade-damage-3", "tanks", "laser-turret-damage-1", "laser-turret-speed-1", "flamethrower-damage-2", "combat-robot-damage-1", "rocket-damage-1", "rocket-speed-1"}, 1, 13, 1) --ADD packs 15-16 morescience.tech.add_science_pack_range({"military-3", "grenade-damage-3", "tanks", "laser-turret-damage-1", "laser-turret-speed-1", "flamethrower-damage-2", "combat-robot-damage-1", "rocket-damage-1", "rocket-speed-1"}, 15, 16, 1) --MAIN PACKS 1-16 morescience.tech.add_science_pack_range({"laser-turret-damage-2", "laser-turret-speed-2", "combat-robot-damage-2", "rocket-damage-2", "rocket-speed-2"}, 1, 16, 1) --ADD pack 17 morescience.tech.add_science_pack_range({"inserter-capacity-bonus-3", "advanced-electronics-2", "braking-force-1", "power-armor", "research-speed-3", "advanced-material-processing-2", "worker-robots-speed-1", "worker-robots-storage-1", "character-logistic-slots-3", "character-logistic-trash-slots-2", "battery-mk2-equipment", "exoskeleton-equipment", "personal-roboport-equipment", "advanced-oil-processing"}, 17, 17, 1) --ADD pack 17-19 morescience.tech.add_science_pack_range({"automation-3", "braking-force-2", "research-speed-4", "worker-robots-speed-2", "auto-character-logistic-trash-slots"}, 17, 19, 1) --MAIN PACKS 1-19 morescience.tech.add_science_pack_range({"grenade-damage-4", "explosive-rocketry", "shotgun-shell-damage-5", "shotgun-shell-speed-5", "laser-turret-damage-3", "laser-turret-speed-3", "gun-turret-damage-5", "flamethrower-damage-3", "energy-shield-mk2-equipment", "personal-laser-defense-equipment", "discharge-defense-equipment", "bullet-damage-5", "bullet-speed-5", "combat-robotics-2", "combat-robot-damage-3", "rocket-damage-3", "rocket-speed-3", "cannon-shell-damage-1", "cannon-shell-speed-1"}, 1, 19, 1) --ADD pack 17-21 morescience.tech.add_science_pack_range({"inserter-capacity-bonus-4", "logistics-3", "research-speed-5", "effect-transmission", "worker-robots-speed-3", "worker-robots-storage-2", "character-logistic-slots-4", "coal-liquefaction", "inserter-capacity-bonus-5", "inserter-capacity-bonus-6", "inserter-capacity-bonus-7", "braking-force-3", "braking-force-4", "braking-force-5", "braking-force-6", "braking-force-7", "research-speed-6", "logistic-system", "fusion-reactor-equipment"}, 17, 21, 1) --MAIN PACKS 1-21 morescience.tech.add_science_pack_range({"military-4", "grenade-damage-5", "grenade-damage-6", "shotgun-shell-damage-6", "shotgun-shell-speed-6", "laser-turret-damage-4", "laser-turret-damage-5", "laser-turret-damage-6", "laser-turret-damage-7", "laser-turret-speed-4", "laser-turret-speed-5", "laser-turret-speed-6", "laser-turret-speed-7", "gun-turret-damage-6", "flamethrower-damage-4", "flamethrower-damage-5", "flamethrower-damage-6", "bullet-damage-6", "bullet-speed-6", "combat-robot-damage-4", "combat-robot-damage-5", "rocket-damage-4", "rocket-damage-5", "rocket-damage-6", "rocket-speed-4", "rocket-speed-5", "rocket-speed-6", "rocket-speed-7", "cannon-shell-damage-2", "cannon-shell-damage-3", "cannon-shell-damage-4", "cannon-shell-speed-2", "cannon-shell-speed-3", "cannon-shell-speed-4", "cannon-shell-speed-5"}, 1, 21, 1) --ADD pack 22-23 morescience.tech.add_science_pack_range({"inserter-capacity-bonus-5", "inserter-capacity-bonus-6", "inserter-capacity-bonus-7", "braking-force-3", "braking-force-4", "braking-force-5", "braking-force-6", "braking-force-7", "research-speed-6", "logistic-system", "fusion-reactor-equipment"}, 22, 23, 1) --ADD pack 17-27 morescience.tech.add_science_pack_range({"worker-robots-speed-4", "worker-robots-speed-5", "worker-robots-storage-3", "character-logistic-slots-5", "character-logistic-slots-6", "personal-roboport-equipment-2", "worker-robots-speed-6"}, 17, 27, 1) --MAIN PACKS 1-27 morescience.tech.add_science_pack_range({"atomic-bomb", "cannon-shell-damage-5", "uranium-ammo", "power-armor-2", "combat-robotics-3", "grenade-damage-7", "shotgun-shell-damage-7", "laser-turret-damage-8", "gun-turret-damage-7", "flamethrower-damage-7", "bullet-damage-7", "combat-robot-damage-6", "rocket-damage-7", "cannon-shell-damage-6", "artillery-shell-range-1", "artillery-shell-speed-1"}, 1, 27, 1) --ROCKET SILO: 1-29 morescience.tech.add_science_pack_range({"rocket-silo"}, 1, 29, 1) --ADD pack 28-29 morescience.tech.add_science_pack_range({"uranium-ammo", "power-armor-2", "combat-robotics-3", "worker-robots-speed-6", "grenade-damage-7", "shotgun-shell-damage-7", "laser-turret-damage-8", "gun-turret-damage-7", "flamethrower-damage-7", "bullet-damage-7", "combat-robot-damage-6", "rocket-damage-7", "cannon-shell-damage-6", "artillery-shell-range-1", "artillery-shell-speed-1"}, 28, 29, 1) --ADD pack 30 to infinite techs morescience.tech.add_science_pack_range({"worker-robots-speed-6", "grenade-damage-7", "shotgun-shell-damage-7", "laser-turret-damage-8", "gun-turret-damage-7", "flamethrower-damage-7", "bullet-damage-7", "combat-robot-damage-6", "rocket-damage-7", "cannon-shell-damage-6", "artillery-shell-range-1", "artillery-shell-speed-1"}, 30, 30, 1) end
local physics_demo = class() --for the demo state ui physics_demo.name = "physics and platforming" physics_demo.description = ([[ an example physics system and a player avatar (wasd or arrows to move) ]]):dedent() --setup function physics_demo:new(parent) self.k = ferris.kernel() :add_system("bg_tiles", require("src.systems.tile_system"){ map = assets.map.physics, layer = "bg", image = assets.image.tiles, tilesize = vec2(8, 8), }) :add_system("behaviour", ferris.systems.behaviour_system()) :add_system("sprite", ferris.systems.sprite_system()) :add_system("animation", ferris.systems.animation_system()) :add_system("tiles", require("src.systems.tile_system"){ map = assets.map.physics, layer = "fg", image = assets.image.tiles, tilesize = vec2(8, 8), }) :add_system("physics", require("src.systems.physics_system")()) local collisions = require("src.load_objects")(assets.map.physics, "collision") for _, v in ipairs(collisions) do self.k.systems.physics:add_level_geo(v.a, v.b) end local water = require("src.load_objects")(assets.map.physics, "water") for _, v in ipairs(water) do self.k.systems.physics:add_zone(v.pos, v.halfsize, "water") end local objects = require("src.load_objects")(assets.map.physics, "objects") local function fetch_object(name) return functional.find_match(objects, function(v) return v.name == name end) end --create player require("src.demos.physics.player")(self.k.systems, { pos = fetch_object("player").pos, }) --create dispenser require("src.demos.physics.dispenser")(self.k.systems, { spawn = fetch_object("dispenser"), path = fetch_object("dispenser path"), }) end function physics_demo:update(dt) self.k:update(dt) end function physics_demo:draw() self.k:draw() end return physics_demo
simulation = { mesh = { index_extents = {21}, domain_bounds = {1} }, shapes = { { type = "yz_rect", psi = 0.001, normal = 1, boundary_condition = "dirichlet" }, { type = "yz_rect", psi = 0.9, normal = -1, boundary_condition = "floating" } }, scheme = { order = 1, type = "E2-poly", floating_alpha = {13 / 100, 7 / 50, 3 / 20, 4 / 25, 17 / 100, 9 / 50}, dirichlet_alpha = {3 / 25, 13 / 100, 7 / 50} }, system = { type = "eigenvalues" } }
--[[ ================================================================================ ProjectNukeCoreServiceHandler Provides internal service handling to allow the initalization and assignment of services ================================================================================ Author: stuntguy3000 --]] -- http://www.computercraft.info/forums2/index.php?/topic/29696-apifunction-failing/ local ServiceBasePath = "/ProjectNuke/Services/" local Services = { ["EmergencyService"] = "ProjectNukeEmergencyService.lua", } function DownloadServices() fs.delete("/ProjectNuke/Services/") -- Download and load services for serviceName,fileName in pairs(Services) do print("Downloading "..serviceName.."("..fileName..")") fullURL = "https://raw.githubusercontent.com/stuntguy3000/ProjectNuke/master/v2.0/Services/"..fileName fullPath = ServiceBasePath..fileName shell.run("wget "..fullURL.." "..fullPath) end end function LoadServices() for serviceName,fileName in pairs(Services) do fullPath = ServiceBasePath..fileName os.loadAPI(fullPath) end end function RunServices() ProjectNukeEmergencyService.Run() end
local Root = script.Parent.Parent local RequestType = require(Root.Enums.RequestType) return function(state) return state.promptRequest.requestType ~= RequestType.None end
function redraw_lines() local visible = #global.player_rendering > 0 for k,v in pairs(global.drivers) do if v.render then rendering.set_players(v.render, global.player_rendering) rendering.set_visible(v.render, visible) else log("Mass driver id# "..k.." doesn't have a valid line rendering") end end end function draw_line(turret, position) -- position.x,position.y = position.x - 0.5, position.y - 0.5 local tid = turret.unit_number local color = is_in_range(turret,position) and const.green or const.red if global.drivers[tid].render then rendering.set_color(global.drivers[tid].render, color) rendering.set_to(global.drivers[tid].render, position) else global.drivers[tid].render = rendering.draw_line{color=color,width="2",from=turret,to=position,surface=turret.surface,forces={turret.force}} end redraw_lines() end function render_gps(event) if game.get_player(event.player_index).cursor_stack and game.get_player(event.player_index).cursor_stack.valid_for_read and game.get_player(event.player_index).cursor_stack.name == "mass-driver-gps" then global.player_rendering[event.player_index] = event.player_index redraw_lines() else if global.player_rendering[event.player_index] then global.player_rendering[event.player_index] = nil redraw_lines() end end end -- displays a floating-text error message above a turret function show_error (turretID, message) rendering.set_text(global.drivers[turretID].alert, {"mass-driver-error." .. message}) rendering.set_visible(global.drivers[turretID].alert, true) --[[ if not global.drivers[turret.unit_number].last_alert or game.tick > global.drivers[turret.unit_number].last_alert + 60 then turret.surface.create_entity{name="stationary-flying-text", position={turret.position.x-.5,turret.position.y-1},force=turret.force,text=message} global.drivers[turret.unit_number].last_alert = game.tick end ]] end
--[[---------------------------------------------------------------------------- Application Name: ControlFlowEvents Summary: Introduction of how to notify and react on events from within a ControlFlow Description: This sample shows how to notify an event to which a ControlFlow block is registered to. Another event is notified from ControlFlow which a function in this script is registered to. 1. Script notifying event -> Controlflow reacts 2. Delay of 2000 ms within Controlflow 3. ControlFlow notifying event -> Script reacts How to run: This sample can be run on any device or on the emulator. After startup the delayed event triggers a function from the script which prints to the console. ------------------------------------------------------------------------------]] --Start of Global Scope--------------------------------------------------------- -- Serving an event which is used to trigger the ControlFlow. Must be served to the Engine CROWN. -- Engine events are always global, no serve in App properties necessary Script.serveEvent('Engine.OnMyEventIn', 'OnMyEventIn') --End of Global Scope----------------------------------------------------------- --Start of Function and Event Scope--------------------------------------------- local function main() -- Notify the event to trigger the ControlFlow directly after startup Script.notifyEvent('OnMyEventIn') end --The following registration is part of the global scope which runs once after startup --Registration of the 'main' function to the 'Engine.OnStarted' event Script.register('Engine.OnStarted', main) -- Function is registered to the event which is raised from the flow local function callFromFlow() print('ControlFlow says hello') end -- Registration to the 'Engine.OnMyEventOut' as specified in the ControlFlow Script.register('Engine.OnMyEventOut', callFromFlow) --End of Function and Event Scope-----------------------------------------------
--- Turbo.lua TCP Server module -- A simple non-blocking extensible TCP Server based on the IOStream class. -- Includes SSL support. Used as base for the Turbo HTTP Server. -- -- Copyright 2011, 2012, 2013 John Abrahamsen -- -- 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 "turbo.log" local util = require "turbo.util" local iostream = require "turbo.iostream" local platform = require "turbo.platform" local ioloop = require "turbo.ioloop" local socket = require "turbo.socket_ffi" local sockutil = require "turbo.sockutil" local crypto = require "turbo.crypto" local platform = require "turbo.platform" local ffi = require "ffi" local bit = jit and require "bit" or require "bit32" require "turbo.cdef" require "turbo.3rdparty.middleclass" local C = ffi.C local tcpserver = {} -- tcpserver namespace --- A non-blocking TCP server class. -- Users which want to create a TCP server should inherit from this class and -- implement the TCPServer:handle_stream() method. -- SSL is supported by providing the ssl_options table on class initialization. tcpserver.TCPServer = class('TCPServer') --- Create a new TCPServer class instance. -- @param io_loop (IOLoop instance) -- @param ssl_options (Table) Optional SSL parameters. -- @param max_buffer_size (Number) The maximum buffer size of the server. If -- the limit is hit, the connection is closed. -- @note If the SSL certificates can not be loaded, a error is raised. function tcpserver.TCPServer:initialize(io_loop, ssl_options, max_buffer_size) self.io_loop = io_loop self.ssl_options = ssl_options self.max_buffer_size = max_buffer_size self._sockets = {} self._pending_sockets = {} self._started = false -- Validate SSL options if set. if self.ssl_options and platform.__LINUX__ then if not type(ssl_options.cert_file) == "string" then error("ssl_options argument is set, but cert_file argument is \ missing or not a string.") end if not type(ssl_options.key_file) == "string" then error("ssl_options argument is set, but key_file arguments is \ missing or not a string.") end -- So the only check that is done is that the cert and key file are -- readable. However the validity of the keys are not checked until -- we create the SSL context. if not util.file_exists(ssl_options.cert_file) then error(string.format("SSL cert_file, %s, does not exist.", ssl_options.cert_file)) end if not util.file_exists(ssl_options.key_file) then error(string.format("SSL key_file, %s, does not exist.", ssl_options.key_file)) end -- The ssl_create_context function will raise error and exit by its -- own, so there is no need to catch errors. local rc, ctx_or_err = crypto.ssl_create_server_context( self.ssl_options.cert_file, self.ssl_options.key_file) if rc ~= 0 then error(string.format("Could not create SSL context. %s", ctx_or_err)) end self._ssl_ctx = ctx_or_err self.ssl_options._ssl_ctx = self._ssl_ctx end end --- Implement this method to handle new connections. -- @param stream (IOStream instance) Stream for the newly connected client. -- @param address (String) IP address of newly connected client. function tcpserver.TCPServer:handle_stream(stream, address) error('handle_stream method not implemented in this object') end --- Start listening on port and address. -- When using this method, as oposed to TCPServer:bind you should not call -- TCPServer:start. You can call this method multiple times with different -- parameters to bind multiple sockets to the same TCPServer. -- @param port (Number) The port number to bind to. -- @param address (Number) The address to bind to in unsigned integer hostlong -- format. If not address is given, INADDR_ANY will be used, binding to all -- addresses. -- @param backlog (Number) Maximum backlogged client connects to allow. If not -- defined then 128 is used as default. -- @param family (Number) Optional socket family. Defined in Socket module. If -- not defined AF_INET is used as default. function tcpserver.TCPServer:listen(port, address, backlog, family) assert(port, [[Please specify port for listen() method]]) local sock = sockutil.bind_sockets(port, address, backlog, family) self:add_sockets({sock}) end --- Add multiple sockets in a table that should be bound on calling start. -- @param sockets (Table) 1 or more socket fd's. -- @note Use the sockutil.bind_sockets function to create sockets easily and -- add them to the sockets table. function tcpserver.TCPServer:add_sockets(sockets) if not self.io_loop then self.io_loop = ioloop.instance() end for _, sock in ipairs(sockets) do self._sockets[#self._sockets + 1] = sock sockutil.add_accept_handler(sock, self._handle_connection, self.io_loop, self) end end --- Add a single socket that should be bound on calling start. -- @param socket (Number) Socket fd. -- @note Use the sockutil.bind_sockets to create sockets easily and add them to -- the sockets table. function tcpserver.TCPServer:add_socket(socket) self:add_sockets({socket}) end --- Bind this server to port and address. -- @note No sockets are bound until TCPServer:start is called. -- @param port (Number) The port number to bind to. -- @param address (Number) The address to bind to in unsigned integer hostlong -- format. If not address is given, INADDR_ANY will be used, binding to all -- addresses. -- @param backlog (Number) Maximum backlogged client connects to allow. If not -- defined then 128 is used as default. -- @param family (Number) Optional socket family. Defined in Socket module. If -- not defined AF_INET is used as default. function tcpserver.TCPServer:bind(port, address, backlog, family) local sockets = sockutil.bind_sockets(port, address, backlog, family) if self._started then self:add_sockets(sockets) else self._pending_sockets[#self._pending_sockets + 1] = sockets end end --- Start the TCPServer. function tcpserver.TCPServer:start(procs) assert((not self._started), "Already started TCPServer.") self._started = true if procs and procs > 1 and platform.__LINUX__ then for _ = 1, procs - 1 do local pid = ffi.C.fork() if pid ~= 0 then log.devel(string.format( "[tcpserver.lua] Created extra worker process: %d", tonumber(pid))) break end end end local sockets = self._pending_sockets self._pending_sockets = {} self:add_sockets(sockets) end --- Stop the TCPServer. function tcpserver.TCPServer:stop() for _, fd in ipairs(self._sockets) do self.io_loop:remove_handler(fd) self:_close(fd) end self._sockets = {} end if platform.__LINUX__ and not _G.__TURBO_USE_LUASOCKET__ then function tcpserver.TCPServer:_close(fd) assert(C.close(fd) == 0, "Failed to close socket.") end else function tcpserver.TCPServer:_close(fd) assert(fd:close()) end end --- Internal function for wrapping new raw sockets in a IOStream class instance. -- @param connection (Number) Client socket fd. -- @param address (String) IP address of newly connected client. function tcpserver.TCPServer:_handle_connection(connection, address) if self.ssl_options ~= nil and platform.__LINUX__ then local stream = iostream.SSLIOStream( connection, self.ssl_options, self.io_loop, self.max_buffer_size) self:handle_stream(stream, address) else local stream = iostream.IOStream( connection, self.io_loop, self.max_buffer_size) self:handle_stream(stream, address) end end return tcpserver