content
stringlengths
5
1.05M
return Def.ActorFrame{ LoadActor(THEME:GetPathB("","ScreenSelectMusic overlay/current_group"))..{ InitCommand=cmd(x,SCREEN_LEFT;y,SCREEN_TOP+5;horizalign,left;vertalign,top;zoomx,1;cropbottom,0.3); }; LoadFont("monsterrat/_montserrat light 60px")..{ InitCommand=cmd(uppercase,true;horizalign,left;x,SCREEN_LEFT+18;y,SCREEN_TOP+10;zoom,0.185;skewx,-0.1); OnCommand=function(self) self:uppercase(true); self:settext("NEW PLAYER"); end; }; LoadFont("monsterrat/_montserrat semi bold 60px")..{ InitCommand=cmd(uppercase,true;horizalign,left;x,SCREEN_LEFT+16;y,SCREEN_TOP+30;zoom,0.6;skewx,-0.255); OnCommand=function(self) self:uppercase(true); self:settext("ENTER YOUR PROFILE NAME"); end; }; --TIME LoadFont("monsterrat/_montserrat light 60px")..{ Text="TIME"; InitCommand=cmd(x,SCREEN_CENTER_X-25;y,SCREEN_BOTTOM-92;zoom,0.6;skewx,-0.2); }; };
local node_box = { type = "connected", fixed = {{-1/4, -1/2, -1/4, 1/4, 1/2, 1/4}}, -- connect_bottom = connect_front = {{-3/16, -1/2, -1/2, 3/16, 3/8, -1/4}}, connect_left = {{-1/2, -1/2, -3/16, -1/4, 3/8, 3/16}}, connect_back = {{-3/16, -1/2, 1/4, 3/16, 3/8, 1/2}}, connect_right = {{ 1/4, -1/2, -3/16, 1/2, 3/8, 3/16}}, } local register_wall = function(base_node) local name = base_node .. "_wall" local ndef = minetest.registered_nodes[base_node] local groups = ndef.groups groups["wall"] = 1 -- inventory node, and pole-type wall start item minetest.register_node(name, { description = ndef.description .. " Wall", drawtype = "nodebox", node_box = node_box, connects_to = {base_node,"group:wall"}, paramtype = "light", is_ground_content = false, tiles = ndef.tiles, walkable = true, groups = groups, sounds = ndef.sounds, }) -- crafting recipe minetest.register_craft({ output = name .. " 6", recipe = { { '', '', '' }, { base_node, base_node, base_node}, { base_node, base_node, base_node}, } }) end register_wall("darkage:basalt_rubble") register_wall("darkage:ors_rubble") register_wall("darkage:stone_brick") register_wall("darkage:slate_rubble") register_wall("darkage:tuff_bricks") register_wall("darkage:old_tuff_bricks") register_wall("darkage:rhyolitic_tuff_bricks")
min = 2; max = 20; side = min + math.random(max - min); factor = min + math.random(5); if (ITEM == 1) then circ = side * 4 answ = msg1 .. tostring(math.floor(circ)) .. msg2 else circ = side * (factor + 1) * 2 answ = msg3 .. tostring(math.floor(circ)) .. msg4 .. tostring(math.floor(factor)) .. msg5 end
local VALIDATOR = {} -- faz a checagem de tipo para os parametros simples recebidos local function checkSimpleType(interfaceType, param) local err = nil if interfaceType == "char" then if type(param) ~= "string" or #param ~= 1 then err = "Erro parametro não eh char. Param recebido: " .. type(param) end elseif interfaceType == "string" then if type(param) ~= "string" then err = "Erro parametro não eh string. Param recebido: " .. type(param) end elseif interfaceType == "double" then if type(param) ~= "number" then err = "Erro parametro não eh double. Param recebido: " .. type(param) elseif math.type(param) ~= "float" and math.type(param) ~= "integer" then -- aceito int no double err = "Erro parametro não eh double. Param recebido: " .. math.type(param) end elseif interfaceType == "int" then if type(param) ~= "number" then err = "Erro parametro não eh int. Param recebido: " .. type(param) elseif math.type(param) ~= "integer" then err = "Erro parametro não eh int. Param recebido: " .. math.type(param) end else -- tipo desconhecido err = "Erro parametro desconhecido. Parametro esperado: " .. interfaceType .. " Param recebido: " .. type(param) end return err end -- checa tipo struct local function checkStructType(param, structFields) local err = nil local paramSize = 0 for k, v in pairs(param) do paramSize = paramSize + 1 end if paramSize ~= #structFields then return "Erro, o numero de campos da struct está incorreto." .. "num esperado " .. #structFields .. " recebidos " .. paramSize end for k, v in pairs(structFields) do err = checkSimpleType(v.type, param[v.name]) if err then err = "Erro na Struct. No campo " .. v.name .. ". " .. err return err end end end -- conta e retorna quantos argumentos são do tipo "in" e quantos do tipo "out" local function getNumberOfInAndOutArguments(arguments) local i = 0 local o = 0 for k, v in pairs(arguments) do if v.direction == "in" then i = i + 1 else o = o + 1 end end -- assert(i+o == #arguments) -- sanity check return i, o end -- checa se os retornos casam com a interface, se o numero de parametros não casar com o esperado, retorna erro direto -- caso contrario retorna apenas o ultimo erro, se houver function VALIDATOR.checkReturnTypes(returnTbl, returnType, params, structTbl) local inParams, outParams = getNumberOfInAndOutArguments(params) local defaultReturn = 1 -- por default toda funçao retona 1 parametro, vou tratar o caso void passando pra zero if returnType == "void" then defaultReturn = 0 end -- caso void não tem retorno "default" local expectedReturns = defaultReturn + outParams -- o numero de parametros retornados eh o retorno default da função mais os parametros out if #returnTbl ~= expectedReturns then return "Erro, Numero de retornos diferente do esperado na IDL. Esperava: " .. expectedReturns .. "Recebeu " .. #returnTbl end local err = nil local index = 1 if defaultReturn == 1 then -- temos que checar o retorno "basico" if returnType == structTbl.name then err = checkStructType(returnTbl[index], structTbl.fields) else err = checkSimpleType(returnType, returnTbl[index]) end if err then return err end index = index + 1 end -- checando os parametros out na ordem for _, v in ipairs(params) do if (v.direction == "out") then if v.type == structTbl.name then err = checkStructType(returnTbl[index], structTbl.fields) else err = checkSimpleType(v.type, returnTbl[index]) end if err then return err end index = index + 1 end end end -- Checa se todas as funções estão no objeto recebido -- recebe o objeto representando a interface function VALIDATOR.checkServantObj(obj, interface) -- Não utilizado para não alterar muito o luarpc que estamos usando for k, v in pairs(obj) do if interface.methods[k] == nil then print("Erro, objeto recebido não implementa a interface a função " .. k .. " não existe") return "error" end end end function VALIDATOR.validate_client(params, fname, iface_args, struct_data) local valid = true local inputs = {} local reasons = "" for i = 1, #iface_args do local arg_direc = iface_args[i].direction if arg_direc == "in" or arg_direc == "inout" then local arg_type = iface_args[i].type table.insert(inputs, arg_type) end end if not (#params == #inputs) then local reason = string.format("Method '%s' should receive %i args, but received %i instead", fname, #inputs, #params) -- -- print("[ERROR] Invalid request! " .. reason) valid = false reasons = reasons .. "___ERRORPC: " .. reason .. "\n" return valid, params, reasons end for i = 1, #inputs do -- checando tipos, local err if inputs[i] == struct_data.name then err = checkStructType(params[i], struct_data.fields) else err = checkSimpleType(inputs[i], params[i]) end if err then return false, params, err end end return valid, params, reasons end return VALIDATOR
local ffi = require('ffi') local const = require('metrics.const') local quantile = {} if not pcall(ffi.typeof, "sample") then ffi.cdef[[ typedef struct sample {int Delta, Width; double Value; } sample; ]] end local sample_constructor = ffi.typeof('sample') local function quicksort(array, low, high) assert(low >= 0, 'Low bound must be non-negative') assert(high < ffi.sizeof(array) / ffi.sizeof('double'), 'Upper bound must be lower than array size') if high - low < 1 then return array end local pivot = low for i = low + 1, high do if array[i] <= array[pivot] then if i == pivot + 1 then array[pivot], array[pivot + 1] = array[pivot + 1], array[pivot] else array[pivot], array[pivot + 1], array[i] = array[i], array[pivot], array[pivot + 1] end pivot = pivot + 1 end end array = quicksort(array, low, pivot - 1) return quicksort(array, pivot + 1, high) end quantile.quicksort = quicksort local function make_sample(value, width, delta) return sample_constructor(delta or 0, width or 0, value) end local inf_obj = make_sample(math.huge) local function insert_sample(sample_obj, value, width, delta) sample_obj.Value = value sample_obj.Width = width sample_obj.Delta = delta end local stream = {} -- Stream computes quantiles for a stream of float64s. function stream.new(f, max_samples) if not max_samples then max_samples = 500 end assert(max_samples > 0, 'max_samples must be positive') return setmetatable({ stream = { f = f, l = {}, n = 0, }, b = {}, sorted = true, __max_samples = max_samples, }, { __index = stream }) end function stream:flush() self:maybe_sort() self:merge(self.b, self.b_len) self.b_len = 0 end function stream:maybe_sort() if not self.sorted and self.b_len > 1 then self.sorted = true quicksort(self.b, 0, self.b_len - 1) end end function stream:flushed() return self.stream.l_len > 0 end local function sample_copy(dst, src) dst.Value = src.Value dst.Width = src.Width or 0 dst.Delta = src.Delta or 0 end function stream:sample_insert(value, width, delta, pos) local arr = self.stream.l local len = self.stream.l_len local cap = self.stream.l_cap local do_shift = true if not pos then pos = len + 1 do_shift = false end if len == cap then cap = math.modf(cap * 1.5) local new_arr = ffi.new('sample[?]', cap + 2) for i = 0, pos - 1 do sample_copy(new_arr[i], arr[i]) end insert_sample(new_arr[pos], value, width, delta ) for i = pos + 1, len do sample_copy(new_arr[i], arr[i-1]) end for i = len + 1, cap + 1 do new_arr[i] = inf_obj end self.stream.l_cap = cap self.stream.l = new_arr return end if do_shift then for i = len + 1, pos + 1, -1 do sample_copy(arr[i], arr[i-1]) end end insert_sample(arr[pos], value, width, delta ) end local function sample_remove(arr, len, pos) for i = pos, len - 1 do sample_copy(arr[i], arr[i+1]) end arr[len].Value = math.huge end function stream:merge(samples, len) local s = self.stream local i = 1 local r = 0 for z = 1, len do local sample = samples[z-1] for j = i, s.l_len do local c = s.l[j] if c.Value > sample then self:sample_insert(sample, 1, s.f(s, r) - 1, j) s.l_len = s.l_len + 1 i = j + 1 goto inserted end r = r + c.Width end self:sample_insert(sample, 1, 0) s.l_len = s.l_len + 1 i = i + 1 ::inserted:: s.n = s.n + 1 end end function stream:query(q) local s = self.stream local t = q * s.n t = t + s.f(s, t) / 2 local p = s.l[0] local r = 0 for i = 1, s.l_len do local c = s.l[i] if r + c.Width + c.Delta > t then return p.Value end r = r + p.Width p = c end return p.Value end function stream:compress() local s = self.stream if s.l_len < 2 then return end local x = make_sample(0) sample_copy(x, s.l[s.l_len]) local xi = s.l_len local r = s.n - x.Width for i = s.l_len - 1, 1, -1 do local c = make_sample(0) sample_copy(c, s.l[i]) if c.Width + x.Width + x.Delta <= s.f(s, r) then x.Width = x.Width + c.Width sample_copy(s.l[xi], x) sample_remove(s.l, s.l_len, i) s.l_len = s.l_len - 1 xi = xi - 1 else x = c xi = i end r = r - c.Width end self.compress_cnt = 0 end function quantile.NewTargeted(quantiles, max_samples) local qs={} local epss = {} for q, eps in pairs(quantiles) do assert(q >= 0 and q <= 1, 'Quantile must be in [0; 1]') table.insert(qs, q) table.insert(epss, eps) end local len = #qs local function fun(s, r) local m = math.huge local f for i = 1, len do local q = qs[i] local eps = epss[i] if q*s.n <= r then f = (2 * eps * r) / q else f = (2 * eps * (s.n - r)) / (1 - q) end if math.floor(f) < m then m = math.floor(f) end end return math.max(m, 1) end local s = stream.new(fun, max_samples) s.b = ffi.new('double[?]', s.__max_samples) for i = 0, s.__max_samples - 1 do s.b[i] = math.huge end local minf_obj = make_sample(-math.huge) s.stream.l = ffi.new('sample[?]', s.__max_samples * 2 + 2) s.stream.l[0] = minf_obj for i = 1, s.__max_samples * 2 + 1 do s.stream.l[i] = inf_obj end s.b_len = 0 s.stream.l_len = 0 s.stream.l_cap = s.__max_samples * 2 s.compress_cnt = 0 return s end -- Insert inserts v into the stream. function quantile.Insert(stream_obj, v) stream_obj.b[stream_obj.b_len] = v stream_obj.b_len = stream_obj.b_len + 1 stream_obj.compress_cnt = stream_obj.compress_cnt + 1 stream_obj.sorted = false if stream_obj.b_len == stream_obj.__max_samples or stream_obj.compress_cnt == stream_obj.__max_samples then stream_obj:flush() stream_obj:compress() end end -- Query returns the computed qth percentiles value. If s was created with -- NewTargeted, and q is not in the set of quantiles provided a priori, Query -- will return an unspecified result. function quantile.Query(stream_obj, q) if not stream_obj:flushed() then -- Fast path when there hasn't been enough data for a flush; -- this also yields better accuracy for small sets of data. local l = stream_obj.b_len -- if buffer is empty and wasn't flushed yet then quantile value is NaN if l == 0 then return const.NAN end local i = math.modf(l * q) stream_obj:maybe_sort() return stream_obj.b[i] end stream_obj:flush() return stream_obj:query(q) end -- Reset reinitializes and clears the list reusing the samples buffer memory. function quantile.Reset(stream_obj) stream_obj.stream.n = 0 stream_obj.b_len = 0 stream_obj.stream.l_len = 0 for i = 1, stream_obj.__max_samples * 2 + 1 do stream_obj.stream.l[i] = inf_obj end for i = 0, stream_obj.__max_samples - 1 do stream_obj.b[i] = math.huge end end return quantile
-- Developers: --Divine (http://forum.botoflegends.com/user/86308-divine/) --PvPSuite (http://forum.botoflegends.com/user/76516-pvpsuite/) local sVersion = '2.1'; local rVersion = GetWebResult('raw.githubusercontent.com','/Nader-Sl/BoLStudio/master/Versions/p_movementHumanizer.version?no-cache=' .. math.random(1, 25000)); if ((rVersion) and (tonumber(rVersion) ~= nil)) then if (tonumber(sVersion) < tonumber(rVersion)) then print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FFFF00">An update has been found and it is now downloading!</font>'); DownloadFile('https://raw.githubusercontent.com/Nader-Sl/BoLStudio/master/Scripts/p_movementHumanizer.lua?no-cache=' .. math.random(1, 25000), (SCRIPT_PATH.. GetCurrentEnv().FILE_NAME), function() print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00FF00">Script has been updated, please reload!</font>'); end); return; end; else print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FF0000">Update Error</font>'); end; if (not VIP_USER) then print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FF0000">Non-VIP Not Supported</font>'); return; elseif ((string.find(GetGameVersion(), 'Releases/5.23') == nil) and (string.find(GetGameVersion(), 'Releases/5.24') == nil)) then print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FF0000">Game Version Not Supported</font>'); return; end; local theMenu = nil; local moveHeader = nil; local orbwalkerOK = false; local theOrbwalker = 0; local lastSecondMillis = 0; local humanizerMS = 0; local myLastPassedMovementMillis = 0; local myBlockedMovements = 0; local myPassedMovements = 0; local myTotalMovements = 0; local myHamsterLastPassedMovementMillis = 0; if (string.find(GetGameVersion(), 'Releases/5.23') ~= nil) then moveHeader = 0xD8; elseif (string.find(GetGameVersion(), 'Releases/5.24') ~= nil) then moveHeader = 0xC5; end; DelayAction(function() if ((_G.Reborn_Loaded) or (_G.AutoCarry)) then theOrbwalker = 2; print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00EE00">Sida\'s Auto Carry: Reborn Found</font>'); orbwalkerOK = true; elseif ((_G.MMA_Loaded) or (_G.MMA_Version)) then theOrbwalker = 3; print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00EE00">Marksman\'s Mighty Assistant Found</font>'); orbwalkerOK = true; elseif ((_G.NebelwolfisOrbWalkerInit) or (_G.NebelwolfisOrbWalkerLoaded)) then theOrbwalker = 4; print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00EE00">Nebelwolfi\'s Orbwalker Found</font>'); orbwalkerOK = true; elseif (_G.BigFatOrb_Loaded) then theOrbwalker = 5; print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00EE00">Big Fat Walk Found</font>'); orbwalkerOK = true; elseif (FileExist(LIB_PATH .. '/SxOrbWalk.lua')) then if (not _G.SxOrb) then require('SxOrbWalk'); end; theOrbwalker = 1; print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00EE00">SxOrbWalk Found</font>'); orbwalkerOK = true; else orbwalkerOK = false; end; if (orbwalkerOK) then InitMenu(); humanizerMS = (1000 / (theMenu.maximum + math.random(-1, 2))); orbwalkerOK = true; print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#00EE00">Loaded Successfully</font>'); else print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FF0000">No Supported Orbwalker Found</font>'); end; end, 0.25); function OnSendPacket(thePacket) if (orbwalkerOK) then if (thePacket.header == moveHeader) then local netID = thePacket:DecodeF(); if (IsOrbwalking()) then if (netID == myHero.networkID) then if (theMenu.enabled) then if ((not IsEvading()) or (theMenu.block)) then if ((CurrentTimeInMillis() - myLastPassedMovementMillis) <= humanizerMS) then thePacket:Block(); myBlockedMovements = myBlockedMovements + 1; else myLastPassedMovementMillis = CurrentTimeInMillis(); myPassedMovements = myPassedMovements + 1; end; end; end; myTotalMovements = myTotalMovements + 1; else if (theMenu.enabled) then if ((not IsEvading()) or (theMenu.block)) then if ((CurrentTimeInMillis() - myHamsterLastPassedMovementMillis) <= humanizerMS) then thePacket:Block(); else myHamsterLastPassedMovementMillis = CurrentTimeInMillis(); end; end; end; end; end; end; end; end; function OnTick() if (orbwalkerOK) then if ((CurrentTimeInMillis() - lastSecondMillis) >= 1000) then lastSecondMillis = CurrentTimeInMillis(); if (IsOrbwalking()) then if (theMenu.print) then if (theMenu.enabled) then print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FFFF00">' .. myPassedMovements .. ' passed ' .. ((myPassedMovements == 1) and 'command' or 'commands') .. ' - ' .. myBlockedMovements .. ' blocked ' .. ((myBlockedMovements == 1) and 'command' or 'commands') .. '</font>'); else print('<font color="#FF1493"><b>[p_movementHumanizer]</b> </font><font color="#FFFF00">' .. myTotalMovements .. ' total ' .. ((myTotalMovements == 1) and 'command' or 'commands') .. '</font>'); end; end; end; humanizerMS = (1000 / (theMenu.maximum + math.random(-1, 2))); myPassedMovements = 0; myBlockedMovements = 0; myTotalMovements = 0; end; end; end; function InitMenu() theMenu = scriptConfig('p_movementHumanizer', 'p_movementHumanizer'); theMenu:addParam('print', 'Print Movements', SCRIPT_PARAM_ONOFF, false); theMenu:addParam('enabled', 'Enable Movement Humanizer', SCRIPT_PARAM_ONOFF, true); theMenu:addParam('block', 'Block Evading Scripts', SCRIPT_PARAM_ONOFF, false); theMenu:addParam('maximum', 'Maximum Movements / Second', SCRIPT_PARAM_SLICE, 7, 4, 10, 0); theMenu:setCallback('maximum', function(nV) humanizerMS = (1000 / (nV + math.random(-1, 2))); end); end; function IsOrbwalking() if (theOrbwalker == 1) then return ((_G.SxOrb) and ((_G.SxOrb.isFight) or (_G.SxOrb.isHarass) or (_G.SxOrb.isLaneClear) or (_G.SxOrb.isLastHit))); elseif (theOrbwalker == 2) then return ((_G.AutoCarry) and ((_G.AutoCarry.Keys.AutoCarry) or (_G.AutoCarry.Keys.MixedMode) or (_G.AutoCarry.Keys.LaneClear) or (_G.AutoCarry.Keys.LastHit))); elseif (theOrbwalker == 3) then return (((_G.MMA_IsOrbwalking) and (_G.MMA_IsOrbwalking())) or ((_G.MMA_IsDualCarrying) and (_G.MMA_IsDualCarrying())) or ((_G.MMA_IsClearing) and (_G.MMA_IsClearing())) or ((_G.MMA_IsLasthitting) and (_G.MMA_IsLasthitting()))); elseif (theOrbwalker == 4) then return ((_G.NebelwolfisOrbWalker) and ((_G.NebelwolfisOrbWalker.Config.k.Combo) or (_G.NebelwolfisOrbWalker.Config.k.Harass) or (_G.NebelwolfisOrbWalker.Config.k.LastHit) or (_G.NebelwolfisOrbWalker.Config.k.LaneClear))); elseif (theOrbwalker == 5) then return ((_G.BigFatOrb_Mode) and ((_G.BigFatOrb_Mode == 'Combo') or (_G.BigFatOrb_Mode == 'Harass') or (_G.BigFatOrb_Mode == 'LastHit') or (_G.BigFatOrb_Mode == 'LaneClear'))); end; return false; end; function IsEvading() return ((_G.Evading) or (_G.NeoEvading) or (_G.Evade)); end; function CurrentTimeInMillis() return (os.clock() * 1000); end;
----------------------------------------------------------- -- FFI ----------------------------------------------------------- local ffi = require 'ffi' ffi.cdef [[ typedef void* CURL; typedef int CODE; int curl_version (); void curl_free (void* p); CURL curl_easy_init (); CURL curl_easy_duphandle (CURL handle); void curl_easy_cleanup (CURL handle); void curl_easy_reset (CURL handle); CODE curl_easy_perform (CURL handle); CODE curl_easy_setopt (CURL handle, int option, ...); CODE curl_easy_getinfo (CURL handle, int info, ...); char* curl_easy_escape (CURL handle, char* url, int length); char* curl_easy_unescape (CURL handle, char* url, int length, int* outlength); CODE curl_easy_recv (CURL handle, void* buffer, size_t length, size_t* n); CODE curl_easy_send (CURL handle, const void* buffer, size_t length, size_t* n); const char* curl_easy_strerror (CODE errcode); ]] local lib = ffi.load 'libcurl.dll' ----------------------------------------------------------- -- CURL Option Data ----------------------------------------------------------- local co_long = { 00000 } local co_objectpoint = { 10000 } local co_functionpoint = { 20000 } local co_off_t = { 30000 } local curl_opt = { file = { 001, co_objectpoint }, url = { 002, co_objectpoint }, port = { 003, co_long }, proxy = { 004, co_objectpoint }, userpwd = { 005, co_objectpoint }, proxyuserpwd = { 006, co_objectpoint }, range = { 007, co_objectpoint }, infile = { 009, co_objectpoint }, errorbuffer = { 010, co_objectpoint }, writefunction = { 011, co_functionpoint }, readfunction = { 012, co_functionpoint }, timeout = { 013, co_long }, infilesize = { 014, co_long }, postfields = { 015, co_objectpoint }, referer = { 016, co_objectpoint }, ftpport = { 017, co_objectpoint }, useragent = { 018, co_objectpoint }, low_speed_limit = { 019, co_long }, low_speed_time = { 020, co_long }, resume_from = { 021, co_long }, cookie = { 022, co_objectpoint }, httpheader = { 023, co_objectpoint }, httppost = { 024, co_objectpoint }, sslcert = { 025, co_objectpoint }, keypasswd = { 026, co_objectpoint }, crlf = { 027, co_long }, quote = { 028, co_objectpoint }, writeheader = { 029, co_objectpoint }, cookiefile = { 031, co_objectpoint }, sslversion = { 032, co_long }, timecondition = { 033, co_long }, timevalue = { 034, co_long }, customrequest = { 036, co_objectpoint }, stderr = { 037, co_objectpoint }, postquote = { 039, co_objectpoint }, writeinfo = { 040, co_objectpoint }, verbose = { 041, co_long }, header = { 042, co_long }, noprogress = { 043, co_long }, nobody = { 044, co_long }, failonerror = { 045, co_long }, upload = { 046, co_long }, post = { 047, co_long }, dirlistonly = { 048, co_long }, append = { 050, co_long }, netrc = { 051, co_long }, followlocation = { 052, co_long }, transfertext = { 053, co_long }, put = { 054, co_long }, progressfunction = { 056, co_functionpoint }, progressdata = { 057, co_objectpoint }, autoreferer = { 058, co_long }, proxyport = { 059, co_long }, postfieldsize = { 060, co_long }, httpproxytunnel = { 061, co_long }, interface = { 062, co_objectpoint }, krblevel = { 063, co_objectpoint }, ssl_verifypeer = { 064, co_long }, cainfo = { 065, co_objectpoint }, maxredirs = { 068, co_long }, filetime = { 069, co_long }, telnetoptions = { 070, co_objectpoint }, maxconnects = { 071, co_long }, closepolicy = { 072, co_long }, fresh_connect = { 074, co_long }, forbid_reuse = { 075, co_long }, random_file = { 076, co_objectpoint }, egdsocket = { 077, co_objectpoint }, connecttimeout = { 078, co_long }, headerfunction = { 079, co_functionpoint }, httpget = { 080, co_long }, ssl_verifyhost = { 081, co_long }, cookiejar = { 082, co_objectpoint }, ssl_cipher_list = { 083, co_objectpoint }, http_version = { 084, co_long }, ftp_use_epsv = { 085, co_long }, sslcerttype = { 086, co_objectpoint }, sslkey = { 087, co_objectpoint }, sslkeytype = { 088, co_objectpoint }, sslengine = { 089, co_objectpoint }, sslengine_default = { 090, co_long }, dns_use_global_cache = { 091, co_long }, dns_cache_timeout = { 092, co_long }, prequote = { 093, co_objectpoint }, debugfunction = { 094, co_functionpoint }, debugdata = { 095, co_objectpoint }, cookiesession = { 096, co_long }, capath = { 097, co_objectpoint }, buffersize = { 098, co_long }, nosignal = { 099, co_long }, share = { 100, co_objectpoint }, proxytype = { 101, co_long }, accept_encoding = { 102, co_objectpoint }, private = { 103, co_objectpoint }, http200aliases = { 104, co_objectpoint }, unrestricted_auth = { 105, co_long }, ftp_use_eprt = { 106, co_long }, httpauth = { 107, co_long }, ssl_ctx_function = { 108, co_functionpoint }, ssl_ctx_data = { 109, co_objectpoint }, ftp_create_missing_dirs = { 110, co_long }, proxyauth = { 111, co_long }, ftp_response_timeout = { 112, co_long }, ipresolve = { 113, co_long }, maxfilesize = { 114, co_long }, infilesize_large = { 115, co_off_t }, resume_from_large = { 116, co_off_t }, maxfilesize_large = { 117, co_off_t }, netrc_file = { 118, co_objectpoint }, use_ssl = { 119, co_long }, postfieldsize_large = { 120, co_off_t }, tcp_nodelay = { 121, co_long }, ftpsslauth = { 129, co_long }, ioctlfunction = { 130, co_functionpoint }, ioctldata = { 131, co_objectpoint }, ftp_account = { 134, co_objectpoint }, cookielist = { 135, co_objectpoint }, ignore_content_length = { 136, co_long }, ftp_skip_pasv_ip = { 137, co_long }, ftp_filemethod = { 138, co_long }, localport = { 139, co_long }, localportrange = { 140, co_long }, connect_only = { 141, co_long }, conv_from_network_function = { 142, co_functionpoint }, conv_to_network_function = { 143, co_functionpoint }, conv_from_utf8_function = { 144, co_functionpoint }, max_send_speed_large = { 145, co_off_t }, max_recv_speed_large = { 146, co_off_t }, ftp_alternative_to_user = { 147, co_objectpoint }, sockoptfunction = { 148, co_functionpoint }, sockoptdata = { 149, co_objectpoint }, ssl_sessionid_cache = { 150, co_long }, ssh_auth_types = { 151, co_long }, ssh_public_keyfile = { 152, co_objectpoint }, ssh_private_keyfile = { 153, co_objectpoint }, ftp_ssl_ccc = { 154, co_long }, timeout_ms = { 155, co_long }, connecttimeout_ms = { 156, co_long }, http_transfer_decoding = { 157, co_long }, http_content_decoding = { 158, co_long }, new_file_perms = { 159, co_long }, new_directory_perms = { 160, co_long }, postredir = { 161, co_long }, ssh_host_public_key_md5 = { 162, co_objectpoint }, opensocketfunction = { 163, co_functionpoint }, opensocketdata = { 164, co_objectpoint }, copypostfields = { 165, co_objectpoint }, proxy_transfer_mode = { 166, co_long }, seekfunction = { 167, co_functionpoint }, seekdata = { 168, co_objectpoint }, crlfile = { 169, co_objectpoint }, issuercert = { 170, co_objectpoint }, address_scope = { 171, co_long }, certinfo = { 172, co_long }, username = { 173, co_objectpoint }, password = { 174, co_objectpoint }, proxyusername = { 175, co_objectpoint }, proxypassword = { 176, co_objectpoint }, noproxy = { 177, co_objectpoint }, tftp_blksize = { 178, co_long }, socks5_gssapi_service = { 179, co_objectpoint }, socks5_gssapi_nec = { 180, co_long }, protocols = { 181, co_long }, redir_protocols = { 182, co_long }, ssh_knownhosts = { 183, co_objectpoint }, ssh_keyfunction = { 184, co_functionpoint }, ssh_keydata = { 185, co_objectpoint }, mail_from = { 186, co_objectpoint }, mail_rcpt = { 187, co_objectpoint }, ftp_use_pret = { 188, co_long }, rtsp_request = { 189, co_long }, rtsp_session_id = { 190, co_objectpoint }, rtsp_stream_uri = { 191, co_objectpoint }, rtsp_transport = { 192, co_objectpoint }, rtsp_client_cseq = { 193, co_long }, rtsp_server_cseq = { 194, co_long }, interleavedata = { 195, co_objectpoint }, interleavefunction = { 196, co_functionpoint }, wildcardmatch = { 197, co_long }, chunk_bgn_function = { 198, co_functionpoint }, chunk_end_function = { 199, co_functionpoint }, fnmatch_function = { 200, co_functionpoint }, chunk_data = { 201, co_objectpoint }, fnmatch_data = { 202, co_objectpoint }, resolve = { 203, co_objectpoint }, tlsauth_username = { 204, co_objectpoint }, tlsauth_password = { 205, co_objectpoint }, tlsauth_type = { 206, co_objectpoint }, transfer_encoding = { 207, co_long }, closesocketfunction = { 208, co_functionpoint }, closesocketdata = { 209, co_objectpoint }, gssapi_delegation = { 210, co_long }, dns_servers = { 211, co_objectpoint }, accepttimeout_ms = { 212, co_long }, tcp_keepalive = { 213, co_long }, tcp_keepidle = { 214, co_long }, tcp_keepintvl = { 215, co_long }, ssl_options = { 216, co_long }, mail_auth = { 217, co_objectpoint }, sasl_ir = { 218, co_long }, xferinfofunction = { 219, co_functionpoint }, xoauth2_bearer = { 220, co_objectpoint }, dns_interface = { 221, co_objectpoint }, dns_local_ip4 = { 222, co_objectpoint }, dns_local_ip6 = { 223, co_objectpoint }, login_options = { 224, co_objectpoint }, ssl_enable_npn = { 225, co_long }, ssl_enable_alpn = { 226, co_long }, expect_100_timeout_ms = { 227, co_long } } -- Aliases curl_opt.xferinfodata = curl_opt.progressdata curl_opt.server_response_timeout = curl_opt.ftp_response_timeout curl_opt.writedata = curl_opt.file curl_opt.readdata = curl_opt.infile curl_opt.headerdata = curl_opt.writeheader curl_opt.rtspheader = curl_opt.httpheader ----------------------------------------------------------- -- CURL Info Data ----------------------------------------------------------- local ci_string = { 0x100000, 'char* [1]', ffi.string } local ci_long = { 0x200000, 'long [1]', tonumber } local ci_double = { 0x300000, 'double[1]', tonumber } local ci_slist = { 0x400000, 'slist [1]', tostring } local curl_info = { effective_url = { 01, ci_string }, response_code = { 02, ci_long }, total_time = { 03, ci_double }, namelookup_time = { 04, ci_double }, connect_time = { 05, ci_double }, pretransfer_time = { 06, ci_double }, size_upload = { 07, ci_double }, size_download = { 08, ci_double }, speed_download = { 09, ci_double }, speed_upload = { 10, ci_double }, header_size = { 11, ci_long }, request_size = { 12, ci_long }, ssl_verifyresult = { 13, ci_long }, filetime = { 14, ci_long }, content_length_download = { 15, ci_double }, content_length_upload = { 16, ci_double }, starttransfer_time = { 17, ci_double }, content_type = { 18, ci_string }, redirect_time = { 19, ci_double }, redirect_count = { 20, ci_long }, private = { 21, ci_string }, http_connectcode = { 22, ci_long }, httpauth_avail = { 23, ci_long }, proxyauth_avail = { 24, ci_long }, os_errno = { 25, ci_long }, num_connects = { 26, ci_long }, ssl_engines = { 27, ci_slist }, cookielist = { 28, ci_slist }, lastsocket = { 29, ci_long }, ftp_entry_path = { 30, ci_string }, redirect_url = { 31, ci_string }, primary_ip = { 32, ci_string }, appconnect_time = { 33, ci_double }, certinfo = { 34, ci_slist }, condition_unmet = { 35, ci_long }, rtsp_session_id = { 36, ci_string }, rtsp_client_cseq = { 37, ci_long }, rtsp_server_cseq = { 38, ci_long }, rtsp_cseq_recv = { 39, ci_long }, primary_port = { 40, ci_long }, local_ip = { 41, ci_string }, local_port = { 42, ci_long }, tls_session = { 43, ci_slist } } ----------------------------------------------------------- -- Function Wrapping ----------------------------------------------------------- local opt_utils = {} local function version() return lib.curl_version() end local function easy_init() local handle = lib.curl_easy_init() if handle ~=nil then ffi.gc(handle, lib.curl_easy_cleanup) return handle end return false end local function easy_duphandle(handle) local duplicate = lib.curl_easy_duphandle(handle) if handle ~=nil then ffi.gc(handle, lib.curl_easy_cleanup) return handle end return false end local function easy_reset(handle) lib.curl_easy_reset(handle) end local function easy_perform(handle) return lib.curl_easy_perform(handle); end local function easy_setopt(handle, key, val) local data = curl_opt[key] if data then local opt_code = data[2][1] + data[1] local opt_util = opt_utils[key] if opt_util then val = opt_util(handle, val) end return lib.curl_easy_setopt(handle, opt_code, val) end end local function easy_getinfo(handle, key) local data = curl_info[key] if data then local info_code = data[2][1] + data[1] local info_type = data[2][2] local cast_func = data[2][3] local result = ffi.new(info_type) lib.curl_easy_getinfo(handle, info_code, result) if result[0] ~= nil then return cast_func(result[0]) end end end local function easy_escape(handle, url) local i_cstr = ffi.new('char[?]', #url, url) local o_cstr = lib.curl_easy_escape(handle, i_cstr, #url) local str = ffi.string(o_cstr) lib.curl_free(o_cstr) return str end local function easy_unescape(handle, url) local out_n = ffi.new('int[1]') -- int* local i_cstr = ffi.new('char[?]', #url, url) local o_cstr = lib.curl_easy_unescape(handle, i_cstr, #url, out_n) local str = ffi.string(o_cstr) lib.curl_free(o_cstr) return str end local function easy_strerror(code) local cstr = lib.curl_easy_strerror(code) return ffi.string(cstr) end ----------------------------------------------------------- -- OOP Wrapper ----------------------------------------------------------- local wrapper_mt = {} wrapper_mt.__index = wrapper_mt local function wrap(handle) local wrapper = { handle = handle } return setmetatable(wrapper, wrapper_mt) end local function init() return wrap(easy_init()) end function wrapper_mt:reset() easy_reset(self.handle) end function wrapper_mt:clone() return wrap(easy_duphandle(self.handle)) end function wrapper_mt:options(options) local e = {} for key, val in pairs(options) do local err = easy_setopt(self.handle, key, val) end end function wrapper_mt:perform(options) self:options(options) return easy_perform(self.handle) end function wrapper_mt:escape(url) return easy_escape(self.handle, url) end function wrapper_mt:unescape(url) return easy_unescape(self.handle, url) end info_mt = {} function info_mt:__index(key) return easy_getinfo(self.handle, key) end function wrapper_mt:info() local info = { handle = self.handle } return setmetatable(info, info_mt) end ----------------------------------------------------------- -- Option Utils ----------------------------------------------------------- function opt_utils.postfields(handle, post_data) if type(post_data) == 'string' then return post_data end if type(post_data) == 'table' then local fields = {} for k,v in pairs(post_data) do fields[#fields + 1] = k .. '=' .. v end return table.concat(fields, '&') end return '' end function opt_utils.writefunction(handle, callback) local type = 'size_t (*)(char*, size_t, size_t, void*)' return ffi.cast(type, callback) end function opt_utils.readfunction(handle, callback) local type = 'size_t (*)(void*, size_t, size_t, void*)' return ffi.cast(type, callback) end function opt_utils.headerfunction(handle, callback) local type = 'size_t (*)(void*, size_t, size_t, void*)' return ffi.cast(type, callback) end function opt_utils.progressfunction(handle, callback) local type = 'size_t (*)(void*, double, double, double, double)' return ffi.cast(type, callback) end ----------------------------------------------------------- -- Interface ----------------------------------------------------------- return { version = version; init = init; }
local red = require "resty.redis" local setmetatable = setmetatable local tonumber = tonumber local concat = table.concat local floor = math.floor local sleep = ngx.sleep local null = ngx.null local now = ngx.now local var = ngx.var local function enabled(val) if val == nil then return nil end return val == true or (val == "1" or val == "true" or val == "on") end local defaults = { prefix = var.session_redis_prefix or "sessions", socket = var.session_redis_socket, host = var.session_redis_host or "127.0.0.1", port = tonumber(var.session_redis_port) or 6379, auth = var.session_redis_auth, uselocking = enabled(var.session_redis_uselocking or true), spinlockwait = tonumber(var.session_redis_spinlockwait) or 10000, maxlockwait = tonumber(var.session_redis_maxlockwait) or 30, pool = { timeout = tonumber(var.session_redis_pool_timeout), size = tonumber(var.session_redis_pool_size) }, ssl = enabled(var.session_redis_ssl) or false, ssl_verify = enabled(var.session_redis_ssl_verify) or false, server_name = var.session_redis_server_name, } local redis = {} redis.__index = redis function redis.new(config) local r = config.redis or defaults local p = r.pool or defaults.pool local l = enabled(r.uselocking) if l == nil then l = defaults.uselocking end local self = { redis = red:new(), auth = r.auth or defaults.auth, encode = config.encoder.encode, decode = config.encoder.decode, delimiter = config.cookie.delimiter, prefix = r.prefix or defaults.prefix, uselocking = l, spinlockwait = tonumber(r.spinlockwait) or defaults.spinlockwait, maxlockwait = tonumber(r.maxlockwait) or defaults.maxlockwait, pool = { timeout = tonumber(p.timeout) or defaults.pool.timeout, size = tonumber(p.size) or defaults.pool.size }, connect_opts = { ssl = r.ssl or defaults.ssl, ssl_verify = r.ssl_verify or defaults.ssl_verify, server_name = r.server_name or defaults.server_name, }, } local s = r.socket or defaults.socket if s and s ~= "" then self.socket = s else self.host = r.host or defaults.host self.port = r.port or defaults.port end return setmetatable(self, redis) end function redis:connect() local r = self.redis local ok, err if self.socket then ok, err = r:connect(self.socket) else ok, err = r:connect(self.host, self.port, self.connect_opts) end if ok and self.auth and self.auth ~= "" then ok, err = r:get_reused_times() if ok == 0 then ok, err = r:auth(self.auth) end end return ok, err end function redis:set_keepalive() local pool = self.pool local timeout, size = pool.timeout, pool.size if timeout and size then return self.redis:set_keepalive(timeout, size) end if timeout then return self.redis:set_keepalive(timeout) end return self.redis:set_keepalive() end function redis:key(i) return concat({ self.prefix, self.encode(i) }, ":" ) end function redis:lock(k) if not self.uselocking then return true, nil end local s = self.spinlockwait local m = self.maxlockwait local w = s / 1000000 local r = self.redis local i = 1000000 / s * m local l = concat({ k, "lock" }, "." ) for _ = 1, i do local ok = r:setnx(l, "1") if ok then return r:expire(l, m + 1) end sleep(w) end return false, "no lock" end function redis:unlock(k) if self.uselocking then return self.redis:del(concat({ k, "lock" }, "." )) end return true, nil end function redis:get(k) local d = self.redis:get(k) return d ~= null and d or nil end function redis:set(k, d, l) return self.redis:setex(k, l, d) end function redis:expire(k, l) self.redis:expire(k, l) end function redis:delete(k) self.redis:del(k) end function redis:cookie(c) local r, d = {}, self.delimiter local i, p, s, e = 1, 1, c:find(d, 1, true) while s do if i > 2 then return nil end r[i] = c:sub(p, e - 1) i, p = i + 1, e + 1 s, e = c:find(d, p, true) end if i ~= 3 then return nil end r[3] = c:sub(p) return r end function redis:open(cookie, lifetime) local c = self:cookie(cookie) if c and c[1] and c[2] and c[3] then local ok, err = self:connect() if ok then local i, e, h = self.decode(c[1]), tonumber(c[2]), self.decode(c[3]) local k = self:key(i) ok, err = self:lock(k) if ok then local d = self:get(k) if d then self:expire(k, floor(lifetime)) end self:unlock(k) self:set_keepalive() return i, e, d, h end self:set_keepalive() return nil, err else return nil, err end end return nil, "invalid" end function redis:start(i) local ok, err = self:connect() if ok then ok, err = self:lock(self:key(i)) self:set_keepalive() end return ok, err end function redis:save(i, e, d, h, close) local ok, err = self:connect() if ok then local l, k = floor(e - now()), self:key(i) if l > 0 then ok, err = self:set(k, d, l) if close then self:unlock(k) end self:set_keepalive() if ok then return concat({ self.encode(i), e, self.encode(h) }, self.delimiter) end return ok, err end if close then self:unlock(k) self:set_keepalive() end return nil, "expired" end return ok, err end function redis:close(i) local ok, err = self:connect() if ok then local k = self:key(i) self:unlock(k) self:set_keepalive() end return ok, err end function redis:destroy(i) local ok, err = self:connect() if ok then local k = self:key(i) self:delete(k) self:unlock(k) self:set_keepalive() end return ok, err end function redis:ttl(i, ttl) local k = self:key(i) return self:expire(k, floor(ttl)) end return redis
--[[ A top-down action game made with Bitty Engine Copyright (C) 2021 Tony Wang, all rights reserved Engine page: https://paladin-t.github.io/bitty/ Game page: https://paladin-t.github.io/games/hb/ ]] Melee = class({ --[[ Variables. ]] _shape = nil, _affecting = false, _isBlade = false, _preInterval = 0.05, _postInterval = 0.05, --[[ Constructor. ]] ctor = function (self, isBlocked, options) Weapon.ctor(self, isBlocked, options) self._color = Color.new(255, 0, 0) local cfg = Weapons[options.type] self._shape = cfg['shape'] self._isBlade = cfg['blade'] self._preInterval, self._postInterval = cfg['pre_interval'], cfg['post_interval'] end, --[[ Meta methods. ]] __tostring = function (self) return 'Melee' end, --[[ Methods. ]] isMelee = function (self) return true end, isBlade = function (self) return self._isBlade end, interval = function (self) return self._interval + self._preInterval + self._postInterval, self._preInterval, self._interval, self._postInterval end, affecting = function (self) if not self._affecting then return false, nil end local shape = nil if self._shape['type'] == 'circle' then shape = Vec3.new(self.x, self.y, self._shape['r']) end return true, shape end, -- Attacks with this melee itself. -- returns success, emitted bullet (always nil), out of bullet (always false), recoil (always nil). attack = function (self, dir, _3, _4, _5) -- Check for cooldown interval. local now = DateTime.ticks() if self._timestamp ~= nil then local diff = now - self._timestamp diff = DateTime.toSeconds(diff) if diff < self._interval then return false, nil, false, nil end end self._timestamp = now -- Add effect. if self._effect ~= nil then local fx = self._effect(self.x, self.y, self._facing, self._spriteAngle) if fx ~= nil then self:_emit(fx) end end -- Finish. return true, nil, false, nil end, behave = function (self, delta, hero) if self._timestamp ~= nil then local now = DateTime.ticks() local diff = now - self._timestamp diff = DateTime.toSeconds(diff) if diff < self._preInterval then self._affecting = false elseif diff < self._interval - self._postInterval then self._affecting = true elseif diff < self._interval then self._affecting = false else self._timestamp = nil end end Weapon.behave(self, delta, hero) return self end, update = function (self, delta) Weapon.update(self, delta) if DEBUG_SHOW_WIREFRAME then if self._affecting then if self._shape['type'] == 'circle' then circ( self.x, self.y, self._shape['r'], false, self._color ) end end end end }, Weapon)
CreateConVar("karma_tracker_debug", 0, 1, "Print debug messages to console.") local enableDebugLogging = GetConVar("karma_tracker_debug"):GetBool() function print_debug(...) if (enableDebugLogging) then print("[Karma Tracker]", ...) end end
--- Define an object Share. --- @class Share Share = {} Share.__index = Share --- The constructor of the object Share --- @return Share The new Share just created with the table of available services function Share:new() return setmetatable({services = {}}, Share) end --- This method inserts a service into the table of available services --- @param s Service The service to add function Share:attach(s) if (getmetatable(s) == Service) and (not self:is_present(s, self.services)) then table.insert(self.services, s) end end --- This method removes a service from the table of available services --- @param s Service The service to remove function Share:detach(s) if (getmetatable(s) == Service) and self:is_present(s, self.services) then for i, k in pairs(self.services) do if (s == k) then table.remove(self.services, i) end end end end --- This method search a service from the services table and returns true if it finds an occurrence --- @param s Service The service to search --- @param t table The table on which doing the search --- @return boolean True if the service is present, false otherwise function Share:is_present(s, t) for _, k in pairs(t) do if (s == k) then return true end end return false end function Share:mobile_app() local result = {} -- ip = net.service.mdns.resolvehost("whitecat-share") local ip_list = {"localhost", "192.168.1.9","192.168.1.10"} for _, ip in pairs(ip_list) do self:open_udp_mobile(ip, result) end return result end function Share:discovery(macro_mib) local result = {} -- ip = net.service.mdns.resolvehost("whitecat-share") local ip_list = {"localhost","192.168.1.9","192.168.1.10"} for _, ip in pairs(ip_list) do self:open_udp_socket(ip, macro_mib, result) end return result end --- Internal function that retrieve the set of services with the corresponding prefix --- @param macro_mib string The prefix of the mib to search --- @return table The set of corresponding services function Share:find(macro_mib) if #self.services == 0 then return 0 end local saved = {} for _, k in pairs(self.services) do if (k.name:match(macro_mib)) then table.insert(saved, k.name) end end if #saved == 0 then return 0 else return saved end end function Share:find_all() if #self.services == 0 then return "{}" end local tab = {} for i, k in pairs(self.services) do table.insert(tab, k.name) end return tab end function Share:open_udp_mobile(ip, result) local socket = require("socket") local udp_mobile = socket.udp() udp_mobile:setpeername(ip, 7878) udp_mobile:settimeout(5) udp_mobile:send("\n") local data_mib = udp_mobile:receive() if (data_mib and not (data_mib == "{}")) then pcall(load("mib_tab = " .. data_mib)) local ip_tab = {} table.insert(ip_tab, ip) Utilities:add_new_ip(ip_tab, result, ip, mib_tab) end udp_mobile:close() end --- Internal function used to establish a remote connection with udp socket --- @param ip string The ip of the remote device --- @param macro_mib string MIB of the service owned by the remote service --- @param result table The table used to save all results function Share:open_udp_socket(ip, macro_mib, result) local socket = require("socket") local udp_discovery = socket.udp() -- local udp = socket.udp() udp_discovery:setpeername(ip, 9898) udp_discovery:settimeout(2) udp_discovery:send(macro_mib) local data_mib = udp_discovery:receive() -- udp:setsockname("*", 9898) -- local data_mib, ip_mib, port_mib = udp:receivefrom() if (data_mib and not (data_mib == "{}")) then pcall(load("mib_tab = " .. data_mib)) local ip_tab = {} table.insert(ip_tab, ip) Utilities:add_new_ip(ip_tab, result, ip, mib_tab) end -- udp:close() udp_discovery:close() end
function Populater(level, map) local spawnedPrism = false local treasureRoom = false local store = false local toSpawn = {} local roomsLeft = #map._rooms - 1 -- subtract the starting room local doors = {} local function hash(x, y) return x and y * 0x4000000 + x or false -- 26-bit x and y end local function spawnActor(room, actor, x, y) local _x, _y = room:getRandomWalkableTile() local x, y = x or _x, y or _y actor.position.x = x actor.position.y = y level:addActor(actor) end local function moveActorToRoom(room, actor) local x, y = room:getRandomWalkableTile() actor.position.x = x actor.position.y = y end local function spawnDoors(room) for _, x, y in room._doors:each() do if not doors[hash(x, y)] and math.random() > 0.50 then local door = actors.Door() door.position.x = x door.position.y = y level:addActor(door) doors[hash(x,y)] = true end end end local function spawnShards(room, i, j) for i = 1, love.math.random(i, j) do spawnActor(room, actors.Shard()) end end local function spawnShrooms(room, i, j) for i = 1, love.math.random(i, j) do spawnActor(room, actors.Glowshroom()) end end local function populateStartRoom(room) spawnDoors(room) spawnActor(room, game.Player) spawnActor(room, actors.Box()) spawnActor(room, actors.Snip()) -- spawnActor(room, actors.Gazer()) end local chestContents = { actors.Ring_of_protection, actors.Ring_of_vitality, actors.Armor, actors.Cloak_of_invisibility, actors.Slippers_of_swiftness, actors.Wand_of_lethargy, actors.Wand_of_swapping, actors.Wand_of_fireball, actors.Wand_of_displacement, actors.Dagger_of_venom } local function populateShopRoom(room) local shop = actors.Shopkeep() shop.position.x, shop.position.y = room:getCenterTile() shop.position.x = shop.position.x - 3 level:addActor(shop) local torch = actors.Stationarytorch() torch.position.x, torch.position.y = shop.position.x, shop.position.y torch.position.x = shop.position.x - 1 level:addActor(torch) local shopItems = { { components.Weapon, components.Wand }, { components.Equipment }, { components.Edible, components.Drinkable, components.Readable } } for i = 1, 3 do local itemTable =shopItems[i] local item = Loot.generateLoot(itemTable[love.math.random(1, #itemTable)]) local product = actors.Product() product.position.x = shop.position.x + i*2 product.position.y = shop.position.y product:setItem(item) product:setPrice(actors.Shard, item.cost) product:setShopkeep(shop) level:addActor(product) end end local function populateTreasureRoom(room) treasureRoom = true local locked = false if roomsLeft <= #toSpawn then locked = false elseif love.math.random() > .5 then locked = true end local chest = actors.Chest() local key = actors.Key() table.insert(chest.inventory, chestContents[math.random(#chestContents)]()) chest:setKey(key) spawnActor(room, chest) table.insert(toSpawn, key) spawnShards(room, 3, 10) end local function populateSpiderRoom(room) spawnActor(room, actors.Webweaver()) end local function populateRoom(room) if #room._doors == 2 and not treasureRoom then populateTreasureRoom(room) return end if not store and love.math.random(1, roomsLeft)/roomsLeft > 0.6 then store = true populateShopRoom(room) return end if roomsLeft <= #toSpawn and not (#toSpawn == 0) then local actor = table.remove(toSpawn, 1) spawnActor(room, actor) room.actors = room.actors or {} table.insert(room.actors, actor) if math.random() > 0.50 then populateSpiderRoom(room) end return end if false then spawnShards(room, 2, 4) spawnShrooms(room, 0, 2) spawnActor(room, actors.Snip()) spawnActor(room, actors.Snip()) spawnActor(room, actors.Snip()) return end spawnShards(room, 0, 2) spawnShrooms(room, 0, 2) spawnActor(room, actors.Sqeeto()) spawnActor(room, actors.Gloop()) end table.insert(toSpawn, actors.Prism()) table.insert(toSpawn, actors.Stairs()) local startRoom = table.remove(map._rooms, love.math.random(1, #map._rooms)) for _, room in ipairs(map._rooms) do roomsLeft = roomsLeft - 1 populateRoom(room) end populateStartRoom(startRoom) end return Populater
object_mobile_greck_thug_m_04 = object_mobile_shared_greck_thug_m_04:new { } ObjectTemplates:addTemplate(object_mobile_greck_thug_m_04, "object/mobile/greck_thug_m_04.iff")
local CHIP_DATA = require "defs.chip_data_defs" local GENERIC_DEFS = require "defs.generic_defs" local gauntlet_data = require "gauntlet_data" local deepcopy = require "deepcopy" local CHIP = require "defs.chip_defs" local CHIP_ID = require "defs.chip_id_defs" local CHIP_CODE = require "defs.chip_code_defs" local randomchoice_key = require "randomchoice_key" local DRAFT_STANDARD_MEGA_GIGA = {} local standard_chips = {} local mega_chips = {} local giga_chips = {} function DRAFT_STANDARD_MEGA_GIGA.random_chip_generator(chip_index) if chip_index == 10 or chip_index == 20 then return CHIP.new_chip_with_random_code(randomchoice_key(mega_chips, "DRAFTING")) elseif chip_index == 30 then return CHIP.new_chip_with_random_code(randomchoice_key(giga_chips, "DRAFTING")) else return CHIP.new_chip_with_random_code(randomchoice_key(standard_chips, "DRAFTING")) end end function DRAFT_STANDARD_MEGA_GIGA.activate() gauntlet_data.folder_draft_chip_list = {} for key, value in pairs(CHIP_DATA) do if (value.CHIP_RANKING % 4) == 0 then standard_chips[key] = value elseif (value.CHIP_RANKING % 4) == 1 then mega_chips[key] = value elseif (value.CHIP_RANKING % 4) == 2 then giga_chips[key] = value end end -- Add all combination of chips and codes. --[[for key, id in pairs(CHIP_ID) do for key2, code in pairs(CHIP_CODE) do local new_chip = { ID = id, CODE = code } gauntlet_data.folder_draft_chip_list[#gauntlet_data.folder_draft_chip_list + 1] = new_chip end end]] gauntlet_data.current_folder = {} gauntlet_data.current_state = gauntlet_data.GAME_STATE.TRANSITION_TO_DRAFT_FOLDER gauntlet_data.folder_draft_chip_generator = DRAFT_STANDARD_MEGA_GIGA.random_chip_generator print("Draft S/M/G - Patched folder.") --print("Length of folder draft chip list:", #gauntlet_data.folder_draft_chip_list) end DRAFT_STANDARD_MEGA_GIGA.NAME = "Draft Folder (Mixed)" DRAFT_STANDARD_MEGA_GIGA.DESCRIPTION = "You pick 30 Chips for your folder!\n(27 Standard, 2 Mega, 1 Giga)!" return DRAFT_STANDARD_MEGA_GIGA
ITEM.name = "Browning Hi-Power" ITEM.description= "A semi-automatic pistol chambered for 9x19mm." ITEM.longdesc = "The Browning Hi-Power pistol is product of the French military requesting a new service pistol.\nThe Hi-Power name alludes to the 13-round magazine capacity, almost twice that of contemporary designs such as the Luger or Colt M1911.\nIt has been widely used throughout history, mainly in the second world war by both the Axis and the Allied forces.\nWhen the war ended, over 50 armies adopted it as their service pistol.\n\nAmmo: 9x19mm\nMagazine Capacity: 13" ITEM.model = "models/weapons/w_pist_brhp.mdl" ITEM.class = "cw_brhp" ITEM.weaponCategory = "secondary" ITEM.price = 1200 ITEM.width = 2 ITEM.height = 1 ITEM.validAttachments = {"md_microt1","md_eotech","md_rmr","md_tundra9mm"} ITEM.bulletweight = 0.008 ITEM.unloadedweight = 1.01 ITEM.repair_PartsComplexity = 2 ITEM.repair_PartsRarity = 2 function ITEM:GetWeight() return self.unloadedweight + (self.bulletweight * self:GetData("ammo", 0)) end ITEM.exRender = false ITEM.img = ix.util.GetMaterial("vgui/hud/weapons/brhp.png") ITEM.pacData = { [1] = { ["children"] = { [1] = { ["children"] = { [1] = { ["children"] = { }, ["self"] = { ["Model"] = "models/weapons/w_pist_brhp.mdl", ["ClassName"] = "model", ["Position"] = Vector(-6.918, 3.162, 3.067), ["EditorExpand"] = true, ["UniqueID"] = "3543276491", ["Bone"] = "pelvis", ["Name"] = "brhp", ["Angles"] = Angle(-30, 180, 0), }, }, }, ["self"] = { ["AffectChildrenOnly"] = true, ["ClassName"] = "event", ["UniqueID"] = "1016812402", ["Event"] = "weapon_class", ["EditorExpand"] = true, ["Name"] = "weapon class find simple\"@@1\"", ["Arguments"] = "cw_brhp@@0", }, }, }, ["self"] = { ["ClassName"] = "group", ["UniqueID"] = "1118321183", ["EditorExpand"] = true, }, }, }
local wibox = require('wibox') local mat_list_item = require('widgets.mat-list-item') local mat_slider = require('widgets.mat-slider') local icons = require('theme.icons') local watch = require('awful.widget.watch') local dpi = require('beautiful').xresources.apply_dpi local total_prev = 0 local idle_prev = 0 local slider = wibox.widget { read_only = true, widget = mat_slider } watch( --'bash -c "free | grep -z Mem.*Swap.*"', 'bash -c "free | grep -z Mem."', 1, function(widget, stdout, stderr, exitreason, exitcode) total, used, free, shared, buff_cache, available, total_swap, used_swap, free_swap = stdout:match('(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*(%d+)%s*Swap:%s*(%d+)%s*(%d+)%s*(%d+)') slider:set_value(used / total * 100) collectgarbage('collect') end ) local ram_meter = wibox.widget { wibox.widget { wibox.widget { image = icons.memory, widget = wibox.widget.imagebox }, margins = dpi(12), widget = wibox.container.margin }, slider, widget = mat_list_item } return ram_meter
-------------------------------------------------------------------------------- -- Lua client for the DomRobot XML-RPC API. -- https://github.com/boethin/inwx-lua -- -- Copyright (c) 2015 Sebastian Böthin <[email protected]> -------------------------------------------------------------------------------- -- Sample client. -- -- namespace DomRobot. -- Make sure the path is found by lua. local DomRobot = { API = require "DomRobot/API", Client = require "DomRobot/Client" } -- SSL parameters. -- See: https://github.com/brunoos/luasec/wiki local SSLParams = { mode = "client", protocol = "sslv23", cafile = "/etc/ssl/certs/ca-certificates.crt", verify = "peer", options = "all", } -- OT&E API request parameters (Testing) -- ==> Insert your OT&E username/password <== local OTE_creds = { host = "api.ote.domrobot.com", user = "[ username here ]", pass = "[ password here ]", lang = "en" } --[[ -- API request parameters (Production) -- local PROD_creds = { host = "api.domrobot.com", user = "[ username here ]", pass = "[ password here ]", lang = "en" } --]] -- Set to PROD_creds in order to access production environment. local creds = OTE_creds -- Save authentication cookie (make tsure the path is writable). -- ==> Remove the file when the cookie is expired. <== local authFile = creds.host..".txt" -- Create API client instance. local api = DomRobot.API(DomRobot.Client(DomRobot.API,creds.host,SSLParams)) -- Authenticate or load cookie file api:persistentLogin(authFile,creds.user,creds.pass,creds.lang) local ok, res -------------------------------------------------------------------------------- -- Example: -- Request account.info() to see if it works. ok, res = api.account:info() if ok then -- request successful: assert(res.resData.email) print("request ok: your email is:", res.resData.email) else -- request failed for i, v in pairs(res) do print ('\t', i, v) end end -------------------------------------------------------------------------------- -- Example: -- Check some domains for availabilty. -- unpack() Lua table to send XML-RPC array -- DOES NOT WORK PROPERLY ok, res = api.domain:check( { domain = unpack({ "example.net", "example.global", "foo.bar" }) } ) if ok then -- request successful: assert(type(res.resData.domain) == "table") for i, v in pairs(res.resData.domain) do print ('\t', i, v.domain,v.avail,v.status ) end else -- request failed for i, v in pairs(res) do print ('\t', i, v) end end
-------------------------------------------------------------------------------- -- БАРС для 81-722 -------------------------------------------------------------------------------- Metrostroi.DefineSystem("81_722_BARS") TRAIN_SYSTEM.DontAccelerateSimulation = true function TRAIN_SYSTEM:Initialize() self.Train:LoadSystem("ALSCoil") self.Power = 0 self.ARSPower = 0 -- Internal state self.Active = 0 self.SpeedLimit = 0 self.NextLimit = 0 self.Ring = 0 self.Overspeed = false self.Brake = false self.Brake2 = false self.Drive = false self.Braking = false self.PN1 = 0 self.PN2 = 0 self.RVTB = 0 self.NoFreq = 0 self.F1 = 0 self.F2 = 0 self.F3 = 0 self.F4 = 0 self.F5 = 0 self.F6 = 0 end function TRAIN_SYSTEM:Outputs() return {"Active","Ring","Brake","Brake2","Drive","PN1","PN2", "SpeedLimit", "RVTB"} end function TRAIN_SYSTEM:Inputs() return {"NoFreq","F1","F2","F3","F4","F5","F6"} end function TRAIN_SYSTEM:TriggerInput(name,value) end function TRAIN_SYSTEM:Think(dT) local Train = self.Train local ALS = Train.ALSCoil local speed = ALS.Speed local Power = self.Power local EnableALS = Power and Train.ALS.Value > 0.5-- and Train.BUKP.Active > 0 if EnableALS ~= (ALS.Enabled==1) then ALS:TriggerInput("Enable",EnableALS and 1 or 0) end self.NoFreq = ALS.NoFreq self.F1 = ALS.F1 self.F2 = ALS.F2 self.F3 = ALS.F3 self.F4 = ALS.F4 self.F5 = ALS.F5 self.F6 = ALS.F6 self.RealF5 = self.F5*(1-self.F6) if (self.F1+self.F2+self.F3+self.F4+self.F5+self.F6) == 0 then self.NoFreq = 1 end -- Speed check and update speed data if CurTime() - (self.LastSpeedCheck or 0) > 0.5 then self.LastSpeedCheck = CurTime() end -- ARS system placeholder logic self.KVT = (Train.PB.Value > 0.5 or Train.Vigilance.Value > 0.5)-- and not self.PBBlock --[[if self.PBBlock == nil and self.NoFreq then self.PBBlock = Train.PB.Value > 0.5 or Train.Vigilance.Value > 0.5 end if self.PBBlock and Train.PB.Value < 0.5 and Train.Vigilance.Value < 0.5 then self.PBBlock = false end if self.PBBlock ~= nil and not self.NoFreq then self.PBBlock = nil end]] local Active = Power and self.ARSPower if self.KVT and not self.AttentionPedalTimer then self.AttentionPedalTimer = CurTime() + 1 end if self.KVT and self.AttentionPedalTimer and (CurTime() - self.AttentionPedalTimer) > 0 then self.AttentionPedal = true end if not self.KVT and (self.AttentionPedalTimer or self.AttentionPedal) then self.AttentionPedal = false self.AttentionPedalTimer = nil end if EnableALS then local V = math.floor(speed +0.05) local Vlimit = 0 if self.F4 then Vlimit = 40 end if self.F3 then Vlimit = 60 end if self.F2 then Vlimit = 70 end if self.F1 then Vlimit = 80 end --if ( self.KVT) and (Vlimit ~= 0) and (V > Vlimit) then self.Overspeed = true end --if ( self.KVT) and (Vlimit == 0) and (V > 20) then self.Overspeed = true end --if (not self.KVT) and (V > Vlimit) and (V > (self.RealNoFreq and 0 or 3)) then self.Overspeed = true end --if ( self.KVT) and (Vlimit == 0) and self.Train.ARSType and self.Train.ARSType == 3 and not self.Train["PA-KSD"].VRD then self.Overspeed = true end --self.Ring = self.Overspeed and (speed > 5) -- Determine next limit and current limit self.SpeedLimit = Vlimit+0.5 self.NextLimit = Vlimit if self.F1 then self.NextLimit = 80 end if self.F2 then self.NextLimit = 70 end if self.F3 then self.NextLimit = 60 end if self.F4 then self.NextLimit = 40 end if self.F5 then self.NextLimit = 20 end else local V = math.floor(speed +0.05) self.SpeedLimit = 0 self.NextLimit = 0 end if Active then if Train.Pneumatic.RVTBLeak == 0 then self.RVTB = 1 end if self.Starting and CurTime() - self.Starting > 7 then if speed > 7 then self.Starting = nil else self.Starting = false end end if speed < 0.1 and self.Starting == false and self.KVT then self.Starting = nil end local Drive = self.Drive > 0 local Brake = self.Brake > 0 local Brake2 = self.Brake2 > 0 local SpeedLimit = self.SpeedLimit if self.SpeedLimit < 20 then SpeedLimit = 20 end if self.AttentionPedal or Train.VRD.Value > 0.5 then SpeedLimit = 20 end if speed > SpeedLimit or (self.Starting == false or self.Starting and CurTime() - self.Starting > 7) --or (self.F1 or self.F2 or self.F3 or self.F4) and self.KVT and speed > 20 or not EnableALS and not self.NoFreq or (self.NoFreq) and not self.KVT or not self.NoFreq and self.RealF5 and (not self.KVT or not self.F6 and not self.VRD) or self.Braking and not Brake then if not Brake and self.SpeedLimit > 20 then self.Braking = true end if not Brake and (self.SpeedLimit > 20 or speed > 0.1) then self.Ringing = true end Brake = true elseif speed < SpeedLimit and not self.Braking then Brake = false Brake2 = false end if (self.Braking or self.Ringing) and self.KVT and (self.NoFreq or EnableALS) then self.Braking = false self.Ringing = false end if self.Ringing and self.KVT then self.Ringing = false end if self.Ringing then self.RVTB = 0 end if speed < 3 and self.PN1 == 0 and Train.BUKP.PowerCommand <= 0 then self.PN1 = 1 self.PN2Timer = CurTime() if self.Starting then self.Starting = nil end end if (Train.BUKP.PowerCommand > 0.1 or self.NoFreq and self.KVT) and self.PN1 > 0 then if not self.Starting and not self.NoFreq then self.Starting = CurTime() end self.PN1 = 0 end if self.PN1 > 0 and (--[[ Train.BUKP.PN2 > 0 or --]] self.PN2Timer and CurTime()-self.PN2Timer > 1) and self.PN2 == 0 then self.PN2 = 1 self.PN2Timer = nil end if self.PN1 < 1 then self.PN2 = 0 end if self.BPSArmed then self.PN2 = 1 end if Brake and not Brake2 and not self.Brake2Timer then self.Brake2Timer = CurTime() end if Brake and not Brake2 and self.Brake2Timer and CurTime() - self.Brake2Timer > 1.5 then self.Brake2Timer = nil Brake2 = true end if not Brake and (Brake2 or self.Brake2Timer) then self.Brake2Timer = nil Brake2 = false end if Train.VRD.Value > 0.5 and self.RealF5 and self.VRD == nil then self.VRD = false end if (Train.VRD.Value < 0.5 or not self.RealF5) and self.VRD ~= nil then self.VRD = nil end if self.VRD == false and speed <= 0.1 then self.VRD = true end --[[ self.BPSMeter = self.BPSMeter or 0 if Train.Speed*Train.SpeedSign < 0 or self.BPSMeter < 0 then self.BPSMeter = self.BPSMeter + math.min(0,Train.Speed*Train.SpeedSign*1000/3600)*dT if Train.Speed*Train.SpeedSign > 0.1 then self.BPSMeter = 0 end if -self.BPSMeter > 1.5 then self.BPSArmed = true end end if Train.BUV.Reverser == 0 and self.BPSArmed then self.BPSArmed = nil end--]] --speed >= SpeedLimit-3 and (Train.BUKP.PowerCommand > 5 or Train:ReadTrainWire(19) > 0) or self.DriveOff = speed >= SpeedLimit-2 Drive = not self.DriveOff and ( not self.NoFreq and EnableALS and self.RealF5 and self.KVT and (self.F6 or self.VRD) or (self.NoFreq or not EnableALS) and self.KVT or not self.NoFreq and EnableALS and not self.RealF5 ) and not Brake and not self.BPSArmed self.Ring = self.Ringing and 1 or 0 self.Brake = Brake and 1 or 0 self.Brake2 = Brake2 and 1 or 0 self.Drive = Drive and 1 or 0 if self.RVTBReset then self.RVTB = 1 self.RVTBReset = false end else if self.RVTB == 0 and not self.RVTBReset then if not self.RVTBResetTimer then self.RVTBResetTimer = CurTime() end end if not self.RVTBReset and self.RVTB == 1 or self.RVTBResetTimer and CurTime()-self.RVTBResetTimer > 3 then self.RVTBReset = trueя self.RVTBResetTimer = nil end self.RVTB = (self.KVT or Train.VAH.Value > 0.5) and 1 or 0 self.Brake = 0 self.Brake2 = 0 self.Brake2Timer = nil self.Drive = 0 self.Ring = 0 self.PN1 = 0 self.PN2 = Train.RCARS.Value*Train.BUKP.Active self.Starting = nil self.Braking = true self.Ringing = true self.BPSArmed = nil end self.Active = Active and 1 or 0 end
--[[ Copyright 2019 Manticore Games, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] -- Internal custom properties local COMPONENT_ROOT = script:GetCustomProperty("ComponentRoot"):WaitForObject() local ROTATION_ROOT = script:GetCustomProperty("RotationRoot"):WaitForObject() local TRIGGER = script:GetCustomProperty("Trigger"):WaitForObject() local LOOT_ITEM_SPAWN_POINT = script:GetCustomProperty("LootItemSpawnPoint"):WaitForObject() -- User exposed properties local OPEN_ONCE = COMPONENT_ROOT:GetCustomProperty("OpenOnce") local SPEED = COMPONENT_ROOT:GetCustomProperty("Speed") local OPEN_LABEL = COMPONENT_ROOT:GetCustomProperty("OpenLabel") local CLOSE_LABEL = COMPONENT_ROOT:GetCustomProperty("CloseLabel") local LOOT_ITEM = COMPONENT_ROOT:GetCustomProperty("LootItem") local RESET_ON_ROUND_START = COMPONENT_ROOT:GetCustomProperty("ResetOnRoundStart") -- Check user properties if SPEED <= 0.0 then warn("Speed must be positive") SPEED = 450.0 end -- Constants local USE_DEBOUNCE_TIME = 0.2 -- Time after using that a player can't use again -- Variables -- Rotation is 1.0 for +90 degree rotation, 0.0 for closed, -1.0, for -90 degree rotation local targetDoorRotation = 0.0 local playerLastUseTimes = {} -- Player -> float -- float GetChestLidRotation() -- Gives you the current rotation of the chest lid function GetChestLidRotation() return ROTATION_ROOT:GetRotation().x / 90.0 end -- nil SetCurrentRotation(float) -- Snap instantly to the given rotation function SetCurrentRotation(rotation) targetDoorRotation = rotation ROTATION_ROOT:SetRotation(Rotation.New(90.0 * rotation, 0.0, 0.0)) end -- nil SetTargetRotation(float) -- Sets the rotation that the chest lid should move to (at SPEED) function SetTargetRotation(rotation) targetDoorRotation = rotation ROTATION_ROOT:RotateTo(Rotation.New(90.0 * rotation, 0.0, 0.0), 90.0 * math.abs(targetDoorRotation - GetChestLidRotation()) / SPEED, true) end -- nil ResetChestLid() -- Instantly snaps the chest to the closed state function ResetChestLid() SetCurrentRotation(0.0) TRIGGER.isInteractable = true end -- nil OpenChestLid() -- Opens the chest with loot item spawn function OpenChestLid() SetTargetRotation(1.0) if LOOT_ITEM then World.SpawnAsset(LOOT_ITEM, {position = LOOT_ITEM_SPAWN_POINT:GetWorldPosition()}) end end -- nil CloseChestLid() -- Closes the door, even if it was only partially open function CloseChestLid() SetTargetRotation(0.0) end -- nil OnInteracted(Trigger, CoreObject) -- Handles the player using the chest function OnInteracted(trigger, player) if playerLastUseTimes[player] and playerLastUseTimes[player] + USE_DEBOUNCE_TIME > time() then return end playerLastUseTimes[player] = time() if GetChestLidRotation() == 0.0 then -- Chest is closed OpenChestLid(player) if OPEN_ONCE then TRIGGER.isInteractable = false -- Resets interactivity if RESET_ON_ROUND_START is true end TRIGGER.interactionLabel = CLOSE_LABEL else -- Chest is open or moving, clsoe it CloseChestLid() end end -- nil OnRoundStart() -- Handles the roundStartEvent function OnRoundStart() ResetChestLid() end -- nil Tick(float) -- Handle closing the chest lid function Tick(deltaTime) if targetDoorRotation == 0.0 and GetChestLidRotation() == 0.0 then TRIGGER.interactionLabel = OPEN_LABEL Events.Broadcast("ChestClosed", COMPONENT_ROOT) end end -- Initialize TRIGGER.interactedEvent:Connect(OnInteracted) if RESET_ON_ROUND_START then Game.roundStartEvent:Connect(OnRoundStart) end
project "assimp" kind "StaticLib" language "C++" cppdialect "C++17" systemversion "latest" staticruntime "On" targetdir ("bin/" .. outputdir .. "/%{prj.name}") objdir ("inter/" .. outputdir .. "/%{prj.name}") warnings "Off" defines { -- For more info on the formats: http://assimp.sourceforge.net/main_features_formats.html -- Also check ImporterRegistry.cpp for all the macro guards -- Uncomment to build importers -- Comment to stop building them "ASSIMP_BUILD_NO_X_IMPORTER", -- DirectX X "ASSIMP_BUILD_NO_AMF_IMPORTER", -- "ASSIMP_BUILD_NO_3DS_IMPORTER", -- 3ds Max 3DS -- "ASSIMP_BUILD_NO_MDL_IMPORTER", -- Quake I -- "ASSIMP_BUILD_NO_MD2_IMPORTER", -- Quake II -- "ASSIMP_BUILD_NO_MD3_IMPORTER", -- Quake III "ASSIMP_BUILD_NO_PLY_IMPORTER", -- Stanford Polygon Library -- "ASSIMP_BUILD_NO_ASE_IMPORTER", -- 3ds Max ASE ( .ase ) -- "ASSIMP_BUILD_NO_OBJ_IMPORTER", -- obj "ASSIMP_BUILD_NO_HMP_IMPORTER", -- 3D GameStudio (3DGS) Terrain "ASSIMP_BUILD_NO_SMD_IMPORTER", -- Valve Model ( .smd,.vta ) "ASSIMP_BUILD_NO_MDC_IMPORTER", -- Return to Castle Wolfenstein ( .mdc ) -- "ASSIMP_BUILD_NO_MD5_IMPORTER", -- Doom 3 ( .md5* ) "ASSIMP_BUILD_NO_STL_IMPORTER", -- Stereolithography "ASSIMP_BUILD_NO_LWO_IMPORTER", -- LightWave "ASSIMP_BUILD_NO_DXF_IMPORTER", -- AutoCad DXF "ASSIMP_BUILD_NO_NFF_IMPORTER", -- Neutral File Format / Sense8 WorldToolKit "ASSIMP_BUILD_NO_RAW_IMPORTER", -- PovRAY Raw "ASSIMP_BUILD_NO_SIB_IMPORTER", -- ?? "ASSIMP_BUILD_NO_OFF_IMPORTER", -- Object File Format "ASSIMP_BUILD_NO_AC_IMPORTER", -- AC3D "ASSIMP_BUILD_NO_BVH_IMPORTER", -- Biovision "ASSIMP_BUILD_NO_IRRMESH_IMPORTER", -- Irrlicht Mesh "ASSIMP_BUILD_NO_IRR_IMPORTER", -- Irrlicht Scene "ASSIMP_BUILD_NO_Q3D_IMPORTER", -- Quick3D "ASSIMP_BUILD_NO_B3D_IMPORTER", -- BlitzBasic 3D -- "ASSIMP_BUILD_NO_COLLADA_IMPORTER", -- Collada ( .dae ) "ASSIMP_BUILD_NO_TERRAGEN_IMPORTER", -- Terragen Terrain ( .ter ) "ASSIMP_BUILD_NO_CSM_IMPORTER", -- CharacterStudio Motion "ASSIMP_BUILD_NO_3D_IMPORTER", -- ?? "ASSIMP_BUILD_NO_LWS_IMPORTER", -- LightWave Scene "ASSIMP_BUILD_NO_OGRE_IMPORTER", -- Ogre XML ( .xml ) "ASSIMP_BUILD_NO_OPENGEX_IMPORTER", -- Open Game Engine Exchange ( .ogex ) "ASSIMP_BUILD_NO_MS3D_IMPORTER", -- Milkshape 3D ( .ms3d ) "ASSIMP_BUILD_NO_COB_IMPORTER", -- TrueSpace "ASSIMP_BUILD_NO_BLEND_IMPORTER", -- Blender 3D ( .blend ) "ASSIMP_BUILD_NO_Q3BSP_IMPORTER", -- Quake III Map/BSP ( .pk3 ) "ASSIMP_BUILD_NO_NDO_IMPORTER", -- Izware Nendo ( .ndo ) "ASSIMP_BUILD_NO_IFC_IMPORTER", -- Industry Foundation Classes (IFC/Step) ( .ifc ) "ASSIMP_BUILD_NO_XGL_IMPORTER", -- XGL ( .xgl,.zgl ) -- "ASSIMP_BUILD_NO_FBX_IMPORTER", -- Autodesk ( .fbx ) "ASSIMP_BUILD_NO_ASSBIN_IMPORTER", -- "ASSIMP_BUILD_NO_GLTF_IMPORTER", -- ?? "ASSIMP_BUILD_NO_C4D_IMPORTER", -- Cinema4D is MSVC only and needs some weird headers to work "ASSIMP_BUILD_NO_3MF_IMPORTER", -- ?? "ASSIMP_BUILD_NO_X3D_IMPORTER", -- ?? "ASSIMP_BUILD_NO_MMD_IMPORTER", -- ?? "ASSIMP_BUILD_NO_STEP_IMPORTER", -- ?? "ASSIMP_BUILD_NO_EXPORT", "OPENDDL_STATIC_LIBARY", } files { "code/**.cpp", "code/**.h", "contrib/irrXML/*.cpp", "contrib/irrXML/*.h", "contrib/unzip/*.c", "contrib/unzip/*.h", "contrib/openddlparser/code/*.cpp", "contrib/poly2tri/poly2tri/**.cc", "contrib/clipper/*.cpp", "contrib/zlib/*.c", "contrib/zlib/*.h" } includedirs { "config/", "include/", "contrib/irrXML/", "contrib/rapidjson/include/", "contrib/openddlparser/include/", "contrib/unzip/", "contrib/zlib/", "./" } removefiles { "code/Importer/IFC/IFCReaderGen_4.*", } filter "system:windows" systemversion "latest" cppdialect "C++17" staticruntime "On" buildoptions { "/bigobj" } defines { "_CRT_SECURE_NO_WARNINGS" } filter "configurations:Debug" defines "PYRO_DEBUG" runtime "Debug" symbols "on" filter "configurations:Release" defines "PYRO_RELEASE" runtime "Release" optimize "on" filter "configurations:Dist" defines "PYRO_DIST" runtime "Release" optimize "on"
----------------------------------------------------------------------------- -- Simple 911 Script by Mr.Gamer- A Simple FiveM Script, Made By Mr.Gamer#2222 -- ----------------------------------------------------------------------------- ---------------------------------------------------------------------------------------------- -- !WARNING! !WARNING! !WARNING! !WARNING! !WARNING! -- -- DO NOT TOUCH THIS FILE OR YOU /WILL/ FUCK SHIT UP! THERE IS NOTHING TO EDIT -- -- DO NOT BE STUPID AND WHINE TO ME ABOUT THIS BEING BROKEN IF YOU TOUCHED THE LINES BELOW. -- ---------------------------------------------------------------------------------------------- -- Branding! local label = [[ // || 📞🆘 | 911 Script for HAMZ CAD | 📞🆘 || Created by Mr.Gamer#2222 ||]] Citizen.CreateThread(function() local CurrentVersion = GetResourceMetadata(GetCurrentResourceName(), 'version', 0) if not CurrentVersion then print('^1Simple 911 Script by Mr.Gamer Version Check Failed!^7') end function VersionCheckHTTPRequest() PerformHttpRequest('https://raw.githubusercontent.com/TheGamerCoder121/911Script/main/version.json', VersionCheck, 'GET') end function VersionCheck(err, response, headers) Citizen.Wait(3000) if err == 200 then local Data = json.decode(response) if CurrentVersion ~= Data.NewestVersion then print(label) print(' || \n || Simple 911 Script by Mr.Gamer is outdated!') print(' || Current version: ^2' .. Data.NewestVersion .. '^7') print(' || Your version: ^1' .. CurrentVersion .. '^7') print(' || Please download the lastest version from ^5' .. Data.DownloadLocation .. '^7') if Data.Changes ~= '' then print(' || \n || ^5Changes: ^7' .. Data.Changes .. "\n^0 \\\\\n") end else print(label) print(' || ^2Simple 911 Script by Mr.Gamer is up to date!\n^0 ||\n \\\\\n') end else print(label) print(' || ^1There was an error getting the latest version information, if the issue persists contact Mr.Gamer#2222 on Discord.\n^0 ||\n \\\\\n') end SetTimeout(60000000, VersionCheckHTTPRequest) end VersionCheckHTTPRequest() end)
project "02-Instancing" kind "ConsoleApp" language "C++" cppdialect "C++17" targetdir ("%{wks.location}/bin/" .. outputdir .. "/%{prj.name}") objdir ("%{wks.location}/bin-int/" .. outputdir .. "/%{prj.name}") files { "src/**.h", "src/**.cpp", "assets/**/*", "%{wks.location}/Valiance/vendor/glm/glm/**.hpp", "%{wks.location}/Valiance/vendor/glm/glm/**.inl", } includedirs { "%{wks.location}/Valiance/src", "%{wks.location}/Valiance/vendor/Glad/include", "%{wks.location}/Valiance/vendor/imgui", "%{wks.location}/Valiance/vendor/glm", "%{wks.location}/Valiance/vendor/GLFW/include", } libdirs { "%{wks.location}/Valiance/vendor/GLFW/lib" } links { "Valiance", "Glad", "ImGui", "glfw3", } filter "configurations:Debug" defines { "DEBUG" } symbols "On" filter "configurations:Release" defines { "NDEBUG" } optimize "On"
object_tangible_loot_beast_beast_steroid_gorilla_griffon = object_tangible_loot_beast_shared_beast_steroid_gorilla_griffon:new { } ObjectTemplates:addTemplate(object_tangible_loot_beast_beast_steroid_gorilla_griffon, "object/tangible/loot/beast/beast_steroid_gorilla_griffon.iff")
local myname, ns = ... _G["SLASH_".. myname:upper().."1"] = GetAddOnMetadata(myname, "X-LoadOn-Slash") SlashCmdList[myname:upper()] = function(msg) ns:Slash() end
object_tangible_loot_creature_loot_collections_aurebesh_tile_senth = object_tangible_loot_creature_loot_collections_shared_aurebesh_tile_senth:new { } ObjectTemplates:addTemplate(object_tangible_loot_creature_loot_collections_aurebesh_tile_senth, "object/tangible/loot/creature/loot/collections/aurebesh_tile_senth.iff")
object_intangible_beast_bm_tauntaun = object_intangible_beast_shared_bm_tauntaun:new { } ObjectTemplates:addTemplate(object_intangible_beast_bm_tauntaun, "object/intangible/beast/bm_tauntaun.iff")
return { IsClient = false, IsServer = true, Module = function() App.route( { method = "GET", path = "/", }, function (Request, Response, go) Response.body = '<p>OwO</p> <meta http-equiv="refresh" content="3; URL=/index.html" />' Response.code = 200 end ) App.route( { method = "GET", path = "/API/tag", }, function (Request, Response, go) local Response, Body = require("coro-http").request("GET", "https://api.github.com/repos/CoreBytee/Sugar/releases", {{"User-Agent", "Sugarrrrr"}}) p(Body) p(require("json").parse(Body)) Response.body = require("json").parse(Body)[0].tag_name Response.code = 200 end ) local Static = require('weblit-static') App.use(Static("./Static/")) App.route( { method = "GET", path = "/API/Connections/List", }, function (Request, Response, go) local Body = "" for Index, Connection in pairs(Connections) do Body = Body .. "'" .. Connection.Username .. "' - '" .. Connection.WifiName .. "\n" end Response.body = Body Response.code = 200 end ) App.route( { method = "GET", path = "/API/Connections/", }, function (Request, Response, go) Response.body = tostring(#Connections) Response.code = 200 end ) App.route( { method = "GET", path = "/API/Media", }, function (Request, Response, go) Response.body = '<p>OwO</p> <meta http-equiv="refresh" content="0; URL=/index.html" />' Response.code = 200 for Index, Connection in pairs(Connections) do Connection.Write({payload = CommandHandler.RunCommand("PlayMedia", {Link = Request.query.Link, Display = Request.query.Display})}) end end ) App.route( { method = "GET", path = "/API/Brightness", }, function (Request, Response, go) Response.body = '<p>OwO</p> <meta http-equiv="refresh" content="0; URL=/index.html" />' Response.code = 200 for Index, Connection in pairs(Connections) do Connection.Write({payload = CommandHandler.RunCommand("Brightness", {Amount = tonumber(Request.query.A)})}) end end ) App.route( { method = "GET", path = "/API/Volume", }, function (Request, Response, go) Response.body = '<p>OwO</p> <meta http-equiv="refresh" content="0; URL=/index.html" />' Response.code = 200 for Index, Connection in pairs(Connections) do Connection.Write({payload = CommandHandler.RunCommand("Volume", {Amount = tonumber(Request.query.A)})}) end end ) App.route( { method = "GET", path = "/API/Open", }, function (Request, Response, go) Response.body = '<p>OwO</p> <meta http-equiv="refresh" content="0; URL=/index.html" />' Response.code = 200 for Index, Connection in pairs(Connections) do Connection.Write({payload = CommandHandler.RunCommand("Open", {Program = Request.query.Program})}) end end ) end }
-- dvdlogo.lua -- -- An object to control a dvdlogo. -- -- Uses bounce movement method for it's movement pattern. Changes -- it's sprite's colors when it bounces off of a wall. ----------------------------------------------------------------------- local dvdlogo = {} ----------------------------------------------------------------------- -- Returns a function to pass to sprite:mapPixel for color shifting. ----------------------------------------------------------------------- local function randomColorFunc(self) -- Don't repeat the same color repeat color = love.math.random(1,7) until(color ~= self.lastcolor) self.lastcolor = color -- TODO: better color list local colors = {{255,0,0}, -- red {0,255,0}, -- green {0,0,255}, -- blue {255,255,0}, {255,0,255}, {0,255,255}, {255,255,255} -- white } -- Return the color as a new anonymous function return function(x,y,r,g,b,a) r,g,b = unpack(colors[color]) return r,g,b,a end end ----------------------------------------------------------------------- -- Changes associated sprite's color using sprite:mapPixel() ----------------------------------------------------------------------- local function doColorShift(self) self.sprite:mapPixel(self:randomColorFunc()) end ----------------------------------------------------------------------- -- Changes sprite color when bouncing off wall and calls bounce:update ----------------------------------------------------------------------- local function update(self) -- Change sprite color if bouncing off a wall local on_edge = self.movement:onEdge() if on_edge.x or on_edge.y then self:doColorShift() end -- Update actual (x,y) values self.movement:update() end ----------------------------------------------------------------------- -- Create a new dvdlogo instance. -- @param x Starting x position -- @param y Starting y position -- @param x_speed Amount of pixels to move on x axis (negative is left) -- @param y_speed Amount of pixels to move on y axis (negative is up) ----------------------------------------------------------------------- function dvdlogo.create(x, y, x_speed, y_speed) local inst = {} local sprite = require('src.sprite') local entity = require('src.entity') local bounce = require('src.bounce') -- Member values inst.sprite = sprite.create('assets/dvd_logo.png') -- If no (x,y) is passed in, start in center of screen x = x or (love.graphics.getWidth() - inst.sprite.image:getWidth()) / 2 y = y or (love.graphics.getHeight() - inst.sprite.image:getHeight()) / 2 inst.entity = entity.create(inst.sprite, x, y) -- Movement pattern inst.movement = bounce.init(inst.entity, x_speed, y_speed) inst.lastcolor = nil -- Member methods inst.randomColorFunc = randomColorFunc inst.doColorShift = doColorShift inst.update = update return inst end return dvdlogo
function CreateWindow(name, mode, x, y, width, height, id) local Window = { name = name or 'Generic Window', mode = mode or 'fill', x_offset = NormalizeToWindowWidth(x), y_offset = NormalizeToWindowHeight(y), width = width, height = height, id = id } Window.update_offsets = function() end return Window end
local K, C = unpack(select(2, ...)) if not IsAddOnLoaded("KkthnxUI_Config") then return end local pairs = pairs -- Blizzard has too many issues with per character saved variables. if (not KkthnxUIConfigShared) then KkthnxUIConfigShared = {} end if (not KkthnxUIConfigShared.Account) then KkthnxUIConfigShared.Account = {} end if (not KkthnxUIConfigShared[K.Realm]) then KkthnxUIConfigShared[K.Realm] = {} end if (not KkthnxUIConfigShared[K.Realm][K.Name]) then KkthnxUIConfigShared[K.Realm][K.Name] = {} end if (KkthnxUIConfigNotShared) then KkthnxUIConfigShared[K.Realm][K.Name] = KkthnxUIConfigNotShared KkthnxUIConfigNotShared = nil end local Settings if (KkthnxUIConfigPerAccount) then Settings = KkthnxUIConfigShared.Account else Settings = KkthnxUIConfigShared[K.Realm][K.Name] end for group, options in pairs(Settings) do if C[group] then local Count = 0 for option, value in pairs(options) do if (C[group][option] ~= nil) then if (C[group][option] == value) then Settings[group][option] = nil else Count = Count + 1 C[group][option] = value end end end -- Keeps KkthnxUI_Config clean and small if (Count == 0) then Settings[group] = nil end else Settings[group] = nil end end
-- The following code is from "Get Comfortable [cozy]" (by everamzah; published under WTFPL) -- Thomas S. modified it, so that it can be used in this mod ts_vehicles.sit = function(pos, player, offset) local name = player:get_player_name() if not player_api.player_attached[name] then player:move_to(pos) local eye_pos = { x = offset and offset.x or 0, y = offset and (offset.y - 7) or -7, z = offset and (offset.z + 2) or 2, } player:set_eye_offset(eye_pos, {x = 0, y = 0, z = 0}) player:set_physics_override(0, 0, 0) player_api.player_attached[name] = true minetest.after(0.1, function() if player then player_api.set_animation(player, "sit" , 30) end end) end end ts_vehicles.up = function(player) local name = player:get_player_name() if player_api.player_attached[name] then player:set_eye_offset({x = 0, y = 0, z = 0}, {x = 0, y = 0, z = 0}) player:set_physics_override(1, 1, 1) player_api.player_attached[name] = false player_api.set_animation(player, "stand", 30) end end if not (minetest.get_modpath("ts_furniture") and ts_furniture.enable_sitting) or not minetest.get_modpath("cozy") then minetest.register_globalstep(function(dtime) local players = minetest.get_connected_players() for i = 1, #players do local name = players[i]:get_player_name() if default.player_attached[name] and not players[i]:get_attach() and (players[i]:get_player_control().up == true or players[i]:get_player_control().down == true or players[i]:get_player_control().left == true or players[i]:get_player_control().right == true or players[i]:get_player_control().jump == true) then players[i]:set_eye_offset({ x = 0, y = 0, z = 0 }, { x = 0, y = 0, z = 0 }) players[i]:set_physics_override(1, 1, 1) default.player_attached[name] = false default.player_set_animation(players[i], "stand", 30) end end end) end
local InputDevice = require("web-driver/interactions/input-device") local PointerInput = require("web-driver/interactions/pointer-input") local KeyInput = require("web-driver/interactions/key-input") local NoneInput = require("web-driver/interactions/none-input") local Interaction = require("web-driver/interactions/interaction") local PointerPress = require("web-driver/interactions/pointer-press") local PointerMove = require("web-driver/interactions/pointer-move") local PointerCancel = require("web-driver/interactions/pointer-cancel") local TypingInteraction = require("web-driver/interactions/typing-interaction") local Pause = require("web-driver/interactions/pause") local Interactions = { InputDevice = InputDevice, PointerInput = PointerInput, KeyInput = KeyInput, Interaction = Interaction, PointerPress = PointerPress, PointerMove = PointerMove, PointerCancel = PointerCancel, TypingInteraction = TypingInteraction, Pause = Pause } function Interactions.key(name) return KeyInput.new(name) end function Interactions.pointer(kind, name) return PointerInput.new(kind, name) end function Interactions.none(name) return NoneInput.new(name) end return Interactions
if (!PW.Enabled) then return; end local Player = FindMetaTable("Player"); function Player:CanUsePW() for k,v in pairs(PW.Groups) do if (self:IsUserGroup(v)) then return true; end end return false; end if (CLIENT) then function Player:AddMsg(str) chat.AddText(PW.Chat.TagBracketsCol, "[", PW.Chat.TagCol, PW.Chat.Tag, PW.Chat.TagBracketsCol, "] ", PW.Chat.ChatColor, str); end end if (SERVER) then function Player:GiveWeapon(wep) local weps = self.PWeapons; for k,v in pairs(weps) do if (v == wep) then return false; end end self:Give(wep); table.insert(weps, wep); return true; end function Player:TakeWeapon(wep) local weps = self.PWeapons; for k,v in pairs(weps) do if (v == wep) then if (self:HasWeapon(wep)) then self:StripWeapon(wep); end table.remove(weps, k); return true; end end return false; end function Player:CreateWEPProfile() local id = self:SteamID(); local weps = util.TableToJSON({}); Query("INSERT INTO `pw_general` (weps, steamid) VALUES ('"..weps.."', '"..id.."')", function(res) self.PWeapons = {}; end) end function Player:SaveWeapons() local id = self:SteamID(); local weps = util.TableToJSON(self.PWeapons); Query("UPDATE `pw_general` SET weps = '"..weps.."' WHERE steamid = '"..id.."'"); end function Player:LoadWeapons() local id = self:SteamID(); Query("SELECT * FROM `pw_general` WHERE steamid = '"..id.."'", function(res) if (res[1] == nil) then self:CreateWEPProfile() return; end local weps = res[1]['weps']; local weps = util.JSONToTable(weps); for k,v in pairs(weps) do self:Give(v); end self.PWeapons = weps; end) end end
-- Health check implementation for debugpy.nvim local M = {} local health = require 'health' local command = require('debugpy').adapter.executable.command local function check_dap() local success = pcall(require, 'dap') if success then health.report_ok "Plugin 'nvim-dap' found" else health.report_error "Plugin 'nvim-dap' not found" health.report_info 'Official nvim-dap website: https://github.com/mfussenegger/nvim-dap' end return success end local function check_python() local success = vim.fn.executable(command) ~= 0 if success then health.report_ok(string.format("Executable '%s' found", command)) else health.report_error(string.format("Executable '%s' not found", command)) health.report_warn 'Skipping check for debugpy module' health.report_info 'See debugpy.adapter.executable on how to set your Python executable' return end return success end local function check_debugpy() -- Note: this might not work on old versions of Python, tested with 3.10; -- the goal is to check for the presence of a module without actually -- importing it (for security, just in case). vim.fn.system { command, '-c', 'from importlib.util import find_spec as fs; exit(0 if fs("debugpy") else 1)' } if vim.v.shell_error == 0 then health.report_ok "Python module 'debugpy' found" else health.report_error "Python module 'debugpy' not found" health.report_info 'Official debugpy website: https://github.com/microsoft/debugpy' end end function M.check() health.report_start 'Debugpy.nvim' check_dap() check_python() check_debugpy() end return M
local names = {"FormDefine", "Form", "FormCategory", "FormInstance", "FileItem"} for i, it in ipairs(names) do io.write("Query<", it, "> query", it, "();\n") end
-- create node Combine require "moon.sg" local node = moon.sg.new_node("sg_combine") if node then node:set_pos(moon.mouse.get_position()) end
function do_remap() ts.client_request.set_url_host(ts.client_request.header["X-Api-Umbrella-Backend-Server-Host"]) ts.client_request.set_url_port(ts.client_request.header["X-Api-Umbrella-Backend-Server-Port"]) ts.client_request.set_url_scheme(ts.client_request.header["X-Api-Umbrella-Backend-Server-Scheme"]) -- For cache key purposes, allow HEAD requests to re-use the cache key for -- GET requests (since HEAD queries can be answered from cached GET data). -- But since HEAD requests by themselves aren't cacheable, we don't have to -- worry about GET requests re-using the HEAD response. local method_key = ts.client_request.get_method() if method_key == "HEAD" then method_key = "GET" end local cache_key = { -- Include the HTTP method (GET, POST, etc) in the cache key. This prevents -- delayed processing when long-running GET and POSTs are running against -- the same URL: https://issues.apache.org/jira/browse/TS-3431 method_key, -- Include the Host header in the cache key, since this may differ from the -- underlying server host/IP being connected to (for virtual hosts). The -- underlying server host is included in get_url() below, but we need both -- to be part of the cache key to keep underling servers and virtual hosts -- cached separately. ts.client_request.header["Host"], -- Note that by default, the cache key doesn't include the backend server -- port, so by re-setting the cache key based on the full URL here, this -- also helps ensure the backend port is included (so backends running on -- separate ports are kept separate). ts.client_request.get_url(), } ts.http.set_cache_lookup_url(table.concat(cache_key, "/")) return TS_LUA_REMAP_DID_REMAP end
local get_buffers = require "helpers.nvim_get_buffers" local is_empty = require "helpers.is_empty" local function get_terminal_buffers() local buffers = get_buffers() local terminal_buffers = {} for _, buffer in pairs(buffers) do if not is_empty(vim.fn.matchstr(buffer, "^term://.*")) then table.insert(terminal_buffers, buffer) end end return terminal_buffers end return get_terminal_buffers
vim.opt_local.expandtab = false vim.opt_local.softtabstop = 0
Citizen.CreateThread(function() while true do if IsPedInAnyVehicle(GetPlayerPed(-1)) then local canshoot = false local kmhSpeed = GetEntitySpeed(GetVehiclePedIsUsing(PlayerPedId(-1))) * 3.6; if kmhSpeed < sc0tt_lucky_driveby.kmh then canshoot = true else canshoot = false end SetPlayerCanDoDriveBy(sc0tt_lucky_driveby.player, canshoot) end Citizen.Wait(0); end end) SetPlayerCanDoDriveBy(sc0tt_lucky_driveby.player, false)
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local voices = { { text = 'Alms! Alms for the poor!' }, { text = 'Sir, Ma\'am, have a gold coin to spare?' }, { text = 'I need help! Please help me!' } } npcHandler:addModule(VoiceModule:new(voices)) function BeggarFirst(cid, message, keywords, parameters, node) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if player:isPremium() then if player:getStorageValue(Storage.OutfitQuest.BeggarFirstAddon) == -1 then if player:getItemCount(5883) >= 100 and player:getMoney() >= 20000 then if player:removeItem(5883, 100) and player:removeMoney(20000) then npcHandler:say("Ah, right! The beggar beard or beggar dress! Here you go.", cid) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) player:setStorageValue(Storage.OutfitQuest.BeggarFirstAddon, 1) player:addOutfitAddon(153, 1) player:addOutfitAddon(157, 1) end else npcHandler:say("You do not have all the required items.", cid) end else npcHandler:say("It seems you already have this addon, don't you try to mock me son!", cid) end end end function BeggarSecond(cid, message, keywords, parameters, node) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if player:isPremium() then if player:getStorageValue(Storage.OutfitQuest.BeggarSecondAddon) == -1 then if player:getItemCount(6107) >= 1 then if player:removeItem(6107, 1) then npcHandler:say("Ah, right! The beggar staff! Here you go.", cid) player:getPosition():sendMagicEffect(CONST_ME_MAGIC_BLUE) player:setStorageValue(Storage.OutfitQuest.BeggarSecondAddon, 1) player:addOutfitAddon(153, 2) player:addOutfitAddon(157, 2) end else npcHandler:say("You do not have all the required items.", cid) end else npcHandler:say("It seems you already have this addon, don't you try to mock me son!", cid) end end end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false end local player = Player(cid) if msgcontains(msg, 'cookie') then if player:getStorageValue(Storage.WhatAFoolishQuest.Questline) == 31 and player:getStorageValue(Storage.WhatAFoolishQuest.CookieDelivery.SimonTheBeggar) ~= 1 then npcHandler:say('Have you brought a cookie for the poor?', cid) npcHandler.topic[cid] = 1 end elseif msgcontains(msg, 'help') then npcHandler:say('I need gold. Can you spare 100 gold pieces for me?', cid) npcHandler.topic[cid] = 2 elseif msgcontains(msg, 'yes') then if npcHandler.topic[cid] == 1 then if not player:removeItem(8111, 1) then npcHandler:say('You have no cookie that I\'d like.', cid) npcHandler.topic[cid] = 0 return true end player:setStorageValue(Storage.WhatAFoolishQuest.CookieDelivery.SimonTheBeggar, 1) if player:getCookiesDelivered() == 10 then player:addAchievement('Allow Cookies?') end Npc():getPosition():sendMagicEffect(CONST_ME_GIFT_WRAPS) npcHandler:say('Well, it\'s the least you can do for those who live in dire poverty. A single cookie is a bit less than I\'d expected, but better than ... WHA ... WHAT?? MY BEARD! MY PRECIOUS BEARD! IT WILL TAKE AGES TO CLEAR IT OF THIS CONFETTI!', cid) npcHandler:releaseFocus(cid) npcHandler:resetNpc(cid) elseif npcHandler.topic[cid] == 2 then if not player:removeMoney(100) then npcHandler:say('You haven\'t got enough money for me.', cid) npcHandler.topic[cid] = 0 return true end npcHandler:say('Thank you very much. Can you spare 500 more gold pieces for me? I will give you a nice hint.', cid) npcHandler.topic[cid] = 3 elseif npcHandler.topic[cid] == 3 then if not player:removeMoney(500) then npcHandler:say('Sorry, that\'s not enough.', cid) npcHandler.topic[cid] = 0 return true end npcHandler:say('That\'s great! I have stolen something from Dermot. You can buy it for 200 gold. Do you want to buy it?', cid) npcHandler.topic[cid] = 4 elseif npcHandler.topic[cid] == 4 then if not player:removeMoney(200) then npcHandler:say('Pah! I said 200 gold. You don\'t have that much.', cid) npcHandler.topic[cid] = 0 return true end local key = player:addItem(2087, 1) if key then key:setActionId(3940) end npcHandler:say('Now you own the hot key.', cid) npcHandler.topic[cid] = 0 end elseif msgcontains(msg, 'no') and npcHandler.topic[cid] ~= 0 then if npcHandler.topic[cid] == 1 then npcHandler:say('I see.', cid) elseif npcHandler.topic[cid] == 2 then npcHandler:say('Hmm, maybe next time.', cid) elseif npcHandler.topic[cid] == 3 then npcHandler:say('It was your decision.', cid) elseif npcHandler.topic[cid] == 4 then npcHandler:say('Ok. No problem. I\'ll find another buyer.', cid) end npcHandler.topic[cid] = 0 end return true end node1 = keywordHandler:addKeyword({'addon'}, StdModule.say, {npcHandler = npcHandler, text = 'For the small fee of 20000 gold pieces I will help you mix this potion. Just bring me 100 pieces of ape fur, which are necessary to create this potion. ...Do we have a deal?'}) node1:addChildKeyword({'yes'}, BeggarFirst, {}) node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'Alright then. Come back when you got all neccessary items.', reset = true}) node2 = keywordHandler:addKeyword({'dress'}, StdModule.say, {npcHandler = npcHandler, text = 'For the small fee of 20000 gold pieces I will help you mix this potion. Just bring me 100 pieces of ape fur, which are necessary to create this potion. ...Do we have a deal?'}) node2:addChildKeyword({'yes'}, BeggarFirst, {}) node2:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'Alright then. Come back when you got all neccessary items.', reset = true}) node3 = keywordHandler:addKeyword({'staff'}, StdModule.say, {npcHandler = npcHandler, text = 'To get beggar staff you need to give me simon the beggar\'s staff. Do you have it with you?'}) node3:addChildKeyword({'yes'}, BeggarSecond, {}) node3:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, text = 'Alright then. Come back when you got all neccessary items.', reset = true}) npcHandler:setMessage(MESSAGE_GREET, "Hello |PLAYERNAME|. I am a poor man. Please help me.") npcHandler:setMessage(MESSAGE_FAREWELL, "Have a nice day.") npcHandler:setMessage(MESSAGE_WALKAWAY, "Have a nice day.") npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
AddCSLuaFile() ENT.Base = "gballoon_tower_base" ENT.Type = "anim" ENT.PrintName = "Rainbow Beamer" ENT.Category = "RotgB: Towers" ENT.Author = "Piengineer" ENT.Contact = "http://steamcommunity.com/id/Piengineer12/" ENT.Purpose = "This tower shoots a rainbow beam that shreds gBalloons." ENT.Instructions = "" ENT.Spawnable = false ENT.AdminOnly = false ENT.RenderGroup = RENDERGROUP_BOTH ENT.Model = Model("models/hunter/tubes/tube1x1x1.mdl") ENT.FireRate = 20 ENT.Cost = 2500 ENT.DetectionRadius = 512 ENT.AbilityCooldown = 60 ENT.UseLOS = true ENT.LOSOffset = Vector(0,0,150) ENT.UserTargeting = true ENT.AttackDamage = 10 ENT.rotgb_BeamWidth = 8 ENT.UpgradeReference = { { Names = {"Super Range","Enhanced Prisms","Secondary Spectrum","Fury of the Radiant Sun","Rainbow Overlord","Orbital Friendship Cannon","Dyson Sphere","INFINITE POWER!"}, Descs = { "Increases range to infinite.", "Considerably increases attack damage and enables the tower to pop purple gBalloons.", "Tremendously increases attack damage. gBalloons popped by this tower do not spawn any children.", "Colossally increases attack damage and enables the tower to pop Hidden gBalloons.", "This tower now hits ALL gBalloons within sight.", "Once every 60 seconds, shooting at this tower OBLITERATES the strongest gBalloon on the map after 5 seconds. You still get the cash.", "Reduces Orbital Friendship Cannon's cooldown by 30 seconds and you gain $10,000,000 for every use.", "It's worth it." }, Prices = {2000,15000,100000,1.25e6,5e6,10e6,50e6,1e9}, Funcs = { function(self) self.InfiniteRange = true end, function(self) self.AttackDamage = self.AttackDamage + 20 self.rotgb_BeamWidth = self.rotgb_BeamWidth * 1.5 self.rotgb_UseAltLaser = true end, function(self) self.AttackDamage = self.AttackDamage + 80 self.rotgb_BeamWidth = self.rotgb_BeamWidth * 1.5 self.rotgb_BeamNoChildren = true end, function(self) self.AttackDamage = self.AttackDamage + 240 self.rotgb_BeamWidth = self.rotgb_BeamWidth * 1.5 self.SeeCamo = true end, function(self) self.UserTargeting = false end, function(self) self.HasAbility = true if SERVER and IsValid(self.InternalLaser) then self.InternalLaser:Fire("Alpha",127) end end, function(self) self.rotgb_Infinite = true self.AbilityCooldown = self.AbilityCooldown - 30 end, function(self) self.HasAbility = nil self.FireRate = self.FireRate / 10 if SERVER and IsValid(self.InternalLaser) then self.InternalLaser:Fire("Alpha",255) end self.UseLOS = nil end } } } ENT.UpgradeLimits = {99} local function SnipeEntity() while true do local self,ent,damagemul = coroutine.yield() local startPos = self.rotgb_StartPos local laser = ents.Create("env_beam") --[[local oldEntName = ent:GetName() local entityName = ent:GetName() ~= "" and ent:GetName() or "ROTGB08_"..ent:GetCreationID() ent:SetName(entityName)]] local endEnt = ents.Create("info_target") --local percent = math.Remap(self.rotgb_NextFire - CurTime(), self.rotgb_BeamDelay + self.rotgb_BeamTime, self.rotgb_BeamDelay, 1, 0) laser:SetPos(startPos:GetPos()) if IsValid(endEnt) then endEnt:SetName("ROTGB08_"..endEnt:GetCreationID()) endEnt:SetPos(ent:GetPos()+ent.loco:GetVelocity()*0.1+ent:OBBCenter()) end laser:SetKeyValue("renderamt","63") laser:SetKeyValue("rendercolor","255 255 255") laser:SetKeyValue("BoltWidth",self.rotgb_BeamWidth) laser:SetKeyValue("NoiseAmplitude","1") laser:SetKeyValue("texture","beams/rainbow1.vmt") laser:SetKeyValue("TextureScroll","0") laser:SetKeyValue("damage",self.AttackDamage*damagemul) laser:SetKeyValue("LightningStart",startPos:GetName()) laser:SetKeyValue("LightningEnd",endEnt:GetName()) laser:SetKeyValue("HDRColorScale","0.7") laser:SetKeyValue("decalname","decals/dark") laser:SetKeyValue("spawnflags","97") --[[if percent then laser:SetKeyValue("life",self.rotgb_BeamTime) end]] laser:Spawn() laser.rotgb_Owner = self laser:Activate() laser.rotgb_UseLaser = self.rotgb_UseAltLaser and 2 or 1 laser.rotgb_NoChildren = self.rotgb_BeamNoChildren --if percent then --laser:Fire("Alpha",percent*255) --end laser:Fire("TurnOn") --[[local canOtherBonus = #ents.GetAll()<1000 if not percent then local lastfiretime = CurTime() timer.Create("ROTGB_08_B_"..endEnt:GetCreationID(),0.05,self.rotgb_BeamTime*20,function() if IsValid(laser) then laser.CurAlpha = (laser.CurAlpha or 255) - 0.05/self.rotgb_BeamTime*255 laser:Fire("Alpha",laser.CurAlpha) end if (IsValid(self) and self.rotgb_OtherBonus and canOtherBonus) then self:ExpensiveThink(true) if IsValid(self.SolicitedgBalloon) and IsValid(self.rotgb_StartPos) then percent = (CurTime()-lastfiretime)/self.rotgb_BeamTime for k,v in pairs(self.gBalloons or {}) do local perf,str = coroutine.resume(self.thread,self,v,percent) if not perf then error(str) end end end end end) end]] timer.Simple(0.2,function() if IsValid(laser) then self:DontDeleteOnRemove(laser) laser:Remove() end --[[if (IsValid(ent) and entityName == ent:GetName()) then ent:SetName(oldEntName) end]] if IsValid(endEnt) then endEnt:Remove() end end) self:DeleteOnRemove(laser) end end ENT.thread = coroutine.create(SnipeEntity) --coroutine.resume(ENT.thread) function ENT:ROTGB_Initialize() if SERVER then --[[if not self.rotgb_Infinite then self:SetNWFloat("LastFireTime",CurTime()-self.rotgb_BeamTime) end]] local startPos = ents.Create("info_target") startPos:SetName("ROTGB08_"..startPos:GetCreationID()) startPos:SetPos(self:GetShootPos()) startPos:SetParent(self) startPos:Spawn() self.rotgb_StartPos = startPos self:DeleteOnRemove(startPos) self:SetName("ROTGB08_"..self:GetCreationID()) local laser = ents.Create("env_beam") laser:SetPos(self:GetPos()) laser:SetKeyValue("renderamt","255") laser:SetKeyValue("rendercolor","255 255 255") laser:SetKeyValue("BoltWidth","8") laser:SetKeyValue("NoiseAmplitude","2") laser:SetKeyValue("texture","beams/rainbow1.vmt") laser:SetKeyValue("TextureScroll","0") laser:SetKeyValue("LightningStart",self:GetName()) laser:SetKeyValue("LightningEnd",startPos:GetName()) laser:SetKeyValue("HDRColorScale","0.7") laser:SetKeyValue("spawnflags","129") laser:Spawn() laser:Activate() laser:Fire("TurnOn") self.InternalLaser = laser self:DeleteOnRemove(laser) end end function ENT:ROTGB_Think() if IsValid(self.KillDamagePos) then for k,v in pairs(ents.FindInSphere(self.KillDamagePos:GetPos(),32)) do if v:GetClass()=="gballoon_base" then v:TakeDamage(v:GetRgBE()*1000, self:GetTowerOwner(), self) end end end end function ENT:ROTGB_Draw() --[[local elapsedseconds = CurTime()-self:GetNWFloat("LastFireTime") local val = 0 if elapsedseconds < self.rotgb_BeamTime then val = math.Remap(self.rotgb_BeamTime-elapsedseconds,self.rotgb_BeamTime,0,255,0) else val = math.Remap(elapsedseconds-self.rotgb_BeamTime,0,self.rotgb_BeamDelay,0,255) end]] self:DrawModel() render.SetColorMaterial() render.DrawSphere(self:GetShootPos(),24,24,13,color_white)--val >= 255 and color_white or Color(val,val,val)) end local abilityFunction function ENT:FireFunction(gBalloons) if not self.UseLOS then abilityFunction(self) elseif IsValid(self.rotgb_StartPos) then --[[if self.rotgb_NextFire <= CurTime() then self.rotgb_NextFire = CurTime() + self.rotgb_BeamDelay + self.rotgb_BeamTime if not self.rotgb_Infinite then self:SetNWFloat("LastFireTime",CurTime()) end end if self.rotgb_NextFire > CurTime() + self.rotgb_BeamDelay then]] if self.UserTargeting then local perf,str = coroutine.resume(self.thread,self,gBalloons[1],10) if not perf then error(str) end else --[[local damagemul = 10 if self.rotgb_Infinite then damagemul = 10 for k,v in pairs(gBalloons) do damagemul = damagemul + v:GetRgBE() / 10 end end]] for k,v in pairs(gBalloons) do local perf,str = coroutine.resume(self.thread,self,v,10) if not perf then error(str) end end end --end if self.rotgb_OtherBonus then self.rotgb_OtherBy = self.rotgb_OtherBy or 0 self.FireRate = self.FireRate / (1+self.rotgb_OtherBy*0.2) self.rotgb_OtherBy = ents.FindInSphere(self:GetShootPos(),512) for k,v in pairs(self.rotgb_OtherBy) do if v:GetClass()~="gballoon_tower_08" then self.rotgb_OtherBy[k] = nil end end self.rotgb_OtherBy = #self.rotgb_OtherBy self.FireRate = self.FireRate * (1+self.rotgb_OtherBy*0.2) end end end local ShotSound = Sound("Airboat.FireGunHeavy") local AlertSound = Sound("npc/attack_helicopter/aheli_megabomb_siren1.wav") abilityFunction = function(self) local entities = ROTGB_GetBalloons() --if not next(entities) then return true end local enttab = {} for index,ent in pairs(entities) do enttab[ent] = ent:GetRgBE()+ent:GetDistanceTravelled()*1e-9 end local ent = next(entities) and self:ChooseSomething(enttab) if IsValid(self) and IsValid(ent) then if self.rotgb_Infinite then self:AddCash(1e7, self:GetTowerOwner()) end ent:EmitSound("ambient/explosions/explode_6.wav",100) local startPos = ents.Create("info_target") local ecp = ent:GetPos() ecp.z = 16000 startPos:SetPos(ecp) startPos:SetName("ROTGB08_"..startPos:GetCreationID()) local endPos = ents.Create("info_target") ecp = ent:GetPos() ecp.z = ecp.z + ent:OBBMins().z endPos:SetPos(ecp) endPos:SetName("ROTGB08_"..endPos:GetCreationID()) self.KillDamagePos = endPos local effdata = EffectData() ecp.z = ecp.z + 24 effdata:SetOrigin(ecp) util.Effect("rainbow_wave",effdata) util.ScreenShake(ecp,5,5,6,1024) local beam = ents.Create("env_beam") beam:SetPos(ecp) beam:SetKeyValue("renderamt","255") beam:SetKeyValue("rendercolor","255 255 255") beam:SetKeyValue("BoltWidth","64") beam:SetKeyValue("NoiseAmplitude","0") beam:SetKeyValue("texture","beams/rainbow1.vmt") beam:SetKeyValue("TextureScroll","100") beam:SetKeyValue("LightningStart",startPos:GetName()) beam:SetKeyValue("LightningEnd",endPos:GetName()) beam:SetKeyValue("HDRColorScale","1") beam:SetKeyValue("spawnflags","1") --beam:SetKeyValue("damage","999999") beam:Spawn() beam:Activate() beam:Fire("TurnOn") timer.Create("ROTGB_08_AB_"..endPos:GetCreationID(),0.05,120,function() if IsValid(beam) then beam.CurAlpha = (beam.CurAlpha or 255) - 0.05/6*255 beam:Fire("Alpha",beam.CurAlpha) end end) timer.Simple(6,function() if IsValid(startPos) then startPos:Remove() end if IsValid(endPos) then endPos:Remove() end if IsValid(beam) then beam:Remove() end end) elseif IsValid(self) then timer.Simple(math.random(),function() abilityFunction(self) end) end end function ENT:TriggerAbility() local entities = ROTGB_GetBalloons() if not next(entities) then return true end local enttab = {} for index,ent in pairs(entities) do enttab[ent] = ent:GetRgBE() end local ent = self:ChooseSomething(enttab) if IsValid(ent) then self:EmitSound(ShotSound,0) self:EmitSound(AlertSound,0) timer.Simple(5,function() abilityFunction(self) end) else return true end end function ENT:ChooseSomething(enttab) local chosen = table.GetWinningKey(enttab) --[[local trace = util.TraceLine({ start = chosen:GetPos(), endpos = chosen:GetPos()+Vector(0,0,32768), filter = ents.GetAll(), })]] --if trace.HitSky then return chosen --[[else enttab[chosen] = nil if next(enttab) then return self:ChooseSomething(enttab) else return NULL end end]] end if CLIENT then -- This will be a highly bootlegged version to avoid potential lag. local EFFECT = {} function EFFECT:Init(data) local start = data:GetOrigin() local emitter = ParticleEmitter(start) local pi2 = math.pi*2 for i=1,360 do local particle = emitter:Add("particle/smokesprites_0009",start) if particle then local radians = math.rad(i) local sine,cosine = math.sin(radians),math.cos(radians) local vellgh = math.random(340,400) local vel = Vector(sine,cosine,0)*vellgh particle:SetVelocity(vel) local col = HSVToColor(math.Remap(sine,-1,1,0,360),1,1) particle:SetColor(col.r,col.g,col.b) particle:SetDieTime(5+math.random()) particle:SetStartSize((vellgh-320)*0.25) particle:SetEndSize(vellgh-320) particle:SetAirResistance(5) particle:SetRollDelta(math.random(-2,2)) end end for i=1,100 do local particle = emitter:Add("particle/smokesprites_0010",start) if particle then local vel = Vector(math.random(-100,100),math.random(-100,100),math.random(-3,3)):GetNormal()*math.random(20,480) local vellgh = vel:Length2D() particle:SetVelocity(vel) particle:SetColor(255,255,255) particle:SetDieTime(5+math.random()) particle:SetStartSize(30-vellgh/16) particle:SetEndSize(120-vellgh/4) particle:SetAirResistance(50) particle:SetRollDelta(math.random(-2,2)) end particle = emitter:Add("particle/smokesprites_0010",start) if particle then particle:SetVelocity(Vector(math.random(-10,10),math.random(-10,10),0):GetNormal()*400) particle:SetColor(255,255,255) particle:SetDieTime(5+math.random()) particle:SetStartSize(5) particle:SetEndSize(16+8*math.random()) particle:SetAirResistance(30+math.random()) particle:SetRollDelta(math.random(-2,2)) end end emitter:Finish() end function EFFECT:Think() end function EFFECT:Render() end effects.Register(EFFECT,"rainbow_wave") end
local request = require 'lusty-nginx.request' local response = require 'lusty-nginx.response' --returns a request table for this server --uses metatables to memoize calls out to nginx local function getRequest() local memo = {} return setmetatable({},{ -- lazy-load all of the ngx data requests so we only call out to ngx when we -- have to __index = function(self, key) local func = request.index[key] return func and func(memo) or memo[key] end, __newindex = function(self, key, value) local func = request.newindex[key] if func then func(memo, value) else memo[key] = value end end }) end --returns a response table for this server --uses metatables to memoize calls out to nginx local function getResponse() local memo = {} return setmetatable({},{ __index = function(self, key) local func = response.index[key] return func and func(memo) or memo[key] end, __newindex = function(self, key, value) local func = response.newindex[key] if func then func(memo, value) else memo[key] = value end end }) end return function(lusty) local server = { request = function(self, request, response) local context = setmetatable({ suffix = {}, request = request or getRequest(), response = response or getResponse(), input = {}, output = {} }, lusty.context.__meta) --split url at / string.gsub(context.request.uri, "([^/]+)", function(c) context.suffix[#context.suffix+1] = c end) return lusty:request(context) end } return setmetatable({}, { __index = function(self, key) return server[key] or lusty[key] end, __newindex = function(self, key, value) lusty[key] = value end }) end
--[[ RA-MOD ]]-- module("luci.controller.chinadns", package.seeall) function index() if not nixio.fs.access("/etc/config/chinadns") then return end local page page = node("admin", "RA-MOD") page.target = firstchild() page.title = _("RA-MOD") page.order = 65 page = entry({"admin", "RA-MOD", "chinadns"}, cbi("chinadns"), _("chinadns"), 55) page.i18n = "chinadns" page.dependent = true end
-- -- test if ss is working -- local host, port = "www.youtube.com", 443 local socket = require("socket") local tcp = assert(socket.tcp()) tcp:settimeout(2); tcp:connect(host, port); tcp:send("GET / HTTP/1.1\n"); local s, status, partial = tcp:receive() if status == "closed" then io.write('yes') else io.write('no') end tcp:close()
local c local player = Var "Player" local JudgeCmds = { TapNoteScore_W1 = THEME:GetMetric("Judgment", "JudgmentW1Command"), TapNoteScore_W2 = THEME:GetMetric("Judgment", "JudgmentW2Command"), TapNoteScore_W3 = THEME:GetMetric("Judgment", "JudgmentW3Command"), TapNoteScore_W4 = THEME:GetMetric("Judgment", "JudgmentW4Command"), TapNoteScore_W5 = THEME:GetMetric("Judgment", "JudgmentW5Command"), TapNoteScore_Miss = THEME:GetMetric("Judgment", "JudgmentMissCommand") } local TNSFrames = { TapNoteScore_W1 = 0, TapNoteScore_W2 = 1, TapNoteScore_W3 = 2, TapNoteScore_W4 = 3, TapNoteScore_W5 = 4, TapNoteScore_Miss = 5 } local t = Def.ActorFrame {} t[#t + 1] = Def.ActorFrame { Def.Sprite { Texture = "../../../../" .. getAssetPath("judgment"), Name = "Judgment", InitCommand = function(self) self:pause():visible(false) end, OnCommand = THEME:GetMetric("Judgment", "JudgmentOnCommand"), ResetCommand = function(self) self:finishtweening():stopeffect():visible(false) end }, InitCommand = function(self) c = self:GetChildren() end, JudgmentMessageCommand = function(self, param) if param.Player ~= player then return end if param.HoldNoteScore then return end local iNumStates = c.Judgment:GetNumStates() local iFrame = TNSFrames[param.TapNoteScore] local iTapNoteOffset = param.TapNoteOffset if not iFrame then return end if iNumStates == 12 then iFrame = iFrame * 2 if not param.Early then iFrame = iFrame + 1 end end self:playcommand("Reset") c.Judgment:visible(true) c.Judgment:setstate(iFrame) JudgeCmds[param.TapNoteScore](c.Judgment) end } return t
function polypoints(sides, radius, start, displacement) local vertices = {} local x_center = RAND(-displacement,displacement) or 0.0 local y_center = RAND(-displacement,displacement) or 0.0 local angle = start local angle_increment = 2 * math.pi / sides local x=0.0 local y=0.0 -- print(string.format("coordinates for a %d sided regular polygon of radius %d\nVertex",sides,radius),"X"," ","Y") for i=1,sides do x_center = RAND(-displacement,displacement) or 0.0 y_center = RAND(-displacement,displacement) or 0.0 x = x_center + radius * math.cos(angle) y = y_center + radius * math.sin(angle) -- print(string.format("%d\t%f\t%f",i,x,y)) table.insert(vertices,x) table.insert(vertices,y) angle = angle + angle_increment end -- computes coordinates for n-sided, regular polygon of given radius and start angle -- all values are in radians local function create(vertices) local r, g, b = math.random(),math.random(),math.random() local o = display.newPolygon( 0, 0, vertices ) o:translate(RAND(1,screenW),RAND(1,screenH)) o:setFillColor( 0,0,0,0 ) o:setStrokeColor( 1,1,1 ) o.strokeWidth = 1 o.vertices = vertices return o end --create return create(vertices) end function SplitString (line,sep) local res = {} local pos = 1 sep = sep or ',' while true do local c = string.sub(line,pos,pos) if (c == "") then break end if (c == '"') then -- quoted value (ignore separator within) local txt = "" repeat local startp,endp = string.find(line,'^%b""',pos) txt = txt..string.sub(line,startp+1,endp-1) pos = endp + 1 c = string.sub(line,pos,pos) if (c == '"') then txt = txt..'"' end -- check first char AFTER quoted string, if it is another -- quoted string without separator, then append it -- this is the way to "escape" the quote char in a quote. example: -- value1,"blub""blip""boing",value3 will result in blub"blip"boing for the middle until (c ~= '"') table.insert(res,txt) assert(c == sep or c == "") pos = pos + 1 else -- no quotes used, just look for the first separator local startp,endp = string.find(line,sep,pos) if (startp) then table.insert(res,string.sub(line,pos,startp-1)) pos = endp + 1 else -- no separator found -> use rest of string and terminate table.insert(res,string.sub(line,pos)) break end end end return res end
return {'zaza','zazas'}
function GetDesire() return ( 0.0); end
local ReplicatedStorage = game:GetService("ReplicatedStorage") local ServerStorage = game:GetService("ServerStorage") local Knit = require(ReplicatedStorage.Knit) Knit.Shared = ReplicatedStorage.Shared Knit.Modules = ServerStorage.Modules Knit.AddServices(ServerStorage.Services) Knit.Start():ThenCall(print, "Started Knit!"):Catch(warn)
require'nvim-treesitter.configs'.setup { ensure_installed = { "c_sharp", "rust", "html", "css", "scss", "javascript", "typescript", "tsx", "toml", "yaml", "json", "swift", "vim", "lua" }, highlight = { enable = true, disable = { } }, indent = { enable = false, disable = {} } } local parser_config = require'nvim-treesitter.parsers'.get_parser_configs() parser_config.tsx.used_by = { "javascript", "typescript.tsx" }
local txAdminClientVersion = "1.1.0" print("[txAdminClient] Version "..txAdminClientVersion.." starting...") -- Detect version compatibility issues Citizen.CreateThread(function() Citizen.Wait(1000) local serverCompatVersion = GetConvar("txAdmin-clientCompatVersion", "--") if serverCompatVersion ~= txAdminClientVersion then Citizen.CreateThread(function() while true do print("[txAdminClient] This resource version is not compatible with the current txAdmin version. Please update or remove this resource to prevent any issues.") Citizen.Wait(5000) end end) end end) -- FIXME: temp function Citizen.CreateThread(function() local apiPort = GetConvar("txAdmin-apiPort", "invalid"); local apiToken = GetConvar("txAdmin-apiToken", "invalid"); local url = "http://localhost:"..apiPort.."/intercom/monitor" while true do local exData = { txAdminToken = apiToken, alive = true } PerformHttpRequest(url, function(httpCode, data, resultHeaders) local resp = tostring(data) if httpCode ~= 200 or resp ~= 'okay' then print("[txAdminClient] HeartBeat failed with message: "..resp) end end, 'POST', json.encode(exData), {['Content-Type']='application/json'}) Citizen.Wait(3000) end end) -- Kick all players RegisterCommand("txaKickAll", function(source, args) if args[1] == nil then args[1] = 'no reason provided' end print("[txAdminClient] Kicking all players with reason: "..args[1]) for _, pid in pairs(GetPlayers()) do DropPlayer(pid, "Kicked for: " .. args[1]) end CancelEvent() end, true) -- Kick specific player RegisterCommand("txaKickID", function(source, args) if args[1] ~= nil then if args[2] == nil then args[2] = 'no reason provided' end print("[txAdminClient] Kicking #"..args[1].." with reason: "..args[2]) DropPlayer(args[1], "Kicked for: " .. args[2]) else print('[txAdminClient] invalid arguments for txaKickID') end CancelEvent() end, true) -- Broadcast admin message to all players RegisterCommand("txaBroadcast", function(source, args) if args[1] ~= nil then print("[txAdminClient] Admin Broadcast: "..args[1]) TriggerClientEvent("chat:addMessage", -1, { args = { "Admin Broadcast", args[1] }, color = {255, 0, 0} }) else print('[txAdminClient] invalid arguments for txaBroadcast') end CancelEvent() end, true) -- Send admin direct message to specific player RegisterCommand("txaSendDM", function(source, args) if args[1] ~= nil and args[2] ~= nil then print("[txAdminClient] Admin DM to #"..args[1]..": "..args[2]) TriggerClientEvent("chat:addMessage", args[1], { args = { "Admin Direct Message", args[2] }, color = {255, 0, 0} }) else print('[txAdminClient] invalid arguments for txaSendDM') end CancelEvent() end, true) -- Get all resources/statuses and report back to txAdmin RegisterCommand("txaReportResources", function(source, args) print("===============================================") local max = GetNumResources() - 1 -- max = 1 for i = 0, max do local name = GetResourceByFindIndex(i) local state = GetResourceState(name) local path = GetResourcePath(name) print(state .. "\t" .. name .. "\t" .. path) end end, true)
if vim.b.did_ftp == true then return end vim.bo.commentstring = "#\\ %s" vim.opt_local.cursorline = true vim.opt_local.cursorcolumn = false
local config = {} function config.lsp() local servers = { 'bash', 'cpp', 'css', 'dart', 'docker', 'elixir', 'go', 'graphql', 'html', 'java', 'js-ts', 'json', 'latex', 'lua', 'omnisharp', 'php', 'python', 'ruby', 'rust', 'svelte', 'vim', 'yaml' } for _, server in ipairs(servers) do local settins = {lsp_config = "lsp.global.languages." .. server} require(settins.lsp_config) end end function config.dart() if not packer_plugins["plenary.nvim"].loaded then vim.cmd [[packadd plenary.nvim]] end require("flutter-tools").setup {} end function config.treesitter() if not packer_plugins["playground"].loaded then vim.cmd [[packadd playground]] end require"nvim-treesitter.configs".setup { ensure_installed = "all", ignore_install = {"haskell"}, highlight = {enable = true}, indent = {enable = {"javascriptreact"}}, playground = { enable = true, disable = {}, updatetime = 25, persist_queries = false, keybindings = { toggle_query_editor = "o", toggle_hl_groups = "i", toggle_injected_languages = "t", toggle_anonymous_nodes = "a", toggle_language_display = "I", focus_language = "f", unfocus_language = "F", update = "R", goto_node = "<cr>", show_help = "?" } }, autotag = {enable = true}, rainbow = {enable = true}, context_commentstring = { enable = true, config = {javascriptreact = {style_element = "{/*%s*/}"}} } } end function config.jump() vim.cmd([[unmap <leader>j]]) vim.g.any_jump_disable_default_keybindings = 1 vim.g.any_jump_list_numbers = 1 end function config.trouble() require("trouble").setup { height = 12, mode = "lsp_document_diagnostics", use_lsp_diagnostic_signs = true, action_keys = { refresh = "r", toggle_mode = "m", toggle_preview = "P", close_folds = "zc", open_folds = "zo", toggle_fold = "zt" } } end function config.symbols() require("symbols-outline").setup { highlight_hovered_item = true, show_guides = true } end function config.dependency() require"dependency_assist".setup {} end return config
--[[ This file was extracted by 'EsoLuaGenerator' at '2021-09-04 16:42:28' 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. **************************************************************************** ]] -- ColorDef implementation ZO_ColorDef = ZO_Object:Subclass() function ZO_ColorDef:New(r, g, b, a) local c = ZO_Object.New(self) if type(r) == "string" then c.r, c.g, c.b, c.a = self.HexToFloats(r) elseif type(r) == "table" then local otherColorDef = r c.r = otherColorDef.r or 1 c.g = otherColorDef.g or 1 c.b = otherColorDef.b or 1 c.a = otherColorDef.a or 1 else c.r = r or 1 c.g = g or 1 c.b = b or 1 c.a = a or 1 end return c end function ZO_ColorDef.FromInterfaceColor(colorType, fieldValue) return ZO_ColorDef:New(GetInterfaceColor(colorType, fieldValue)) end function ZO_ColorDef:UnpackRGB() return self.r, self.g, self.b end function ZO_ColorDef:UnpackRGBA() return self.r, self.g, self.b, self.a end function ZO_ColorDef:SetRGB(r, g, b) self.r = r self.g = g self.b = b end function ZO_ColorDef:SetRGBA(r, g, b, a) self.r = r self.g = g self.b = b self.a = a end function ZO_ColorDef:SetAlpha(a) self.a = a end function ZO_ColorDef:IsEqual(other) return self.r == other.r and self.g == other.g and self.b == other.b and self.a == other.a end function ZO_ColorDef:Clone() return ZO_ColorDef:New(self:UnpackRGBA()) end function ZO_ColorDef:ToHex() return self.FloatsToHex(self.r, self.g, self.b, 1) end function ZO_ColorDef:ToARGBHex() return self.FloatsToHex(self.r, self.g, self.b, self.a) end function ZO_ColorDef:Colorize(text) local combineTable = { "|c", self:ToHex(), tostring(text), "|r" } return table.concat(combineTable) end function ZO_ColorDef:Lerp(colorToLerpTorwards, amount) return ZO_ColorDef:New( zo_lerp(self.r, colorToLerpTorwards.r, amount), zo_lerp(self.g, colorToLerpTorwards.g, amount), zo_lerp(self.b, colorToLerpTorwards.b, amount), zo_lerp(self.a, colorToLerpTorwards.a, amount) ) end function ZO_ColorDef:ToHSL() return ConvertRGBToHSL(self.r, self.g, self.b) end function ZO_ColorDef:ToHSV() return ConvertRGBToHSV(self.r, self.g, self.b) end -- Utility functions for ColorDef... -- Some of these functions are not fast, they were copied from an internal dev utility. -- RGBA values are values from 0 - 255 -- Float values are values from 0 - 1 -- Hex values are either 6 (RRGGBB) or 8 (AARRGGBB) character hexideciaml strings (e.g.: 0fc355, bb0fc355) local g_colorDef = ZO_ColorDef function ZO_ColorDef.RGBAToFloats(r, g, b, a) return r / 255, g / 255, b / 255, a / 255 end function ZO_ColorDef.FloatsToRGBA(r, g, b, a) return zo_round(r * 255), zo_round(g * 255), zo_round(b * 255), zo_round(a * 255) end function ZO_ColorDef.RGBAToStrings(r, g, b, a) return string.format("%d", r), string.format("%d", g), string.format("%d", b), string.format("%d", a) end function ZO_ColorDef.FloatsToStrings(r, g, b, a) return string.format("%.3f", r), string.format("%.3f", g), string.format("%.3f", b), string.format("%.3f", a) end function ZO_ColorDef.RGBAToHex(r, g, b, a) if a == 255 then return string.format("%02x%02x%02x", r, g, b) else return string.format("%02x%02x%02x%02x", a, r, g, b) end end function ZO_ColorDef.FloatsToHex(r, g, b, a) r, g, b, a = g_colorDef.FloatsToRGBA(r, g, b, a) return g_colorDef.RGBAToHex(r, g, b, a) end do local function ConsumeRightmostChannel(value) local channel = value % 256 value = zo_floor(value / 256) return channel, value end function ZO_ColorDef.HexToRGBA(hexColor) local hexColorLen = #hexColor if hexColorLen >= 6 then local value = tonumber(hexColor, 16) if value then local r, g, b, a b, value = ConsumeRightmostChannel(value) g, value = ConsumeRightmostChannel(value) r, value = ConsumeRightmostChannel(value) if hexColorLen >= 8 then a = ConsumeRightmostChannel(value) else a = 255 end return r, g, b, a end end end function ZO_ColorDef.HexToFloats(hexColor) local r, g, b, a = g_colorDef.HexToRGBA(hexColor) if r then return g_colorDef.RGBAToFloats(r, g, b, a) end end end
--[[-------------------------------------------------------------------- optparser.lua: does parser-based optimizations This file is part of LuaSrcDiet. Copyright (c) 2008 Kein-Hong Man <[email protected]> The COPYRIGHT file describes the conditions under which this software may be distributed. See the ChangeLog for more information. ----------------------------------------------------------------------]] --[[-------------------------------------------------------------------- -- NOTES: -- * For more parser-based optimization ideas, see the TODO items or -- look at technotes.txt. -- * The processing load is quite significant, but since this is an -- off-line text processor, I believe we can wait a few seconds. -- * TODO: might process "local a,a,a" wrongly... need tests! -- * TODO: remove position handling if overlapped locals (rem < 0) -- needs more study, to check behaviour -- * TODO: there are probably better ways to do allocation, e.g. by -- choosing better methods to sort and pick locals... -- * TODO: we don't need 53*63 two-letter identifiers; we can make -- do with significantly less depending on how many that are really -- needed and improve entropy; e.g. 13 needed -> choose 4*4 instead ----------------------------------------------------------------------]] local base = {} -- local base = _G -- local string = require "string" -- local table = require "table" -- module "optparser" ---------------------------------------------------------------------- -- Letter frequencies for reducing symbol entropy (fixed version) -- * Might help a wee bit when the output file is compressed -- * See Wikipedia: http://en.wikipedia.org/wiki/Letter_frequencies -- * We use letter frequencies according to a Linotype keyboard, plus -- the underscore, and both lower case and upper case letters. -- * The arrangement below (LC, underscore, %d, UC) is arbitrary. -- * This is certainly not optimal, but is quick-and-dirty and the -- process has no significant overhead ---------------------------------------------------------------------- local LETTERS = "etaoinshrdlucmfwypvbgkqjxz_ETAOINSHRDLUCMFWYPVBGKQJXZ" local ALPHANUM = "etaoinshrdlucmfwypvbgkqjxz_0123456789ETAOINSHRDLUCMFWYPVBGKQJXZ" -- names or identifiers that must be skipped -- * the first two lines are for keywords local SKIP_NAME = {} for v in string.gmatch([[ and break do else elseif end false for function if in local nil not or repeat return then true until while self]], "%S+") do SKIP_NAME[v] = true end ------------------------------------------------------------------------ -- variables and data structures ------------------------------------------------------------------------ local toklist, seminfolist, -- token lists globalinfo, localinfo, -- variable information tables globaluniq, localuniq, -- unique name tables var_new, -- index of new variable names varlist -- list of output variables ---------------------------------------------------------------------- -- preprocess information table to get lists of unique names ---------------------------------------------------------------------- local function preprocess(infotable) local uniqtable = {} for i = 1, #infotable do -- enumerate info table local obj = infotable[i] local name = obj.name -------------------------------------------------------------------- if not uniqtable[name] then -- not found, start an entry uniqtable[name] = { decl = 0, token = 0, size = 0, } end -------------------------------------------------------------------- local uniq = uniqtable[name] -- count declarations, tokens, size uniq.decl = uniq.decl + 1 local xref = obj.xref local xcount = #xref uniq.token = uniq.token + xcount uniq.size = uniq.size + xcount * #name -------------------------------------------------------------------- if obj.decl then -- if local table, create first,last pairs obj.id = i obj.xcount = xcount if xcount > 1 then -- if ==1, means local never accessed obj.first = xref[2] obj.last = xref[xcount] end -------------------------------------------------------------------- else -- if global table, add a back ref uniq.id = i end -------------------------------------------------------------------- end--for return uniqtable end ---------------------------------------------------------------------- -- calculate actual symbol frequencies, in order to reduce entropy -- * this may help further reduce the size of compressed sources -- * note that since parsing optimizations is put before lexing -- optimizations, the frequency table is not exact! -- * yes, this will miss --keep block comments too... ---------------------------------------------------------------------- local function recalc_for_entropy(option) local byte = string.byte local char = string.char -- table of token classes to accept in calculating symbol frequency local ACCEPT = { TK_KEYWORD = true, TK_NAME = true, TK_NUMBER = true, TK_STRING = true, TK_LSTRING = true, } if not option["opt-comments"] then ACCEPT.TK_COMMENT = true ACCEPT.TK_LCOMMENT = true end -------------------------------------------------------------------- -- create a new table and remove any original locals by filtering -------------------------------------------------------------------- local filtered = {} for i = 1, #toklist do filtered[i] = seminfolist[i] end for i = 1, #localinfo do -- enumerate local info table local obj = localinfo[i] local xref = obj.xref for j = 1, obj.xcount do local p = xref[j] filtered[p] = "" -- remove locals end end -------------------------------------------------------------------- local freq = {} -- reset symbol frequency table for i = 0, 255 do freq[i] = 0 end for i = 1, #toklist do -- gather symbol frequency local tok, info = toklist[i], filtered[i] if ACCEPT[tok] then for j = 1, #info do local c = byte(info, j) freq[c] = freq[c] + 1 end end--if end--for -------------------------------------------------------------------- -- function to re-sort symbols according to actual frequencies -------------------------------------------------------------------- local function resort(symbols) local symlist = {} for i = 1, #symbols do -- prepare table to sort local c = byte(symbols, i) symlist[i] = { c = c, freq = freq[c], } end table.sort(symlist, -- sort selected symbols function(v1, v2) return v1.freq > v2.freq end ) local charlist = {} -- reconstitute the string for i = 1, #symlist do charlist[i] = char(symlist[i].c) end return table.concat(charlist) end -------------------------------------------------------------------- LETTERS = resort(LETTERS) -- change letter arrangement ALPHANUM = resort(ALPHANUM) end ---------------------------------------------------------------------- -- returns a string containing a new local variable name to use, and -- a flag indicating whether it collides with a global variable -- * trapping keywords and other names like 'self' is done elsewhere ---------------------------------------------------------------------- local function new_var_name() local var local cletters, calphanum = #LETTERS, #ALPHANUM local v = var_new if v < cletters then -- single char v = v + 1 var = string.sub(LETTERS, v, v) else -- longer names local range, sz = cletters, 1 -- calculate # chars fit repeat v = v - range range = range * calphanum sz = sz + 1 until range > v local n = v % cletters -- left side cycles faster v = (v - n) / cletters -- do first char first n = n + 1 var = string.sub(LETTERS, n, n) while sz > 1 do local m = v % calphanum v = (v - m) / calphanum m = m + 1 var = var..string.sub(ALPHANUM, m, m) sz = sz - 1 end end var_new = var_new + 1 return var, globaluniq[var] ~= nil end ---------------------------------------------------------------------- -- calculate and print some statistics -- * probably better in main source, put here for now ---------------------------------------------------------------------- local function stats_summary(globaluniq, localuniq, afteruniq, option) local fmt = string.format local opt_details = option.DETAILS local uniq_g , uniq_li, uniq_lo, uniq_ti, uniq_to, -- stats needed decl_g, decl_li, decl_lo, decl_ti, decl_to, token_g, token_li, token_lo, token_ti, token_to, size_g, size_li, size_lo, size_ti, size_to = 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 local function avg(c, l) -- safe average function if c == 0 then return 0 end return l / c end -------------------------------------------------------------------- -- collect statistics (note: globals do not have declarations!) -------------------------------------------------------------------- for name, uniq in pairs(globaluniq) do uniq_g = uniq_g + 1 token_g = token_g + uniq.token size_g = size_g + uniq.size end for name, uniq in pairs(localuniq) do uniq_li = uniq_li + 1 decl_li = decl_li + uniq.decl token_li = token_li + uniq.token size_li = size_li + uniq.size end for name, uniq in pairs(afteruniq) do uniq_lo = uniq_lo + 1 decl_lo = decl_lo + uniq.decl token_lo = token_lo + uniq.token size_lo = size_lo + uniq.size end uniq_ti = uniq_g + uniq_li decl_ti = decl_g + decl_li token_ti = token_g + token_li size_ti = size_g + size_li uniq_to = uniq_g + uniq_lo decl_to = decl_g + decl_lo token_to = token_g + token_lo size_to = size_g + size_lo -------------------------------------------------------------------- -- detailed stats: global list -------------------------------------------------------------------- if opt_details then local sorted = {} -- sort table of unique global names by size for name, uniq in pairs(globaluniq) do uniq.name = name sorted[#sorted + 1] = uniq end table.sort(sorted, function(v1, v2) return v1.size > v2.size end ) local tabf1, tabf2 = "%8s%8s%10s %s", "%8d%8d%10.2f %s" local hl = string.rep("-", 44) print("*** global variable list (sorted by size) ***\n"..hl) print(fmt(tabf1, "Token", "Input", "Input", "Global")) print(fmt(tabf1, "Count", "Bytes", "Average", "Name")) print(hl) for i = 1, #sorted do local uniq = sorted[i] print(fmt(tabf2, uniq.token, uniq.size, avg(uniq.token, uniq.size), uniq.name)) end print(hl) print(fmt(tabf2, token_g, size_g, avg(token_g, size_g), "TOTAL")) print(hl.."\n") -------------------------------------------------------------------- -- detailed stats: local list -------------------------------------------------------------------- local tabf1, tabf2 = "%8s%8s%8s%10s%8s%10s %s", "%8d%8d%8d%10.2f%8d%10.2f %s" local hl = string.rep("-", 70) print("*** local variable list (sorted by allocation order) ***\n"..hl) print(fmt(tabf1, "Decl.", "Token", "Input", "Input", "Output", "Output", "Global")) print(fmt(tabf1, "Count", "Count", "Bytes", "Average", "Bytes", "Average", "Name")) print(hl) for i = 1, #varlist do -- iterate according to order assigned local name = varlist[i] local uniq = afteruniq[name] local old_t, old_s = 0, 0 for j = 1, #localinfo do -- find corresponding old names and calculate local obj = localinfo[j] if obj.name == name then old_t = old_t + obj.xcount old_s = old_s + obj.xcount * #obj.oldname end end print(fmt(tabf2, uniq.decl, uniq.token, old_s, avg(old_t, old_s), uniq.size, avg(uniq.token, uniq.size), name)) end print(hl) print(fmt(tabf2, decl_lo, token_lo, size_li, avg(token_li, size_li), size_lo, avg(token_lo, size_lo), "TOTAL")) print(hl.."\n") end--if opt_details -------------------------------------------------------------------- -- display output -------------------------------------------------------------------- -- local tabf1, tabf2 = "%-16s%8s%8s%8s%8s%10s", "%-16s%8d%8d%8d%8d%10.2f" -- local hl = string.rep("-", 58) -- print("*** local variable optimization summary ***\n"..hl) -- print(fmt(tabf1, "Variable", "Unique", "Decl.", "Token", "Size", "Average")) -- print(fmt(tabf1, "Types", "Names", "Count", "Count", "Bytes", "Bytes")) -- print(hl) -- print(fmt(tabf2, "Global", uniq_g, decl_g, token_g, size_g, avg(token_g, size_g))) -- print(hl) -- print(fmt(tabf2, "Local (in)", uniq_li, decl_li, token_li, size_li, avg(token_li, size_li))) -- print(fmt(tabf2, "TOTAL (in)", uniq_ti, decl_ti, token_ti, size_ti, avg(token_ti, size_ti))) -- print(hl) -- print(fmt(tabf2, "Local (out)", uniq_lo, decl_lo, token_lo, size_lo, avg(token_lo, size_lo))) -- print(fmt(tabf2, "TOTAL (out)", uniq_to, decl_to, token_to, size_to, avg(token_to, size_to))) -- print(hl.."\n") end ---------------------------------------------------------------------- -- main entry point -- * does only local variable optimization for now ---------------------------------------------------------------------- function base.optimize(option, _toklist, _seminfolist, _globalinfo, _localinfo) -- set tables toklist, seminfolist, globalinfo, localinfo = _toklist, _seminfolist, _globalinfo, _localinfo var_new = 0 -- reset variable name allocator varlist = {} ------------------------------------------------------------------ -- preprocess global/local tables, handle entropy reduction ------------------------------------------------------------------ globaluniq = preprocess(globalinfo) localuniq = preprocess(localinfo) if option["opt-entropy"] then -- for entropy improvement recalc_for_entropy(option) end ------------------------------------------------------------------ -- build initial declared object table, then sort according to -- token count, this might help assign more tokens to more common -- variable names such as 'e' thus possibly reducing entropy -- * an object knows its localinfo index via its 'id' field -- * special handling for "self" special local (parameter) here ------------------------------------------------------------------ local object = {} for i = 1, #localinfo do object[i] = localinfo[i] end table.sort(object, -- sort largest first function(v1, v2) return v1.xcount > v2.xcount end ) ------------------------------------------------------------------ -- the special "self" function parameters must be preserved -- * the allocator below will never use "self", so it is safe to -- keep those implicit declarations as-is ------------------------------------------------------------------ local temp, j, gotself = {}, 1, false for i = 1, #object do local obj = object[i] if not obj.isself then temp[j] = obj j = j + 1 else gotself = true end end object = temp ------------------------------------------------------------------ -- a simple first-come first-served heuristic name allocator, -- note that this is in no way optimal... -- * each object is a local variable declaration plus existence -- * the aim is to assign short names to as many tokens as possible, -- so the following tries to maximize name reuse -- * note that we preserve sort order ------------------------------------------------------------------ local nobject = #object while nobject > 0 do local varname, gcollide repeat varname, gcollide = new_var_name() -- collect a variable name until not SKIP_NAME[varname] -- skip all special names varlist[#varlist + 1] = varname -- keep a list local oleft = nobject ------------------------------------------------------------------ -- if variable name collides with an existing global, the name -- cannot be used by a local when the name is accessed as a global -- during which the local is alive (between 'act' to 'rem'), so -- we drop objects that collides with the corresponding global ------------------------------------------------------------------ if gcollide then -- find the xref table of the global local gref = globalinfo[globaluniq[varname].id].xref local ngref = #gref -- enumerate for all current objects; all are valid at this point for i = 1, nobject do local obj = object[i] local act, rem = obj.act, obj.rem -- 'live' range of local -- if rem < 0, it is a -id to a local that had the same name -- so follow rem to extend it; does this make sense? while rem < 0 do rem = localinfo[-rem].rem end local drop for j = 1, ngref do local p = gref[j] if p >= act and p <= rem then drop = true end -- in range? end if drop then obj.skip = true oleft = oleft - 1 end end--for end--if gcollide ------------------------------------------------------------------ -- now the first unassigned local (since it's sorted) will be the -- one with the most tokens to rename, so we set this one and then -- eliminate all others that collides, then any locals that left -- can then reuse the same variable name; this is repeated until -- all local declaration that can use this name is assigned -- * the criteria for local-local reuse/collision is: -- A is the local with a name already assigned -- B is the unassigned local under consideration -- => anytime A is accessed, it cannot be when B is 'live' -- => to speed up things, we have first/last accesses noted ------------------------------------------------------------------ while oleft > 0 do local i = 1 while object[i].skip do -- scan for first object i = i + 1 end ------------------------------------------------------------------ -- first object is free for assignment of the variable name -- [first,last] gives the access range for collision checking ------------------------------------------------------------------ oleft = oleft - 1 local obja = object[i] i = i + 1 obja.newname = varname obja.skip = true obja.done = true local first, last = obja.first, obja.last local xref = obja.xref ------------------------------------------------------------------ -- then, scan all the rest and drop those colliding -- if A was never accessed then it'll never collide with anything -- otherwise trivial skip if: -- * B was activated after A's last access (last < act) -- * B was removed before A's first access (first > rem) -- if not, see detailed skip below... ------------------------------------------------------------------ if first and oleft > 0 then -- must have at least 1 access local scanleft = oleft while scanleft > 0 do while object[i].skip do -- next valid object i = i + 1 end scanleft = scanleft - 1 local objb = object[i] i = i + 1 local act, rem = objb.act, objb.rem -- live range of B -- if rem < 0, extend range of rem thru' following local while rem < 0 do rem = localinfo[-rem].rem end -------------------------------------------------------- if not(last < act or first > rem) then -- possible collision -------------------------------------------------------- -- B is activated later than A or at the same statement, -- this means for no collision, A cannot be accessed when B -- is alive, since B overrides A (or is a peer) -------------------------------------------------------- if act >= obja.act then for j = 1, obja.xcount do -- ... then check every access local p = xref[j] if p >= act and p <= rem then -- A accessed when B live! oleft = oleft - 1 objb.skip = true break end end--for -------------------------------------------------------- -- A is activated later than B, this means for no collision, -- A's access is okay since it overrides B, but B's last -- access need to be earlier than A's activation time -------------------------------------------------------- else if objb.last and objb.last >= obja.act then oleft = oleft - 1 objb.skip = true end end end -------------------------------------------------------- if oleft == 0 then break end end end--if first ------------------------------------------------------------------ end--while ------------------------------------------------------------------ -- after assigning all possible locals to one variable name, the -- unassigned locals/objects have the skip field reset and the table -- is compacted, to hopefully reduce iteration time ------------------------------------------------------------------ local temp, j = {}, 1 for i = 1, nobject do local obj = object[i] if not obj.done then obj.skip = false temp[j] = obj j = j + 1 end end object = temp -- new compacted object table nobject = #object -- objects left to process ------------------------------------------------------------------ end--while ------------------------------------------------------------------ -- after assigning all locals with new variable names, we can -- patch in the new names, and reprocess to get 'after' stats ------------------------------------------------------------------ for i = 1, #localinfo do -- enumerate all locals local obj = localinfo[i] local xref = obj.xref if obj.newname then -- if got new name, patch it in for j = 1, obj.xcount do local p = xref[j] -- xrefs indexes the token list seminfolist[p] = obj.newname end obj.name, obj.oldname -- adjust names = obj.newname, obj.name else obj.oldname = obj.name -- for cases like 'self' end end ------------------------------------------------------------------ -- deal with statistics output ------------------------------------------------------------------ if gotself then -- add 'self' to end of list varlist[#varlist + 1] = "self" end local afteruniq = preprocess(localinfo) stats_summary(globaluniq, localuniq, afteruniq, option) ------------------------------------------------------------------ end return base
# -*- lua -*- propT = { state = { validT = { experimental = 1, testing = 1, obsolete = 1 }, displayT = { experimental = { short = "(E)", long = "(E)", color = "blue", doc = "Experimental", }, testing = { short = "(T)", long = "(T)", color = "green", doc = "Testing", }, obsolete = { short = "(O)", long = "(O)", color = "red", doc = "Obsolete", }, }, }, lmod = { validT = { sticky = 1 }, displayT = { sticky = { short = "(S)", long = "(S)", color = "red", doc = "Module is Sticky, requires --force to unload or purge", }, }, }, arch = { validT = { mic = 1, offload = 1, gpu = 1, }, displayT = { ["mic:offload"] = { short = "(*)", long = "(m,o)", color = "blue", doc = "built for host, native MIC and offload to the MIC", }, ["mic"] = { short = "(m)", long = "(m)", color = "blue", doc = "built for host and native MIC", }, ["offload"] = { short = "(o)", long = "(o)", color = "blue", doc = "built for offload to the MIC only",}, ["gpu"] = { short = "(g)", long = "(g)", color = "red" , doc = "built for GPU",}, ["gpu:mic"] = { short = "(gm)", long = "(g,m)", color = "red" , doc = "built natively for MIC and GPU",}, ["gpu:mic:offload"] = { short = "(@)", long = "(g,m,o)", color = "red" , doc = "built natively for MIC and GPU and offload to the MIC",}, }, }, status = { validT = { active = 1, }, displayT = { active = { short = "(L)", long = "(L)", color = "yellow", doc = "Module is loaded", }, }, }, pkgtype = { validT = { dev = 1, script = 1, mpi = 1, viz = 1, io = 1, }, displayT = { ["dev"] = { short = "(dev)", long = "(dev)", color = "blue", doc = "Development Application / Library", }, ["script"] = { short = "(sc)", long = "(sc)", color = "yellow", doc = "Scripting Language", }, ["mpi"] = { short = "(M)", long = "(mpi)", color = "cyan", doc = "MPI Implementation", }, ["viz"] = { short = "(V)", long = "(viz)", color = "magenta", doc = "Visualization Package", }, ["io"] = { short = "(io)", long = "(io)", color = "blue", doc = "Input/Output Library", }, }, }, scitype = { validT = { math = 1, atm = 1, gen = 1, bio = 1, eng = 1, chem = 1, phys = 1, geo = 1 }, displayT = { ["math"] = { short = "(M)", long = "(math)", color = "blue", doc = "Math related software", }, ["atm"] = { short = "(A)", long = "(atm)", color = "cyan", doc = "Atmospheric science software", }, ["gen"] = { short = "(G)", long = "(gen)", color = "red", doc = "Genomic science related", }, ["bio"] = { short = "(B)", long = "(bio)", color = "green", doc = "Biology related software", }, ["eng"] = { short = "(E)", long = "(eng)", color = "yellow", doc = "Engineering related software", }, ["chem"] = { short = "(C)", long = "(chem)", color = "magenta", doc = "Chemistry related software", }, ["phys"] = { short = "(P)", long = "(phys)", color = "white", doc = "Physics related software", }, ["geo"] = { short = "(G)", long = "(geo)", color = "yellow", doc = "Geology / Geophysics related software", }, }, }, }
--- A tiny program to remove most errors in your program. -- -- No, this isn't serious. It's a terrible idea. -- -- @usage require("error-fix") print(2 + false) -- won't error! local mt, void = {}, function() return nil end local methods = { "__call", "__index", "__newindex", "__len", "__unm", "__add", "__sub", "__mul", "__div", "__pow", "__concat", } for _, method in ipairs(methods) do mt[method] = void end debug.setmetatable(nil, mt) debug.setmetatable(1, mt) debug.setmetatable(true, mt) debug.setmetatable(print, mt) local st = debug.getmetatable("") for k, v in pairs(mt) do st[k] = st[k] or v end
local ffi = require 'ffi' local ParseBack = require 'parseback' ffi.cdef [[ struct Expr; struct Select; struct sql_trigger; enum ast_type { AST_TYPE_UNDEFINED = 0, AST_TYPE_SELECT, AST_TYPE_EXPR, AST_TYPE_TRIGGER, ast_type_MAX }; struct sql_parsed_ast { const char* sql_query; /**< original query */ enum ast_type ast_type; /**< Type of parsed_ast member. */ bool keep_ast; /**< Keep AST after .parse */ union { struct Expr *expr; struct Select *select; struct sql_trigger *trigger; }; }; ]] -- print (ParseBack.dot('union {struct {int x, y;}; long il; struct {Point px; union blurb bl;} st;}[5]')) -- print (ParseBack.dot('enum twoenums', true)) -- print (ParseBack.dot('getit', true)) -- print (ParseBack.dot('enum ast_type', true)) print (ParseBack.dot('struct sql_parsed_ast', true))
data:extend({ { type = "radar", name = "long-range-radar", icon = "__Long_Range_Radar__/graphics/item_icon_advanced_radar.png", icon_size = 64, icon_mipmaps = 4, flags = {"placeable-player", "player-creation"}, minable = {hardness = 0.2, mining_time = 0.5, result = "long-range-radar"}, max_health = 250, corpse = "big-remnants", resistances = { { type = "fire", percent = 70 }, { type = "impact", percent = 30 } }, collision_box = {{-1.2, -1.2}, {1.2, 1.2}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, energy_per_sector = "10MJ", max_distance_of_sector_revealed = 28, max_distance_of_nearby_sector_revealed = 6, energy_per_nearby_scan = "250kJ", energy_source = { type = "electric", usage_priority = "secondary-input" }, energy_usage = "1200kW", integration_patch = { filename = "__base__/graphics/entity/radar/radar-integration.png", priority = "low", width = 119, height = 108, apply_projection = false, direction_count = 1, repeat_count = 64, line_length = 1, shift = util.by_pixel(1.5, 4), hr_version = { filename = "__base__/graphics/entity/radar/hr-radar-integration.png", priority = "low", width = 238, height = 216, apply_projection = false, direction_count = 1, repeat_count = 64, line_length = 1, shift = util.by_pixel(1.5, 4), scale = 0.5 } }, pictures = { layers = { { filename = "__base__/graphics/entity/radar/radar.png", priority = "low", width = 98, height = 128, apply_projection = false, direction_count = 64, line_length = 8, shift = util.by_pixel(1, -16), hr_version = { filename = "__base__/graphics/entity/radar/hr-radar.png", priority = "low", width = 196, height = 254, apply_projection = false, direction_count = 64, line_length = 8, shift = util.by_pixel(1, -16), scale = 0.5 } }, { filename = "__base__/graphics/entity/radar/radar-shadow.png", priority = "low", width = 172, height = 94, apply_projection = false, direction_count = 64, line_length = 8, shift = util.by_pixel(39,3), draw_as_shadow = true, hr_version = { filename = "__base__/graphics/entity/radar/hr-radar-shadow.png", priority = "low", width = 343, height = 186, apply_projection = false, direction_count = 64, line_length = 8, shift = util.by_pixel(39.25,3), draw_as_shadow = true, scale = 0.5 } } } }, vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 }, working_sound = { sound = { { filename = "__base__/sound/radar.ogg" } }, apparent_volume = 2, }, radius_minimap_visualisation_color = { r = 0.059, g = 0.092, b = 0.235, a = 0.275 }, fast_replaceable_group = "radar", } })
local node = require("nodes/node") local gameState = require("data/gamestate") local gameData = require("data/gamedata") local fonts = require("data/fonts") local display = require("data/display") local button = require("nodes/ui/textbutton") local uiOverlay = node:create() uiOverlay.TEXT_COLOR = { 1, 1, 1 } uiOverlay.PAUSE_TEXT = " | | " uiOverlay.PLAY_TEXT = " > " function uiOverlay:init() node.init(self) self.playPauseButton = button:create(self.PAUSE_TEXT, 10, 10, 41, 50, fonts.small) self.playPauseButton:addClickListener(function() if gameState:get() == gameState.PLAYING then gameState:set(gameState.PAUSED) elseif gameState:get() == gameState.PAUSED then gameState:set(gameState.PLAYING) end end) node.addChild(self, self.playPauseButton) end function uiOverlay:deinit() node.deinit(self) end function uiOverlay:update(dt) node.update(self, dt) end function uiOverlay:render() node.render(self) if gameState:get() == gameState.PLAYING then self:drawScore() self.playPauseButton:setText(self.PAUSE_TEXT) elseif gameState:get() == gameState.PAUSED then self.playPauseButton:setText(self.PLAY_TEXT) end end function uiOverlay:onMousePressed(x, y, button, istouch) self.playPauseButton:onMousePressed(x, y, button, istouch) end function uiOverlay:drawScore() love.graphics.setColor(self.TEXT_COLOR) love.graphics.setFont(fonts.medium) local scoreText = tostring(gameData.score) local textWidth = self:getTextWidth(scoreText) love.graphics.print(scoreText, display.GAME_WIDTH / 2 - textWidth / 2, display.GAME_HEIGHT / 10, 0, 1, 1) end function uiOverlay:getTextWidth(text) local font = love.graphics.getFont() return font:getWidth(text) end function uiOverlay:getTextHeight() local font = love.graphics.getFont() return font:getHeight() end function uiOverlay:onPauseClicked() end return uiOverlay
SURVIVAL_IN_POLLUTION = "survival_in_pollution"
--- --- Copy a file from the system to a mass storage gadget --- usb = luausb.create({ id = 0, type = "keyboard"}, {id = 0, type = "storage" }) kb = usb.dev[1] local LABEL = "MY_DRIVE_LABEL" -- label of the drive (as assigned by you) while true do print("idle") -- poll until usb plugged in while usb.state() == "not attached" do wait(1000) end print("running") -- wait 1 second for things to settle down wait(1000) kb.chord(MOD_LSUPER, KEY_R) wait(1000) kb.string("powershell\n") wait(2000) kb.string("$drive = Get-WmiObject -Class Win32_LogicalDisk -Filter \"VolumeName='" .. LABEL .. "'\" | Select -Expand DeviceID\n") print("done") -- poll until usb unplugged while usb.state() == "configured" do wait(1000) end print("disconnected") end
local EnemyBuffList = {} local function SortBuffs(buffs) local passive_buff = {} local other_buff = {} for _, buff in ipairs(buffs) do if buff.icon and buff.icon ~= "0" and buff.icon ~= "" and buff.icon ~= 0 then if buff.id >= 3000000 and buff.id < 4000000 then table.insert(passive_buff, buff) else table.insert(other_buff, buff) end end end return passive_buff ,other_buff end function EnemyBuffList:Start() self.view = SGK.UIReference.Setup(self.gameObject); self.view.transform:DOScale(Vector3(1, 0.1, 1), 0) self.view:SetActive(false) end function EnemyBuffList:ShowView(buffs) local passive_buff ,other_buff = SortBuffs(buffs) if #passive_buff == 0 and #other_buff == 0 then return end local item_count = 0 local id_list = {} for k, buff in ipairs(passive_buff) do if id_list[buff.id] then else item_count = item_count + 1 if item_count > 10 then break end local item = self.view["item"..item_count] id_list[buff.id] = true SGK.ResourcesManager.LoadAsync("icon/" .. buff.icon .. ".png", typeof(UnityEngine.Sprite), function(o) item.icon[UnityEngine.UI.Image].sprite = o; item.icon[UnityEngine.UI.Image]:SetNativeSize() item.icon.transform.localScale = Vector3.one * (buff.icon_scale ~= 0 and buff.icon_scale or 1) item.Text[UI.Text].text = buff._desc; item:SetActive(true) end); end end for k, buff in ipairs(other_buff) do if id_list[buff.id] then else item_count = item_count + 1 if item_count > 10 then break end local item = self.view["item"..item_count] id_list[buff.id] = true SGK.ResourcesManager.LoadAsync("icon/" .. buff.icon .. ".png", typeof(UnityEngine.Sprite), function(o) item.icon[UnityEngine.UI.Image].sprite = o; item.icon[UnityEngine.UI.Image]:SetNativeSize() item.icon.transform.localScale = Vector3.one * (buff.icon_scale ~= 0 and buff.icon_scale or 1) item.Text[UI.Text].text = buff._desc; item:SetActive(true) end); end end self.view.transform.localScale = Vector3(1, 0.1, 1) self.view:SetActive(true) self.view.transform:DOScale(Vector3.one, 0.3) end function EnemyBuffList:CloseView() for i = 1,10,1 do self.view["item"..i]:SetActive(false) end self.view:SetActive(false) self.view.transform.localScale = Vector3(1, 0.1, 1) end return EnemyBuffList;
-- Configurations -- Config = { width = lg.getWidth(), height = lg.getHeight(), debug = true, camera = { scale = 3 }, world = { tileSize = 16, cellSize = 32, }, color = { debug = { _:color('red-800') }, white = { _:color('white') }, black = { _:color('black') }, slopes = { _:color('blue-400') }, bounds = { _:color('red-400') }, overlay = { 0, 0, 0, 0.65 }, highlight = { _:color('green-500') }, radar = { _:color('yellow-300') }, stats = { hp = { _:color('red-300') }, sp = { _:color('green-300') }, xp = { _:color('blue-300') }, } }, ui = { font = { xs = love.graphics.newFont('res/ui/fonts/Fool.ttf', 10), sm = love.graphics.newFont('res/ui/fonts/Fool.ttf', 12), md = love.graphics.newFont('res/ui/fonts/Fool.ttf', 24), lg = love.graphics.newFont('res/ui/fonts/Fool.ttf', 32), xl = love.graphics.newFont('res/ui/fonts/Fool.ttf', 48) } }, }
--[[ author: @sw1tch ]]-- function checkPlayerAdminLevel(player,level) local level = tonumber(level) local a_level = getElementData(player,"admin_level") if not level then if a_level > 0 then return true else return false end return end if a_level == level then return true else return false end end function checkPlayerSupporterLevel(player,level) local level = tonumber(level) local s_level = getElementData(player,"supporter_level") if not level then if s_level > 0 then return true else return false end return end if s_level == level then return true else return false end end -- Kullanım Örneği function use(oyuncu,cmd) if checkPlayerAdminLevel(oyuncu,2) == true then outputChatBox("Admin Level'in 2'ye eşit.", oyuncu) else outputChatBox("Admin Level'in 2'ye eşit değil", oyuncu) end if checkPlayerSupporterLevel(oyuncu,1) == true then outputChatBox("Supporter levelin 1'e eşit.", oyuncu) else outputChatBox("Supporter levelin 1'e eşit değil", oyuncu) end if checkPlayerAdminLevel(oyuncu) == true then outputChatBox("Adminsin.", oyuncu) else outputChatBox("Admin değilsin.",oyuncu) end if checkPlayerSupporterLevel(oyuncu) == true then outputChatBox("Supportersın", oyuncu) else outputChatBox("Supporter değilsin.",oyuncu) end end addCommandHandler("test", use)
function onEvent(name, value1, value2) if name == 'foxyj2' then makeAnimatedLuaSprite( 'foxyj2', 'foxyj2', 0, 0); addAnimationByPrefix('foxyj2', 'foxyj2', 'idle'); setObjectCamera('foxyj2', 'hud') addLuaSprite('foxyj2', true); objectPlayAnimation('foxyj2', 'idle', true); end end
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <[email protected]> -- -- Copyright (C) 2015-2016 Alexey Melnichuk <[email protected]> -- -- Licensed according to the included 'LICENSE' document -- -- This file is part of lua-gntp library. -- ------------------------------------------------------------------ local function prequire(m) local ok, err = pcall(require, m) if ok then return err, m end return nil, err end local function orequire(...) for _, name in ipairs{...} do local mod = prequire(name) if mod then return mod, name end end end local function vrequire(...) local m, n = orequire(...) if m then return m, n end error("Can not fine any of this modules: " .. table.concat({...}, "/"), 2) end local crypto, cryptoName = orequire('crypto', 'openssl') local rand_bytes, make_hash, make_encrypt_fn, make_decrypt_fn if cryptoName == 'openssl' then local Cipher = crypto.cipher local Digest = crypto.digest make_hash = function(algo) local hash = Digest.get(algo) return { digest = function(data, hex) local msg = hash:digest(data) if hex then msg = crypto.hex(msg) end return msg end } end local call_mt = {__call = function(self, ...) return self.digest(...) end} make_encrypt = function(algo) local ctx = Cipher.get(algo) return{ encrypt = setmetatable({ digest = function(data, key, iv, pad) return ctx:encrypt(data, key, iv) end; new = function(key, iv, pad) return ctx:encrypt_new(key, iv, true) end; }, call_mt); decrypt = setmetatable({ digest = function(data, key, iv, pad) return ctx:decrypt(data, key, iv) end; new = function(key, iv, pad) return ctx:decrypt_new(key, iv, true) end; }, call_mt); } end rand_bytes = function(n) return crypto.random(n, false) end elseif cryptoName == 'crypto' then make_hash = function(algo) return { digest = function(data, hex) return crypto.digest(algo, data, not hex) end } end local call_mt = {__call = function(self, ...) return self.digest(...) end} make_encrypt = function(algo) return{ encrypt = setmetatable({ digest = function(data, key, iv, pad) return crypto.encrypt(algo, data, key, iv) end; new = function(key, iv, pad) return crypto.encrypt.new(algo, key, iv, true) end; }, call_mt); decrypt = setmetatable({ digest = function(data, key, iv, pad) return crypto.decrypt(algo, data, key, iv) end; new = function(key, iv, pad) return crypto.decrypt.new(algo, key, iv, true) end; }, call_mt); } end rand_bytes = crypto.rand.pseudo_bytes end if not rand_bytes then rand_bytes = function (n) local r = {} for i = 1, n do r[#r + 1] = string.char(math.random(0, 0xFF)) end return table.concat(r) end end local HASH = {} if make_hash then HASH.MD5 = make_hash('MD5') HASH.SHA1 = make_hash('SHA1') HASH.SHA256 = make_hash('SHA256') HASH.SHA512 = make_hash('SHA512') end local ENCRYPT = {} if make_encrypt then ENCRYPT.AES = make_encrypt('AES-192-CBC'); ENCRYPT.AES.key_size = 24; ENCRYPT.AES.block_size = 16; ENCRYPT.AES.iv_size = 16; ENCRYPT.DES = make_encrypt('DES-CBC'); ENCRYPT.DES.key_size = 8; ENCRYPT.DES.block_size = 8; ENCRYPT.DES.iv_size = 8; ENCRYPT['3DES'] = make_encrypt('DES3'); ENCRYPT['3DES'].key_size = 24; ENCRYPT['3DES'].block_size = 8; ENCRYPT['3DES'].iv_size = 8; end return { hash = HASH; cipher = ENCRYPT; rand_bytes = rand_bytes; }
vol,mute=io.popen("osascript -e 'get Volume settings'"):read("*all"):match(".*output volume:(%d+).*output muted:(%l+).*") vol=tonumber(vol) if mute=="true" then icon="婢" else icon="墳" end if vol==0 then bar=' ' elseif val < 13 then bar='_' elseif val < 25 then bar='▁' elseif val < 38 then bar='▂' elseif val < 50 then bar='▃' elseif val < 63 then bar='▄' elseif val < 75 then bar='▅' elseif val < 88 then bar='▆' elseif val < 100 then bar='▇' elseif val == 100 then bar='█' end print(icon.." "..bar)
return { PlaceObj("ModItemOptionNumber", { "name", "Range", "DisplayName", T(302535920011581, "Range"), "Help", T(302535920011582, "Max Range of Artificial Sun."), "DefaultValue", ArtificialSun.effect_range or 8, "MinValue", 1, "MaxValue", 250, --~ "StepSize", 10, }), }
-------------------------------------------------------------------------------- -- db.lua -------------------------------------------------------------------------------- local string_format = string.format local c = tengine.c local redis = tengine.redis local INFO_MSG = tengine.INFO_MSG local ERROR_MSG = tengine.ERROR_MSG local p = tengine.p local store = require("lib.store") local _M = {} local db function _M.init(conf) db = redis.new(conf.redis or 'redis') if not db then ERROR_MSG("create db failed !!!") end end function _M.driver() return db end function _M.data(name, key) local _define = define.get(name) if not _define then ERROR_MSG("cann't find define %s", type) return end local model = store.model(name, _define) if not model then ERROR_MSG("cann't get %s model !!!", name) return end local data = model:fetch(db, tostring(key)) -- p("db data", name, key, data) return data, model end return _M
-- -- User: Glastis -- Date: 15-Nov-19 -- local file = require('common.file') local utilities = {} local function trim(str) return str:gsub("^%s+", ""):gsub("%s+$", "") end utilities.trim = trim local function get_elem_in_table(table, elem) local i i = 1 while i <= #table do if table[i] == elem then return i end i = i + 1 end return false end utilities.get_elem_in_table = get_elem_in_table local function concatenate_arrays(t1, t2) local i i = 1 while i <= #t2 do t1[#t1 + 1] = t2[i] i = i + 1 end return t1 end utilities.concatenate_arrays = concatenate_arrays local function split(str, separator) local t = {} local i i = 1 for line in string.gmatch(str, "([^" .. separator .. "]+)") do t[i] = line i = i + 1 end return t end utilities.split = split local function exec_function_table(actions, param) local i i = 1 if not param then param = {} end while i <= #actions do actions[i](param[i]) i = i + 1 end end utilities.exec_function_table = exec_function_table local function exec_function_table_revert(actions, param) local i i = #actions if not param then param = {} end while i > 0 do actions[i](param[i]) i = i - 1 end end utilities.exec_function_table_revert = exec_function_table_revert local function debug_info(more, calltrace) if not more then more = " " end if calltrace then local trace trace = split(split(debug.traceback(), '\n')[3], '/') file.write("trace.log", '\n' .. trace[#trace] .. '\n' .. more .. '\n') else file.write("trace.log", more .. '\n') end end utilities.debug_info = debug_info local function var_dump_indent(depth) local ret ret = '' while depth > 0 do ret = ret .. ' ' depth = depth - 1 end return ret end local function var_dump(var, printval, max_depth, cur_depth) if max_depth == nil then max_depth = 1000 end if not cur_depth then cur_depth = 0 end if type(var) == 'table' then local s s = '{ ' for k,v in pairs(var) do if type(k) ~= 'number' then k = '"' .. k .. '"' end if max_depth > 0 then s = s .. '\n' .. var_dump_indent(cur_depth) .. '[' .. k .. '] = ' .. var_dump(v, false, max_depth - 1, cur_depth + 1) .. ',' else s = s .. '\n' .. var_dump_indent(cur_depth) .. '[' .. k .. '] = ' .. tostring(v) .. ',' end end if printval then print(tostring(s .. '\n}')) end return s .. '\n' .. var_dump_indent(cur_depth - 1) .. '} ' end if printval then print(tostring(var)) end return tostring(var) end utilities.var_dump = var_dump local function round(number, decimals, ext_abs) if ext_abs then ext_abs = math.floor else ext_abs = math.ceil end if not decimals then return ext_abs(number) end decimals = 10 ^ decimals return ext_abs(number * decimals) / decimals end utilities.round = round local function usleep(ms) local start_time local end_time start_time = system.getTimer() end_time = start_time + ms while true do if system.getTimer() >= end_time then break end end end utilities.usleep = usleep return utilities
local Context = require "Base.Context" local Mode = require "Base.Mode" local CardStatusViewer = require "Card.StatusViewer" local CardConsole = require "Card.Console" -- define the state local mode = Mode("Eject") local window = CardStatusViewer() local context = Context("Eject", window) function mode:enter() Mode.enter(self) local Application = require "Application" Application.setVisibleContext(context) if CardConsole.context then Application.setVisibleContext(CardConsole.context) else Application.setVisibleContext(context) end end return mode
-- replace.lua --[[---------------------------------------------------------------------------- * LuaFAR 2.6 is required because of 'gsub' method of compiled Far regex. This method is used in the "fast count" case, namely (aOp == "count") and not aParams.bSearchBack, that greatly speeds up counting matches. * Counting using PCRE with the PCRE_UCP flag set is by far slower than with other regex libraries being used. * LuaFAR 2.8 is required because of DM_LISTSETDATA, DM_LISTGETDATA. ------------------------------------------------------------------------------]] local ReqLuafarVersion = "2.8" -- CONFIGURATION : keep it at the file top !! local Cfg = { -- Default script will be recompiled and run every time OpenPlugin/ -- OpenFilePlugin are called: set true for debugging, false for normal use; ReloadDefaultScript = true, -- Reload lua libraries each time they are require()d: -- set true for libraries debugging, false for normal use; ReloadOnRequire = true, histfield_Main = "main", histfield_Menu = "menu", histfield_Config = "config", UserMenuFile = "@_usermenu.lua", RegPath = "LuaFAR\\LF Search\\", } -- Upvalues -- local Utils = require "far2.utils" local M = require "lfs_message" local F = far.Flags local LibFunc, History, ModuleDir local function Require (name) if Cfg.ReloadOnRequire then package.loaded[name] = nil; end return require(name) end local function InitUpvalues (_Plugin) LibFunc = Require("luarepl").SearchOrReplace History = _Plugin.History History:field(Cfg.histfield_Config) ModuleDir = _Plugin.ModuleDir end local function ResolvePath (template, dir) return (template:gsub("@", dir or ModuleDir)) end local function MakeAddToMenu (Items) return function (aItemText, aFileName, aParam1, aParam2) local SepText = type(aItemText)=="string" and aItemText:match("^:sep:(.*)") if SepText then table.insert(Items, { text=SepText, separator=true }) elseif type(aFileName)=="string" then table.insert(Items, { text=tostring(aItemText), filename=ModuleDir..aFileName, param1=aParam1, param2=aParam2 }) end end end local function MakeMenuItems (aUserMenuFile) local items = { {text=M.MMenuFind, action="search" }, {text=M.MMenuReplace, action="replace"}, {text=M.MMenuRepeat, action="repeat" }, {text=M.MMenuConfig, action="config" }, } local Info = win.GetFileInfo(aUserMenuFile) if Info and not Info.FileAttributes:find("d") then local f = assert(loadfile(aUserMenuFile)) local env = setmetatable( {AddToMenu=MakeAddToMenu(items)}, {__index=_G} ) setfenv(f, env)() end return items end local function export_OpenPlugin (From, Item) if not Utils.CheckLuafarVersion(ReqLuafarVersion, M.MMenuTitle) then return end if bit.band(From, F.OPEN_FROMMACRO) ~= 0 then far.Message(Item); return end if From == F.OPEN_EDITOR then local hMenu = History:field(Cfg.histfield_Menu) local items = MakeMenuItems(ResolvePath(Cfg.UserMenuFile)) local ret, pos = far.Menu( { Flags = {FMENU_WRAPMODE=1, FMENU_AUTOHIGHLIGHT=1}, Title = M.MMenuTitle, HelpTopic = "Contents", SelectIndex = hMenu.position, }, items) if ret then hMenu.position = pos if ret.action then local data = History:field(Cfg.histfield_Main) data.fUserChoiceFunc = nil LibFunc (ret.action, data, false) elseif ret.filename then assert(loadfile(ret.filename))(ret.param1, ret.param2) end History:save() end elseif From == F.OPEN_PLUGINSMENU then local SearchFromPanel = Require("lfs_panels") SearchFromPanel(History) History:save() end end local function export_GetPluginInfo() return { Flags = F.PF_EDITOR, PluginMenuStrings = { M.MMenuTitle }, SysId = 0x10001, } end function SearchOrReplace (aOp, aData) assert(type(aOp)=="string", "arg #1: string expected") assert(type(aData)=="table", "arg #2: table expected") local newdata = {}; for k,v in pairs(aData) do newdata[k] = v end History:setfield(Cfg.histfield_Main, newdata) return LibFunc(aOp, newdata, true) end local function SetExportFunctions() export.GetPluginInfo = export_GetPluginInfo export.OpenPlugin = export_OpenPlugin end local function main() if not _Plugin then _Plugin = Utils.InitPlugin("LuaFAR Search") _Plugin.RegPath = Cfg.RegPath package.cpath = _Plugin.ModuleDir .. "?.dl;" .. package.cpath end SetExportFunctions() InitUpvalues(_Plugin) far.ReloadDefaultScript = Cfg.ReloadDefaultScript end main()
-- schema.lua -- Holds the schema of your plugin's configuration, so that the user can only enter valid configuration values. -- Required: Yes return { no_consumer = true, -- this plugin is available on APIs as well as on Consumers, fields = { -- Describe your plugin's configuration's schema here. -- resource_name = {type = "string", required = true, unique = true}, -- transform_uuid = {type = "string", required = true, regex = "[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[4][0-9A-Fa-f]{3}-[89ABab][0-9A-Fa-f]{3}-[0-9A-Fa-f]{12}$"} }, self_check = function(schema, plugin_t, dao, is_updating) -- perform any custom verification return true end }
Locales["tr"] = { -- :) laot ["LAOT_GLING_PLAYDICE"] = "Oynamak için ~r~E ~w~basın.", ["LAOT_GLING_CANTPLAY"] = "Başkası oyunda!", ["LAOT_GLING_WAITNIGHT"] = "Şuan gece değil!", ["LAOT_GLING_NOTENOUGHMONEY"] = "Yeterince paranız yok!", ["LAOT_GLING_MINBET"] = "Mininum bahis mutlaka basılmalı!" }
init_vanilla() --+--------------------------------------------------------------------------------+-- -- if Registry['VA_ENV'] == nil then local helpers = LoadV "vanilla.v.libs.utils" function sprint_r( ... ) return helpers.sprint_r(...) end function lprint_r( ... ) local rs = sprint_r(...) print(rs) end function print_r( ... ) local rs = sprint_r(...) ngx.say(rs) end function err_log(msg) ngx.log(ngx.ERR, "===zjdebug" .. msg .. "===") end -- end --+--------------------------------------------------------------------------------+-- local vanilla_application = LoadV 'vanilla.v.application' local application_config = LoadApp 'config.application' local boots = LoadApp 'application.bootstrap' vanilla_application:new(ngx, application_config):bootstrap(boots):run()
--[[ Model - Private Traffic Route Choice Type - MNL Authors - Adnan, Shahita ]] --Estimated values for all betas --Note: the betas that not estimated are fixed to zero. local beta_bTTVOT = -0.0013904847537047364 local beta_bCommonFactor = 1.542931900577706 local beta_bLength = -2.2760243196051997e-06 local beta_bHighway = 4.494847364656496e-05 local beta_bCost = -2.0595 local beta_bSigInter = -0.0020431164328690793 local beta_bLeftTurns = 0.0 local beta_bWork = 0.0 local beta_bLeisure = 0.0 local beta_highwayBias = 0.23998897032620298 local beta_minTravelTimeParam = 0.37320274392971114 local beta_minDistanceParam = 0.08777962943862566 local beta_minSignalParam = 0.020236935452274854 local beta_maxHighwayParam = 0.125971989288778 --utility --utility[i] for choice[i] local utility = {} local choice = {} local availability = {} local function computeUtilities(params, N_choice) utility = {} choice = {} availability = {} for i = 1,N_choice do choice[i] = i availability[i] = 1 end for i = 1,N_choice do local travel_time = params:travel_time(i) local travel_cost = params:travel_cost(i) local partial_utility = params:partial_utility(i) local path_size = params:path_size(i) local length = params:length(i) local highway_distance = params:highway_distance(i) local signal_number = params:signal_number(i) local right_turn_number = params:right_turn_number(i) local is_min_distance = params:is_min_distance(i) local is_min_signal = params:is_min_signal(i) local is_max_highway_usage = params:is_max_highway_usage(i) local purpose = params:purpose(i) local pUtility = 0.0 if partial_utility > 0.0 then pUtility = partial_utility else pUtility = pUtility + (path_size)*beta_bCommonFactor pUtility = pUtility + (length)*beta_bLength pUtility = pUtility + (highway_distance)*beta_bHighway if highway_distance > 0 then pUtility = pUtility + beta_highwayBias end pUtility = pUtility+(signal_number)*beta_bSigInter pUtility = pUtility+(right_turn_number)*beta_bLeftTurns if is_min_distance == 1 then pUtility = pUtility+beta_minDistanceParam end if is_min_signal == 1 then pUtility = pUtility+beta_minSignalParam end if is_max_highway_usage == 1 then pUtility = pUtility+beta_maxHighwayParam end if purpose == 1 then pUtility = pUtility+purpose*beta_bWork end if purpose == 2 then pUtility = pUtility+purpose*beta_bLeisure end end utility[i] = pUtility utility[i] = utility[i] + travel_time * beta_bTTVOT utility[i] = utility[i]+ travel_cost * beta_bCost end end --scale local scale= 1 --for all choices -- function to call from C++ preday simulator -- params and dbparams tables contain data passed from C++ -- to check variable bindings in params or dbparams, refer PredayLuaModel::mapClasses() function in dev/Basic/medium/behavioral/lua/PredayLuaModel.cpp function choose_PVT_path(params, N_choice) computeUtilities(params, N_choice) local probability = calculate_probability("mnl", choice, utility, availability, scale) return make_final_choice(probability) end
-- zenburn-red, awesome3 theme, by Adrian C. (anrxc), modified by jessor --{{{ Main local awful = require("awful") awful.util = require("awful.util") theme = {} home = os.getenv("HOME") config = awful.util.getdir("config") shared = "/usr/share/awesome" if not awful.util.file_readable(shared .. "/icons/awesome16.png") then shared = "/usr/share/local/awesome" end sharedicons = shared .. "/icons" sharedthemes = shared .. "/themes" themes = config .. "/themes" themename = "/zenburn-red" if not awful.util.file_readable(themes .. themename .. "/theme.lua") then themes = sharedthemes end themedir = themes .. themename wallpaper1 = themedir .. "/background.jpg" wallpaper2 = themedir .. "/background.png" wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png" wallpaper4 = sharedthemes .. "/default/background.png" wpscript = home .. "/.wallpaper" if awful.util.file_readable(wallpaper1) then theme.wallpaper = wallpaper1 elseif awful.util.file_readable(wallpaper2) then theme.wallpaper = wallpaper2 elseif awful.util.file_readable(wpscript) then theme.wallpaper_cmd = { "sh " .. wpscript } elseif awful.util.file_readable(wallpaper3) then theme.wallpaper = wallpaper3 else theme.wallpaper = wallpaper4 end --}}} -- {{{ Styles theme.font = "Terminus 8" -- {{{ Colors theme.fg_normal = "#DCDCCC" theme.fg_focus = "#FFFFFF" theme.fg_urgent = "#BC0909" theme.bg_normal = "#181818" theme.bg_focus = "#400000" theme.bg_urgent = theme.bg_normal -- }}} -- {{{ Borders theme.border_width = 1 theme.border_focus = "#EE6363" theme.border_normal = theme.bg_normal theme.border_marked = "#622323" -- }}} -- {{{ Titlebars theme.titlebar_bg_focus = theme.bg_normal theme.titlebar_bg_normal = theme.bg_normal -- theme.titlebar_[normal|focus] -- }}} -- {{{ Widgets theme.fg_widget = "#9ACD32" -- low theme.fg_center_widget = "#de8120" theme.fg_end_widget = "#CC0000" -- high theme.fg_off_widget = theme.bg_normal -- bg theme.fg_netup_widget = "#9ACD32" theme.fg_netdn_widget = theme.border_focus theme.bg_widget = theme.bg_urgent theme.border_widget = theme.bg_urgent -- }}} -- {{{ Mouse finder theme.mouse_finder_color = theme.fg_urgent -- theme.mouse_finder_[timeout|animate_timeout|radius|factor] -- }}} -- {{{ Tooltips -- theme.tooltip_[font|opacity|fg_color|bg_color|border_width|border_color] -- }}} -- {{{ Taglist and Tasklist -- theme.[taglist|tasklist]_[bg|fg]_[focus|urgent] -- }}} -- {{{ Menu -- theme.menu_[bg|fg]_[normal|focus] -- theme.menu_[height|width|border_color|border_width] -- }}} -- }}} -- {{{ Icons -- -- {{{ Taglist icons theme.taglist_squares_sel = themedir .. "/taglist/squarefz.png" theme.taglist_squares_unsel = themedir .. "/taglist/squareza.png" --theme.taglist_squares_resize = "false" -- }}} -- {{{ Misc icons --theme.awesome_icon = themedir .. "/awesome.png" --theme.menu_submenu_icon = "/usr/share/awesome/themes/default/submenu.png" --theme.tasklist_floating_icon = "/usr/share/awesome/themes/default/tasklist/floatingw.png" -- }}} -- {{{ Layout icons theme.layout_tile = themedir .. "/layouts/tile.png" theme.layout_tileleft = themedir .. "/layouts/tileleft.png" theme.layout_tilebottom = themedir .. "/layouts/tilebottom.png" theme.layout_tiletop = themedir .. "/layouts/tiletop.png" theme.layout_fairv = themedir .. "/layouts/fairv.png" theme.layout_fairh = themedir .. "/layouts/fairh.png" theme.layout_spiral = themedir .. "/layouts/spiral.png" theme.layout_dwindle = themedir .. "/layouts/dwindle.png" theme.layout_max = themedir .. "/layouts/max.png" theme.layout_fullscreen = themedir .. "/layouts/fullscreen.png" theme.layout_magnifier = themedir .. "/layouts/magnifier.png" theme.layout_floating = themedir .. "/layouts/floating.png" -- }}} -- {{{ Widget icons theme.widget_cpu = themes .. "/icons/zenburn/cpu.png" theme.widget_bat = themes .. "/icons/zenburn/bat.png" theme.widget_mem = themes .. "/icons/zenburn/mem.png" theme.widget_fs = themes .. "/icons/zenburn/disk.png" theme.widget_net = themes .. "/icons/zenburn/down.png" theme.widget_netup = themes .. "/icons/zenburn/up.png" theme.widget_wifi = themes .. "/icons/zenburn/wifi.png" theme.widget_mail = themes .. "/icons/zenburn/mail.png" theme.widget_vol = themes .. "/icons/zenburn/vol.png" theme.widget_org = themes .. "/icons/zenburn/cal.png" theme.widget_date = themes .. "/icons/zenburn/time.png" theme.widget_crypto = themes .. "/icons/zenburn/crypto.png" theme.widget_sep = themes .. "/icons/zenburn/separator.png" -- }}} -- {{{ Titlebar icons theme.titlebar_close_button_focus = themedir .. "/titlebar/close_focus.png" theme.titlebar_close_button_normal = themedir .. "/titlebar/close_normal.png" theme.titlebar_ontop_button_focus_active = themedir .. "/titlebar/ontop_focus_active.png" theme.titlebar_ontop_button_normal_active = themedir .. "/titlebar/ontop_normal_active.png" theme.titlebar_ontop_button_focus_inactive = themedir .. "/titlebar/ontop_focus_inactive.png" theme.titlebar_ontop_button_normal_inactive = themedir .. "/titlebar/ontop_normal_inactive.png" theme.titlebar_sticky_button_focus_active = themedir .. "/titlebar/sticky_focus_active.png" theme.titlebar_sticky_button_normal_active = themedir .. "/titlebar/sticky_normal_active.png" theme.titlebar_sticky_button_focus_inactive = themedir .. "/titlebar/sticky_focus_inactive.png" theme.titlebar_sticky_button_normal_inactive = themedir .. "/titlebar/sticky_normal_inactive.png" theme.titlebar_floating_button_focus_active = themedir .. "/titlebar/floating_focus_active.png" theme.titlebar_floating_button_normal_active = themedir .. "/titlebar/floating_normal_active.png" theme.titlebar_floating_button_focus_inactive = themedir .. "/titlebar/floating_focus_inactive.png" theme.titlebar_floating_button_normal_inactive = themedir .. "/titlebar/floating_normal_inactive.png" theme.titlebar_maximized_button_focus_active = themedir .. "/titlebar/maximized_focus_active.png" theme.titlebar_maximized_button_normal_active = themedir .. "/titlebar/maximized_normal_active.png" theme.titlebar_maximized_button_focus_inactive = themedir .. "/titlebar/maximized_focus_inactive.png" theme.titlebar_maximized_button_normal_inactive = themedir .. "/titlebar/maximized_normal_inactive.png" -- }}} -- }}} return theme
--[[ Create a dictionary where each value in the given list corresponds to a key in the dictionary with a value of true ]] local function toSet(list) local new = {} for i = 1, #list do new[list[i]] = true end return new end return toSet
-------------------------------- -- Happy Weather: ABM registers -- License: MIT -- Credits: xeranas -------------------------------- -- ABM for extinguish fire minetest.register_abm({ nodenames = {"fire:basic_flame"}, interval = 4.0, chance = 2, action = function(pos, node, active_object_count, active_object_count_wider) if happy_weather.is_weather_active("heavy_rain") or happy_weather.is_weather_active("rain") then if hw_utils.is_outdoor(pos) then minetest.remove_node(pos) end end end })
local skynet = require "skynet" local socket = require "skynet.socket" local crypt = require "skynet.crypt" local log = require "skynet.log" local pbc = require "protobuf" local redis = require "skynet.db.redis" require "skynet.manager" local utils = require "utils" local constant = require "constant" local cjson = require "cjson" local CMD = {} local SOCKET = {} local GATE_SERVICE local SECRET_STATE = { WAIT_CLIENT_KEY = 1, CONFIRM_SUCCESS = 2, } local fd_to_info = {} local userid_to_info = {} local roomid_to_agent = {} local room_services = {} local hearts = {} --获取一个唯一的房间号ID local function getUnusedRandomId() return skynet.call(".mysql_pool","lua","getRandomRoomId") end local agent_manager = {} local function send(fd, content, secret) local data, err = pbc.encode("S2C", content) if err then log.errorf("encode protobuf error: %s", err) return end if data then if secret then local success, e = pcall(crypt.desencode, secret, data) if success then data = e else log.error("desencode error") return end end socket.write(fd, string.pack(">s2", crypt.base64encode(data))) end end function SOCKET.close(fd) log.info("socket close",fd) local info = fd_to_info[fd] local room_id = info.room_id local user_id = info.user_id if info and room_id then local service_id = roomid_to_agent[info.room_id] local data = {user_id=info.user_id,room_id=info.room_id} skynet.send(service_id, "lua", "request", "disconnect",data) end if user_id then userid_to_info[user_id] = nil end fd_to_info[fd] = nil end function SOCKET.error(fd, msg) print("socket error",fd, msg) SOCKET.close(fd) end function SOCKET.warning(fd, size) -- size K bytes havn't send out in fd log.info("socket warning", fd, size) end function CMD.debugProto(user_id,proto_name,proto_msg) -- body local info = userid_to_info[user_id] if info and info.room_id then proto_msg.user_id = info.user_id proto_msg.room_id = info.room_id local service_id = roomid_to_agent[info.room_id] local result = skynet.call(service_id, "lua", "request", proto_name,proto_msg) return result end end --建立连接 function SOCKET.open(fd, addr) local info = {} info.fd = fd info.state = SECRET_STATE.WAIT_CLIENT_KEY info.challenge = crypt.randomkey() info.serverkey = crypt.randomkey() info.ip = string.match(addr, "(.-):") local req_msg = {} req_msg["v1"] = crypt.base64encode(info.challenge) req_msg["v2"] = crypt.base64encode(crypt.dhexchange(info.serverkey)) send(fd, {["handshake"] = req_msg}) fd_to_info[fd] = info end function SOCKET.data(fd, data) local info = fd_to_info[fd] if not info then log.error("internal error") skynet.call(GATE_SERVICE,"lua","kick",fd) return end data = crypt.base64decode(data) local secret = info.secret if secret then data = crypt.desdecode(secret, data) end local content, err = pbc.decode("C2S", data) if err or not content then log.errorf("decode protobuf error: %s", data) end if info.state == SECRET_STATE.WAIT_CLIENT_KEY then if rawget(content, "handshake") then local req_msg = content["handshake"] local clientkey = crypt.base64decode(req_msg["v1"]) local secret = crypt.dhsecret(clientkey, info.serverkey) if crypt.base64decode(req_msg["v2"]) == crypt.hmac64(info.challenge, secret) then info.clientkey = clientkey info.secret = secret info.state = SECRET_STATE.CONFIRM_SUCCESS else log.error("key exchange error") skynet.call(GATE_SERVICE,"lua","kick",fd) end return end elseif info.state == SECRET_STATE.CONFIRM_SUCCESS then -- 心跳包直接返回 if rawget(content,"heartbeat") then skynet.remove_timeout(hearts[fd]) local next_heart = 100*7 hearts[fd] = skynet.timeout(next_heart,function() --如果7秒之后还没有收到心跳包则 断开连接 print("FYD---->>>玩家:",info.user_id,"断开连接") skynet.call(GATE_SERVICE,"lua","kick",fd) end) send(fd, {session_id = content.session_id, heartbeat = {}},secret) return end if rawget(content, "login") then local req_msg = content["login"] local user_id = req_msg.user_id local token = req_msg.token local rsp_msg = {result = "success"} local check = skynet.call(".mysql_pool","lua","checkLoginToken",user_id,token) if check then info.user_id = user_id local fd = info.fd local secret = info.secret local origin_info = userid_to_info[user_id] if origin_info and origin_info.fd then send(origin_info.fd, { handle_error = {result="other_player_login"} }, origin_info.secret) skynet.call(GATE_SERVICE,"lua","kick",origin_info.fd) end userid_to_info[user_id] = info else rsp_msg.result = "auth_fail" end send(fd, { ["session_id"] = content.session_id, ["login"] = rsp_msg }, secret) elseif rawget(content, "create_room") then local rsp_msg = {} local data = skynet.call(".mysql_pool","lua","checkIsInGame",info.user_id) if data then rsp_msg.result = "current_in_game" send(fd, { ["session_id"] = content.session_id, ["create_room"] = rsp_msg }, secret) return end local req_msg = content["create_room"] local room_id = getUnusedRandomId() local service_id = table.remove(room_services) if not service_id then service_id = skynet.newservice("room") end local now = skynet.time() local expire_time = now + 30*60 roomid_to_agent[room_id] = service_id info.room_id = room_id req_msg.room_id = room_id req_msg.fd = info.fd req_msg.user_id = info.user_id req_msg.secret = info.secret req_msg.expire_time = expire_time local result = skynet.call(service_id,"lua","create_room",req_msg) rsp_msg.result = result send(fd, { ["session_id"] = content.session_id, ["create_room"] = rsp_msg }, secret) elseif rawget(content,"join_room") then local rsp_msg = {} local req_name = "join_room" local req_msg = content["join_room"] local data = skynet.call(".mysql_pool","lua","checkIsInGame",info.user_id) if data then req_name = "back_room" end local req_msg = content["join_room"] local room_id = req_msg.room_id if not roomid_to_agent[room_id] then rsp_msg.result = "not_exist_room" send(fd, { ["session_id"] = content.session_id, ["join_room"] = rsp_msg }, secret) return end info.room_id = room_id req_msg.fd = info.fd req_msg.user_id = info.user_id req_msg.secret = info.secret local service_id = roomid_to_agent[room_id] local result = skynet.call(service_id,"lua",req_name,req_msg) rsp_msg.result = result send(fd, { ["session_id"] = content.session_id, ["join_room"] = rsp_msg }, secret) elseif info.room_id then local rsp_msg = {} local req_name,req_content for k,v in pairs(content) do if k ~= "session_id" then req_name = k req_content = v end end if not roomid_to_agent[info.room_id] then rsp_msg.result = "not_exist_room" send(fd, { ["session_id"] = content.session_id, [req_name] = rsp_msg }, secret) return end req_content.user_id = info.user_id req_content.room_id = info.room_id local service_id = roomid_to_agent[info.room_id] local result = skynet.call(service_id, "lua", "request", req_name,req_content) rsp_msg.result = result send(fd, { ["session_id"] = content.session_id, [req_name] = rsp_msg }, secret) if req_name == "leave_room" and result == "success" then info.room_id = nil end else log.errorf("wrong connect, state: %s, req_name = ", info.state,req_name) end end end local genneralUnusedService = function() for i=1,10 do local service_id = skynet.newservice("room") table.insert(room_services,service_id) end end local recoverRoomList = function() --恢复房间列表 local server_id = skynet.getenv("server_id") local room_list = skynet.call(".mysql_pool","lua","selectRoomListByServerId",server_id) for i,info in ipairs(room_list) do local service_id = table.remove(room_services) if not service_id then service_id = skynet.newservice("room") end roomid_to_agent[info.room_id] = service_id skynet.send(service_id,"lua","recover",info) end end function CMD.distroyRoomById(room_id) local service_id = roomid_to_agent[room_id] if service_id then skynet.send(service_id,"lua","force_distroy") table.insert(room_services,room_info.service_id) roomid_to_agent[room_id] = nil end end function CMD.distroyRoom(room_id) local service_id = roomid_to_agent[room_id] if service_id then table.insert(room_services,room_info.service_id) roomid_to_agent[room_id] = nil end end local function checkExpireRoom() local server_id = skynet.getenv("server_id") --每隔1小时检查一下失效的房间并删除 skynet.send(".mysql_pool","lua","distroyCord",server_id) skynet.timeout( 60 * 60 * 100, checkExpireRoom) end skynet.start(function() skynet.dispatch("lua", function(session, source, cmd, subcmd, ...) if cmd == "socket" then local f = SOCKET[subcmd] f(...) else local f = assert(CMD[cmd]) skynet.ret(skynet.pack(f(subcmd, ...))) end end) checkExpireRoom() recoverRoomList() --注册protobuf协议 pbc.register_file(skynet.getenv("protobuf")) -- 启动gate服务 监听来自客户端的连接 GATE_SERVICE = skynet.newservice("gate") skynet.call(GATE_SERVICE, "lua", "open" , { port = tonumber(skynet.getenv("port")), nodelay = true, }) genneralUnusedService() skynet.register ".agent_manager" end)
local basaltFileName = "basalt-source.lua" local absolutePath = "source" local basalt = dofile(fs.combine(absolutePath, "packager.lua")) -- path to packager local b = fs.open(fs.combine(absolutePath, basaltFileName), "w") b.write(basalt) b.close()
local hissedHP = 0.45 local takedown = 0.11 local creepIsShaking = false function start (song) if difficulty == 1 then hissedHP = 0.63 takedown = 0 end print("Heww yeh, is angwy cat time >:3 -- Hiss Rate: " .. hissedHP .. " per hisssss") end function update (elapsed) local currentBeat = (songPos / 1000) * (bpm / 60) if creepIsShaking then -- last minute addition courtesy of the retrospecter mod. i did thought of it, just dont know how to do it, so thanks retro... yoink! if difficulty == 1 then for i=4,7 do setActorX(_G['defaultStrum'..i..'X'] + 5 * math.sin((currentBeat * 10 + i * 0.25) * math.pi), i) setActorY(_G['defaultStrum'..i..'Y'] + 2 * math.cos((currentBeat * 10 + i * 0.25) * math.pi) + 10.93, i) end -- it actually offsets the note locations a little bit, dunno how to fix it and i feel like people are gonna point it out, i tried my best :( else for i=4,7 do setActorX(_G['defaultStrum'..i..'X'] + 2 * math.sin((currentBeat * 10 + i * 0.25) * math.pi), i) setActorY(_G['defaultStrum'..i..'Y'] + 1 * math.cos((currentBeat * 10 + i * 0.25) * math.pi) + 10.93, i) end end end end function beatHit (beat) -- HISS MECHANIC & SHIT -- btw the health drain will not work in other mods, it's exclusive to this mod alone if beat == 30 then healthDrain(0.77, 0.56) -- first drain always set to drain until bf's struggle sprite creepIsShaking = true elseif beat == 46 or beat == 62 or beat == 79 or beat == 83 or beat == 87 or beat == 91 or beat == 95 or beat == 179 or beat == 183 or beat == 187 or beat == 191 or beat == 195 or beat == 211 or beat == 215 or beat == 219 or beat == 223 then healthDrain(hissedHP, 0.56) creepIsShaking = true elseif beat == 227 then healthDrain(takedown, 0.56, true) -- troll [°͜ʖ°] -- also the reason its set to take you down to 0 hp on hard is because health gained by hitting notes during the drain is considered -- i could also set it to negative but i feel like thats too brutal, 0 is enough... creepIsShaking = true elseif creepIsShaking then creepIsShaking = false end end -- dont fucking know how to modchart the camera zooms so they're still hardcoded in... i should REALLY learn to accept my limits sometimes QwQ -- seriously though, i have a problem... -- *sigh* i could really use a warm hug right now oof
local actions = require('telescope.actions') local action_set = require('telescope.actions.set') local action_state = require('telescope.actions.state') local finders = require('telescope.finders') local make_entry = require('telescope.make_entry') local path = require('telescope.path') local pickers = require('telescope.pickers') local previewers = require('telescope.previewers') local sorters = require('telescope.sorters') local utils = require('telescope.utils') local conf = require('telescope.config').values local filter = vim.tbl_filter local internal = {} -- TODO: What the heck should we do for accepting this. -- vim.fn.setreg("+", "nnoremap $TODO :lua require('telescope.builtin').<whatever>()<CR>") -- TODO: Can we just do the names instead? internal.builtin = function(opts) opts.hide_filename = utils.get_default(opts.hide_filename, true) opts.ignore_filename = utils.get_default(opts.ignore_filename, true) local objs = {} for k, v in pairs(require'telescope.builtin') do local debug_info = debug.getinfo(v) table.insert(objs, { filename = string.sub(debug_info.source, 2), text = k, }) end pickers.new(opts, { prompt_title = 'Telescope Builtin', finder = finders.new_table { results = objs, entry_maker = function(entry) return { value = entry, text = entry.text, display = entry.text, ordinal = entry.text, filename = entry.filename } end }, previewer = previewers.builtin.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(_) actions.select_default:replace(actions.run_builtin) return true end }):find() end internal.planets = function(opts) local show_pluto = opts.show_pluto or false local sourced_file = require('plenary.debug_utils').sourced_filepath() local base_directory = vim.fn.fnamemodify(sourced_file, ":h:h:h:h") local globbed_files = vim.fn.globpath(base_directory .. '/data/memes/planets/', '*', true, true) local acceptable_files = {} for _, v in ipairs(globbed_files) do if show_pluto or not v:find("pluto") then table.insert(acceptable_files,vim.fn.fnamemodify(v, ':t')) end end pickers.new { prompt_title = 'Planets', finder = finders.new_table { results = acceptable_files, entry_maker = function(line) return { ordinal = line, display = line, filename = base_directory .. '/data/memes/planets/' .. line, } end }, previewer = previewers.cat.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) print("Enjoy astronomy! You viewed:", selection.display) end) return true end, }:find() end internal.symbols = function(opts) local files = vim.api.nvim_get_runtime_file('data/telescope-sources/*.json', true) if table.getn(files) == 0 then print("No sources found! Check out https://github.com/nvim-telescope/telescope-symbols.nvim " .. "for some prebuild symbols or how to create you own symbol source.") return end local sources = {} if opts.sources then for _, v in ipairs(files) do for _, s in ipairs(opts.sources) do if v:find(s) then table.insert(sources, v) end end end else sources = files end local results = {} for _, source in ipairs(sources) do local data = vim.fn.json_decode(path.read_file(source)) for _, entry in ipairs(data) do table.insert(results, entry) end end pickers.new(opts, { prompt_title = 'Symbols', finder = finders.new_table { results = results, entry_maker = function(entry) return { value = entry, ordinal = entry[1] .. ' ' .. entry[2], display = entry[1] .. ' ' .. entry[2], } end }, sorter = conf.generic_sorter(opts), attach_mappings = function(_) actions.select_default:replace(actions.insert_symbol) return true end }):find() end internal.commands = function(opts) pickers.new(opts, { prompt_title = 'Commands', finder = finders.new_table { results = (function() local command_iter = vim.api.nvim_get_commands({}) local commands = {} for _, cmd in pairs(command_iter) do table.insert(commands, cmd) end return commands end)(), entry_maker = opts.entry_maker or make_entry.gen_from_commands(opts), }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) local val = selection.value local cmd = string.format([[:%s ]], val.name) if val.nargs == "0" then vim.cmd(cmd) else vim.cmd [[stopinsert]] vim.fn.feedkeys(cmd) end end) return true end }):find() end internal.quickfix = function(opts) local locations = vim.fn.getqflist() if vim.tbl_isempty(locations) then return end pickers.new(opts, { prompt_title = 'Quickfix', finder = finders.new_table { results = locations, entry_maker = opts.entry_maker or make_entry.gen_from_quickfix(opts), }, previewer = conf.qflist_previewer(opts), sorter = conf.generic_sorter(opts), }):find() end internal.loclist = function(opts) local locations = vim.fn.getloclist(0) local filename = vim.api.nvim_buf_get_name(0) for _, value in pairs(locations) do value.filename = filename end if vim.tbl_isempty(locations) then return end pickers.new(opts, { prompt_title = 'Loclist', finder = finders.new_table { results = locations, entry_maker = opts.entry_maker or make_entry.gen_from_quickfix(opts), }, previewer = conf.qflist_previewer(opts), sorter = conf.generic_sorter(opts), }):find() end internal.oldfiles = function(opts) opts.include_current_session = utils.get_default(opts.include_current_session, true) local current_buffer = vim.api.nvim_get_current_buf() local current_file = vim.api.nvim_buf_get_name(current_buffer) local results = {} if opts.include_current_session then for _, buffer in ipairs(vim.split(vim.fn.execute(':buffers! t'), "\n")) do local match = tonumber(string.match(buffer, '%s*(%d+)')) if match then local file = vim.api.nvim_buf_get_name(match) if vim.loop.fs_stat(file) and match ~= current_buffer then table.insert(results, file) end end end end for _, file in ipairs(vim.v.oldfiles) do if vim.loop.fs_stat(file) and not vim.tbl_contains(results, file) and file ~= current_file then table.insert(results, file) end end if opts.cwd_only then local cwd = vim.loop.cwd() cwd = cwd:gsub([[\]],[[\\]]) results = vim.tbl_filter(function(file) return vim.fn.matchstrpos(file, cwd)[2] ~= -1 end, results) end pickers.new(opts, { prompt_title = 'Oldfiles', finder = finders.new_table{ results = results, entry_maker = opts.entry_maker or make_entry.gen_from_file(opts), }, sorter = conf.file_sorter(opts), previewer = conf.file_previewer(opts), }):find() end internal.command_history = function(opts) local history_string = vim.fn.execute('history cmd') local history_list = vim.split(history_string, "\n") local results = {} for i = #history_list, 3, -1 do local item = history_list[i] local _, finish = string.find(item, "%d+ +") table.insert(results, string.sub(item, finish + 1)) end pickers.new(opts, { prompt_title = 'Command History', finder = finders.new_table(results), sorter = conf.generic_sorter(opts), attach_mappings = function(_, map) map('i', '<CR>', actions.set_command_line) map('n', '<CR>', actions.set_command_line) map('n', '<C-e>', actions.edit_command_line) map('i', '<C-e>', actions.edit_command_line) -- TODO: Find a way to insert the text... it seems hard. -- map('i', '<C-i>', actions.insert_value, { expr = true }) return true end, }):find() end internal.search_history = function(opts) local search_string = vim.fn.execute('history search') local search_list = vim.split(search_string, "\n") local results = {} for i = #search_list, 3, -1 do local item = search_list[i] local _, finish = string.find(item, "%d+ +") table.insert(results, string.sub(item, finish + 1)) end pickers.new(opts, { prompt_title = 'Search History', finder = finders.new_table(results), sorter = conf.generic_sorter(opts), attach_mappings = function(_, map) map('i', '<CR>', actions.set_search_line) map('n', '<CR>', actions.set_search_line) map('n', '<C-e>', actions.edit_search_line) map('i', '<C-e>', actions.edit_search_line) -- TODO: Find a way to insert the text... it seems hard. -- map('i', '<C-i>', actions.insert_value, { expr = true }) return true end, }):find() end internal.vim_options = function(opts) -- Load vim options. local vim_opts = loadfile(utils.data_directory() .. path.separator .. 'options' .. path.separator .. 'options.lua')().options pickers.new(opts, { prompt = 'options', finder = finders.new_table { results = vim_opts, entry_maker = opts.entry_maker or make_entry.gen_from_vimoptions(opts), }, -- TODO: previewer for Vim options -- previewer = previewers.help.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function() actions.select_default:replace(function() local selection = action_state.get_selected_entry() local esc = "" if vim.fn.mode() == "i" then -- TODO: don't make this local esc = vim.api.nvim_replace_termcodes("<esc>", true, false, true) end -- TODO: Make this actually work. -- actions.close(prompt_bufnr) -- vim.api.nvim_win_set_var(vim.api.nvim_get_current_win(), "telescope", 1) -- print(prompt_bufnr) -- print(vim.fn.bufnr()) -- vim.cmd([[ autocmd BufEnter <buffer> ++nested ++once startinsert!]]) -- print(vim.fn.winheight(0)) -- local prompt_winnr = vim.fn.getbufinfo(prompt_bufnr)[1].windows[1] -- print(prompt_winnr) -- local float_opts = {} -- float_opts.relative = "editor" -- float_opts.anchor = "sw" -- float_opts.focusable = false -- float_opts.style = "minimal" -- float_opts.row = vim.api.nvim_get_option("lines") - 2 -- TODO: inc `cmdheight` and `laststatus` in this calc -- float_opts.col = 2 -- float_opts.height = 10 -- float_opts.width = string.len(selection.last_set_from)+15 -- local buf = vim.api.nvim_create_buf(false, true) -- vim.api.nvim_buf_set_lines(buf, 0, 0, false, -- {"default value: abcdef", "last set from: " .. selection.last_set_from}) -- local status_win = vim.api.nvim_open_win(buf, false, float_opts) -- -- vim.api.nvim_win_set_option(status_win, "winblend", 100) -- vim.api.nvim_win_set_option(status_win, "winhl", "Normal:PmenuSel") -- -- vim.api.nvim_set_current_win(status_win) -- vim.cmd[[redraw!]] -- vim.cmd("autocmd CmdLineLeave : ++once echom 'beep'") vim.api.nvim_feedkeys(string.format("%s:set %s=%s", esc, selection.name, selection.current_value), "m", true) end) return true end }):find() end internal.help_tags = function(opts) opts.lang = utils.get_default(opts.lang, vim.o.helplang) opts.fallback = utils.get_default(opts.fallback, true) local langs = vim.split(opts.lang, ',', true) if opts.fallback and not vim.tbl_contains(langs, 'en') then table.insert(langs, 'en') end local langs_map = {} for _, lang in ipairs(langs) do langs_map[lang] = true end local tag_files = {} local function add_tag_file(lang, file) if langs_map[lang] then if tag_files[lang] then table.insert(tag_files[lang], file) else tag_files[lang] = {file} end end end local help_files = {} local all_files = vim.fn.globpath(vim.o.runtimepath, 'doc/*', 1, 1) for _, fullpath in ipairs(all_files) do local file = utils.path_tail(fullpath) if file == 'tags' then add_tag_file('en', fullpath) elseif file:match('^tags%-..$') then local lang = file:sub(-2) add_tag_file(lang, fullpath) else help_files[file] = fullpath end end local tags = {} local tags_map = {} local delimiter = string.char(9) for _, lang in ipairs(langs) do for _, file in ipairs(tag_files[lang] or {}) do local lines = vim.split(path.read_file(file), '\n', true) for _, line in ipairs(lines) do -- TODO: also ignore tagComment starting with ';' if not line:match'^!_TAG_' then local fields = vim.split(line, delimiter, true) if #fields == 3 and not tags_map[fields[1]] then table.insert(tags, { name = fields[1], filename = help_files[fields[2]], cmd = fields[3], lang = lang, }) tags_map[fields[1]] = true end end end end end pickers.new(opts, { prompt_title = 'Help', finder = finders.new_table { results = tags, entry_maker = function(entry) return { value = entry.name .. '@' .. entry.lang, display = entry.name, ordinal = entry.name, filename = entry.filename, cmd = entry.cmd } end, }, previewer = previewers.help.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) action_set.select:replace(function(_, cmd) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) if cmd == 'default' or cmd == 'horizontal' then vim.cmd('help ' .. selection.value) elseif cmd == 'vertical' then vim.cmd('vert bo help ' .. selection.value) elseif cmd == 'tab' then vim.cmd('tab help ' .. selection.value) end end) return true end }):find() end internal.man_pages = function(opts) opts.sections = utils.get_default(opts.sections, {'1'}) assert(vim.tbl_islist(opts.sections), 'sections should be a list') opts.man_cmd = utils.get_lazy_default(opts.man_cmd, function() local is_darwin = vim.loop.os_uname().sysname == 'Darwin' return is_darwin and {'apropos', ' '} or {'apropos', ''} end) opts.entry_maker = opts.entry_maker or make_entry.gen_from_apropos(opts) pickers.new(opts, { prompt_title = 'Man', finder = finders.new_oneshot_job(opts.man_cmd, opts), previewer = previewers.man.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) action_set.select:replace(function(_, cmd) local selection = action_state.get_selected_entry() local args = selection.section .. ' ' .. selection.value actions.close(prompt_bufnr) if cmd == 'default' or cmd == 'horizontal' then vim.cmd('Man ' .. args) elseif cmd == 'vertical' then vim.cmd('vert bo Man ' .. args) elseif cmd == 'tab' then vim.cmd('tab Man ' .. args) end end) return true end }):find() end internal.reloader = function(opts) local package_list = vim.tbl_keys(package.loaded) -- filter out packages we don't want and track the longest package name opts.column_len = 0 for index, module_name in pairs(package_list) do if type(require(module_name)) ~= 'table' or module_name:sub(1,1) == "_" or package.searchpath(module_name, package.path) == nil then table.remove(package_list, index) elseif #module_name > opts.column_len then opts.column_len = #module_name end end pickers.new(opts, { prompt_title = 'Packages', finder = finders.new_table { results = package_list, entry_maker = opts.entry_maker or make_entry.gen_from_packages(opts), }, -- previewer = previewers.vim_buffer.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) require('plenary.reload').reload_module(selection.value) print(string.format("[%s] - module reloaded", selection.value)) end) return true end }):find() end internal.buffers = function(opts) local bufnrs = filter(function(b) if 1 ~= vim.fn.buflisted(b) then return false end if not opts.show_all_buffers and not vim.api.nvim_buf_is_loaded(b) then return false end if opts.ignore_current_buffer and b == vim.api.nvim_get_current_buf() then return false end if opts.only_cwd and not string.find(vim.api.nvim_buf_get_name(b), vim.loop.cwd()) then return false end return true end, vim.api.nvim_list_bufs()) if not next(bufnrs) then return end local buffers = {} local default_selection_idx = 1 for _, bufnr in ipairs(bufnrs) do local flag = bufnr == vim.fn.bufnr('') and '%' or (bufnr == vim.fn.bufnr('#') and '#' or ' ') if opts.sort_lastused and not opts.ignore_current_buffer and flag == "#" then default_selection_idx = 2 end local element = { bufnr = bufnr, flag = flag, info = vim.fn.getbufinfo(bufnr)[1], } if opts.sort_lastused and (flag == "#" or flag == "%") then local idx = ((buffers[1] ~= nil and buffers[1].flag == "%") and 2 or 1) table.insert(buffers, idx, element) else table.insert(buffers, element) end end if not opts.bufnr_width then local max_bufnr = math.max(unpack(bufnrs)) opts.bufnr_width = #tostring(max_bufnr) end pickers.new(opts, { prompt_title = 'Buffers', finder = finders.new_table { results = buffers, entry_maker = opts.entry_maker or make_entry.gen_from_buffer(opts) }, previewer = conf.grep_previewer(opts), sorter = conf.generic_sorter(opts), default_selection_index = default_selection_idx, }):find() end internal.colorscheme = function(opts) local colors = vim.list_extend(opts.colors or {}, vim.fn.getcompletion('', 'color')) pickers.new(opts,{ prompt = 'Change Colorscheme', finder = finders.new_table { results = colors }, -- TODO: better preview? sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.cmd("colorscheme " .. selection.value) end) return true end }):find() end internal.marks = function(opts) local marks = vim.api.nvim_exec("marks", true) local marks_table = vim.fn.split(marks, "\n") -- Pop off the header. table.remove(marks_table, 1) pickers.new(opts,{ prompt = 'Marks', finder = finders.new_table { results = marks_table, entry_maker = opts.entry_maker or make_entry.gen_from_marks(opts), }, previewer = conf.grep_previewer(opts), sorter = conf.generic_sorter(opts), }):find() end internal.registers = function(opts) local registers_table = {"\"", "_", "#", "=", "_", "/", "*", "+", ":", ".", "%"} -- named for i = 0, 9 do table.insert(registers_table, tostring(i)) end -- alphabetical for i = 65, 90 do table.insert(registers_table, string.char(i)) end pickers.new(opts,{ prompt_title = 'Registers', finder = finders.new_table { results = registers_table, entry_maker = opts.entry_maker or make_entry.gen_from_registers(opts), }, -- use levenshtein as n-gram doesn't support <2 char matches sorter = sorters.get_levenshtein_sorter(), attach_mappings = function(_, map) actions.select_default:replace(actions.paste_register) map('i', '<C-e>', actions.edit_register) return true end, }):find() end -- TODO: make filtering include the mapping and the action internal.keymaps = function(opts) local modes = {"n", "i", "c"} local keymaps_table = {} for _, mode in pairs(modes) do local global = vim.api.nvim_get_keymap(mode) for _, keymap in pairs(global) do table.insert(keymaps_table, keymap) end local buf_local = vim.api.nvim_buf_get_keymap(0, mode) for _, keymap in pairs(buf_local) do table.insert(keymaps_table, keymap) end end pickers.new(opts, { prompt_title = 'Key Maps', finder = finders.new_table { results = keymaps_table, entry_maker = function(line) return { valid = line ~= "", value = line, ordinal = utils.display_termcodes(line.lhs) .. line.rhs, display = line.mode .. ' ' .. utils.display_termcodes(line.lhs) .. ' ' .. line.rhs } end }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() vim.api.nvim_feedkeys( vim.api.nvim_replace_termcodes(selection.value.lhs, true, false, true), "t", true) return actions.close(prompt_bufnr) end) return true end }):find() end internal.filetypes = function(opts) local filetypes = vim.fn.getcompletion('', 'filetype') pickers.new(opts, { prompt_title = 'Filetypes', finder = finders.new_table { results = filetypes, }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.cmd('setfiletype ' .. selection[1]) end) return true end }):find() end internal.highlights = function(opts) local highlights = vim.fn.getcompletion('', 'highlight') pickers.new(opts, { prompt_title = 'Highlights', finder = finders.new_table { results = highlights, entry_maker = opts.entry_maker or make_entry.gen_from_highlights(opts) }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.cmd('hi ' .. selection.value) end) return true end, previewer = previewers.highlights.new(opts), }):find() end internal.autocommands = function(opts) local autocmd_table = {} local pattern = {} pattern.BUFFER = "<buffer=%d+>" pattern.EVENT = "[%a]+" pattern.GROUP = "[%a%d_:]+" pattern.INDENT = "^%s%s%s%s" -- match indentation of 4 spaces local event, group, ft_pat, cmd, source_file, source_lnum local current_event, current_group, current_ft local inner_loop = function(line) -- capture group and event group, event = line:match("^(" .. pattern.GROUP .. ")%s+(" .. pattern.EVENT .. ")") -- ..or just an event if event == nil then event = line:match("^(" .. pattern.EVENT .. ")") end if event then group = group or "<anonymous>" if event ~= current_event or group ~= current_group then current_event = event current_group = group end return end -- non event/group lines ft_pat = line:match(pattern.INDENT .. "(%S+)") if ft_pat then if ft_pat:match("^%d+") then ft_pat = "<buffer=" .. ft_pat .. ">" end current_ft = ft_pat -- is there a command on the same line? cmd = line:match(pattern.INDENT .. "%S+%s+(.+)") return end if current_ft and cmd == nil then -- trim leading spaces cmd = line:gsub("^%s+", "") return end if current_ft and cmd then source_file, source_lnum = line:match("Last set from (.*) line (.*)") if source_file then local autocmd = {} autocmd.event = current_event autocmd.group = current_group autocmd.ft_pattern = current_ft autocmd.command = cmd autocmd.source_file = source_file autocmd.source_lnum = source_lnum table.insert(autocmd_table, autocmd) cmd = nil end end end local cmd_output = vim.fn.execute("verb autocmd *", "silent") for line in cmd_output:gmatch("[^\r\n]+") do inner_loop(line) end pickers.new(opts,{ prompt_title = 'autocommands', finder = finders.new_table { results = autocmd_table, entry_maker = opts.entry_maker or make_entry.gen_from_autocommands(opts), }, previewer = previewers.autocommands.new(opts), sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) action_set.select:replace(function(_, type) local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.cmd(action_state.select_key_to_edit_key(type) .. ' ' .. selection.value) end) return true end }):find() end internal.spell_suggest = function(opts) if not vim.wo.spell then return false end local cursor_word = vim.fn.expand("<cword>") local suggestions = vim.fn.spellsuggest(cursor_word) pickers.new(opts, { prompt_title = 'Spelling Suggestions', finder = finders.new_table { results = suggestions, }, sorter = conf.generic_sorter(opts), attach_mappings = function(prompt_bufnr) actions.select_default:replace(function() local selection = action_state.get_selected_entry() actions.close(prompt_bufnr) vim.cmd('normal! ciw' .. selection[1]) vim.cmd('stopinsert') end) return true end }):find() end internal.tagstack = function(opts) opts = opts or {} local tagstack = vim.fn.gettagstack() if vim.tbl_isempty(tagstack.items) then print("No tagstack available") return end for _, value in pairs(tagstack.items) do value.valid = true value.bufnr = value.from[1] value.lnum = value.from[2] value.col = value.from[3] value.filename = vim.fn.bufname(value.from[1]) value.text = vim.api.nvim_buf_get_lines( value.bufnr, value.lnum - 1, value.lnum, false )[1] end -- reverse the list local tags = {} for i = #tagstack.items, 1, -1 do tags[#tags+1] = tagstack.items[i] end pickers.new(opts, { prompt_title = 'TagStack', finder = finders.new_table { results = tags, entry_maker = make_entry.gen_from_quickfix(opts), }, previewer = conf.qflist_previewer(opts), sorter = conf.generic_sorter(opts), }):find() end internal.jumplist = function(opts) opts = opts or {} local jumplist = vim.fn.getjumplist()[1] -- reverse the list local sorted_jumplist = {} for i = #jumplist, 1, -1 do jumplist[i].text = '' table.insert(sorted_jumplist, jumplist[i]) end pickers.new(opts, { prompt_title = 'Jumplist', finder = finders.new_table { results = sorted_jumplist, entry_maker = make_entry.gen_from_jumplist(opts), }, previewer = conf.qflist_previewer(opts), sorter = conf.generic_sorter(opts), }):find() end local function apply_checks(mod) for k, v in pairs(mod) do mod[k] = function(opts) opts = opts or {} v(opts) end end return mod end return apply_checks(internal)
--- removes a player from the call for everyone in the call. ---@param source number the player to remove from the call ---@param callChannel number the call channel to remove them from function removePlayerFromCall(source, callChannel) logger.verbose('[call] Removed %s from call %s', source, callChannel) callData[callChannel] = callData[callChannel] or {} for player, _ in pairs(callData[callChannel]) do TriggerClientEvent('pma-voice:removePlayerFromCall', player, source) end callData[callChannel][source] = nil voiceData[source] = voiceData[source] or defaultTable(source) voiceData[source].call = 0 end --- adds a player to a call ---@param source number the player to add to the call ---@param callChannel number the call channel to add them to function addPlayerToCall(source, callChannel) logger.verbose('[call] Added %s to call %s', source, callChannel) -- check if the channel exists, if it does set the varaible to it -- if not create it (basically if not callData make callData) callData[callChannel] = callData[callChannel] or {} for player, _ in pairs(callData[callChannel]) do -- don't need to send to the source because they're about to get sync'd! if player ~= source then TriggerClientEvent('pma-voice:addPlayerToCall', player, source) end end callData[callChannel][source] = false voiceData[source] = voiceData[source] or defaultTable(source) voiceData[source].call = callChannel TriggerClientEvent('pma-voice:syncCallData', source, callData[callChannel]) end --- set the players call channel ---@param source number the player to set the call off ---@param _callChannel number the channel to set the player to (or 0 to remove them from any call channel) function setPlayerCall(source, _callChannel) if GetConvarInt('voice_enableCalls', 1) ~= 1 then return end voiceData[source] = voiceData[source] or defaultTable(source) local isResource = GetInvokingResource() local plyVoice = voiceData[source] local callChannel = tonumber(_callChannel) if not callChannel then -- only full error if its sent from another server-side resource if isResource then error(("'callChannel' expected 'number', got: %s"):format(type(_callChannel))) else return logger.warn("%s sent a invalid call, 'callChannel' expected 'number', got: %s", source,type(_callChannel)) end end if isResource then -- got set in a export, need to update the client to tell them that their call -- changed TriggerClientEvent('pma-voice:clSetPlayerCall', source, callChannel) end Player(source).state.callChannel = callChannel if callChannel ~= 0 and plyVoice.call == 0 then addPlayerToCall(source, callChannel) elseif callChannel == 0 then removePlayerFromCall(source, plyVoice.call) elseif plyVoice.call > 0 then removePlayerFromCall(source, plyVoice.call) addPlayerToCall(source, callChannel) end end exports('setPlayerCall', setPlayerCall) RegisterNetEvent('pma-voice:setPlayerCall', function(callChannel) setPlayerCall(source, callChannel) end) function setTalkingOnCall(talking) if GetConvarInt('voice_enableCalls', 1) ~= 1 then return end local source = source voiceData[source] = voiceData[source] or defaultTable(source) local plyVoice = voiceData[source] local callTbl = callData[plyVoice.call] if callTbl then logger.verbose('[call] %s %s talking in call %s', source, talking and 'started' or 'stopped', plyVoice.call) for player, _ in pairs(callTbl) do if player ~= source then logger.verbose('[call] Sending event to %s to tell them that %s is talking', player, source) TriggerClientEvent('pma-voice:setTalkingOnCall', player, source, talking) end end else logger.verbose('[call] %s tried to talk in call %s, but it doesnt exist.', source, plyVoice.call) end end RegisterNetEvent('pma-voice:setTalkingOnCall', setTalkingOnCall)
local utils = require('util') local url = require('url') local fs = require('fs') local path = require('path') local core = require('core') local client = require('rtsp/client') local RtspClient = client.RtspClient local rtspClient = nil local TAG = 'RTSPC' local color = console.color local function test_rtsp_client() rtspClient = RtspClient:new() rtspClient:on('close', function(err) print(TAG, 'close', err) end) rtspClient:on('error', function(err) print(TAG, 'error', err) end) local lastState = 0 rtspClient:on('state', function(state) print(TAG, color('function') .. 'state = ' .. state, color()) if (state == client.STATE_READY) then console.log(rtspClient.mediaTracks); console.log(rtspClient.isMpegTSMode); end lastState = state end) local lastSample = nil; rtspClient:on('sample', function(sample) if (not sample.isVideo) then return end if (not lastSample) then lastSample = {} end local buffer = sample.data[1] if (not buffer) then return end local startCode = string.char(0x00, 0x00, 0x00, 0x01) if (not sample.isFragment) or (sample.isStart) then local naluType = buffer:byte(1) & 0x1f --print('naluType', naluType) if (naluType ~= 1) then -- console.log('sample: ', naluType, sample.sampleTime, sample.sequence) end table.insert(lastSample, startCode) end for _, item in ipairs(sample.data) do table.insert(lastSample, item) end if (sample.marker) then local sampleData = table.concat(lastSample) lastSample.sampleTime = sample.sampleTime lastSample.isVideo = sample.isVideo -- TODO: lastSample console.log('sample: ', lastSample.isVideo, lastSample.sampleTime, #sampleData); lastSample = nil end end) local url = 'rtsp://192.168.31.64/live.mp4' rtspClient.username = 'admin'; rtspClient.password = 'admin123456'; rtspClient:open(url) end test_rtsp_client()
local orig_update_creative_inventory = creative.update_creative_inventory function creative.update_creative_inventory(player_name, tab_content) -- do original stuff orig_update_creative_inventory(player_name, tab_content) -- Set all stacks to maximum count local player_inv = minetest.get_inventory({type = "detached", name = "creative_" .. player_name}) local list = player_inv:get_list("main") for _, stack in ipairs(list) do stack:set_count(stack:get_stack_max()) end player_inv:set_list("main", list) end
help( [[ This module loads the MPC Libraries into the environment. Gnu Mpc is a C library for the arithmetic of complex numbers with arbitrarily high precision and correct rounding of the result. ]]) whatis("Loads the Gnu MPC Libraries") local version = "1.0.3" local base = "/cvmfs/oasis.opensciencegrid.org/osg/modules/mpc/"..version prepend_path("LD_LIBRARY_PATH", pathJoin(base, "lib")) load('mpfr/3.1.3') load('gmp/6.0.0') family('mpc')
gadsle_distombe = Creature:new { objectName = "@mob/creature_names:gadsle_distombe", socialGroup = "sith_shadow", faction = "sith_shadow", level = 87, chanceHit = 0.75, damageMin = 620, damageMax = 950, baseXp = 8315, baseHAM = 12400, baseHAMmax = 15200, armor = 0, resists = {70,70,70,70,70,70,70,70,-1}, meatType = "", meatAmount = 0, hideType = "", hideAmount = 0, boneType = "", boneAmount = 0, milk = 0, tamingChance = 0, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + KILLER + HEALER, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/dressed_fs_village_enemy_gadsle.iff"}, lootGroups = {}, weapons = {"mixed_force_weapons"}, conversationTemplate = "", attacks = merge(brawlermaster,pikemanmaster) } CreatureTemplates:addCreatureTemplate(gadsle_distombe, "gadsle_distombe")
--- @param character EsvCharacter --- @param status string --- @param tooltip TooltipData local function OnStatusTooltip(character, status, tooltip) end local function Statuses_Tooltips_Init() Game.Tooltip.RegisterListener("StatusDescription", nil, OnStatusTooltip) end Ext.RegisterListener("SessionLoaded", Statuses_Tooltips_Init)
-- -- HERKULEX_* SUBSYSTEM REPORTING -- -- Setup reporter components for servo_inv and herkulex_sched. -- Component -- -- Intended to be run via config script. -- require "reporting" -- herkulex_sched statistics reporting.add_filereporter("herkulex_statistics", { { name = "herkulex/sched" , ports= {"statistics"} } }, directory .. "/statistics.out") -- servo statej reporting.add_filereporter("herkulex_states", { { name = "herkulex/sched" , ports= {"out_states"} } }, directory .. "/states.out") -- control signals reporting.add_filereporter("herkulex_control", { { name = "aggregator_ref" , ports= {"out_joints_sorted"} }, { name = "aggregator_real" , ports= {"out_joints_sorted"} } }, directory .. "/control.out")
return { byte = 1, char = 1, dump = 1, find = 1, format = 4, gmatch = 1, gsub = 4, len = 1, lower = 1, match = 1, pack = 4, rep = 1, reverse = 1, sub = 1, unpack = 4, upper = 1, }
ResFontNumTxt = ClassUtil.class("ResFontNumTxt") ResFontNumTxt.ctor = function (slot0, slot1, slot2, slot3, slot4, slot5) slot0.iNum = nil ClassUtil.extends(slot0, ResFontTxt, true, slot1, slot2, slot3, slot4, slot5) end ResFontNumTxt.setNumber = function (slot0, slot1, slot2) if slot0.iNum ~= slot1 or slot2 then slot0.iNum = slot1 slot0:setTxt(tostring(slot1), slot2) end end ResFontNumTxt.getNumber = function (slot0) return slot0.iNum or 0 end return
--[[ Awesome-Freedesktop Freedesktop.org compliant desktop entries and menu Menu section Licensed under GNU General Public License v2 * (c) 2016, Luke Bonham * (c) 2014, Harvey Mittens --]] local awful_menu = require("awful.menu") local menu_gen = require("menubar.menu_gen") local menu_utils = require("menubar.utils") local icon_theme = require("menubar.icon_theme") local io, pairs, string, table, os = io, pairs, string, table, os -- Add support for NixOS systems too table.insert(menu_gen.all_menu_dirs, string.format("%s/.nix-profile/share/applications", os.getenv("HOME"))) -- Expecting a wm_name of awesome omits too many applications and tools menu_utils.wm_name = "" -- Menu -- freedesktop.menu local menu = {} -- Determines if a path points to a directory, by checking if it can be read -- (which is `nil` also for empty files) and if its size is not 0. -- @author blueyed -- @param path the path to check function menu.is_dir(path) local f = io.open(path) return f and not f:read(0) and f:seek("end") ~= 0 and f:close() end -- Remove non existent paths in order to avoid issues local existent_paths = {} for k,v in pairs(menu_gen.all_menu_dirs) do if menu.is_dir(v) then table.insert(existent_paths, v) end end menu_gen.all_menu_dirs = existent_paths -- Determines whether an table includes a certain element -- @param tab a given table -- @param val the element to search for -- @return true if the given string is found within the search table; otherwise, false if not function menu.has_value (tab, val) for index, value in pairs(tab) do if val:find(value) then return true end end return false end -- Use MenuBar parsing utils to build a menu for Awesome -- @return awful.menu function menu.build(args) local args = args or {} local icon_size = args.icon_size local before = args.before or {} local after = args.after or {} local skip_items = args.skip_items or {} local sub_menu = args.sub_menu or false local result = {} local _menu = awful_menu({ items = before }) menu_gen.generate(function(entries) -- Add category icons for k, v in pairs(menu_gen.all_categories) do table.insert(result, { k, {}, v.icon }) end -- Get items table for k, v in pairs(entries) do for _, cat in pairs(result) do if cat[1] == v.category then if not menu.has_value(skip_items, v.name) then table.insert(cat[2], { v.name, v.cmdline, v.icon }) end break end end end -- Cleanup things a bit for i = #result, 1, -1 do local v = result[i] if #v[2] == 0 then -- Remove unused categories table.remove(result, i) else --Sort entries alphabetically (by name) table.sort(v[2], function (a, b) return string.byte(a[1]) < string.byte(b[1]) end) -- Replace category name with nice name v[1] = menu_gen.all_categories[v[1]].name end end -- Sort categories alphabetically also table.sort(result, function(a, b) return string.byte(a[1]) < string.byte(b[1]) end) -- Add menu item to hold the generated menu if sub_menu then result = {{sub_menu, result}} end -- Add items to menu for _, v in pairs(result) do _menu:add(v) end for _, v in pairs(after) do _menu:add(v) end end) -- Set icon size if icon_size then for _,v in pairs(menu_gen.all_categories) do v.icon = icon_theme():find_icon_path(v.icon_name, icon_size) end end -- Hold the menu in the module menu.menu = _menu return _menu end return menu
local RegionAttachment = {} function RegionAttachment.new (name) if not name then error("name cannot be nil", 2) end local self = { name = name } return self end return RegionAttachment
local GSE = GSE local AceGUI = LibStub("AceGUI-3.0") local L = GSE.L local libS = LibStub:GetLibrary("AceSerializer-3.0") local libC = LibStub:GetLibrary("LibCompress") local libCE = libC:GetAddonEncodeTable() local importframe = AceGUI:Create("Frame") importframe.AutoCreateIcon = true importframe:Hide() importframe:SetTitle(L["GSE: Import a Macro String."]) importframe:SetStatusText(L["Import Macro from Forums"]) importframe:SetCallback("OnClose", function(widget) importframe:Hide(); GSE.GUIShowViewer() end) importframe:SetLayout("List") local importsequencebox = AceGUI:Create("MultiLineEditBox") importsequencebox:SetLabel(L["Macro Collection to Import."]) importsequencebox:SetNumLines(20) importsequencebox:DisableButton(true) importsequencebox:SetFullWidth(true) importframe:AddChild(importsequencebox) local createicondropdown = AceGUI:Create("CheckBox") createicondropdown:SetLabel(L["Automatically Create Macro Icon"]) createicondropdown:SetWidth(250) createicondropdown:SetType("checkbox") createicondropdown:SetValue(true) createicondropdown:SetCallback("OnValueChanged", function (obj,event,key) importframe.AutoCreateIcon = key end) importframe:AddChild(createicondropdown) local recButtonGroup = AceGUI:Create("SimpleGroup") recButtonGroup:SetLayout("Flow") local recbutton = AceGUI:Create("Button") recbutton:SetText(L["Import"]) recbutton:SetWidth(150) recbutton:SetCallback("OnClick", function() GSE.GUIImportSequence() end) recButtonGroup:AddChild(recbutton) --local testbutton = AceGUI:Create("Button") --testbutton:SetText("Test") --testbutton:SetWidth(150) --testbutton:SetCallback("OnClick", function() -- GSE.Print(GSE.StripControlandExtendedCodes(importsequencebox:GetText())) -- for i=69,85 do -- GSE.Print(string.byte(importsequencebox:GetText(), i)) -- end -- GSE.Print("Next") -- for i=69,85 do -- GSE.Print(string.byte(GSE.StripControlandExtendedCodes(importsequencebox:GetText()), i)) -- end --end) --recButtonGroup:AddChild(testbutton) importframe:AddChild(recButtonGroup) GSE.GUIImportFrame = importframe -- function GSE.GUIToggleImportDefault(switchstate) -- if switchstate == 1 then -- legacyradio:SetValue(true) -- defaultradio:SetValue(false) -- else -- legacyradio:SetValue(false) -- defaultradio:SetValue(true) -- end -- end function GSE.GUIImportSequence() local importstring = importsequencebox:GetText() importstring = GSE.TrimWhiteSpace(importstring) if string.sub(importstring,1,9) == "Sequences" then local legacy = false if GSE.isEmpty(string.find(importstring, "MacroVersions")) then legacy = true end local success, message = GSE.ImportSequence(importstring, legacy, importframe.AutoCreateIcon) if success then importsequencebox:SetText('') GSE.GUIImportFrame:Hide() else StaticPopup_Show ("GSE-MacroImportFailure") end else -- Either a compressed import or a failed copy local success = GSE.ImportSerialisedSequence(importstring, importframe.AutoCreateIcon) if success then importsequencebox:SetText('') GSE.GUIImportFrame:Hide() else StaticPopup_Show ("GSE-MacroImportFailure") end end end
res = 4 - 10 print(res) res = -34 print(res) numeroReal = 45.5 print(numeroReal) outroReal = -3.1 print(outroReal) pi = 3.145654646465656 print('PI ' .. pi)
local App = { gotoScene = function(class, options) end, newScene = function() return {} end } return App
-- * 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. -- This library contains shared code for Access Control Decision Function. local ipairs, type = ipairs, type; local clone, error_reply = require "util.stanza".clone, require "util.stanza".error_reply; local bare, section, split, t_remove = require "util.jid".bare, require "util.jid".section, require "util.jid".split, table.remove; local is_contact_subscribed = require "util.rostermanager".is_contact_subscribed; local function match_affiliation(affiliation, responses) for _, response in ipairs(responses) do if response == affiliation then return true; end end end local function match_jid(jid, list) for _, listed_jid in ipairs(list) do if jid == listed_jid then return true; end end end local function apply_policy(label, session, stanza, actions, check_acl) local breaks_policy; local from, to = stanza.attr.from, stanza.attr.to; if type(actions) == "table" then local _from, _to, _resource_jid; if type(check_acl) == "table" then -- assume it's a MAM ACL request if not to then to = check_acl.attr.from or session.full_jid; end _resource_jid = stanza.attr.resource; end _from, _to = section(from, "host"), section(to, "host"); if actions.type and stanza.attr.type ~= actions.type then breaks_policy = true; elseif actions.muc_affiliation then local muc_to, muc_from; if module:host_is_muc(_to) then muc_to = true; elseif module:host_is_muc(_from) then muc_from = true; end local rooms; if muc_to then rooms = module:get_host_session(_to).muc.rooms; local room = rooms[bare(to)]; if stanza.attr.type == "groupchat" then local affiliation, match = room:get_affiliation(from); match = match_affiliation(affiliation, actions.response); if not match then breaks_policy = true; end else local affiliation_from, match_from, affiliation_to, match_to; affiliation_from = room:get_affiliation(from); match_from = match_affiliation(affiliation_from, actions.response); affiliation_to = room:get_affiliation( room._occupants[to] and room._occupants[to].jid or nil ); match_to = match_affiliation(affiliation_to, actions.response); if not (match_to and match_from) then breaks_policy = true; end end elseif muc_from then rooms = module:get_host_session(_from).muc.rooms; local room = rooms[bare(from)]; if stanza.attr.type == "groupchat" then local affiliation, match = room:get_affiliation(to); match = match_affiliation(affiliation, actions.response); if not match then breaks_policy = true; end else local affiliation_from, match_from, affiliation_to, match_to; affiliation_from = room:get_affiliation( _resource_jid or (room._occupants[from] and room._occupants[from].jid or nil) ); match_from = match_affiliation(affiliation_from, actions.response); affiliation_to = room:get_affiliation(to); match_to = match_affiliation(affiliation_to, actions.response); if not (match_to and match_from) then breaks_policy = true; end end end elseif type(actions.host) == "table" then if actions.include_muc_subdomains then if module:host_is_muc(_from) and module:get_host_session(_from:match("%.([^%.].*)")) then _from = _from:match("%.([^%.].*)"); end if module:host_is_muc(_to) and module:get_host_session(_to:match("%.([^%.].*)")) then _to = _to:match("%.([^%.].*)"); end end if _from ~= (actions.host[1] or actions.host[2]) or _to ~= (actions.host[1] or actions.host[2]) then breaks_policy = true; end elseif type(actions.whitelist) == "table" and #actions.whitelist > 0 then local bare_from, bare_to = bare(from or session.full_jid), bare(to); if not (match_jid(bare_from, actions.whitelist) and match_jid(bare_to, actions.whitelist)) then breaks_policy = true; end end elseif actions == "roster" then local from_node, from_host = split(from); local to_node, to_host = split(to); if from_node and module:get_host_session(from_host) then if not is_contact_subscribed(from_node, from_host, bare(to)) then breaks_policy = true; end elseif to_node and module:get_host_session(to_host) then if not is_contact_subscribed(to_node, to_host, bare(from)) then breaks_policy = true; end end end if breaks_policy then if not check_acl then module:log("warn", "%s message to %s was blocked because it breaks the provided security label policy (%s)", from or session.full_jid, to, label); session.send(error_reply(stanza, "cancel", "policy-violation", "Message breaks security label "..label.." policy")); end return true; end end local policy_cache = {}; local function get_actions(host, label) local host_object = module:get_host_session(host); if host_object and label then if not policy_cache[host] then policy_cache[host] = setmetatable({}, { __mode = "v" }); end local cache = policy_cache[host]; if not cache[label] then cache[label] = host_object.events.fire_event("sec-labels-fetch-actions", label); end return cache[label]; end end local function check_policy(label, jid, stanza, request_stanza) local host, actions = section(stanza.attr.from, "host"); local actions = get_actions(host, label); if actions then return apply_policy(label, { full_jid = jid }, stanza, actions, request_stanza or true); end end return { apply_policy = apply_policy, check_policy = check_policy, get_actions = get_actions };