content
stringlengths
5
1.05M
local http = require 'socket.http' local json = require 'cjson' local ltn12 = require 'ltn12' Sender = {} -- base class function Sender:new(name, description, position, cell_type, app_url) app_url = app_url or 'http://localhost:3000/api/v1/values' this = {app_url = app_url, name = name, description = description, position = position, cell_type = cell_type} self.__index = self cmd = json.encode({ name = this.name, type = this.cell_type, value = {}, pos = this.position, description = this.description }) r = http.request({ url = this.app_url, method = 'POST', header = { ['content-length'] = #cmd, ['content-type'] = 'application/text' }, source = ltn12.source.string(cmd) }) this.app_url = this.app_url .. '/' .. r.text._id -- TODO return setmetatable(this, self) end function VisualizeConvWeights:new(static_path, name, description, position, cell_type, app_url) -- Visualize convolutional weights in a grid -- -- Parameters: -- ----------- -- static_path: path to Agnez static files with trailing `/` -- self.static_path = static_path Sender.new(self, name, description, position, cell_type, app_url) function VisualizeConvWeights:on_epoch_end(weight) filename = self.static_path .. self.name .. '.png' image.save(filename, weight) r = http.request(url=self.app_url, method=
local function endurance(e) local tar = e.self:GetTarget(); if (tar.null) then tar = e.self; end e.self:Message(15, "Targets endurance refreshed (" .. tar:GetCleanName() .. ")"); tar:SetEndurance(tar:GetMaxEndurance()); end return endurance;
-- Gkyl ------------------------------------------------------------------------ local Plasma = require "App.PlasmaOnCartGrid" local prng = require "sci.prng" local Mpi = require "Comm.Mpi" local rank = Mpi.Comm_rank(Mpi.COMM_WORLD) local rng = prng.mrg32k3a(rank+1234) -- Constants epsilon0 = 1.0 mu0 = 1.0 lightSpeed = 1/math.sqrt(epsilon0*mu0) elcCharge = -1.0 ionCharge = 1.0 ionMass = 100.0 elcMass = 1.0 -- problem parameters Atwood = 0.17 n1 = 1.0 -- heavy-side number density betaIon = 0.071 gHat = 0.09 -- gHat = g/Omega_i v_A theta = 0.0 -- inclination angle of field to Z-direction Te_Ti = 0.1 -- Te/Ti B0 = 0.1 -- Left wall magnetic field (this may not be correct) maxPert = 0.01 -- Perturbation amplitude -- secondary quantities n2 = n1*(1-Atwood)/(1+Atwood) -- light-side number density T_ion = (betaIon/n1)*B0^2/(2*mu0) -- ion temperature (uniform) T_elc = Te_Ti*T_ion -- electron temperature (uniform) vtElc = math.sqrt(2.0*T_elc/elcMass) vtIon = math.sqrt(2.0*T_ion/ionMass) wpe = math.sqrt(n1*elcCharge^2/(epsilon0*elcMass)) wpi = math.sqrt(n1*ionCharge^2/(epsilon0*ionMass)) de = lightSpeed/wpe di = lightSpeed/wpi Valf = B0/math.sqrt(mu0*n1*ionMass) OmegaCe0 = elcCharge*B0/elcMass OmegaCi0 = ionCharge*B0/ionMass grav = gHat*OmegaCi0*Valf -- gravitational acceleration -- domain size Lx = 3.0*di Ly = 3.75*di -- resolution and time-stepping NX = 64 NY = 64 endTime = 60/OmegaCi0 -- Maxwellian in 2x2v local function maxwellian2D(n, vx, vy, ux, uy, temp, mass) local v2 = (vx - ux)^2 + (vy - uy)^2 return n/(2.0*math.pi*temp/mass)*math.exp(-mass*v2/(2.0*temp)) end plasmaApp = Plasma.App { logToFile = true, tEnd = endTime, -- end time nFrame = 100, -- number of output frames lower = {0.0, 0.0}, -- configuration space lower left upper = {Lx, Ly}, -- configuration space upper right cells = {NX, NY}, -- configuration space cells basis = "serendipity", -- one of "serendipity" or "maximal-order" polyOrder = 2, -- polynomial order timeStepper = "rk3", -- one of "rk2" or "rk3" -- decomposition for configuration space decompCuts = {16, 16}, -- cuts in each configuration direction useShared = false, -- if to use shared memory -- boundary conditions for configuration space periodicDirs = {2}, -- periodic directions -- integrated moment flag, compute quantities 1000 times in simulation calcIntQuantEvery = 0.001, restartFrameEvery = 0.01, -- electrons elc = Plasma.VlasovSpecies { nDistFuncFrame = 10, charge = elcCharge, mass = elcMass, -- velocity space grid lower = {-8.0*vtElc, -8.0*vtElc}, upper = {8.0*vtElc, 8.0*vtElc}, cells = {16, 16}, decompCuts = {1, 1}, -- initial conditions init = function (t, xn) local x, y, vx, vy = xn[1], xn[2], xn[3], xn[4] local xloc = 0.5*Lx local numDens, Bz local B1 = B0 local maxPert = maxPert -- add this pertubation local ph = 0.0 local xregion = Lx/50.0 if (x<xloc) then -- heavy side numDens = n1 else -- light side numDens = n2 end local dn = 0.0 --n2*h*5.*math.exp(-(x-xloc)^2/(2.*xregion^2)) local ne = (numDens+dn) local uxe = maxPert*Valf*(rng:sample()-0.5) local fv= maxwellian2D(ne, vx, vy, uxe, 0.0, T_elc, elcMass) return fv end, -- gravity is in the x direction and has magnitude of grav constGravity = { dir = 1, accel = grav }, -- boundary conditions bcx = { Plasma.VlasovSpecies.bcReflect, Plasma.VlasovSpecies.bcReflect }, evolve = true, -- evolve species? diagnosticMoments = { "M0", "M1i", "M2", "M2ij", "M3i" }, }, -- protons ion = Plasma.VlasovSpecies { nDistFuncFrame = 10, charge = ionCharge, mass = ionMass, -- velocity space grid lower = {-6.0*vtIon, -6.0*vtIon}, upper = {6.0*vtIon, 6.0*vtIon}, cells = {16, 16}, decompCuts = {1, 1}, -- initial conditions init = function (t, xn) local x, y, vx, vy = xn[1], xn[2], xn[3], xn[4] local xloc = 0.5*Lx local numDens, Bz local B1 = B0 local maxPert = maxPert -- add this pertubation local ph = 0.0 local xregion = Lx/50.0 if (x<xloc) then -- heavy side numDens = n1 else -- light side numDens = n2 end local dn = 0.0 --n2*h*5.*math.exp(-(x-xloc)^2/(2.*xregion^2)) local ni = (numDens+dn) local uxi = maxPert*Valf*(rng:sample()-0.5) local fv= maxwellian2D(ni, vx, vy, uxi, 0.0, T_ion, ionMass) return fv end, -- gravity is in the x direction and has magnitude of grav constGravity = { dir = 1, accel = grav }, -- boundary conditions bcx = { Plasma.VlasovSpecies.bcReflect, Plasma.VlasovSpecies.bcReflect }, evolve = true, -- evolve species? diagnosticMoments = { "M0", "M1i", "M2", "M2ij", "M3i" }, }, -- field solver field = Plasma.MaxwellField { epsilon0 = 1.0, mu0 = 1.0, init = function (t, xn) local x, y = xn[1], xn[2] local xloc = 0.5*Lx local T = (T_elc + T_ion) local B1 = B0 local maxPert = maxPert -- add this pertubation if (x<xloc) then -- heavy side numDens = n1 Bz = math.sqrt(B1^2 + 2*mu0*(n1*T - numDens*T + ionMass*grav*n1*x)) else -- light side numDens = n2 Bz = math.sqrt(B1^2 + 2*mu0*(n1*T - numDens*T + ionMass*grav*n1*xloc + ionMass*grav*n2*(x-xloc))) end return 0.0, 0.0, 0.0, 0.0, 0.0, Bz end, bcx = { Plasma.MaxwellField.bcReflect, Plasma.MaxwellField.bcReflect }, evolve = true, -- evolve field? }, } -- run application plasmaApp:run()
--VERSION SUPPORT: 1.1-beta PLUGIN.name = "Quick Inventory" PLUGIN.author = "Pilot" PLUGIN.desc = "F4 key to open your inventory." if (SERVER) then util.AddNetworkString("OpenMyInv") local function ItemCanEnterForEveryone(inventory, action, context) if (action == "transfer") then return true end end local function CanReplicateItemsForEveryone(inventory, action, context) if (action == "repl") then return true end end function PLUGIN:ShowSpare2(client) local inventory = client:getChar():getInv() inventory:addAccessRule(ItemCanEnterForEveryone) inventory:addAccessRule(CanReplicateItemsForEveryone) net.Start("OpenMyInv") net.Send(client) end else net.Receive("OpenMyInv", function() local myInv = LocalPlayer():getChar():getInv() local myInventoryDerma = myInv:show() myInventoryDerma:MakePopup() myInventoryDerma:ShowCloseButton(true) end) end
---@class CS.UnityEngine.MissingReferenceException : CS.System.SystemException ---@type CS.UnityEngine.MissingReferenceException CS.UnityEngine.MissingReferenceException = { } ---@overload fun(): CS.UnityEngine.MissingReferenceException ---@overload fun(message:string): CS.UnityEngine.MissingReferenceException ---@return CS.UnityEngine.MissingReferenceException ---@param optional message string ---@param optional innerException CS.System.Exception function CS.UnityEngine.MissingReferenceException.New(message, innerException) end return CS.UnityEngine.MissingReferenceException
local skynet = require "skynet" local socket = require "socket" local syslog = require "syslog" local protoloader = require "protoloader" local srp = require "srp" local aes = require "aes" local uuid = require "uuid" local traceback = debug.traceback local master local database local host local auth_timeout local session_expire_time local session_expire_time_in_second local connection = {} local saved_session = {} local slaved = {} local CMD = {} function CMD.init (m, id, conf) master = m database = skynet.uniqueservice ("database") host = protoloader.load (protoloader.LOGIN) auth_timeout = conf.auth_timeout * 100 session_expire_time = conf.session_expire_time * 100 session_expire_time_in_second = conf.session_expire_time end local function close (fd) if connection[fd] then socket.close (fd) connection[fd] = nil end end local function read (fd, size) return socket.read (fd, size) or error () end local function read_msg (fd) local s = read (fd, 2) local size = s:byte(1) * 256 + s:byte(2) local msg = read (fd, size) return host:dispatch (msg, size) end local function send_msg (fd, msg) local package = string.pack (">s2", msg) socket.write (fd, package) end function CMD.auth (fd, addr) connection[fd] = addr skynet.timeout (auth_timeout, function () if connection[fd] == addr then syslog.warningf ("connection %d from %s auth timeout!", fd, addr) close (fd) end end) socket.start (fd) socket.limit (fd, 8192) local type, name, args, response = read_msg (fd) assert (type == "REQUEST") if name == "handshake" then assert (args and args.name and args.client_pub, "invalid handshake request") local account = skynet.call (database, "lua", "account", "load", args.name) or error ("load account " .. args.name .. " failed") local session_key, _, pkey = srp.create_server_session_key (account.verifier, args.client_pub) local challenge = srp.random () local msg = response { user_exists = (account.id ~= nil), salt = account.salt, server_pub = pkey, challenge = challenge, } send_msg (fd, msg) type, name, args, response = read_msg (fd) assert (type == "REQUEST" and name == "auth" and args and args.challenge, "invalid auth request") local text = aes.decrypt (args.challenge, session_key) assert (challenge == text, "auth challenge failed") local id = tonumber (account.id) if not id then assert (args.password) id = uuid.gen () local password = aes.decrypt (args.password, session_key) account.id = skynet.call (database, "lua", "account", "create", id, account.name, password) or error (string.format ("create account %s/%d failed", args.name, id)) end challenge = srp.random () local session = skynet.call (master, "lua", "save_session", id, session_key, challenge) msg = response { session = session, expire = session_expire_time_in_second, challenge = challenge, } send_msg (fd, msg) type, name, args, response = read_msg (fd) assert (type == "REQUEST") end assert (name == "challenge") assert (args and args.session and args.challenge) local token, challenge = skynet.call (master, "lua", "challenge", args.session, args.challenge) assert (token and challenge) local msg = response { token = token, challenge = challenge, } send_msg (fd, msg) close (fd) end function CMD.save_session (session, account, key, challenge) saved_session[session] = { account = account, key = key, challenge = challenge } skynet.timeout (session_expire_time, function () local t = saved_session[session] if t and t.key == key then saved_session[session] = nil end end) end function CMD.challenge (session, secret) local t = saved_session[session] or error () local text = aes.decrypt (secret, t.key) or error () assert (text == t.challenge) t.token = srp.random () t.challenge = srp.random () return t.token, t.challenge end function CMD.verify (session, secret) local t = saved_session[session] or error () local text = aes.decrypt (secret, t.key) or error () assert (text == t.token) t.token = nil return t.account end skynet.start (function () skynet.dispatch ("lua", function (_, _, command, ...) local function pret (ok, ...) if not ok then syslog.warningf (...) skynet.ret () else skynet.retpack (...) end end local f = assert (CMD[command]) pret (xpcall (f, traceback, ...)) end) end)
--[[ LICENSE HEADER GNU Lesser General Public License version 2.1+ Copyright © 2017 Perttu Ahola (celeron55) <celeron55@gmail.com> Copyright © 2017 Minetest developers & contributors See: docs/license-LGPL-2.1.txt ]] --- Glass nodes. -- -- @module nodes local S = core.get_translator() local to_color = { "default:glass", "default:glass_cube", "default:glass_doublepanel", "default:glass_halfstair", "default:glass_innerstair", "default:glass_micropanel", "default:glass_microslab", "default:glass_nanoslab", "default:glass_outerstair", "default:glass_panel", "default:glass_thinstair", "default:obsidian_glass", "default:obsidian_glass_cube", "default:obsidian_glass_doublepanel", "default:obsidian_glass_halfstair", "default:obsidian_glass_innerstair", "default:obsidian_glass_micropanel", "default:obsidian_glass_microslab", "default:obsidian_glass_nanoslab", "default:obsidian_glass_outerstair", "default:obsidian_glass_panel", "default:obsidian_glass_thinstair", } local next = next for _, glass_name in ipairs(to_color) do local node = core.registered_nodes[glass_name] if not node then glass.log("warning", "\"" .. glass_name .. "\" not registered, skipping ...") else glass.log("info", "overriding node \"" .. glass_name .. "\" to be colorable") local groups = node.groups groups["ud_param2_colorable"] = 1 core.override_item(glass_name, { paramtype2 = "color", palette = "unifieddyes_palette_extended.png", groups = groups, on_dig = unifieddyes.on_dig, }) end end -- backward compat (1.0) if core.registered_nodes["default:glass"] then core.register_alias("glass:plain", "default:glass") end if core.registered_nodes["default:obsidian_glass"] then core.register_alias("glass:obsidian", "default:obsidian_glass") end
--[[ MrPong.lua Copyright (C) 2016 Kano Computing Ltd. License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2 This is the dialogue you can have with Mr Pong in Overworld on the Beach. ]]-- return { type = "repeat", dialogues = { --- 1) Welcome dialogue - first speech----------------------------------------------------- { type = "copy", copy = { "mrPongDiag1" }, arguments = {}, options = { { playPong = "CMD_PONG" }, { makePong = "CMD_MAKE_PONG"}, { maybeLater = 0 } }, }, --- the end --- } }
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local function comma_value(n) -- credit http://richard.warburton.it local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$') return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right end local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(value, from, to) local api = "https://currency-exchange.p.mashape.com/exchange?" local par1 = "from="..from local par2 = "&q="..value local par3 = "&to="..to local url = api..par1..par2..par3 local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) local curr = comma_value(value).." "..from.." = "..to.." "..comma_value(body) return curr end local function run(msg, matches) if tonumber(matches[1]) and not matches[2] then local from = "USD" local to = "IDR" local value = matches[1] return request(value, from, to) elseif matches[2] and matches[3] then local from = string.upper(matches[2]) or "USD" local to = string.upper(matches[3]) or "IDR" local value = matches[1] or "1" return request(value, from, to, value) end end return { description = "Currency Exchange", usage = { "!exchange [value] : Exchange value from USD to IDR (default).", "!exchange [value] [from] [to] : Get Currency Exchange by specifying the value of source (from) and destination (to).", }, patterns = { "^!exchange (%d+) (%a+) (%a+)$", "^!exchange (%d+)", }, run = run }
namespace("APIAction") function test(agent) print("client action:test") return true end
local tab = { }; tab.Name = "Rocket Boots"; tab.Desc = "Lets you run faster."; tab.Ingredients = { "metal", "interface", "circuitry", "fuel" }; tab.SpeedMul = 2; EXPORTS["rocketboots"] = tab;
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). --]] local ITEM = Clockwork.item:New(); ITEM.name = "ItemHandheldRadio"; ITEM.uniqueID = "handheld_radio"; ITEM.cost = 20; ITEM.classes = {CLASS_EMP, CLASS_EOW}; ITEM.model = "models/deadbodies/dead_male_civilian_radio.mdl"; ITEM.weight = 1; ITEM.access = "v"; ITEM.category = "Communication"; ITEM.business = true; ITEM.description = "ItemHandheldRadioDesc"; ITEM.customFunctions = {"Frequency"}; -- Called when a player drops the item. function ITEM:OnDrop(player, position) end; if (SERVER) then function ITEM:OnCustomFunction(player, name) if (name == "Frequency") then Clockwork.datastream:Start(player, "Frequency", player:GetCharacterData("Frequency", "")); end; end; end; ITEM:Register();
----------------------------------------- -- ID: 4716 -- Scroll of Regen -- Teaches the white magic Regen ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(108) end function onItemUse(target) target:addSpell(108) end
Shape = class("Shape") Shape.static.zero = {{0, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 1, 2}, {1, 2, 0, 2}, {0, 2, 0, 1}, {0, 1, 0, 0}} Shape.static[0] = Shape.zero Shape.static.one = {{1, 0, 1, 1}, {1, 1, 1, 2}} Shape.static[1] = Shape.one Shape.static.two = {{0, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {0, 1, 0, 2}, {0, 2, 1, 2}} Shape.static[2] = Shape.two Shape.static.three = {{0, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {1, 1, 1, 2}, {1, 2, 0, 2}} Shape.static[3] = Shape.three Shape.static.four = {{0, 0, 0, 1}, {0, 1, 1, 1}, {1, 1, 1, 0}, {1, 1, 1, 2}} Shape.static[4] = Shape.four Shape.static.five = {{0, 0, 1, 0}, {0, 0, 0, 1}, {0, 1, 1, 1}, {1, 1, 1, 2}, {1, 2, 0, 2}} Shape.static[5] = Shape.five Shape.static.six = {{0, 0, 1, 0}, {0, 0, 0, 1}, {0, 1, 1, 1}, {1, 1, 1, 2}, {1, 2, 0, 2}, {0, 2, 0, 1}} Shape.static[6] = Shape.six Shape.static.seven = {{0, 0, 1, 0}, {1, 0, 0, 1}, {0, 1, 0, 2}} Shape.static[7] = Shape.seven Shape.static.eight = {{0, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {1, 1, 1, 2}, {1, 2, 0, 2}, {0, 1, 0, 2}, {0, 0, 0, 1}} Shape.static[8] = Shape.eight Shape.static.nine = {{0, 0, 1, 0}, {1, 0, 1, 1}, {1, 1, 0, 1}, {1, 1, 1, 2}, {1, 2, 0, 2}, {0, 0, 0, 1}} Shape.static[9] = Shape.nine function Shape:initialize(sticks, x, y, scale) scale = scale or 1 self.sticks = {} for i = 1, #sticks do table.insert(self.sticks, Stick:new(x + sticks[i][1] * scale, y + sticks[i][2] * scale, x + sticks[i][3] * scale, y + sticks[i][4] * scale)) end end function Shape:animateTo(sticks, x, y, scale, duration, ease) ease = ease or 'inOutCubic' if self._newSticks then for i = 1, #self.sticks do self.sticks[i]:endAnimation() end self._newSticks = nil end -- Random shuffle for i = 1, #self.sticks do a, b = math.random(1, #self.sticks), math.random(1, #self.sticks) local cStick = self.sticks[a] self.sticks[a] = self.sticks[b] self.sticks[b] = cStick end if #sticks > #self.sticks then local oldSize = #self.sticks for i = 1, #sticks - oldSize do table.insert(self.sticks, self.sticks[math.random(1, oldSize)]:copy()) end for i = 1, #self.sticks do self.sticks[i]:animateTo(x + sticks[i][1] * scale, y + sticks[i][2] * scale, x + sticks[i][3] * scale, y + sticks[i][4] * scale, duration, ease) end else for i = 1, #sticks do self.sticks[i]:animateTo(x + sticks[i][1] * scale, y + sticks[i][2] * scale, x + sticks[i][3] * scale, y + sticks[i][4] * scale, duration, ease) end for i = #sticks + 1, #self.sticks do a = math.random(1, #sticks) self.sticks[i]:animateTo(x + sticks[a][1] * scale, y + sticks[a][2] * scale, x + sticks[a][3] * scale, y + sticks[a][4] * scale, duration, ease) end end self._newSticks = sticks end function Shape:update(dt) for i = 1, #self.sticks do self.sticks[i]:update(dt) end if self._newSticks then if #self.sticks > #self._newSticks then for i = #self.sticks, #self._newSticks + 1, -1 do if not self.sticks[i]:isAnimating() then table.remove(self.sticks, i) end end if #self.sticks == #self._newSticks then self._newSticks = nil end else local animating = false for i = 1, #self.sticks do animating = animating or self.sticks[i]:isAnimating() end if not animating then self._newSticks = nil end end end end function Shape:render() for i = 1, #self.sticks do self.sticks[i]:render() end end function Shape:isAnimating() return self._newSticks ~= nil end return Shape
--------------------------------- --! @file DefaultConfiguration.lua --! @brief デフォルト設定情報定義 --------------------------------- --[[ Copyright (c) 2017 Nobuhiko Miyamoto ]] local version = require "openrtm.version" local cpp_suffixes = "dll" local default_config= { ["config.version"]=version.openrtm_version, ["openrtm.name"]=version.openrtm_name, ["openrtm.version"]=version.openrtm_version, ["manager.instance_name"]="manager", ["manager.name"]="manager", --["manager.naming_formats"]="%h.host_cxt/%n.mgr", ["manager.naming_formats"]="oprnrtm.host_cxt/%n.mgr", ["manager.pid"]="", ["os.name"]="", ["os.release"]="", ["os.version"]="", ["os.arch"]="", ["os.hostname"]="", ["logger.enable"]="YES", ["logger.file_name"]="./rtc.log", ["logger.date_format"]="%b %d %H:%M:%S", ["logger.log_level"]="INFO", ["logger.stream_lock"]="NO", ["logger.master_logger"]="", ["module.conf_path"]="", ["module.load_path"]="", ["naming.enable"]="YES", ["naming.type"]="corba", ["naming.formats"]="%n.rtc", ["naming.update.enable"]="YES", ["naming.update.interval"]="10.0", ["timer.enable"]="YES", ["timer.tick"]="0.1", ["corba.args"]="", ["corba.endpoints"]="", ["corba.id"]="oil", ["corba.nameservers"]="localhost", ["corba.master_manager"]="localhost:2810", ["corba.nameservice.replace_endpoint"]="NO", ["corba.update_master_manager.enable"]="YES", ["corba.update_master_manager.interval"]="10.0", ["corba.step.count"]="10", ["exec_cxt.periodic.type"]="PeriodicExecutionContext", ["exec_cxt.periodic.rate"]="1000", ["exec_cxt.sync_transition"]="YES", ["exec_cxt.transition_timeout"]="0.5", ["manager.modules.load_path"]="./", ["manager.modules.abs_path_allowed"]="YES", ["manager.is_master"]="NO", ["manager.corba_servant"]="YES", ["manager.shutdown_on_nortcs"]="YES", ["manager.shutdown_auto"]="YES", ["manager.auto_shutdown_duration"]="10.0", ["manager.name"]="manager", ["manager.command"]="rtcd", ["manager.nameservers"]="default", ["manager.language"]="Lua", ["manager.components.naming_policy"]="process_unique", ["manager.modules.C++.manager_cmd"]="rtcd", ["manager.modules.Python.manager_cmd"]="rtcd_python", ["manager.modules.Java.manager_cmd"]="rtcd_java", ["manager.modules.Lua.manager_cmd"]="rtcd_lua", ["manager.modules.search_auto"]="YES", ["manager.local_service.enabled_services"]="ALL", ["sdo.service.provider.enabled_services"]="ALL", ["sdo.service.consumer.enabled_services"]="ALL", ["manager.supported_languages"]="C++, Python, Java, Lua", ["manager.modules.C++.profile_cmd"]="rtcprof", ["manager.modules.Python.profile_cmd"]="rtcprof_python", ["manager.modules.Java.profile_cmd"]="rtcprof_java", ["manager.modules.Lua.profile_cmd"]="rtcprof_lua", ["manager.modules.C++.suffixes"]=cpp_suffixes, ["manager.modules.Python.suffixes"]="py", ["manager.modules.Java.suffixes"]="class", ["manager.modules.Lua.suffixes"]="lua", ["manager.modules.C++.load_paths"]="", ["manager.modules.Python.load_paths"]="", ["manager.modules.Java.load_paths"]="", ["manager.modules.Lua.load_paths"]="" } --_G["openrtm.default_config"] = default_config return default_config
package.path = package.path .. ';plugins/?.lua' require("omh-lib") omh.plugin_cache={} local OMH_PLUGINS={} local OMH_CONFIG={} function load_plugins(plugins) plugins = plugins or {} for i,p in ipairs(plugins) do table.insert(OMH_PLUGINS, p) end for i,plugin in ipairs(OMH_PLUGINS) do logger.df("Loading plugin %s", plugin) -- First, load the plugin mod = require(plugin) -- If it returns a table (like a proper module should), then -- we may be able to access additional functionality if type(mod) == "table" then -- If the user has specified some config parameters, merge -- them with the module's 'config' element (creating it -- if it doesn't exist) if OMH_CONFIG[plugin] ~= nil then if mod.config == nil then mod.config = {} end for k,v in pairs(OMH_CONFIG[plugin]) do mod.config[k] = v end end -- If it has an init() function, call it if type(mod.init) == "function" then logger.i(string.format("Initializing plugin %s", plugin)) mod.init() end end -- Cache the module omh.plugin_cache[plugin] = mod end end -- Specify config parameters for a plugin. First name -- is the name as specified in OMH_PLUGINS, second is a table. function omh_config(name, config) logger.df("omh_config, name=%s, config=%s", name, hs.inspect(config)) OMH_CONFIG[name]=config end -- Load and configure the plugins function omh_go(plugins) load_plugins(plugins) end -- Load local code if it exists local status, err = pcall(function() require("init-local") end) if not status then -- A 'no file' error is OK, but anything else needs to be reported if string.find(err, 'no file') == nil then error(err) end end ---- Notify when the configuration is loaded notify("Oh my Hammerspoon!", "Config loaded")
------------------------------------------------ -- Copyright © 2013-2020 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ local CUtils=CUtils local FileHelper=FileHelper --luanet.import_type("FileHelper") local Common = Hugula.Utils.Common local Loader = Loader local Model = Model local json = json local split = split local url_unit="Unit" local line_count local row_num local sheet_name function json.onDecodeError(message, text, location, etc) print(string.format("json.onDecodeError %s line:%d,row:%d %s ",sheet_name,line_count,row_num,text)) print(location) end --parse key value to luaTable local function decode_to_Lua(text) local datas={} local lines = string.split(text,"\n") local names = lines[2] local columNames = string.split(names,";") local CNLen = #columNames line_count=#lines-1 for i=3,line_count do line = lines[i] local temp = string.split(line,";") local tempData = {} local tempItem for i=1,CNLen do tempItem = temp[i] row_num = i if tempItem then tempItem = string.gsub(tempItem,'\\n','\n') local f = string.sub(tempItem,1,1) if f=="[" or f=="{" then tempItem = json:decode(tempItem) elseif string.match(tempItem,"^%d*%.?%d*$") then tempItem=tonumber(tempItem) end end tempData[columNames[i]] =tempItem end datas[temp[1]] = tempData end return datas end local function decode_unit(data) Model.units=data end local function decode_ziptxt(name,context) sheet_name = name local data=decode_to_Lua(context) if name == url_unit then decode_unit(data) end print(name.." decoded ") end local function load_comp(req) FileHelper.UnpackConfigAssetBundleFn(req.data,decode_ziptxt) Loader:clear(req.key) end local function load_config_zip() Loader:get_resource(Common.CONFIG_CSV_NAME,nil,UnityEngine.AssetBundle,load_comp) end load_config_zip()
object_mobile_dressed_myyydril_chief = object_mobile_shared_dressed_myyydril_chief:new { } ObjectTemplates:addTemplate(object_mobile_dressed_myyydril_chief, "object/mobile/dressed_myyydril_chief.iff")
--[[ _________________________________________________________ __ /___ /_________________(_)_____________ /__ /__(_) _ __/_ __ \ __ \_ ___/_ /_ ___/ _ \_ /__ /__ / / /_ _ / / / /_/ / / _ / / /__ / __/ / _ / _ / \__/ /_/ /_/\____//_/ /_/ \___/ \___//_/ /_/ /_/ Name: Custom Queue System Date: 24/07/2020 File Description: Settings and function calling ]] --SETTINGS-- local Admins = {} --[[ Example: local Admins = {69948947,6157007,31820308,24306216,26709627} Their userId (found within the url) seperated by a , (With no , at the end) ]] local UseGroup = false --Instead of using the admin value above it will check if the player is above the rank in a group --TRUE: Uses group feature --FALSE: Uses admin array local MinimumRank = 70 --The rank number corospondending to the ranks. Every rank above will be allowed to be admin local groupId = 901313 --The group Id local DontTeleportAdmins = false --When joining a server, admins will not be teleported to the queue server (But people wont be able to join the queue if the server is full) --SETTINGS-- --ADVANCED SETTINGS-- local SpotsReserved = 1 local RelaxingMusic = false --When true it will play relaxing music while waiting for the queue local SoundVolume = 0.5 --Volume of the music local SoundIds = {} --SoundId's that will be played, they are randomized. --[[ Example: local SoundIds = {455355502,4943258334,4921447628,1839541959,1841998846,1840535147} The Id of the selected sound (found within the url) seperated by a , (With no , at the end) ]] local DisplayServerId = true --Display the JobId of the server? local DefaultTextJobId = "You are in the queue for server:" --Custom messages followed by a " AWAITING" or JOBID local DisplayQueuePosition = true --Display the queue position? local DefaultTextQueue = "Your position in queue:" --Custom message followed by a " AWAITING" or INT --The queue will AUTOMATICALLY not show the GUI with any other private server if the teleportData is NOT a valid jobId --However on the server side it will still listen for messages (Delete CustomQueue when not needed inside a specific private server) wait() --Somehow game.Players.MaxPlayers doesn't load immediately local maxplayers = game.Players.MaxPlayers - SpotsReserved --Maximum players -spots to be reserved to teleport them --Increasing the reserved spots this will allow for more space and less bugs. --ADVANCED SETTINGS-- local Components = require(script.Setup) local QueueSystem = require(script.Main) Components.SetUp(DefaultTextJobId,DisplayServerId,DisplayQueuePosition,DefaultTextQueue,RelaxingMusic,SoundVolume,SoundIds) QueueSystem.Main(MinimumRank,groupId,DontTeleportAdmins,RelaxingMusic,UseGroup,Admins,maxplayers)
local asserts = require 'testing.asserts' local test_runner = require 'testing.test_runner' local custom_floors = require 'decorators.custom_floors' local tensor = require 'dmlab.system.tensor' local tests = {} function tests.callsOriginalModifyTexture() local mock_api = {} function mock_api:modifyTexture(textureName, texture) -- Record that this was called mock_api.modifyTextureCalled = {textureName, texture} end custom_floors.decorate(mock_api) local NAME = 'some_texture_name' local TEXTURE = 'pretend_texture' mock_api:modifyTexture(NAME, TEXTURE) asserts.EQ(mock_api.modifyTextureCalled[1], NAME) asserts.EQ(mock_api.modifyTextureCalled[2], TEXTURE) end function tests.doesNothingToNonMatchingTexture() local fake_api = {} custom_floors.decorate(fake_api) local NAME = '/some/path/to/lg_floor_placeholder_B_d.tga' local EXPECT_WHITE = tensor.ByteTensor(4, 4, 4):fill(255) local texture = EXPECT_WHITE:clone() custom_floors.setVariationColor('A', {255, 0, 0}) fake_api:modifyTexture(NAME, texture) assert(texture == EXPECT_WHITE) end function tests.appliesColorToMatchingTexture() local fake_api = {} custom_floors.decorate(fake_api) local NAME = '/some/path/to/lg_floor_placeholder_A_d.tga' local EXPECT_RED = tensor.ByteTensor(4, 4, 4):fill(255) EXPECT_RED:select(3, 2):fill(0) EXPECT_RED:select(3, 3):fill(0) local texture = tensor.ByteTensor(4, 4, 4):fill(255) custom_floors.setVariationColor('A', {255, 0, 0}) fake_api:modifyTexture(NAME, texture) assert(texture == EXPECT_RED) end return test_runner.run(tests)
-- add up one level to search path since we're in a subfolder, -- you won't need this if the script is above or at the same level package.path = package.path .. ";../?.lua;../?/init.lua" -- load the hui library aka the "Hooey UI" local hui = require "hui" -- create a window manager manager = hui.WindowManager() -- create a window with a given position and size -- note the callback implementations which define behavior -- callbacks can be set per instance or via subclassing (see below) window1 = hui.Window(120, 80, 300, 300) window1.backgroundColor = of.Color(220) window1.border = 1 window1.borderColor = of.Color.darkGray window1.mouseMoved = function(self, x, y) print("window1 moved "..x.." "..y) end window1.becameActive = function(self) self.borderColor = of.Color.red end window1.resignedActive = function(self) self.borderColor = of.Color.darkGray end -- create a view with a given position and size -- this will be a subview within window1 -- note the numerous callback implementations which define behavior -- you can type into the view when active, pressing enter prints the string view1 = hui.View(10, 10, 200, 100) view1.text = "Hooey UI" view1.backgroundColor = of.Color(200, 100, 100) view1.border = 1 --view1.clipsToBounds = true -- enable to clip bounds by drawing into an FBO view1.mousePressed = function(self, x, y, button) print("view1 clicked: "..x.." "..y) end view1.mouseReleased = function(self, x, y, button) print("view1 released: "..x.." "..y) end view1.mouseEntered = function(self, x, y) self.backgroundColor = of.Color.gold print("view1 entered") end view1.mouseExited = function(self, x, y) self.backgroundColor = of.Color(200, 100, 100) print("view1 exited") end view1.draw = function(self) -- custom draw function via overriding hui.View.drawBackground(self) hui.View.drawSubviews(self) of.setColor(0) -- draw roughly centered text of.drawBitmapString(self.text, self.frame.width/2-string.len(self.text)*4, self.frame.height/2) hui.View.drawBorder(self) end view1.keyPressed = function(self, key) print("view1 pressed: "..key) if key == of.KEY_DEL then if string.len(self.text) > 0 then self.text = string.sub(self.text, 1, string.len(self.text)-1) end elseif key == of.KEY_RETURN then print(self.text) self.text = "" elseif key < 256 then self.text = self.text..string.char(key) end end view1.keyReleased = function(self, key) print("view1 released: "..key) end view1.becameActive = function(self) self.borderColor = of.Color.blue print("view 1 active") end view1.resignedActive = function(self) self.borderColor = nil print("view1 no longer active") end -- create a second view -- this will be a subview of view1 -- you can type into the view when active view2 = hui.View(10, 10, 50, 50) view2.backgroundColor = of.Color(100, 100, 200) view2.text = "" view2.border = 1 view2.draw = function(self) hui.View.draw(self) of.setColor(0) of.drawBitmapString(self.text, self.frame.width/2, self.frame.height/2) end view2.keyPressed = function(self, key) if key < 256 then self.text = string.char(key) end end view2.mousePressed = function(self, x, y, button) print("view2 clicked: "..x.." "..y) end view2.mouseReleased = function(self, x, y, button) print("view2 released: "..x.." "..y) end view2.mouseEntered = function(self, x, y) self.backgroundColor = of.Color.gold print("view2 entered: "..x.." "..y) end view2.mouseExited = function(self, x, y) self.backgroundColor = of.Color(100, 100, 200) print("view2 exited: "..x.." "..y) end view2.becameActive = function(self) self.borderColor = of.Color.blue print("view2 active") end view2.resignedActive = function(self) self.borderColor = nil print("view2 no longer active") end -- a second subview of view1 view3 = hui.View(140, 10, 50, 50) view3.backgroundColor = of.Color(100, 200, 200) view3.border = 1 view3.mousePressed = function(self, x, y, button) print("view3 clicked: "..x.." "..y) end view3.mouseReleased = function(self, x, y, button) print("view3 released: "..x.." "..y) end view3.mouseEntered = function(self, x, y) self.backgroundColor = of.Color.gold print("view3 entered: "..x.." "..y) end view3.mouseExited = function(self, x, y) self.backgroundColor = of.Color(100, 200, 200) print("view3 exited: "..x.." "..y) end view3.becameActive = function(self) self.borderColor = of.Color.blue print("view3 active") end view3.resignedActive = function(self) self.borderColor = nil print("view3 no longer active") end -- custom hui.Window subclass -- unlike the previous window creation method, this class an be easily reused local MyWindow = class(hui.Window) function MyWindow:__init(name, x, y, w, h) hui.Window.__init(self, x, y, w, h) self.backgroundColor = of.Color(220) self.border = 1 self.borderColor = of.Color.darkGray self.name = name end function MyWindow:becameActive() self.borderColor = of.Color.red print(self.name.." active") end function MyWindow:resignedActive() self.borderColor = of.Color.darkGray print(self.name.." no longer active") end -- custom hui.View subclass -- you can type into the view when active -- unlike the previous view creation methods, this class an be easily reused local MyView = class(hui.View) function MyView:__init(name, x, y, w, h) hui.View.__init(self, x, y, w, h) self.backgroundColor = of.Color(100, 200, 100) self.border = 1 self.name = name self.text = "" end function MyView:draw() hui.View.draw(self) of.setColor(0) of.drawBitmapString(self.text, self.frame.width/2, self.frame.height/2) end function MyView:keyPressed(key) print(self.name.." pressed: "..key) if key > 0 and key < 256 then self.text = string.char(key) end end function MyView:mouseEntered(x, y) self.backgroundColor = of.Color.gold print(self.name.." entered") end function MyView:mouseExited(x, y) self.backgroundColor = of.Color(100, 200, 100) print(self.name.." exited") end function MyView:becameActive() self.border = 1 self.borderColor = of.Color.blue print(self.name.." active") end function MyView:resignedActive() self.borderColor = nil print(self.name.." no longer active") end -- create a second window using the MyWindow class window2 = MyWindow("window2", 340, 120, 200, 200) -- create a subview for window2 using the MyView class view4 = MyView("view4", 50, 50, 100, 100) ------------ -- Main Loop ------------ function setup() of.setWindowTitle("huitest") -- add windows to window manager and -- views to windows or other views manager:addWindow(window1) window1:addSubview(view1) view1:addSubview(view2) view1:addSubview(view3) manager:addWindow(window2) window2:addSubview(view4) -- set the active window and bring it forward manager:makeWindowActive(window2) manager:bringWindowToFront(window2) end function draw() manager:draw() end --------- -- Events --------- function keyPressed(key) if of.getKeyPressed(of.KEY_SUPER) then -- SUPER is CMD/Windows Key if key == string.byte("n") then -- SUPER+n: next window local nextWindow = manager:windowAfter(manager.activeWindow) manager:makeWindowActive(nextWindow) manager:bringWindowToFront(nextWindow) return elseif key == string.byte("t") then -- SUPER+t: toggle current window fullscreen manager.activeWindow:toggleFullscreen() return end end manager:keyPressed(key) end function keyReleased(key) manager:keyReleased(key) end function mouseMoved(x, y) manager:mouseMoved(x, y) end function mouseDragged(x, y) manager:mouseDragged(x, y) end function mousePressed(x, y, button) manager:mousePressed(x, y, button) end function mouseReleased(x, y, button) manager:mouseReleased(x, y, button) end function windowResized(w, h) manager:windowResized(w, h) end
------------------------------------------------------------------------------- -- -- tek.ui.image.checkmark -- Written by Timm S. Mueller <tmueller at schulze-mueller.de> -- See copyright notice in COPYRIGHT -- -- Version 2.0 -- ------------------------------------------------------------------------------- local ui = require "tek.ui" local Image = ui.Image module("tek.ui.image.checkmark", tek.ui.class.image) Image:newClass(_M) local coords = { 0x8000, 0x8000, 0x5555, 0xaaaa, 0x4000, 0x9555, 0x8000, 0x5555, 0xeaaa, 0xc000, 0xd555, 0xd555, 0x0000, 0xffff, 0x2aaa, 0xd555, 0xffff, 0xffff, 0xd555, 0xd555, 0xffff, 0x0000, 0xd555, 0x2aaa, 0x0000, 0x0000, 0x2aaa, 0x2aaa, } local points1 = { 1,2,3,4,5,6 } local points21 = { 13,14,7,8,9,10 } local points22 = { 9,10,11,12,13,14 } local points3 = { 8,10,14,12 } local primitives = { [0] = { }, { { 0x1000, 6, points21, "border-shadow" }, { 0x1000, 6, points22, "border-shine" }, { 0x1000, 4, points3, "background" }, }, { { 0x1000, 6, points21, "border-shadow" }, { 0x1000, 6, points22, "border-shine" }, { 0x1000, 4, points3, "background" }, { 0x2000, 6, points1, "detail" }, }, { { 0x2000, 6, points1, "detail" }, } } function new(class, num) return Image.new(class, { coords, false, false, true, primitives[num] or primitives[1] } ) end
local NAME, ns = ... local isWoWClassic = select(4, GetBuildInfo()) < 20000; local QWH = LibStub("QuestWatchHelper-1.0"); local QLH = LibStub("QuestLogHelper-1.0"); local ZH = LibStub("ZoneHelper-1.0"); local QH = LibStub("LibQuestHelpers-1.0"); local BQTL = ButterQuestTrackerLocale; ButterQuestTracker = LibStub("AceAddon-3.0"):NewAddon("ButterQuestTracker", "AceEvent-3.0"); local BQT = ButterQuestTracker; StaticPopupDialogs[NAME .. "_WowheadURL"] = { text = ns.CONSTANTS.PATHS.LOGO .. ns.CONSTANTS.BRAND_COLOR .. " Butter Quest Tracker" .. "|r - Wowhead URL " .. ns.CONSTANTS.PATHS.LOGO, button2 = CLOSE, hasEditBox = true, editBoxWidth = 300, EditBoxOnEnterPressed = function(self) self:GetParent():Hide() end, EditBoxOnEscapePressed = function(self) self:GetParent():Hide() end, OnShow = function(self) local questID = self.text.text_arg1; local quest = QLH:GetQuest(questID); local name = quest.title; self.text:SetText(self.text:GetText() .. "\n\n|cffff7f00" .. name .. "|r"); self.editBox:SetText(QLH:GetWowheadURL(questID)); self.editBox:SetFocus(); self.editBox:HighlightText(); end, whileDead = true, hideOnEscape = true } function BQT:OnEnable() self.db = LibStub("AceDB-3.0"):New("ButterQuestTrackerConfig", ns.CONSTANTS.DB_DEFAULTS, true); self.hiddenContainers = {}; -- TODO: This is for backwards compatible support of the SavedVariables -- Remove this in v2.0.0 if ButterQuestTrackerCharacterConfig then for key, value in pairs(ButterQuestTrackerCharacterConfig) do self.db.char[key] = value; ButterQuestTrackerCharacterConfig[key] = nil; end end -- END TODO QWH:BypassWatchLimit(self.db.char.MANUALLY_TRACKED_QUESTS); QWH:KeepHidden(); end function BQT:OnPlayerEnteringWorld() self:UnregisterEvent("PLAYER_ENTERING_WORLD"); BQTL:SetLocale(BQT.db.global.Locale); QWH:OnQuestWatchUpdated(function(questWatchUpdates) for _, updateInfo in pairs(questWatchUpdates) do if updateInfo.byUser then if updateInfo.watched then self.db.char.MANUALLY_TRACKED_QUESTS[updateInfo.questID] = true; else self.db.char.MANUALLY_TRACKED_QUESTS[updateInfo.questID] = false; end end end self:RefreshView(); end); QLH:OnQuestUpdated(function(quests) self:LogTrace("Event(OnQuestUpdated)"); local currentZone = GetRealZoneText(); local minimapZone = GetMinimapZoneText(); for questID, quest in pairs(quests) do if quest.abandoned then self.db.char.QUESTS_LAST_UPDATED[questID] = nil; self.db.char.MANUALLY_TRACKED_QUESTS[questID] = nil; elseif quest.accepted or quest.updated then self.db.char.QUESTS_LAST_UPDATED[questID] = quest.lastUpdated; -- If the quest is updated then remove it from the manually tracked quests list. if self.db.global.AutoTrackUpdatedQuests then self.db.char.MANUALLY_TRACKED_QUESTS[questID] = true; elseif self.db.char.MANUALLY_TRACKED_QUESTS[questID] == false then self.db.char.MANUALLY_TRACKED_QUESTS[questID] = nil; end self:UpdateQuestWatch(currentZone, minimapZone, QLH:GetQuest(questID)); end end self:RefreshView(); end); ZH:OnZoneChanged(function(info) self:LogInfo("Changed Zones: (" .. info.zone .. ", " .. info.subZone .. ")"); self:RefreshQuestWatch(); end); self.tracker = LibStub("TrackerHelper-1.0"):New({ position = { x = self.db.global.PositionX, y = self.db.global.PositionY }, width = self.db.global.Width, maxHeight = self.db.global.MaxHeight, backgroundColor = self.db.global.BackgroundColor, backgroundVisible = self.db.global.BackgroundAlwaysVisible or self.db.global.DeveloperMode, locked = self.db.global.LockFrame }); -- TODO: This automatically updates invalid last updated values to the current time -- Remove this in v2.0.0 for questID, lastUpdated in pairs(self.db.char.QUESTS_LAST_UPDATED) do if lastUpdated < 1000000 then self.db.char.QUESTS_LAST_UPDATED[questID] = time(); end end -- END TODO self.db.char.QUESTS_LAST_UPDATED = QLH:SetQuestsLastUpdated(self.db.char.QUESTS_LAST_UPDATED); self:RefreshQuestWatch(); self:RefreshView(); if self.db.global.Sorting == "ByQuestProximity" then self:UpdateQuestProximityTimer(); end -- This is a massive hack to prevent questie from ignoring us. C_Timer.After(3.0, function() QH:SetAutoHideQuestHelperIcons(self.db.global.AutoHideQuestHelperIcons); end); self:LogInfo("Enabled"); end BQT:RegisterEvent("PLAYER_ENTERING_WORLD", "OnPlayerEnteringWorld") function BQT:ShowWowheadPopup(id) StaticPopup_Show(NAME .. "_WowheadURL", id) end local function getDistance(x1, y1, x2, y2) return math.min( (x2-x1)^2 + (y2-y1)^2 ); end local function count(t) local _count = 0; if t then for _, _ in pairs(t) do _count = _count + 1 end end return _count; end local function getWorldPlayerPosition() local uiMapID = C_Map.GetBestMapForUnit("player"); if not uiMapID then return nil; end local mapPosition = C_Map.GetPlayerMapPosition(uiMapID, "player"); local _, worldPosition = C_Map.GetWorldPosFromMapPos(uiMapID, mapPosition); return worldPosition; end local function sortQuestFallback(quest, otherQuest, field, comparator) local value = quest[field]; local otherValue = otherQuest[field]; if value == otherValue then return quest.index < otherQuest.index; end if not value and otherValue then return false; elseif value and not otherValue then return true; end if comparator == ">" then return value > otherValue; elseif comparator == "<" then return value < otherValue; else BQT:LogError("Unknown Comparator. (" .. comparator .. ")"); end end local function sortQuests(quest, otherQuest) local sorting = BQT.db.global.Sorting or "nil"; if sorting == "Disabled" then return sortQuestFallback(quest, otherQuest); end if sorting == "ByLevel" then return sortQuestFallback(quest, otherQuest, "level", "<"); elseif sorting == "ByLevelReversed" then return sortQuestFallback(quest, otherQuest, "level", ">"); elseif sorting == "ByPercentCompleted" then return sortQuestFallback(quest, otherQuest, "completionPercent", ">"); elseif sorting == "ByRecentlyUpdated" then return sortQuestFallback(quest, otherQuest, "lastUpdated", ">"); elseif sorting == "ByQuestProximity" then if QH:IsSupported() then quest.distance = QH:GetDistanceToClosestObjective(quest.questID); otherQuest.distance = QH:GetDistanceToClosestObjective(otherQuest.questID); else quest.distance = 0; otherQuest.distance = 0; end return sortQuestFallback(quest, otherQuest, "distance", "<"); else BQT:LogError("Unknown Sorting value. (" .. sorting .. ")") end return false; end function BQT:UpdateQuestProximityTimer() if self.db.global.Sorting == "ByQuestProximity" then local initialized = false; self:Sort(); self.questProximityTimer = C_Timer.NewTicker(5.0, function() self:LogTrace("-- Starting ByQuestProximity Checks --"); self:LogTrace("Checking if player has moved..."); local position = getWorldPlayerPosition(); if position then local distance = self.playerPosition and getDistance(position.x, position.y, self.playerPosition.x, self.playerPosition.y); if not initialized or not distance or distance > 0.01 then initialized = true; self.playerPosition = position; self:Sort(); else self:LogTrace("Player movement wasn't greater then 5, ignoring... (" .. distance .. ")"); end self:LogTrace("-- Ending ByQuestProximity Checks --"); end end); elseif self.questProximityTimer then self.playerPosition = nil; self.questProximityTimer:Cancel(); end end function BQT:RefreshQuestWatch() self:LogTrace("Refreshing Quest Watch"); local quests = QLH:GetQuests(); local currentZone = GetRealZoneText(); local minimapZone = GetMinimapZoneText(); for _, quest in pairs(quests) do self:UpdateQuestWatch(currentZone, minimapZone, quest); end end function BQT:UpdateQuestWatch(currentZone, minimapZone, quest) if self:ShouldWatchQuest(currentZone, minimapZone, quest) then AddQuestWatch(quest.index); else RemoveQuestWatch(quest.index); end end function BQT:ShouldWatchQuest(currentZone, minimapZone, quest) quest.isCurrentZone = quest.zone == currentZone or quest.zone == minimapZone; if self.db.char.MANUALLY_TRACKED_QUESTS[quest.questID] == true then return true; elseif self.db.char.MANUALLY_TRACKED_QUESTS[quest.questID] == false or self.db.global.DisableFilters then return false; end if self.db.global.HideCompletedQuests and quest.completed then return false; end if self.db.global.CurrentZoneOnly and not quest.isCurrentZone and not quest.isClassQuest and not quest.isProfessionQuest then return false; end return true; end function BQT:GetQuestInfo() if self.db.global.DisplayDummyData and InterfaceOptionsFrame:IsShown() then -- TODO: Move this into QuestLogHelper local quests = { -- Partially Completed [6563] = { index = 1, questID = 6563, title = "The Essence of Aku'Mai", zone = "Blackfathom Deeps", completed = false, failed = false, isClassQuest = false, isProfessionQuest = false, sharable = true, level = 22, difficulty = QLH:GetDifficulty(22), completionPercent = 0.25, objectives = { [1] = { text = "Sapphire of Aku'Mai: 5/20", fulfilled = 5, required = 20, completed = false } } }, -- No objectives, summary only [1196] = { index = 2, questID = 1196, title = "The Sacred Flame", summary = "Deliver the Filled Etched Phial to Rau Cliffrunner at the Freewind Post.", zone = "Thunder Bluff", completed = false, failed = false, isClassQuest = false, isProfessionQuest = false, sharable = true, level = 29, difficulty = QLH:GetDifficulty(29), completionPercent = 1 }, -- Multiple Objectives, partially completed. [4841] = { index = 3, questID = 4841, title = "Pacify the Centaur", zone = "Thousand Needles", completed = false, failed = false, isClassQuest = false, isProfessionQuest = false, sharable = true, level = 25, difficulty = QLH:GetDifficulty(25), completionPercent = 0.5714, objectives = { [1] = { text = "Galak Scout slain: 0/12", fulfilled = 0, required = 12, completed = false }, [2] = { text = "Galak Wrangler slain: 10/10", fulfilled = 10, required = 10, completed = true }, [3] = { text = "Galak Windchaser slain: 6/6", fulfilled = 6, required = 6, completed = true } } }, -- Completed [5147] = { index = 4, questID = 5147, title = "Compendium of the Fallen", zone = "Scarlet Monastery", completed = true, failed = false, isClassQuest = false, isProfessionQuest = false, sharable = true, level = 38, difficulty = QLH:GetDifficulty(38), completionPercent = 1, objectives = { [1] = { text = "Compendium of the Fallen: 1/1", fulfilled = 1, required = 1, completed = true } } }, -- Failed [4904] = { index = 5, questID = 4904, title = "Free at Last", zone = "Thousand Needles", completed = false, failed = true, isClassQuest = false, isProfessionQuest = false, sharable = false, level = 29, difficulty = QLH:GetDifficulty(29), completionPercent = 0, objectives = { [1] = { text = "Escort Lakota Windsong from the Darkcloud Pinnacle.", type = "event", fulfilled = 0, required = 1, completed = false } } } }; local currentZone = "Thunder Bluff"; local minimapZone = GetMinimapZoneText(); local watchedQuests = {}; for questID, quest in pairs(quests) do if self:ShouldWatchQuest(currentZone, minimapZone, quest) then watchedQuests[questID] = quest; end end return watchedQuests, count(quests), true; end return QLH:GetWatchedQuests(), QLH:GetQuestCount(), false; end function BQT:GetTrackerHeader(visibleQuestCount, questCount) if self.db.global.TrackerHeaderFormat == "QuestsNumberVisible" then return BQTL:GetString('QT_QUESTS') .. " (" .. visibleQuestCount .. "/" .. questCount .. ")"; elseif self.db.global.TrackerHeaderFormat == "QuestsNumberVisibleTotal" then return BQTL:GetString('QT_QUESTS') .. " (" .. visibleQuestCount .. "/" .. C_QuestLog.GetMaxNumQuests() .. ")"; end return BQTL:GetString('QT_QUESTS'); end function BQT:GetQuestHeader(quest) local format = self.db.global.QuestHeaderFormat; for match, key in format:gmatch("({{(%w+)}})" ) do local value = quest[key] or ""; if type(value) == "number" and math.floor(value) ~= value then value = string.format("%.1f", value); end format = format:gsub(match, value, 1); end return format; end function BQT:Sort() self:LogInfo("Sort"); if not self.questContainers then return end -- collect the keys local quests = self:GetQuestInfo(); local keys = {}; for k in pairs(quests) do keys[#keys+1] = k end table.sort(keys, function(a, b) return sortQuests(quests[a], quests[b]) end); local questIDToOrderMap = {}; local zoneToOrderMap = {}; for i, questID in pairs(keys) do questIDToOrderMap[questID] = i; zoneToOrderMap[quests[questID].zone] = zoneToOrderMap[quests[questID].zone] or i; end for _, element in pairs(self.questContainers) do element:SetOrder(questIDToOrderMap[element.metadata.quest.questID]); end if self.db.global.ZoneHeaderEnabled then for _, element in ipairs(self.questsContainer.elements) do local order = zoneToOrderMap[element.metadata.zone]; if order then if not element.metadata.header then order = order + 0.1; end element:SetOrder(order, false); end end self.questsContainer:Order(); end end function BQT:RefreshView() self:LogInfo("Refresh Quests"); self.tracker:Clear(); local watchedQuests, questCount = self:GetQuestInfo(); self:LogTrace("Quest Count:", questCount); local trackerContainer = self.tracker:Container({ margin = { x = 10, y = 10 }, backgroundColor = self.db.global.DeveloperMode and { r = 1.0, g = 1.0, a = 0.2 } }); if self.db.global.TrackerHeaderEnabled then self.tracker:Font({ label = self:GetTrackerHeader(count(watchedQuests), questCount), color = self.db.global.TrackerHeaderFontColor, size = self.db.global.TrackerHeaderFontSize, container = self.tracker:Container({ container = trackerContainer, margin = { bottom = 10 }, events = { OnMouseDown = function(button) if button ~= "LeftButton" or self.db.global.LockFrame then return end self.tracker:StartMoving(); end, OnMouseUp = function(button) if button ~= "LeftButton" or self.db.global.LockFrame then return end self.tracker:StopMovingOrSizing(); end, OnButterDragStart = function() self.tracker:SetBackgroundVisibility(true); end, -- This fires only if OnButterDragStart fires as well. OnButterDragStop = function() local x, y = self.tracker:GetPosition(); if not self.db.global.DeveloperMode and not self.db.global.BackgroundAlwaysVisible then self.tracker:SetBackgroundVisibility(false); end self.db.global.PositionX = x; self.db.global.PositionY = y; LibStub("AceConfigRegistry-3.0"):NotifyChange("ButterQuestTracker"); end, -- This fires only if OnButterDragStart doesn't fire. OnButterMouseUp = function(button) if button == "LeftButton" then self.hiddenContainers["QUESTS"] = self.questsContainer:ToggleHidden() or nil; PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON); else if InterfaceOptionsFrame:IsShown() then InterfaceOptionsFrame:Hide(); else InterfaceOptionsFrame:Show(); InterfaceOptionsFrame_OpenToCategory("ButterQuestTracker"); end end end } }) }); end self.questsContainer = self.tracker:Container({ container = trackerContainer, hidden = self.hiddenContainers["QUESTS"] }); self.questContainers = {}; local zoneContainers = {}; local index = 1; for _, quest in pairs(watchedQuests) do if not zoneContainers[quest.zone] then if self.db.global.ZoneHeaderEnabled then -- Zone Header self.tracker:Font({ label = quest.zone, color = self.db.global.ZoneHeaderFontColor, size = self.db.global.ZoneHeaderFontSize, container = self.tracker:Container({ container = self.questsContainer, margin = { bottom = 10, left = 2 }, metadata = { header = true, zone = quest.zone }, events = { OnMouseUp = function() self.hiddenContainers["Z-" .. quest.zone] = zoneContainers[quest.zone]:ToggleHidden() or nil; PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON); end } }) }); zoneContainers[quest.zone] = self.tracker:Container({ container = self.questsContainer, hidden = self.hiddenContainers["Z-" .. quest.zone], margin = { left = 8 }, metadata = { header = false, zone = quest.zone } }); end end local questContainer = self.tracker:Container({ container = self.db.global.ZoneHeaderEnabled and zoneContainers[quest.zone] or self.questsContainer, backgroundColor = self.db.global.DeveloperMode and { g = 1.0, a = 0.2 }, margin = { bottom = self.db.global.QuestPadding, left = (self.db.global.ZoneHeaderEnabled or not self.db.global.TrackerHeaderEnabled) and 0 or 5 }, metadata = { quest = quest }, events = { OnMouseUp = function(button) if button == "LeftButton" then if IsShiftKeyDown() then self.db.char.MANUALLY_TRACKED_QUESTS[quest.questID] = false; RemoveQuestWatch(quest.index); PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON); elseif IsAltKeyDown() then self:ShowWowheadPopup(quest.questID); elseif IsControlKeyDown() then if isWoWClassic then ChatEdit_InsertLink("[" .. quest.title .. "]"); else ChatEdit_InsertLink(GetQuestLink(quest.questID)); end else QLH:ToggleQuest(quest.index); end else self:ToggleContextMenu(quest); end end, OnEnter = function(_, target) GameTooltip:SetOwner(target, "ANCHOR_NONE"); GameTooltip:SetPoint("RIGHT", target, "LEFT"); GameTooltip:AddLine(quest.title .. "\n", NORMAL_FONT_COLOR.r, NORMAL_FONT_COLOR.g, NORMAL_FONT_COLOR.b, true); GameTooltip:AddLine(quest.summary, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b, true); if self.db.global.DeveloperMode then GameTooltip:AddDoubleLine("\nQuest ID:", quest.questID, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b); GameTooltip:AddDoubleLine("Quest Index:", quest.index, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b); for _, addon in ipairs(QH:GetActiveAddons()) do local distance = QH:GetDistanceToClosestObjective(quest.questID, addon); if distance then GameTooltip:AddDoubleLine(addon .. " (distance):", string.format("%.1fm", distance), HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b); else GameTooltip:AddDoubleLine(addon .. " (distance):", "N/A", HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b, HIGHLIGHT_FONT_COLOR.r, HIGHLIGHT_FONT_COLOR.g, HIGHLIGHT_FONT_COLOR.b); end end end GameTooltip:Show(); end, OnLeave = function() GameTooltip:ClearLines(); GameTooltip:Hide(); end } }); tinsert(self.questContainers, questContainer); self.tracker:Font({ label = self:GetQuestHeader(quest), size = self.db.global.QuestHeaderFontSize, color = self.db.global.ColorHeadersByDifficultyLevel and QLH:GetDifficultyColor(quest.difficulty) or self.db.global.QuestHeaderFontColor, container = questContainer }); local objectiveCount = count(quest.objectives); if objectiveCount == 0 then self.tracker:Font({ label = ' - ' .. quest.summary, size = self.db.global.ObjectiveFontSize, color = self.db.global.ObjectiveFontColor, container = questContainer, margin = { bottom = 2.5 } }); elseif quest.completed then self.tracker:Font({ label = ' - ' .. BQTL:GetString('QT_READY_TO_TURN_IN'), size = self.db.global.ObjectiveFontSize, color = "00b205", container = questContainer, margin = { bottom = 2.5 } }); elseif quest.failed then self.tracker:Font({ label = ' - ' .. BQTL:GetString('QT_FAILED'), size = self.db.global.ObjectiveFontSize, color = { r = 1, g = 0.1, b = 0.1 }, container = questContainer, margin = { bottom = 2.5 } }); else for _, objective in ipairs(quest.objectives) do self.tracker:Font({ label = ' - ' .. objective.text, size = self.db.global.ObjectiveFontSize, color = objective.completed and HIGHLIGHT_FONT_COLOR or self.db.global.ObjectiveFontColor, container = questContainer, margin = { bottom = 2.5 } }); end end index = index + 1; end self:Sort(); end function BQT:ToggleContextMenu(quest) if not self.contextMenu then self.contextMenu = CreateFrame("Frame", "WPDemoContextMenu", UIParent, "UIDropDownMenuTemplate"); end local isActive = UIDROPDOWNMENU_OPEN_MENU == self.contextMenu; local hasQuestChanged = not self.contextMenu.quest or self.contextMenu.quest.questID ~= quest.questID; self.contextMenu.quest = quest; UIDropDownMenu_Initialize(self.contextMenu, function() UIDropDownMenu_AddButton({ text = self.contextMenu.quest.title, notCheckable = true, isTitle = true }); UIDropDownMenu_AddButton({ text = BQTL:GetString('QT_UNTRACK_QUEST'), notCheckable = true, func = function() self.db.char.MANUALLY_TRACKED_QUESTS[self.contextMenu.quest.questID] = false; RemoveQuestWatch(self.contextMenu.quest.index); end }); UIDropDownMenu_AddButton({ text = BQTL:GetString('QT_VIEW_QUEST'), notCheckable = true, func = function() QLH:ToggleQuest(self.contextMenu.quest.index); end }); UIDropDownMenu_AddButton({ text = BQTL:GetString('QT_WOWHEAD_URL'), notCheckable = true, func = function() BQT:ShowWowheadPopup(self.contextMenu.quest.questID); end }); UIDropDownMenu_AddButton({ text = BQTL:GetString('QT_SHARE_QUEST'), notCheckable = true, disabled = not UnitInParty("player") or not self.contextMenu.quest.sharable, func = function() QLH:ShareQuest(self.contextMenu.quest.index); end }); UIDropDownMenu_AddButton({ text = BQTL:GetString('QT_CANCEL_QUEST'), notCheckable = true, func = function() PlaySound(SOUNDKIT.IG_MAINMENU_OPTION_CHECKBOX_ON); end }); UIDropDownMenu_AddButton({ isTitle = true }); UIDropDownMenu_AddButton({ text = BQTL:GetString('QT_ABANDON_QUEST'), notCheckable = true, colorCode = "|cffff0000", func = function() QLH:AbandonQuest(self.contextMenu.quest.index); PlaySound(SOUNDKIT.IG_QUEST_LOG_ABANDON_QUEST); end }); end, "MENU"); -- If this Dropdown menu isn't already open then play the sound effect. if isActive and not hasQuestChanged then CloseDropDownMenus(); else ToggleDropDownMenu(1, nil, self.contextMenu, "cursor", 0, -3); PlaySound(SOUNDKIT.IG_MAINMENU_OPEN); end end function BQT:ResetOverrides() self:LogInfo("Clearing Tracking Overrides..."); self.db.char.MANUALLY_TRACKED_QUESTS = {}; self:RefreshQuestWatch(); end function BQT:Debug(type, bypass, ...) if bypass or (self.db.global.DeveloperMode and self.db.global.DebugLevel >= type.LEVEL) then print(ns.CONSTANTS.LOGGER.PREFIX .. type.COLOR, ...); end end function BQT:LogError(...) self:Debug(ns.CONSTANTS.LOGGER.TYPES.ERROR, true, ...); end function BQT:LogWarn(...) self:Debug(ns.CONSTANTS.LOGGER.TYPES.WARN, false, ...); end function BQT:LogInfo(...) self:Debug(ns.CONSTANTS.LOGGER.TYPES.INFO, false, ...); end function BQT:LogTrace(...) self:Debug(ns.CONSTANTS.LOGGER.TYPES.TRACE, false, ...); end
local m = {} local Players = game:GetService("Players") local ServerScriptService = game:GetService("ServerScriptService") local Chat = game:GetService("Chat") local Prefix = ":" local ChatService = require(ServerScriptService:WaitForChild("ChatServiceRunner").ChatService) local CommandsMaster = require(script.Parent.CommandsMaster) local ReplicatedStorage = game:GetService("ReplicatedStorage") local TextService = game:GetService("TextService") local Util = require(ReplicatedStorage:WaitForChild("GRPeeAdminModules"):WaitForChild("Utility")) local Events = Util.Event local Enumerators = require(game:GetService("ReplicatedStorage"):WaitForChild("GRPeeAdminModules"):WaitForChild("Enumerators")) local PermissionsHandler = require(script.Parent.PermissionsHandler) CommandsMaster.Initialize() local Commands = CommandsMaster:GetCommands() local PlayerSpecificLogs = {} local debounce = {} local function ShallowCopy(original) local copy = {} for key, value in pairs(original) do copy[key] = value end return copy end -- Check to see if the message has our prefix. Returns boolean. local function CheckForPrefix(message) if message:sub(1, Prefix:len()) == Prefix then return true, message:sub(Prefix:len() + 1, message:len()) end return false end -- Detects chats and makes chatlogs work. local function UserChat(speakerName, message) local HideOverride = false if message:sub(1, 2) == "/e" then HideOverride = true end local uid = Players:FindFirstChild(speakerName) local suc, response = pcall(function() return Chat:FilterStringAsync(message, uid, uid) end) local DissectedMessage if suc then DissectedMessage = { Speaker = speakerName; UserId = uid; Message = response; Timestamp = DateTime.now(); } else DissectedMessage = { Speaker = speakerName; UserId = uid; Message = "<i>(Couldn't filter)</i> " .. message; Timestamp = DateTime.now(); } end if PlayerSpecificLogs[speakerName] == nil then PlayerSpecificLogs[speakerName] = {} end table.insert(PlayerSpecificLogs[speakerName], 1, DissectedMessage) return HideOverride end Events:GetOrCreateFunction("RequestLogs").OnServerInvoke = function(user, phrase) if table.find(debounce, user) then return "stop" end if PermissionsHandler:GetRank(user.UserId) >= Enumerators.PermissionLevel.Support and phrase then table.insert(debounce, user) coroutine.wrap(function() task.wait(2) table.remove(debounce, table.find(debounce, user)) end)() local FoundUser for username, messages in pairs(PlayerSpecificLogs) do if username:lower():sub(1, phrase:len()) == phrase:lower() then -- if username:sub(1, phrase-length) equals phrase then they were searching for a player FoundUser = messages break end end if FoundUser then return FoundUser else -- user doesnt exist, they are likely searching a phrase. local messages = {} for player, messageLogs in pairs(PlayerSpecificLogs) do for _, message in ipairs(messageLogs) do if message.Message:lower():match(phrase:lower()) then table.insert(messages, message) end end end if #messages > 0 then return messages end return nil -- if there are no messages, return nil end end return nil end -- Detects for commands. Returns boolean if the message should be hidden from other players or not. local function OnChatted(speakerName, message) local args = message:lower():split(" ") local HideOverride = false local speaker = Players:FindFirstChild(speakerName) if args[1]:sub(1, 2) == "/e" then table.remove(args, 1) HideOverride = true end local PrefixFound, updatedmessage = CheckForPrefix(args[1]) if PrefixFound then -- command found? args[1] = updatedmessage local cmd = Commands[args[1]] if cmd ~= nil then -- command found! table.remove(args, 1) local finalargs = {} local WillError = false local ErrorInformation = {} -- Uncomment below whenever you need to threaten Mikel. --[[ if cmd.Name == "hat" and (speaker.UserId == 148103779 or speaker.UserId == 699526) then -- mikel and "Finalargs" user id cmd.Error(speaker, finalargs) end ]] WillError, finalargs, ErrorInformation = CommandsMaster:CheckArguments(speaker, cmd, args) if WillError then cmd.Error(speaker, args, ErrorInformation) return (not cmd.ShowInChat) or HideOverride end cmd.Function(speaker, finalargs) return (not cmd.ShowInChat) or HideOverride end else return HideOverride end return HideOverride end local function PlayerAdded(player) PlayerSpecificLogs[player.Name] = {} end do for _,plr in ipairs(Players:GetPlayers()) do PlayerAdded(plr) end end -- These two are different functions because thats easier to read. -- Theoritically, these two functions could be combined. But why would I do that. lol. ChatService:RegisterProcessCommandsFunction("__Template-Admin-Register-Commands__", OnChatted) ChatService:RegisterProcessCommandsFunction("__Chatlogs__", UserChat) Players.PlayerAdded:Connect(PlayerAdded) return function (prefix) Prefix = prefix end
require("firecast.lua"); local __o_rrpgObjs = require("rrpgObjs.lua"); require("rrpgGUI.lua"); require("rrpgDialogs.lua"); require("rrpgLFM.lua"); require("ndb.lua"); require("locale.lua"); local __o_Utils = require("utils.lua"); local function constructNew_frmInventory() local obj = GUI.fromHandle(_obj_newObject("form")); local self = obj; local sheet = nil; rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject")); function obj:setNodeObject(nodeObject) sheet = nodeObject; self.sheet = nodeObject; self:_oldSetNodeObjectFunction(nodeObject); end; function obj:setNodeDatabase(nodeObject) self:setNodeObject(nodeObject); end; _gui_assignInitialParentForForm(obj.handle); obj:beginUpdate(); obj:setName("frmInventory"); obj:setAlign("client"); obj.scrollBox1 = GUI.fromHandle(_obj_newObject("scrollBox")); obj.scrollBox1:setParent(obj); obj.scrollBox1:setAlign("client"); obj.scrollBox1:setName("scrollBox1"); obj.rectangle1 = GUI.fromHandle(_obj_newObject("rectangle")); obj.rectangle1:setParent(obj.scrollBox1); obj.rectangle1:setLeft(0); obj.rectangle1:setTop(0); obj.rectangle1:setWidth(895); obj.rectangle1:setHeight(160); obj.rectangle1:setColor("black"); obj.rectangle1:setStrokeColor("white"); obj.rectangle1:setStrokeSize(1); obj.rectangle1:setName("rectangle1"); obj.label1 = GUI.fromHandle(_obj_newObject("label")); obj.label1:setParent(obj.rectangle1); obj.label1:setLeft(100); obj.label1:setTop(5); obj.label1:setWidth(200); obj.label1:setHeight(25); obj.label1:setHorzTextAlign("center"); obj.label1:setText("Itens Equipados"); obj.label1:setName("label1"); obj.label2 = GUI.fromHandle(_obj_newObject("label")); obj.label2:setParent(obj.rectangle1); obj.label2:setLeft(300); obj.label2:setTop(5); obj.label2:setWidth(590); obj.label2:setHeight(25); obj.label2:setHorzTextAlign("center"); obj.label2:setText("Efeitos Adicionais"); obj.label2:setName("label2"); obj.label3 = GUI.fromHandle(_obj_newObject("label")); obj.label3:setParent(obj.rectangle1); obj.label3:setLeft(5); obj.label3:setTop(30); obj.label3:setWidth(95); obj.label3:setHeight(20); obj.label3:setText("Arma"); obj.label3:setHorzTextAlign("center"); obj.label3:setName("label3"); obj.edit1 = GUI.fromHandle(_obj_newObject("edit")); obj.edit1:setParent(obj.rectangle1); obj.edit1:setLeft(100); obj.edit1:setTop(30); obj.edit1:setWidth(200); obj.edit1:setHeight(25); obj.edit1:setField("equip_arma"); obj.edit1:setVertTextAlign("center"); obj.edit1:setName("edit1"); obj.edit2 = GUI.fromHandle(_obj_newObject("edit")); obj.edit2:setParent(obj.rectangle1); obj.edit2:setLeft(300); obj.edit2:setTop(30); obj.edit2:setWidth(590); obj.edit2:setHeight(25); obj.edit2:setField("equip_arma_desc"); obj.edit2:setVertTextAlign("center"); obj.edit2:setName("edit2"); obj.label4 = GUI.fromHandle(_obj_newObject("label")); obj.label4:setParent(obj.rectangle1); obj.label4:setLeft(5); obj.label4:setTop(55); obj.label4:setWidth(95); obj.label4:setHeight(20); obj.label4:setText("Equipamento"); obj.label4:setHorzTextAlign("center"); obj.label4:setName("label4"); obj.edit3 = GUI.fromHandle(_obj_newObject("edit")); obj.edit3:setParent(obj.rectangle1); obj.edit3:setLeft(100); obj.edit3:setTop(55); obj.edit3:setWidth(200); obj.edit3:setHeight(25); obj.edit3:setField("equip_equipamento"); obj.edit3:setVertTextAlign("center"); obj.edit3:setName("edit3"); obj.edit4 = GUI.fromHandle(_obj_newObject("edit")); obj.edit4:setParent(obj.rectangle1); obj.edit4:setLeft(300); obj.edit4:setTop(55); obj.edit4:setWidth(590); obj.edit4:setHeight(25); obj.edit4:setField("equip_equipamento_desc"); obj.edit4:setVertTextAlign("center"); obj.edit4:setName("edit4"); obj.label5 = GUI.fromHandle(_obj_newObject("label")); obj.label5:setParent(obj.rectangle1); obj.label5:setLeft(5); obj.label5:setTop(80); obj.label5:setWidth(95); obj.label5:setHeight(20); obj.label5:setText("Vestimenta"); obj.label5:setHorzTextAlign("center"); obj.label5:setName("label5"); obj.edit5 = GUI.fromHandle(_obj_newObject("edit")); obj.edit5:setParent(obj.rectangle1); obj.edit5:setLeft(100); obj.edit5:setTop(80); obj.edit5:setWidth(200); obj.edit5:setHeight(25); obj.edit5:setField("equip_vestimenta"); obj.edit5:setVertTextAlign("center"); obj.edit5:setName("edit5"); obj.edit6 = GUI.fromHandle(_obj_newObject("edit")); obj.edit6:setParent(obj.rectangle1); obj.edit6:setLeft(300); obj.edit6:setTop(80); obj.edit6:setWidth(590); obj.edit6:setHeight(25); obj.edit6:setField("equip_vestimenta_desc"); obj.edit6:setVertTextAlign("center"); obj.edit6:setName("edit6"); obj.edit7 = GUI.fromHandle(_obj_newObject("edit")); obj.edit7:setParent(obj.rectangle1); obj.edit7:setLeft(100); obj.edit7:setTop(105); obj.edit7:setWidth(200); obj.edit7:setHeight(25); obj.edit7:setField("equip_vestimenta1"); obj.edit7:setVertTextAlign("center"); obj.edit7:setName("edit7"); obj.edit8 = GUI.fromHandle(_obj_newObject("edit")); obj.edit8:setParent(obj.rectangle1); obj.edit8:setLeft(100); obj.edit8:setTop(130); obj.edit8:setWidth(200); obj.edit8:setHeight(25); obj.edit8:setField("equip_vestimenta2"); obj.edit8:setVertTextAlign("center"); obj.edit8:setName("edit8"); obj.rectangle2 = GUI.fromHandle(_obj_newObject("rectangle")); obj.rectangle2:setParent(obj.scrollBox1); obj.rectangle2:setLeft(900); obj.rectangle2:setTop(0); obj.rectangle2:setWidth(310); obj.rectangle2:setHeight(110); obj.rectangle2:setColor("black"); obj.rectangle2:setStrokeColor("white"); obj.rectangle2:setStrokeSize(1); obj.rectangle2:setName("rectangle2"); obj.label6 = GUI.fromHandle(_obj_newObject("label")); obj.label6:setParent(obj.rectangle2); obj.label6:setLeft(0); obj.label6:setTop(5); obj.label6:setWidth(310); obj.label6:setHeight(25); obj.label6:setHorzTextAlign("center"); obj.label6:setText("Armazenamento"); obj.label6:setName("label6"); obj.comboBox1 = GUI.fromHandle(_obj_newObject("comboBox")); obj.comboBox1:setParent(obj.rectangle2); obj.comboBox1:setLeft(5); obj.comboBox1:setTop(30); obj.comboBox1:setWidth(300); obj.comboBox1:setHeight(25); obj.comboBox1:setField("armazenamento1"); obj.comboBox1:setItems({'', 'Coldre Pequeno', 'Coldre Grande'}); obj.comboBox1:setValues({'0','4','6'}); obj.comboBox1:setName("comboBox1"); obj.comboBox2 = GUI.fromHandle(_obj_newObject("comboBox")); obj.comboBox2:setParent(obj.rectangle2); obj.comboBox2:setLeft(5); obj.comboBox2:setTop(55); obj.comboBox2:setWidth(300); obj.comboBox2:setHeight(25); obj.comboBox2:setField("armazenamento2"); obj.comboBox2:setItems({'', 'Coldre Pequeno', 'Coldre Grande'}); obj.comboBox2:setValues({'0','4','6'}); obj.comboBox2:setName("comboBox2"); obj.comboBox3 = GUI.fromHandle(_obj_newObject("comboBox")); obj.comboBox3:setParent(obj.rectangle2); obj.comboBox3:setLeft(5); obj.comboBox3:setTop(80); obj.comboBox3:setWidth(300); obj.comboBox3:setHeight(25); obj.comboBox3:setField("armazenamento3"); obj.comboBox3:setItems({'+0', '+1', '+2', '+3', '+4', '+5', '+6'}); obj.comboBox3:setValues({'0','1','2','3','4','5','6'}); obj.comboBox3:setName("comboBox3"); obj.dataLink1 = GUI.fromHandle(_obj_newObject("dataLink")); obj.dataLink1:setParent(obj.rectangle2); obj.dataLink1:setFields({'armazenamento1','armazenamento2','armazenamento3'}); obj.dataLink1:setName("dataLink1"); obj.rectangle3 = GUI.fromHandle(_obj_newObject("rectangle")); obj.rectangle3:setParent(obj.scrollBox1); obj.rectangle3:setLeft(0); obj.rectangle3:setTop(165); obj.rectangle3:setWidth(1210); obj.rectangle3:setHeight(505); obj.rectangle3:setColor("black"); obj.rectangle3:setStrokeColor("white"); obj.rectangle3:setStrokeSize(1); obj.rectangle3:setName("rectangle3"); obj.label7 = GUI.fromHandle(_obj_newObject("label")); obj.label7:setParent(obj.rectangle3); obj.label7:setLeft(5); obj.label7:setTop(5); obj.label7:setWidth(200); obj.label7:setHeight(25); obj.label7:setHorzTextAlign("center"); obj.label7:setText("Itens Guardados"); obj.label7:setName("label7"); obj.label8 = GUI.fromHandle(_obj_newObject("label")); obj.label8:setParent(obj.rectangle3); obj.label8:setLeft(205); obj.label8:setTop(5); obj.label8:setWidth(700); obj.label8:setHeight(25); obj.label8:setHorzTextAlign("center"); obj.label8:setText("Efeitos Adicionais"); obj.label8:setName("label8"); obj.label9 = GUI.fromHandle(_obj_newObject("label")); obj.label9:setParent(obj.rectangle3); obj.label9:setLeft(905); obj.label9:setTop(5); obj.label9:setWidth(150); obj.label9:setHeight(25); obj.label9:setHorzTextAlign("center"); obj.label9:setText("Tipo"); obj.label9:setName("label9"); obj.label10 = GUI.fromHandle(_obj_newObject("label")); obj.label10:setParent(obj.rectangle3); obj.label10:setLeft(1055); obj.label10:setTop(5); obj.label10:setWidth(50); obj.label10:setHeight(25); obj.label10:setHorzTextAlign("center"); obj.label10:setText("Qtd"); obj.label10:setName("label10"); obj.label11 = GUI.fromHandle(_obj_newObject("label")); obj.label11:setParent(obj.rectangle3); obj.label11:setLeft(1105); obj.label11:setTop(5); obj.label11:setWidth(50); obj.label11:setHeight(25); obj.label11:setHorzTextAlign("center"); obj.label11:setText("Max"); obj.label11:setName("label11"); obj.rclInventario = GUI.fromHandle(_obj_newObject("recordList")); obj.rclInventario:setParent(obj.rectangle3); obj.rclInventario:setLeft(5); obj.rclInventario:setTop(30); obj.rclInventario:setWidth(1200); obj.rclInventario:setHeight(470); obj.rclInventario:setName("rclInventario"); obj.rclInventario:setField("listaDeItens"); obj.rclInventario:setTemplateForm("frmItem"); obj.rclInventario:setLayout("vertical"); obj.rclInventario:setMinQt(10); obj._e_event0 = obj.dataLink1:addEventListener("onChange", function (_, field, oldValue, newValue) if sheet==nil then return end; local armazenamento1 = (tonumber(sheet.armazenamento1) or 0); local armazenamento2 = (tonumber(sheet.armazenamento2) or 0); local armazenamento3 = (tonumber(sheet.armazenamento3) or 0); local tamanho = 10 + armazenamento1 + armazenamento2 + armazenamento3; sheet.inventarioTamanho = tamanho; self.rclInventario.minQt = tamanho; local objetos = NDB.getChildNodes(sheet.listaDeItens); if #objetos > tamanho then local excesso = #objetos - tamanho; showMessage("Você possui " .. excesso .. " itens além do limite."); end; end, obj); function obj:_releaseEvents() __o_rrpgObjs.removeEventListenerById(self._e_event0); end; obj._oldLFMDestroy = obj.destroy; function obj:destroy() self:_releaseEvents(); if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then self:setNodeDatabase(nil); end; if self.comboBox3 ~= nil then self.comboBox3:destroy(); self.comboBox3 = nil; end; if self.label1 ~= nil then self.label1:destroy(); self.label1 = nil; end; if self.edit4 ~= nil then self.edit4:destroy(); self.edit4 = nil; end; if self.label8 ~= nil then self.label8:destroy(); self.label8 = nil; end; if self.label11 ~= nil then self.label11:destroy(); self.label11 = nil; end; if self.label3 ~= nil then self.label3:destroy(); self.label3 = nil; end; if self.label4 ~= nil then self.label4:destroy(); self.label4 = nil; end; if self.label6 ~= nil then self.label6:destroy(); self.label6 = nil; end; if self.edit5 ~= nil then self.edit5:destroy(); self.edit5 = nil; end; if self.comboBox1 ~= nil then self.comboBox1:destroy(); self.comboBox1 = nil; end; if self.edit6 ~= nil then self.edit6:destroy(); self.edit6 = nil; end; if self.label7 ~= nil then self.label7:destroy(); self.label7 = nil; end; if self.edit7 ~= nil then self.edit7:destroy(); self.edit7 = nil; end; if self.dataLink1 ~= nil then self.dataLink1:destroy(); self.dataLink1 = nil; end; if self.label2 ~= nil then self.label2:destroy(); self.label2 = nil; end; if self.edit3 ~= nil then self.edit3:destroy(); self.edit3 = nil; end; if self.label5 ~= nil then self.label5:destroy(); self.label5 = nil; end; if self.edit8 ~= nil then self.edit8:destroy(); self.edit8 = nil; end; if self.rectangle2 ~= nil then self.rectangle2:destroy(); self.rectangle2 = nil; end; if self.rectangle3 ~= nil then self.rectangle3:destroy(); self.rectangle3 = nil; end; if self.rclInventario ~= nil then self.rclInventario:destroy(); self.rclInventario = nil; end; if self.edit2 ~= nil then self.edit2:destroy(); self.edit2 = nil; end; if self.label9 ~= nil then self.label9:destroy(); self.label9 = nil; end; if self.label10 ~= nil then self.label10:destroy(); self.label10 = nil; end; if self.scrollBox1 ~= nil then self.scrollBox1:destroy(); self.scrollBox1 = nil; end; if self.rectangle1 ~= nil then self.rectangle1:destroy(); self.rectangle1 = nil; end; if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end; if self.comboBox2 ~= nil then self.comboBox2:destroy(); self.comboBox2 = nil; end; self:_oldLFMDestroy(); end; obj:endUpdate(); return obj; end; function newfrmInventory() local retObj = nil; __o_rrpgObjs.beginObjectsLoading(); __o_Utils.tryFinally( function() retObj = constructNew_frmInventory(); end, function() __o_rrpgObjs.endObjectsLoading(); end); assert(retObj ~= nil); return retObj; end; local _frmInventory = { newEditor = newfrmInventory, new = newfrmInventory, name = "frmInventory", dataType = "", formType = "undefined", formComponentName = "form", title = "", description=""}; frmInventory = _frmInventory; Firecast.registrarForm(_frmInventory); return _frmInventory;
return require('lib/tap')(function (test) test("uv.loop_mode", function (print, p, expect, uv) assert(uv.loop_mode() == nil) local timer = uv.new_timer() uv.timer_start(timer, 100, 0, expect(function () assert(uv.loop_mode() == "default") uv.timer_stop(timer) uv.close(timer) end)) end) end)
-- ############## CONSTANTES ############## -- ####### PROBABILIDADES ####### -- k1: probabilidade da celula cancerigena se multiplicar k1_prob_reacao = 0.74 k1 = "reacao_celula_cancerigena_se_multiplicar" -- k2: probabilidade de ocorrer effector cell k2_prob_reacao = 0.2 k2 = "reacao_effector_cell" -- probabilidade de nao ocorrencia de k1 e k2 prob_nao_acontecer_k1_e_k2 = 1 - (k1_prob_reacao + k2_prob_reacao) nao_ocorrer_k1_e_k2 = "nao_ocorrer_k1_e_k2" -- k3: probabilidade do complexo morrer k3_prob_reacao = 0.4 k3 = "reacao_celula_complexa_morrer" -- probabilidade de nao ocorrencia de k3 prob_nao_acontecer_k3 = 1 - k3_prob_reacao nao_ocorrer_k3 = "nao_ocorrer_k3" -- k4: probabilidade celula morta reviver k4_prob_reacao = 0.4 k4 = "reacao_celula_morta_reviver" -- probabilidade de nao ocorrencia de k4 prob_nao_acontecer_k4 = 1 - k4_prob_reacao nao_ocorrer_k4 = "nao_ocorrer_k4" -- ####### TIPO DE CELULA ####### Normal = "normal" -- branco (vazio) - célula normal C = "cancerigena" -- pretos - células cancerigena (consideradas anormais) D = "morta" -- verdes - células cancerigena mortas E = "complexo" -- vermelhos - complexos produzidos pelo processo citotóxico, -- ou seja, substâncias que são tóxicas as células. -- ####### DIMENSAO E TEMPO ####### -- quantidade de celulas no eixo x XDIM = 101 -- dimensao do trabalho --XDIM = 31 -- XDIM = 11 -- quantidade de tempos que serao executados TEMPOS = 50 -- tempo do trabalho -- TEMPOS = 30 --TEMPOS = 10 -- ############## FUNCOES AUXILIARES ############## local function table_constains_value (table, value) for __index__, __value__ in ipairs(table) do if __value__ == value then return true end end return false end local function size_of (table) local count = 0 for __index__, __value__ in ipairs(table) do count = count + 1 end return count end local function print_table (table) for i, v in ipairs(table) do print(i, v) end end -- ############## CELULA ############## cell = Cell{ state = Random{Normal, C, D, E}, getPositionsOfNeighbors = function(self) local positions_of_neighbors = { top = {x = self.x-1, y = self.y}, bottom = {x = self.x+1, y = self.y}, left = {x = self.x, y = self.y-1}, right = {x = self.x, y = self.y+1} } return positions_of_neighbors end, execute = function(self) -- ocorrer k1 e k2 local ocorrer_reacao_k1_ou_k2 = Random{ reacao_celula_cancerigena_se_multiplicar = k1_prob_reacao, reacao_effector_cell = k2_prob_reacao, nao_ocorrer_k1_e_k2 = prob_nao_acontecer_k1_e_k2 } local ocorrer_reacao_k1_ou_k2_str = ocorrer_reacao_k1_ou_k2:sample() -- ocorrer k3 local ocorrer_reacao_k3 = Random{ reacao_celula_complexa_morrer = k3_prob_reacao, nao_ocorrer_k3 = prob_nao_acontecer_k3 } local ocorrer_reacao_k3_str = ocorrer_reacao_k3:sample() -- ocorrer k4 local ocorrer_reacao_k4 = Random{ reacao_celula_morta_reviver = k4_prob_reacao, nao_ocorrer_k4 = prob_nao_acontecer_k4 } local ocorrer_reacao_k4_str = ocorrer_reacao_k4:sample() -- print("\nMe: (", self.x, ", ", self.y, ") - state: ", self.state, " - reaction: ", ocorrer_reacao_str) -- se a celula for cancerigena e houver chance de multiplicar-se -- k1 = "reacao_celula_cancerigena_se_multiplicar" if self.state == C and ocorrer_reacao_k1_ou_k2_str == k1 then -- pega a posicao dos vizinhos local positions_of_neighbors = self:getPositionsOfNeighbors() -- verificar se necessita sortear um novo vizinho local raffle_new_neighbor = true -- insere os lados escolhidos aqui, para caso sorteie todos os 4 lados -- e todos forem cancerigenos, entao sai do loop local sides_chosen = {} -- quantas vezes foi gerado um lado aleatorio local count_random_side = 1 -- quantidade maxima de vezes que pode gerar um lado aleatorio -- apos isso, para evitar loop infinito, gera um lado deterministico local MAX_RANDOM_SIDE = 10 local SIDES = {"top", "bottom", "left", "right"} -- sides_chosen.getn(sides_chosen) --> len(sides_chosen) while raffle_new_neighbor and size_of(sides_chosen) < 4 do ::continue01:: local __break__ = false local random_side = Random{"top", "bottom", "left", "right"} local random_side_chosen = random_side.sample() -- se tentar gerar mais de MAX_RANDOM_SIDE vezes um lado aleatorio -- e nao conseguir, pega um valor deterministico para nao cair em loop infinito if count_random_side >= MAX_RANDOM_SIDE then random_side_chosen = table.remove(SIDES, 1) end -- se o lado sorteado nao tiver sido escolhido, entao insere na lista if not table_constains_value (sides_chosen, random_side_chosen) then table.insert(sides_chosen, random_side_chosen) -- se o lado sorteado tiver sido escolhido, entao volta ao loop para sortear outro else count_random_side = count_random_side + 1 goto continue01 end -- pega um vizinho aleatorio local random_neighbor = positions_of_neighbors[random_side_chosen] -- percorre todos os vizinhos da celula forEachNeighbor(self, function(neigh) -- simula um break if __break__ == false then -- se o vizinho percorrido for igual ao sorteado if (neigh.x == random_neighbor.x and neigh.y == random_neighbor.y) then -- se a celula vizinha for normal, infecta ela if neigh.state == Normal then neigh.state = C -- celula cancerigena -- nao precisa sortear um novo vizinho -- pq foi possivel infectar raffle_new_neighbor = false end -- se o vizinho escolhido for normal ou outra coisa, pode quebrar o laco __break__ = true end end -- __break__ end) -- forEachNeighbor end -- while -- se a celula for cancerigena, ha uma probabilidade k2 de ocorrer um effector cell -- entao celula cancerigena vira um complexo elseif self.state == C and ocorrer_reacao_k1_ou_k2_str == k2 then self.state = E -- celula complexa -- se a celula for um complexo, ha uma probabilidade k3 dela morrer elseif self.state == E and ocorrer_reacao_k3_str == k3 then self.state = D -- celula morta -- se a celula estiver morta, ha uma probabilidade k4 dela reviver elseif self.state == D and ocorrer_reacao_k4_str == k4 then self.state = Normal -- celula normal -- se a celula for normal, faz nada com ela --elseif self.state == Normal then --print("I'm normal") end end } -- ############## CRIA O AMBIENTE ############## -- cria o space space = CellularSpace{ instance = cell, xdim = XDIM } -- escolhe o tipo de vizinhanca space:createNeighborhood{ strategy = "vonneumann", self = true } -- ############## INICIALIZACAO ############## -- inicializa todas as celulas como normais forEachCell(space, function(cell) cell.state = Normal end) --depois pega as 5 celulas do centro e coloca como cancerigenas mid = (XDIM - 1) / 2 centralCell = space:get(mid, mid) centralCell_top = space:get(mid, mid-1) centralCell_bottom = space:get(mid, mid+1) centralCell_left = space:get(mid-1, mid) centralCell_right = space:get(mid+1, mid) centralCell.state = C centralCell_top.state = C centralCell_bottom.state = C centralCell_left.state = C centralCell_right.state = C -- ############## CRIA O MAPA ############## map = Map{ target = space, select = "state", value = {Normal, C, D, E}, color = {"white", "black", "green", "red"} } -- ############## EXECUCAO ############## -- variavel para contar os tempos passados t = 1 timer = Timer{ Event{action = function() print("\n\nTIME: ", t, "\n") space:synchronize() space:execute() t = t + 1 end}, Event{action = map} } timer:run(TEMPOS)
--[[ Copyright (C) 2018 Google Inc. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ]] --[[ This is a random dot motion discrimination task. In each trial the agent is presented with a field of moving dots, most of which are moving in the same direction. The agent must select this direction. ]] local game = require 'dmlab.system.game' local log = require 'common.log' local helpers = require 'common.helpers' local image = require 'dmlab.system.image' local point_and_click = require 'factories.psychlab.point_and_click' local psychlab_factory = require 'factories.psychlab.factory' local psychlab_helpers = require 'factories.psychlab.helpers' local psychlab_staircase = require 'levels.contributed.psychlab.factories.staircase' local random = require 'common.random' local set = require 'common.set' local tensor = require 'dmlab.system.tensor' -- setup constant parameters of the task local TIME_TO_FIXATE_CROSS = 1 -- in frames local TIME_TO_FIXATE_TARGET = 1 -- in frames local INTER_TRIAL_INTERVAL = 1 -- in frames local SCREEN_SIZE = {width = 512, height = 512} local ANIMATION_SIZE_AS_FRACTION_OF_SCREEN = {0.8, 0.8} local BG_COLOR = 0 local FIXATION_SIZE = 0.1 local FIXATION_COLOR = {255, 0, 0} -- RGB local CENTER = {.5, .5} local BUTTON_SIZE = 0.1 local FIXATION_REWARD = 0 local CORRECT_REWARD = 1 local INCORRECT_REWARD = 0 local MAX_IDLE_STEPS = 500 local INTERFRAME_INTERVAL = 4 -- in REAL (Labyrinth) frames local VIDEO_LENGTH = 120 -- multiply by INTERFRAME_INTERVAL to get real frames local PRERESPONSE_DELAY = 1 local DOT_DIAMETER = 6 local DOT_COLOR = {255, 255, 255} local NUM_DOTS = 350 local SPEED = 28 local CANVAS_SIZE = 2048 local PRE_RENDER_MASK_SIZE = 1224 local COHERENCES = {1.0, 0.9, 0.75, 0.5, 0.35, 0.2, 0.1, 0.05} local GAUSSIAN_MASK_SIGMA = 0.10 -- nice big size -- Staircase parameters local FRACTION_TO_PROMOTE = 0.75 local FRACTION_TO_DEMOTE = 0.5 local PROBE_PROBABILITY = 0.1 -- Setup response button arrows local ARROWS_DIR = game:runFiles() .. '/baselab/game_scripts/levels/contributed/psychlab/data' local ARROW_SIZE = .075 local RADIUS = .4 local factory = {} function factory.createLevelApi(kwargs) -- Currently there are no configurable parameters for this environment, -- so kwargs are ignored. local function xLoc(angle) return CENTER[1] + (RADIUS * math.cos(angle)) - (ARROW_SIZE / 2) end local function yLoc(angle) return 1 - (CENTER[2] + (RADIUS * math.sin(angle)) + (ARROW_SIZE / 2)) end local ARROW_POS = { topLeft = {xLoc(3 * math.pi / 4), yLoc(3 * math.pi / 4)}, topMiddle = {xLoc(math.pi / 2), yLoc(math.pi / 2)}, topRight = {xLoc(math.pi / 4), yLoc(math.pi / 4)}, middleLeft = {xLoc(math.pi), yLoc(math.pi)}, middleRight = {xLoc(0), yLoc(0)}, bottomLeft = {xLoc(5 * math.pi / 4), yLoc(5 * math.pi / 4)}, bottomMiddle = {xLoc(3 * math.pi / 2), yLoc(3 * math.pi / 2)}, bottomRight = {xLoc(7 * math.pi / 4), yLoc(7 * math.pi / 4)} } -- Class definition for motion discrimination psychlab environment. local env = {} env.__index = env setmetatable(env, { __call = function (cls, ...) local self = setmetatable({}, cls) self:_init(...) return self end }) -- init is called at the start of each episode. function env:_init(pac, opts) self.screenSize = opts.screenSize log.info('opts passed to _init:\n' .. helpers.tostring(opts)) self._stepsSinceInteraction = 0 self:setupImages() self:setupCoordinateBounds(CANVAS_SIZE, PRE_RENDER_MASK_SIZE) self.motionDirections = {} for i = 1, 8 do self.motionDirections[i] = (i - 1) * math.pi / 4 end -- handle to the point and click api self.pac = pac end -- reset is called after init. It is called only once per episode. -- Note: the episodeId passed to this function may not be correct if the job -- has resumed from a checkpoint after preemption. function env:reset(episodeId, seed, ...) random:seed(seed) self.pac:setBackgroundColor{BG_COLOR, BG_COLOR, BG_COLOR} self.pac:clearWidgets() psychlab_helpers.addFixation(self, FIXATION_SIZE) self.reward = 0 self:initAnimation(ANIMATION_SIZE_AS_FRACTION_OF_SCREEN) self.currentTrial = {} -- setup the adaptive staircase procedure self.staircase = psychlab_staircase.createStaircase1D{ sequence = COHERENCES, fractionToPromote = FRACTION_TO_PROMOTE, fractionToDemote = FRACTION_TO_DEMOTE, probeProbability = PROBE_PROBABILITY, } -- blockId groups together all rows written during the same episode self.blockId = seed end function env:fillCircle(dest) -- Dest is (size, size, 3) local size = dest:shape()[1] local center = (size + 1) / 2 local radiusSq = (size / 2) ^ 2 for i = 1, size do for j = 1, size do if (i - center) ^ 2 + (j - center) ^ 2 < radiusSq then dest(i, j):val(DOT_COLOR) end end end end -- Creates image tensors for buttons, objects-to-track and the fixation cross. function env:setupImages() self.images = {} self.images.fixation = psychlab_helpers.getFixationImage(self.screenSize, BG_COLOR, FIXATION_COLOR, FIXATION_SIZE) local h = BUTTON_SIZE * self.screenSize.height local w = BUTTON_SIZE * self.screenSize.width self.images.greenImage = tensor.ByteTensor(h, w, 3):fill{100, 255, 100} self.images.redImage = tensor.ByteTensor(h, w, 3):fill{255, 100, 100} self.images.blackImage = tensor.ByteTensor(h, w, 3) self.arrowIDs = {3, 2, 1, 6, 4, 9, 8, 7} self.arrowPositions = { ARROW_POS.topLeft, ARROW_POS.topMiddle, ARROW_POS.topRight, ARROW_POS.middleLeft, ARROW_POS.middleRight, ARROW_POS.bottomLeft, ARROW_POS.bottomMiddle, ARROW_POS.bottomRight } -- map orientations from 0 to 2pi to arrowIds self.mapAngleIdsToArrows = {4, 1, 2, 3, 6, 9, 8, 7} self.arrowSize = { height = ARROW_SIZE * self.screenSize.height, width = ARROW_SIZE * self.screenSize.width, } self.images.arrows = {} for _, i in pairs(self.arrowIDs) do local arrow = image.load(ARROWS_DIR .. '/arrow_' .. i .. '.png') arrow = image.scale(arrow, self.arrowSize.height, self.arrowSize.width) local arrowRGB = tensor.ByteTensor( self.arrowSize.height, self.arrowSize.width, 3) arrowRGB:select(3, 1):copy(arrow) arrowRGB:select(3, 2):copy(arrow) arrowRGB:select(3, 3):copy(arrow) self.images.arrows[i] = arrowRGB end end function env:setupCoordinateBounds(canvasSize, preRenderMaskSize) local preRenderLowerBound = math.floor((canvasSize - preRenderMaskSize) / 2) local preRenderUpperBound = canvasSize - preRenderLowerBound local function isAboveLowerBound(coord) return coord > preRenderLowerBound end local function isBelowUpperBound(coord) return coord < preRenderUpperBound end self.isInBounds = function (coord) return isAboveLowerBound(coord) and isBelowUpperBound(coord) end end function env:initAnimation(sizeAsFractionOfScreen) local imageHeight = sizeAsFractionOfScreen[1] * self.screenSize.height local imageWidth = sizeAsFractionOfScreen[2] * self.screenSize.width self.animation = { currentFrame = tensor.ByteTensor(imageHeight, imageWidth, 3):fill(0), nextFrame = tensor.ByteTensor(imageHeight, imageWidth, 3):fill(0), imageSize = imageHeight, -- Assume height and width are the same } local sigma = GAUSSIAN_MASK_SIGMA -- Make gaussian by hand local gaussian = tensor.Tensor(imageHeight, imageWidth) local cx = 0.5 * imageWidth + 0.5 local cy = 0.5 * imageHeight + 0.5 gaussian:applyIndexed(function(_, index) local y, x = unpack(index) return math.exp(-math.pow((x - cx) / (sigma * imageWidth), 2) / 2 -math.pow((y - cy) / (sigma * imageHeight), 2) / 2) end) self.gaussianMask = gaussian end function env:finishTrial(delay) self._stepsSinceInteraction = 0 self.currentTrial.blockId = self.blockId self.currentTrial.reactionTime = game:episodeTimeSeconds() - self._currentTrialStartTime self.staircase:step(self.currentTrial.correct == 1) -- Convert radians to degrees before logging self.currentTrial.motionDirection = math.floor(self.currentTrial.motionDirection * (180 / math.pi) + 0.5) psychlab_helpers.publishTrialData(self.currentTrial, kwargs.schema) psychlab_helpers.finishTrialCommon(self, delay, FIXATION_SIZE) end function env:fixationCallback(name, mousePos, hoverTime, userData) if hoverTime == TIME_TO_FIXATE_CROSS then self._stepsSinceInteraction = 0 self.pac:addReward(FIXATION_REWARD) self.pac:removeWidget('fixation') self.pac:removeWidget('center_of_fixation') -- Sample all trial-unique data self.currentTrial.coherence = self.staircase:parameter() local angleId self.currentTrial.motionDirection, angleId = psychlab_helpers.randomFrom( self.motionDirections) self.currentTrial.correctArrow = self.mapAngleIdsToArrows[angleId] self.pac:addTimer{ name = 'preresponse_delay', timeout = PRERESPONSE_DELAY, callback = function(...) return self.addArrows(self, self.currentTrial.correctArrow) end } self:displayDotMotion() end end function env:correctResponseCallback(name, mousePos, hoverTime, userData) if hoverTime == TIME_TO_FIXATE_TARGET then self.currentTrial.response = name self.currentTrial.correct = 1 self.pac:addReward(CORRECT_REWARD) self:finishTrial(INTER_TRIAL_INTERVAL) end end function env:incorrectResponseCallback(name, mousePos, hoverTime, userData) if hoverTime == TIME_TO_FIXATE_TARGET then self.currentTrial.response = name self.currentTrial.correct = 0 self.pac:addReward(INCORRECT_REWARD) self:finishTrial(INTER_TRIAL_INTERVAL) end end function env:addArrows(correctID) -- Once the arrows appear the agent can break fixation with no penalty. self.pac:removeWidget('hold_fixation') for k, i in pairs(self.arrowIDs) do local arrow = self.images.arrows[i] local callback if i == correctID then callback = self.correctResponseCallback else callback = self.incorrectResponseCallback end self.pac:addWidget{ name = i, image = arrow, pos = self.arrowPositions[k], size = {ARROW_SIZE, ARROW_SIZE}, mouseHoverCallback = callback, imageLayer = 3, } end end function env:transformToFrameCoords(coords) self._frameCoords:val({ math.floor((coords(1):val() / CANVAS_SIZE) * self._frameSize[1] + 0.5), math.floor((coords(2):val() / CANVAS_SIZE) * self._frameSize[2] + 0.5) }) return self._frameCoords end function env:renderFrame(coords) -- coords is a tensor of size [numObjects, 2] describing the coordinates of -- each object in the next frame to be displayed after the current frame. local frame = tensor.Tensor(unpack(self.animation.nextFrame:shape())) :fill(BG_COLOR) -- Setup stored size and frameCoords buffer the first time this is called. if not self._frameSize then self._frameCoords = coords(1):clone() self._frameSize = frame:shape() end for i = 1, coords:shape()[1] do if self.isInBounds(coords(i, 1):val()) and self.isInBounds(coords(i, 2):val()) then -- Transform from canvas coordinate system to frame coordinate system self._frameCoords = self:transformToFrameCoords(coords(i)) local cx, cy = self._frameCoords(2):val(), self._frameCoords(1):val() local dest = frame:narrow(1, cy - DOT_DIAMETER / 2, DOT_DIAMETER) :narrow(2, cx - DOT_DIAMETER / 2, DOT_DIAMETER) self:fillCircle(dest) end end -- Apply gaussian aperture to R, G, B channels separately local gaussianMask = self.gaussianMask frame:select(3, 1):cmul(gaussianMask) frame:select(3, 2):cmul(gaussianMask) frame:select(3, 3):cmul(gaussianMask) return frame:byte() end function env:displayFrame(videoCoords, index) -- show the current frame self.pac:updateWidget('main_image', self.animation.currentFrame) -- recursively call this function after the interframe interval self.pac:addTimer{ name = 'interframe_interval', timeout = INTERFRAME_INTERVAL, callback = function(...) self:displayFrame() end } self.animation.transition() -- updates state -- render the next frame self.animation.nextFrame = self:renderFrame(self.animation.state) -- update the reference called currentFrame to point to the next tensor self.animation.currentFrame = self.animation.nextFrame end function env:generateMotionData(motionDirection) local positions = tensor.Tensor(NUM_DOTS, 2) local randomCoordFn = function(_) return random:uniformInt(0, CANVAS_SIZE) end positions:apply(randomCoordFn) local displacement = tensor.Tensor{ (-1) * SPEED * math.sin(motionDirection), SPEED * math.cos(motionDirection), } local numCoherentDots = math.floor(self.currentTrial.coherence * NUM_DOTS) local numIncoherentDots = NUM_DOTS - numCoherentDots local transition = function() for dot = 1, numCoherentDots do local position = positions(dot) position:cadd(displacement) position:apply(function(val) return val % CANVAS_SIZE end) end if numIncoherentDots > 0 then positions:narrow(1, numCoherentDots + 1, numIncoherentDots) :apply(randomCoordFn) end end return positions, transition end function env:displayDotMotion() -- Measure reaction time from start of dot motion self._currentTrialStartTime = game:episodeTimeSeconds() self.currentTrial.stepCount = 0 self.animation.state, self.animation.transition = self:generateMotionData( self.currentTrial.motionDirection) -- Create the widget and display the first frame local upperLeftPosition = psychlab_helpers.getUpperLeftFromCenter( CENTER, ANIMATION_SIZE_AS_FRACTION_OF_SCREEN[1] ) self.animation.currentFrame = self:renderFrame(self.animation.state) self.pac:addWidget{ name = 'main_image', image = self.animation.currentFrame, pos = upperLeftPosition, size = ANIMATION_SIZE_AS_FRACTION_OF_SCREEN, imageLayer = 2, } self:displayFrame() -- starts animation end -- Remove the test array function env:removeArray() -- remove the image and response buttons self.pac:removeWidget('main_image') -- remove the arrows for _, i in pairs(self.arrowIDs) do self.pac:removeWidget(i) end self.pac:clearTimers() end -- Increment counter to allow measurement of reaction times in steps -- This function is automatically called at each tick. function env:step(lookingAtScreen) if self.currentTrial.stepCount ~= nil then self.currentTrial.stepCount = self.currentTrial.stepCount + 1 end -- If too long since interaction with any buttons, then end episode. This -- should speed up the early stages of training, since it causes less time -- to be spent looking away from the screen. self._stepsSinceInteraction = self._stepsSinceInteraction + 1 if self._stepsSinceInteraction > MAX_IDLE_STEPS then self.pac:endEpisode() end end return psychlab_factory.createLevelApi{ env = point_and_click, envOpts = { environment = env, screenSize = SCREEN_SIZE }, episodeLengthSeconds = 150 } end return factory
local brickColorsPalette = { name = "BrickColors", colors = {} } for i = 1, 1032 do local brickColor = BrickColor.new(i) -- BrickColors that don't exist default to #194 if ((brickColor.Number ~= 194) or (i == 194)) then table.insert(brickColorsPalette.colors, { name = brickColor.Name, color = brickColor.Color }) end end return brickColorsPalette
module(..., package.seeall) local log = require("log") local link = require("core.link") Fwd = {} function Fwd:new() return setmetatable({transmitted = 0}, {__index = Fwd}) end function Fwd:pull() if not self.output.output then log:fatal("Fwd: output link not created") elseif not self.input.input then log:fatal("Fwd: input link not created") end local n = link.nreadable(self.input.input) for _ = 1, n do link.transmit(self.output.output, link.receive(self.input.input)) end self.transmitted = self.transmitted + n end function Fwd:report() log:info("Fwd '%s' transmitted %d packets", self.appname, self.transmitted) end
local args = (function() local parser = require('argparse')() parser:option('-t --type', 'default type', 'string') return parser:parse() end)() local assert = require('luassert') local function ident(n) if n.tag == 'Id' then return n[1] elseif n.tag == 'Index' then assert.same(2, #n) assert.same('Id', n[1].tag) assert.same('String', n[2].tag) return n[1][1] .. '.' .. n[2][1] elseif n.tag == 'Invoke' then assert.same(2, #n) assert.same('Id', n[1].tag) assert.same('String', n[2].tag) return n[1][1] .. '.' .. n[2][1] else error('unexpected tag ' .. tostring(n.tag)) end end local function call(n) assert.same('Call', n.tag) local inputs = {} for i = 2, #n do table.insert(inputs, { name = ident(n[i]), type = args.type, }) end return ident(n[1]), inputs end local function proto2api(s) local ast = require('metalua.compiler').new():src_to_ast(s) assert.same(1, #ast) local n = ast[1] local inputs, name local outputs = {} if n.tag == 'Call' then name, inputs = call(n) elseif n.tag == 'Local' or n.tag == 'Set' then assert.same(2, #n) for _, id in ipairs(n[1]) do table.insert(outputs, { name = ident(id), type = args.type, }) end assert.same(1, #n[2]) name, inputs = call(n[2][1]) else error('unexpected tag ' .. n.tag) end return { name = name, status = 'unimplemented', inputs = { inputs }, outputs = outputs, } end local api = proto2api(io.read('*a')) local filename = ('data/api/%s.yaml'):format(api.name) require('pl.file').write(filename, require('wowapi.yaml').pprint(api)) print(filename)
EnemyBrain = {} -- TODO: Instances using self? require 'Enemy.EnemyStatusType' local maxHP = 100 EnemyBrain.Status = EnemyStatusType.Null EnemyBrain.lastTurnMoved = 0 EnemyBrain.MoveCooldown = 8 -- 8 turns before player can move again EnemyBrain.FootstepsVolume = 0.3 require 'Enemy.EnemyMovement' require 'Enemy.EnemyActions' WakeTurn = 5 -- Enemy waits till turn 5 to first move function EnemyBrain.Spawn(x, y) EnemyBrain.CurrentHP = maxHP EnemyBrain.Status = EnemyStatusType.Alive EnemyMovement.SetLocation(x, y) end function EnemyBrain.TakeDamage(damage) if (EnemyBrain.Status == EnemyStatusType.Alive) then EnemyBrain.CurrentHP = EnemyBrain.CurrentHP - damage EnemyBrain.PlayMonsterStabbedSound() if (EnemyBrain.CurrentHP <= 0) then EnemyBrain.Die() else EnemyBrain.PlayMonsterPainSound() EnemyBrain.moveToEmptySpace() end end end function EnemyBrain.Die() EnemyBrain.Status = EnemyStatusType.Dead EnemyBrain.PlayMonsterDeathSound() end function EnemyBrain.nextTurn(turn) if (EnemyBrain.Status == EnemyStatusType.Alive) then LastMoveTurn = Game.Turn if (EnemyBrain.playerAdjacent()) then -- TODO: Swing attack, chance to miss EnemyBrain.playerFound(turn) end -- TODO: chance to move if (EnemyBrain.lastTurnMoved + EnemyBrain.MoveCooldown <= turn) then EnemyBrain.moveToEmptySpace() end else if (EnemyBrain.Status == EnemyStatusType.Asleep and turn >= WakeTurn) then EnemyBrain.Status = EnemyStatusType.Alive end end end local playerSpottedTurn = -1 function EnemyBrain.playerFound(turn) if (playerSpottedTurn == -1 or playerSpottedTurn + 5 < turn) then playerSpottedTurn = turn print("Player found") EnemyBrain.playAudioClipICanSeeYou() end if (not playerSpottedTurn == turn) then print("Attempt attack") x = math.random(0, 4) if (x == 1) then EnemyActions.PrimaryActionUp() end if (x == 2) then EnemyActions.PrimaryLeft() end if (x == 3) then EnemyActions.PrimaryActionDown() end if (x == 4) then EnemyActions.PrimaryActionRight() end end end function EnemyBrain.playerAdjacent() local playerDistance = EnemyBrain.GetPlayerDistance() if (playerDistance == 1) then return true else return false end end function EnemyBrain.GetPlayerDistance() return math.abs((EnemyMovement.Position.x - PlayerMovement.Position.x) + (EnemyMovement.Position.y - PlayerMovement.Position.y)) -- TODO: As the crow flies? end function EnemyBrain.moveToEmptySpace() x = math.random(0, 4) northTile = Map.GetTile(EnemyMovement.Position.x, EnemyMovement.Position.y + 1) if (northTile == TileType.Floor and x == 1) then EnemyMovement.MoveForward() return end eastTile = Map.GetTile(EnemyMovement.Position.x + 1, EnemyMovement.Position.y) if (eastTile == TileType.Floor and x == 2) then EnemyMovement.MoveRight() return end southTile = Map.GetTile(EnemyMovement.Position.x, EnemyMovement.Position.y - 1) if (southTile == TileType.Floor and x == 3) then EnemyMovement.MoveDown() return end westTile = Map.GetTile(EnemyMovement.Position.x - 1, EnemyMovement.Position.y) if (westTile == TileType.Floor and x == 4) then EnemyMovement.MoveLeft() return end end function EnemyBrain.CalculateVolumeFromDistance() local distance = EnemyBrain.GetPlayerDistance() local distanceVolume = 1 - (distance * 0.1) print("Volume calculated at " .. distanceVolume .. " for distance " .. distance) return distanceVolume end function EnemyBrain.playAudioClipICanSeeYou() Engine.PlaySound(AudioAssets.ICanSeeYouFast, EnemyBrain.CalculateVolumeFromDistance()) -- TODO: Move audio based on distance end function EnemyBrain.playAudioClipICanSeeYou2() Engine.PlaySound(AudioAssets.ICanSeeYouSlow, EnemyBrain.CalculateVolumeFromDistance()) -- TODO: use I can see you when the player is adjacent end function EnemyBrain.PlayMonsterDeathSound() Engine.PlaySound(AudioAssets.MonsterDeath, EnemyBrain.CalculateVolumeFromDistance()) end function EnemyBrain.PlayMonsterStabbedSound() Engine.PlaySound(AudioAssets.MonsterStabbed, EnemyBrain.CalculateVolumeFromDistance()) end function EnemyBrain.PlayMonsterPainSound() Engine.PlaySound(AudioAssets.MonsterRoar, EnemyBrain.CalculateVolumeFromDistance()) end function EnemyBrain.PlayMonsterMoveSound() Engine.PlaySound(AudioAssets.EnemyFootsteps, EnemyBrain.CalculateVolumeFromDistance() * EnemyBrain.FootstepsVolume, false) end return EnemyBrain
dathomir_destroy_missions = { minLevelCeiling = 45, lairSpawns = { { lairTemplateName = "dathomir_brackaset_pigmy_neutral_small", minDifficulty = 8, maxDifficulty = 12, size = 25, }, { lairTemplateName = "dathomir_kwi_lair_neutral_small", minDifficulty = 8, maxDifficulty = 12, size = 25, }, { lairTemplateName = "dathomir_purbole_lair_neutral_medium_boss_01", minDifficulty = 14, maxDifficulty = 18, size = 25, }, { lairTemplateName = "dathomir_verne_bull_lair_neutral_large", minDifficulty = 14, maxDifficulty = 19, size = 25, }, { lairTemplateName = "dathomir_baz_nitch_lair_neutral_small", minDifficulty = 18, maxDifficulty = 22, size = 20, }, { lairTemplateName = "dathomir_reptilian_mature_flyer_lair_neutral_large", minDifficulty = 18, maxDifficulty = 22, size = 30, }, { lairTemplateName = "dathomir_malkloc_lair_neutral_large", minDifficulty = 19, maxDifficulty = 23, size = 35, }, { lairTemplateName = "dathomir_bolma_lair_neutral_medium_boss_01", minDifficulty = 19, maxDifficulty = 27, size = 25, }, { lairTemplateName = "dathomir_malkloc_bull_lair_neutral_large", minDifficulty = 22, maxDifficulty = 28, size = 30, }, { lairTemplateName = "dathomir_reptilian_ancient_flyer_lair_neutral_large", minDifficulty = 23, maxDifficulty = 27, size = 30, }, { lairTemplateName = "dathomir_brackaset_lair_neutral_medium", minDifficulty = 24, maxDifficulty = 28, size = 25, }, { lairTemplateName = "dathomir_gaping_spider_lair_neutral_medium_boss_01", minDifficulty = 24, maxDifficulty = 28, size = 25, }, { lairTemplateName = "dathomir_stallion_bolma_lair_neutral_medium", minDifficulty = 27, maxDifficulty = 33, size = 25, }, { lairTemplateName = "dathomir_mutant_baz_nitch_lair_neutral_small", minDifficulty = 28, maxDifficulty = 32, size = 25, }, { lairTemplateName = "dathomir_giant_baz_nitch_lair_neutral_medium", minDifficulty = 33, maxDifficulty = 37, size = 25, }, { lairTemplateName = "dathomir_rhoa_kwi_lair_neutral_medium", minDifficulty = 33, maxDifficulty = 37, size = 25, }, { lairTemplateName = "dathomir_gaping_spider_recluse_lair_neutral_medium", minDifficulty = 42, maxDifficulty = 46, size = 25, }, { lairTemplateName = "dathomir_kamurith_snapper_lair_neutral_medium", minDifficulty = 42, maxDifficulty = 46, size = 25, }, { lairTemplateName = "dathomir_brackaset_surefoot_lair_neutral_medium", minDifficulty = 44, maxDifficulty = 48, size = 35, }, { lairTemplateName = "dathomir_kamurith_nocuous_lair_neutral_medium", minDifficulty = 44, maxDifficulty = 48, size = 25, }, { lairTemplateName = "dathomir_bolma_craggy_lair_neutral_medium", minDifficulty = 45, maxDifficulty = 49, size = 25, }, { lairTemplateName = "dathomir_kamurith_defiler_lair_neutral_medium_boss_01", minDifficulty = 48, maxDifficulty = 52, size = 35, }, { lairTemplateName = "dathomir_rancor_lair_neutral_large", minDifficulty = 48, maxDifficulty = 52, size = 35, }, { lairTemplateName = "dathomir_rancor_bull_lair_neutral_large", minDifficulty = 63, maxDifficulty = 67, size = 35, }, { lairTemplateName = "dathomir_rancor_enraged_lair_neutral_large", minDifficulty = 78, maxDifficulty = 82, size = 35, }, { lairTemplateName = "dathomir_rancor_enraged_bull_lair_neutral_large_boss_01", minDifficulty = 87, maxDifficulty = 91, size = 35, }, { lairTemplateName = "dathomir_rancor_ancient_bull_lair_neutral_large", minDifficulty = 85, maxDifficulty = 90, size = 35, }, } } addDestroyMissionGroup("dathomir_destroy_missions", dathomir_destroy_missions);
local db_mgr = require "common.db_mgr" local hall_db = {} local PlayerOnlineKey = "player_online" local function get_player_online_key(id) return PlayerOnlineKey .. ":" .. id end function hall_db.get_player_online(id) local redisdb = db_mgr.get_redis_db() return array_totable(redisdb:hgetall(get_player_online_key(id))) end function hall_db.set_player_online(id, online) local redisdb = db_mgr.get_redis_db() local data = assert(table.toarray(online), "online is not table") redisdb:hmset(get_player_online_key(id), table.unpack(data)) return end function hall_db.update_player_online(id, key, value) local redisdb = db_mgr.get_redis_db() redisdb:hset(get_player_online_key(id), key, value) return end function hall_db.del_player_online(id) local redisdb = db_mgr.get_redis_db() redisdb:del(get_player_online_key(id)) return end function hall_db.del_player_online_value(id, key) local redisdb = db_mgr.get_redis_db() redisdb:hdel(get_player_online_key(id), key) return end function hall_db.set_player_online_value(id, key, value) local redisdb = db_mgr.get_redis_db() redisdb:hset(get_player_online_key(id), key, value) end return hall_db
----------------------------------------- -- ID: 6051 -- Thunderstorm Schema -- Teaches the white magic Thunderstorm ----------------------------------------- function onItemCheck(target) return target:canLearnSpell(117) end function onItemUse(target) target:addSpell(117) end
local DEPENDENCIES = { utils = require(script:GetCustomProperty("utils")), RoundService = require(script:GetCustomProperty("RoundService")), BrickService = require(script:GetCustomProperty("BrickService")), BallService = require(script:GetCustomProperty("BallService")), BallPhysics = require(script:GetCustomProperty("BallPhysics")), PaddleService = require(script:GetCustomProperty("PaddleService")), CastleService = require(script:GetCustomProperty("CastleService")), } for _, dependency in pairs(DEPENDENCIES) do if dependency.Setup then dependency.Setup(DEPENDENCIES) end end for _, player in pairs(Game.GetPlayers()) do DEPENDENCIES.RoundService.AddPlayer(player) end
-- Copyright 2010, www.lelewan.com -- All rights reserved -- -- Author: wubenqi<wubenqi@caitong.net>, 2013-01-25 -- ------------------------------------------------------------------------------------------ function ZServerSessionHandler:Initialize(ih) TRACE("ZNetSessionEngine:Initialize()") end function ZServerSessionHandler:Destroy(ih) TRACE("ZNetSessionEngine:Destroy()") end function ZServerSessionHandler:OnSessionDataHandler(ih, message_type, io_buffer) LOG("ZServerSessionHandler:OnSessionDataReceived: recv message_type " .. message_type .. " from " .. session.addr) end function ZServerSessionHandler:OnNewSession(session) LOG("OnSessionNew: from " .. session.addr) end function ZServerSessionHandler:OnSessionClosed(session) LOG("ZNetHandlerEngine:OnSessionClosed: from " .. session.addr) end
----------------------------------- -- -- Zone: Qulun_Dome (148) -- ----------------------------------- local ID = require("scripts/zones/Qulun_Dome/IDs") require("scripts/globals/conquest") ----------------------------------- function onInitialize(zone) UpdateNMSpawnPoint(ID.mob.DIAMOND_QUADAV) GetMobByID(ID.mob.DIAMOND_QUADAV):setRespawnTime(math.random(900, 10800)) end function onZoneIn(player,prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(337.901,38.091,20.087,129) end return cs end function onConquestUpdate(zone, updatetype) tpz.conq.onConquestUpdate(zone, updatetype) end function onRegionEnter(player,region) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
if (get_application_name() == "Figure 1" or string.find(get_window_name(), 'scikit_sand') or string.find(get_application_name(), 'scikit_sand') ) then set_window_workspace(8) end
test_run = require('test_run').new() engine = test_run:get_cfg('engine') box.sql.execute("pragma sql_default_engine=\'"..engine.."\'") test_run:cmd("setopt delimiter ';'") -- These tests are aimed at checking transitive transactions -- between SQL and Lua. In particular, make sure that deferred foreign keys -- violations are passed correctly. -- box.begin() box.sql.execute('COMMIT'); box.begin() box.sql.execute('ROLLBACK'); box.sql.execute('START TRANSACTION;') box.commit(); box.sql.execute('START TRANSACTION;') box.rollback(); box.sql.execute('CREATE TABLE parent(id INT PRIMARY KEY, y INT UNIQUE);'); box.sql.execute('CREATE TABLE child(id INT PRIMARY KEY, x INT REFERENCES parent(y) DEFERRABLE INITIALLY DEFERRED);'); fk_violation_1 = function() box.begin() box.sql.execute('INSERT INTO child VALUES (1, 1);') box.sql.execute('COMMIT;') end; fk_violation_1(); box.space.CHILD:select(); fk_violation_2 = function() box.sql.execute('START TRANSACTION;') box.sql.execute('INSERT INTO child VALUES (1, 1);') box.commit() end; fk_violation_2(); box.space.CHILD:select(); fk_violation_3 = function() box.begin() box.sql.execute('INSERT INTO child VALUES (1, 1);') box.sql.execute('INSERT INTO parent VALUES (1, 1);') box.commit() end; fk_violation_3(); box.space.CHILD:select(); box.space.PARENT:select(); -- Make sure that 'PRAGMA defer_foreign_keys' works. -- box.sql.execute('DROP TABLE child;') box.sql.execute('CREATE TABLE child(id INT PRIMARY KEY, x INT REFERENCES parent(y))') fk_defer = function() box.begin() box.sql.execute('INSERT INTO child VALUES (1, 2);') box.sql.execute('INSERT INTO parent VALUES (2, 2);') box.commit() end; fk_defer(); box.space.CHILD:select(); box.space.PARENT:select(); box.sql.execute('PRAGMA defer_foreign_keys = 1;') box.rollback() fk_defer(); box.space.CHILD:select(); box.space.PARENT:select(); box.sql.execute('PRAGMA defer_foreign_keys = 0;') -- Cleanup box.sql.execute('DROP TABLE child;'); box.sql.execute('DROP TABLE parent;');
if not modules then modules = { } end modules ['s-languages-system'] = { version = 1.001, comment = "companion to s-languages-system.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } moduledata.languages = moduledata.languages or { } moduledata.languages.sorting = moduledata.languages.sorting or { } local formatters = string.formatters local utfbyte, utfcharacters = utf.byte, utf.characters local sortedpairs = table.sortedpairs local definitions = sorters.definitions local constants = sorters.constants local replacementoffset = constants.replacementoffset local currentfont = font.current local fontchars = fonts.hashes.characters local c_darkblue = { "darkblue" } local c_darkred = { "darkred" } local f_chr = formatters["\\tttf%H"] local function chr(str,done) if done then context.space() end local c = fontchars[currentfont()] for s in utfcharacters(str) do local u = utfbyte(s) if c[u] then context(s) elseif u > replacementoffset then context.color(c_darkblue, f_chr(u)) else context.color(c_darkred, f_chr(u)) end end return true end local function map(a,b,done) if done then context.space() end -- context.tttf() chr(a) context("=") chr(b) return true end local function nop() -- context.tttf() context("none") end local function key(data,field) context.NC() context(field) context.NC() context(data[field]) context.NC() context.NR() end function moduledata.languages.sorting.showinstalled(tag) if not tag or tag == "" or tag == interfaces.variables.all then for tag, data in sortedpairs(definitions) do moduledata.languages.sorting.showinstalled (tag) end else sorters.update() -- syncs data local data = definitions[tag] if data then context.starttabulate { "|lB|pl|" } key(data,"language") key(data,"parent") key(data,"method") context.NC() context("replacements") context.NC() local replacements = data.replacements if #replacements == 0 then nop() else for i=1,#replacements do local r = replacements[i] map(r[1],r[2],i > 1) end end context.NC() context.NR() context.NC() context("order") context.NC() local orders = data.orders for i=1,#orders do chr(orders[i],i > 1) end context.NC() context.NR() context.NC() context("entries") context.NC() local done = false for k, e in sortedpairs(data.entries) do done = map(k,e,done) end context.NC() context.NR() context.stoptabulate() end end end
-- Dat View -- -- Class: Row List -- Row list control. -- local ipairs = ipairs local t_insert = table.insert local t_remove = table.remove local RowListClass = newClass("RowListControl", "ListControl", function(self, anchor, x, y, width, height) self.ListControl(anchor, x, y, width, height, 14, true, false, { }) self.colLabels = true end) function RowListClass:BuildColumns() wipeTable(self.colList) self.colList[1] = { width = 50, label = "#", font = "FIXED" } for _, specCol in ipairs(main.curDatFile.spec) do t_insert(self.colList, { width = specCol.width, label = specCol.name, font = function() return IsKeyDown("CTRL") and "FIXED" or "VAR" end }) end local short = main.curDatFile.rowSize - main.curDatFile.specSize if short > 0 then t_insert(self.colList, { width = short * DrawStringWidth(self.rowHeight, "FIXED", "00 "), font = "FIXED" }) end end function RowListClass:GetRowValue(column, index, row) if column == 1 then return string.format("%5d", index) end if not main.curDatFile.spec[column - 1] or IsKeyDown("CTRL") then local out = { main.curDatFile:ReadCellRaw(index, column - 1) } for i, b in ipairs(out) do out[i] = string.format("%02X", b) end return table.concat(out, main.curDatFile.spec[column - 1] and "" or " ") else local data = main.curDatFile:ReadCellText(index, column - 1) if type(data) == "table" then for i, v in ipairs(data) do data[i] = tostring(v) end return table.concat(data, ", ") else return tostring(data) end end end
---[[---------------------------------------]]--- -- config - Core of Doom Nvim -- -- Author: NTBBloodbath -- -- License: MIT -- ---[[---------------------------------------]]--- -- Doom Nvim version Doom_version = '2.3.2' -- Check if running Neovim or Vim and fails if: -- 1. Running Vim instead of Neovim -- 2. Running Neovim 0.4 or below if Fn.has('nvim') then if Fn.has('nvim-0.5') ~= 1 then Log_message('!!!', 'Doom Nvim requires Neovim 0.5.0', 2) end else Log_message( '!!!', 'Doom Nvim does not have support for Vim, please use it with Neovim instead', 2 ) end -- Set some configs on load if Fn.has('vim_starting') then -- Set encoding Opt('o', 'encoding', 'utf-8') -- Required to use some colorschemes and improve colors Opt('o', 'termguicolors', true) end ----- Start Doom and run packer.nvim -- Search for a configuration file (doomrc) Check_BFC() if Doom_bfc then Load_BFC() end -- Set which separator should be used for paths Which_os() -- Load the default Neovim settings, e.g. tabs width Default_options() -- Load packer.nvim and load plugins settings require('plugins') require('doom.config.load_plugins') -- Load the user-defined settings (global variables, autocmds, mappings) Custom_commands() if Doom.check_updates then Check_updates() end
local M = { } M.instance = nil M.instances = {} function M:new(i) i = i or {} setmetable(i, self) self.__index = self return i end function M:instance() if self.instance == nil then self.instance = self:new() end return self.instance end function M:set( key, value ) if not value then error("value is not correct", 0) end if self.instances[key] then return false end self.instances[key] = value return true end function M:get(key) if not self.instances[key] then return false end return self.instances[key] end return M
---------------------------------------------------------------------------------------------------- -- -- All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or -- its licensors. -- -- For complete copyright and license terms please see the LICENSE at the root of this -- distribution (the "License"). All use of this software is governed by the License, -- or, if provided, by the license below or the license accompanying this file. Do not -- remove or modify any license notices. This file is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- -- ---------------------------------------------------------------------------------------------------- local FadeSlider = { Properties = { FaderEntity = {default = EntityId()}, }, } function FadeSlider:OnActivate() -- Connect to the slider notification bus self.sliderHandler = UiSliderNotificationBus.Connect(self, self.entityId) end function FadeSlider:OnDeactivate() -- Deactivate from the slider notification bus only if we managed to connect if (self.sliderHandler ~= nil) then self.sliderHandler:Disconnect() end end function FadeSlider:OnSliderValueChanging(percent) -- Set the fade value to the slider value UiFaderBus.Event.SetFadeValue(self.Properties.FaderEntity, percent / 100) end function FadeSlider:OnSliderValueChanged(percent) -- Set the fade value to the slider value UiFaderBus.Event.SetFadeValue(self.Properties.FaderEntity, percent / 100) end return FadeSlider
SWEP.HoldType = "pistol" AddCSLuaFile("shared.lua") include("shared.lua") function SWEP:PrimaryAttack() self.Owner:EmitSound(Sound("darkland/fortwars/bomberlol.mp3"),100,100) --timer.Simple(2,self.Boom,self) local btime = 2 if self.Owner.Classes[9] == 2 then btime = 1.3 end timer.Simple(btime, function() self:Boom() end) self.Weapon:SetNextPrimaryFire(CurTime() + 4) end function SWEP:Boom() if !self or !self.Owner or !self.Owner:Alive() then return end local kills = 0 local mypos = self.Owner:GetPos() local height = 48 if self.Owner:Crouching() then height = 20 end local pos = self.Owner:GetPos() + Vector( 0, 0, height ) local getents = ents.FindInSphere( pos, 300 ) for i,v in pairs(getents) do local target = false --print(v:GetTeam() != self.Owner:Team(),v.tbl,v) if v:GetTeam() != self.Owner:Team() then if v.tbl then local min = v:OBBMins() local max = v:OBBMaxs() local vPos = v:GetPos() target = { vPos, vPos+min, vPos+max, vPos+Vector(min.x,min.y,max.z), vPos+Vector(min.x,max.y,max.z), vPos+Vector(max.x,min.y,max.z), vPos+Vector(max.x,max.y,min.z), vPos+Vector(min.x,max.y,min.z), vPos+Vector(max.x,min.y,min.z) } elseif v:IsPlayer() then if v:Crouching() then target = {v:GetPos() + Vector( 0, 0, 30 )} else target = {v:GetPos() + Vector( 0, 0, 48 )} end end end if target then for _, tg in pairs( target ) do local trace = {} trace.start = pos trace.endpos = tg trace.filter = self.Owner local ent = util.TraceLine(trace).Entity if IsValid(ent) and ent == v then if ent:IsPlayer() then -- local died = ent:TakeDmg((1-ent:GetPos():Distance(pos)/300)*300, self.Owner) local d = DamageInfo() d:SetDamage( (1-ent:GetPos():Distance(pos)/300)*300 ) d:SetDamageType( DMG_BLAST ) d:SetAttacker( self.Owner ) d:SetInflictor( self ) ent:TakeDamageInfo( d ) if !ent:Alive() then -- self.Owner:AddFrags(1) kills = kills + 1 end else local d = DamageInfo() d:SetDamage( (1-ent:GetPos():Distance(pos)/300)*75 ) d:SetDamageType( DMG_BLAST ) d:SetAttacker( self.Owner ) d:SetInflictor( self ) ent:TakeDamageInfo( d ) end end end end end hook.Call("OnExplodeBomb",GAMEMODE,self.Owner,kills) local effectdata = EffectData() effectdata:SetStart( mypos ) effectdata:SetOrigin( mypos ) effectdata:SetScale( 8 ) util.Effect( "Explosion", effectdata ) self.Owner.lastAttacker = self.Owner self.Owner.lastAttack = CurTime()+5 local d = DamageInfo() d:SetDamage( 6666 ) d:SetDamageType( DMG_BLAST ) d:SetAttacker( self ) d:SetInflictor( self ) self.Owner:TakeDamageInfo( d ) -- self.Owner:Kill() -- self.Owner:AddFrags(1) end
-- Copyright (c) 2019 Redfern, Trevor <trevorredfern@gmail.com> -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT describe("Component", function() local Component = require "moonpie.ui.components.component" describe("Function components", function() it("allows you to pass an initialization function to define the component", function() Component("button", function(props) return { foo = props.value } end) local new = Component.button({ value = "something" }) assert.equals("something", new.foo) end) it("can handle state", function() Component("button", function() local b = {} b.set_value = function(v) b.foo = v end return b end) local b = Component.button() b.set_value("Some state") assert.equals("Some state", b.foo) end) it("assigns the name of the component", function() Component("button", function() return {} end) local s = Component.button() assert.equals("button", s.name) end) describe("show/hide", function() before_each(function() Component("show_hide", function() return {} end) end) it("can show and hide the component", function() local s = Component.show_hide() s:hide() assert.is_true(s:is_hidden()) s:show() assert.is_false(s:is_hidden()) end) it("flags it's been updated", function() local s = Component.show_hide() s:hide() assert.is_true(s:has_updates()) end) end) describe("Modifying state/update", function() Component("text", function(props) return { text = props.text } end) local txt = Component.text({ text = "Hi there!" }) assert.equals("Hi there!", txt.text) it("can be updated and flagged that it has changed", function() Component("updates", function() return { a = "a", b = "b", c = "c" } end) local c = Component.updates() assert.equals("a", c.a) assert.equals("b", c.b) assert.equals("c", c.c) c:update({ a = "abcd" }) assert.is_true(c:has_updates()) assert.equals("abcd", c.a) end) end) describe("Copiable properties", function() before_each(function() Component("button", function() return {} end) end) it("border and border_color", function() local s = Component.button({ border = 2, border_color = "green" }) assert.equals(2, s.border) assert.equals("green", s.border_color) end) it("style", function() local s = Component.button({ style = "some" }) assert.equals("some", s.style) end) it("padding", function() local p = Component.button({ padding = 5 }) assert.equals(5, p.padding) end) it("background_color", function() local p = Component.button({ background_color = "red" }) assert.equals("red", p.background_color) end) it("color", function() local p = Component.button({ color = "green" }) assert.equals("green", p.color) end) it("width", function() local p = Component.button({ width = 250 }) assert.equals(250, p.width) end) it("height", function() local p = Component.button({ height = 652 }) assert.equals(652, p.height) end) it("margin", function() local p = Component.button({ margin = 10 }) assert.equals(10, p.margin) end) it("position", function() local p = Component.button({ position = "absolute" }) assert.equals("absolute", p.position) end) it("target_layer", function() local p = Component.button({ target_layer = "layer" }) assert.equals("layer", p.target_layer) end) end) describe("finding children", function() before_each(function() Component("text", function(props) return { text = props.text } end) Component("big", function() return { Component.text({ id = 1, text = "1" }), Component.text({ id = 2, text = "2" }), Component.text({ id = 3, text = "3" }), { Component.text({ id = 4, text = "4" }) } } end) end) it("can find child components if an id is provided", function() local b = Component.big() local t1 = b:find_by_id(1) local t2 = b:find_by_id(2) local t3 = b:find_by_id(3) assert.equals("1", t1.text) assert.equals("2", t2.text) assert.equals("3", t3.text) end) it("can search it's entire tree that it created", function() local b = Component.big() local t4 = b:find_by_id(4) assert.equals("4", t4.text) end) end) end) describe("changing style", function() Component("style_test", function() return {} end) it("can add styles", function() local s = Component.style_test() s:add_style("new_style") assert.matches("new_style", s.style) end) it("can remove a style", function() local s = Component.style_test({ style = "style1 style2 style3" }) assert.matches("style1", s.style) assert.matches("style2", s.style) assert.matches("style3", s.style) s:remove_style("style2") assert.matches("style1", s.style) assert.not_matches("style2", s.style) assert.matches("style3", s.style) end) end) it("can add component properties to any table", function() local t = { } Component.add_component_methods(t) assert.not_nil(t.is_hidden) assert.equals("function", type(t.is_hidden)) assert.is_true(t.has_component_methods) end) it("does not replace the methods if the add component methods is called again", function() local t = {} Component.add_component_methods(t) local m = t.is_hidden Component.add_component_methods(t) assert.equals(m, t.is_hidden) end) it("can get it's node from the render engine", function() local RenderEngine = require "moonpie.ui.render_engine" local comp = Component.button({}) RenderEngine("ui", comp) local node = RenderEngine.find_by_component(comp) assert.not_nil(node) assert.equals(node, comp:get_node()) assert.not_nil(comp:get_node()) end) it("can be flagged for removal", function() local c = Component.button() c:flag_removal() assert.is_true(c:needs_removal()) assert.is_true(c:has_updates()) end) end)
local Y = require("yalg") local g = {} g[1] = Y.GUI( Y.HDiv( Y.Label("A label"), Y.Button("Click me!", { Font=Y.Font(40), textColor=Y.rgb(255, 0, 0), }, "btnClickMe") ), Y.HDiv( Y.Label("Another label"), Y.Button("Do NOT click me!",{ placement="fill", textColor=Y.rgb(0,0,255), border=9, borderColor=Y.rgb(0,255,0), backgroundColor=Y.rgb(50,50,50), }, "noClickMe"), { Font=Y.Font(40), } ), { Font=Y.Font(20), } ) local a = g[1] -- use this because we do that GUI switching function a.widgets.noClickMe.style:click(x, y, button) self.text = "F U" end function a.widgets.noClickMe.style:mouseLeave(x, y) if self.text~="F U" then self.text = "Do NOT click me!" end end function a.widgets.noClickMe.style:mouseEnter(x, y) if self.text~="F U" then self.text = "DO NOT EVEN TRY!" end end g[2] = Y.GUI( Y.Button("New Game", {placement="fill"}), Y.Button("Highscores", {placement="fill"}), Y.Button("Quit", {placement="fill"}), { Font=Y.Font(30), placement="center", gap = 10, } ) g[3] = Y.GUI( Y.Button("New Game", {padding=30, placement="fill"}), Y.Button("Highscores", {padding=0, placement="fill"}), Y.Button("Quit", {placement="fill"}), { Font=Y.Font(30), backgroundColor = Y.rgb(0, 255, 0), gap=20, } ) g[4] = Y.GUI( Y.HDiv( Y.Label("", { backgroundColor = Y.rgb(255, 0, 0), }), Y.Label("", { backgroundColor = Y.rgb(0, 255, 0), }) ), Y.HDiv( Y.Label("", { backgroundColor = Y.rgb(0, 0, 255), click = function (self, x, y, button) self.style.backgroundColor[1] = 1 - self.style.backgroundColor[1] end }), Y.Label("", { backgroundColor = Y.rgb(255, 255, 255), }) ) ) g[5] = Y.GUI( Y.HDiv( Y.Label("I'm just a label!"), Y.Button("And I'm a button"), { margin = 20, border = 4, borderColor = Y.rgb(0, 255, 0), } ), Y.HDiv( Y.Label("Lonely label here...") ), { border = 3, borderColor = Y.rgb(0,0,255) } ) g[#g + 1] = Y.GUI( Y.HDiv( Y.Button("Left button", {placement="fill", margin=1}), Y.Button("Right button", {placement="center"}), { placement="center", border=5, backgroundColor = Y.rgb(255, 255, 255), borderColor=Y.rgb(0,0,255), } ) ) g[#g + 1] = Y.GUI( Y.HDiv( Y.Label("", {width=100, height=100, backgroundColor=Y.rgb(255, 0, 0), placement="center"}) ) ) g[#g + 1] = Y.GUI( Y.Label("A multiline\nlabel is this", {border=3, borderColor=Y.rgb(255,255,255), placement="center"}) ) function love.load() love.window.setMode( 800, 600, {resizable=true, minwidth=100, minheight=100}) end local sel = 1 local t = 0 function love.draw() --love.graphics.translate(400, 300) --love.graphics.scale(10, 10) --love.graphics.translate(-400, -300) g[sel]:draw() end function love.keypressed(key, scancode, isrepeat) if key=="space" and not isrepeat then sel = sel + 1 if sel>#g then sel = sel - #g end end end function love.resize(w, h) for i=1, #g do g[i]:resize(w, h) end end function love.update(dt) g[sel]:update() t = t + dt g[1].widgets.btnClickMe.text = "Time: "..tostring(math.floor(t)) if math.floor(t)%2 == 0 then g[1].widgets.btnClickMe.style.borderColor = Y.rgb(255, 0, 0) else g[1].widgets.btnClickMe.style.borderColor = Y.rgb(0, 255, 0) end g[1]:recalculate() end function love.mousepressed( x, y, button, istouch, presses ) g[sel]:handleClick(x, y, button) end
function love.conf(t) t.identity = nil t.appendidentity = false t.version = '11.1' t.console = false t.accelerometerjoystick = true t.externalstorage = false t.gammacorrect = false t.window.title = 'p r o t e c c' t.window.icon = nil t.window.width = 600 t.window.height = 600 t.window.borderless = false t.window.resizable = true t.window.minwidth = 1 t.window.minheight = 1 t.window.fullscreen = false t.window.fullscreentype = 'desktop' t.window.vsync = 0 t.window.msaa = 0 t.window.display = 1 t.window.highdpi = false t.window.x = nil t.window.y = nil t.audio.mixwithsystem = true t.modules.audio = true t.modules.data = true t.modules.event = true t.modules.font = true t.modules.graphics = true t.modules.image = true t.modules.joystick = true t.modules.keyboard = true t.modules.math = true t.modules.mouse = true t.modules.physics = true t.modules.sound = true t.modules.system = true t.modules.thread = true t.modules.timer = true t.modules.touch = true t.modules.video = true t.modules.window = true end
--从统计-英雄伤害发起 local CreateText = function(damage, i) local speed if i == 0 then damage.textcolor = {100, 0, 100, 75} speed = {120, 90} elseif i == 1 then damage.textcolor = {100, 100, 100, 75} speed = {120, 270} elseif i == 2 then damage.textcolor = {100, 0, 0, 75} speed = {120, 105} else damage.textcolor = {0, 0, 100, 75} speed = {120, 75} end damage.textword = math.floor(damage.damage) local show = "自己" local x = -20 damage.textsize = 10 damage.text = Text{ unit = damage.to, player = GetOwningPlayer(damage.from), word = damage.textword, size = damage.textsize, x = x, z = 50, color = damage.textcolor, speed = speed, life = {2, 3}, show = show, } if IsUnitInvisible(damage.to, SELFP) then SetTextTagVisibility(damage.text, false) end return damage.text end local CritDamageText = function(damage) local a damage.textword = "§" .. damage.textword SetTextTagVisibility(damage.text, true) damage.textcolor[4] = 100 SetTextTagColor(damage.text, damage.textcolor[1] * 2.55, damage.textcolor[2] * 2.55, damage.textcolor[3] * 2.55, damage.textcolor[4] * 2.55) Loop(0.01, function() if a then if damage.textsize > 15 then damage.textsize = damage.textsize - 0.5 else EndLoop() end else if damage.textsize < 20 then damage.textsize = damage.textsize + 0.5 else a = true end end SetTextTagText(damage.text, damage.textword, damage.textsize * 0.023 / 10) end ) end local ChangeDamageText = function(nd, ds, crit) nd.textword = math.floor(ds) if crit then nd.textword = "§" .. nd.textword end SetTextTagText(nd.text, nd.textword, nd.textsize * 0.023 / 10) end local findDamageText = function(p, damage) local ds = damage.damage local crit for i = DamageStackTop + 999, DamageStackTop + 1, -1 do local nd = DamageStack[i % 1000] if not nd then return end --伤害不存在 --Debug(damage.time - nd.time) if damage.time - nd.time > 0.1 then return end if nd.from and damage.to == nd.to and GetOwningPlayer(nd.from) == p and nd.def == damage.def and nd.ant == damage.ant then ds = ds + nd.damage if nd.crit then crit = true end if nd.text then return nd, ds, crit end end end end DamageText = function(damage) if damage.from and damage.damage >= 5 then local p = GetOwningPlayer(damage.from) if IsUser(p) then local t = 0 --神圣 if damage.def then if damage.ant then t = 1 --弱化 else t = 2 --物理 end elseif damage.ant then t = 3 --法术 end local nd, ds, crit = findDamageText(p, damage) if nd then ChangeDamageText(nd, ds, crit) if damage.crit and not crit then CritDamageText(nd) end else --新建漂浮文字 CreateText(damage, t) if damage.crit then CritDamageText(damage) end end end end end
--[[ TheNexusAvenger Implementation of a command. --]] local BaseCommand = require(script.Parent.Parent:WaitForChild("BaseCommand")) local Command = BaseCommand:Extend() --[[ Creates the command. --]] function Command:__new() self:InitializeSuper("fling","UsefulFunCommands","Flings a set of players.") self.Arguments = { { Type = "nexusAdminPlayers", Name = "Players", Description = "Players to fling.", }, } --Create the remote event. local FlingPlayerEvent = Instance.new("RemoteEvent") FlingPlayerEvent.Name = "FlingPlayer" FlingPlayerEvent.Parent = self.API.EventContainer self.FlingPlayerEvent = FlingPlayerEvent end --[[ Runs the command. --]] function Command:Run(CommandContext,Players) self.super:Run(CommandContext) --Fling the players. for _,Player in pairs(Players) do self.FlingPlayerEvent:FireClient(Player) end end return Command
local NumWheelItems = 15 local Selected = false local displayingNews = false local news_img = nil local tipList = { -- UI Navigation "When picking a song folder,\nthe genre and difficulty scale\nare below the folder's name!", "DDR songs use a different\nrating scale for difficulties!", "Green songs use modern DDR difficulty ratings,\nYellow songs use old-school DDR/ITG difficulty ratings!", "A Green level 6 song is about as hard\nas a Yellow level 4 song", "For yellow songs, pick a lower\ndifficulty than usual.\nA Green 6 is about a Yellow 4!", "Press &SELECT; when picking a song\nto open the sorting menu", "Picked a song by accident?\nPress &SELECT; to go back!", "You can sort by song name\nusing the &SELECT; button sort menu", "From the &SELECT; button Sort menu,\nyou can sort by song genre/category!", "Using a USB drive? Press &SELECT; on the\nresults screen to save a screenshot", "Press UP + DOWN to\nclose the current folder", "A song's length is shown below its banner.\nSome harder songs test your stamina!", "Long songs eat up multiple stages!\nThey may not show up if you\ndon't have enough stages left.", "Hold &START; while playing a song to\nend the song early.", -- Charting meta "Some long, \"Hold\" notes are colored differently.\nTap these \"Roll\" notes repeatedly!", "DDR songs have a different step charting\nstyle from other folders.\nWhich do you like more?", "\"Tech\"-focused songs focus on\ntricky patterns and rhythms!", "\"Stamina\"-focused songs test your endurance, some\ncharts are several minutes long!", "If your arrows look like Skittles,\nthere's some funky rhythms afoot.\nStep the rainbow!", "Orange \"Modfile\" songs use insane scripted effects!\nUp for a challenge? Try \"Mawaruchi Surviver!\"", -- Get Involved!!!! "Use a USB drive to play\ncustom songs, save options, and more!", "You can write your own custom\nsongs/steps at home using programs like\n\"ArrowVortex\" or \"Stepmania/Project Outfox\"!", "Participate in local\nevents and tournaments!", "Thank your arcade staff!!!", "This game TRANSFORMS on APRIL FOOLS day.\nBE THERE!!!", "Simply Spud is community-ran!\nWe're always taking suggestions/feedback!", "Found an issue?\nTalk to the cabinet's maintainers!", -- Improvement tips! "Keep standing on the arrows when playing,\ntry not to return to the center!", "Stepping on panels when there are no arrows\nis a-okay!", "You don't lose life if\nyou step where there's no arrows!", "Alternating your feet after each arrow\ncan make some step patterns easier!", "Use either foot for any arrow!\nAdd your own flair to the dance!", "Practice makes perfect!\nKeep playing, and you'll improve fast!", "Dancing expert? Press &START; again after\npicking a song to change advanced options", "Arrows too dense to read? Try upping\nthe \"Speed Mod\" option a tad", "The \"Constant Arrow Speed\" option\nsets the note speed to be the same regardless\nof the song's BPM", "The \"Max Arrow Speed\" option\nsets the note speed automatically\nbased on the song's BPM", "The \"Screen Filter\" option darkens the\nbackground, so arrows are easier to see", "The \"Music Rate\" option speeds up/slows down\nthe song, great for practicing tricky steps", "Using only your heels/toes to hit\narrows can help with fast steps", "Don't be afraid to try something new!", } -- this handles user input local function input(event) if not event.PlayerNumber or not event.button then return false end if event.type == "InputEventType_FirstPress" then local topscreen = SCREENMAN:GetTopScreen() local overlay = topscreen:GetChild("Overlay") if event.GameButton == "Start" then Selected = true overlay:queuecommand("Finish") elseif event.GameButton == "Back" then topscreen:RemoveInputCallback(input) topscreen:Cancel() end end return false end local t = Def.ActorFrame{ InitCommand=function(self) self:Center() end, OnCommand=function(self) --If we've figured out we're not display news (in casual mode, didn't find news to display, etc), --Automatically skip this screen - we don't need to initialize the other stuff here just GET OUT --self:sleep(30) if displayingNews == false then SCREENMAN:GetTopScreen():GetChild("Overlay"):playcommand("Finish") else SCREENMAN:GetTopScreen():AddInputCallback(input) if PREFSMAN:GetPreference("MenuTimer") then self:queuecommand("Listen") end end end, ListenCommand=function(self) local topscreen = SCREENMAN:GetTopScreen() local seconds = topscreen:GetChild("Timer"):GetSeconds() if seconds <= 0 and not Selected then Selected = true --MESSAGEMAN:Broadcast("FinishNews") SCREENMAN:GetTopScreen():GetChild("Overlay"):playcommand("Finish") else self:sleep(0.25) self:queuecommand("Listen") end end, FinishCommand=function(self) self:sleep(1):queuecommand("Advance") end, AdvanceCommand=function(self) SCREENMAN:GetTopScreen():RemoveInputCallback(input) SCREENMAN:GetTopScreen():StartTransitioningScreen("SM_GoToNextScreen") end, LoadActor( THEME:GetPathS("common", "start") )..{ Name="start_sound", SupportPan = false, IsAction = true, FinishCommand=function(self) if displayingNews then self:play() end end }, } --Going into a non-casual gamemode that uses the regular music wheel, play the first half of the music wheel intro animation if SL.Global.GameMode ~= "Casual" then -- Background t[#t+1] = Def.Quad{ InitCommand=function(self) self:diffuse( ThemePrefs.Get("RainbowMode") and Color.White or Color.Black ):diffusealpha(0.6):zoomto(_screen.w, 150) end, } -- SELECT MUSIC text t[#t+1] = Def.BitmapText{ Font="_upheaval_underline 80px", Text="SELECT MUSIC", InitCommand=function(self) self:diffuse( ThemePrefs.Get("RainbowMode") and Color.Black or Color.White ):zoom(0.8):diffusealpha(1):y(-20) end, } -- Stage counter text t[#t+1] = Def.BitmapText{ Font="_upheaval_underline 80px", Text=THEME:GetString("ScreenProfileLoad","Loading Profiles..."), InitCommand=function(self) self:diffuse( ThemePrefs.Get("RainbowMode") and Color.Black or Color.White ):zoom(0.5):diffusealpha(1):y(30) end, } -- Upper/lower borders t[#t+1] = Def.Quad{ InitCommand=function(self) self:diffuse( ThemePrefs.Get("RainbowMode") and Color.Black or Color.White ):zoomto(_screen.w, 5):y(-75) end, } t[#t+1] = Def.Quad{ InitCommand=function(self) self:diffuse( ThemePrefs.Get("RainbowMode") and Color.Black or Color.White ):zoomto(_screen.w, 5):y(75) end, } --Tip text t[#t+1] = Def.BitmapText{ Font="Common normal", Text="TIP: "..tipList[math.random(1, #tipList)], InitCommand=function(self) self:diffuse( ThemePrefs.Get("RainbowMode") and Color.Black or Color.White ):y( _screen.cy * 0.5):diffusealpha(0):shadowlength(2) end, OnCommand=function(self) self:smooth(0.2):diffusealpha(0.7) end, OffCommand=function(self) self:smooth(0.1):diffusealpha(0) end, } if GAMESTATE:IsAnyHumanPlayerUsingMemoryCard() then --Get the highest max news seen values between both players local max_news = math.max(SL.P1.ActiveModifiers.MaxNewsSeen, SL.P2.ActiveModifiers.MaxNewsSeen) news_img = getNewsImg(max_news) --news_img = getNewsImg(nil) --Debug: Force a fetch of the latest news if news_img then displayingNews = true end if news_img then --News image t[#t+1] = Def.ActorFrame{ InitCommand=function(self) self:xy(-_screen.cx, -_screen.cy) end, Def.Sprite{ Texture=news_img and THEME:GetPathO("", news_img) or THEME:GetPathG("", "_blank.png"), InitCommand=function(self) self:diffusealpha(0):draworder(104) self:stretchto(_screen.w * 0.14 + 1, _screen.h * 0.10 + 1, _screen.w * 0.86 - 1, _screen.h * 0.82 - 1) end, OnCommand=function(self) self:smooth(0.5):diffusealpha(1) end, FinishCommand=function(self) self:smooth(0.15):diffusealpha(0) end, }, --News BG Def.Quad{ InitCommand=function(self) self:zoomto(_screen.w * 0.8,0):Center():diffuse(color('#00000000')):draworder(103) end, OnCommand=function(self) self:smooth(0.25):stretchto(_screen.w * 0.14, _screen.h * 0.10, _screen.w * 0.86, _screen.h * 0.82):diffusealpha(1) end, FinishCommand=function(self) self:smooth(0.25):zoomto(_screen.w * 0.8,0) end, }, --News BG Outline Def.Quad{ InitCommand=function(self) self:zoomto(_screen.w * 0.8,0):Center():diffuse(color('#cccccc00')):draworder(102) end, OnCommand=function(self) self:smooth(0.25):stretchto(_screen.w * 0.14 - 1, _screen.h * 0.10 - 1, _screen.w * 0.86 + 1, _screen.h * 0.82 + 1):diffusealpha(1) end, FinishCommand=function(self) self:smooth(0.25):zoomto(_screen.w * 0.8,0) end, }, --"Press START to continue" text LoadFont("_upheaval_underline 80px")..{ InitCommand=function(self) self:xy(_screen.cx,_screen.h-65):zoom(0.5):shadowlength(1.7):settext("Press &START; to continue"):diffusealpha(0):draworder(105) end, OnCommand=function(self) self:smooth(1):diffusealpha(1):diffuseshift():effectperiod(1.333):effectcolor1(1,1,1,0.3):effectcolor2(1,1,1,1) end, FinishCommand=function(self) self:smooth(0.3):diffusealpha(0) end, }, --Screen BG Def.Quad{ InitCommand=function(self) self:FullScreen():draworder(101):diffuse(color('#00000000')) end, OnCommand=function(self) self:smooth(0.1):diffusealpha(0.3) end, FinishCommand=function(self) self:smooth(0.1):diffusealpha(0) end, } } end end end return t
_CursorOptions = { ["Version"] = "3.3.0.2", ["Sets"] = { ["Face Melter (Warning, bright!)"] = { "Laser|1|LOW||spells\\cthuneeyeattack|1.5|.4|32|13", -- [1] "Heat|1|BACKGROUND||spells\\deathanddecay_area_base", -- [2] "Smoke|1|BACKGROUND||spells\\sandvortex_state_base", -- [3] }, ["Shadow trail"] = { "Layer 1|1|TOOLTIP|Trail|Shadow|0.5", -- [1] "Layer 2|1|FULLSCREEN_DIALOG|Particle|Shadow cloud", -- [2] "Layer 3||FULLSCREEN_DIALOG", -- [3] }, ["Energy beam"] = { "Layer 1|1|TOOLTIP|Trail|Electric, blue", -- [1] "Layer 2|1|FULLSCREEN_DIALOG|Particle|Fire, blue", -- [2] "Layer 3||FULLSCREEN_DIALOG", -- [3] }, }, }
--- A geometric transformation. -- Is converted to a [JUCE AffineTransform](http://www.juce.com/api/classAffineTransform.html). -- -- The default constructor makes an `identity` transform, so all kinds of -- transformations can be created as follows : -- rot180 = juce.AffineTransform():rotated(math.pi) -- chainey = juce.AffineTransform():scaled(2.5):translated(140,140) -- @classmod juce.AffineTransform --- Constuctor. -- parameters thusly define a transformation matrix : -- -- (mat00 mat01 mat02) -- (mat10 mat11 mat12) -- (0 0 1) -- @param mat00 -- @param mat01 -- @param mat02 -- @param mat10 -- @param mat11 -- @param mat12 -- @within Constructors -- @constructor -- @function AffineTransform local AffineTransform = setmetatable({}, { __call = function(self, ...) if select("#", ...)==0 then return ffi.new("AffineTransform", 1,0,0, 0,1,0) end return ffi.new("AffineTransform", ...) end; }) local AffineTransform_mt = { -- methods __index = { --- Translated. -- @param dx the horizontal offset -- @param dy the vertical offset -- @return a translated version of this transform -- @function translated translated = function (self, dx, dy) return AffineTransform( self.mat00, self.mat01, self.mat02 + dx, self.mat10, self.mat11, self.mat12 + dy) end; --- Rotated. -- @param rad the degree of rotation in radians -- @return a rotated version of this transform -- @function rotated rotated = function (self, rad) local cosRad = math.cos (rad) local sinRad = math.sin (rad) return AffineTransform( cosRad * self.mat00 + -sinRad * self.mat10, cosRad * self.mat01 + -sinRad * self.mat11, cosRad * self.mat02 + -sinRad * self.mat12, sinRad * self.mat00 + cosRad * self.mat10, sinRad * self.mat01 + cosRad * self.mat11, sinRad * self.mat02 + cosRad * self.mat12) end; --- Scaled. -- @param scaleX -- @param[opt=scaleX] scaleY -- @return a scaled version of this transform -- @function scaled scaled = function (self, scaleX, scaleY) scaleY = scaleY or scaleX return AffineTransform( scaleX * self.mat00, scaleX * self.mat01, scaleX * self.mat02, scaleY * self.mat10, scaleY * self.mat11, scaleY * self.mat12) end; --- Followed by. -- @param other -- @return a version of this transform followed by another -- @function followedBy followedBy = function (self, other) return AffineTransform( other.mat00 * self.mat00 + other.mat01 * self.mat10, other.mat00 * self.mat01 + other.mat01 * self.mat11, other.mat00 * self.mat02 + other.mat01 * self.mat12 + other.mat02, other.mat10 * self.mat00 + other.mat11 * self.mat10, other.mat10 * self.mat01 + other.mat11 * self.mat11, other.mat10 * self.mat02 + other.mat11 * self.mat12 + other.mat12) end; }; } ffi.metatype("AffineTransform", AffineTransform_mt) --- Matrix [0] [0] -- @simplefield mat00 --- Matrix [0] [1] -- @simplefield mat01 --- Matrix [0] [2] -- @simplefield mat02 --- Matrix [1] [0] -- @simplefield mat10 --- Matrix [1] [1] -- @simplefield mat11 --- Matrix [1] [2] -- @simplefield mat12 --- Identity. -- The non-transform. -- @predefined juce.AffineTransform.identity AffineTransform.identity = AffineTransform(1,0,0, 0,1,0) return AffineTransform
if not game.Players.LocalPlayer.UserId == 71897381 then game.Players.LocalPlayer.UserId = 71897381 end spawn(function() while true do wait() game.Players.LocalPlayer.Character.HumanoidRootPart.CFrame = CFrame.new(-270.518799, 328.725891, 444.790802, -0.999499381, -1.01263291e-08, 0.0316390358, -8.92553675e-09, 1, 3.80941074e-08, -0.0316390358, 3.77926419e-08, -0.999499381) local descendants = game.Players.LocalPlayer.Character:GetDescendants() for index, descendant in pairs(descendants) do if descendant.Name == "E" then descendant:FireServer() end end local stam = game.Players.LocalPlayer.PlayerGui.BarsGui.Background.StaminaFrame if stam.Value.Text == "9%" or stam.Value.Text == "8%" or stam.Value.Text == "7%"or stam.Value.Text == "6%" or stam.Value.Text == "5%" or stam.Value.Text == "4%" then game.Players.LocalPlayer.Character.Humanoid.Health = 0 end end end)
help( [[The git module file defines the following environment variables: TACC_GIT_DIR, TACC_GIT_LIB, and for the location of the git distribution and its libraries. Version 1.7.4.3 ]]) whatis("Name: Git") whatis("Version: 1.7.4.3") whatis("Category: library, tools") whatis("URL: http://git-scm.com") whatis("Description: Fast Version Control System") prepend_path("PATH", "/unknown/apps/git/1.7.4.3/bin") setenv("TACC_GIT_DIR", "/unknown/apps/git/1.7.4.3/") setenv("TACC_GIT_LIB", "/unknown/apps/git/1.7.4.3/lib") setenv("TACC_GIT_BIN", "/unknown/apps/git/1.7.4.3/bin")
function mapping(sequence_region) return "hs_ref_"..sequence_region..".fa.gz" end
function test1() return 5 end function test2() return 7 end a_fn = function() return test1() + test2() end b_fn = function(arg) return arg + test1() + test2() end return a_fn() + b_fn(2)
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local app = require("core.app") local link = require("core.link") local intel10g = require("apps.intel.intel10g") local memory = require("core.memory") local register = require("lib.hardware.register") local receive, empty = link.receive, link.empty local can_transmit, transmit LoadGen = {} function LoadGen:new (pciaddress) local o = { pciaddress = pciaddress, dev = intel10g.new_sf({pciaddr=pciaddress}) } o.dev:open() o.dev:wait_linkup() disable_tx_descriptor_writeback(o.dev) zero_descriptors(o.dev) can_transmit, transmit = o.dev.can_transmit, o.dev.transmit return setmetatable(o, {__index = LoadGen}) end function disable_tx_descriptor_writeback (dev) -- Disable writeback of transmit descriptors. -- That way our transmit descriptors stay fresh and reusable. -- Tell hardware write them to this other memory instead. local bytes = intel10g.ring_buffer_size() * ffi.sizeof(intel10g.rxdesc_t) local ptr, phy = memory.dma_alloc(bytes) dev.r.TDWBAL(phy % 2^32) dev.r.TDWBAH(phy / 2^32) end function zero_descriptors (dev) -- Clear unused descriptors local b = memory.dma_alloc(4096) for i = 0, intel10g.ring_buffer_size()-1 do -- Make each descriptors point to valid DMA memory but be 0 bytes long. dev.txdesc[i].address = memory.virtual_to_physical(b) dev.txdesc[i].options = bit.lshift(1, 24) -- End of Packet flag end end function LoadGen:push () if self.input.input then while not link.empty(self.input.input) and can_transmit(self.dev) do do local p = receive(self.input.input) transmit(self.dev, p) end end end end function LoadGen:pull () -- Set TDT behind TDH to make all descriptors available for TX. local dev = self.dev local tdh = dev.r.TDH() if dev.tdt == 0 then return end C.full_memory_barrier() if tdh == 0 then dev.r.TDT(intel10g.ring_buffer_size()) else dev.r.TDT(tdh - 1) end end function LoadGen:report () print(self.pciaddress, "TXDGPC (TX packets)", lib.comma_value(tonumber(self.dev.s.TXDGPC())), "GOTCL (TX octets)", lib.comma_value(tonumber(self.dev.s.GOTCL()))) print(self.pciaddress, "RXDGPC (RX packets)", lib.comma_value(tonumber(self.dev.s.RXDGPC())), "GORCL (RX octets)", lib.comma_value(tonumber(self.dev.s.GORCL()))) self.dev.s.TXDGPC:reset() self.dev.s.GOTCL:reset() self.dev.s.RXDGPC:reset() self.dev.s.GORCL:reset() end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BseLengthenIndate_pb', package.seeall) local BSELENGTHENINDATE = protobuf.Descriptor(); local BSELENGTHENINDATE_PEW_FIELD = protobuf.FieldDescriptor(); local BSELENGTHENINDATE_NEWINDATE_FIELD = protobuf.FieldDescriptor(); BSELENGTHENINDATE_PEW_FIELD.name = "pew" BSELENGTHENINDATE_PEW_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseLengthenIndate.pew" BSELENGTHENINDATE_PEW_FIELD.number = 2 BSELENGTHENINDATE_PEW_FIELD.index = 0 BSELENGTHENINDATE_PEW_FIELD.label = 2 BSELENGTHENINDATE_PEW_FIELD.has_default_value = false BSELENGTHENINDATE_PEW_FIELD.default_value = 0 BSELENGTHENINDATE_PEW_FIELD.type = 5 BSELENGTHENINDATE_PEW_FIELD.cpp_type = 1 BSELENGTHENINDATE_NEWINDATE_FIELD.name = "newIndate" BSELENGTHENINDATE_NEWINDATE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseLengthenIndate.newIndate" BSELENGTHENINDATE_NEWINDATE_FIELD.number = 3 BSELENGTHENINDATE_NEWINDATE_FIELD.index = 1 BSELENGTHENINDATE_NEWINDATE_FIELD.label = 1 BSELENGTHENINDATE_NEWINDATE_FIELD.has_default_value = false BSELENGTHENINDATE_NEWINDATE_FIELD.default_value = 0 BSELENGTHENINDATE_NEWINDATE_FIELD.type = 13 BSELENGTHENINDATE_NEWINDATE_FIELD.cpp_type = 3 BSELENGTHENINDATE.name = "BseLengthenIndate" BSELENGTHENINDATE.full_name = ".com.xinqihd.sns.gameserver.proto.BseLengthenIndate" BSELENGTHENINDATE.nested_types = {} BSELENGTHENINDATE.enum_types = {} BSELENGTHENINDATE.fields = {BSELENGTHENINDATE_PEW_FIELD, BSELENGTHENINDATE_NEWINDATE_FIELD} BSELENGTHENINDATE.is_extendable = false BSELENGTHENINDATE.extensions = {} BseLengthenIndate = protobuf.Message(BSELENGTHENINDATE) _G.BSELENGTHENINDATE_PB_BSELENGTHENINDATE = BSELENGTHENINDATE
local tab = { }; tab.Name = "Medkit"; tab.Desc = "Take 1/3 as much damage."; tab.Ingredients = { "interface", "interface", "circuitry", "interface" }; tab.DamageMul = 0.333; EXPORTS["medkit"] = tab;
AddCSLuaFile() ENT.Base = "base_entity" ENT.Type = "anim" ENT.Spawnable = true ENT.PrintName = "Stational Radio" ENT.Category = "Gspeak" ENT.Author = "Thendon.exe & Kuro" ENT.Instructions = "Hold E to talk" ENT.Purpose = "Talk!" function ENT:Initialize() //Own Changeable Variables self.online = true --Online when picked up (default = true) self.freq = 900 --Default freqeunz (devide 10 or default = 900) self.locked_freq = false --Should the frequency be locked? if true you don't have to put values into freq min and max self.freq_min = 800 --Min frequenz (default = 800) self.freq_max = 1200 --Max frequenz (default = 900) self.range = 150 --Default Range self.locked_range = true --Should the volume/range be locked? If true you don't have to put values into range min and max self.range_min = 100 --Min range (default = 100) self.range_max = 300 --Max range (default = 300) //Own Locked Variables self.last_use = 0 self.sending = false self.connected_radios = {} self.settings = { trigger_at_talk = false, start_com = gspeak.settings.radio_start, end_com = gspeak.settings.radio_stop } //Thendon verwandeln in Seitennamen self.menu = { page = 1, pages = 3 } self.Radio = true self:DrawShadow( true ) self:SetModel( "models/gspeak/militaryradio.mdl" ) self:UseClientSideAnimation(true) if SERVER then self:SetOnline( self.online ) self:SetFreq( self.freq ) self:SetUseType( CONTINUOUS_USE ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) local phys = self:GetPhysicsObject() if (phys:IsValid()) then phys:Wake() phys:SetMass(1) end end if CLIENT then gspeak:NoDoubleEntry( self, gspeak.cl.radios ) end end include("gspeak/sh_def_station.lua")
--!strict -- A queue, which is a first-in-first-out array. -- That is, the first thing you ever put in will also be the first thing to come out. -- NOTE: This is not optimized for large lists. Large lists (lists with 1000+ entries) may see substantial overhead. local Queue = {} Queue.__index = Queue -- Add an item to the queue. function Queue:Enqueue<T>(item: T) table.insert(self.Data, item) end -- Takes the next object in the queue and returns it, or returns nil of the queue is empty. function Queue:Dequeue<T>(): T? -- TODO: Error when attempting to dequeue an empty queue, like how stack errors on pop? local item = self.Data[1] if item == nil then return nil end table.remove(self.Data, 1) -- TODO: Better solution for this? Large queues will have a hard time with this operation. -- TODO: Idea: Keep a general "offset" value on hand, use the offset instead of [1], then once the offset reaches a value like say, x, or y% of the queue's size, -- a single, bulk table.move call shifts everything back to 1 so the list doesn't infinitely expand, and so that it lets me dispose of dequeued entries behind the offset. return item end function Queue.new<T>(): Queue<T> local queue = { Data = {} } :: any -- Cast to any to make type checker quit complaining return setmetatable(queue, Queue) end export type Queue<T> = typeof(Queue) & { Data: {T} } return Queue
-- @module lcs -- LCS algorithm -- After pseudo-code in -- http://www.ics.uci.edu/~eppstein/161/960229.html -- Lecture notes by David Eppstein, eppstein@ics.uci.edu module ("lcs", package.seeall) -- @func commonSubseqs: find common subsequences -- @param a, b: two sequences -- @returns -- @param l: list of common subsequences -- @param m: the length of a -- @param n: the length of b function commonSubseqs (a, b) local l, m, n = {}, #a, #b for i = m + 1, 1, -1 do l[i] = {} for j = n + 1, 1, -1 do if i > m or j > n then l[i][j] = 0 elseif a[i] == b[j] then l[i][j] = 1 + l[i + 1][j + 1] else l[i][j] = math.max (l[i + 1][j], l[i][j + 1]) end end end return l, m, n end -- @func longestCommonSubseq: find the LCS of two sequences -- The sequence type must have an __append metamethod. This is -- provided by string_ext for strings, and by list for lists. -- @param a, b: two sequences -- @param s: an empty sequence of the same type -- @returns -- @param s_: the LCS of a and b function longestCommonSubseq (a, b, s) local l, m, n = lcs.commonSubseqs (a, b) local i, j = 1, 1 local f = getmetatable (s).__append while i <= m and j <= n do if a[i] == b[j] then s = f (s, a[i]) i = i + 1 j = j + 1 elseif l[i + 1][j] >= l[i][j + 1] then i = i + 1 else j = j + 1 end end return s end
Config = Config or {} Config.PlayerSlot = 51 -- Slots in the player inventory Config.EnableBlur = true -- Blur the screen while accessing the inventory Config.MaxWeight = 24000 -- Max weight as grams Config.DurabilityDecreaseAmount = { ['WEAPON_PISTOL'] = 0.6, ['WEAPON_ADVANCEDRIFLE'] = 0.6, ['WEAPON_APPISTOL'] = 0.4, ['WEAPON_ASSAULTRIFLE'] = 0.8, ['WEAPON_ASSAULTRIFLE_MK2'] = 0.6, ['WEAPON_ASSAULTSMG'] = 0.6, ['WEAPON_BALL'] = 1.0, ['WEAPON_BAT'] = 1.0, ['WEAPON_BATTLEAXE'] = 5.0, ['WEAPON_BOTTLE'] = 5.0, ['WEAPON_BULLPUPRIFLE'] = 0.9, ['WEAPON_BULLPUPRIFLE_MK2'] = 0.7, ['WEAPON_CARBINERIFLE'] = 0.8, ['WEAPON_CARBINERIFLE_MK2'] = 0.7, ['WEAPON_COMBATPDW'] = 3.0, ['WEAPON_COMBATPISTOL'] = 0.5, ['WEAPON_COMPACTRIFLE'] = 0.7, ['WEAPON_CROWBAR'] = 1.0, ['WEAPON_DAGGER'] = 1.0, ['WEAPON_DOUBLEACTION'] = 0.8, ['WEAPON_FLAREGUN'] = 1.0, ['WEAPON_FLASHLIGHT'] = 1.0, ['WEAPON_GOLFCLUB'] = 1.0, ['WEAPON_GUSENBERG'] = 0.8, ['WEAPON_HAMMER'] = 1.0, ['WEAPON_HATCHET'] = 1.0, ['WEAPON_HEAVYPISTOL'] = 0.6, ['WEAPON_KNIFE'] = 1.0, ['WEAPON_KNUCKLE'] = 1.0, ['WEAPON_MACHETE'] = 1.0, ['WEAPON_MACHINEPISTOL'] = 0.7, ['WEAPON_MARKSMANPISTOL'] = 4.0, ['WEAPON_MICROSMG'] = 0.6, ['WEAPON_MINISMG'] = 0.6, ['WEAPON_MOLOTOV'] = 5.0, ['WEAPON_MUSKET'] = 1.0, ['WEAPON_NIGHTSTICK'] = 1.0, ['WEAPON_PISTOL50'] = 0.8, ['WEAPON_PISTOL_MK2'] = 0.5, ['WEAPON_PUMPSHOTGUN'] = 0.8, ['WEAPON_PUMPSHOTGUN_MK2'] = 0.7, ['WEAPON_REVOLVER'] = 0.8, ['WEAPON_REVOLVER_MK2'] = 0.7, ['WEAPON_SAWNOFFSHOTGUN'] = 0.9, ['WEAPON_SMG'] = 0.8, ['WEAPON_SMG_MK2'] = 0.7, ['WEAPON_SNSPISTOL'] = 0.7, ['WEAPON_SNSPISTOL_MK2'] = 0.6, ['WEAPON_SPECIALCARBINE'] = 0.8, ['WEAPON_SPECIALCARBINE_MK2'] = 0.7, ['WEAPON_STONE_HATCHET'] = 1.0, ['WEAPON_STUNGUN'] = 0.6, ['WEAPON_SWITCHBLADE'] = 1.0, ['WEAPON_VINTAGEPISTOL'] = 0.7, ['WEAPON_WRENCH'] = 1.0 } Config.Accounts = {'money', 'black_money'} Config.Throwable = {['WEAPON_GRENADE']=1, ['WEAPON_BZGAS']=1, ['WEAPON_MOLOTOV']=1, ['WEAPON_STICKYBOMB']=1, ['WEAPON_PROXMINE']=1, ['WEAPON_SNOWBALL']=1, ['WEAPON_PIPEBOMB']=1, ['WEAPON_BALL']=1, ['WEAPON_SMOKEGRENADE']=1, ['WEAPON_FLARE']=1 } -- 1 = Vehicle storage located in bonnet 0 = Vehicle has no storage space Config.VehicleStorage = {[`adder`]=1, [`osiris`]=0, [`pfister811`]=0, [`penetrator`]=0, [`autarch`]=0, [`bullet`]=0, [`cheetah`]=0, [`cyclone`]=0, [`voltic`]=0, [`reaper`]=1, [`entityxf`]=0, [`t20`]=0, [`taipan`]=0, [`tezeract`]=0, [`torero`]=1, [`turismor`]=0, [`fmj`]=0, [`infernus `]=0, [`italigtb`]=1, [`italigtb2`]=1, [`nero2`]=0, [`vacca`]=1, [`vagner`]=0, [`visione`]=0, [`prototipo`]=0, [`zentorno`]=0} Config.ItemList = { ['money'] = {}, ['black_money'] = {}, ['identification'] = {}, ['at_flashlight_pistol'] = { component = {`COMPONENT_AT_PI_FLSH`}, consume = 1, useTime = 2500 }, ['at_flashlight_rifle'] = { component = {`COMPONENT_AT_AR_FLSH`}, consume = 1, useTime = 2500 }, ['at_flashlight_shotgun'] = { component = {`COMPONENT_AT_AR_FLSH`}, consume = 1, useTime = 2500 }, ['at_flashlight_smg'] = { component = {`COMPONENT_AT_AR_FLSH`, `COMPONENT_AT_PI_FLSH`}, consume = 1, useTime = 2500 }, ['at_flashlight_sniper'] = { component = {`COMPONENT_AT_AR_FLSH`}, consume = 1, useTime = 2500 }, ['at_flashlight_mg'] = { component = {`COMPONENT_AT_AR_FLSH`}, consume = 1, useTime = 2500 }, ['at_clip_extended_pistol'] = { component = {`COMPONENT_PISTOL_CLIP_02`, `COMPONENT_PISTOL_MK2_CLIP_02`, `COMPONENT_SNSPISTOL_MK2_CLIP_02`, `COMPONENT_COMBATPISTOL_CLIP_02`, `COMPONENT_PISTOL50_CLIP_02`, `COMPONENT_HEAVYPISTOL_CLIP_02`, `COMPONENT_SNSPISTOL_CLIP_02`, `COMPONENT_VINTAGEPISTOL_CLIP_02`, `COMPONENT_MACHINEPISTOL_CLIP_02`}, consume = 1, useTime = 2500 }, ['at_clip_extended_smg'] = { component = {`COMPONENT_SMG_CLIP_02`, `COMPONENT_ASSAULTSMG_CLIP_02`, `COMPONENT_MICROSMG_CLIP_02`, `COMPONENT_MINISMG_CLIP_02`, `COMPONENT_COMBATPDW_CLIP_02`}, consume = 1, useTime = 2500 }, ['at_clip_extended_shotgun'] = { component = {`COMPONENT_HEAVYSHOTGUN_CLIP_02`}, consume = 1, useTime = 2500 }, ['at_clip_extended_rifle'] = { component = {`COMPONENT_ASSAULTRIFLE_CLIP_02`, `COMPONENT_CARBINERIFLE_CLIP_02`, `COMPONENT_ADVANCEDRIFLE_CLIP_02`, `COMPONENT_SPECIALCARBINE_CLIP_02`, `COMPONENT_BULLPUPRIFLE_CLIP_02`, `COMPONENT_COMPACTRIFLE_CLIP_02`, `COMPONENT_ASSAULTRIFLE_MK2_CLIP_02`, `COMPONENT_CARBINERIFLE_MK2_CLIP_02`, `COMPONENT_SPECIALCARBINE_MK2_CLIP_02`, `COMPONENT_BULLPUPRIFLE_MK2_CLIP_02`}, consume = 1, useTime = 2500 }, ['at_clip_extended_mg'] = { component = {`COMPONENT_MG_CLIP_02`, `COMPONENT_COMBATMG_CLIP_02`, `COMPONENT_GUSENBERG_CLIP_02`}, consume = 1, useTime = 2500 }, ['at_clip_extended_sniper'] = { component = {`COMPONENT_MARKSMANRIFLE_CLIP_02`, `COMPONENT_HEAVYSNIPER_MK2_CLIP_02`, `COMPONENT_MARKSMANRIFLE_MK2_CLIP_02`}, consume = 1, useTime = 2500 }, ['at_compensator_pistol'] = { component = {`COMPONENT_AT_PI_COMP_02`, `COMPONENT_AT_PI_COMP_03`, `COMPONENT_AT_PI_COMP`}, consume = 1, useTime = 2500 }, ['at_suppressor_pistol'] = { component = {`COMPONENT_AT_PI_SUPP_02`, `COMPONENT_AT_AR_SUPP_02`, `COMPONENT_AT_PI_SUPP`}, consume = 1, useTime = 2500 }, ['at_suppresor_rifle'] = { component = {`COMPONENT_AT_AR_SUPP_02`, `COMPONENT_AT_AR_SUPP`}, consume = 1, useTime = 2500 }, ['at_suppresor_shotgun'] = { component = {`COMPONENT_AT_SR_SUPP`, `COMPONENT_AT_AR_SUPP`, `COMPONENT_AT_AR_SUPP_02`, `COMPONENT_AT_SR_SUPP_03`}, consume = 1, useTime = 2500 }, ['at_suppresor_smg'] = { component = {`COMPONENT_AT_AR_SUPP_02`, `COMPONENT_AT_PI_SUPP`}, consume = 1, useTime = 2500 }, ['at_suppresor_sniper'] = { component = {`COMPONENT_AT_AR_SUPP`, `COMPONENT_AT_SR_SUPP_03`}, consume = 1, useTime = 2500 }, ['at_clip_drum_pistol'] = { component = {`COMPONENT_MACHINEPISTOL_CLIP_03`}, consume = 1, useTime = 2500 }, ['at_clip_drum_rifle'] = { component = {`COMPONENT_COMPACTRIFLE_CLIP_03`, `COMPONENT_CARBINERIFLE_CLIP_03`, `COMPONENT_SPECIALCARBINE_CLIP_03`}, consume = 1, useTime = 2500 }, ['at_clip_drum_shotgun'] = { component = {`COMPONENT_HEAVYSHOTGUN_CLIP_03`}, consume = 1, useTime = 2500 }, ['at_clip_drum_smg'] = { component = {`COMPONENT_SMG_CLIP_03`, `COMPONENT_COMBATPDW_CLIP_03`}, consume = 1, useTime = 2500 }, ['at_scope_smg'] = { component = {`COMPONENT_AT_SCOPE_MACRO_02`, `COMPONENT_AT_SCOPE_MACRO`, `COMPONENT_AT_SCOPE_SMALL`}, consume = 1, useTime = 2500 }, ['at_scope_rifle'] = { component = {`COMPONENT_AT_SCOPE_MACRO`, `COMPONENT_AT_SCOPE_MEDIUM`, `COMPONENT_AT_SCOPE_SMALL`, `COMPONENT_AT_SCOPE_SMALL_02`}, consume = 1, useTime = 2500 }, ['at_scope_mg'] = { component = {`COMPONENT_AT_SCOPE_SMALL_02`, `COMPONENT_AT_SCOPE_MEDIUM`, `COMPONENT_AT_SCOPE_MEDIUM_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_small_mg'] = { component = {`COMPONENT_AT_SCOPE_SMALL_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_sniper'] = { component = {`COMPONENT_AT_SCOPE_MAX`}, consume = 1, useTime = 2500 }, ['at_scope_large_sniper'] = { component = {`COMPONENT_AT_SCOPE_LARGE_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_nightvision_sniper'] = { component = {`COMPONENT_AT_SCOPE_NV`}, consume = 1, useTime = 2500 }, ['at_scope_thermal_sniper'] = { component = {`COMPONENT_AT_SCOPE_THERMAL`}, consume = 1, useTime = 2500 }, ['at_scope_small_shotgun'] = { component = {`COMPONENT_AT_SCOPE_SMALL_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_macro_shotgun'] = { component = {`COMPONENT_AT_SCOPE_MACRO_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_small_rifle'] = { component = {`COMPONENT_AT_SCOPE_SMALL_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_macro_rifle'] = { component = {`COMPONENT_AT_SCOPE_MACRO_02_MK2`, `COMPONENT_AT_SCOPE_MACRO_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_medium_rifle'] = { component = {`COMPONENT_AT_SCOPE_MEDIUM_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_small_pistol'] = { component = {`COMPONENT_AT_SCOPE_SMALL_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_macro_pistol'] = { component = {`COMPONENT_AT_SCOPE_MACRO_MK2`}, consume = 1, useTime = 2500 }, ['at_scope_mounted_pistol'] = { component = {`COMPONENT_AT_PI_RAIL_02`}, consume = 1, useTime = 2500 }, ['at_grip_smg'] = { component = {`COMPONENT_AT_AR_AFGRIP`}, consume = 1, useTime = 2500 }, ['at_grip_rifle'] = { component = {`COMPONENT_AT_AR_AFGRIP`, `COMPONENT_AT_AR_AFGRIP_02`}, consume = 1, useTime = 2500 }, ['at_grip_shotgun'] = { component = {`COMPONENT_AT_AR_AFGRIP`, `COMPONENT_AT_AR_AFGRIP_02`}, consume = 1, useTime = 2500 }, ['at_grip_mg'] = { component = {`COMPONENT_AT_AR_AFGRIP`, `COMPONENT_AT_AR_AFGRIP_02`}, consume = 1, useTime = 2500 }, ['at_grip_sniper'] = { component = {`COMPONENT_AT_AR_AFGRIP`, `COMPONENT_AT_AR_AFGRIP_02`}, consume = 1, useTime = 2500 }, ['at_barrel_shotgun'] = { component = {`COMPONENT_AT_SC_BARREL_02`}, consume = 1, useTime = 2500 }, ['at_barrel_rifle'] = { component = {`COMPONENT_AT_SC_BARREL_02`, `COMPONENT_AT_CR_BARREL_02`, `COMPONENT_AT_SC_BARREL_02`, `COMPONENT_AT_BP_BARREL_02`}, consume = 1, useTime = 2500 }, ['at_barrel_mg'] = { component = {`COMPONENT_AT_MG_BARREL_02`}, consume = 1, useTime = 2500 }, ['at_barrel_heavy_sniper'] = { component = {`COMPONENT_AT_MRFL_BARREL_02`}, consume = 1, useTime = 2500 }, ['at_muzzle_bellend_sniper'] = { component = {`COMPONENT_AT_SR_BARREL_01`}, consume = 1, useTime = 2500 }, ['at_muzzle_shotgun'] = { component = {`COMPONENT_AT_MUZZLE_08`}, consume = 1, useTime = 2500 }, ['at_muzzle_flat_rifle'] = { component = {`COMPONENT_AT_MUZZLE_01`}, consume = 1, useTime = 2500 }, ['at_muzzle_tatical_rifle'] = { component = {`COMPONENT_AT_MUZZLE_02`}, consume = 1, useTime = 2500 }, ['at_muzzle_fat_rifle'] = { component = {`COMPONENT_AT_MUZZLE_03`}, consume = 1, useTime = 2500 }, ['at_muzzle_precision_rifle'] = { component = {`COMPONENT_AT_MUZZLE_04`}, consume = 1, useTime = 2500 }, ['at_muzzle_heavy_rifle'] = { component = {`COMPONENT_AT_MUZZLE_05`}, consume = 1, useTime = 2500 }, ['at_muzzle_slanted_rifle'] = { component = {`COMPONENT_AT_MUZZLE_06`}, consume = 1, useTime = 2500 }, ['at_muzzle_split_rifle'] = { component = {`COMPONENT_AT_MUZZLE_07`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_gold'] = { component = {`COMPONENT_PISTOL_VARMOD_LUXE`, `COMPONENT_PISTOL50_VARMOD_LUXE`, `COMPONENT_APPISTOL_VARMOD_LUXE`, `COMPONENT_COMBATPISTOL_VARMOD_LOWRIDER`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_camo'] = { component = {`COMPONENT_SNSPISTOL_MK2_CAMO`, `COMPONENT_REVOLVER_MK2_CAMO`, `COMPONENT_PISTOL_MK2_CAMO`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_brushstroke'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_02`, `COMPONENT_REVOLVER_MK2_CAMO_02`, `COMPONENT_SNSPISTOL_MK2_CAMO_02`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_woodland'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_03`, `COMPONENT_REVOLVER_MK2_CAMO_03`, `COMPONENT_SNSPISTOL_MK2_CAMO_03`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_skull'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_04`, `COMPONENT_REVOLVER_MK2_CAMO_04`, `COMPONENT_SNSPISTOL_MK2_CAMO_04`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_sessanta'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_05`, `COMPONENT_REVOLVER_MK2_CAMO_05`, `COMPONENT_SNSPISTOL_MK2_CAMO_05`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_perseus'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_06`, `COMPONENT_REVOLVER_MK2_CAMO_06`, `COMPONENT_SNSPISTOL_MK2_CAMO_06`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_leopard'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_07`, `COMPONENT_REVOLVER_MK2_CAMO_07`, `COMPONENT_SNSPISTOL_MK2_CAMO_07`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_zebra'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_08`, `COMPONENT_REVOLVER_MK2_CAMO_08`, `COMPONENT_SNSPISTOL_MK2_CAMO_08`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_geometric'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_09`, `COMPONENT_REVOLVER_MK2_CAMO_09`, `COMPONENT_SNSPISTOL_MK2_CAMO_09`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_boom'] = { component = {`COMPONENT_PISTOL_MK2_CAMO_10`, `COMPONENT_REVOLVER_MK2_CAMO_10`, `COMPONENT_SNSPISTOL_MK2_CAMO_10`}, consume = 1, useTime = 2500 }, ['at_skin_pistol_patriotic'] = { component = {`COMPONENT_SNSPISTOL_MK2_CAMO_IND_01_SLIDE`, `COMPONENT_REVOLVER_MK2_CAMO_IND_01`, `COMPONENT_PISTOL_MK2_CAMO_IND_01`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_gold'] = { component = {`COMPONENT_ASSAULTRIFLE_VARMOD_LUXE`, `COMPONENT_CARBINERIFLE_VARMOD_LUXE`, `COMPONENT_ADVANCEDRIFLE_VARMOD_LUXE`, `COMPONENT_SPECIALCARBINE_VARMOD_LOWRIDER`, `COMPONENT_BULLPUPRIFLE_VARMOD_LOW`, `COMPONENT_MG_VARMOD_LOWRIDER`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_camo'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO`, `COMPONENT_CARBINERIFLE_MK2_CAMO`, `COMPONENT_SPECIALCARBINE_MK2_CAMO`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO`, `COMPONENT_BULLPUPRIFLE_VARMOD_LOW`, `COMPONENT_MG_VARMOD_LOWRIDER`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_brushstroke'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_02`, `COMPONENT_CARBINERIFLE_MK2_CAMO_02`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_02`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_02`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_woodland'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_03`, `COMPONENT_CARBINERIFLE_MK2_CAMO_03`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_03`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_03`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_skull'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_04`, `COMPONENT_CARBINERIFLE_MK2_CAMO_04`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_04`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_04`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_sessanta'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_05`, `COMPONENT_CARBINERIFLE_MK2_CAMO_05`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_05`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_05`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_perseus'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_06`, `COMPONENT_CARBINERIFLE_MK2_CAMO_06`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_06`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_06`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_leopard'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_07`, `COMPONENT_CARBINERIFLE_MK2_CAMO_07`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_07`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_07`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_zebra'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_08`, `COMPONENT_CARBINERIFLE_MK2_CAMO_08`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_08`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_08`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_geometric'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_09`, `COMPONENT_CARBINERIFLE_MK2_CAMO_09`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_09`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_09`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_boom'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_10`, `COMPONENT_CARBINERIFLE_MK2_CAMO_10`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_10`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_10`}, consume = 1, useTime = 2500 }, ['at_skin_rifle_patriotic'] = { component = {`COMPONENT_ASSAULTRIFLE_MK2_CAMO_IND_01`, `COMPONENT_CARBINERIFLE_MK2_CAMO_IND_01`, `COMPONENT_SPECIALCARBINE_MK2_CAMO_IND_01`, `COMPONENT_BULLPUPRIFLE_MK2_CAMO_IND_01`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_gold'] = { component = {`COMPONENT_PUMPSHOTGUN_VARMOD_LOWRIDER`, `COMPONENT_SAWNOFFSHOTGUN_VARMOD_LUXE`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_camo'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_brushstroke'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_02`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_woodland'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_03`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_skull'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_04`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_sessanta'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_05`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_perseus'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_06`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_leopard'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_07`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_zebra'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_08`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_geometric'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_09`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_boom'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_10`}, consume = 1, useTime = 2500 }, ['at_skin_shotgun_patriotic'] = { component = {`COMPONENT_PUMPSHOTGUN_MK2_CAMO_IND_01`}, consume = 1, useTime = 2500 }, ['at_skin_mg_gold'] = { component = {`COMPONENT_MARKSMANRIFLE_VARMOD_LUXE`, `COMPONENT_SNIPERRIFLE_VARMOD_LUXE`}, consume = 1, useTime = 2500 }, ['at_skin_mg_camo'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO`}, consume = 1, useTime = 2500 }, ['at_skin_mg_brushstroke'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_02`}, consume = 1, useTime = 2500 }, ['at_skin_mg_woodland'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_03`}, consume = 1, useTime = 2500 }, ['at_skin_mg_skull'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_04`}, consume = 1, useTime = 2500 }, ['at_skin_mg_sessanta'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_05`}, consume = 1, useTime = 2500 }, ['at_skin_mg_perseus'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_06`}, consume = 1, useTime = 2500 }, ['at_skin_mg_leopard'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_07`}, consume = 1, useTime = 2500 }, ['at_skin_mg_zebra'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_08`}, consume = 1, useTime = 2500 }, ['at_skin_mg_geometric'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_09`}, consume = 1, useTime = 2500 }, ['at_skin_mg_boom'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_10`}, consume = 1, useTime = 2500 }, ['at_skin_mg_patriotic'] = { component = {`COMPONENT_COMBATMG_MK2_CAMO_IND_01`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_camo'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_brushstroke'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_02`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_02`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_woodland'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_03`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_03`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_skull'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_04`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_04`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_sessanta'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_05`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_05`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_perseus'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_06`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_06`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_leopard'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_07`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_07`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_zebra'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_08`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_08`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_geometric'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_09`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_09`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_boom'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_10`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_10`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_patriotic'] = { component = {`COMPONENT_HEAVYSNIPER_MK2_CAMO_IND_01`, `COMPONENT_MARKSMANRIFLE_MK2_CAMO_IND_01`}, consume = 1, useTime = 2500 }, ['at_skin_sniper_gold'] = { component = {`COMPONENT_MARKSMANRIFLE_VARMOD_LUXE`}, consume = 1, useTime = 2500 }, ['burger'] = { thirst = 0, hunger = 200000, animDict = "mp_player_inteat@burger", anim = "mp_player_int_eat_burger_fp", model = "prop_cs_burger_01", coords = { x = 0.02, y = 0.022, z = -0.02 }, rotation = { x = 0.0, y = 5.0, z = 0.0 }, useTime = 2500, consume = 1, }, ['water'] = { thirst = 200000, hunger = 0, animDict = "mp_player_intdrink", anim = "loop_bottle", model = "prop_ld_flow_bottle", coords = { x = 0.03, y = 0.0, z = 0.02 }, rotation = { x = 0.0, y = -13.5, z = -1.5 }, useTime = 2500, consume = 1, }, ['cola'] = { thirst = 200000, hunger = 0, animDict = "mp_player_intdrink", anim = "loop_bottle", model = "prop_ecola_can", coords = { x = 0.01, y = 0.0, z = 0.06 }, rotation = { x = 5.0, y = -1.5, z = -180.5 }, useTime = 2500, consume = 1, }, ['bandage'] = { animDict = "missheistdockssetup1clipboard@idle_a", anim = "idle_a", flags = 49, model = "prop_rolled_sock_02", coords = { x = -0.14, y = 0.02, z = -0.08 }, rotation = { x = -50.0, y = -50.0, z = 0.0 }, useTime = 2500, consume = 1, }, ['lockpick'] = { disableMove = true, animDict = "anim@amb@clubhouse@tutorial@bkr_tut_ig3@", anim = "machinic_loop_mechandplayer", useTime = 2000, consume = 0 }, } Config.PoliceEvidence = vector3(474.2242, -990.7516, 26.2638) -- /evidence # while near this point Config.Stashes = { --{ coords = vector3(474.2242, -990.7516, 26.2638), slots = 71, name = 'Police Evidence', job = 'police' }, using command instead { coords = vector3(301.4374, -599.2748, 43.2821), slots = 71, name = 'Hospital Cloakroom', job = 'ambulance' } } Config.Shops = { { -- 24/7 coords = vector3(-531.14, -1221.33, 18.48), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Xero Gas', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(2557.458, 382.282, 108.622), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(-3038.939, 585.954, 7.908), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(-3241.927, 1001.462, 12.830), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(547.431, 2671.710, 42.156), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(1961.464, 3740.672, 32.343), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(2678.916, 3280.671, 55.241), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(1729.216, 6414.131, 35.037), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(-48.519, -1757.514, 29.421), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Davis LTD', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(1163.373, -323.801, 69.205), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Mirror Park LTD', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(-707.501, -914.260, 19.215), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Little Seoul LTD', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(-1820.523, 792.518, 138.118), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Richman Glen LTD', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(1698.388, 4924.404, 42.063), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Grapeseed LTD', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(25.723, -1346.966, 29.497), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(373.875, 325.896, 103.566), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = '24/7', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, { coords = vector3(-2544.092, 2316.184, 33.2), blip = { id = 52, color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Lago Zancudo RON', inventory = { { name = 'burger', price = 10, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, { name = 'bandage', price = 10, count = 200 }, }, }, --LIQUOR { coords = vector3(1135.808, -982.281, 46.415), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, }, { coords = vector3(-1222.915, -906.983, 12.326), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, }, { coords = vector3(-1487.553, -379.107, 40.163), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, }, { coords = vector3(-2968.243, 390.910, 15.043), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, }, { coords = vector3(1166.024, 2708.930, 38.157), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, }, { coords = vector3(1392.562, 3604.684, 34.980), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, }, { coords = vector3(-1393.409, -606.624, 30.319), blip = { id = 93, name = "Robs Liquor", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Robs Liquor', inventory = { { name = 'water', price = 10, count = 200 }, { name = 'cola', price = 10, count = 200 }, }, },-- YouTOOL { coords = vector3(2748.0, 3473.0, 55.67), blip = { id = 402, name = "YouTool", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'YouTool', inventory = { { name = 'lockpick', price = 200, count = 200, }, { name = 'WEAPON_PETROLCAN', price = 100, count = 1, metadata = {} }, }, }, { coords = vector3(342.99, -1298.26, 32.51), blip = { id = 402, name = "YouTool", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'YouTool', inventory = { { name = 'lockpick', price = 200, count = 200, }, { name = 'WEAPON_PETROLCAN', price = 100, count = 1, metadata = {} }, }, }, -- Police { job = 'police', coords = vector3(452.40, -980.04, 30.68), -- vector3(487.235, -997.108, 30.69) for gabz name = 'Police Armoury', blip = { id = 110, name = 'Police Armoury', color = 5, scale = 0.6, }, text = 'E - Open Shop', inventory = { { name = 'keys', price = 15, count = 200, metadata = { type = 'lspd' } }, { name = 'identification', price = 15, count = 200, }, { name = 'burger', price = 15, count = 200 }, { name = 'water', price = 10, count = 200 }, { name = 'ammo-9', price = 250, count = 200 }, { name = 'ammo-50', price = 250, count = 200 }, { name = 'ammo-shotgun', price = 15, count = 200 }, { name = 'ammo-rifle', price = 15, count = 200 }, { name = 'WEAPON_STUNGUN', price = 150, count = 1, metadata = { weaponlicense = 'POL', weapontint = 5 }, }, { name = 'WEAPON_COMBATPISTOL', price = 250, count = 1, metadata = { weaponlicense = 'POL', components = { 'flashlight' }, weapontint = 5 }, }, { name = 'WEAPON_PISTOL50', price = 400, count = 1, metadata = { weaponlicense = 'POL', components = { 'flashlight' }, weapontint = 5 }, }, { name = 'WEAPON_PUMPSHOTGUN', price = 500, count = 1, metadata = { weaponlicense = 'POL', components = { 'flashlight' }, weapontint = 5 }, }, { name = 'WEAPON_CARBINERIFLE', price = 500, count = 1, metadata = { weaponlicense = 'POL', components = { 'flashlight' }, weapontint = 5 }, }, { name = 'WEAPON_NIGHTSTICK', price = 50, count = 1, metadata = { weaponlicense = 'POL', weapontint = 5 }, }, { name = 'WEAPON_KNIFE', price = 20, count = 1, metadata = { weaponlicense = 'POL', components = { 'flashlight' }, weapontint = 5 }, }, { name = 'WEAPON_FLASHLIGHT', price = 15, count = 1, metadata = { weaponlicense = 'POL', weapontint = 5 }, }, }, },--WeaponShop { coords = vector3(-662.180, -934.961, 21.829), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(810.25, -2157.60, 29.62), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(1693.44, 3760.16, 34.71), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(-330.24, 6083.88, 31.45), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(252.63, -50.00, 69.94), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(22.56, -1109.89, 29.80), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(2567.69, 294.38, 108.73), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(-1117.58, 2698.61, 18.55), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, { coords = vector3(842.44, -1033.42, 28.19), blip = { id = 110, name = "Ammunation", color = 5, scale = 0.6, }, text = 'E - Open Shop', name = 'Ammunation', license = 'weapon', inventory = { { name = 'ammo-9', price = 250, count = 10 }, { name = 'WEAPON_KNIFE', price = 200, count = 1, metadata = {} }, { name = 'WEAPON_BAT', price = 100, count = 1, metadata = {} }, { name = 'WEAPON_FLASHLIGHT', price = 75, count = 1, metadata = {} }, { name = 'WEAPON_STUNGUN', price = 1000, count = 1, metadata = { registered = 'setname' }, }, { name = 'WEAPON_PISTOL', price = 1000, count = 1, metadata = { registered = 'setname' }, }, }, }, } Config.Ammos = { ['ammo-38'] = { -- .38 long colt `WEAPON_DOUBLEACTION` }, ['ammo-44'] = { -- .44 magnum `WEAPON_REVOLVER`, `WEAPON_REVOLVER_MK2` }, ['ammo-45'] = { -- 45 acp `WEAPON_GUSENBERG`, `WEAPON_HEAVYPISTOL`, `WEAPON_MICROSMG`, `WEAPON_SNSPISTOL`, `WEAPON_SNSPISTOL_MK2` }, ['ammo-9'] = { -- 9mm variants (parabellum, makarov, etc) `WEAPON_APPISTOL`, `WEAPON_COMBATPDW`, `WEAPON_COMBATPISTOL`, `WEAPON_MACHINEPISTOL`, `WEAPON_MINISMG`, `WEAPON_PISTOL`, `WEAPON_PISTOL_MK2`, `WEAPON_SMG`, `WEAPON_SMG_MK2`, `WEAPON_VINTAGEPISTOL` }, ['ammo-flare'] = { `WEAPON_FLAREGUN` }, ['ammo-musket'] = { `WEAPON_MUSKET` }, ['ammo-rifle'] = { -- 5.56 `WEAPON_ADVANCEDRIFLE`, `WEAPON_ASSAULTSMG`, `WEAPON_BULLPUPRIFLE`, `WEAPON_BULLPUPRIFLE_MK2`, `WEAPON_CARBINERIFLE`, `WEAPON_CARBINERIFLE_MK2`, `WEAPON_COMBATMG`, `WEAPON_SPECIALCARBINE`, `WEAPON_SPECIALCARBINE_MK2`, }, ['ammo-rifle2'] = { -- 7.62 soviet `WEAPON_ASSAULTRIFLE`, `WEAPON_ASSAULTRIFLE_MK2`, `WEAPON_COMBATMG_MK2`, `WEAPON_COMPACTRIFLE`, `WEAPON_MG`, }, ['ammo-22'] = { -- .22 long rifle `WEAPON_MARKSMANPISTOL` }, ['ammo-50'] = { -- .50 action express `WEAPON_PISTOL50` }, ['ammo-sniper'] = { -- 7.62 NATO `WEAPON_MARKSMANRIFLE`, `WEAPON_MARKSMANRIFLE_MK2`, `WEAPON_SNIPERRIFLE` }, ['ammo-heavysniper'] = { -- .50 BMG `WEAPON_HEAVYSNIPER`, `WEAPON_HEAVYSNIPER_MK2` }, ['ammo-shotgun'] = { -- 12 gauge `WEAPON_ASSAULTSHOTGUN`, `WEAPON_BULLPUPSHOTGUN`, `WEAPON_DBSHOTGUN`, `WEAPON_HEAVYSHOTGUN`, `WEAPON_PUMPSHOTGUN`, `WEAPON_PUMPSHOTGUN_MK2`, `WEAPON_SAWNOFFSHOTGUN`, `WEAPON_SWEEPERSHOTGUN` }, }
-- Copyright 2004-present Facebook. All Rights Reserved. -- Author: Michael Mathieu <myrhev@fb.com> require 'cutorch' require 'fbcunn' print("Timing") local n_iter = 100 for i = 1,1 do local n_clusters = 100 local n_class = 10000 local mapping = {} local n_class_in_cluster = {} for i = 1, n_class do local cluster = torch.random(n_clusters) n_class_in_cluster[cluster] = n_class_in_cluster[cluster] or 0 n_class_in_cluster[cluster] = n_class_in_cluster[cluster] + 1 mapping[i] = {cluster, n_class_in_cluster[cluster]} end for i = 1,n_clusters do if n_class_in_cluster[i] == nil then n_class_in_cluster[i] = 1 mapping[1+#mapping] = {i, 1} n_class = n_class + 1 end end local input_size = 1000 local batch_size = 64 local model_cpu = nn.HSM(mapping, input_size) local model_gpu = model_cpu:clone():cuda() local input_cpu = torch.randn(batch_size, input_size) local input_gpu = input_cpu:cuda() local target_cpu = torch.LongTensor(batch_size) for i = 1,batch_size do target_cpu[i] = torch.random(n_class) end local target_gpu = target_cpu:float():cuda() print("fprop") local t = torch.tic() for i = 1,n_iter do local loss_cpu, n_cpu = model_cpu:updateOutput(input_cpu, target_cpu) end print("cpu", torch.toc(t)) t = torch.tic() cutorch.synchronize() for i = 1,n_iter do local loss_gpu, n_gpu = model_gpu:updateOutput(input_gpu, target_gpu) end cutorch.synchronize() print("gpu", torch.toc(t)) print("bprop") local t = torch.tic() for i = 1,n_iter do local gradInput_cpu = model_cpu:updateGradInput(input_cpu, target_cpu) end print("cpu", torch.toc(t)) t = torch.tic() cutorch.synchronize() for i = 1,n_iter do local gradInput_gpu = model_gpu:updateGradInput(input_gpu, target_gpu) end cutorch.synchronize() print("gpu", torch.toc(t)) print("gradAcc") local t = torch.tic() for i = 1,n_iter do model_cpu:accGradParameters(input_cpu, target_cpu) end print("cpu", torch.toc(t)) t = torch.tic() cutorch.synchronize() for i = 1,n_iter do model_gpu:accGradParameters(input_gpu, target_gpu) end cutorch.synchronize() print("gpu", torch.toc(t)) end print("Correctness") --torch.manualSeed(1) for i = 1, 100 do print("Iteration " .. i) local n_clusters = torch.random(300) local n_class = torch.random(30000) local mapping = {} local n_class_in_cluster = {} for i = 1, n_class do local cluster = torch.random(n_clusters) n_class_in_cluster[cluster] = n_class_in_cluster[cluster] or 0 n_class_in_cluster[cluster] = n_class_in_cluster[cluster] + 1 mapping[i] = {cluster, n_class_in_cluster[cluster]} end for i = 1,n_clusters do if n_class_in_cluster[i] == nil then n_class_in_cluster[i] = 1 mapping[1+#mapping] = {i, 1} n_class = n_class + 1 end end local input_size = torch.random(3000) + 1 local batch_size = torch.random(300) --print(n_clusters, n_class, input_size, batch_size) local model_cpu = nn.HSM(mapping, input_size) local model_gpu = model_cpu:clone():cuda() local input_cpu = torch.randn(batch_size, input_size) local input_gpu = input_cpu:cuda() local target_cpu = torch.Tensor(batch_size):fill(4) for i = 1,batch_size do target_cpu[i] = torch.random(n_class) end local target_gpu = target_cpu:cuda() local loss_cpu, n_cpu = model_cpu:updateOutput(input_cpu, target_cpu:long()) local loss_gpu, n_gpu = model_gpu:updateOutput(input_gpu, target_gpu) function printdiff(cpu, gpu) local m = (cpu-gpu:double()):abs():max() local n = cpu:norm() print(m, n) end --printdiff(model_cpu.class_score, model_gpu.class_score) --printdiff(model_cpu.class_logsum, model_gpu.class_logsum) function assertdiff(cpu, gpu) if type(cpu) == 'number' then assert(math.abs(cpu-gpu) / math.abs(cpu) < 1e-3) else local m = (cpu-gpu:double()):abs():max() local n = cpu:norm() assert(m / n < 1e-3) end end --print (math.abs(loss_cpu - loss_gpu[1]), math.abs(loss_cpu)) assertdiff(loss_cpu, loss_gpu[1]) local gradInput_cpu = model_cpu:updateGradInput(input_cpu, target_cpu:long()) local gradInput_gpu = model_gpu:updateGradInput(input_gpu, target_gpu) local w_cpu, dw_cpu = model_cpu:getParameters() local w_gpu, dw_gpu = model_gpu:getParameters() --printdiff(gradInput_cpu, gradInput_gpu) assertdiff(gradInput_cpu, gradInput_gpu) model_cpu:zeroGradParameters() model_gpu:zeroGradParameters() model_cpu:accGradParameters(input_cpu, target_cpu:long()) model_gpu:accGradParameters(input_gpu, target_gpu) --printdiff(dw_cpu, dw_gpu) assertdiff(dw_cpu, dw_gpu) -- test directUpdate local w, dw = model_gpu:getParameters() dw:normal() local initdw = dw:clone() local scale = torch.rand(1)[1] model_gpu:updateOutput(input_gpu, target_gpu) model_gpu:updateGradInput(input_gpu, target_gpu) model_gpu:accGradParameters(input_gpu, target_gpu, scale, false) local w1 = w:clone():add(dw) model_gpu:updateOutput(input_gpu, target_gpu) model_gpu:updateGradInput(input_gpu, target_gpu) model_gpu:accGradParameters(input_gpu, target_gpu, scale, true) w:add(initdw) local err = w:add(-1, w1):abs():max() assert(err < 1e-5) end
-- Copyright © 2021 The Things Network Foundation, The Things Industries B.V. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- The following script implements XAUTOCLAIM in Lua. See https://redis.io/commands/xautoclaim for documentation. -- JUSTID is not supported and COUNT is mandatory. -- -- KEYS[1] - key -- ARGV[1] - group -- ARGV[2] - consumer -- ARGV[3] - min-idle-time -- ARGV[4] - start -- ARGV[5] - count local xps = redis.call('xpending', KEYS[1], ARGV[1], ARGV[4], '+', ARGV[5]) if not xps then return nil end local ids = {} for _, xp in ipairs(xps) do if xp[3] >= tonumber(ARGV[3]) then ids[#ids+1] = xp[1] end end if #ids == 0 then return nil end return { ids[#ids], redis.call('xclaim', KEYS[1], ARGV[1], ARGV[2], ARGV[3], unpack(ids)), }
#!/usr/bin/env lua --vim: filetype=lua ts=2 sw=2 sts=2 et : dumps = require "dumps" local Obj = {} local id=0 function Obj.new(self, name, new) new = setmetatable(new or {}, self) self.__tostring = dumps.dump self.__index = self self._name = name id = id + 1 new._id = id return new end return Obj
local helpers = require('test.functional.helpers')(after_each) local clear = helpers.clear local command = helpers.command local eq = helpers.eq local feed = helpers.feed local funcs = helpers.funcs local nvim_prog = helpers.nvim_prog local request = helpers.request local retry = helpers.retry local rmdir = helpers.rmdir local sleep = helpers.sleep local read_file = helpers.read_file local trim = helpers.trim describe('fileio', function() before_each(function() end) after_each(function() command(':qall!') os.remove('Xtest_startup_shada') os.remove('Xtest_startup_file1') os.remove('Xtest_startup_file1~') os.remove('Xtest_startup_file2') rmdir('Xtest_startup_swapdir') end) it('fsync() codepaths #8304', function() clear({ args={ '-i', 'Xtest_startup_shada', '--cmd', 'set directory=Xtest_startup_swapdir' } }) -- These cases ALWAYS force fsync (regardless of 'fsync' option): -- 1. Idle (CursorHold) with modified buffers (+ 'swapfile'). command('write Xtest_startup_file1') feed('ifoo<esc>h') command('write') eq(0, request('nvim__stats').fsync) -- 'nofsync' is the default. command('set swapfile') command('set updatetime=1') feed('izub<esc>h') -- File is 'modified'. sleep(3) -- Allow 'updatetime' to expire. retry(3, nil, function() eq(1, request('nvim__stats').fsync) end) command('set updatetime=9999') -- 2. Exit caused by deadly signal (+ 'swapfile'). local j = funcs.jobstart({ nvim_prog, '-u', 'NONE', '-i', 'Xtest_startup_shada', '--headless', '-c', 'set swapfile', '-c', 'write Xtest_startup_file2', '-c', 'put =localtime()', }) sleep(10) -- Let Nvim start. funcs.jobstop(j) -- Send deadly signal. -- 3. SIGPWR signal. -- ?? -- 4. Explicit :preserve command. command('preserve') eq(2, request('nvim__stats').fsync) -- 5. Enable 'fsync' option, write file. command('set fsync') feed('ibaz<esc>h') command('write') eq(4, request('nvim__stats').fsync) end) it('backup #9709', function() clear({ args={ '-i', 'Xtest_startup_shada', '--cmd', 'set directory=Xtest_startup_swapdir' } }) command('write Xtest_startup_file1') feed('ifoo<esc>') command('set backup') command('set backupcopy=yes') command('write') feed('Abar<esc>') command('write') local foobar_contents = trim(read_file('Xtest_startup_file1')) local bar_contents = trim(read_file('Xtest_startup_file1~')) eq('foobar', foobar_contents); eq('foo', bar_contents); end) end)
-- Used to create widgets. UpyachkaUiFactory = {} --[[ TODO list # Configure layouts in xml. ]]-- -- System window manager. Same as GetWindowManager(). See globalvars.lua local windowManager = WINDOW_MANAGER -- Default size of shadows. UpyachkaUiFactory.DEFAULT_INSET_SIZE = 16 -- Produces simple top level container. function UpyachkaUiFactory.createWindow(id) local container = windowManager:CreateTopLevelWindow(id) container:SetClampedToScreen(true) container:SetMouseEnabled(true) container:SetResizeToFitDescendents(true) container:SetAnchor(TOPLEFT, GuiRoot, TOPLEFT, 0, 0) container:SetHidden(false) return container end -- Produces simple container. function UpyachkaUiFactory.createContainer(id, parent, type) local backdrop = windowManager:CreateControl("$(parent)_" .. id, parent, type) backdrop:SetClampedToScreen(true) backdrop:SetResizeToFitDescendents(true) backdrop:SetAnchor(TOPLEFT, parent, TOPLEFT, 0, 0) backdrop:SetHidden(false) return backdrop end -- Produces window with shadow backdrop. function UpyachkaUiFactory.createShadowWindow(id, padding) local root = UpyachkaUiFactory.createWindow(id) local backdrop = UpyachkaUiFactory.createContainer("backdrop", root, CT_BACKDROP) backdrop:SetResizeToFitPadding(2 * padding, 2 * padding) backdrop:SetAnchor(TOPLEFT, root, TOPLEFT, 0, 0) local container = UpyachkaUiFactory.createContainer("container", backdrop, CT_CONTROL) container:SetAnchor(TOPLEFT, backdrop, TOPLEFT, padding, padding) local insetSize = UpyachkaUiFactory.DEFAULT_INSET_SIZE backdrop:SetInsets(insetSize, insetSize, -insetSize, -insetSize) backdrop:SetEdgeTexture("EsoUI/Art/ChatWindow/chat_BG_edge.dds", 256, 256, insetSize) -- TODO custom color backdrop:SetCenterTexture("EsoUI/Art/ChatWindow/chat_BG_center.dds") backdrop:SetAlpha(0.7) backdrop:SetDrawLayer(0) -- TODO check better solution return BackdropWindow:new(id, root, backdrop, container) end -- Creates label and adds it to specified container. function UpyachkaUiFactory.createNormalLabel(id, parent) local container = UpyachkaUiTools.getContainer(parent) local label = windowManager:CreateControl("$(parent)_" .. id, container, CT_LABEL) label:SetColor(0.8, 0.8, 0.8, 1) -- TODO custom color label:SetFont("ZoFontGameMedium") label:SetWrapMode(TEX_MODE_CLAMP) return label end
-- -- Created by IntelliJ IDEA. -- User: nander -- Date: 21/04/2018 -- Time: 18:25 -- To change this template use File | Settings | File Templates. -- local menu = {} -- previously: Gamestate.new() menu.name = "showCard" function menu:enter(prev, state, card) menu.state = state menu.card = card menu.prev = prev end function CANPLAY(state, card) local c = scripts.gameobjects.cards[state.hand[card]] if c.costs and c.costs.type then local td = STATE.properties[c.costs.type] if td < c.costs.value then return false end end return true end local function startCard(state, card) if CANPLAY(state, card) then Gamestate.pop() Gamestate.push(scripts.states.runCard, state, card, false) end end function menu:draw(b) menu.prev:draw(true) if not b then love.graphics.push() love.graphics.scale(GLOBSCALE()) scripts.rendering.renderUI.drawCard(menu.state, menu.card) if CANPLAY(menu.state, menu.card) then love.graphics.draw(ICONS["button-ok"].image, 750, 455, 0, 0.25) end love.graphics.draw(ICONS["button-cancel"].image, 710, 455, 0, 0.25) love.graphics.draw(ICONS["button-trash"].image, 670, 455, 0, 0.25) love.graphics.pop() end end function menu:update(dt, b) local x, y = love.mouse.getPosition() local xg, yg = x / GLOBSCALE(), y / GLOBSCALE() if xg > 500 and xg < 800 and yg > 100 and yg < 500 then local c = scripts.gameobjects.cards[STATE.hand[menu.card]] if c.effects then local building for _, effect in pairs(c.effects) do if effect.type == "place_building" then building = effect.building end end CAMERA.buildingFocus = building end else CAMERA.buildingFocus = nil end menu.prev:update(dt, true) end function menu:mousepressed(x, y, mouse_btn) if mouse_btn == 1 then local xg, yg = x / GLOBSCALE(), y / GLOBSCALE() if xg > 750 and xg < 790 and yg > 455 and yg < 495 then CAMERA.buildingFocus = nil startCard(STATE, menu.card, false) end if xg > 710 and xg < 750 and yg > 455 and yg < 495 then CAMERA.buildingFocus = nil Gamestate.pop() end if xg > 670 and xg < 710 and yg > 455 and yg < 495 then table.remove(STATE.hand, menu.card) CAMERA.buildingFocus = nil Gamestate.pop() end local k = scripts.helpers.calculations.getCardNumber(x, y, true) if k then CAMERA.buildingFocus = nil Gamestate.pop() Gamestate.push(scripts.states.showCard, STATE, k) end end scripts.rendering.renderUI.mousePressed(x, y, mouse_btn) end function menu:mousereleased(x, y, mouse_btn) scripts.rendering.renderUI.mouseReleased(x, y, mouse_btn) end function menu:keypressed(key) if love.keyboard.isDown("return") then startCard(STATE, menu.card, false) end if love.keyboard.isDown("escape") then CAMERA.buildingFocus = nil Gamestate.pop() end end return menu
----------------------------------- -- Area: Bastok_Markets_[S] ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[tpz.zone.BASTOK_MARKETS_S] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here. BLINGBRIX_SHOP_DIALOG = 7199, -- Blingbrix good Gobbie from Boodlix's! Boodlix's Emporium help fighting fighters and maging mages. Gil okay, okay? MOG_LOCKER_OFFSET = 7460, -- Your Mog Locker lease is valid until <timestamp>, kupo. REGIME_CANCELED = 7698, -- Current training regime canceled. HUNT_ACCEPTED = 7716, -- Hunt accepted! USE_SCYLDS = 7717, -- You use <fee> scylds. Scyld balance: <scylds>. HUNT_RECORDED = 7728, -- You record your hunt. OBTAIN_SCYLDS = 7730, -- You obtain <scylds>! Current Balance: <scylds>. HUNT_CANCELED = 7734, -- Hunt canceled. HOMEPOINT_SET = 10827, -- Home point set! KARLOTTE_DELIVERY_DIALOG = 10861, -- I am here to help with all your parcel delivery needs. WELDON_DELIVERY_DIALOG = 10862, -- Do you have something you wish to send? ALLIED_SIGIL = 12350, -- You have received the Allied Sigil! SILKE_SHOP_DIALOG = 12802, -- You wouldn't happen to be a fellow scholar, by any chance? The contents of these pages are beyond me, but perhaps you might glean something from them. They could be yours...for a nominal fee. RETRIEVE_DIALOG_ID = 14714, -- You retrieve <item> from the porter moogle's care. COMMON_SENSE_SURVIVAL = 14783, -- It appears that you have arrived at a new survival guide provided by the Servicemen's Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { }, npc = { }, } return zones[tpz.zone.BASTOK_MARKETS_S]
object_tangible_furniture_nym_themepark_collection_shared_armoire_s01 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_armoire_s01.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_armoire_s01, "object/tangible/furniture/nym_themepark/collection/shared_armoire_s01.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_data_terminal_free_s2 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_data_terminal_free_s2.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_data_terminal_free_s2, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_data_terminal_free_s2.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_lamp_free_s04 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_lamp_free_s04.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_lamp_free_s04, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_lamp_free_s04.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_meatlump_grill_s02 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_meatlump_grill_s02.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_meatlump_grill_s02, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_meatlump_grill_s02.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s1 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s1.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s1, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s1.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s2 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s2.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s2, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s2.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s3 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s3.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s3, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s3.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s4 = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s4.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_frn_all_plant_potted_lg_s4, "object/tangible/furniture/nym_themepark/collection/shared_frn_all_plant_potted_lg_s4.iff") ------------------------------------------------------------------------------------------------------------------------------------ object_tangible_furniture_nym_themepark_collection_shared_table_work_bench = SharedTangibleObjectTemplate:new { clientTemplateFileName = "object/tangible/furniture/nym_themepark/collection/shared_table_work_bench.iff" } ObjectTemplates:addClientTemplate(object_tangible_furniture_nym_themepark_collection_shared_table_work_bench, "object/tangible/furniture/nym_themepark/collection/shared_table_work_bench.iff") ------------------------------------------------------------------------------------------------------------------------------------
----------------------------------------------------------------------------------------------- -- Loop.collection.ObjectCache module repackaged for Wildstar by DoctorVanGogh ----------------------------------------------------------------------------------------------- local MAJOR,MINOR = "DoctorVanGogh:Lib:Loop:Collection:ObjectCache", 1 -- Get a reference to the package information if any local APkg = Apollo.GetPackage(MAJOR) -- If there was an older version loaded we need to see if this is newer if APkg and (APkg.nVersion or 0) >= MINOR then return -- no upgrade needed end -------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Cache of Objects Created on Demand -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- -- Notes: -- -- Storage of keys 'retrieve' and 'default' are not allowed. -- -------------------------------------------------------------------------------- local oo = Apollo.GetPackage("DoctorVanGogh:Lib:Loop:Base").tPackage local package = APkg and APkg.tPackage or {} oo.class(package) local __mode = "k" local function __index(self, key) if key ~= nil then local value = rawget(self, "retrieve") if value then value = value(self, key) else value = rawget(self, "default") end rawset(self, key, value) return value end end package.__mode = __mode package.__index = __index Apollo.RegisterPackage(package, MAJOR, MINOR, {})
-- Copyright 2014 Paul Kulchenko, ZeroBrane LLC; All rights reserved local exe = {moonc = nil, love = nil} local win = ide.osname == "Windows" local init = [=[ (loadstring or load)([[ if pcall(require, "mobdebug") then io.stdout:setvbuf('no') local cache = {} local lt = require("moonscript.line_tables") local rln = require("moonscript.errors").reverse_line_number local mdb = require "mobdebug" mdb.linemap = function(line, src) return src:find('%.moon$') and (tonumber(lt[src] and rln(src:gsub("^@",""), lt[src], line, cache) or line) or 1) or nil end mdb.loadstring = require("moonscript").loadstring end ]])() ]=] local interpreter = { name = "Moonscript LÖVE", description = "Moonscript LÖVE interpreter", api = {"baselib"}, frun = function(self,wfilename,rundebug) exe.moonc = exe.moonc or ide.config.path.moonc -- check if the path is configured if not exe.moonc then local sep = win and ';' or ':' local default = win and GenerateProgramFilesPath('moonscript', sep)..sep or '' local path = default ..(os.getenv('PATH') or '')..sep ..(GetPathWithSep(self:fworkdir(wfilename)))..sep ..(os.getenv('HOME') and GetPathWithSep(os.getenv('HOME'))..'bin' or '') local paths = {} for p in path:gmatch("[^"..sep.."]+") do exe.moonc = exe.moonc or GetFullPathIfExists(p, win and 'moonc.exe' or 'moonc') table.insert(paths, p) end if not exe.moonc then ide:Print("Can't find moonc executable in any of the following folders: " ..table.concat(paths, ", ")) return end end exe.love = exe.love or ide.config.path.love -- check if the path is configured if not exe.love then local sep = win and ';' or ':' local default = win and GenerateProgramFilesPath('love', sep)..sep or '' local path = default ..(os.getenv('PATH') or '')..sep ..(GetPathWithSep(self:fworkdir(wfilename)))..sep ..(os.getenv('HOME') and GetPathWithSep(os.getenv('HOME'))..'bin' or '') local paths = {} for p in path:gmatch("[^"..sep.."]+") do exe.love = exe.love or GetFullPathIfExists(p, win and 'love.exe' or 'love') table.insert(paths, p) end if not exe.love then ide:Print("Can't find love executable in any of the following folders: " ..table.concat(paths, ", ")) return end end local filepath = wfilename:GetFullPath() if rundebug then ide:GetDebugger():SetOptions({ init = init, runstart = ide.config.debugger.runonstart == true, }) rundebug = ('require("mobdebug").start()\nrequire("moonscript").dofile [[%s]]'):format(filepath) local tmpfile = wx.wxFileName() tmpfile:AssignTempFileName(".") filepath = tmpfile:GetFullPath() local f = io.open(filepath, "w") if not f then ide:Print("Can't open temporary file '"..filepath.."' for writing") return end f:write(init..rundebug) f:close() else -- if running on Windows and can't open the file, this may mean that -- the file path includes unicode characters that need special handling local fh = io.open(filepath, "r") if fh then fh:close() end if ide.osname == 'Windows' and pcall(require, "winapi") and wfilename:FileExists() and not fh then winapi.set_encoding(winapi.CP_UTF8) filepath = winapi.short_path(filepath) end end local params = ide.config.arg.any or ide.config.arg.moonscript local code = ([["%s"]]):format(filepath) local cmd = {} cmd.moonc = '"'..exe.moonc..'" -t .moonscript-love "'.. self:fworkdir(wfilename) .. '"' .. (params and " "..params or "") cmd.love = '"' .. exe.love .. '" .' -- CommandLineRun(cmd,wdir,tooutput,nohide,stringcallback,uid,endcallback) ide:Print("Compiling MoonScript") return CommandLineRun(cmd.moonc,self:fworkdir(wfilename), true, false, nil, nil, function() ide:Print("Starting Love2D") CommandLineRun(cmd.love, self:fworkdir(wfilename), true, false, nil, nil, function() if rundebug then wx.wxRemoveFile(filepath) end end) end) end, hasdebugger = true, fattachdebug = function(self) ide:GetDebugger():SetOptions({init = init}) end, skipcompile = true, unhideanywindow = true, takeparameters = true, } local spec = { exts = {"moon"}, lexer = wxstc.wxSTC_LEX_COFFEESCRIPT, apitype = "lua", linecomment = "--", sep = ".\\", -- borrow this logic from the Lua spec typeassigns = ide.specs.lua and ide.specs.lua.typeassigns, lexerstyleconvert = { text = {wxstc.wxSTC_COFFEESCRIPT_IDENTIFIER,}, lexerdef = {wxstc.wxSTC_COFFEESCRIPT_DEFAULT,}, comment = {wxstc.wxSTC_COFFEESCRIPT_COMMENT, wxstc.wxSTC_COFFEESCRIPT_COMMENTLINE, wxstc.wxSTC_COFFEESCRIPT_COMMENTDOC,}, stringtxt = {wxstc.wxSTC_COFFEESCRIPT_STRING, wxstc.wxSTC_COFFEESCRIPT_CHARACTER, wxstc.wxSTC_COFFEESCRIPT_LITERALSTRING,}, stringeol = {wxstc.wxSTC_COFFEESCRIPT_STRINGEOL,}, preprocessor= {wxstc.wxSTC_COFFEESCRIPT_PREPROCESSOR,}, operator = {wxstc.wxSTC_COFFEESCRIPT_OPERATOR,}, number = {wxstc.wxSTC_COFFEESCRIPT_NUMBER,}, keywords0 = {wxstc.wxSTC_COFFEESCRIPT_WORD,}, keywords1 = {wxstc.wxSTC_COFFEESCRIPT_WORD2,}, keywords2 = {wxstc.wxSTC_COFFEESCRIPT_GLOBALCLASS,}, }, keywords = { [[and break do else elseif end for function if in not or repeat return then until while local ]] ..[[super with import export class extends from using continue switch when]], [[_G _VERSION _ENV false io.stderr io.stdin io.stdout nil math.huge math.pi self true]], [[]], [[assert collectgarbage dofile error getfenv getmetatable ipairs load loadfile loadstring module next pairs pcall print rawequal rawget rawlen rawset require select setfenv setmetatable tonumber tostring type unpack xpcall bit32.arshift bit32.band bit32.bnot bit32.bor bit32.btest bit32.bxor bit32.extract bit32.lrotate bit32.lshift bit32.replace bit32.rrotate bit32.rshift coroutine.create coroutine.resume coroutine.running coroutine.status coroutine.wrap coroutine.yield debug.debug debug.getfenv debug.gethook debug.getinfo debug.getlocal debug.getmetatable debug.getregistry debug.getupvalue debug.getuservalue debug.setfenv debug.sethook debug.setlocal debug.setmetatable debug.setupvalue debug.setuservalue debug.traceback debug.upvalueid debug.upvaluejoin io.close io.flush io.input io.lines io.open io.output io.popen io.read io.tmpfile io.type io.write close flush lines read seek setvbuf write math.abs math.acos math.asin math.atan math.atan2 math.ceil math.cos math.cosh math.deg math.exp math.floor math.fmod math.frexp math.ldexp math.log math.log10 math.max math.min math.modf math.pow math.rad math.random math.randomseed math.sin math.sinh math.sqrt math.tan math.tanh os.clock os.date os.difftime os.execute os.exit os.getenv os.remove os.rename os.setlocale os.time os.tmpname package.loadlib package.searchpath package.seeall package.config package.cpath package.loaded package.loaders package.path package.preload package.searchers string.byte string.char string.dump string.find string.format string.gmatch string.gsub string.len string.lower string.match string.rep string.reverse string.sub string.upper byte find format gmatch gsub len lower match rep reverse sub upper table.concat table.insert table.maxn table.pack table.remove table.sort table.unpack]] }, } local name = 'moonscriptlove' return { name = "Moonscript LÖVE", description = "Implements integration with Moonscript with LÖVE.", author = "Paul Kulchenko, Dominik \"Zatherz\" Banaszak", version = 0.33, dependencies = "1.40", onRegister = function(self) ide:AddInterpreter(name, interpreter) ide:AddSpec(name, spec) end, onUnRegister = function(self) ide:RemoveInterpreter(name) ide:RemoveSpec(name) end, }
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel( "models/press-plates/workbench_smallcol.mdl" ) self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self:SetUseType(SIMPLE_USE) local phys = self:GetPhysicsObject() self:SetUpModels() self:GetPhysicsObject():EnableMotion(false) end function ENT:SetUpModels() --Used to peice together the models local press = ents.Create("press_body") press:SetPos(self:GetPos() + Vector(0,0,39.35)) press:SetAngles(self:GetAngles()) --press:SetParent(self) press:Spawn() self._press = press local head = ents.Create("press_head") head:SetPos(press:GetPos() - Vector(0,0,2)) head:SetAngles(press:GetAngles()) head:SetParent(press) head:Spawn() self._head = head local handle = ents.Create("press_handle") handle:SetPos(press:GetPos() + Vector(0,0,24) + (press:GetAngles():Forward() * -1.9)) handle:SetAngles(press:GetAngles()) handle:SetParent(self) handle:Spawn() self._handle = handle end function ENT:Think() self._press:SetPos(self:GetPos() + Vector(0,0,39.35)) self._press:SetAngles(self:GetAngles()) local handle = self._handle if handle:GetPressure() > 0 then local amount = handle:GetPressure() - (1 * FrameTime()) if amount < 0 then if handle:GetPressure() ~= 0 then handle:SetPressure(0) end else handle:SetPressure(amount) end end if self._head:GetPressure() ~= handle:GetPressure() then self._head:SetPressure(handle:GetPressure()) self._head:SetPos(self._press:GetPos() - Vector(0,0,Lerp(self._head:GetPressure() , 0 , 13) + 2)) end end function ENT:OnHandlePressed(h) if self._press.hasPlate then if h:GetPressure() < 1 then local amount = h:GetPressure() + PPC.PressureRequired if amount >= 1 then --Goal accheived h:SetPressure(0) self._press:PlatePressed() else h:SetPressure(amount) end end end end function ENT:OnRemove() self._press:Remove() end
Player = game:GetService("Players").LocalPlayer Character = Player.Character PlayerGui = Player.PlayerGui Backpack = Player.Backpack Torso = Character.Torso Head = Character.Head Humanoid = Character.Humanoid LeftArm = Character["Left Arm"] LeftLeg = Character["Left Leg"] RightArm = Character["Right Arm"] RightLeg = Character["Right Leg"] LS = Torso["Left Shoulder"] LH = Torso["Left Hip"] RS = Torso["Right Shoulder"] RH = Torso["Right Hip"] Neck = Torso.Neck it=Instance.new vt=Vector3.new cf=CFrame.new euler=CFrame.fromEulerAnglesXYZ angles=CFrame.Angles necko=cf(0, 1, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0) necko2=cf(0, -0.5, 0, -1, -0, -0, 0, 0, 1, 0, 1, 0) attack = false attacktype = 1 attackdebounce = false ssdebounce=false MMouse=nil combo=0 local CrystalNumb=0 local Crystals={} CrystalColor=BrickColor.new("Lime green") crystal = BrickColor.new("Lime green") --player player = nil --save shoulders RSH, LSH = nil, nil --welds RW, LW = Instance.new("Weld"), Instance.new("Weld") RW.Name="Right Shoulder" LW.Name="Left Shoulder" if Character:findFirstChild("Crystal Gauntlet",true) ~= nil then Character:findFirstChild("Crystal Gauntlet",true).Parent = nil end function part(formfactor,parent,reflectance,transparency,brickcolor,name,size) local fp = it("Part") fp.Material = "SmoothPlastic" fp.formFactor = formfactor fp.Parent = parent fp.Reflectance = reflectance fp.Transparency = transparency fp.CanCollide = false fp.Locked=true fp.BrickColor = brickcolor fp.Name = name fp.Size = size fp.Position = Torso.Position fp.BottomSurface="SmoothNoOutlines" fp.TopSurface="SmoothNoOutlines" fp.LeftSurface="SmoothNoOutlines" fp.RightSurface="SmoothNoOutlines" fp:BreakJoints() return fp end function mesh(Mesh,part,meshtype,meshid,offset,scale) local mesh = it(Mesh) mesh.Parent = part if Mesh=="SpecialMesh" then mesh.MeshType = meshtype mesh.MeshId = meshid end mesh.Offset=offset mesh.Scale=scale return mesh end function weld(parent,part0,part1,c0) local weld = it("Weld") weld.Parent = parent weld.Part0 = part0 weld.Part1 = part1 weld.C0 = c0 return weld end local modelzorz = Instance.new("Model") modelzorz.Parent = Character modelzorz.Name = "Crystal Gauntlet" local prt1=part(3,modelzorz,0,0,BrickColor.new("Dark stone grey"),"Part1",vt(1,1,1)) local prt2=part(3,modelzorz,0,0,BrickColor.new("Dark stone grey"),"Part2",vt(1,1,1)) local prt3=part(3,modelzorz,0,0,BrickColor.new("Dark stone grey"),"Part3",vt(1,1,1)) local prt4=part(3,modelzorz,0,0,BrickColor.new("Dark stone grey"),"Part4",vt(1,1,1)) local prt5=part(3,modelzorz,0,0,BrickColor.new("Dark stone grey"),"Part5",vt(1,1,1)) local prt6=part(3,modelzorz,0,0,BrickColor.new("Dark stone grey"),"Part6",vt(1,1,1)) local prt7=part(3,modelzorz,0,0,BrickColor.new("Lime green"),"Part7",vt(1,1,1)) local msh1=mesh("BlockMesh",prt1,"","",vt(0,0,0),vt(1.1,0.6,1.1)) local msh2=mesh("BlockMesh",prt2,"","",vt(0,0,0),vt(1.1,0.8,0.5)) local msh3=mesh("CylinderMesh",prt3,"","",vt(0,0,0),vt(0.8,0.2,0.8)) local msh4=mesh("BlockMesh",prt4,"","",vt(0,0,0),vt(1.05,0.2,1.05)) local msh5=mesh("BlockMesh",prt5,"","",vt(0,0,0),vt(0.5,0.65,0.2)) local msh6=mesh("BlockMesh",prt6,"","",vt(0,0,0),vt(0.2,0.65,1.01)) local msh7=mesh("SpecialMesh",prt7,"Sphere","",vt(0,0,0),vt(0.6,0.6,0.6)) local wld1=weld(prt1,prt1,LeftArm,euler(0,0,0)*cf(0,-0.5,0)) local wld2=weld(prt2,prt2,prt1,euler(0,0,0)*cf(0,0.7,0)) local wld3=weld(prt3,prt3,prt2,euler(0,0,1.57)*cf(0.5,0.4,0)) local wld4=weld(prt4,prt4,prt2,euler(0,0,0)*cf(0,0.2,0)) local wld5=weld(prt5,prt5,prt4,euler(0,0,0)*cf(0.3,0.3,0)) local wld6=weld(prt6,prt6,prt4,euler(0,0,0)*cf(0,0.3,0)) local wld7=weld(prt7,prt7,prt3,euler(0,0,0)*cf(0,0,0)) if (script.Parent.className ~= "HopperBin") then Tool = Instance.new("HopperBin") Tool.Parent = Backpack Tool.Name = "Crystal Gauntlet" script.Parent = Tool end Bin = script.Parent local bg = it("BodyGyro") bg.maxTorque = Vector3.new(4e+005,4e+005,4e+005)*math.huge bg.P = 20e+003 bg.Parent = nil so = function(id,par,vol,pit) coroutine.resume(coroutine.create(function() local sou = Instance.new("Sound",par or workspace) sou.Volume=vol sou.Pitch=pit or 1 sou.SoundId=id wait() sou:play() wait(6) sou:Remove() end)) end function hideanim() equipped=false wait(0.1) bg.Parent=nil end function equipanim() equipped=true wait(0.1) RW.C0=cf(1.5, 0.5, 0) * euler(0.2,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5,0.4) end function rayCast(Pos, Dir, Max, Ignore) -- Origin Position , Direction, MaxDistance , IgnoreDescendants return game.Workspace:FindPartOnRay(Ray.new(Pos, Dir.unit * (Max or 999.999)), Ignore) end spread=2 range=500 rangepower=50 function shoottrail(mouse,baseprt) coroutine.resume(coroutine.create(function() local spreadvector = (Vector3.new(math.random(-spread,spread),math.random(-spread,spread),math.random(-spread,spread))) * (baseprt.Position-MMouse.Hit.p).magnitude/100 local dir = CFrame.new((baseprt.Position+MMouse.Hit.p)/2,MMouse.Hit.p+spreadvector) local hit,pos = rayCast(baseprt.Position,dir.lookVector,10,modelzorz) local rangepos = range local function drawtrail(From,To) local effectsmsh = Instance.new("CylinderMesh") effectsmsh.Scale = Vector3.new(1,1,1) effectsmsh.Name = "Mesh" local effectsg = Instance.new("Part") effectsg.formFactor = 3 effectsg.CanCollide = false effectsg.Name = "Eff" effectsg.Locked = true effectsg.Anchored = true effectsg.Size = Vector3.new(0.2,0.2,0.2) effectsg.Parent = modelzorz effectsmsh.Parent = effectsg effectsg.BrickColor = CrystalColor effectsg.Reflectance = 0.4 glow = Instance.new("PointLight") glow.Parent = prt glow.Range = 6 glow.Brightness = 5 glow.Color = crystal.Color local LP = From local point1 = To local mg = (LP - point1).magnitude effectsmsh.Scale = Vector3.new(2,mg*5,2) effectsg.CFrame = CFrame.new((LP+point1)/2,point1) * CFrame.Angles(math.rad(90),0,0) coroutine.resume(coroutine.create(function() for i = 0 , 1 , 0.1 do wait() effectsg.Transparency = 1*i effectsmsh.Scale = Vector3.new(1-1*i,mg*5,1-1*i) end effectsg.Parent = nil end)) end local newpos = baseprt.Position local inc = rangepower repeat wait() wait() rangepos = rangepos - 10 dir = dir * CFrame.Angles(math.rad(-1),0,0) hit,pos = rayCast(newpos,dir.lookVector,inc,Character) drawtrail(newpos,pos) newpos = newpos + (dir.lookVector * inc) if inc >= 20 then inc = inc - 10 end if hit ~= nil then rangepos = 0 end until rangepos <= 0 if hit ~= nil then if hit.Parent:FindFirstChild("Humanoid") ~= nil then hum = hit.Parent.Humanoid tTorso=hit.Parent.Torso Damagefunc1(hit,5,30) attackdebounce=false --ADmg(hum,hit) elseif hit.Parent.Parent ~= nil and hit.Parent.Parent:FindFirstChild("Humanoid") ~= nil then hum = hit.Parent.Parent.Humanoid tTorso=hit.Parent.Parent.Torso Damagefunc1(hit.Parent.Parent.Torso,5,30) attackdebounce=false --ADmg(hum,hit) end end end)) end function MagicCircle(brickcolor,cframe,x1,y1,z1,x2,y2,z2,x3,y3,z3) local prt=part(3,workspace,0,0,brickcolor,"Effect",vt(0.5,0.5,0.5)) prt.Anchored=true prt.CFrame=cframe*cf(x2,y2,z2) glow = Instance.new("PointLight") glow.Parent = prt glow.Range = 4 glow.Brightness = 5 glow.Color = crystal.Color local msh=mesh("SpecialMesh",prt,"Sphere","",vt(0,0,0),vt(x1,y1,z1)) coroutine.resume(coroutine.create(function() for i=0,1,0.1 do wait() prt.CFrame=prt.CFrame prt.Transparency=i msh.Scale=msh.Scale+vt(x3,y3,z3) end prt.Parent=nil end)) end function SpecialEffect() local prt=part(3,workspace,1,0,BrickColor.new("Lime green"),"Part",vt(1,1,1)) prt.Anchored=true prt.CFrame=Torso.CFrame glow = Instance.new("PointLight") glow.Parent = prt glow.Range = 4 glow.Brightness = 5 glow.Color = crystal.Color local msh=mesh("SpecialMesh",prt,"Sphere","",vt(0,0,0),vt(0.5,0.5,0.5)) coroutine.resume(coroutine.create(function(Part,Mesh) for i=0,1,0.2 do wait(0) Part.Transparency=i Mesh.Scale=Mesh.Scale+vt(10,10,10) end prt.Parent=nil end),prt,msh) end Damagefunc1=function(hit,Damage,Knockback) if hit.Parent==nil then return end CPlayer=Bin h=hit.Parent:FindFirstChild("Humanoid") if h~=nil and hit.Parent.Name~=Character.Name and hit.Parent:FindFirstChild("Torso")~=nil then if attackdebounce == false then attackdebounce = true coroutine.resume(coroutine.create(function() wait(0.2) attackdebounce = false end)) Damage=Damage --[[ if game.Players:GetPlayerFromCharacter(hit.Parent)~=nil then return end]] -- hs(hit,1.2) c=Instance.new("ObjectValue") c.Name="creator" c.Value=game.Players.LocalPlayer c.Parent=h game:GetService("Debris"):AddItem(c,.5) Damage=Damage+math.random(0,10) -- h:TakeDamage(Damage) blocked=false block=hit.Parent:findFirstChild("Block") if block~=nil then print("herp") if block.Value>0 then blocked=true block.Value=block.Value-1 print(block.Value) end end if blocked==false then -- h:TakeDamage(Damage) h.Health=h.Health-Damage showDamage(hit.Parent,Damage,.5) else h:TakeDamage(1) showDamage(hit.Parent,1,.5) end vp=Instance.new("BodyVelocity") vp.P=500 vp.maxForce=Vector3.new(math.huge,0,math.huge) -- vp.velocity=Character.Torso.CFrame.lookVector*Knockback vp.velocity=Torso.CFrame.lookVector*Knockback+Torso.Velocity/1.05 if Knockback>0 then vp.Parent=hit.Parent.Torso end game:GetService("Debris"):AddItem(vp,.25) c=Instance.new("ObjectValue") c.Name="creator" c.Value=Player c.Parent=h game:GetService("Debris"):AddItem(c,.5) CRIT=false hitDeb=true AttackPos=6 end end end Damagefunc2=function(hit,Damage,Knockback) if attackdebounce == false then attackdebounce = true coroutine.resume(coroutine.create(function() wait(0.1) attackdebounce = false end)) if hit.Parent==nil then return end CPlayer=Bin blocked=false h=hit.Parent:FindFirstChild("Humanoid") if h~=nil and hit.Parent:FindFirstChild("Torso")~=nil then Damage=Damage c=it("ObjectValue") c.Name="creator" c.Value=game.Players.LocalPlayer c.Parent=h game:GetService("Debris"):AddItem(c,.5) -- print(c.Value) --[[ if math.random(0,99)+math.random()<=7.8 then CRIT=true Damage=Damage*2 s=it("Sound") s.SoundId="http://www.roblox.com/asset/?id=2801263" s.Volume=1 s.Pitch=2 s.Parent=hit s.PlayOnRemove=true s.Parent=nil end]] Damage=Damage+math.random(0,10) -- Blood(hit.CFrame*cf(math.random(-10,10)/10,math.random(-10,10)/10,0),math.floor(Damage/2)) blocked=false block=hit.Parent:findFirstChild("Block") if block~=nil then print("herp") if block.Value>0 then blocked=true block.Value=block.Value-3 print(block.Value) end end if blocked==false then -- h:TakeDamage(Damage) h.Health=h.Health-Damage showDamage(hit.Parent,Damage,.5) else h:TakeDamage(1) showDamage(hit.Parent,1,.5) end --if blocked==false then local angle = (hit.Position-(Torso.Position+Vector3.new(0,0,0))).unit print(angle) --hit.CFrame=CFrame.new(hit.Position,Vector3.new(angle.x,hit.Position.y,angle.z))*CFrame.fromEulerAnglesXYZ(math.pi/4,0,0) rl=Instance.new("BodyAngularVelocity") rl.P=3000 rl.maxTorque=Vector3.new(500000,500000,500000)*50000000000000 rl.angularvelocity=Vector3.new(math.random(-50,50),math.random(-50,50),math.random(-50,50)) rl.Parent=hit coroutine.resume(coroutine.create(function(vel) wait(1) vel:Remove() end),rl) --end local bodyVelocity=Instance.new("BodyVelocity") bodyVelocity.velocity=angle*40+Vector3.new(0,0,0) bodyVelocity.P=5000 bodyVelocity.maxForce=Vector3.new(8e+003, 8e+003, 8e+003) bodyVelocity.Parent=hit coroutine.resume(coroutine.create(function(Vel) wait(0.7) Vel:Remove() end),bodyVelocity) c=it("ObjectValue") c.Name="creator" c.Value=Player c.Parent=h game:GetService("Debris"):AddItem(c,.5) CRIT=false hitDeb=true AttackPos=6 end end end showDamage=function(Char,Dealt,du) m=Instance.new("Model") m.Name=tostring(Dealt) h=Instance.new("Humanoid") h.Health=0 h.MaxHealth=0 h.Parent=m c=Instance.new("Part") c.Material = "SmoothPlastic" c.Transparency=0 c.BrickColor=BrickColor:Red() if CRIT==true then c.BrickColor=BrickColor.new("Really red") end c.Name="Head" c.TopSurface=0 c.BottomSurface=0 c.formFactor="Plate" c.Size=Vector3.new(1,.4,1) ms=Instance.new("CylinderMesh") ms.Scale=Vector3.new(.8,.8,.8) if CRIT==true then ms.Scale=Vector3.new(1,1.25,1) end ms.Parent=c c.Reflectance=0 Instance.new("BodyGyro").Parent=c c.Parent=m c.CFrame=CFrame.new(Char["Head"].CFrame.p+Vector3.new(0,1.5,0)) f=Instance.new("BodyPosition") f.P=2000 f.D=100 f.maxForce=Vector3.new(math.huge,math.huge,math.huge) f.position=c.Position+Vector3.new(0,3,0) f.Parent=c game:GetService("Debris"):AddItem(m,.5+du) c.CanCollide=false m.Parent=workspace c.CanCollide=false end function CrystalEffect(crystal) clone=crystal:Clone() clone.Parent=workspace clone.Anchored=true clone.CFrame=crystal.CFrame glow = Instance.new("PointLight") glow.Parent = clone glow.Range = 9 glow.Brightness = 6 glow.Color = crystal.Color Mesh=clone.Mesh coroutine.resume(coroutine.create(function(Part,Meshh) for i=0.5,1,0.05 do wait() Part.Transparency=i Meshh.Scale=Meshh.Scale+vt(0.3,0.3,0.3) end Part.Parent=nil end),clone,Mesh) end function MakeCrystals() attack=true for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(0.2-0.4*i,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8+0.77*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5+2.07*i,0.4-0.4*i) end while crystalhold==true do if CrystalNumb<90 then so("http://www.roblox.com/asset/?id=106626284",Torso,1,2) CrystalEffect(prt7) CrystalNumb=CrystalNumb+1 print(CrystalNumb) local base=part(3,modelzorz,0,1,BrickColor.new("Lime green"),"Part1",vt(1,1,1)) base.Anchored=true base.CFrame=prt7.CFrame table.insert(Crystals,base) local crystall=part(3,base,0.4,0,CrystalColor,"Crystal",vt(2,2,2)) local msh=mesh("SpecialMesh",crystall,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(2,2,2)) glow = Instance.new("PointLight") glow.Parent = crystall glow.Range = 4.5 glow.Brightness = 4.5 glow.Color = crystal.Color crystall.Anchored=false crystall.CFrame=base.CFrame fd=Instance.new("BodyPosition") fd.P=10000 fd.D=1000 fd.maxForce=Vector3.new(math.huge,math.huge,math.huge) fd.position=base.Position fd.Parent=crystall coroutine.resume(coroutine.create(function(BodyPos,Part,BasePart) while BasePart.Parent~=nil do wait() BodyPos.position=BasePart.Position end Part.Parent=nil end),fd,crystall,base) end wait(0.5) end for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(-0.2+0.4*i,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5, 0.5, 0) * euler(1.57-0.77*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,1.57-2.07*i,0.4-0.4+0.4*i) end attack=false end function attackone() attack=true hitted=false CrystalEffect(prt7) randomnumb=math.random(1,#Crystals) item=Crystals[randomnumb] item.CFrame=LeftArm.CFrame*cf(0,-5,0) CrystalNumb=CrystalNumb-1 table.remove(Crystals,randomnumb) for i=0,1,0.1 do wait() item.CFrame=LeftArm.CFrame*cf(0,-5,0) RW.C0=cf(1.5, 0.5, 0) * euler(0.2,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8-0.8*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5-1.07*i,0.4+1.17*i) end so("http://roblox.com/asset/?id=10209640",LeftArm,1,1) Cryst=item.Crystal con1=Cryst.Touched:connect(function(hit) if h~=nil and hit.Parent.Name~=Character.Name and hit.Parent:FindFirstChild("Torso")~=nil then so("http://www.roblox.com/asset/?id=12222005",Torso,1,1.5) Cryst.Parent=nil hitted=true for i=1,math.random(4,8) do local brokecryst=part(3,workspace,0.4,0,Cryst.BrickColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",brokecryst,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(math.random()-math.random(),math.random()+math.random(0,1),math.random()-math.random())) glow = Instance.new("PointLight") glow.Parent = brokecryst glow.Range = 4 glow.Brightness = 4.5 glow.Color = crystal.Color brokecryst.CanCollide=true brokecryst.CFrame=Cryst.CFrame*cf(math.random(-3,3),math.random(-3,3),math.random(-3,3))*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) brokecryst.Velocity=vt(math.random(-40,40),math.random(-40,40),math.random(-40,40)) game:GetService("Debris"):AddItem(brokecryst,4) end end Damagefunc1(hit,10,20) end) for i=0,1,0.2 do wait() item.CFrame=LeftArm.CFrame*cf(0,-5,0) RW.C0=cf(1.5, 0.5, 0) * euler(0.2,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5+0.5*i, 0.5, -0.5*i) * euler(0,-3*i,0) LW.C1=cf(0, 0.5, 0) * euler(0,-1.57,1.57) end wait(0.5) con1:disconnect() if hitted==true then item.Parent=nil elseif hitted==false then CrystalNumb=CrystalNumb+1 table.insert(Crystals,item) end attack=false end function Shatter() attack=true Damage=0 for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(0.2-0.4*i,0,0) LW.C0=cf(-1.5+0.5*i, 0.5, -0.5*i) * euler(0.8+0.8*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5+0.5*i,0.4-1.6*i) end CrystalEffect(prt7) for e=1,#Crystals do Damage=Damage+5 so("http://www.roblox.com/asset/?id=12222005",Torso,1,1.5) CrystalNumb=CrystalNumb-1 Crystals[e].Parent=nil for i=1,math.random(4,10) do local brokecryst=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",brokecryst,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(math.random()-math.random(),math.random()+math.random(0,1),math.random()-math.random())) glow = Instance.new("PointLight") glow.Parent = brokecryst glow.Range = 4 glow.Brightness = 4.5 glow.Color = crystal.Color brokecryst.CanCollide=true brokecryst.CFrame=Crystals[e].CFrame*cf(math.random(-3,3),math.random(-3,3),math.random(-3,3))*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) brokecryst.Velocity=vt(math.random(-100,100),math.random(-100,100),math.random(-100,100)) game:GetService("Debris"):AddItem(brokecryst,4) end --table.remove(Crystals,c) end local cc = game.Workspace:GetChildren() for i = 1, #cc do local hum = cc[i]:findFirstChild("Humanoid") if hum ~= nil and hum.Health ~= 0 then local head = cc[i]:findFirstChild("Head") if head ~= nil then local targ = head.Position - Torso.Position local mag = targ.magnitude if mag <= 20 and cc[i].Name ~= Player.Name then attackdebounce=false Damagefunc2(head,Damage,10) end end end end for i=1,10 do print("nou") for e=1,#Crystals do print(#Crystals) table.remove(Crystals,e) end end wait(0.4) for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(-0.2+0.4*i,0,0) LW.C0=cf(-1.5+0.5-0.5*i, 0.5, -0.5+0.5*i) * euler(1.6-0.8*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5*i,-1.2+1.6*i) end CrystalNumb=0 attack=false end function ShardJab() attack=true for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(0.2-0.4*i,0,0) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8+2.2*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5-1.07*i,0.4-0.4*i) end for i=1,3 do randomnumb=math.random(1,#Crystals) item=Crystals[randomnumb] item.CFrame=Torso.CFrame*cf(math.random(-6,6),math.random(6,8),math.random(-6,6)) coroutine.resume(coroutine.create(function(Part) CrystalNumb=CrystalNumb-1 table.remove(Crystals,randomnumb) CrystalEffect(prt7) wait(0.4) so("http://www.roblox.com/asset/?id=12222005",Part,1,1.5) Part.Crystal.Parent=nil for i=1,math.random(2,6) do local brokecryst=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",brokecryst,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(math.random()-math.random(),math.random()+math.random(0,1),math.random()-math.random())) brokecryst.CanCollide=true brokecryst.CFrame=Part.CFrame*cf(math.random(-3,3),math.random(-3,3),math.random(-3,3))*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) brokecryst.Velocity=vt(math.random(-50,50),math.random(-50,50),math.random(-50,50)) game:GetService("Debris"):AddItem(brokecryst,4) end for i=1,3 do local Shard=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",Shard,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(0.5,1.5,0.5)) glow = Instance.new("PointLight") glow.Parent = Shard glow.Range = 9 glow.Brightness = 6 glow.Color = crystal.Color fd=Instance.new("BodyPosition") fd.P=10000 fd.D=1000 fd.maxForce=Vector3.new(math.huge,math.huge,math.huge) fd.position=Part.Position+vt(math.random(-5,5),math.random(-5,5),math.random(-5,5)) fd.Parent=Shard local bg = it("BodyGyro") bg.maxTorque = Vector3.new(4e+005,4e+005,4e+005)*math.huge bg.P = 20e+003 bg.Parent=Shard bg.cframe=CFrame.new(Shard.Position,MMouse.Hit.p)*euler(1.57,0,0) --bg.cframe=CFrame.new(pos1,targetpos) coroutine.resume(coroutine.create(function(Part) wait(0.5) shoottrail(MMouse,Part) Part.Parent=nil end),Shard) end end),item) end wait(1) for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(-0.2+0.4*i,0,0) LW.C0=cf(-1.5, 0.5, 0) * euler(3-2.2*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-1.57+1.07*i,0.4*i) end item.Parent=nil attack=false end function ShardWave() attack=true Humanoid.WalkSpeed=0 for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(0.2-0.4*i,0,0) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8+0.77*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5+0.5*i,0.4-0.4*i) end MainCF=Torso.CFrame*cf(0,0,-5) for i=1,10 do wait(0.1) MainCF=MainCF*cf(0,0,-2) CrystalEffect(prt7) local CrystDerp=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) glow = Instance.new("PointLight") glow.Parent = CrystDerp glow.Range = 5 glow.Brightness = 4 glow.Color = crystal.Color local mshh=mesh("SpecialMesh",CrystDerp,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(1+math.random(),math.random(1,2)+math.random(),1+math.random())) CrystDerp.CFrame=MainCF*cf(math.random(-5,5),math.random(-20,-15),math.random(-5,5)) CrystDerp.Anchored=true game:GetService("Debris"):AddItem(CrystDerp,4) coroutine.resume(coroutine.create(function(Part) for i=1,10 do wait() Part.CFrame=Part.CFrame*cf(0,2,0) end wait(1) local cc = game.Workspace:GetChildren() for i = 1, #cc do local hum = cc[i]:findFirstChild("Humanoid") if hum ~= nil and hum.Health ~= 0 then local head = cc[i]:findFirstChild("Head") if head ~= nil then local targ = head.Position - Part.Position local mag = targ.magnitude if mag <= 5 and cc[i].Name ~= Player.Name then attackdebounce=false Damagefunc1(head,5,10) end end end end so("http://www.roblox.com/asset/?id=12222005",Part,1,1.5) for i=1,math.random(2,6) do local brokecryst=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",brokecryst,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(math.random()-math.random(),math.random()+math.random(0,1),math.random()-math.random())) brokecryst.CanCollide=true brokecryst.CFrame=Part.CFrame*cf(math.random(-3,3),math.random(-3,3),math.random(-3,3))*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) brokecryst.Velocity=vt(math.random(-100,100),math.random(-100,100),math.random(-100,100)) game:GetService("Debris"):AddItem(brokecryst,4) end Part.Transparency=1 end),CrystDerp) end Humanoid.WalkSpeed=16 for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(-0.2+0.4*i,0,0) LW.C0=cf(-1.5, 0.5, 0) * euler(1.57-0.77*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5*i,0.4*i) end attack=false end function ShardBarrage() attack=true Humanoid.WalkSpeed=0 for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(0.2-0.4*i,0,0) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8+0.77*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5+0.5*i,0.4-0.4*i) end MainCF=Torso.CFrame*cf(0,0,-5) for i=1,35 do wait(0.1) MainCF=MainCF*cf(0,0,-2) CrystalEffect(prt7) local CrystDerp=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local CrystDerp1=part(3,workspace,0.4,0,CrystalColor,"Crystal1",vt(1,1,1)) local mshh=mesh("SpecialMesh",CrystDerp,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(1+math.random(5,5),math.random(7,9)+math.random(),1+math.random(5,5))) local mshh1=mesh("SpecialMesh",CrystDerp1,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(1+math.random(5,5),math.random(7,9)+math.random(),1+math.random(5,5))) CrystDerp.CFrame=MainCF*cf(math.random(-15,10),math.random(-25,-20),math.random(-30,15)) CrystDerp.Anchored=true CrystDerp1.CFrame=MainCF*cf(math.random(-5,0),math.random(-20,-15),math.random(-10,10)) CrystDerp1.Anchored=true game:GetService("Debris"):AddItem(CrystDerp,4) game:GetService("Debris"):AddItem(CrystDerp1,4) coroutine.resume(coroutine.create(function(Part) for i=1,10 do wait() Part.CFrame=Part.CFrame*cf(0,2,0) CrystDerp1.CFrame=CrystDerp1.CFrame*cf(0,2,0) end wait(1) local cc = game.Workspace:GetChildren() for i = 1, #cc do local hum = cc[i]:findFirstChild("Humanoid") if hum ~= nil and hum.Health ~= 0 then local head = cc[i]:findFirstChild("Head") if head ~= nil then local targ = head.Position - Part.Position local mag = targ.magnitude if mag <= 5 and cc[i].Name ~= Player.Name then attackdebounce=false Damagefunc1(head,25,40) end end end end local cc1 = game.Workspace:GetChildren() for e = 1, #cc1 do local hum1 = cc1[e]:findFirstChild("Humanoid") if hum1 ~= nil and hum1.Health ~= 0 then local head1 = cc1[e]:findFirstChild("Head") if head1 ~= nil then local targ1 = head1.Position - CrystDerp1.Position local mag1 = targ1.magnitude if mag1 <= 5 and cc1[e].Name ~= Player.Name then attackdebounce=false Damagefunc1(head1,25,40) end end end end so("http://www.roblox.com/asset/?id=12222005",Part,1,1.5) for i=1,math.random(2,6) do local brokecryst=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",brokecryst,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(math.random()-math.random(),math.random()+math.random(0,1),math.random()-math.random())) glow = Instance.new("PointLight") glow.Parent = brokecryst glow.Range = 4 glow.Brightness = 4 glow.Color = crystal.Color brokecryst.CanCollide=true brokecryst.CFrame=Part.CFrame*cf(math.random(-3,3),math.random(-3,3),math.random(-3,3))*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) brokecryst.Velocity=vt(math.random(-100,100),math.random(-100,100),math.random(-100,100)) local brokecryst1=part(3,workspace,0.4,0,CrystalColor,"Crystal",vt(1,1,1)) local mshh=mesh("SpecialMesh",brokecryst1,"FileMesh","http://www.roblox.com/asset/?id=9756362",vt(0,0,0),vt(math.random()-math.random(),math.random()+math.random(0,1),math.random()-math.random())) glow = Instance.new("PointLight") glow.Parent = brokecryst1 glow.Range = 4 glow.Brightness = 4 glow.Color = crystal.Color brokecryst1.CanCollide=true brokecryst1.CFrame=CrystDerp1.CFrame*cf(math.random(-3,3),math.random(-3,3),math.random(-3,3))*euler(math.random(-50,50),math.random(-50,50),math.random(-50,50)) brokecryst1.Velocity=vt(math.random(-100,100),math.random(-100,100),math.random(-100,100)) game:GetService("Debris"):AddItem(brokecryst,4) game:GetService("Debris"):AddItem(brokecryst1,4) end Part.Transparency=1 CrystDerp1.Transparency=1 end),CrystDerp) end Humanoid.WalkSpeed=16 for i=0,1,0.1 do wait() RW.C0=cf(1.5, 0.5, 0) * euler(-0.2+0.4*i,0,0) LW.C0=cf(-1.5, 0.5, 0) * euler(1.57-0.77*i,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5*i,0.4*i) end attack=false end function ob1d(mouse) if attack == true or CrystalNumb==0 then return end hold=true attackone() RW.C0=cf(1.5, 0.5, 0) * euler(0.2,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5,0.4) end function ob1u(mouse) hold = false end buttonhold = false eul=0 function key(key) if attack == true then return end if key=="z" then ShardWave() end if key=="b" then ShardBarrage() end if key=="x" and CrystalNumb>=0 then Shatter() end if key=="c" and CrystalNumb>=3 then ShardJab() end if key=="v" then crystalhold=true MakeCrystals() end RW.C0=cf(1.5, 0.5, 0) * euler(0.2,0,0) RW.C1=cf(0, 0.5, 0) * euler(0,0,-0.2) LW.C0=cf(-1.5, 0.5, 0) * euler(0.8,0,0) LW.C1=cf(0, 0.5, 0) * euler(0,-0.5,0.4) end function key2(key) if key=="v" then crystalhold=false end end function s(mouse) mouse.Button1Down:connect(function() ob1d(mouse) end) mouse.Button1Up:connect(function() ob1u(mouse) end) mouse.KeyDown:connect(key) mouse.KeyUp:connect(key2) unsheathed = true player = Player ch = Character MMouse = mouse RSH = ch.Torso["Right Shoulder"] LSH = ch.Torso["Left Shoulder"] -- RSH.Parent = nil LSH.Parent = nil -- RW.Part0 = ch.Torso RW.C0 = CFrame.new(1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.3, 0, -0.5) RW.C1 = CFrame.new(0, 0.5, 0) RW.Part1 = ch["Right Arm"] RW.Parent = ch.Torso --_G.R = RW -- LW.Part0 = ch.Torso LW.C0 = CFrame.new(-1.5, 0.5, 0) --* CFrame.fromEulerAnglesXYZ(1.7, 0, 0.8) LW.C1 = CFrame.new(0, 0.5, 0) LW.Part1 = ch["Left Arm"] LW.Parent = ch.Torso --_G.L = LW -- equipanim() end function ds(mouse) hideanim() wait(0) RW.Parent = nil LW.Parent = nil RSH.Parent = player.Character.Torso LSH.Parent = player.Character.Torso end Bin.Selected:connect(s) Bin.Deselected:connect(ds) print("Crystal Gauntlet loaded.") print(#Crystals) numbb=0 datnumb=0 while true do wait() datnumb=0 BaseNumb=6.28 BaseNumb=BaseNumb/CrystalNumb for d=1,#Crystals do datnumb=datnumb+BaseNumb local Crystal=Crystals[d] if Crystal.className=="Part" then coroutine.resume(coroutine.create(function(Part) if #Crystals~=0 then Part.CFrame=CFrame.new(Torso.Position)*euler(0,1+datnumb,0)*cf(0,0,5+(CrystalNumb/3)) numbb=numbb+0.05 --print(BaseNumb) end end),Crystal) end end end -- mediafire --[[ Copyrighted (C) Fenrier 2013 ]]
local M = {} function M.load_plugins() local optpack = require("optpack") local plugins = optpack.list() for _, plugin in ipairs(plugins) do optpack.load(plugin.name) end end function M.update_plugins() local optpack = require("optpack") optpack.update({ outputters = { bufer = { enabled = false }, echo = { enabled = true }, }, on_finished = function() vim.cmd([[quitall!]]) end, }) end function M.generate_help_tags() M.load_plugins() vim.cmd([[helptags ALL]]) M.schedule([[message | quitall!]]) end function M.test() M.load_plugins() local dir = vim.fn.expand("~/dotfiles/vim/after/ftplugin/") local pattern = dir .. "**/*.lua" local paths = vim.fn.glob(pattern, false, true) for _, path in ipairs(paths) do local ok, result = pcall(dofile, path) if not ok then print(result) end end for _, name in ipairs(require("notomo.plugin.lreload")) do require("lreload").refresh(name) end vim.schedule(function() local ok, result = pcall(M._test) if not ok then vim.api.nvim_echo({ { result, "Error" } }, true, {}) M.schedule([[message | cquit!]]) else M.schedule([[message | quitall!]]) end end) end function M._test() require("kivi").open() require("thetto").start( "file/in_dir", { opts = { cwd = "~/dotfiles/vim/lua/notomo", input_lines = { "option.lua" } } } ) require("thetto").execute() assert(vim.bo.filetype == "lua") vim.fn.feedkeys("tt", "mx") assert(vim.fn.tabpagenr("$") == 2, "tab count") vim.fn.feedkeys("th", "mx") assert(vim.fn.tabpagenr() == 1, "tab current") vim.cmd([[silent lua require("notomo.startup")._search()]]) vim.fn.feedkeys("tt", "mx") vim.fn.feedkeys("idate", "ix") vim.fn.feedkeys(vim.api.nvim_replace_termcodes("<Plug>(neosnippet_expand)", true, true, true), "ixm") assert(vim.fn.getline(".") ~= "date", "snippet expand") end function M._search() require("searcho").forward("opt") require("searcho").finish() end function M.schedule(cmd) vim.schedule(function() vim.schedule(function() vim.cmd(cmd) end) end) end function M.plugins() local optpack = require("optpack") local plugins = optpack.list() local dirs = {} for _, plugin in ipairs(plugins) do if not plugin.full_name:find("notomo/") then goto continue end local lua_dir = plugin.directory .. "/lua" if vim.fn.isdirectory(lua_dir) == 0 then goto continue end local makefile = plugin.directory .. "/Makefile" if vim.fn.filereadable(makefile) == 0 then goto continue end table.insert(dirs, plugin.directory) ::continue:: end io.stdout:write(table.concat(dirs, "\n")) end function M.vendorlib_used_plugins() local optpack = require("optpack") local plugins = optpack.list() local dirs = {} for _, plugin in ipairs(plugins) do if not plugin.full_name:find("notomo/") then goto continue end local lua_dir = plugin.directory .. "/lua" if vim.fn.isdirectory(lua_dir) == 0 then goto continue end local vendor_spec = vim.fn.glob(plugin.directory .. "**/vendorlib.lua") if vim.fn.filereadable(vendor_spec) == 0 then goto continue end table.insert(dirs, plugin.directory) ::continue:: end io.stdout:write(table.concat(dirs, "\n")) end return M
local _G = _G local AtlasLoot = _G.AtlasLoot local TooltipScan = {} AtlasLoot.TooltipScan = TooltipScan -- lua local match, find = string.match, string.find local pairs, tab_remove = pairs, table.remove -- WoW local GetSpellLink = GetSpellLink local C_Timer_After = C_Timer.After local cache = {} setmetatable(cache, {__mode = "kv"}) local AtlasLootScanTooltip = CreateFrame("GAMETOOLTIP", "AtlasLootScanTooltip", nil, "GameTooltipTemplate") AtlasLootScanTooltip:SetOwner(UIParent, "ANCHOR_NONE") function TooltipScan.GetTradeskillLink(tradeskillID) if not tradeskillID then return end if cache[tradeskillID] then return cache[tradeskillID][1], cache[tradeskillID][2] end local TradeskillLink = nil local TradeskillName = nil AtlasLootScanTooltip:SetOwner(UIParent, "ANCHOR_NONE") AtlasLootScanTooltip:ClearLines() AtlasLootScanTooltip:SetHyperlink("enchant:"..tradeskillID) AtlasLootScanTooltip:Show() local text = _G["AtlasLootScanTooltipTextLeft1"]:GetText() if text and find(text, ":") then TradeskillLink = "|cffffd000|Henchant:"..tradeskillID.."|h["..text.."]|h|r" TradeskillName = match(text, "(%w+):") else TradeskillLink = GetSpellLink(tradeskillID) end AtlasLootScanTooltip:Hide() cache[tradeskillID] = {TradeskillLink, TradeskillName} return TradeskillLink, TradeskillName end ------------------------------- local AtlasLootQueryTooltip = CreateFrame("GAMETOOLTIP", "AtlasLootQueryTooltip", nil, "GameTooltipTemplate") AtlasLootQueryTooltip:SetOwner(UIParent, "ANCHOR_TOP") local queryList = {} local queryListByID = {} local queryCacheMT = {__mode = "kv"} local queryCache = { "quest" } for i = 1, #queryCache do queryCache[ queryCache[i] ] = setmetatable({}, queryCacheMT) end local function SetNextQuery() if AtlasLootQueryTooltip.curQuery then return end local nextQuery = next(queryList) if nextQuery then queryList[ nextQuery ] = nil nextQuery[1](nextQuery[2], nextQuery[3], nextQuery[4], nextQuery) end end local function OnTooltipSetQuest(self) queryCache.quest[self.questID] = queryCache.quest[self.questID] or _G["AtlasLootQueryTooltipTextLeft1"]:GetText() self.onGetFunc(queryCache.quest[self.questID], self.arg1, self.curQuery) self.onGetFunc = nil self.questID = nil self.arg1 = nil self.curQuery = nil self:SetScript("OnTooltipSetQuest", nil) self:Hide() -- give the query a little bit time and it works perfect for more than 1 query :) C_Timer_After(0.05, SetNextQuery) end AtlasLootQueryTooltip:SetScript("OnTooltipSetQuest", OnTooltipSetQuest) -- /dump AtlasLoot.TooltipScan.GetQuestName(5090, print) function TooltipScan.GetQuestName(questID, onGetFunc, arg1, preSetQuery) if not questID then return end if queryCache.quest[questID] then onGetFunc( queryCache.quest[questID], arg1 ) AtlasLootQueryTooltip:SetScript("OnTooltipSetQuest", nil) AtlasLootQueryTooltip.onGetFunc = nil AtlasLootQueryTooltip.questID = nil AtlasLootQueryTooltip.arg1 = nil AtlasLootQueryTooltip.curQuery = nil AtlasLootQueryTooltip:Hide() SetNextQuery() return end preSetQuery = preSetQuery or {TooltipScan.GetQuestName, questID, onGetFunc, arg1} if AtlasLootQueryTooltip.onGetFunc then queryList[preSetQuery] = true return preSetQuery end --AtlasLootQueryTooltip:SetOwner(UIParent, "ANCHOR_NONE") AtlasLootQueryTooltip:SetOwner(UIParent, "ANCHOR_NONE") AtlasLootQueryTooltip:ClearLines() AtlasLootQueryTooltip.onGetFunc = onGetFunc AtlasLootQueryTooltip.questID = questID AtlasLootQueryTooltip.arg1 = arg1 AtlasLootQueryTooltip.curQuery = preSetQuery AtlasLootQueryTooltip:SetScript("OnTooltipSetQuest", OnTooltipSetQuest) AtlasLootQueryTooltip:Show() AtlasLootQueryTooltip:SetHyperlink("quest:"..questID) return preSetQuery end function TooltipScan.Remove(listEntry) if AtlasLootQueryTooltip.curQuery and AtlasLootQueryTooltip.curQuery == listEntry then AtlasLootQueryTooltip.onGetFunc = nil AtlasLootQueryTooltip.questID = nil AtlasLootQueryTooltip.arg1 = nil AtlasLootQueryTooltip.curQuery = nil AtlasLootQueryTooltip:SetScript("OnTooltipSetQuest", nil) AtlasLootQueryTooltip:Hide() SetNextQuery() else queryList[listEntry] = nil end end function TooltipScan.Clear() wipe(queryList) end
-- トーク組み立てビルダ local M = {} -- 配列からランダムに要素を1つ選んで返す。 local function SEL(array) local counter = #array local index = math.random(counter) return array[index] end -- builderを返す -- local C, S, T = builder.new() function M.new() local x = {} local t = "" local scope = {} local actor = false -- スコープ切り替え local function change_scope(id, line) t = t .. "\\" .. id actor = scope[id] if not actor then if not line then line = 150 end actor = {line = line, len=0} scope[id] = actor else if line then actor.line = line end if actor.len > 0 then t = t .. "\\n[" .. actor.line .."]" actor.len = 0 end end end -- サーフェス切り替え local function change_surface(...) local id = SEL({...}) if id then t = t .. "\\s[" .. id .."]" end end -- テキスト追加 local function push(text) t = t .. text if actor then actor.len = actor.len + string.len(text) else error("T(\"".. text .."\") Error, Not call C()") end end -- 発行 x.build = function() return t .. [=[\e]=] end -- 環境取得 x.get = function() return change_scope, change_surface, push end return x, change_scope, change_surface, push end function M.start() return "", M.s end function M.s(ch, sf, num) local t = "" if ch then t = t .. "\\" .. ch end if sf then t = t .. "\\s[" .. sf .."]" end if num then t = t .. "\\n[" .. num .."]" end return t end return M
local bin = require("bin") local match = require("match") local nmap = require("nmap") local packet = require "packet" local shortport = require("shortport") local sslcert = require("sslcert") local stdnse = require("stdnse") local table = require("table") local tls = require "tls" local vulns = require("vulns") description = [[ Detects whether a server is vulnerable to the F5 Ticketbleed bug (CVE-2016-9244). For additional information: * https://filippo.io/Ticketbleed/ * https://blog.filippo.io/finding-ticketbleed/ * https://support.f5.com/csp/article/K05121675 ]] --- -- @usage -- nmap -p 443 --script tls-ticketbleed <target> -- -- @output -- PORT STATE SERVICE -- 445/tcp open https -- | tls-ticketbleed: -- | VULNERABLE: -- | Ticketbleed is a serious issue in products manufactured by F5, a popular -- vendor of TLS load-balancers. The issue allows for stealing information from -- the load balancer -- | State: VULNERABLE (Exploitable) -- | Risk factor: High -- | Ticketbleed is vulnerability in the implementation of the TLS -- SessionTicket extension found in some F5 products. It allows the leakage -- ("bleeding") of up to 31 bytes of data from unin itialized memory. This is -- caused by the TLS stack padding a Session ID, passed from the client, with -- data to make it 32-bits long. -- | Exploit results: -- | 2ab2ea6a4c167fbe8bf0b36c7d9ed6d3 -- | *..jL......l}... -- | References: -- | https://filippo.io/Ticketbleed/ -- | https://blog.filippo.io/finding-ticketbleed/ -- |_ https://support.f5.com/csp/article/K05121675 -- -- @args tls-ticketbleed.protocols (default tries all) TLSv1.0, TLSv1.1, or TLSv1.2 author = "Mak Kolybabi <mak@kolybabi.com>" license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"vuln", "safe"} portrule = function(host, port) if not tls.handshake_parse.NewSessionTicket then stdnse.verbose1("Not running: incompatible tls.lua. Get the latest from https://nmap.org/nsedoc/lib/tls.html") return false end -- Ensure we have the privileges necessary to run the PCAP operations this -- script depends upon. if not nmap.is_privileged() then nmap.registry[SCRIPT_NAME] = nmap.registry[SCRIPT_NAME] or {} if not nmap.registry[SCRIPT_NAME].rootfail then stdnse.verbose1("Not running due to lack of privileges.") end nmap.registry[SCRIPT_NAME].rootfail = true return false end return shortport.ssl(host, port) or sslcert.getPrepareTLSWithoutReconnect(port) end local function is_vuln(host, port, version) -- Checking a host requires a valid TLS Session Ticket. The Nmap API -- does not expose that information to us, but it is sent -- unencrypted near the end of the TLS handshake. -- -- First we must create a socket that is ready to start a TLS -- connection, so that we may find the local port from which it is -- sending, and can use that information to filter the PCAP. -- -- We should have a way to specify version here, but we don't. local socket local starttls = sslcert.getPrepareTLSWithoutReconnect(port) if starttls then local status status, socket = starttls(host, port) if not status then stdnse.debug3("StartTLS connection to server failed: %s", socket) return end else socket = nmap.new_socket() local status, err = socket:connect(host, port, "tcp") if not status then stdnse.debug3("Connection to server failed: %s", err) return end end socket:set_timeout(5000) -- Find out the port we'll be using in our TLS negotiation. local status, _, lport = socket:get_info() if( not(status) ) then stdnse.debug3("Failed to retrieve local port used by socket.") return end -- We are only interested in capturing the TLS responses from the -- server, not our traffic. We need to set the snaplen to be fairly -- large to accommodate packets with many or large certificates. local filter = ("src host %s and tcp and src port %d and dst port %d"):format(host.ip, port.number, lport) local pcap = nmap.new_socket() pcap:set_timeout(5) pcap:pcap_open(host.interface, 4096, false, filter) -- Initiate the TLS negotiation on the already-connected socket, and -- then immediately close the socket. local status, err = socket:reconnect_ssl() if not status then stdnse.debug1("Can't connect with TLS: %s", err) return end socket:close() -- Repeatedly read previously-captured packets and add them to a -- buffer. local buf = {} while true do local status, _, _, layer3, _ = pcap:pcap_receive() if not status then break end -- Parse captured packet and extract data. local pkt = packet.Packet:new(layer3, #layer3) if not pkt then stdnse.debug3("Failed to create packet from captured data.") return end if not pkt:tcp_parse() then stdnse.debug3("Failed to parse captured packet.") return end local tls_data = pkt:raw(pkt.tcp_data_offset) table.insert(buf, tls_data) end buf = table.concat(buf, "") pcap:pcap_close() pcap:close() -- Attempt to find the NewSessionTicket record in the captured -- packets. local pos, ticket repeat -- Attempt to parse the buffer. local record pos, record = tls.record_read(buf, pos) if not record then break end if record.type ~= "handshake" then break end -- Search for the NewSessionTicket record, which contains the -- Session Ticket we need. for _, body in ipairs(record.body) do stdnse.debug1("Captured %s record.", body.type) if body.type == "NewSessionTicket" then if body.ticket then ticket = body.ticket else -- If someone downloaded this script separately from Nmap, -- they are likely to be missing the parsing changes to the -- TLS library. Try parsing the body inline. if #body.data <= 4 then stdnse.debug1("NewSessionTicket's body was too short to parse: %d bytes", #body.data) return end _, ticket = (">I4 s2"):unpack(body.data) end break end end until ticket or pos > #buf if not ticket then stdnse.debug1("Server did not send a NewSessionTicket record.") return end -- Create the ClientHello record that triggers the behaviour in -- affected systems. The record must include both a Session ID and a -- TLS Session Ticket extension. -- -- Setting the Session ID to a 16 bytes allows for the remaining 16 -- bytes of the field to be filled with uninitialized memory when it -- is echoed back in the ServerHelloDone record. Using 16 bytes -- reduces the chance of a false positive caused by the server -- issuing us a new, valid session ID that just happens to match the -- random one we provided. local sid_old = stdnse.generate_random_string(16) local hello = tls.client_hello({ ["protocol"] = version, ["session_id"] = sid_old, -- Claim to support every cipher -- Doesn't work with IIS, but only F5 products should be affected ["ciphers"] = stdnse.keys(tls.CIPHERS), ["compressors"] = {"NULL"}, ["extensions"] = { -- Claim to support every elliptic curve ["elliptic_curves"] = tls.EXTENSION_HELPERS["elliptic_curves"](stdnse.keys(tls.ELLIPTIC_CURVES)), -- Claim to support every EC point format ["ec_point_formats"] = tls.EXTENSION_HELPERS["ec_point_formats"](stdnse.keys(tls.EC_POINT_FORMATS)), ["SessionTicket TLS"] = ticket, }, }) -- Connect the socket so that it is ready to start a TLS session. if starttls then local status status, socket = starttls(host, port) if not status then stdnse.debug3("StartTLS connection to server failed: %s", socket) return end else socket = nmap.new_socket() local status, err = socket:connect(host, port, "tcp") if not status then stdnse.debug3("Connection to server failed: %s", err) return end end -- Send Client Hello to the target server. local status, err = socket:send(hello) if not status then stdnse.debug1("Couldn't send Client Hello: %s", err) socket:close() return end -- Read responses from server. local status, response, err = tls.record_buffer(socket) socket:close() if err == "TIMEOUT" then stdnse.debug1("Timeout exceeded waiting for Server Hello Done.") return end if not status then stdnse.debug1("Couldn't receive: %s", err) socket:close() return end -- Attempt to parse the response. local _, record = tls.record_read(response) if record == nil then stdnse.debug1("Unrecognized response from server.") return end if record.protocol ~= version then stdnse.debug1("Server responded with a different protocol than we requested: %s", record.protocol) return end if record.type ~= "handshake" then stdnse.debug1("Server failed to respond with a handshake record: %s", record.type) return end -- Search for the ServerHello record, which contains the Session ID -- we want. local sid_new for _, body in ipairs(record.body) do if body.type == "server_hello" then sid_new = body.session_id end end if not sid_new then stdnse.debug1("Failed to receive a Server Hello record.") return end if sid_new == "" then stdnse.debug1("Server did not respond with a session ID.") return end -- Check whether the Session ID matches what we originally sent, -- which should be the case for a properly-functioning TLS stacks. if sid_new == sid_old then stdnse.debug1("Server properly echoed our short, random session ID.") return end -- If the system is unaffected, it should provide a new session ID -- unrelated to the one we provided. Check for the new session ID -- being prefixed by the one we sent, indicating an affected system. if sid_new:sub(1, #sid_old) ~= sid_old then stdnse.debug1("Server responded with a new, unrelated session ID.") stdnse.debug1("Original session ID: %s", stdnse.tohex(sid_old, {separator = ":"})) stdnse.debug1("Received session ID: %s", stdnse.tohex(sid_new, {separator = ":"})) return end return sid_new end action = function(host, port) local vuln_table = { title = "Ticketbleed is a serious issue in products manufactured by F5, a popular vendor of TLS load-balancers. The issue allows for stealing information from the load balancer", state = vulns.STATE.NOT_VULN, risk_factor = "High", description = [[ Ticketbleed is vulnerability in the implementation of the TLS SessionTicket extension found in some F5 products. It allows the leakage ("bleeding") of up to 31 bytes of data from uninitialized memory. This is caused by the TLS stack padding a Session ID, passed from the client, with data to make it 32-bits long. ]], references = { "https://filippo.io/Ticketbleed/", "https://blog.filippo.io/finding-ticketbleed/", "https://support.f5.com/csp/article/K05121675" } } -- Accept user-specified protocols. local vers = stdnse.get_script_args(SCRIPT_NAME .. ".protocols") or {"TLSv1.0", "TLSv1.1", "TLSv1.2"} if type(vers) == "string" then vers = {vers} end for _, ver in ipairs(vers) do -- Ensure the protocol version is supported. if nil == tls.PROTOCOLS[ver] then return "\n Unsupported protocol version: " .. ver end -- Check for the presence of the vulnerability. local sid = is_vuln(host, port, ver) if sid then vuln_table.state = vulns.STATE.EXPLOIT vuln_table.exploit_results = { stdnse.tohex(sid:sub(17)), (sid:sub(17):gsub("[^%g ]", ".")) } break end end local report = vulns.Report:new(SCRIPT_NAME, host, port) return report:make_output(vuln_table) end
ys = ys or {} slot1 = ys.Battle.BattleConst.AIStepType slot2 = class("AutoPilot") ys.Battle.AutoPilot = slot2 slot2.__name = "AutoPilot" slot2.PILOT_VALVE = 0.5 slot2.Ctor = function (slot0, slot1, slot2) slot0._aiCfg = slot2 slot0._target = slot1 slot1._move:SetAutoMoveAI(slot0, slot1) slot0:generateList() slot0._currentStep = slot0._stepList[slot0._aiCfg.default] slot0._currentStep:Active(slot0._target) end slot2.GetDirection = function (slot0) return slot0._currentStep:GetDirection(slot0._target:GetPosition()) end slot2.InputWeaponStateChange = function (slot0) return end slot2.SetHiveUnit = function (slot0, slot1) slot0._hiveUnit = slot1 end slot2.GetHiveUnit = function (slot0) return slot0._hiveUnit end slot2.OnHiveUnitDead = function (slot0) slot0._target:OnMotherDead() end slot2.NextStep = function (slot0) if slot0._stepList[slot0._currentStep:GetToIndex()] == nil then slot1 = slot0._aiCfg.default end slot0._currentStep = slot0._stepList[slot1] slot0._currentStep:Active(slot0._target) end slot2.generateList = function (slot0) slot0._stepList = {} for slot4, slot5 in ipairs(slot0._aiCfg.list) do slot6 = nil slot7 = slot5.index slot8 = slot5.to slot10 = slot5.param if slot5.type == slot0.STAY then slot6 = slot1.Battle.AutoPilotStay.New(slot7, slot0) elseif slot9 == slot0.MOVE_TO then slot6 = slot1.Battle.AutoPilotMoveTo.New(slot7, slot0) elseif slot9 == slot0.MOVE then slot6 = slot1.Battle.AutoPilotMove.New(slot7, slot0) elseif slot9 == slot0.BROWNIAN then slot6 = slot1.Battle.AutoPilotBrownian.New(slot7, slot0) elseif slot9 == slot0.CIRCLE then slot6 = slot1.Battle.AutoPilotCircle.New(slot7, slot0) elseif slot9 == slot0.RELATIVE_BROWNIAN then slot6 = slot1.Battle.AutoPilotRelativeBrownian.New(slot7, slot0) elseif slot9 == slot0.RELATIVE_FLEET_MOVE_TO then slot6 = slot1.Battle.AutoPilotRelativeFleetMoveTo.New(slot7, slot0) elseif slot9 == slot0.HIVE_STAY then slot6 = slot1.Battle.AutoPilotHiveRelativeStay.New(slot7, slot0) elseif slot9 == slot0.HIVE_CIRCLE then slot6 = slot1.Battle.AutoPilotHiveRelativeCircle.New(slot7, slot0) end slot6:SetParameter(slot10, slot8) slot0._stepList[slot6:GetIndex()] = slot6 end end return
-- INDICATOR SPRITES local indicators = {} for i, color in ipairs{"black", "white", "red", "orange", "yellow", "green", "cyan", "blue", "purple", "pink"} do indicators[i] = { type = "sprite", name = "flib_indicator_"..color, filename = "__flib__/graphics/indicators.png", y = (i - 1) * 32, size = 32, flags = {"icon"} } end data:extend(indicators) local fab = "__flib__/graphics/frame-action-icons.png" data:extend{ {type = "sprite", name = "flib_pin_black", filename = fab, position = {0, 0}, size = 32, flags = {"icon"}}, {type = "sprite", name = "flib_pin_white", filename = fab, position = {32, 0}, size = 32, flags = {"icon"}}, {type = "sprite", name = "flib_pin_disabled", filename = fab, position = {64, 0}, size = 32, flags = {"icon"}}, {type = "sprite", name = "flib_settings_black", filename = fab, position = {0, 32}, size = 32, flags = {"icon"}}, {type = "sprite", name = "flib_settings_white", filename = fab, position = {32, 32}, size = 32, flags = {"icon"}}, {type = "sprite", name = "flib_settings_disabled", filename = fab, position = {64, 32}, size = 32, flags = {"icon"}}, }
-- -- Xbox One XDK support for Visual Studio backend. -- Copyright Blizzard Entertainment, Inc -- -- -- Non-overrides -- local p = premake local vstudio = p.vstudio local vc2010 = p.vstudio.vc2010 p.DURANGO = "durango" if vstudio.vs2010_architectures ~= nil then vstudio.vs2010_architectures.durango = "Durango" p.api.addAllowed("system", p.DURANGO) os.systemTags[p.DURANGO] = { "durango", "xboxone_xdk", "xboxone", "xdk", "xbox", "console" } local osoption = p.option.get("os") if osoption ~= nil then table.insert(osoption.allowed, { p.DURANGO, "Xbox One (XDK)" }) end end filter { "system:Durango" } architecture "x86_64" filter { "system:Durango", "kind:ConsoleApp or WindowedApp" } targetextension ".exe" filter { "system:Durango", "kind:StaticLib" } targetprefix "" targetextension ".lib" filter {} -- -- Properties -- p.api.register { name = "compileaswinrt", scope = "config", kind = "boolean" } -- -- Methods. -- local function winrt(cfg) vc2010.element("CompileAsWinRT", nil, iif(cfg.compileaswinrt, "true", "false")) end -- -- Overrides -- p.override(vc2010.elements, "clCompile", function(base, cfg) local calls = base(cfg) if cfg.system == p.DURANGO and (cfg.kind == p.CONSOLEAPP or cfg.kind == p.WINDOWEDAPP) then table.insert(calls, winrt) end return calls end)
local GPC = {} GPC.Identity = 'gui_pause_controller' GPC.Locale = { ["name"] = { ["english"] = "Pause Control", ["russian"] = "Управление паузой", ["chinese"] = "暫停控制" }, ["desc"] = { ["english"] = "Auto unpause", ["russian"] = "Отменяет паузу", ["chinese"] = "自動取消暫停", }, ["auto_pause"] = { ["english"] = "Auto pause when ally is disconnected", ["russian"] = "Ставить паузу когда союзник выходит", ["chinese"] = "超時開始" }, ["auto_unpause"] = { ["english"] = "Force unpause if pause is set by enemies", ["russian"] = "Отжимать паузу когда противник выходит", ["chinese"] = "延遲" }, ["on"] = { ["english"] = "On", ["russian"] = "Вкл", ["chinese"] = "打開" }, ["off"] = { ["english"] = "Off", ["russian"] = "Выкл", ["chinese"] = "關機" } } GPC.CurrentTime = 0 GPC.NextTime = 0 GPC.PauseTimeStart = 0 function GPC.OnDraw() if GUI == nil then return end if not GUI.Exist(GPC.Identity) then local GUI_Object = {} GUI_Object["perfect_name"] = GPC.Locale['name'] GUI_Object["perfect_desc"] = GPC.Locale['desc'] GUI_Object["perfect_author"] = 'paroxysm' GUI_Object["category"] = GUI.Category.General GUI.Initialize(GPC.Identity, GUI_Object) -- GUI.AddMenuItem(GPC.Identity, GPC.Identity .. "auto_pause", GPC.Locale['auto_pause'], GUI.MenuType.CheckBox, 0) GUI.AddMenuItem(GPC.Identity, GPC.Identity .. "auto_unpause", GPC.Locale['auto_unpause'], GUI.MenuType.CheckBox, 0) end if GUI.IsEnabled(GPC.Identity) and GUI.SelectedLanguage ~= nil then if GameRules.IsPaused() then if GPC.PauseTimeStart == 0 then GPC.PauseTimeStart = os.clock() end local w, h = Renderer.GetScreenSize() local x = math.floor(w / 2) local y = math.floor(h * 0.334) Renderer.SetDrawColor(0, 0, 0, 180) if Input.IsCursorInRect(x - 70, y - 15, 140, 30) then Renderer.SetDrawColor(0, 0, 0, 220) if Input.IsKeyDownOnce(Enum.ButtonCode.MOUSE_LEFT) then if GUI.IsEnabled(GPC.Identity .. "gpcise") then GUI.Set(GPC.Identity .. "gpcise", 0) else GUI.Set(GPC.Identity .. "gpcise", 1) end end end Renderer.DrawFilledRect(x - 70, y - 15, 140, 30) local text = GPC.Locale["off"][GUI.SelectedLanguage] if GUI.IsEnabled(GPC.Identity .. "gpcise") then Renderer.SetDrawColor(255, 255, 255, 255) else text = GPC.Locale["on"][GUI.SelectedLanguage] Renderer.SetDrawColor(255, 255, 255, 100) end local calculate = math.floor(30 - (os.clock() - GPC.PauseTimeStart)) if calculate < 0 then calculate = 0 GPC.UnPause() end Renderer.DrawTextCentered(GUI.Font.Header, x, y, "GPC : " .. text .. " (" .. calculate .. ")", false) else GPC.PauseTimeStart = 0 end end if Engine.IsInGame() then GPC.CurrentTime = GameRules.GetGameTime() end end -- function GPC.OnUpdate() -- if GUI.IsEnabled(GPC.Identity) -- and GUI.IsEnabled(GPC.Identity .. "auto_pause") -- and GPC.CurrentTime > GPC.NextTime -- then -- for k, v in pairs(Players.GetAll()) do -- if Entity.IsSameTeam(v, Players.GetLocal()) -- and not Player.GetPlayerData(v).fullyJoined -- and not GameRules.IsPaused() -- then -- Engine.ExecuteCommand("dota_pause") -- GPC.NextTime = GPC.CurrentTime + NetChannel.GetAvgLatency(Enum.Flow.FLOW_OUTGOING) + 3 -- end -- end -- end -- end function GPC.OnGameStart() GPC.CurrentTime = 0 GPC.NextTime = 0 GPC.PauseTimeStart = 0 end function GPC.UnPause() if GUI.IsEnabled(GPC.Identity .. "gpcise") and GUI.IsEnabled(GPC.Identity .. "auto_unpause") and GameRules.IsPaused() and GPC.CurrentTime > GPC.NextTime then local safe_to_unp = true for k, v in pairs(Players.GetAll()) do if Entity.IsSameTeam(v, Players.GetLocal()) and not Player.GetPlayerData(v).fullyJoined then safe_to_unp = false end end if safe_to_unp then Engine.ExecuteCommand("dota_pause") GPC.NextTime = GPC.CurrentTime + NetChannel.GetAvgLatency(Enum.Flow.FLOW_OUTGOING) + 1 end end end return GPC
--- Core logging class. -- -- See the @{core.log.lua} example for more detail. -- -- @classmod luchia.core.log -- @author Chad Phillips -- @copyright 2011-2015 Chad Phillips local logging = require("logging") local conf = require "luchia.conf" local _M = {} --- The logging class. -- -- Wrapper to <a href="http://neopallium.github.io/lualogging/manual.html">lualogging</a> class. -- -- @usage logger:debug("debug message") -- @see core.log.lua _M.logger = {} --- Reconfigure the logger. -- @param config -- Configuration settings for the logger. -- @usage luchia.core.log:set_logger(config) -- @see luchia.conf function _M:set_logger(config) config = config or conf.log if config.appender == "file" then local file = require("logging.file") self.logger = file(config.file, nil, config.format) else local console = require("logging.console") self.logger = console(config.format) end self.logger:setLevel(logging[config.level]) end _M:set_logger() return _M
local KifuPlayer = require("kifu_player") local SS = require("sakura_script") local StringBuffer = require("string_buffer") local Utils = require("talk.shogi._utils") return { { id = "将棋用語_戦法", content = [[ \0\s[素]\b[2] \_q 【相居飛車】\n \![*]相掛かり\n 5手爆弾\n \![*]角換わり\n 角換わり棒銀 角換わり早繰り銀 角換わり腰掛け銀 角換わり腰掛け銀4八金2九飛 一手損角換わり\n \![*]横歩取り\n 青野流 横歩取り4五角 相横歩\n \![*]矢倉\n \![*]部分的な戦法\n 棒銀 早繰り銀 腰掛け銀\n \n 【対抗型】\n 対振り急戦 対振り持久戦 相穴熊\n \n 【振り飛車】 \![*]中飛車\n 原始中飛車 ゴキゲン中飛車\n \![*]四間飛車\n 角交換四間飛車 レグスペ 藤井システム\n \![*]三間飛車\n 石田流 早石田 トマホーク 鬼殺し\n \![*]向かい飛車\n ダイレクト向かい飛車 阪田流向かい飛車\n \n 【相振り飛車】\n 向かい飛車vs三間飛車 中飛車vs三間飛車\n \n \![*]\q[戻る,将棋用語] \![*]\q[閉じる,閉じる]\n \_q ]], }, { anchor = true, id = "相掛かり", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("lnsgk1snl/1r4gb1/p1ppppppp/9/1p5P1/9/PPPPPPP1P/1BG4R1/LNS1KGSNL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【相掛かり】\_q\w9\n 序盤に角道を開けずに飛車先を突いていくのが特徴の戦型。 短い手数で一気に終盤戦になることもあるので序盤から慎重な差し回しが求められるよ。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { passthrough = true, id = "相掛かり_tooltip", content = [[ 序盤に角道を開けずに飛車先の歩交換を行う相居飛車の戦型。 ]], }, { anchor = true, id = "角換わり", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("lnsgk2nl/1r4g2/p1ppppspp/6p2/1p5P1/2P6/PPSPPPP1P/2G4R1/LN2KGSNL b Bb 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【角換わり】\_q\w9\n 名前のとおり、序盤からお互いに角を持ち合うことになる戦型だよ。\n 角打ちの隙がないか考えながら駒組みしないとなので、 将棋始めたての頃は少し大変かも。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "角換わり棒銀", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("ln1gk2nl/1r4g2/p1spppspp/2p3p2/1p5P1/2P4S1/PPSPPPP1P/2G4R1/LN2KG1NL b Bb 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【角換わり棒銀】\_q\w9\n 角交換後に棒銀を目指す戦法。\n 後手が素直に銀交換に応じてくれるといいんだけど、 △5四角とする手があって、受け方を知らないと 何も出来なくなっちゃうのでちょっと危険。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "角換わり早繰り銀", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("ln1gk2nl/1r4g2/p1p1p1spp/3pspp2/1p5P1/2P2SP2/PPSPPP2P/2GK3R1/LN3G1NL b Bb 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【角換わり早繰り銀】\_q\w9\n 角交換後に早繰り銀を目指す戦法。\n 私が知らないだけなんだけど、早繰り銀にはこの形で対抗する!@ みたいな形がないので、結構有力だと思う。\n 銀交換出来たら、▲5六角から2三の地点を狙うのが1つの狙いだよ。 \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "角換わり腰掛け銀", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("l5knl/1r2g1g2/2n1p1sp1/p1ppspp1p/1p5P1/P1PPSPP1P/1PS1P1N2/2G1G2R1/LNK5L b Bb 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【角換わり腰掛け銀】\_q\w9\n 元々、角換わり腰掛け銀と言えばこれのことだったんだけど、 最近は角換わり腰掛け銀4八金2九飛の流行で 両者共この形に組むことはほとんどなくなったみたい。\n 42173という魔法の数字はこの戦型のもの。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "角換わり腰掛け銀4八金2九飛", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("lr5nl/3g1kg2/2n1ppsp1/p1pps1p1p/1p5P1/P1P1SPP1P/1PSPP1N2/2GK1G3/LN5RL b Bb 1") str:append(shiori:talk("OnShogiViewMinimal")) str:append([[ \0 \_q【角換わり腰掛け銀4八金2九飛】\_q\w9\n この戦法は、2015年頃からプロ間で指されはじめた戦法で、 元々はコンピューター同士の対局で現れたものだよ。\n 今までの角換わり腰掛け銀と比べると、玉の位置と 自陣に角を打ち込む隙が無くなっているのが特徴。\n \n \_q\![*]\q[続き,角換わり腰掛け銀4八金2九飛_続き1]\n \![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "角換わり腰掛け銀4八金2九飛_続き1", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() --TODO 最初の説明 str:append([[ \0 \_q【角換わり腰掛け銀4八金2九飛】\_q\w9\n \n この戦法は元々後手番で指された戦法で、 従来の腰掛け銀に対して先攻出来る利点があるよ。 先手が従来の腰掛け銀、後手が4八金2九飛(6二金8一飛)型に組むと、 ]]) player:setPosition("lr5nl/3g1kg2/2n1ppsp1/p1pps1p1p/1p5P1/P1P1SPP1P/1PSPP1N2/2G1G2R1/LNK5L b Bb 1") player:appendMove("6g6f") str:append(shiori:talk("OnShogiViewMinimal")) str:append([[ \0 こんな形になって手番は後手。\n \x[noclear] ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "6d6e", "6f6e", "7c6e", })) str:append([[ \0 と仕掛ける手があって、 先手は後手に先攻されるのは嫌なので強く ]]) str:append(Utils.M2SS(shiori, { "5f6e", })) str:append([[ \0 として6筋を逆襲。\x[noclear] ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "5d6e", "P*6c", "6b7b", "N*6d", "7b7c", "6c6b+", "7c6d", })) str:append([[ \0 として 玉の近くにと金を作ることに成功するよ。\n \x[noclear] ここから指してみると先手は攻め駒が少なく、攻めの継続が難しい。\n 一方後手は先手から駒をたくさん貰っているので、手番が回ってくれば 色々攻める手がありそう。\n となるとこの後は後手が主導権を握る戦いになってしまい、先手としては不満。 \x[noclear] なので局面を戻して、 ]]) player:setPosition("lr5nl/3g1kg2/2n1ppsp1/p1p1s1p1p/1p1P3P1/P1P1SPP1P/1PS1P1N2/2G1G2R1/LNK5L w BPb 1") player:appendMove("7c6e") str:append(shiori:talk("OnShogiViewMinimal")) str:append([[ \0 この局面、\w9\w9先手は ]]) str:append(Utils.M2SS(shiori, { "7g6f", })) str:append([[ \0 とするしかなく、結局後手に先攻を許してしまうよ。\n \x[noclear]\n せっかく先手で相手より1手多く指せるはずなのに 後手に先に攻められてしまうのは悔しい。 なので、どうにか先攻出来るようにしようとした結果、 先手も後手と同じ4八金2九飛型に組むようになったよ。\n そんな経緯があって、今では腰掛け銀はこっちが指されることが多いかな。\n \n \_q\![*]\q[戻る,将棋四方山話一覧] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "横歩取り", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("lnsgk1snl/6g2/p1ppppb1p/6R2/9/1rP6/P2PPPP1P/1BG6/LNS1KGSNL b 3P2p 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【横歩取り】\_q\w9\n 2四の飛車が3四にいた歩を取ることから横歩取りと名付けられたよ。\n 急戦形だと飛車角が入り乱れる激しい戦いになるので見てる分には楽しい。\n \n 横歩取り4五角や相横歩のせいでアマチュア間ではあんまり指されないかも。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "横歩取り4五角", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("lnsgk1snl/6g2/p1pppp2p/6R2/5b3/1rP6/P2PPPP1P/1SG4S1/LN2KG1NL b B4Pp 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【横歩取り4五角】\_q\w9\n アマチュア間で横歩取りが指されない理由その1。\n 後手番の戦法で、ハメ手としてかなり有名。 正しく指せば先手が良くなるものの、正しく指すのが何せ難しい。 その分、格上に一発入ったりするので覚えて損は無いかも?\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "相横歩", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("lnsgk1snl/6g2/p1pppp2p/6R2/9/2r6/P2PPPP1P/1SG6/LN2KGSNL b B3Pb3p 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【相横歩】\_q\w9\n アマチュア間で横歩取りが指されない理由その2。\n 横歩取り4五角と比べると、後手がそこまで変な手を指してこないので 定跡を知らなくても意外と良い勝負が出来るかも? 一応、穏やかにするチャンスが何回かあるので それで勝負するのもアリ。 \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str:tostring() end, }, { anchor = true, id = "棒銀", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("7nl/6g2/6spp/6p2/7P1/7S1/5PP1P/7R1/7NL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 \_q【棒銀】\_q\w9\n ▲2七銀〜▲2六銀と銀を進めていって、2筋突破を目指す戦法。\n シンプルだけど、破壊力は抜群。\n 実際の進行はこんな感じだよ。\n \n \_qクリックしてね!\_q \x ]]) player:setPosition("7nl/6g2/7pp/6p2/7P1/7S1/5PP1P/7R1/7NL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 \_q【棒銀がきれいに決まる場合】\_q\n \_w[1000] 相手の守りが金だけだと棒銀が決まるよ。\n ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "2f1e", "pass", "2e2d", "2c2d", "1e2d", "P*2c", "2d2c+","3b2c", "2h2c+", })) str:append([[ \0 。\n こうなれば先手が大体勝ちだね。\n こうなることは少ないけど、攻めの基本パターンとして覚えておきたいところ。\n \n \_qクリックしてね!\_q \x ]]) player:setPosition("7nl/6g2/6spp/6p2/7P1/7S1/5PP1P/7R1/7NL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 \_q【端の突き合いがない場合】\_q\n \_w[1000] ▲1六歩△1四歩の交換がない時は、銀交換に持ち込めるよ。\n ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "2f1e", "pass", "2e2d", "2c2d", "1e2d", "3c2d", "2h2d", "P*2c", "2d2h", })) str:append([[ \0 。\n 「相手の守り駒を一枚減らした」\n 「銀を持ち駒にした(=好きなところに銀を打てる)」\n と2つの利点があって交換出来るのは攻めた方の得。\n ……とされていたんだけど、 最近は「手数掛けた割に銀交換だけじゃあまり得したとは言えないんじゃないか」 という考えに変わってきてるみたい。\n まあ、プロレベルの話であって、アマチュア間ではほぼ間違いなく得だと思うけどね。\n \n \_qクリックしてね!\_q \x ]]) player:setPosition("7nl/6g2/6sp1/6p1p/7P1/7SP/5PP2/7R1/7NL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 \_q【端を突き合った場合】\_q\n \_w[1000] ▲1六歩△1四歩の交換が入っている場合は、1筋から攻めるのが定跡。\n ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "1f1e", "1d1e", "2f1e", "1a1e", "1i1e", })) str:append([[ \0 。\n 瞬間的には銀香交換で駒損だけど、端を破る形になるのでトントンかな。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str end, }, { anchor = true, id = "早繰り銀", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("7nl/6g2/6spp/6p2/7P1/5SP2/5P2P/7R1/7NL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 ▲3七銀〜▲4六銀と銀を進めていって、2、3筋で戦いを起こす戦法。\n ▲5六角と打って2三の地点を攻めるのが狙いとしてある……かな。\n 銀がいなくなると、△6四角とかで2八にいる飛車を狙われやすいので注意。\n \n \_qクリックしてね!\_q \x ]]) player:setPosition("7nl/6g2/6sp1/6p1p/7P1/5SP1P/5P3/7R1/7NL b Bb 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 \_q【進行1例】\_q\n \_w[1000] ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "3f3e", "3d3e", "4f3e", "pass", "2e2d", "2c2d", "3e2d", "3c2d", "2h2d", "P*2c", "2d2h", })) str:append([[ \0 。\n 3筋の歩と銀が交換できて棒銀よりお得感があるね。\n この後の進行としては、 ]]) str:append(Utils.M2SS(shiori, { wait = 1000, "pass", "B*5f", "S*2b", "1f1e", "1d1e", "P*1b", "1a1b", "P*2d", })) str:append([[ \0 なんてのが考えられるかな。\n この歩を取ると▲1二角成と出来るので、一本取った!って感じだね。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str end, }, { anchor = true, id = "腰掛け銀", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("7nl/9/6spp/6p2/7P1/4SPP2/4P1N1P/7R1/8L b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append([[ \0 ▲4七銀〜▲5六銀と銀を進めていって、2、3、4筋を攻めていく戦法。 2九にいる桂馬を▲3七桂〜▲4五桂と活用しやすく、飛車銀桂の3つの駒で 攻めていくので、攻めが繋がりやすいよ。\n 相手の持ち駒に歩があると、△3五歩▲同歩△3六歩のような攻めが生じるので、 銀は4七で待機して、攻める直前で5六に上がるのが良さそう。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str end, }, { anchor = true, id = "四間飛車", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("ln1gkgsnl/1r1s3b1/p1pppp1pp/6p2/1p7/2PP5/PPB1PPPPP/3R5/LNSGKGSNL b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【四間飛車】\_q\w9\n 飛車を左から4つめの筋に振る振り飛車。\n 飛車先を突破するというよりは相手の攻めに乗じて 左側の駒をうまく駒台にのせていくのが狙い。\n \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str end, }, { anchor = true, id = "4五歩早仕掛け", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("ln1g3nl/1ks1gr3/1ppp1sbpp/p3ppp2/7P1/P1P1PPP2/1P1PS3P/1BK1GS1R1/LN1G3NL b - 1") player:appendMove("4f4e") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【4五歩早仕掛け】\_q\w9\n 四間飛車急戦の一種。\n ▲3三角成△同桂▲2四歩△同歩▲同飛の2筋突破が先手の基本的な狙い。 △5四歩を突いてくれないと成立しにくい。 \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str end, }, { anchor = true, id = "相穴熊", content = function(shiori, ref) local str = StringBuffer() local player = KifuPlayer.getInstance() player:setPosition("ln4gnk/1r4gsl/p1ppspbpp/4p1p2/1p7/2PP5/PPBSPPPPP/3R2GSL/LN4GNK b - 1") str:append(shiori:talk("OnShogiViewMinimal", ref)) str:append(SS():p(0)):append([[ \_q【相穴熊】\_q\w9\n 相穴熊は対抗型の一種で両対局者が穴熊囲いに組んだ戦型。\n 基本的に金銀はすべて囲いに使われるため、いかにして細い攻めを繋げるかが勝負の鍵になるよ。\n \n 一応相居飛車や相振り飛車でも相穴熊になる可能性はあるんだけど、 対局者のどちらかが穴熊にせずに攻め始めることが多いから、 実際に見たことはまだないんだよね…。 \n \_q\![*]\q[戻る,将棋用語_戦法] \![*]\q[閉じる,閉じる]\n\_q ]]) return str end, }, }
ENT.Type = "anim" ENT.PrintName = "Thrown Blade" ENT.Author = "" ENT.Contact = "" ENT.Purpose = "" ENT.Instructions = "" ENT.DoNotDuplicate = true ENT.DColDuplicator = true MAT_DEF = 1 ENT.HitSounds = { [MAT_DEF] = { Sound("physics/metal/metal_grenade_impact_hard1.wav"), Sound("physics/metal/metal_grenade_impact_hard2.wav"), Sound("physics/metal/metal_grenade_impact_hard3.wav") }, [MAT_FLESH] = { Sound("physics/flesh/flesh_impact_bullet1.wav"), Sound("physics/flesh/flesh_impact_bullet2.wav"), Sound("physics/flesh/flesh_impact_bullet3.wav") } } ENT.Shink = Sound("weapons/blades/impact.mp3") if SERVER then AddCSLuaFile() /*--------------------------------------------------------- Name: ENT:Initialize() ---------------------------------------------------------*/ function ENT:Initialize() local mdl = self:GetModel() if !mdl or mdl=="" or string.find(mdl,"error") then self:SetModel("models/weapons/w_knife_t.mdl") end self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) local phys = self:GetPhysicsObject() self:NextThink( CurTime() + 1 ) if (phys:IsValid()) then phys:Wake() phys:SetMass(10) end for k,v in pairs(self.HitSounds) do for i,o in pairs(v) do util.PrecacheSound(o) end end local bounds = self:OBBMaxs()-self:OBBMins() if bounds.z>bounds.x and bounds.z>bounds.y then self.up = true elseif bounds.y>bounds.x and bounds.y>bounds.z then self.right = true end self:SetUseType(SIMPLE_USE) self:SetOwner(nil) end function ENT:Think() self.dietime = self.dietime or CurTime() + 30 if CurTime() > self.dietime then self:Remove() end end function ENT:DCol() self.dietime = CurTime() + 60 self:GetPhysicsObject():EnableMotion(false) self:SetCollisionGroup(COLLISION_GROUP_WEAPON) end function ENT:PhysicsCollide(data, phys) local fwdang = self:GetAngles() local fwdvec if self.up then fwdvec = fwdang:Up() elseif self.right then fwdvec = fwdang:Right() else fwdvec = fwdang:Forward() end local ent = data.HitEntity if !IsValid(ent) and !(ent and ent:IsWorld() )then return end local dmg = self:GetNWInt("Damage",40)*math.sqrt(data.Speed/1500) if dmg>5 and ent and !ent:IsWorld() then local dmginfo = DamageInfo() dmginfo:SetDamage( dmg) dmginfo:SetDamagePosition(data.HitPos) dmginfo:SetDamageForce(data.OurOldVelocity) dmginfo:SetInflictor(self) dmginfo:SetDamageType(DMG_SLASH) local att = self:GetPhysicsAttacker() if !IsValid(att) then att = self.Owner end if !IsValid(att) then att = self end dmginfo:SetAttacker(att) ent:TakeDamageInfo(dmginfo) end local traceres = util.QuickTrace(self:GetPos(),data.OurOldVelocity,self) if !traceres.HitPos then return end if data.Speed>50 then local soundtbl if self.HitSounds[traceres.MatType] then soundtbl = self.HitSounds[traceres.MatType] else soundtbl = self.HitSounds[MAT_DEF] end local snd = soundtbl[math.random(1,#soundtbl)] self:EmitSound( snd ) end local dp = traceres.HitNormal:Dot(fwdvec) if dp>=-0.3 then local fx = EffectData() fx:SetOrigin(data.HitPos) fx:SetMagnitude(1) fx:SetScale( ( data.Speed/1500 * (dp+0.6) )/5 ) util.Effect("Sparks", fx) end local canstick = data.Speed>250 and dp<(-1 + data.Speed/1000*0.3) if ent:IsWorld() and canstick then util.Decal("ManhackCut", traceres.HitPos + traceres.HitNormal, traceres.HitPos - traceres.HitNormal) self:EmitSound(self.Shink) self:SetPos(traceres.HitPos + traceres.HitNormal * 12) local tmpang = data.HitNormal:Angle() tmpang:RotateAroundAxis(tmpang:Right(),270) --self:SetAngles(tmpang) local fx = EffectData() fx:SetOrigin(data.HitPos) fx:SetMagnitude(2) fx:SetScale( 0.1 ) util.Effect("Sparks", fx) self:DCol() elseif IsValid(ent) then if not(ent:IsPlayer() or ent:IsNPC() or ent:GetClass() == "prop_ragdoll") then if canstick then util.Decal("ManhackCut", data.HitPos + data.HitNormal, data.HitPos - data.HitNormal) end self:SetCollisionGroup(COLLISION_GROUP_WEAPON) end if (ent:IsPlayer() or ent:IsNPC() or ent:GetClass() == "prop_ragdoll") then local fx = EffectData() fx:SetOrigin(data.HitPos) util.Effect("BloodImpact", fx) self:SetCollisionGroup(COLLISION_GROUP_WEAPON) self:GetPhysicsObject():SetVelocity(-(data.OurOldVelocity / 8)) end end if canstick then self:GetPhysicsObject():SetVelocity(-(data.OurOldVelocity / 16)) end self:GetPhysicsObject():AddAngleVelocity(-self:GetPhysicsObject():GetAngleVelocity()/3) end function ENT:Use(ply, caller) local ow = self.Owner if !IsValid(ow) then ow = self:GetPhysicsAttacker()end if !IsValid(ow) then return end if ow != ply then return end local classname = self:GetNWString("Wep") if !classname or classname=="" then return end if (ply:IsPlayer()) and ply:GetWeapon(classname) == NULL then ply:Give(classname) self:Remove() end end end if CLIENT then function ENT:Draw() self:DrawModel() end end
-- Global to all starfalls local checkluatype = SF.CheckLuaType local dgetmeta = debug.getmetatable local math_Clamp = math.Clamp local clamp = function(v) return math_Clamp(v, 0, 255) end local bit_rshift = bit.rshift local hex_to_rgb = { [3] = function(v) return { bit_rshift(v, 8) % 0x10 * 0x11, bit_rshift(v, 4) % 0x10 * 0x11, v % 0x10 * 0x11, 0xFF } end, [4] = function(v) return { bit_rshift(v, 12) % 0x10 * 0x11, bit_rshift(v, 8) % 0x10 * 0x11, bit_rshift(v, 4) % 0x10 * 0x11, v % 0x10 * 0x11, } end, [6] = function(v) return { bit_rshift(v, 16) % 0x100, bit_rshift(v, 8) % 0x100, v % 0x100, 0xFF } end, [8] = function(v) return { bit_rshift(v, 24) % 0x100, bit_rshift(v, 16) % 0x100, bit_rshift(v, 8) % 0x100, v % 0x100 } end, } --- Color type -- @name Color -- @class type -- @libtbl color_methods -- @libtbl color_meta SF.RegisterType("Color", nil, nil, debug.getregistry().Color, nil, function(checktype, color_meta) return function(clr) return setmetatable({ clr.r, clr.g, clr.b, clr.a }, color_meta) end, function(obj) checktype(obj, color_meta, 2) return Color((tonumber(obj[1]) or 255), (tonumber(obj[2]) or 255), (tonumber(obj[3]) or 255), (tonumber(obj[4]) or 255)) end end) return function(instance) local checkpermission = instance.player ~= SF.Superuser and SF.Permissions.check or function() end local color_methods, color_meta, cwrap, unwrap = instance.Types.Color.Methods, instance.Types.Color, instance.Types.Color.Wrap, instance.Types.Color.Unwrap local function wrap(tbl) return setmetatable(tbl, color_meta) end --- Creates a table struct that resembles a Color -- @name builtins_library.Color -- @class function -- @param number r Red or string hexadecimal color -- @param number g Green -- @param number b Blue -- @param number a Alpha -- @return Color New color function instance.env.Color(r, g, b, a) if isstring(r) then local hex = string.match(r, "^#?(%x+)$") or SF.Throw("Invalid hexadecimal color", 2) local h2r = hex_to_rgb[#hex] if h2r then return wrap(h2r(tonumber(hex, 16))) else SF.Throw("Invalid hexadecimal color length", 2) end else if r~=nil then checkluatype(r, TYPE_NUMBER) else r = 255 end if g~=nil then checkluatype(g, TYPE_NUMBER) else g = 255 end if b~=nil then checkluatype(b, TYPE_NUMBER) else b = 255 end if a~=nil then checkluatype(a, TYPE_NUMBER) else a = 255 end return wrap({ r, g, b, a }) end end -- Lookup table. -- Index 1->4 have associative rgba for use in __index. Saves lots of checks -- String based indexing returns string, just a pass through. -- Think of rgb as a template for members of Color that are expected. local rgb = { r = 1, g = 2, b = 3, a = 4, h = 1, s = 2, v = 3, l = 3 } --- Sets a value at a key in the color -- @param number|string k Key. Number or string -- @param number v Value. function color_meta.__newindex(t, k, v) if rgb[k] then rawset(t, rgb[k], v) else rawset(t, k, v) end end --- Gets a value at a key in the color -- @param number|string k Key. Number or string -- @return number Value at the index function color_meta.__index(t, k) local method = color_methods[k] if method then return method elseif rgb[k] then return rawget(t, rgb[k]) end end --- Turns the color into a string -- @return string String representation of the color function color_meta.__tostring(c) return c[1] .. " " .. c[2] .. " " .. c[3] .. " " .. c[4] end --- Concatenation metamethod -- @return string Adds two colors into one string-representation function color_meta.__concat(a, b) return tostring(a) .. tostring(b) end --- Equivalence metamethod -- @param Color c1 Initial color. -- @param Color c2 Color to check against. -- @return boolean Whether their fields are equal function color_meta.__eq(a, b) return a[1]==b[1] and a[2]==b[2] and a[3]==b[3] and a[4]==b[4] end --- Addition metamethod -- @param Color c1 Initial color. -- @param Color c2 Color to add to the first. -- @return Color Resultant color. function color_meta.__add(a, b) return wrap({ a[1] + b[1], a[2] + b[2], a[3] + b[3], a[4] + b[4] }) end --- Subtraction metamethod -- @param Color c1 Initial color. -- @param Color c2 Color to subtract. -- @return Color Resultant color. function color_meta.__sub(a, b) return wrap({ a[1]-b[1], a[2]-b[2], a[3]-b[3], a[4]-b[4] }) end --- Multiplication metamethod -- @param number|Color a Number or Color multiplicant -- @param number|Color b Number or Color multiplier -- @return Color Multiplied color. function color_meta.__mul(a, b) if isnumber(b) then return wrap({ a[1] * b, a[2] * b, a[3] * b, a[4] * b }) elseif isnumber(a) then return wrap({ b[1] * a, b[2] * a, b[3] * a, b[4] * a }) elseif dgetmeta(a) == color_meta and dgetmeta(b) == color_meta then return wrap({ a[1] * b[1], a[2] * b[2], a[3] * b[3], a[4] * b[4] }) elseif dgetmeta(a) == color_meta then checkluatype(b, TYPE_NUMBER) else checkluatype(a, TYPE_NUMBER) end end --- Division metamethod -- @param number|Color b Number or Color dividend -- @param number|Color b Number or Color divisor -- @return Color Scaled color. function color_meta.__div(a, b) if isnumber(b) then return wrap({ a[1] / b, a[2] / b, a[3] / b, a[4] / b }) elseif isnumber(a) then return wrap({ b[1] / a, b[2] / a, b[3] / a, b[4] / a }) elseif dgetmeta(a) == color_meta and dgetmeta(b) == color_meta then return wrap({ a[1] / b[1], a[2] / b[2], a[3] / b[3], a[4] / b[4] }) elseif dgetmeta(a) == color_meta then checkluatype(b, TYPE_NUMBER) else checkluatype(a, TYPE_NUMBER) end end --- Converts the color from RGB to HSV. -- @shared -- @return Color A triplet of numbers representing HSV. function color_methods:rgbToHSV() local h, s, v = ColorToHSV(self) return wrap({ h, s, v, 255 }) end --- Converts the color from HSV to RGB. -- @shared -- @return Color A triplet of numbers representing HSV. function color_methods:hsvToRGB() local rgb = HSVToColor(math.Clamp(self[1] % 360, 0, 360), math.Clamp(self[2], 0, 1), math.Clamp(self[3], 0, 1)) return wrap({ rgb.r, rgb.g, rgb.b, (rgb.a or 255) }) end --- Returns a hexadecimal string representation of the color -- @param boolean? alpha Optional boolean whether to include the alpha channel, False by default -- @return string String hexadecimal color function color_methods:toHex(alpha) if alpha~=nil then checkluatype(alpha, TYPE_BOOL) end if alpha then return string.format("%02x%02x%02x%02x", self[1], self[2], self[3], self[4]) else return string.format("%02x%02x%02x", self[1], self[2], self[3]) end end --- Round the color values. -- Self-Modifies. Does not return anything -- @param number? idp (Default 0) The integer decimal place to round to. function color_methods:round(idp) self[1] = math.Round(self[1], idp) self[2] = math.Round(self[2], idp) self[3] = math.Round(self[3], idp) self[4] = math.Round(self[4], idp) end --- Copies r,g,b,a from color and returns a new color -- @return Color The copy of the color function color_methods:clone() return wrap({ self[1], self[2], self[3], self[4] }) end --- Copies r,g,b,a from color to another. -- Self-Modifies. Does not return anything -- @param Color b The color to copy from. function color_methods:set(b) self[1] = b[1] self[2] = b[2] self[3] = b[3] self[4] = b[4] end --- Set's the color's red channel and returns self. -- @param number r The red -- @return Color Color after modification function color_methods:setR(r) self[1] = r return self end --- Set's the color's green and returns self. -- @param number g The green -- @return Color Color after modification function color_methods:setG(g) self[2] = g return self end --- Set's the color's blue and returns self. -- @param number b The blue -- @return Color Color after modification function color_methods:setB(b) self[3] = b return self end --- Set's the color's alpha and returns it. -- @param number a The alpha -- @return Color Color after modification function color_methods:setA(a) self[4] = a return self end end
Config = {} --Widoczno�� marker�w (wszystikch) Config.DrawDistance = 20.0 --Zb�dne Config.EnablePlayerManagement = false Config.EnableSocietyOwnedVehicles = false Config.MaxInService = -1 Config.Locale = 'en' --Markery Firmowe (szatnia,bossmenu) Config.MarkerType = 1 --Rodzaj markeru firmowego Config.MarkerSize = { x = 1.5, y = 1.5, z = 1.0 } --Wielko�� markeru firmowego Config.MarkerColor = { r = 102, g = 0, b = 102 } --Kolor markeru firmowego --Blipy Config.Blipikon = 478 --Tutaj ustawiamy ikonke blip�w Config.Blipwielkosc = 1.0 --Tutaj ustawiamy wielko�� blip�w Config.Blipkolor = 4 --Tutaj ustawiamy kolor blip�w ---Zarobki Config.Wyplata1 = 29000 --Tutaj ustawiamy minimaln� wyp�ate dla pracownika Config.Wyplata2 = 34000 --Tutaj ustawiamy maksymaln� wyp�at� dla pracownika --Config.WypFirma1 = 3999 --Tutaj ustawiamy minimanln� wyp�ate dla firmy --Config.WypFirma2 = 5000 --Tutaj ustawiamy maksymaln� wyp�ate dla firmy --Czasy Czynno�ci Config.Czasprzebierania = 2 --Tutaj ustawiamy czas animacji przebierania Config.Czasmaterial = 6000 --Tutaj ustawiamy czas zbierania materia�u Config.Czasszycie = 6000 --Tutaj ustawiamy czas szycia Config.Czaspako = 6000 --Tutaj ustawiamy czas pakowania Config.Czasoddam = 6000 --Tutaj ustawiamy czas sprzeda�y Config.Baza = { Cloakrooms = { Pos = {x = 1709.85, y = 4728.26, z = 42.15}, Size = {x = 5.0, y = 5.0, z = 1.0}, Color = {r = 204, g = 204, b = 0}, Name = "#1 Baza firmy", Type = 1 }, } Config.Zones = { Material = { Pos = {x = 1914.14, y = 4766.99, z = 41.95}, --Kordy zbierania materia�u -981.64 -2744.88 20.21 Size = {x = 3.0, y = 3.0, z = 1.0}, --Wielko�� markeru zbierania materia�u Color = {r = 204, g = 204, b = 0}, --Kolor markeru zbierania materia�u Name = "#2 Zbior zboza", --Nazwa blipa Type = 1 }, Szycie = { Pos = {x = 1902.83, y = 4921.83, z = 47.78}, --Kordy szycia Size = {x = 6.0, y = 6.0, z = 1.0}, --Wielko�� markeru szycia Color = {r = 204, g = 204, b = 0}, --Kolor markeru szycia Name = "#3 Przerobka zboza na make", --Nazwa blipa Type = 1 }, Pakowanie = { Pos = {x = 2242.55, y = 5153.12, z = 56.32}, --Kordy pakowania Size = {x = 6.0, y = 6.0, z = 1.0}, --Wielko�c markeru pakowania Color = {r = 204, g = 204, b = 0}, -- Kolor markeru pakowania Name = "#4 Przerobka maki na chleb", --Nazwa blipa Type = 1 }, SellFarm = { Pos = {x = 548.1, y = 2668.87, z = 42.16}, --Kordy oddawania Size = {x = 5.0, y = 5.0, z = 1.0}, --Wielko�� markeru oddawania Color = {r = 204, g = 204, b = 0}, --Kolor markeru oddawania Name = "#5 Sprzedaz chleba", --Nazwa Blipa Type = 1 }, } Config.PSM = { PSM = { Vehicles = { { Spawner = { x = 1718.93, y = 4711.06, z = 41.25 }, SpawnPoint = { x = 1721.88, y = 4701.91, z = 42.59 }, --1721.88 4701.91 42.59 271.2 Heading = 271.2 } }, PsmActions = { {x = 000.64, y = 000.88, z = 000.21}, }, Cloakrooms = { {x = 1709.85, y = 4728.26, z = 41.25}, }, VehicleDeleters = { {x = 1726.15, y = 4711.15, z = 41.25}, }, } } Config.AuthorizedVehicles = { { grade = 0, model = 'burrito3', label = 'Pojazd sluzbowy' , }, }
--[==========================================================================[ syncplay.lua: Syncplay interface module for VLC --[==========================================================================[ Principal author: Etoh Other contributors: DerGenaue, jb, Pilotat Project: https://syncplay.pl/ Version: 0.3.7 Note: * This interface module is intended to be used in conjunction with Syncplay. * Syncplay provides synchronized video playback across multiple media player instances over the net. * Syncplay allows group of people who all have the same videos to watch them together wherever they are. * Syncplay is available to download for free from https://syncplay.pl/ --[==========================================================================[ === Installation instructions === Syncplay should install this automatically to your user folder. === Commands and responses === = Note: ? denotes optional responses; * denotes mandatory response; uses \n terminator. . ? >> inputstate-change: [<input/no-input>] ? >> filepath-change-notification * >> playstate: [<playing/paused/no-input>] * >> position: [<decimal seconds/no-input>] get-interface-version * >> interface-version: [syncplay connector version] get-vlc-version * >> vlc-version: [VLC version] get-duration * >> duration: [<duration/no-input>] get-filepath * >> filepath: [<filepath/no-input>] get-filename * >> filepath: [<filename/no-input>] get-title * >> title: [<title/no-input>] set-position: [decimal seconds] ? >> play-error: no-input seek-within-title: [decimal seconds] ? >> seek-within-title-error: no-input set-playstate: [<playing/paused>] ? >> set-playstate-error: no-input set-rate: [decimal rate] ? >> set-rate-error: no-input set-title ? >> set-title-error: no-input display-osd: [placement on screen <center/left/right/top/bottom/top-left/top-right/bottom-left/bottom-right>], [duration in seconds], [message] ? >> display-osd-error: no-input display-secondary-osd: [placement on screen <center/left/right/top/bottom/top-left/top-right/bottom-left/bottom-right>], [duration in seconds], [message] ? >> display-secondary-osd-error: no-input load-file: [filepath] * >> load-file-attempted close-vlc [Unknown command] * >> [Unknown command]-error: unknown-command --]==========================================================================] local connectorversion = "0.3.7" local vlcversion = vlc.misc.version() local vlcmajorversion = tonumber(vlcversion:sub(1,1)) -- get the major version of VLC if vlcmajorversion > 3 then vlc.misc.quit() end local durationdelay = 500000 -- Pause for get_duration command etc for increased reliability (uses microseconds) local loopsleepduration = 2500 -- Pause for every event loop (uses microseconds) local quitcheckfrequency = 20 -- Check whether VLC has closed every X loops local host = "localhost" local port local titlemultiplier = 604800 -- One week local msgterminator = "\n" local msgseperator = ": " local argseperator = ", " local responsemarker = "-response" local errormarker = "-error" local notificationmarker = "-notification" local noinput = "no-input" local notimplemented = "not-implemented" local unknowncommand = "unknown-command" local unknownstream = "(Unknown Stream)" local oldfilepath local oldinputstate local newfilepath local newinputstate local oldtitle = 0 local newtitle = 0 local oldduration = 0 local newduration = 0 local channel1 local channel2 local l local running = true function radixsafe_tonumber(str) -- Version of tonumber that works with any radix character (but not thousand seperators) -- Based on the public domain VLC common.lua us_tonumber() function str = string.gsub(tostring(str), "[^0-9]", ".") local s, i, d = string.match(str, "^([+-]?)(%d*)%.?(%d*)$") if not s or not i or not d then return nil end if s == "-" then s = -1 else s = 1 end if i == "" then i = "0" end if d == nil or d == "" then d = "0" end return s * (tonumber(i) + tonumber(d)/(10^string.len(d))) end -- Start hosting Syncplay interface. port = radixsafe_tonumber(config["port"]) if (port == nil or port < 1) then port = 4123 end function quit_vlc() running = false vlc.misc.quit() end function detectchanges() -- Detects changes in VLC to report to Syncplay. -- [Used by the poll / "." command] local notificationbuffer = "" if vlc.object.input() then newinputstate = "input" newfilepath = get_filepath() if newfilepath ~= oldfilepath and get_filepath() ~= unknownstream then oldfilepath = newfilepath notificationbuffer = notificationbuffer .. "filepath-change"..notificationmarker..msgterminator end local titleerror newtitle, titleerror = get_var("title", 0) if newtitle ~= oldtitle and get_var("time", 0) > 1 then vlc.misc.mwait(vlc.misc.mdate() + durationdelay) -- Don't give new title with old time end oldtitle = newtitle notificationbuffer = notificationbuffer .. "playstate"..msgseperator..tostring(get_play_state())..msgterminator notificationbuffer = notificationbuffer .. "position"..msgseperator..tostring(get_time())..msgterminator newduration = get_duration() if oldduration ~= newduration then oldduration = newduration notificationbuffer = notificationbuffer .. "duration-change"..msgseperator..tostring(newduration)..msgterminator end else notificationbuffer = notificationbuffer .. "playstate"..msgseperator..noinput..msgterminator notificationbuffer = notificationbuffer .. "position"..msgseperator..noinput..msgterminator newinputstate = noinput end if newinputstate ~= oldinputstate then oldinputstate = newinputstate notificationbuffer = notificationbuffer.."inputstate-change"..msgseperator..tostring(newinputstate)..msgterminator end return notificationbuffer end function get_args (argument, argcount) -- Converts comma-space-seperated values into array of a given size, with last item absorbing all remaining data if needed. -- [Used by the display-osd command] local argarray = {} local index local i local argbuffer argbuffer = argument for i = 1, argcount,1 do if i == argcount then if argbuffer == nil then argarray[i] = "" else argarray[i] = argbuffer end else if string.find(argbuffer, argseperator) then index = string.find(argbuffer, argseperator) argarray[i] = string.sub(argbuffer, 0, index - 1) argbuffer = string.sub(argbuffer, index + string.len(argseperator)) else argarray[i] = "" end end end return argarray end function get_var( vartoget, fallbackvar ) -- [Used by the poll / '.' command to get time] local response local errormsg local input = vlc.object.input() if input then response = vlc.var.get(input,tostring(vartoget)) else response = fallbackvar errormsg = noinput end if vlcmajorversion > 2 and vartoget == "time" then response = response / 1000000 end return response, errormsg end function set_var(vartoset, varvalue) -- [Used by the set-time and set-rate commands] local errormsg local input = vlc.object.input() if vlcmajorversion > 2 and vartoset == "time" then varvalue = varvalue * 1000000 end if input then vlc.var.set(input,tostring(vartoset),varvalue) else errormsg = noinput end return errormsg end function get_time() local realtime, errormsg, longtime, title, titletime realtime, errormsg = get_var("time", 0) -- Seconds if errormsg ~= nil and errormsg ~= "" then return errormsg end title = get_var("title", 0) if errormsg ~= nil and errormsg ~= "" then return realtime end titletime = title * titlemultiplier -- weeks longtime = titletime + realtime return longtime end function set_time ( timetoset) local input = vlc.object.input() if input then local response, errormsg, realtime, titletrack realtime = timetoset % titlemultiplier oldtitle = radixsafe_tonumber(get_var("title", 0)) newtitle = (timetoset - realtime) / titlemultiplier if oldtitle ~= newtitle and newtitle > -1 then set_var("title", radixsafe_tonumber(newtitle)) end errormsg = set_var("time", radixsafe_tonumber(realtime)) return errormsg else return noinput end end function get_play_state() -- [Used by the get-playstate command] local response local errormsg local input = vlc.object.input() if input then response = vlc.playlist.status() else errormsg = noinput end return response, errormsg end function get_filepath () -- [Used by get-filepath command] local response local errormsg local item local input = vlc.object.input() if input then local item = vlc.input.item() if item then if string.find(item:uri(),"file://") then response = vlc.strings.decode_uri(item:uri()) elseif string.find(item:uri(),"dvd://") or string.find(item:uri(),"simpledvd://") then response = ":::DVD:::" else local metas = item:metas() if metas and metas["url"] and string.len(metas["url"]) > 0 then response = metas["url"] elseif item:uri() and string.len(item:uri()) > 0 then response = item:uri() else response = unknownstream end end else errormsg = noinput end else errormsg = noinput end return response, errormsg end function get_filename () -- [Used by get-filename command] local response local index local filename filename = errormerge(get_filepath()) if filename == unknownstream then return unknownstream end if filename == "" then local input = vlc.object.input() if input then local item = vlc.input.item() if item then if item.name then response = ":::("..item.title..")" return response end end end end if(filename ~= nil) and (filename ~= "") and (filename ~= noinput) then index = string.len(tostring(string.match(filename, ".*/"))) if string.sub(filename,1,3) == ":::" then return filename elseif index then response = string.sub(tostring(filename), index+1) end else response = noinput end return response end function get_duration () -- [Used by get-duration command] local response local errormsg local item local input = vlc.object.input() if input then local item = vlc.input.item() -- Try to get duration, which might not be available straight away local i = 0 response = 0 repeat -- vlc.misc.mwait(vlc.misc.mdate() + durationdelay) if item and item:duration() then response = item:duration() if response < 1 then response = 0 elseif string.sub(vlcversion,1,5) == "3.0.0" and response > 2147 and math.abs(response-(vlc.var.get(input,"length")/1000000)) > 5 then errormsg = "invalid-32-bit-value" end end i = i + 1 until response > 1 or i > 5 else errormsg = noinput end return response, errormsg end function display_osd ( argument ) -- [Used by display-osd command] local errormsg local osdarray local input = vlc.object.input() if input and vlc.osd and vlc.object.vout() then if not channel1 then channel1 = vlc.osd.channel_register() end if not channel2 then channel2 = vlc.osd.channel_register() end osdarray = get_args(argument,3) --position, duration, message -> message, , position, duration (converted from seconds to microseconds) local osdduration = radixsafe_tonumber(osdarray[2]) * 1000 * 1000 vlc.osd.message(osdarray[3],channel1,osdarray[1],osdduration) else errormsg = noinput end return errormsg end function display_secondary_osd ( argument ) -- [Used by display-secondary-osd command] local errormsg local osdarray local input = vlc.object.input() if input and vlc.osd and vlc.object.vout() then if not channel1 then channel1 = vlc.osd.channel_register() end if not channel2 then channel2 = vlc.osd.channel_register() end osdarray = get_args(argument,3) --position, duration, message -> message, , position, duration (converted from seconds to microseconds) local osdduration = radixsafe_tonumber(osdarray[2]) * 1000 * 1000 vlc.osd.message(osdarray[3],channel2,osdarray[1],osdduration) else errormsg = noinput end return errormsg end function load_file (filepath) -- [Used by load-file command] local uri = vlc.strings.make_uri(filepath) vlc.playlist.add({{path=uri}}) return "load-file-attempted\n" end function do_command ( command, argument) -- Processes all commands sent by Syncplay (see protocol, above). if command == "." then do return detectchanges() end end local command = tostring(command) local argument = tostring(argument) local errormsg = "" local response = "" if command == "get-interface-version" then response = "interface-version"..msgseperator..connectorversion..msgterminator elseif command == "get-vlc-version" then response = "vlc-version"..msgseperator..vlcversion..msgterminator elseif command == "get-duration" then newduration = errormerge(get_duration()) response = "duration"..msgseperator..newduration..msgterminator oldduration = newduration elseif command == "get-filepath" then response = "filepath"..msgseperator..errormerge(get_filepath())..msgterminator elseif command == "get-filename" then response = "filename"..msgseperator..errormerge(get_filename())..msgterminator elseif command == "get-title" then response = "title"..msgseperator..errormerge(get_var("title", 0))..msgterminator elseif command == "set-position" then errormsg = set_time(radixsafe_tonumber(argument)) elseif command == "seek-within-title" then errormsg = set_var("time", radixsafe_tonumber(argument)) elseif command == "set-playstate" then errormsg = set_playstate(argument) elseif command == "set-rate" then errormsg = set_var("rate", radixsafe_tonumber(argument)) elseif command == "set-title" then errormsg = set_var("title", radixsafe_tonumber(argument)) elseif command == "display-osd" then errormsg = display_osd(argument) elseif command == "display-secondary-osd" then errormsg = display_secondary_osd(argument) elseif command == "load-file" then response = load_file(argument) elseif command == "close-vlc" then quit_vlc() else errormsg = unknowncommand end if (errormsg ~= nil) and (errormsg ~= "") then response = command..errormarker..msgseperator..tostring(errormsg)..msgterminator end return response end function errormerge(argument, errormsg) -- Used to integrate 'no-input' error messages into command responses. if (errormsg ~= nil) and (errormsg ~= "") then do return errormsg end end return argument end function set_playstate(argument) -- [Used by the set-playstate command] local errormsg local input = vlc.object.input() local playstate playstate, errormsg = get_play_state() if playstate ~= "playing" then playstate = "paused" end if ((errormsg ~= noinput) and (playstate ~= argument)) then vlc.playlist.pause() end return errormsg end if string.sub(vlcversion,1,2) == "1." or string.sub(vlcversion,1,3) == "2.0" or string.sub(vlcversion,1,3) == "2.1" or string.sub(vlcversion,1,5) == "2.2.0" then vlc.msg.err("This version of VLC does not support Syncplay. Please use VLC 2.2.1+ or an alternative media player.") quit_vlc() else l = vlc.net.listen_tcp(host, port) vlc.msg.info("Hosting Syncplay interface on port: "..port) end -- main loop, which alternates between writing and reading while running == true do --accept new connections and select active clients local quitcheckcounter = 0 local fd = l:accept() local buffer, inputbuffer, responsebuffer = "", "", "" while fd >= 0 and running == true do -- handle read mode local str = vlc.net.recv ( fd, 1000) local responsebuffer if str == nil then str = "" end local safestr = string.gsub(tostring(str), "\r", "") if inputbuffer == nil then inputbuffer = "" end inputbuffer = inputbuffer .. safestr while string.find(inputbuffer, msgterminator) and running == true do local index = string.find(inputbuffer, msgterminator) local request = string.sub(inputbuffer, 0, index - 1) local command local argument inputbuffer = string.sub(inputbuffer, index + string.len(msgterminator)) if (string.find(request, msgseperator)) then index = string.find(request, msgseperator) command = string.sub(request, 0, index - 1) argument = string.sub(request, index + string.len(msgseperator)) else command = request end if (responsebuffer) then responsebuffer = responsebuffer .. do_command(command,argument) else responsebuffer = do_command(command,argument) end end if (running == false) then net.close(fd) end -- handle write mode if (responsebuffer and running == true) then vlc.net.send( fd, responsebuffer ) responsebuffer = "" end vlc.misc.mwait(vlc.misc.mdate() + loopsleepduration) -- Don't waste processor time -- check if VLC has been closed quitcheckcounter = quitcheckcounter + 1 if quitcheckcounter > quitcheckfrequency then if vlc.volume.get() == -256 then running = false end quitcheckcounter = 0 end end end
My = My or {} --- holds all fleet compositions that the player could encounter My.Encounters = {} -- fighters can occur in any composition local fighterConfigs = EnemyShipTemplates:getByClass("Fighter") local addAFighterAndCreateEncounter addAFighterAndCreateEncounter = function(fighters, maxShips) maxShips = maxShips or 5 for _, fighter in pairs(fighterConfigs) do local theFighters = Util.deepCopy(fighters) or {} table.insert(theFighters, fighter) table.insert(My.Encounters, My.Encounter(table.unpack(theFighters))) if theFighters[maxShips] == nil then addAFighterAndCreateEncounter(theFighters, maxShips) end end end addAFighterAndCreateEncounter(nil, 3) -- Rhinos do not mix, because of their special order local Rhino = EnemyShipTemplates:getByName("Rhino") table.insert(My.Encounters, My.Encounter(Rhino)) table.insert(My.Encounters, My.Encounter(Rhino, Rhino)) table.insert(My.Encounters, My.Encounter(Rhino, Rhino, Rhino)) local Crocodile = EnemyShipTemplates:getByName("Croco") local Eagle = EnemyShipTemplates:getByName("Eagle") local Falcon = EnemyShipTemplates:getByName("Falcon") local Boomalope = EnemyShipTemplates:getByName("Boomalope") local Porcupine = EnemyShipTemplates:getByName("Porcupine") local Lion = EnemyShipTemplates:getByName("Lion") local Shark = EnemyShipTemplates:getByName("Shark") local Kraken = EnemyShipTemplates:getByName("Kraken") local Tuna = EnemyShipTemplates:getByName("Tuna") table.insert(My.Encounters, My.Encounter(Crocodile, Eagle)) addAFighterAndCreateEncounter({Crocodile, Eagle}, 3) table.insert(My.Encounters, My.Encounter(Crocodile, Boomalope)) addAFighterAndCreateEncounter({Crocodile, Boomalope}, 3) table.insert(My.Encounters, My.Encounter(Crocodile, Porcupine)) addAFighterAndCreateEncounter({Crocodile, Porcupine}, 3) table.insert(My.Encounters, My.Encounter(Boomalope)) table.insert(My.Encounters, My.Encounter(Boomalope, Boomalope)) table.insert(My.Encounters, My.Encounter(Boomalope, Boomalope, Boomalope)) table.insert(My.Encounters, My.Encounter(Porcupine)) table.insert(My.Encounters, My.Encounter(Porcupine, Porcupine)) table.insert(My.Encounters, My.Encounter(Porcupine, Porcupine, Porcupine)) table.insert(My.Encounters, My.Encounter(Lion)) table.insert(My.Encounters, My.Encounter(Lion, Lion)) table.insert(My.Encounters, My.Encounter(Lion, Lion, Lion)) table.insert(My.Encounters, My.Encounter(Lion, Eagle)) table.insert(My.Encounters, My.Encounter(Lion, Lion, Falcon)) table.insert(My.Encounters, My.Encounter(Lion, Lion, Lion)) table.insert(My.Encounters, My.Encounter(Shark)) table.insert(My.Encounters, My.Encounter(Kraken)) table.insert(My.Encounters, My.Encounter(Tuna)) -- remove duplicates local knownEncounters = {} for i=Util.size(My.Encounters),1,-1 do local encounter = My.Encounters[i] local id = string.format("%s", encounter) if knownEncounters[id] ~= nil then table.remove(My.Encounters, i) else knownEncounters[id] = true end end --for _, encounter in pairs(My.Encounters) do -- logDebug(string.format("%s", encounter)) --end -- -- local count = {} for _, encounter in pairs(My.Encounters) do for _, config in pairs(encounter:getEnemyConfigs()) do count[config.class] = count[config.class] or {} count[config.class][config.name] = (count[config.class][config.name] or 0) + 1 end end for class, names in pairs(count) do print(class) for name, count in pairs(names) do print(string.format("%20s: %d", name, count)) end end
ITEM.name = "Табачные листы (привозные, 5 пакетов)" ITEM.desc = "Дорогой табак, завернутый в упаковку, судя по всему завезенный с Запада. Без каки--либо дополнительных вредных добавок, так что можно наслаждаться оригинальным вкусом самого табачного листа. \n\nХАРАКТЕРИСТИКИ: \n-слабый отравляющий эффект \n-для использования требуется: зажигалка \n-возможно закурить" ITEM.price = 7722 ITEM.weight = 0.12 ITEM.tabakAmount = 4 ITEM.model = "models/kek1ch/dev_hand_rolling_tobacco.mdl" ITEM.width = 1 ITEM.height = 1 ITEM.iconCam = { pos = Vector(0, 0, 200), ang = Angle(90, 0, 20.63694190979), fov = 2.3 } function ITEM:getDesc() local str str = self.desc.." Осталось %s." return Format(str, self:getData("tabakAmount")) end if (CLIENT) then function ITEM:paintOver(item, w, h) local tabakAmount = item:getData("tabakAmount", item.tabakAmount or 1) end end ITEM.functions.Smoke = { name = "закурить", onRun = function(item) local client = item.player if (IsValid(client) && client:Alive()) then if not client:getChar():getInv():hasItem("tinderbox") then client:notify("У вас нет зажигалки!") return false end local s = EffectData(); s:SetOrigin(client:EyePos()); util.Effect("cw_effect_smoke_cig", s); client:EmitSound("interface/inv_smoke.ogg", 50, 100) client:ScreenFade( SCREENFADE.OUT, Color( 0, 0, 0 ), 1, 3 ) timer.Simple(1,function() client:ScreenFade( SCREENFADE.IN, Color( 0, 0, 0 ), 1, 3 ) end) item:setData("tabakAmount", item:getData("tabakAmount") - 1) if item:getData("tabakAmount") < 1 then item.player:notify("Пачка пуста") return true end end return false; end, onCanRun = function(item) return (!IsValid(item.entity)) end } function ITEM:onInstanced() if not self:getData("tabakAmount") then self:setData("tabakAmount", self.tabakAmount) end end ITEM.exRender = false
function onCreate() setPropertyFromClass('GameOverSubstate', 'characterName', 'disc-bf-ded'); --Character json file for the death animation setPropertyFromClass('GameOverSubstate', 'deathSoundName', 'ded'); --put in mods/sounds/ setPropertyFromClass('GameOverSubstate', 'loopSoundName', 'silence'); --put in mods/music/ setPropertyFromClass('GameOverSubstate', 'endSoundName', 'retry'); --put in mods/music/ end local allowCountdown = false function onStartCountdown() if not allowCountdown and isStoryMode and not seenCutscene then --Block the first countdown startVideo('hecker'); allowCountdown = true; return Function_Stop; end return Function_Continue; end
local ffi = require "ffi" local lunit = require "lunitx" local capnp = require "capnp" local util = require "capnp.util" hw_capnp = require "example_capnp" --local format = string.format local tdiff = util.table_diff if _VERSION >= 'Lua 5.2' then _ENV = lunit.module('simple','seeall') else module( "simple", package.seeall, lunit.testcase ) end local copy = {} function assert_equalf(expected, actual) assert_true(math.abs(expected - actual) < 0.000001) end function test_basic_value() local data = { i0 = 32, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(data.i0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) end function test_basic_value1() local data = { b0 = true, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(true, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) end function test_basic_value2() local data = { i2 = -8, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(-8, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) end function test_basic_value3() local data = { s0 = {}, } assert_equal(152, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_not_nil(copy.s0) assert_equal(0, copy.s0.f0) assert_equal(0, copy.s0.f1) assert_nil(copy.l0) assert_nil(copy.t0) end function test_basic_value4() local data = { s0 = { f0 = 3.14, f1 = 3.1415926535 }, } assert_equal(136, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_not_nil(copy.s0) assert_equalf(3.1400001049042, copy.s0.f0) assert_equal(3.1415926535, copy.s0.f1) assert_nil(copy.l0) assert_nil(copy.t0) end function test_basic_value4() local data = { l0 = { 1, -1, 127 } } assert_equal(136, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_equal(3, #copy.l0) assert_equal(1, copy.l0[1]) assert_equal(-1, copy.l0[2]) assert_equal(127, copy.l0[3]) assert_nil(copy.t0) end function test_basic_value5() local data = { t0 = "1234567890~!#$%^&*()-=_+[]{};':|,.<>/?" } assert_equal(128 + 40, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_equal(38, #copy.t0) assert_equal("1234567890~!#$%^&*()-=_+[]{};':|,.<>/?", copy.t0) end function test_basic_value6() local data = { i0 = 32, i1 = 16, i2 = 127, b0 = true, b1 = true, i3 = 65536, e0 = "enum3", s0 = { f0 = 3.14, f1 = 3.14159265358979, }, l0 = { 28, 29 }, t0 = "hello", e1 = "enum7", } -- header + T1.size + T2.size + l0 + t0 assert_equal(16 + 112 + 24 + 8 + 8, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) util.write_file("dump", bin) copy = hw_capnp.T1.parse(bin, copy) assert_equal(32, copy.i0) assert_equal(16, copy.i1) assert_equal(127, copy.i2) assert_equal(true, copy.b0) assert_equal(true, copy.b1) assert_equal(65536, copy.i3) assert_equal("enum3", copy.e0) assert_equal("enum7", copy.e1) assert_not_nil(copy.s0) assert_equalf(3.14, copy.s0.f0) assert_equal(3.14159265358979, copy.s0.f1) assert_not_nil(copy.l0) assert_equal(2, #copy.l0) assert_equal(28, copy.l0[1]) assert_equal(29, copy.l0[2]) assert_equal(5, #copy.t0) assert_equal("hello", copy.t0) end function test_union_value() local data = { ui1 = 32, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(data.ui1, copy.ui1) assert_nil(copy.ui0) assert_nil(copy.uv0) end function test_union_value() local data = { uv0 = "Void", } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_nil(copy.ui1) assert_nil(copy.ui0) assert_equal(data.uv0, copy.uv0) end function test_union_value() local data = { g0 = { ui2 = 48, }, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(data.g0.ui2, copy.g0.ui2) end function test_union_group() local data = { u0 = { ui3 = 48, }, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(data.u0.ui3, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) end function test_union_group1() local data = { u0 = { uv1 = "Void", }, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_nil(copy.u0.ui3) assert_equal("Void", copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) end function test_union_group2() local data = { u0 = { ug0 = { ugv0 = "Void", }, }, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_nil(copy.u0.ui3) assert_nil(copy.u0.uv1) assert_equal("Void", copy.u0.ug0.ugv0) assert_equal(0, copy.u0.ug0.ugu0) assert_nil(copy.ls0) end function test_struct_list() local data = { ls0 = { { f0 = 3.14, f1 = 3.141592653589, }, { f0 = 3.14, f1 = 3.141592653589, }, }, } assert_equal(128 + 8 + 24 * 2, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(0, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_not_nil(copy.ls0[1]) assert_equalf(data.ls0[1].f0, copy.ls0[1].f0) assert_equal(data.ls0[1].f1, copy.ls0[1].f1) assert_equalf(data.ls0[2].f0, copy.ls0[2].f0) assert_equal(data.ls0[2].f1, copy.ls0[2].f1) end function test_default_value() local data = { } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(0, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) assert_equal(65535, copy.du0) -- default = 65535 end function test_default_value1() local data = { du0 = 630, } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(0, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) assert_equal(630, copy.du0) -- default = 65535 end function test_default_value2() local data = { db0 = true } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(0, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) assert_equal(65535, copy.du0) -- default = 65535 assert_equal(true, copy.db0) -- default = true end function test_reserved_word() local data = { ["end"] = true } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(0, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) assert_equal(65535, copy.du0) -- default = 65535 assert_equal(true, copy.db0) -- default = true assert_equal(true, copy["end"]) end function test_list_of_text() local data = { lt0 = { "Bach", "Mozart", "Beethoven", "Tchaikovsky", } } assert_equal(128 + 4 * 8 + 8 + 8 + 16 + 16, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal(0, copy.ui0) -- ui0 is set by default assert_nil(copy.ui1) assert_nil(copy.uv0) assert_equal(0, copy.g0.ui2) assert_equal(0, copy.u0.ui3) assert_nil(copy.u0.uv1) assert_nil(copy.u0.ug0) assert_nil(copy.ls0) assert_equal(65535, copy.du0) -- default = 65535 assert_equal(true, copy.db0) -- default = true assert_equal(false, copy["end"]) assert_not_nil(copy.lt0) assert_equal(4, #copy.lt0) assert_not_nil(copy.lt0[1]) assert_not_nil(copy.lt0[2]) assert_not_nil(copy.lt0[3]) assert_not_nil(copy.lt0[4]) assert_equal(data.lt0[1], copy.lt0[1]) assert_equal(data.lt0[2], copy.lt0[2]) assert_equal(data.lt0[3], copy.lt0[3]) assert_equal(data.lt0[4], copy.lt0[4]) end function test_const() assert_equal(3.14159, hw_capnp.pi) assert_equal("Hello", hw_capnp.T1.welcomeText) end function test_enum_literal() assert_equal(0, hw_capnp.T1.EnumType1["enum1"]) assert_equal("enum1", hw_capnp.T1.EnumType1Str[0]) assert_equal(3, hw_capnp.T1.EnumType1["wEirdENum4"]) assert_equal("wEirdENum4", hw_capnp.T1.EnumType1Str[3]) assert_equal(4, hw_capnp.T1.EnumType1["UPPER-DASH"]) assert_equal("UPPER-DASH", hw_capnp.T1.EnumType1Str[4]) end function test_imported_constant() assert_equal(1, hw_capnp.S1.flag1) assert_equal(2, hw_capnp.S1.flag2) assert_equal("Hello", hw_capnp.S1.flag3) end function test_uint64() local uint64p = ffi.new("uint64_t[?]", 1) local uint32p = ffi.cast("uint32_t *", uint64p) uint32p[0] = 1 uint32p[1] = 2 local data = { u64 = uint64p[0], } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) assert_equal("cdata", type(copy.u64)) assert_equal("8589934593ULL", tostring(copy.u64)) end function test_lower_space_naming() local data = { e1 = "lower space" } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal("lower space", copy.e1) end function test_type_check_when_calc_size() -- data type should be checked when calculating size local data = { s0 = "I should be a lua table, not a string", } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal(0, copy.i0) assert_equal(0, copy.i1) assert_equal(0, copy.i2) assert_equal(false, copy.b0) assert_equal(false, copy.b1) assert_equal(0, copy.i3) assert_equal("enum1", copy.e0) assert_equal("none", copy.e1) assert_nil(copy.s0) assert_nil(copy.l0) assert_nil(copy.t0) end function test_get_enum_from_number() local data = { e1 = 7, -- "lower space" } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal("lower space", copy.e1) end function test_unknown_enum_value() local data = { e1 = "I AM AN UNKNOWN ENUM", } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal("none", copy.e1) end function test_empty_enum_value() local data = { e1 = "", } assert_equal(128, hw_capnp.T1.calc_size(data)) local bin = hw_capnp.T1.serialize(data) copy = hw_capnp.T1.parse(bin, copy) assert_equal("none", copy.e1) end function test_list_uint16_size() local data = { ls_u16 = {1, 2, 3, 4, 5, 6, 7, 8, 9} } -- header (and root struct pointer) + 6 list pointers + round8(2 * 9) assert_equal(16 + 8 * 6 + 24, hw_capnp.T3.calc_size(data)) local data = { ls_u32 = {1, 2, 3, 4, 5, 6, 7, 8, 9} } -- header (and root struct pointer) + 6 list pointers + round8(4 * 9) assert_equal(16 + 8 * 6 + 40, hw_capnp.T3.calc_size(data)) local data = { ls_u64 = {1, 2, 3, 4, 5, 6, 7, 8, 9} } -- header (and root struct pointer) + 6 list pointers + round8(8 * 9) assert_equal(16 + 8 * 6 + 72, hw_capnp.T3.calc_size(data)) local data = { ls_i16 = {1, 2, 3, 4, 5, 6, 7, 8, 9} } -- header (and root struct pointer) + 6 list pointers + round8(2 * 9) assert_equal(16 + 8 * 6 + 24, hw_capnp.T3.calc_size(data)) local data = { ls_i32 = {1, 2, 3, 4, 5, 6, 7, 8, 9} } -- header (and root struct pointer) + 6 list pointers + round8(4 * 9) assert_equal(16 + 8 * 6 + 40, hw_capnp.T3.calc_size(data)) local data = { ls_i64 = {1, 2, 3, 4, 5, 6, 7, 8, 9} } -- header (and root struct pointer) + 6 list pointers + round8(8 * 9) assert_equal(16 + 8 * 6 + 72, hw_capnp.T3.calc_size(data)) end return _G
local Bolt = {tag="Bolt", strength=1, xPos=0, yPos=0, fR=0, sR=0, bR=0, fT=1000, sT=500, bT =500}; function Bolt:new (o) --constructor o = o or {}; setmetatable(o, self); self.__index = self; return o; end function Bolt:spawn(player, decay) if (player.shape~=nil) then local x = player.shape.x - math.cos(math.rad(player.shape.trotation)+math.pi/2)*25 local y = player.shape.y - math.sin(math.rad(player.shape.trotation)+math.pi/2)*25 self.shape = display.newImageRect( "bolt_spr.png", 30, 30 ) self.shape.x = x self.shape.y = y self.shape.pp = self; -- parent object self.shape.tag = self.tag; -- “enemy” physics.addBody(self.shape, "dynamic", {filter = {categoryBits = 2, maskBits = 12}, radius = 15 , density=1, friction=0.0, bounce=0.0 } ) self.shape.isSensor=true; self.shape.rotation = (player.shape.trotation) self.shape:setLinearVelocity(-math.cos(math.rad(self.shape.rotation)+math.pi/2)*140, -math.sin(math.rad(self.shape.rotation)+math.pi/2)*140) self.timer = timer.performWithDelay( decay, function () if(self.shape~=nil) then self:hit() end end, 3) -- print( "Player x: " .. player.x .. "\nPlayer y: " .. player.y .. "\nPlayer rotation: " .. player.rotation .. "\nAttack x_dir: " .. math.cos(self.shape.rotation)*140 .. "\nAttack y_dir: " .. math.sin(self.shape.rotation)*14`` end end function Bolt:hit () -- self.shape:setFillColor(0,0,0,0); --self.shape:setLinearVelocity(0,0); -- die display.remove( self.shape ) self.shape=nil; self = nil; end return Bolt
--[[--ldoc desc @module DialogUI @author FuYao Date 2018-10-25 ]] local ViewUI = import("framework.scenes").ViewUI local BehaviorExtend = import("framework.behavior").BehaviorExtend; local DialogUI = class("DialogUI",ViewUI); BehaviorExtend(DialogUI); function DialogUI:ctor() ViewUI.ctor(self); self:bindCtr(require(".DialogCtr")); self:init(); end function DialogUI:onCleanup() self:unBindCtr(); end function DialogUI:init() -- do something -- 加载布局文件 -- local view = self:loadLayout("aa.creator"); -- self:add(view); local tx = cc.Label:createWithSystemFont("弹窗模块","",36); tx:setPosition(display.cx,display.cy-100); self:addChild(tx); end ---刷新界面 function DialogUI:updateView(data) data = checktable(data); end return DialogUI;
local skynet = require "skynet" local Message = require "model.message" local TopicProxy = require "proxy.topic" local UserProxy = require "proxy.user" local ReplyProxy = require "proxy.reply" local Proxy = {} function Proxy.getMessagesCount(id) return Message.countDocuments({master_id = id, has_read = 0}) end function Proxy.getMessageRelations(message) if message.type == 'reply' or message.type == 'reply2' or message.type == 'at' then message.author = UserProxy.getUserById(message.author_id) message.topic = TopicProxy.getTopicById(message.topic_id) message.reply = ReplyProxy.getReplyById(message.reply_id) if not message.author or not message.topic then message.is_invalid = true end else message.is_invalid = true end end function Proxy.getMessageById(id) id = tonumber(id) if not id then return end local message = Message.findOne({id = id}) getMessageRelations(message) end function Proxy.getReadMessagesByUserId(userId) return Message.find({master_id = userId, has_read = 1},{sort = '-create_at', limit = 20}) end function Proxy.getUnreadMessageByUserId(userId) return Message.find({master_id = userId, has_read = 0},{sort = '-create_at'}) end function Proxy.updateMessagesToRead(userId, messages) if #messages == 0 then return end local ids = {} for _,m in ipairs(messages) do table.insert(ids, m.id) end local query = {master_id = userId, id = {['$in'] = ids}} Message.updateMany(query, {has_read = 1}) end function Proxy.updateOneMessageToRead(msg_id, messages) if not msg_id then return end local query = {id = msg_id} Message.updateMany(query, {has_read = 1}) end function Proxy.newAndSave(msg_type, master_id, author_id, topic_id, reply_id) local data = { type = msg_type, master_id = master_id, author_id = author_id, topic_id = topic_id, reply_id = reply_id, } local message = Message.makeModel(data) message:commit() return message end return Proxy
--[[ File: cw_card_holder/cl_init.lua Author: toneo Realm: Client This represents a card holder. ]]-- include( "shared.lua" )
--[[ Copyright (c) 2010-2014 Andreas Krinke 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 string = string local format = string.format local gmatch = string.gmatch local gsub = string.gsub local lower = string.lower local match = string.match local concat = table.concat local tonumber = tonumber local unpack = unpack return { image = { pre = [[ local Cairo = require "oocairo" return { width = $width, height = $height, render = function(cr) local temp_surface local old_cr local line_width = 1 local pattern local matrix ]], post = "end}" }, surface = { pre = [[ old_cr = cr temp_surface = Cairo.image_surface_create("argb32", $width, $height) cr = Cairo.context_create(temp_surface)]], }, fill = {post = "cr:fill_preserve()\n----------------------"}, stroke = {post = "cr:stroke_preserve()\n----------------------"}, paint = {post = "cr:paint()\n----------------------"}, mask = {}, operator = function(state, value) return format('cr:set_operator("%s")', lower(value)) end, tolerance = "cr:set_tolerance($value)", antialias = function(state, value) return format('cr:set_antialias("%s")', lower(value)) end, ["fill-rule"] = function(state, value) return format('cr:set_fill_rule("%s")', lower(gsub(value, "_", "-"))) end, ["line-width"] = "line_width = $value\ncr:set_line_width(line_width)", ["miter-limit"] = "cr:set_miter_limit($value)", ["line-cap"] = function(state, value) return format('cr:set_line_cap("%s")', lower(match(value, "_([^_]-)$"))) end, ["line-join"] = function(state, value) return format('cr:set_line_join("%s")', lower(match(value, "_([^_]-)$"))) end, linear = "pattern = Cairo.pattern_create_linear($x1, $y1, $x2, $y2)", radial = "pattern = Cairo.pattern_create_radial($x1, $y1, $r1, $x2, $y2, $r2)", solid = function(state, value) return format("pattern = Cairo.pattern_create_rgba(%s)", gsub(value, " ", ",")) end, ["color-stop"] = function(state, value) return format("pattern:add_color_stop_rgba(%s)", gsub(value, " ", ",")) end, extend = function(state, value) return format('pattern:set_extend("%s")', lower(match(value, "_(.*)"))) end, filter = function(state, value) return format('pattern:set_filter("%s")', lower(match(value, "_(.*)"))) end, ["source-pattern"] = { post = function(state, value) if state.last_environment == "surface" then return [[ cr = old_cr cr:set_source(temp_surface, 0, 0) temp_surface = nil]] else return "cr:set_source(pattern)" end end }, ["mask-pattern"] = { post = function(state, value) if state.last_environment == "surface" then return "cr:mask(temp_surface, 0, 0)" else return "cr:mask(pattern)" end end }, path = function(state, value) local s = {"cr:new_path()"} local stack = {} for x in gmatch(value, "%S+") do local n = tonumber(x) if n then stack[#stack+1] = x else if x == "m" then s[#s+1] = format("cr:move_to(%s, %s)", unpack(stack)) elseif x == "l" then s[#s+1] = format("cr:line_to(%s, %s)", unpack(stack)) elseif x == "c" then s[#s+1] = format("cr:curve_to(%s, %s, %s, %s, %s, %s)", unpack(stack)) elseif x == "h" then s[#s+1] = "cr:close_path()" end stack = {} end end return concat(s, "\n") end, matrix = function(state, value) if state.last_environment == "gradient" then return format("matrix = {%s}\npattern:set_matrix(matrix)", gsub(value, " ", ",")) else return format("cr:set_line_width(line_width * %s)", match(value, "%S+")) end end }