content
stringlengths
5
1.05M
data.raw["train-stop"]["train-stop"].fast_replaceable_group = "train-stop"
DefineClass.TrainingBuilding = { __parents = {"ShiftsBuilding", "Holder", "DomeOutskirtBld"}, properties = { {template = true, id = "max_visitors", name = T(823, "Max visitors per shift"), default = 5, category = "TrainingBuilding", editor = "number", min = 1, modifiable = true}, {template = true, id = "usable_by_children",name = T(735, "Usable by children"), default = false, category = "TrainingBuilding", editor = "bool"}, {template = true, id = "children_only", name = T(736, "Children Only"), default = false, category = "TrainingBuilding", editor = "bool"}, {template = true, id = "gain_point", name = T(824, "Min points per Sol"), default = 20, category = "TrainingBuilding", editor = "number"}, {template = true, id = "evaluation_points",name = T(825, "Points to evaluate"), default = -1, category = "TrainingBuilding", editor = "number", modifiable = true}, }, visitors = false, -- visitors arrays in shifts closed_visitor_slots = false,-- per shift current_accident_chance = false, -- declarations only to use the same logic as workplace (Set/UpdateWorkplace) overtime = false, specialist = "none", force_lock_workplace = true,-- does not change workplace/ training center on its own, change it on certаin event training_type = "graduation", life_time_trained = false, dome_label = "TrainingBuilding", } function TrainingBuilding:Init() self.visitors = {} for i = 1, self.max_shifts do self.visitors[i] = {} end self.closed_visitor_slots = {} self.current_accident_chance = 0 self.life_time_trained = 0 self.city:AddToLabel("TrainingBuilding", self) end function TrainingBuilding:GameInit() self:CheckForVisitors() end function TrainingBuilding:Done() self.city:RemoveFromLabel("TrainingBuilding", self) self:KickAllVisitors() end function TrainingBuilding:GetUnitsInShifts() return self.visitors or empty_table end function TrainingBuilding:OnDestroyed() self:KickAllVisitors() RebuildInfopanel() end function TrainingBuilding:SetDome(dome) if self.parent_dome then self.parent_dome:RemoveFromLabel("TrainingBuilding") end ShiftsBuilding.SetDome(self, dome) if self.parent_dome then self.parent_dome:AddToLabel("TrainingBuilding", self) end end function TrainingBuilding:AddWorker(unit, shift) self.visitors[shift] = self.visitors[shift] or {} table.insert(self.visitors[shift],unit) if shift == CurrentWorkshift then self:UpdateOccupation(#self.visitors[shift], self.max_visitors) end self:UpdateConsumption() end function TrainingBuilding:RemoveWorker(unit) for i=1,#self.visitors do table.remove_entry(self.visitors[i], unit) end self:StopWorkCycle(unit) self:UpdateConsumption() self:UpdateOccupation(#self.visitors[CurrentWorkshift], self.max_visitors) if unit:IsInWorkCommand() then unit:InterruptCommand() end end function TrainingBuilding:OnSetUIWorking(work) Building.OnSetUIWorking(self, work) --might wna call super if not work then self:KickAllVisitors() self:InterruptUnitsInHolder() else self:CheckForVisitors() end end function TrainingBuilding:OnModifiableValueChanged(prop, old_value, new_valaue) if prop == "max_visitors" then if self.closed_visitor_slots then for i=1, self.max_shifts do if self.closed_visitor_slots[i]==old_value then self:CloseShift(i) end end end self:CheckForVisitors() RebuildInfopanel(self) end end function TrainingBuilding:IsSuitable(colonist) return colonist:CanTrain() and self:CanTrain(colonist) and self:CanWorkTrainHereDomeCheck(colonist) end function TrainingBuilding:ColonistCanInteract(col) if not self:CanTrain(col) then return false, T(8739, "<red>Cannot be trained here</red>") end if col.workplace == self then return false, T(8740, "Currently training here") end if not col:CanReachBuilding(self) then return false, T(4308, "<red>Out of reach</red>") end if not self:HasOpenTrainSlots() then return false, T(4312, "<red>Current work shift is closed</red>") end return true, T{8741, "<UnitMoveControl('ButtonA', interaction_mode)>: Set Training", self} end function TrainingBuilding:ColonistInteract(col) if col.workplace == self then return end if not self.parent_dome then return end local current_shift = CurrentWorkshift --should be the shift @ click moment for i = 1, 3 do if self:HasFreeTrainSlots(current_shift) then break end current_shift = current_shift + 1 current_shift = current_shift > 3 and current_shift % 3 or current_shift end col.user_forced_workplace = {self, current_shift, GameTime()} if self.parent_dome == col.dome then col:UpdateWorkplace() else col:SetForcedDome(self.parent_dome) end return true end function TrainingBuilding:GetWorstVisitor(unit, shift) local shift_found local worst = unit local training_type = self.training_type local check_forced = true for k = 1,2 do for s = shift or 1, shift or #self.visitors do for _, visitor in ipairs(self.visitors[s]) do local found = true if check_forced and visitor:CheckForcedWorkplace() == self then found = false elseif worst then local worker_training = (visitor.training_points or empty_table)[training_type] or 0 local worst_training = (worst.training_points or empty_table)[training_type] or 0 if worker_training < worst_training then found = true end end if found then worst = visitor shift_found = s end end end if shift_found then return worst, shift_found end check_forced = false end return nil, shift end function TrainingBuilding:CheckServicedDome() return self.parent_dome end function TrainingBuilding:FindFreeSlotForced(shift) for i = 1, 3 do if self:HasFreeTrainSlots(shift) then return shift end shift = shift + 1 shift = shift > 3 and shift % 3 or shift end local to_kick to_kick, shift = self:GetWorstVisitor(nil, shift) if to_kick then to_kick.user_forced_workplace = nil return shift, to_kick end return shift end function TrainingBuilding:CloseShift(shift) ShiftsBuilding.CloseShift(self, shift) self.closed_visitor_slots[shift] = self.max_visitors local visitors = self.visitors[shift] or empty_table for i=#visitors,1, -1 do local worker = visitors[i] worker:SetWorkplace(false) worker:UpdateWorkplace() end assert(#visitors == 0) end function TrainingBuilding:OpenShift(shift) ShiftsBuilding.OpenShift(self, shift) self.closed_visitor_slots[shift] = 0 self:CheckForVisitors() end function TrainingBuilding:ClosePositions(shift, idx) self.closed_visitor_slots[shift] = Clamp(self.max_visitors - idx + 1, 0,self.max_visitors - self:GetVisitorsCount(shift)) end function TrainingBuilding:OpenPositions(shift, idx) self.closed_visitor_slots[shift] = Clamp(self.max_visitors - idx, 0, self.max_visitors - self:GetVisitorsCount(shift)) end function TrainingBuilding:GetVisitorsCount(shift) return self.visitors and #self.visitors[shift] or 0 end function TrainingBuilding:FireWorker(worker, shift, idx) worker:GetFired() RebuildInfopanel(self) end function TrainingBuilding:CheckForVisitors() end function TrainingBuilding:KickAllVisitors() for i = 1, #self.visitors do local shift = self.visitors[i] or empty_table for j = #shift,1,-1 do local worker = shift[j] if not worker:IsDying() then worker:SetWorkplace(false) worker:UpdateWorkplace() end end end end function TrainingBuilding:GetFreeTrainSlots(shift) shift = shift or self.active_shift or 0 local max = self.max_visitors local occupied = self.visitors or empty_table local closed = self.closed_visitor_slots or empty_table local sum = 0 local from, to = shift > 0 and shift or 1, shift > 0 and shift or self.max_shifts for i = from, to do sum = sum + Max(0, max - #occupied[i] - (closed[i] or 0)) end return sum end function TrainingBuilding:HasFreeTrainSlots(shift) shift = shift or self.active_shift or 0 local max = self.max_visitors local occupied = self.visitors or empty_table local closed = self.closed_visitor_slots or empty_table local from, to = shift > 0 and shift or 1, shift > 0 and shift or self.max_shifts for i = from, to do if max - #occupied[i] - (closed[i] or 0) > 0 then return true end end end function TrainingBuilding:HasOpenTrainSlots(shift) shift = shift or self.active_shift or 0 local max = self.max_visitors local closed = self.closed_visitor_slots or empty_table local from, to = shift > 0 and shift or 1, shift > 0 and shift or self.max_shifts for i = from, to do if max - (closed[i] or 0) > 0 then return true end end end function TrainingBuilding:OnChangeWorkshift(old, new) if old then local dark_penalty = IsDarkHour(self.city.hour - 4) and -g_Consts.WorkDarkHoursSanityDecrease for _, visitor in ipairs(self.visitors[old]) do if dark_penalty then visitor:ChangeSanity(dark_penalty, "work in dark hours") end visitor:InterruptVisit() end end self:UpdateOccupation(#self.visitors[new], self.max_visitors) RebuildInfopanel(self) end function TrainingBuilding:StartWorkCycle(unit) end function TrainingBuilding:StopWorkCycle(unit) end function TrainingBuilding:BuildingUpdate(time, day, hour) local visitors = self.visitors[self.current_shift] or empty_table local martianborn_adaptability = self.city:IsTechResearched("MartianbornAdaptability") and TechDef.MartianbornAdaptability.param1 for j= #visitors, 1, -1 do -- 'someone can 'graduate' and leave the list' local unit = visitors[j] self:GainPoints(unit, time, martianborn_adaptability) if self.evaluation_points>0 and (unit.training_points and unit.training_points[self.training_type] or 0)>= self.evaluation_points then self:OnTrainingCompleted(unit) self.life_time_trained = self.life_time_trained + 1 end end end function TrainingBuilding:CheatCompleteTraining() for shift, list in ipairs(self.visitors) do for _, unit in ipairs(list) do unit.training_points = unit.training_points or {} unit.training_points[self.training_type] = self.evaluation_points self:OnTrainingCompleted(unit) self.life_time_trained = self.life_time_trained + 1 end end end function TrainingBuilding:CanTrain(unit) local is_child = unit.traits["Child"] if is_child and not self.usable_by_children then return false end if not is_child and self.children_only then return false end return true end function TrainingBuilding:GainPoints(unit, time, martianborn_adaptability) if self.working then local gain_point = self.gain_point if martianborn_adaptability and unit.traits.Martianborn then gain_point = gain_point + MulDivRound(martianborn_adaptability, gain_point, 100) end gain_point = gain_point + MulDivRound(unit.performance, gain_point, 100) unit.training_points = unit.training_points or {} unit.training_points[self.training_type] = (unit.training_points[self.training_type] or 0) + MulDivRound(gain_point, time, g_Consts.WorkingHours * const.HourDuration) end end function TrainingBuilding:OnTrainingCompleted(unit) end function InitInsideTrainingAndWorkplaceBld(self, dome) local label = self.dome_label for _, dome in ipairs(UICity.labels.Dome or empty_table) do if IsBuildingInDomeRange(self, dome) then dome:RemoveFromLabel(label, self) end end Building.InitInside(self, dome) self:AddToDomeLabels(dome) end TrainingBuilding.InitInside = InitInsideTrainingAndWorkplaceBld function SavegameFixups.SetOccupationForExistingTrainingBuildings() MapForEach("map", "TrainingBuilding", function(o) o.occupation = #o.visitors[CurrentWorkshift] end) end
local Region = require("refactoring.region") local eq = assert.are.same local vim_motion = require("refactoring.tests.utils").vim_motion local function setup() vim.cmd(":new") vim.api.nvim_buf_set_lines(0, 0, -1, false, { "foo", "if (true) {", " bar", "}", }) end describe("Region", function() it("select text : line", function() setup() vim_motion("jV") local region = Region:from_current_selection() eq(region:get_text(), { "if (true) {" }) end) it("select text : partial-line", function() setup() -- TODO: Why is first selection just not present... vim_motion("jwvww") local region = Region:from_current_selection() eq({ "(true)" }, region:get_text()) end) it("select text : multi-partial-line", function() setup() -- TODO: Why is first selection just not present... vim.cmd(":1") vim_motion("jwvje") eq("n", vim.fn.mode()) eq(3, vim.fn.line(".")) local region = Region:from_current_selection() eq({ "(true) {", " bar" }, region:get_text()) end) it("contain region", function() local region = Region:from_values(0, 10, 100, 12, 50) local ins = { Region:from_values(0, 11, 0, 11, 69), Region:from_values(0, 10, 100, 12, 50), Region:from_values(0, 10, 100, 10, 10000), } local outs = { Region:from_values(0, 9, 100, 12, 50), -- out on start row Region:from_values(0, 10, 99, 11, 69), -- out on start col Region:from_values(0, 11, 100, 13, 50), -- out on end row Region:from_values(0, 11, 51, 12, 51), -- out on end col Region:from_values(1, 11, 51, 11, 52), -- diff bufnr } for _, v in pairs(ins) do eq(true, region:contains(v)) end for _, v in pairs(outs) do eq(false, region:contains(v)) end end) end)
require("prototypes.entities")
local to_json to_json = require("lapis.util").to_json local AttachedServer AttachedServer = require("lapis.cmd.attached_server").AttachedServer local CqueuesAttachedServer do local _class_0 local _parent_0 = AttachedServer local _base_0 = { start = function(self, env, overrides) local thread = require("cqueues.thread") self.port = overrides and overrides.port or require("lapis.config").get(env).port self.current_thread, self.thread_socket = assert(thread.start(function(sock, env, overrides) local from_json from_json = require("lapis.util").from_json local push, pop do local _obj_0 = require("lapis.environment") push, pop = _obj_0.push, _obj_0.pop end local start_server start_server = require("lapis.cmd.cqueues").start_server overrides = from_json(overrides) if not (next(overrides)) then overrides = nil end push(env, overrides) local config = require("lapis.config").get() local app_module = config.app_class or "app" return start_server(app_module) end, env, to_json(overrides or { }))) return self:wait_until_ready() end, detach = function(self) end } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) _class_0 = setmetatable({ __init = function(self, ...) return _class_0.__parent.__init(self, ...) end, __base = _base_0, __name = "CqueuesAttachedServer", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then local parent = rawget(cls, "__parent") if parent then return parent[name] end else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end CqueuesAttachedServer = _class_0 end return { AttachedServer = CqueuesAttachedServer }
-- Override digilines.transmit and digilines.receptor_send to add more functionality -- Mostly copied from https://github.com/minetest-mods/digilines/blob/master/internal.lua local function queue_new() return {nextRead = 1, nextWrite = 1} end local function queue_empty(queue) return queue.nextRead == queue.nextWrite end local function queue_enqueue(queue, object) local nextWrite = queue.nextWrite queue[nextWrite] = object queue.nextWrite = nextWrite + 1 end local function queue_dequeue(queue) local nextRead = queue.nextRead local object = queue[nextRead] queue[nextRead] = nil queue.nextRead = nextRead + 1 return object[1], object[2] end function digilines.transmit(pos, channel, msg, checked, origin) local checkedID = minetest.hash_node_position(pos) if checked[checkedID] or not origin then return end checked[checkedID] = true digilines.vm_begin() local queue = queue_new() queue_enqueue(queue, {pos, origin}) while not queue_empty(queue) do local curPos, fromPos = queue_dequeue(queue) local node = digilines.get_node_force(curPos) local spec = digilines.getspec(node) if spec then -- Effector actions --> Receive if spec.effector then spec.effector.action(curPos, node, channel, msg, fromPos) end -- Cable actions --> Transmit local rules -- Custom semiconductor def for digicontrol nodes if spec.semiconductor then rules = spec.semiconductor.rules(node, curPos, fromPos, channel) elseif spec.wire then rules = digilines.importrules(spec.wire.rules, node) end if rules then for _, rule in ipairs(rules) do local nextPos = digilines.addPosRule(curPos, rule) if digilines.rules_link(curPos, nextPos) then checkedID = minetest.hash_node_position(nextPos) if not checked[checkedID] then checked[checkedID] = true queue_enqueue(queue, {nextPos, curPos}) end end end end end end digilines.vm_end() end function digilines.receptor_send(pos, rules, channel, msg) local checked = {} checked[minetest.hash_node_position(pos)] = true -- exclude itself for _,rule in ipairs(rules) do if digilines.rules_link(pos, digilines.addPosRule(pos, rule)) then digilines.transmit(digilines.addPosRule(pos, rule), channel, msg, checked, pos) end end end
-- Local instances of Global tables -- local PA = PersonalAssistant local PAC = PA.Constants local PAHF = PA.HelperFunctions -- --------------------------------------------------------------------------------------------------------------------- local function _updateSavedVarsVersion(savedVarsVersion) local PAISavedVars = PA.SavedVars.Integration if tonumber(PAISavedVars.savedVarsVersion) < savedVarsVersion then PAHF.debuglnAuthor(table.concat({ PAC.COLORED_TEXTS.PA, " - Patched PAIntegration from [", tostring(PAISavedVars.savedVarsVersion), "] to [", tostring(savedVarsVersion), "]"})) PAISavedVars.savedVarsVersion = savedVarsVersion end end local function _getIsPatchNeededInfo(savedVarsVersion) local PAISavedVars = PA.SavedVars.Integration local currentVersion = tonumber(PAISavedVars.savedVarsVersion) or PAC.ADDON.SAVED_VARS_VERSION.MINOR return savedVarsVersion, (currentVersion < savedVarsVersion) end -- --------------------------------------------------------------------------------------------------------------------- local function _applyPatch_2_5_11(savedVarsVersion, isPatchingNeeded) if isPatchingNeeded then local PASavedVars = PA.SavedVars -- copy the profileCounter value PASavedVars.Integration.profileCounter = PASavedVars.General.profileCounter -- then loop through all profiles and copy the profileName for profileNo = 1, PASavedVars.General.profileCounter do if istable(PASavedVars.Integration[profileNo]) then PASavedVars.Integration[profileNo].name = PASavedVars.General[profileNo].name end end _updateSavedVarsVersion(savedVarsVersion) end end -- local function _applyPatch_x_x_x(savedVarsVersion, isPatchingNeeded) -- --------------------------------------------------------------------------------------------------------------------- local function applyPatchIfNeeded() -- Patch 2.5.11 April 23, 2021 _applyPatch_2_5_11(_getIsPatchNeededInfo(020511)) end -- --------------------------------------------------------------------------------------------------------------------- -- Export PA.SavedVarsPatcher.applyPAIntegrationPatchIfNeeded = applyPatchIfNeeded
-- -- -- ---------------------------------------------------------- -- Mosaic | OF Visual Patching Developer Platform -- -- Copyright (c) 2019 Emanuele Mazza aka n3m3da -- -- Mosaic is distributed under the MIT License. This gives everyone the -- freedoms to use Mosaic in any context: commercial or non-commercial, -- public or private, open or closed source. -- -- See https://github.com/d3cod3/Mosaic for documentation -- ---------------------------------------------------------- -- -- -- Polyline.lua -- -- Basic use of of.polyline class. -- -- created by n3m3da | www.d3cod3.org -- translated from GAmuza examples by ferhoyo https://github.com/ferhoyo -- -- -- variables for mouse interaction (DO NOT DELETE) mouseX = 0 mouseY = 0 lazo = of.Polyline() smoothed = of.Polyline() box = of.Rectangle() ---------------------------------------------------- function setup() for i=0,90 do lazo:addVertex(math.sin(of.degToRad(i))*OUTPUT_WIDTH,math.cos(i)*OUTPUT_HEIGHT/4,0) end smoothed = lazo:getSmoothed(9,0.3) box = lazo:getBoundingBox() end ---------------------------------------------------- function update() end ---------------------------------------------------- function draw() of.background(0) of.pushMatrix() of.translate(0,OUTPUT_HEIGHT/2,0) -- polyline of.setColor(255) of.setLineWidth(1) lazo:draw() -- smoothed polyline of.setColor(18,159,211) of.setLineWidth(2) smoothed:draw() -- bounding box of.setColor(255) of.noFill() of.drawRectangle(box.x,box.y,box.width,box.height) of.popMatrix() end ---------------------------------------------------- function exit() end -- input callbacks ---------------------------------------------------- function keyPressed(key) end function keyReleased(key) end function mouseMoved(x,y) mouseX = x mouseY = y end function mouseDragged(x,y) mouseX = x mouseY = y end function mouseReleased(x,y) end function mouseScrolled(x,y) end
--DO NOT EDIT OR REUPLOAD THIS FILE AddCSLuaFile( "shared.lua" ) AddCSLuaFile( "cl_init.lua" ) include("shared.lua") function ENT:SpawnFunction( ply, tr, ClassName ) if not tr.Hit then return end local ent = ents.Create( ClassName ) ent:SetPos( tr.HitPos + tr.HitNormal * 120 ) ent:Spawn() ent:Activate() return ent end function ENT:RunOnSpawn() end function ENT:PrimaryAttack() if not self:CanPrimaryAttack() then return end self:EmitSound( "TIE_FIRE" ) self:SetNextPrimary( 0.32 ) for i = 0,1 do self.MirrorPrimary = not self.MirrorPrimary local Mirror = self.MirrorPrimary and -1 or 1 local bullet = {} bullet.Num = 1 bullet.Src = self:LocalToWorld( Vector(36.78,11.5 * Mirror,-30.955) ) bullet.Dir = self:LocalToWorldAngles( Angle(0,0,0) ):Forward() bullet.Spread = Vector( 0.02, 0.02, 0 ) bullet.Tracer = 1 bullet.TracerName = "lfs_laser_green" bullet.Force = 100 bullet.HullSize = 35 bullet.Damage = 60 bullet.Attacker = self:GetDriver() bullet.AmmoType = "Pistol" bullet.Callback = function(att, tr, dmginfo) dmginfo:SetDamageType(DMG_AIRBOAT) local effectdata = EffectData() effectdata:SetOrigin( tr.HitPos ) util.Effect( "helicoptermegabomb", effectdata ) end self:FireBullets( bullet ) self:TakePrimaryAmmo() end end function ENT:SecondaryAttack() if not self:CanSecondaryAttack() then return end self:EmitSound( "TIE_FIRE" ) self:SetNextSecondary( 0.16 ) local fP = { Vector(36.78,11.5,-30.955), Vector(36.78,-11.5,-30.955), Vector(36.78,11.5,-30.955),Vector(36.78,-11.5,-30.955) } self.NumPrim = self.NumPrim and self.NumPrim + 1 or 1 if self.NumPrim > 4 then self.NumPrim = 1 end local startpos = self:GetRotorPos() local TracePlane = util.TraceHull( { start = startpos, endpos = (startpos + self:GetForward() * 50000), mins = Vector( -10, -10, -10 ), maxs = Vector( 10, 10, 10 ), filter = self } ) local bullet = {} bullet.Num = 1 bullet.Src = self:LocalToWorld( fP[self.NumPrim] ) bullet.Dir = (TracePlane.HitPos - bullet.Src):GetNormalized() bullet.Spread = Vector( 0.01, 0.01, 0 ) bullet.Tracer = 1 bullet.TracerName = "lfs_laser_green" bullet.Force = 100 bullet.HullSize = 50 bullet.Damage = 50 bullet.Attacker = self:GetDriver() bullet.AmmoType = "Pistol" bullet.Callback = function(att, tr, dmginfo) dmginfo:SetDamageType(DMG_AIRBOAT) local effectdata = EffectData() effectdata:SetOrigin( tr.HitPos ) util.Effect( "helicoptermegabomb", effectdata ) end self:FireBullets( bullet ) self:TakePrimaryAmmo() end function ENT:RunEngine() local IdleRPM = self:GetIdleRPM() local MaxRPM =self:GetMaxRPM() local LimitRPM = self:GetLimitRPM() local MaxVelocity = self:GetMaxVelocity() self.TargetRPM = self.TargetRPM or 0 if self:GetEngineActive() then local Pod = self:GetDriverSeat() if not IsValid( Pod ) then return end local Driver = Pod:GetDriver() local RPMAdd = 0 local KeyThrottle = false local KeyBrake = false if IsValid( Driver ) then KeyThrottle = Driver:KeyDown( IN_FORWARD ) KeyBrake = Driver:KeyDown( IN_BACK ) RPMAdd = ((KeyThrottle and 2000 or 0) - (KeyBrake and 2000 or 0)) * FrameTime() end if KeyThrottle ~= self.oldKeyThrottle then self.oldKeyThrottle = KeyThrottle if KeyThrottle then if self:CanSound() then self:EmitSound( "TIE_BOOST" ) self:DelayNextSound( 1 ) end else if (self:GetRPM() + 1) > MaxRPM then if self:CanSound() then self:EmitSound( "TIE_BRAKE" ) self:DelayNextSound( 0.5 ) end end end end self.TargetRPM = math.Clamp( self.TargetRPM + RPMAdd,IdleRPM,KeyThrottle and LimitRPM or MaxRPM) else self.TargetRPM = self.TargetRPM - math.Clamp(self.TargetRPM,-250,250) end self:SetRPM( self:GetRPM() + (self.TargetRPM - self:GetRPM()) * FrameTime() ) local PhysObj = self:GetPhysicsObject() if not IsValid( PhysObj ) then return end local Throttle = self:GetRPM() / self:GetLimitRPM() local Power = (MaxVelocity * Throttle - self:GetForwardVelocity()) / MaxVelocity * self:GetMaxThrust() * self:GetLimitRPM() if self:IsDestroyed() or not self:GetEngineActive() then self:StopEngine() return end PhysObj:ApplyForceOffset( self:GetForward() * Power * FrameTime(), self:GetRotorPos() ) end function ENT:HandleActive() local Pod = self:GetDriverSeat() if not IsValid( Pod ) then self:SetActive( false ) return end local Driver = Pod:GetDriver() if Driver ~= self:GetDriver() then if IsValid( self:GetDriver() ) then self:GetDriver():SetNoDraw( false ) end if IsValid( Driver ) then Driver:SetNoDraw( true ) end self:SetDriver( Driver ) self:SetActive( IsValid( Driver ) ) if self:GetActive() then self:EmitSound( "vehicles/atv_ammo_close.wav" ) else self:EmitSound( "vehicles/atv_ammo_open.wav" ) end end end function ENT:PrepExplode() if self.MarkForDestruction then self:Explode() end if self:IsDestroyed() then self:Explode() end end function ENT:Explode() if self.ExplodedAlready then return end self.ExplodedAlready = true local Driver = self:GetDriver() local Gunner = self:GetGunner() if IsValid( Driver ) then Driver:TakeDamage( 200, self.FinalAttacker or Entity(0), self.FinalInflictor or Entity(0) ) end if IsValid( Gunner ) then Gunner:TakeDamage( 200, self.FinalAttacker or Entity(0), self.FinalInflictor or Entity(0) ) end if istable( self.pSeats ) then for _, pSeat in pairs( self.pSeats ) do if IsValid( pSeat ) then local psgr = pSeat:GetDriver() if IsValid( psgr ) then psgr:TakeDamage( 200, self.FinalAttacker or Entity(0), self.FinalInflictor or Entity(0) ) end end end end local ent = ents.Create( "lunasflightschool_destruction_tie" ) if IsValid( ent ) then ent:SetPos( self:GetPos() + Vector(0,0,100) ) ent.GibModels = self.GibModels ent:Spawn() ent:Activate() end self:Remove() end function ENT:CreateAI() end function ENT:RemoveAI() end function ENT:InitWheels() local PObj = self:GetPhysicsObject() if IsValid( PObj ) then PObj:EnableMotion( true ) end end function ENT:ToggleLandingGear() end function ENT:RaiseLandingGear() end function ENT:CreateAI() self:SetBodygroup( 1, 1 ) end function ENT:RemoveAI() self:SetBodygroup( 1, 0 ) end function ENT:HandleWeapons(Fire1, Fire2) local Driver = self:GetDriver() if IsValid( Driver ) then if self:GetAmmoPrimary() > 0 then Fire1 = Driver:KeyDown( IN_ATTACK ) end if self:GetAmmoPrimary() > 0 then Fire2 = Driver:KeyDown( IN_ATTACK2 ) end end if Fire1 then self:PrimaryAttack() end if Fire2 then self:SecondaryAttack() end end
-- --BEAVER -- local S, modpath, mg_name = ... local pet_name = "beaver" local mesh = nil local scale_beaver = 1.2 local textures = {} local collisionbox = {} local fixed = {} local tiles = {} local spawn_nodes = {} if mg_name == "valleys" then spawn_nodes = {"default:river_water_source"} else spawn_nodes = {"default:water_source"} end local animation_terrestrial = { speed_normal = 15, walk_start = 1, walk_end = 12, speed_run = 25, run_start = 13, run_end = 25, stand_start = 26, stand_end = 46, stand2_start = 47, stand2_end = 59, --sit stand3_start = 71, stand4_end = 91, stand4_start = 82, stand4_end = 95, } local animation_aquatic = { speed_normal = 15, walk_start = 96, walk_end = 121, --swin speed_run = 25, run_start = 96, run_end = 121, stand_start = 26, stand_end = 46, stand2_start = 82, stand4_end = 95, } if petz.settings.type_model == "cubic" then local node_name = "petz:"..pet_name.."_block" fixed = { {-0.1875, -0.375, -0.25, 0.125, -0.0625002, 0.1875}, -- body {-0.1875, -0.375, -0.375, 0.125, -0.125, -0.25}, -- head {-0.125, -0.375, -0.4375, 0.0625, -0.25, -0.375}, -- snout {-0.125, -0.25, 0.1875, 0.0625, -0.1875, 0.5}, -- tail {-0.0625, -0.4375, -0.4375, -5.58794e-09, -0.375, -0.375}, -- teeth {0, -0.5, -0.25, 0.125, -0.375, -0.125}, -- front_left_leg {-0.1875, -0.5, -0.25, -0.0625, -0.375, -0.125}, -- front_right_leg {0, -0.5, 0.0625, 0.125, -0.375, 0.1875}, -- back_left_leg {-0.1875, -0.5, 0.0625, -0.0625, -0.375, 0.1875}, -- back_right_leg {-0.25, -0.25, -0.3125, -0.1875, -0.1875, -0.25}, -- left_ear {0.125, -0.25, -0.3125, 0.1875, -0.1875, -0.25}, -- right_ear } tiles = { "petz_beaver_top.png", "petz_beaver_bottom.png", "petz_beaver_right.png", "petz_beaver_left.png", "petz_beaver_back.png", "petz_beaver_front.png" } petz.register_cubic(node_name, fixed, tiles) textures= {"petz:beaver_block"} collisionbox = {-0.35, -0.75*scale_beaver, -0.28, 0.35, -0.125, 0.28} else mesh = 'petz_beaver.b3d' textures= {{"petz_beaver.png"}} collisionbox = {-0.35, -0.75*scale_beaver, -0.28, 0.35, -0.3125, 0.28} end local create_dam = function(self, mod_path, pos) if petz.settings.beaver_create_dam == true and self.dam_created == false then --a beaver can create only one dam if math.random(1, 60000) > 1 then --chance of the dam to be created return false end local pos_underwater = { --check if water below (when the beaver is still terrestrial but float in the surface of the water) x = pos.x, y = pos.y - 4.5, z = pos.z, } if minetest.get_node(pos_underwater).name == "default:sand" then local pos_dam = { --check if water below (when the beaver is still terrestrial but float in the surface of the water) x = pos.x, y = pos.y - 2.0, z = pos.z, } minetest.place_schematic(pos_dam, modpath..'/schematics/beaver_dam.mts', 0, nil, true) self.dam_created = true return true end end return false end local set_behaviour= function(self, behaviour) if behaviour == "aquatic" then self.fly = true self.floats = 0 self.animation = animation_aquatic elseif behaviour == "terrestrial" then self.fly = false -- make terrestrial self.floats = 1 self.animation = animation_terrestrial end end mobs:register_mob("petz:"..pet_name, { type = "animal", rotate = petz.settings.rotate, damage = 8, hp_min = 4, hp_max = 8, armor = 200, visual = petz.settings.visual, visual_size = {x=petz.settings.visual_size.x*scale_beaver, y=petz.settings.visual_size.y*scale_beaver}, mesh = mesh, textures = textures, collisionbox = collisionbox, makes_footstep_sound = false, walk_velocity = 0.75, run_velocity = 1, runaway = true, pushable = true, fly = true, fly_in = spawn_nodes, floats = 1, jump = true, follow = petz.settings.beaver_follow, drops = { {name = "mobs:meat_raw", chance = 1, min = 1, max = 1,}, {name = "petz:beaver_fur", chance = 1, min = 1, max = 1,}, }, water_damage = 0, lava_damage = 6, light_damage = 0, sounds = { random = "petz_beaver_sound", }, animation = animation_aquatic, view_range = 4, fear_height = 3, stay_near= { nodes = spawn_nodes, chance = 3, }, on_rightclick = function(self, clicker) petz.on_rightclick(self, clicker) end, do_custom = function(self, dtime) if not self.custom_vars_set02 then self.custom_vars_set02 = 0 self.petz_type = "beaver" self.is_pet = false self.give_orders = false self.affinity = 100 self.init_timer = false self.fed= false self.brushed = false self.beaver_oil_applied = false self.dam_created = false end local beaver_behaviour --terrestrial, floating or aquatic local pos = self.object:get_pos() -- check the beaver pos to togle between aquatic-terrestrial local node = minetest.get_node_or_nil(pos) if node and minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].groups.water then set_behaviour(self, "aquatic") create_dam(self, modpath, pos) else local pos_underwater = { --check if water below (when the beaver is still terrestrial but float in the surface of the water) x = pos.x, y = pos.y - 3.5, z = pos.z, } node = minetest.get_node_or_nil(pos_underwater) if node and minetest.registered_nodes[node.name] and minetest.registered_nodes[node.name].groups.water and self.floats == false then local pos_below = { x = pos.x, y = pos.y - 2.0, z = pos.z, } self.object:move_to(pos_below, true) -- move the beaver underwater set_behaviour(self, "aquatic") create_dam(self, modpath, pos) else set_behaviour(self, "terrestrial") end end end, }) mobs:register_egg("petz:beaver", S("Beaver"), "petz_spawnegg_beaver.png", 0) mobs:spawn({ name = "petz:beaver", nodes = spawn_nodes, neighbors = {"default:sand", "default:dirt", "group:seaplants"}, min_light = 14, interval = 90, chance = petz.settings.beaver_spawn_chance, min_height = 1, max_height = -8, day_toggle = true, })
require "class.tile" Island = Class {} function Island:init(x, y) self.x = x self.y = y self.xmin = 0 self.xmax = 0 self.ymin = 0 self.ymax = 0 self.h = 1 self.tiles = {} for i=0,5 do for j=0,5 do self:addTile(i, j, Tile()) end end self:redraw() end function Island:redraw() self.canvas = drawHandler.generateIslandCanvas(self) end function Island:addTile(x, y, tile) if not self.tiles[y] then self.tiles[y] = {} end self.tiles[y][x] = tile if x > self.xmax then self.xmax = x end if x < self.xmin then self.xmin = x end if y > self.ymax then self.ymax = y end if y < self.ymin then self.ymin = y end if #tile.textures > self.h then self.h = #tile.textures end end function Island:getTile(x, y) if not self.tiles[y] then return nil end if not self.tiles[y][x] then return nil end return self.tiles[y][x] end -- returns center coordinates: x, y function Island:getCenter() return self.x + self.xmax / 2, self.y + self.ymax / 2 end
--[[ 索引管理器 --]] local THIS_MODULE = ... local C_LOGTAG = "IndexManager" local cjson = cc.safe_require("cjson") local IndexManager = class("IndexManager") -- 获得单例对象 local instance = nil function IndexManager:getInstance() if instance == nil then instance = IndexManager:create() end return instance end -- 构造函数 function IndexManager:ctor() self._envs = {} -- 环境变量 self._indexnodes = {} -- 索引节点 self._indexes = {} -- 索引表 self._listen = { -- 监听 remove = { entities = {} }, -- 移除配置 loads = {}, -- 加载配置 } end ---------------------------------------------------------- -- 环境变量 -- 设置环境变量 function IndexManager:setEnv(key, value) local fkey = "$(" .. key .. ")" if self._envs[fkey] then local msg = string.format("index env %s conflict", key) if ERROR.INDEX_ENV_CONFLICT then error(msg) else logMgr:warn(C_LOGTAG, msg) end end self._envs[fkey] = value end -- 设置环境配置 function IndexManager:setEnvConfig(envconf) if envconf then for key,value in pairs(envconf) do self:setEnv(key, value) end end end -- 获得环境变量 function IndexManager:getEnv(key) return self._envs["$(" .. key .. ")"] end -- 清除环境变量 function IndexManager:clearEnvs() self._envs = {} end ---------------------------------------------------------- -- json配置读写 -- 读取json文件 function IndexManager:readJson(jsonfile) local jsonpath = fileUtils:fullPathForFilename(jsonfile) if fileUtils:isFileExist(jsonpath) then return cjson.decode(fileUtils:getDataFromFile(jsonpath)) end end -- 写入json文件 function IndexManager:writeJson(jdata,jsonfile) if jdata and jsonfile then fileUtils:writeStringToFile(cjson.encode(jdata), jsonfile) end end -- 读取json配置文件,环境变量替换 function IndexManager:readJsonConfig(jsonfile) logMgr:verbose(C_LOGTAG, "read config json : %s", jsonfile) local jsonpath = fileUtils:fullPathForFilename(jsonfile) if fileUtils:isFileExist(jsonpath) then local newenvs = { ["$(curpath)"] = io.pathinfo(jsonpath).dirname } table.merge(newenvs, self._envs) local jsondata = fileUtils:getDataFromFile(jsonpath) jsondata = jsondata:gsub("%$%(%w+%)", newenvs) return cjson.decode(jsondata) end end ---------------------------------------------------------- -- 索引操作 -- 合并表 function IndexManager:mergeTalbe(jdest, jsrc, jpath, listen, jsonpath) jpath = jpath or "" for name,value in pairs(jsrc) do if type(name) == "number" then name = #jdest + 1 end local ijpath = (jpath ~= "") and (jpath .. "/" .. name) or name if type(value) == "table" then local itable = jdest[name] if not itable then itable = {} jdest[name] = itable end self:mergeTalbe(itable, value, ijpath, listen, jsonpath) else if jdest[name] then local msg = string.format("index path %s conflict : %s", ijpath, jsonpath or "[unknown]") if ERROR.INDEX_PATH_CONFLICT then error(msg) else logMgr:warn(C_LOGTAG, msg) end end jdest[name] = value end if listen then self:notifyIndexesLoaded(ijpath, value) end end end -- 重构索引 function IndexManager:rebuildIndexes() self._indexes = {} for node,index in pairs(self._indexnodes) do self:mergeTalbe(self._indexes, index) end end -- 获得指定索引 function IndexManager:getIndex(path) local value = self._indexes for _,pnode in ipairs(path:split('/')) do if not value then return nil end value = value[pnode] end return value end -- 加载索引文件 function IndexManager:loadIndexFile(file, node) node = node or file local newindex = self:readJsonConfig(file) local nodeindex = self._indexnodes[node] if not nodeindex then self._indexnodes[node] = newindex else self:mergeTalbe(nodeindex, newindex) end self:mergeTalbe(self._indexes, newindex, "", true, file) end -- 移除索引节点 function IndexManager:removeIndexNode(node) if self._indexnodes[node] then self._indexnodes[node] = nil self:rebuildIndexes() self:notifyIndexesRemoved() end end -- 加载索引文件配置 function IndexManager:loadIndexFileConfig(confile, node) local indexconf = self:readJsonConfig(confile) if indexconf then for _,indexfile in pairs(indexconf) do self:loadIndexFile(indexfile, node or confile) end end end -- 清除全部索引 function IndexManager:clearIndexes() self._indexnodes = {} self._indexes = {} self:notifyIndexesRemoved() end ---------------------------------------------------------- -- 索引监听 -- 添加监听器 function IndexManager:addListener(listener, ipaths, priority) self:removeListener(listener) local lentity = { listener = listener, priority = priority or 0, } -- 更新移除监听器 self._listen.remove.entities[listener] = lentity self._listen.remove.queue = table.values(self._listen.remove.entities) table.sort(self._listen.remove.queue, function (a, b) return a.priority < b.priority end) -- 更新加载路径监听器 if ipaths then for _,ipath in ipairs(ipaths) do if ipath:byte(#ipath) == 47 then -- / ipath = ipath:sub(1,-2) end local loadconf = self._listen.loads[ipath] if not loadconf then loadconf = { entities = {} } self._listen.loads[ipath] = loadconf end loadconf.entities[listener] = lentity loadconf.queue = table.values(loadconf.entities) table.sort(loadconf.queue, function (a, b) return a.priority > b.priority end) end end end -- 移除监听器 function IndexManager:removeListener(listener) if self._listen.remove.entities[listener] then -- 移除移除表 self._listen.remove.entities[listener] = nil self._listen.remove.queue = table.values(self._listen.remove.entities) table.sort(self._listen.remove.queue, function (a, b) return a.priority < b.priority end) -- 移除路径表 for _,loadconf in pairs(self._listen.loads) do if loadconf.entities[listener] then loadconf.entities[listener] = nil loadconf.queue = table.values(loadconf.entities) table.sort(loadconf.queue, function (a, b) return a.priority > b.priority end) end end end end -- 清空监听器 function IndexManager:clearListeners() self._listen = { remove = { entities = {} }, loads = {}, } end -- 通知索引加载 function IndexManager:notifyIndexesLoaded(ipath, ivalue) local loadconf = self._listen.loads[ipath] if loadconf then for _,lentity in ipairs(loadconf.queue or {}) do lentity.listener:onIndexesLoaded(ipath, ivalue) end end end -- 通知索引移除 function IndexManager:notifyIndexesRemoved() for _,lentity in ipairs(self._listen.remove.queue or {}) do lentity.listener:onIndexesRemoved() end end return IndexManager
ITEM.name = "FN F2000" ITEM.desc = "Бельгийский автоматно-гранатомётный комплекс, выполненный в компоновке «булл-пап». Оснащён компьютеризованным прицелом и подствольным гранатомётом. Встречается только у ветеранов и мастеров в экзоскелетах. \n\nБоеприпасы 5.56х45" ITEM.price = 66112 ITEM.model = "models/wick/weapons/stalker/stcopwep/w_fn2000_model_stcop.mdl" ITEM.class = "weapon_cop_fn2000" ITEM.weaponCategory = "1" ITEM.category = "Оружие" ITEM.height = 2 ITEM.width = 4 ITEM.exRender = false ITEM.weight = 4.13 ITEM.iconCam = { pos = Vector(-4.5, 200, 0), ang = Angle(0, 270, 0), fov = 12 }
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' client_script 'client.lua' exports { 'OpenStorage' }
---@class Void : java.lang.Void ---@field public TYPE Class|Unknown Void = {}
-- example HTTP POST script which demonstrates setting the -- HTTP method, body, and adding a header wrk.method = "POST" wrk.body = '{"text":"This was the biggest hit movie of 1971"}' wrk.headers["Content-Type"] = "application/json"
--[[ Copyright 2016 Adobe Systems Incorporated. All rights reserved. This file is licensed 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 RESPRESENTATIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]] -- -- Checks if the rule has to be redirected to a different backend. -- Usage: -- location /randomlocation { -- set_by_lua $backend " -- local m = require 'api-gateway.tracking.validator.rewritingRulesValidator'; -- local v = m:new(); -- local backend = m:validateRequest(); -- return backend; -- "; -- content_by_lua "ngx.say(ngx.var.backend)"; -- } -- local BaseValidator = require "api-gateway.validation.validator" local _M = BaseValidator:new() local function getBackendFromRewriteRule( rewrite_rule ) local backend = rewrite_rule.meta or nil local variableManager = ngx.apiGateway.tracking.variableManager if ( backend == nil ) then return nil end if ( string.sub(backend, 1, 1) == "$" ) then backend = variableManager:getRequestVariable(string.sub(backend, 2), nil) end return backend end --- -- @param config_obj configuration object -- returns the meta field of the first matched rule. -- function _M:validate_rewrite_rules(config_obj) local trackingManager = ngx.apiGateway.tracking.manager if ( trackingManager == nil ) then ngx.log(ngx.WARN, "Please initialize RequestTrackingManager before calling this method") end -- 1. read the keys in the shared dict and compare it with the current request local stop_at_first_block_match = true local rewrite_rule = trackingManager:getMatchingRulesForRequest("rewrite",";", stop_at_first_block_match) if rewrite_rule == nil then -- there is no match, so we return nil return nil end ngx.var.rewritten_by = rewrite_rule.id local backend = getBackendFromRewriteRule(rewrite_rule) return backend end function _M:validateRequest(obj) local backend = self:validate_rewrite_rules(obj) return backend end return _M
local api = require("api") local irc = {} function irc.connect(server, port) local srv = server or "irc.freenode.net" local prt = port or 6667 api.connect(srv, prt) end function irc.sendUser(username, hostname, server, realname) api.sendf( "USER %s %s %s :%s", username, hostname, server, realname ) end function irc.sendNick(nickname) api.sendf("NICK %s", nickname) end function irc.sendPassword(password) if password then api.sendf("PASS %s", password) end end function irc.sendPing(server) api.sendf("PING %s", server) end function irc.sendPong(code) api.sendf("PONG %s", code) end function irc.sendQuit(reason) api.sendf("QUIT :%s", reason) end function irc.joinChannel(channel) if channel then api.sendf("JOIN %s", channel) end end return irc
-- ------------------------------------------------------------------------------------- -- Including Standard Awesome Libraries local awful = require("awful") local wibox = require("wibox") local gears = require("gears") local naughty = require("naughty") local beautiful = require("beautiful").startscreen.alarm -- ------------------------------------------------------------------------------------- -- Including Custom Helper Libraries local helpers = require("helpers") -- ------------------------------------------------------------------------------------- -- Creating the Alarm Widget local alarm_icon = wibox.widget { image = beautiful.icon, resize = true, forced_width = beautiful.icon_size, forced_height = beautiful.icon_size, widget = wibox.widget.imagebox } local centered = helpers.centered local alarm = wibox.widget { centered( centered(alarm_icon, "horizontal"), "vertical" ), bg = beautiful.bg, shape = helpers.rrect(beautiful.border_radius or 0), forced_width = beautiful.width, forced_height = beautiful.height, widget = wibox.container.background } helpers.add_clickable_effect( alarm, function() alarm.bg = beautiful.bg_hover end, function() alarm.bg = beautiful.bg end ) -- ------------------------------------------------------------------------------------- -- Adding Button Controls to the Widget alarm:buttons(gears.table.join( -- Left click - Open alarm awful.button({}, 1, function() awful.spawn.with_shell("alarm-clock-applet") end) )) -- ------------------------------------------------------------------------------------- return alarm
-- 修改:SomeBlu local E, L, V, P, G = unpack(ElvUI) -- Import Functions/Constants, Config, Locales local WT = E:GetModule("WindTools") local AB = E:NewModule('Wind_AutoButton', 'AceEvent-3.0') local _G = _G local setglobal = setglobal local wipe = table.wipe local tinsert, strmatch = table.insert, strmatch local tonumber,pairs,select,gsub = tonumber,pairs,select,string.gsub local CreateFrame = CreateFrame local CreateButton = CreateButton local GetNumQuestWatches = GetNumQuestWatches local GetQuestWatchInfo = GetQuestWatchInfo local GetQuestLogSpecialItemInfo = GetQuestLogSpecialItemInfo local GetItemSpell = GetItemSpell local GetItemInfo = GetItemInfo local InCombatLockdown = InCombatLockdown local GetItemCount = GetItemCount local GetCurrentMapAreaID = C_Map.GetBestMapForUnit local GetQuestsForPlayerByMapID = C_TaskQuest.GetQuestsForPlayerByMapID local GetItemIcon = GetItemIcon local IsArtifactPowerItem = IsArtifactPowerItem local GetQuestLogSpecialItemCooldown = GetQuestLogSpecialItemCooldown local GetItemCooldown = GetItemCooldown local CooldownFrame_SetTimer = CooldownFrame_Set local IsItemInRange = IsItemInRange local GetInventoryItemTexture = GetInventoryItemTexture local GetItemQualityColor = GetItemQualityColor local GetInventoryItemCooldown = GetInventoryItemCooldown local GetBindingKey = GetBindingKey local GetContainerNumSlots = GetContainerNumSlots local GetContainerItemLink = GetContainerItemLink local GetContainerItemInfo = GetContainerItemInfo local ARTIFACT_POWER = ARTIFACT_POWER local Cache = {} local tooltipName = "EAPUscanner" local tooltipScanner = CreateFrame("GameTooltip", tooltipName, nil, "GameTooltipTemplate") --Binding Variables BINDING_HEADER_AutoSlotButton = "|cffC495DDWindTools|r".. L["Auto InventoryItem Button"]; BINDING_HEADER_AutoQuestButton = "|cffC495DDWindTools|r".. L["Auto QuestItem Button"]; for i = 1, 12 do _G["BINDING_NAME_CLICK AutoSlotButton"..i..":LeftButton"] = L["Auto InventoryItem Button"]..i _G["BINDING_NAME_CLICK AutoQuestButton"..i..":LeftButton"] = L["Auto QuestItem Button"]..i end ---------------------------------------------------------------------------------------- -- AutoButton (by eui.cc at 2015/02/07) ---------------------------------------------------------------------------------------- local QuestItemList = {} local garrisonsmv = {118897, 118903} local garrisonsc = {114116, 114119, 114120, 120301, 120302} local function GetAptifactItem() for bag = 0, NUM_BAG_SLOTS do for slot = 1, GetContainerNumSlots(bag) do local itemLink = GetContainerItemLink(bag, slot) local itemID = select(10, GetContainerItemInfo(bag, slot)) if itemLink and IsArtifactPowerItem(itemLink) then if Cache[itemLink] then return itemLink, itemID else tooltipScanner:SetOwner(UIParent, "ANCHOR_NONE") tooltipScanner:SetHyperlink(itemLink) for i = 2,4 do local tooltipText = _G[tooltipName.."TextLeft"..i]:GetText() if tooltipText and tooltipText:match(ARTIFACT_POWER) then Cache[itemLink] = true return itemLink, itemID end end end end end end return nil end local function GetQuestItemList() wipe(QuestItemList) for i = 1, GetNumQuestWatches() do local questID, title, questLogIndex, numObjectives, requiredMoney, isComplete, startEvent, isAutoComplete, failureTime, timeElapsed, questType, isTask, isStory, isOnMap, hasLocalPOI = GetQuestWatchInfo(i); if questLogIndex then local link, item, charges, showItemWhenComplete = GetQuestLogSpecialItemInfo(questLogIndex); if link then local itemID = tonumber(link:match(":(%d+):")) QuestItemList[itemID] = { ['isComplete'] = isComplete, ['showItemWhenComplete'] = showItemWhenComplete, ['questLogIndex'] = questLogIndex, } end end end AB:ScanItem('QUEST') end local function GetWorldQuestItemList(toggle) local mapID = GetCurrentMapAreaID("player") or 0; local taskInfo = GetQuestsForPlayerByMapID(mapID); if (taskInfo and #taskInfo > 0) then for i, info in pairs(taskInfo) do local questID = info.questId local questLogIndex = GetQuestLogIndexByID(questID); if questLogIndex then local link, item, charges, showItemWhenComplete = GetQuestLogSpecialItemInfo(questLogIndex); if link then local itemID = tonumber(link:match(":(%d+):")) QuestItemList[itemID] = { ['isComplete'] = isComplete, ['showItemWhenComplete'] = showItemWhenComplete, ['questLogIndex'] = questLogIndex, } end end end end if(toggle ~= 'init') then AB:ScanItem('QUEST') end end local function haveIt(num, spellName) if not spellName then return false; end for i = 1, num do local AutoButton = _G["AutoQuestButton"..i] if not AutoButton then break; end if AutoButton.spellName == spellName then return false; end end return true; end local function IsUsableItem(itemId) local itemSpell = GetItemSpell(itemId) if not itemSpell then return false; end return itemSpell end local function IsSlotItem(itemId) local itemSpell = IsUsableItem(itemId) local itemName = GetItemInfo(itemId) return itemSpell end local function AutoButtonHide(AutoButton) if not AutoButton then return end AutoButton:SetAlpha(0) if not InCombatLockdown() then AutoButton:EnableMouse(false) else AutoButton:RegisterEvent("PLAYER_REGEN_ENABLED") AutoButton:SetScript("OnEvent", function(self, event) if event == "PLAYER_REGEN_ENABLED" then self:EnableMouse(false) self:UnregisterEvent("PLAYER_REGEN_ENABLED") end end) end end local function HideAllButton(event) local i, k = 1, 1 if (event ~= "BAG_UPDATE_DELAYED") and _G["AutoQuestButton1"].ap then k = 2 end for i = k, 12 do AutoButtonHide(_G["AutoQuestButton"..i]) end for i = 1, 12 do AutoButtonHide(_G["AutoSlotButton"..i]) end end local function AutoButtonShow(AutoButton) if not AutoButton then return end AutoButton:SetAlpha(1) AutoButton:SetScript("OnEnter", function(self) if InCombatLockdown() then return; end GameTooltip:SetOwner(self, 'ANCHOR_BOTTOMRIGHT', 0, -2) GameTooltip:ClearLines() if self.slotID then GameTooltip:SetInventoryItem('player', self.slotID) else GameTooltip:SetItemByID(self.itemID) end GameTooltip:Show() end) AutoButton:SetScript("OnLeave", function(self) GameTooltip:Hide() end) if not InCombatLockdown() then AutoButton:EnableMouse(true) if AutoButton.slotID then AutoButton:SetAttribute("type", "macro") AutoButton:SetAttribute("macrotext", "/use "..AutoButton.slotID) elseif AutoButton.itemName then AutoButton:SetAttribute("type", "item") AutoButton:SetAttribute("item", AutoButton.itemName) end else AutoButton:RegisterEvent("PLAYER_REGEN_ENABLED") AutoButton:SetScript("OnEvent", function(self, event) if event == "PLAYER_REGEN_ENABLED" then self:EnableMouse(true) if self.slotID then self:SetAttribute("type", "macro") self:SetAttribute("macrotext", "/use "..self.slotID) elseif self.itemName then self:SetAttribute("type", "item") self:SetAttribute("item", self.itemName) end self:UnregisterEvent("PLAYER_REGEN_ENABLED") end end) end end local function CreateButton(name, size) if _G[name] then _G[name]:Size(size) _G[name].c:FontTemplate(nil, E.db.WindTools["Interface"]["Auto Buttons"].countFontSize, 'OUTLINE') _G[name].k:FontTemplate(nil, E.db.WindTools["Interface"]["Auto Buttons"].bindFontSize, 'OUTLINE') return _G[name] end -- Create button local AutoButton = CreateFrame("Button", name, E.UIParent, "SecureActionButtonTemplate") AutoButton:Size(size) AutoButton:SetTemplate("Default") AutoButton:StyleButton() AutoButton:SetClampedToScreen(true) AutoButton:SetAttribute("type", "item") AutoButton:SetAlpha(0) AutoButton:EnableMouse(false) AutoButton:RegisterForClicks('AnyUp') -- Texture for our button AutoButton.t = AutoButton:CreateTexture(nil, "OVERLAY", nil) AutoButton.t:Point("TOPLEFT", AutoButton, "TOPLEFT", 2, -2) AutoButton.t:Point("BOTTOMRIGHT", AutoButton, "BOTTOMRIGHT", -2, 2) AutoButton.t:SetTexCoord(0.1, 0.9, 0.1, 0.9) -- Count text for our button AutoButton.c = AutoButton:CreateFontString(nil, "OVERLAY") AutoButton.c:FontTemplate(nil, E.db.WindTools["Interface"]["Auto Buttons"].countFontSize, 'OUTLINE') AutoButton.c:SetTextColor(1, 1, 1, 1) AutoButton.c:Point("BOTTOMRIGHT", AutoButton, "BOTTOMRIGHT", 0.5, 0) AutoButton.c:SetJustifyH("CENTER") -- Binding text for our button AutoButton.k = AutoButton:CreateFontString(nil, "OVERLAY") AutoButton.k:FontTemplate(nil, E.db.WindTools["Interface"]["Auto Buttons"].bindFontSize, 'OUTLINE') AutoButton.k:SetTextColor(0.6, 0.6, 0.6) AutoButton.k:Point("TOPRIGHT", AutoButton, "TOPRIGHT", 1, -3) AutoButton.k:SetJustifyH("RIGHT") -- Cooldown AutoButton.Cooldown = CreateFrame("Cooldown", nil, AutoButton, "CooldownFrameTemplate") AutoButton.Cooldown:Point("TOPLEFT", AutoButton, "TOPLEFT", 2, -2) AutoButton.Cooldown:Point("BOTTOMRIGHT", AutoButton, "BOTTOMRIGHT", -2, 2) AutoButton.Cooldown:SetSwipeColor(0, 0, 0, 0) AutoButton.Cooldown:SetDrawBling(false) E:RegisterCooldown(AutoButton.Cooldown) E.FrameLocks[name] = true; return AutoButton end function AB:ScanItem(event) local db = E.db.WindTools["Interface"]["Auto Buttons"] HideAllButton(event) GetWorldQuestItemList('init'); -- Scan bags for Item matchs local questItemIDList = {} local minimapZoneText = GetMinimapZoneText() if minimapZoneText == L["Alliance Mine"] or minimapZoneText == L["Horde Mine"] then for i = 1, #garrisonsmv do local count = GetItemCount(garrisonsmv[i]) if count and (count > 0) and (not db.blankList[garrisonsmv[i]]) then tinsert(questItemIDList, garrisonsmv[i]) end end elseif minimapZoneText == L["Salvage Yard"] then for i = 1, #garrisonsc do local count = GetItemCount(garrisonsc[i]) if count and (count > 0) and (not db.blankList[garrisonsc[i]]) then tinsert(questItemIDList, garrisonsc[i]) end end else for k, v in pairs(QuestItemList) do if (not QuestItemList[k].isComplete) or (QuestItemList[k].isComplete and QuestItemList[k].showItemWhenComplete) then if not db.blankList[k] then tinsert(questItemIDList, k) end end end for k, v in pairs(E.db.WindTools["Interface"]["Auto Buttons"].whiteList) do local count = GetItemCount(k) if count and (count > 0) and v and (not db.blankList[k]) then tinsert(questItemIDList, k) end end if GetItemCount(123866) and (GetItemCount(123866) >= 5) and (not db.blankList[123866]) and (GetCurrentMapAreaID("player") == 945) then tinsert(questItemIDList, 123866) end end sort(questItemIDList, function(v1, v2) local itemType1 = select(7, GetItemInfo(v1)) local itemType2 = select(7, GetItemInfo(v2)) if itemType1 and itemType2 then return itemType1 > itemType2 else return v1 > v2 end end) if db.questNum > 0 then local ApItemNum = 0 if db.AptifactItem and (event == "BAG_UPDATE_DELAYED") then local itemLink, itemID = GetAptifactItem() if itemLink then ApItemNum = 1 local AutoButton = _G["AutoQuestButton1"] local itemName = GetItemInfo(itemID) local itemIcon = GetItemIcon(itemID) AutoButton.t:SetTexture(itemIcon) AutoButton.itemName = itemName AutoButton.itemID = itemID AutoButton.ap = true AutoButton.questLogIndex = -1 AutoButton.spellName = IsUsableItem(itemID) AutoButton:SetBackdropBorderColor(1.0, 0.3, 0.3) AutoButton.c:SetText("") AutoButtonShow(AutoButton) else _G["AutoQuestButton1"].ap = false end end if _G["AutoQuestButton1"].ap then ApItemNum = 1 end if not db.AptifactItem then _G["AutoQuestButton1"].ap = false ApItemNum = 0 end for i = 1, #questItemIDList do local itemID = questItemIDList[i] local itemName = GetItemInfo(itemID) if i > db.questNum then break; end local AutoButton = _G["AutoQuestButton"..(i+ApItemNum)] local count = GetItemCount(itemID, nil, 1) local itemIcon = GetItemIcon(itemID) if not AutoButton then break end -- Set our texture to the item found in bags AutoButton.t:SetTexture(itemIcon) AutoButton.itemName = itemName AutoButton.itemID = itemID AutoButton.ap = false AutoButton.questLogIndex = QuestItemList[itemID] and QuestItemList[itemID].questLogIndex or -1 AutoButton.spellName = IsUsableItem(itemID) AutoButton:SetBackdropBorderColor(1.0, 0.3, 0.3) -- Get the count if there is one if count and count > 1 then AutoButton.c:SetText(count) else AutoButton.c:SetText("") end AutoButton:SetScript("OnUpdate", function(self, elapsed) local start, duration, enable if self.questLogIndex > 0 then start, duration, enable = GetQuestLogSpecialItemCooldown(self.questLogIndex) else start, duration, enable = GetItemCooldown(self.itemID) end CooldownFrame_SetTimer(self.Cooldown, start, duration, enable) if ( duration and duration > 0 and enable and enable == 0 ) then self.t:SetVertexColor(0.4, 0.4, 0.4); elseif IsItemInRange(itemID, 'target') == 0 then self.t:SetVertexColor(1, 0, 0) else self.t:SetVertexColor(1, 1, 1) end end) AutoButtonShow(AutoButton) end end -- Scan inventory for Equipment matches local num = 0 if db.slotNum > 0 then for w = 1, 18 do local slotID = GetInventoryItemID("player", w) if slotID and IsSlotItem(slotID) and not db.blankList[slotID] then local iSpell = GetItemSpell(slotID) local itemName, _, rarity = GetItemInfo(slotID) local itemIcon = GetInventoryItemTexture("player", w) num = num + 1 if num > db.slotNum then break; end local AutoButton = _G["AutoSlotButton".. num] if not AutoButton then break; end if rarity and rarity > 1 then local r, g, b = GetItemQualityColor(rarity); AutoButton:SetBackdropBorderColor(r, g, b); end -- Set our texture to the item found in bags AutoButton.t:SetTexture(itemIcon) AutoButton.c:SetText("") -- AutoButton.itemName = itemName AutoButton.slotID = w AutoButton.itemID = slotID -- AutoButton.itemLink = GetInventoryItemLink('player', w) AutoButton.spellName = IsUsableItem(slotID) AutoButton:SetScript("OnUpdate", function(self, elapsed) local cd_start, cd_finish, cd_enable = GetInventoryItemCooldown("player", self.slotID) CooldownFrame_SetTimer(AutoButton.Cooldown, cd_start, cd_finish, cd_enable) end) AutoButtonShow(AutoButton) end end end end local lastUpdate = 0 function AB:ScanItemCount(elapsed) lastUpdate = lastUpdate + elapsed if lastUpdate < 0.5 then return end lastUpdate = 0 for i = 1, E.db.WindTools["Interface"]["Auto Buttons"].questNum do local f = _G["AutoQuestButton"..i] if f and f.itemName then local count = GetItemCount(f.itemID, nil, 1) if count and count > 1 then f.c:SetText(count) else f.c:SetText("") end end end end function AB:UpdateBind() local db = E.db.WindTools["Interface"]["Auto Buttons"] if not db then return; end for i = 1, db.questNum do local bindButton = 'CLICK AutoQuestButton'..i..':LeftButton' local button = _G['AutoQuestButton'..i] local bindText = GetBindingKey(bindButton) if not bindText then bindText = '' else bindText = gsub(bindText, 'SHIFT--', 'S') bindText = gsub(bindText, 'CTRL--', 'C') bindText = gsub(bindText, 'ALT--', 'A') end if button then button.k:SetText(bindText) end end for i = 1, db.slotNum do local bindButton = 'CLICK AutoSlotButton'..i..':LeftButton' local button = _G['AutoSlotButton'..i] local bindText = GetBindingKey(bindButton) if not bindText then bindText = '' else bindText = gsub(bindText, 'SHIFT--', 'S') bindText = gsub(bindText, 'CTRL--', 'C') bindText = gsub(bindText, 'ALT--', 'A') end if button then button.k:SetText(bindText) end end end function AB:ToggleAutoButton() if E.db.WindTools["Interface"]["Auto Buttons"].enabled then self:RegisterEvent("BAG_UPDATE_DELAYED", "ScanItem") self:RegisterEvent("UNIT_INVENTORY_CHANGED", "ScanItem") self:RegisterEvent("ZONE_CHANGED", "ScanItem") self:RegisterEvent("ZONE_CHANGED_NEW_AREA", "ScanItem") self:RegisterEvent("UPDATE_BINDINGS", "UpdateBind") self:RegisterEvent("QUEST_WATCH_LIST_CHANGED", GetQuestItemList); self:RegisterEvent("QUEST_LOG_UPDATE", GetQuestItemList); self:RegisterEvent("QUEST_ACCEPTED", GetWorldQuestItemList); self:RegisterEvent("QUEST_TURNED_IN", GetWorldQuestItemList); -- self:RegisterEvent("BAG_UPDATE_DELAYED", "ScanItem") if not AB.Update then AB.Update = CreateFrame("Frame") end; self.Update:SetScript("OnUpdate", AB.ScanItemCount) self:ScanItem('FIRST'); self:UpdateBind(); else HideAllButton() self:UnregisterEvent("BAG_UPDATE_DELAYED") self:UnregisterEvent("UNIT_INVENTORY_CHANGED") self:UnregisterEvent("ZONE_CHANGED") self:UnregisterEvent("ZONE_CHANGED_NEW_AREA") self:UnregisterEvent("UPDATE_BINDINGS") self:UnregisterEvent("QUEST_WATCH_LIST_CHANGED") self:UnregisterEvent("QUEST_LOG_UPDATE") -- self:UnregisterEvent("BAG_UPDATE_DELAYED") if self.Update then self.Update:SetScript("OnUpdate", nil) end end end function AB:UpdateAutoButton() local db = E.db.WindTools["Interface"]["Auto Buttons"] local i = 0 local lastButton, lastColumnButton, buttonsPerRow; for i = 1, db.questNum do local f = CreateButton("AutoQuestButton"..i, db.questSize) buttonsPerRow = db.questPerRow lastButton = _G["AutoQuestButton"..i-1]; lastColumnButton = _G["AutoQuestButton"..i-buttonsPerRow]; if db.questNum < db.questPerRow then buttonsPerRow = db.questNum; end f:ClearAllPoints() if i == 1 then f:Point("LEFT", AutoButtonAnchor, "LEFT", 0, 0) elseif (i-1) % buttonsPerRow == 0 then f:Point("TOP", lastColumnButton, "BOTTOM", 0, -3) else f:Point("LEFT", lastButton, "RIGHT", 3, 0) end end for i = 1, db.slotNum do local f = CreateButton("AutoSlotButton"..i, db.slotSize) buttonsPerRow = db.slotPerRow lastButton = _G["AutoSlotButton"..i-1]; lastColumnButton = _G["AutoSlotButton"..i-buttonsPerRow]; if db.slotNum < db.slotPerRow then buttonsPerRow = db.questNum; end f:ClearAllPoints() if i == 1 then f:Point("LEFT", AutoButtonAnchor2, "LEFT", 0, 0) elseif (i-1) % buttonsPerRow == 0 then f:Point("TOP", lastColumnButton, "BOTTOM", 0, -3) else f:Point("LEFT", lastButton, "RIGHT", 3, 0) end end self:ToggleAutoButton() end function AB:Initialize() if not E.db.WindTools["Interface"]["Auto Buttons"].enabled then return end local db = E.db.WindTools["Interface"]["Auto Buttons"] -- Create anchor local AutoButtonAnchor = CreateFrame("Frame", "AutoButtonAnchor", UIParent) AutoButtonAnchor:SetClampedToScreen(true) AutoButtonAnchor:Point("BOTTOMLEFT", RightChatPanel or LeftChatPanel, "TOPLEFT", 0, 4) AutoButtonAnchor:Size(db.questNum > 0 and db.questSize * db.questNum or 260, db.questNum > 0 and db.questSize or 40) E:CreateMover(AutoButtonAnchor, "AutoButtonAnchorMover", L["Auto QuestItem Button"], nil, nil, nil, "ALL,EUI", function() return E.db.WindTools["Interface"]["Auto Buttons"].enabled; end) -- Create anchor2 local AutoButtonAnchor2 = CreateFrame("Frame", "AutoButtonAnchor2", UIParent) AutoButtonAnchor2:SetClampedToScreen(true) AutoButtonAnchor2:Point("BOTTOMLEFT", RightChatPanel or LeftChatPanel, "TOPLEFT", 0, 48) AutoButtonAnchor2:Size(db.slotNum > 0 and db.slotSize * db.slotNum or 260, db.slotNum > 0 and db.slotSize or 40) E:CreateMover(AutoButtonAnchor2, "AutoButtonAnchor2Mover", L["Auto InventoryItem Button"], nil, nil, nil, "ALL,EUI", function() return E.db.WindTools["Interface"]["Auto Buttons"].enabled; end) self:UpdateAutoButton() end local function InitializeCallback() AB:Initialize() end E:RegisterModule(AB:GetName(), InitializeCallback)
local CorePackages = game:GetService("CorePackages") local Action = require(CorePackages.AppTempCommon.Common.Action) return Action("SET_VIDEO_RECORDING", function (recording) return { recording = recording, } end)
-- base da quantidade de materiais cobblestone = 80 stick = 25 tnt = 12 enderpearls = 10 function packConvert(x) -- Conversor da quantindade de itens, em packs local packs = math.floor(x / 64) local itens = x % 64 local msg = packs .. " packs + " .. itens return msg end function quantItens(quant) -- Calcula a quantidade de itens local quantCobblestone = cobblestone * quant local quantStick = stick * quant local quantTnt = tnt * quant local quantEnder = enderpearls * quant local x = packConvert(quantCobblestone) .. " de Cobblestone.\n" local y = packConvert(quantStick) .. " de Stick.\n" local z = packConvert(quantTnt) .. " de TNT.\n" local w = packConvert(quantEnder) .. " de Ender Pearls.\n" return print("\nLista de materiais:\n",x, y, z, w) end -- Programa shell.run("clear") -- limpa o terminal print("CALCULADORA PARA FABRICAÇÃO DE INDUCTIVE MECHANISM\n") print("Digite a quantidade de Inductive Mechanism:") inputTerm = read() -- da entrada na quantidade de itens if (inputTerm == "s") then --Finaliza o programa para manutenção a = inputTerm return end quant = tonumber(inputTerm) quantItens(quant) print("Pressione qualquer tecla para realizar um novo calculo.") key = read() if (key ~= nil) then shell.run("startup") end
-- Texture utilities package.path = package.path..";../?.lua" local gl = require("moongl") local glmath = require("moonglmath") local mi = require("moonimage") local random = require("common.random") ------------------------------------------------------------------------------- local function load_texture(filename) mi.flip_vertically_on_load(true) local data, width, height = mi.load(filename, 'rgba') --print(#data, width, height, width*height*4, filename) local texid = gl.new_texture('2d') gl.texture_storage('2d', 1, 'rgba8', width, height) gl.texture_sub_image('2d', 0, 'rgba', 'ubyte', data, 0, 0, width, height) gl.texture_parameter('2d', 'mag filter', 'linear') gl.texture_parameter('2d', 'min filter', 'nearest') gl.unbind_texture('2d') return texid, width, height end local SUFFIX = { "posx", "negx", "posy", "negy", "posz", "negz" } local TARGET = { 'cube map positive x', 'cube map negative x', 'cube map positive y', 'cube map negative y', 'cube map positive z', 'cube map negative z' } ------------------------------------------------------------------------------- local function load_cube_map(basename, extension) local extension = estension or "png" local texid = gl.new_texture('cube map') mi.flip_vertically_on_load(false) local data, width, height for i=1,6 do local filename = basename .."_"..SUFFIX[i].."."..extension data, width, height = mi.load(filename, 'rgba') if i == 1 then -- Allocate immutable storage for the whole cube map texture gl.texture_storage('cube map', 1, 'rgba8', width, height) end gl.texture_sub_image(TARGET[i], 0, 'rgba', 'ubyte', data, 0, 0, width, height) end gl.texture_parameter('cube map', 'mag filter', 'linear') gl.texture_parameter('cube map', 'min filter', 'nearest') gl.texture_parameter('cube map', 'wrap s', 'clamp to edge') gl.texture_parameter('cube map', 'wrap t', 'clamp to edge') gl.texture_parameter('cube map', 'wrap r', 'clamp to edge') gl.unbind_texture('cube map') return texid, width, height end ------------------------------------------------------------------------------- local function load_hdr_cube_map(basename) local texid = gl.new_texture('cube map') -- mi.flip_vertically_on_load(true) local data, width, height for i=1,6 do local filename = basename .."_"..SUFFIX[i]..".hdr" data, width, height = mi.load(filename, 'rgb', 'f') if i == 1 then -- Allocate immutable storage for the whole cube map texture gl.texture_storage('cube map', 1, 'rgb32f', width, height) end gl.texture_sub_image(TARGET[i], 0, 'rgb', 'float', data, 0, 0, width, height) end gl.texture_parameter('cube map', 'mag filter', 'linear') gl.texture_parameter('cube map', 'min filter', 'nearest') gl.texture_parameter('cube map', 'wrap s', 'clamp to edge') gl.texture_parameter('cube map', 'wrap t', 'clamp to edge') gl.texture_parameter('cube map', 'wrap r', 'clamp to edge') gl.unbind_texture('cube map') return texid, width, height end ------------------------------------------------------------------------------- local perlin = mi.perlin local clamp = glmath.clamp local floor = math.floor local function noise_2d(base_freq, persistence, width, height, periodic) local base_freq = base_freq or 4 local persistence = persistence or 0.5 local w = width or 128 local h = height or 128 local data = {} -- size = w*h*4 for row = 0, h-1 do for col = 0, w-1 do local x = col/(w-1) local y = row/(h-1) local sum = 0.0 local freq = base_freq local persist = persistence local wrap = periodic and freq or nil for oct = 0, 3 do sum = sum + perlin(x*freq, y*freq, 0, wrap, wrap) -- Move to the range [0, 1] and convert to a 0-255 color component local val = floor(clamp((sum + 1)/2, 0.0, 1.0) * 255) -- Store in texture data data[(row*w + col)*4 + 1 + oct] = val freq = freq * 2 persist = persist * persistence end end end -- assert(#data, w*h*4) -- Store in a texture local texid = gl.new_texture('2d') gl.texture_storage('2d', 1, 'rgba8', w, h) gl.texture_sub_image('2d', 0, 'rgba', 'ubyte', gl.pack('ubyte', data), 0, 0, w, h) gl.texture_parameter('2d', 'mag filter', 'linear') gl.texture_parameter('2d', 'min filter', 'linear') gl.texture_parameter('2d', 'wrap s', 'repeat') gl.texture_parameter('2d', 'wrap t', 'repeat') return texid end local function noise_2d_periodic(base_freq, persistence, width, height) return noise_2d(base_freq, persistence, width, height, true) end ------------------------------------------------------------------------------- local function random_1d(size) -- Creates a 1D texture of random floating point values in the range [0, 1) local data = {} for i=0, size do data[i] = random.uniform() end data = gl.packf(data) local texid = gl.new_texture('1d') gl.texture_storage('1d', 1, 'r32f', size) gl.texture_sub_image('1d', 0, 'red', 'float', data, 0, size) gl.texture_parameter('1d', 'mag filter', 'nearest') gl.texture_parameter('1d', 'min filter', 'nearest') return texid end return { load_texture = load_texture, load_hdr_cube_map = load_hdr_cube_map, load_cube_map = load_cube_map, noise_2d = noise_2d, noise_2d_periodic = noise_2d_periodic, random_1d = random_1d, }
local ok, cmp = pcall(require, "cmp") if not ok then vim.notify "Could not load cmp" return end local ok, luasnip = pcall(require, "luasnip") if not ok then vim.notify "Could not load luasnip" return end local ok, lspkind = pcall(require, "lspkind") if not ok then vim.notify "Could not load lspkind" return end local has_words_before = function() local line, col = unpack(vim.api.nvim_win_get_cursor(0)) return col ~= 0 and vim.api.nvim_buf_get_lines(0, line - 1, line, true)[1]:sub(col, col):match "%s" == nil end cmp.setup { window = { completion = { border = "rounded", }, documentation = { border = "rounded", }, }, snippet = { expand = function(args) luasnip.lsp_expand(args.body) end, }, mapping = { ["<C-p>"] = cmp.mapping(cmp.mapping.select_prev_item(), { "i", "c" }), ["<C-n>"] = cmp.mapping(cmp.mapping.select_next_item(), { "i", "c" }), ["<C-d>"] = cmp.mapping(cmp.mapping.scroll_docs(-4), { "i", "c" }), ["<C-f>"] = cmp.mapping(cmp.mapping.scroll_docs(4), { "i", "c" }), ["<C-Space>"] = cmp.mapping(cmp.mapping.complete(), { "i", "c" }), ["<C-e>"] = cmp.mapping { i = cmp.mapping.close(), c = cmp.mapping.close(), }, ["<CR>"] = cmp.mapping.confirm { select = true }, ["<Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_next_item() elseif luasnip.expand_or_jumpable() then luasnip.expand_or_jump() elseif has_words_before() then cmp.complete() else fallback() end end, { "i", "c", }), ["<S-Tab>"] = cmp.mapping(function(fallback) if cmp.visible() then cmp.select_prev_item() elseif luasnip.jumpable(-1) then luasnip.jump(-1) else fallback() end end, { "i", "c", }), }, sources = { { name = "luasnip" }, { name = "nvim_lsp" }, { name = "nvim_lua" }, { name = "buffer", option = { get_bufnrs = function() local bufs = {} for _, win in ipairs(vim.api.nvim_list_wins()) do bufs[vim.api.nvim_win_get_buf(win)] = true end return vim.tbl_keys(bufs) end, }, }, { name = "path" }, { name = "calc" }, { name = "latex_symbols" }, { name = "orgmode" }, }, formatting = { format = lspkind.cmp_format { mode = "symbol", maxwidth = 50, menu = { luasnip = "[SNP]", nvim_lsp = "[LSP]", nvim_lua = "[VIM]", buffer = "[BUF]", path = "[PTH]", calc = "[CLC]", latex_symbols = "[TEX]", orgmode = "[ORG]", }, }, fields = { "kind", "abbr", "menu", }, }, sorting = { comparators = { cmp.config.compare.offset, cmp.config.compare.exact, cmp.config.compare.score, require("cmp-under-comparator").under, cmp.config.compare.kind, cmp.config.compare.sort_text, cmp.config.compare.length, cmp.config.compare.order, }, }, } cmp.setup.cmdline(":", { sources = cmp.config.sources({ { name = "path" }, }, { { name = "cmdline" }, }), }) cmp.setup.cmdline("/", { sources = { { name = "buffer" }, }, }) vim.cmd [[ autocmd FileType toml lua require("cmp").setup.buffer { sources = { { name = "crates" } } } autocmd FileType sql,mysql,plsql lua require("cmp").setup.buffer { sources = { { name = "vim-dadbod-completion" } } } ]]
function lang_switch_keys(lang) local in_lang = {} local langs = { [1] = {lang_key = "tr", lang_name = "Türkçe", script_name = "Satır Çoğalt", sub_menu = "Satır/Çoğalt"}, [2] = {lang_key = "en", lang_name = "English", script_name = "Duplicate Lines", sub_menu = "Lines/Duplicate"} } local lang_list = {} local script_name_list = {} local sub_menu_list = {} for i = 1, #langs do lang_list[langs[i].lang_key] = langs[i].lang_name script_name_list[langs[i].lang_key] = langs[i].script_name sub_menu_list[langs[i].lang_key] = langs[i].sub_menu end if lang == langs[1].lang_key then in_lang["module_incompatible"] = "Mag modülünün kurulu sürümü bu lua dosyası ile uyumsuz!\n\nModül dosyasının en az \"%s\" sürümü veya daha üstü gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_not_found"] = "Mag modülü bulunamadı!\n\nBu lua dosyasını kullanmak için Mag modülünü indirip Aegisub programı kapalıyken\n\"Aegisub/automation/include/\" dizinine taşımanız gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_yes"] = "Git" in_lang["module_no"] = "Daha Sonra" in_lang["sub_menu"] = langs[1].sub_menu in_lang["s_name"] = langs[1].script_name in_lang["s_desc"] = "Satırları çoğaltarak çeviri kipi imkanı sunar." in_lang["tabKey1"] = "Çoğalt" in_lang["tabKey2"] = "Kaldır" in_lang["dModeListKey1"] = "Açıklama Parantezleri > Satır Sonu" in_lang["dModeListKey2"] = "Açıklama Parantezleri > Satır İçeriği Yerine" in_lang["dModeListKey3"] = "Yeni Satır > Sonraki Satır" in_lang["dModeListKey4"] = "Yeni Satır > Son Satırdan Sonra" in_lang["buttonKey1"] = "Çoğalt" in_lang["buttonKey2"] = "Kapat" in_lang["buttonKey3"] = "Kaldır" in_lang["guiLabelKey1"] = "Çoğaltma kipi:" in_lang["outKey1"] = "[SÇ] Değiştirildi" in_lang["outKey2"] = "[SÇ] Hedef" in_lang["outKey3"] = "[SÇ] Kaynak" elseif lang == langs[2].lang_key then in_lang["module_incompatible"] = "The installed version of the Mag module is incompatible with this lua file!\n\nAt least \"%s\" version or higher of the module file is required.\n\n\nWould you like to go to the download page now?" in_lang["module_not_found"] = "The module named Mag could not be found!\n\nTo use this file, you need to download the module named mag\nand move it to \"Aegisub/automation/include/\" directory when Aegisub is off.\n\n\nDo you want to go to download page now?" in_lang["module_yes"] = "Go" in_lang["module_no"] = "Later" in_lang["sub_menu"] = langs[2].sub_menu in_lang["s_name"] = langs[2].script_name in_lang["s_desc"] = "Provides translation mode by duplicating lines." in_lang["tabKey1"] = "Duplicate" in_lang["tabKey2"] = "Remove" in_lang["dModeListKey1"] = "Comment Brackets > End of Line" in_lang["dModeListKey2"] = "Comment Brackets > Instead of Line Content" in_lang["dModeListKey3"] = "New Line > Next Line" in_lang["dModeListKey4"] = "New Line > After Last Line" in_lang["buttonKey1"] = "Duplicate" in_lang["buttonKey2"] = "Close" in_lang["buttonKey3"] = "Remove" in_lang["guiLabelKey1"] = "Duplicate mode:" in_lang["guiLabelKey2"] = "Sort lines by start time" in_lang["outKey1"] = "[DL] Changed" in_lang["outKey2"] = "[DL] Target" in_lang["outKey3"] = "[DL] Source" end return in_lang, lang_list, script_name_list, sub_menu_list end c_lang_switch = "en" c_lang, c_lang_list, c_script_name_list, c_sub_name_list = lang_switch_keys(c_lang_switch) script_name = c_lang.s_name script_description = c_lang.s_desc script_author = "Magnum357" script_version = "3.2.0" script_mag_version = "1.1.4.7" script_file_name = "mag.duplicate_lines" script_file_ext = ".lua" include_unicode = true include_karaskel = true mag_import, mag = pcall(require, "mag") if mag_import then mag.lang = c_lang_switch c_lock_gui = false c_dmode_list = {mag.window.lang.message("select"), c_lang.dModeListKey1, c_lang.dModeListKey2, c_lang.dModeListKey3, c_lang.dModeListKey4} c_buttons1 = {c_lang.buttonKey1, c_lang.buttonKey2} c_buttons2 = {c_lang.buttonKey3, c_lang.buttonKey2} c = {} c.dmode_select = mag.window.lang.message("select") c.apply1 = mag.window.lang.message("select") c.apply2 = mag.window.lang.message("select") c.comment_mode = false c.empty_mode = false c.sort_lines = false gui = { main1 = { {class = "label", x = 0, y = 0, width = 1, height = 1, label = c_lang.guiLabelKey1}, dmode_select = {class = "dropdown", name = "dmode_select", x = 1, y = 0, width = 1, height = 1}, {class = "label", x = 0, y = 1, width = 1, height = 1, label = mag.window.lang.message("apply")}, apply1 = {class = "dropdown", name = "apply1", x = 1, y = 1, width = 1, height = 1, hint = mag.window.lang.message("style_hint1")}, comment_mode = {class = "checkbox", name = "comment_mode", x = 1, y = 2, width = 1, height = 1, label = mag.window.lang.message("comment_mode")}, empty_mode = {class = "checkbox", name = "empty_mode", x = 1, y = 3, width = 1, height = 1, label = mag.window.lang.message("empty_mode")}, sort_lines = {class = "checkbox", name = "sort_lines", x = 1, y = 4, width = 1, height = 1, label = c_lang.guiLabelKey2}, }, main2 = { {class = "label", x = 0, y = 0, width = 1, height = 1, label = mag.window.lang.message("apply")}, apply2 = {class = "dropdown", name = "apply2", x = 1, y = 0, width = 1, height = 1, hint = mag.window.lang.message("style_hint1")}, } } end function duplicate_lines(subs,sel) local line, index local jlines = {} local pcs = false local lines_index = mag.line.index(subs, sel, c.apply1, c.comment_mode, c.empty_mode) if c.sort_lines then mag.line.sort(subs, lines_index) end if c.dmode_select == c_dmode_list[2] then for i = 1, #lines_index do mag.window.progress(i, #lines_index) if not pcs then pcs = true end index = lines_index[i] line = subs[index] line.text = mag.format("%s{%s}", line.text, strip(line.text)) line.effect = c_lang.outKey1 subs[index] = line end if pcs then jlines = lines_index end end if c.dmode_select == c_dmode_list[3] then for i = 1, #lines_index do mag.window.progress(i, #lines_index) if not pcs then pcs = true end index = lines_index[i] line = subs[index] line.text = mag.format("{%s}", strip(line.text)) line.effect = c_lang.outKey1 subs[index] = line end if pcs then jlines = lines_index end end if c.dmode_select == c_dmode_list[4] then local j = 0 local dlines = {} for i = 1, #lines_index do mag.window.progress(i, #lines_index) index = lines_index[i] line = subs[index] line.effect = c_lang.outKey3 subs[index] = line mag.array.insert(dlines, line) end for i = 1, #lines_index do mag.window.progress(i, #lines_index) if not pcs then pcs = true end index = lines_index[i] line = dlines[i] l = table.copy(line) l.comment = true l.effect = c_lang.outKey2 l.text = strip(l.text) j = j + 1 subs.insert(index + j, l) mag.array.insert(jlines, index + j) end end if c.dmode_select == c_dmode_list[5] then local j = 0 local dlines = {} for i = 1, #lines_index do mag.window.progress(i, #lines_index) index = lines_index[i] line = subs[index] line.effect = c_lang.outKey3 subs[index] = line mag.array.insert(dlines, line) end local last_index = lines_index[#lines_index] for i = 1, #lines_index do mag.window.progress(i, #lines_index) if not pcs then pcs = true end line = dlines[i] l = table.copy(line) l.comment = true l.effect = c_lang.outKey2 l.text = strip(l.text) j = j + 1 subs.insert(last_index + j, l) mag.array.insert(jlines, last_index + j) end end mag.show.no_op(pcs) if jlines[1] ~= nil then return jlines end end function remove_duplicate_lines(subs,sel) local line, index local pcs = false local delete_index = {} local lines_index = mag.line.index(subs, sel, c.apply2, false, false) lines_index = mag.sort.reverse(lines_index) for i = 1, #lines_index do mag.window.progress(i, #lines_index) index = lines_index[i] line = subs[index] if line.effect == c_lang.outKey1 then local trim1, trim2 = mag.string.last_find(line.text, "{"), mag.string.last_find(line.text, "}") if trim1 and trim2 then if trim2 > trim1 then if not pcs then pcs = true end local s = "" s = s..mag.sub(line.text, 0, trim1 - 1) s = s..mag.sub(line.text, trim2 + 1, mag.convert.len(line.text)) line.text = s line.effect = "" subs[index] = line end end elseif line.effect == c_lang.outKey2 then if not pcs then pcs = true end subs.delete(index) elseif line.effect == c_lang.outKey3 then if not pcs then pcs = true end line.effect = "" subs[index] = line end end mag.show.no_op(pcs, "effect", mag.string.format("{%s}, {%s}", c_lang.outKey1, c_lang.outKey2)) end function strip(t) t = mag.strip.all(t) t = mag.trim.all(t) return t end function add_macro1(subs,sel) local apply_items = mag.list.full_apply(subs, sel, "comment") c.apply1 = mag.array.search_apply(apply_items, c.apply1) gui.main1.apply1.items = apply_items gui.main1.dmode_select.items = c_dmode_list local ok, config repeat mag.config.put(gui.main1) ok, config = mag.window.dialog(gui.main1, c_buttons1) mag.config.take(config) until ok == mag.convert.ascii(c_buttons1[1]) and c.dmode_select ~= mag.window.lang.message("select") and c.apply1 ~= mag.window.lang.message("select") or ok == mag.convert.ascii(c_buttons1[2]) if ok == mag.convert.ascii(c_buttons1[1]) then return duplicate_lines(subs, sel) end end function add_macro2(subs,sel) local apply_items = mag.list.full_apply(subs, sel, "comment") c.apply2 = mag.array.search_apply(apply_items, c.apply2) gui.main2.apply2.items = apply_items local ok, config repeat mag.config.put(gui.main2) ok, config = mag.window.dialog(gui.main2, c_buttons2) mag.config.take(config) until ok == mag.convert.ascii(c_buttons2[1]) and c.apply2 ~= mag.window.lang.message("select") or ok == mag.convert.ascii(c_buttons2[2]) if ok == mag.convert.ascii(c_buttons2[1]) then remove_duplicate_lines(subs, sel) end end function check_macro1(subs,sel) if c_lock_gui then mag.show.log(1, mag.window.lang.message("restart_aegisub")) else mag.config.get(c) local fe, fee = pcall(add_macro1, subs, sel) mag.window.funce(fe, fee) mag.window.undo_point() mag.config.set(c) return fee end end function check_macro2(subs,sel) if c_lock_gui then mag.show.log(1, mag.window.lang.message("restart_aegisub")) else mag.config.get(c) local fe, fee = pcall(add_macro2, subs, sel) mag.window.funce(fe, fee) mag.window.undo_point() mag.config.set(c) end end function mag_redirect_gui() local mag_module_link = "https://github.com/magnum357i/Magnum-s-Aegisub-Scripts" local k = aegisub.dialog.display({{class = "label", label = mag_gui_message}}, {c_lang.module_yes, c_lang.module_no}) if k == c_lang.module_yes then os.execute("start "..mag_module_link) end end if mag_import then if mag_module_version:gsub("%.", "") < script_mag_version:gsub("%.", "") then mag_gui_message = string.format(c_lang.module_incompatible, script_mag_version) aegisub.register_macro(script_name, script_desription, mag_redirect_gui) else mag.window.register(c_sub_name_list[c_lang_switch].."/"..c_lang.tabKey1, check_macro1) mag.window.register(c_sub_name_list[c_lang_switch].."/"..c_lang.tabKey2, check_macro2) mag.window.lang.register(c_sub_name_list[c_lang_switch]) end else mag_gui_message = c_lang.module_not_found aegisub.register_macro(script_name, script_desription, mag_redirect_gui) end
local Parallel, parent = torch.class('nn.Parallel', 'nn.Module') function Parallel:__init(inputDimension,outputDimension) parent.__init(self) self.modules = {} self.size = torch.LongStorage() self.inputDimension = inputDimension self.outputDimension = outputDimension end function Parallel:add(module) table.insert(self.modules, module) end function Parallel:get(index) return self.modules[index] end function Parallel:forward(input) local modules=input:size(self.inputDimension) for i=1,modules do local currentOutput = self.modules[i]:forward(input:select(self.inputDimension,i)) if i == 1 then self.size:resize(currentOutput:dim()):copy(currentOutput:size()) else self.size[self.outputDimension] = self.size[self.outputDimension] + currentOutput:size(self.outputDimension) end end self.output:resize(self.size) local offset = 1 for i=1,modules do local currentOutput = self.modules[i]:forward(input:select(self.inputDimension,i)) self.output:narrow(self.outputDimension, offset, currentOutput:size(self.outputDimension)):copy(currentOutput) offset = offset + currentOutput:size(self.outputDimension) end return self.output end function Parallel:backward(input, gradOutput) local modules=input:size(self.inputDimension) self.gradInput:resizeAs(input) local offset = 1 for i=1,modules do local module=self.modules[i]; local currentOutput = module.output local currentGradInput = module:backward(input:select(self.inputDimension,i), gradOutput:narrow(self.outputDimension, offset, currentOutput:size(self.outputDimension))) self.gradInput:select(self.inputDimension,i):copy(currentGradInput) offset = offset + currentOutput:size(self.outputDimension) end return self.gradInput end function Parallel:zeroGradParameters() for _,module in ipairs(self.modules) do module:zeroGradParameters() end end function Parallel:updateParameters(learningRate) for _,module in ipairs(self.modules) do module:updateParameters(learningRate) end end function Parallel:write(file) parent.write(self, file) file:writeObject(self.modules) file:writeObject(self.size) file:writeInt(self.inputDimension) file:writeInt(self.outputDimension) end function Parallel:read(file, version) parent.read(self, file) self.modules = file:readObject() if version > 0 then self.size = file:readObject() else local size = file:readObject() self.size = torch.LongStorage(size:size()) self.size:copy(size) end self.inputDimension = file:readInt() self.outputDimension = file:readInt() end function Parallel:share(mlp,...) for i=1,#self.modules do self.modules[i]:share(mlp.modules[i],...); end end
---@class CS.FairyEditor.ProcessUtil ---@type CS.FairyEditor.ProcessUtil CS.FairyEditor.ProcessUtil = { } function CS.FairyEditor.ProcessUtil.LaunchApp() end ---@return string ---@param path string ---@param args String[] ---@param dir string ---@param waitUntilExit boolean function CS.FairyEditor.ProcessUtil.Start(path, args, dir, waitUntilExit) end ---@return string function CS.FairyEditor.ProcessUtil.GetOpenFilename() end ---@return string function CS.FairyEditor.ProcessUtil.GetUUID() end ---@return string function CS.FairyEditor.ProcessUtil.GetAppVersion() end return CS.FairyEditor.ProcessUtil
return { { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 6 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 7 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 8 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 9 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 10 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 11 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 12 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 13 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 14 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, { effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 15 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }, init_effect = "", name = "怒旋·大吉岭", time = 15, picture = "", desc = "属性提升", stack = 1, id = 101123, icon = 101123, last_effect = "Health", effect_list = { { type = "BattleBuffHOT", trigger = { "onUpdate" }, arg_list = { time = 3, number = 6 } }, { type = "BattleBuffCastSkill", trigger = { "onRemove" }, arg_list = { skill_id = 101123, target = "TargetSelf" } } } }
--[[ #module Input **TODO:** -[ ] repeated? -[ ] multikeys -[/] mouse inputs -[ ] multitouch ]]-- Input = {} Input.keys = {} Input.mouse = {} Input.mouseX = 0 Input.mouseY = 0 Input.mouseDx = 0 Input.mouseDy = 0 function Input:trigger(key) if self.keys[key] then if self.keys[key].state == "trigger" then return true end end return false end function Input:release(key) if self.keys[key] then if self.keys[key].state == "release" then return true end end return false end function Input:press(key) if self.keys[key] then if self.keys[key].state == "press" or self.keys[key].state == "repeat" or self.keys[key].state == "trigger" then return true end end return false end function Input:repeated(key) if self.keys.key then if self.keys.key.state == "repeat" then return true end end return false end function Input:dir4() if self:press("down") then return 2 end if self:press("left") then return 4 end if self:press("right") then return 6 end if self:press("up") then return 8 end return 0 end function Input:dir8() if self:press("down") and self:press("left") then return 1 end if self:press("down") and self:press("right") then return 3 end if self:press("up") and self:press("left") then return 7 end if self:press("up") and self:press("right") then return 9 end return dir4 end function Input:mousetrigger(button) local but = self.mouse[tostring(button)] if but then if but.state == "trigger" then return true,but.hit[1],but.hit[2] end end return false end function Input:mousedown(button) if self.mouse[tostring(button)] then if self.mouse[tostring(button)].state == "press" or self.mouse[tostring(button)].state == "repeat" or self.mouse[tostring(button)].state == "trigger" then return true,Input.mouseX,Input.mouseY end end return false end function Input:mouseup(button) local but = self.mouse[tostring(button)] if but then if but.state == "release" then return true,but.hit[1],but.hit[2] end end return false end function love.keypressed( key, scancode, isrepeat ) local k = {} k.state = "pretrigger" Input.keys[key] = k end function love.keyreleased( key, scancode ) local k = {} k.state = "prerelease" Input.keys[key] = k end function love.mousepressed( x, y, button, isTouch ) local k = {} k.state = "pretrigger" k.hit = {x,y} k.touch = isTouch Input.mouse[tostring(button)] = k end function love.mousereleased( x, y, button, isTouch ) local k = {} k.state = "prerelease" k.hit = {x,y} k.touch = isTouch Input.mouse[tostring(button)] = k end function love.mousemoved( x, y, dx, dy, isTouch ) Input.mouseX = x Input.mouseY = y Input.mouseDx = dx Input.mouseDy = dy end function Input:update(dt) for i,v in pairs(self.keys) do if v.state == "release" then v.state = "none" end if v.state == "trigger" then v.state = "press" end if v.state == "prerelease" then v.state = "release" end if v.state == "pretrigger" then v.state = "trigger" end end for i,v in pairs(self.mouse) do if v.state == "release" then v.state = "none" end if v.state == "trigger" then v.state = "press" end if v.state == "prerelease" then v.state = "release" end if v.state == "pretrigger" then v.state = "trigger" end end end
object_tangible_component_weapon_lightsaber_lightsaber_module_blackwing_crystal = object_tangible_component_weapon_lightsaber_shared_lightsaber_module_blackwing_crystal:new { } ObjectTemplates:addTemplate(object_tangible_component_weapon_lightsaber_lightsaber_module_blackwing_crystal, "object/tangible/component/weapon/lightsaber/lightsaber_module_blackwing_crystal.iff")
local repl = game:GetService('ReplicatedStorage') local players = game:GetService('Players') local FetchToken = repl.FetchToken local CheckClient = repl.CheckClient local TokenService = require(script.Parent.Modules.TokenService) local TOKEN_SETTINGS = { FETCH = FetchToken, CHECK = CheckClient } local ANTI_SETTINGS = { WalkSpeed = 16, JumpPower = 50 } TokenService:Init(TOKEN_SETTINGS, ANTI_SETTINGS)
-- usage example -- -- first we require the module local INPUT = require 'input' local CONFIGURE = require 'input.configure' local USE_JSON, JSON = pcall(require, 'dkjson') local USE_TOML, TOML = pcall(require, 'toml') -- it also needs to be set up with a virtual mapping; -- that's specific to your game local DIGITAL = { QUIT = {"f8"}, D_UP = {"up"}, D_LEFT = {"left"}, D_DOWN = {"down"}, D_RIGHT = {"right"}, BUTTON_01 = {1}, BUTTON_02 = {2}, BUTTON_03 = {3}, BUTTON_04 = {4}, BUTTON_05 = {5}, BUTTON_06 = {6}, BUTTON_07 = {7}, BUTTON_08 = {8}, BUTTON_09 = {9}, BUTTON_10 = {10}, BUTTON_11 = {11}, BUTTON_12 = {12}, } local ANALOG = { X_AXIS = 2, Y_AXIS = 4, } local HAT = { HAT_DIR = 1 } -- we call the setup method and pass the virtual mapping as argument function love.load() -- you can load it from your save data with 'load' -- > returns false if there's no controls save or if it's corrupted, -- > returns true if the controls were successfully loaded love.filesystem.setIdentity("joystick") local decoder = (USE_JSON and JSON.decode) or (USE_TOML and TOML.parse) local loaded = INPUT.load("controls", decoder) if not loaded then -- or you can manually load it from memory with 'setup' -- > returns true always INPUT.setup( { digital = DIGITAL, analog = ANALOG, hat = HAT, } ) end end function love.quit() -- you can save your mappings with 'save' -- returns true on success, throws an error if it fails local encoder if USE_JSON then function encoder(data) return JSON.encode(data, { indent = true }) end elseif USE_TOML then function encoder(data) return TOML.encode(data) end end INPUT.save("controls", encoder) end local x, y = 0, 0 local held = {} function love.update(dt) if INPUT.wasActionPressed('QUIT') then return love.event.quit() end -- set held buttons while #held > 0 do held[#held] = nil end for action, key in pairs(DIGITAL) do if INPUT.isActionDown(action) then held[#held+1] = action end end -- set directional input x, y = 0 x = INPUT.getAxis('X_AXIS') y = INPUT.getAxis('Y_AXIS') local dir = INPUT.getHat('HAT_DIR') if dir ~= 'c' then if dir:match('l') then x = -1 end if dir:match('r') then x = 1 end if dir:match('u') then y = -1 end if dir:match('d') then y = 1 end end if x == 0 and y == 0 then x = x + (INPUT.isActionDown('D_LEFT') and -1 or 0) x = x + (INPUT.isActionDown('D_RIGHT') and 1 or 0) y = y + (INPUT.isActionDown('D_UP') and -1 or 0) y = y + (INPUT.isActionDown('D_DOWN') and 1 or 0) end INPUT.flush() if love.keyboard.isDown('f1') then local mappings = INPUT.getMap() CONFIGURE(INPUT, mappings) end end function love.draw() local g = love.graphics local width, height = g.getDimensions() local radius = 64 local dot = 8 local midx, midy = width/2, height/2 g.setBackgroundColor(0, 0, 0) -- let's draw the directional input on the screen for debug g.push() g.translate(midx, midy) g.setColor(255, 255, 255) g.ellipse("line", 0, 0, radius) g.line(0, -radius, 0, radius) g.line(-radius, 0, radius, 0) g.printf(("[%.3f, %.3f]"):format(x, y), -radius, -radius-32, radius*2, "center") g.setColor(50, 100, 255) g.ellipse("fill", radius * x, radius * y, dot) g.printf("PRESS F1 TO RECONFIGURE CONTROLS", -radius, radius+64, radius*2, "center") g.pop() -- now let's draw the currently held buttons on screen too g.push() g.setNewFont(16) g.setColor(255, 255, 255) g.translate(64, 64) for i,button in ipairs(held) do g.print(("[%s]"):format(button), 0, 0) g.translate(0, 16) end g.pop() end
--- -- Lua JSON-RPC module. -- -- I want to be JSON-RPC 2.0 compliant. -- -- @module jsonrpc -- @author t-kenji <[email protected]> -- @license MIT -- @copyright 2020 t-kenji local json = require('json') local errors = require('jsonrpc.errors') local _M = { _VERSION = "JSON-RPC 0.1.0", jsonrpc_version = '2.0', } local recvall = function (sock) local frags = {} while true do local err, partial = select(2, sock:receive('*a')) if err ~= 'timeout' then error(err) end if partial == '' then break end table.insert(frags, partial) end return table.concat(frags) end local responses = {} function _M.run(application, stdin, stdout, stderr) stdin = stdin or io.stdin stdout = stdout or io.stdout stderr = stderr or io.stderr local json_str = recvall(stdin) or error('Connection established but noting received') local request = json.decode(json_str) local environ = {} for k, v in pairs(request) do environ[k] = v end environ['jsonrpc.input'] = stdin environ['jsonrpc.errors'] = stderr if not environ.method and environ.id then if responses[environ.id] then responses[environ.id](environ.result) responses[environ.id] = nil end return end environ['jsonrpc.request'] = function (method, params, id, response) stdout:send(json.encode{ jsonrpc = _M.jsonrpc_version, method = method, params = params, id = id, }) if id then responses[id] = response end end local function write(data) stdout:send(data) end local result, error_code = application(environ) local ok, err = pcall(function () local response = { jsonrpc = _M.jsonrpc_version, id = environ.id, } if not error_code then response.result = result else response.error = { code = error_code, message = errors.message[error_code], } end write(json.encode(response)) end) if not ok then error(err) end end function _M.errors(message, stdin, stdout, stderr) stdin = stdin or io.stdin stdout = stdout or io.stdout stderr = stderr or io.stderr stdout:send(json.encode({ jsonrpc = _M.jsonrpc_version, error = { code = jsonrpc.errors.code.INTERNAL_ERROR, message = jsonrpc.errors.message[code], data = message, } })) end return _M
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- B E N C H M A R K T O O L -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- === cp.bench === --- --- Benchmarking Tool. --- --- TIME FUNCTION EXECUTION: --- Use this to benchmark sections of code. Wrap them in a function inside this --- function call. Eg: --- --- local _bench = require("hs.bench") --- --- local foo = _bench("Foo Test", function() --- return do.somethingHere() --- end) --_bench --- --- You can also benchmark all (or some) of the functions on a table in one hit --- by using the 'bench.press' function: --- --- local mod = { ... } --- -- All functions are benchmarked --- mod = _bench.press("mymod", mod) --- -- Just the "foo" and "bar" functions are benchmarked. --- mod = _bench.press("mymod", mod, {"foo", "bar"}) -------------------------------------------------------------------------------- -- -- EXTENSIONS: -- -------------------------------------------------------------------------------- local log = require("hs.logger").new("bench") local clock = require("hs.timer").secondsSinceEpoch -------------------------------------------------------------------------------- -- -- THE MODULE: -- -------------------------------------------------------------------------------- local mod = {} local _timeindent = 0 local _timelog = {} function mod.mark(label, fn, ...) loops = loops or 1 local result = nil local t = _timelog t[#t+1] = {label = label, indent = _timeindent} _timeindent = _timeindent + 2 local start = clock() for i=1,loops do result = fn(...) end local stop = clock() local total = stop - start _timeindent = _timeindent - 2 t[#t+1] = {label = label, indent = _timeindent, value = total} if _timeindent == 0 then -- print when we are back at zero indents. local text = nil for i,v in ipairs(_timelog) do text = v.value and string.format("%0.3fms", v.value*1000) or "START" inOut = v.value and "<" or ">" log.df(string.format("%"..v.indent.."s%40s %s %"..(30-v.indent).."s", "", v.label, inOut, text)) end -- clear the log _timelog = {} end return result end local function set(list) if list then local set = {} for _, l in ipairs(list) do set[l] = true end return set else return nil end end function mod.press(label, value, names) if not value.___benched then names = set(names) for k,v in pairs(value) do if type(v) == "function" and (names == nil or names[k]) then value[k] = function(...) return mod.mark(label.."."..k, v, ...) end end end value.___benched = true local mt = getmetatable(value) if mt then mod.press(label, mt, names) end end return value end setmetatable(mod, {__call = function(_, ...) return mod.mark(...) end}) return mod
local traject = { __VERSION = 'traject 0.1.0', __AUTHOR = 'Pablo Ariel Mayobre' __DESCRIPTION = 'A library to create complex easing animations easily for Lua and LÖVE', __URL = 'https://github.com/Positive07/Traject', __LICENSE = [[ -------------- Copyright (c) 2016 Pablo Ariel Mayobre -------------- -------------------------- THE MIT LICENSE -------------------------- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] } local methods = require (... .. ".methods") local meta = { traject = { __call = function (self, ...) return self.new(...) end }, new = { __index = methods, __call = function (self, ...) return self:start(...) end }, } local update = function (self, dt) local rt = self.time + dt local t = rt * (self.anim.duration / self.duration) if t >= self.anim.duration then if self.loop then t = t % self.anim.duration else t = self.anim.duration self.finished = true end end local value = 0 for i, step in ipairs(self.anim._anim) do local a = t - step.start if a < step.prop.duration then if step.f then local change = step.prop.final and (step.prop.final - value) or step.prop.change value = step.f(a, value, change, step.prop.duration) end break else value = step.prop.final and step.prop.final or (value + step.prop.change) end end self.value = value self.time = rt return self.finished end local start = function (anim, duration, loop, callback) if not anim._anim then error("start expects an animation as first argument", 2) end return { anim = anim, duration = duration, time = 0, callback = callback, value = value, loop = loop, update = update, } end traject.new = function (start) local self = { start = start or 0, _anim = {}, delay = delay, sudden = sudden, custom = custom, cubicBezier = cubicBezier, duration = 0, start = start, } return setmetatable(self, meta.new) end return setmetatable(traject, meta.traject)
--------------------- -- Local variables -- --------------------- local g_Tab = nil local g_Input, g_Output local g_FromLang, g_ToLang local g_TranslateBtn, g_SayBtn local g_ChatMsgCb local g_ChatMsg = {} local g_MsgCount = 0 local g_Langs = { 'en' } local g_LangNames = { en = "English" } local g_Timer = false addEvent ( 'onTranslateReq', true ) addEvent ( 'onTranslateLangListReq', true ) addEvent ( 'onClientTranslate', true ) addEvent ( 'onClientTranslateLangList', true ) local TranslatorPanel = { name = "Translator", img = 'translator/icon.png', tooltip = "Translate any sentence into your own language", height = 370, } -------------------------------- -- Local function definitions -- -------------------------------- local function LoadLanguages () g_LangNames = {} local node, i = xmlLoadFile ( 'conf/iso_langs.xml' ), 0 if ( node ) then while ( true ) do local subnode = xmlFindChild ( node, 'lang', i ) if ( not subnode ) then break end i = i + 1 local code = xmlNodeGetAttribute ( subnode, 'code' ) local name = xmlNodeGetValue ( subnode ) assert ( code and name ) g_LangNames[code] = name end xmlUnloadFile ( node ) end end local function timerProc () guiSetEnabled ( g_TranslateBtn, true ) guiSetEnabled ( g_SayBtn, true ) g_Timer = false end local function onTranslateClick () local text = guiGetText ( g_Input ) if ( not text:match ( '^%s*$' ) ) then local from_i = guiComboBoxGetSelected ( g_FromLang ) local from = from_i > 0 and g_Langs[from_i] -- auto is supported local to_i = guiComboBoxGetSelected ( g_ToLang ) local to = to_i > -1 and g_Langs[to_i + 1] assert ( to, tostring(to_i)..' '..(#g_Langs) ) local say = ( source == g_SayBtn ) guiSetEnabled ( g_TranslateBtn, false ) guiSetEnabled ( g_SayBtn, false ) guiSetText ( g_Output, MuiGetMsg ( "Please wait..." ) ) g_Timer = setTimer ( timerProc, 1000, 1 ) triggerServerEvent ( 'onTranslateReq', g_Me, text, from, to, say ) else guiSetText ( g_Output, text ) end end local function onSwitchLangsClick () local from_i = guiComboBoxGetSelected ( g_FromLang ) -- auto is supported local to_i = guiComboBoxGetSelected ( g_ToLang ) if ( from_i > 0 and to_i >= 0 ) then guiComboBoxSetSelected ( g_FromLang, to_i + 1 ) guiComboBoxSetSelected ( g_ToLang, from_i - 1 ) end end local function loadChatMsg () local sel = guiComboBoxGetSelected ( g_ChatMsgCb ) if ( sel > -1 ) then local text = guiComboBoxGetItemText ( g_ChatMsgCb, sel ) guiSetText ( g_Input, text ) end guiComboBoxSetSelected ( g_ChatMsgCb, -1 ) end local function updateLangComboBoxes () -- From guiComboBoxClear ( g_FromLang ) guiComboBoxAddItem ( g_FromLang, "Auto-detect" ) for i, lang in ipairs ( g_Langs ) do guiComboBoxAddItem ( g_FromLang, g_LangNames[lang] or lang ) end guiComboBoxSetSelected ( g_FromLang, 0 ) -- To guiComboBoxClear ( g_ToLang ) local default = 0 for i, lang in ipairs ( g_Langs ) do local id = guiComboBoxAddItem ( g_ToLang, g_LangNames[lang] or lang ) if ( lang == 'en' ) then default = id end end guiComboBoxSetSelected ( g_ToLang, default ) end local function createGui(panel) local w, h = guiGetSize(panel, false) LoadLanguages () triggerServerEvent('onTranslateLangListReq', g_Root) guiCreateLabel(10, 10, 50, 15, "From:", false, panel) g_FromLang = guiCreateComboBox ( 50, 10, 130, 300, '', false, panel ) local btn = guiCreateButton ( 200, 10, 40, 25, '<->', false, panel ) addEventHandler ( 'onClientGUIClick', btn, onSwitchLangsClick, false ) guiCreateLabel ( 260, 10, 50, 15, "To:", false, panel ) g_ToLang = guiCreateComboBox ( 310, 10, math.min(130, w - 320), 300, '', false, panel ) updateLangComboBoxes () g_TranslateBtn = guiCreateButton ( 10, 40, 80, 25, "Translate", false, panel ) addEventHandler ( 'onClientGUIClick', g_TranslateBtn, onTranslateClick, false ) g_SayBtn = guiCreateButton ( 100, 40, 120, 25, "Say translated", false, panel ) addEventHandler ( 'onClientGUIClick', g_SayBtn, onTranslateClick, false ) g_ChatMsgCb = guiCreateComboBox ( 230, 40, w - 240, 210, MuiGetMsg ( "Load chat message" ), false, panel ) addEventHandler ( 'onClientGUIComboBoxAccepted', g_ChatMsgCb, loadChatMsg, false ) for i, msg in ipairs ( g_ChatMsg ) do guiComboBoxAddItem ( g_ChatMsgCb, msg ) end g_ChatMsg = false guiCreateLabel ( 10, 70, 50, 15, "Input:", false, panel ) g_Input = guiCreateMemo ( 10, 90, w - 20, 90, '', false, panel ) guiCreateLabel(10, 190, 50, 15, "Output:", false, panel) g_Output = guiCreateMemo(10, 210, w - 20, 90, '', false, panel) guiMemoSetReadOnly(g_Output, true) local label = guiCreateLabel(10, 310, w - 20, 15, MuiGetMsg("Translation by %s"):format('Microsoft Bing (tm)'), false, panel) guiSetFont(label, 'default-small') guiLabelSetHorizontalAlign(label, 'right') if(UpNeedsBackBtn()) then local btn = guiCreateButton(w - 80, h - 35, 70, 25, "Back", false, panel) addEventHandler('onClientGUIClick', btn, UpBack, false) end end function TranslatorPanel.onShow ( panel ) if(not g_Tab) then g_Tab = panel createGui(g_Tab) end end local function onTranslate ( text ) guiSetText ( g_Output, text ) if ( g_Timer ) then killTimer ( g_Timer ) g_Timer = false end guiSetEnabled ( g_TranslateBtn, true ) guiSetEnabled ( g_SayBtn, true ) end local function onTranslateLangList ( langs ) g_Langs = langs updateLangComboBoxes () end local function onChatMessage ( text ) local LIMIT = 12 text = text:gsub ( '#%x%x%x%x%x%x', '' ) if ( g_ChatMsgCb ) then if ( g_MsgCount >= LIMIT ) then guiComboBoxRemoveItem ( g_ChatMsgCb, 0 ) end guiComboBoxAddItem ( g_ChatMsgCb, text ) else if ( g_MsgCount >= LIMIT ) then table.remove ( g_ChatMsg, 1 ) end table.insert ( g_ChatMsg, text ) end if ( g_MsgCount < LIMIT ) then g_MsgCount = g_MsgCount + 1 end assert ( not g_ChatMsg or g_MsgCount == #g_ChatMsg ) end addInitFunc(function() UpRegister(TranslatorPanel) addEventHandler('onClientTranslate', g_Root, onTranslate) addEventHandler('onClientTranslateLangList', g_Root, onTranslateLangList) addEventHandler('onClientChatMessage', g_Root, onChatMessage) end)
object_tangible_loot_creature_loot_kashyyyk_loot_varactyl_claw_01 = object_tangible_loot_creature_loot_kashyyyk_loot_shared_varactyl_claw_01:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_kashyyyk_loot_varactyl_claw_01, "object/tangible/loot/creature_loot/kashyyyk_loot/varactyl_claw_01.iff")
local main = require("ido.main") local options = require("ido.config").options -- @module event The event loop of Ido local event = {} -- Timer event.timer = vim.loop.new_timer() -- Helper function for starting asynchronous jobs -- @param action The function to execute -- @return true function event.async(action) event.timer:start(0, 0, vim.schedule_wrap(action)) return true end -- Stop the event loop of Ido -- @return true function event.stop() main.sandbox.variables.looping = false return true end -- Exit Ido -- @return true function event.exit() main.sandbox.variables.results = {} event.stop() return true end -- Loop Ido -- @return nil if errors were encountered, else true function event.loop() local variables = main.sandbox.variables while (variables.looping) do local key_pressed = vim.fn.getchar() local binding = variables.bindings[key_pressed] if binding then if type(binding) == "function" then binding() elseif type(binding) == "string" then if binding:sub(1, 3) == "ido" then binding = binding:sub(5, -1) local binding_module = binding:gsub("%..*$", "") local binding_function = binding:gsub("^.*%.", "") binding = "require('ido."..binding_module.."')."..binding_function.."()" end load(binding)() else -- Invalid binding, throw error event.stop() print("Invalid binding for key: "..key_pressed, 3) return nil end else main.insert(vim.fn.nr2char(key_pressed)) end end return true end return event
#!/usr/bin/env lua print(arg[0])
AddCSLuaFile( ) DEFINE_BASECLASS("base_aperture_ent") local WireAddon = WireAddon or WIRE_CLIENT_INSTALLED ENT.PrintName = "Base Aperture Turret" ENT.IsAperture = true ENT.TurretSoundFound = "" ENT.TurretSoundSearch = "" ENT.TurretSoundFizzle = "" ENT.TurretSoundPickup = "" ENT.TurretDrawLaserbeam = true ENT.TurretEyePos = Vector() ENT.TurretDisabled = "" local TURRET_STATE_IDLE = 1 local TURRET_STATE_PREPARE_DEPLOY = 2 local TURRET_STATE_DEPLOY = 3 local TURRET_STATE_SHOOT = 4 local TURRET_STATE_SEARCH = 5 local TURRET_STATE_PREPARE_RETRACT = 6 local TURRET_STATE_RETRACT = 7 local TURRET_STATE_PANIC = 8 local TURRET_STATE_PANIC_LIGHTER = 9 local TURRET_STATE_EXPLODE = 10 local TURRET_TARGET_DEGRESE = 60 if WireAddon then ENT.WireDebugName = ENT.PrintName end function ENT:SetupDataTables() self:NetworkVar("Bool", 0, "Enable") self:NetworkVar("Bool", 1, "Toggle") self:NetworkVar("Bool", 2, "StartEnabled") self:NetworkVar("Int", 3, "TurretState") self:NetworkVar("Entity", 4, "Target") self:NetworkVar("Angle", 5, "TurretAngles") self:NetworkVar("Float", 6, "TurretOpen") end function ENT:Enable(enable) if self:GetEnable() != enable then if enable then else end self:SetEnable(enable) end end function ENT:EnableEX(enable) if self:GetToggle() then if enable then self:Enable(not self:GetEnable()) end return true end if self:GetStartEnabled() then enable = !enable end self:Enable(enable) end if SERVER then function ENT:RotateTurret(angle, speed) local turretAngles = self:GetTurretAngles() local pitch = turretAngles.pitch - math.AngleDifference(turretAngles.pitch, angle.pitch) / speed local yaw = turretAngles.yaw - math.AngleDifference(turretAngles.yaw, angle.yaw) / speed pitch = math.max(-TURRET_TARGET_DEGRESE, math.min(TURRET_TARGET_DEGRESE, pitch)) yaw = math.max(-TURRET_TARGET_DEGRESE, math.min(TURRET_TARGET_DEGRESE, yaw)) self:SetTurretAngles(Angle(pitch, yaw, 0)) end function ENT:RotateTurretPoint(pos, speed) local center = self:LocalToWorld(self:GetPhysicsObject():GetMassCenter()) local dirAng = (pos - center):Angle() local angle = self:WorldToLocalAngles(dirAng) self:RotateTurret(angle, speed) end end function ENT:Initialize() self.BaseClass.BaseClass.Initialize(self) if SERVER then self:SetTurretState(TURRET_STATE_IDLE) end if CLIENT then end end function ENT:Drawing() if not LIB_APERTURE then return end if not self:GetEnable() then return end if not self.TurretDrawLaserbeam then return end if self:GetNWBool("TA:TurretDifferent") then return end local angles = self:GetTurretAngles() local wangles = self:LocalToWorldAngles(angles) local eyePos = self:LocalToWorld(self.TurretEyePos) local points = LIB_APERTURE:GetAllPortalPassagesAng(eyePos, wangles, 0, self) render.SetMaterial(Material("effects/redlaser1")) for k,v in pairs(points) do local startpos = v.startpos local endpos = v.endpos local distance = startpos:Distance(endpos) render.DrawBeam(startpos, endpos, 1, distance / 100, 1, Color(255, 255, 255)) end end function ENT:Draw() self:DrawModel() if not self:GetEnable() then return end end function ENT:IsTurretKnockout() local angles = self:GetAngles() return (angles.pitch < -60 or angles.pitch > 60) or (angles.roll < -60 or angles.roll > 60) end if SERVER then function ENT:TurretShootBullets(startpos, dir) self:FireBullets({ Attacker = self, Damage = 7, Force = 1, Dir = dir, Spread = Vector(math.Rand(-1, 1), math.Rand(-1, 1)) * 0.05, Src = startpos }, false) end function ENT:TurretMuzzleEffect(startpos, dir) local effectdata = EffectData() effectdata:SetOrigin(startpos) effectdata:SetNormal(dir) util.Effect("turret_muzzle", effectdata) end function ENT:Shoot(angle) if timer.Exists("TA:TurretShooting"..self:EntIndex()) then return end if self.CantShoot then timer.Create("TA:TurretShooting"..self:EntIndex(), 2, 1, function() end) self:EmitSound("TA:TurretDryFire") return end timer.Create("TA:TurretShooting"..self:EntIndex(), 0.1, 1, function() end) local boneBase = self:LookupBone("Aim_LR") local pos = self:GetBonePosition(boneBase) local forward = angle:Forward() local right = angle:Right() local posR = pos + forward * 10 + right * 10 local posL = pos + forward * 10 - right * 10 self:TurretMuzzleEffect(posR, forward) self:TurretMuzzleEffect(posL, forward) self:EmitSound("TA:TurretShoot") self:TurretShootBullets(posR, forward) self:TurretShootBullets(posL, forward) end function ENT:CheckFoShoot() local target = self:GetTarget() local eyePos = self:LocalToWorld(self.TurretEyePos) local angles = self:GetTurretAngles() local wangles = self:LocalToWorldAngles(angles) local dir = wangles:Forward() self:Shoot(wangles) end end function ENT:Think() if not LIB_APERTURE then return end self:NextThink(CurTime()) if CLIENT then local turretsBone = self:LookupBone("Aim_LR") local turretAntenna = self:LookupBone("cables_antenna_bone") local turretLeftBone = self:LookupBone("LFT_Wing") local turretRightBone = self:LookupBone("RT_Wing") local turretRGun1 = self:LookupBone("RT_Gun1") local turretRGun2 = self:LookupBone("RT_Gun2") local turretLGun1 = self:LookupBone("LFT_Gun1") local turretLGun2 = self:LookupBone("LFT_Gun2") local turretOpen = self:GetTurretOpen() local angle = self:GetTurretAngles() angle = Angle(angle.yaw, 0, angle.pitch) if turretsBone then self:ManipulateBoneAngles(turretsBone, angle) end -- wings if turretLeftBone then self:ManipulateBonePosition(turretLeftBone, Vector(-turretOpen, 0, 0) * 8) end if turretRightBone then self:ManipulateBonePosition(turretRightBone, Vector(turretOpen, 0, 0) * 8) end -- antenna if turretAntenna then self:ManipulateBonePosition(turretAntenna, Vector(0, turretOpen, 0) * 15) end -- guns if turretRGun1 then self:ManipulateBonePosition(turretRGun1, Vector(0, 0, turretOpen) * 4) end if turretRGun2 then self:ManipulateBonePosition(turretRGun2, Vector(0, 0, turretOpen) * 4) end if turretLGun1 then self:ManipulateBonePosition(turretLGun1, Vector(0, 0, turretOpen) * 4) end if turretLGun2 then self:ManipulateBonePosition(turretLGun2, Vector(0, 0, turretOpen) * 4) end return true end -- SERVER side local turretState = self:GetTurretState() local eyePos = self:LocalToWorld(self.TurretEyePos) local target, center if self:GetEnable() then target, center = LIB_APERTURE:FindClosestAliveInConeIncludingPortalPassages(eyePos, self:GetForward(), 2000, TURRET_TARGET_DEGRESE) end if IsValid(target) then local _, trace = LIB_APERTURE:GetAllPortalPassages(eyePos, (center - eyePos), nil, self) if not IsValid(trace.Entity) or trace.Entity != target then target = nil end if self.TurretDifferent then target = nil end end if (not self:GetEnable() and not self:IsTurretKnockout() or self.TurretDifferent) and turretState == TURRET_STATE_SEARCH then -- Retracting turret self:SetTurretState(TURRET_STATE_PREPARE_RETRACT) end if IsValid(target) then -- Deploy turret if turretState == TURRET_STATE_IDLE then self:SetTurretState(TURRET_STATE_PREPARE_DEPLOY) self:SetTarget(target) timer.Remove("TA:TurretAutoSearch"..self:EntIndex()) end end if self:GetEnable() then -- if player Hold turret if self:IsPlayerHolding() then if turretState != TURRET_STATE_PANIC_LIGHTER and turretState != TURRET_STATE_SHOOT then self:SetTurretState(TURRET_STATE_PANIC_LIGHTER) if self.TurretSoundPickup then self:EmitSound(self.TurretSoundPickup) end timer.Remove("TA:StopSearching"..self:EntIndex()) timer.Remove("TA:KnockoutTime"..self:EntIndex()) timer.Remove("TA:PrepareDeploy"..self:EntIndex()) timer.Remove("TA:TurretReleaseTarget"..self:EntIndex()) timer.Remove("TA:TurretActivatePing"..self:EntIndex()) end elseif turretState == TURRET_STATE_PANIC_LIGHTER then self:SetTurretState(TURRET_STATE_SEARCH) end if self:IsTurretKnockout() then if turretState != TURRET_STATE_PANIC then self:SetTurretState(TURRET_STATE_PANIC) timer.Create("TA:KnockoutTime"..self:EntIndex(), 3, 1, function() if self.TurretDisabled then self:EmitSound(self.TurretDisabled) end if not IsValid(self) then return end self:SetTurretState(TURRET_STATE_PREPARE_RETRACT) self:Enable(false) self:EmitSound("TA:TurretDie") end) timer.Remove("TA:StopSearching"..self:EntIndex()) timer.Remove("TA:PrepareDeploy"..self:EntIndex()) timer.Remove("TA:TurretReleaseTarget"..self:EntIndex()) timer.Remove("TA:TurretActivatePing"..self:EntIndex()) end elseif turretState == TURRET_STATE_PANIC then self:SetTurretState(TURRET_STATE_SEARCH) timer.Remove("TA:KnockoutTime"..self:EntIndex()) end end if turretState == TURRET_STATE_PREPARE_DEPLOY then if not timer.Exists("TA:PrepareDeploy"..self:EntIndex()) then timer.Create("TA:PrepareDeploy"..self:EntIndex(), 1, 1, function() if not IsValid(self) then return end self:EmitSound("TA:TurretDeploy") if self.TurretSoundFound != "" then self:EmitSound(self.TurretSoundFound) end self:SetTurretState(TURRET_STATE_DEPLOY) timer.Simple(1, function() if not IsValid(self) then return end self:SetTurretState(TURRET_STATE_SHOOT) end) end) end elseif turretState == TURRET_STATE_PREPARE_RETRACT then self:RotateTurret(Angle(), 20) if not timer.Exists("TA:PrepareRetract"..self:EntIndex()) then timer.Create("TA:PrepareRetract"..self:EntIndex(), 1.5, 1, function() if not IsValid(self) then return end self:EmitSound("TA:TurretRetract") if self.TurretRetract != "" then self:EmitSound(self.TurretRetract) end self:SetTurretState(TURRET_STATE_RETRACT) timer.Simple(1, function() if not IsValid(self) then return end self:SetTurretState(TURRET_STATE_IDLE) timer.Remove("TA:StopSearching"..self:EntIndex()) timer.Create("TA:TurretAutoSearch"..self:EntIndex(), 3, 1, function() if not IsValid(self) then return end if self.TurretSoundAutoSearch != "" then self:EmitSound(self.TurretSoundAutoSearch) end end) end) end) end elseif turretState == TURRET_STATE_SEARCH then local specCurTime = CurTime() * 2 + self:EntIndex() * 5 local pitch = math.cos(specCurTime * 1.5 + self:EntIndex() * 10) * 30 local yaw = math.sin(specCurTime) * 40 self:RotateTurret(Angle(pitch, yaw, 0), 10) -- Turret ping sound if not timer.Exists("TA:TurretPing"..self:EntIndex()) then self:EmitSound("TA:TurretPing") timer.Create("TA:TurretPing"..self:EntIndex(), 1, 1, function() end) end if IsValid(target) then if not timer.Exists("TA:StartShoot"..self:EntIndex()) then timer.Create("TA:StartShoot"..self:EntIndex(), 0.5, 1, function() if not IsValid(self) then return end self:SetTarget(target) self:SetTurretState(TURRET_STATE_SHOOT) end) end timer.Remove("TA:StopSearching"..self:EntIndex()) elseif not timer.Exists("TA:StopSearching"..self:EntIndex()) then timer.Create("TA:StopSearching"..self:EntIndex(), 5, 1, function() if not IsValid(self) then return end self:SetTurretState(TURRET_STATE_PREPARE_RETRACT) end) end elseif turretState == TURRET_STATE_SHOOT then if IsValid(target) then -- local center = IsValid(target:GetPhysicsObject()) and target:LocalToWorld(target:GetPhysicsObject():GetMassCenter()) or target:GetPos() if not self.LockingSound then self.LockingSound = true self:EmitSound("TA:TurretActivate") end self:SetTarget(target) self:RotateTurretPoint(center, 5) timer.Remove("TA:TurretReleaseTarget"..self:EntIndex()) self:CheckFoShoot() else target = self:GetTarget() if not timer.Exists("TA:TurretReleaseTarget"..self:EntIndex()) then timer.Create("TA:TurretReleaseTarget"..self:EntIndex(), 0.25, 1, function() if not IsValid(self) then return end if self.TurretSoundSearch != "" then self:EmitSound(self.TurretSoundSearch) end self.LockingSound = false self:SetTurretState(TURRET_STATE_SEARCH) self:SetTarget(NULL) end) end end elseif turretState == TURRET_STATE_PANIC then local specCurTime = CurTime() * 10 + self:EntIndex() * 5 local pitch = math.cos(specCurTime * 1.5 + self:EntIndex() * 10) * 30 local yaw = math.sin(specCurTime) * 40 local turretOpen = self:GetTurretOpen() self:RotateTurret(Angle(pitch, yaw, 0), 10) self:CheckFoShoot() if turretOpen < 1 then self:SetTurretOpen(turretOpen + 2 * FrameTime()) else self:SetTurretOpen(1) end elseif turretState == TURRET_STATE_PANIC_LIGHTER then local specCurTime = CurTime() * 2 + self:EntIndex() * 5 local pitch = math.cos(specCurTime * 1.5 + self:EntIndex() * 10) * 30 local yaw = math.sin(specCurTime) * 40 local turretOpen = self:GetTurretOpen() self:RotateTurret(Angle(pitch, yaw, 0), 10) if turretOpen < 1 then self:SetTurretOpen(turretOpen + 2 * FrameTime()) else self:SetTurretOpen(1) end if not timer.Exists("TA:TurretActivatePing"..self:EntIndex()) then if math.random(1, 2) == 1 then self:EmitSound("TA:TurretActivate") else self:EmitSound("TA:TurretPing") end timer.Create("TA:TurretActivatePing"..self:EntIndex(), 1 + math.Rand(0, 1), 1, function() end) end if IsValid(target) then if not timer.Exists("TA:StartShoot"..self:EntIndex()) then timer.Create("TA:StartShoot"..self:EntIndex(), 0.5, 1, function() if not IsValid(self) then return end self:SetTarget(target) self:SetTurretState(TURRET_STATE_SHOOT) end) end end elseif turretState == TURRET_STATE_DEPLOY then local turretOpen = self:GetTurretOpen() if turretOpen < 1 then self:SetTurretOpen(turretOpen + 2 * FrameTime()) else self:SetTurretOpen(1) end elseif turretState == TURRET_STATE_RETRACT then local turretOpen = self:GetTurretOpen() if turretOpen > 0 then self:SetTurretOpen(turretOpen - 2 * FrameTime()) else self:SetTurretOpen(0) end end if self:IsOnFire() and turretState != TURRET_STATE_EXPLODE then self:SetTurretState(TURRET_STATE_EXPLODE) if self.TurretDisabled then self:EmitSound(self.TurretDisabled) end timer.Simple(3, function() if not IsValid(self) then return end local effectdata = EffectData() effectdata:SetOrigin(self:GetPos()) effectdata:SetNormal(Vector(0, 0, 1)) util.Effect("Explosion", effectdata) util.BlastDamage(self, self, self:GetPos(), 150, 100) self:Remove() end) end return true end function ENT:OnFizzle() if self.TurretSoundFizzle != "" then self:EmitSound(self.TurretSoundFizzle) end self:Enable(false) end function ENT:OnRemove() if CLIENT then end end if CLIENT then return end -- no more client side function ENT:TriggerInput(iname, value) if not WireAddon then return end if iname == "Enable" then self:Enable(tobool(value)) end end numpad.Register("PortalTurretFloor_Enable", function(pl, ent, keydown) if not IsValid(ent) then return false end ent:EnableEX(keydown) return true end)
-- //////////////////////////////////// -- // MYSQL // -- //////////////////////////////////// sqlUsername = exports.mysql:getMySQLUsername() sqlPassword = exports.mysql:getMySQLPassword() sqlDB = exports.mysql:getMySQLDBName() sqlHost = exports.mysql:getMySQLHost() sqlPort = exports.mysql:getMySQLPort() handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) function checkMySQL() if not (mysql_ping(handler)) then handler = mysql_connect(sqlHost, sqlUsername, sqlPassword, sqlDB, sqlPort) end end setTimer(checkMySQL, 300000, 0) function closeMySQL() if (handler) then mysql_close(handler) end end addEventHandler("onResourceStop", getResourceRootElement(getThisResource()), closeMySQL) -- //////////////////////////////////// -- // MYSQL END // -- //////////////////////////////////// local smallRadius = 5 --units ----------------------[CUFF]-------------------- function cuffPlayer(thePlayer, commandName, targetPartialNick) local username = getPlayerName(thePlayer) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then if not (targetPartialNick) then outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick]", thePlayer) else local faction = getPlayerTeam(thePlayer) local ftype = getElementData(faction, "type") if (ftype~=2) then outputChatBox("You do not have handcuffs.", thePlayer, 255, 0, 0) else local targetPlayer = exports.global:findPlayerByPartialNick(targetPartialNick) if not (targetPlayer) then outputChatBox("Player not found or multiple were found.", thePlayer, 255, 0, 0) else local restrain = getElementData(targetPlayer, "restrain") if (restrain==1) then outputChatBox("Player is already restrained.", thePlayer, 255, 0, 0) else local targetPlayerName = getPlayerName(targetPlayer) local x, y, z = getElementPosition(targetPlayer) local colSphere = createColSphere(x, y, z, smallRadius) exports.pool:allocateElement(colSphere) if (isElementWithinColShape(thePlayer, colSphere)) then outputChatBox("You have been hand cuffed by " .. username .. ".", targetPlayer) outputChatBox("You are cuffing " .. targetPlayerName .. ".", thePlayer) toggleControl(targetPlayer, "sprint", false) toggleControl(targetPlayer, "jump", false) toggleControl(targetPlayer, "next_weapon", false) toggleControl(targetPlayer, "previous_weapon", false) toggleControl(targetPlayer, "accelerate", false) toggleControl(targetPlayer, "brake_reverse", false) toggleControl(targetPlayer, "fire", false) toggleControl(targetPlayer, "aim_weapon", false) setPedWeaponSlot(targetPlayer, 0) setElementData(targetPlayer, "restrain", 1) else outputChatBox("You are not within range of " .. targetPlayerName .. ".", thePlayer, 255, 0, 0) end destroyElement(colSphere) end end end end end end --addCommandHandler("cuff", cuffPlayer, false, false) ----------------------[UNCUFF]-------------------- function uncuffPlayer(thePlayer, commandName, targetPartialNick) local username = getPlayerName(thePlayer) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then if not (targetPartialNick) then outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick]", thePlayer) else local faction = getPlayerTeam(thePlayer) local ftype = getElementData(faction, "type") if (ftype~=2) then outputChatBox("You do not have handcuffs.", thePlayer, 255, 0, 0) else local targetPlayer = exports.global:findPlayerByPartialNick(targetPartialNick) if not (targetPlayer) then outputChatBox("Player not found or multiple were found.", thePlayer, 255, 0, 0) else local restrain = getElementData(targetPlayer, "restrain") if (restrain==0) then outputChatBox("Player is not restrained.", thePlayer, 255, 0, 0) else local targetPlayerName = getPlayerName(targetPlayer) local x, y, z = getElementPosition(targetPlayer) local colSphere = createColSphere(x, y, z, smallRadius) exports.pool:allocateElement(colSphere) if (isElementWithinColShape(thePlayer, colSphere)) then outputChatBox("You have been uncuffed by " .. username .. ".", targetPlayer) outputChatBox("You are uncuffing " .. targetPlayerName .. ".", thePlayer) toggleControl(targetPlayer, "sprint", true) toggleControl(targetPlayer, "fire", true) toggleControl(targetPlayer, "jump", true) toggleControl(targetPlayer, "next_weapon", true) toggleControl(targetPlayer, "previous_weapon", true) toggleControl(targetPlayer, "accelerate", true) toggleControl(targetPlayer, "brake_reverse", true) toggleControl(targetPlayer, "aim_weapon", true) setElementData(targetPlayer, "restrain", 0) exports.global:removeAnimation(targetPlayer) else outputChatBox("You are not within range of " .. targetPlayerName .. ".", thePlayer, 255, 0, 0) end destroyElement(colSphere) end end end end end end --addCommandHandler("uncuff", uncuffPlayer, false, false) -- /fingerprint function fingerprintPlayer(thePlayer, commandName, targetPlayerNick) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then local theTeam = getPlayerTeam(thePlayer) local factionType = getElementData(theTeam, "type") if (factionType==2) then if not (targetPlayerNick) then outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick]", thePlayer, 255, 194, 14) else local targetPlayer = exports.global:findPlayerByPartialNick(targetPlayerNick) if not (targetPlayer) then outputChatBox("Player is not online.", thePlayer, 255, 0, 0) else local x, y, z = getElementPosition(thePlayer) local tx, ty, tz = getElementPosition(targetPlayer) local distance = getDistanceBetweenPoints3D(x, y, z, tx, ty, tz) if (distance<=10) then local fingerprint = getElementData(targetPlayer, "fingerprint") outputChatBox(getPlayerName(targetPlayer) .. "'s Fingerprint: " .. tostring(fingerprint) .. ".", thePlayer, 255, 194, 14) else outputChatBox("You are too far away from " .. getPlayerName(targetPlayer) .. ".", thePlayer, 255, 0, 0) end end end end end end addCommandHandler("fingerprint", fingerprintPlayer, false, false) -- /ticket function ticketPlayer(thePlayer, commandName, targetPlayerNick, amount, ...) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then local theTeam = getPlayerTeam(thePlayer) local factionType = getElementData(theTeam, "type") if (factionType==2) then if not (targetPlayerNick) or not (amount) or not (...) then outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick] [Amount] [Reason]", thePlayer, 255, 194, 14) else local targetPlayer = exports.global:findPlayerByPartialNick(targetPlayerNick) if not (targetPlayer) then outputChatBox("Player is not online.", thePlayer, 255, 0, 0) else local x, y, z = getElementPosition(thePlayer) local tx, ty, tz = getElementPosition(targetPlayer) local distance = getDistanceBetweenPoints3D(x, y, z, tx, ty, tz) if (distance<=10) then amount = tonumber(amount) local reason = table.concat({...}, " ") local money = exports.global:getMoney(targetPlayer) local bankmoney = getElementData(targetPlayer, "bankmoney") if money + bankmoney < amount then outputChatBox("This player cannot afford such a ticket.", thePlayer, 255, 0, 0) else local takeFromCash = math.min( money, amount ) local takeFromBank = amount - takeFromCash exports.global:takeMoney(targetPlayer, takeFromCash) -- Distribute money between the PD and Government local tax = exports.global:getTaxAmount() exports.global:giveMoney( getTeamFromName("Los Santos Police Department"), math.ceil((1-tax)*amount) ) exports.global:giveMoney( getTeamFromName("Government of Los Santos"), math.ceil(tax*amount) ) outputChatBox("You ticketed " .. getPlayerName(targetPlayer) .. " for " .. amount .. "$. Reason: " .. reason .. ".", thePlayer) outputChatBox("You were ticketed for " .. amount .. "$ by " .. getPlayerName(thePlayer) .. ". Reason: " .. reason .. ".", targetPlayer) if takeFromBank > 0 then outputChatBox("Since you don't have enough money with you, $" .. takeFromBank .. " have been taken from your bank account.", targetPlayer) setElementData(targetPlayer, "bankmoney", bankmoney - takeFromBank) end end else outputChatBox("You are too far away from " .. getPlayerName(targetPlayer) .. ".", thePlayer, 255, 0, 0) end end end end end end addCommandHandler("ticket", ticketPlayer, false, false) function takeLicense(thePlayer, commandName, targetPartialNick, licenseType) local username = getPlayerName(thePlayer) local logged = getElementData(thePlayer, "loggedin") if (logged==1) then local faction = getPlayerTeam(thePlayer) local ftype = getElementData(faction, "type") if (ftype==2) then if not (targetPartialNick) then outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick][license Type 1:Driving 2:Weapon]", thePlayer) else if not (licenseType) then outputChatBox("SYNTAX: /" .. commandName .. " [Player Partial Nick][license Type 1:Driving 2:Weapon]", thePlayer) else local targetPlayer = exports.global:findPlayerByPartialNick(targetPartialNick) local targetPlayerName = getPlayerName(targetPlayer) local name = getPlayerName(thePlayer) if (tonumber(licenseType)==1) then if(tonumber(getElementData(targetPlayer, "license.car")) == 1) then local query = mysql_query(handler, "UPDATE characters SET car_license='0' WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(targetPlayer)) .. "' LIMIT 1") mysql_free_result(query) outputChatBox(name.." has revoked your driving license.", targetPlayer, 255, 194, 14) outputChatBox("You have revoked " .. targetPlayerName .. "'s driving license.", thePlayer, 255, 194, 14) setElementData(targetPlayer, "license.car", 0) else outputChatBox(targetPlayerName .. " does not have a driving license.", thePlayer, 255, 0, 0) end elseif (tonumber(licenseType)==2) then if(tonumber(getElementData(targetPlayer, "license.gun")) == 1) then local query = mysql_query(handler, "UPDATE characters SET gun_license='0' WHERE charactername='" .. mysql_escape_string(handler, getPlayerName(targetPlayer)) .. "' LIMIT 1") mysql_free_result(query) outputChatBox(name.." has revoked your weapon license.", targetPlayer, 255, 194, 14) outputChatBox("You have revoked " .. targetPlayerName .. "'s weapon license.", thePlayer, 255, 194, 14) setElementData(targetPlayer, "license.gun", 0) else outputChatBox(targetPlayerName .. " does not have a weapon license.", thePlayer, 255, 0, 0) end else outputChatBox("License type not recognised.", thePlayer, 255, 194, 14) end end end end end end addCommandHandler("takelicense", takeLicense, false, false) function tellNearbyPlayersVehicleStrobesOn() local x, y, z = getElementType(source) local checkSphere = createColSphere(x, y, z, 300) local nearbyPlayers = getElementsWithinColShape(checkSphere, "player") destroyElement(checkSphere) for _, nearbyPlayer in ipairs(nearbyPlayers) do triggerClientEvent(nearbyPlayer, "forceElementStreamIn", source) end end addEvent("forceElementStreamIn", true) addEventHandler("forceElementStreamIn", getRootElement(), tellNearbyPlayersVehicleStrobesOn)
local sailor = require "sailor" local M = {} function M.index(page) local categorys = sailor.model("category"):find_all() page:render('index',{categorys = categorys}) end function M.create(page) local category = sailor.model("category"):new() local saved if next(page.POST) then category:get_post(page.POST) saved = category:save() if saved then page:redirect('category/index') end end page:render('create',{category = category, saved = saved}) end function M.update(page) local category = sailor.model("category"):find_by_id(page.GET.id) if not category then return 404 end local saved if next(page.POST) then category:get_post(page.POST) saved = category:update() if saved then page:redirect('category/index') end end page:render('update',{category = category, saved = saved}) end function M.view(page) local category = sailor.model("category"):find_by_id(page.GET.id) if not category then return 404 end page:render('view',{category = category}) end function M.delete(page) local category = sailor.model("category"):find_by_id(page.GET.id) if not category then return 404 end if category:delete() then page:redirect('category/index') end end return M
local module = {} local function receive(socket, data) node.input(data) if socket == nil then print("connection terminated") end end local function disconnection(socket) node.output(nil) end function module.start() server = net.createServer(net.TCP, 600) server:listen(23, function(socket) local function send(data) socket:send(data) end node.output(send, 0) socket:on("receive", receive) socket:on("disconnection", disconnection) end) end function module.stop() server.stop() end return module
return {'breeveertien','bretoen','bretoens','bretons','break','breakbeat','breakdance','breakdancen','breakdancer','breakdown','breakpoint','breed','breedband','breedbandig','breedbandinternet','breedbandnetwerk','breedbandtechnologie','breedbandverbinding','breedbeeld','breedbeeldscherm','breedbeeldtelevisie','breedbladig','breeddenkend','breedgebouwd','breedgedragen','breedgerand','breedgeschouderd','breedgrijnzend','breedheid','breedspoor','breedsprakig','breedsprakigheid','breedstraler','breedte','breedtecirkel','breedtegraad','breedtepass','breedtesport','breeduit','breedvoerig','breedvoerigheid','breefok','breek','breekal','breekbaar','breekbaarheid','breekbeitel','breekgeld','breekijzer','breekijzerfunctie','breekpen','breekpercentage','breekpunt','breeks','breekschade','breeksterkte','breekwerf','breekwerk','breeuwen','breeuwhamer','breeuwijzer','breeuwwerk','breezer','brei','breidel','breidelen','breideling','breidelloos','breien','breier','breigaren','breigoed','breikatoen','breikous','breimachine','brein','breinaald','breinbreker','breipatroon','breipen','breipriem','breischool','breisel','breister','breiwerk','breiwerkje','breiwol','brekebeen','breken','breker','breking','brekingshoek','brekingsindex','brem','bremraap','brems','bremstruik','bremze','bremzout','bren','brengen','brenger','brengservice','bres','bressen','bretel','bretels','breuk','breukband','breukbelasting','breukdeel','breukdelen','breukgedeelte','breukje','breuklijn','breukoperatie','breukpunt','breukspanning','breuksplitsing','breuksteen','breukstreep','breukvastheid','breukvlak','breukzone','breve','brevet','brevetteren','breviarium','breviatuur','brevier','brevieren','breedlachend','breedteniveau','breakdansen','breedbandpenetratie','breekmes','breedbandaansluiting','brekingsverhouding','breakpunt','breedbandinfrastructuur','breedbandmarkt','breedbandtoegang','breedbeeldformaat','breedtemaat','breedterichting','brekingsafwijking','breukregister','breedbandgebruik','breukzak','breedtesportimpuls','breekplaat','breekinstallatie','breedbandmodem','breekhout','breinbaas','breintrainer','bremraapfamilie','brecht','breda','bredaas','bredanaar','bredaenaar','bredaer','bredenaar','bredene','bredens','brederwiede','bree','breendonk','brees','breeenaar','breeernaar','bremen','brenda','brennerpas','breton','breugel','breukelaar','breukelen','breukels','breel','breeuwer','bremer','brederode','breedveld','breukink','breughel','brekelmans','breman','breuker','breukhoven','breij','brentjens','bredero','brechje','brechtje','bregje','bregt','brendan','brennan','brent','brett','bremmer','breeman','breure','breen','breed','breedijk','breemen','breet','bregman','bresser','breteler','breur','breuer','breevaart','breugem','breebaart','breukel','breetveld','breunesse','breddels','breeuwsma','breeveld','breg','brehler','breijer','breimer','brenkman','brenters','breukelman','bredius','bredewoud','breeuwer','brendel','breemer','bredewout','breems','breuls','brethouwer','bredewold','breevoort','brehm','breider','breunissen','breden','brederveld','breekveldt','brekveld','bretveld','breunis','bredenhoff','brewster','brederoo','breel','breidel','bretoenen','bretoense','bretonse','brede','breder','bredere','breedbanddiensten','breedbandige','breedbandnetwerken','breedbandverbindingen','breedbeeldtelevisies','breedbladige','breeddenkende','breedgebouwde','breedgerande','breedgeschouderde','breedgrijnzende','breedlachende','breedsprakige','breedsprakiger','breedst','breedste','breedtecirkels','breedtegraden','breedten','breedtes','breedvoerige','breedvoeriger','breedvoerigst','breekbaarder','breekbaarst','breekbare','breekbeitels','breekijzers','breekmesje','breekpennen','breekpunten','breekt','breeuw','breeuwers','breeuwhamers','breeuwijzers','breeuwt','breid','breidde','breidden','breide','breidelde','breidelloze','breidels','breidelt','breiden','breidt','breiend','breikousen','breimachines','breimandje','breinaalden','breinen','breipatronen','breipennen','breipriemen','breischolen','breisters','breistertje','breit','breiwerken','brekebenen','brekers','brekingen','brekingshoeken','bremrapen','bremstruiken','bremzen','bremzoute','breng','brengend','brengende','brengers','brengt','bretellen','breukbanden','breuken','breukoperaties','breukstenen','breven','brevetteerde','brevetteert','brevetten','breviaria','brevierde','brevierden','breviert','breakbeats','breakdancet','breakdancete','breakdowns','breakpoints','breaks','breedtepasses','breekwerven','breeuwde','breezers','breiende','breinbrekers','breisels','brekend','brekende','breuklijnen','breukstrepen','breukvlakken','breviariums','breviaturen','breidelloost','breidellozer','breviertje','breukzones','breakdanste','breedstralers','breukpunten','bredase','brechjes','brechts','brechtjes','bregjes','bregts','brendas','brendans','brennans','brents','bretts','breedbandaansluitingen','breakpunten','breedtematen','brekingsafwijkingen','breukjes','breekbaars','breekplaten','breedbeeldschermen','breekinstallaties','breedbandmarkten','brekingsindexen','breekpennetjes','breekmesjes','brechtse','breese'}
---@class TranslatedString local TranslatedString = LeaderLib.Classes["TranslatedString"] local function sortupgrades(a,b) return a:upper() < b:upper() end local upgradeInfoEntryColorText = TranslatedString:Create("ha4587526ge140g42f9g9a98gc92b537d4209", "<font color='[2]' size='18'>[1]</font>") local upgradeInfoEntryColorlessText = TranslatedString:Create("h869a7616gfbb7g4cc2ga233g7c22612af67b", "<font size='18'>[1]</font>") ---@param character EsvCharacter local function GetUpgradeInfoText(character, isControllerMode) if Ext.IsDeveloperMode() then HighestLoremaster = 10 end if HighestLoremaster == nil or HighestLoremaster == 0 then pcall(function() if LeaderLib.UI.ClientCharacter ~= nil then local clientChar = Ext.GetCharacter(LeaderLib.UI.ClientCharacter) if clientChar ~= nil and clientChar.Stats.Loremaster > 0 then HighestLoremaster = clientChar.Stats.Loremaster end end end) end local upgradeKeys = {} for status,data in pairs(UpgradeData.Statuses) do if character:GetStatus(status) ~= nil then table.insert(upgradeKeys, status) end end local count = #upgradeKeys if count > 0 then table.sort(upgradeKeys, sortupgrades) local output = "<img src='Icon_Line' width='350%'><br>" if isControllerMode == true then output = "" -- No Icon_Line end local i = 0 for _,status in ipairs(upgradeKeys) do local infoText = UpgradeInfo_GetText(status) if infoText ~= nil then local color = infoText.Color if HighestLoremaster > 0 then ---@type TranslatedString local translatedString = infoText.Name if translatedString ~= nil then local nameText = translatedString.Value if infoText.Lore > 0 and HighestLoremaster < infoText.Lore then nameText = "???" end if color ~= nil and color ~= "" then local text = string.gsub(upgradeInfoEntryColorText.Value, "%[1%]", nameText):gsub("%[2%]", color) if isControllerMode ~= true then text = "<img src='Icon_BulletPoint'>"..text end output = output..text else if isControllerMode ~= true then output = output.."<img src='Icon_BulletPoint'>"..string.gsub(upgradeInfoEntryColorlessText.Value, "%[1%]", nameText) else output = output..string.gsub(upgradeInfoEntryColorlessText.Value, "%[1%]", nameText) end end end else if color ~= nil and color ~= "" then local text = string.gsub(upgradeInfoEntryColorText.Value, "%[1%]", "???"):gsub("%[2%]", color) if isControllerMode ~= true then text = "<img src='Icon_BulletPoint'>"..text end output = output..text else if isControllerMode ~= true then output = output.."<img src='Icon_BulletPoint'>"..string.gsub(upgradeInfoEntryColorlessText.Value, "%[1%]", "???") else output = output..string.gsub(upgradeInfoEntryColorlessText.Value, "%[1%]", "???") end end end if i < count - 1 then output = output.."<br>" end end i = i + 1 end --LeaderLib.PrintDebug("[EnemyUpgradeOverhaul:LLENEMY_DescriptionParams.lua] Upgrade info for (" .. uuid .. ") is nil or empty ("..LeaderLib.Common.Dump(data)..")") --LeaderLib.PrintDebug("Upgrade info (".. tostring(uuid)..") = ("..output..")") return output end return "" end ---@param character EsvCharacter local function GetChallengePointsText(character, isControllerMode) local output = "<img src='Icon_Line' width='350%'><br>" if isControllerMode == true then output = "" -- No Icon_Line end local isTagged = false for k,tbl in pairs(ChallengePointsText) do if character:HasTag(tbl.Tag) then if HighestLoremaster >= 2 then if character:GetStatus("LLENEMY_DUPLICANT") == nil then output = output .. string.gsub(DropText.Value, "%[1%]", tbl.Text.Value) else output = output .. string.gsub(ShadowDropText.Value, "%[1%]", tbl.Text.Value) end else if character:GetStatus("LLENEMY_DUPLICANT") == nil then output = output .. HiddenDropText.Value else output = output .. HiddenShadowDropText.Value end end isTagged = true end end --LeaderLib.PrintDebug("CP Tooltip | Name("..tostring(character.Name)..") NetID(".. tostring(character.NetID)..") character.Stats.NetID("..tostring(Ext.GetCharacter(character.NetID).Stats.NetID)..")") --LeaderLib.PrintDebug("Tags: " .. LeaderLib.Common.Dump(character:GetTags())) -- if statusSource ~= nil then -- LeaderLib.PrintDebug("CP Tooltip | Source Name("..tostring(statusSource.Name)..") NetID(".. tostring(statusSource.NetID)..") character.Stats.NetID("..tostring(Ext.GetCharacter(statusSource.NetID).Stats.NetID)..")") -- LeaderLib.PrintDebug("Tags: " .. LeaderLib.Common.Dump(statusSource:GetTags())) -- end -- if data.isDuplicant == true then -- output = output .. "<br><font color='#65C900' size='14'>Grants no experience, but drops guaranteed loot.</font>" -- end if isTagged then return output end return "" end return { GetUpgradeInfoText = GetUpgradeInfoText, GetChallengePointsText = GetChallengePointsText }
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] --- -- read_query() can rewrite packets -- -- You can use read_query() to replace the packet sent by the client and rewrite -- query as you like -- -- @param packet the mysql-packet sent by the client -- -- @return -- * nothing to pass on the packet as is, -- * proxy.PROXY_SEND_QUERY to send the queries from the proxy.queries queue -- * proxy.PROXY_SEND_RESULT to send your own result-set -- function read_query( packet ) if string.byte(packet) == proxy.COM_QUERY then local query = string.sub(packet, 2) print("we got a normal query: " .. query) -- try to match the string up to the first non-alphanum local f_s, f_e, command = string.find(packet, "^%s*(%w+)", 2) local option if f_e then -- if that match, take the next sub-string as option f_s, f_e, option = string.find(packet, "^%s+(%w+)", f_e + 1) end -- support -- -- ls [db] -- cd db -- who if command == "ls" then if option then -- FIXME: SQL INJECTION proxy.queries:append(1, string.char(proxy.COM_QUERY) .. "SHOW TABLES FROM " .. option ) else proxy.queries:append(1, string.char(proxy.COM_QUERY) .. "SHOW TABLES" ) end return proxy.PROXY_SEND_QUERY elseif command == "who" then proxy.queries:append(1, string.char(proxy.COM_QUERY) .. "SHOW PROCESSLIST" ) return proxy.PROXY_SEND_QUERY elseif command == "cd" and option then proxy.queries:append(1, string.char(proxy.COM_INIT_DB) .. option ) return proxy.PROXY_SEND_QUERY end end end --- -- read_query_result() is called when we receive a query result -- from the server -- -- we can analyze the response, drop the response and pass it on (default) -- -- @return -- * nothing or proxy.PROXY_SEND_RESULT to pass the result-set to the client -- * proxy.PROXY_IGNORE_RESULT to drop the result-set -- -- @note: the function has to exist in 0.5.0 if proxy.PROXY_SEND_QUERY -- got used in read_query() -- function read_query_result(inj) end
-- Light minetest.register_node("tardis:light_wall", { description = "Tardis Wall (non-craftable)", tiles = {"tardis_wall.png"}, diggable = false, groups = {not_in_creative_inventory = 1}, }) minetest.register_node("tardis:light_wall_craftable", { description = "Tardis Wall", tiles = {"tardis_wall.png"}, groups = {oddly_breakable_by_hand = 1}, }) -- Dark minetest.register_node("tardis:dark_wall", { description = "Tardis Wall (non-craftable)", tiles = {"tardis_wall_dark.png"}, diggable = false, groups = {not_in_creative_inventory = 1}, }) minetest.register_node("tardis:dark_wall_craftable", { description = "Tardis Wall", tiles = {"tardis_wall_dark.png"}, groups = {oddly_breakable_by_hand = 1}, })
local function create( ... ) local tFns = table.pack(...) local tCos = {} for i = 1, tFns.n, 1 do local fn = tFns[i] if type( fn ) ~= "function" then error( "bad argument #" .. i .. " (expected function, got " .. type( fn ) .. ")", 3 ) end tCos[i] = coroutine.create(fn) end return tCos end local function runUntilLimit( _routines, _limit ) local count = #_routines local living = count local tFilters = {} local eventData = { n = 0 } while true do for n=1,count do local r = _routines[n] if r then if tFilters[r] == nil or tFilters[r] == eventData[1] or eventData[1] == "terminate" then local ok, param = coroutine.resume( r, table.unpack( eventData, 1, eventData.n ) ) if not ok then error( param, 0 ) else tFilters[r] = param end if coroutine.status( r ) == "dead" then _routines[n] = nil living = living - 1 if living <= _limit then return n end end end end end for n=1,count do local r = _routines[n] if r and coroutine.status( r ) == "dead" then _routines[n] = nil living = living - 1 if living <= _limit then return n end end end eventData = table.pack( os.pullEventRaw() ) end end function waitForAny( ... ) local routines = create( ... ) return runUntilLimit( routines, #routines - 1 ) end function waitForAll( ... ) local routines = create( ... ) runUntilLimit( routines, 0 ) end
iron_claw_rear_up = class({}) LinkLuaModifier( 'iron_claw_rear_up_modifier', 'encounters/iron_claw/iron_claw_rear_up_modifier', LUA_MODIFIER_MOTION_NONE ) function iron_claw_rear_up:OnSpellStart() --- Get Caster, Victim, Player, Point --- local caster = self:GetCaster() local caster_loc = caster:GetAbsOrigin() local playerID = caster:GetPlayerOwnerID() local player = PlayerResource:GetPlayer(playerID) local team = caster:GetTeamNumber() local victim = caster local victim_loc = victim:GetAbsOrigin() --- Get Special Values --- local duration = self:GetSpecialValueFor("duration") local delay = self:GetSpecialValueFor("delay") caster:AddNewModifier(caster, self, "casting_rooted_modifier", {duration=delay*2}) DisableMotionControllers(caster, delay*2) EncounterUnitWarning(caster, 1.0, true, nil) --nil=yellow, "red", "orange", "green" -- Sound -- caster:EmitSound("Hero_LoneDruid.BattleCry.Bear") -- Animation -- caster:StartGestureWithPlaybackRate(ACT_DOTA_IDLE_RARE, 0.8) local timer = Timers:CreateTimer(delay, function() local resting_mod = caster:FindModifierByName("iron_claw_iron_hide_resting_modifier") if resting_mod ~= nil then return end -- Sound -- caster:EmitSound("Hero_LoneDruid.SavageRoar.Cast") -- Particle -- local particle = ParticleManager:CreateParticle("particles/units/heroes/hero_lone_druid/lone_druid_savage_roar.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:SetParticleControl( particle, 0, caster:GetAbsOrigin() ) ParticleManager:SetParticleControl( particle, 1, caster:GetAbsOrigin() ) ParticleManager:ReleaseParticleIndex( particle ) particle = nil for _,hero in pairs( GetHeroesAliveEntities() ) do local fear_angle = 150 local hero_angle = hero:GetAnglesAsVector().y local origin_difference = hero:GetAbsOrigin() - caster_loc local origin_difference_radian = math.atan2(origin_difference.y, origin_difference.x) origin_difference_radian = origin_difference_radian * 180 local caster_angle = origin_difference_radian / math.pi caster_angle = caster_angle + 180.0 local result_angle = caster_angle - hero_angle result_angle = math.abs(result_angle) local forward = hero:GetForwardVector() if ( result_angle >= 0 and result_angle <= (fear_angle / 2) ) or ( result_angle >= (360 - (fear_angle / 2)) and result_angle <= 360 ) then -- Modifier -- local modifier = hero:AddNewModifier(caster, self, "iron_claw_rear_up_modifier", {duration = duration}) PersistentModifier_Add(modifier) end end end) PersistentTimer_Add(timer) end function iron_claw_rear_up:OnAbilityPhaseStart() local caster = self:GetCaster() local playerID = caster:GetPlayerOwnerID() local player = PlayerResource:GetPlayer(playerID) return true end function iron_claw_rear_up:GetManaCost(abilitylevel) return self.BaseClass.GetManaCost(self, abilitylevel) end function iron_claw_rear_up:GetCooldown(abilitylevel) return self.BaseClass.GetCooldown(self, abilitylevel) end
-- This file is subject to copyright - contact [email protected] for more information. if (SERVER) then util.AddNetworkString("player_equip_item") util.AddNetworkString("player_pony_cm_send") --util.AddNetworkString( "player_pony_set_charpars" ) net.Receive("player_equip_item", function(len, ply) local id = net.ReadFloat() local item = PPM:pi_GetItemById(id) if (item ~= nil) then PPM.setupPony(ply, false) PPM:pi_SetupItem(item, ply) end end) function HOOK_PlayerLeaveVehicle(ply, ent) --if(table.HasValue(ponyarray_temp,ply:GetInfo( "cl_playermodel" ))) then if ply:IsPPMPony() then if ply.ponydata ~= nil and IsValid(ply.ponydata.clothes1) then local bdata = {} for i = 0, 14 do bdata[i] = ply.ponydata.clothes1:GetBodygroup(i) ply.ponydata.clothes1:SetBodygroup(i, 0) end timer.Simple(0.2, function() if ply.ponydata ~= nil and IsValid(ply.ponydata.clothes1) then for i = 0, 14 do ply.ponydata.clothes1:SetBodygroup(i, bdata[i]) end end end) end end end ponyarray_temp = {"pony", "ponynj"} PPM.camoffcetenabled = CreateConVar("ppm_enable_camerashift", "1", {FCVAR_REPLICATED, FCVAR_ARCHIVE}, "Enables ViewOffset Setup") hook.Add("PlayerLeaveVehicle", "pony_fixclothes", HOOK_PlayerLeaveVehicle) end
AddCSLuaFile( "cl_init.lua" ) -- Make sure clientside AddCSLuaFile( "shared.lua" ) -- and shared scripts are sent. include('shared.lua') local Length = 4 local Width = 1 local Height = 1 local MaxHealth = 300 local Constraintable = true ENT.OurHealth = MaxHealth function Connector() end function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) -- Make us work with physics, self:SetMoveType( MOVETYPE_VPHYSICS ) -- after all, gmod is a physics self:SetSolid( SOLID_VPHYSICS ) -- Toolbox local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() end --self:EmitSound("weapon_effects/rocket_fire.wav") end function Connector(self) if (Constraintable == true) then print("Checking for neighbors") local constrainttrace = util.QuickTrace(self:GetPos(), self:LocalToWorld(Vector(0,0,100)), self) print(constrainttrace.Entity) if(constrainttrace.Entity:IsValid()) then constraint.Weld(self.Entity, constrainttrace.Entity, 0, 0, 0, true, false) print("WE FOUND SOMETHING!") end end end function ENT:Use( activator, caller ) return end function ENT:Think() end local function SelfExplode(self) local explosion = ents.Create( "env_explosion" ) explosion:SetPos(self:GetPos()) explosion:SetOwner(self) explosion:SetKeyValue("spawnflags", 64) explosion:Spawn() explosion:SetKeyValue("iMagnitude", "100") explosion:Fire( "Explode", 0, 0) explosion:EmitSound("weapon_effects/rocket_explode.wav", 400, 100) end function ENT:PhysicsCollide( touchdata, toucherobj ) end function ENT:OnTakeDamage(dmg) if(self.Entity.OurHealth < (MaxHealth * 0.9)) then Constraintable = false if(self.Entity:GetPhysicsObject():IsMoveable() == false) then self.Entity:GetPhysicsObject():EnableMotion(true) end end if(self.Entity.OurHealth < (MaxHealth * 0.50)) then constraint.RemoveAll(self.Entity) end self.Entity:TakePhysicsDamage(dmg) if(self.Entity.OurHealth <= 0) then return end self.Entity.OurHealth = self.Entity.OurHealth - dmg:GetDamage() if(self.Entity.OurHealth <= 0) then self.Entity:Remove() end end
--[[function list_iter (t) local i = 0 local n = table.getn(t) return function() i = i + 1 if i <= n then return t[i] end end end --]] --[[t = {10,20,30} iter = list_iter(t) while true do local element = iter() if element == nil then break end print(element) end --]] --[[t = {10,20,30} for element in list_iter(t) do print(element) end function allwords() local line = io.read() local pos = 1 return function() while line do local s,e = string.find(line,"%w+",pos) if s then pos = e + 1 return string.sub(line,s,e) else line = io.read() pos = 1 end end return nil end end --]] a = {"one","two","three"} for i, v in ipairs(a) do print(i,v) end function iter (a, i) i = i + 1 local v = a[i] if v then return i, v end end function ipairs (a) return iter, a, 0 end function pairs(t) return next, t, nil end local iterator function allwords() local state = {line = io.read(),pos = 1} return iterator, state end function allwords (f) for l in io.lines () do for w in string.gfind(l,"%w+") do f(w) end end end allwords(print) local count = 0 allwords(function (w) if w == "hello" then count = count + 1 end end ) print(count) local count = 0 for w in allwords() do if w == "hello" then count = count + 1 end end print(count)
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- Copyright (C) 2014 Daurnimator -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza"; local valid_roles = { "none", "visitor", "participant", "moderator" }; local default_broadcast = { visitor = true; participant = true; moderator = true; }; local function get_presence_broadcast(room) return room._data.presence_broadcast or default_broadcast; end local function set_presence_broadcast(room, broadcast_roles) broadcast_roles = broadcast_roles or default_broadcast; local changed = false; local old_broadcast_roles = get_presence_broadcast(room); for _, role in ipairs(valid_roles) do if old_broadcast_roles[role] ~= broadcast_roles[role] then changed = true; end end if not changed then return false; end room._data.presence_broadcast = broadcast_roles; for _, occupant in room:each_occupant() do local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";}); local role = occupant.role or "none"; if broadcast_roles[role] and not old_broadcast_roles[role] then -- Presence broadcast is now enabled, so announce existing user room:publicise_occupant_status(occupant, x); elseif old_broadcast_roles[role] and not broadcast_roles[role] then -- Presence broadcast is now disabled, so mark existing user as unavailable room:publicise_occupant_status(occupant, x, nil, nil, nil, nil, true); end end return true; end module:hook("muc-config-form", function(event) local values = {}; for role, value in pairs(get_presence_broadcast(event.room)) do if value then values[#values + 1] = role; end end table.insert(event.form, { name = "muc#roomconfig_presencebroadcast"; type = "list-multi"; label = "Only show participants with roles:"; value = values; options = valid_roles; }); end, 70-7); module:hook("muc-config-submitted/muc#roomconfig_presencebroadcast", function(event) local broadcast_roles = {}; for _, role in ipairs(event.value) do broadcast_roles[role] = true; end if set_presence_broadcast(event.room, broadcast_roles) then event.status_codes["104"] = true; end end); return { get = get_presence_broadcast; set = set_presence_broadcast; };
-- Expertcoder2 -- Created: 26/03/2021 -- Updated: 28/03/2021 client = nil service = nil return function(data) local window = client.UI.Make("Window",{ Name = "OnlineFriends"; Title = "Online Friends"; Size = {390, 320}; MinSize = {180, 120}; AllowMultiple = false; }) do local function locationTypeToStr(int) return ({ [0] = "Mobile Website"; [1] = "Mobile InGame"; [2] = "Webpage"; [3] = "Studio"; [4] = "InGame"; [5] = "Xbox"; [6] = "Team Create"; })[int] end; local friendDictionary = game:GetService("Players").LocalPlayer:GetFriendsOnline() local sortedFriends = {} local friendInfo = {} for _, item in pairs(friendDictionary) do table.insert(sortedFriends, item.UserName) friendInfo[item.UserName] = {id=item.VisitorId;displayName=item.DisplayName;lastLocation=item.LastLocation;locationType=item.LocationType;} end table.sort(sortedFriends) local i = 1 local friendCount = 0 for _, friendName in ipairs(sortedFriends) do friendCount = friendCount + 1 local entryText = "" if friendName == friendInfo[friendName].displayName then entryText = friendName else entryText = friendInfo[friendName].displayName.." (@"..friendName..")" end local entry = window:Add("TextLabel", { Text = " "..entryText; ToolTip = "Location: "..friendInfo[friendName].lastLocation; BackgroundTransparency = (i%2 == 0 and 0) or 0.2; Size = UDim2.new(1, -10, 0, 30); Position = UDim2.new(0, 5, 0, (30*(i-1))+5); TextXAlignment = "Left"; }) entry:Add("TextLabel", { Text = " "..locationTypeToStr(friendInfo[friendName].locationType).." "; BackgroundTransparency = 1; Size = UDim2.new(0, 120, 1, 0); Position = UDim2.new(1, -120, 0, 0); TextXAlignment = "Right"; }) spawn(function() entry:Add("ImageLabel", { Image = game:GetService("Players"):GetUserThumbnailAsync(friendInfo[friendName].id, Enum.ThumbnailType.HeadShot, Enum.ThumbnailSize.Size420x420); BackgroundTransparency = 1; Size = UDim2.new(0, 30, 0, 30); Position = UDim2.new(0, 0, 0, 0); }) end) i = i + 1 end window:SetTitle("Online Friends ("..friendCount..")") end window:ResizeCanvas(false, true, false, false, 5, 5) window:Ready() end
--[[ @Description This is the base component that all other components can be derived from. @Interface [table] new([table] self, [varArg?] properties) This clones the table and intializes it. [table] extend([table] self) [nil] destroy([table] self) Calls self.maid:cleanUp() by default. [nil] redraw() Implement this function when you extend this component! By default, it is a noop function. [nil] init([table] self, [varArg?] properties) Preferably implement this function when you extend this component! By default, it is not implemented at all nor does it need to be. --]] local simState = require("./simState.lua") local maid = require("./maid.lua") local baseObj = require("./baseObj.lua") local noop = function() end return baseObj:extend { destroy = function(self) --[[ @Description Cleans up object with maid. @Parameters [table] self Object @Returns nil ]] self.maid:cleanAll() end, setState = function(self, ...) self.state:set(...) end, new = function(self, ...) --[[ @Description Builds a new UI element based off the given object. @Parameters [table] self Object [varArg?] properties This is where the user can pass in properties to 'init' if it does exist. @Returns [table] newObject --]] local newObject = self:extend() newObject.maid = maid:new() newObject.state = simState:new() if newObject.init then newObject:init(...) end newObject.maid:addTask( newObject.state:hook(function(oldState, newState) if oldState == newState then return end newObject:redraw() end) ) newObject:redraw() return newObject end, }
local box = require("box") local json = require("json") local log = require("log") local os = require("os") local fiber = require('fiber') local tnt_kafka = require('kafka') local consumer = nil local errors = {} local logs = {} local rebalances = {} local function create(brokers, additional_opts) local err errors = {} logs = {} rebalances = {} local error_callback = function(err) log.error("got error: %s", err) table.insert(errors, err) end local log_callback = function(fac, str, level) log.info("got log: %d - %s - %s", level, fac, str) table.insert(logs, string.format("got log: %d - %s - %s", level, fac, str)) end local rebalance_callback = function(msg) log.info("got rebalance msg: %s", json.encode(msg)) table.insert(rebalances, msg) end local options = { ["enable.auto.offset.store"] = "false", ["group.id"] = "test_consumer", ["auto.offset.reset"] = "earliest", ["enable.partition.eof"] = "false", ["log_level"] = "7", } if additional_opts ~= nil then for key, value in pairs(additional_opts) do options[key] = value end end consumer, err = tnt_kafka.Consumer.create({ brokers = brokers, options = options, error_callback = error_callback, log_callback = log_callback, rebalance_callback = rebalance_callback, default_topic_options = { ["auto.offset.reset"] = "earliest", }, }) if err ~= nil then log.error("got err %s", err) box.error{code = 500, reason = err} end log.info("consumer created") end local function subscribe(topics) log.info("consumer subscribing") log.info(topics) local err = consumer:subscribe(topics) if err ~= nil then log.error("got err %s", err) box.error{code = 500, reason = err} end log.info("consumer subscribed") end local function unsubscribe(topics) log.info("consumer unsubscribing") log.info(topics) local err = consumer:unsubscribe(topics) if err ~= nil then log.error("got err %s", err) box.error{code = 500, reason = err} end log.info("consumer unsubscribed") end local function consume(timeout) log.info("consume called") local consumed = {} local f = fiber.create(function() local out = consumer:output() while true do if out:is_closed() then break end local msg = out:get() if msg ~= nil then log.info(msg) log.info("got msg with topic='%s' partition='%d' offset='%d' key='%s' value='%s'", msg:topic(), msg:partition(), msg:offset(), msg:key(), msg:value()) table.insert(consumed, msg:value()) local err = consumer:store_offset(msg) if err ~= nil then log.error("got error '%s' while commiting msg from topic '%s'", err, msg:topic()) end end end end) log.info("consume wait") fiber.sleep(timeout) log.info("consume ends") f:cancel() return consumed end local function get_errors() return errors end local function get_logs() return logs end local function get_rebalances() return rebalances end local function close() log.info("closing consumer") local exists, err = consumer:close() if err ~= nil then log.error("got err %s", err) box.error{code = 500, reason = err} end log.info("consumer closed") end return { create = create, subscribe = subscribe, unsubscribe = unsubscribe, consume = consume, close = close, get_errors = get_errors, get_logs = get_logs, get_rebalances = get_rebalances, }
--[[ death_messages - A Minetest mod which sends a chat message when a player dies. Copyright (C) 2016 EvergreenTree This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] --Carbone death coords --License of media (textures and sounds) From carbone subgame -------------------------------------- --mods/default/sounds/player_death.ogg: from OpenArena – GNU GPL v2. ----------------------------------------------------------------------------------------------- local title = "Death Messages" local version = "0.1.2" local mname = "death_messages" ----------------------------------------------------------------------------------------------- dofile(minetest.get_modpath("death_messages").."/settings.txt") ----------------------------------------------------------------------------------------------- -- A table of quips for death messages. The first item in each sub table is the -- default message used when RANDOM_MESSAGES is disabled. local messages = {} -- Toxic death messages messages.toxic = { " melted into a ball of radioactivity.", " thought chemical waste was cool.", " melted into a jittering pile of flesh.", " couldn't resist that warm glow of toxic water.", " dug straight down.", " went into the toxic curtain.", " thought it was a toxic-tub.", " is radioactive.", " didn't know toxic water was radioactive." } -- Lava death messages messages.lava = { " melted into a ball of fire.", " thought lava was cool.", " melted into a ball of fire.", " couldn't resist that warm glow of lava.", " dug straight down.", " went into the lava curtain.", " thought it was a hottub.", " is melted.", " didn't know lava was hot." } -- Drowning death messages messages.water = { " drowned.", " ran out of air.", " failed at swimming lessons.", " tried to impersonate an anchor.", " forgot he wasn't a fish.", " blew one too many bubbles.", } -- Burning death messages messages.fire = { " burned to a crisp.", " got a little too warm.", " got too close to the camp fire.", " just got roasted, hotdog style.", " got burned up. More light that way." } -- Other death messages messages.other = { " died.", " did something fatal.", " gave up on life.", " is somewhat dead now.", " passed out -permanently.", " kinda screwed up.", " couldn't fight very well.", " got 0wn3d.", " got SMOKED.", " got hurted by Oerkki.", " got blowed up." } -- PVP Messages messages.pvp = { " fisted", " sliced up", " rekt", " punched", " hacked", " skewered", " blasted", " tickled", " gotten", " sword checked", " turned into a jittering pile of flesh", " buried", " served", " poked", " attacked viciously", " busted up", " schooled", " told", " learned", " chopped up", " deader than ded ded ded", " CHOSEN to be the ONE", " all kinds of messed up", " smoked like a Newport", " hurted", " ballistic-ed", " jostled", " messed-da-frig-up", " lanced", " shot", " knocked da heck out", " pooped on" } -- Player Messages messages.player = { " for talking smack about thier mother.", " for cheating at Tic-Tac-Toe.", " for being a stinky poop butt.", " for letting Baggins grief.", " because it felt like the right thing to do.", " for spilling milk.", " for wearing a n00b skin.", " for not being good at PVP.", " because they are a n00b.", " for reasons uncertain.", " for using a tablet.", " with the quickness.", " while texting." } -- MOB After Messages messages.mobs = { " and was eaten with a gurgling growl.", " then was cooked for dinner.", " then went to the supermarket.", " badly.", " terribly.", " horribly.", " in a haphazard way.", " that sparkles in the twilight with that evil grin.", " and now is covered by blood.", " so swiftly, that not even Chuck Norris could block.", " for talking smack about Oerkkii's mother.", " and grimmaced wryly." } function get_message(mtype) if RANDOM_MESSAGES then return messages[mtype][math.random(1, #messages[mtype])] else return messages[1] -- 1 is the index for the non-random message end end minetest.register_on_dieplayer(function(player) local player_name = player:get_player_name() local node = minetest.registered_nodes[minetest.get_node(player:getpos()).name] local pos = player:getpos() local death = {x=0, y=23, z=-1.5} minetest.sound_play("player_death", {pos = pos, gain = 1}) pos.x = math.floor(pos.x + 0.5) pos.y = math.floor(pos.y + 0.5) pos.z = math.floor(pos.z + 0.5) local param2 = minetest.dir_to_facedir(player:get_look_dir()) local player_name = player:get_player_name() if minetest.is_singleplayer() then player_name = "You" end -- Death by lava if node.name == "default:lava_source" then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("lava")) --player:setpos(death) elseif node.name == "default:lava_flowing" then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("lava")) --player:setpos(death) -- Death by drowning elseif player:get_breath() == 0 then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("water")) --player:setpos(death) -- Death by fire elseif node.name == "fire:basic_flame" then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("fire")) --player:setpos(death) -- Death by Toxic water elseif node.name == "es:toxic_water_source" then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("toxic")) --player:setpos(death) elseif node.name == "es:toxic_water_flowing" then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("toxic")) --player:setpos(death) elseif node.name == "groups:radioactive" then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player_name .. string.char(0x1b).."(c@#ff0000)"..get_message("toxic")) --player:setpos(death) -- Death by something else else --minetest.chat_send_all( --string.char(0x1b).."(c@#ffffff)"..player_name .. --string.char(0x1b).."(c@#ff0000)"..get_message("other")) --toospammy --minetest.after(0.5, function(holding) --player:setpos(death) --gamebreaker? --end) end --minetest.chat_send_all(string.char(0x1b).."(c@#000000)".."[DEATH COORDINATES] "..string.char(0x1b).."(c@#ffffff)" .. player_name .. string.char(0x1b).."(c@#000000)".." left a corpse full of diamonds here: " .. --minetest.pos_to_string(pos) .. string.char(0x1b).."(c@#aaaaaa)".." Come and get them!") --player:setpos(death) --minetest.sound_play("pacmine_death", { gain = 0.35}) NOPE!!! end) --bigfoot code -- bigfoot547's death messages -- hacked by maikerumine -- get tool/item when hitting get_name() returns item name (e.g. "default:stone") minetest.register_on_punchplayer(function(player, hitter) local pos = player:getpos() local death = {x=0, y=23, z=-1.5} if not (player or hitter) then return false end if not hitter:get_player_name() == "" then return false end minetest.after(0, function(holding) if player:get_hp() == 0 and hitter:get_player_name() ~= "" and holding == hitter:get_wielded_item() ~= "" then local holding = hitter:get_wielded_item() if holding:to_string() ~= "" then local weap = holding:get_name(holding:get_name()) if holding then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player:get_player_name().. string.char(0x1b).."(c@#ff0000)".." was".. string.char(0x1b).."(c@#ff0000)"..get_message("pvp").. string.char(0x1b).."(c@#ff0000)".." by ".. string.char(0x1b).."(c@#00CED1)"..hitter:get_player_name().. string.char(0x1b).."(c@#ffffff)".." with ".. string.char(0x1b).."(c@#FF8C00)"..weap.. string.char(0x1b).."(c@#00bbff)"..get_message("player")) --TODO: make custom mob death messages end end if player=="" or hitter=="" then return end -- no killers/victims return true elseif hitter:get_player_name() == "" and player:get_hp() == 0 then minetest.chat_send_all( string.char(0x1b).."(c@#00CED1)"..player:get_player_name().. string.char(0x1b).."(c@#ff0000)".." was".. string.char(0x1b).."(c@#ff0000)"..get_message("pvp").. string.char(0x1b).."(c@#ff0000)".." by ".. string.char(0x1b).."(c@#FF8C00)"..hitter:get_luaentity().name.. --too many mobs add to crash string.char(0x1b).."(c@#00bbff)"..get_message("mobs")) --TODO: make custom mob death messages if player=="" or hitter=="" or hitter=="*" then return end -- no mob killers/victims else return false end end) end) ----------------------------------------------------------------------------------------------- print("[Mod] "..title.." ["..version.."] ["..mname.."] Loaded...") -----------------------------------------------------------------------------------------------
--local Attrs = GetFileConfig(OUTPUTBASE.."server/setting/hero_attribute.lua").ConstInfo["人物职业"] return function(Data) local RetTbl = {} local List = Split(Data, "|") for _,Value in ipairs(List) do --assert(Attrs[Value], "在人物属性表中找不到".. Value .. "这个职业") table.insert(RetTbl, Value) end return RetTbl end
local a = require("plenary.async").tests local Path = require("plenary.path") local debug = require("refactoring.debug") local scandir = require("plenary.scandir") local utils = require("refactoring.utils") local test_utils = require("refactoring.tests.utils") local async = require("plenary.async") local Config = require("refactoring.config") local cwd = vim.loop.cwd() vim.cmd("set rtp+=" .. cwd) local eq = assert.are.same local function remove_cwd(file) return file:sub(#cwd + 2 + #"lua/refactoring/tests/") end -- TODO: Move this to utils local function for_each_file(cb) local files = scandir.scan_dir( Path:new(cwd, "lua", "refactoring", "tests", "debug"):absolute() ) for _, file in pairs(files) do file = remove_cwd(file) if string.match(file, "start") then cb(file) end end end describe("Debug", function() for_each_file(function(file) a.it(string.format("printf: %s", file), function() local parts = utils.split_string(file, "%.") local filename_prefix = parts[1] local filename_extension = parts[3] local bufnr = test_utils.open_test_file(file) local expected = test_utils.get_contents( string.format( "%s.expected.%s", filename_prefix, filename_extension ) ) test_utils.run_inputs_if_exist(filename_prefix, cwd) test_utils.run_commands(filename_prefix) Config.get():set_test_bufnr(bufnr) debug["printf"]({}) async.util.scheduler() local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false) eq(expected, lines) end) end) end)
object_mobile_dressed_tatooine_opening_reimos = object_mobile_shared_dressed_tatooine_opening_reimos:new { } ObjectTemplates:addTemplate(object_mobile_dressed_tatooine_opening_reimos, "object/mobile/dressed_tatooine_opening_reimos.iff")
--[[ Nodes in the `combustable` group will sometimes spotaneously combust when exposed to `air` A node can define a `on_combust(pos :: vector, node :: NodeDef) :: boolean` callback to handle the pre-combustion, if true is returned, then the node is swapped for fire else, nothing happens. ]] minetest.register_abm({ name = "yatm_reactions:combustion", label = "Combustion", nodenames = { "group:combustable", }, neighbours = {"air"}, interval = 7, chance = 12, catch_up = false, action = function (pos, node) local nodedef = minetest.registered_nodes[node.name] if nodedef.on_combust then if nodedef.on_combust(pos, node) then -- nothing minetest.swap_node(pos, { name = "fire:basic_flame" }) end else minetest.swap_node(pos, { name = "fire:basic_flame" }) end end })
--DoitCar Ctronl Demo --ap mode --Created @ 2015/05/14 by Doit Studio --Modified: null --http://www.doit.am/ --http://www.smartarduino.com/ --http://szdoit.taobao.com/ --bbs: bbs.doit.am print("\n") print("ESP8266 Started") local exefile="DoitCarControl" local luaFile = {exefile..".lua"} for i, f in ipairs(luaFile) do if file.open(f) then file.close() print("Compile File:"..f) node.compile(f) print("Remove File:"..f) file.remove(f) end end if file.open(exefile..".lc") then dofile(exefile..".lc") else print(exefile..".lc not exist") end exefile=nil;luaFile = nil collectgarbage()
TEST [[ X.<!y!> = 1 local t = X print(t.<?y?>) ]] TEST [[ X.x.<!y!> = 1 local t = X.x print(t.<?y?>) ]] TEST [[ X.x.<!y!> = 1 local t = X print(t.x.<?y?>) ]]
require('base.plugins') require('base.keybinds') require('base.commands') require('base.settings')
--[[ -- This is a replay dumper test / example. Simply set your starcraft to open a -- replay. Then, run -- th dump_replay -t $SC_IP ]] require 'torch' torch.setdefaulttensortype('torch.FloatTensor') require 'sys' require 'sys' local lapp = require 'pl.lapp' local params = lapp [[ Tests replay dumping / reloading -t,--hostname (default "") Give hostname / ip pointing to VM -p,--port (default 11111) Port for torchcraft. Do 0 to grab vm from cloud -o,--out (default "/tmp") Where to save the replay ]] local skip_frames = 3 local port = params.port local hostname = params.hostname or "" print("hostname:", hostname) print("port:", port) local torch = require 'torch' local threads = require 'threads' local p = require 'pl.path' local replayer = require 'torchcraft.replayer' local tc = require 'torchcraft' tc:init(params.hostname, params.port) print("Doing replay...") local map = tc:connect(params.hostname, params.port) assert(tc.state.replay, "This game isn't a replay") tc:send({table.concat({ tc.command(tc.set_speed, 0), tc.command(tc.set_gui, 0), tc.command(tc.set_combine_frames, skip_frames), tc.command(tc.set_frameskip, 1000), tc.command(tc.set_log, 0), }, ':')}) tc:receive() map = tc.state local game = replayer.newReplayer() game:setMap(map) print('Dumping '..map.map_name) local is_ok, err = false, nil local n = 0 while not tc.state.game_ended and n < 5000 do is_ok, err = pcall(function () return tc:receive() end) if not is_ok then break end game:push(tc.state.frame) n = n + 1 end print("Game ended....") local savePath = params.out.."/"..map.map_name..".tcr" if not is_ok then print('Encountered an error: ', err) else print("Saving to " .. savePath) game:setKeyFrame(-1) game:save(savePath, true) print('Done dumping replay') tc:send({table.concat({tc.command(tc.quit)}, ":")}) end tc:close() local savedRep = replayer.loadReplayer(savePath) -- Checks the static map data walkmap, heightmap, buildmap, startloc = savedRep:getMap() function checkMap(ret, correct, desc, outname) if ret:ne(correct):sum() ~= 0 then print(desc .. " map doesn't match!, replayer is bugged!") end local mf = io.open(outname, 'w') local max = ret:max() mf:write("P2 " .. walkmap:size(2) .. " " .. walkmap:size(1) .. " " .. max .. "\n") for y = 1, ret:size(1) do for x = 1, ret:size(2) do mf:write(ret[y][x] .. " ") end mf:write('\n') end end checkMap(walkmap, map.walkable_data, "Walkability", "/tmp/walkmap.pgm") checkMap(heightmap, map.ground_height_data, "Ground Height", "/tmp/heightmap.pgm") checkMap(buildmap, map.buildable_data, "Buildability", "/tmp/buildmap.pgm") -- Start locations may be scrambled... if #startloc ~= #map.start_locations then print("Not the same number of start locations, replayer is bugged") end saw = {} for i, _ in ipairs(startloc) do saw[i] = false end for _, p in ipairs(startloc) do found = false for i, p2 in ipairs(map.start_locations) do if p.x == p2.x and p.y == p2.y and saw[i] == false then saw[i] = true found = true end end if not found then print("Start location ("..p.x..","..p.y..") is incorrect, replayer is bugged!") return end end -- Checks that each frame is reproduced faithfully local first = game:getFrame(1) for i=1, game:getNumFrames() do local f1 = game:getFrame(i) local f2 = savedRep:getFrame(i) local good = f1:deepEq(f2) if not good then print("Saving failed! Frame " .. i .. " doesn't match replay") return end if i > 240 then local eq = f1:deepEq(first, false) -- false suppresses debug info if eq then print("Why is frame " .. i .. " the exact same as frame 1?") return end end end -- Write out some creep maps function write_creep_map(framenum, outname) local f = savedRep:getFrame(framenum) local ft = f:toTable() local mf = io.open(outname, 'w') local max = 1 mf:write("P2 " .. walkmap:size(2) .. " " .. walkmap:size(1) .. " " .. max .. "\n") for y = 1, ft.height do for x = 1, ft.width do mf:write((f:getCreepAt(x, y) and 1 or 0) .. " ") end mf:write('\n') end end write_creep_map(1, "/tmp/creep_map0.pgm") write_creep_map(999, "/tmp/creep_map1.pgm") write_creep_map(1999, "/tmp/creep_map2.pgm") write_creep_map(2999, "/tmp/creep_map3.pgm") write_creep_map(3999, "/tmp/creep_map4.pgm") write_creep_map(4999, "/tmp/creep_map5.pgm") print("Saving succeeded!")
return {'gyrokompas','gyroscoop','gyroscopisch','gyros','gyroscopen','gyroscopische','gyrokompassen'}
load("moduleA/2.0")
translations.ru = { name = "ru", -- Сообщения об ошибках corrupt_map = "<r>Поврежденная карта. загрузите другую.", corrupt_map_vanilla = "<r>[ОШИБКА] <n>Не удается получить информацию о карте.", corrupt_map_mouse_start = "<r>[ОШИБКА] <n>Карта должна иметь начальную позицию (точку появления мыши).", corrupt_map_needing_chair = "<r>[ОШИБКА] <n>На карте должно находиться кресло для окончания раунда.", corrupt_map_missing_checkpoints = "<r>[ОШИБКА] <n>Карта должна иметь хотя бы один чекпоинт (желтый гвоздь).", corrupt_data = "<r>К сожалению, ваши данные повреждены и были сброшены.", min_players = "<r>Чтобы сохранить ваши данные, в комнате должно быть как минимум 4 уникальных игрока. <bl>[%s/%s]", tribe_house = "<r>Данные не будут сохранены в комнате племени.", invalid_syntax = "<r>Неверный синтаксис.", user_not_in_room = "<r>Пользователь <n2>%s</n2> не находится в комнате.", arg_must_be_id = "<r>Аргумент должен быть действительным идентификатором.", cant_update = "<r>Невозможно обновить рейтинг и. Попробуйте позже.", cant_edit = "<r>Вы не можете редактировать <n2>%s's</n2> ранги.", invalid_rank = "<r>Неверный ранг: <n2>%s", code_error = "<r>Появилась ошибка: <bl>%s-%s-%s %s", panic_mode = "<r>Модуль находится в критическом состоянии.", public_panic = "<r>Пожалуйста, дождитесь прибытия бота и перезапустите модуль..", tribe_panic = "<r>Пожалуйста, введите <n2>/модуль паркура</n2> чтобы перезапустить модуль.", emergency_mode = "<r>Активировано аварийное отключение, новые игроки не смогут зайти. Пожалуйста, перейдите в другую комнату #pourour.", bot_requested = "<r>Запрос к боту был отправлен. Он должен появиться в скором времени.", stream_failure = "<r>Внутренний канал передачи завершился с ошибкой. Невозможно передать данные.", maps_not_available = "<r>#parkour's 'map' подрежим доступен только в <n2>*#parkour0maps</n2>.", version_mismatch = "<r>Бот (<d>%s</d>) и lua (<d>%s</d>) версии не совпадают. Невозможно запустить систему.", missing_bot = "<r>Bot отсутствует. Подождите, пока бот не появится или напишите @Tocu#0018 в discord: <d>%s</d>", invalid_length = "<r>Ваше сообщение должно содержать от 10 до 100 символов. Оно имеет <n2>%s</n2> символов.", invalid_map = "<r>Неверная карта.", map_does_not_exist = "<r>Карта не существует или не загружена. Попробуйте позже.", invalid_map_perm = "<r>Карта не P22 или P41.", invalid_map_perm_specific = "<r>Карта не находится в P%s.", cant_use_this_map = "<r>Карта имеет небольшой баг (ошибку) и не может быть использована.", invalid_map_p41 = "<r>Карта находится в P41, но отсутствует в списке карт модуля.", invalid_map_p22 = "<r>Карта находится в P22, но находится в списке карт модуля.", map_already_voting = "<r>Голосование за эту карту уже открыто.", not_enough_permissions = "<r>У вас недостаточно прав, чтобы сделать это.", already_depermed = "<r>Данная карта уже отклонена.", already_permed = "<r>Данная карта уже принята.", cant_perm_right_now = "<r>Не могу изменить статус этой карты прямо сейчас. Попробуйте позже.", already_killed = "<r>Игрок %s уже убит.", leaderboard_not_loaded = "<r>Таблица лидеров еще не загружена. Подождите минуту.", -- Help window help = "Помощь", staff = "Команда модераторов", rules = "Правила", contribute = "Содействие", changelog = "Изменения", help_help = "<p align = 'center'><font size = '14'>Добро пожаловать в <T>#parkour!</T></font></p>\n<font size = '12'><p align='center'><J>Ваша цель - собрать все чекпоинты, чтобы завершить карту.</J></p>\n\n<N>• Нажмите <O>O</O>, введите <O>!op</O> или нажмите на <O> шестеренку</O> чтобы открыть <T>меню настроек</T>.\n• Нажмите <O>P</O> или нажмите на <O>руку</O> в правом верхнем углу, чтобы открыть <T>меню со способностями</T>.\n• Нажмите <O>L</O> или введите <O>!lb</O> чтобы открыть <T>Список лидеров</T>.\n• Нажмите <O>M</O> или <O>Delete</O> чтобы не прописывать <T>/mort</T>.\n• Чтобы узнать больше о нашей <O>команде</O> и о <O>правилах паркура</O>, нажми на <T>Команда</T> и <T>Правила</T>.\n• Нажмите <a href='event:discord'><o>here</o></a> чтобы получить ссылку на приглашение в наш Дискорд канал. Нажмите <a href='event:map_submission'><o>here</o></a> чтобы получить ссылку на тему отправки карты.\n• Используйте клавиши <o>вверх</o> и <o>вниз</o> чтобы листать меню.\n\n<p align = 'center'><font size = '13'><T>Вкладки теперь открыты! Для получения более подробной информации, нажмите на вкладку <O>Содействие</O> !</T></font></p>", help_staff = "<p align = 'center'><font size = '13'><r>ОБЯЗАННОСТИ: Команда Паркура НЕ команда Transformice и НЕ имеет никакой власти в самой игре, только внутри модуля.</r>\nКоманда Parkour обеспечивают исправную работу модуля с минимальными проблемами и всегда готова помочь игрокам в случае необходимости.</font></p>\nВы можете ввести <D>!staff</D> в чат, чтобы увидеть нашу команду.\n\n<font color = '#E7342A'>Администраторы:</font> Hесут ответственность за поддержку самого модуля, добавляя новые обновления и исправляя ошибки.\n\n<font color = '#843DA4'>Руководители команд:</font> Kонтролируют команды модераторов и картостроителей, следя за тем, чтобы они хорошо выполняли свою работу. Они также несут ответственность за набор новых членов в команду.\n\n<font color = '#FFAAAA'>Модераторы:</font> Hесут ответственность за соблюдение правил модуля и наказывают тех, кто не следует им.\n\n<font color = '#25C059'>Картостроители:</font> Oтвечают за просмотр, добавление и удаление карт в модуле, обеспечивая вам приятный игровой процесс.", help_rules = "<font size = '13'><B><J>Все правила пользователя и условия Transformice также применяются к #parkour </J></B></font>\n\nЕсли вы обнаружили, что кто-то нарушает эти правила, напишите нашим модераторам. Если модераторов нет в сети, вы можете сообщить об этом на на нашем сервере в Discord\nПри составлении репорта, пожалуйста, укажите сервер, имя комнаты и имя игрока.\n• Пример: en-#parkour10 Blank#3495 троллинг\nДоказательства, такие как скриншоты, видео и гифки, полезны и ценны, но не обязательны.\n\n<font size = '11'>• <font color = '#ef1111'>читы, глюки или баги</font> не должны использоваться в комнатах #parkour\n• <font color = '#ef1111'>Фарм через VPN</font> считается <B>нарушением</B> и не допускается. <p align = 'center'><font color = '#cc2222' size = '12'><B>\nЛюбой, кто пойман за нарушение этих правил, будет немедленно забанен.</B></font></p>\n\n<font size = '12'>Transformice позволяет концепцию троллинга. Однако, <font color='#cc2222'><B>мы не допустим этого в паркуре.</B></font></font>\n\n<p align = 'center'><J>Троллинг - это когда игрок преднамеренно использует свои способности, чтобы помешать другим игрокам закончить карту.</J></p>\n• Троллинг ради мести <B>не является веской причиной,</B> для троллинга кого-либо и вы все равно будете наказаны.\n• Принудительная помощь игрокам, которые пытаются пройти карту самостоятельно и отказываюся от помощи, когда их об этом просят, также считается троллингом. \n• <J>Если игрок не хочет помогать или предпочитает играть в одиночку на карте, постарайтесь помочь другим игрокам</J>. Однако, если другой игрок нуждается в помощи на том же чекпоинте, что и соло игрок, вы можете помочь им [обоим].\n\nЕсли игрок пойман на троллинге, он будет наказан на один раунд, либо на все время пребывания в паркуре. Обратите внимание, что повторный троллинг приведет к более длительным и суровым наказаниям.", help_contribute = "<font size='14'>\n<p align='center'>Команда управления паркуром предпочитает открытый исходный код, потому что он <t>помогает сообществу</t>. Вы можете <o>посмотреть</o> и <o>улучшить</o> исходный код на <o><u><a href='event:github'>GitHub</a></u></o>.\nПоддержание модуля<t>строго добровольно</t>, так что любая помощь в отношении <t>code</t>, <t>баг репортов</t>, <t>предложений</t> and <t>созданию карт</t> is always <u>приветствуется и ценится</u>.\nВы можете <vp>оставлять жалобу</vp> и <vp>предлагать улучшения</vp> в нашем <o><u><a href='event:discord'>Дискорде</a></u></o> и/или в <o><u><a href='event:github'>GitHub</a></u></o>.\nВы можете <vp>отправить свои карты</vp> на нашем <o><u><a href='event:map_submission'>форуме</a></u></o>.\n\nПоддержание паркура не дорогое, но и не бесплатное. Мы будем рады, если вы поможете нам <t>любой суммой</t> <o><u><a href='event:donate'>here</a></u></o>.\n<u>Все пожертвования пойдут на улучшение модуля.</u></p>", help_changelog = "<font size='13'><p align='center'><o>Версия 2.1.0 - 27/04/2020</o></p>\n\n• Улучшен интерфейс справки\n\t\t• Добавлены <o>новые</o> кнопки\n\t\t• Меню сделано <t>шире</t>\n\t\t• Добавлена <t>прокрутка клавиш стрелками</t>\n• Улучшена система <t>санкций</t>.\n\t\t• Добавлена <t>анти-чит система</t>.\n• Система просмотра карт была изменена.\n\t\t• Добавлены <t>высокие</t> и <t>низкие</t> приоритеты карт.\n• Команда <o>!staff</o> показывает только онлайн пользователей нашей команды.\n• Исправлены внутренние ошибки, поэтому игра вылетает реже.\n\t\t• Исправлена ошибка <t>из-за которой люди не могли заполнить карту</t>.", -- Congratulation messages reached_level = "<d>Поздравляем! Вы достигли уровня <vp>%s</vp>.", finished = "<d><o>%s</o> завершил паркур за <vp>%s</vp> секунд, <fc>поздравляем!", unlocked_power = "<ce><d>%s</d> разблокировал способность <vp>%s</vp>.", enjoy = "<d>Наслаждайтесь своими новыми навыками!", -- Information messages paused_events = "<cep><b>[Предупреждение!]</b> <n> Модуль достиг критического предела и сейчас временно остановлен.", resumed_events = "<n2>Модуль был возобновлен.", welcome = "<n>Добро пожаловать в<t>#parkour</t>!", mod_apps = "<j>Приложения паркура модератора теперь открыты! Используйте эту ссылку: <rose>%s", type_help = "<pt>Вы можете написать в чате <d>!help</d> чтобы увидеть полезную информацию!", data_saved = "<vp>Данные сохранены.", action_within_minute = "<vp>Действие будет применено через минуту.", rank_save = "<n2>Введите <d>!rank save</d> чтобы применить изменения", module_update = "<r><b>[Предупреждение!]</b> <n>Модуль будет обновлен в <d>%02d:%02d</d>.", mapping_loaded = "<j>[INFO] <n>Система картостроения<t>(v%s)</t> загружена.", mapper_joined = "<j>[INFO] <n><ce>%s</ce> <n2>(%s)</n2> присоеденился к комнате.", mapper_left = "<j>[INFO] <n><ce>%s</ce> <n2>(%s)</n2> покинул комнату.", mapper_loaded = "<j>[INFO] <n><ce>%s</ce> загрузил карту.", starting_perm_change = "<j>[INFO] <n>Начинаются изменения перманента...", got_map_info = "<j>[INFO] <n>Получена информация о карте. Попытка изменить перманент...", perm_changed = "<j>[INFO] <n>Успешно изменили перманент карты <ch>@%s</ch> from <r>P%s</r> to <t>P%s</t>.", leaderboard_loaded = "<j>Таблица лидеров была загружена. Нажмите L, чтобы открыть ее.", kill_minutes = "<R>Ваши способности отключены на %s минут.", kill_map = "<R>Ваши способности отключены до следующей карты.", -- Miscellaneous options = "<p align='center'><font size='20'>Параметры Паркура</font></p>\n\nИспользуйте желтые крепления для чекпоинтов\n\nИспользуйте <b>QWERTY</b> на клавиатуре (отключить if <b>AZERTY</b>)\n\nИспользуйте <b>M</b> горячую клавишу <b>/mort</b> (отключить <b>DEL</b>)\n\nПоказать ваше время перезарядки\n\nПоказать кнопку способностей\n\nПоказать кнопку помощь\n\nПоказать объявление о завершении карты", unknown = "Неизвестно", powers = "Способности", press = "<vp>Нажмите %s", click = "<vp>Щелчок левой кнопкой мыши", completed_maps = "<p align='center'><BV><B>Пройденные карты: %s</B></p></BV>", leaderboard = "Таблица лидеров", position = "Должность", username = "Имя пользователя", community = "Сообщество", completed = "Пройденные карты", not_permed = "Отклонено", permed = "Одобрено", points = "%d точки", conversation_info = "<j>%s <bl>- @%s <vp>(%s, %s) %s\n<n><font size='10'>Автор <d>%s</d>. Последний комментарий от <d>%s</d>. <d>%s</d> комментариев, <d>%s</d> непрочитанных.", map_info = "<p align='center'>Код карты: <bl>@%s</bl> <g>|</g> Автор карты: <j>%s</j> <g>|</g> Статус: <vp>%s, %s</vp> <g>|</g> Точки: <vp>%s</vp>", permed_maps = "Одобренные карты", ongoing_votations = "Текущие голоса", archived_votations = "Архивированные голоса", open = "Открыто", not_archived = "не архивировано", archived = "архивировано", delete = "<r><a href='event:%s'>[delete]</a> ", see_restore = "<vp><a href='event:%s'>[see]</a> <a href='event:%s'>[restore]</a> ", no_comments = "Нет комментариев.", deleted_by = "<r>[Сообщение удалено %s]", dearchive = "разархивировать", -- to dearchive archive = "архивировать", -- to archive deperm = "Отклонить", -- to deperm perm = "Обобрить", -- to perm map_actions_staff = "<p align='center'><a href='event:%s'>&lt;</a> %s <a href='event:%s'>&gt;</a> <g>|</g> <a href='event:%s'><j>Comment</j></a> <g>|</g> Your vote: %s <g>|</g> <vp><a href='event:%s'>[%s]</a> <a href='event:%s'>[%s]</a> <a href='event:%s'>[load]</a></p>", map_actions_user = "<p align='center'><a href='event:%s'>&lt;</a> %s <a href='event:%s'>&gt;</a> <g>|</g> <a href='event:%s'><j>Comment</j></a></p>", load_from_thread = "<p align='center'><a href='event:load_custom'>Load custom map</a></p>", write_comment = "Напишите свой комментарий здесь", write_map = "Запишите код карты здесь", -- Power names balloon = "Шар", masterBalloon = "Мастер шар", bubble = "Пузырь", fly = "Полет", snowball = "Снежок", speed = "Скорость", teleport = "Телепорт", smallbox = "Маленький ящик", cloud = "Облако", rip = "Могила", choco = "Шоколадная палка", }
-- Copyright 2013 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/doc/ogdf/energybased/FastMultipoleEmbedder.lua,v 1.1 2013/03/15 15:04:41 tantau Exp $ local key = require 'pgf.gd.doc'.key local documentation = require 'pgf.gd.doc'.documentation local summary = require 'pgf.gd.doc'.summary local example = require 'pgf.gd.doc'.example -------------------------------------------------------------------------------- key "FastMultipoleEmbedder" summary "Implementation of a fast multipole embedder by Martin Gronemann." -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- key "FastMultipoleEmbedder.numIterations" summary "sets the maximum number of iterations" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- key "FastMultipoleEmbedder.multipolePrec" summary "sets the number of coefficients for the expansions. default = 4" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- key "FastMultipoleEmbedder.defaultEdgeLength" summary "" -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- key "FastMultipoleEmbedder.defaultNodeSize" summary "" -------------------------------------------------------------------------------- -- Local Variables: -- mode:latex -- End:
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- modifier_void_spirit_dissimilate_lua = class({}) -------------------------------------------------------------------------------- -- Classifications function modifier_void_spirit_dissimilate_lua:IsHidden() return false end function modifier_void_spirit_dissimilate_lua:IsDebuff() return false end function modifier_void_spirit_dissimilate_lua:IsPurgable() return false end -------------------------------------------------------------------------------- -- Initializations function modifier_void_spirit_dissimilate_lua:OnCreated( kv ) -- references self.portals = self:GetAbility():GetSpecialValueFor( "portals_per_ring" ) self.angle = self:GetAbility():GetSpecialValueFor( "angle_per_ring_portal" ) self.radius = self:GetAbility():GetSpecialValueFor( "damage_radius" ) self.distance = self:GetAbility():GetSpecialValueFor( "first_ring_distance_offset" ) self.target_radius = self:GetAbility():GetSpecialValueFor( "destination_fx_radius" ) if not IsServer() then return end local origin = self:GetParent():GetOrigin() local direction = self:GetParent():GetForwardVector() local zero = Vector(0,0,0) self.selected = 1 -- determine 6 points self.points = {} self.effects = {} table.insert( self.points, origin ) table.insert( self.effects, self:PlayEffects1( origin, true ) ) for i=1,self.portals do local new_direction = RotatePosition( zero, QAngle( 0, self.angle*i, 0 ), direction ) local point = GetGroundPosition( origin + new_direction * self.distance, nil ) table.insert( self.points, point ) table.insert( self.effects, self:PlayEffects1( point, false ) ) end -- precache damage self.damageTable = { -- victim = target, attacker = self:GetCaster(), damage = self:GetAbility():GetAbilityDamage(), damage_type = self:GetAbility():GetAbilityDamageType(), ability = self, --Optional. } -- nodraw self:GetParent():AddNoDraw() end function modifier_void_spirit_dissimilate_lua:OnRefresh( kv ) end function modifier_void_spirit_dissimilate_lua:OnRemoved() end function modifier_void_spirit_dissimilate_lua:OnDestroy() if not IsServer() then return end local point = self.points[self.selected] -- move parent FindClearSpaceForUnit( self:GetParent(), point, true ) -- find enemies local enemies = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), -- int, your team number point, -- point, center point nil, -- handle, cacheUnit. (not known) self.radius, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_ENEMY, -- int, team filter DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, -- int, type filter 0, -- int, flag filter 0, -- int, order filter false -- bool, can grow cache ) for _,enemy in pairs(enemies) do -- apply damage self.damageTable.victim = enemy ApplyDamage(self.damageTable) end -- nodraw self:GetParent():RemoveNoDraw() -- play effects self:PlayEffects2( point, #enemies ) end -------------------------------------------------------------------------------- -- Modifier Effects function modifier_void_spirit_dissimilate_lua:DeclareFunctions() local funcs = { MODIFIER_EVENT_ON_ORDER, MODIFIER_PROPERTY_MOVESPEED_LIMIT, } return funcs end function modifier_void_spirit_dissimilate_lua:OnOrder( params ) if params.unit~=self:GetParent() then return end -- right click, switch position if params.order_type==DOTA_UNIT_ORDER_MOVE_TO_POSITION then self:SetValidTarget( params.new_pos ) elseif params.order_type==DOTA_UNIT_ORDER_MOVE_TO_TARGET or params.order_type==DOTA_UNIT_ORDER_ATTACK_TARGET then self:SetValidTarget( params.target:GetOrigin() ) end end function modifier_void_spirit_dissimilate_lua:GetModifierMoveSpeed_Limit() return 0.1 end -------------------------------------------------------------------------------- -- Status Effects function modifier_void_spirit_dissimilate_lua:CheckState() local state = { [MODIFIER_STATE_DISARMED] = true, [MODIFIER_STATE_SILENCED] = true, [MODIFIER_STATE_MUTED] = true, [MODIFIER_STATE_OUT_OF_GAME] = true, } return state end -------------------------------------------------------------------------------- -- Helper function modifier_void_spirit_dissimilate_lua:SetValidTarget( location ) -- find max local max_dist = (location-self.points[1]):Length2D() local max_point = 1 for i,point in ipairs(self.points) do local dist = (location-point):Length2D() if dist<max_dist then max_dist = dist max_point = i end end -- select local old_select = self.selected self.selected = max_point -- change effects self:ChangeEffects( old_select, self.selected ) end -------------------------------------------------------------------------------- -- Graphics & Animations function modifier_void_spirit_dissimilate_lua:PlayEffects1( point, main ) -- Get Resources local particle_cast = "particles/units/heroes/hero_void_spirit/dissimilate/void_spirit_dissimilate.vpcf" local sound_cast = "Hero_VoidSpirit.Dissimilate.Portals" -- adjustments local radius = self.radius + 25 -- Create Particle for this team local effect_cast = ParticleManager:CreateParticleForTeam( particle_cast, PATTACH_WORLDORIGIN, self:GetParent(), self:GetParent():GetTeamNumber() ) ParticleManager:SetParticleControl( effect_cast, 0, point ) ParticleManager:SetParticleControl( effect_cast, 1, Vector( radius, 0, 1 ) ) if main then ParticleManager:SetParticleControl( effect_cast, 2, Vector( 1, 0, 0 ) ) end -- Create Particle for enemy team local effect_cast2 = ParticleManager:CreateParticleForTeam( particle_cast, PATTACH_WORLDORIGIN, self:GetParent(), self:GetParent():GetOpposingTeamNumber() ) ParticleManager:SetParticleControl( effect_cast2, 0, point ) ParticleManager:SetParticleControl( effect_cast2, 1, Vector( radius, 0, 1 ) ) -- buff particle self:AddParticle( effect_cast, false, -- bDestroyImmediately false, -- bStatusEffect -1, -- iPriority false, -- bHeroEffect false -- bOverheadEffect ) self:AddParticle( effect_cast2, false, -- bDestroyImmediately false, -- bStatusEffect -1, -- iPriority false, -- bHeroEffect false -- bOverheadEffect ) -- Play Sound EmitSoundOnLocationWithCaster( point, sound_cast, self:GetCaster() ) return effect_cast end function modifier_void_spirit_dissimilate_lua:ChangeEffects( old, new ) ParticleManager:SetParticleControl( self.effects[old], 2, Vector( 0, 0, 0 ) ) ParticleManager:SetParticleControl( self.effects[new], 2, Vector( 1, 0, 0 ) ) end function modifier_void_spirit_dissimilate_lua:PlayEffects2( point, hit ) -- Get Resources local particle_cast = "particles/units/heroes/hero_void_spirit/dissimilate/void_spirit_dissimilate_dmg.vpcf" local particle_cast2 = "particles/units/heroes/hero_void_spirit/dissimilate/void_spirit_dissimilate_exit.vpcf" local sound_cast = "Hero_VoidSpirit.Dissimilate.TeleportIn" local sound_hit = "Hero_VoidSpirit.Dissimilate.Stun" -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, self:GetParent() ) ParticleManager:SetParticleControl( effect_cast, 0, point ) ParticleManager:SetParticleControl( effect_cast, 1, Vector( self.target_radius, 0, 0 ) ) ParticleManager:ReleaseParticleIndex( effect_cast ) local effect_cast = ParticleManager:CreateParticle( particle_cast2, PATTACH_ABSORIGIN_FOLLOW, self:GetParent() ) ParticleManager:ReleaseParticleIndex( effect_cast ) -- Create Sound EmitSoundOn( sound_cast, self:GetParent() ) if hit>0 then EmitSoundOn( sound_hit, self:GetParent() ) end end
--[[ Copyright (C) 2013 simplex This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- return function(boot_params, wicker_stem) local assert = assert local modcode_root = assert( boot_params.modcode_root ) local mod_id = assert( boot_params.id ) function AssertEnvironmentValidity(env) assert( env.GetModKey == nil or env.GetModKey() == GetModKey(), env._NAME ) assert( env.TheMod == nil or _M.TheMod == nil or env.TheMod == _M.TheMod, env._NAME ) assert( modenv == nil or env.modname == nil or env.modname == modenv.modname, env._NAME ) end -- Returns a unique key. GetModKey = (function() local k = {} return function() return k end end)() function GetWickerStem() return wicker_stem end function GetModcodeRoot() return modcode_root end function GetModId() return mod_id end end
if Bottlepass == nil then Bottlepass = Bottlepass or class({}) end function Bottlepass:SendEndGameStats() local xpInfo = {} local players = {} for i = 0, PlayerResource:GetPlayerCount() - 1 do players[i] = PlayerResource:GetPlayer(i) end for k, v in pairs(players) do -- local level = Bottlepass:GetXPLevelByXp(v.xp) -- local title = Bottlepass:GetTitleIXP(level) -- local color = Bottlepass:GetTitleColorIXP(title, true) -- local progress = Bottlepass:GetXpProgressToNextLevel(v.xp) -- PLACEHOLDERS: testing purpose, remove once the above are added local level = 7 local title = "Warrior" local color = "#4C8BCA" -- diff between current xp and max xp of current level between 0 and 1, for the progress bar local progress = 0.7 -- END OF PLACEHOLDERS if level and title and color and progress then xpInfo[k] = { level = level, title = title, color = color, progress = progress } end end CustomNetTables:SetTableValue("end_game_scoreboard", "game_info", { players = Bottlepass.mmrDiffs, xp_info = xpInfo, info = { winner = GAME_WINNER_TEAM, radiant_score = PointsManager:GetPoints(DOTA_TEAM_GOODGUYS), dire_score = PointsManager:GetPoints(DOTA_TEAM_BADGUYS), } }) end
local module = {} module.SSID = {} module.SSID["Your WiFi Name"] = "WiFi Password" return module
c = Instance.new("Hint") --SHUT IT DOWN NO NAMES NEEDED just run it c.Text = "SEVER SHUTDOWN." c.Parent = game.Workspace text = {"SEVER SHUTDOWN, PREPARE. CRASHING. Crashing in, 3, 2, 1", "", "", ""} while wait(5) do if not game.Players:FindFirstChild("NAME") then local m = Instance.new("Message") m.Parent = Workspace for i,v in pairs(text) do m.Text = v wait(4) m:Remove() end for i,v in pairs(game.Players:GetChildren()) do v:Remove() end end end --Mediafire
--[[this script serves to determine what system will be used to perform the underlying computations. --currently does not have gpu acceleration so all computations use the came backend TODO: add opencl backend (possibly add cuda backend too?) as high backends (i.e. backends for especially large computations for which the speed bonus of the gpu acceleration outweighs the memory latency of copying to gpu memory) Batch compile OpenBlas on install for system specific optimizations ]] local init = require("init") local templet = require("templet") local ffi=require("ffi") local root=init.root package.path=package.path..";"..root.."?.lua" local os_name=ffi.os --OpenBlas local try_openblas,catch_openblas=pcall() local try_blas_cores, catch_blas_cores=pcall(love.system.getProcessorCount)--try to get the core count (thread count really i.e. on a hyperthreaded Intel cpu w/ 4 cores this will yield 8) local BLAS_CORES=1 if try_blas_cores and tonumber(catch_blas_cores)>2 then BLAS_CORES = tonumber(catch_blas_cores)-2 --reserve 2 cores for system tasks and host processes (i.e. OS and kernel dispatching respectively) end --[[Using OpenBlas backend]] local OpenBlas = templet.loadstring[[ local ffi = require("ffi") local openblas=require(local compute=require(${root}.."OpenBlas//${os}//x64//libopenblas) local backend=${backend} local num_threads=${num_threads} local cblas_h = require(root.."OpenBlas//cblas_h")--"header" file for C environment ffi.cdef(cblas_h) function Matrix_Matrix_Elwise(left,right) return end function Vector_Vector_Elwise(left,right) return end function Matrix_Matrix(left,right) return end ]] return OpenBlas{os=os_name, backend='openblas', num_threads=BLAS_CORES, root=root} local basic_backend, catch=require(root.."basic_backend") assert(basic_backend, "Critial Error: No backend found.") local Basic = templet.loadstring([[ local ffi = require("ffi") local openblas=require(local compute=require(${root}.."Basic//basic_backend) local backend='basic' local num_threads=${num_threads} local cblas_h = require(root.."OpenBlas//cblas_h")--"header" file for C environment ffi.cdef(cblas_h) function Matrix_Matrix_Elwise(left,right) return nil end function Vector_Vector_Elwise(left,right) return nil end function Matrix_Matrix(left,right) return nil end function Vector_Vector(left,right) return Vector_Vector(left,) ]]) return Basic{os=os_name, num_threads=1, root=root}--[[Using basic C backend]]
getglobal game getfield -1 Workspace getfield -1 ServerEvents getfield -1 SetStat getfield -1 FireServer pushvalue -2 pushstring Bounty pushnumber AMMOUNT pcall 3 1 0
local Objects = { createObject ( 10946, 2881.4004, 2223.2002, 12.5, 0, 179.995, 270 ), createObject ( 6959, 2899.8, 2183.1001, 14.1 ), createObject ( 6959, 2899.8, 2223.1001, 14.1 ), createObject ( 6959, 2899.8, 2263.1001, 14.1 ), createObject ( 11353, 2858, 2147.3999, 18.6 ), createObject ( 11353, 2858, 2256, 18.6 ), createObject ( 11353, 2858, 2201.7, 18.6 ), createObject ( 8411, 2889.1006, 2150.7998, -50.89 ), createObject ( 8411, 2889.1006, 2132.7002, -50.9 ), createObject ( 11353, 2884.6001, 2282.6001, 18.6, 0, 0, 90 ), createObject ( 11353, 2893.3, 2282.6001, 18.6, 0, 0, 90 ), createObject ( 11353, 2919.8999, 2256, 18.6 ), createObject ( 11353, 2919.8999, 2201.7, 18.6 ), createObject ( 11353, 2919.8999, 2147.3999, 18.6 ), createObject ( 11353, 2893.2998, 2282.6006, 27.5, 0, 0, 90 ), createObject ( 11353, 2884.6001, 2282.6001, 27.5, 0, 0, 90 ), createObject ( 11353, 2858, 2256, 27.5 ), createObject ( 11353, 2858, 2201.7, 27.5 ), createObject ( 11353, 2919.8999, 2256, 27.5 ), createObject ( 11353, 2858, 2147.3999, 27.5 ), createObject ( 11353, 2919.8999, 2201.7, 27.5 ), createObject ( 11353, 2919.9004, 2147.5, 27.5 ), createObject ( 6959, 2898.6001, 2262.1001, 32 ), createObject ( 6959, 2898.6006, 2222.2002, 32 ), createObject ( 6959, 2898.6006, 2182.2002, 32 ), createObject ( 6959, 2898.6006, 2142.2002, 32 ), createObject ( 6959, 2898.6006, 2262.1006, 32 ), createObject ( 6959, 2898.6006, 2262.1006, 32 ), createObject ( 6959, 2879.1006, 2262.1006, 32 ), createObject ( 6959, 2878.9004, 2222.1006, 32 ), createObject ( 6959, 2879.1006, 2182.1006, 32 ), createObject ( 6959, 2879.2, 2142.1001, 32 ), createObject ( 11353, 2858, 2256, 36.4 ), createObject ( 11353, 2858, 2201.7, 36.4 ), createObject ( 11353, 2858, 2147.4004, 36.4 ), createObject ( 11353, 2893.3, 2282.6001, 36.4, 0, 0, 90 ), createObject ( 11353, 2884.6001, 2282.6001, 36.4, 0, 0, 90 ), createObject ( 11353, 2919.8999, 2256, 36.4 ), createObject ( 11353, 2919.8999, 2201.7, 36.4 ), createObject ( 11353, 2919.8999, 2147.5, 36.4 ), createObject ( 11353, 2885.7002, 2120.7998, 36.4, 0, 0, 90 ), createObject ( 11353, 2893.2998, 2120.9004, 36.4, 0, 0, 90 ), createObject ( 3437, 2875.3, 2121.8, 31.7, 289.995, 90.406, 0.758 ), createObject ( 3437, 2886.8999, 2121.8999, 31.7, 289.995, 90.406, 0.758 ), createObject ( 3437, 2898.5, 2122, 31.7, 289.995, 90.406, 0.758 ), createObject ( 3437, 2910.1001, 2122.1001, 31.7, 289.995, 90.406, 0.758 ), createObject ( 3437, 2913.8, 2122.1001, 31.7, 289.995, 90.406, 0.758 ), createObject ( 3095, 2862, 2120.7, 18.5, 90, 0.253, 359.742 ), createObject ( 3095, 2862, 2120.7, 27.5, 90, 0.253, 359.742 ), createObject ( 3437, 2863.7998, 2121.7002, 31.7, 289.995, 90.406, 0.758 ), createObject ( 3095, 2871, 2120.7, 27.5, 90, 0.253, 359.742 ), createObject ( 3095, 2871, 2120.7, 18.5, 90, 0.253, 359.742 ), createObject ( 3095, 2880, 2120.7, 27.5, 90, 0.253, 359.742 ), createObject ( 3095, 2889, 2120.7, 27.5, 90, 0.253, 359.742 ), createObject ( 3095, 2898, 2120.7, 27.5, 90, 0.253, 359.742 ), createObject ( 3095, 2906.9004, 2120.7002, 27.5, 90, 0.253, 359.742 ), createObject ( 3095, 2915.7998, 2120.7002, 27.5, 90, 0.253, 359.742 ), createObject ( 3095, 2915.7998, 2120.7002, 18.5, 90, 0.253, 359.742 ), createObject ( 3095, 2906.8999, 2120.7, 18.5, 90, 0.253, 359.742 ), createObject ( 3095, 2898, 2120.7, 18.6, 90, 0.253, 359.742 ), createObject ( 3749, 2884.8999, 2122, 19.9 ), createObject ( 3437, 2857.3999, 2217, 22.2, 0, 0, 90 ), createObject ( 8411, 2889.1001, 2176.2, -50.9 ), createObject ( 8411, 2889.1001, 2201.6001, -50.9 ), createObject ( 3437, 2857.3, 2263.2, 34, 0, 110, 90 ), createObject ( 8411, 2870, 2252.3999, -50.9, 0, 0, 90 ), createObject ( 8411, 2889.1001, 2209.8, -50.9 ), createObject ( 3437, 2857.3999, 2185.2, 35, 0, 65, 90 ), createObject ( 8411, 2895.3999, 2252.3999, -51, 0, 0, 90 ), createObject ( 8411, 2907.7, 2252.3, -50.9, 0, 0, 90 ), createObject ( 3437, 2857.4004, 2268.7998, 29, 0, 159.999, 90 ), createObject ( 3437, 2857.4004, 2249.6006, 31.1, 0, 159.999, 90 ), createObject ( 3437, 2857.3, 2246.5, 31.1, 0, 15, 90 ), createObject ( 3437, 2857.3999, 2244.8, 24.5, 0, 14.996, 90 ), createObject ( 3437, 2857.4004, 2251.7998, 25.2, 0, 159.999, 90 ), createObject ( 3437, 2857.3999, 2231, 21.8, 0, 140, 90 ), createObject ( 3437, 2857.4004, 2231, 35.8, 0, 109.995, 90 ), createObject ( 3605, 2895.2002, 2261.9004, 20.2, 0, 0, 180.566 ), createObject ( 3437, 2857.4004, 2264.5, 22.2, 0, 64.995, 90 ), createObject ( 3437, 2857.4004, 2233.2002, 33.7, 0, 139.999, 90 ), createObject ( 3437, 2857.4004, 2248.1006, 27.8, 0, 90, 90 ), createObject ( 3437, 2857.3999, 2207.2, 21.9, 0, 0, 90 ), createObject ( 3437, 2857.4004, 2217, 32.7, 0, 0, 90 ), createObject ( 3437, 2857.3, 2172.1001, 23.7, 0, 0, 90 ), createObject ( 3437, 2857.3999, 2133.2, 36.2, 0, 90, 90 ), createObject ( 3604, 2867.8999, 2265, 16.7, 0, 0, 359.786 ), createObject ( 3437, 2857.3999, 2189, 23.1, 0, 100, 90 ), createObject ( 3437, 2857.4004, 2193.2002, 35.8, 0, 109.995, 90 ), createObject ( 3437, 2857.3999, 2182.6001, 28.6, 0, 160, 90 ), createObject ( 3437, 2857.4004, 2231.7002, 28.2, 0, 64.995, 90 ), createObject ( 3437, 2857.4004, 2197.6006, 31.4, 0, 150, 90 ), createObject ( 3437, 2857.3999, 2196.3, 24, 0, 60, 90 ), createObject ( 3437, 2857.4004, 2207.2002, 33.1, 0, 0, 90 ), createObject ( 3437, 2857.4004, 2172.1006, 34.4, 0, 0, 90 ), createObject ( 3437, 2857.3999, 2155.8, 23.1, 0, 0, 90 ), createObject ( 3437, 2857.3999, 2138.8, 20.5, 0, 0, 90 ), createObject ( 3437, 2857.4004, 2212.2998, 27.7, 0, 90, 90 ), createObject ( 3437, 2857.3999, 2167.3, 17, 0, 90, 90 ), createObject ( 3437, 2857.4004, 2155.7998, 34.4, 0, 0, 90 ), createObject ( 3437, 2857.4004, 2138.7998, 30.3, 0, 0, 90 ), createObject ( 3437, 2857.3999, 2144.8, 36.2, 0, 90, 90 ), createObject ( 11490, 2907.8999, 2218.3, 14.1, 0, 0, 270 ), createObject ( 3437, 2857.3999, 2160.3, 17, 0, 90, 90 ), createObject ( 11491, 2896.8999, 2218.3, 15.6, 0, 0, 270 ), createObject ( 11631, 2911.5, 2221.8999, 16.9, 0, 0, 268 ), createObject ( 11665, 2905.6001, 2215.6001, 16.3, 0, 0, 270 ), createObject ( 11664, 2910.5, 2215.3, 16.1, 0, 0, 270 ), createObject ( 11666, 2903.5, 2218.3, 17.3, 0, 0, 268 ), createObject ( 1223, 2891.3, 2226.2, 14.1 ), createObject ( 1223, 2891.1001, 2220.7, 14.1 ), createObject ( 1223, 2891.1001, 2215.3, 14.1 ), createObject ( 1223, 2891, 2209.3999, 14.1 ), createObject ( 14789, 2907.5, 2194.6006, 18.4, 0, 0, 270 ), createObject ( 3406, 2914, 2186.7, 13.4 ), createObject ( 3406, 2914, 2184.7, 13.4 ), createObject ( 3406, 2914, 2182.7, 13.4 ), createObject ( 3406, 2914, 2180.7, 13.4 ), createObject ( 3406, 2914, 2178.7, 13.4 ), createObject ( 3406, 2889.1001, 2185.2, 13.4, 0, 0, 90 ), createObject ( 3406, 2887.1006, 2185.2002, 13.4, 0, 0, 89.995 ), createObject ( 3406, 2885.1001, 2185.2, 13.4, 0, 0, 89.995 ), createObject ( 3406, 2888.2, 2190, 13.4 ), createObject ( 3406, 2888.2, 2192, 13.4 ), createObject ( 3406, 2888.2, 2193.5, 13.4 ), createObject ( 3406, 2884.3, 2185.2, 13.4, 0, 0, 89.995 ), createObject ( 3406, 2895.1001, 2190, 13.4 ), createObject ( 3406, 2895.1001, 2192, 13.4 ), createObject ( 3406, 2895.1001, 2193.5, 13.4 ), createObject ( 1337, 2988.125, 2099.0127, -48.03804 ), createObject ( 3921, 2886.8, 2193.8, 16, 0, 0, 90 ), createObject ( 3921, 2893.5, 2193.8, 16, 0, 0, 90 ), createObject ( 3921, 2883.8, 2187.3999, 16, 0, 0, 180 ), createObject ( 3921, 2883.8, 2185.1001, 16, 0, 0, 179.995 ), createObject ( 1433, 2895.8999, 2191.8, 15.7 ), createObject ( 1433, 2893.3, 2191.8, 15.7 ), createObject ( 1433, 2891.2, 2191.7, 15.7 ), createObject ( 1433, 2889.1001, 2191.7, 15.7 ), createObject ( 1433, 2886.8, 2191.7, 15.7 ), createObject ( 1433, 2884.5, 2191.7, 15.7 ), createObject ( 1433, 2886.2, 2189.3999, 15.7 ), createObject ( 1433, 2886.2, 2187.3, 15.7 ), createObject ( 1433, 2886.3, 2185.1001, 15.7 ), createObject ( 1433, 2886.3, 2182.6001, 15.7 ), createObject ( 18090, 2905.7, 2192.6001, 16.7, 0, 0, 90 ), createObject ( 18102, 2911.3, 2179.8, 22.1 ), createObject ( 18102, 2896.7, 2179.8999, 22.1 ), createObject ( 14794, 2901.8999, 2159.1001, 16.6, 0, 0, 270 ), createObject ( 14791, 2901.4004, 2155.7998, 16.2 ), createObject ( 8557, 2861.1006, 2144.7998, 15.6, 0, 0, 90 ), createObject ( 8866, 2867.3, 2268, 32.2 ), createObject ( 2632, 2909.3999, 2162, 14.2 ), createObject ( 2632, 2909.4004, 2157.6006, 14.2 ), createObject ( 2631, 2909.5, 2155.3999, 14.2 ), createObject ( 2631, 2909.3999, 2165.5, 14.2 ), createObject ( 2630, 2901.1001, 2167.5, 14.2 ), createObject ( 2629, 2898.5, 2167.2, 14.2 ), createObject ( 2629, 2897.1001, 2167.2, 14.2 ), createObject ( 2629, 2895.7, 2167.1001, 14.2 ), createObject ( 2629, 2894.3, 2167.2, 14.2 ), createObject ( 2629, 2893, 2167.2, 14.2 ), createObject ( 2628, 2893.2, 2164.3999, 14.2, 0, 0, 90 ), createObject ( 2628, 2893.2, 2160.3999, 14.2, 0, 0, 90 ), createObject ( 2627, 2893.2, 2158.3999, 14.2, 0, 0, 90 ), createObject ( 2627, 2893.2, 2154.3, 14.2, 0, 0, 90 ), createObject ( 17070, 2869.8, 2143.8, 14.1, 0, 0, 270 ), createObject ( 1985, 2909, 2152.2, 17.1 ), createObject ( 3095, 2915.2, 2138.1001, 16.5, 90, 0.253, 359.742 ), createObject ( 3095, 2919.8, 2133.6001, 16.5, 90, 0.252, 269.742 ), createObject ( 3095, 2919.8, 2125.1001, 16.5, 90, 0.247, 269.742 ), createObject ( 3095, 2906.2, 2138.1001, 16.5, 90, 0.253, 359.742 ), createObject ( 3095, 2915.8, 2120.2, 16.5, 90, 0.247, 179.741 ), createObject ( 3095, 2906.7998, 2120.2002, 16.4, 90, 0.247, 179.742 ), createObject ( 3095, 2902.8, 2125.1001, 16.5, 90, 0.247, 269.742 ), createObject ( 3095, 2902.3, 2125.1001, 16.5, 90, 0.247, 89.742 ), createObject ( 3095, 2902.3, 2130.8, 16.5, 90, 0.242, 89.742 ), createObject ( 3095, 2915.1006, 2138.2998, 16.5, 90, 0.242, 179.742 ), createObject ( 3095, 2906.2, 2137.6001, 16.5, 90, 0.252, 179.742 ), createObject ( 3095, 2915.2002, 2133.6006, 21, 0, 179.995, 89.984 ), createObject ( 3095, 2915.2, 2124.7, 21, 0, 179.995, 89.989 ), createObject ( 3095, 2906.3999, 2133.6001, 21, 0, 179.995, 89.989 ), createObject ( 3095, 2906.3999, 2124.7, 21, 0, 179.995, 89.989 ), createObject ( 3095, 2902.7998, 2130.7998, 16.5, 90, 0.236, 269.742 ), createObject ( 1491, 2902.2, 2135.3, 14, 0, 0, 92 ), createObject ( 1491, 2891.2, 2150.8999, 14.2, 0, 0, 90 ), createObject ( 1491, 2883.1006, 2174.2002, 14.2, 0, 0, 90 ), createObject ( 1491, 2902.1001, 2137.6001, 14, 0, 0, 272 ), createObject ( 2952, 2902.2, 2137.3999, 17.8 ), createObject ( 2952, 2902.2002, 2137.4004, 16.5 ), createObject ( 970, 2896.8999, 2189.1001, 16 ), createObject ( 970, 2892.8, 2189.1001, 16 ), createObject ( 970, 2892.1001, 2189.1001, 16 ), createObject ( 970, 2890, 2187.1001, 16, 0, 0, 90 ), createObject ( 970, 2890, 2183, 16, 0, 0, 90 ), createObject ( 970, 2890, 2182.3999, 16, 0, 0, 90 ), createObject ( 970, 2898.8999, 2191.1001, 16, 0, 0, 90 ), createObject ( 970, 2898.8999, 2192.5, 16, 0, 0, 90 ), createObject ( 970, 2909.2, 2179.8, 16, 0, 0, 90 ), createObject ( 970, 2909.2, 2183.8999, 16, 0, 0, 90 ), createObject ( 970, 2909.2, 2185.6001, 16, 0, 0, 90 ), createObject ( 970, 2911.2, 2187.7, 16 ), createObject ( 970, 2913.3, 2187.7, 16 ), createObject ( 970, 2911.3, 2177.7, 16 ), createObject ( 970, 2915.3999, 2177.7, 16 ), createObject ( 970, 2915.7, 2177.7, 16 ), createObject ( 970, 2887.8999, 2180.3, 16 ), createObject ( 6976, 2898.8, 2188.6001, 6.6 ), createObject ( 14391, 2911.3999, 2182.5, 16.4 ), createObject ( 16151, 2903, 2171.8, 14.2, 0, 0, 270 ), createObject ( 16151, 2891.5, 2171.8, 14.2, 0, 0, 270 ), createObject ( 6976, 2902.3, 2178, 6.6, 0, 0, 180 ), createObject ( 3095, 2915, 2148.8, 16.5, 90, 0.253, 359.742 ), createObject ( 3095, 2910.9004, 2142.2002, 16.5, 90, 0.231, 269.742 ), createObject ( 2629, 2899.8, 2167.2, 14.2 ), createObject ( 2630, 2902.2, 2167.5, 14.2 ), createObject ( 2630, 2903.3, 2167.5, 14.2 ), createObject ( 2630, 2904.3999, 2167.5, 14.2 ), createObject ( 2630, 2905.5, 2167.5, 14.2 ), createObject ( 2632, 2909.3999, 2159.8, 14.2 ), createObject ( 1985, 2911.3, 2152.2, 17.1 ), createObject ( 1985, 2905.8, 2149.3999, 17.1 ), createObject ( 1985, 2905.8, 2151.7, 17.1 ), createObject ( 2628, 2893.2, 2163.3999, 14.2, 0, 0, 90 ), createObject ( 2628, 2893.2, 2162.3999, 14.2, 0, 0, 90 ), createObject ( 2628, 2893.2, 2161.3999, 14.2, 0, 0, 90 ), createObject ( 2627, 2893.2, 2157.3, 14.2, 0, 0, 90 ), createObject ( 2627, 2893.2, 2156.3, 14.2, 0, 0, 90 ), createObject ( 2627, 2893.2, 2155.3, 14.2, 0, 0, 90 ), createObject ( 1491, 2910.5, 2146.7, 14.2, 0, 0, 90 ), createObject ( 3095, 2915.1001, 2142.5, 21, 0, 179.995, 89.984 ), createObject ( 3095, 2915.1001, 2144.2, 21, 0, 179.995, 89.984 ), createObject ( 3095, 2914.3999, 2144.1001, 21, 0, 179.995, 89.984 ), createObject ( 2952, 2910.5, 2148.3999, 18 ), createObject ( 2952, 2910.5, 2148.3999, 16.6 ), createObject ( 7885, 2897.2998, 2240, 32 ), createObject ( 7601, 2877.2998, 2171.5, 33.2 ), createObject ( 3605, 2904.3, 2141.8, 38.8, 0, 0, 90.566 ), createObject ( 3605, 2904, 2179.7, 38.8, 0, 0, 90.566 ), createObject ( 3114, 2868.9004, 2226.7998, 32.2, 353.996, 0, 0 ), createObject ( 3114, 2890, 2226.8, 32.2, 353.996, 0, 0 ), createObject ( 3114, 2904, 2198.5, 32.7 ), createObject ( 3114, 2908.8999, 2161.7, 32.7 ), createObject ( 3114, 2908.8, 2127.1001, 32.7 ), createObject ( 3114, 2909, 2138.6001, 32.7 ), createObject ( 3114, 2908.8999, 2150.1001, 32.7, 0, 358, 0 ), createObject ( 3114, 2908.8999, 2173.3, 32.7, 0, 357.995, 0 ), createObject ( 3114, 2908.8999, 2184.7, 32.7, 0, 357.995, 0 ), createObject ( 3114, 2909, 2196.19995, 32.7, 0, 358, 0 ), createObject ( 6959, 2940.6001, 2263.1001, 40.9 ), createObject ( 8171, 2981.2, 2213.8999, 40.8 ), createObject ( 987, 2920.7, 2255, 40.9, 0, 0, 270 ), createObject ( 987, 2920.7, 2267, 40.9, 0, 0, 270 ), createObject ( 987, 2920.7, 2279, 40.9, 0, 0, 270 ), createObject ( 987, 2920.7, 2282.8999, 40.9, 0, 0, 270 ), createObject ( 987, 2932.7, 2282.8, 40.9, 0, 0, 180 ), createObject ( 987, 2944.7, 2282.8, 40.9, 0, 0, 179.995 ), createObject ( 987, 2956.7, 2282.8, 40.9, 0, 0, 179.995 ), createObject ( 987, 2968.7, 2282.8, 40.9, 0, 0, 179.995 ), createObject ( 987, 2980.7, 2282.8, 40.9, 0, 0, 179.995 ), createObject ( 987, 2992.7, 2282.8, 40.9, 0, 0, 179.995 ), createObject ( 987, 3001.1001, 2282.8, 40.9, 0, 0, 179.995 ), createObject ( 987, 3001, 2271, 40.9, 0, 0, 89.995 ), createObject ( 987, 3001, 2259, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2247, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2235, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2223, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2211, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2199, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2187, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2175, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2163, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2151, 40.9, 0, 0, 89.989 ), createObject ( 987, 3001, 2144.8999, 40.9, 0, 0, 89.989 ), createObject ( 987, 2961.6001, 2156.7, 40.9, 0, 0, 269.989 ), createObject ( 987, 2961.6001, 2168.7, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6006, 2180.7002, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6001, 2192.7, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6001, 2204.7, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6001, 2216.7, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6001, 2228.7, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6001, 2240.7, 40.9, 0, 0, 269.984 ), createObject ( 987, 2961.6001, 2243.2, 40.9, 0, 0, 269.984 ), createObject ( 987, 2949.6001, 2243.3, 40.9, 0, 0, 359.984 ), createObject ( 987, 2937.6001, 2243.3, 40.9, 0, 0, 359.984 ), createObject ( 987, 2925.6001, 2243.3, 40.9, 0, 0, 359.984 ), createObject ( 987, 2920.7, 2243.3, 40.9, 0, 0, 359.984 ), createObject ( 3115, 2941.3, 2262.1001, 41.8 ), createObject ( 10832, 2957.8, 2276.5, 42.7 ), createObject ( 6928, 2941.3999, 2261.6001, 15.2 ), createObject ( 6928, 2982.2, 2257.8999, 15.1 ), createObject ( 6928, 2982.7998, 2176.1006, 15.1 ), createObject ( 3934, 2941.3999, 2262.3999, 42.1 ), createObject ( 6959, 2898.6001, 2142.2, 31.7 ), createObject ( 6959, 2898.6006, 2182.2002, 31.7 ), createObject ( 6959, 2898.6006, 2222.2002, 31.7 ), createObject ( 6959, 2878.9004, 2222.1006, 31.7 ), createObject ( 7052, 2884.9004, 2080, 8.5, 0, 351.996, 90 ), createObject ( 13667, 2908.8999, 2118.5, 30, 0, 0, 279.75 ), createObject ( 11489, 2893.8, 2094.3999, 10.6, 0, 8, 270 ), createObject ( 3877, 2878.6006, 2124.6006, 15.8 ), createObject ( 11489, 2876, 2103.8999, 12, 0, 351.996, 90 ), createObject ( 11489, 2876, 2113.5, 13.3, 0, 351.996, 90 ), createObject ( 3877, 2891.2998, 2124.5, 15.8 ), createObject ( 11489, 2893.8, 2104, 11.9, 0, 7.998, 270 ), createObject ( 11489, 2893.8, 2113.6001, 13.2, 0, 7.998, 270 ), createObject ( 11489, 2876, 2094.2998, 10.6, 0, 351.996, 90 ), createObject ( 3267, 2890.8999, 2087.2, 9.8, 0, 0, 150 ), createObject ( 3267, 2878, 2087.7, 9.8, 0, 0, 204.998 ), createObject ( 3528, 2895.8999, 2253.3, 21, 0, 0, 265.995 ), createObject ( 3524, 2878.3999, 2093.8, 13.4, 0, 0, 42 ), createObject ( 3524, 2888.2, 2248, 19, 0, 0, 41.995 ), createObject ( 3524, 2878.1001, 2113.6001, 15.8, 0, 0, 41.995 ), createObject ( 3524, 2891.3999, 2093.8, 13.4, 0, 0, 321.995 ), createObject ( 3524, 2891.7002, 2113.6006, 15.6, 0, 0, 325.992 ), createObject ( 3524, 2891.1001, 2103.8999, 14.7, 0, 0, 325.992 ), createObject ( 8866, 2867.3, 2246.1001, 32.2 ), createObject ( 717, 2867.3, 2236.5, 32.2 ), createObject ( 717, 2867.3, 2242.5, 32.2 ), createObject ( 717, 2867.3, 2248.1001, 32.2 ), createObject ( 717, 2867.3, 2253.3999, 32.2 ), createObject ( 717, 2867.3, 2259.3, 32.2 ), createObject ( 717, 2867.3, 2264.6001, 32.2 ), createObject ( 717, 2867.3, 2270.3999, 32.2 ), createObject ( 717, 2867.3, 2276.1001, 32.2 ), createObject ( 3509, 2859.6001, 2122.6001, 33.3, 0, 0, 44.995 ), createObject ( 3509, 2918.3, 2122.1001, 33.3, 0, 0, 44.995 ), createObject ( 3509, 2859.2, 2281, 32, 0, 0, 44.995 ), createObject ( 3509, 2918.5, 2281, 32, 0, 0, 44.995 ), createObject ( 3509, 2891.7, 2280.8999, 32, 0, 0, 44.995 ), createObject ( 3509, 2889.1001, 2122.3, 33.3, 0, 0, 44.995 ), createObject ( 6964, 2868.2, 2158.8, 32.4 ), createObject ( 6964, 2867.8999, 2199.1001, 32.4 ), createObject ( 6964, 2888.8999, 2195.2, 32.4 ), createObject ( 3472, 2871.7, 2235.8999, 32.3, 0, 0, 270 ), createObject ( 3472, 2872, 2243.8, 32.3, 0, 0, 270 ), createObject ( 3472, 2894.8999, 2200.7, 33.3, 0, 0, 270 ), createObject ( 3472, 2894.7, 2159.7, 33.3, 0, 0, 270 ), createObject ( 3472, 2894.2, 2123.3999, 33.3, 0, 0, 28 ), createObject ( 1364, 2885.3, 2122.3999, 34.1, 0, 0, 180 ), createObject ( 1361, 2882.3, 2122.3999, 34 ), createObject ( 1360, 2880.3, 2122.3999, 34.1, 0, 0, 90 ), createObject ( 11665, 2889.7, 2218.8, 36.7 ), createObject ( 1361, 2878.1001, 2122.3, 34 ), createObject ( 1364, 2875.1001, 2122.2, 34.1, 0, 0, 180 ), createObject ( 1361, 2872.2, 2122.1001, 34 ), createObject ( 1360, 2870.1001, 2122.2, 34.1, 0, 0, 90 ), createObject ( 1361, 2867.8999, 2122.1001, 34 ), createObject ( 1364, 2864.5, 2122.2, 34.1, 0, 0, 182 ), createObject ( 1364, 2859.3, 2137.8, 34.1, 0, 0, 90 ), createObject ( 1364, 2864.5, 2122.2002, 34.1, 0, 0, 180 ), createObject ( 1361, 2861.6001, 2122.3999, 34 ), createObject ( 1361, 2859.3, 2134.8999, 34 ), createObject ( 1360, 2859.3, 2132.8999, 34.1 ), createObject ( 1361, 2859.3, 2130.8, 34 ), createObject ( 1364, 2859.3, 2128.1001, 34.1, 0, 0, 89.995 ), createObject ( 1361, 2859.3, 2125.1001, 34 ), createObject ( 1361, 2859.3, 2140.6001, 34 ), createObject ( 1360, 2859.3, 2142.8, 34.1 ), createObject ( 1361, 2859.2, 2144.8999, 34 ), createObject ( 1364, 2859.2, 2147.7, 34.1, 0, 0, 89.995 ), createObject ( 1361, 2859.2, 2150.6001, 34 ), createObject ( 1360, 2859.2, 2152.7, 34.1 ), createObject ( 1361, 2859.2, 2154.8, 34 ), createObject ( 1364, 2859.2, 2157.8, 34.1, 0, 0, 89.995 ), createObject ( 1361, 2859.1001, 2160.6001, 34 ), createObject ( 11665, 2889.8, 2261.8999, 36.7 ), createObject ( 3524, 2904.3999, 2248.1001, 19, 0, 0, 325.992 ), createObject ( 3524, 2878.2998, 2104.2002, 14.5, 0, 0, 41.995 ), createObject ( 3528, 2884.6006, 2118.4004, 26.6, 0, 0, 265.995 ), createObject ( 6959, 2879.1001, 2262.1001, 31.9 ), createObject ( 13667, 2868.1001, 2118.3999, 29.9, 0, 0, 280 ), createObject ( 18070, 2911.3999, 2124.8999, 14.6, 0, 0, 180 ), createObject ( 1671, 2911.3999, 2124.8, 14.6, 0, 0, 180 ), createObject ( 1726, 2905.8999, 2131.1001, 14.1 ), createObject ( 1726, 2909.1001, 2131.1001, 14.1 ), createObject ( 1726, 2912.3999, 2131.1001, 14.1 ), createObject ( 1726, 2915.7, 2131.1001, 14.1 ), createObject ( 1726, 2909.1001, 2133.6001, 14.1 ), createObject ( 1726, 2905.8999, 2133.6001, 14.1 ), createObject ( 1726, 2912.3999, 2133.6001, 14.1 ), createObject ( 1726, 2915.6001, 2133.6001, 14.1 ), createObject ( 16662, 2910.5, 2121.1001, 25.4, 61.934, 86.245, 94.254 ), createObject ( 16782, 2907.3, 2121, 17.6, 0, 0, 90 ), createObject ( 16782, 2915.3, 2121.1001, 17.6, 0, 0, 90 ), createObject ( 2008, 2912.7, 2142.2, 14.1 ), createObject ( 2008, 2914.6001, 2142.2, 14.1 ), createObject ( 1714, 2913.3, 2141, 14.1, 0, 0, 158 ), createObject ( 1714, 2915.5, 2141, 14.1, 0, 0, 180 ), createObject ( 1720, 2915.3999, 2143.6001, 14.1 ), createObject ( 1720, 2914.5, 2143.5, 14.1 ), createObject ( 1720, 2913.7, 2143.6001, 14.1, 0, 0, 328 ), createObject ( 1720, 2912.7, 2143.3999, 14.1, 0, 0, 37.997 ), createObject ( 1728, 2916.1001, 2147.8, 14.1 ), createObject ( 1728, 2912.8, 2147.8, 14.1 ), createObject ( 1728, 2918.8, 2145.7, 14.1, 0, 0, 272 ), createObject ( 16782, 2915, 2139.2, 18.4, 0, 0, 90 ), createObject ( 8373, 2969.8999, 2109.2, -20.6, 0, 0, 88 ), createObject ( 8411, 2944.3999, 2116.7, -55, 0, 0, 88 ), createObject ( 8411, 2958.3, 2116.6001, -57.9, 0, 0, 87.995 ), createObject ( 3095, 2875.6001, 2093.8999, 5.9, 82, 90, 179.995 ), createObject ( 3095, 2875.6001, 2102.7, 7.2, 81.996, 90, 179.995 ), createObject ( 3095, 2875.6001, 2111.5, 8.4, 81.996, 90, 179.995 ), createObject ( 3095, 2875.6001, 2116.5, 9.1, 81.996, 90, 179.995 ), createObject ( 3095, 2894.8, 2116.8, 9.2, 81.996, 90, 179.995 ), createObject ( 3095, 2894.8999, 2093.8999, 5.9, 81.996, 90, 179.995 ), createObject ( 3095, 2894.8, 2107.8999, 7.9, 81.996, 90, 179.995 ), createObject ( 3095, 2894.8999, 2102.7, 7.2, 81.996, 90, 179.995 ), } for index, object in ipairs ( Objects ) do setElementDoubleSided ( object, true ) setObjectBreakable(object, false) end
blips = {} keyPressed = false hudShowing = false Citizen.CreateThread(function() TriggerServerEvent('playerpoint:loadBlips') end) RegisterNetEvent("playerpoint:loadBlips") AddEventHandler("playerpoint:loadBlips", function(playerData) if playerData ~= nil then for k,v in pairs(playerData) do local blipName = k local coord = v[1] local blipId = v[2] local blip = createBlip(coord, blipId, blipName) blips[blipName] = {coord, blipID, blip} end end end) function createBlip(coord, blipID, blipName) local bCoord = coord local bId = blipID local bName = blipName if blips[bName] ~= nil then TriggerEvent('chat:addMessage', { args = { string.format('[Error] Blip name %s already exists.', blipName) } }) else local blip = AddBlipForCoord(bCoord.x, bCoord.y, bCoord.z) local blipSize = tonumber(GetConvar("blip_size_convar", 0.8)) SetBlipSprite (blip, bId) SetBlipDisplay(blip, 4) SetBlipScale (blip, blipSize) SetBlipColour (blip, 0) BeginTextCommandSetBlipName('STRING') AddTextComponentSubstringPlayerName(bName) EndTextCommandSetBlipName(blip) SetBlipAsShortRange(blip, true) return blip end end RegisterCommand('addpoint', function(source, args) local blipID = tonumber(args[1]) local blipName = args[2] if blipID ~= nil and blipName ~= nil then local waypointBlip = GetFirstBlipInfoId( 8 ) local coord = GetEntityCoords(GetPlayerPed(-1)) local blip = createBlip(coord, blipID, blipName) blips[blipName] = {coord, blipID, blip} TriggerServerEvent("playerpoint:saveBlip", blips) else TriggerEvent('chat:addMessage', { args = { '[Error] /addpoint <blipId> <blipName>' } }) end end, false) RegisterCommand('removepoint', function(source, args) if args[1] ~= nil then local blipName = args[1] if blips[blipName] ~= nil then local blipName = args[1] local blip = blips[blipName][3] blips[blipName] = nil RemoveBlip(blip) TriggerServerEvent("playerpoint:saveBlip", blips) else TriggerEvent('chat:addMessage', { args = { string.format('[Error] Blip name %s does not exist.', blipName) } }) end else TriggerEvent('chat:addMessage', { args = { '[Error] /removepoint <blipName>' } }) end end, false) RegisterNUICallback("createPoint", function(data, cb) local blipID = tonumber(data.blipId) local blipName = data.blipName local waypointBlip = GetFirstBlipInfoId( 8 ) local coord = GetEntityCoords(GetPlayerPed(-1)) local blip = createBlip(coord, blipID, blipName) blips[blipName] = {coord, blipID, blip} TriggerServerEvent("playerpoint:saveBlip", blips) end) RegisterNUICallback("closeHUD", function(data, cb) SetNuiFocus(false, false) SendNUIMessage({ type = "ui", display = false }) hudShowing = false end) RegisterNetEvent("openHUD") AddEventHandler("openHUD", function() SetNuiFocus(true, true) SendNUIMessage({ type = "ui", display = true }) hudShowing = true end) Citizen.CreateThread(function() while true do Wait(0) if not keyPressed then if IsControlPressed(0, 29) then keyPressed = true if not hudShowing then TriggerEvent("openHUD") else TriggerEvent("closeHUD") end end end if keyPressed then if not IsControlPressed(0, 29) then keyPressed = false end end end end)
local fennel = require "fennel" table.insert(package.loaders or package.searchers, fennel.searcher) require "raymarching"
-- An iterator that steps through every non-empty substring of a given string. function subs(s) function iter(state, ix) local h = state.head local t = state.tail + 1 local m = state.max -- If tail has moved past the end advance head and reset tail if t > m then h = h + 1 t = h end if h > m then return nil, state end state.head = h state.tail = t return string.sub(s, h, t), state end return iter, {s=s, head=1, tail=0, max=string.len(s)}, '' end io.write('Give me a string to get substrings of: ') local str = io.read() for sub in subs(str) do print(sub) end
-- << Services >> -- local MarketplaceService = game:GetService("MarketplaceService") local TweenService = game:GetService("TweenService") local Players = game:GetService("Players") local RS = game:GetService("ReplicatedStorage") local CollectionService = game:GetService("CollectionService") -- << Constants >> -- local CLIENT = script.Parent.Parent.Parent local MODULES = CLIENT.Parent:WaitForChild("Modules") local PLAYER = Players.LocalPlayer local GUI = PLAYER:WaitForChild("PlayerGui") local NEWMENU = GUI:WaitForChild("DesktopPauseMenu").Base.Mask local MODIFYSKIN = NEWMENU.EditWindow.NotHide.AnalyzeWindow.Analyze.ModifySkin local LIMBSHOWER = NEWMENU.EditWindow:WaitForChild("SkinLimbShower") local SWAPPART = MODIFYSKIN.SwapPart local COLOURPICK = MODIFYSKIN.ColourPicker local SAVE = MODIFYSKIN.Save local SAVESLOTS = SAVE.WorkingSpace -- << Modules >> -- local Socket = require(MODULES.socket) local PaletteScript = require(MODULES.PaletteScript) local ColourPicker = require(MODULES.ColorPicker) local Hint = require(CLIENT.UIEffects.Hint) local DataValues = require(CLIENT.DataValues) local Morpher = require(RS.Scripts.Modules.Morpher) -- << Variables >> -- local currentColourGroups = {"Primary", "Secondary", "Tertiary", "Quaternary"} local limbInfo = Morpher:GetLimbInfo() local currentColourTarget local currentOutfitSlot ----------------------------- NEWMENU:GetPropertyChangedSignal("Size"):Connect(function() MODIFYSKIN.Visible = false LIMBSHOWER.Visible = false COLOURPICK.Visible = false NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.SaveSet.Visible = false NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.LoadSet.Visible = false SAVE.Visible = false SWAPPART.Temp:ClearAllChildren() end) MODIFYSKIN:GetPropertyChangedSignal("Visible"):Connect(function() NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.SaveSet.Visible = false NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.LoadSet.Visible = false local colorPick = GUI:FindFirstChild("Colorpicker") if colorPick then colorPick:Destroy() end SWAPPART.Temp:ClearAllChildren() for _, window in ipairs(MODIFYSKIN:GetChildren()) do window.Visible = window.Name == SWAPPART.Name and true or false end end) NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.ModifySet.MouseButton1Down:Connect(function() local CHARACTER = PLAYER.Character or PLAYER.CharacterAdded:Wait() NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.Equip.Visible = false MODIFYSKIN.Visible = not MODIFYSKIN.Visible NEWMENU.EditWindow.Weapons.Visible = not MODIFYSKIN.Visible TweenService:Create(GUI.DesktopPauseMenu.Gradient, TweenInfo.new(0.5, Enum.EasingStyle.Linear), {ImageTransparency = not NEWMENU.EditWindow.Weapons.Visible and 1 or 0}):Play() if not NEWMENU.EditWindow.Weapons.Visible then DataValues.CAMERAOFFSET = Vector3.new(4, 0.25, 6) for limb, _ in pairs(DataValues.CharInfo.CurrentSkinPieces) do local part = CHARACTER:FindFirstChild(limb) if part then local newBillboard = SWAPPART.Template.BillboardGui:Clone() newBillboard.TextButton.Text = limb newBillboard.Adornee = part newBillboard.Enabled = true newBillboard.Parent = SWAPPART.Temp newBillboard.TextButton.MouseButton1Down:Connect(function() if COLOURPICK.Visible then currentColourTarget = PLAYER.Character:FindFirstChild(limbInfo[limb]) COLOURPICK.WorkingSpace.Targeting.Target.Text = currentColourTarget and limb or "Nothing" for _, limb in ipairs(SWAPPART.Temp:GetChildren()) do limb.Enabled = false end else local oldInventory = LIMBSHOWER:FindFirstChild("Inventory") if oldInventory then oldInventory:Destroy() end local newInventory = NEWMENU.EditWindow.Weapons.Inventory:Clone() newInventory.Size = UDim2.new(1, 0, 0.9, 0) newInventory.Position = UDim2.new(0, 0, 0.1, 0) for _, outfitButton in ipairs(newInventory:GetChildren()) do if outfitButton:IsA("Frame") then outfitButton.TextButton.MouseButton1Down:Connect(function() Socket:Emit("EquipPiece", limb, outfitButton.Name) LIMBSHOWER.Visible = false end) end end newInventory.Parent = LIMBSHOWER LIMBSHOWER.Visible = true end end) end end end end) SWAPPART.Buttons.ColourChange.MouseButton1Down:Connect(function() local success = pcall(function() return MarketplaceService:UserOwnsGamePassAsync(PLAYER.UserId, 7052268) end) if success then SWAPPART.Visible = false SAVE.Visible = false COLOURPICK.Visible = true currentColourTarget = PLAYER.Character or PLAYER.CharacterAdded:Wait() COLOURPICK.WorkingSpace.Targeting.Target.Text = "Character" for _, limb in ipairs(SWAPPART.Temp:GetChildren()) do limb.Enabled = false end else Hint("Color Dye Module or a Spraycan is required. This can be purchased at the shop.") end end) COLOURPICK.WorkingSpace.Targeting.TargetChar.MouseButton1Down:Connect(function() currentColourTarget = PLAYER.Character COLOURPICK.WorkingSpace.Targeting.Target.Text = "Character" for _, limb in ipairs(SWAPPART.Temp:GetChildren()) do limb.Enabled = false end end) COLOURPICK.WorkingSpace.Targeting.TargetLimb.MouseButton1Down:Connect(function() Hint("Select a limb on the left to target.") for _, limb in ipairs(SWAPPART.Temp:GetChildren()) do limb.Enabled = true end end) COLOURPICK.WorkingSpace.ColourType.Reset.MouseButton1Down:Connect(function() local target = currentColourTarget == PLAYER.Character and DataValues.CharInfo.CurrentSkinPieces if not target then for realLimb, limb in pairs(limbInfo) do if limb == currentColourTarget.Name then target = {} target[realLimb] = DataValues.CharInfo.CurrentSkinPieces[realLimb] break end end end local published = {} for limb, value in pairs(target) do local colours = {} local convertedLimb = limbInfo[limb] local armor = RS.Models.Armor:FindFirstChild(value.N) --- Find original armor piece colours if armor then local limbPart = armor:FindFirstChild(convertedLimb) if limbPart then for _, part in ipairs(limbPart:GetDescendants()) do if part:IsA("BasePart") then local tags = CollectionService:GetTags(part) for _, tag in ipairs(tags) do if not colours[tag] and table.find(currentColourGroups, tag) then colours[tag] = part.Color end end end end end end if not published[limb] then published[limb] = {} end --- Reset current worn armor pieces to normal colours local findPiece = PLAYER.Character:FindFirstChild(convertedLimb) if findPiece then for _, part in ipairs(findPiece:GetDescendants()) do if part:IsA("BasePart") then for colourGroup, colour in pairs(colours) do if CollectionService:HasTag(part, colourGroup) then part.Color = colour published[limb][colourGroup] = -1 end end end end end end Socket:Emit("ChangeColour", published) end) for _, colourGroup in ipairs(COLOURPICK.WorkingSpace.ColourType:GetChildren()) do if colourGroup:IsA("TextButton") and colourGroup.Name ~= "Reset" then colourGroup.MouseButton1Down:Connect(function() COLOURPICK.Visible = false local ui = ColourPicker:Init() local published = {} local isCharacter = currentColourTarget == PLAYER.Character ui.Frame.ColourPicking.Event:Connect(function(changingColour) for _, part in ipairs(currentColourTarget:GetDescendants()) do if part:IsA("BasePart") then if CollectionService:HasTag(part, colourGroup.Name) then part.Color = changingColour for realLimb, limb in pairs(limbInfo) do if limb == part.Parent.Name then if not published[realLimb] then published[realLimb] = {} end published[realLimb][colourGroup.Name] = part.Color break end end end end end end) local applied, finalColour = ColourPicker:Prompt(ui) if applied then COLOURPICK.Visible = true Socket:Emit("ChangeColour", published) end end) end end SWAPPART.Buttons.Save.MouseButton1Down:Connect(function() SWAPPART.Visible = false COLOURPICK.Visible = false SAVE.Visible = true currentOutfitSlot = nil for i = 1, DataValues.AccInfo.OutfitSlots do local outfitSlot = SAVESLOTS[string.format("Slot%s", i)] outfitSlot.Lock.Visible = false outfitSlot.ViewportFrame:ClearAllChildren() for slotName, slotData in pairs(DataValues.CharInfo.CurrentSkinLoadout) do if slotName == outfitSlot.Name and slotData.Head then --- See if it exists first local worldModel = Instance.new("WorldModel") local newRig = PLAYER.Character:Clone() local camera = Instance.new("Camera", outfitSlot.ViewportFrame) for _, model in ipairs(newRig:GetChildren()) do if model:IsA("Model") or model:IsA("Script") or model:IsA("LocalScript") then model:Destroy() end end newRig.PrimaryPart.Anchored = true newRig.Parent = worldModel worldModel.Parent = outfitSlot.ViewportFrame local Pos = CFrame.new(newRig.PrimaryPart.Position + (newRig.PrimaryPart.CFrame.LookVector * 4)) camera.CameraType = Enum.CameraType.Scriptable camera.CameraSubject = newRig.PrimaryPart camera.CFrame = CFrame.lookAt(Pos.Position, newRig.PrimaryPart.Position) Morpher:morph(newRig, slotData) outfitSlot.ViewportFrame.CurrentCamera = camera end end end end) for _, slot in ipairs(SAVESLOTS:GetChildren()) do if slot:IsA("Frame") then slot.TextButton.MouseButton1Down:Connect(function() if not slot.Lock.Visible then currentOutfitSlot = slot NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.ModifySet.Visible = false NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.SaveSet.Visible = true NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.LoadSet.Visible = true else Hint("Additional outfit slots can be purchased at the shop.") end end) end end NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.SaveSet.MouseButton1Down:Connect(function() local slotName = currentOutfitSlot.Name NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.SaveSet.Visible = false NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.LoadSet.Visible = false local success, newCharacterData = Socket:Request("OutfitManage", "Save", slotName) if success ~= -1 then Hint(string.format("Outfit saved to %s", slotName)) currentOutfitSlot.ViewportFrame:ClearAllChildren() local slotData = DataValues.CharInfo.CurrentSkinPieces local newRig = PLAYER.Character:Clone() local camera = Instance.new("Camera", currentOutfitSlot.ViewportFrame) newRig.Parent = currentOutfitSlot.ViewportFrame local Pos = CFrame.new(newRig.PrimaryPart.Position + (newRig.PrimaryPart.CFrame.LookVector * 4)) camera.CameraType = Enum.CameraType.Scriptable camera.CameraSubject = newRig.PrimaryPart camera.CFrame = CFrame.lookAt(Pos.Position, newRig.PrimaryPart.Position) currentOutfitSlot.ViewportFrame.CurrentCamera = camera DataValues.CharInfo = newCharacterData end end) NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.LoadSet.MouseButton1Down:Connect(function() local slotName = currentOutfitSlot.Name NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.SaveSet.Visible = false NEWMENU.EditWindow.NotHide.AnalyzeWindow.Buttons.LoadSet.Visible = false local success = Socket:Request("OutfitManage", "Load", slotName) if success == -1 then Hint("Cannot load outfit from empty slot.") return end if success then Hint(string.format("Outfit loaded from %s", slotName)) end end) return nil
--Lua syntax parser --Lua Keywords local keywords = { "and", "break", "do", "else", "elseif", "end", "false", "for", "function", "if", "in", "local", "nil", "not", "or", "repeat", "return", "then", "true", "until", "while" } --Lua escapable characters local escapable = {"a", "b", "f", "n", "r", "t", "v", "\\", '"', "'"} --LIKO-12 API Functions local api = _APIList --LIKO-12 Callbacks local callbacks = {"_draw","_draw30","_draw60","_init","_keypressed","_keyreleased","_mousemoved","_mousepressed","_mousereleased","_textinput","_touchcontrol","_touchmoved","_touchpressed","_touchreleased","_update","_update30","_update60","_wheelmoved","_filedropped","self"} --Convert values to keys for instant searching for _, list in ipairs({keywords, api, callbacks, escapable}) do for i=1, #list do list[list[i]] = true list[i] = nil end end local function token(stream, state) if state.tokenizer == "base" then local char = stream:next() --Read a character from the stream local pos = stream.pos --The position of the next character --Comment and multiline comment matching if char == "-" and stream:eat('%-') then --Parse the '--' if stream:match("^%[=*%[") then --It's a multilineComment state.tokenizer = "multilineComment" state.multilen = stream.pos - pos - 3 else --It's a single line comment stream:skipToEnd() --The rest of the line is a comment return "comment" end --String matching elseif char == '"' or char == "'" then state.starter = char state.tokenizer = "string" return "string" -- Return immediatelly so quotes doesn't get affected by escape sequences -- Decimal numbers elseif char == '.' and stream:match('%d+') then return "number" -- Hex and Binary numbers elseif char == "0" and (stream:eat("[xX]") or stream:eat("[bB]")) then stream:eatChain("%x") return "number" -- Ints and floats numbers elseif char:find('%d') then stream:eatChain("%d") stream:match("\\.%d+") local nextChar = stream:peek() or "" -- TODO: Do this to hex and decimals too if not nextChar:find("[%w_]") then return "number" end -- Multiline string matching elseif char == "[" and stream:match("^=*%[") then state.multilen = stream.pos - pos - 1 state.tokenizer = "multilineString" return "string" -- Keyword matching elseif char:find('[%w_]') then stream:eatChain('[%w_]') local word = stream:current() if keywords[word] then return "keyword" elseif api[word] then return "api" elseif callbacks[word] then return "callback" end end end if state.tokenizer == "string" then local char = stream:next() if char == "\\" then local escaped = stream:peek() if escaped and escapable[escaped] then stream:next() return "escape" end elseif char == state.starter then state.starter = "" state.tokenizer = "base" else if stream:eol() then state.tokenizer = "base" end end return "string" elseif state.tokenizer == "multilineString" then local char = stream:next() if char == "\\" then local escaped = stream:peek() if escaped and escapable[escaped] then stream:next() return "escape" end elseif char == "]" and stream:match("^" .. string.rep("=", state.multilen) .. "%]") then state.tokenizer = "base" end return "string" elseif state.tokenizer == "multilineComment" then if stream:skipTo("%]" .. string.rep("=", state.multilen) .. "%]") then stream:next() state.tokenizer = "base" else stream:skipToEnd() end return "comment" end end return { startState = { tokenizer = "base", multilen = 0, --Multiline comment/string '==' number, example: [=[ COMMENT ]=] -> 1 starter = "" }, token = token }
local L = BigWigs:NewBossLocale("Master Snowdrift", "ptBR") if not L then return end if L then -- Quando eu era filhote, eu mal conseguia dar uns soquinhos, mas após anos de treinamento eu consigo muito mais! L.stage3_yell = "era filhote" end
--[[ ä Name: Advanced Questbook By: Crypton ]] if (AQB_ITEM_STRINGS == nil) then AQB_ITEM_STRINGS = { ["AQB_LC"] = TEXT("Sys202939_name") or TEXT("Sys202939_name_plural"), ["AQB_IC"] = TEXT("Sys202940_name") or TEXT("Sys202940_name_plural"), ["AQB_TC"] = TEXT("Sys202941_name") or TEXT("Sys202941_name_plural"), ["AQB_OL"] = TEXT("Sys201764_name") or TEXT("Sys201764_name_plural"), ["AQB_CN"] = TEXT("Sys201726_name") or TEXT("Sys201726_name_plural"), ["AQB_MSAP"] = TEXT("Sys201802_name") or TEXT("Sys201802_name_plural"), ["AQB_ASE"] = TEXT("Sys202942_name") or TEXT("Sys202942_name_plural"), ["AQB_SE"] = TEXT("Sys202943_name") or TEXT("Sys202943_name_plural"), ["AQB_ME"] = TEXT("Sys202944_name") or TEXT("Sys202944_name_plural"), ["AQB_AL"] = TEXT("Sys201761_name") or TEXT("Sys201761_name_plural"), ["AQB_ZN"] = TEXT("Sys201723_name") or TEXT("Sys201723_name_plural"), ["AQB_MDGS"] = TEXT("Sys201799_name") or TEXT("Sys201799_name_plural"), ["AQB_WL"] = TEXT("Sys201762_name") or TEXT("Sys201762_name_plural"), ["AQB_TN"] = TEXT("Sys201724_name") or TEXT("Sys201724_name_plural"), ["AQB_BSAP"] = TEXT("Sys201800_name") or TEXT("Sys201800_name_plural"), ["AQB_MS"] = TEXT("Sys202945_name") or TEXT("Sys202945_name_plural"), ["AQB_SOW"] = TEXT("Sys202946_name") or TEXT("Sys202946_name_plural"), ["AQB_HHS"] = TEXT("Sys202947_name") or TEXT("Sys202947_name_plural"), }; end
local reports = require "kong.reports" local redis = require "resty.redis" local kong = kong local null = ngx.null local shm = ngx.shared.kong_rate_limiting_counters local fmt = string.format local EMPTY_UUID = "00000000-0000-0000-0000-000000000000" local EXPIRATION = 10*60 local function is_present(str) return str and str ~= "" and str ~= null end local function get_service_and_route_ids(conf) conf = conf or {} local service_id = conf.service_id local route_id = conf.route_id if not service_id or service_id == null then service_id = EMPTY_UUID end if not route_id or route_id == null then route_id = EMPTY_UUID end return service_id, route_id end local get_local_key = function(conf, identifier, period, period_date) local service_id, route_id = get_service_and_route_ids(conf) return fmt("concurrent-connections-quota:%s:%s:%s", route_id, service_id, identifier) end local sock_opts = {} local function get_redis_connection(conf) local red = redis:new() red:set_timeout(conf.redis_timeout) -- use a special pool name only if redis_database is set to non-zero -- otherwise use the default pool name host:port sock_opts.pool = conf.redis_database and conf.redis_host .. ":" .. conf.redis_port .. ":" .. conf.redis_database local ok, err = red:connect(conf.redis_host, conf.redis_port, sock_opts) if not ok then kong.log.err("failed to connect to Redis: ", err) return nil, err end local times, err = red:get_reused_times() if err then kong.log.err("failed to get connect reused times: ", err) return nil, err end if times == 0 then if is_present(conf.redis_password) then local ok, err = red:auth(conf.redis_password) if not ok then kong.log.err("failed to auth Redis: ", err) return nil, err end end if conf.redis_database ~= 0 then -- Only call select first time, since we know the connection is shared -- between instances that use the same redis database local ok, err = red:select(conf.redis_database) if not ok then kong.log.err("failed to change Redis database: ", err) return nil, err end end end reports.retrieve_redis_version(red) return red end return { ["local"] = { increment = function(conf, identifier, value) local cache_key = get_local_key(conf, identifier) local newval, err = shm:incr(cache_key, value, 0) if not newval then kong.log.err("could not increment counter: ", err) return nil, err end return true end, decrement = function(conf, identifier, value) local cache_key = get_local_key(conf, identifier) local newval, err = shm:incr(cache_key, -1*value, 0) -- no shm:decr sadly if not newval then kong.log.err("could not increment counter: ", err) return nil, err end return true end, usage = function(conf, identifier) local cache_key = get_local_key(conf, identifier) local current_metric, err = shm:get(cache_key) if err then return nil, err end if current_metric == nil or current_metric < 0 then current_metric = 0 shm:set(cache_key, 0) end return current_metric or 0 end }, ["redis"] = { increment = function(conf, identifier, value) local red, err = get_redis_connection(conf) if not red then kong.log.err("failed to connect to Redis: ", err) return nil, err end local cache_key = get_local_key(conf, identifier) red:init_pipeline() red:incrby(cache_key, value) red:expire(cache_key, EXPIRATION) local _, err = red:commit_pipeline() if err then kong.log.err("failed to commit pipeline in Redis: ", err) return nil, err end local ok, err = red:set_keepalive(10000, 100) if not ok then kong.log.err("failed to set Redis keepalive: ", err) return nil, err end return true end, decrement = function(conf, identifier, value) local red, err = get_redis_connection(conf) if not red then kong.log.err("failed to connect to Redis: ", err) return nil, err end local cache_key = get_local_key(conf, identifier) red:init_pipeline() red:decrby(cache_key, value) red:expire(cache_key, EXPIRATION) local _, err = red:commit_pipeline() if err then kong.log.err("failed to commit pipeline in Redis: ", err) return nil, err end local ok, err = red:set_keepalive(10000, 100) if not ok then kong.log.err("failed to set Redis keepalive: ", err) return nil, err end return true end, usage = function(conf, identifier) local red, err = get_redis_connection(conf) if not red then kong.log.err("failed to connect to Redis: ", err) return nil, err end local cache_key = get_local_key(conf, identifier) local current_metric, err = red:get(cache_key) if err then return nil, err end if current_metric == null or current_metric == nil or tonumber(current_metric) < 0 then current_metric = 0 red:init_pipeline() red:set(cache_key, 0) local _, err = red:commit_pipeline() if err then kong.log.err("failed to commit pipeline in Redis: ", err) end end local ok, err = red:set_keepalive(10000, 100) if not ok then kong.log.err("failed to set Redis keepalive: ", err) end return current_metric or 0 end } }
function shift(a) local out = a << 9 shift(out) end shift(1)
-------------------------core------------------------- package.preload["core/sceneLoader"] = function() return require('editorRT/sceneLoader') end package.preload["core/http"] = function() return require('network/http') end package.preload["core/shaderManager"] = function() return require('coreex/shaderManager') end package.preload["core/socket"] = function() return require('network/socket') end package.preload["coreex/sceneLoaderex"] = function() return require('editorRT/sceneLoader') end -------------------------coreex------------------------- package.preload["coreex/httpex"] = function() return require('network/http') end -------------------------swfTween------------------------- package.preload["swfTween/drawingex2"] = function() end package.preload["swfTween/swfPlayer"] = function() end -------------------------alphaAreaY------------------------- package.preload["libEffect/shaders/alphaAreaY"] = function() return require('coreex/alphaAreaY') end
-- Note: This file is loaded by lsunit.lua print("-- LuaSkinTests testinit.lua loaded")
local syntaxTable = { ["s"] = "#00a8ff[Melancia]#ffffff ", ["e"] = "#e84118[Melancia]#ffffff ", ["w"] = "#fbc531[Melancia]#ffffff ", } addEvent("skinshop-system:buySkin", true) addEventHandler("skinshop-system:buySkin", root, function(player, skinID, price) if exports["mrp_global"]:hasMoney(player, tonumber(price)) then exports["mrp_global"]:takeMoney(player, tonumber(price)) outputChatBox(syntaxTable["s"].."Kıyafet başarıyla satın alındı.",player,255,255,255,true) exports["mrp_global"]:giveItem(player, 16, tonumber(skinID)) setElementModel(player, tonumber(skinID)) end end )
local Util = require("vlua.util") local Watcher = require("vlua.watcher") local pairs = pairs local warn, isRef = Util.warn, Util.isRef local xpcall = xpcall local tinsert, tpop = table.insert, table.remove ---@class Binder ---@field children Binder[] ---@field events table<string, fun():nil> local Binder = Util.class("Binder") function Binder:ctor(source, parent) self.source = source self.parent = parent end local HookIds = { mounted = 1, unmount = 2, destroy = 3, errorCaptured = 4 } Binder.HookIds = HookIds -- The current target watcher being evaluated. -- This is globally unique because only one watcher -- can be evaluated at a time. ---@type Binder local target = nil local targetStack = {} ---@param context Binder local function pushContext(context) tinsert(targetStack, context) target = context end local function popContext() tpop(targetStack) target = targetStack[#targetStack] end function Binder:emit(event, ...) local events = self[event] if not events then return end for _, cb in pairs(events) do cb(...) end end function Binder:on(event, cb) local events = self[event] if not events then events = {} self[event] = events end events[cb] = cb end function Binder:off(event, cb) local events = self[event] if events then events[cb] = nil end end function Binder:once(event, cb) local function callback(...) self:off(event, callback) cb(...) end self:on(event, callback) end --- unwatch all watcher and teardown function Binder:teardown() self:emit(HookIds.unmount) self:emit(HookIds.destroy) end function Binder:createChild(source) local child = Binder.new(source, self) self:onUnmount( function() child:teardown() end ) return child end function Binder.apiNewBinder(source) if target then return target:createChild(source) else return Binder.new(source) end end --- create a reactive function ---@param fn fun():nil function Binder:newFunction(fn) -- a content hold my watches and all children ---@type Binder local binder = self and self:createChild() or Binder.new() local reactiveFn = function() binder:emit(HookIds.unmount) pushContext(binder) local value = xpcall( fn, function(msg) warn("error when new:" .. msg .. " stack :" .. debug.traceback()) binder:emit(HookIds.errorCaptured, msg) end, binder ) popContext(binder) binder:emit(HookIds.mounted, value) end -- watch and run one time local watcher = Watcher.new(nil, reactiveFn) -- only teardown when destory, but not unmount binder:once( HookIds.destroy, function() watcher:teardown() end ) return binder end --- create a reactive function ---@param fn fun():nil function Binder.apiNew(fn) return Binder.newFunction(target, fn) end function Binder:onMounted(cb) self:on(HookIds.mounted, cb) end function Binder:onUnmount(cb) self:on(HookIds.unmount, cb) end function Binder:onDestroy(cb) self:on(HookIds.destroy, cb) end function Binder:onErrorCaptured(cb) self:on(HookIds.errorCaptured, cb) end --- call cb when expr changed ---@param expOrFn string | Function | Ref | Computed ---@param cb Function ---@param immediacy boolean @call cb when start function Binder:watch(expOrFn, cb, immediacy) -- support to watch ref or computed value if isRef(expOrFn) then local ref = expOrFn expOrFn = function() return ref.value end end -- watch and run one time local watcher = Watcher.new(self.source, expOrFn, cb) self:onUnmount( function() watcher:teardown() end ) if immediacy then cb(self.source, watcher.value, watcher.value) end end return Binder
-- -- THIS FILE HAS BEEN GENERATED AUTOMATICALLY -- DO NOT CHANGE IT MANUALLY UNLESS YOU KNOW WHAT YOU'RE DOING -- -- GENERATED USING @colyseus/schema 1.0.0-alpha.58 -- local schema = require 'colyseus.serialization.schema.schema' local PlayerV2 = require 'test.schema.BackwardsForwards.PlayerV2' local StateV2 = schema.define({ ["str"] = "string", ["map"] = { map = PlayerV2 }, ["countdown"] = "number", ["_fields_by_index"] = { "str", "map", "countdown" }, }) return StateV2
local key = KEYS[1] local id = ARGV[1] local ms = ARGV[2] local current_id = redis.call('GET', key) if (id == current_id) then redis.call('PEXPIRE', key, ms) return 1 else return 0 end
--[=============================================================================[ The MIT License (MIT) Copyright (c) 2014 RepeatPan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]=============================================================================] --! realm jelly local util = {} -- Localise stuff. local jelly, radiant = jelly, radiant local table = table local type, pairs, setmetatable, loadstring, next = type, pairs, setmetatable, loadstring, next --! desc Attempts to "mixinto" `parents` into `child`. --! param table child Table that should receive the parent's data. --! param table parents A table that contains the values we should inherit. --! remarks Numeric tables will be merged (i.e. the parent's values will be placed after the child ones, --! remarks if any), other values will be hard-copied over. In the end, `child` can override any value --! remarks that is set in any of the `parents`, except tables, which can only be added. --! remarks --! remarks Currently, this only works with "flat" classes, i.e. tables contained in child or parent are --! remarks assumed to be numeric arrays that are to be merged. --! EXPERIMENTAL function util.mixinto(child, parents) -- Create the "inherited" table local t = {} -- For each parent... for _, parent in pairs(parents) do -- For each key in each parent... for k, v in pairs(parent) do -- If the key already exists as table and the new one's a table too, merge. if type(t[k]) == 'table' and type(v) == 'table' then for i = 1, #v do table.insert(t[k], v) end -- Otherwise, this parent overwrites the old one. But just to make sure, copy it. else t[k] = util.copy(v) end end end -- Now that we have our base, copy our child in. for k, v in pairs(child) do -- The child does not specify this key: Copy it from the parents. if type(v) == 'table' and type(t[k]) == 'table' then -- t[k] is already a copy. for i = 1, #v do table.insert(t[k], v) end else t[k] = util.copy(v) end -- otherwise the key already existed in the child, therefore was overwritten end return t end --! desc Creates a shallow copy of `tbl`. --! param table tbl Table to be copied. If `tbl` is not a table it will simply be returned. --! returns table Simple copy of `tbl`. --! remarks This does **not** create a deep table. Tables inside of `tbl` will simply be referenced! function util.copy(tbl) if type(tbl) ~= 'table' then return tbl end local t = {} for k,v in pairs(tbl) do t[k] = v end return t end -- LOADING is bad, nil is good, LOADED is better local LOADING, LOADED = 0, 1 -- Loads elements[name] and makes sure to mixin parent_key stuff if encountered local function load_class(elements, parent_key, loaded, name) local class = elements[name] -- Avoid cycles. if loaded[name] == LOADING then error('cyclic behaviour detected while loading class ' .. name) -- Avoid duplicate loading. elseif loaded[name] == LOADED then return class end -- Make sure it's a table. Load if necessary. Create a copy. elements[name] = util.copy(jelly.resources.load_table(class)) -- mutex. loaded[name] = LOADING -- Get the parents, if any local parents = class[parent_key] or {} -- Strength through uniformity . if type(parents) ~= 'table' then parents = { parents } end local mixintos = {} -- Load all parents for k, parent_name in pairs(parents) do table.insert(mixintos, load_class(elements, parent_key, loaded, parent_name)) end -- Merge magic. class = util.mixinto(class, mixintos) -- Loaded. loaded[name] = LOADED elements[name] = class return class end -- TODO: Refactor this into some sort of factory local classes_cache = {} local classes_loaded = {} --! desc Attempts to load `name` as class. `name` is a defined alias (or file path) that defines the class. --! param string name Name of the class to load. This has to be an alias. --! param string parent_key Name that defines what the class' inheritance system is based on. --! returns table containing the finished class function util.load_class(name, parent_key) local class = classes_cache[name] if class then return class end class = load_class(util.json_table(), parent_key, classes_loaded, name) classes_cache[name] = class return class end --! desc Builds "classes" out of `elements`, using `parent_key` to determine inheritance/mixintos. --! param table elements A hash table/object that contains the classes (`class_name => class_data`) --! param string parent_key The key that determines which key in a class defines its parents/mixintos --! returns table The modified `elements`. --! remarks Internally, it's loading the parents using `jelly.resources.load_table` and the inheritance --! remarks is dealt with by `jelly.util.mixinto`. This function modifies `elements`. --! This can be used to create "classes" or other (named) mixintos. --! EXPERIMENTAL function util.build_classes(elements, parent_key) local loaded = {} elements = util.copy(elements) for class_name, _ in pairs(elements) do elements[class_name] = load_class(elements, parent_key, loaded, class_name) end return elements end local json_table = nil --! desc Returns a table that, if accessed by key, tries to load the json identified by that name. --! returns Magic table. function util.json_table() if json_table then return json_table end json_table = setmetatable({}, { __index = function(tbl, key) local json = radiant.resources.load_json(key) tbl[key] = json return json end }) return json_table end --! desc Requires `file`, which is a path to a lua file (without extension), relative to "/mods". --! param string file Module to be required. Without file extensions. Slashes or periods (`.`) are acceptable. --! returns value The file. Usually, this is a `table` or `class`, although it depends on the file. --! remarks Since `radiant.mods.require`could be mis-interpreted as "load a mod" opposed to --! remarks "load a file", this function does explicitly the latter. function util.require(file) return _host:require(file) end --! desc Checks if `tbl` contains `value`. --! param table tbl Table to check --! param value value Value to find --! returns true if the value is in tbl, false otherwise function util.contains(tbl, value) for k, v in pairs(tbl) do if v == value then return true end end return false end --! desc Compiles `str` into a function, if any. `args` is a table of string which contains the function's passed arguments. --! param string str Function's return value. --! param table args Table containing the name of the passed arguments, as strings. --! returns function if the compilation succeeded, false and the error message otherwise --! remarks Because the "return" statement of the function is given, this may only be used for very simple calculations. --! remarks Its real use is to have json defined short functions for attributes, chances or simple calculations. function util.compile(str, args) if not str then return nil, "str is nil" end local argStr = table.concat(args, ',') return loadstring(string.format('local %s=... return %s', table.concat(args, ','), str)) end -- Used to allow chaining of linq functions -- without interfering with the normal metatable's index -- (if available) local linq_meta_index_table local function __linq_index(tbl, key) local m = getmetatable(tbl) local val if m.__jelly_pre_linq_index then val = m.__jelly_pre_linq_index(tbl, key) if val ~= nil then return val end end -- Is it a linq function? return linq_meta_index_table[key] end --! desc Sets the metatable of `tbl` to allow chaining of operations --! param table tbl Table that should be linqified function util.linqify(tbl) local m = getmetatable(tbl) if m then -- If this table was already patched, don't patch it again if m.__jelly_linqed then return tbl end if m.__index then m.__jelly_pre_linq_index = m.__index end else m = {} end m.__index = __linq_index m.__jelly_linqed = true return setmetatable(tbl, m) end --! desc Maps `tbl` using `func`. --! param table tbl Table that should be mapped --! param function func Function that receives two arguments (`key`, `value`) and returns the new element. --! returns table with mapped values function util.map(tbl, func) local t = {} for k, v in jelly.linq.map_pairs(tbl, func) do t[k] = v end return util.linqify(t) end --! desc Filters `tbl` using `func` --! param table tbl Table that should be filtered --! param function func Function that receives two arguments: (`key`, `value`) and returns true if the element should be taken, false otherwise --! returns table with reduced entries --! remarks **Note:** This function will **not** re-sort the table; i.e. the keys are consistent. This can lead to "holes". Use to_list() to fix these if an array is desired. function util.where(tbl, func) local t = {} for k, v in jelly.linq.where_pairs(tbl, func) do t[k] = v end return util.linqify(t) end --! desc re-sorts `tbl` to be a normal array without "holes" as keys. --! param table tbl --! returns re-arranged table function util.to_list(tbl) local t = {} local tn = 1 for k, v in pairs(tbl) do t[tn] = v tn = tn + 1 end return util.linqify(t) end linq_meta_index_table = { map = util.map, where = util.where, to_list = util.to_list } --! desc Returns the best key/value in a table by calling `func` on each pair to evaluate it --! param table tbl Table to maximize over --! param function func Function to call --! DEPRECATED This function is going to be replaced with LINQ. function util.table_max(tbl, func) local k, v, m = next(tbl, nil) if not k then return nil, nil, nil end local best_k, best_v, best_m = k, v, func(k, v) repeat m = func(k, v) if m > best_m then best_k, best_v, best_m = k, v, m end k, v = next(tbl, k) until not k return best_k, best_v, best_m end -- List of things we consider "true" or "false" when dealing with configs. local boolean_table = { [0] = false, ["0"] = false, ["false"] = false, ["no"] = false, [1] = true, ["1"] = true, ["true"] = true, ["yes"] = true } local comfort_table -- Returns `given` in a way it comforts `default` local function comfort_values(given, default) local given_type, default_type = type(given), type(default) -- Not compatible? if given_type ~= default_type then -- Boxing? if default_type == 'table' then return comfort_table({ given }, default) -- tostring elseif default_type == 'string' then return tostring(given) -- numbering elseif default_type == 'number' and tonumber(given) then return tonumber(given) -- booleaning elseif default_type == 'boolean' and boolean_table[given] ~= nil then return boolean_table[given] -- default value else return default -- This will already be properly aligned end -- Otherwise, if both are tables, comfort them elseif default_type == 'table' then return comfort_table(given, default) end return given end -- compares if all values in `given` are comfortable to `default` -- and returns json modified in a way that all values comfort default -- (i.e. have the same type) function comfort_table(given, default) for key, default_value in pairs(default) do local given_value = given[key] -- json does not define this value: We do it. if given_value == nil then given[key] = default_value else -- json does define this value, validate it given[key] = comfort_values(given_value, default_value) end end return given end --! desc Loads the config of the current mod function util.load_config() local mod_name = __get_current_module_name(3) local manifest_loaded, manifest = pcall(radiant.resources.load_manifest, mod_name) if not manifest_loaded then error(string.format('cannot load manifest of %s: %s', mod_name, manifest)) end if not manifest.jelly or not manifest.jelly.default_config then error(string.format('manifest of %s does not contain default config values', mod_name)) end manifest = manifest.jelly.default_config -- Try to load the user settings local user_settings = _host:get_config('mods.' .. __get_current_module_name(3)) -- Try to comfort the user_settings to json (which, by now, is our new default) if user_settings then manifest = comfort_table(user_settings, manifest) end return manifest, user_settings ~= nil end return util
local _, MySlot = ...; local L = MySlot.L; local crc32 = LibStub:GetLibrary("CRC32-1.0"); local base64 = LibStub:GetLibrary("BASE64-1.0"); local pblua = LibStub:GetLibrary('pblua') local _MySlot = pblua.load_proto_ast(MySlot.ast) local MYSLOT_AUTHOR = "T.G. <[email protected]>" local MYSLOT_VER = 24 local MYSLOT_ALLOW_VER = 23 MySlot_SavedDb = MySlot_SavedDb or {} local MYSLOT_LINE_SEP = IsWindowsClient() and "\r\n" or "\n" local MYSLOT_MAX_ACTIONBAR = 120 local MySlot_Scheme = {} local MYSLOT_SPELL = _MySlot.Slot.SlotType.SPELL local MYSLOT_COMPANION = _MySlot.Slot.SlotType.COMPANION local MYSLOT_ITEM = _MySlot.Slot.SlotType.ITEM local MYSLOT_MACRO = _MySlot.Slot.SlotType.MACRO local MYSLOT_FLYOUT = _MySlot.Slot.SlotType.FLYOUT local MYSLOT_EQUIPMENTSET = _MySlot.Slot.SlotType.EQUIPMENTSET local MYSLOT_EMPTY = _MySlot.Slot.SlotType.EMPTY local MYSLOT_SUMMONPET = _MySlot.Slot.SlotType.SUMMONPET local MYSLOT_SUMMONMOUNT = _MySlot.Slot.SlotType.SUMMONMOUNT local MYSLOT_NOTFOUND = "notfound" MySlot.SLOT_TYPE = { ["spell"] = MYSLOT_SPELL, ["companion"] = MYSLOT_COMPANION, ["macro"]= MYSLOT_MACRO, ["item"]= MYSLOT_ITEM, ["flyout"] = MYSLOT_FLYOUT, ["petaction"] = MYSLOT_EMPTY, ["futurespell"] = MYSLOT_EMPTY, ["equipmentset"] = MYSLOT_EQUIPMENTSET, ["summonpet"] = MYSLOT_SUMMONPET, ["summonmount"] = MYSLOT_SUMMONMOUNT, [MYSLOT_NOTFOUND] = MYSLOT_EMPTY, } local MYSLOT_BIND_CUSTOM_FLAG = 0xFFFF local function MergeTable(target, source) if source then assert(type(target) == 'table' and type(source) == 'table'); for _,b in ipairs(source) do assert(b < 256); target[#target+1] = b; end return #source; else return 0; end end -- fix unpack stackoverflow local function StringToTable(s) if type(s) ~= 'string' then return {} end local r = {} for i = 1, string.len(s) do r[#r + 1] = string.byte(s, i) end return r end local function TableToString(s) if type(s) ~= 'table' then return '' end local t = {} for _,c in pairs(s) do t[#t + 1] = string.char(c) end return table.concat(t) end function MySlot:Print(msg) print("|CFFFF0000<|r|CFFFFD100MySlot|r|CFFFF0000>|r"..(msg or "nil")); end StaticPopupDialogs["MySlot_SAVE_SET"] = { text = GEARSETS_POPUP_TEXT, button1 = ACCEPT, button2 = CANCEL, hasEditBox = 1, maxLetters = 16, OnAccept = function(self) local name = _G[self:GetName().."EditBox"]:GetText(); if name then local Stable = {}; Stable.Sname = name; Stable.Scheme = MYSLOT_ReportFrame_EditBox:GetText(); Stable.addtime = time(); MySlot_Save_Check(Stable, name); end end, OnShow = function(self) local SnameTemplate = ""; SnameTemplate = (UnitClass("player")).." - "..UnitName("player"); _G[self:GetName().."EditBox"]:SetText(SnameTemplate); _G[self:GetName().."EditBox"]:HighlightText(); _G[self:GetName().."EditBox"]:SetFocus(); end, OnHide = function(self) _G[self:GetName().."EditBox"]:SetText(""); end, OnCancel = function(self) end, EditBoxOnEnterPressed = function(self) local name = _G[self:GetName()]:GetText(); if name then local Stable = {}; Stable.Sname = name; Stable.Scheme = MYSLOT_ReportFrame_EditBox:GetText(); Stable.addtime = time(); MySlot_Save_Check(Stable,name); end self:GetParent():Hide(); end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide(); end, timeout = 0, exclusive = 1, whileDead = 1, hideOnEscape = 1 }; StaticPopupDialogs["MySlot_DELETE_SET"] = { text = MySlot_DEL_Text, button1 = YES, button2 = NO, OnAccept = function(self) local Sname = StaticPopupDialogs["MySlot_DELETE_SET"].Sname; for i,Stable in pairs(MySlot_SavedDb) do if Stable and Stable.Sname and Sname == Stable.Sname then table.remove(MySlot_SavedDb, i); end end if MySlot_SavedDb[1] then MYSLOT_LoadFrame_Update(); MYSLOT_LoadFrameDelButton:Disable() MYSLOT_LoadFrameLoadSchemeButton:Disable(); else HideUIPanel(MYSLOT_LoadFrame); end MYSLOT_LoadFrame.selectedSname = nil; MySlot_Check_Status(); local str = string.format(MySlot_DEL_SUCCESS,Sname); MySlot:Print(str); end, OnCancel = function(self) end, showAlert = 1, timeout = 0, hideOnEscape = 1, whileDead = 1, }; function MySlot:GetMacroInfo(macroId) -- {macroId ,icon high 8, icon low 8 , namelen, ..., bodylen, ...} local name, iconTexture, body, isLocal = GetMacroInfo(macroId) if not name then return nil end local t = {macroId} iconTexture = gsub( strupper(iconTexture or "INV_Misc_QuestionMark") , "INTERFACE\\ICONS\\", ""); local msg = _MySlot.Macro() msg.id = macroId msg.icon = iconTexture msg.name = name msg.body = body return msg end function MySlot:GetActionInfo(slotId) -- { slotId, slotType and high 16 ,high 8 , low 8, } local slotType, index = GetActionInfo(slotId) if MySlot.SLOT_TYPE[slotType] == MYSLOT_EQUIPMENTSET then for i = 1, GetNumEquipmentSets() do if GetEquipmentSetInfo(i) == index then index = i break end end elseif not MySlot.SLOT_TYPE[slotType] then if slotType then self:Print(L["[WARN] Ignore unsupported Slot Type [ %s ] , contact %s please"]:format(slotType , MYSLOT_AUTHOR)) end return nil elseif not index then return nil end local msg = _MySlot.Slot() msg.id = slotId msg.type = MySlot.SLOT_TYPE[slotType] if type(index) == 'string' then msg.strindex = index msg.index = 0 else msg.index = index end return msg end local function KeyToByte(key, command) -- {mod , key , command high 8, command low 8} if not key then return nil end local mod,key = nil, key local t = {} local _,_,_mod,_key = string.find(key ,"(.+)-(.+)") if _mod and _key then mod, key = _mod, _key end mod = mod or "NONE" if not MySlot.MOD_KEYS[mod] then MySlot:Print(L["[WARN] Ignore unsupported Key Binding [ %s ] , contact %s please"]:format(mod, MYSLOT_AUTHOR)) return nil end local msg = _MySlot.Key() if MySlot.KEYS[key] then msg.key = MySlot.KEYS[key] else msg.key = MySlot.KEYS["KEYCODE"] msg.keycode = key end msg.mod = MySlot.MOD_KEYS[mod] return msg end function MySlot:GetBindingInfo(index) -- might more than 1 local _command, _, key1, key2 = GetBinding(index) if not _command then return end local command = MySlot.BINDS[_command] local msg = _MySlot.Bind() if not command then msg.command = _command command = MYSLOT_BIND_CUSTOM_FLAG end msg.id = command msg.key1 = KeyToByte(key1) msg.key2 = KeyToByte(key2) if msg.key1 or msg.key2 then return msg else return nil end end function MySlot:FindOrCreateMacro(macroInfo) if not macroInfo then return end -- cache local macro index local localMacro = {} for i = 1, MAX_ACCOUNT_MACROS + MAX_CHARACTER_MACROS do local name, _, body = GetMacroInfo(i) if name then localMacro[ name .. "_" .. body ] = i localMacro[ body ] = i end end local id = macroInfo["oldid"] local name = macroInfo["name"] local icon = macroInfo["icon"] local body = macroInfo["body"] local localIndex = localMacro[ name .. "_" .. body ] or localMacro[ body ] if localIndex then return localIndex else local numglobal, numperchar = GetNumMacros() local perchar = id > MAX_ACCOUNT_MACROS and 2 or 1 local testallow = bit.bor( numglobal < MAX_ACCOUNT_MACROS and 1 or 0 , numperchar < MAX_CHARACTER_MACROS and 2 or 0) perchar = bit.band( perchar, testallow) perchar = perchar == 0 and testallow or perchar if perchar ~= 0 then -- fix icon using #showtooltip if strsub(body,0, 12) == '#showtooltip' then icon = 'INV_Misc_QuestionMark' end local newid = CreateMacro(name, icon, body, perchar >= 2) if newid then return newid end end self:Print(L["Macro %s was ignored, check if there is enough space to create"]:format(name)) return nil end end StaticPopupDialogs["MYSLOT_MSGBOX"] = { text = MySlot_Sure_Scheme, button1 = OKAY, button2 = CANCEL, timeout = 0, whileDead = 1, hideOnEscape = 1, multiple = 1, } function MySlot_Export() local msg = _MySlot.Charactor() msg.ver = MYSLOT_VER msg.name = UnitName("player") msg.macro = {} for i = 1, MAX_ACCOUNT_MACROS + MAX_CHARACTER_MACROS do local m = MySlot:GetMacroInfo(i) if m then msg.macro[#msg.macro + 1] = m end end msg.slot = {} for i = 1,MYSLOT_MAX_ACTIONBAR do local m = MySlot:GetActionInfo(i) if m then msg.slot[#msg.slot + 1] = m end end msg.bind = {} for i = 1, GetNumBindings() do local m = MySlot:GetBindingInfo(i) if m then msg.bind[#msg.bind + 1] = m end end local ct = msg:Serialize() t = {MYSLOT_VER,86,04,22,0,0,0,0} MergeTable(t, StringToTable(ct)) -- {{{ CRC32 -- crc local crc = crc32.enc(t) t[5] = bit.rshift(crc , 24) t[6] = bit.band(bit.rshift(crc , 16), 255) t[7] = bit.band(bit.rshift(crc , 8) , 255) t[8] = bit.band(crc , 255) -- }}} -- {{{ OUTPUT local s = "" s = "@ --------------------" .. MYSLOT_LINE_SEP .. s s = "@ " .. LEVEL .. ":" ..UnitLevel("player") .. MYSLOT_LINE_SEP .. s s = "@ " .. SPECIALIZATION ..":" .. ( GetSpecialization() and select(2, GetSpecializationInfo(GetSpecialization())) or NONE_CAPS ) .. MYSLOT_LINE_SEP .. s s = "@ " .. CLASS .. ":" ..UnitClass("player") .. MYSLOT_LINE_SEP .. s s = "@ " .. PLAYER ..":" ..UnitName("player") .. MYSLOT_LINE_SEP .. s s = "@ " .. L["Time"] .. ":" .. date() .. MYSLOT_LINE_SEP .. s s = "@ Myslot ( V" .. MYSLOT_VER .. ")" .. MYSLOT_LINE_SEP .. s s = s .. base64.enc(t) MYSLOT_ReportFrame_EditBox:SetText(s) MYSLOT_ReportFrame_EditBox:HighlightText() MYSLOT_ReportFrame_EditBox:SetCursorPosition(0); end function MySlot_Import() local text = MYSLOT_ReportFrame_EditBox:GetText() or "" MySlot:ImportByText(text); end function MySlot:ImportByText(text, Sname) if InCombatLockdown() then self:Print(MySlot_InCombat); return; end local s = text; if not s then return end s = string.gsub(s,"(@.[^\n]*\n)","") s = string.gsub(s,"\n","") s = string.gsub(s,"\r","") s = base64.dec(s) if #s < 8 then MySlot:Print(L["Bad importing text [TEXT]"]) return end local ver = s[1] local crc = s[5] * 2^24 + s[6] * 2^16 + s[7] * 2^8 + s[8] s[5], s[6], s[7] ,s[8] = 0, 0 ,0 ,0 if ( crc ~= bit.band(crc32.enc(s), 2^32 - 1)) then self:Print(L["Bad importing text [CRC32]"]) return end if ver < MYSLOT_ALLOW_VER then self:Print(L["Importing text [ver:%s] is not compatible with current version"]:format(ver)) return end local ct = {} for i = 9, #s do ct[#ct + 1] = s[i] end ct = TableToString(ct) local msg = _MySlot.Charactor():Parse(ct) StaticPopupDialogs["MYSLOT_MSGBOX"].OnAccept = function() MySlot:RecoverData(msg) end StaticPopup_Show("MYSLOT_MSGBOX","") end function MySlot:RecoverData(msg) --cache spells local spells = {} for i = 1, GetNumSpellTabs() do local tab, tabTex, offset, numSpells, isGuild, offSpecID = GetSpellTabInfo(i); offSpecID = (offSpecID ~= 0) if not offSpecID then offset = offset + 1; local tabEnd = offset + numSpells; for j = offset, tabEnd - 1 do local spellType, spellId = GetSpellBookItemInfo(j, BOOKTYPE_SPELL) if spellType then local slot = j + ( SPELLS_PER_PAGE * (SPELLBOOK_PAGENUMBERS[i] - 1)); local spellName = GetSpellInfo(spellId) spells[MySlot.SLOT_TYPE[string.lower(spellType)] .. "_" .. spellId] = {slot, BOOKTYPE_SPELL, "spell"} if spellName then -- flyout spells[MySlot.SLOT_TYPE[string.lower(spellType)] .. "_" .. spellName] = {slot, BOOKTYPE_SPELL, "spell"} end end end end end -- removed in 6.0 for _, companionsType in pairs({"CRITTER"}) do for i =1,GetNumCompanions(companionsType) do local _,_,spellId = GetCompanionInfo( companionsType, i) if (spellId) then spells[MYSLOT_SPELL .. "_" .. spellId] = {i, companionsType, "companions"} end end end for _, p in pairs({GetProfessions()}) do local _, _, _, _, numSpells, spelloffset = GetProfessionInfo(p) for i = 1,numSpells do local slot = i + spelloffset local spellType, spellId = GetSpellBookItemInfo(slot, BOOKTYPE_PROFESSION) if spellType then spells[MySlot.SLOT_TYPE[string.lower(spellType)] .. "_" .. spellId] = {slot, BOOKTYPE_PROFESSION, "spell"} end end end local mounts = {} for i = 1, C_MountJournal.GetNumMounts() do ClearCursor() C_MountJournal.Pickup(i) local _, mount_id = GetCursorInfo() if mount_id then mounts[mount_id] = i end end -- cache macro local macro = {} for _, m in pairs(msg.macro or {}) do local macroId = m.id local icon = m.icon local name = m.name local body = m.body macro[macroId] = { ["oldid"] = macroId, ["name"] = name, ["icon"] = icon, ["body"] = body, } self:FindOrCreateMacro(macro[macroId]) end -- }}} Macro local slotBucket = {} for _, s in pairs(msg.slot or {}) do local slotId = s.id local slotType = _MySlot.Slot.SlotType[s.type] local index = s.index local strindex = s.strindex local curType, curIndex = GetActionInfo(slotId) curType = MySlot.SLOT_TYPE[curType or MYSLOT_NOTFOUND] slotBucket[slotId] = true if not pcall(function() if curIndex ~= index or curType ~= slotType or slotType == MYSLOT_MACRO then -- macro always test if slotType == MYSLOT_SPELL or slotType == MYSLOT_FLYOUT or slotType == MYSLOT_COMPANION then if slotType == MYSLOT_SPELL or slotType == MYSLOT_COMPANION then PickupSpell(index) end if not GetCursorInfo() then -- flyout and failover local spellName = GetSpellInfo(index) or "NOSUCHSPELL" local newId, spellType, pickType = unpack(spells[slotType .."_" ..index] or spells[slotType .."_" ..spellName] or {}) if newId then if pickType == "spell" then PickupSpellBookItem(newId, spellType) elseif pickType == "companions" then PickupCompanion(spellType , newId) end else MySlot:Print(L["Ignore unlearned skill [id=%s], %s"]:format(index, GetSpellLink(index))) end end elseif slotType == MYSLOT_ITEM then PickupItem(index) elseif slotType == MYSLOT_MACRO then local macroid = self:FindOrCreateMacro(macro[index]) if curType ~= MYSLOT_MACRO or curIndex ~=index then PickupMacro(macroid) end elseif slotType == MYSLOT_SUMMONPET and strindex and strindex ~=curIndex then C_PetJournal.PickupPet(strindex , false) if not GetCursorInfo() then C_PetJournal.PickupPet(strindex, true) end if not GetCursorInfo() then MySlot:Print(L["Ignore unactived pet[id=%s], %s"]:format(strindex, C_PetJournal.GetBattlePetLink(strindex))) end elseif slotType == MYSLOT_SUMMONMOUNT then index = mounts[index] if index then C_MountJournal.Pickup(index) else C_MountJournal.Pickup(0) MySlot:Print(L["Use random mount instead of an unactived mount"]) end elseif slotType == MYSLOT_EMPTY then PickupAction(slotId) elseif slotType == MYSLOT_EQUIPMENTSET then PickupEquipmentSet(index) end PlaceAction(slotId) ClearCursor() end end) then MySlot:Print(L["[WARN] Ignore slot due to an unknown error DEBUG INFO = [S=%s T=%s I=%s] Please send Importing Text and DEBUG INFO to %s"]:format(slotId,slotType,index,MYSLOT_AUTHOR)) end end for i = 1, MYSLOT_MAX_ACTIONBAR do if not slotBucket[i] then if GetActionInfo(i) then PickupAction(i) ClearCursor() end end end for _, b in pairs(msg.bind or {}) do local command = b.command if b.id ~= MYSLOT_BIND_CUSTOM_FLAG then command = MySlot.R_BINDS[b.id] end if b.key1 then local mod, key = MySlot.R_MOD_KEYS[ b.key1.mod], MySlot.R_KEYS[ b.key1.key] if key == "KEYCODE" then key = b.key1.keycode end local key = ( mod ~= "NONE" and (mod .. "-") or "" ) .. key SetBinding(key ,command, 1) end if b.key2 then local mod, key = MySlot.R_MOD_KEYS[ b.key2.mod], MySlot.R_KEYS[ b.key2.key] if key == "KEYCODE" then key = b.key2.keycode end local key = ( mod ~= "NONE" and (mod .. "-") or "" ) .. key SetBinding(key ,command, 1) end end SaveBindings(GetCurrentBindingSet()) MySlot:Print(L["All slots were restored"]) end function MYSLOT_ReportFrame_OnLoad() UIPanelWindows["MYSLOT_ReportFrame"] = {area = "center", pushable = 0}; end function MYSLOT_ReportFrame_OnMouseDown(self, button) if button == "LeftButton" then MYSLOT_ReportFrame:StartMoving(); end end function MYSLOT_ReportFrame_OnMouseUp(self, button) if button == "LeftButton" then MYSLOT_ReportFrame:StopMovingOrSizing(); end end function MYSLOT_LoadButton_OnClick() if not MYSLOT_LoadFrame:IsVisible() then ShowUIPanel(MYSLOT_LoadFrame); else HideUIPanel(MYSLOT_LoadFrame); end end function MYSLOT_LoadFrame_OnLoad(self) local lastBtn; for i=1, 4 do MySlot_Scheme[i] = CreateFrame("Button", "MySlot_Scheme" .. i, self, "MYSLOT_SchemeTemplate"); MySlot_Scheme[i]:SetID(i); if (i == 1) then MySlot_Scheme[i]:SetPoint("TOPLEFT", self, "TOPLEFT", 10, -20); else MySlot_Scheme[i]:SetPoint("TOPLEFT", lastBtn, "BOTTOMLEFT", 0, -3); end lastBtn = MySlot_Scheme[i]; end end local function MySlot_UpdateItem(button,Sname) if Sname then _G[button:GetName().."Name"]:SetText(Sname); button.Sname = Sname if button.Sname ==button:GetParent().selectedSname then button:LockHighlight() else button:UnlockHighlight() end button:Show() end end function MYSLOT_LoadFrame_Update() if not MySlot_SavedDb then return end for i = 1, 4 do _G["MySlot_Scheme"..i]:Hide(); end local tempSortTable ={} for _,Stable in pairs(MySlot_SavedDb) do if Stable and Stable.Sname and Stable.addtime then tinsert(tempSortTable,{Stable.Sname,Stable.addtime}) end end local function sortByTime(a,b) if not a or not b then return false end if not a[2] or not b[2] then return false end return a[2] >= b[2] end table.sort(tempSortTable,sortByTime) local index = 0; local offset = FauxScrollFrame_GetOffset(MYSLOT_LoadFrameScrollFrame) + 1; for _,_table in pairs(tempSortTable) do local _name = _table[1] index = index + 1; if index >= offset and index <offset + 4 then local button = _G["MySlot_Scheme"..(index + 1 - offset)] if button then MySlot_UpdateItem(_G["MySlot_Scheme"..(index + 1 - offset)],_name); end end end FauxScrollFrame_Update(MYSLOT_LoadFrameScrollFrame, index, 4, 32 ); end local function MYSLOT_ReportFrame_Update(name) for _, Stable in pairs(MySlot_SavedDb) do if Stable and Stable.Sname and Stable.Sname == name then MYSLOT_ReportFrame_EditBox.change = false; MYSLOT_ReportFrame_EditBox:SetText("") MYSLOT_ReportFrame_EditBox:SetText(Stable.Scheme) MYSLOT_ReportFrame_EditBox:HighlightText() MYSLOT_ReportFrame_EditBox:SetCursorPosition(0); end end end function MYSLOT_Scheme_OnClick(button) local parent = button:GetParent(); parent.selectedSname = button.Sname; MYSLOT_ReportFrame_Update(button.Sname); MYSLOT_LoadFrame_Update(); MYSLOT_LoadFrameDelButton:Enable() MYSLOT_LoadFrameLoadSchemeButton:Enable(); end function MySlot_LoadScheme_Onclick() local Sname = MYSLOT_LoadFrame.selectedSname; if Sname then for _,Stable in pairs(MySlot_SavedDb) do if Stable and Stable.Scheme and Stable.Sname == Sname then StaticPopupDialogs["MYSLOT_MSGBOX"].Sname = Sname; MySlot:ImportByText(Stable.Scheme, Sname); end end end end function MySlot_Del_Onclick() local Sname = MYSLOT_LoadFrame.selectedSname; if Sname then StaticPopupDialogs["MySlot_DELETE_SET"].Sname = Sname; StaticPopup_Show("MySlot_DELETE_SET",Sname); end end function MySlot_Save_Check(Stable,name) if (not Stable or not name) then return end; local alreadyScheme = false; local index; for i,_table in pairs(MySlot_SavedDb) do if _table.Sname == Stable.Sname then alreadyScheme = true; index = i; break; end end if not alreadyScheme then table.insert(MySlot_SavedDb, Stable); local str = string.format(MySlot_SAVE_SUCCESS, name); MySlot:Print(str); MySlot_Check_Status(); MYSLOT_LoadFrame_Update(); else MySlot_SavedDb[index] = Stable; local str = string.format(MySlot_CHANGE_SUCCESS, name); MySlot:Print(str); end end function MySlot_Check_Status() if MySlot_SavedDb and MySlot_SavedDb[1] then MYSLOT_ReportFrameLoadButton:Enable(); else MYSLOT_ReportFrameLoadButton:Disable(); end end function MySlot_Check_Status_Update(button) if MYSLOT_ReportFrame_EditBox:GetText() ~= nil and MYSLOT_ReportFrame_EditBox:GetText() ~= "" then button:Enable(); else button:Disable(); end end function MYSLOT_LoadFrame_OnScroll(self, offset) FauxScrollFrame_OnVerticalScroll(self, offset, 27, MYSLOT_LoadFrame_Update) end local function MySlot_Clearall(what) -- if what == "action" then for i = 1, MYSLOT_MAX_ACTIONBAR do PickupAction(i) ClearCursor() end -- elseif what == "binding" then -- for i = 1, GetNumBindings() do -- local _, _, key1, key2 = GetBinding(i) -- for _, key in pairs({key1, key2}) do -- if key then -- SetBinding(key, nil, 1) -- end -- end -- end -- SaveBindings(GetCurrentBindingSet()) -- end end SlashCmdList["Myslot"] = function(msg, editbox) local cmd, what = msg:match("^(%S*)%s*(%S*)%s*$") if cmd == "clear" then MySlot_Clearall(what) else if not MYSLOT_ReportFrame:IsVisible() then ShowUIPanel(MYSLOT_ReportFrame); else HideUIPanel(MYSLOT_ReportFrame); end end end SLASH_Myslot1 = "/Myslot"
-- binds to configured LDAP server -- -------------------------------------------------------------------------- -- omit arguments for anonymous bind -- -- arguments: -- dn: the distinguished name to be used fo binding (string) -- password: password credentials (string) -- -- returns: -- ldap: in case of success, an LDAP connection handle -- err: in case of an error, an error code (string) -- err2: error dependent extra error information function ldap.bind(dn, password) local libldap = require("mldap") local hostlist = ldap.get_hosts() -- try binding to LDAP server until success of no host entry left local ldap while not ldap do if #hostlist < 1 then break end local host = table.remove(hostlist, 1) local err ldap, err, errno = libldap.bind{ uri = host.uri, timeout = host.timeout, who = dn, password = password } if not err and ldap then return ldap, nil end local errno_string if errno then errno_string = libldap.errorcodes[errno] end if errno == libldap.errorcodes.invalid_credentials then return nil, "invalid_credentials", errno_string end end return nil, "cant_contact_ldap_server" end
ardour { ["type"] = "EditorAction", name = "Bulk Rename Regions", license = "MIT", author = "David Healey", description = [[Rename selected regions]] } function factory () local bulk_rename_regions_input_values --Persistent variable (session lifespan) return function () -- Define dialog -- When avaiable use previously used values as defaults local defaults = bulk_rename_regions_input_values if defaults == nil then defaults = {} defaults["name"] = "" end local dialog_options = {{ type = "entry", key = "name", title = "New Name", default = defaults["name"] }} -- undo stuff local add_undo = false -- keep track of changes Session:begin_reversible_command ("Bulk Rename Regions") -- show dialog local od = LuaDialog.Dialog ("Rename Regions", dialog_options) local rv = od:run() if rv then bulk_rename_regions_input_values = rv --Save in persistent variable local sel = Editor:get_selection() -- Get current selection local rl = sel.regions:regionlist() -- Rename regions for key, r in pairs(rl:table()) do -- preare for undo operation r:to_stateful():clear_changes() r:set_name(rv["name"]) if not Session:add_stateful_diff_command(r:to_statefuldestructible()):empty() then add_undo = true end end end od=nil collectgarbage() -- all done, commit the combined Undo Operation if add_undo then -- the 'nil' Command here mean to use the collected diffs added above Session:commit_reversible_command(nil) else Session:abort_reversible_command() end end end
local id=0 local function new() id=id+1; return id end return {new=new}
--test_procfs_procids.lua package.path = "../?.lua;"..package.path; local procfs = require("lj2procfs.procfs") local fun = require("lj2procfs.fun") local Decoders = require("lj2procfs.Decoders") local function printTable(name, tbl, indent) indent = indent or "" --print("TABLE: ", #mapped) print(string.format("%s['%s'] = {", indent, name)) if #tbl > 0 then -- it's a list,so use ipairs for _, value in ipairs(tbl) do print(string.format("%s\t'%s',",indent, value)) end else -- assume it's a dictionary, so use pairs for key, value in pairs(tbl) do print(string.format("%s\t['%s'] = [[%s]],",indent, key, value)) end end print(string.format("%s},", indent)) end local function printFile(entry) local mapper = Decoders[entry.Name] local indent = '\t\t\t' if mapper then local mapped = mapper(entry.Path) if type(mapped) == "table" then printTable(entry.Name, mapped, indent) elseif type(mapped) == "string" then print(string.format("%s['%s'] = [[%s]],", indent, entry.Name, mapped)) end else print(string.format("%s'%s',", indent,entry.Name)) end end local function printProcfsFiles() --print(string.format("\t[%d] = {", procEntry.Id)) fun.each(printFile, procfs.files()) --print(string.format("\t},")) end print(string.format("return {")) printProcfsFiles(); print(string.format("}"))
function BWMessenger_OnEnterCombat(Unit,Event) Unit:FullCastSpellOnTarget(35570,Unit:GetClosestPlayer()) end RegisterUnitEvent(21244, 1, "BWMessenger_OnEnterCombat")
laser = class:new() function laser:init(x, y) self.i = 0 self.x = x self.y = y end function laser:update(dt) local oldi = self.i self.i = self.i + dt*5 if self.i > 1 then return true end if enemies then for i, v in pairs(enemies) do if v:checkcol(self.x + oldi*100, self.y, self.x + self.i*100) then v:explode() end end end end function laser:draw() love.graphics.setColor(getrainbowcolor(math.random(), 400)) love.graphics.rectangle("fill", self.x*scale, self.y*scale, 100*scale*self.i, scale*2) end