content
stringlengths
5
1.05M
local Class = require "Utils/Class" local UGaeaEventFunctionLibrary = _G.UGaeaEventFunctionLibrary local Logger = require "Logger/Logger" local EventHelper = require "Event/EventHelper" local function EventParamToTable(EventParam) if not EventParam then return nil end local EventParamTable = {} local Num = UGaeaEventFunctionLibrary.GetEventParamNum(EventParam) for i = 0, Num - 1 do local Element = UGaeaEventFunctionLibrary.GetEventParamByIndex(EventParam, i) local FunName = UGaeaEventFunctionLibrary.GetGFunNameByType(Element.EventParamType) local Fun = UGaeaEventFunctionLibrary[FunName] if not _G.IsCallable(Fun) then Logger.warn("EventParamToTable => Fun is not found") else local Param = Fun(Element) table.insert(EventParamTable, Param) end end return EventParamTable end local LuaDispatcherWarp = Class("LuaDispatcherWarp") local function __initWarp(self, LuaFun, SelfTable, ParamTable) self._luaFun = LuaFun self._selfTable = SelfTable self._paramTable = ParamTable end local function DelegateTrigger(self, EventParam) local Param = EventParamToTable(EventParam) if not _G.IsCallable(self._luaFun) then Logger.warn("LuaDispatcherInfo.DelegateTrigger => _luaFun is not found") else if self._selfTable then table.insert(Param, 1, self._selfTable) end table.insert(Param, self._paramTable) xpcall(self._luaFun, _G.CallBackError, table.unpack(Param)) end end LuaDispatcherWarp.__init = __initWarp LuaDispatcherWarp.DelegateTrigger = DelegateTrigger local LuaDispatcher = Class("LuaDispatcher") local function __init(self, Dispatcher) self.RawDispatcher = Dispatcher end local function Add(self, EventId, LuaFun, SelfTable, ParamTable) if type(EventId) ~= "number" then Logger.warn("LuaDispatcher:Dispatch => EventId is illegal") return end if not _G.IsValid(self.RawDispatcher) then Logger.warn("LuaDispatcher:Add => RawDispatcher is nil") return nil end local Delegate = self.RawDispatcher:GetDelegateCallBack(EventId) if not _G.IsValid(Delegate) then self.RawDispatcher:CreateDelegateCallBack(EventId) Delegate = self.RawDispatcher:GetDelegateCallBack(EventId) if not _G.IsValid(Delegate) then Logger.warn("LuaDispatcher:Add --> GetDelegateByEvent failed") return nil end end local Info = LuaDispatcherWarp(LuaFun, SelfTable, ParamTable) return EventHelper.Add(Delegate, "callback", Info.DelegateTrigger, Info) end local function Remove(self, EventId, LuaDelegate) if type(EventId) ~= "number" then Logger.warn("LuaDispatcher:Remove => EventId is illegal") return end if not _G.IsValid(self.RawDispatcher) then Logger.warn("LuaDispatcher:Remove => RawDispatcher is nil") return end local Delegate = self.RawDispatcher:GetDelegateCallBack(EventId) if not _G.IsValid(Delegate) then Logger.warn("LuaDispatcher:Remove => GetDelegateByEvent failed") return end return EventHelper.Remove(Delegate, "callback", LuaDelegate) end local function Dispatch(self, EventId, ...) if type(EventId) ~= "number" then Logger.warn("LuaDispatcher:Dispatch => EventId is illegal") return end if not _G.IsValid(self.RawDispatcher) then Logger.warn("LuaDispatcher:Dispatch => RawDispatcher is nil") return end local EventParam = {...} local EventParamTArray = UGaeaEventFunctionLibrary.ConstructEventParamTArray() for i = 1, #EventParam do local Element = EventParam[i] local ParamType = Element[1] local ParamValue = Element[2] if ParamType == nil or ParamValue == nil then Logger.warn("LuaDispatcher:Dispatch => ParamType or ParamValue is nil") return end local FunName = UGaeaEventFunctionLibrary.GetSFunNameByType(ParamType) local Fun = UGaeaEventFunctionLibrary[FunName] if not _G.IsCallable(Fun) then Logger.warn("LuaDispatcher:Dispatch => Fun is not found") else local Param = _G.FEventParam() Param = Fun(Param, ParamValue) EventParamTArray:Add(Param) end end self.RawDispatcher:DispatchImp(EventId, EventParamTArray) end LuaDispatcher.__init = __init LuaDispatcher.Add = Add LuaDispatcher.Remove = Remove LuaDispatcher.Dispatch = Dispatch return LuaDispatcher
local dht = require 'dht' local socket = require 'socket' local sock = socket.udp() sock:setsockname('*', 6881) local node = dht.node_create(nil, function(data, ip, port) sock:sendto(data, ip, port) end) node:set_bootstrap_callback(function(ready) node:get_peers('4E64AAAF48D922DBD93F8B9E4ACAA78C99BC1F40', function(infohash, peers) print(string.format('Search for %s done. Peers:', infohash)) if peers then for _, v in ipairs(peers) do print(v[1], v[2]) end end end) end) node:start() while true do local timeout = node:timeout() local t = socket.select({sock}, nil, timeout) if t[sock] then local data, ip, port = sock:receivefrom() node:input(data, ip, port) end node:work() end
-- @module lib.attacks.common local bytes = require('lib.bytes') local sorting = require('lib.sorting') local toolbox = require('lib.toolbox') local common = {} function common.break_one_char_encryption(seq) --[[ Given a byte sequence that is a result of a single character encryption -- of plaintext English, returns a list of potential candidate decodings in -- the decreasing order of likelihood. -- -- seq: Array of bytes, the ciphertext. -- return: -- - An array of pairs ((k, v), score), where k is the key, v is the decryption -- as a plaintext and score is the likelihood. The array is sorted by -- decreasing likelihood. --]] local scores = {} for i = 0, 255 do local b = {} for j = 1,#seq do table.insert(b, i) end local c = bytes.bytearrayxor(seq, b) local text = bytes.bytearray2string(c) local cur_score = toolbox.score_string_as_english(text) local index = {} index[1] = i index[2] = text scores[index] = cur_score end local kv_pairs = sorting.sort_table_by_value(scores) return kv_pairs end function common.break_k_char_encoding(seq, key_size) --[[ Given a byte sequence that is a result of a key_size character encryption -- of plaintext English, returns a list of potential candidate decodings in -- the decreasing order of likelihood. -- -- seq: Array of bytes, the ciphertext. -- return: -- - An array of pairs ((k, v), score), where k is the key, v is the decryption -- as a plaintext and score is the likelihood. The array is sorted by -- decreasing likelihood. --]] local transposed = {} for i = 1,key_size do transposed[i] = {} end for i = 1,#seq do table.insert(transposed[(i - 1) % key_size + 1], seq[i]) end local guesses = {} for i = 1,key_size do guesses[i] = common.break_one_char_encryption(transposed[i]) end local kv_pairs = {} for ind = 1,256 do -- Assemble the key and get average score. local cur_key = {} local cur_score = 0.0 for i = 1,key_size do table.insert(cur_key, guesses[i][ind][1][1]) cur_score = cur_score + guesses[i][ind][2]/key_size end -- Assemble the candidate plaintext. local plaintext = "" for l = 1,#transposed[1] do for i = 1,key_size do if l <= #transposed[i] then plaintext = plaintext .. guesses[i][ind][1][2]:sub(l,l) end end end local index = {} index[1] = cur_key index[2] = plaintext kv_pairs[#kv_pairs + 1] = {index, cur_score} end return kv_pairs end return common
#!/usr/bin/env lua5.3 local cqueues = require "cqueues" local lredis = require "lredis.cqueues" local resolver = require 'cqueues.dns.resolver' local http_server = require "http.server" local http_headers = require "http.headers" local cjson = require "cjson.safe" local cipher = require "openssl.cipher" local rand = require "openssl.rand" local hmac = require "openssl.hmac" local digest = require "openssl.digest" local sslcontext = require "openssl.ssl.context" local sslpkey = require "openssl.pkey" local x509 = require "openssl.x509" local x509chain = require "openssl.x509.chain" local b64 = require "b64" local fmt = string.format local usetls = arg[1] ~= "dev" local oplogpath = "operations.log" local tlschainpath = "fullchain.pem" local tlskeypath = "privkey.pem" local port = 8888 local cq = cqueues.new() local tlsctx = nil local testclientid = "1234567890client" local testclientpass = "clientpass" local testdeviceid = "1234567890device" local testdevicekey = {0x0c, 0xc0, 0x52, 0xf6, 0x7b, 0xbd, 0x05, 0x0e, 0x75, 0xac, 0x0d, 0x43, 0xf1, 0x0a, 0x8f, 0x35} testdevicekey = string.pack(string.rep("B",16), table.unpack(testdevicekey)) local redisaddr do local r = resolver.new({lookup = {"file"}}) local packet = r:query("redisserv") assert(packet, "Could not find redis server address") local section = packet:grep({section = "ANSWER"})() redisaddr = section:addr() end local redis = lredis.connect_tcp(redisaddr) -- load test db items if redis:call("get", "testdbitems") ~= "v3" then redis:call("flushall") redis:call("set", "clientpass:"..testclientid, testclientpass) redis:call("set", "devkeys:"..testdeviceid, testdevicekey) redis:call("sadd", "cldevops:"..testclientid..":"..testdeviceid, "lock", "unlock") redis:call("set", "testdbitems", "v3") end if usetls then -- setup TLS tlsctx = sslcontext.new("TLS", true) local keyf = assert(io.open(tlskeypath)) local key = keyf:read("a") keyf:close() local chainf = assert(io.open(tlschainpath)) local chainstr = chainf:read("a") chainf:close() local chain = x509chain.new() local cert local i = 1 while true do local ipos = chainstr:find("-----BEGIN CERTIFICATE-----", i, true) if not ipos then break end _,i = assert(chainstr:find("-----END CERTIFICATE-----", ipos, true)) local ccert = x509.new(string.sub(chainstr, ipos, i)) if not cert then cert = ccert else chain:add(ccert) end end assert(cert, "No certificate found in: " .. tlschainpath) tlsctx:setCertificate(cert) tlsctx:setCertificateChain(chain) local pkey = sslpkey.new(key, "PEM") tlsctx:setPrivateKey(pkey) end local function auth_decrypt(message, key) assert(#message >= 64, "load too small") local iv_blocks = string.sub(message, 1, -33) local messagehmac = string.sub(message, -32) assert(hmac.new(key, "sha256"):final(iv_blocks) == messagehmac, "invalid HMAC") local iv = string.sub(iv_blocks, 1, 16) local ciphertext = string.sub(iv_blocks, 17, -1) local aes = cipher.new("AES-128-CBC") aes:decrypt(key, iv, false) return aes:final(ciphertext) end local function auth_encrypt(plain, key) local rem = #plain % 16 plain = plain .. string.rep(' ', rem == 0 and 0 or 16 - rem) local aes = cipher.new("AES-128-CBC") local iv = rand.bytes(16) aes:encrypt(key, iv, false) local ivaes = iv .. aes:final(plain) return ivaes .. hmac.new(key, "sha256"):final(ivaes) end local function make_authopmsg(operation, key, N1, N2) local t = { OP = operation, N1 = N1, N2 = N2 } return b64.encode(auth_encrypt(cjson.encode(t), key)) end local function client_error(stream, res_headers) res_headers:upsert(":status", "400") assert(stream:write_headers(res_headers, true)) end local function safe_decode_load(dload) assert(#dload < 500, "device load too large") assert(not string.find(dload, "[^a-zA-Z0-9/%+=]"), "invalid base64 device load") dload = b64.decode(dload) local loadlen = #dload dload = string.sub(dload, 1, loadlen - (loadlen % 16)) return dload end local function authenticate_client(clientid, clientpass) return clientpass == redis:call("get", "clientpass:"..clientid) end local function authorize_client(clientid, deviceid, operation) local t = redis:call("smembers", "cldevops:"..clientid..":"..deviceid) for _,op in ipairs(t) do if op == operation then return true end end return false end local function get_device_key(deviceid) return redis:call("get", "devkeys:"..deviceid) end local function record_authorization(ticket, N2, clientid, deviceid, operation) redis:call("hmset", ticket, "N2", N2, "clientid", clientid, "deviceid", deviceid, "operation", operation) redis:call("expire", ticket, "120") end local function get_ticketdata(ticket) local t = redis:call("hgetall", ticket) local tt = {} for i=1,#t,2 do tt[t[i]] = t[i+1] end return tt end local function log_operation(td) local log = os.time().." cli: "..td.clientid.."; dev: "..td.deviceid.."; op: "..td.operation redis:call("rpush", "oplog", log) end local function notarize_hash(hash) -- to be implemented end -- thread that every 5 minutes saves a block of logs to disk and its hash on the blockchain local function log_notarizer() while true do cqueues.sleep(300) local all = redis:call("lrange", "oplog", "0", "-1") if #all > 1 then local block = "###BEGIN_BLOCK\n"..table.concat(all, "\n").."\n###END_BLOCK\n" local f = io.open(oplogpath, "a") f:write(block) f:close() notarize_hash(digest.new("sha256"):final(block)) redis:call("del", "oplog") end end end cq:wrap(log_notarizer) local function authorize_operation_handler(stream, res_headers) local body = stream:get_body_as_string() if not body then return client_error(stream, res_headers) end local json = cjson.decode(body) if not json then return client_error(stream, res_headers) end local clientid = json.client_id local clientpass = json.client_pass local deviceid = json.device_id local operation = json.operation local deviceload = json.load if not (clientid and deviceid and operation and deviceload and clientpass) then return client_error(stream, res_headers) end if not authenticate_client(clientid, clientpass) then res_headers:upsert(":status", "403") assert(stream:write_headers(res_headers, true)) return end if not authorize_client(clientid, deviceid, operation) then res_headers:upsert(":status", "403") assert(stream:write_headers(res_headers, true)) return end local binload = safe_decode_load(deviceload) local key = assert(get_device_key(deviceid)) local devjson = assert(cjson.decode(auth_decrypt(binload, key))) local N1 = devjson.N1 assert(N1) local ticket = string.format("%x", (string.unpack("l", rand.bytes(8)))) local N2 = string.format("%x", (string.unpack("l", rand.bytes(8)))) record_authorization(ticket, N2, clientid, deviceid, operation) local aOP = make_authopmsg(operation, key, N1, N2) local body = cjson.encode({ success = true, load = aOP, ticket = ticket }) res_headers:append(":status", "200") res_headers:append("content-type", "application/json") assert(stream:write_headers(res_headers, false)) assert(stream:write_chunk(body, true)) end local function result_handler(stream, res_headers) local body = stream:get_body_as_string() if not body then return client_error(stream, res_headers) end local json = cjson.decode(body) if not json then return client_error(stream, res_headers) end local ticket = json.ticket local deviceload = json.load if not (ticket and deviceload) then return client_error(stream, res_headers) end local ticketdata = get_ticketdata(ticket) if not ticketdata then res_headers:upsert(":status", "403") assert(stream:write_headers(res_headers, true)) return end local binload = safe_decode_load(deviceload) local key = get_device_key(ticketdata.deviceid) local devjson = assert(cjson.decode(auth_decrypt(binload, key))) local N2 = devjson.N2 local RES = devjson.RES assert(N2 == ticketdata.N2, "Invalid nonce received during confirmation") if RES then log_operation(ticketdata) end local body = cjson.encode({ success = RES }) res_headers:append(":status", "200") res_headers:append("content-type", "application/json") assert(stream:write_headers(res_headers, false)) assert(stream:write_chunk(body, true)) end local myserver = assert(http_server.listen { tls = usetls; ctx = tlsctx; host = "0.0.0.0"; port = port; cq = cq; onstream = function(myserver, stream) local req_headers = assert(stream:get_headers()) local req_method = req_headers:get ":method" local res_headers = http_headers.new() if req_method ~= "POST" then res_headers:upsert(":status", "405") assert(stream:write_headers(res_headers, true)) return end if req_headers:get(":path") == "/authorize-operation" and req_headers:get "content-type" == "application/json" then return authorize_operation_handler(stream, res_headers) elseif req_headers:get(":path") == "/result" and req_headers:get "content-type" == "application/json" then return result_handler(stream, res_headers) else res_headers:append(":status", "404") assert(stream:write_headers(res_headers, true)) end end; onerror = function(myserver, context, op, err, errno) local msg = op .. " on " .. tostring(context) .. " failed" if err then msg = msg .. ": " .. tostring(err) end assert(io.stderr:write(msg, "\n")) end; }) assert(myserver:listen()) do local bound_port = select(3, myserver:localname()) assert(io.stderr:write(string.format("Now listening on port %d\n", bound_port))) end assert(myserver:loop())
-- Déconnecte le WIFI print("\n wifi_off.lua zf180822.0959 \n") wifi.setmode(wifi.NULLMODE) --[[ print(wifi.NULLMODE, wifi.STATION, wifi.SOFTAP, wifi.STATIONAP) print(wifi.getmode()) ]]
local function noremap(mode, lhs, rhs) vim.api.nvim_set_keymap(mode, lhs, rhs, { noremap = true, silent = true }) end local function nnoremap(lhs, rhs) noremap("n", lhs, rhs) end -- Files nnoremap("<Leader>ff", "<Cmd>Telescope find_files<CR>") nnoremap("<Leader>fg", "<Cmd>Telescope live_grep<CR>") -- Git nnoremap("<Leader>gc", "<Cmd>Telescope git_commits<CR>") -- Neovim nnoremap("<Leader>fb", "<Cmd>Telescope buffers<CR>") nnoremap("<Leader>fh", "<Cmd>Telescope help_tags<CR>") nnoremap("<Leader>ts", "<Cmd>Telescope treesitter<CR>") nnoremap("<Leader>wd", "<Cmd>Telescope lsp_workspace_diagnostics<CR>")
--[[ actionObject.lua Copyright (C) 2016 Kano Computing Ltd. License: http://www.gnu.org/licenses/gpl-2.0.txt GNU GPLv2 ]]-- local Utils = require 'system.utils' local Easing = require 'libs.easing.easing' local love = love local g = love.graphics local ActionObject = {} ActionObject.__index = ActionObject -- constants local STATE_INACTIVE = 1 local STATE_ACTIVE = 2 function ActionObject.create(gameStates, objectManager) -- print("CREATING Action Object") -- DEBUG_TAG local self = setmetatable({}, ActionObject) self.gameStates = gameStates self.objectManager = objectManager self.state = STATE_INACTIVE self.type = "" -- "speech, dialogue" self.properties = {} return self end function ActionObject:load() -- print("LOADING Action Object") -- DEBUG_TAG -- Create quad self.uiElements = g_resMngr.images[g_resMngr.UI_ELEMENTS] self.w, self.h = 47, 24 self.enterQuad = g.newQuad(112, 0, self.w, self.h, Utils.getSize(self.uiElements)) end function ActionObject:update(dt) self.elapsedTime = self.elapsedTime + dt if self.vy > 0 then local ending = self.maxY - self.minY self.y = Easing.inCubic(self.elapsedTime, self.minY, ending, 0.5) else local ending = self.minY - self.maxY self.y = Easing.outCubic(self.elapsedTime, self.maxY, ending, 0.5) end -- Change direction if self.y > self.maxY or self.y < self.minY then self.vy = self.vy * -1 self.elapsedTime = 0 end end function ActionObject:draw() g.draw(self.uiElements, self.enterQuad, self.x, self.y) end function ActionObject:activate(type, x, y, ...) -- self.type = type self.state = STATE_ACTIVE self.orig = {x = x, y = y} self.vy = 1 self.elapsedTime = 0 -- local n = select('#', ...) -- number of arguments for i = 1, n do local a = select(i, ...) self.properties[i] = a end -- Position of the ENTER image self.x = x - 7 self.y = y - self.h self.minY = self.y - self.h / 4 self.maxY = self.y + self.h / 4 -- Track the interaction Utils.addInteraction() -- check if characterDialog if self.type == 'characterDialog' then self.character = self.properties[#self.properties] end end function ActionObject:deactivate() self.state = STATE_INACTIVE self.properties = {} -- notify the character of the deactivation event (restores his state) if self.type == 'characterDialog' then self.character:deactivate() end end function ActionObject:isActive() return self.state ~= STATE_INACTIVE end -- Input -------------------------------------------------------------------------------- function ActionObject:controls(isReleased, key, mousebutton) -- check for enter key or left mouse button if isReleased and (key == "return" or mousebutton == 1) then g_resMngr.playSound(g_resMngr.SFX_CONFIRM) if self.type == "bubble" then local text = self.properties[1] self.objectManager:activateBubble(self.orig.x, self.orig.y, text, true) elseif self.type == "characterDialog" or self.type == "signDialog" or self.type == "plaqueDialog" or self.type == "terminalDialog" then self.gameStates:activateDialog(self.type, unpack(self.properties)) self.gameStates:changeState(self.gameStates.STATE_LAUNCH) end self.objectManager:deactivate("action") end end return ActionObject
local resolve_relative_path = require "core.configmanager".resolve_relative_path; local logger = require "util.logger".init; local it = require "util.iterators"; local definitions = module:shared("definitions"); local active_definitions = {}; local default_chains = { preroute = { type = "event"; priority = 0.1; "pre-message/bare", "pre-message/full", "pre-message/host"; "pre-presence/bare", "pre-presence/full", "pre-presence/host"; "pre-iq/bare", "pre-iq/full", "pre-iq/host"; }; deliver = { type = "event"; priority = 0.1; "message/bare", "message/full", "message/host"; "presence/bare", "presence/full", "presence/host"; "iq/bare", "iq/full", "iq/host"; }; deliver_remote = { type = "event"; "route/remote"; priority = 0.1; }; }; local extra_chains = module:get_option("firewall_extra_chains", {}); local chains = {}; for k,v in pairs(default_chains) do chains[k] = v; end for k,v in pairs(extra_chains) do chains[k] = v; end -- Returns the input if it is safe to be used as a variable name, otherwise nil function idsafe(name) return name:match("^%a[%w_]*$") end -- Run quoted (%q) strings through this to allow them to contain code. e.g.: LOG=Received: $(stanza:top_tag()) function meta(s, extra) return (s:gsub("$(%b())", [["..tostring(%1).."]]) :gsub("$(%b<>)", function (expr) expr = expr:sub(2,-2); if expr:match("^@") then return "\"..stanza.attr["..("%q"):format(expr:sub(2)).."]..\""; end return "\"..stanza:find("..("%q"):format(expr:sub(2, -2))..")..\""; end) :gsub("$$(%a+)", extra or {}) :gsub([[^""%.%.]], "") :gsub([[%.%.""$]], "")); end -- Dependency locations: -- <type lib> -- <type global> -- function handler() -- <local deps> -- if <conditions> then -- <actions> -- end -- end local available_deps = { st = { global_code = [[local st = require "util.stanza";]]}; jid_split = { global_code = [[local jid_split = require "util.jid".split;]]; }; jid_bare = { global_code = [[local jid_bare = require "util.jid".bare;]]; }; to = { local_code = [[local to = stanza.attr.to;]] }; from = { local_code = [[local from = stanza.attr.from;]] }; type = { local_code = [[local type = stanza.attr.type;]] }; name = { local_code = [[local name = stanza.name]] }; split_to = { -- The stanza's split to address depends = { "jid_split", "to" }; local_code = [[local to_node, to_host, to_resource = jid_split(to);]]; }; split_from = { -- The stanza's split from address depends = { "jid_split", "from" }; local_code = [[local from_node, from_host, from_resource = jid_split(from);]]; }; bare_to = { depends = { "jid_bare", "to" }, local_code = "local bare_to = jid_bare(to)"}; bare_from = { depends = { "jid_bare", "from" }, local_code = "local bare_from = jid_bare(from)"}; group_contains = { global_code = [[local group_contains = module:depends("groups").group_contains]]; }; is_admin = { global_code = [[local is_admin = require "core.usermanager".is_admin]]}; core_post_stanza = { global_code = [[local core_post_stanza = prosody.core_post_stanza]] }; zone = { global_code = function (zone) assert(idsafe(zone), "Invalid zone name: "..zone); return ("local zone_%s = zones[%q] or {};"):format(zone, zone); end }; date_time = { global_code = [[local os_date = os.date]]; local_code = [[local current_date_time = os_date("*t");]] }; time = { local_code = function (what) local defs = {}; for field in what:gmatch("%a+") do table.insert(defs, ("local current_%s = current_date_time.%s;"):format(field, field)); end return table.concat(defs, " "); end, depends = { "date_time" }; }; timestamp = { global_code = [[local get_time = require "socket".gettime]]; local_code = [[local current_timestamp = get_time()]]; }; globalthrottle = { global_code = function (throttle) assert(idsafe(throttle), "Invalid rate limit name: "..throttle); assert(active_definitions.RATE[throttle], "Unknown rate limit: "..throttle); return ("local global_throttle_%s = rates.%s:single();"):format(throttle, throttle); end; }; multithrottle = { global_code = function (throttle) assert(pcall(require, "util.cache"), "Using LIMIT with 'on' requires Prosody 0.10 or higher"); assert(idsafe(throttle), "Invalid rate limit name: "..throttle); assert(active_definitions.RATE[throttle], "Unknown rate limit: "..throttle); return ("local multi_throttle_%s = rates.%s:multi();"):format(throttle, throttle); end; }; }; local function include_dep(dependency, code) local dep, dep_param = dependency:match("^([^:]+):?(.*)$"); local dep_info = available_deps[dep]; if not dep_info then module:log("error", "Dependency not found: %s", dep); return; end if code.included_deps[dep] then if code.included_deps[dep] ~= true then module:log("error", "Circular dependency on %s", dep); end return; end code.included_deps[dep] = false; -- Pending flag (used to detect circular references) for _, dep_dep in ipairs(dep_info.depends or {}) do include_dep(dep_dep, code); end if dep_info.global_code then if dep_param ~= "" then table.insert(code.global_header, dep_info.global_code(dep_param)); else table.insert(code.global_header, dep_info.global_code); end end if dep_info.local_code then if dep_param ~= "" then table.insert(code, "\n\t\t-- "..dep.."\n\t\t"..dep_info.local_code(dep_param).."\n"); else table.insert(code, "\n\t\t-- "..dep.."\n\t\t"..dep_info.local_code.."\n"); end end code.included_deps[dep] = true; end local definition_handlers = module:require("definitions"); local condition_handlers = module:require("conditions"); local action_handlers = module:require("actions"); local function new_rule(ruleset, chain) assert(chain, "no chain specified"); local rule = { conditions = {}, actions = {}, deps = {} }; table.insert(ruleset[chain], rule); return rule; end local function parse_firewall_rules(filename) local line_no = 0; local function errmsg(err) return "Error compiling "..filename.." on line "..line_no..": "..err; end local ruleset = { deliver = {}; }; local chain = "deliver"; -- Default chain local rule; local file, err = io.open(filename); if not file then return nil, err; end local state; -- nil -> "rules" -> "actions" -> nil -> ... local line_hold; for line in file:lines() do line = line:match("^%s*(.-)%s*$"); if line_hold and line:sub(-1,-1) ~= "\\" then line = line_hold..line; line_hold = nil; elseif line:sub(-1,-1) == "\\" then line_hold = (line_hold or "")..line:sub(1,-2); end line_no = line_no + 1; if line_hold or line:find("^[#;]") then -- luacheck: ignore 542 -- No action; comment or partial line elseif line == "" then if state == "rules" then return nil, ("Expected an action on line %d for preceding criteria") :format(line_no); end state = nil; elseif not(state) and line:sub(1, 2) == "::" then chain = line:gsub("^::%s*", ""); local chain_info = chains[chain]; if not chain_info then return nil, errmsg("Unknown chain: "..chain); elseif chain_info.type ~= "event" then return nil, errmsg("Only event chains supported at the moment"); end ruleset[chain] = ruleset[chain] or {}; elseif not(state) and line:sub(1,1) == "%" then -- Definition (zone, limit, etc.) local what, name = line:match("^%%%s*(%w+) +([^ :]+)"); if not definition_handlers[what] then return nil, errmsg("Definition of unknown object: "..what); elseif not name or not idsafe(name) then return nil, errmsg("Invalid "..what.." name"); end local val = line:match(": ?(.*)$"); if not val and line:find(":<") then -- Read from file local fn = line:match(":< ?(.-)%s*$"); if not fn then return nil, errmsg("Unable to parse filename"); end local f, err = io.open(fn); if not f then return nil, errmsg(err); end val = f:read("*a"):gsub("\r?\n", " "):gsub("%s+5", ""); end if not val then return nil, errmsg("No value given for definition"); end local ok, ret = pcall(definition_handlers[what], name, val); if not ok then return nil, errmsg(ret); end if not active_definitions[what] then active_definitions[what] = {}; end active_definitions[what][name] = ret; elseif line:find("^[^%s:]+[%.=]") then -- Action if state == nil then -- This is a standalone action with no conditions rule = new_rule(ruleset, chain); end state = "actions"; -- Action handlers? local action = line:match("^[%w_]+"); if not action_handlers[action] then return nil, ("Unknown action on line %d: %s"):format(line_no, action or "<unknown>"); end table.insert(rule.actions, "-- "..line) local ok, action_string, action_deps = pcall(action_handlers[action], line:match("=(.+)$")); if not ok then return nil, errmsg(action_string); end table.insert(rule.actions, action_string); for _, dep in ipairs(action_deps or {}) do table.insert(rule.deps, dep); end elseif state == "actions" then -- state is actions but action pattern did not match state = nil; -- Awaiting next rule, etc. table.insert(ruleset[chain], rule); rule = nil; else if not state then state = "rules"; rule = new_rule(ruleset, chain); end -- Check standard modifiers for the condition (e.g. NOT) local negated; local condition = line:match("^[^:=%.]*"); if condition:find("%f[%w]NOT%f[^%w]") then local s, e = condition:match("%f[%w]()NOT()%f[^%w]"); condition = (condition:sub(1,s-1)..condition:sub(e+1, -1)):match("^%s*(.-)%s*$"); negated = true; end condition = condition:gsub(" ", "_"); if not condition_handlers[condition] then return nil, ("Unknown condition on line %d: %s"):format(line_no, (condition:gsub("_", " "))); end -- Get the code for this condition local ok, condition_code, condition_deps = pcall(condition_handlers[condition], line:match(":%s?(.+)$")); if not ok then return nil, errmsg(condition_code); end if negated then condition_code = "not("..condition_code..")"; end table.insert(rule.conditions, condition_code); for _, dep in ipairs(condition_deps or {}) do table.insert(rule.deps, dep); end end end return ruleset; end local function process_firewall_rules(ruleset) -- Compile ruleset and return complete code local chain_handlers = {}; -- Loop through the chains in the parsed ruleset (e.g. incoming, outgoing) for chain_name, rules in pairs(ruleset) do local code = { included_deps = {}, global_header = {} }; local condition_uses = {}; -- This inner loop assumes chain is an event-based, not a filter-based -- chain (filter-based will be added later) for _, rule in ipairs(rules) do for _, condition in ipairs(rule.conditions) do if condition:find("^not%(.+%)$") then condition = condition:match("^not%((.+)%)$"); end condition_uses[condition] = (condition_uses[condition] or 0) + 1; end end local condition_cache, n_conditions = {}, 0; for _, rule in ipairs(rules) do for _, dep in ipairs(rule.deps) do include_dep(dep, code); end table.insert(code, "\n\t\t"); local rule_code; if #rule.conditions > 0 then for i, condition in ipairs(rule.conditions) do local negated = condition:match("^not%(.+%)$"); if negated then condition = condition:match("^not%((.+)%)$"); end if condition_uses[condition] > 1 then local name = condition_cache[condition]; if not name then n_conditions = n_conditions + 1; name = "condition"..n_conditions; condition_cache[condition] = name; table.insert(code, "local "..name.." = "..condition..";\n\t\t"); end rule.conditions[i] = (negated and "not(" or "")..name..(negated and ")" or ""); else rule.conditions[i] = (negated and "not(" or "(")..condition..")"; end end rule_code = "if "..table.concat(rule.conditions, " and ").." then\n\t\t\t" ..table.concat(rule.actions, "\n\t\t\t") .."\n\t\tend\n"; else rule_code = table.concat(rule.actions, "\n\t\t"); end table.insert(code, rule_code); end for name in pairs(definition_handlers) do table.insert(code.global_header, 1, "local "..name:lower().."s = definitions."..name..";"); end local code_string = "return function (definitions, fire_event, log)\n\t" ..table.concat(code.global_header, "\n\t") .."\n\tlocal db = require 'util.debug';\n\n\t" .."return function (event)\n\t\t" .."local stanza, session = event.stanza, event.origin;\n" ..table.concat(code, "") .."\n\tend;\nend"; chain_handlers[chain_name] = code_string; end return chain_handlers; end local function compile_firewall_rules(filename) local ruleset, err = parse_firewall_rules(filename); if not ruleset then return nil, err; end local chain_handlers = process_firewall_rules(ruleset); return chain_handlers; end local function compile_handler(code_string, filename) -- Prepare event handler function local chunk, err = loadstring(code_string, "="..filename); if not chunk then return nil, "Error compiling (probably a compiler bug, please report): "..err; end local function fire_event(name, data) return module:fire_event(name, data); end chunk = chunk()(active_definitions, fire_event, logger(filename)); -- Returns event handler with 'zones' upvalue. return chunk; end function module.load() if not prosody.arg then return end -- Don't run in prosodyctl active_definitions = {}; local firewall_scripts = module:get_option_set("firewall_scripts", {}); for script in firewall_scripts do script = resolve_relative_path(prosody.paths.config, script); local chain_functions, err = compile_firewall_rules(script) if not chain_functions then module:log("error", "Error compiling %s: %s", script, err or "unknown error"); else for chain, handler_code in pairs(chain_functions) do local handler, err = compile_handler(handler_code, "mod_firewall::"..chain); if not handler then module:log("error", "Compilation error for %s: %s", script, err); else local chain_definition = chains[chain]; if chain_definition and chain_definition.type == "event" then for _, event_name in ipairs(chain_definition) do module:hook(event_name, handler, chain_definition.priority); end elseif not chain:sub(1, 5) == "user/" then module:log("warn", "Unknown chain %q", chain); end module:hook("firewall/chains/"..chain, handler); end end end end -- Replace contents of definitions table (shared) with active definitions for k in it.keys(definitions) do definitions[k] = nil; end for k,v in pairs(active_definitions) do definitions[k] = v; end end function module.command(arg) if not arg[1] or arg[1] == "--help" then require"util.prosodyctl".show_usage([[mod_firewall <firewall.pfw>]], [[Compile files with firewall rules to Lua code]]); return 1; end local verbose = arg[1] == "-v"; if verbose then table.remove(arg, 1); end local serialize = require "util.serialization".serialize; if verbose then print("local logger = require \"util.logger\".init;"); print(); print("local function fire_event(name, data)\n\tmodule:fire_event(name, data)\nend"); print(); end for _, filename in ipairs(arg) do print("do -- File "..filename); local chain_functions = assert(compile_firewall_rules(arg[1])); if verbose then print(); print("local active_definitions = "..serialize(active_definitions)..";"); print(); end for chain, handler_code in pairs(chain_functions) do print("---- Chain "..chain:gsub("_", " ")); if not verbose then print(("%s = %s;"):format(chain, handler_code:sub(8))); else print(("local %s = (%s)(active_definitions, fire_event, logger(%q));"):format(chain, handler_code:sub(8), filename)); print(); local chain_definition = chains[chain]; if chain_definition and chain_definition.type == "event" then for _, event_name in ipairs(chain_definition) do print(("module:hook(%q, %s, %d);"):format(event_name, chain, chain_definition.priority or 0)); end end print(("module:hook(%q, %s, %d);"):format("firewall/chains/"..chain, chain, chain_definition.priority or 0)); end print("---- End of chain "..chain); print(); end print("end -- End of file "..filename); end end
local path = (...):sub(1, #(...) - #(".physics.PhysicsJson")) local JSON = require(path..".3p.JSON").new() -- new instance local Luaoop = require(path..".3p.Luaoop") local nvec = require(path..".3p.nvec") ---@type NVec ---@class L2DF.PhysicsJson local PhysicsJson = Luaoop.class("L2DF.PhysicsJson") -- JSON keys local Position = "Position" local X = "X" local Y = "Y" local Angle = "Angle" local Type = "Type" local Id = "Id" -- Meta local Meta = "Meta" local EffectiveForces = "EffectiveForces" local TotalInputCount = "TotalInputCount" local TotalOutputCount = "TotalOutputCount" local PhysicsSettingCount = "PhysicsSettingCount" local Gravity = "Gravity" local Wind = "Wind" local VertexCount = "VertexCount" -- PhysicsSettings local PhysicsSettings = "PhysicsSettings" local Normalization = "Normalization" local Minimum = "Minimum" local Maximum = "Maximum" local Default = "Default" local Reflect = "Reflect" local Weight = "Weight" -- Input local Input = "Input" local Source = "Source" -- Output local Output = "Output" local Scale = "Scale" local VertexIndex = "VertexIndex" local Destination = "Destination" -- Particle local Vertices = "Vertices" local Mobility = "Mobility" local Delay = "Delay" local Radius = "Radius" local Acceleration = "Acceleration" function PhysicsJson:__construct(jsondata) self.json = JSON:decode(jsondata) self.meta = self.json[Meta] self.effectiveForces = self.meta[EffectiveForces] self.setting = self.json[PhysicsSettings] end function PhysicsJson:getGravity() return nvec( assert(tonumber(self.effectiveForces[Gravity][X])), assert(tonumber(self.effectiveForces[Gravity][Y])) ) end function PhysicsJson:getWind() return nvec(self.effectiveForces[Wind][X], self.effectiveForces[Wind][Y]) end ---@return number function PhysicsJson:getSubRigCount() return assert(tonumber(self.meta[PhysicsSettingCount])) end ---@return number function PhysicsJson:getTotalInputCount() return assert(tonumber(self.meta[TotalInputCount])) end ---@return number function PhysicsJson:getTotalOutputCount() return assert(tonumber(self.meta[TotalOutputCount])) end ---@return number function PhysicsJson:getVertexCount() return assert(tonumber(self.meta[VertexCount])) end -- -- Input -- ---@param i number ---@return number function PhysicsJson:getNormalizationPositionMinimumValue(i) return assert(tonumber(self.setting[i][Normalization][Position][Minimum])) end ---@param i number ---@return number function PhysicsJson:getNormalizationPositionMaximumValue(i) return assert(tonumber(self.setting[i][Normalization][Position][Maximum])) end ---@param i number ---@return number function PhysicsJson:getNormalizationPositionDefaultValue(i) return assert(tonumber(self.setting[i][Normalization][Position][Default])) end ---@param i number ---@return number function PhysicsJson:getNormalizationAngleMinimumValue(i) return assert(tonumber(self.setting[i][Normalization][Angle][Minimum])) end ---@param i number ---@return number function PhysicsJson:getNormalizationAngleMaximumValue(i) return assert(tonumber(self.setting[i][Normalization][Angle][Maximum])) end ---@param i number ---@return number function PhysicsJson:getNormalizationAngleDefaultValue(i) return assert(tonumber(self.setting[i][Normalization][Angle][Default])) end ---@param i number function PhysicsJson:getInputCount(i) return #self.setting[i][Input] end ---@param i number ---@param j number ---@return number function PhysicsJson:getInputWeight(i, j) return assert(tonumber(self.setting[i][Input][j][Weight])) end ---@param i number ---@param j number ---@return boolean function PhysicsJson:getInputReflect(i, j) return not(not(self.setting[i][Input][j][Reflect])) end ---@param i number ---@param j number ---@return string function PhysicsJson:getInputType(i, j) return self.setting[i][Input][j][Type] end ---@param i number ---@param j number function PhysicsJson:getInputSourceID(i, j) return tostring(assert(self.setting[i][Input][j][Source][Id])) end -- -- Output -- ---@param i number function PhysicsJson:getOutputCount(i) return #self.setting[i][Output] end ---@param i number ---@param j number ---@return number function PhysicsJson:getOutputVertexIndex(i, j) return assert(tonumber(self.setting[i][Output][j][VertexIndex])) end ---@param i number ---@param j number ---@return number function PhysicsJson:getOutputAngleScale(i, j) return assert(tonumber(self.setting[i][Output][j][Scale])) end ---@param i number ---@param j number ---@return number function PhysicsJson:getOutputWeight(i, j) return assert(tonumber(self.setting[i][Output][j][Weight])) end ---@param i number ---@param j number function PhysicsJson:getOutputDestinationID(i, j) return tostring(assert(self.setting[i][Output][j][Destination][Id])) end ---@param i number ---@param j number function PhysicsJson:getOutputType(i, j) return tostring(assert(self.setting[i][Output][j][Type])) end ---@param i number ---@param j number ---@return boolean function PhysicsJson:getOutputReflect(i, j) return not(not(self.setting[i][Output][j][Reflect])) end -- -- Particle -- ---@param i number function PhysicsJson:getParticleCount(i) return #self.setting[i][Vertices] end ---@param i number ---@param j number ---@return number function PhysicsJson:getParticleMobility(i, j) return assert(tonumber(self.setting[i][Vertices][j][Mobility])) end ---@param i number ---@param j number ---@return number function PhysicsJson:getParticleDelay(i, j) return assert(tonumber(self.setting[i][Vertices][j][Delay])) end ---@param i number ---@param j number ---@return number function PhysicsJson:getParticleAcceleration(i, j) return assert(tonumber(self.setting[i][Vertices][j][Acceleration])) end ---@param i number ---@param j number ---@return number function PhysicsJson:getParticleRadius(i, j) return assert(tonumber(self.setting[i][Vertices][j][Radius])) end ---@param i number ---@param j number function PhysicsJson:getParticlePosition(i, j) return nvec( assert(tonumber(self.setting[i][Vertices][j][Position][X])), assert(tonumber(self.setting[i][Vertices][j][Position][Y])) ) end return PhysicsJson
local json = require("json") local zip = require("plugin.zip") local buyProductPage = {} local properties = {} function buyProductPage:render(param) print("parent mci page") print(appConfig:getTypeOperator()) ------------------------------------------------------------------------------ -- Declarations ------------------------------------------------------------------------------ local buttonTouchHandlers, textListener local requestIsValid = false local confirmIsValid = false local requestAuthenticationCodeFuc, downloadProduct, uncompressProduct local showBlur, closeBlur, changeText, callBackFunc ------------------------------------------------------------------------------ -- View Objects ------------------------------------------------------------------------------ local background = display.newImage( "images/mainBackGround.jpg") background.x = backgroundX background.y = backgroundY table.insert(properties, background) local pageTitleBackground = display.newImage("images/titleBackGround.png") pageTitleBackground.x = pageTitleBackgroundX pageTitleBackground.y = pageTitleBackgroundY pageTitleBackground.name = "pageTitle" table.insert(properties, pageTitleBackground) local pageTitle = display.newText(texts.parent.pageTitle, pageTitleX, pageTitleY, fonts.lalezar, fonts.pageTitleSize) table.insert(properties, pageTitle) local backButton = display.newImageRect( "images/back.png", 125, 125) backButton.x = backButtonX backButton.y = backButtonY backButton.name = "back" table.insert(properties, backButton) local formBackground = display.newRoundedRect( centerX, centerY, 700, 450, 15 ) formBackground:setFillColor(247 / 255, 247 / 255, 247 / 255) formBackground:setStrokeColor(0 / 255, 169 / 255, 126 / 255, 1) formBackground.strokeWidth = 10 local mobile = native.newTextField( centerX - 90, centerY - 90, 400, 70) mobile.align = "right" mobile.inputType = "number" mobile.placeholder = "09---------" local options = { text = texts.parent.mobile, x = centerX + 210, y = mobile.y, font = fonts.lalezar, fontSize = 33 } local mobileTag = display.newText(options) mobileTag:setFillColor( 80 / 255, 80 / 255, 80 / 255 ) table.insert(properties, mobile) table.insert(properties, mobileTag) local requestAuthenticationCodeBackground = display.newRoundedRect( centerX, centerY +35, 400, 80, 10) requestAuthenticationCodeBackground:setFillColor(0 / 255, 169 / 255, 126 / 255) requestAuthenticationCodeBackground.name = "requestAuthenticationCode" requestAuthenticationCodeBackground.fill.effect = "filter.grayscale" options = { text = texts.parent.requestAuthenticationCode, x = requestAuthenticationCodeBackground.x, y = requestAuthenticationCodeBackground.y, font = fonts.lalezar, fontSize = 36 } local requestAuthenticationCode = display.newText(options) table.insert(properties, requestAuthenticationCodeBackground) table.insert(properties, requestAuthenticationCode) local haveAuthenticationCodeBackground = display.newRoundedRect( centerX, centerY + 140, 400, 80, 10) haveAuthenticationCodeBackground:setFillColor(0 / 255, 169 / 255, 126 / 255) haveAuthenticationCodeBackground.name = "haveAuthenticationCode" haveAuthenticationCodeBackground.fill.effect = "filter.grayscale" options = { text = texts.parent.haveAuthenticationCode, x = haveAuthenticationCodeBackground.x, y = haveAuthenticationCodeBackground.y, font = fonts.lalezar, fontSize = 36 } local haveAuthenticationCode = display.newText(options) table.insert(properties, haveAuthenticationCodeBackground) table.insert(properties, haveAuthenticationCode) local myText = display.newText( texts.support.content, 650, 230, fonts.lalezar, 25 ) myText:setFillColor( 80 / 255, 80 / 255, 80 / 255) renderSoundButton() local hint = display.newImage("images/hint.png") hint.width, hint.height = 100, 100 hint.x = centerX + 370 hint.y = 260 hint.isVisible = false ------------------------------------------------------------------------------ -- Event Handelers ------------------------------------------------------------------------------ textListener = function( event ) if ( event.phase == "began" ) then elseif ( event.phase == "ended" or event.phase == "submitted" ) then elseif ( event.phase == "editing" ) then if mobile.text ~= "" then requestIsValid = true requestAuthenticationCodeBackground.fill.effect = nil haveAuthenticationCodeBackground.fill.effect = nil else requestIsValid = false requestAuthenticationCodeBackground.fill.effect = "filter.grayscale" haveAuthenticationCodeBackground.fill.effect = "filter.grayscale" end end end mobile:addEventListener( "userInput", textListener ) buttonTouchHandlers = function (event) if not requestIsValid and event.target.name == "requestAuthenticationCode" then return end if not requestIsValid and event.target.name == "haveAuthenticationCode" then return end if event.phase == "began" then audio.stop(clickSoundCannel) audio.play(clickSound, clickPlayOptions) event.target.width = event.target.width * clickResizeFactor event.target.height = event.target.height * clickResizeFactor if event.target.name == "chooseImage" and image then image.width = image.width * clickResizeFactor image.height = image.height * clickResizeFactor end display.getCurrentStage():setFocus( event.target ) event.target.isFocus = true end if not event.target.isFocus then return false end if event.phase == "ended" then event.target.width = event.target.width / clickResizeFactor event.target.height = event.target.height / clickResizeFactor mobileNumber = mobile.text appConfig:setParentPhone(mobileNumber) print(mobileNumber) if event.target.name == "requestAuthenticationCode" then local s = mobile.text local tempPrefix = s:sub( 0, 2 ) if string.len(mobile.text) ~= 11 and tempPrefix ~= "09" then showBlur() showTextOnBlur(texts.mobile.numChar) timer.performWithDelay(2000, delayCloseBlur, 1) mobile.text = "" return else requestAuthenticationCodeFuc() end elseif event.target.name == "haveAuthenticationCode" then navigate("submitFromMessage") elseif event.target.name == "back" then back() end event.target.isFocus = false display.getCurrentStage():setFocus(nil) end end backButton:addEventListener("touch", buttonTouchHandlers) requestAuthenticationCodeBackground:addEventListener("touch", buttonTouchHandlers) haveAuthenticationCodeBackground:addEventListener("touch", buttonTouchHandlers) ------------------------------------------------------------------------------ -- Functions ------------------------------------------------------------------------------ local blur = nil local text = nil ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ callBackFunc = function() print("navigating") navigate("submitMciInApp") end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ showTextOnBlur = function(newText) print(newText) if text then print("logging") display.remove(text) text = nil end text = display.newText({ text = newText, x = centerX, y = centerY, font = fonts.lalezar, fontSize = 46, }) print(text) text:setFillColor(1, 1, 1, 1) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ function delayCloseBlur() closeBlur() end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ function delayCloseBlurWithCB() closeBlur(true) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ closeBlur = function(triggerCallBack) print("closblur") local function removeGroup(cb1) display.remove(blur) blur = nil if text then display.remove(text) text = nil end mobile.isVisible = true if triggerCallBack then print("callback") callBackFunc() end end transition.to(blur, { alpha = 0, onComplete = removeGroup}) return true end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ showBlur = function() if blur then return end blur = display.captureScreen() blur.x, blur.y = centerX, centerY blur:setFillColor(.1, .1, .1) blur.fill.effect = "filter.blur" blur.alpha = 0 mobile.isVisible = false transition.to(blur, {alpha = 1}) blur:addEventListener("tap", function() return true end) blur:addEventListener("touch", function() return true end) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ requestAuthenticationCodeFuc = function() local function networkListener( event ) local response = json.decode(event.response) print(event) print(response) print ( "RESPONSE:33 " .. event.response ) print ( "RESPONSE:55 " .. event.status ) if ( event.isError ) then showTextOnBlur(texts.parent.problemInConnectingToServer) timer.performWithDelay( 1500, delayCloseBlur, 1) elseif ( response.status == 'POL0506' ) then print("status-POL0506") showTextOnBlur(texts.parent.sendRequstBefor) timer.performWithDelay( 1500, delayCloseBlur, 1) elseif ( response.status == 'POL0510' ) then print("POL0510") showTextOnBlur(texts.parent.shortTimeTwoRequst) timer.performWithDelay( 1500, delayCloseBlur, 1) elseif ( event.status == 200 ) then -------------------------------------------------------------------------- NEEDS CHANGING print("success &&&&&&&&&&&&&&&") showTextOnBlur(texts.parent.successfulRequest) timer.performWithDelay(1500, delayCloseBlurWithCB, 1) print(timer) else errorResponse(response) timer.performWithDelay( 1500, delayCloseBlur, 1) end end local tempUrl = { urls.requestAuthenticationCodeForParent, "?user_number=", mobile.text, urls.serviceCodeProductCode} print("zzzzzzzzzz") print( table.concat(tempUrl)) showBlur() showTextOnBlur(texts.parent.pleaseWait) network.request( table.concat(tempUrl), "POST", networkListener) end ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ end -- related to the render function ------------------------------------------------------------------------------ -- Close Method ------------------------------------------------------------------------------ function buyProductPage:close() closeSoundButton() if #properties > 0 then for n = #properties, 1, - 1 do display.remove(properties[n]) properties[n] = nil end end end return buyProductPage
--[[ © CloudSixteen.com do not share, re-distribute or modify without permission of its author (kurozael@gmail.com). --]] local ITEM = Clockwork.item:New(); ITEM.name = "ItemParacetamol"; ITEM.uniqueID = "paracetamol"; ITEM.cost = 10; ITEM.model = "models/props_junk/garbage_metalcan002a.mdl"; ITEM.weight = 0.2; ITEM.access = "1v"; ITEM.useText = "Swallow"; ITEM.category = "Medical"; ITEM.business = true; ITEM.description = "ItemParacetamolDesc"; -- Called when a player uses the item. function ITEM:OnUse(player, itemEntity) player:SetCharacterData("stamina", 100); player:BoostAttribute(self.name, ATB_STAMINA, 3, 120); end; -- Called when a player drops the item. function ITEM:OnDrop(player, position) end; ITEM:Register();
disPlayerNames = 5 --distance you see IDs at keyToToggleIDs = 19 --left alt by default playerDistances = {} showIDsAboveHead = false Citizen.CreateThread(function() while true do if IsControlJustPressed(0, keyToToggleIDs) then showIDsAboveHead = not showIDsAboveHead print("changed") Wait(50) end Wait(0) end end) Citizen.CreateThread(function() while true do for id = 0, 255 do if GetPlayerPed(id) ~= GetPlayerPed(-1) then x1, y1, z1 = table.unpack(GetEntityCoords(GetPlayerPed(-1), true)) x2, y2, z2 = table.unpack(GetEntityCoords(GetPlayerPed(id), true)) distance = math.floor(GetDistanceBetweenCoords(x1, y1, z1, x2, y2, z2, true)) playerDistances[id] = distance end end Citizen.Wait(1000) end end) Citizen.CreateThread(function() while true do if showIDsAboveHead then for id = 0, 255 do if NetworkIsPlayerActive(id) then if GetPlayerPed(id) ~= GetPlayerPed(-1) then if (playerDistances[id] < disPlayerNames) then x2, y2, z2 = table.unpack(GetEntityCoords(GetPlayerPed(id), true)) if NetworkIsPlayerTalking(id) then DrawText3D(x2, y2, z2+1, GetPlayerServerId(id), 247,124,24) else DrawText3D(x2, y2, z2+1, GetPlayerServerId(id), 255,255,255) end end end end end end Citizen.Wait(0) end end) function DrawText3D(x,y,z, text, r,g,b) local onScreen,_x,_y=World3dToScreen2d(x,y,z) local px,py,pz=table.unpack(GetGameplayCamCoords()) local dist = GetDistanceBetweenCoords(px,py,pz, x,y,z, 1) local scale = (1/dist)*2 local fov = (1/GetGameplayCamFov())*100 local scale = scale*fov if onScreen then SetTextScale(0.0*scale, 0.55*scale) SetTextFont(0) SetTextProportional(1) SetTextColour(r, g, b, 255) SetTextDropshadow(0, 0, 0, 0, 255) SetTextEdge(2, 0, 0, 0, 150) SetTextDropShadow() SetTextOutline() SetTextEntry("STRING") SetTextCentre(1) AddTextComponentString(text) DrawText(_x,_y) end end
--[[ 索引监听器 --]] local IndexListener = class("IndexListener") -- 回调:索引加载 function IndexListener:onIndexesLoaded(ipath, ivalue) end -- 回调:索引移除(可能非清空) function IndexListener:onIndexesRemoved() end return IndexListener
local luaunit = require("luaunit") local Replacer = require("collectd/monitor/config-replacer") local options = { Services = { collectd = { CommandPath = "collectd", ConfigPath = "collectd.conf", PIDPath = "collectd.pid", }, }, } TestReplacer = {} function TestReplacer:test_config_path() local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:config_path(), "collectd.conf") end function TestReplacer:test_new_config_path() local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:new_config_path(), "collectd.conf.lock") end function TestReplacer:test_old_config_path() local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:old_config_path(), "collectd.conf.orig") end function TestReplacer:test_pid_path() local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:pid_path(), "collectd.pid") end function TestReplacer:test_default_start_command() local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:start_command(), "collectd -P collectd.pid -C collectd.conf 2>&1") end function TestReplacer:test_start_command() local options = { Services = { collectd = { CommandPath = "collectd", ConfigPath = "collectd.conf", PIDPath = "collectd.pid", commands = { start = "start", }, }, }, } local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:start_command(), "start") end function TestReplacer:test_stop_command() local options = { Services = { collectd = { CommandPath = "collectd", ConfigPath = "collectd.conf", PIDPath = "collectd.pid", commands = { start = "stop", }, }, }, } local replacer = Replacer.new(0, options) luaunit.assert_equals(replacer:start_command(), "stop") end
OBJECT.Name = "Gadget" OBJECT.Creator = "Robin Wellner" OBJECT.Version = 0.0 OBJECT.Resources = { texture = "snakeface/block" } OBJECT.TextureScale = { x = 1 } OBJECT.Static = false OBJECT.Polygon = { {-.4, -.4, -.4, .4, .4, .4, .4, -.4} } function OBJECT:collision(a) end
local bu = require "spec.fixtures.balancer_utils" local helpers = require "spec.helpers" for _, strategy in helpers.each_strategy() do for mode, localhost in pairs(bu.localhosts) do describe("Balancing with consistent hashing #" .. mode, function() local bp describe("over multiple targets", function() lazy_setup(function() bp = bu.get_db_utils_for_dc_and_admin_api(strategy, { "routes", "services", "plugins", "upstreams", "targets", }) assert(helpers.start_kong({ database = strategy, nginx_conf = "spec/fixtures/custom_nginx.template", db_update_frequency = 0.1, }, nil, nil, nil)) end) lazy_teardown(function() helpers.stop_kong() end) it("hashing on header", function() local requests = bu.SLOTS * 2 -- go round the balancer twice bu.begin_testcase_setup(strategy, bp) local upstream_name, upstream_id = bu.add_upstream(bp, { hash_on = "header", hash_on_header = "hashme", }) local port1 = bu.add_target(bp, upstream_id, localhost) local port2 = bu.add_target(bp, upstream_id, localhost) local api_host = bu.add_api(bp, upstream_name) bu.end_testcase_setup(strategy, bp) -- setup target servers local server1 = bu.http_server(localhost, port1, { requests }) local server2 = bu.http_server(localhost, port2, { requests }) -- Go hit them with our test requests local oks = bu.client_requests(requests, { ["Host"] = api_host, ["hashme"] = "just a value", }) assert.are.equal(requests, oks) -- collect server results; hitcount -- one should get all the hits, the other 0 local _, count1 = server1:done() local _, count2 = server2:done() -- verify assert(count1 == 0 or count1 == requests, "counts should either get 0 or ALL hits") assert(count2 == 0 or count2 == requests, "counts should either get 0 or ALL hits") assert(count1 + count2 == requests) end) describe("hashing on cookie", function() it("does not reply with Set-Cookie if cookie is already set", function() bu.begin_testcase_setup(strategy, bp) local upstream_name, upstream_id = bu.add_upstream(bp, { hash_on = "cookie", hash_on_cookie = "hashme", }) local port = bu.add_target(bp, upstream_id, localhost) local api_host = bu.add_api(bp, upstream_name) bu.end_testcase_setup(strategy, bp) -- setup target server local server = bu.http_server(localhost, port, { 1 }) -- send request local client = helpers.proxy_client() local res = client:send { method = "GET", path = "/", headers = { ["Host"] = api_host, ["Cookie"] = "hashme=some-cookie-value", } } local set_cookie = res.headers["Set-Cookie"] client:close() server:done() -- verify assert.is_nil(set_cookie) end) it("replies with Set-Cookie if cookie is not set", function() local requests = bu.SLOTS * 2 -- go round the balancer twice bu.begin_testcase_setup(strategy, bp) local upstream_name, upstream_id = bu.add_upstream(bp, { hash_on = "cookie", hash_on_cookie = "hashme", }) local port1 = bu.add_target(bp, upstream_id, localhost) local port2 = bu.add_target(bp, upstream_id, localhost) local api_host = bu.add_api(bp, upstream_name) bu.end_testcase_setup(strategy, bp) -- setup target servers local server1 = bu.http_server(localhost, port1, { requests }) local server2 = bu.http_server(localhost, port2, { requests }) -- initial request without the `hash_on` cookie local client = helpers.proxy_client() local res = client:send { method = "GET", path = "/", headers = { ["Host"] = api_host, ["Cookie"] = "some-other-cooke=some-other-value", } } local cookie = res.headers["Set-Cookie"]:match("hashme%=(.*)%;") client:close() -- subsequent requests add the cookie that was set by the first response local oks = 1 + bu.client_requests(requests - 1, { ["Host"] = api_host, ["Cookie"] = "hashme=" .. cookie, }) assert.are.equal(requests, oks) -- collect server results; hitcount -- one should get all the hits, the other 0 local _, count1 = server1:done() local _, count2 = server2:done() -- verify assert(count1 == 0 or count1 == requests, "counts should either get 0 or ALL hits, but got " .. count1 .. " of " .. requests) assert(count2 == 0 or count2 == requests, "counts should either get 0 or ALL hits, but got " .. count2 .. " of " .. requests) assert(count1 + count2 == requests) end) end) end) end) end end
if not modules then modules = { } end modules ['sort-ini'] = { version = 1.001, comment = "companion to sort-ini.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } -- It took a while to get there, but with Fleetwood Mac's "Don't Stop" -- playing in the background we sort of got it done. --[[<p>The code here evolved from the rather old mkii approach. There we concatinate the key and (raw) entry into a new string. Numbers and special characters get some treatment so that they sort ok. In addition some normalization (lowercasing, accent stripping) takes place and again data is appended ror prepended. Eventually these strings are sorted using a regular string sorter. The relative order of character is dealt with by weighting them. It took a while to figure this all out but eventually it worked ok for most languages, given that the right datatables were provided.</p> <p>Here we do follow a similar approach but this time we don't append the manipulated keys and entries but create tables for each of them with entries being tables themselves having different properties. In these tables characters are represented by numbers and sorting takes place using these numbers. Strings are simplified using lowercasing as well as shape codes. Numbers are filtered and after getting an offset they end up at the right end of the spectrum (more clever parser will be added some day). There are definitely more solutions to the problem and it is a nice puzzle to solve.</p> <p>In the future more methods can be added, as there is practically no limit to what goes into the tables. For that we will provide hooks.</p> <p>Todo: decomposition with specific order of accents, this is relatively easy to do.</p> <p>Todo: investigate what standards and conventions there are and see how they map onto this mechanism. I've learned that users can come up with any demand so nothing here is frozen.</p> <p>Todo: I ran into the Unicode Collation document and noticed that there are some similarities (like the weights) but using that method would still demand extra code for language specifics. One option is to use the allkeys.txt file for the uc vectors but then we would also use the collapsed key (sq, code is now commented). In fact, we could just hook those into the replacer code that we reun beforehand.</p> <p>In the future index entries will become more clever, i.e. they will have language etc properties that then can be used.</p> ]]-- local gsub, rep, sub, sort, concat, tohash, format = string.gsub, string.rep, string.sub, table.sort, table.concat, table.tohash, string.format local utfbyte, utfchar, utfcharacters, utfvalues = utf.byte, utf.char, utf.characters, utf.values local next, type, tonumber, rawget, rawset = next, type, tonumber, rawget, rawset local P, Cs, R, S, lpegmatch = lpeg.P, lpeg.Cs, lpeg.R, lpeg.S, lpeg.match local allocate = utilities.storage.allocate local setmetatableindex = table.setmetatableindex local trace_tests = false trackers.register("sorters.tests", function(v) trace_tests = v end) local trace_methods = false trackers.register("sorters.methods", function(v) trace_methods = v end) local trace_orders = false trackers.register("sorters.orders", function(v) trace_orders = v end) local report_sorters = logs.reporter("languages","sorters") local comparers = { } local splitters = { } local definitions = allocate() local tracers = allocate() local ignoredoffset = 0x10000 -- frozen local replacementoffset = 0x10000 -- frozen local digitsoffset = 0x20000 -- frozen local digitsmaximum = 0xFFFFF -- frozen local lccodes = characters.lccodes local uccodes = characters.uccodes local lcchars = characters.lcchars local ucchars = characters.ucchars local shchars = characters.shchars local fscodes = characters.fscodes local fschars = characters.fschars local decomposed = characters.decomposed local variables = interfaces.variables local v_numbers = variables.numbers local v_default = variables.default local v_before = variables.before local v_after = variables.after local v_first = variables.first local v_last = variables.last local validmethods = tohash { "ch", -- raw character (for tracing) "mm", -- minus mapping "zm", -- zero mapping "pm", -- plus mapping "mc", -- lower case - 1 "zc", -- lower case "pc", -- lower case + 1 "uc", -- unicode } local predefinedmethods = { [v_default] = "zc,pc,zm,pm,uc", [v_before] = "mm,mc,uc", [v_after] = "pm,mc,uc", [v_first] = "pc,mm,uc", [v_last] = "mc,mm,uc", } sorters = { comparers = comparers, splitters = splitters, definitions = definitions, tracers = tracers, constants = { ignoredoffset = ignoredoffset, replacementoffset = replacementoffset, digitsoffset = digitsoffset, digitsmaximum = digitsmaximum, defaultlanguage = v_default, defaultmethod = v_default, defaultdigits = v_numbers, validmethods = validmethods, } } local sorters = sorters local constants = sorters.constants local data, language, method, digits local replacements, m_mappings, z_mappings, p_mappings, entries, orders, lower, upper, method, sequence, usedinsequence local thefirstofsplit local mte = { -- todo: assign to t __index = function(t,k) if k and k ~= "" and utfbyte(k) < digitsoffset then -- k check really needed (see s-lan-02) local el if k then local l = lower[k] or lcchars[k] el = rawget(t,l) end if not el then local l = shchars[k] if l and l ~= k then if #l > 1 then l = sub(l,1,1) -- todo end el = rawget(t,l) if not el then l = lower[k] or lcchars[l] if l then el = rawget(t,l) end end end el = el or k end -- rawset(t,k,el) return el else -- rawset(t,k,k) end end } local noorder = false local nothing = { 0 } local function preparetables(data) local orders, lower, m_mappings, z_mappings, p_mappings = data.orders, data.lower, { }, { }, { } for i=1,#orders do local oi = orders[i] local n = { 2 * i } m_mappings[oi], z_mappings[oi], p_mappings[oi] = n, n, n end local mtm = { __index = function(t,k) local n, nn if k then if trace_orders then report_sorters("simplifing character %C",k) end local l = lower[k] or lcchars[k] if l then if trace_orders then report_sorters(" 1 lower: %C",l) end local ml = rawget(t,l) if ml then n = { } nn = 0 for i=1,#ml do nn = nn + 1 n[nn] = ml[i] + (t.__delta or 0) end if trace_orders then report_sorters(" 2 order: % t",n) end end end if not n then local s = shchars[k] -- maybe all components? if s and s ~= k then if trace_orders then report_sorters(" 3 shape: %C",s) end n = { } nn = 0 for l in utfcharacters(s) do local ml = rawget(t,l) if ml then if trace_orders then report_sorters(" 4 keep: %C",l) end if ml then for i=1,#ml do nn = nn + 1 n[nn] = ml[i] end end else l = lower[l] or lcchars[l] if l then if trace_orders then report_sorters(" 5 lower: %C",l) end local ml = rawget(t,l) if ml then for i=1,#ml do nn = nn + 1 n[nn] = ml[i] + (t.__delta or 0) end end end end end else -- this is a kind of last resort branch that we might want to revise -- one day -- -- local b = utfbyte(k) -- n = decomposed[b] or { b } -- if trace_tests then -- report_sorters(" 6 split: %s",utf.tostring(b)) -- todo -- end -- -- we need to move way above valid order (new per 2014-10-16) .. maybe we -- need to move it even more up to get numbers right (not all have orders) -- if k == "\000" then n = nothing -- shared if trace_orders then report_sorters(" 6 split: space") -- todo end else local b = 2 * #orders + utfbyte(k) n = decomposed[b] or { b } -- could be shared tables if trace_orders then report_sorters(" 6 split: %s",utf.tostring(b)) -- todo end end end if n then if trace_orders then report_sorters(" 7 order: % t",n) end else n = noorder if trace_orders then report_sorters(" 8 order: 0") end end end else n = noorder if trace_orders then report_sorters(" 9 order: 0") end end rawset(t,k,n) return n end } data.m_mappings = m_mappings data.z_mappings = z_mappings data.p_mappings = p_mappings m_mappings.__delta = -1 z_mappings.__delta = 0 p_mappings.__delta = 1 setmetatable(data.entries,mte) setmetatable(data.m_mappings,mtm) setmetatable(data.z_mappings,mtm) setmetatable(data.p_mappings,mtm) thefirstofsplit = data.firstofsplit end local function update() -- prepare parent chains, needed when new languages are added for language, data in next, definitions do local parent = data.parent or "default" if language ~= "default" then setmetatableindex(data,definitions[parent] or definitions.default) end data.language = language data.parent = parent data.m_mappings = { } -- free temp data data.z_mappings = { } -- free temp data data.p_mappings = { } -- free temp data end end local function setlanguage(l,m,d,u) -- this will become a specification table (also keep this one as it's used in manuals) language = (l ~= "" and l) or constants.defaultlanguage data = definitions[language or constants.defaultlanguage] or definitions[constants.defaultlanguage] method = (m ~= "" and m) or (data.method ~= "" and data.method) or constants.defaultmethod digits = (d ~= "" and d) or (data.digits ~= "" and data.digits) or constants.defaultdigits if trace_tests then report_sorters("setting language %a, method %a, digits %a",language,method,digits) end replacements = data.replacements entries = data.entries orders = data.orders lower = data.lower upper = data.upper preparetables(data) m_mappings = data.m_mappings z_mappings = data.z_mappings p_mappings = data.p_mappings -- method = predefinedmethods[variables[method]] or method data.method = method -- data.digits = digits -- local seq = utilities.parsers.settings_to_array(method or "") -- check the list sequence = { } local nofsequence = 0 for i=1,#seq do local s = seq[i] if validmethods[s] then nofsequence = nofsequence + 1 sequence[nofsequence] = s else report_sorters("invalid sorter method %a in %a",s,method) end end usedinsequence = tohash(sequence) data.sequence = sequence data.usedinsequence = usedinsequence -- usedinsequence.ch = true -- better just store the string if trace_tests then report_sorters("using sort sequence: % t",sequence) end -- return data end function sorters.update() update() setlanguage(language,method,numberorder) -- resync current language and method end function sorters.setlanguage(language,method,numberorder) update() setlanguage(language,method,numberorder) -- new language and method end -- tricky: { 0, 0, 0 } vs { 0, 0, 0, 0 } => longer wins and mm, pm, zm can have them -- inlining and checking first slot first doesn't speed up (the 400K complex author sort) local function basicsort(sort_a,sort_b) if sort_a and sort_b then local na = #sort_a local nb = #sort_b if na > nb then na = nb end if na > 0 then for i=1,na do local ai, bi = sort_a[i], sort_b[i] if ai > bi then return 1 elseif ai < bi then return -1 end end end end return 0 end -- todo: compile compare function local function basic(a,b) -- trace ea and eb if a == b then -- hashed (shared) entries return 0 end local ea, eb = a.split, b.split local na, nb = #ea, #eb if na == 0 and nb == 0 then -- simple variant (single word) local result = 0 for j=1,#sequence do local m = sequence[j] result = basicsort(ea[m],eb[m]) if result ~= 0 then return result end end if result == 0 then local la, lb = #ea.uc, #eb.uc if la > lb then return 1 elseif lb > la then return -1 else return 0 end else return result end else -- complex variant, used in register (multiple words) local result = 0 for i=1,nb < na and nb or na do local eai, ebi = ea[i], eb[i] for j=1,#sequence do local m = sequence[j] result = basicsort(eai[m],ebi[m]) if result ~= 0 then return result end end if result == 0 then local la, lb = #eai.uc, #ebi.uc if la > lb then return 1 elseif lb > la then return -1 end else return result end end if result ~= 0 then return result elseif na > nb then return 1 elseif nb > na then return -1 else return 0 end end end -- if we use sq: -- -- local function basic(a,b) -- trace ea and eb -- local ea, eb = a.split, b.split -- local na, nb = #ea, #eb -- if na == 0 and nb == 0 then -- -- simple variant (single word) -- return basicsort(ea.sq,eb.sq) -- else -- -- complex variant, used in register (multiple words) -- local result = 0 -- for i=1,nb < na and nb or na do -- local eai, ebi = ea[i], eb[i] -- result = basicsort(ea.sq,eb.sq) -- if result ~= 0 then -- return result -- end -- end -- if result ~= 0 then -- return result -- elseif na > nb then -- return 1 -- elseif nb > na then -- return -1 -- else -- return 0 -- end -- end -- end comparers.basic = basic function sorters.basicsorter(a,b) return basic(a,b) == -1 end local function numify(old) if digits == v_numbers then -- was swapped, fixed 2014-11-10 local new = digitsoffset + tonumber(old) -- alternatively we can create range if new > digitsmaximum then new = digitsmaximum end return utfchar(new) else return old end end local pattern = nil local function prepare() -- todo: test \Ux{hex} pattern = Cs( ( characters.tex.toutfpattern() + lpeg.patterns.whitespace / "\000" + (P("\\Ux{") / "" * ((1-P("}"))^1/function(s) return utfchar(tonumber(s,16)) end) * (P("}")/"")) + (P("\\") / "") * R("AZ")^0 * (P(-1) + #(1-R("AZ"))) + (P("\\") * P(1) * R("az","AZ")^0) / "" + S("[](){}$\"'") / "" + R("09")^1 / numify + P(1) )^0 ) return pattern end function sorters.strip(str) -- todo: only letters and such if str and str ~= "" then return lpegmatch(pattern or prepare(),str) else return "" end end local function firstofsplit(entry) -- numbers are left padded by spaces local split = entry.split if #split > 0 then split = split[1].ch else split = split.ch end local first = split and split[1] or "" if thefirstofsplit then return thefirstofsplit(first,data,entry) -- normally the first one is needed else return first, entries[first] or "\000" -- tag end end sorters.firstofsplit = firstofsplit -- for the moment we use an inefficient bunch of tables but once -- we know what combinations make sense we can optimize this function splitters.utf(str,checked) -- we could append m and u but this is cleaner, s is for tracing if #replacements > 0 then -- todo make an lpeg for this for k=1,#replacements do local v = replacements[k] str = gsub(str,v[1],v[2]) end end local m_case, z_case, p_case, m_mapping, z_mapping, p_mapping, char, byte, n = { }, { }, { }, { }, { }, { }, { }, { }, 0 local nm, nz, np = 0, 0, 0 for sc in utfcharacters(str) do local b = utfbyte(sc) if b >= digitsoffset then if n == 0 then -- we need to force number to the top z_case[1] = 0 m_case[1] = 0 p_case[1] = 0 char[1] = sc byte[1] = 0 m_mapping[1] = 0 z_mapping[1] = 0 p_mapping[1] = 0 n = 2 else n = n + 1 end z_case[n] = b m_case[n] = b p_case[n] = b char[n] = sc byte[n] = b nm = nm + 1 nz = nz + 1 np = np + 1 m_mapping[nm] = b z_mapping[nz] = b p_mapping[np] = b else n = n + 1 local l = lower[sc] l = l and utfbyte(l) or lccodes[b] or b -- local u = upper[sc] -- u = u and utfbyte(u) or uccodes[b] or b if type(l) == "table" then l = l[1] -- there are currently no tables in lccodes but it can be some, day end -- if type(u) == "table" then -- u = u[1] -- there are currently no tables in lccodes but it can be some, day -- end z_case[n] = l if l ~= b then m_case[n] = l - 1 p_case[n] = l + 1 else m_case[n] = l p_case[n] = l end char[n], byte[n] = sc, b local fs = fscodes[b] or b local msc = m_mappings[sc] if msc ~= noorder then if not msc then msc = m_mappings[fs] end for i=1,#msc do nm = nm + 1 m_mapping[nm] = msc[i] end end local zsc = z_mappings[sc] if zsc ~= noorder then if not zsc then zsc = z_mappings[fs] end for i=1,#zsc do nz = nz + 1 z_mapping[nz] = zsc[i] end end local psc = p_mappings[sc] if psc ~= noorder then if not psc then psc = p_mappings[fs] end for i=1,#psc do np = np + 1 p_mapping[np] = psc[i] end end end end -- -- only those needed that are part of a sequence -- -- local b = byte[1] -- if b then -- -- we set them to the first split code (korean) -- local fs = fscodes[b] or b -- if #m_mapping == 0 then -- m_mapping = { m_mappings[fs][1] } -- end -- if #z_mapping == 0 then -- z_mapping = { z_mappings[fs][1] } -- end -- if #p_mapping == 0 then -- p_mapping = { p_mappings[fs][1] } -- end -- end local result if checked then result = { ch = trace_tests and char or nil, -- not in sequence uc = usedinsequence.uc and byte or nil, mc = usedinsequence.mc and m_case or nil, zc = usedinsequence.zc and z_case or nil, pc = usedinsequence.pc and p_case or nil, mm = usedinsequence.mm and m_mapping or nil, zm = usedinsequence.zm and z_mapping or nil, pm = usedinsequence.pm and p_mapping or nil, } else result = { ch = char, uc = byte, mc = m_case, zc = z_case, pc = p_case, mm = m_mapping, zm = z_mapping, pm = p_mapping, } end -- local sq, n = { }, 0 -- for i=1,#byte do -- for s=1,#sequence do -- n = n + 1 -- sq[n] = result[sequence[s]][i] -- end -- end -- result.sq = sq return result end local function packch(entry) local split = entry.split if split and #split > 0 then -- useless test local t = { } for i=1,#split do local tt = { } local ch = split[i].ch for j=1,#ch do local chr = ch[j] local byt = utfbyte(chr) if byt > ignoredoffset then tt[j] = "[]" elseif byt == 0 then tt[j] = " " else tt[j] = chr end end t[i] = concat(tt) end return concat(t," + ") else local t = { } local ch = (split and split.ch) or entry.ch or entry if ch then for i=1,#ch do local chr = ch[i] local byt = utfbyte(chr) if byt > ignoredoffset then t[i] = "[]" elseif byt == 0 then t[i] = " " else t[i] = chr end end return concat(t) else return "" end end end local function packuc(entry) local split = entry.split if split and #split > 0 then -- useless test local t = { } for i=1,#split do t[i] = concat(split[i].uc, " ") -- sq end return concat(t," + ") else local uc = (split and split.uc) or entry.uc or entry if uc then return concat(uc," ") -- sq else return "" end end end sorters.packch = packch sorters.packuc = packuc function sorters.sort(entries,cmp) if trace_methods then local nofentries = #entries report_sorters("entries: %s, language: %s, method: %s, digits: %s",nofentries,language,method,tostring(digits)) for i=1,nofentries do report_sorters("entry %s",table.serialize(entries[i].split,i,true,true,true)) end end if trace_tests then sort(entries,function(a,b) local r = cmp(a,b) local e = (not r and "?") or (r<0 and "<") or (r>0 and ">") or "=" report_sorters("%s %s %s | %s %s %s",packch(a),e,packch(b),packuc(a),e,packuc(b)) return r == -1 end) local s for i=1,#entries do local entry = entries[i] local letter, first = firstofsplit(entry) if first == s then first = " " else s = first if first and letter then report_sorters(">> %C (%C)",first,letter) end end report_sorters(" %s | %s",packch(entry),packuc(entry)) end else sort(entries,function(a,b) return cmp(a,b) == -1 end) end end
dofile("../framework/framework.lua") SetupSolution("Test") SetupProject("Test", "test.cpp")
local PLUGIN = PLUGIN PLUGIN.name = "Suits" PLUGIN.author = "Subleader and Alexgrist and verne (Outfit base used)" PLUGIN.desc = "Compatible with bad air and localized damage, plus it adds damage resistance" ix.util.Include("cl_plugin.lua") ix.config.Add("disablePVP", true, "If true, disables player versus player damage.", nil, { category = "pvp" }) function PLUGIN:EntityTakeDamage( target, dmginfo ) --disable pvp if (ix.config.Get("disablePVP", true)) then if target:IsPlayer() and dmginfo:GetAttacker():IsPlayer() and (target != dmginfo:GetAttacker()) then return true end end -- Bullet resistance if ( target:IsPlayer() and dmginfo:IsDamageType(DMG_BULLET)) then local damage = dmginfo:GetDamage() local perRes = target:GetNWFloat("ixperbulletres") local flatRes = target:GetNWInt("ixflatbulletres") local suitDuraDmg = damage / 100 local suit = target:getEquippedBodyArmor() if suit != nil then suit:SetData("durability", math.Clamp(suit:GetData("durability", 100) - suitDuraDmg, 0, 100)) end damage = damage - flatRes damage = damage * perRes --Make sure we dont heal the player damage = math.max(damage,0) dmginfo:SetDamage(damage) end --Anomaly resistance local anomtypes = {} anomtypes[DMG_SHOCK] = true anomtypes[DMG_BURN] = true anomtypes[DMG_ACID] = true anomtypes[DMG_BLAST] = true anomtypes[DMG_SONIC] = true anomtypes[DMG_DROWN] = true anomtypes[DMG_POISON] = true anomtypes[DMG_NERVEGAS] = true anomtypes[DMG_SLOWBURN] = true anomtypes[DMG_GENERIC] = true if ( target:IsPlayer() and anomtypes[dmginfo:GetDamageType()]) then local damage = dmginfo:GetDamage() local perRes = target:GetNWFloat("ixperanomres") local flatRes = target:GetNWInt("ixflatanomres") local suitDuraDmg = damage / 50 local suit = target:getEquippedBodyArmor() if suit != nil then suit:SetData("durability", math.Clamp(suit:GetData("durability", 100) - suitDuraDmg, 0, 100)) end damage = damage - flatRes damage = damage * perRes --Make sure we dont heal the player damage = math.max(damage,0) dmginfo:SetDamage(damage) end end local playerMeta = FindMetaTable("Player") function playerMeta:getPercentageBulletRes() local res = 1 local char = self:GetCharacter() local items = char:GetInventory():GetItems() for k, v in pairs(items) do if (v.isBodyArmor and v:GetData("equip")) then res = v:getBR(v) end if (v.br ~= nil and !v.isBodyArmor and v:GetData("equip") == true) then res = res * (1 - v.br) end end --BUFFS GO HERE return res end function playerMeta:getFlatBulletRes() local res = 0 local char = self:GetCharacter() local items = char:GetInventory():GetItems() for k, v in pairs(items) do if (v.isBodyArmor and v:GetData("equip")) then res = res + v:getFBR(v) end if (v.fbr ~= nil and !v.isBodyArmor and v:GetData("equip") == true) then res = res + v.fbr end end --BUFFS GO HERE return res end function playerMeta:getPercentageAnomalyRes() local res = 1 local char = self:GetCharacter() local items = char:GetInventory():GetItems() for k, v in pairs(items) do if (v.isBodyArmor and v:GetData("equip")) then res = v:getAR(v) end if (v.ar ~= nil and !v.isBodyArmor and v:GetData("equip") == true) then res = res * (1 - v.ar) end end --BUFFS GO HERE return res end function playerMeta:getFlatAnomalyRes() local res = 0 local char = self:GetCharacter() local items = char:GetInventory():GetItems() for k, v in pairs(items) do if (v.isBodyArmor and v:GetData("equip")) then res = res + v:getFAR(v) end if (v.far ~= nil and !v.isBodyArmor and v:GetData("equip") == true) then res = res + v.far end end --BUFFS GO HERE return res end function playerMeta:getEquippedBodyArmor() local char = self:GetCharacter() local inventory = char:GetInventory() if inventory then local items = char:GetInventory():GetItems(true) for k, v in pairs(items) do if (v.isBodyArmor and v:GetData("equip")) then return v end end return nil end return nil end function playerMeta:getEquippedHelmet() local char = self:GetCharacter() local inventory = char:GetInventory() if inventory then local items = char:GetInventory():GetItems(true) for k, v in pairs(items) do if (v.isHelmet and v:GetData("equip")) then return v end end return nil end return nil end function playerMeta:getEquippedGasmask() local char = self:GetCharacter() local inventory = char:GetInventory() if inventory then local items = char:GetInventory():GetItems(true) for k, v in pairs(items) do if (v.isGasmask and v:GetData("equip")) then return v end end return nil end return nil end function playerMeta:RecalculateResistances() self:SetNWFloat("ixperbulletres", self:getPercentageBulletRes()) self:SetNWInt("ixflatbulletres", self:getFlatBulletRes()) self:SetNWFloat("ixperanomres", self:getPercentageAnomalyRes()) self:SetNWInt("ixflatanomres", self:getFlatAnomalyRes()) end function playerMeta:ReevaluateOverlay() local char = self:GetCharacter() local inventory = char:GetInventory() if inventory then local items = char:GetInventory():GetItems(true) for k, v in pairs(items) do if (v.overlayPath and v:GetData("equip")) then self:SetNetVar("gasmask", false) else self:SetNetVar("gasmask", true) end end end end function playerMeta:ReevaluateGasmaskDSP() if self:getEquippedGasmask() then self:SetDSP(31) end end function playerMeta:ApplyDSPGasmask() self:SetDSP(31) end function playerMeta:UnApplyDSPGasmask() self:SetDSP(1) end function PLUGIN:EntityEmitSound(sndTable) local client = sndTable.Entity if (client and IsValid(client) and client:IsPlayer() and client:GetCharacter()) then local gasmaskequip = client:getEquippedGasmask() if gasmaskequip then local sndName = sndTable.SoundName:lower() if (sndName:find("male") or sndName:find("voice")) then sndTable.DSP = 15 end return true end end end function PLUGIN:PostPlayerLoadout(client) client:RecalculateResistances() client:ReevaluateOverlay() client:ReevaluateGasmaskDSP() end
local addonName = ... Speedy = LibStub("AceAddon-3.0"):NewAddon(addonName, "AceConsole-3.0", "AceEvent-3.0") Speedy.DatabaseName = "SpeedyDB" local LibDeflate = LibStub("LibDeflate") local AceGUI = LibStub("AceGUI-3.0") -- database version local DB_VERSION = 2 -- color of console output local CHAT_COLOR = "ff82bf4c" -- TODO: handle different expansions and max levels local MAX_LEVEL = 70 -- set true to update /played time on next TIME_PLAYED_MSG event local calculateLevelTime = false -- convert integer returned from UnitSex() to description local GenderMap = { [1] = "Unknown", [2] = "Male", [3] = "Female" } local SpeedyDB_defaults = { global = { Characters = { ["*"] = { Key = nil, Realm = nil, Name = nil, Class = nil, Race = nil, Gender = nil, -- enum, need map table Level = nil, XP = nil, -- current level xp PlayedTotal = 0, -- in seconds PlayedLevel = 0, -- in seconds LastSeen = nil, -- timestamp in seconds LevelTimes = { ["*"] = { Played = nil, -- in seconds LastUpdated = nil -- timestamp in seconds } } } } } } ------------------------------------ -- base64 encode/decode functions ------------------------------------ local base64 = {} -- character table string base64.b = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" function base64:encode(data) return ((data:gsub( ".", function(x) local r, b = "", x:byte() for i = 8, 1, -1 do r = r .. (b % 2 ^ i - b % 2 ^ (i - 1) > 0 and "1" or "0") end return r end ) .. "0000"):gsub( "%d%d%d?%d?%d?%d?", function(x) if (#x < 6) then return "" end local c = 0 for i = 1, 6 do c = c + (x:sub(i, i) == "1" and 2 ^ (6 - i) or 0) end return self.b:sub(c + 1, c + 1) end ) .. ({"", "==", "="})[#data % 3 + 1]) end function base64:decode(data) data = gsub(data, "[^" .. self.b .. "=]", "") return (data:gsub( ".", function(x) if (x == "=") then return "" end local r, f = "", (self.b:find(x) - 1) for i = 6, 1, -1 do r = r .. (f % 2 ^ i - f % 2 ^ (i - 1) > 0 and "1" or "0") end return r end ):gsub( "%d%d%d?%d?%d?%d?%d?%d?", function(x) if (#x ~= 8) then return "" end local c = 0 for i = 1, 8 do c = c + (x:sub(i, i) == "1" and 2 ^ (8 - i) or 0) end return string.char(c) end )) end ------------------------------------ -- Event Handlers ------------------------------------ local function OnPlayerXPUpdate() Speedy.Character.XP = UnitXP("player") end local function OnTimePlayedMsg(_, totalTime, currentLevelTime) Speedy:UnregisterEvent("TIME_PLAYED_MSG") local char = Speedy.Character char.PlayedTotal = totalTime char.PlayedLevel = currentLevelTime -- if not max level, update played time of progressing level if char.Level ~= MAX_LEVEL then char.LevelTimes[tostring(char.Level + 1)].Played = totalTime char.LevelTimes[tostring(char.Level + 1)].LastUpdated = time() end if calculateLevelTime then char.LevelTimes[tostring(char.Level)].Played = totalTime - currentLevelTime char.LevelTimes[tostring(char.Level)].LastUpdated = time() calculateLevelTime = false end -- update XP values since we just updated time OnPlayerXPUpdate() end local function OnPlayerLevelUp(_, newLevel) Speedy.Character.Level = newLevel -- if now max level, don't need these handlers anymore if newLevel == MAX_LEVEL then Speedy:UnregisterEvent("PLAYER_LEVEL_UP") Speedy:UnregisterEvent("PLAYER_XP_UPDATE") end -- request /played to finalize the just achieved level's time calculateLevelTime = true Speedy:RegisterEvent("TIME_PLAYED_MSG", OnTimePlayedMsg) RequestTimePlayed() end local function OnPlayerLogout() if Speedy.Character.Level ~= MAX_LEVEL then Speedy.Character.LevelTimes[tostring(Speedy.Character.Level + 1)].LastUpdated = time() end Speedy.Character.LastSeen = time() end ------------------------------------ -- Mixins ------------------------------------ function Speedy:SetCurrentCharacter() local account = "Default" local realm = GetRealmName() local char = UnitName("player") local key = format("%s.%s.%s", account, realm, char) if self.db.global.Characters[key].Key == nil then self.db.global.Characters[key].Key = key end self.Character = self.db.global.Characters[key] end function Speedy:UpdateCharacterMetadata() local char = self.Character char.Realm = GetRealmName() char.Name = UnitName("player") char.Class = UnitClass("player") char.Race = UnitRace("player") char.Gender = GenderMap[UnitSex("player")] or GenderMap[1] char.Level = UnitLevel("player") char.LastSeen = time() -- update char.XP OnPlayerXPUpdate() end function Speedy:PrintCharacterMetadata() self:PrintMessage("Key >> %s", self.Character.Key) self:PrintMessage("Realm >> %s", self.Character.Realm) self:PrintMessage("Name >> %s", self.Character.Name) self:PrintMessage("Class >> %s", self.Character.Class) self:PrintMessage("Race >> %s", self.Character.Race) self:PrintMessage("Gender >> %s", self.Character.Gender) self:PrintMessage("Level >> %s", self.Character.Level) local numLevels = 0 for _, _ in pairs(self.Character.LevelTimes) do numLevels = numLevels + 1 end self:PrintMessage("# Levels Tracked >> %d", numLevels) self:PrintMessage("LastSeen >> %s", self.Character.LastSeen) end function Speedy:InitLevelTimes() local char = self.Character local levelTime = char.LevelTimes[tostring(char.Level)] if levelTime.LastUpdated ~= nil then return end if char.Level == 1 then levelTime.Played = 0 else calculateLevelTime = true end levelTime.LastUpdated = time() end function Speedy:PrintMessage(...) self:Print("|c" .. CHAT_COLOR .. format(...) .. "|r") end function Speedy:PrintVersion() self:PrintMessage("Version %s", self.Version) end function Speedy:PrintUsage() self:PrintMessage("------------------------------------") self:PrintVersion() self:Print() self:PrintMessage(" /speedy - print this usage info") self:PrintMessage(" /speedy version - print version info") self:PrintMessage(" /speedy char - print character data") self:PrintMessage(" /speedy export - export character data") self:PrintMessage("------------------------------------") end function Speedy:ShowExportString() local json = LibStub("json.lua") local data = json.encode(self.db.global.Characters) local compressed = LibDeflate:CompressZlib(data) local printable = base64:encode(compressed) local frame = AceGUI:Create("Frame") frame:SetTitle("Speedy Character Export") frame:SetStatusText("Exporting Speedy Character Data") frame:SetCallback( "OnClose", function(widget) AceGUI:Release(widget) end ) frame:SetLayout("Fill") local editBox = AceGUI:Create("MultiLineEditBox") editBox:DisableButton(true) editBox:SetLabel(nil) editBox:SetText(printable) editBox:SetFocus() editBox:HighlightText() frame:AddChild(editBox) end function Speedy:UpgradeDB() local dbVersion = self.db.global.DBVersion or 1 -- nothing to do if already at max db version if dbVersion == DB_VERSION then return end while dbVersion < DB_VERSION do if dbVersion == 1 then -- delete LevelXPMax global table if self.db.global.LevelXPMax then self.db.global.LevelXPMax = nil end -- remove XP and XPMax from each LevelTimes -- set LevelTimes keys to strings for _, char in pairs(self.db.global.Characters) do local newLevelTimes = {} for levelNum, levelTime in pairs(char.LevelTimes) do newLevelTimes[tostring(levelNum)] = { Played = levelTime.Played, LastUpdated = levelTime.LastUpdated } end char.LevelTimes = newLevelTimes end -- completed 1 => 2 upgrade dbVersion = 2 self.db.global.DBVersion = dbVersion end end end ------------------------------------ -- Slash Commands ------------------------------------ function Speedy:SpeedySlashHandler(input) if input == nil then self:PrintUsage() return end local command = self:GetArgs(input, 1) if command == "version" then self:PrintVersion() return end if command == "char" then self:PrintCharacterMetadata() return end if command == "export" then self:ShowExportString() return end if command ~= nil then self:PrintMessage("Unknown command: %s", input) self:Print() end self:PrintUsage() end ------------------------------------ -- Addon Setup ------------------------------------ function Speedy:OnInitialize() self.Version = "v" .. GetAddOnMetadata("Speedy", "Version") self.db = LibStub("AceDB-3.0"):New(self.DatabaseName, SpeedyDB_defaults, true) self:UpgradeDB() self:SetCurrentCharacter() self:RegisterChatCommand("speedy", "SpeedySlashHandler") end function Speedy:OnEnable() self:PrintVersion() self:UpdateCharacterMetadata() self:InitLevelTimes() self:PrintCharacterMetadata() self:RegisterEvent("PLAYER_LOGOUT", OnPlayerLogout) self:RegisterEvent("TIME_PLAYED_MSG", OnTimePlayedMsg) -- only need to register if below max level if self.Character.Level ~= MAX_LEVEL then self:RegisterEvent("PLAYER_LEVEL_UP", OnPlayerLevelUp) self:RegisterEvent("PLAYER_XP_UPDATE", OnPlayerXPUpdate) end -- trigger a TIME_PLAYED_MSG RequestTimePlayed() end function Speedy:OnDisable() -- TODO: keep a running list of event handlers since not all will be registered at all times self:UnregisterEvent("PLAYER_LOGOUT") self:UnregisterEvent("TIME_PLAYED_MSG") self:UnregisterEvent("PLAYER_LEVEL_UP") self:UnregisterEvent("PLAYER_XP_UPDATE") self:UnregisterChatCommand("speedy") end
-- file to test relative t.require function -- return { content = "I live 'a/b.lua'" }
local Prop = {} Prop.Name = "Suburbs House 3" Prop.Cat = "House" Prop.Price = 2000 Prop.Doors = { Vector( -11929, 2308, 190 ), Vector( -11852, 2531, 190 ), Vector( -11852, 2771, 190 ), Vector( -12116, 2771, 350 ), Vector( -12116, 2325, 350 ), Vector( -12214, 2808, 212 ), } GM.Property:Register( Prop )
--esmobs v1.3 --maikerumine --made for Extreme Survival game --License for code WTFPL -- nametag minetest.register_craftitem("esmobs:nametag", { description = "Nametag", inventory_image = "mobs_nametag.png", }) core.register_craft({ type = "shapeless", output = "esmobs:nametag", recipe = {"default:paper", "dye:black", "farming:string"}, }) -- leather minetest.register_craftitem("esmobs:leather", { description = "Leather", inventory_image = "mobs_leather.png", }) -- raw meat minetest.register_craftitem("esmobs:meat_raw", { description = "Raw Meat", inventory_image = "mobs_meat_raw.png", on_use = minetest.item_eat(3), }) -- cooked meat minetest.register_craftitem("esmobs:meat", { description = "Meat", inventory_image = "mobs_meat.png", on_use = minetest.item_eat(8), }) minetest.register_craft({ type = "cooking", output = "esmobs:meat", recipe = "esmobs:meat_raw", cooktime = 5, }) -- raw porkchop minetest.register_craftitem("esmobs:pork_raw", { description = "Raw Porkchop", inventory_image = "mobs_pork_raw.png", on_use = minetest.item_eat(4), }) -- cooked porkchop minetest.register_craftitem("esmobs:pork_cooked", { description = "Cooked Porkchop", inventory_image = "mobs_pork_cooked.png", on_use = minetest.item_eat(8), }) minetest.register_craft({ type = "cooking", output = "esmobs:pork_cooked", recipe = "esmobs:pork_raw", cooktime = 5, }) -- cooked rat, yummy! minetest.register_craftitem("esmobs:rat_cooked", { description = "Cooked Rat", inventory_image = "mobs_cooked_rat.png", on_use = minetest.item_eat(3), }) minetest.register_craft({ type = "cooking", output = "esmobs:rat_cooked", recipe = "esmobs:rat", cooktime = 5, }) -- egg entity --moved to throwing -- egg entity mobs:register_arrow("esmobs:egg_entity", { visual = "sprite", visual_size = {x=.5, y=.5}, textures = {"mobs_chicken_egg.png"}, velocity = 6, hit_player = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 1}, }, nil) end, hit_mob = function(self, player) player:punch(self.object, 1.0, { full_punch_interval = 1.0, damage_groups = {fleshy = 1}, }, nil) end, hit_node = function(self, pos, node) local num = math.random(1, 10) if num == 1 then pos.y = pos.y + 1 local nod = minetest.get_node_or_nil(pos) if not nod or not minetest.registered_nodes[nod.name] or minetest.registered_nodes[nod.name].walkable == true then return end local mob = minetest.add_entity(pos, "esmobs:chicken") local ent2 = mob:get_luaentity() mob:set_properties({ textures = ent2.child_texture[1], visual_size = { x = ent2.base_size.x / 2, y = ent2.base_size.y / 2 }, collisionbox = { ent2.base_colbox[1] / 2, ent2.base_colbox[2] / 2, ent2.base_colbox[3] / 2, ent2.base_colbox[4] / 2, ent2.base_colbox[5] / 2, ent2.base_colbox[6] / 2 }, }) ent2.child = true ent2.tamed = true ent2.owner = self.playername end end }) -- egg throwing item local egg_GRAVITY = 9 local egg_VELOCITY = 19 -- shoot egg local mobs_shoot_egg = function (item, player, pointed_thing) local playerpos = player:getpos() minetest.sound_play("default_place_node_hard", { pos = playerpos, gain = 1.0, max_hear_distance = 5, }) local obj = minetest.add_entity({ x = playerpos.x, y = playerpos.y +1.5, z = playerpos.z }, "esmobs:egg_entity") local ent = obj:get_luaentity() local dir = player:get_look_dir() ent.velocity = egg_VELOCITY -- needed for api internal timing ent.switch = 1 -- needed so that egg doesn't despawn straight away obj:setvelocity({ x = dir.x * egg_VELOCITY, y = dir.y * egg_VELOCITY, z = dir.z * egg_VELOCITY }) obj:setacceleration({ x = dir.x * -3, y = -egg_GRAVITY, z = dir.z * -3 }) -- pass player name to egg for chick ownership local ent2 = obj:get_luaentity() ent2.playername = player:get_player_name() item:take_item() return item end -- egg minetest.register_node("esmobs:egg", { description = "Chicken Egg", tiles = {"mobs_chicken_egg.png"}, inventory_image = "mobs_chicken_egg.png", visual_scale = 0.7, drawtype = "plantlike", wield_image = "mobs_chicken_egg.png", paramtype = "light", walkable = false, is_ground_content = true, sunlight_propagates = true, selection_box = { type = "fixed", fixed = {-0.2, -0.5, -0.2, 0.2, 0, 0.2} }, groups = {snappy = 2, dig_immediate = 3}, after_place_node = function(pos, placer, itemstack) if placer:is_player() then minetest.set_node(pos, {name = "esmobs:egg", param2 = 1}) end end, on_use = mobs_shoot_egg }) -- fried egg minetest.register_craftitem("esmobs:chicken_egg_fried", { description = "Fried Egg", inventory_image = "mobs_chicken_egg_fried.png", on_use = minetest.item_eat(2), }) minetest.register_craft({ type = "cooking", recipe = "esmobs:egg", output = "esmobs:chicken_egg_fried", }) -- raw chicken minetest.register_craftitem("esmobs:chicken_raw", { description = "Raw Chicken", inventory_image = "mobs_chicken_raw.png", on_use = minetest.item_eat(2), }) -- cooked chicken minetest.register_craftitem("esmobs:chicken_cooked", { description = "Cooked Chicken", inventory_image = "mobs_chicken_cooked.png", on_use = minetest.item_eat(6), }) minetest.register_craft({ type = "cooking", recipe = "esmobs:chicken_raw", output = "esmobs:chicken_cooked", }) -- golden lasso minetest.register_tool("esmobs:magic_lasso", { description = "Magic Lasso (right-click animal to put in inventory)", inventory_image = "mobs_magic_lasso.png", }) minetest.register_craft({ output = "esmobs:magic_lasso", recipe = { {"farming:string", "default:gold_lump", "farming:string"}, {"default:gold_lump", "default:diamondblock", "default:gold_lump"}, {"farming:string", "default:gold_lump", "farming:string"}, } }) -- net minetest.register_tool("esmobs:net", { description = "Net (right-click animal to put in inventory)", inventory_image = "mobs_net.png", }) minetest.register_craft({ output = "esmobs:net", recipe = { {"default:stick", "", "default:stick"}, {"default:stick", "", "default:stick"}, {"farming:string", "default:stick", "farming:string"}, } }) -- shears (right click to shear animal) minetest.register_tool("esmobs:shears", { description = "Steel Shears (right-click to shear)", inventory_image = "mobs_shears.png", }) minetest.register_craft({ output = 'esmobs:shears', recipe = { {'', 'default:steel_ingot', ''}, {'', 'group:stick', 'default:steel_ingot'}, } }) -- leather, feathers, saddle, etc. minetest.register_craftitem("esmobs:feather", { description = "Feather", inventory_image = "mobs_feather.png", }) minetest.register_craftitem("esmobs:saddle", { description = "Saddle", inventory_image = "saddle.png", }) minetest.register_craft({ output = "esmobs:saddle", recipe = { {"esmobs:leather", "esmobs:leather", "esmobs:leather"}, {"farming:string", "", "farming:string"}, {"default:steel_ingot", "", "default:steel_ingot"} }, }) -- bucket of milk minetest.register_craftitem("esmobs:bucket_milk", { description = "Bucket of Milk", inventory_image = "mobs_bucket_milk.png", stack_max = 1, on_use = minetest.item_eat(8, 'bucket:bucket_empty'), }) -- cheese wedge minetest.register_craftitem("esmobs:cheese", { description = "Cheese", inventory_image = "mobs_cheese.png", on_use = minetest.item_eat(4), }) minetest.register_craft({ type = "cooking", output = "esmobs:cheese", recipe = "esmobs:bucket_milk", cooktime = 5, replacements = {{ "esmobs:bucket_milk", "bucket:bucket_empty"}} }) -- cheese block minetest.register_node("esmobs:cheeseblock", { description = "Cheese Block", tiles = {"mobs_cheeseblock.png"}, is_ground_content = false, groups = {crumbly = 3}, sounds = default.node_sound_dirt_defaults() }) minetest.register_craft({ output = "esmobs:cheeseblock", recipe = { {'esmobs:cheese', 'esmobs:cheese', 'esmobs:cheese'}, {'esmobs:cheese', 'esmobs:cheese', 'esmobs:cheese'}, {'esmobs:cheese', 'esmobs:cheese', 'esmobs:cheese'}, } }) minetest.register_craft({ output = "esmobs:cheese 9", recipe = { {'esmobs:cheeseblock'}, } }) -- cobweb minetest.register_node("esmobs:cobweb", { description = "Cobweb", drawtype = "plantlike", visual_scale = 1.1, tiles = {"mobs_cobweb.png"}, inventory_image = "mobs_cobweb.png", paramtype = "light", sunlight_propagates = true, liquid_viscosity = 11, liquidtype = "source", liquid_alternative_flowing = "esmobs:cobweb", liquid_alternative_source = "esmobs:cobweb", liquid_renewable = false, liquid_range = 0, walkable = false, groups = {snappy=1,liquid=3}, drop = "farming:cotton", sounds = default.node_sound_leaves_defaults(), }) minetest.register_craft({ output = "esmobs:cobweb", recipe = { {"farming:string", "", "farming:string"}, {"", "farming:string", ""}, {"farming:string", "", "farming:string"}, } })
local card_reward_hooks = require "hook_card_rewards" local character_unlock_hooks = require "hook_character_unlock" -- TODO: clear deck, clear card pack/stash -- TODO: clear chars -- TODO: randomize pack of N cards -- TODO: randomly unlock N chars with their full forms, 3 limit, 200 (?) exp local max_card_id = 125 local deck_card_start_addr = 0x0DDF local num_cards_addr = 0x0041 local num_cards_in_deck = 20 local pack_card_start_addr = 0x0DF3 local NUM_RANDOM_CARDS = 50 local NUM_RANDOM_CHARS = 5 -- Clear deck for i = 0, num_cards_in_deck do memory.writebyte(deck_card_start_addr + i, 0x00, "WRAM") end -- Clear pack for i = 1, max_card_id do memory.writebyte(pack_card_start_addr + (i - 1), 0x00, "WRAM") end -- Randomize N cards for i = 0, NUM_RANDOM_CARDS do local rand_card_offset = math.random(max_card_id) - 1 -- value between 0 and (max_card_id - 1) local previous_num = memory.readbyte(pack_card_start_addr + rand_card_offset, "WRAM") memory.writebyte(pack_card_start_addr + rand_card_offset, previous_num + 1, "WRAM") end -- Unlock N random chars character_unlock_hooks.clear_chars() character_unlock_hooks.unlock_random_chars(NUM_RANDOM_CHARS) function update() card_reward_hooks.on_card_reward() end event.onframestart(update, "UPDATE")
local event = require("event") local sides = require("sides") local component = require("component") local glasses = component.glasses local nav = require("navigation") local map = require("map") local utils = require("utils") local vec3 = require("vec3") local locTracker = require("locationtracker") local ScanBatch = require("scanbatch") glasses.startLinking("Kristopher38") glasses.setRenderPosition("absolute") glasses.removeAll() print("Mapping...") local batch = ScanBatch() batch:scanAround(vec3(8, 8, 8)) print("Finished mapping sorrounding area") while true do local EVENT, ID, USER, PLAYER_POSITION_X, PLAYER_POSITION_Y, PLAYER_POSITION_Z, PLAYER_LOOKAT_X, PLAYER_LOOKAT_Y, PLAYER_LOOKAT_Z, PLAYER_EYE_HEIGHT, BLOCK_POSITION_X, BLOCK_POSITION_Y, BLOCK_POSITION_Z, BLOCK_SIDE, PLAYER_ROTATION, PLAYER_PITCH, PLAYER_FACING = event.pull("interact_world_block_right") local target = vec3(math.ceil(BLOCK_POSITION_X), math.ceil(BLOCK_POSITION_Y), math.ceil(BLOCK_POSITION_Z)) if target ~= locTracker.position then glasses.removeAll() utils.timeIt(nav.goTo, target, true) end end
local discordia = require("discordia") local client = discordia.Client() client:on("ready", function() -- bot is ready print("Logged in as " .. client.user.username) end) client:on("messageCreate", function(message) local content = message.content if content == "!ping" then message:reply("Pong!") elseif content == "!pong" then message:reply("Ping!") end end) client:run("Bot BOT_TOKEN") -- replace BOT_TOKEN with your bot token
-- -- uPnPclient - Simple client to support uPnP packets to devices on the network -- -- Author: Karl Bunch <karlbunch@karlbunch.com> -- -- Created: Fri Mar 18 05:22:03 EDT 2016 -- local socket = require('socket') local http = require('httpclient').new() local urlparser = require('httpclient.neturl') local inspect = require("inspect") local uPnPclient = { } local _M = { VERSION = "v0.3" } function _M.new(self, init) if type(init) == "table" then for k,v in pairs(init) do self[k] = v end end self.debug_level = self.debug_level or 0 return setmetatable(self, { __index = uPnPclient }) end function uPnPclient:debug(lvl, ...) if lvl > self.debug_level then return end local args = { ... } local msg = { } for _, v in ipairs(args) do if type(v) == "table" then msg[#msg+1] = (inspect and inspect(v)) or (cjson and cjson.encode(v)) or "*table*" else msg[#msg+1] = v end end (self.debug_print or print)((self.debug_prefix or "") .. table.concat(msg)) end local function simple_xml_parse(xml) local idx_cur = 1 local root = { } local node_cur = root local nodes = { } while true do local idx_start, idx_end, end_tag, label, args, empty = string.find(xml, "<(%/?)([%w:]+)(.-)(%/?)>", idx_cur) if not idx_start then break end if end_tag == "" then -- start tag node_cur[label] = { } nodes[#nodes+1] = node_cur[label] node_cur = nodes[#nodes] else -- end tag table.remove(nodes) node_cur = nodes[#nodes] local value = string.sub(xml, idx_cur, idx_start - 1) if not string.find(value, "^%s*$") then node_cur[label] = value end end idx_cur = idx_end + 1 end return root end local function findNodes(t, name, found) if found == nil then found = { } end if type(t) == "table" then for k,v in pairs(t) do if type(v) == "table" then if k == name then found[#found+1] = v end findNodes(v, name, found) end end end return found end function uPnPclient:discoverIGD() local ok, err = self:discover("urn:schemas-upnp-org:device:InternetGatewayDevice:1") if err then return nil, err end -- Find all the "service" nodes local services = findNodes(self.deviceProfile, "service") if #services == 0 then return nil, "ERROR: Unable to find service nodes in: " .. dev_http_response.body end self:debug(9, "Services: ", services) -- Search for the WAN.*Connection serviceType for _,v in pairs(services) do if v.serviceType ~= nil then self.schema = string.match(v.serviceType, "(.*:WANP*[IP]PConnection:%d+)") if self.schema then self.url.path = v.controlURL self.controlURL = tostring(self.url) break end end end if self.schema == nil then return nil, "ERROR: Unable to find serviceType WANIPConnection or WANPPPConnection in: " .. dev_http_response.body end if self.controlURL == nil then return nil, "ERROR: Unable to find controlURL in object for serviceType: " .. self.schema end -- connect location's host quickly to get our LAN ip local skt, err = socket.connect(self.url.host, self.url.port) if err then return nil, "ERROR: failed to open tcp socket to " .. self.url.host .. ':' .. self.url.port .. " - " .. err end self.internalClient = skt:getsockname() skt:close() self.readyIGD = true return self.deviceProfile, nil end function uPnPclient:discoverBasicDevice() local ok, err = self:discover("urn:schemas-upnp-org:device:basic:1") if err then return nil, err end return self.deviceProfile, nil end function uPnPclient:discover(search_target) -- Send sspd discover packet local udp = assert(socket.udp()) udp:settimeout(10) local pkt_ssdp_discover = table.concat({ 'M-SEARCH * HTTP/1.1\r\n', 'HOST: 239.255.255.250:1900\r\n', 'MAN: "ssdp:discover"\r\n', 'MX: 2\r\n', 'ST: ', search_target, '\r\n', '\r\n' }) assert(udp:sendto(pkt_ssdp_discover, "239.255.255.250", 1900)) -- Wait for reply -- TODO handle multiple replies local discover_response, err = udp:receive() if err then return nil, "ERROR: No response to discovery packet: " .. err end local location = string.match(discover_response,"LOCATION:%s+(http://%S+)") if location == nil or location == "" then return nil, "ERROR: Unable to parse location from discover response: " .. discover_response end self:debug(1, "Location: " .. location) local url = urlparser.parse(location) self.url = url -- Ask gateway for it's profile local dev_http_response = http:get(location) if dev_http_response.err then return nil, "ERROR: GET " .. location .. " FAILED: " .. dev_http_response.err end -- Parse into a simple table tree self.deviceProfile = simple_xml_parse(dev_http_response.body) self:debug(9, "deviceProfile: ", self.deviceProfile) return true, nil end function uPnPclient:SendSoapRequest(soap_body, action) local soap_headers = { ['SOAPAction'] = '"' .. self.schema .. '#' .. action .. '"', ['Content-Type'] = "text/xml" } self:debug(8, "Soap Headers:\n", soap_headers, "\nSoap Body:\n", soap_body); -- Send request to IGD local dev_http_response = http:post(self.controlURL, soap_body, { headers = soap_headers }) if dev_http_response.err then if dev_http_response.err:match('^<s:Envelope') then local err = simple_xml_parse(dev_http_response.err) for k,v in pairs({ "s:Envelope", "s:Body", "s:Fault", 'detail', 'UPnPError' }) do if err[v] == nil then break end err = err[v] end if err.errorCode then return nil, err.errorCode .. " - " .. err.errorDescription, err end end return nil, "GET " .. self.controlURL .. " ACTION: " .. action .. " FAILED: " .. dev_http_response.err end self:debug(9, "dev_response.body: ", dev_http_response.body) -- Parse into a simple table tree local r = simple_xml_parse(dev_http_response.body) self:debug(7, "dev_response: ", r) return true, nil, r end function uPnPclient:AddPortMapping(protocol, external_port, internal_port, description, duration) if not self.readyIGD then return nil, "ERROR: Not ready to send commands, did you run discoverIGD()?" end if internal_port == nil then internal_port = external_port end if description == nil then description = 'Port ' .. external_port .. '->' .. self.internalClient .. ':' .. internal_port end if duration == nil then duration = 0 end protocol = string.upper(protocol) self:debug(1, "AddPortMapping " .. protocol .. ' ' .. external_port .. " -> " .. self.internalClient .. ':' .. internal_port .. " (" .. description .. ")") local soap_body = table.concat({ '<?xml version="1.0"?>\r\n', '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\r\n', ' <s:Body>\r\n', ' <u:AddPortMapping xmlns:u="', self.schema, '">\r\n', ' <NewRemoteHost></NewRemoteHost>\r\n', ' <NewExternalPort>', external_port, '</NewExternalPort>\r\n', ' <NewProtocol>', protocol, '</NewProtocol>\r\n', ' <NewInternalPort>', internal_port, '</NewInternalPort>\r\n', ' <NewInternalClient>', self.internalClient, '</NewInternalClient>\r\n', ' <NewEnabled>1</NewEnabled>\r\n', ' <NewPortMappingDescription>', description, '</NewPortMappingDescription>\r\n', ' <NewLeaseDuration>', tonumber(duration),'</NewLeaseDuration>\r\n', ' </u:AddPortMapping>\r\n', ' </s:Body>\r\n', '</s:Envelope>\r\n\r\n', }) return self:SendSoapRequest(soap_body, 'AddPortMapping') end function uPnPclient:DeletePortMapping(protocol, external_port, internal_port) if not self.readyIGD then return nil, "ERROR: Not ready to send commands, did you run discoverIGD()?" end if internal_port == nil then internal_port = external_port end if description == nil then description = 'Port ' .. external_port .. '->' .. self.internalClient .. ':' .. internal_port end if duration == nil then duration = 0 end protocol = string.upper(protocol) self:debug(1, "DeletePortMapping " .. protocol .. ' ' .. external_port .. " -> " .. self.internalClient .. ':' .. internal_port .. " (" .. description .. ")") local soap_body = table.concat({ '<?xml version="1.0"?>\r\n', '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\r\n', ' <s:Body>\r\n', ' <u:DeletePortMapping xmlns:u="', self.schema, '">\r\n', ' <NewExternalPort>', external_port, '</NewExternalPort>\r\n', ' <NewProtocol>', string.upper(protocol), '</NewProtocol>\r\n', ' <NewInternalPort>', internal_port, '</NewInternalPort>\r\n', ' <NewInternalClient>', self.internalClient, '</NewInternalClient>\r\n', ' </u:DeletePortMapping>\r\n', ' </s:Body>\r\n', '</s:Envelope>\r\n\r\n', }) return self:SendSoapRequest(soap_body, 'DeletePortMapping') end function uPnPclient:GetExternalIPAddress() if not self.readyIGD then return nil, "ERROR: Not ready to send commands, did you run discoverIGD()?" end self:debug(1, "GetExternalIPAddress()") local soap_body = table.concat({ '<?xml version="1.0"?>\r\n', '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\r\n', ' <s:Body>\r\n', ' <u:GetExternalIPAddress xmlns:u="', self.schema, '">\r\n', ' </u:GetExternalIPAddress>\r\n', ' </s:Body>\r\n', '</s:Envelope>\r\n\r\n', }) local status, err, ret = self:SendSoapRequest(soap_body, 'GetExternalIPAddress') for _,k in pairs({ "s:Envelope", "s:Body", "u:GetExternalIPAddressResponse", "NewExternalIPAddress" }) do if ret[k] == nil then return nil end ret = ret[k] end return ret end function uPnPclient:GetListOfPortMappings() if not self.readyIGD then return nil, "ERROR: Not ready to send commands, did you run discoverIGD()?" end self:debug(1, "GetListOfPortMappings()") local soap_body = table.concat({ '<?xml version="1.0"?>\r\n', '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\r\n', ' <s:Body>\r\n', ' <u:GetListOfPortMappings xmlns:u="', self.schema, '">\r\n', ' <NewStartPort>0</NewStartPort>\r\n', ' <NewEndPort>65535</NewEndPort>\r\n', ' <NewProtocol>TCP</NewProtocol>\r\n', ' <NewNumberOfPorts>65535</NewNumberOfPorts>\r\n', ' </u:GetListOfPortMappings>\r\n', ' </s:Body>\r\n', '</s:Envelope>\r\n\r\n', }) local status, err, ret = self:SendSoapRequest(soap_body, 'GetListOfPortMappings') if err then return nil, err end return ret end function uPnPclient:GetCommonLinkProperties() if not self.readyIGD then return nil, "ERROR: Not ready to send commands, did you run discoverIGD()?" end self:debug(1, "GetCommonLinkProperties()") local soap_body = table.concat({ '<?xml version="1.0"?>\r\n', '<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">\r\n', ' <s:Body>\r\n', ' <u:GetCommonLinkProperties xmlns:u="', self.schema, '">\r\n', ' </u:GetCommonLinkProperties>\r\n', ' </s:Body>\r\n', '</s:Envelope>\r\n\r\n', }) local status, err, ret = self:SendSoapRequest(soap_body, 'GetCommonLinkProperties') if err then return nil, err end return ret end return _M
package("libxt") set_homepage("https://gitlab.freedesktop.org/xorg/lib/libxt") set_description("X.Org: X Toolkit Intrinsics library") add_urls("https://www.x.org/archive/individual/lib/libXt-$(version).tar.gz") add_versions("1.2.1", "6da1bfa9dd0ed87430a5ce95b129485086394df308998ebe34d98e378e3dfb33") if is_plat("linux") then add_extsources("apt::libxt-dev") end add_deps("libx11", "libsm") on_install("macosx", "linux", function (package) import("package.tools.autoconf").install(package) end) on_test(function (package) assert(package:has_cfuncs("XtConvertAndStore", {includes = "X11/Intrinsic.h"})) end)
local _M = {} local function configure_origin(ngx, conf) if conf.origin == nil then ngx.header["Access-Control-Allow-Origin"] = "*" else ngx.header["Access-Control-Allow-Origin"] = conf.origin ngx.header["Vary"] = "Origin" end end local function configure_credentials(ngx, conf) if (conf.credentials) then ngx.header["Access-Control-Allow-Credentials"] = "true" end end local function configure_headers(ngx, conf, headers) if conf.headers == nil then ngx.header["Access-Control-Allow-Headers"] = headers['access-control-request-headers'] or "" else ngx.header["Access-Control-Allow-Headers"] = conf.headers end end local function configure_exposed_headers(ngx, conf) if conf.exposed_headers ~= nil then ngx.header["Access-Control-Expose-Headers"] = conf.exposed_headers end end local function configure_methods(ngx, conf) if conf.methods ~= nil then ngx.header["Access-Control-Allow-Methods"] = conf.methods else ngx.header["Access-Control-Allow-Methods"] = "GET,HEAD,PUT,PATCH,POST,DELETE" end end local function configure_max_age(ngx, conf) if conf.max_age ~= nil then ngx.header["Access-Control-Max-Age"] = tostring(conf.max_age) end end function _M.execute(conf) local request = ngx.req local method = request.get_method() local headers = request.get_headers() configure_origin(ngx, conf) configure_credentials(ngx, conf) if method == "OPTIONS" then -- Preflight configure_headers(ngx, conf, headers) configure_methods(ngx, conf) configure_max_age(ngx, conf) if not conf.preflight_continue then utils.no_content() end else configure_exposed_headers(ngx, conf) end end return _M
DECK = { vanilla = { -- 108 cartas -- 2 cópias de 1 a 9 de cada cor -- 2 cópias de draw2 de cada cor -- 2 cópias de skip de cada cor -- 2 cópias de reverse de cada cor -- 1 cópia de 0 de cada cor -- 4 cópias de wild -- 4 cópias de draw4 {"red","n0"}, {"red","n1"},{"red","n2"},{"red","n3"},{"red","n4"},{"red","n5"},{"red","n6"},{"red","n7"},{"red","n8"},{"red","n9"}, {"red","n1"},{"red","n2"},{"red","n3"},{"red","n4"},{"red","n5"},{"red","n6"},{"red","n7"},{"red","n8"},{"red","n9"}, {"red","draw2"},{"red","draw2"},{"red","skip"},{"red","skip"},{"red","reverse"},{"red","reverse"}, {"blue","n0"}, {"blue","n1"},{"blue","n2"},{"blue","n3"},{"blue","n4"},{"blue","n5"},{"blue","n6"},{"blue","n7"},{"blue","n8"},{"blue","n9"}, {"blue","n1"},{"blue","n2"},{"blue","n3"},{"blue","n4"},{"blue","n5"},{"blue","n6"},{"blue","n7"},{"blue","n8"},{"blue","n9"}, {"blue","draw2"},{"blue","draw2"},{"blue","skip"},{"blue","skip"},{"blue","reverse"},{"blue","reverse"}, {"yellow","n0"}, {"yellow","n1"},{"yellow","n2"},{"yellow","n3"},{"yellow","n4"},{"yellow","n5"},{"yellow","n6"},{"yellow","n7"},{"yellow","n8"},{"yellow","n9"}, {"yellow","n1"},{"yellow","n2"},{"yellow","n3"},{"yellow","n4"},{"yellow","n5"},{"yellow","n6"},{"yellow","n7"},{"yellow","n8"},{"yellow","n9"}, {"yellow","draw2"},{"yellow","draw2"},{"yellow","skip"},{"yellow","skip"},{"yellow","reverse"},{"yellow","reverse"}, {"green","n0"}, {"green","n1"},{"green","n2"},{"green","n3"},{"green","n4"},{"green","n5"},{"green","n6"},{"green","n7"},{"green","n8"},{"green","n9"}, {"green","n1"},{"green","n2"},{"green","n3"},{"green","n4"},{"green","n5"},{"green","n6"},{"green","n7"},{"green","n8"},{"green","n9"}, {"green","draw2"},{"green","draw2"},{"green","skip"},{"green","skip"},{"green","reverse"},{"green","reverse"}, {"black","wild"},{"black","wild"},{"black","wild"},{"black","wild"}, {"black","draw4"},{"black","draw4"},{"black","draw4"},{"black","draw4"} }, numbers = { -- 80 cartas -- 2 cópias de 1 a 9 de cada cor -- 1 cópia de 0 de cada cor -- 4 cópias de wild {"red","n0"}, {"red","n1"},{"red","n2"},{"red","n3"},{"red","n4"},{"red","n5"},{"red","n6"},{"red","n7"},{"red","n8"},{"red","n9"}, {"red","n1"},{"red","n2"},{"red","n3"},{"red","n4"},{"red","n5"},{"red","n6"},{"red","n7"},{"red","n8"},{"red","n9"}, {"blue","n0"}, {"blue","n1"},{"blue","n2"},{"blue","n3"},{"blue","n4"},{"blue","n5"},{"blue","n6"},{"blue","n7"},{"blue","n8"},{"blue","n9"}, {"blue","n1"},{"blue","n2"},{"blue","n3"},{"blue","n4"},{"blue","n5"},{"blue","n6"},{"blue","n7"},{"blue","n8"},{"blue","n9"}, {"yellow","n0"}, {"yellow","n1"},{"yellow","n2"},{"yellow","n3"},{"yellow","n4"},{"yellow","n5"},{"yellow","n6"},{"yellow","n7"},{"yellow","n8"},{"yellow","n9"}, {"yellow","n1"},{"yellow","n2"},{"yellow","n3"},{"yellow","n4"},{"yellow","n5"},{"yellow","n6"},{"yellow","n7"},{"yellow","n8"},{"yellow","n9"}, {"green","n0"}, {"green","n1"},{"green","n2"},{"green","n3"},{"green","n4"},{"green","n5"},{"green","n6"},{"green","n7"},{"green","n8"},{"green","n9"}, {"green","n1"},{"green","n2"},{"green","n3"},{"green","n4"},{"green","n5"},{"green","n6"},{"green","n7"},{"green","n8"},{"green","n9"}, {"black","wild"},{"black","wild"},{"black","wild"},{"black","wild"}, }, mess = { -- 32 cartas -- 2 cópias de cada carta de ação -- 4 curingas comuns -- 4 curingas +4 -- é preenchido por cartas de todas as regras {"red","skip"},{"red","reverse"},{"red","draw2"}, {"red","skip"},{"red","reverse"},{"red","draw2"}, {"blue","skip"},{"blue","reverse"},{"blue","draw2"}, {"blue","skip"},{"blue","reverse"},{"blue","draw2"}, {"yellow","skip"},{"yellow","reverse"},{"yellow","draw2"}, {"yellow","skip"},{"yellow","reverse"},{"yellow","draw2"}, {"green","skip"},{"green","reverse"},{"green","draw2"}, {"green","skip"},{"green","reverse"},{"green","draw2"}, {"black","wild"},{"black","wild"},{"black","wild"},{"black","wild"}, {"black","draw4"},{"black","draw4"},{"black","draw4"},{"black","draw4"} }, peace = { -- 4 cartas -- 1 cópias de peace de cada cor {"red","peace"},{"blue","peace"},{"yellow","peace"},{"green","peace"} }, confuse = { -- 8 cartas -- 2 cópias de confuse de cada cor {"red","confuse"},{"blue","confuse"},{"yellow","confuse"},{"green","confuse"}, {"red","confuse"},{"blue","confuse"},{"yellow","confuse"},{"green","confuse"} }, death = { -- 2 cartas -- 1 cópia de death de cada cor {"red","death"},{"blue","death"} }, carousel = { -- 4 cartas -- 1 cópia de carousel de cada cor {"red","carousel"},{"blue","carousel"},{"yellow","carousel"},{"green","carousel"} }, tornado = { -- 8 cartas -- 2 cópias de tornado de cada cor {"red","tornado"},{"blue","tornado"},{"yellow","tornado"},{"green","tornado"}, {"red","tornado"},{"blue","tornado"},{"yellow","tornado"},{"green","tornado"}, }, trade = { -- 4 cartas -- 1 cópia de trade de cada cor {"red","trade"},{"blue","trade"},{"yellow","trade"},{"green","trade"} }, gift = { -- 4 cartas -- 1 cópia de gift de cada cor {"red","gift"},{"blue","gift"},{"yellow","gift"},{"green","gift"} }, ban = { -- 4 cartas -- 1 cópia de ban de cada cor {"red","ban"},{"blue","ban"},{"yellow","ban"},{"green","ban"} }, magnet = { -- 8 cartas -- 2 cópias de magnet de cada cor {"red","magnet"},{"blue","magnet"},{"yellow","magnet"},{"green","magnet"}, {"red","magnet"},{"blue","magnet"},{"yellow","magnet"},{"green","magnet"}, }, random = { -- 4 cartas pretas {"black","random"},{"black","random"},{"black","random"},{"black","random"} }, clone = { -- 4 cartas pretas {"black","clone"},{"black","clone"},{"black","clone"},{"black","clone"} }, spy = { -- 8 cartas -- 2 cópias de spy de cada cor {"red","spy"},{"blue","spy"},{"yellow","spy"},{"green","spy"}, {"red","spy"},{"blue","spy"},{"yellow","spy"},{"green","spy"} }, compass = { -- 8 cartas -- 2 cópias de compass de cada cor {"red","compass"},{"blue","compass"},{"yellow","compass"},{"green","compass"}, {"red","compass"},{"blue","compass"},{"yellow","compass"},{"green","compass"} }, chair = { -- 4 cartas -- 1 cópia de chair de cada cor {"red","chair"},{"blue","chair"},{"yellow","chair"},{"green","chair"} }, theft = { -- 8 cartas -- 1 cópia de theft de cada cor {"red","theft"},{"blue","theft"},{"yellow","theft"},{"green","theft"}, {"red","theft"},{"blue","theft"},{"yellow","theft"},{"green","theft"} }, imitate = { -- 4 cartas -- 1 cópia de imitate de cada cor {"red","imitate"},{"blue","imitate"},{"yellow","imitate"},{"green","imitate"} }, equality = { -- 4 cartas -- 1 cópia de equality de cada cor {"red","equality"},{"blue","equality"},{"yellow","equality"},{"green","equality"} }, web = { -- 4 cartas -- 1 cópia de web de cada cor {"red","web"},{"blue","web"},{"yellow","web"},{"green","web"} }, rule = { -- 4 cartas -- 1 cópia de rule de cada cor {"red","rule"},{"blue","rule"},{"yellow","rule"},{"green","rule"} }, steal = { -- 4 cartas -- 1 cópia de steal de cada cor {"red","steal"},{"blue","steal"},{"yellow","steal"},{"green","steal"} }, thunder = { -- 2 cartas {"yellow","thunder"},{"green","thunder"} }, rain = { -- 2 cartas {"red","rain"},{"blue","rain"} }, box = { -- 2 cartas {"red","box"},{"blue","box"} }, wish = { -- 4 cartas {"red","wish"},{"blue","wish"},{"yellow","wish"},{"green","wish"} }, ink = { -- 4 cartas {"red","ink"},{"blue","ink"},{"yellow","ink"},{"green","ink"} }, curse = { -- 4 cartas {"red","curse"},{"blue","curse"},{"yellow","curse"},{"green","curse"} }, dice = { -- 4 cartas {"red","dice"},{"blue","dice"},{"yellow","dice"},{"green","dice"} }, paradox = { -- 4 cartas {"red","paradox"},{"blue","paradox"},{"yellow","paradox"},{"green","paradox"} }, mimic = { -- 4 cartas {"red","mimic"},{"blue","mimic"},{"yellow","mimic"},{"green","mimic"} }, justice = { -- 4 cartas {"red","justice"},{"blue","justice"},{"yellow","justice"},{"green","justice"} }, oddeven = { -- 8 cartas {"red","oddeven"},{"blue","oddeven"},{"yellow","oddeven"},{"green","oddeven"}, {"red","oddeven"},{"blue","oddeven"},{"yellow","oddeven"},{"green","oddeven"} }, bomb = { -- 1 carta {"black","bomb"} }, batata = { -- 1 carta {"red","batata"} }, draw99 = { -- 1 carta {"black","draw99"} }, half = { -- 1 carta {"black","half"} }, simon = { -- 8 cartas {"black","simon"},{"black","simon"},{"black","simon"},{"black","simon"},{"black","simon"},{"black","simon"},{"black","simon"},{"black","simon"} }, meep = { -- 8 cartas -- 2 cópias de meep de cada cor {"red","meep"},{"blue","meep"},{"yellow","meep"},{"green","meep"}, {"red","meep"},{"blue","meep"},{"yellow","meep"},{"green","meep"} }, luck = { -- 8 cartas -- 2 cópias de luck de cada cor {"red","luck"},{"blue","luck"},{"yellow","luck"},{"green","luck"}, {"red","luck"},{"blue","luck"},{"yellow","luck"},{"green","luck"} }, portal = { -- 8 cartas -- 2 cópias de portal de cada cor {"red","portal"},{"blue","portal"},{"yellow","portal"},{"green","portal"}, {"red","portal"},{"blue","portal"},{"yellow","portal"},{"green","portal"}, }, key = { -- 4 cartas -- 1 cópias de key de cada cor {"red","key"},{"blue","key"},{"yellow","key"},{"green","key"}, }, share = { -- 8 cartas -- 2 cópias de share de cada cor {"green","share"},{"yellow","share"}, }, mix = { -- 12 cartas -- 1 cópia de reverse skip de cada cor -- 1 cópia de reverse +2 de cada cor -- 1 cópia de skip +2 de cada cor {"red","mix1"},{"blue","mix1"},{"yellow","mix1"},{"green","mix1"}, {"red","mix2"},{"blue","mix2"},{"yellow","mix2"},{"green","mix2"}, {"red","mix3"},{"blue","mix3"},{"yellow","mix3"},{"green","mix3"}, }, chess = { -- 22 cartas -- 1 rei preto -- 1 rainha preto -- 1 cópia de bispo de cada cor -- 1 cópia de cavalo de cada cor -- 1 cópia de torre de cada cor -- 2 cópias de peões de cada cor {"black","king"},{"black","queen"}, {"red","bishop"},{"blue","bishop"},{"yellow","bishop"},{"green","bishop"}, {"red","knight"},{"blue","knight"},{"yellow","knight"},{"green","knight"}, {"red","rook"},{"blue","rook"},{"yellow","rook"},{"green","rook"}, {"red","pawn"},{"blue","pawn"},{"yellow","pawn"},{"green","pawn"}, {"red","pawn"},{"blue","pawn"},{"yellow","pawn"},{"green","pawn"}, } }
local allowCountdown = false local inSelection = true local ofsx = -210 local ofsy = 0 local mult = 1.25 characterNames = {'bf', 'pico-player', 'dad', 'spooky', 'mom', 'monster', 'senpai', 'spirit', 'angryplankton-player-old', 'diego-player', 'foxa'} --character json name characterDisplays = {'boyfriend', 'pico', 'dad', 'spooky kids', 'mom', 'monster', 'senpai', 'spirit', 'plankton', 'diego', 'foxa'} --display name for text characterLimit = {3, 1, 1, 1, 1, 2, 2, 1, 1, 1, 1} --how many variations does the character have maxpage = 11 --amount of characters u have variation = 1 -- 1 = original local page = 1 local inSelection = true function onCreate() if allowCountdown == false then makeLuaSprite('fader', '', -200, -200) makeGraphic('fader', 1920, 1080, '000000') addLuaSprite('fader', true) setScrollFactor('fader', 0, 0) setProperty('fader.alpha', 0) setObjectCamera('fader', 'other') makeLuaSprite('5', 'stagesea', -500, -300); setScrollFactor('2', 0.9, 0.9); scaleObject('2', 1.1, 1.1); addLuaSprite('5', false); makeLuaText('text1', characterDisplays[page], 600, 15, 350) setTextSize('text1', 50);--Sets text size setTextWidth('text1', 600);--Sets text width addLuaText('text1') setProperty('gf.visible', false) setProperty('dad.visible', false) playMusic('offsetSong') end end function onStartCountdown() -- Block the first countdown and start a timer of 0.8 seconds to play the dialogue if not allowCountdown and not isStoryMode and not seenCutscene then setProperty('inCutscene', true); setProperty('gf.visible', false) setProperty('dad.visible', false) allowCountdown = true; return Function_Stop; end return Function_Continue; end function onUpdate() if getPropertyFromClass('flixel.FlxG', 'keys.justPressed.ENTER') then if inSelection == true and getProperty('inCutscene') == true then removeLuaText('text1', true) stopSound('offsetSong`') playMusic('gameOverEnd', 0.5) if page < 3 then objectPlayAnimation('boyfriend', 'hey', true) else objectPlayAnimation('boyfriend', 'singUP', true) end runTimer('startsong', 5) runTimer('fadein', 2.5) runTimer('fadedelay', 1.5) setProperty('seenCutscene', true) end end if getPropertyFromClass('flixel.FlxG', 'keys.justPressed.BACKSPACE') then endSong() end if getPropertyFromClass('flixel.FlxG', 'keys.justPressed.RIGHT') then if page < maxpage and inSelection == true then variation = 1 page = page+1 --debugPrint(page, characterNames[page], characterDisplays[page], variation) setCharacter() end elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.LEFT') then if page > 0 and inSelection == true then variation = 1 page = page-1 --debugPrint(page, characterNames[page], characterDisplays[page], variation) setCharacter() end end if getPropertyFromClass('flixel.FlxG', 'keys.justPressed.UP') then if variation < characterLimit[page] and inSelection == true then variation = variation+1 --debugPrint(page, characterNames[page], characterDisplays[page], variation) setCharacter() end elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.DOWN') then if variation > -1 and inSelection == true then variation = variation-1 --debugPrint(page, characterNames[page], characterDisplays[page], variation) setCharacter() end end --animation player if inSelection == true then if getPropertyFromClass('flixel.FlxG', 'keys.justPressed.D') then objectPlayAnimation('boyfriend', 'singLEFT', true) elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.J') then objectPlayAnimation('boyfriend', 'singUP', true) elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.F') then objectPlayAnimation('boyfriend', 'singDOWN', true) elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.K') then objectPlayAnimation('boyfriend', 'singRIGHT', true) elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.G') then objectPlayAnimation('boyfriend', 'hey', true) elseif getPropertyFromClass('flixel.FlxG', 'keys.justPressed.H') then objectPlayAnimation('boyfriend', 'idle', true) end end end function onTimerCompleted(tag) if tag == 'startsong' then startCountdown() end if tag == 'fadein' then inSelection = false setProperty('dad.visible', true) if page == 1 then setProperty('gf.visible', true) end removeLuaSprite('5', true) runTimer('fadeout', 2.5) end if tag == 'fadedelay' then doTweenAlpha('faderfader', 'fader', 1, 0.9, 'linear') end end function setCharacter() if page > 0 and page < maxpage+1 and inSelection == true then setVariation() setTextString('text1', characterDisplays[page]); --setProperty('boyfriend', 'x', defaultBoyfriendX+characterOfsX[page]) --setProperty('boyfriend', 'y', defaultBoyfriendY+characterOfsY[page]) triggerEvent('Change Character', 0, characterNames[page]); objectPlayAnimation('boyfriend', 'idle', true) end end function setVariation() if variation == 1 then characterNames = {'bf', 'pico-player', 'dad', 'spooky', 'mom', 'monster', 'senpai', 'spirit', 'angryplankton-player-old', 'diego-player', 'foxa'} --character json name characterDisplays = {'boyfriend', 'pico', 'dad', 'spooky kids', 'mom', 'monster', 'senpai', 'spirit', 'plankton', 'diego'} --display name for text elseif variation == 2 then characterNames = {'bf-spong', 'pico-player', 'dad', 'spooky', 'mom', 'monster-christmas', 'senpai-angry', 'spirit', 'angryplankton-player-old', 'diego', 'foxa'} --character json name characterDisplays = {'boyfriend (spong)', 'pico', 'dad', 'spooky kids', 'mom', 'monster (christmas)', 'senpai (mad)', 'spirit', 'plankton', 'diego'} --display name for text elseif variation == 3 then characterNames = {'bf-pixel', 'pico-player', 'dad', 'spooky', 'mom', 'monster-christmas', 'senpai-angry', 'spirit', 'angryplankton-player-old', 'diego-player', 'foxa'} --character json name characterDisplays = {'boyfriend (pixel)', 'pico', 'dad', 'spooky kids','mom', 'monster (christmas)', 'senpai (mad)', 'spirit', 'plankton', 'diego'} --display name for text end end function onTweenCompleted(tag) if tag == 'faderfader' then doTweenAlpha('faderfaderBYE', 'fader', 0, 1.4, 'linear') end end
vim.api.nvim_set_keymap('n', '<Leader>tt', ':NERDTreeToggle<CR>', {noremap = true}) vim.api.nvim_set_keymap('n', '<Leader>tr', ':NERDTreeRefreshRoot<CR>', {noremap = true}) -- vim.api.nvim_set_keymap('n', '<Leader>tf', ':NERDTreeFocus<CR>', {noremap = true}) vim.g.NERDTreeWinPos = "right" vim.api.nvim_command([[ augroup DragQuickfixWindowDown autocmd FileType qf wincmd J augroup end ]]) vim.api.nvim_command([[ autocmd BufEnter * if tabpagenr('$') == 1 && winnr('$') == 1 && exists('b:NERDTree') && b:NERDTree.isTabTree() | quit | endif ]])
local M = { } local TK = require("PackageToolkit") local prepend = (TK.module.import(..., "_prepend")).prepend local tail = (TK.module.import(..., "_tail")).tail M.reverse = function(list) local aux aux = function(list, accum) if #list == 0 then return accum else return aux((tail(list)), (prepend(list[1], accum))) end end return aux(list, { }) end return M
local math = require('math') local os = require('os') local string = require('string') local helper = require('../helper') local fixtures = require('/tests/fixtures').checks local WindowsChecks = require('/check/windows').checks local exports = {} exports['test_windowsperfos_check'] = function(test, asserts) local check = WindowsChecks.WindowsPerfOSCheck:new({id='foo', period=30}) asserts.ok(check._lastResult == nil) check:run(function(result) asserts.ok(result ~= nil) asserts.ok(check._lastResult ~= nil) if os.type() == 'win32' then asserts.equals(result:getStatus(), 'success') asserts.ok(#check._lastResult:serialize() > 0) local metrics = result:getMetrics()['none'] asserts.ok(metrics['Processes']['t'] == 'uint32') -- Values always become strings internally asserts.ok(tonumber(metrics['Processes']['v']) > 0) else asserts.ok(result:getStatus() ~= 'success') end test.done() end) end local function add_iterative_test(original_test_set, base_name, test_function) local test_name = 'test_' .. base_name if helper.test_configs == nil or helper.test_configs[test_name] == nil then original_test_set[test_name] = function(test, asserts) test.skip(test_name .. ' requires at least one config file entry') end else for i, config in ipairs(helper.test_configs[test_name]) do original_test_set[string.format('%s_%u', test_name, i)] = function(test, asserts) return test_function(test, asserts, config) end end end return original_test_set end local function add_iterative_and_fixture_test(original_test_set, base_name, test_function) local test_name = 'test_' .. base_name if not fixtures[base_name .. ".txt"] then original_test_set[test_name .. '_fixture'] = function(test, asserts) test.skip(test_name .. '_fixture, fixture is missing') end else original_test_set[test_name .. '_fixture'] = function(test, asserts) return test_function(test, asserts, {db='foo', powershell_csv_fixture=fixtures[base_name .. ".txt"]}) end end return add_iterative_test(original_test_set, base_name, test_function) end local function mssql_test_common(check, test, asserts, specific_tests) asserts.ok(check._lastResult == nil) --p(check) check:run(function(result) asserts.ok(result ~= nil) asserts.ok(check._lastResult ~= nil) if os.type() == 'win32' or check:getPowershellCSVFixture() then asserts.equals(result:getStatus(), 'success') asserts.ok(#check._lastResult:serialize() > 0, "no metrics") --local metrics = result:getMetrics()['none'] --p(metrics) specific_tests(result, test, asserts) else asserts.ok(result:getStatus() ~= 'success') end test.done() end) end exports = add_iterative_and_fixture_test(exports, 'mssql_database', function(test, asserts, config) mssql_test_common(WindowsChecks.MSSQLServerDatabaseCheck:new({id='foo', period=30, details=config}), test, asserts, function(result, test, asserts) local metrics = result:getMetrics()['none'] -- Values always become strings internally asserts.ok(tonumber(metrics['size']['v']) > 0) end ) end) exports = add_iterative_and_fixture_test(exports, 'mssql_buffer_manager', function(test, asserts, config) mssql_test_common(WindowsChecks.MSSQLServerBufferManagerCheck:new({id='foo', period=30, details=config}), test, asserts, function(result, test, asserts) local metrics = result:getMetrics()['none'] -- Values always become strings internally asserts.ok(tonumber(metrics['total_pages']['v']) > 0) end ) end) exports = add_iterative_and_fixture_test(exports, 'mssql_sql_statistics', function(test, asserts, config) mssql_test_common(WindowsChecks.MSSQLServerSQLStatisticsCheck:new({id='foo', period=30, details=config}), test, asserts, function(result, test, asserts) local metrics = result:getMetrics()['none'] -- Values always become strings internally asserts.ok(tonumber(metrics['sql_attention_rate']['v']) >= 0) end ) end) exports = add_iterative_and_fixture_test(exports, 'mssql_memory_manager', function(test, asserts, config) mssql_test_common(WindowsChecks.MSSQLServerMemoryManagerCheck:new({id='foo', period=30, details=config}), test, asserts, function(result, test, asserts) local metrics = result:getMetrics()['none'] -- Values always become strings internally asserts.ok(tonumber(metrics['total_server_memory']['v']) > 0) end ) end) exports = add_iterative_and_fixture_test(exports, 'mssql_plan_cache', function(test, asserts, config) mssql_test_common(WindowsChecks.MSSQLServerPlanCacheCheck:new({id='foo', period=30, details=config}), test, asserts, function(result, test, asserts) local metrics = result:getMetrics()['none'] -- Values always become strings internally asserts.ok(tonumber(metrics['total_cache_pages']['v']) > 0) end ) end) return exports
#!/usr/bin/env lua -- MoonAssimp example: inspect3d.lua - 3D Model Inspector -- -- For usage help, type at the shell prompt: -- $ ./inspect3d.lua --help ai = require("moonassimp") -- Set to false or comment out if you don't want verbose logging: ai.enable_verbose_logging(true) -- Uncomment/comment items if you want to change the default post-process flags: DEFAULT_POSTPROCESSFLAGS = { -- 'calc tangent space', 'join identical vertices', -- 'make left handed', 'triangulate', -- 'remove component', -- 'gen normals', -- 'gen smooth normals', -- 'split large meshes', -- 'pre transform vertices', -- 'limit bone weights', -- 'validate data structure', -- 'improve cache locality', -- 'remove redundant materials', -- 'fix infacing normals', -- 'sort by p type', -- 'find degenerates', -- 'find invalid data', -- 'gen uv coords', -- 'transform uv coords', -- 'find instances', -- 'optimize meshes', -- 'optimize graph', -- 'flip uvs', -- 'flip winding order', -- 'split by bone count', -- 'debone', } POSTPROCESSFLAGS = { { 'calc tangent space', '0x1' }, { 'join identical vertices', '0x2' }, { 'make left handed', '0x4' }, { 'triangulate', '0x8' }, { 'remove component', '0x10' }, { 'gen normals', '0x20' }, { 'gen smooth normals', '0x40' }, { 'split large meshes', '0x80' }, { 'pre transform vertices', '0x100' }, { 'limit bone weights', '0x200' }, { 'validate data structure', '0x400' }, { 'improve cache locality', '0x800' }, { 'remove redundant materials', '0x1000' }, { 'fix infacing normals', '0x2000' }, { 'sort by p type', '0x8000' }, { 'find degenerates', '0x10000' }, { 'find invalid data', '0x20000' }, { 'gen uv coords', '0x40000' }, { 'transform uv coords', '0x80000' }, { 'find instances', '0x100000' }, { 'optimize meshes', '0x200000' }, { 'optimize graph', '0x400000' }, { 'flip uvs', '0x800000' }, { 'flip winding order', '0x1000000' }, { 'split by bone count', '0x2000000' }, { 'debone', '0x4000000' }, } -- Utilities ------------------------------------------------------------------ function concatflags(t) if not t[1] then return "-" end return "'"..table.concat(t, "', '").. "'" end function concatboolean(val) if val==nil then return "-" end return tostring(val) end function concat2(a,b) if a==nil then return "-" end return "(" .. a ..", " .. b ..")" end function concatcolor(r, g, b, a) if not r then return "-" end if a then return string.format("{%.2f, %.2f, %.2f, %.2f}", r, g, b, a) end return string.format("{%.2f, %.2f, %.2f}", r, g, b) end function concatvec3(x, y, z) if not x then return "-" end return string.format("{%.1f, %.1f, %.1f}", x, y, z) end function concatvec2(x, y) if not x then return "-" end return string.format("{%.1f, %.1f}", x, y) end -- Print functions ------------------------------------------------------------ function PrintMesh(mesh, indent) local indent = indent or "" print(indent .. "mesh: '" .. (mesh:name() or "???").."'" .. " (" .. tostring(mesh) .. ")") indent = indent .. " " print(indent .. "vertices: " .. mesh:num_vertices()) print(indent .. "normals: " .. (mesh:has_normals() and "yes" or "no")) print(indent .. "tangents: " .. (mesh:has_tangents() and "yes" or "no")) print(indent .. "faces: " .. mesh:num_faces()) print(indent .. "primitive types: " .. concatflags({ai.primtypes(mesh:primitive_types())})) print(indent .. "bones: " .. mesh:num_bones()) print(indent .. "anim meshes: " .. mesh:num_anim_meshes()) local material = mesh:material() print(indent .. "material: '" .. material:name().."' (".. tostring(material)..")") -- print(indent .. "colors: " .. (mesh:has_colors(1) and "yes" or "no")) local ncc = mesh:num_color_channels() print(indent .. "color channels: " .. ncc) -- print(indent .. "texture coords: " .. (mesh:has_texture_coords(1) and "yes" or "no")) local ntc = mesh:num_texture_coords_channels() print(indent .. "texture channels: " .. ntc) for i = 1,ntc do print(indent .. " channel "..i.. " components: " .. mesh:num_texture_coords_components(i)) end end function PrintNodes(node, indent) local indent = indent or "" print(indent .. "node " .. "'".. (node:name() or "???") .. "' (" .. tostring(node) ..")" .. " children:".. node:num_children() .. ", meshes:".. node:num_meshes()) --[[ local indent1 = indent .. " " print(indent1 .. "meshes:") indent1 = indent1 .. " " for _, mesh in ipairs(node:meshes()) do print(indent1 .. tostring(mesh)) end --]] for _, child in ipairs(node:children()) do PrintNodes(child, indent .. " ") end end function PrintMaterial(material, indent) local indent = indent or "" print(indent .. "material: '" .. (material:name() or "???").."'" .. " (" .. tostring(material) .. ")") indent = indent .. " " print(indent .. "twosided: ".. concatboolean(material:twosided())) print(indent .. "wireframe: ".. concatboolean(material:wireframe())) print(indent .. "blend: ".. (material:blend() or "-")) print(indent .. "color_diffuse: ".. concatcolor(material:color_diffuse())) print(indent .. "color_ambient: ".. concatcolor(material:color_ambient())) print(indent .. "color_specular: ".. concatcolor(material:color_specular())) print(indent .. "color_emissive: ".. concatcolor(material:color_emissive())) print(indent .. "color_transparent: ".. concatcolor(material:color_transparent())) print(indent .. "color_reflective: ".. concatcolor(material:color_reflective())) print(indent .. "opacity: ".. (material:opacity() or "-")) print(indent .. "shininess: ".. (material:shininess() or "-")) print(indent .. "shinpercent: ".. (material:shinpercent() or "-")) print(indent .. "refraction: ".. (material:refraction() or "-")) print(indent .. "bumpscaling: ".. (material:bumpscaling() or "-")) print(indent .. "reflectivity: ".. (material:reflectivity() or "-")) print(indent .. "shading: ".. (material:shading() or "-")) print(indent .. "global_bg_image: ".. ( material:global_bg_image() or "-")) local function PrintTexture(indent, tt, index) -- tt = texturetype print(indent .. "texture: " .. tt .. "[" .. index.."]") local indent = indent .. " " print(indent .. "path: " .. (material:texture_path(tt, index) or "-")) print(indent .. "channel: " .. (material:texture_channel(tt, index) or "-")) print(indent .. "op: " .. (material:texture_op(tt, index) or "-")) print(indent .. "mapping: " .. (material:texture_mapping(tt, index) or "-")) print(indent .. "blend: " .. (material:texture_blend(tt, index) or "-")) print(indent .. "mapmode (u,v): " .. concat2(material:texture_mapmode(tt, index))) print(indent .. "axis: " .. concatvec3(material:texture_axis(tt, index))) print(indent .. "translation: " .. concatvec2(material:texture_translation(tt, index))) print(indent .. "scaling: " .. concatvec2(material:texture_scaling(tt, index))) print(indent .. "rotation: " .. (material:texture_rotation(tt, index) or "-")) local flags = material:texture_flags(tt, index) print(indent .. "textureflags: " .. (flags and concatflags({ai.textureflags(flags)}) or "-")) end local function P(texturetype) for i = 1, material:texture_count(texturetype) do PrintTexture(indent, texturetype, i) end end P("diffuse") P("specular") P("ambient") P("emissive") P("height") P("normals") P("shininess") P("opacity") P("displacement") P("lightmap") P("reflection") P("unknown") end function PrintEmbeddedTexture(texture, n, indent) local indent = indent or "" print(indent .. "embedded texture: " .. n) indent = indent .. " " print(indent .. "compressed: ".. concatboolean(texture:is_compressed())) print(indent .. "format_hint: ".. (texture:format_hint() or "-")) print(indent .. "width: ".. (texture:width() or "-")) print(indent .. "height: ".. (texture:height() or "-")) print(indent .. "size (bytes): ".. (texture:size() or "-")) end function PrintLight(light, indent) local indent = indent or "" print(indent .. "light: '" .. (light:name() or "???").."'" .. " (" .. tostring(light) .. ")") indent = indent .. " " print(indent .. "source_type: ".. (light:source_type() or "-")) print(indent .. "attenuation_constant: ".. (light:attenuation_constant() or "-")) print(indent .. "attenuation_linear: ".. (light:attenuation_linear() or "-")) print(indent .. "attenuation_quadratic: ".. (light:attenuation_quadratic() or "-")) print(indent .. "angle_inner_cone: ".. (light:angle_inner_cone() or "-")) print(indent .. "angle_outer_cone: ".. (light:angle_outer_cone() or "-")) print(indent .. "position: ".. concatvec3(light:position())) print(indent .. "direction: ".. concatvec3(light:direction())) print(indent .. "color_diffuse: ".. concatvec3(light:color_diffuse())) print(indent .. "color_specular: ".. concatvec3(light:color_specular())) print(indent .. "color_ambient: ".. concatvec3(light:color_ambient())) end function PrintCamera(camera, indent) local indent = indent or "" print(indent .. "camera: '" .. (camera:name() or "???").."'" .. " (" .. tostring(camera) .. ")") indent = indent .. " " print(indent .. "aspect: ".. (camera:aspect() or "-")) print(indent .. "clip_plane_near: ".. (camera:clip_plane_near() or "-")) print(indent .. "clip_plane_far: ".. (camera:clip_plane_far() or "-")) print(indent .. "horizontal_fov: ".. (camera:horizontal_fov() or "-")) print(indent .. "position: ".. concatvec3(camera:position())) print(indent .. "up: ".. concatvec3(camera:up())) print(indent .. "look_at: ".. concatvec3(camera:look_at())) end function PrintHelp() print("\nInspect a 3D model file using MoonAssimp and prints a report on stdout.\n") print("Usage:") print(" "..arg[0].." <filename> [postprocessflags]") print(" "..arg[0].." [option]") print("Options:") print(" --help - print this help page") print(" --flags - list the postprocessflags") print(" --ext - list the supported extensions") print("Examples:") print(" "..arg[0].." mymodel.obj # use default flags") print(" "..arg[0].." mymodel.obj 0x8 # 'triangulate'") print(" "..arg[0].." mymodel.obj 0x8+0x20 # 'triangulate'+'gen normals'") print(" "..arg[0].." --flags # list flags") print(" "..arg[0].." --ext # list extensions") print("") end -- Main ----------------------------------------------------------------------- if not arg[1] then PrintHelp() return end if arg[1]:sub(1,2) == "--" then -- options if arg[1] == "--help" then PrintHelp() return end if arg[1] == "--flags" then print("Post process flags:") for _,v in ipairs(POSTPROCESSFLAGS) do print("- '"..v[1] .. "' = "..v[2]) end return elseif arg[1] == "--ext" then print(ai.get_extension_list()) return else print("invalid option '"..arg[1].."'") return end end filename = arg[1] -- Determine the post-process flags to be used: if arg[2] then local flags = tonumber(arg[2]) if not flags then flags = load("return "..arg[2])() end postprocessflags = {ai.postprocessflags(flags)} else postprocessflags = DEFAULT_POSTPROCESSFLAGS end -- Import the model: scene, errmsg = ai.import_file(filename, table.unpack(postprocessflags)) assert(scene, errmsg) -- Print the report: print("======================================================================") print("3D MODEL INSPECTION REPORT") print("======================================================================") print("model file: " .. filename) print("post process flags: ".. concatflags(postprocessflags)) mem = ai.get_memory_requirements(scene) print("\n-- Memory requirements: ----------------------------------------------") print("total: " .. mem.total .. " bytes") print("nodes: " .. mem.nodes .. " bytes") print("meshes: " .. mem.meshes .. " bytes") print("textures: " .. mem.textures .. " bytes") print("materials: " .. mem.materials .. " bytes") print("lights: " .. mem.lights .. " bytes") print("cameras: " .. mem.cameras .. " bytes") print("animations: " .. mem.animations .. " bytes") print("\n-- Scene -------------------------------------------------------------") flags = scene:flags() print("sceneflags: ".. concatflags({ai.sceneflags(flags)})) print("scene contents:") print(" meshes: " .. scene:num_meshes()) print(" materials: " .. scene:num_materials()) print(" textures: " .. scene:num_textures()) print(" lights: " .. scene:num_lights()) print(" cameras: " .. scene:num_cameras()) print(" animations: " .. scene:num_animations()) root = scene:root_node() print("\nNodes tree:") PrintNodes(root, " ") print("\n-- Meshes ------------------------------------------------------------") meshes = scene:meshes() for k, mesh in ipairs(meshes) do PrintMesh(mesh) print() end print("\n-- Materials ---------------------------------------------------------") materials = scene:materials() for k, material in ipairs(materials) do PrintMaterial(material) print() end print("\n-- Textures ----------------------------------------------------------") textures = scene:textures() for k, texture in ipairs(textures) do PrintEmbeddedTexture(texture, k) print() end print("\n-- Lights ------------------------------------------------------------") lights = scene:lights() for k, light in ipairs(lights) do PrintLight(light) print() end print("\n-- Cameras -----------------------------------------------------------") cameras = scene:cameras() for k, camera in ipairs(cameras) do PrintCamera(camera) print() end --[[ @@TODO: print("\n-- Animations --------------------------------------------------------") animations = scene:animations() for k, animation in ipairs(animations) do PrintAnimation(animation) print() end --]] print("\nEND OF REPORT")
return {'kummel','kumquat','kumtich','kumar','kummeling','kumquats'}
--[[ Provides a player's thumbnail to other components. Usage: Roact.createElement(Thumbnail, { userId = "-1", -- Must be a string render = function(thumbnail) return Roact.createElement("ImageLabel", { Image = thumbnail.image }) end }) --]] local Players = game:GetService("Players") local Promise = require(script.Parent.Parent.Lib.Promise) local Roact = require(script.Parent.Parent.Lib.Roact) local t = require(script.Parent.Parent.Lib.t) -- Must be one of the values from here: -- http://wiki.roblox.com/index.php?title=API:Enum/ThumbnailSize local AVATAR_SIZE = 420 local function fetchUserThumbnail(userId, thumbnailType) thumbnailType = thumbnailType or Enum.ThumbnailType.AvatarBust local size = ("Size{size}x{size}"):gsub("{size}", AVATAR_SIZE) return Promise.new(function(resolve, reject) spawn(function() local ok, result = pcall(function() return Players:GetUserThumbnailAsync(tonumber(userId), thumbnailType, Enum.ThumbnailSize[size]) end) if ok then resolve(result) else reject(result) end end) end) end local Thumbnail = Roact.Component:extend("Thumbnail") local Props = t.interface({ userId = t.string, render = t.callback, type = t.optional(t.enum(Enum.ThumbnailType)) }) function Thumbnail:init() self.state = { image = "" } end function Thumbnail:render() assert(Props(self.props)) return self.props.render({ image = self.state.image, size = Vector2.new(AVATAR_SIZE, AVATAR_SIZE) }) end function Thumbnail:didMount() fetchUserThumbnail(self.props.userId, self.props.thumbnailType) :andThen(function(image) self:setState({ image = image }) end) end return Thumbnail
--------------------------------------------------------------------------------------------------- -- func: capallskills -- desc: Caps all the players skills. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "" } function onTrigger(player) player:capAllSkills() player:PrintToPlayer( 'All skills capped!' ) end
-- Copyright 2016 krunkathos -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. local leveldata = {} require("lib/Tserial") leveldata.TIL_SIZE = 16 leveldata.template ={ { "<title>", 2, false }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" }, { "T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0","T0:0:0:0:0:0" } } function leveldata.save(filename) love.filesystem.write(filename, Tserial.pack(leveldata.map, nil, true)) end function leveldata.load(filename) if love.filesystem.exists(filename) then leveldata.map = Tserial.unpack(love.filesystem.read(filename)) else print("**** Could not open file "..filename) end end function leveldata.save_checkpoint(filename, new_cp) love.filesystem.write(filename, Tserial.pack({ new_cp }, nil, true)) end function leveldata.load_checkpoint(filename) local level = { 0 } if love.filesystem.exists(filename) then level = Tserial.unpack(love.filesystem.read(filename)) end return level[1] end function leveldata.update_checkpoint(filename, new_cp) if love.filesystem.exists(filename) then local old_cp = leveldata.load_checkpoint(filename) if new_cp > old_cp then leveldata.save_checkpoint(filename, new_cp) end else leveldata.save_checkpoint(filename, new_cp) end end function leveldata.getXY(level, x, y) local tx = math.floor(x / leveldata.TIL_SIZE) + 1 local ty = math.floor(y / leveldata.TIL_SIZE) if ty < 1 then ty = 1 end if ty > #leveldata.map[level]-1 then ty = #leveldata.map[level]-1 end if tx < 1 then tx = 1 end if tx > #leveldata.map[level][ty+1] then tx = #leveldata.map[level][ty+1] end return tx, ty end function leveldata.getTileAt(level, x, y) local tx, ty = leveldata.getXY(level, x, y) local element, param = leveldata.getBlock(level, tx, ty) local args = leveldata.mysplit(param, ":") if element == "T" then return tonumber(args[1]) end return 0 end function leveldata.getBlock(level, x, y) local str = leveldata.map[level][y+1][x] return string.sub(str, 1, 1), string.sub(str, 2, -1) end function leveldata.setTileAt(level, x, y, str) leveldata.map[level][y+1][x] = str end -- mysplit function courtesy of SuperFastNinja, stackoverflow.com function leveldata.mysplit(inputstr, sep) if sep == nil then sep = "%s" end local t={} local i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end function leveldata.myjoin(args, sep) local str = "" for a = 1, #args do str = str..args[a] if a < #args then str = str..sep end end return str end return leveldata
local KUI, E, L, V, P, G = unpack(select(2, ...)) local KQ = KUI:NewModule("KuiQuest", "AceEvent-3.0") KQ.modName = L["Quest"] -- Cache global variables local _G = _G local select, type, tostring, tonumber = select, type, tostring, tonumber local find, gsub = string.find, gsub -- WoW API / Variables local QuestFlagsPVP = QuestFlagsPVP local GetNumActiveQuests = GetNumActiveQuests local GetNumAvailableQuests = GetNumAvailableQuests local GetGossipAvailableQuests = GetGossipAvailableQuests local AcceptQuest = AcceptQuest local ConfirmAcceptQuest = ConfirmAcceptQuest local CompleteQuest = CompleteQuest local GetNumQuestChoices = GetNumQuestChoices local IsModifierKeyDown = IsModifierKeyDown local UnitGUID = UnitGUID -- Global variables that we don"t cache, list them here for the mikk"s Find Globals script -- GLOBALS: QuestInfo_GetRewardButton, QuestInfoItemHighlight function KQ:CheckConfigs() if UnitInRaid("player") and ( not KQ.db.inraid ) then return end if IsModifierKeyDown() then if ( KQ.db.diskey == 1 ) and IsAltKeyDown() then return elseif ( KQ.db.diskey == 2 ) and IsControlKeyDown() then return elseif ( KQ.db.diskey == 3 ) and IsShiftKeyDown() then return end end if (UnitGUID("target") and string.find(UnitGUID("target"), "(.*)-(.*)")) then local type, zero, server_id, instance_id, zone_uid, npc_id, spawn_uid = strsplit("-",UnitGUID("target")) if (npc_id and ((tonumber(npc_id) == 141584) or (tonumber(npc_id) == 142063)) -- Seal of Wartron (BfA) or (tonumber(npc_id) == 111243) -- Seal of Broken Fate (Legion) or ((tonumber(npc_id) == 87391) or (tonumber(npc_id) == 88570) or (tonumber(npc_id) == 96130)) -- Seal of Inevitable Fate + Seal of Tempered Fate (WoD) or ((tonumber(npc_id) == 64029) or (tonumber(npc_id) == 63996)) -- Warforged Seals (MoP) or (tonumber(npc_id) == 73305)) -- Mogu Rune of Fate (MoP) then return end end return true end function KQ:CheckQuestData() if KQ.db.dailiesonly then return end if QuestFlagsPVP() and ( not KQ.db.pvp ) then return end return true end function KQ:QUEST_GREETING() if KQ:CheckConfigs() and KQ.db.greeting then local numact,numava = GetNumActiveQuests(), GetNumAvailableQuests() if numact+numava == 0 then return end if numava > 0 then SelectAvailableQuest(1) end if numact > 0 then SelectActiveQuest(1) end end end function KQ:GOSSIP_SHOW() if KQ:CheckConfigs() and KQ.db.greeting then if GetGossipAvailableQuests() then SelectGossipAvailableQuest(1) elseif GetGossipActiveQuests() then SelectGossipActiveQuest(1) end end end function KQ:QUEST_DETAIL() --if IsQuestIgnored() then --return --end if KQ:CheckConfigs() and KQ:CheckQuestData() and KQ.db.accept then AcceptQuest() end end function KQ:QUEST_ACCEPT_CONFIRM() if KQ:CheckConfigs() and KQ.db.escort then ConfirmAcceptQuest() end end function KQ:QUEST_PROGRESS() if KQ:CheckConfigs() and KQ.db.complete then CompleteQuest() end end local dbg = 0; function KQ:SelectQuestReward(index) local frame = QuestInfoFrame.rewardsFrame; if dbg == 1 then KUI:Print("index: "..index) end local button = QuestInfo_GetRewardButton(frame, index) if (button.type == "choice") then QuestInfoItemHighlight:ClearAllPoints() QuestInfoItemHighlight:SetOutside(button.Icon) if E.private.skins.blizzard.enable ~= true or E.private.skins.blizzard.quest ~= true then QuestInfoItemHighlight:SetPoint("TOPLEFT", button, "TOPLEFT", -8, 7); else button.Name:SetTextColor(1, 1, 0) end QuestInfoItemHighlight:Show() -- set choice QuestInfoFrame.itemChoice = button:GetID() end end function KQ:QUEST_COMPLETE() if KQ:CheckConfigs() and KQ.db.complete then if GetNumQuestChoices() == 0 then GetQuestReward(QuestFrameRewardPanel.itemChoice) elseif GetNumQuestChoices() == 1 and QuestFrameRewardPanel.itemChoice == nil then GetQuestReward(1) end end if KQ.db.reward then local choice, highest = 1, 0 local num = GetNumQuestChoices() if dbg == 1 then KUI:Print("GetNumQuestChoices"..num) end if num <= 0 then return end -- no choices for index = 1, num do local link = GetQuestItemLink("choice", index); if link then local price = select(11, GetItemInfo(link)) if price and price > highest then highest = price choice = index end end end if dbg == 1 then KUI:Print("Choice: "..choice) end KQ:SelectQuestReward(choice) end end function KQ:UI_INFO_MESSAGE(event, id, msg) if (msg ~= nil) then if (E.db.KlixUI.quest.announce.enable) then local questText = gsub(msg, "(.*):%s*([-%d]+)%s*/%s*([-%d]+)%s*$", "%1", 1) KQ:SendDebugMsg("Quest Text: "..questText) if (questText ~= msg) then local ii, jj, strItemName, iNumItems, iNumNeeded = string.find(msg, "(.*):%s*([-%d]+)%s*/%s*([-%d]+)%s*$") local stillNeeded = iNumNeeded - iNumItems KQ:SendDebugMsg("Item Name: "..strItemName.." :: Num Items: "..iNumItems.." :: Num Needed: "..iNumNeeded.." :: Still Need: "..stillNeeded) if(stillNeeded == 0 and KQ.db.announce.every == 0) then KQ:SendMsg(L["Completed: "]..msg) elseif(KQ.db.announce.every > 0) then local every = math.fmod(iNumItems, KQ.db.announce.every) KQ:SendDebugMsg("Every fMod: "..every) if(every == 0 and stillNeeded > 0) then KQ:SendMsg(L["Progress: "]..msg) elseif(stillNeeded == 0) then KQ:SendMsg(L["Completed: "]..msg) end end end end end end function KQ:SendDebugMsg(msg) if(msg ~= nil and E.db.KlixUI.quest.announce.debug) then KUI:Print("Quest Announce Debug: "..msg) end end function KQ:SendMsg(msg) local announceIn = E.db.KlixUI.quest.announce.In local announceTo = E.db.KlixUI.quest.announce.To if (msg ~= nil and E.db.KlixUI.quest.announce.enable) then if(announceTo.chatFrame) then if(announceIn.say) then SendChatMessage(msg, "SAY") KQ:SendDebugMsg("KQ:SendMsg(SAY) :: "..msg) end if(announceIn.party) then if(IsInGroup() and GetNumSubgroupMembers(LE_PARTY_CATEGORY_HOME) > 0) then SendChatMessage(msg, "PARTY") end KQ:SendDebugMsg("KQ:SendMsg(PARTY) :: "..msg) end if(announceIn.instance) then if (IsInInstance() and GetNumSubgroupMembers(LE_PARTY_CATEGORY_INSTANCE) > 0) then SendChatMessage(msg, "INSTANCE_CHAT") end KQ:SendDebugMsg("KQ:SendMsg(INSTANCE) :: "..msg) end if(announceIn.guild) then if(IsInGuild()) then SendChatMessage(msg, "GUILD") end KQ:SendDebugMsg("KQ:SendMsg(GUILD) :: "..msg) end if(announceIn.officer) then if(IsInGuild()) then SendChatMessage(msg, "OFFICER") end KQ:SendDebugMsg("KQ:SendMsg(OFFICER) :: "..msg) end if(announceIn.whisper) then local who = announceIn.whisperWho if(who ~= nil and who ~= "") then SendChatMessage(msg, "WHISPER", nil, who) KQ:SendDebugMsg("KQ:SendMsg(WHISPER) :: "..who.."-"..msg) end end end if(announceTo.raidWarningFrame) then RaidNotice_AddMessage(RaidWarningFrame, msg, ChatTypeInfo["RAID_WARNING"]) end if(announceTo.uiErrorsFrame) then UIErrorsFrame:AddMessage(msg, 1.0, 1.0, 0.0, 7) end if(E.db.KlixUI.quest.announce.sound) then PlaySound(PlaySoundKitID and "RAID_WARNING" or 8959) end end KQ:SendDebugMsg("KQ:SendMsg - "..msg) end function KQ:Initialize() KQ.db = E.db.KlixUI.quest if E.db.KlixUI.quest.enable then self:CheckConfigs() self:CheckQuestData() self:RegisterEvent("QUEST_GREETING") self:RegisterEvent("GOSSIP_SHOW") self:RegisterEvent("QUEST_DETAIL") self:RegisterEvent("QUEST_ACCEPT_CONFIRM") self:RegisterEvent("QUEST_PROGRESS") self:RegisterEvent("QUEST_COMPLETE") end if E.db.KlixUI.quest.announce.enable then self:RegisterEvent("UI_INFO_MESSAGE") end function KQ:ForUpdateAll() KQ.db = E.db.KlixUI.quest end end local function InitializeCallback() KQ:Initialize() end KUI:RegisterModule(KQ:GetName(), InitializeCallback)
require 'ex' scriptPath = ((debug.getinfo(1, "S").source:match("@(.+)[\\/]") or '.') .. '\\'):gsub('\\', '/'):lower() function test(a, b) if a ~= b then print('Actual:', a) print('Expected:', b) assert() end end test(os.path.add_extension('', 'ext'), '.ext') test(os.path.add_extension(' ', ' ext'), ' . ext') test(os.path.add_extension('', '.ext'), '.ext') test(os.path.add_extension('hello', 'ext'), 'hello.ext') test(os.path.add_extension('hello', '.ext'), 'hello.ext') test(os.path.add_extension('hello.txt', 'ext'), 'hello.txt.ext') test(os.path.add_extension('hello.txt', '.ext'), 'hello.txt.ext') test(os.path.add_slash(''), '/') test(os.path.add_slash(' '), ' /') test(os.path.add_slash('hello'), 'hello/') test(os.path.add_slash(' hello'), ' hello/') test(os.path.add_slash(' hello '), ' hello /') test(os.path.add_slash('hello/'), 'hello/') test(os.path.append('', 'filename.txt'), 'filename.txt') test(os.path.append('', 'dir', 'filename.txt'), 'dir/filename.txt') test(os.path.append('', 'dirA', '', 'dirB', 'filename.txt'), 'dirA/dirB/filename.txt') test(os.path.append('..', 'filename.txt'), '../filename.txt') test(os.path.append('root', 'filename.txt'), 'root/filename.txt') test(os.path.append('root', 'dir', 'filename.txt'), 'root/dir/filename.txt') test(os.path.append('root', 'dirA', '', 'dirB', 'filename.txt'), 'root/dirA/dirB/filename.txt') test(os.path.append('root', 'dirA', '', 'dirB', '..', 'filename.txt'), 'root/dirA/dirB/../filename.txt') test(os.path.append('root', 'dirA', '', '/dirB', '..', 'filename.txt'), '/dirB/../filename.txt') test(os.path.combine('', 'filename.txt'), 'filename.txt') test(os.path.combine('', 'dir', 'filename.txt'), 'dir/filename.txt') test(os.path.combine('', 'dirA', '', 'dirB', 'filename.txt'), 'dirA/dirB/filename.txt') test(os.path.combine('..', 'filename.txt'), '../filename.txt') test(os.path.combine('root', 'filename.txt'), 'root/filename.txt') test(os.path.combine('root', 'dir', 'filename.txt'), 'root/dir/filename.txt') test(os.path.combine('root', 'dirA', '', 'dirB', 'filename.txt'), 'root/dirA/dirB/filename.txt') test(os.path.combine('root', 'dirA', '', 'dirB', '..', 'filename.txt'), 'root/dirA/filename.txt') test(os.path.combine('c:/test/test2', '..', '.'), 'c:/test/') test(os.path.combine('c:/test/test2', '..', '.', 'filename.txt'), 'c:/test/filename.txt') test(os.path.combine('c:/test/test2', '..'), 'c:/test/') test(os.path.combine('c:/test/test2', '..', '..'), 'c:/') test(os.path.combine('c:/test/test2', '..', '..', '..'), 'c:/') test(os.path.escape(''), '') test(os.path.escape('filename.txt'), 'filename.txt') if os.getenv("OS") == "Windows_NT" then test(os.path.escape(' '), '" "') test(os.path.escape('file name.txt'), '"file name.txt"') else test(os.path.escape(' '), '\\ ') test(os.path.escape('file name.txt'), 'file\\ name.txt') end test(os.path.exists(scriptPath .. 'pathtests.lua'), true) test(os.path.exists(scriptPath .. 'pathtests2.lua'), false) test(os.path.find_extension(''), nil) test(os.path.find_extension('filename'), nil) test(os.path.find_extension('.lua'), 1) test(os.path.find_extension('pathtests.lua'), 10) test(os.path.find_extension('pathtests'), nil) test(os.path.find_filename('pathtests.lua'), 1) test(os.path.find_filename('/pathtests'), 2) test(os.path.find_filename('c:/pathtests'), 4) test(os.path.find_filename('c:pathtests'), 3) test(os.path.get_extension(''), '') test(os.path.get_extension('filename'), '') test(os.path.get_extension('filename.ext'), '.ext') test(os.path.get_extension('filename.txt.ext'), '.ext') test(os.path.get_filename(''), '') test(os.path.get_filename('filename'), 'filename') test(os.path.get_filename('filename.ext'), 'filename.ext') test(os.path.get_filename('c:/directory/filename.ext'), 'filename.ext') test(os.path.get_filename('c:/directory/'), '') test(os.path.is_directory(''), false) test(os.path.is_directory(scriptPath .. 'pathtests.lua'), false) test(os.path.is_directory('.'), true) test(os.path.is_directory('..'), true) test(os.path.is_directory(scriptPath .. '../tests'), true) test(os.path.is_directory(scriptPath .. '../tests/'), true) test(os.path.is_file(''), nil) test(os.path.is_file(scriptPath .. 'pathtests.lua'), true) test(os.path.is_file('.'), false) test(os.path.is_file('..'), false) test(os.path.is_file(scriptPath .. '../tests'), false) test(os.path.is_file(scriptPath .. '../tests/'), nil) test(os.path.is_relative(''), true) test(os.path.is_relative('filename.ext'), true) test(os.path.is_relative('/filename.ext'), false) test(os.path.is_relative('c:/filename.ext'), false) test(os.path.is_root(''), false) test(os.path.is_root('filename.ext'), false) test(os.path.is_root('/filename.ext'), true) test(os.path.is_root('c:/filename.ext'), true) test(os.path.is_unc(''), false) test(os.path.is_unc('filename.ext'), false) test(os.path.is_unc('/filename.ext'), false) test(os.path.is_unc('c:/filename.ext'), false) test(os.path.is_unc('\\\\share'), true) test(os.path.is_unc('//share'), true) local cwd = os.getcwd():gsub('\\', '/') test(os.path.make_absolute(''), cwd) test(os.path.make_absolute('.'), cwd .. '/') test(os.path.make_absolute('..'), cwd:match('(.+)/') .. '/') test(os.path.make_absolute('abc'), cwd .. '/abc') test(os.path.make_backslash(''), '') test(os.path.make_backslash(' '), ' ') test(os.path.make_backslash('\\\\abc'), '\\\\abc') test(os.path.make_backslash('//abc'), '\\\\abc') test(os.path.make_backslash('c:/abc/def/'), 'c:\\abc\\def\\') test(os.path.make_slash(''), '') test(os.path.make_slash(' '), ' ') test(os.path.make_slash('\\\\abc'), '//abc') test(os.path.make_slash('//abc'), '//abc') test(os.path.make_slash('c:\\abc\\def\\'), 'c:/abc/def/') do os.remove('out.dat') local file = io.open('out.dat', 'wb') file:write('junk') file:close() test(os.path.is_writable('out.dat'), true) os.chmod('out.dat', 'r') test(os.path.is_writable('out.dat'), false) os.path.make_writable('out.dat') test(os.path.is_writable('out.dat'), true) os.remove('out.dat') end test(os.path.match('', ''), true) test(os.path.match('', '*'), true) test(os.path.match('', '*.*'), false) test(os.path.match('', 'a*'), false) test(os.path.match('abcdefg.txt', 'a*'), true) test(os.path.match('abcdefg.txt', 'a*b*c?e*'), true) test(os.path.match('abcdefg.txt', 'a*b*c?f*'), false) test(os.path.match('abcdefg.txt', '*.'), false) test(os.path.match('abcdefg.txt', '*.t'), false) test(os.path.match('abcdefg.txt', '*.t*'), true) test(os.path.match('abcdefg.txt', '*.t'), false) test(os.path.match('abcdefg.txt', '*.*t'), true) test(os.path.match('abcdefg.txt', '*.*x'), false) test(os.path.match('abcdefg.txt', '*.txt'), true) test(os.path.remove_directory(''), '') test(os.path.remove_directory(' \t'), ' \t') test(os.path.remove_directory('abc'), 'abc') test(os.path.remove_directory('/abc.'), 'abc.') test(os.path.remove_directory('/dir/abc.'), 'abc.') test(os.path.remove_directory('c:/abc.'), 'abc.') test(os.path.remove_directory('c:/dir/abc'), 'abc') test(os.path.remove_extension(''), '') test(os.path.remove_extension(' \t'), ' \t') test(os.path.remove_extension('abc'), 'abc') test(os.path.remove_extension('abc.'), 'abc') test(os.path.remove_extension('abc.txt'), 'abc') test(os.path.remove_extension('abc.txt.dat'), 'abc.txt') test(os.path.remove_filename(''), '') test(os.path.remove_filename(' \t'), '') test(os.path.remove_filename('abc'), '') test(os.path.remove_filename('/abc.'), '/') test(os.path.remove_filename('/dir/abc.'), '/dir/') test(os.path.remove_filename('c:/abc.'), 'c:/') test(os.path.remove_filename('c:/dir/abc'), 'c:/dir/') test(os.path.remove_slash(''), '') test(os.path.remove_slash(' \t'), ' \t') test(os.path.remove_slash('abc'), 'abc') test(os.path.remove_slash('abc/'), 'abc') test(os.path.replace_extension('', 'ext'), '.ext') test(os.path.replace_extension('', '.ext'), '.ext') test(os.path.replace_extension('hello', 'ext'), 'hello.ext') test(os.path.replace_extension('hello', '.ext'), 'hello.ext') test(os.path.replace_extension('hello.txt', 'ext'), 'hello.ext') test(os.path.replace_extension('hello.txt', '.ext'), 'hello.ext') test(os.path.replace_extension('hello.txt.dat', 'ext'), 'hello.txt.ext') test(os.path.replace_extension('hello.txt.dat', '.ext'), 'hello.txt.ext') test(os.path.simplify(''), '') test(os.path.simplify('abc'), 'abc') test(os.path.simplify('.abc'), '.abc') test(os.path.simplify('./abc'), 'abc') test(os.path.simplify('..abc'), '..abc') test(os.path.simplify('../abc'), '../abc') test(os.path.simplify('abc/////def'), 'abc/def') test(os.path.simplify('abc/././././def'), 'abc/def') test(os.path.simplify('c:/somedir/.././././def'), 'c:/def') test(os.path.simplify('abc/.././././def'), 'def') test(os.path.simplify('abc/ABC/../../../../def'), 'def') test(os.path.simplify('c:\\abc\\ABC\\../..\\../..\\def'), 'c:/def') test(os.path.simplify('\\\\uncserver\\pathA\\file.txt'), '\\\\uncserver/pathA/file.txt') function compare_split(path, expectedDirname, expectedFilename) local actualDirname, actualFilename = os.path.split(path) return actualDirname == expectedDirname and actualFilename == expectedFilename end test(compare_split('', '', ''), true) test(compare_split('abc.txt', '', 'abc.txt'), true) test(compare_split('/', '/', ''), true) test(compare_split('/abc', '/', 'abc'), true) test(compare_split('/abc/', '/abc/', ''), true) test(compare_split('c:/', 'c:/', ''), true) test(compare_split('c:/abc', 'c:/', 'abc'), true) test(compare_split('c:/abc/', 'c:/abc/', ''), true) test(os.path.trim('abc.txt'), 'abc.txt') test(os.path.trim(' abc.txt'), 'abc.txt') test(os.path.trim('abc.txt '), 'abc.txt') test(os.path.trim(' \t abc.txt \t \t \t '), 'abc.txt') test(os.path.unescape(''), '') if os.getenv("OS") == "Windows_NT" then test(os.path.unescape('"'), '') test(os.path.unescape('""'), '') test(os.path.unescape('" "'), ' ') test(os.path.unescape('"file with spaces'), 'file with spaces') test(os.path.unescape('"file with spaces"'), 'file with spaces') else test(os.path.unescape('"'), '"') test(os.path.unescape('""'), '""') test(os.path.unescape('"\\ "'), '" "') test(os.path.unescape('"file\\ with\\ spaces'), '"file with spaces') test(os.path.unescape('"file\\ with\\ spaces"'), '"file with spaces"') end
RatingsFetcher = {} function RatingsFetcher.requestAll() dbQuery(function(qh) local res = dbPoll(qh, 0) if res then AllMapsRatings.receiveRatingsFromDatabase(res) end end, Database.getConnection(), 'SELECT `mapresourcename`, sum(case when `rating`= 1 then 1 else 0 end) AS likes, sum(case when `rating`= 0 then 1 else 0 end) AS dislikes FROM `mapratings` GROUP BY `mapresourcename') end function RatingsFetcher.request() local resname = getResourceName(exports.mapmanager:getRunningGamemodeMap()) if not resname then outputDebugString("No running map to fetch") return end dbQuery(function(qh) local res = dbPoll(qh, 0) if res then CurrentMapRatings.receiveRatingsFromDatabase(resname, res) end end, Database.getConnection(), 'SELECT `forumid`, `rating` FROM `mapratings` WHERE `mapresourcename` = ?', resname) end
-- Autogenerated from KST: please remove this line if doing any edits by hand! local luaunit = require("luaunit") require("valid_fail_contents") TestValidFailContents = {} function TestValidFailContents:test_valid_fail_contents() luaunit.assertErrorMsgMatches(".+: not equal, expected .*, but got .*", ValidFailContents.from_file, ValidFailContents, "src/fixed_struct.bin") end
local service = require "../src/service" describe("The check module", function() it("falls back to a display", function() local expected = "DISPLAY=:0" local actual = service.get_display() assert.are.equal(expected, actual) end) it("constructs key/values for the service file options", function() local expected = 'Environment="DISPLAY=:0"' local actual = service.make_option('Environment', 'DISPLAY=:0') assert.are.equal(expected, actual) end) it("creates a service file given some parameters", function() local expected = [[ [Unit] Description="Check Republic Service" [Service] User="joe" Type="oneshot" Environment="DISPLAY=:0" Environment="XAUTH=/bla/bla" Environment="DBUS=/blabla" ExecStart="/home/joe/bin/check-republicd"]] local actual = service.make_service_file( "joe", "DISPLAY=:0", "XAUTH=/bla/bla", "DBUS=/blabla", "/home/joe/bin/check-republicd" ) assert.are.equal(expected, actual) end) end)
-------------------------------- -- @module DrawNode -- @extend Node -- @parent_module cc -------------------------------- -- @function [parent=#DrawNode] drawQuadraticBezier -- @param self -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #unsigned int int -- @param #color4f_table color4f -------------------------------- -- @function [parent=#DrawNode] onDraw -- @param self -- @param #mat4_table mat4 -- @param #unsigned int int -------------------------------- -- @function [parent=#DrawNode] clear -- @param self -------------------------------- -- @function [parent=#DrawNode] drawTriangle -- @param self -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #color4f_table color4f -------------------------------- -- @function [parent=#DrawNode] drawDot -- @param self -- @param #vec2_table vec2 -- @param #float float -- @param #color4f_table color4f -------------------------------- -- @function [parent=#DrawNode] drawCubicBezier -- @param self -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #unsigned int int -- @param #color4f_table color4f -------------------------------- -- @function [parent=#DrawNode] drawSegment -- @param self -- @param #vec2_table vec2 -- @param #vec2_table vec2 -- @param #float float -- @param #color4f_table color4f -------------------------------- -- @function [parent=#DrawNode] create -- @param self -- @return DrawNode#DrawNode ret (return value: cc.DrawNode) -------------------------------- -- @function [parent=#DrawNode] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table mat4 -- @param #unsigned int int return nil
RPGM.RegisteredFonts = RPGM.RegisteredFonts or {} local registeredFonts = RPGM.RegisteredFonts do RPGM.SharedFonts = RPGM.SharedFonts or {} local sharedFonts = RPGM.SharedFonts function RPGM.RegisterFontUnscaled(name, font, size, weight) weight = weight or 500 local identifier = font .. size .. ":" .. weight local fontName = "RPGM:" .. identifier registeredFonts[name] = fontName if sharedFonts[identifier] then return end sharedFonts[identifier] = true surface.CreateFont(fontName, { font = font, size = size, weight = weight, antialias = true }) end end do RPGM.ScaledFonts = RPGM.ScaledFonts or {} local scaledFonts = RPGM.ScaledFonts function RPGM.RegisterFont(name, font, size, weight) scaledFonts[name] = { font = font, size = size, weight = weight } RPGM.RegisterFontUnscaled(name, font, RPGM.Scale(size), weight) end hook.Add("OnScreenSizeChanged", "RPGM.ReRegisterFonts", function() for k,v in pairs(scaledFonts) do RPGM.RegisterFont(k, v.font, v.size, v.weight) end end) end do local setFont = surface.SetFont local function setRPGMFont(font) local RPGMFont = registeredFonts[font] if RPGMFont then setFont(RPGMFont) return end setFont(font) end RPGM.SetFont = setRPGMFont local getTextSize = surface.GetTextSize function RPGM.GetTextSize(text, font) if font then setRPGMFont(font) end return getTextSize(text) end function RPGM.GetRealFont(font) return registeredFonts[font] end end
-- * Metronome IM * -- -- This file is part of the Metronome XMPP server and is released under the -- ISC License, please see the LICENSE file in this source package for more -- information about copyright and licensing. -- -- As per the sublicensing clause, this file is also MIT/X11 Licensed. -- ** Copyright (c) 2009-2013, Matthew Wild, Waqas Hussain -- XEP-0082: XMPP Date and Time Profiles local os_date = os.date; local os_time = os.time; local os_difftime = os.difftime; local error = error; local tonumber = tonumber; module "datetime" function date(t) return os_date("!%Y-%m-%d", t); end function datetime(t) return os_date("!%Y-%m-%dT%H:%M:%SZ", t); end function time(t) return os_date("!%H:%M:%S", t); end function legacy(t) return os_date("!%Y%m%dT%H:%M:%S", t); end function parse(s) if s then local year, month, day, hour, min, sec, tzd; year, month, day, hour, min, sec, tzd = s:match("^(%d%d%d%d)-?(%d%d)-?(%d%d)T(%d%d):(%d%d):(%d%d)%.?%d*([Z+%-].*)$"); if year then local time_offset = os_difftime(os_time(os_date("*t")), os_time(os_date("!*t"))); -- to deal with local timezone local tzd_offset = 0; if tzd ~= "" and tzd ~= "Z" then local sign, h, m = tzd:match("([+%-])(%d%d):?(%d*)"); if not sign then return; end if #m ~= 2 then m = "0"; end h, m = tonumber(h), tonumber(m); tzd_offset = h * 60 * 60 + m * 60; if sign == "-" then tzd_offset = -tzd_offset; end end sec = (sec + time_offset) - tzd_offset; return os_time({year=year, month=month, day=day, hour=hour, min=min, sec=sec, isdst=false}); end end end return _M;
data:extend({ { type = "recipe", name = "replication-lab", enabled = "true", ingredients = { {'rare-earth-magnet', 5}, {'copper-plate', 10} }, result = "replication-lab" }, { type = "item", name = "replication-lab", icon = "__replicators__/graphics/icons/replication-lab.png", flags = {"goes-to-quickbar"}, subgroup = "replication-research", order = "a[replication-lab]", place_result = "replication-lab", stack_size = 50, }, { type = "lab", name = "replication-lab", icon = "__replicators__/graphics/icons/replication-lab.png", flags = {"placeable-player", "player-creation"}, minable = {mining_time = 1, result = "replication-lab"}, max_health = 150, corpse = "big-remnants", dying_explosion = "big-explosion", collision_box = {{-1.2, -1.2}, {1.2, 1.2}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, light = {intensity = 0.75, size = 8}, on_animation = { filename = "__replicators__/graphics/entity/replication-lab/replication-lab.png", width = 113, height = 91, frame_count = 33, line_length = 11, animation_speed = 1 / 3, shift = {0.2, 0.15} }, off_animation = { filename = "__replicators__/graphics/entity/replication-lab/replication-lab.png", width = 113, height = 91, frame_count = 1, shift = {0.2, 0.15} }, working_sound = { sound = { filename = "__base__/sound/lab.ogg", volume = 0.7 }, apparent_volume = 1.5 }, energy_source = { type = "electric", usage_priority = "secondary-input" }, energy_usage = "60kW", inputs = { "rare-earth", "rare-earth-magnet", "superconductor", "ion-conduit" }, module_specification = { module_slots = 2, }, }, })
bracketl = "{" bracketr = "}" compare = {">", "<", "≥", "≤"} operation = {"+", "-"} stampa = 3 ind = math.random(2) sign = operation[ind] ind2 = math.random(2) sign2 = operation[ind2] index = math.random(4) relat1 = compare[index] if (ind == 1) then relat2 = compare[index] else if (index < 3) then relat2 = compare[3 - index] else relat2 = compare[7 - index] end end term = math.random(699) + 101; solution = math.random(900 - term) + 100; value = term + solution; if (ind == 2) then temp = value; value = term; term = temp; end t2 = math.floor(term/2) rest = term - 2 * t2 if (ind2 == ind) then temp = math.random(t2 - 30) term1 = t2 + rest + temp term3 = t2 - temp else temp = t2 + math.random(t2 - 10) term1 = t2 + rest + temp term3 = temp - t2 end answ = "x " .. "\(\small\in\) " .. bracketl if (index == 1 or index == 3) then if (ind == 1) then if (index == 1) then min_range = 1 max_range = stampa else min_range = 0 max_range = stampa - 1 end for i = min_range, max_range do out = solution + i answ = answ .. lib.check_number(out,25) .. ", " end answ = answ .. "..." .. bracketr neq = " x " .. lib.check_one_option_dropdown(compare,relat2).. " " .. lib.check_number(solution,25) else if (index == 3) then min_range = 1 max_range = stampa else min_range = 0 max_range = stampa - 1 end answ = answ .. lib.check_number(1,25) for i = min_range, max_range do out = solution - stampa + i answ = answ .. ", " .. lib.check_number(out,25) end answ = answ .. bracketr neq = lib.check_number(1,25) .. " " .. lib.check_one_option_dropdown(compare,compare[4]).. " x " .. lib.check_one_option_dropdown(compare,relat2).. " " .. lib.check_number(solution,25) end end if (index == 2 or index == 4) then if (ind == 1) then if (index == 2) then min_range = 0 max_range = stampa -1 else min_range = 1 max_range = stampa end answ = answ .. lib.check_number(1,25) for i = min_range, max_range do out = solution - stampa + i answ = answ .. ", " .. lib.check_number(out,25) end answ = answ .. bracketr neq = lib.check_number(1,25) .. " " .. lib.check_one_option_dropdown(compare,compare[4]).. " x " .. lib.check_one_option_dropdown(compare,relat2).. " " .. lib.check_number(solution,25) else if (index == 2) then min_range = 1 max_range = stampa else min_range = 0 max_range = stampa - 1 end for i = min_range, max_range do out = solution + i answ = answ .. lib.check_number(out,25) .. ", " end temp = term - 1 answ = answ .. "..." .. lib.check_number(temp,25) .. bracketr neq = lib.check_number(temp,25) .. " " .. lib.check_one_option_dropdown(compare,compare[3]).. " x " .. lib.check_one_option_dropdown(compare,relat2).. " " .. lib.check_number(solution,25) end end
-- Copyright 2012 by Till Tantau -- -- This file may be distributed an/or modified -- -- 1. under the LaTeX Project Public License and/or -- 2. under the GNU Public License -- -- See the file doc/generic/pgf/licenses/LICENSE for more information -- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/control/Sublayouts.lua,v 1.4 2013/09/23 20:04:26 tantau Exp $ local function full_print(g, pref) local s = "" for _,v in ipairs(g.vertices) do s = s .. tostring(v) .. "[" .. tostring(v.pos) .. "]\n " end s = s .. "\n" for _,a in ipairs(g.arcs) do for _,e in ipairs(a.syntactic_edges) do s = s .. tostring(e) .. "(" .. tostring(e.path) .. ")\n" end end pgf.debug((pref or "") .. s) end --- -- The |Sublayouts| module handles graphs for which multiple layouts are defined. -- -- Please see Section~\ref{section-gd-sublayouts} for an overview of -- sublayouts. -- local Sublayouts = {} -- Namespace require("pgf.gd.control").Sublayouts = Sublayouts -- Includes local Digraph = require "pgf.gd.model.Digraph" local Vertex = require "pgf.gd.model.Vertex" local Coordinate = require "pgf.gd.model.Coordinate" local Path = require "pgf.gd.model.Path" local lib = require "pgf.gd.lib" local InterfaceCore = require "pgf.gd.interface.InterfaceCore" local Storage = require "pgf.gd.lib.Storage" -- Storages local subs = Storage.newTableStorage() local already_nudged = Storage.new() local positions = Storage.newTableStorage() -- Offset a node by an offset. This will \emph{also} offset all -- subnodes, which arise from sublayouts. -- -- @param vertex A vertex -- @param pos A offset -- local function offset_vertex(v, delta) v.pos:shiftByCoordinate(delta) for _,sub in ipairs(subs[v]) do offset_vertex(sub, delta) end end -- Nudge positioning. You can call this function several times on the -- same graph; nudging will be done only once. -- -- @param graph A graph -- local function nudge(graph) for _,v in ipairs(graph.vertices) do local nudge = v.options['nudge'] if nudge and not already_nudged[v] then offset_vertex(v, nudge) already_nudged[v] = true end end end -- Create subgraph nodes -- -- @param scope A scope -- @param syntactic_digraph The syntactic digraph. -- @param test Only for vertices whose subgraph collection passes this test will we create subgraph nodes local function create_subgraph_node(scope, syntactic_digraph, vertex) local subgraph_collection = vertex.subgraph_collection local binding = InterfaceCore.binding local cloud = {} -- Add all points of n's collection, except for v itself, to the cloud: for _,v in ipairs(subgraph_collection.vertices) do if vertex ~= v then assert(syntactic_digraph:contains(v), "the layout must contain all nodes of the subgraph") for _,p in ipairs(v.path) do if type(p) == "table" then cloud[#cloud+1] = p + v.pos end end end end for _,e in ipairs(subgraph_collection.edges) do for _,p in ipairs(e.path) do if type(p) == "table" then cloud[#cloud+1] = p:clone() end end end local x_min, y_min, x_max, y_max, c_x, c_y = Coordinate.boundingBox(cloud) -- Shift the graph so that it is centered on the origin: for _,p in ipairs(cloud) do p:unshift(c_x,c_y) end local o = vertex.subgraph_info.generated_options o[#o+1] = { key = "subgraph point cloud", value = table.concat(lib.imap(cloud, tostring)) } o[#o+1] = { key = "subgraph bounding box height", value = tostring(y_max-y_min) .. "pt" } o[#o+1] = { key = "subgraph bounding box width", value = tostring(x_max-x_min) .. "pt" } -- And now, the "grand call": binding:createVertex(vertex.subgraph_info) -- Shift it were it belongs vertex.pos:shift(c_x,c_y) -- Remember all the subnodes for nudging and regardless -- positioning local s = {} for _,v in ipairs(subgraph_collection.vertices) do if v ~= vertex then s[#s+1] = v end end subs[vertex] = s end -- Tests whether two graphs have a vertex in common local function intersection(g1, g2) for _,v in ipairs(g1.vertices) do if g2:contains(v) then return v end end end -- Tests whether a graph is a set is a subset of another local function special_vertex_subset(vertices, graph) for _,v in ipairs(vertices) do if not graph:contains(v) and not (v.kind == "subgraph node") then return false end end return true end --- -- The layout recursion. See \ref{section-gd-sublayouts} for details. -- -- @param scope The graph drawing scope -- @param layout The to-be-laid-out collection -- @param fun The to-be-called function for laying out the graph. -- processed. This stack is important when a new syntactic vertex is -- added by the algorithm: In this case, this vertex is added to all -- layouts on this stack. -- -- @return A laid out graph. function Sublayouts.layoutRecursively(scope, layout, fun) -- Step 1: Iterate over all sublayouts of the current layout: local resulting_graphs = {} local loc = Storage.new() -- Now, iterate over all sublayouts for i,child in ipairs(layout:childrenOfKind(InterfaceCore.sublayout_kind)) do resulting_graphs[i] = Sublayouts.layoutRecursively(scope, child, fun) loc[resulting_graphs[i]] = child end -- Step 2: Run the merge process: local merged_graphs = {} while #resulting_graphs > 0 do local n = #resulting_graphs -- Setup marked array: local marked = {} for i=1,n do marked[i] = false end -- Mark first graph and copy everything from there marked[1] = true local touched = Storage.new() for _,v in ipairs(resulting_graphs[1].vertices) do v.pos = positions[v][resulting_graphs[1]] touched[v] = true end -- Repeatedly find a node that is connected to a marked node: local i = 1 while i <= n do if not marked[i] then for j=1,n do if marked[j] then local v = intersection(resulting_graphs[i], resulting_graphs[j]) if v then -- Aha, they intersect at vertex v -- Mark the i-th graph: marked[i] = true connected_some_graph = true -- Shift the i-th graph: local x_offset = v.pos.x - positions[v][resulting_graphs[i]].x local y_offset = v.pos.y - positions[v][resulting_graphs[i]].y for _,u in ipairs(resulting_graphs[i].vertices) do if not touched[u] then touched[u] = true u.pos = positions[u][resulting_graphs[i]]:clone() u.pos:shift(x_offset, y_offset) for _,a in ipairs(resulting_graphs[i]:outgoing(u)) do for _,e in ipairs(a.syntactic_edges) do for _,p in ipairs(e.path) do if type(p) == "table" then p:shift(x_offset, y_offset) end end end end end end -- Restart i = 0 break end end end end i = i + 1 end -- Now, we can collapse all marked graphs into one graph: local merge = Digraph.new {} merge.syntactic_digraph = merge local remaining = {} -- Add all vertices and edges: for i=1,n do if marked[i] then merge:add (resulting_graphs[i].vertices) for _,a in ipairs(resulting_graphs[i].arcs) do local ma = merge:connect(a.tail,a.head) for _,e in ipairs(a.syntactic_edges) do ma.syntactic_edges[#ma.syntactic_edges+1] = e end end else remaining[#remaining + 1] = resulting_graphs[i] end end -- Remember the first layout this came from: loc[merge] = loc[resulting_graphs[1]] -- Restart with rest: merged_graphs[#merged_graphs+1] = merge resulting_graphs = remaining end -- Step 3: Run the algorithm on the layout: local class = layout.options.algorithm_phases.main assert (type(class) == "table", "algorithm selection failed") local algorithm = class local uncollapsed_subgraph_nodes = lib.imap( scope.collections[InterfaceCore.subgraph_node_kind] or {}, function (c) if c.parent_layout == layout then return c.subgraph_node end end) -- Create a new syntactic digraph: local syntactic_digraph = Digraph.new { options = layout.options } syntactic_digraph.syntactic_digraph = syntactic_digraph -- Copy all vertices and edges from the collection... syntactic_digraph:add (layout.vertices) for _,e in ipairs(layout.edges) do syntactic_digraph:add {e.head, e.tail} local arc = syntactic_digraph:connect(e.tail, e.head) arc.syntactic_edges[#arc.syntactic_edges+1] = e end -- Find out which subgraph nodes can be created now and make them part of the merged graphs for i=#uncollapsed_subgraph_nodes,1,-1 do local v = uncollapsed_subgraph_nodes[i] local vertices = v.subgraph_collection.vertices -- Test, if all vertices of the subgraph are in one of the merged graphs. for _,g in ipairs(merged_graphs) do if special_vertex_subset(vertices, g) then -- Ok, we can create a subgraph now create_subgraph_node(scope, syntactic_digraph, v) -- Make it part of the collapse! g:add{v} -- Do not consider again uncollapsed_subgraph_nodes[i] = false break end end end -- Collapse the nodes that are part of a merged_graph local collapsed_vertices = {} for _,g in ipairs(merged_graphs) do local intersection = {} for _,v in ipairs(g.vertices) do if syntactic_digraph:contains(v) then intersection[#intersection+1] = v end end if #intersection > 0 then -- Compute bounding box of g (this should actually be the convex -- hull) Hmm...: local array = {} for _,v in ipairs(g.vertices) do local min_x, min_y, max_x, max_y = v:boundingBox() array[#array+1] = Coordinate.new(min_x + v.pos.x, min_y + v.pos.y) array[#array+1] = Coordinate.new(max_x + v.pos.x, max_y + v.pos.y) end for _,a in ipairs(g.arcs) do for _,e in ipairs(a.syntactic_edges) do for _,p in ipairs(e.path) do if type(p) == "table" then array[#array+1] = p end end end end local x_min, y_min, x_max, y_max, c_x, c_y = Coordinate.boundingBox(array) -- Shift the graph so that it is centered on the origin: for _,v in ipairs(g.vertices) do v.pos:unshift(c_x,c_y) end for _,a in ipairs(g.arcs) do for _,e in ipairs(a.syntactic_edges) do for _,p in ipairs(e.path) do if type(p) == "table" then p:unshift(c_x,c_y) end end end end x_min = x_min - c_x x_max = x_max - c_x y_min = y_min - c_y y_max = y_max - c_y local index = loc[g].event.index local v = Vertex.new { -- Standard stuff shape = "none", kind = "node", path = Path.new { "moveto", x_min, y_min, x_min, y_max, x_max, y_max, x_max, y_min, "closepath" }, options = {}, event = scope.events[index] } -- Update node_event scope.events[index].parameters = v local collapse_vertex = syntactic_digraph:collapse( intersection, v, nil, function (new_arc, arc) for _,e in ipairs(arc.syntactic_edges) do new_arc.syntactic_edges[#new_arc.syntactic_edges+1] = e end end) syntactic_digraph:remove(intersection) collapsed_vertices[#collapsed_vertices+1] = collapse_vertex end end -- Sort the vertices table.sort(syntactic_digraph.vertices, function(u,v) return u.event.index < v.event.index end) -- Should we "hide" the subgraph nodes? local hidden_node if not algorithm.include_subgraph_nodes then local subgraph_nodes = lib.imap (syntactic_digraph.vertices, function (v) if v.kind == "subgraph node" then return v end end) if #subgraph_nodes > 0 then hidden_node = Vertex.new {} syntactic_digraph:collapse(subgraph_nodes, hidden_node) syntactic_digraph:remove (subgraph_nodes) syntactic_digraph:remove {hidden_node} end end -- Now, we want to call the actual algorithm. This call may modify -- the layout's vertices and edges fields, namely when new vertices -- and edges are created. We then need to add these to our local -- syntactic digraph. So, we remember the length of these fields -- prior to the call and then add everything ``behind'' these -- positions later on. -- Ok, everything setup! Run the algorithm... fun(scope, algorithm, syntactic_digraph, layout) if hidden_node then syntactic_digraph:expand(hidden_node) end -- Now, we need to expand the collapsed vertices once more: for i=#collapsed_vertices,1,-1 do syntactic_digraph:expand( collapsed_vertices[i], function (c, v) v.pos:shiftByCoordinate(c.pos) end, function (a, v) for _,e in ipairs(a.syntactic_edges) do for _,p in ipairs(e.path) do if type(p) == "table" then p:shiftByCoordinate(v.pos) end end end end ) for _,a in ipairs(syntactic_digraph:outgoing(collapsed_vertices[i])) do for _,e in ipairs(a.syntactic_edges) do for _,p in ipairs(e.path) do if type(p) == "table" then p:shiftByCoordinate(a.tail.pos) p:unshiftByCoordinate(e.tail.pos) end end end end end syntactic_digraph:remove(collapsed_vertices) -- Step 4: Create the layout node if necessary for i=#uncollapsed_subgraph_nodes,1,-1 do if uncollapsed_subgraph_nodes[i] then create_subgraph_node(scope, syntactic_digraph, uncollapsed_subgraph_nodes[i]) end end -- Now seems like a good time to nudge and do regardless positioning nudge(syntactic_digraph) -- Step 5: Cleanup -- Push the computed position into the storage: for _,v in ipairs(syntactic_digraph.vertices) do positions[v][syntactic_digraph] = v.pos:clone() end return syntactic_digraph end --- -- Regardless positioning. -- -- @param graph A graph -- function Sublayouts.regardless(graph) for _,v in ipairs(graph.vertices) do local regardless = v.options['regardless at'] if regardless then offset_vertex(v, regardless - v.pos) end end end -- Done return Sublayouts
-- Editors: -- Earth Salamander #42 if Mutation == nil then Mutation = class({}) IMBA_MUTATION = {} IMBA_MUTATION["positive"] = "" IMBA_MUTATION["negative"] = "" IMBA_MUTATION["terrain"] = "" end POSITIVE_MUTATION_LIST = {} -- VANILLA POSITIVE_MUTATION_LIST["killstreak_power"] = false -- POSITIVE_MUTATION_LIST["jump_start"] = false POSITIVE_MUTATION_LIST["teammate_resurrection"] = false POSITIVE_MUTATION_LIST["super_blink"] = false POSITIVE_MUTATION_LIST["pocket_tower"] = false -- Not coded/approved yet -- POSITIVE_MUTATION_LIST["damage_reduction"] = false -- POSITIVE_MUTATION_LIST["stationary_damage_reduction"] = false -- POSITIVE_MUTATION_LIST["super_runes"] = false -- IMBA POSITIVE_MUTATION_LIST["frantic"] = false POSITIVE_MUTATION_LIST["slark_mode"] = false -- Not coded/approved yet -- POSITIVE_MUTATION_LIST["greedisgood"] = false -- POSITIVE_MUTATION_LIST["angel_arena"] = false -- POSITIVE_MUTATION_LIST["speed_freaks"] = false NEGATIVE_MUTATION_LIST = {} -- VANILLA NEGATIVE_MUTATION_LIST["death_explosion"] = false -- NEGATIVE_MUTATION_LIST["death_gold_drop"] = false -- NEGATIVE_MUTATION_LIST["no_health_bar"] = false NEGATIVE_MUTATION_LIST["periodic_spellcast"] = false -- IMBA NEGATIVE_MUTATION_LIST["defense_of_the_ants"] = false -- Disabled -- NEGATIVE_MUTATION_LIST["stay_frosty"] = false -- Not coded/approved yet -- NEGATIVE_MUTATION_LIST["monkey_business"] = false -- NEGATIVE_MUTATION_LIST["the_walking_dead"] = false -- NEGATIVE_MUTATION_LIST["alien_incubation"] = false TERRAIN_MUTATION_LIST = {} TERRAIN_MUTATION_LIST["sleepy_river"] = false TERRAIN_MUTATION_LIST["fast_runes"] = false TERRAIN_MUTATION_LIST["minefield"] = false TERRAIN_MUTATION_LIST["gift_exchange"] = false -- Disabled -- TERRAIN_MUTATION_LIST["no_trees"] = false -- TERRAIN_MUTATION_LIST["omni_vision"] = false -- Not coded/approved yet -- TERRAIN_MUTATION_LIST["danger_zone"] = false -- add archer's music danger zone -- TERRAIN_MUTATION_LIST["river_fag"] = false -- TERRAIN_MUTATION_LIST["diretide"] = false -- TERRAIN_MUTATION_LIST["void_path"] = false -- TERRAIN_MUTATION_LIST["reality_rift"] = false -- TERRAIN_MUTATION_LIST["blizzard"] = false -- TERRAIN_MUTATION_LIST["twister"] = false
camp_waypoint_datapad = { minimumLevel = 0, maximumLevel = -1, customObjectName = "", directObjectTemplate = "object/tangible/loot/quest/force_sensitive/camp_waypoint_datapad.iff", craftingValues = { }, customizationStringNames = {}, customizationValues = {} } addLootItemTemplate("camp_waypoint_datapad", camp_waypoint_datapad)
---@class ModelInfo C_ModelInfo = {} --- This function does nothing in public clients ---@param modelSceneFrame table ---@param modelSceneID number function C_ModelInfo.AddActiveModelScene(modelSceneFrame, modelSceneID) end --- This function does nothing in public clients ---@param modelSceneFrameActor table ---@param modelSceneActorID number function C_ModelInfo.AddActiveModelSceneActor(modelSceneFrameActor, modelSceneActorID) end --- This function does nothing in public clients ---@param modelSceneFrame table function C_ModelInfo.ClearActiveModelScene(modelSceneFrame) end --- This function does nothing in public clients ---@param modelSceneFrameActor table function C_ModelInfo.ClearActiveModelSceneActor(modelSceneFrameActor) end ---@param modelActorDisplayID number ---@return UIModelSceneActorDisplayInfo actorDisplayInfo function C_ModelInfo.GetModelSceneActorDisplayInfoByID(modelActorDisplayID) end ---@param modelActorID number ---@return UIModelSceneActorInfo actorInfo function C_ModelInfo.GetModelSceneActorInfoByID(modelActorID) end ---@param modelSceneCameraID number ---@return UIModelSceneCameraInfo modelSceneCameraInfo function C_ModelInfo.GetModelSceneCameraInfoByID(modelSceneCameraID) end ---@param modelSceneID number ---@return ModelSceneType, number, number modelSceneType, modelCameraIDs, modelActorsIDs function C_ModelInfo.GetModelSceneInfoByID(modelSceneID) end ---@class ItemTryOnReason local ItemTryOnReason = {} ItemTryOnReason.Success = 0 ItemTryOnReason.WrongRace = 1 ItemTryOnReason.NotEquippable = 2 ItemTryOnReason.DataPending = 3 ---@class ModelSceneSetting local ModelSceneSetting = {} ModelSceneSetting.AlignLightToOrbitDelta = 1 ---@class ModelSceneType local ModelSceneType = {} ModelSceneType.MountJournal = 0 ModelSceneType.PetJournalCard = 1 ModelSceneType.ShopCard = 2 ModelSceneType.EncounterJournal = 3 ModelSceneType.PetJournalLoadout = 4 ModelSceneType.ArtifactTier2 = 5 ModelSceneType.ArtifactTier2ForgingScene = 6 ModelSceneType.ArtifactTier2SlamEffect = 7 ModelSceneType.CommentatorVictoryFanfare = 8 ModelSceneType.ArtifactRelicTalentEffect = 9 ModelSceneType.PvpWarModeOrb = 10 ModelSceneType.PvpWarModeFire = 11 ModelSceneType.PartyPose = 12 ModelSceneType.AzeriteItemLevelUpToast = 13 ModelSceneType.AzeritePowers = 14 ModelSceneType.AzeriteRewardGlow = 15 ModelSceneType.HeartOfAzeroth = 16 ModelSceneType.WorldMapThreat = 17 ---@class UIModelSceneActorDisplayInfo ---@field animation number ---@field animationVariation number ---@field animSpeed number ---@field animationKitID number|nil ---@field spellVisualKitID number|nil ---@field alpha number ---@field scale number local UIModelSceneActorDisplayInfo = {} ---@class UIModelSceneActorInfo ---@field modelActorID number ---@field scriptTag string ---@field position table ---@field yaw number ---@field pitch number ---@field roll number ---@field normalizeScaleAggressiveness number|nil ---@field useCenterForOriginX bool ---@field useCenterForOriginY bool ---@field useCenterForOriginZ bool ---@field modelActorDisplayID number|nil local UIModelSceneActorInfo = {} ---@class UIModelSceneCameraInfo ---@field modelSceneCameraID number ---@field scriptTag string ---@field cameraType string ---@field target table ---@field yaw number ---@field pitch number ---@field roll number ---@field zoomDistance number ---@field minZoomDistance number ---@field maxZoomDistance number ---@field zoomedTargetOffset table ---@field zoomedYawOffset number ---@field zoomedPitchOffset number ---@field zoomedRollOffset number ---@field flags ModelSceneSetting local UIModelSceneCameraInfo = {}
--[[------------------------------------------------------------------------- Copyright 2017 - 2021 viral32111 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. ---------------------------------------------------------------------------]] if ( CLIENT ) then return end include("autorun/shared/sh_viralsscoreboard.lua") --[[------------------------------------------------------------------------- Chat Command ---------------------------------------------------------------------------]] hook.Add("PlayerSay", "ViralsScoreboardChatCommand", function( ply, text ) local text = string.lower( text ) if ( text == "!viralsscoreboard" ) then if ( table.HasValue( ViralsScoreboard.AdminGroups, ply:GetUserGroup() ) ) then net.Start( "ViralsScoreboardAdmin" ) net.WriteTable( string.Explode( "\n", file.Read( "viralsscoreboard_config.txt" ) ) ) net.WriteTable( string.Explode( ";", file.Read( "viralsscoreboard_displayconfig.txt" ) ) ) --net.WriteTable( string.Explode( "\n", file.Read( "viralsscoreboard_groupconfig.txt" ) ) ) --net.WriteTable( string.Explode( "\n", file.Read( "viralsscoreboard_userconfig.txt" ) ) ) net.Send( ply ) else ply:ChatPrint("You must be Super Admin or above to use this command!") end return "" end end ) --[[------------------------------------------------------------------------- Save new configs ---------------------------------------------------------------------------]] net.Receive( "ViralsScoreboardAdmin", function() local Config = net.ReadString() local DisplayConfig = net.ReadString() --local GroupConfig = net.ReadString() --local UserConfig = net.ReadString() file.Write( "viralsscoreboard_config.txt", Config ) file.Write( "viralsscoreboard_displayconfig.txt", DisplayConfig ) --file.Write( "viralsscoreboard_groupconfig.txt", GroupConfig ) --file.Write( "viralsscoreboard_userconfig.txt", UserConfig ) end ) --[[------------------------------------------------------------------------- Return the request for files ---------------------------------------------------------------------------]] hook.Add( "PlayerInitialSpawn", "ViralsScoreboardSendConfig", function( ply ) net.Start( "ViralsScoreboardSendConfig" ) net.WriteTable( string.Explode( "\n", file.Read( "viralsscoreboard_config.txt" ) ) ) net.WriteTable( string.Explode( ";", file.Read( "viralsscoreboard_displayconfig.txt" ) ) ) --net.WriteTable( string.Explode( "\n", file.Read( "viralsscoreboard_groupconfig.txt" ) ) ) --net.WriteTable( string.Explode( "\n", file.Read( "viralsscoreboard_userconfig.txt" ) ) ) net.Send( ply ) end )
object_tangible_collection_publish_gift_comlink_component_01 = object_tangible_collection_shared_publish_gift_comlink_component_01:new { gameObjectType = 8211,} ObjectTemplates:addTemplate(object_tangible_collection_publish_gift_comlink_component_01, "object/tangible/collection/publish_gift_comlink_component_01.iff")
local util = require 'util' local lovetoys = require 'lovetoys.lovetoys' local Light = lovetoys.Component.create('Light') function Light:initialize() self:clear() self:reset() end function Light:reset() self.map = {} self:flush() end function Light:flush() util.fill(self.dirty) end function Light:clear() self.map = {} self.dirty = {} end function Light:setColor(value, x, y) x = x or 1 y = y or 1 util.setMap(self.map, value, x, y) util.fill(self.dirty) end function Light:getColor(x, y) x = x or 1 y = y or 1 return util.getMap(self.map, x, y) end return Light
-------------------------------- -- @module SpriteDisplayData -- @extend DisplayData -- @parent_module ccs ---@class ccs.SpriteDisplayData:ccs.DisplayData local SpriteDisplayData = {} ccs.SpriteDisplayData = SpriteDisplayData -------------------------------- --- ---@param displayData ccs.DisplayData ---@return ccs.SpriteDisplayData function SpriteDisplayData:copy(displayData) end -------------------------------- --- ---@return ccs.SpriteDisplayData function SpriteDisplayData:create() end -------------------------------- --- js ctor ---@return ccs.SpriteDisplayData function SpriteDisplayData:SpriteDisplayData() end return nil
if SERVER then AddCSLuaFile() end -- CREATE CONVARS local maxhealth = CreateConVar("ttt2_zomb_maxhealth_new_zomb", 100, {FCVAR_ARCHIVE, FCVAR_NOTIFY}) local walkspeed = CreateConVar("ttt2_zomb_walkspeed", 0.5, {FCVAR_ARCHIVE, FCVAR_NOTIFY}) -- SYNC CONVARS <> GLOBAL VARS if SERVER then hook.Add("TTT2SyncGlobals", "TTT2ZombieSyncGlobals", function() SetGlobalFloat(walkspeed:GetName(), walkspeed:GetFloat()) end) cvars.AddChangeCallback(walkspeed:GetName(), function(name, old, new) SetGlobalFloat(walkspeed:GetName(), tonumber(new) == 1) end, walkspeed:GetName()) end function ROLE:PreInitialize() self.color = Color(68, 28, 44, 255) self.abbr = "zomb" self.surviveBonus = 1 self.scoreKillsMultiplier = 5 self.scoreTeamKillsMultiplier = -16 self.notSelectable = true self.preventFindCredits = true self.preventKillCredits = true self.preventTraitorAloneCredits = true self.defaultTeam = TEAM_NECROMANCER self.defaultEquipment = SPECIAL_EQUIPMENT end function ROLE:Initialize() roles.SetBaseRole(self, ROLE_NECROMANCER) end hook.Add("TTTUlxDynamicRCVars", "TTTUlxDynamicZombCVars", function(tbl) tbl[ROLE_ZOMBIE] = tbl[ROLE_ZOMBIE] or {} table.insert(tbl[ROLE_ZOMBIE], {cvar = "ttt2_zomb_maxhealth_new_zomb", slider = true, min = 10, max = 500, desc = "Health for new zombies (Def. 100)"}) table.insert(tbl[ROLE_ZOMBIE], {cvar = "ttt2_zomb_walkspeed", slider = true, min = 0, max = 5, decimal = 2, desc = "Zombie walkspeed multplier (Def. 0.5)"}) end) if SERVER then -- Give Loadout on respawn and rolechange function ROLE:GiveRoleLoadout(ply, isRoleChange) -- remove normal player loadout ply:StripWeapon("weapon_zm_improvised") ply:StripWeapon("weapon_zm_carry") ply:StripWeapon("weapon_ttt_unarmed") -- give zombie deagle ply:GiveEquipmentWeapon("weapon_ttth_zombpistol") end -- Remove Loadout on death and rolechange function ROLE:RemoveRoleLoadout(ply, isRoleChange) -- give back normal player loadout ply:GiveEquipmentWeapon("weapon_zm_improvised") ply:GiveEquipmentWeapon("weapon_zm_carry") ply:GiveEquipmentWeapon("weapon_ttt_unarmed") -- remove zombie deagle ply:StripWeapon("weapon_ttth_zombpistol") end zombie_sound_idles = { "npc/zombie/zombie_voice_idle1.wav", "npc/zombie/zombie_voice_idle2.wav", "npc/zombie/zombie_voice_idle3.wav", "npc/zombie/zombie_voice_idle4.wav", "npc/zombie/zombie_voice_idle5.wav", "npc/zombie/zombie_voice_idle6.wav", "npc/zombie/zombie_voice_idle7.wav", "npc/zombie/zombie_voice_idle8.wav", "npc/zombie/zombie_voice_idle9.wav", "npc/zombie/zombie_voice_idle10.wav", "npc/zombie/zombie_voice_idle11.wav", "npc/zombie/zombie_voice_idle12.wav", "npc/zombie/zombie_voice_idle13.wav", "npc/zombie/zombie_voice_idle14.wav" } local zombie_sound_idles_len = #zombie_sound_idles local minDelay, maxDelay = 5, 25 local function CanIdle(ply) return IsValid(ply) and ply:IsPlayer() and ply:IsActive() and ply:GetSubRole() == ROLE_ZOMBIE and (not ply.IsGhost or not ply:IsGhost()) end function StartZombieIdle(target, name, startDelay) startDelay = startDelay or 0 if timer.Exists(name) then timer.Stop(name) timer.Remove(name) end if not CanIdle(target) then return end timer.Create(name, math.random(minDelay, maxDelay) + startDelay, 1, function() if not CanIdle(target) then return end target:EmitSound(zombie_sound_idles[math.random(zombie_sound_idles_len)], SNDLVL_90dB, 100, 1, CHAN_VOICE) StartZombieIdle(target, name) end) end function AddZombie(target) target:SetRole(ROLE_ZOMBIE) local name = "sound_idle_" .. target:EntIndex() timer.Create(name, 10, 1, function() StartZombieIdle(target, name) end) target:SetMaxHealth(maxhealth:GetInt()) target:SetHealth(maxhealth:GetInt()) target:ResetConfirmPlayer() SendFullStateUpdate() end function StopZombieIdle(ply) local str = "sound_idle_" .. ply:EntIndex() if timer.Exists(str) then timer.Stop(str) timer.Remove(str) end end hook.Add("TTT2UpdateSubrole", "UpdateZombRoleSelect", function(ply, oldSubrole, newSubrole) if newSubrole == ROLE_ZOMBIE then ply:SetSubRoleModel("models/player/skeleton.mdl") elseif oldSubrole == ROLE_ZOMBIE then ply:SetSubRoleModel(nil) end end) hook.Add("PlayerCanPickupWeapon", "ZombModifyPickupWeapon", function(ply, wep) if not IsValid(wep) or not IsValid(ply) or ply:GetSubRole() ~= ROLE_ZOMBIE or ply:IsSpec() and ply.IsGhost and ply:IsGhost() then return end if WEPS.GetClass(wep) ~= "weapon_ttth_zombpistol" then return false end end) hook.Add("TTTEndRound", "ZombEndRound", function() for _, v in ipairs(player.GetAll()) do v:SetMaxHealth(100) -- reset StopZombieIdle(v) end end) -- tttc support hook.Add("TTTCClassDropNotPickupable", "ZombiePickupClassDrop", function(ply) if IsValid(ply) and ply:IsActive() and ply:GetSubRole() == ROLE_ZOMBIE then return true end end) end -- walk speed change has to be run on client and server hook.Add("TTTPlayerSpeedModifier", "ZombModifySpeed", function(ply, _, _, noLag) if not IsValid(ply) or ply:GetSubRole() ~= ROLE_ZOMBIE then return end noLag[1] = noLag[1] * GetGlobalFloat(walkspeed:GetName(), 0.5) end)
local shuffle = require "libs.shuffle" local function table_copy(t) local t2 = {} for k,v in pairs(t) do t2[k] = v end return t2 end -- SEQ実行 local function SEQ(talk) local function task(args) local talk_type = type(talk) -- 文字列:そのまま1回返す if talk_type == "string" then args = coroutine.yield(talk) return -- 関数:コルーチンとみなしてループを回す elseif talk_type == "function" then local co = coroutine.wrap(talk) while true do value = co(args) if value == nil then break end args = coroutine.yield(value) end -- テーブル:配列とみなして1つずつSEQ()を回す。 elseif talk_type == "table" then for i,v in ipairs(talk) do local co = SEQ(v) while true do value = co(args) if value == nil then break end args = coroutine.yield(value) end end end end return task end -- シャッフル実行 local function RAND(talk) local sh = table_copy(talk) shuffle.shuffle(sh) return SEQ(sh) end -- 無限SEQ実行 local function INFINITY(talk) local function task(args) while true do local co = SEQ(talk) while true do value = co(args) if value == nil then break end args = coroutine.yield(value) end end end return task end -- 関数を1回実行するタスク(warpはSEQで行うこと) local function ONE(func) local function task(args) coroutine.yield(func(args)) end return task end return { INFINITY = INFINITY, SEQ = SEQ, RAND = RAND, ONE = ONE, }
local sync = require("util.sync") local Server = require('utilityNoobhub') local Message = require('messageTemplates') local restAPI = require("api.rest") local isDebug = true local print = isDebug and Runtime._G.print or function() end local socket = {} local _props = {} local connection = { sessionId=nil, userId=nil, initEventId=nil, rooms=nil } local srv = Server.new({ server='localhost', port=7776, callback=function(event) end, eventName="pubsub" }) local function isAuthenticated() return connection.sessionId and connection.initEventId and connection.userId and connection.state == 'ready' end function socket.connect(cb) srv:connect(Message.init(),function(err, res) if(err) then cb(err); return false end if(type(res.response) ~= 'table') then print(res); return end connection = { initEventId = res.response.initEventId, appName = res.response.appName, sessionId = res.response.sessionId, userId = res.response.userId, eventId = res.response.eventId, --this changes per publish rooms = res.response.rooms } cb(nil, {status="CONNECTED", message="Verifying..", timeout=5000}) srv:publish(Message.confirmInit(connection), function(errC, resC) print('confirming init publish') if(errC) then print('Confirm Error | Err ', errC) cb(errC) connection.state = 'init' --reset return false end connection.state = 'ready' print('confirm', resC) cb(nil, 'READY') cb = nil end) end) end function socket.disconnect(cb) srv:disconnect(nil, function(err, res) if(err) then cb(err); return false end connection = {} cb(nil, 'OK') end) end function socket.join(roomName, options, cb) options = options or {} if(not isAuthenticated()) then cb('UNAUTHORIZED'); return false end local params = options.roomProps or {} local performSubscribe = function(roomName) srv:publish(Message.subscribe({roomName = roomName, params = params}), cb) end if(not options.path) then performSubscribe(roomName); return end restAPI.reserveGameRoom(connection, roomName, params, function(err, roomName) if(err) then cb(err); return false end performSubscribe(roomName) end) end function socket.leave(roomName, cb) if(not isAuthenticated()) then cb('UNAUTHORIZED'); return false end if(type(roomName) == 'function') then cb = roomName end srv:leave(nil, function(res) connection = {} end) end return socket
print("Project15: Blynk accelerometer from phone") vw_cb = function(cmd) pin = tonumber(cmd[2]) -- ALL vpin "vw" messages arrive here. What vpin is this packet? if pin == 13 then -- v13 = accel xx=tonumber(cmd[3]) yy=tonumber(cmd[4]) zz=tonumber(cmd[5]) print("pitch", axl.pitch(yy,zz), "roll", axl.roll(xx,zz)) end if pin == 14 then -- v14 = light ll = cmd[3] print("light level", ll) end end dofile("{token}.lua") dofile ( 'lib-BLYNK.lua' ) b=blynk.new (token, function(b) b:on("vw", vw_cb) end ):connect() dofile("lib-ACCEL.lua") -- provides the pitch/roll maths -- at phone, accelerometer vpin 13, 1 sec -- also (incidentlally) a light sensor on V14, 1/sec
project "SharpLang.Compiler" kind "ConsoleApp" language "C#" flags { "Unsafe"} SetupManagedProject() files { "**.cs" } excludes { "obj/**" } dependson { "SharpLang.Runtime" } links { "System", "System.Core", "SharpLLVM", "Mono.Cecil", "Mono.Cecil.Pdb", "Mono.Cecil.Rocks", "Mono.Linker", depsdir .. "/Mono.Options/Mono.Options", depsdir .. "/System.Reflection.Metadata/System.Collections.Immutable", depsdir .. "/System.Reflection.Metadata/System.Reflection.Metadata", }
local Tract = {} Tract.fixed = {} Tract.fixed.L = {} Tract.fixed.L[1] = 18 Tract.fixed.L[2] = 18 Tract.AreaNose = {} Tract.AreaNose[1] = 1.5714285714285714 Tract.AreaNose[2] = 2.1036641929499069 Tract.AreaNose[3] = 2.8453153988868278 Tract.AreaNose[4] = 3.5904452690166977 Tract.AreaNose[5] = 4.25 Tract.AreaNose[6] = 4.8186456400742124 Tract.AreaNose[7] = 5.308441558441559 Tract.AreaNose[8] = 5.6117810760667899 Tract.AreaNose[9] = 5.6071428571428568 Tract.AreaNose[10] = 5.2052875695732839 Tract.AreaNose[11] = 4.4056122448979584 Tract.AreaNose[12] = 3.2993970315398866 Tract.AreaNose[13] = 2.0714285714285698 Tract.AreaNose[14] = 1 Tract.noise = {} Tract.noise.F = {} Tract.noise.F.freqs = {} Tract.noise.F.freqs[1] = 2500 Tract.noise.F.freqs[2] = 7500 Tract.noise.F.bw = {} Tract.noise.F.bw[1] = 0.14999999999999999 Tract.noise.F.bw[2] = 0.14999999999999999 Tract.noise.F.pos = 19 Tract.noise.S = {} Tract.noise.S.freqs = {} Tract.noise.S.freqs[1] = 2500 Tract.noise.S.freqs[2] = 7500 Tract.noise.S.bw = {} Tract.noise.S.bw[1] = 0.14999999999999999 Tract.noise.S.bw[2] = 0.14999999999999999 Tract.noise.S.pos = 19 Tract.noise.Z = {} Tract.noise.Z.freqs = {} Tract.noise.Z.freqs[1] = 4000 Tract.noise.Z.freqs[2] = 4500 Tract.noise.Z.bw = {} Tract.noise.Z.bw[1] = 0.14999999999999999 Tract.noise.Z.bw[2] = 0.14999999999999999 Tract.noise.Z.pos = 19 Tract.AreaNoseC = {} Tract.AreaNoseC[1] = 0 Tract.AreaNoseC[2] = 2.1036641929499069 Tract.AreaNoseC[3] = 2.8453153988868278 Tract.AreaNoseC[4] = 3.5904452690166977 Tract.AreaNoseC[5] = 4.25 Tract.AreaNoseC[6] = 4.8186456400742124 Tract.AreaNoseC[7] = 5.308441558441559 Tract.AreaNoseC[8] = 5.6117810760667899 Tract.AreaNoseC[9] = 5.6071428571428568 Tract.AreaNoseC[10] = 5.2052875695732839 Tract.AreaNoseC[11] = 4.4056122448979584 Tract.AreaNoseC[12] = 3.2993970315398866 Tract.AreaNoseC[13] = 2.0714285714285698 Tract.AreaNoseC[14] = 1 Tract.areas = {} Tract.areas.K = {} Tract.areas.K[1] = 0.378 Tract.areas.K[2] = 0.99200000000000021 Tract.areas.K[3] = 1.25 Tract.areas.K[4] = 0.73999999999999977 Tract.areas.K[5] = 1.45 Tract.areas.K[6] = 1.7619999999999996 Tract.areas.K[7] = 1.5900000000000001 Tract.areas.K[8] = 1.3239999999999994 Tract.areas.K[9] = 1.1839999999999997 Tract.areas.K[10] = 0.95999999999999996 Tract.areas.K[11] = 0.68200000000000038 Tract.areas.K[12] = 0 Tract.areas.K[13] = 0.066000000000000086 Tract.areas.K[14] = 0.067999999999999977 Tract.areas.K[15] = 0.47999999999999998 Tract.areas.K[16] = 2.294 Tract.areas.K[17] = 2.4039999999999999 Tract.areas.K[18] = 3.7059999999999986 Tract.areas.K[19] = 2.46 Tract.areas.K[20] = 1.5 Tract.areas.I2 = {} Tract.areas.I2[1] = 0.17100000000000001 Tract.areas.I2[2] = 0.16399999999999998 Tract.areas.I2[3] = 1.254 Tract.areas.I2[4] = 1.4599999999999997 Tract.areas.I2[5] = 1.0249999999999999 Tract.areas.I2[6] = 2.6479999999999997 Tract.areas.I2[7] = 3.2919999999999998 Tract.areas.I2[8] = 3.448 Tract.areas.I2[9] = 3.8070000000000004 Tract.areas.I2[10] = 3.4700000000000002 Tract.areas.I2[11] = 2.5949999999999998 Tract.areas.I2[12] = 1.972 Tract.areas.I2[13] = 1.6219999999999997 Tract.areas.I2[14] = 1.2940000000000005 Tract.areas.I2[15] = 0.81000000000000005 Tract.areas.I2[16] = 1.1980000000000004 Tract.areas.I2[17] = 1.8150000000000002 Tract.areas.I2[18] = 1.9159999999999993 Tract.areas.I2[19] = 1.6500000000000006 Tract.areas.I2[20] = 1.1799999999999999 Tract.areas.Ui = {} Tract.areas.Ui[1] = 0.35000000000000003 Tract.areas.Ui[2] = 0.502 Tract.areas.Ui[3] = 2.7910000000000004 Tract.areas.Ui[4] = 2.3160000000000003 Tract.areas.Ui[5] = 4.7450000000000001 Tract.areas.Ui[6] = 5.4699999999999998 Tract.areas.Ui[7] = 4.5329999999999995 Tract.areas.Ui[8] = 3.5260000000000002 Tract.areas.Ui[9] = 3.2650000000000001 Tract.areas.Ui[10] = 2.3300000000000001 Tract.areas.Ui[11] = 1.9049999999999996 Tract.areas.Ui[12] = 0.43399999999999928 Tract.areas.Ui[13] = 0.21299999999999991 Tract.areas.Ui[14] = 0.41600000000000065 Tract.areas.Ui[15] = 0.81000000000000005 Tract.areas.Ui[16] = 2.2439999999999984 Tract.areas.Ui[17] = 3.9040000000000026 Tract.areas.Ui[18] = 3.6320000000000032 Tract.areas.Ui[19] = 0.86899999999999911 Tract.areas.Ui[20] = 0.85999999999999999 Tract.areas.R = {} Tract.areas.R[1] = 0.31799999999999995 Tract.areas.R[2] = 0.54399999999999993 Tract.areas.R[3] = 2.237000000000001 Tract.areas.R[4] = 2.6260000000000003 Tract.areas.R[5] = 3.5949999999999998 Tract.areas.R[6] = 4.2359999999999998 Tract.areas.R[7] = 4.4550000000000001 Tract.areas.R[8] = 4.3720000000000008 Tract.areas.R[9] = 3.6840000000000002 Tract.areas.R[10] = 2.3300000000000001 Tract.areas.R[11] = 2.4700000000000002 Tract.areas.R[12] = 2.6579999999999999 Tract.areas.R[13] = 3.6279999999999992 Tract.areas.R[14] = 5.2780000000000014 Tract.areas.R[15] = 6.4900000000000002 Tract.areas.R[16] = 6.758 Tract.areas.R[17] = 3.9449999999999981 Tract.areas.R[18] = 0.01 Tract.areas.R[19] = 4.6690000000000031 Tract.areas.R[20] = 3.7000000000000002 Tract.areas.L = {} Tract.areas.L[1] = 0.31799999999999995 Tract.areas.L[2] = 0.54399999999999993 Tract.areas.L[3] = 2.237000000000001 Tract.areas.L[4] = 2.6260000000000003 Tract.areas.L[5] = 3.5949999999999998 Tract.areas.L[6] = 4.2359999999999998 Tract.areas.L[7] = 4.4550000000000001 Tract.areas.L[8] = 4.3720000000000008 Tract.areas.L[9] = 3.6840000000000002 Tract.areas.L[10] = 2.3300000000000001 Tract.areas.L[11] = 2.4700000000000002 Tract.areas.L[12] = 2.6579999999999999 Tract.areas.L[13] = 3.6279999999999992 Tract.areas.L[14] = 5.2780000000000014 Tract.areas.L[15] = 6.4900000000000002 Tract.areas.L[16] = 6.758 Tract.areas.L[17] = 3.9449999999999981 Tract.areas.L[18] = 0.13999999999999987 Tract.areas.L[19] = 4.6690000000000031 Tract.areas.L[20] = 3.7000000000000002 Tract.areas.E = {} Tract.areas.E[1] = 0.13 Tract.areas.E[2] = 0.14000000000000001 Tract.areas.E[3] = 0.78000000000000003 Tract.areas.E[4] = 1.24 Tract.areas.E[5] = 0.71999999999999997 Tract.areas.E[6] = 1.0600000000000001 Tract.areas.E[7] = 1.97 Tract.areas.E[8] = 2.7000000000000002 Tract.areas.E[9] = 3.0299999999999998 Tract.areas.E[10] = 2.8399999999999999 Tract.areas.E[11] = 2.3599999999999999 Tract.areas.E[12] = 2 Tract.areas.E[13] = 1.8100000000000001 Tract.areas.E[14] = 1.5 Tract.areas.E[15] = 1.3600000000000001 Tract.areas.E[16] = 1.8300000000000001 Tract.areas.E[17] = 2.5899999999999999 Tract.areas.E[18] = 2.1099999999999999 Tract.areas.E[19] = 2.7400000000000002 Tract.areas.E[20] = 1.6000000000000001 Tract.areas.T = {} Tract.areas.T[1] = 0.47999999999999998 Tract.areas.T[2] = 1.1940000000000002 Tract.areas.T[3] = 1.4340000000000002 Tract.areas.T[4] = 0.93799999999999994 Tract.areas.T[5] = 1.03 Tract.areas.T[6] = 2.4160000000000004 Tract.areas.T[7] = 2.6260000000000003 Tract.areas.T[8] = 3.088000000000001 Tract.areas.T[9] = 3.9420000000000002 Tract.areas.T[10] = 4.4100000000000001 Tract.areas.T[11] = 3.8880000000000003 Tract.areas.T[12] = 3.1780000000000008 Tract.areas.T[13] = 2.6579999999999999 Tract.areas.T[14] = 2.0959999999999996 Tract.areas.T[15] = 1.3899999999999999 Tract.areas.T[16] = 0.81599999999999917 Tract.areas.T[17] = 0 Tract.areas.T[18] = 0.078000000000000194 Tract.areas.T[19] = 1.2199999999999962 Tract.areas.T[20] = 1.4299999999999999 Tract.areas.Lorig = {} Tract.areas.Lorig[1] = 0.66599999999999993 Tract.areas.Lorig[2] = 2.5079999999999996 Tract.areas.Lorig[3] = 3.4610000000000003 Tract.areas.Lorig[4] = 3.0940000000000003 Tract.areas.Lorig[5] = 3.2850000000000001 Tract.areas.Lorig[6] = 3.5759999999999996 Tract.areas.Lorig[7] = 2.3919999999999999 Tract.areas.Lorig[8] = 2.3100000000000005 Tract.areas.Lorig[9] = 2.2769999999999997 Tract.areas.Lorig[10] = 2.3300000000000001 Tract.areas.Lorig[11] = 2.4700000000000002 Tract.areas.Lorig[12] = 2.6579999999999999 Tract.areas.Lorig[13] = 3.6279999999999992 Tract.areas.Lorig[14] = 5.2780000000000014 Tract.areas.Lorig[15] = 6.4900000000000002 Tract.areas.Lorig[16] = 6.758 Tract.areas.Lorig[17] = 3.9449999999999981 Tract.areas.Lorig[18] = 0.62999999999999934 Tract.areas.Lorig[19] = 4.6690000000000031 Tract.areas.Lorig[20] = 3.7000000000000002 Tract.areas.N = {} Tract.areas.N[1] = 0.22599999999999998 Tract.areas.N[2] = 0.18599999999999997 Tract.areas.N[3] = 0.96599999999999975 Tract.areas.N[4] = 1.4119999999999999 Tract.areas.N[5] = 0.70999999999999996 Tract.areas.N[6] = 1.5419999999999994 Tract.areas.N[7] = 2.0880000000000001 Tract.areas.N[8] = 2.2800000000000002 Tract.areas.N[9] = 2.8080000000000003 Tract.areas.N[10] = 1.9299999999999999 Tract.areas.N[11] = 0.94600000000000006 Tract.areas.N[12] = 1.2519999999999998 Tract.areas.N[13] = 1.2039999999999997 Tract.areas.N[14] = 0.42599999999999971 Tract.areas.N[15] = 0.22 Tract.areas.N[16] = 0 Tract.areas.N[17] = 0 Tract.areas.N[18] = 0 Tract.areas.N[19] = 1.5980000000000001 Tract.areas.N[20] = 1.1699999999999999 Tract.areas.Ute = {} Tract.areas.Ute[1] = 1 Tract.areas.Ute[2] = 0.90391938499535995 Tract.areas.Ute[3] = 0.3754760024698407 Tract.areas.Ute[4] = 0.048198018727254009 Tract.areas.Ute[5] = 0.072959482854799751 Tract.areas.Ute[6] = 0.069058453516163007 Tract.areas.Ute[7] = 0.041272012955707496 Tract.areas.Ute[8] = 0.58666562996535399 Tract.areas.Ute[9] = 1.3470017685637881 Tract.areas.Ute[10] = 1.07171677738344 Tract.areas.Ute[11] = 0.76179835729825585 Tract.areas.Ute[12] = 1.1411667779434918 Tract.areas.Ute[13] = 1.2253422503067091 Tract.areas.Ute[14] = 0.52233652725121071 Tract.areas.Ute[15] = 0.22218549588177749 Tract.areas.Ute[16] = 0.40546009453562215 Tract.areas.Ute[17] = 0.437193355487205 Tract.areas.Ute[18] = 0.38233156632320997 Tract.areas.Ute[19] = 1.5482263571014692 Tract.areas.Ute[20] = 2.9854003878669002 Tract.areas.Ate = {} Tract.areas.Ate[1] = 1 Tract.areas.Ate[2] = 0.95204914287383291 Tract.areas.Ate[3] = 0.68831942867991458 Tract.areas.Ate[4] = 0.76737114612512425 Tract.areas.Ate[5] = 1.4462903689388074 Tract.areas.Ate[6] = 1.3026997215274092 Tract.areas.Ate[7] = 0.47368418226177522 Tract.areas.Ate[8] = 1.2185924284757987 Tract.areas.Ate[9] = 2.5537220942446917 Tract.areas.Ate[10] = 2.2864964096159497 Tract.areas.Ate[11] = 2.2710837524813385 Tract.areas.Ate[12] = 6.3761567206856764 Tract.areas.Ate[13] = 8.2156859795424779 Tract.areas.Ate[14] = 4.0137653468058385 Tract.areas.Ate[15] = 2.7382508996803248 Tract.areas.Ate[16] = 4.9744238752881627 Tract.areas.Ate[17] = 5.1528690326368753 Tract.areas.Ate[18] = 4.1554697224089487 Tract.areas.Ate[19] = 13.487868436864515 Tract.areas.Ate[20] = 25.115777823472001 Tract.areas.O = {} Tract.areas.O[1] = 0.15129999999999999 Tract.areas.O[2] = 0.51600000000000001 Tract.areas.O[3] = 1.355 Tract.areas.O[4] = 1.0700000000000001 Tract.areas.O[5] = 1.3955 Tract.areas.O[6] = 1.8644000000000001 Tract.areas.O[7] = 1.738 Tract.areas.O[8] = 1.3560000000000001 Tract.areas.O[9] = 1.28 Tract.areas.O[10] = 1.25 Tract.areas.O[11] = 0.63019999999999998 Tract.areas.O[12] = 0.16439999999999999 Tract.areas.O[13] = 3.1230000000000002 Tract.areas.O[14] = 4.7670000000000003 Tract.areas.O[15] = 5.5068000000000001 Tract.areas.O[16] = 5.4245999999999999 Tract.areas.O[17] = 6.5140000000000002 Tract.areas.O[18] = 6 Tract.areas.O[19] = 3.887 Tract.areas.O[20] = 0.54800000000000004 Tract.areas.A = {} Tract.areas.A[1] = 0.21200000000000002 Tract.areas.A[2] = 0.25400000000000006 Tract.areas.A[3] = 0.318 Tract.areas.A[4] = 1.1060000000000001 Tract.areas.A[5] = 0.63 Tract.areas.A[6] = 0.26400000000000001 Tract.areas.A[7] = 0.26600000000000001 Tract.areas.A[8] = 0.28399999999999997 Tract.areas.A[9] = 0.60800000000000021 Tract.areas.A[10] = 1.05 Tract.areas.A[11] = 2.1839999999999997 Tract.areas.A[12] = 2.8119999999999998 Tract.areas.A[13] = 3.4580000000000011 Tract.areas.A[14] = 4.992 Tract.areas.A[15] = 6.5499999999999998 Tract.areas.A[16] = 6.2039999999999988 Tract.areas.A[17] = 5.0480000000000009 Tract.areas.A[18] = 4.0260000000000007 Tract.areas.A[19] = 4.266 Tract.areas.A[20] = 5.0300000000000002 Tract.areas.Lmalo = {} Tract.areas.Lmalo[1] = 0.66599999999999993 Tract.areas.Lmalo[2] = 2.5079999999999996 Tract.areas.Lmalo[3] = 3.4610000000000003 Tract.areas.Lmalo[4] = 3.0940000000000003 Tract.areas.Lmalo[5] = 3.2850000000000001 Tract.areas.Lmalo[6] = 3.5759999999999996 Tract.areas.Lmalo[7] = 2.3919999999999999 Tract.areas.Lmalo[8] = 2.3100000000000005 Tract.areas.Lmalo[9] = 2.2769999999999997 Tract.areas.Lmalo[10] = 2.3300000000000001 Tract.areas.Lmalo[11] = 2.4700000000000002 Tract.areas.Lmalo[12] = 2.6579999999999999 Tract.areas.Lmalo[13] = 3.6279999999999992 Tract.areas.Lmalo[14] = 5.2780000000000014 Tract.areas.Lmalo[15] = 6.4900000000000002 Tract.areas.Lmalo[16] = 6.758 Tract.areas.Lmalo[17] = 3.8519999999999968 Tract.areas.Lmalo[18] = 0.17999999999999972 Tract.areas.Lmalo[19] = 4.6690000000000031 Tract.areas.Lmalo[20] = 3.7000000000000002 Tract.areas.Oorig = {} Tract.areas.Oorig[1] = 0.18200000000000002 Tract.areas.Oorig[2] = 0.40400000000000014 Tract.areas.Oorig[3] = 1.544 Tract.areas.Oorig[4] = 0.87799999999999978 Tract.areas.Oorig[5] = 2.7200000000000002 Tract.areas.Oorig[6] = 1.952 Tract.areas.Oorig[7] = 1.6839999999999999 Tract.areas.Oorig[8] = 1.3759999999999997 Tract.areas.Oorig[9] = 1.3119999999999998 Tract.areas.Oorig[10] = 1.25 Tract.areas.Oorig[11] = 1.0140000000000002 Tract.areas.Oorig[12] = 0.43200000000000011 Tract.areas.Oorig[13] = 0.47000000000000031 Tract.areas.Oorig[14] = 1.3160000000000003 Tract.areas.Oorig[15] = 2.9900000000000002 Tract.areas.Oorig[16] = 4.5880000000000027 Tract.areas.Oorig[17] = 7.1500000000000004 Tract.areas.Oorig[18] = 3.4779999999999975 Tract.areas.Oorig[19] = 0.8400000000000023 Tract.areas.Oorig[20] = 0.14000000000000001 Tract.areas.I = {} Tract.areas.I[1] = 0.33750000000000002 Tract.areas.I[2] = 0.51600000000000001 Tract.areas.I[3] = 1.6049999999999998 Tract.areas.I[4] = 3.036 Tract.areas.I[5] = 2.9399999999999999 Tract.areas.I[6] = 3.6689999999999996 Tract.areas.I[7] = 4.2089999999999996 Tract.areas.I[8] = 4.4209999999999994 Tract.areas.I[9] = 4.2069999999999999 Tract.areas.I[10] = 3.5099999999999998 Tract.areas.I[11] = 2.1409999999999991 Tract.areas.I[12] = 1.2820000000000005 Tract.areas.I[13] = 0.69199999999999973 Tract.areas.I[14] = 0.28500000000000014 Tract.areas.I[15] = 0.13 Tract.areas.I[16] = 0.2320000000000001 Tract.areas.I[17] = 0.59619999999999984 Tract.areas.I[18] = 1.4467200000000005 Tract.areas.I[19] = 2.1372000000000009 Tract.areas.I[20] = 1.1508 Tract.areas.Ote = {} Tract.areas.Ote[1] = 1 Tract.areas.Ote[2] = 0.92688961903093492 Tract.areas.Ote[3] = 0.5247825237010777 Tract.areas.Ote[4] = 0.32189333498550404 Tract.areas.Ote[5] = 0.46763548284492745 Tract.areas.Ote[6] = 0.38635726853350527 Tract.areas.Ote[7] = 0.11589541907971135 Tract.areas.Ote[8] = 0.30564146594226266 Tract.areas.Ote[9] = 0.66796547392344285 Tract.areas.Ote[10] = 0.57199475591236004 Tract.areas.Ote[11] = 0.54426746255746616 Tract.areas.Ote[12] = 1.6572691417567271 Tract.areas.Ote[13] = 2.1318829657157417 Tract.areas.Ote[14] = 0.90412917570076456 Tract.areas.Ote[15] = 0.41877925428769502 Tract.areas.Ote[16] = 0.82431397519691463 Tract.areas.Ote[17] = 0.85136222899597969 Tract.areas.Ote[18] = 0.66213250158924286 Tract.areas.Ote[19] = 2.5126127303419472 Tract.areas.Ote[20] = 4.8163618382411997 Tract.areas.P = {} Tract.areas.P[1] = 0.39600000000000002 Tract.areas.P[2] = 0.93800000000000017 Tract.areas.P[3] = 1.74 Tract.areas.P[4] = 1.2859999999999998 Tract.areas.P[5] = 2.0600000000000001 Tract.areas.P[6] = 2.222 Tract.areas.P[7] = 2.4699999999999998 Tract.areas.P[8] = 1.9620000000000004 Tract.areas.P[9] = 2.2399999999999998 Tract.areas.P[10] = 2.29 Tract.areas.P[11] = 2.2319999999999998 Tract.areas.P[12] = 2.5100000000000002 Tract.areas.P[13] = 1.8499999999999994 Tract.areas.P[14] = 1.2159999999999997 Tract.areas.P[15] = 1.76 Tract.areas.P[16] = 2.0260000000000007 Tract.areas.P[17] = 2.3900000000000001 Tract.areas.P[18] = 2.4300000000000002 Tract.areas.P[19] = 1.222000000000002 Tract.areas.P[20] = 0 Tract.areas.Ite = {} Tract.areas.Ite[1] = 1 Tract.areas.Ite[2] = 1.01576089870161 Tract.areas.Ite[3] = 1.102445841560465 Tract.areas.Ite[4] = 2.2124213096810408 Tract.areas.Ite[5] = 5.1131551970096245 Tract.areas.Ite[6] = 4.7756460856513625 Tract.areas.Ite[7] = 1.7396011420540578 Tract.areas.Ite[8] = 1.0748330897992442 Tract.areas.Ite[9] = 1.2992938717978622 Tract.areas.Ite[10] = 0.79364941476701001 Tract.areas.Ite[11] = 0.28965058875936389 Tract.areas.Ite[12] = 0.53221331201324784 Tract.areas.Ite[13] = 0.63751274141271375 Tract.areas.Ite[14] = 0.3767767205337319 Tract.areas.Ite[15] = 0.41281910093151997 Tract.areas.Ite[16] = 0.80499556286143259 Tract.areas.Ite[17] = 0.95416614675261946 Tract.areas.Ite[18] = 0.96447622890739293 Tract.areas.Ite[19] = 3.7978522081335537 Tract.areas.Ite[20] = 7.2585761644867004 Tract.areas.A1 = {} Tract.areas.A1[1] = 0.27000000000000002 Tract.areas.A1[2] = 0.158 Tract.areas.A1[3] = 0.36599999999999999 Tract.areas.A1[4] = 1.1800000000000002 Tract.areas.A1[5] = 0.81999999999999995 Tract.areas.A1[6] = 0.68799999999999994 Tract.areas.A1[7] = 0.69599999999999995 Tract.areas.A1[8] = 0.97799999999999976 Tract.areas.A1[9] = 1.0660000000000001 Tract.areas.A1[10] = 1.1699999999999999 Tract.areas.A1[11] = 1.6179999999999999 Tract.areas.A1[12] = 2.2859999999999996 Tract.areas.A1[13] = 2.9380000000000006 Tract.areas.A1[14] = 4.202 Tract.areas.A1[15] = 4.9400000000000004 Tract.areas.A1[16] = 5.7339999999999991 Tract.areas.A1[17] = 5.1700000000000017 Tract.areas.A1[18] = 3.7259999999999982 Tract.areas.A1[19] = 2.2460000000000018 Tract.areas.A1[20] = 1.1699999999999999 Tract.areas.Ae = {} Tract.areas.Ae[1] = 0.26000000000000001 Tract.areas.Ae[2] = 0.154 Tract.areas.Ae[3] = 0.39599999999999991 Tract.areas.Ae[4] = 1.4399999999999999 Tract.areas.Ae[5] = 0.83999999999999997 Tract.areas.Ae[6] = 1.9319999999999995 Tract.areas.Ae[7] = 1.9970000000000001 Tract.areas.Ae[8] = 2.7140000000000004 Tract.areas.Ae[9] = 3.6829999999999994 Tract.areas.Ae[10] = 3.6899999999999999 Tract.areas.Ae[11] = 3.6319999999999997 Tract.areas.Ae[12] = 3.266 Tract.areas.Ae[13] = 3.202 Tract.areas.Ae[14] = 3.2979999999999996 Tract.areas.Ae[15] = 3.8099999999999996 Tract.areas.Ae[16] = 4.2380000000000004 Tract.areas.Ae[17] = 4.721000000000001 Tract.areas.Ae[18] = 4.4139999999999997 Tract.areas.Ae[19] = 4.5269999999999992 Tract.areas.Ae[20] = 3.9399999999999999 Tract.areas.U = {} Tract.areas.U[1] = 0.39000000000000001 Tract.areas.U[2] = 0.48199999999999998 Tract.areas.U[3] = 1.9039999999999999 Tract.areas.U[4] = 1.6759999999999999 Tract.areas.U[5] = 1.1100000000000001 Tract.areas.U[6] = 1.236 Tract.areas.U[7] = 0.89000000000000001 Tract.areas.U[8] = 0.82599999999999996 Tract.areas.U[9] = 0.89400000000000002 Tract.areas.U[10] = 0.65000000000000002 Tract.areas.U[11] = 0.65759999999999996 Tract.areas.U[12] = 0.49320000000000003 Tract.areas.U[13] = 0.49320000000000003 Tract.areas.U[14] = 5.2602000000000002 Tract.areas.U[15] = 5.5068000000000001 Tract.areas.U[16] = 5.0136000000000003 Tract.areas.U[17] = 3.4518 Tract.areas.U[18] = 1.3151999999999999 Tract.areas.U[19] = 0.32879999999999998 Tract.areas.U[20] = 0.22 Tract.areas.Ete = {} Tract.areas.Ete[1] = 1 Tract.areas.Ete[2] = 0.97852542619784599 Tract.areas.Ete[3] = 0.86041527028599907 Tract.areas.Ete[4] = 1.2585521381547484 Tract.areas.Ete[5] = 2.5601212976395402 Tract.areas.Ete[6] = 2.4429825812798596 Tract.areas.Ete[7] = 1.1435873017164502 Tract.areas.Ete[8] = 1.1822637462927383 Tract.areas.Ete[9] = 1.7227170874214117 Tract.areas.Ete[10] = 1.1191622403420101 Tract.areas.Ete[11] = 0.49994679103032386 Tract.areas.Ete[12] = 0.86813350760386765 Tract.areas.Ete[13] = 1.0174253889456677 Tract.areas.Ete[14] = 0.58299770966948383 Tract.areas.Ete[15] = 0.51435020460869008 Tract.areas.Ete[16] = 0.88463890860636452 Tract.areas.Ete[17] = 0.96847534843363714 Tract.areas.Ete[18] = 0.88862478016353796 Tract.areas.Ete[19] = 3.316189047836767 Tract.areas.Ete[20] = 6.3009566123863001 Tract.areas.Uo = {} Tract.areas.Uo[1] = 0.39000000000000001 Tract.areas.Uo[2] = 0.48200000000000004 Tract.areas.Uo[3] = 1.9039999999999999 Tract.areas.Uo[4] = 1.6759999999999997 Tract.areas.Uo[5] = 1.1100000000000001 Tract.areas.Uo[6] = 1.2360000000000002 Tract.areas.Uo[7] = 0.89000000000000001 Tract.areas.Uo[8] = 0.82600000000000051 Tract.areas.Uo[9] = 0.89400000000000013 Tract.areas.Uo[10] = 0.65000000000000002 Tract.areas.Uo[11] = 1.006 Tract.areas.Uo[12] = 1.4219999999999997 Tract.areas.Uo[13] = 2.1200000000000006 Tract.areas.Uo[14] = 3.2240000000000002 Tract.areas.Uo[15] = 4.7400000000000002 Tract.areas.Uo[16] = 5.6660000000000004 Tract.areas.Uo[17] = 4.7860000000000014 Tract.areas.Uo[18] = 2.2299999999999978 Tract.areas.Uo[19] = 0.73800000000000132 Tract.areas.Uo[20] = 0.22 Tract.areas.S = {} Tract.areas.S[1] = 0.22599999999999998 Tract.areas.S[2] = 0.18599999999999997 Tract.areas.S[3] = 0.96599999999999975 Tract.areas.S[4] = 1.4119999999999999 Tract.areas.S[5] = 0.70999999999999996 Tract.areas.S[6] = 1.5419999999999994 Tract.areas.S[7] = 2.0880000000000001 Tract.areas.S[8] = 2.2800000000000002 Tract.areas.S[9] = 2.8080000000000003 Tract.areas.S[10] = 1.9299999999999999 Tract.areas.S[11] = 0.94600000000000006 Tract.areas.S[12] = 1.2519999999999998 Tract.areas.S[13] = 1.2039999999999997 Tract.areas.S[14] = 0.42599999999999971 Tract.areas.S[15] = 0.22 Tract.areas.S[16] = 0 Tract.areas.S[17] = 0 Tract.areas.S[18] = 0 Tract.areas.S[19] = 1.5980000000000001 Tract.areas.S[20] = 1.1699999999999999 Tract.areas.M = {} Tract.areas.M[1] = 0.49799999999999989 Tract.areas.M[2] = 1.2200000000000006 Tract.areas.M[3] = 3.036 Tract.areas.M[4] = 3.5380000000000007 Tract.areas.M[5] = 3.5699999999999998 Tract.areas.M[6] = 3.0099999999999998 Tract.areas.M[7] = 2.9819999999999998 Tract.areas.M[8] = 2.758 Tract.areas.M[9] = 2.8420000000000005 Tract.areas.M[10] = 2.27 Tract.areas.M[11] = 2.1040000000000001 Tract.areas.M[12] = 1.8800000000000003 Tract.areas.M[13] = 1.6100000000000003 Tract.areas.M[14] = 2.2720000000000002 Tract.areas.M[15] = 3.5099999999999998 Tract.areas.M[16] = 4.7539999999999996 Tract.areas.M[17] = 3.898000000000001 Tract.areas.M[18] = 1.9879999999999978 Tract.areas.M[19] = 0 Tract.areas.M[20] = 0.69999999999999996 Tract.nasal = {} Tract.nasal.N = true Tract.nasal.M = true Tract.len = {} Tract.len.K = 17.460000000000001 Tract.len.I2 = 16.670000000000002 Tract.len.N = 17.460000000000001 Tract.len.M = 17.460000000000001 Tract.len.L = 18.25 Tract.len.Oorig = 17.460000000000001 Tract.len.E = 15.880000000000001 Tract.len.I = 16.670000000000002 Tract.len.Lorig = 18.25 Tract.len.A = 17.460000000000001 Tract.len.U = 18.25 Tract.len.U1 = 17.460000000000001 Tract.len.A1 = 17.460000000000001 Tract.len.Ae = 16.670000000000002 Tract.len.O = 17.460000000000001 Tract.area1len = 9.1428571428571423 return Tract
--- === hs.doc === --- --- Create documentation objects for interactive help within Hammerspoon --- --- e.g. `doc = hs.doc.fromJSONFile('path-to-docs.json')` --- --- You can use the `hs.docstrings_json_file` constant, e.g. `doc = hs.doc.fromJSONFile(hs.docstrings_json_file)` --- --- Debugging modes: --- Mostly only have an affect on `hs.doc.fromArray` and `hs.doc.fromPackageLoaded`. --- --- Set the flag in the global namespace one of these ways: --- _G["debug.docs.module"] = "build" -- building metatables for return --- _G["debug.docs.module"] = "genjson" -- creating items in genjson --- _G["debug.docs.module"] = "load" -- which files are being loaded --- _G["debug.docs.module"] = "sort" -- sorting module namespaces for item attachment --- --- Setting it to any of these, or even just `true` causes the global arrays --- doc_module_json and doc_module_array to be created for further review. local module = {} -- private variables and methods ----------------------------------------- local json = require("hs.json") -- Provide function 'f' as per _Programming_In_Lua,_3rd_ed_, page 52; otherwise order is ascii order ascending. -- e.g. function(m,n) return not (m < n) end would do descending ascii, assuming string keys. local sorted_keys = function(t, f) if t then local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter else return function() return nil end end end local function item_tostring(item) return item[2] .. ": " .. item[1] .. "\n\n" .. item[3] .. "\n" end local function group_tostring(group) local str = group.__doc .. "\n\n" str = str .. "[submodules]\n" for name, item in sorted_keys(group) do if name ~= '__doc' and name ~= '__name' and getmetatable(item) == getmetatable(group) then str = str .. item.__name .. "\n" end end str = str .. "\n" .. "[subitems]\n" for name, item in sorted_keys(group) do if name ~= '__doc' and name ~= '__name' and getmetatable(item) ~= getmetatable(group) then str = str .. item[1] .. "\n" end end return str .. "\n" end local function doc_tostring(doc) local str = '[modules]\n' for name, group in sorted_keys(doc) do str = str .. group.__name .. '\n' end return str end local group_metatable = {__tostring = group_tostring} local item_metatable = {__tostring = item_tostring} local internalBuild = function(content) local rawdocs = json.decode(content) local doc = setmetatable({}, {__tostring = doc_tostring}) for _, mod in pairs(rawdocs) do local parts = {} for s in string.gmatch(mod.name, "[%w_]+") do table.insert(parts, s) end local parent = doc local keyname = parts[#parts] parts[#parts] = nil local subname = nil for _, s in ipairs(parts) do subname = subname and subname.."."..s or s if type(parent[s]) == "nil" then parent[s] = setmetatable({__doc = subname, __name = subname}, group_metatable) end parent = parent[s] end local m = setmetatable({__doc = mod.doc, __name = mod.name}, group_metatable) parent[keyname] = m for _, item in pairs(mod.items) do if _G["debug.docs.module"] == "build" then print(mod.name, item, item.def) if item.name == nil and package.searchpath("inspect",package.path) then print(require("inspect")(item)) end end m[item.name] = setmetatable({__name = item.name, item.def, item.type, item.doc}, item_metatable) end end return doc end local split = function(div,str) if (div=='') then return { str } end local pos,arr = 0,{} for st,sp in function() return string.find(str,div,pos) end do table.insert(arr,string.sub(str,pos,st-1)) pos = sp + 1 end if string.sub(str,pos) ~= "" then table.insert(arr,string.sub(str,pos)) end return arr end -- Holder object so we can autoupdate for package.loaded without caring where -- the user actually stores the reference. We return a reference to -- package_loaded_holder, which never changes, and then use meta-methods so -- that any direct access is passed through to the internal results, which -- does change every time the update is invoked. local package_loaded_holder = { results = {} } setmetatable(package_loaded_holder, { __tostring = function(o) return tostring(o.results) end, __index = function(o,k) return o.results[k] end }) local do_package_loaded_update = function() local packageLoadedArray = {} for i,v in pairs(package.loaded) do table.insert(packageLoadedArray, i) end package_loaded_holder.results = module.fromArray(packageLoadedArray) end -- Public interface ------------------------------------------------------ --- hs.doc.fromJSONFile(jsonfile) -> doc-array --- Function --- Builds a doc array construct from the json file provided. --- --- Parameters: --- * jsonfile - A string containing the location of a json file --- --- Returns: --- * A table containing the documentation data loaded from the json file --- --- Notes: --- * Usually this will be the json file provided with the Hammerspoon application, but this json file will only contain the documentation for modules recognized by the Hammerspoon builders and the built in modules and not modules from other sources. For those, use `hs.doc.fromArray` and `hs.doc.fromPackageLoaded`. function module.fromJSONFile(docsfile) local f = io.open(docsfile) if not f then print("Documentation file '"..docsfile.."' not found...") return setmetatable( {"Documentation file '"..docsfile.."' not found..."}, {__tostring = function(a) return a[1] end} ) end local content = f:read("*a") f:close() if _G["debug.docs.module"] then doc_module_json = json.encode(mods,true) doc_module_array = "loaded via json file: "..docsfile end return internalBuild(content) end --- hs.doc.fromArray(array) -> doc-array --- Function --- Builds a doc array construct from the lua files of the modules listed in the provided array --- --- Parameters: --- * array - A table containing the locations of files --- --- Returns: --- * A table containing the documentation data loaded from the files --- --- Notes: --- * This is useful for creating doc objects for in progress modules or local files. function module.fromArray(theArray) -- bin/gencomments local lines = {} for i,v in ipairs(theArray) do if package.searchpath(v,package.path) then if _G["debug.docs.module"] == "load" then print("load_path: ", v, package.searchpath(v,package.path)) end local f = io.open(package.searchpath(v, package.path), 'r') local r = f:read('*a') ; f:close() local partial = {} local incomment = false for _,l in ipairs(split("[\r\n]",r)) do if l:match("^[/%-][/%-][/%-]") and not l:match("^[/%-][/%-][/%-][/%-]") then incomment = true table.insert(partial, (l:gsub("^[/%-][/%-][/%-]%s?",""))) elseif incomment then incomment = false table.insert(lines, partial) partial = {} end end end end -- bin/genjson local mods, items = {}, {} local found_mods = {} for i,v in ipairs(lines) do if v[1]:match("===") then local name = string.match(v[1]:gsub("=",""), "^[%s\r\n]*([^%s\r\n].*[^%s\r\n])[%s\r\n]*$") local doc = "" local items = {} for a = 2, #v, 1 do doc = doc..v[a].."\n" end doc = doc:match("^[%s\r\n]*([^%s\r\n].*[^%s\r\n])[%s\r\n]*$") or "--not provided--" if found_mods[name] then print("Duplicate namespace: ", name, " with description\n", doc) else table.insert(mods, {name = name, doc = doc, items = items}) found_mods[name] = true end else local name = "" local def = v[1] or "" local i_type = v[2] or "" local doc = "" for a = 3, #v, 1 do doc = doc..v[a].."\n" end doc = doc:match("^[%s\r\n]*([^%s\r\n].*[^%s\r\n])[%s\r\n]*$") or "--not provided--" table.insert(items, {name = name, def = def, type = i_type, doc = doc}) end end if _G["debug.docs.module"] then doc_module_array = mods end table.sort(mods, function(m,n) if _G["debug.docs.module"] == "sort" then print(m.name, type(m.name), n.name, type(n.name)) end if m and m.name and n and n.name then return not (m.name < n.name) end if _G["debug.docs.module"] then print("error sorting in genjson") if item.name == nil and package.searchpath("inspect",package.path) then print("m:",require("inspect")(m),"n:",require("inspect")(n)) end end return nil end) for i,v in ipairs(items) do local mod for a,b in ipairs(mods) do if v.def:match("^"..b.name:gsub("%.","%%.").."[%.:]") then mod = b break end end if not mod then print("parse error: no module for entity '"..v.def.."'... skipping.") else local name,sep = v.def:match("^"..mod.name:gsub("%.","%%.").."[%.:]([%w_]+)(.?)") if _G["debug.docs.module"] == "genjson" then print(name,sep) end if sep == "." or sep == ":" then print("parse error: '"..name.."' is not a defined submodule of '"..mod.name.."'... skipping.") else v.name = name table.insert(mod.items, v) end end end table.sort(mods, function(m,n) return m.name < n.name end) if _G["debug.docs.module"] then doc_module_array = mods doc_module_json = json.encode(mods,true) end return internalBuild(json.encode(mods,true)) end --- hs.doc.fromPackageLoaded([refreshOnRequire]) -> doc-array --- Function --- Builds a doc array construct from the lua files of all modules currently tracked in `package.loaded` --- --- Parameters: --- * refreshOnRequire - An optional boolean indicating whether the doc array should be refreshed every time `require()` is called. Defaults to false --- --- Returns: --- * A table containing the documentation data loaded from the files module.fromPackageLoaded = function(autorefresh) do_package_loaded_update() if autorefresh then setmetatable(package.loaded, { __newindex = function(o,k,v) rawset(o,k,v) do_package_loaded_update() end }) end return autorefresh and package_loaded_holder or package_loaded_holder.results end -- Return Module Object -------------------------------------------------- return module
-- Source Component -- local Base = require 'modern' local Source = Base:extend() -- New -- function Source:new(host, data) self.host = host -- -- properties self._src = data.src or host end -- Get/set `source` value -- function Source:source(value) if value == nil then return self._src end self._src = value end return Source
local sprite = BaseSprite:extend({ type = 'goomba', enemy = true, collision = 'slide' }) function sprite:constructor (x, y) self.destroyed = false self.frozen = false self.x = x self.y = y self.dx = 0 self.dy = 0 self.behavior = Behavior { default = { { duration = 0, after = 'walk' }, }, walk = { { duration = 0.2, quad = Quads.sprites[1][7] }, { duration = 0.2, quad = Quads.sprites[1][6] }, }, stomp = { { duration = 1, quad = Quads.sprites[1][8] }, }, } self.handler = Event.on('dead', function () self.frozen = true end) GlobalState.world:add(self, self.x, self.y, 16, 16) end function sprite:stomp (touch, kicked) if kicked then Sounds.kick:seek(0) Sounds.kick:play() else Sounds.stomp:seek(0) Sounds.stomp:play() end self.behavior:setState('stomp') self.frozen = true self.collision = false Timer.after(0.5, function () self:destroy() end) end function sprite:update (dt) if self.destroyed or self.frozen then return end self.behavior:update(dt) if GlobalState.onFrame then if not self.visible and -GlobalState.tx + VIRTUAL_WIDTH + 16 > self.x then self.visible = true self.dx = -0x1c8 self.dy = 0x700 end local actualX, actualY, cols = GlobalState.world:move(self, self.x+self.dx/1000, self.y+self.dy/1000, function (_, other) if other.collision == false then return nil end return other.collision or 'slide' end) self.x = actualX self.y = actualY for _, col in pairs(cols) do if col.type == 'slide' and col.normal.x ~= 0 then self.dx = self.dx * -1 end if col.other.type == 'mario' then col.other:hit(self) end end if self.visible and (self.x < -GlobalState.tx-16 or self.x > -GlobalState.tx + VIRTUAL_WIDTH * 1.5) then self:destroy() end if self.x < -16 or self.y > VIRTUAL_HEIGHT + 16 then self:destroy() end end end function sprite:draw () if self.destroyed then return end if self.behavior.frame.quad then love.graphics.draw(Graphics.sprites, self.behavior.frame.quad, math.floor(self.x), math.floor(self.y)) end end function sprite:destroy () GlobalState.world:remove(self) self.handler:remove() self.destroyed = true end return sprite
--[[ /******************************************************* * Copyright (c) 2014, ArrayFire * All rights reserved. * * This file is distributed under 3-clause BSD license. * The complete license agreement can be obtained at: * http://arrayfire.com/licenses/BSD-3-Clause ********************************************************/ #include <cmath> #include <cstdio> #include <cstdlib> #include <arrayfire.h> using namespace af; array changeContrast(const array &in, const float contrast) { float scale = tan((contrast + 1)*Pi / 4); return (((in / 255.0f - 0.5f) * scale + 0.5f) * 255.0f); } array changeBrightness(const array &in, const float brightness, const float channelMax = 255.0f) { float factor = brightness*channelMax; return (in + factor); } array clamp(const array &in, float min = 0.0f, float max = 255.0f) { return ((in<min)*0.0f + (in>max)*255.0f + (in >= min && in <= max)*in); } array usm(const array &in, float radius, float amount) { int gKernelLen = 2 * radius + 1; array blurKernel = gaussianKernel(gKernelLen, gKernelLen); array blur = convolve(in, blurKernel); return (in + amount*(in - blur)); } array digZoom(const array &in, int x, int y, int width, int height) { array cropped = in(seq(x, width - 1), seq(y, height - 1), span); return resize(cropped, (unsigned)in.dims(0), (unsigned)in.dims(1)); } array alphaBlend(const array &a, const array &b, const array &mask) { array tiledMask; if (mask.dims(2) != a.dims(2)) tiledMask = tile(mask, 1, 1, a.dims(2)); return a*tiledMask + (1.0f - tiledMask)*b; } void normalizeImage(array &in) { float min = af::min<float>(in); float max = af::max<float>(in); in = 255.0f*((in - min) / (max - min)); } array boundary(const array &in, const array &mask) { array ret_val = in - erode(in, mask); normalizeImage(ret_val); return ret_val; } int main(int argc, char **argv) { try { int device = argc > 1 ? atoi(argv[1]) : 0; af::setDevice(device); af::info(); array man = loadImage(ASSETS_DIR "/examples/images/man.jpg", true); array fight = loadImage(ASSETS_DIR "/examples/images/fight.jpg", true); array nature = resize(loadImage(ASSETS_DIR "/examples/images/nature.jpg", true), fight.dims(0), fight.dims(1)); array intensity = colorSpace(fight, AF_GRAY, AF_RGB); array mask = clamp(intensity, 10.0f, 255.0f)>0.0f; array blend = alphaBlend(fight, nature, mask); array highcon = changeContrast(man, 0.3); array highbright = changeBrightness(man, 0.2); array translated = translate(man, 100, 100, 200, 126); array sharp = usm(man, 3, 1.2); array zoom = digZoom(man, 28, 10, 192, 192); array morph_mask = constant(1, 3, 3); array bdry = boundary(man, morph_mask); af::Window wnd("Image Editing Operations"); std::cout << "Press ESC while the window is in focus to exit" << std::endl; while (!wnd.close()) { wnd.grid(2, 5); wnd(0, 0).image(man / 255, "Input"); wnd(1, 0).image(highcon / 255, "High Contrast"); wnd(0, 1).image(highbright / 255, "High Brightness"); wnd(1, 1).image(translated / 255, "Translation"); wnd(0, 2).image(sharp / 255, "Unsharp Masking"); wnd(1, 2).image(zoom / 255, "Digital Zoom"); wnd(0, 3).image(nature / 255, "Background for blend"); wnd(1, 3).image(fight / 255, "Foreground for blend"); wnd(0, 4).image(blend / 255, "Alpha blend"); wnd(1, 4).image(bdry / 255, "Boundary extraction"); wnd.show(); } } catch (af::exception& e) { fprintf(stderr, "%s\n", e.what()); throw; } #ifdef WIN32 // pause in Windows if (!(argc == 2 && argv[1][0] == '-')) { printf("hit [enter]..."); fflush(stdout); getchar(); } #endif return 0; } ]]
function update(x) local forceX, forceY; local gLeft, gRight; local animeState; if x == 0 then forceX == forceY = 0.0 animeState = "idle" gLeft == gRight = false end elseif x == 1 then forceX = -0.01 forceY = 0.0 animeState = "moveleft" gLeft = true gRight = false end elseif x == 2 then forceX = 0.01 forceY = 0.0 animeState = "moveright" gLeft = false gRight = true end return forceX,forceY,animeState,gLeft,gRight end
-------------------------------------------------------------------------------- --- Head: Require -- local awful = require("awful") require("awful.autofocus") -- -- Tail: Require -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --- Head: Main -- https://awesomewm.org/doc/api/classes/screen.html -- https://awesomewm.org/doc/api/classes/screen.html#awful.screen.connect_for_each_screen -- https://github.com/awesomeWM/awesome/blob/v4.2/awesomerc.lua#L191 awful.screen.connect_for_each_screen(function(s) -- do something print('connect_for_each_screen') end) --- Tail: Main --------------------------------------------------------------------------------
local ObjectManager = require("managers.object.object_manager") local shuttleanimationHelper = ScreenPlay:new { numberOfActs = 1, questString = "shuttleanimationHelper", states = {}, planetName = "talus", mobileName = "lambda_shuttle", x = 0, z = 200, y = 0, direction = 0, scriptName = "shuttleanimationHelper", waitingtime = 60000, } function shuttleanimationHelper:start() if (isZoneEnabled(self.planetName)) then local pShuttle = spawnMobile(self.planetName, self.mobileName, 0, self.x, self.z, self.y, self.direction, 0) ObjectManager.withCreatureObject(pShuttle, function(shuttle) writeData("shuttleanimation:" .. self.scriptName .. ":objectID", shuttle:getObjectID()) shuttle:setOptionsBitmask(256) shuttle:setPosture(PRONE) createEvent(self.waitingtime, self.scriptName, "launchferry", shuttle) end) end end function shuttleanimationHelper:launchferry(shuttle) local pShuttle = getCreatureObject(readData("shuttleanimation:" .. self.scriptName .. ":objectID")) ObjectManager.withCreatureObject(pShuttle, function(shuttle) shuttle:setPosture(FLYING) createEvent(self.waitingtime, self.scriptName, "landferry", shuttle) end) end function shuttleanimationHelper:landferry(shuttle) local pShuttle = getCreatureObject(readData("shuttleanimation:" .. self.scriptName .. ":objectID")) ObjectManager.withCreatureObject(pShuttle, function(shuttle) shuttle:setPosture(PRONE) createEvent(self.waitingtime, self.scriptName, "launchferry", shuttle) end) end return shuttleanimationHelper
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:29' using the latest game version. NOTE: This file should only be used as IDE support; it should NOT be distributed with addons! **************************************************************************** CONTENTS OF THIS FILE IS COPYRIGHT ZENIMAX MEDIA INC. **************************************************************************** ]] ESO_Dialogs["LEGAL_AGREEMENT_UPDATED_ACKNOWLEDGE"] = { mustChoose = true, gamepadInfo = { dialogType = GAMEPAD_DIALOGS.BASIC, }, mainText = { text = SI_CONSOLE_LEGAL_AGREEMENT_UPDATED_ACKNOWLEDGE_DIALOG_BODY, }, buttons = { { text = SI_CONSOLE_LEGAL_BUTTON_AGREE, keybind = "DIALOG_PRIMARY", callback = function(dialog) PregameStateManager_AdvanceState() end, }, { text = SI_CONSOLE_LEGAL_BUTTON_DISAGREE, keybind = "DIALOG_NEGATIVE", callback = function(dialog) PREGAME_INITIAL_SCREEN_GAMEPAD:ShowError(GetString(SI_LEGAL_DECLINE_HEADER), GetString(SI_LEGAL_DECLINE_PROMPT)) end, }, } } ESO_Dialogs["FREE_TRIAL_INACTIVE"] = { canQueue = true, gamepadInfo = { dialogType = GAMEPAD_DIALOGS.BASIC, }, title = { text = SI_FREE_TRIAL_PURCHASE_DIALOG_HEADER, }, mainText = { text = SI_FREE_TRIAL_PURCHASE_DIALOG_BODY, }, noChoiceCallback = function() ZO_Disconnect() end, buttons = { { text = SI_FREE_TRIAL_PURCHASE_KEYBIND, keybind = "DIALOG_PRIMARY", callback = function() ShowPlatformESOGameClientUI() ZO_Disconnect() end, }, { text = SI_GAMEPAD_BACK_OPTION, keybind = "DIALOG_NEGATIVE", callback = function() ZO_Disconnect() end, }, }, }
--[[ TheNexusAvenger Mirrors the API of Roblox's Plugin class. --]] local CLASS_NAME = "NexusPlugin" local NexusPluginFramework = require(script.Parent.Parent:WaitForChild("NexusPluginFrameworkProject")):GetContext(script) local NexusContainer = NexusPluginFramework:GetResource("Base.NexusContainer") local NexusStudioTheme = NexusPluginFramework:GetResource("Plugin.NexusStudioTheme") local NexusEventCreator = NexusPluginFramework:GetResource("NexusInstance.Event.NexusEventCreator") local NexusPlugin = NexusContainer:Extend() NexusPlugin:SetClassName(CLASS_NAME) NexusPluginFramework:SetContextResource(NexusPlugin) local CachedPlugin = plugin --[[ Returns a static plugin instance. Note it may not be a "mock" plugin (NexusPlugin). --]] function NexusPlugin.GetPlugin() --Craete the cached plugin if needed. if not CachedPlugin then CachedPlugin = NexusPlugin.new() end --Return the cached plugin. return CachedPlugin end --[[ Sets the static plugin instance. Needed to be used in a Script since plugin is not defined in ModuleScripts, even if it required by a plugin Script. --]] function NexusPlugin.SetPlugin(NewPlugin) CachedPlugin = NewPlugin end --[[ Creates a Nexus Plugin object. --]] function NexusPlugin:__new() self:InitializeSuper() self.Name = CLASS_NAME self.CollisionEnabled = true self.GridSize = 1 self.Deactivation = NexusEventCreator:CreateEvent() self.Unloading = NexusEventCreator:CreateEvent() end --[[ Sets the state of the calling plugin to activated. --]] function NexusPlugin:Activate(ExclusiveMouse) warn("Unimplemented: NexusPlugin:Activate(ExclusiveMouse)") end --[[ This function creates a DockWidgetPluginGui using the provided DockWidgetPluginGuiInfo. --]] function NexusPlugin:CreateDockWidgetPluginGui(PluginGuiId,WidgetPluginGuiInfo) error("Unimplemented: NexusPlugin:CreateDockWidgetPluginGui(PluginGuiId,WidgetPluginGuiInfo)") end --[[ Creates a PluginAction which is an object that represents a generic performable action in Roblox Studio, with no directly associated Toolbar or Button. --]] function NexusPlugin:CreatePluginAction(ActionId,Text,StatusTip,IconName,AllowBinding) error("Unimplemented: NexusPlugin:CreatePluginAction(ActionId,Text,StatusTip,IconName,AllowBinding)") end --[[ Creates a new plugin menu. --]] function NexusPlugin:CreatePluginMenu(Id,Title,Icon) error("Unimplemented: NexusPlugin:CreatePluginMenu(Id,Title,Icon)") end --[[ Gets or creates a new Toolbar with the specified name, which is then used to create a plugin button. --]] function NexusPlugin:CreateToolbar(Name) error("Unimplemented: NexusPlugin:CreateToolbar(Name)") end --[[ Deactivates the plugin. --]] function NexusPlugin:Deactivate() warn("Unimplemented: NexusPlugin:Deactivate()") end --[[ Returns the JointCreationMode the user has set in studio under the Model tab. --]] function NexusPlugin:GetJoinMode() warn("Unimplemented: NexusPlugin:GetJoinMode()") return Enum.JointCreationMode.Surface end --[[ Returns a mouse that can be used with the plugin. --]] function NexusPlugin:GetMouse() error("Unimplemented: NexusPlugin:GetMouse()") end --[[ Returns the currently selected RibbonTool. --]] function NexusPlugin:GetSelectedRibbonTool() error("Unimplemented: NexusPlugin:GetSelectedRibbonTool()") end --[[ Retrieves a previously stored value with the given key, or nil if the given key doesn’t exist. --]] function NexusPlugin:GetSetting(Key) error("Unimplemented: NexusPlugin:GetSetting(Key)") end --[[ Returns the studio user’s userId if they’re logged in, otherwise returns 0. --]] function NexusPlugin:GetStudioUserId() error("Unimplemented: NexusPlugin:GetStudioUserId()") end --[[ Prompts the user to open a .fbx animation file that can be loaded onto the rigModel, then proceeds to insert the animation as a KeyframeSequence in the Workspace. --]] function NexusPlugin:ImportFbxAnimation(RigModel,IsR15) error("Unimplemented: NexusPlugin:ImportFbxAnimation(RigModel,IsR15)") end --[[ Prompts the user to open a .fbx file, uploads the individual components of the model as meshes, and generates a character rig for use in animation, which is loaded into the Workspace. --]] function NexusPlugin:ImportFbxRig(IsR15) error("Unimplemented: NexusPlugin:ImportFbxRig(IsR15)") end --[[ Returns true if this plugin is currently active, after having been activated via the Plugin:Activate function. --]] function NexusPlugin:IsActivated() error("Unimplemented: NexusPlugin:IsActivated()") end --[[ Returns true if this plugin is currently active with an exclusive mouse, after having been activated via the Plugin:Activate function. --]] function NexusPlugin:IsActivatedWithExclusiveMouse() error("Unimplemented: NexusPlugin:IsActivatedWithExclusiveMouse()") end --[[ Negates the given parts and returns the resulting NegateOperations. --]] function NexusPlugin:Negate(Objects) error("Unimplemented: NexusPlugin:Negate(Objects)") end --[[ Used to open the given script instance in an editor window, in Roblox studio, at the given line. If no line is given as an argument it will default to 0. --]] function NexusPlugin:OpenScript(Script,LineNumber) error("Unimplemented: NexusPlugin:OpenScript(Script,LineNumber)") end --[[ Opens the context help window to the wiki page that url links to. --]] function NexusPlugin:OpenWikiPage(URL) error("Unimplemented: NexusPlugin:OpenWikiPage(URL)") end --[[ Opens a window in Roblox Studio, which prompts the user to select an asset based on the assetType specified. Returns what assetId was selected, or -1 if the window was closed. --]] function NexusPlugin:PromptForExistingAssetId(AssetType) error("Unimplemented: NexusPlugin:PromptForExistingAssetId(AssetType)") end --[[ Prompts the user to save their current selection with the specified file name. Returns true if the user did save the file. --]] function NexusPlugin:PromptSaveSelection(SuggestedFileName) error("Unimplemented: NexusPlugin:PromptSaveSelection(SuggestedFileName)") end --[[ Opens an upload window for the user’s current selection. --]] function NexusPlugin:SaveSelectedToRoblox() error("Unimplemented: NexusPlugin:SaveSelectedToRoblox()") end --[[ Activates the specified Roblox Studio tool. --]] function NexusPlugin:SelectRibbonTool(Tool,Position) error("Unimplemented: NexusPlugin:SelectRibbonTool(Tool,Position)") end --[[ Separates the given UnionOperations and returns the resulting parts. --]] function NexusPlugin:Separate(Objects) error("Unimplemented: NexusPlugin:Separate(Objects)") end --[[ Stores a given value for later use under the given key. The value will persist even after studio is closed. --]] function NexusPlugin:SetSetting(Key,Value) error("Unimplemented: NexusPlugin:SetSetting(Key,Value)") end --[[ Unions the given parts and returns the resulting UnionOperation. --]] function NexusPlugin:Union(Objects) error("Unimplemented: NexusPlugin:Union(Objects)") end return NexusPlugin
Log = {} function Log.debug(message) if Config.DebugLog then Wrapper.print(message) end end
--下面基础组件间的require有依赖顺序相关,闲着没事也别换顺序,要加新的往文件尾加就好 Mathf = require "Common.UnityEngine.Mathf" Vector2 = require "Common.UnityEngine.Vector2" Vector3 = require "Common.UnityEngine.Vector3" Vector4 = require "Common.UnityEngine.Vector4" Quaternion = require "Common.UnityEngine.Quaternion" Color = require "Common.UnityEngine.Color" Ray = require "Common.UnityEngine.Ray" Bounds = require "Common.UnityEngine.Bounds" RaycastHit = require "Common.UnityEngine.RaycastHit" Touch = require "Common.UnityEngine.Touch" LayerMask = require "Common.UnityEngine.LayerMask" Plane = require "Common.UnityEngine.Plane" Time = require "Common.UnityEngine.Time" Object = require "Common.UnityEngine.Object" require("Common/BaseClass") require("Common.Util.util") require("Common.Util.LuaUtil") list = require("Common.Util.list") require("Common.Util.event") require("Common.Util.Timer") UpdateManager = require "Common.UpdateManager" require "Common.GlobalEventSystem" ECS = require "Game.Common.ECS" require("Game.Common.Action.ActionNodeWrapper") require("Game.Common.Action.ActionTweenFunction") require("Game.Common.Action.Action") require("Game.Common.Action.ActionInterval") require("Game.Common.Action.ActionEase") require("Game.Common.Action.ActionInstant") require("Game.Common.Action.ActionManager") require("Game.Common.Action.ActionCatmullRom") -- require("Game.Common.Action.ActionExtend") --顺序无关的 require("Common.Util.Functor") require("Game.Common.UIGlobal") require("Tools.CookieWrapper") require("Game.Common.ResPath")
workspace "Transcendent-Engine" architecture "x86_64" startproject "Editor" configurations { "Debug", "Release", "Distrib" } flags { "MultiProcessorCompile" } outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}" IncludeDir = {} IncludeDir["GLFW"] = "Transcendent-Engine/vendor/glfw/include" IncludeDir["GLAD"] = "Transcendent-Engine/vendor/glad/include" IncludeDir["ImGui"] = "Transcendent-Engine/vendor/imgui" IncludeDir["glm"] = "Transcendent-Engine/vendor/glm" IncludeDir["stb"] = "Transcendent-Engine/vendor/stb" group "Dependencies" include "Transcendent-Engine/vendor/glfw" include "Transcendent-Engine/vendor/glad" include "Transcendent-Engine/vendor/imgui" group "" project "Transcendent-Engine" location "Transcendent-Engine" kind "StaticLib" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") pchheader "tepch.h" pchsource "Transcendent-Engine/src/tepch.cpp" files { "%{prj.name}/include/Transcendent-Engine.h", "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp", "%{prj.name}/vendor/stb/**.h", "%{prj.name}/vendor/glm/glm/**.hpp", "%{prj.name}/vendor/glm/glm/**.inl" } defines { "_CRT_SECURE_NO_WARNINGS" } includedirs { "%{prj.name}/src", "%{prj.name}/vendor/spdlog/include", "%{prj.name}/src/Transcendent-Engine", "%{IncludeDir.GLFW}", "%{IncludeDir.GLAD}", "%{IncludeDir.ImGui}", "%{IncludeDir.glm}", "%{IncludeDir.stb}" } links { "GLFW", "GLAD", "ImGui", "opengl32.lib" } filter "system:windows" systemversion "latest" defines { "TE_BUILD_DLL", "GLFW_INCLUDE_NONE" } filter "configurations:Debug" defines "TE_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "TE_RELEASE" runtime "Release" optimize "on" filter "configurations:Distrib" defines "TE_DISTRIB" runtime "Release" optimize "on" project "Sandbox" location "Sandbox" kind "ConsoleApp" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } includedirs { "Transcendent-Engine/vendor/spdlog/include", "Transcendent-Engine/include", "Transcendent-Engine/src", "Transcendent-Engine/vendor", "%{IncludeDir.ImGui}", "%{IncludeDir.GLAD}", "%{IncludeDir.glm}" } links { "Transcendent-Engine" } filter "system:windows" systemversion "latest" filter "configurations:Debug" defines "TE_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "TE_RELEASE" runtime "Release" optimize "on" filter "configurations:Dist" defines "TE_DISTRIB" runtime "Release" optimize "on" project "Editor" location "Editor" kind "ConsoleApp" language "C++" cppdialect "C++17" staticruntime "on" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("bin-int/" .. outputdir .. "/%{prj.name}") files { "%{prj.name}/src/**.h", "%{prj.name}/src/**.cpp" } includedirs { "Transcendent-Engine/vendor/spdlog/include", "Transcendent-Engine/include", "Transcendent-Engine/src", "Transcendent-Engine/vendor", "%{IncludeDir.ImGui}", "%{IncludeDir.GLAD}", "%{IncludeDir.glm}" } links { "Transcendent-Engine" } filter "system:windows" systemversion "latest" filter "configurations:Debug" defines "TE_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "TE_RELEASE" runtime "Release" optimize "on" filter "configurations:Dist" defines "TE_DISTRIB" runtime "Release" optimize "on"
local expirationd = require("expirationd") local t = require("luatest") local g = t.group("process_while") local helpers = require("test.helper") g.before_all(function() helpers.init_spaces(g) end) g.after_each(function() helpers.truncate_spaces(g) end) function g.test_passing() local task = expirationd.start("clean_all", g.tree.id, helpers.is_expired_true) -- default process_while always return false, iterations never stopped by this function t.assert_equals(task.process_while(), true) task:kill() local function process_while() return false end task = expirationd.start("clean_all", g.tree.id, helpers.is_expired_true, {process_while = process_while}) t.assert_equals(task.process_while(), false) task:kill() -- errors t.assert_error_msg_contains("bad argument options.process_while to nil (?function expected, got string)", expirationd.start, "clean_all", g.tree.id, helpers.is_expired_true, { process_while = "" }) end local function process_while(task) if task.checked_tuples_count >= 1 then return false end return true end function g.test_tree_index() for _, space in pairs({g.tree, g.vinyl}) do helpers.iteration_result = {} space:insert({1, "3"}) space:insert({2, "2"}) space:insert({3, "1"}) local task = expirationd.start("clean_all", space.id, helpers.is_expired_debug, {process_while = process_while}) -- wait for tuples expired helpers.retrying({}, function() t.assert_equals(helpers.iteration_result, {{1, "3"}}) end) task:kill() end end function g.test_hash_index() helpers.iteration_result = {} g.hash:insert({1, "3"}) g.hash:insert({2, "2"}) g.hash:insert({3, "1"}) local task = expirationd.start("clean_all", g.hash.id, helpers.is_expired_debug, {process_while = process_while}) -- wait for tuples expired helpers.retrying({}, function() t.assert_equals(helpers.iteration_result, {{3, "1"}}) end) task:kill() end
local button = script.parent local TYPE = script:GetCustomProperty("TYPE") while not _G["LoadoutState"] do Task.Wait() end local HOVER_SOUND = script:GetCustomProperty("HOVER_SOUND") button.pressedEvent:Connect(function() if(TYPE) == "Perks" or (TYPE) == "Equipment" then Events.Broadcast("SpawnLoadoutIconPanel", TYPE) else Events.Broadcast("SpawnLoadoutEquipPanel", TYPE) end _G["LoadoutState"] = _G["LOADOUTSTATEENUMS"][3] Events.Broadcast("UpdatedLoadoutState") end) function Hover() World.SpawnAsset(HOVER_SOUND) end button.hoveredEvent:Connect(Hover)
project "App_TinyAudioExample" language "C++" kind "ConsoleApp" includedirs { ".", "../../src", } defines {"B3_USE_STANDALONE_EXAMPLE", "__STK_REALTIME__"} files { "**.cpp", "**.h", "../StandaloneMain/main_console_single_example.cpp", "../Utils/b3ResourcePath.cpp" } links {"Bullet3Common"} if os.is("Windows") then links {"winmm","Wsock32","dsound"} defines {"WIN32","__WINDOWS_MM__","__WINDOWS_DS__"} end if os.is("Linux") then initX11() defines {"__OS_LINUX__","__LINUX_ALSA__"} links {"asound","pthread"} end if os.is("MacOSX") then links{"Cocoa.framework"} links{"CoreAudio.framework", "coreMIDI.framework", "Cocoa.framework"} defines {"__OS_MACOSX__", "__MACOSX_CORE__"} end
KuiNameplatesCoreSaved = { ["216_HEALTH_TRANSITION"] = true, ["2162_PERSONAL_FRAME_SIZE_TRANSITION"] = true, ["profiles"] = { ["RealUI"] = { ["glow_as_shadow"] = false, ["frame_height"] = 18, ["target_arrows_size"] = 38, ["font_size_normal"] = 14, ["bar_texture"] = "Plain", ["level_text"] = true, ["target_glow"] = false, ["frame_width"] = 155, ["font_face"] = "Roboto Condensed", ["bot_vertical_offset"] = 0, ["name_vertical_offset"] = 3.5, ["target_arrows"] = true, ["fade_avoid_execute_hostile"] = true, ["fade_neutral_enemy"] = true, }, ["default"] = { }, }, }
local awful = require("awful") local gears = require("gears") local wibox = require("wibox") local beautiful = require("beautiful") local xresources = require("beautiful.xresources") local dpi = xresources.apply_dpi local bling = require("module.bling") local helpers = require("helpers") -- Helpers ------------- local function create_title_button(c, color_focus, color_unfocus, shp) local tb = wibox.widget { forced_width = dpi(20), forced_height = dpi(20), bg = color_focus .. 90, shape = shp, border_color = beautiful.border_color, widget = wibox.container.background } local function update() if client.focus == c then tb.bg = color_focus else tb.bg = color_unfocus end end update() c:connect_signal("focus", update) c:connect_signal("unfocus", update) tb:connect_signal("mouse::enter", function() tb.bg = color_focus .. 55 end) tb:connect_signal("mouse::leave", function() tb.bg = color_focus end) tb.visible = true return tb end local wrap_widget = function(w) return { w, top = dpi(20), widget = wibox.container.margin } end -- Add a titlebar if titlebars_enabled is set to true in the rules. client.connect_signal("request::titlebars", function(c) -- Buttons for the titlebar ------------------------------ local buttons = gears.table.join(awful.button({}, 1, function() c:emit_signal("request::activate", "titlebar", {raise = true}) if c.maximized == true then c.maximized = false end awful.mouse.client.move(c) end), awful.button({}, 3, function() c:emit_signal("request::activate", "titlebar", {raise = true}) awful.mouse.client.resize(c) end)) local borderbuttons = gears.table.join( awful.button({}, 3, function() c:emit_signal("request::activate", "titlebar", {raise = true}) awful.mouse.client.resize(c) end), awful.button({}, 1, function() c:emit_signal("request::activate", "titlebar", {raise = true}) awful.mouse.client.resize(c) end)) -- Titlebars shapes ---------------------- local ci = function(width, height) return function(cr) gears.shape.circle(cr, width, height) end end -- Create titlebars buttons ------------------------------ local close = create_title_button(c, beautiful.xcolor1, beautiful.titlebar_unfocused, ci(dpi(11), dpi(11))) close:connect_signal("button::press", function() c:kill() end) local float = create_title_button(c, beautiful.xcolor4, beautiful.titlebar_unfocused, ci(dpi(11), dpi(11))) float:connect_signal("button::press", function() awful.client.floating.toggle(c) end) local max = create_title_button(c, beautiful.xcolor5, beautiful.titlebar_unfocused, ci(dpi(11), dpi(11))) max:connect_signal("button::press", function() c.maximized = not c.maximized end) -- Titlebars setup -------------------- awful.titlebar(c, { position = "top", size = beautiful.titlebar_size }):setup{ { -- left wrap_widget({ close, left = dpi(25), widget = wibox.container.margin }), wrap_widget(float), wrap_widget(max), buttons = buttons, layout = wibox.layout.fixed.horizontal, }, { -- middle awful.titlebar.widget.titlewidget(c), layout = wibox.layout.fixed.horizontal }, { -- right layout = wibox.layout.fixed.horizontal }, bg = beautiful.darker_bg, shape = helpers.prrect(beautiful.border_radius, true, true, false, false), widget = wibox.container.background } awful.titlebar(c, { position = "bottom", size = dpi(24) }):setup{ bg = beautiful.darker_bg, shape = helpers.prrect(beautiful.border_radius, false, false, true, true), widget = wibox.container.background } end)
-- RAM and swap usage widget type for FreeBSD -- Copyright (C) 2017-2019 mutlusun <mutlusun@github.com> -- Copyright (C) 2018 Andreas Geisenhainer <psycorama@datenhalde.de> -- Copyright (C) 2019 Nguyễn Gia Phong <vn.mcsinyx@gmail.com> -- -- This file is part of Vicious. -- -- Vicious 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. -- -- Vicious 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 Vicious. If not, see <https://www.gnu.org/licenses/>. -- {{{ Grab environment local tonumber = tonumber local math = { floor = math.floor } local string = { match = string.match, gmatch = string.gmatch, find = string.find } local helpers = require("vicious.helpers") local spawn = require("vicious.spawn") -- }}} -- Mem: provides RAM and Swap usage statistics -- vicious.widgets.mem_freebsd local mem_freebsd = {} -- {{{ Memory widget type function mem_freebsd.async(format, warg, callback) helpers.sysctl_async({ "hw.pagesize", "vm.stats.vm", "vm.swap_total", "vm.swap_enabled" }, function(ret) local pgsz = tonumber(ret["hw.pagesize"]) local _mem = { buf = {}, total = nil } -- Get memory space in bytes _mem.total = tonumber(ret["vm.stats.vm.v_page_count"]) * pgsz _mem.buf.free = tonumber(ret["vm.stats.vm.v_free_count"]) * pgsz _mem.buf.laundry = tonumber(ret["vm.stats.vm.v_laundry_count"]) * pgsz _mem.buf.cache = tonumber(ret["vm.stats.vm.v_cache_count"]) * pgsz _mem.buf.wired = tonumber(ret["vm.stats.vm.v_wire_count"]) * pgsz -- Rework into megabytes _mem.total = math.floor(_mem.total/1048576) _mem.buf.free = math.floor(_mem.buf.free/1048576) _mem.buf.laundry = math.floor(_mem.buf.laundry/1048576) _mem.buf.cache = math.floor(_mem.buf.cache/1048576) _mem.buf.wired = math.floor(_mem.buf.wired/1048576) -- Calculate memory percentage _mem.free = _mem.buf.free + _mem.buf.cache -- used memory basically consists of active+inactive+wired _mem.inuse = _mem.total - _mem.free _mem.notfreeable = _mem.inuse - _mem.buf.laundry _mem.wire = _mem.buf.wired _mem.usep = math.floor(_mem.inuse / _mem.total * 100) _mem.wirep = math.floor(_mem.wire / _mem.total * 100) _mem.notfreeablep = math.floor(_mem.notfreeable / _mem.total * 100) -- Get swap states local vm_swap_total = tonumber(ret["vm.swap_total"]) local vm_swap_enabled = tonumber(ret["vm.swap_enabled"]) local _swp = { buf = {}, total = nil } if vm_swap_enabled == 1 and vm_swap_total > 0 then -- Initialise variables _swp.usep = 0 _swp.inuse = 0 _swp.total = 0 _swp.buf.free = 0 -- Read output of swapinfo in Mbytes (from async function call) -- Read content and sum up spawn.with_line_callback("swapinfo -m", { stdout = function(line) if not string.find(line, "Device") then local ltotal, lused, lfree = string.match( line, "%s+([%d]+)%s+([%d]+)%s+([%d]+)") -- Add swap space in Mbytes _swp.total = _swp.total + tonumber(ltotal) _swp.inuse = _swp.inuse + tonumber(lused) _swp.buf.free = _swp.buf.free + tonumber(lfree) end end, output_done = function() print(_swp.inuse, _swp.total) _swp.usep = math.floor(_swp.inuse / _swp.total * 100) callback({ _mem.usep, _mem.inuse, _mem.total, _mem.free, _swp.usep, _swp.inuse, _swp.total, _swp.buf.free, _mem.wirep, _mem.wire, _mem.notfreeablep, _mem.notfreeable }) end }) else _swp.usep = -1 _swp.inuse = -1 _swp.total = -1 _swp.buf.free = -1 callback({ _mem.usep, _mem.inuse, _mem.total, _mem.free, _swp.usep, _swp.inuse, _swp.total, _swp.buf.free, _mem.wirep, _mem.wire, _mem.notfreeablep, _mem.notfreeable }) end end) end -- }}} return helpers.setasyncall(mem_freebsd)
local plyMeta = FindMetaTable("Player") DarkRP.addPhrase("en", "zombie_approaching", "WARNING: Zombies are approaching!") DarkRP.addPhrase("en", "zombie_leaving", "Zombies are leaving.") DarkRP.addPhrase("en", "zombie_spawn_not_exist", "Zombie Spawn %s does not exist.") DarkRP.addPhrase("en", "zombie_spawn_removed", "You have removed this zombie spawn.") DarkRP.addPhrase("en", "zombie_spawn_added", "You have added a zombie spawn.") DarkRP.addPhrase("en", "zombie_maxset", "Maximum amount of zombies is now set to %s") DarkRP.addPhrase("en", "zombie_enabled", "Zombies are now enabled.") DarkRP.addPhrase("en", "zombie_disabled", "Zombies are now disabled.") DarkRP.addPhrase("en", "zombie_spawn", "Zombie Spawn") DarkRP.addPhrase("en", "zombie_toggled", "Zombies toggled.") DarkRP.registerDarkRPVar("zombieToggle", net.WriteBit, fn.Compose{tobool, net.ReadBit}) DarkRP.registerDarkRPVar("zPoints", function(zSpawns) net.WriteUInt(#zSpawns, 16) for _, pos in pairs(zSpawns) do net.WriteVector(pos) end end, function() local res = {} local count = net.ReadUInt(16) for i = 1, count, 1 do table.insert(res, net.ReadVector()) end return res end) local hasCommandsPriv = fn.Curry(fn.Flip(plyMeta.hasDarkRPPrivilege), 2)("rp_commands") DarkRP.declareChatCommand{ command = "enablestorm", description = "Enable meteor storms.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "disablestorm", description = "Disable meteor storms.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "removezombie", description = "Remove a zombie spawn pos by id (get id with /showzombie).", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "addzombie", description = "Add a zombie spawn pos.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "showzombie", description = "Show zombie spawn positions.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "zombiemax", description = "Set the maximum amount of zombies that can be in a level.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "maxzombie", description = "Set the maximum amount of zombies that can be in a level.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "maxzombies", description = "Set the maximum amount of zombies that can be in a level.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "enablezombie", description = "Enable zombie mod.", delay = 1.5, condition = hasCommandsPriv } DarkRP.declareChatCommand{ command = "disablezombie", description = "Disable zombie mod.", delay = 1.5, condition = hasCommandsPriv }
AddCSLuaFile("cl_init.lua") AddCSLuaFile("shared.lua") include("shared.lua") function ENT:Initialize() self:SetModel("models/star wars the force unleashed/thermal_detonator.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetSolid(SOLID_VPHYSICS) Glow = ents.Create("env_sprite") Glow:SetKeyValue("model","orangecore2.vmt") Glow:SetKeyValue("rendercolor","255 0 0") Glow:SetKeyValue("scale","0.16") Glow:SetPos(self.Entity:GetPos()) Glow:SetParent(self.Entity) Glow:Spawn() Glow:Activate() self:SetUseType(SIMPLE_USE) local phys = self:GetPhysicsObject() phys:Wake() util.SpriteTrail(self, 0, Color(255 * 2,0 * 2,0 * 2), false, 5, .5, .1, 1/(15+1)*0.5, "trails/tube.vmt") self.countsounds = 100 timer.Simple(1,function() if not IsValid(self) then return end local entidex = self:EntIndex() timer.Create("babysounds"..entidex,0.2,0,function() if not IsValid(self) then timer.Destroy("babysounds"..entidex) return end if self.countsounds == 200 then local explode = ents.Create("env_explosion") explode:SetPos(self:GetPos()) explode:SetOwner(self:GetOwner()) explode:Spawn() explode:SetKeyValue("iMagnitude","200") explode:Fire("Explode",0,0) explode:EmitSound("weapons/explosives_cannons_superlazers/sw_detonator_explosion.ogg",90,60) timer.Destroy("babysounds"..self:EntIndex()) self:Remove() else self:EmitSound("weapons/explosives_cannons_superlazers/wpn_thermdet_chargeup_01.ogg",80,self.countsounds) self.countsounds = self.countsounds + 10 end end) end) end function ENT:Use() end function ENT:OnTakeDamage() timer.Create("explodeonimpact"..self:EntIndex(),0.08,1,function() if not IsValid(self) then return end local explode = ents.Create("env_explosion") explode:SetPos(self:GetPos()) explode:SetOwner(self:GetOwner()) explode:Spawn() explode:SetKeyValue("iMagnitude","200") explode:Fire("Explode",0,0) explode:EmitSound("weapons/explosives_cannons_superlazers/sw_detonator_explosion.ogg",90,60) timer.Destroy("babysounds"..self:EntIndex()) self:Remove() end) end
os = require('os') vshard = require('vshard') local IDX_KEY = 1 local IDX_VALUE = 2 local cfg = { memtx_memory = 100 * 1024 * 1024, bucket_count = 120, rebalancer_disbalance_threshold = 10, rebalancer_max_receiving = 1000, sharding = { ['7432f072-c00b-4498-b1a6-6d9547a8a150'] = { -- replicaset #1 replicas = { ['a94e7310-13f0-4690-b136-169599e87ba0'] = { uri = 'qumomf:qumomf@qumomf_1_m.ddk:3301', name = 'qumomf_1_m', master = true }, ['bd1095d1-1e73-4ceb-8e2f-6ebdc7838cb1'] = { uri = 'qumomf:qumomf@qumomf_1_s.ddk:3301', name = 'qumomf_1_s' } }, }, -- replicaset #1 ['5065fb5f-5f40-498e-af79-43887ba3d1ec'] = { -- replicaset #2 replicas = { ['a3ef657e-eb9a-4730-b420-7ea78d52797d'] = { uri = 'qumomf:qumomf@qumomf_2_m.ddk:3301', name = 'qumomf_2_m', master = true }, ['bd64dd00-161e-4c99-8b3c-d3c4635e18d2'] = { uri = 'qumomf:qumomf@qumomf_2_s_1.ddk:3301', name = 'qumomf_2_s_1' }, ['cc4cfb9c-11d8-4810-84d2-66cfbebb0f6e'] = { uri = 'qumomf:qumomf@qumomf_2_s_2.ddk:3301', name = 'qumomf_2_s_2' } }, }, -- replicaset #2 }, -- sharding } local UUID = os.getenv("STORAGE_UUID") cfg.listen = 3301 vshard.storage.cfg(cfg, UUID) box.once("init", function() if UUID == 'a94e7310-13f0-4690-b136-169599e87ba0' then vshard.storage.bucket_force_create(0, 60, {}) end if UUID == 'a3ef657e-eb9a-4730-b420-7ea78d52797d' then vshard.storage.bucket_force_create(61, 60, {}) end box.schema.user.create('qumomf', { password = 'qumomf', if_not_exists = true }) box.schema.user.grant('qumomf', 'read,write,create,execute', 'universe') local space = box.schema.create_space("qumomf", { if_not_exists = true, }) space:create_index('key', { type = 'TREE', if_not_exists = true, parts = { IDX_KEY, 'string', }, unique = true, }) end) dofile('/etc/tarantool/instances.enabled/qumomf/storage/storage.lua')
local objects = { --Maxime createObject ( 14393, 1154.90002, -801.40002, 2100.2981, 0, 0, 270 , 77), createObject ( 1569, 1150.59998, -807.32001, 2098.09009, 0, 0, 270 , 77), createObject ( 14391, 1142.59998, -808.60699, 2099 , 0, 0, 0, 77), createObject ( 14392, 1141.80005, -807.70001, 2099.3999 , 0, 0, 0, 77), createObject ( 14393, 1141.89941, -807.69922, 2100.30005 , 0, 0, 0, 77), createObject ( 1714, 1145.09998, -809.59998, 2098.1001, 0, 0, 270 , 77), createObject ( 1714, 1145.09998, -808.5, 2098.1001, 0, 0, 270 , 77), createObject ( 1714, 1145.09998, -807.40002, 2098.1001, 0, 0, 270 , 77), createObject ( 1215, 1150.90002, -808.09998, 2100.8999, 0, 90, 180 , 77), } local col = createColSphere(1150.19140625, -808.0947265625, 2099.0656738281 ,20) local function watchChanges( ) if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then for key, value in pairs( objects ) do setElementDimension( value, getElementDimension( getLocalPlayer( ) ) ) end elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end end end addEventHandler( "onClientColShapeHit", col, function( element ) if element == getLocalPlayer( ) then addEventHandler( "onClientRender", root, watchChanges ) end end ) addEventHandler( "onClientColShapeLeave", col, function( element ) if element == getLocalPlayer( ) then removeEventHandler( "onClientRender", root, watchChanges ) end end ) -- Put them standby for now. for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end for index, object in ipairs ( objects ) do setElementDoubleSided ( object, true ) --setElementCollisionsEnabled ( object, true ) end
local http = require "resty.http" local server = require "spec.support.server" describe("option generate_certs", function() before_each(server.stop) after_each(server.stop) it("generate_certs disables generation of new SSL certs", function() server.start({ auto_ssl_http_config = [[ server { listen 9444 ssl; ssl_certificate_by_lua_block { auto_ssl:ssl_certificate({ generate_certs = false, }) } location /foo { echo -n "generate_certs = false server"; } } ]], }) local httpc = http.new() -- Make an initial request against the "generate_certs = false" server to -- ensure we don't get back a valid SSL cert. do local _, connect_err = httpc:connect("127.0.0.1", 9444) assert.equal(nil, connect_err) local _, ssl_err = httpc:ssl_handshake(nil, server.ngrok_hostname, true) assert.equal("18: self signed certificate", ssl_err) end -- Reconnect and try again with ssl verification disabled. do local _, connect_err = httpc:connect("127.0.0.1", 9444) assert.equal(nil, connect_err) local _, ssl_err = httpc:ssl_handshake(nil, server.ngrok_hostname, false) assert.equal(nil, ssl_err) local res, request_err = httpc:request({ path = "/foo" }) assert.equal(nil, request_err) assert.equal(200, res.status) local body, body_err = res:read_body() assert.equal(nil, body_err) assert.equal("generate_certs = false server", body) end -- Make a request to a different server block that uses the default -- generate_certs value (true) and ensure that this does still generate -- the cert. do local _, connect_err = httpc:connect("127.0.0.1", 9443) assert.equal(nil, connect_err) local _, ssl_err = httpc:ssl_handshake(nil, server.ngrok_hostname, true) assert.equal(nil, ssl_err) local res, request_err = httpc:request({ path = "/foo" }) assert.equal(nil, request_err) assert.equal(200, res.status) local body, body_err = res:read_body() assert.equal(nil, body_err) assert.equal("foo", body) end -- Make a 3rd request back to the "generate_certs = false" server and -- ensure that it now returns a valid certificate (since it should still -- return already existing certs). do local _, connect_err = httpc:connect("127.0.0.1", 9444) assert.equal(nil, connect_err) local _, ssl_err = httpc:ssl_handshake(nil, server.ngrok_hostname, true) assert.equal(nil, ssl_err) local res, request_err = httpc:request({ path = "/foo" }) assert.equal(nil, request_err) assert.equal(200, res.status) local body, body_err = res:read_body() assert.equal(nil, body_err) assert.equal("generate_certs = false server", body) end local error_log = server.read_error_log() assert.matches("using fallback - did not issue certificate, because the generate_certs setting is false", error_log, nil, true) assert.matches("auto-ssl: issuing new certificate for", error_log, nil, true) assert.Not.matches("[warn]", error_log, nil, true) assert.Not.matches("[alert]", error_log, nil, true) assert.Not.matches("[emerg]", error_log, nil, true) end) end)
local EventManager = require 'utils.EventManager'; local NetworkService = require "utils.NetworkService"; local rewardCfg = LoadDatabaseWithKey("rank_rewards", "rankid", "type"); local function GetActivityReward(rankid) return rewardCfg[rankid]; end local function GetNowPeriod() local cfg = GetActivityReward(2) if not cfg then return nil end local begin_time = cfg.begin_time local end_time = cfg.end_time local period = cfg.period local duration = cfg.duration local ret = math.ceil((module.Time.now() + 1 - begin_time) / period); return ret end local guild_prop_data = nil --获取军团道具 local function getGuildProp(isreset) if guild_prop_data and not isreset then return guild_prop_data; end -- ERROR_LOG("获取军团道具"); NetworkService.Send(3455,{nil}) end local function resetGuildProp() getGuildProp(true) end local prop_data = { [79047] = 0, [79048] = 0, [79049] = 0, } EventManager.getInstance():addListener("server_respond_3456", function(event, cmd, data) -- ERROR_LOG("server_respond_3456",sprinttb(data)) local sn = data[1] local err = data[2] -- prop_data if err == 0 then for k,v in pairs(data[3] or {}) do if prop_data[v[1]] then prop_data[v[1]] = v[2]; end end guild_prop_data = prop_data; DispatchEvent("GET_GUILD_PROP_SUC"); end end) local function GetProp() return prop_data end --个人道具兑换军团道具 local function guildSubProp(id,value) NetworkService.Send(3453,{nil,id,value}); end local function GetRank() local current = GetNowPeriod(); NetworkService.Send(17103,{nil,2,current,10}) end EventManager.getInstance():addListener("server_respond_3454", function(event, cmd, data) -- ERROR_LOG("server_respond_3454",sprinttb(data)) local sn = data[1] local err = data[2] end) --道具发生改变 EventManager.getInstance():addListener("server_notify_1143",function ( event,cmd,data) -- ERROR_LOG("server_notify_1143",sprinttb(data)); if not data[4] then guild_prop_data[data[1]] = data[2] -- ERROR_LOG("军团道具数量更新",guild_prop_data); DispatchEvent("GUILD_ITEM_CHANGE_INFO",data[1]); end end) local function GetRankReward(current,email) current = current or GetNowPeriod() NetworkService.Send(17105,{nil,2,current,email and email or 0}) end return { GetGuildProp = getGuildProp, SubmitGuild = guildSubProp, GetProp = GetProp, GetRankReward = GetRankReward, ResetGuildProp = resetGuildProp }
-- Все возможные точки спавна лута local vehicleSpawnpoints = {} local EDITOR_MODE = false local vehicleModels = { [400] = { 400, 500, 579, 489 }, [426] = { 426, 445, 507, 585, 466, 492, 546, 551, 516, 467, 547, 405, 580, 550, 566 }, [461] = { 461, 521, 463, 468 }, [521] = { 521, 461, 463, 468 } } function loadFile(path, count) if not fileExists(path) then return false end local file = fileOpen(path) if not file then return false end if not count then count = fileGetSize(file) end local data = fileRead(file, count) fileClose(file) return data end function saveFile(path, data) if not path then return false end if fileExists(path) then fileDelete(path) end local file = fileCreate(path) fileWrite(file, data) fileClose(file) return true end function createVehicleSpawnpoints(model, position, rotation) if not position then return end table.insert(vehicleSpawnpoints, { x = position.x, y = position.y, z = position.z, rx = rotation.x, ry = rotation.y, rz = rotation.z, model = model }) saveFile("data/spawnpoints.json", toJSON(vehicleSpawnpoints)) end if EDITOR_MODE then addCommandHandler("addcar", function (player) if not player.vehicle then return end createVehicleSpawnpoints(player.vehicle.model, player.vehicle.position, player.vehicle.rotation) local vehicle = createVehicle(player.vehicle.model, player.vehicle.position, player.vehicle.rotation) vehicle.frozen = true vehicle:setCollisionsEnabled(false) createBlip(player.vehicle.position) outputChatBox("Car added") end) end local function randomChance(chance) return math.random() <= chance end -- Раскидывает лут в dimension function generateVehicles(dimension) local spawnedVehicles = {} for i, spawnpoint in ipairs(vehicleSpawnpoints) do if randomChance(0.4) then local model = spawnpoint.model if vehicleModels[model] then model = vehicleModels[model][math.random(1, #vehicleModels[model])] end local vehicle = createVehicle(model, spawnpoint.x, spawnpoint.y, spawnpoint.z, spawnpoint.rx, spawnpoint.ry, spawnpoint.rz) vehicle.dimension = dimension exports.pb_fuel:setVehicleRandomFuel(vehicle) table.insert(spawnedVehicles, vehicle) end end return spawnedVehicles end addEventHandler("onResourceStart", resourceRoot, function () vehicleSpawnpoints = fromJSON(loadFile("data/spawnpoints.json") or "[[]]") or {} if EDITOR_MODE then for i, s in ipairs(vehicleSpawnpoints) do local vehicle = createVehicle(s.model, s.x, s.y, s.z, s.rx, s.ry, s.rz) vehicle.frozen = true vehicle:setCollisionsEnabled(false) createBlip(s.x, s.y, s.z) end end end)
-- Adopted from shell/sysinfo.lua -- Todo: -- With NodeMCU "built 2017-12-25 17:45 Lua 5.1.4 on SDK 2.1.0(116b762)" it has a memory leak (seems unrelated to httpd/simple.lua) return function(conn,req,gv) dofile("httpd/header.lua")(conn,200,"text/plain") local kv = function(k,v,u) local s = k..': '.. (u and v..' '..u or v); --print(s) conn:send(s.."\n") end kv('Architecture',arch) if arch=='esp8266' then kv('Chip ID',node.chipid().." / "..string.format("0x%x",node.chipid())) kv('Flash ID',node.flashid().." / "..string.format("0x%x",node.flashid())) else kv('Chip ID',node.chipid()) --kv('Flash ID',node.flashid()) -- not yet end kv('Heap',node.heap(),'bytes') if arch=='esp8266' then local maver, miver, devv, cid, fid, fsize, fmode, fspeed = node.info() kv('Info',"V"..maver.."."..miver.."."..devv..", FlashMode "..fmode..", FlashSpeed "..fspeed) end local t = tmr.time(); kv("Uptime",string.format("%dd %dh %dm %ds",int(t/24/3600),int(t/3600)%24,int(t/60)%60,t%60)) if adc then -- make it conditional in case it doesn't exist adc.force_init_mode(adc.INIT_VDD33) kv('Vdd',adc.readvdd33(),'mV') end local address, size = file.fscfg() kv('File System Address',address.." / "..string.format("0x%x",address)) kv('File System Size',size,'bytes') if rtctime then local tm = rtctime.epoch2cal(rtctime.get()) kv('RTC Time',string.format("%04d/%02d/%02d %02d:%02d:%02d %s",tm["year"],tm["mon"],tm["day"],tm["hour"],tm["min"],tm["sec"],'UTC')) end local remain, used, total = file.fsinfo() kv('File System Usage',used..' / '..total,'bytes') if arch=='esp8266' then kv('Wifi STA MAC Address',wifi.sta.getmac()) kv('Wifi AP MAC Address',wifi.ap.getmac()) kv('WiFi Channel',wifi.getchannel()) local wifimode = wifi.getmode() if wifimode == wifi.STATION then kv('WiFi Mode','STATION') elseif wifimode == wifi.SOFTAP then kv('WiFi Mode','SOFTAP') elseif wifimode == wifi.STATIONAP then kv('WiFi Mode','STATIONAP') elseif wifimode == wifi.NULLMODE then kv('WiFi Mode','NULLMODE') end if (wifimode == wifi.STATIONAP) or (wifimode == wifi.SOFTAP) then local ip, netmask, gateway = wifi.ap.getip() kv('AP IP',ip) kv('AP netmask',netmask) kv('AP gateway',gateway) kv('AP client list','') local clients = wifi.ap.getclient() for mac, ip in pairs(clients) do kv(''..mac..'',ip) end end local wifiphymode = wifi.getphymode() if wifiphymode == wifi.PHYMODE_B then kv('WiFi Physical Mode','B') elseif wifiphymode == wifi.PHYMODE_G then kv('WiFi Physical Mode','G') elseif wifiphymode == wifi.PHYMODE_N then kv('WiFi Physical Mode','N') end local s = wifi.sta.status() if s == wifi.STA_IDLE then kv('wifi.sta.status','STA_IDLE') elseif s == wifi.STA_CONNECTING then kv('wifi.sta.status','STA_CONNECTING') elseif s == wifi.STA_WRONGPWD then kv('wifi.sta.status','STA_WRONGPWD') elseif s == wifi.STA_APNOTFOUND then kv('wifi.sta.status','STA_APNOTFOUND') elseif s == wifi.STA_FAIL then kv('wifi.sta.status','STA_FAIL') elseif s == wifi.STA_GOTIP then kv('wifi.sta.status','STA_GOTIP') kv('Hostname',wifi.sta.gethostname()) local ip, netmask, gateway = wifi.sta.getip() kv('STA IP',ip) kv('STA netmask',netmask) kv('STA gateway',gateway) local ssid, password, bssid_set, bssid = wifi.sta.getconfig() kv('SSID',ssid) -- kv('password',password) -- not sure if it should be shown. kv('BSSID set',bssid_set) kv('BSSID',bssid) kv('STA Broadcast IP',wifi.sta.getbroadcast()) kv('RSSI',wifi.sta.getrssi(),'dB') end end end
--- Guild member class -- @classmod discord.guildMember local discord = ... --Passed as an argument. local class = discord.class --Middleclass. local guildMember = class("discord.structures.GuildMember") --A function for verifying the arguments types of a method local function Verify(value, name, ...) local vt, types = type(value), {...} for _, t in pairs(types) do if vt == t or (t=="nil" and not value) then return end end --Verified successfully types = table.concat(types, "/") local emsg = string.format("%s should be %s, provided: %s", name, types, vt) error(emsg, 3) end --REST Request with proper error handling (uses error level 3) local function Request(endpoint, data, method, headers, useMultipart) local response_body, response_headers, status_code, status_line, failure_code, failure_line = discord.rest:request(endpoint, data, method, headers, useMultipart) if not response_body then error(response_headers, 3) else return response_body, response_headers, status_code, status_line end end --New guild member object function guildMember:initialize(data, userID) Verify(data, "data", "table", "string") if type(data) == "string" then Verify(userID, "userID", "string") local endpoint = string.format("/guilds/%s/members/%s", data, userID) data = Request(endpoint) end --== Basic Fields ==-- self.roles = {} --Array of roles snowflakes (array of snowflakes) for id, snowflake in pairs(data.roles) do self.roles[id] = discord.snowflake(snowflake) end self.joinedAt = data.joined_at --When the user joined the guild (number) self.deaf = data.deaf --Whether the user is deafened in voice channels (boolean) self.mute = data.mute --Whether the user is muted in voice channels (boolean) --== Optional Fields ==-- --The user this guild member represents (user) if data.user then self.user = discord.user(data.user) end self.nick = data.nick --This users guild nickname (if one is set) self.premiumSince = data.premium_since --When the user used their Nitro boost on the server (number) end --== Methods ==-- --Returns the user's nickname if set on this guild function guildMember:getNick() return self.nick end --Returns the timestamp which the user has been booting the server since (if he's boosting) function guildMember:getPremiumSince() return self.premiumSince end --Returns a list of roles snowflakes the member has function guildMember:getRoles() local roles = {} for k,v in pairs(self.roles) do roles[k] = v end return roles end --Returns the user object if received function guildMember:getUser() return self.user end --Returns a timestamp of when the user joined the guild function guildMember:getJoinedAt() return self.joinedAt end --Tells if the user is deafened in voice channels function guildMember:isDeafened() return self.deaf end --Tells if the user is muted in voice channels function guildMember:isMuted() return self.mute end return guildMember
Talk(11, "祝少侠此后平步青云.", "talkname11", 0); do return end;
PLUGIN.Title = "CustomChatCommands" PLUGIN.Author = "#Domestos" PLUGIN.Version = "1.1" PLUGIN.Description = "Set completely custom chat commands" PLUGIN.ResourceId = "559" PLUGIN.ConfigFile = "customchatcommands" -- Debug mode local debug = false -- ---------------- function PLUGIN:Init() self:LoadConfig() for key, value in pairs(self.Config.ChatCommands) do self:AddChatCommand(key, self.cmdChatCmd) end print(self.Title .. " v" .. self.Version .. " loaded") end function PLUGIN:LoadConfig() local b, res = config.Read(self.ConfigFile) self.Config = res or {} -- Config settings self.Config.Settings = self.Config.Settings or {} self.Config.Settings.ChatName = self.Config.Settings.ChatName or "SERVER" self.Config.ChatCommands = self.Config.ChatCommands or { ["command1"] = { ["text"] = {"This is an example text"}, ["helptext"] = "This is the helptext for this command", ["admin"] = false }, ["command2"] = { ["text"] = {"This is an example text for admins only", "You can also use multiline messages"}, ["helptext"] = "This is the helptext for this command, also admin only", ["admin"] = true } } -- Save config file config.Save(self.ConfigFile, { indent = true, keyorder = { "Settings", "ChatName", "ChatCommands" } }) end function PLUGIN:PostInit() self:LoadFlags() end -- Flag Handling function PLUGIN:LoadFlags() self.flagsPlugin = plugins.Find("flags") self.oxminPlugin = plugins.Find("oxmin") if(self.oxminPlugin) then self.FLAG_CCC = oxmin.AddFlag("customchatcommands") end end function PLUGIN:HasPermission(netuser) if(netuser:CanAdmin()) then return true elseif((self.oxminPlugin ~= nil) and (self.oxminPlugin:HasFlag(netuser, self.FLAG_CCC))) then return true elseif((self.flagsPlugin ~= nil) and (self.flagsPlugin:HasFlag(netuser, "customchatcommands"))) then return true else return false end end function PLUGIN:cmdChatCmd(netuser, cmd) for key, value in pairs(self.Config.ChatCommands) do if(cmd == key) then -- Check if command is admin only if(self.Config.ChatCommands[key].admin == true) then -- Check if user has permission to use command if(self:HasPermission(netuser) == true) then -- Output the text for k, v in pairs(self.Config.ChatCommands[key].text) do rust.SendChatToUser(netuser, self.Config.Settings.ChatName, self.Config.ChatCommands[key].text[k]) end end else -- Command can be used by everyone for k, v in pairs(self.Config.ChatCommands[key].text) do rust.SendChatToUser(netuser, self.Config.Settings.ChatName, self.Config.ChatCommands[key].text[k]) end end end end end function PLUGIN:SendHelpText(netuser) for key, value in pairs(self.Config.ChatCommands) do if(self.Config.ChatCommands[key].admin == true) then if(self:HasPermission(netuser) == true) then rust.SendChatToUser(netuser, self.Config.ChatCommands[key].helptext) end else rust.SendChatToUser(netuser, self.Config.ChatCommands[key].helptext) end end end
-- -- AMQP/RabbitMQ Bindings for LuaJIT -- Requires at least librrabbitmq.so.1.0 (https://github.com/alanxz/rabbitmq-c) -- -- The contents of this file has been -- derived (by hand) from rabbitmq-c's amqp.h and amqp-framing.h -- local ffi = require("ffi") ffi.cdef[[ static const int AMQP_PROTOCOL_VERSION_MAJOR = 0; static const int AMQP_PROTOCOL_VERSION_MINOR = 9; static const int AMQP_PROTOCOL_VERSION_REVISION = 1; static const int AMQP_PROTOCOL_PORT = 5672; static const int AMQP_FRAME_METHOD = 1; static const int AMQP_FRAME_HEADER = 2; static const int AMQP_FRAME_BODY = 3; static const int AMQP_FRAME_HEARTBEAT = 8; static const int AMQP_FRAME_MIN_SIZE = 4096; static const int AMQP_FRAME_END = 206; static const int AMQP_REPLY_SUCCESS = 200; static const int AMQP_CONTENT_TOO_LARGE = 311; static const int AMQP_NO_ROUTE = 312; static const int AMQP_NO_CONSUMERS = 313; static const int AMQP_ACCESS_REFUSED = 403; static const int AMQP_NOT_FOUND = 404; static const int AMQP_RESOURCE_LOCKED = 405; static const int AMQP_PRECONDITION_FAILED = 406; static const int AMQP_CONNECTION_FORCED = 320; static const int AMQP_INVALID_PATH = 402; static const int AMQP_FRAME_ERROR = 501; static const int AMQP_SYNTAX_ERROR = 502; static const int AMQP_COMMAND_INVALID = 503; static const int AMQP_CHANNEL_ERROR = 504; static const int AMQP_UNEXPECTED_FRAME = 505; static const int AMQP_RESOURCE_ERROR = 506; static const int AMQP_NOT_ALLOWED = 530; static const int AMQP_NOT_IMPLEMENTED = 540; static const int AMQP_INTERNAL_ERROR = 541; static const int AMQP_CONNECTION_START_METHOD = (0x000A000A); static const int AMQP_CONNECTION_START_OK_METHOD = (0x000A000B); static const int AMQP_CONNECTION_SECURE_METHOD = (0x000A0014); static const int AMQP_CONNECTION_SECURE_OK_METHOD = (0x000A0015); static const int AMQP_CONNECTION_TUNE_METHOD = (0x000A001E); static const int AMQP_CONNECTION_TUNE_OK_METHOD = (0x000A001F); static const int AMQP_CONNECTION_OPEN_METHOD = (0x000A0028); static const int AMQP_CONNECTION_OPEN_OK_METHOD = (0x000A0029); static const int AMQP_CONNECTION_CLOSE_METHOD = (0x000A0032); static const int AMQP_CONNECTION_CLOSE_OK_METHOD = (0x000A0033); static const int AMQP_CHANNEL_OPEN_METHOD = (0x0014000A); static const int AMQP_CHANNEL_OPEN_OK_METHOD = (0x0014000B); static const int AMQP_CHANNEL_FLOW_METHOD = (0x00140014); static const int AMQP_CHANNEL_FLOW_OK_METHOD = (0x00140015); static const int AMQP_CHANNEL_CLOSE_METHOD = (0x00140028); static const int AMQP_CHANNEL_CLOSE_OK_METHOD = (0x00140029); static const int AMQP_ACCESS_REQUEST_METHOD = (0x001E000A); static const int AMQP_ACCESS_REQUEST_OK_METHOD = (0x001E000B); static const int AMQP_EXCHANGE_DECLARE_METHOD = (0x0028000A); static const int AMQP_EXCHANGE_DECLARE_OK_METHOD = (0x0028000B); static const int AMQP_EXCHANGE_DELETE_METHOD = (0x00280014); static const int AMQP_EXCHANGE_DELETE_OK_METHOD = (0x00280015); static const int AMQP_EXCHANGE_BIND_METHOD = (0x0028001E); static const int AMQP_EXCHANGE_BIND_OK_METHOD = (0x0028001F); static const int AMQP_EXCHANGE_UNBIND_METHOD = (0x00280028); static const int AMQP_EXCHANGE_UNBIND_OK_METHOD = (0x00280033); static const int AMQP_QUEUE_DECLARE_METHOD = (0x0032000A); static const int AMQP_QUEUE_DECLARE_OK_METHOD = (0x0032000B); static const int AMQP_QUEUE_BIND_METHOD = (0x00320014); static const int AMQP_QUEUE_BIND_OK_METHOD = (0x00320015); static const int AMQP_QUEUE_PURGE_METHOD = (0x0032001E); static const int AMQP_QUEUE_PURGE_OK_METHOD = (0x0032001F); static const int AMQP_QUEUE_DELETE_METHOD = (0x00320028); static const int AMQP_QUEUE_DELETE_OK_METHOD = (0x00320029); static const int AMQP_QUEUE_UNBIND_METHOD = (0x00320032); static const int AMQP_QUEUE_UNBIND_OK_METHOD = (0x00320033); static const int AMQP_BASIC_QOS_METHOD = (0x003C000A); static const int AMQP_BASIC_QOS_OK_METHOD = (0x003C000B); static const int AMQP_BASIC_CONSUME_METHOD = (0x003C0014); static const int AMQP_BASIC_CONSUME_OK_METHOD = (0x003C0015); static const int AMQP_BASIC_CANCEL_METHOD = (0x003C001E); static const int AMQP_BASIC_CANCEL_OK_METHOD = (0x003C001F); static const int AMQP_BASIC_PUBLISH_METHOD = (0x003C0028); static const int AMQP_BASIC_RETURN_METHOD = (0x003C0032); static const int AMQP_BASIC_DELIVER_METHOD = (0x003C003C); static const int AMQP_BASIC_GET_METHOD = (0x003C0046); static const int AMQP_BASIC_GET_OK_METHOD = (0x003C0047); static const int AMQP_BASIC_GET_EMPTY_METHOD = (0x003C0048); static const int AMQP_BASIC_ACK_METHOD = (0x003C0050); static const int AMQP_BASIC_REJECT_METHOD = (0x003C005A); static const int AMQP_BASIC_RECOVER_ASYNC_METHOD = (0x003C0064); static const int AMQP_BASIC_RECOVER_METHOD = (0x003C006E); static const int AMQP_BASIC_RECOVER_OK_METHOD = (0x003C006F); static const int AMQP_BASIC_NACK_METHOD = (0x003C0078); static const int AMQP_TX_SELECT_METHOD = (0x005A000A); static const int AMQP_TX_SELECT_OK_METHOD = (0x005A000B); static const int AMQP_TX_COMMIT_METHOD = (0x005A0014); static const int AMQP_TX_COMMIT_OK_METHOD = (0x005A0015); static const int AMQP_TX_ROLLBACK_METHOD = (0x005A001E); static const int AMQP_TX_ROLLBACK_OK_METHOD = (0x005A001F); static const int AMQP_CONFIRM_SELECT_METHOD = (0x0055000A); static const int AMQP_CONFIRM_SELECT_OK_METHOD = (0x0055000B); static const int AMQP_CONNECTION_CLASS = (0x000A); static const int AMQP_CHANNEL_CLASS = (0x0014); static const int AMQP_ACCESS_CLASS = (0x001E); static const int AMQP_EXCHANGE_CLASS = (0x0028); static const int AMQP_QUEUE_CLASS = (0x0032); static const int AMQP_BASIC_CLASS = (0x003C); static const int AMQP_BASIC_CONTENT_TYPE_FLAG = (1<<15); static const int AMQP_BASIC_CONTENT_ENCODING_FLAG = (1<<14); static const int AMQP_BASIC_HEADERS_FLAG = (1<<13); static const int AMQP_BASIC_DELIVERY_MODE_FLAG = (1<<12); static const int AMQP_BASIC_PRIORITY_FLAG = (1<<11); static const int AMQP_BASIC_CORRELATION_ID_FLAG = (1<<10); static const int AMQP_BASIC_REPLY_TO_FLAG = (1<<9); static const int AMQP_BASIC_EXPIRATION_FLAG = (1<<8); static const int AMQP_BASIC_MESSAGE_ID_FLAG = (1<<7); static const int AMQP_BASIC_TIMESTAMP_FLAG = (1<<6); static const int AMQP_BASIC_TYPE_FLAG = (1<<5); static const int AMQP_BASIC_USER_ID_FLAG = (1<<4); static const int AMQP_BASIC_APP_ID_FLAG = (1<<3); static const int AMQP_BASIC_CLUSTER_ID_FLAG = (1<<2); static const int AMQP_TX_CLASS = (0x005A); static const int AMQP_CONFIRM_CLASS = (0x0055); typedef int amqp_boolean_t; typedef uint32_t amqp_method_number_t; typedef uint32_t amqp_flags_t; typedef uint16_t amqp_channel_t; typedef struct amqp_bytes_t_ { size_t len; void *bytes; } amqp_bytes_t; typedef struct amqp_decimal_t_ { uint8_t decimals; uint32_t value; } amqp_decimal_t; typedef struct amqp_table_t_ { int num_entries; struct amqp_table_entry_t_ *entries; } amqp_table_t; typedef struct amqp_array_t_ { int num_entries; struct amqp_field_value_t_ *entries; } amqp_array_t; typedef struct amqp_field_value_t_ { uint8_t kind; union { amqp_boolean_t boolean; int8_t i8; uint8_t u8; int16_t i16; uint16_t u16; int32_t i32; uint32_t u32; int64_t i64; uint64_t u64; float f32; double f64; amqp_decimal_t decimal; amqp_bytes_t bytes; amqp_table_t table; amqp_array_t array; } value; } amqp_field_value_t; typedef struct amqp_table_entry_t_ { amqp_bytes_t key; amqp_field_value_t value; } amqp_table_entry_t; typedef enum { AMQP_FIELD_KIND_BOOLEAN = 't', AMQP_FIELD_KIND_I8 = 'b', AMQP_FIELD_KIND_U8 = 'B', AMQP_FIELD_KIND_I16 = 's', AMQP_FIELD_KIND_U16 = 'u', AMQP_FIELD_KIND_I32 = 'I', AMQP_FIELD_KIND_U32 = 'i', AMQP_FIELD_KIND_I64 = 'l', AMQP_FIELD_KIND_U64 = 'L', AMQP_FIELD_KIND_F32 = 'f', AMQP_FIELD_KIND_F64 = 'd', AMQP_FIELD_KIND_DECIMAL = 'D', AMQP_FIELD_KIND_UTF8 = 'S', AMQP_FIELD_KIND_ARRAY = 'A', AMQP_FIELD_KIND_TIMESTAMP = 'T', AMQP_FIELD_KIND_TABLE = 'F', AMQP_FIELD_KIND_VOID = 'V', AMQP_FIELD_KIND_BYTES = 'x' } amqp_field_value_kind_t; typedef struct amqp_pool_blocklist_t_ { int num_blocks; void **blocklist; } amqp_pool_blocklist_t; typedef struct amqp_pool_t_ { size_t pagesize; amqp_pool_blocklist_t pages; amqp_pool_blocklist_t large_blocks; int next_page; char *alloc_block; size_t alloc_used; } amqp_pool_t; typedef struct amqp_method_t_ { amqp_method_number_t id; void *decoded; } amqp_method_t; typedef struct amqp_frame_t_ { uint8_t frame_type; amqp_channel_t channel; union { amqp_method_t method; struct { uint16_t class_id; uint64_t body_size; void *decoded; amqp_bytes_t raw; } properties; amqp_bytes_t body_fragment; struct { uint8_t transport_high; uint8_t transport_low; uint8_t protocol_version_major; uint8_t protocol_version_minor; } protocol_header; } payload; } amqp_frame_t; typedef enum amqp_response_type_enum_ { AMQP_RESPONSE_NONE = 0, AMQP_RESPONSE_NORMAL, AMQP_RESPONSE_LIBRARY_EXCEPTION, AMQP_RESPONSE_SERVER_EXCEPTION } amqp_response_type_enum; typedef struct amqp_rpc_reply_t_ { amqp_response_type_enum reply_type; amqp_method_t reply; int library_error; } amqp_rpc_reply_t; typedef enum amqp_sasl_method_enum_ { AMQP_SASL_METHOD_PLAIN = 0 } amqp_sasl_method_enum; typedef struct amqp_connection_state_t_ *amqp_connection_state_t; char const * amqp_version(void); const amqp_bytes_t amqp_empty_bytes; const amqp_table_t amqp_empty_table; const amqp_array_t amqp_empty_array; void init_amqp_pool(amqp_pool_t *pool, size_t pagesize); void recycle_amqp_pool(amqp_pool_t *pool); void empty_amqp_pool(amqp_pool_t *pool); void * amqp_pool_alloc(amqp_pool_t *pool, size_t amount); void amqp_pool_alloc_bytes(amqp_pool_t *pool, size_t amount, amqp_bytes_t *output); amqp_bytes_t amqp_cstring_bytes(char const *cstr); amqp_bytes_t amqp_bytes_malloc_dup(amqp_bytes_t src); amqp_bytes_t amqp_bytes_malloc(size_t amount); void amqp_bytes_free(amqp_bytes_t bytes); amqp_connection_state_t amqp_new_connection(void); int amqp_get_sockfd(amqp_connection_state_t state); void amqp_set_sockfd(amqp_connection_state_t state, int sockfd); int amqp_tune_connection(amqp_connection_state_t state, int channel_max, int frame_max, int heartbeat); int amqp_get_channel_max(amqp_connection_state_t state); int amqp_destroy_connection(amqp_connection_state_t state); int amqp_handle_input(amqp_connection_state_t state, amqp_bytes_t received_data, amqp_frame_t *decoded_frame); amqp_boolean_t amqp_release_buffers_ok(amqp_connection_state_t state); void amqp_release_buffers(amqp_connection_state_t state); void amqp_maybe_release_buffers(amqp_connection_state_t state); int amqp_send_frame(amqp_connection_state_t state, amqp_frame_t const *frame); int amqp_table_entry_cmp(void const *entry1, void const *entry2); int amqp_open_socket(char const *hostname, int portnumber); int amqp_send_header(amqp_connection_state_t state); amqp_boolean_t amqp_frames_enqueued(amqp_connection_state_t state); int amqp_simple_wait_frame(amqp_connection_state_t state, amqp_frame_t *decoded_frame); int amqp_simple_wait_method(amqp_connection_state_t state, amqp_channel_t expected_channel, amqp_method_number_t expected_method, amqp_method_t *output); int amqp_send_method(amqp_connection_state_t state, amqp_channel_t channel, amqp_method_number_t id, void *decoded); amqp_rpc_reply_t amqp_simple_rpc(amqp_connection_state_t state, amqp_channel_t channel, amqp_method_number_t request_id, amqp_method_number_t *expected_reply_ids, void *decoded_request_method); void * amqp_simple_rpc_decoded(amqp_connection_state_t state, amqp_channel_t channel, amqp_method_number_t request_id, amqp_method_number_t reply_id, void *decoded_request_method); amqp_rpc_reply_t amqp_get_rpc_reply(amqp_connection_state_t state); amqp_rpc_reply_t amqp_login(amqp_connection_state_t state, char const *vhost, int channel_max, int frame_max, int heartbeat, amqp_sasl_method_enum sasl_method, ...); struct amqp_basic_properties_t_; int amqp_basic_publish(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t exchange, amqp_bytes_t routing_key, amqp_boolean_t mandatory, amqp_boolean_t immediate, struct amqp_basic_properties_t_ const *properties, amqp_bytes_t body); amqp_rpc_reply_t amqp_channel_close(amqp_connection_state_t state, amqp_channel_t channel, int code); amqp_rpc_reply_t amqp_connection_close(amqp_connection_state_t state, int code); int amqp_basic_ack(amqp_connection_state_t state, amqp_channel_t channel, uint64_t delivery_tag, amqp_boolean_t multiple); amqp_rpc_reply_t amqp_basic_get(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue, amqp_boolean_t no_ack); int amqp_basic_reject(amqp_connection_state_t state, amqp_channel_t channel, uint64_t delivery_tag, amqp_boolean_t requeue); amqp_boolean_t amqp_data_in_buffer(amqp_connection_state_t state); char * amqp_error_string(int err); int amqp_decode_table(amqp_bytes_t encoded, amqp_pool_t *pool, amqp_table_t *output, size_t *offset); int amqp_encode_table(amqp_bytes_t encoded, amqp_table_t *input, size_t *offset); struct amqp_connection_info { char *user; char *password; char *host; char *vhost; int port; }; void amqp_default_connection_info(struct amqp_connection_info *parsed); int amqp_parse_url(char *url, struct amqp_connection_info *parsed); char const * amqp_constant_name(int constantNumber); amqp_boolean_t amqp_constant_is_hard_error(int constantNumber); char const * amqp_method_name(amqp_method_number_t methodNumber); amqp_boolean_t amqp_method_has_content(amqp_method_number_t methodNumber); int amqp_decode_method(amqp_method_number_t methodNumber, amqp_pool_t *pool, amqp_bytes_t encoded, void **decoded); int amqp_decode_properties(uint16_t class_id, amqp_pool_t *pool, amqp_bytes_t encoded, void **decoded); int amqp_encode_method(amqp_method_number_t methodNumber, void *decoded, amqp_bytes_t encoded); int amqp_encode_properties(uint16_t class_id, void *decoded, amqp_bytes_t encoded); /* Method field records. */ typedef struct amqp_connection_start_t_ { uint8_t version_major; uint8_t version_minor; amqp_table_t server_properties; amqp_bytes_t mechanisms; amqp_bytes_t locales; } amqp_connection_start_t; typedef struct amqp_connection_start_ok_t_ { amqp_table_t client_properties; amqp_bytes_t mechanism; amqp_bytes_t response; amqp_bytes_t locale; } amqp_connection_start_ok_t; typedef struct amqp_connection_secure_t_ { amqp_bytes_t challenge; } amqp_connection_secure_t; typedef struct amqp_connection_secure_ok_t_ { amqp_bytes_t response; } amqp_connection_secure_ok_t; typedef struct amqp_connection_tune_t_ { uint16_t channel_max; uint32_t frame_max; uint16_t heartbeat; } amqp_connection_tune_t; typedef struct amqp_connection_tune_ok_t_ { uint16_t channel_max; uint32_t frame_max; uint16_t heartbeat; } amqp_connection_tune_ok_t; typedef struct amqp_connection_open_t_ { amqp_bytes_t virtual_host; amqp_bytes_t capabilities; amqp_boolean_t insist; } amqp_connection_open_t; typedef struct amqp_connection_open_ok_t_ { amqp_bytes_t known_hosts; } amqp_connection_open_ok_t; typedef struct amqp_connection_close_t_ { uint16_t reply_code; amqp_bytes_t reply_text; uint16_t class_id; uint16_t method_id; } amqp_connection_close_t; typedef struct amqp_connection_close_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_connection_close_ok_t; typedef struct amqp_channel_open_t_ { amqp_bytes_t out_of_band; } amqp_channel_open_t; typedef struct amqp_channel_open_ok_t_ { amqp_bytes_t channel_id; } amqp_channel_open_ok_t; typedef struct amqp_channel_flow_t_ { amqp_boolean_t active; } amqp_channel_flow_t; typedef struct amqp_channel_flow_ok_t_ { amqp_boolean_t active; } amqp_channel_flow_ok_t; typedef struct amqp_channel_close_t_ { uint16_t reply_code; amqp_bytes_t reply_text; uint16_t class_id; uint16_t method_id; } amqp_channel_close_t; typedef struct amqp_channel_close_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_channel_close_ok_t; typedef struct amqp_access_request_t_ { amqp_bytes_t realm; amqp_boolean_t exclusive; amqp_boolean_t passive; amqp_boolean_t active; amqp_boolean_t write; amqp_boolean_t read; } amqp_access_request_t; typedef struct amqp_access_request_ok_t_ { uint16_t ticket; } amqp_access_request_ok_t; typedef struct amqp_exchange_declare_t_ { uint16_t ticket; amqp_bytes_t exchange; amqp_bytes_t type; amqp_boolean_t passive; amqp_boolean_t durable; amqp_boolean_t auto_delete; amqp_boolean_t internal; amqp_boolean_t nowait; amqp_table_t arguments; } amqp_exchange_declare_t; typedef struct amqp_exchange_declare_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_exchange_declare_ok_t; typedef struct amqp_exchange_delete_t_ { uint16_t ticket; amqp_bytes_t exchange; amqp_boolean_t if_unused; amqp_boolean_t nowait; } amqp_exchange_delete_t; typedef struct amqp_exchange_delete_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_exchange_delete_ok_t; typedef struct amqp_exchange_bind_t_ { uint16_t ticket; amqp_bytes_t destination; amqp_bytes_t source; amqp_bytes_t routing_key; amqp_boolean_t nowait; amqp_table_t arguments; } amqp_exchange_bind_t; typedef struct amqp_exchange_bind_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_exchange_bind_ok_t; typedef struct amqp_exchange_unbind_t_ { uint16_t ticket; amqp_bytes_t destination; amqp_bytes_t source; amqp_bytes_t routing_key; amqp_boolean_t nowait; amqp_table_t arguments; } amqp_exchange_unbind_t; typedef struct amqp_exchange_unbind_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_exchange_unbind_ok_t; typedef struct amqp_queue_declare_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_boolean_t passive; amqp_boolean_t durable; amqp_boolean_t exclusive; amqp_boolean_t auto_delete; amqp_boolean_t nowait; amqp_table_t arguments; } amqp_queue_declare_t; typedef struct amqp_queue_declare_ok_t_ { amqp_bytes_t queue; uint32_t message_count; uint32_t consumer_count; } amqp_queue_declare_ok_t; typedef struct amqp_queue_bind_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_bytes_t exchange; amqp_bytes_t routing_key; amqp_boolean_t nowait; amqp_table_t arguments; } amqp_queue_bind_t; typedef struct amqp_queue_bind_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_queue_bind_ok_t; typedef struct amqp_queue_purge_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_boolean_t nowait; } amqp_queue_purge_t; typedef struct amqp_queue_purge_ok_t_ { uint32_t message_count; } amqp_queue_purge_ok_t; typedef struct amqp_queue_delete_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_boolean_t if_unused; amqp_boolean_t if_empty; amqp_boolean_t nowait; } amqp_queue_delete_t; typedef struct amqp_queue_delete_ok_t_ { uint32_t message_count; } amqp_queue_delete_ok_t; typedef struct amqp_queue_unbind_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_bytes_t exchange; amqp_bytes_t routing_key; amqp_table_t arguments; } amqp_queue_unbind_t; typedef struct amqp_queue_unbind_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_queue_unbind_ok_t; typedef struct amqp_basic_qos_t_ { uint32_t prefetch_size; uint16_t prefetch_count; amqp_boolean_t global; } amqp_basic_qos_t; typedef struct amqp_basic_qos_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_basic_qos_ok_t; typedef struct amqp_basic_consume_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_bytes_t consumer_tag; amqp_boolean_t no_local; amqp_boolean_t no_ack; amqp_boolean_t exclusive; amqp_boolean_t nowait; amqp_table_t arguments; } amqp_basic_consume_t; typedef struct amqp_basic_consume_ok_t_ { amqp_bytes_t consumer_tag; } amqp_basic_consume_ok_t; typedef struct amqp_basic_cancel_t_ { amqp_bytes_t consumer_tag; amqp_boolean_t nowait; } amqp_basic_cancel_t; typedef struct amqp_basic_cancel_ok_t_ { amqp_bytes_t consumer_tag; } amqp_basic_cancel_ok_t; typedef struct amqp_basic_publish_t_ { uint16_t ticket; amqp_bytes_t exchange; amqp_bytes_t routing_key; amqp_boolean_t mandatory; amqp_boolean_t immediate; } amqp_basic_publish_t; typedef struct amqp_basic_return_t_ { uint16_t reply_code; amqp_bytes_t reply_text; amqp_bytes_t exchange; amqp_bytes_t routing_key; } amqp_basic_return_t; typedef struct amqp_basic_deliver_t_ { amqp_bytes_t consumer_tag; uint64_t delivery_tag; amqp_boolean_t redelivered; amqp_bytes_t exchange; amqp_bytes_t routing_key; } amqp_basic_deliver_t; typedef struct amqp_basic_get_t_ { uint16_t ticket; amqp_bytes_t queue; amqp_boolean_t no_ack; } amqp_basic_get_t; typedef struct amqp_basic_get_ok_t_ { uint64_t delivery_tag; amqp_boolean_t redelivered; amqp_bytes_t exchange; amqp_bytes_t routing_key; uint32_t message_count; } amqp_basic_get_ok_t; typedef struct amqp_basic_get_empty_t_ { amqp_bytes_t cluster_id; } amqp_basic_get_empty_t; typedef struct amqp_basic_ack_t_ { uint64_t delivery_tag; amqp_boolean_t multiple; } amqp_basic_ack_t; typedef struct amqp_basic_reject_t_ { uint64_t delivery_tag; amqp_boolean_t requeue; } amqp_basic_reject_t; typedef struct amqp_basic_recover_async_t_ { amqp_boolean_t requeue; } amqp_basic_recover_async_t; typedef struct amqp_basic_recover_t_ { amqp_boolean_t requeue; } amqp_basic_recover_t; typedef struct amqp_basic_recover_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_basic_recover_ok_t; typedef struct amqp_basic_nack_t_ { uint64_t delivery_tag; amqp_boolean_t multiple; amqp_boolean_t requeue; } amqp_basic_nack_t; typedef struct amqp_tx_select_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_select_t; typedef struct amqp_tx_select_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_select_ok_t; typedef struct amqp_tx_commit_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_commit_t; typedef struct amqp_tx_commit_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_commit_ok_t; typedef struct amqp_tx_rollback_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_rollback_t; typedef struct amqp_tx_rollback_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_rollback_ok_t; typedef struct amqp_confirm_select_t_ { amqp_boolean_t nowait; } amqp_confirm_select_t; typedef struct amqp_confirm_select_ok_t_ { char dummy; /* Dummy field to avoid empty struct */ } amqp_confirm_select_ok_t; /* Class property records. */ typedef struct amqp_connection_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_connection_properties_t; typedef struct amqp_channel_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_channel_properties_t; typedef struct amqp_access_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_access_properties_t; typedef struct amqp_exchange_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_exchange_properties_t; typedef struct amqp_queue_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_queue_properties_t; typedef struct amqp_basic_properties_t_ { amqp_flags_t _flags; amqp_bytes_t content_type; amqp_bytes_t content_encoding; amqp_table_t headers; uint8_t delivery_mode; uint8_t priority; amqp_bytes_t correlation_id; amqp_bytes_t reply_to; amqp_bytes_t expiration; amqp_bytes_t message_id; uint64_t timestamp; amqp_bytes_t type; amqp_bytes_t user_id; amqp_bytes_t app_id; amqp_bytes_t cluster_id; } amqp_basic_properties_t; typedef struct amqp_tx_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_tx_properties_t; typedef struct amqp_confirm_properties_t_ { amqp_flags_t _flags; char dummy; /* Dummy field to avoid empty struct */ } amqp_confirm_properties_t; /* API functions for methods */ amqp_channel_open_ok_t * amqp_channel_open(amqp_connection_state_t state, amqp_channel_t channel); amqp_channel_flow_ok_t * amqp_channel_flow(amqp_connection_state_t state, amqp_channel_t channel, amqp_boolean_t active); amqp_exchange_declare_ok_t * amqp_exchange_declare(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t exchange, amqp_bytes_t type, amqp_boolean_t passive, amqp_boolean_t durable, amqp_table_t arguments); amqp_exchange_delete_ok_t * amqp_exchange_delete(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t exchange, amqp_boolean_t if_unused); amqp_exchange_bind_ok_t * amqp_exchange_bind(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t destination, amqp_bytes_t source, amqp_bytes_t routing_key, amqp_table_t arguments); amqp_exchange_unbind_ok_t * amqp_exchange_unbind(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t destination, amqp_bytes_t source, amqp_bytes_t routing_key, amqp_table_t arguments); amqp_queue_declare_ok_t * amqp_queue_declare(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue, amqp_boolean_t passive, amqp_boolean_t durable, amqp_boolean_t exclusive, amqp_boolean_t auto_delete, amqp_table_t arguments); amqp_queue_bind_ok_t * amqp_queue_bind(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue, amqp_bytes_t exchange, amqp_bytes_t routing_key, amqp_table_t arguments); amqp_queue_purge_ok_t * amqp_queue_purge(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue); amqp_queue_delete_ok_t * amqp_queue_delete(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue, amqp_boolean_t if_unused, amqp_boolean_t if_empty); amqp_queue_unbind_ok_t * amqp_queue_unbind(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue, amqp_bytes_t exchange, amqp_bytes_t routing_key, amqp_table_t arguments); amqp_basic_qos_ok_t * amqp_basic_qos(amqp_connection_state_t state, amqp_channel_t channel, uint32_t prefetch_size, uint16_t prefetch_count, amqp_boolean_t global); amqp_basic_consume_ok_t * amqp_basic_consume(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t queue, amqp_bytes_t consumer_tag, amqp_boolean_t no_local, amqp_boolean_t no_ack, amqp_boolean_t exclusive, amqp_table_t arguments); amqp_basic_cancel_ok_t * amqp_basic_cancel(amqp_connection_state_t state, amqp_channel_t channel, amqp_bytes_t consumer_tag); amqp_basic_recover_ok_t * amqp_basic_recover(amqp_connection_state_t state, amqp_channel_t channel, amqp_boolean_t requeue); amqp_tx_select_ok_t * amqp_tx_select(amqp_connection_state_t state, amqp_channel_t channel); amqp_tx_commit_ok_t * amqp_tx_commit(amqp_connection_state_t state, amqp_channel_t channel); amqp_tx_rollback_ok_t * amqp_tx_rollback(amqp_connection_state_t state, amqp_channel_t channel); amqp_confirm_select_ok_t * amqp_confirm_select(amqp_connection_state_t state, amqp_channel_t channel); ]] return (ffi.load("librabbitmq.so.1"))
local function create_initial_build_orders(self) local order = BuildOrder.from_generator(self.min, self.max, 'astral_plane') BuildOrder.register(order) self:add_order(order) end return { create_initial_build_orders = create_initial_build_orders }
local rhs_opts = {} function rhs_opts:new(cmd) local instance = { cmd = cmd, options = { noremap = false, silent = false, expr = false, nowait = false } } setmetatable(instance, self) self.__index = self return instance end function rhs_opts:with_silent() self.options.silent = true return self end function rhs_opts:with_noremap() self.options.noremap = true return self end function rhs_opts:with_expr() self.options.expr = true return self end function rhs_opts:with_nowait() self.options.nowait = true return self end local pbind = {} function pbind.map(cmd) local ro = rhs_opts:new(cmd) return ro end function pbind.nvim_load_mapping(mapping) for key, value in pairs(mapping) do local mode, keymap = key:match("([^|]*)|?(.*)") if type(value) == 'table' then local rhs = value.cmd local options = value.options vim.api.nvim_set_keymap(mode, keymap, rhs, options) end end end return pbind
----------------------------------- -- Ability: Tenuto -- If the next song you cast affects yourself, it will not subsequently be overwritten by other songs. -- Obtained: Bard Level 83 -- Recast Time: 0:15 -- Duration: 1:00, or until next song is cast. ----------------------------------- require("scripts/globals/settings") require("scripts/globals/status") ----------------------------------- function onAbilityCheck(player,target,ability) return 0,0 end function onUseAbility(player, target, ability) player:addStatusEffect(tpz.effect.TENUTO,0,0,60) end
LANG = { ["Intro"] = function () print "-------------------------------" print "Чудище-умножатель и храбрый богатырь" print "v 1.0.0 by HerrOfTheLand" print "-------------------------------" print "Чудище-умножатель украл царевну тридесятого царства!" print "Помоги богатырю победить его." print "Когда чудище будет загадывать задачу, подскажи богатырю правильный ответ." end, ["RoundBegin"] = function () print "-------------------------------" end, ["RoundEnd"] = function () print() end, ["HealthBar"] = function (hero_health, beast_health) print ("Богатырь: " .. string.rep(">", hero_health) .. "|" .. string.rep("<", beast_health) .. " :Чудище") end, ["BeastProblem"] = function (a, b) print ("Чудище: Ну, сколько будет " .. a .. " * " .. b .. "?") end, ["GetNumber"] = function () local answer = io.read "*number" if answer == nil then print "Чудище: Это даже не число!" io.read() -- trailing symbol fix end return answer end, ["BeastLose"] = function () print "Чудище: Агрх... Правильно" end, ["BeastWin"] = function (answer) print ("Чудище: Хаха, неправильно. Правильный ответ: " .. answer) end, ["GameMessageBegin"] = function () print "-------------------------------" end, ["GameMessageEnd"] = function () print "-------------------------------" end, ["GameWin"] = function () print "Молодец. Чудище больше не сможит никому навредить." end, ["GameLose"] = function () print "Богатырь погиб. Попробуй снова." end, ["StartAgain"] = function () print "Начать сначала? [да/Нет]" end, ["YesNo"] = function () local yesno = (io.read "*line"):sub(1, 2) return yesno == "д" or yesno == "Д" end }
-- src/opcodes/configure.ac:/for arch in/ return { aarch64={'aarch64-asm.c', 'aarch64-dis.c', 'aarch64-opc.c', 'aarch64-asm-2.c', 'aarch64-dis-2.c', 'aarch64-opc-2.c'}, alpha={'alpha-dis.c', 'alpha-opc.c'}, arc={'arc-dis.c', 'arc-opc.c', 'arc-ext.c'}, arm={'arm-dis.c'}, avr={'avr-dis.c'}, bfin={'bfin-dis.c'}, cr16={'cr16-dis.c', 'cr16-opc.c'}, cris={'cris-dis.c', 'cris-opc.c', 'cgen-bitset.c'}, crx={'crx-dis.c', 'crx-opc.c'}, csky={'csky-dis.c'}, d10v={'d10v-dis.c', 'd10v-opc.c'}, d30v={'d30v-dis.c', 'd30v-opc.c'}, dlx={'dlx-dis.c'}, fr30={'fr30-asm.c', 'fr30-desc.c', 'fr30-dis.c', 'fr30-ibld.c', 'fr30-opc.c'}, frv={'frv-asm.c', 'frv-desc.c', 'frv-dis.c', 'frv-ibld.c', 'frv-opc.c'}, ft32={'ft32-opc.c', 'ft32-dis.c'}, moxie={'moxie-dis.c', 'moxie-opc.c'}, h8300={'h8300-dis.c'}, hppa={'hppa-dis.c'}, i386={'i386-dis.c', 'i386-opc.c'}, iamcu={'i386-dis.c', 'i386-opc.c'}, l1om={'i386-dis.c', 'i386-opc.c'}, k1om={'i386-dis.c', 'i386-opc.c'}, ia64={'ia64-dis.c', 'ia64-opc.c'}, ip2k={'ip2k-asm.c', 'ip2k-desc.c', 'ip2k-dis.c', 'ip2k-ibld.c', 'ip2k-opc.c'}, epiphany={'epiphany-asm.c', 'epiphany-desc.c', 'epiphany-dis.c', 'epiphany-ibld.c', 'epiphany-opc.c'}, iq2000={'iq2000-asm.c', 'iq2000-desc.c', 'iq2000-dis.c', 'iq2000-ibld.c', 'iq2000-opc.c'}, lm32={'lm32-asm.c', 'lm32-desc.c', 'lm32-dis.c', 'lm32-ibld.c', 'lm32-opc.c', 'lm32-opinst.c'}, m32c={'m32c-asm.c', 'm32c-desc.c', 'm32c-dis.c', 'm32c-ibld.c', 'm32c-opc.c'}, m32r={'m32r-asm.c', 'm32r-desc.c', 'm32r-dis.c', 'm32r-ibld.c', 'm32r-opc.c', 'm32r-opinst.c'}, m68hc11={'m68hc11-dis.c', 'm68hc11-opc.c'}, m68hc12={'m68hc11-dis.c', 'm68hc11-opc.c'}, m9s12x={'m68hc11-dis.c', 'm68hc11-opc.c'}, m9s12xg={'m68hc11-dis.c', 'm68hc11-opc.c'}, s12z={'s12z-dis.c', 's12z-opc.c'}, m68k={'m68k-dis.c', 'm68k-opc.c'}, mcore={'mcore-dis.c'}, mep={'mep-asm.c', 'mep-desc.c', 'mep-dis.c', 'mep-ibld.c', 'mep-opc.c'}, metag={'metag-dis.c'}, microblaze={'microblaze-dis.c'}, mips={'mips-dis.c', 'mips-opc.c', 'mips16-opc.c', 'micromips-opc.c'}, mmix={'mmix-dis.c', 'mmix-opc.c'}, mn10200={'m10200-dis.c', 'm10200-opc.c'}, mn10300={'m10300-dis.c', 'm10300-opc.c'}, mt={'mt-asm.c', 'mt-desc.c', 'mt-dis.c', 'mt-ibld.c', 'mt-opc.c'}, msp430={'msp430-dis.c', 'msp430-decode.c'}, nds32={'nds32-asm.c', 'nds32-dis.c'}, nfp={'nfp-dis.c'}, nios2={'nios2-dis.c', 'nios2-opc.c'}, ns32k={'ns32k-dis.c'}, or1k={'or1k-asm.c', 'or1k-desc.c', 'or1k-dis.c', 'or1k-ibld.c', 'or1k-opc.c'}, pdp11={'pdp11-dis.c', 'pdp11-opc.c'}, pj={'pj-dis.c', 'pj-opc.c'}, powerpc={'ppc-dis.c', 'ppc-opc.c'}, powerpc_64={'ppc-dis.c', 'ppc-opc.c'}, pru={'pru-dis.c', 'pru-opc.c'}, pyramid={}, romp={}, riscv={'riscv-dis.c', 'riscv-opc.c'}, rs6000={'ppc-dis.c', 'ppc-opc.c'}, rl78={'rl78-dis.c', 'rl78-decode.c'}, rx={'rx-dis.c', 'rx-decode.c'}, s390={'s390-dis.c', 's390-opc.c'}, score={'score-dis.c', 'score7-dis.c'}, sh={'sh-dis.c', 'cgen-bitset.c'}, sparc={'sparc-dis.c', 'sparc-opc.c'}, spu={'spu-dis.c', 'spu-opc.c'}, tic30={'tic30-dis.c'}, tic4x={'tic4x-dis.c'}, tic54x={'tic54x-dis.c', 'tic54x-opc.c'}, tic6x={'tic6x-dis.c'}, tilegx={'tilegx-dis.c', 'tilegx-opc.c'}, tilepro={'tilepro-dis.c', 'tilepro-opc.c'}, v850={'v850-opc.c', 'v850-dis.c'}, v850e={'v850-opc.c', 'v850-dis.c'}, v850ea={'v850-opc.c', 'v850-dis.c'}, v850_rh850={'v850-opc.c', 'v850-dis.c'}, vax={'vax-dis.c'}, visium={'visium-dis.c', 'visium-opc.c'}, wasm32={'wasm32-dis.c'}, xc16x={'xc16x-asm.c', 'xc16x-desc.c', 'xc16x-dis.c', 'xc16x-ibld.c', 'xc16x-opc.c'}, xgate={'xgate-dis.c', 'xgate-opc.c'}, xstormy16={'xstormy16-asm.c', 'xstormy16-desc.c', 'xstormy16-dis.c', 'xstormy16-ibld.c', 'xstormy16-opc.c'}, xtensa={'xtensa-dis.c'}, z80={'z80-dis.c'}, z8k={'z8k-dis.c'}, bpf={'bpf-asm.c', 'bpf-desc.c', 'bpf-dis.c', 'bpf-ibld.c', 'bpf-opc.c'}, }
require "busted.runner"() local Helper = require "spec/scripts/devtools/menu/option/helper" describe("CheckboxOption", function() -- before_each initialization local options local ChoicesOption, choicesoption before_each(function() -- initialization options = { choices = {}, label = "Test", on_accept_fn = spy.new(Empty), on_cursor_fn = spy.new(Empty), on_get_fn = spy.new(Empty), on_set_fn = spy.new(Empty), } ChoicesOption = require "devtools/menu/option/choicesoption" choicesoption = ChoicesOption(options) end) insulate("when initializing", function() local options_fn = function() return options end local init_fn = function() ChoicesOption(options) end local function AssertDefaults(self) -- Option assert.is_equal(options.label, self.label) assert.is_equal(options.label, self.name) assert.is_equal(options.on_accept_fn, self.on_accept_fn) assert.is_equal(options.on_cursor_fn, self.on_cursor_fn) -- general assert.is_nil(self.key) -- options assert.is_equal(options.choices, self.choices) assert.is_equal(options.on_get_fn, self.on_get_fn) assert.is_equal(options.on_set_fn, self.on_set_fn) end it("should have the default fields", function() AssertDefaults(choicesoption) end) Helper.TestOptionAsserts(options_fn, init_fn, "choices", "table") end) end)
--vim: ts=2 sw=2 sts=2 expandtab:cindent: --------- --------- --------- --------- --------- --------- local Thing = require("thing") local div = require("divs") local Some = {klass="Some"} function Some.new(t) i = Thing.new(t) i.me = Some i.has = {} i.divs = nil i.most = t.most or THE.some.most return i end function Some.div(i) i.divs = i.divs and i.divs or divs(i.has) return i.divs end function Some.add(i,x) if x == "?" then return x end x = i.key(x) i.n = i.n + 1 i.divs = nil if #i.has < i.most then i.has[#i.has+1] = x elseif r() < i.most/i.n then i.has[ math.floor(#i.has*r()) + 1 ] = x end end return Some