content
stringlengths
5
1.05M
--https://github.com/FPtje/DarkRP/blob/211395e81fe6024335f04cba6e647e9a1e6849aa/gamemode/modules/base/sv_gamemode_functions.lua#L305 local voiceDistance = RPGM.Config.VoiceRange ^ 2 local voice3d = RPGM.Config.Voice3D local useRadius = RPGM.Config.VoiceUseRadius local roomOnly = RPGM.Config.VoiceRoomOnly local whenDead = RPGM.Config.VoiceWhenDead local gridSize = voiceDistance * 2 --Grid cell size is equal to the size of the diamater of player talking local isInRoom = RPGM.IsInRoom local getHumans = player.GetHumans local ipairs = ipairs local pairs = pairs local insert = table.insert local floor = math.floor --Caching floor as we will need to use it a lot if not useRadius then --Voice radius check is off, don't run checks function GM:PlayerCanHearPlayersVoice(listener, talker) if not whenDead and not talker:Alive() then return false end return true, voice3d end return end local canHearWho = {} for k, ply in pairs(getHumans()) do canHearWho[ply] = {} end hook.Add("PlayerDisconnect", "RPGM.CanHearPlayersVoice", function(ply) canHearWho[ply] = nil end) function GM:PlayerCanHearPlayersVoice(listener, talker) if not whenDead and not talker:Alive() then return false end return canHearWho[listener][talker] == true, voice3d end --Grid based position check local grid --Translate player to grid coordinates. The first table maps players to x --coordinates, the second table maps players to y coordinates. local plyToGrid = { {}, {} } timer.Create("RPGM.CanHearPlayersVoice", RPGM.Config.VoiceCanHearCheckRate, 0, function() local players = getHumans() --Clear old values plyToGrid[1] = {} plyToGrid[2] = {} grid = {} local plyPos = {} local eyePos = {} --Get the grid position of every player O(N) for _, ply in ipairs(players) do eyePos[ply] = ply:EyePos() local pos = ply:GetPos() plyPos[ply] = pos local x = floor(pos.x / gridSize) local y = floor(pos.y / gridSize) local row = grid[x] or {} local cell = row[y] or {} insert(cell, ply) row[y] = cell grid[x] = row plyToGrid[1][ply] = x plyToGrid[2][ply] = y canHearWho[ply] = {} end --Check all neighbouring cells for every player. --We are only checking in 1 direction to avoid duplicate check of cells for _, ply1 in ipairs(players) do local gridX = plyToGrid[1][ply1] local gridY = plyToGrid[2][ply1] local ply1Pos = plyPos[ply1] local ply1EyePos = eyePos[ply1] for i = 0, 3 do local vOffset = 1 - ((i >= 3) and 1 or 0) local hOffset = -(i % 3-1) local x = gridX + hOffset local y = gridY + vOffset local row = grid[x] if not row then continue end local cell = row[y] if not cell then continue end for _, ply2 in ipairs(cell) do local canTalk = ply1Pos:DistToSqr(plyPos[ply2]) < voiceDistance and --Voice radius is on and the two are within hearing distance (not roomOnly or isInRoom(ply1EyePos, eyePos[ply2], ply2)) --Dynamic voice is on and players are in the same room canHearWho[ply1][ply2] = canTalk and (whenDead or ply2:Alive()) canHearWho[ply2][ply1] = canTalk and (whenDead or ply1:Alive()) --Take advantage of the symmetry end end end --Doing a pass-through inside every cell to compute the interactions inside of the cells. --Each grid check is O(N(N+1)/2) where N is the number of players inside the cell. for _, row in pairs(grid) do for _, cell in pairs(row) do local count = #cell for i = 1, count do local ply1 = cell[i] for j = i + 1, count do local ply2 = cell[j] local canTalk = plyPos[ply1]:DistToSqr(plyPos[ply2]) < voiceDistance and --Voice radius is on and the two are within hearing distance (not roomOnly or isInRoom(eyePos[ply1], eyePos[ply2], ply2)) --Dynamic voice is on and players are in the same room canHearWho[ply1][ply2] = canTalk and (whenDead or ply2:Alive()) canHearWho[ply2][ply1] = canTalk and (whenDead or ply1:Alive()) --Take advantage of the symmetry end end end end end)
-- alien modules --
--- -- @module ProjectilePath -- -- ------------------------------------------------ -- Required Modules -- ------------------------------------------------ local Bresenham = require( 'lib.Bresenham' ); local Util = require( 'src.util.Util' ) local Log = require( 'src.util.Log' ) local ChanceToHitCalculator = require( 'src.items.weapons.ChanceToHitCalculator' ) -- ------------------------------------------------ -- Module -- ------------------------------------------------ local ProjectilePath = {}; -- ------------------------------------------------ -- Constants -- ------------------------------------------------ local MARKSMAN_SKILL_MODIFIERS = { [0] = 30, [1] = 28, [2] = 25, [3] = 23, [4] = 20, [5] = 15, [6] = 11, [7] = 8, [8] = 4, [9] = 2, [10] = 1 } local THROWING_SKILL_MODIFIERS = { [0] = 30, [1] = 28, [2] = 25, [3] = 23, [4] = 20, [5] = 15, [6] = 11, [7] = 8, [8] = 4, [9] = 2, [10] = 1 } local RANGED_WEAPON_MODIFIERS = { [0] = 27, [1] = 23, [2] = 20, [3] = 17, [4] = 14, [5] = 11, [6] = 8, [7] = 5, [8] = 3, [9] = 1, [10] = 0 } local RANGED_BURST_MODIFIERS = { [1] = 0, [2] = 2, [3] = 3, [4] = 4, [5] = 6, [6] = 7, [7] = 8, [8] = 9, [9] = 10 } local STANCES = require( 'src.constants.STANCES' ) local RANGED_STANCE_MODIFIER = { [STANCES.STAND] = 1.0, [STANCES.CROUCH] = 0.7, [STANCES.PRONE] = 0.5, } local THROWN_STANCE_MODIFIERS = { [STANCES.STAND] = 1.0, [STANCES.CROUCH] = 0.7, [STANCES.PRONE] = 1.2, -- Throwing should be harder from a prone stance. } local WEAPON_TYPES = require( 'src.constants.WEAPON_TYPES' ) -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ --- -- Returns a random sign. -- @return (number) Either one or minus one. -- local function randomSign() return love.math.random( 0, 1 ) == 0 and -1 or 1; end --- -- Floors a value to the previous multiple of ten. -- @tparam number value The value to round. -- @treturn number The rounded value. -- local function floor( value ) return math.floor( value / 10 ) end --- -- Generates a random angle in the specified range. -- @param range (number) The range to choose from. -- @return (number) The random angle. -- local function getRandomAngle( range ) return love.math.random( range * 100 ) / 100 end --- -- Calculates the maximum angle of deviation for the shot. -- @param character (Character) The character shooting the weapon. -- @param weapon (Weapon) The used weapon. -- @param count (number) Determines how many projectiles have been fired already. -- @return (number) The maximum range for the deviation. -- local function calculateRangedMaximumDeviation( character, weapon, count ) local marksmanSkill = floor( character:getShootingSkill() ) local weaponAccuracy = floor( weapon:getAccuracy() ) local deviation = 0 -- Random angle based on the character's accuracy skill. deviation = deviation + MARKSMAN_SKILL_MODIFIERS[marksmanSkill] -- Random angle based on weapon's accuracy stat. deviation = deviation + RANGED_WEAPON_MODIFIERS[weaponAccuracy] -- Random angle based on how many bullets have been shot before. deviation = deviation + RANGED_BURST_MODIFIERS[math.min( count, #RANGED_BURST_MODIFIERS )] -- Stances influence the whole angle. deviation = deviation * RANGED_STANCE_MODIFIER[character:getStance()] return math.max( deviation, 0 ) end --- -- Calculates the maximum angle of deviation for the shot. -- @param character (Character) The character throwing the weapon. -- @return (number) The maximum range for the deviation. -- local function calculateThrownMaximumDeviation( character ) local throwingSkill = floor( character:getThrowingSkill() ) local deviation = 0 -- Random angle based on the character's accuracy skill. deviation = deviation + THROWING_SKILL_MODIFIERS[throwingSkill] -- Stances influence the whole angle. deviation = deviation * THROWN_STANCE_MODIFIERS[character:getStance()] return deviation end --- -- Determine the height falloff for a projectile. -- This is achieved by taking the height at the origin of the attack and the -- height of the target. -- The height of the target is halved and a random value is either added to or -- subtracted from it. The random value is based on half the target's size and -- an additional modifier. -- @tparam Tile origin The starting tile. -- @tparam number theight The target's height. -- @tparam number steps The distance to the target. -- @treturn number The calculated falloff value. -- local function calculateFalloff( origin, theight, steps ) local oheight = origin:getHeight() -- TODO base on skills? -- This takes the center of the target and adds or subtracts a random value -- based on the half size of the target with a constant modifier added to it. local usedHeight = theight * 0.5 + randomSign() * love.math.random( theight * 0.5 + 10 ) local delta = oheight - usedHeight return delta / steps end --- -- Determines which coordinates a projectile traverses on its way to the target. -- @tparam Character character The character shooting the weapon. -- @tparam number tx The target's x-coordinate. -- @tparam number ty The target's y-coordinate. -- @treturn table A sequence containing the X and Y coordinates of each traversed tile. -- local function determineTraversedCoordinates( character, tx, ty ) local ox, oy = character:getTile():getPosition() local coordinates = {} Bresenham.line( ox, oy, tx, ty, function( sx, sy ) -- Ignore the origin. if sx ~= ox or sy ~= oy then coordinates[#coordinates + 1] = { x = sx, y = sy } end return true end) return coordinates end --- -- Determines which coordinates a projectile traverses on its way to the deviated target. -- @tparam Character character The character shooting the weapon. -- @tparam number tx The target's x-coordinate. -- @tparam number ty The target's y-coordinate. -- @tparam number th The target's height. -- @tparam Weapon weapon The used weapon. -- @tparam number count Determines how many projectiles have been fired already. -- @treturn table A sequence containing all tiles of the projectile's path. -- local function determineDeviationCoordinates( character, tx, ty, th, weapon, count ) -- Calculate the angle of deviation. local maxDeviation = ProjectilePath.getMaximumDeviation( character, weapon, count ) local actualDeviation = randomSign() * getRandomAngle( maxDeviation ) -- Apply the angle to find the final target tile. local origin = character:getTile() local px, py = origin:getPosition() local nx, ny = Util.rotateVector( px, py, tx, ty, actualDeviation, love.math.random( 90, 130 ) / 100 ) nx, ny = math.floor( nx + 0.5 ), math.floor( ny + 0.5 ) -- Determine the height falloff for the projectile. local _, steps = Bresenham.line( px, py, nx, ny ) local falloff = calculateFalloff( origin, th, steps ) -- Get the coords of all tiles the projectile passes on the way to its target. local tiles = {} Bresenham.line( px, py, nx, ny, function( sx, sy, counter ) -- Ignore the origin. if sx ~= px or sy ~= py then tiles[#tiles + 1] = { x = sx, y = sy, z = origin:getHeight() - (counter+1) * falloff } end return true end) return tiles end -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ --- -- Helper function which picks the right calculation function based on the -- weapon's type. -- @param character (Character) The character shooting the weapon. -- @param weapon (Weapon) The used weapon. -- @param count (number) Determines how many projectiles have been fired already. -- @return (number) The maximum range for the deviation. -- function ProjectilePath.getMaximumDeviation( character, weapon, count ) if weapon:getSubType() == WEAPON_TYPES.RANGED then return calculateRangedMaximumDeviation( character, weapon, count ) elseif weapon:getSubType() == WEAPON_TYPES.THROWN then return calculateThrownMaximumDeviation( character ) else error( string.format( 'Can\'t calculate a deviation for selected weapon type %s!', weapon:getSubType() )) end end --- -- Creates the path for a particular projectile. -- @tparam Character character The character shooting the weapon. -- @tparam Tile target The target tile. -- @tparam Weapon weapon The used weapon. -- @tparam number count Determines how many projectiles have been fired already. -- @treturn table A sequence containing all tiles of the projectile's path. -- function ProjectilePath.calculate( character, target, weapon, count ) local chanceToHit = ChanceToHitCalculator.calculate( character, target ) Log.debug( 'Chance to hit: ' .. chanceToHit, 'ProjectilePath' ) -- The shot hits its target. if love.math.random(100) <= chanceToHit then Log.debug( 'Attack hits the target', 'ProjectilePath' ) return determineTraversedCoordinates( character, target:getPosition() ) end -- The shot misses. Log.debug( 'Attack misses the target', 'ProjectilePath' ) return determineDeviationCoordinates( character, target:getX(), target:getY(), target:getHeight(), weapon, count ) end return ProjectilePath;
local awful = require("awful") local beautiful = require("beautiful") local variables = require("modules.variables") -- {{{ Menu -- Create a launcher widget and a main menu local mainmenu = awful.menu({ items = { -- {"manual", variables.terminal .. " -e man awesome"}, -- {"edit config", variables.editor .. " " .. awesome.conffile}, -- {"restart", awesome.restart}, -- {"open terminal", variables.terminal}}, {"launch picom", variables.picom} }) Launcher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = mainmenu }) -- }}}
-- $Id: tmod1.lua,v 1.1 2004/03/25 19:31:05 tomas Exp $ ap.set_content_type"text/html" ap.rputs "ap.args = {" ap.rputs (ap.args() or '') ap.rputs "}<br>\n" assert (ap.setup_client_block ("REQUEST_CHUNKED_ERROR") == ap.OK) if ap.should_client_block () ~= 0 then post_data = {} local block, err = ap.get_client_block () while block do table.insert (post_data, block) block, err = ap.get_client_block () end if err then error (err) end post_data = table.concat (post_data) end ap.rputs "post_data = {" ap.rputs (tostring (post_data)) ap.rputs "}\n"
--Configure home path so you dont have too home_path = os.getenv('HOME') .. '/' -- Standard awesome library local gears = require("gears") local awful = require("awful") awful.rules = require("awful.rules") require("awful.autofocus") -- Widget and layout library local wibox = require("wibox") -- Theme handling library local beautiful = require("beautiful") beautiful.init( awful.util.getdir("config") .. "/themes/default/theme.lua" ) -- Notification library local naughty = require("naughty") local menubar = require("menubar") --FreeDesktop require('freedesktop.utils') require('freedesktop.menu') freedesktop.utils.icon_theme = 'gnome' --Vicious + Widgets vicious = require("vicious") local wi = require("wi") -- {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- another config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal("debug::error", function (err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err) }) in_error = false end) end -- }}} -- This is used later as the default terminal and editor to run. term = "urxvt " terminal = term .. " -e 'tmux'" editor = os.getenv("EDITOR") or "vim" editor_cmd = term .. " -e " .. editor -- editor_cmd = terminal .. " -e " .. editor -- Default modkey. -- Usually, Mod4 is the key with a logo between Control and Alt. -- If you do not like this or do not have such a key, -- I suggest you to remap Mod4 to another key using xmodmap or other tools. -- However, you can use another modifier like Mod1, but it may interact with others. modkey = "Mod4" -- Table of layouts to cover with awful.layout.inc, order matters. awful.layout.layouts = { awful.layout.suit.floating, awful.layout.suit.tile, awful.layout.suit.tile.left, awful.layout.suit.tile.bottom, awful.layout.suit.tile.top, awful.layout.suit.fair, awful.layout.suit.fair.horizontal, awful.layout.suit.spiral, awful.layout.suit.spiral.dwindle, awful.layout.suit.max, awful.layout.suit.max.fullscreen, awful.layout.suit.magnifier } -- }}} -- {{{ Naughty presets naughty.config.defaults.timeout = 5 naughty.config.defaults.screen = 1 naughty.config.defaults.position = "top_right" naughty.config.defaults.margin = 8 naughty.config.defaults.gap = 1 naughty.config.defaults.ontop = true naughty.config.defaults.font = "terminus 8" naughty.config.defaults.icon = nil naughty.config.defaults.icon_size = 128 naughty.config.defaults.fg = beautiful.fg_tooltip naughty.config.defaults.bg = beautiful.bg_tooltip naughty.config.defaults.border_color = beautiful.border_tooltip naughty.config.defaults.border_width = 2 naughty.config.defaults.hover_timeout = nil -- -- }}} local function set_wallpaper(s) -- Wallpaper if beautiful.wallpaper then local wallpaper = beautiful.wallpaper -- If wallpaper is a function, call it with the screen if type(wallpaper) == "function" then wallpaper = wallpaper(s) end gears.wallpaper.maximized(wallpaper, s, true) end end -- Re-set wallpaper when a screen's geometry changes (e.g. different resolution) screen.connect_signal("property::geometry", set_wallpaper) -- Wallpaper Changer Based On -- menu icon menu pdq 07-02-2012 local wallmenu = {} local function wall_load(wall) local f = io.popen('ln -sfn ' .. home_path .. '.config/awesome/wallpaper/' .. wall .. ' ' .. home_path .. '.config/awesome/themes/default/bg.png') awesome.restart() end local function wall_menu() local f = io.popen('ls -1 ' .. home_path .. '.config/awesome/wallpaper/') for l in f:lines() do local item = { l, function () wall_load(l) end } table.insert(wallmenu, item) end f:close() end wall_menu() -- Widgets spacer = wibox.widget.textbox() spacer:set_text(' | ') --Weather Widget weather = wibox.widget.textbox() vicious.register(weather, vicious.widgets.weather, "Weather: ${city}. Sky: ${sky}. Temp: ${tempc}c Humid: ${humid}%. Wind: ${windkmh} KM/h", 1200, "YMML") --Battery Widget batt = wibox.widget.textbox() vicious.register(batt, vicious.widgets.bat, "Batt: $2% Rem: $3", 61, "BAT0") -- {{{ Menu -- Create a laucher widget and a main menu menu_items = freedesktop.menu.new() myawesomemenu = { { "manual", terminal .. " -e man awesome", freedesktop.utils.lookup_icon({ icon = 'help' }) }, { "edit config", editor_cmd .. " " .. awesome.conffile, freedesktop.utils.lookup_icon({ icon = 'package_settings' }) }, { "restart", awesome.restart, freedesktop.utils.lookup_icon({ icon = 'system-shutdown' }) }, { "quit", awesome.quit, freedesktop.utils.lookup_icon({ icon = 'system-shutdown' }) } } table.insert(menu_items, { "Awesome", myawesomemenu, beautiful.awesome_icon }) table.insert(menu_items, { "Wallpaper", wallmenu, freedesktop.utils.lookup_icon({ icon = 'gnome-settings-background' })}) mymainmenu = awful.menu({ items = menu_items, width = 150 }) mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = mymainmenu }) -- Menubar configuration menubar.utils.terminal = terminal -- Set the terminal for applications that require it menubar.app_folders = { "/usr/share/applications/", "~/.local/share/applications/" } menubar.cache_entries = true -- }}} -- {{{ Wibox -- Create a textclock widget mytextclock = wibox.widget.textclock(" %a %b %d, %I:%M:%S ", 1) -- Create a wibox for each screen and add it local taglist_buttons = awful.util.table.join( awful.button({ }, 1, function(t) t:view_only() end), awful.button({ modkey }, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end), awful.button({ }, 4, function(t) awful.tag.viewnext(t.screen) end), awful.button({ }, 5, function(t) awful.tag.viewprev(t.screen) end) ) mytasklist = {} local tasklist_buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else -- Without this, the following -- :isvisible() makes no sense c.minimized = false if not c:isvisible() and c.first_tag then c.first_tag:view_only() end -- This will also un-minimize -- the client, if needed client.focus = c c:raise() end end), awful.button({ }, 3, function () if instance then instance:hide() instance = nil else instance = awful.menu.clients({ width=250 }) end end), awful.button({ }, 4, function () awful.client.focus.byidx(1) if client.focus then client.focus:raise() end end), awful.button({ }, 5, function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end)) awful.screen.connect_for_each_screen(function(s) -- Wallpaper set_wallpaper(s) -- Each screen has its own tag table. awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.layouts[1]) -- Create a promptbox for each screen s.mypromptbox = awful.widget.prompt() -- Create an imagebox widget which will contains an icon indicating which layout we're using. -- We need one layoutbox per screen. s.mylayoutbox = awful.widget.layoutbox(s) s.mylayoutbox:buttons(awful.util.table.join( awful.button({ }, 1, function () awful.layout.inc( 1) end), awful.button({ }, 3, function () awful.layout.inc(-1) end), awful.button({ }, 4, function () awful.layout.inc( 1) end), awful.button({ }, 5, function () awful.layout.inc(-1) end))) -- Create a taglist widget s.mytaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, taglist_buttons) -- Create a tasklist widget s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist_buttons) -- Create the wibox s.mywibox = awful.wibox({ position = "top", screen = s }) -- Widgets that are aligned to the left local left_layout = wibox.layout.fixed.horizontal() left_layout:add(s.mytaglist) left_layout:add(s.mypromptbox) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() right_layout:add(wibox.widget.systray()) right_layout:add(spacer) right_layout:add(mailicon) right_layout:add(mailwidget) right_layout:add(spacer) right_layout:add(pacicon) right_layout:add(pacwidget) right_layout:add(spacer) right_layout:add(volicon) right_layout:add(volpct) right_layout:add(volspace) right_layout:add(spacer) right_layout:add(mytextclock) right_layout:add(s.mylayoutbox) -- Widgets that are aligned to the bottom local bottom_layout = wibox.layout.fixed.horizontal() bottom_layout:add(cpuicon) bottom_layout:add(cpu) bottom_layout:add(spacer) bottom_layout:add(memicon) bottom_layout:add(mem) bottom_layout:add(spacer) bottom_layout:add(wifiicon) bottom_layout:add(wifi) bottom_layout:add(spacer) bottom_layout:add(baticon) bottom_layout:add(batpct) bottom_layout:add(spacer) -- Now bring it all together (with the tasklist in the middle) local layout = wibox.layout.align.horizontal() layout:set_left(left_layout) layout:set_middle(s.mytasklist) layout:set_right(right_layout) local vlayout = wibox.layout.align.vertical() vlayout:set_bottom(bottom_layout) s.mywibox:set_widget(layout) --s.mywibox:set_widget(vlayout) end) -- }}} -- {{{ Mouse bindings root.buttons(awful.util.table.join( awful.button({ }, 3, function () mymainmenu:toggle() end), awful.button({ }, 4, awful.tag.viewnext), awful.button({ }, 5, awful.tag.viewprev) )) -- }}} -- {{{ Key bindings globalkeys = awful.util.table.join( awful.key({ modkey, }, "Left", awful.tag.viewprev ), awful.key({ modkey, }, "Right", awful.tag.viewnext ), awful.key({ modkey, }, "Escape", awful.tag.history.restore), awful.key({ modkey, }, "j", function () awful.client.focus.byidx( 1) if client.focus then client.focus:raise() end end), awful.key({ modkey, }, "k", function () awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end), awful.key({ }, "Print", function () awfuil.spawn("upload_screens scr") end), -- Layout manipulation awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end), awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end), awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end), awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end), awful.key({ modkey, }, "u", awful.client.urgent.jumpto), awful.key({ modkey, }, "Tab", function () awful.client.focus.history.previous() if client.focus then client.focus:raise() end end), -- Standard program awful.key({ modkey, }, "Return", function () awful.spawn(terminal) end), awful.key({ modkey, "Shift" }, "Return", function () awful.spawn(term) end), awful.key({ modkey, "Control" }, "r", awesome.restart), awful.key({ modkey, "Shift" }, "q", awesome.quit), awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end), awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end), awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1) end), awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1) end), awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1) end), awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1) end), awful.key({ modkey, }, "space", function () awful.layout.inc(layouts, 1) end), awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(layouts, -1) end), awful.key({ modkey, }, "w", function () awfuil.spawn("firefox") end, "Start Firefox Web Browser"), awful.key({ modkey, "Control" }, "n", awful.client.restore), -- Prompt awful.key({ modkey }, "r", function () awful.screen.focused().mypromptbox:run() end), awful.key({ modkey }, "x", function () awful.prompt.run { prompt = "Run Lua code: ", textbox = awful.screen.focused().mypromptbox.widget, exe_callback = awful.util.eval, history_path = awful.util.get_cache_dir() .. "/history_eval" } end), -- Menubar awful.key({ modkey }, "p", function() menubar.show() end) ) clientkeys = awful.util.table.join( awful.key({ modkey, }, "f", function (c) c.fullscreen = not c.fullscreen end), awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end), awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle ), awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end), awful.key({ modkey, }, "o", function (c) c:move_to_screen() end), awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end), awful.key({ modkey, }, "n", function (c) -- The client currently has the input focus, so it cannot be -- minimized, since minimized clients can't have the focus. c.minimized = true end), awful.key({ modkey, }, "m", function (c) c.maximized_horizontal = not c.maximized_horizontal c.maximized_vertical = not c.maximized_vertical end) ) -- Bind all key numbers to tags. -- Be careful: we use keycodes to make it works on any keyboard layout. -- This should map on the top row of your keyboard, usually 1 to 9. for i = 1, 9 do globalkeys = awful.util.table.join(globalkeys, -- View tag only. awful.key({ modkey }, "#" .. i + 9, function () local screen = awful.screen.focused() local tag = screen.tags[i] if tag then tag:view_only() end end, {description = "view tag #"..i, group = "tag"}), -- Toggle tag display. awful.key({ modkey, "Control" }, "#" .. i + 9, function () local screen = awful.screen.focused() local tag = screen.tags[i] if tag then awful.tag.viewtoggle(tag) end end, {description = "toggle tag #" .. i, group = "tag"}), -- Move client to tag. awful.key({ modkey, "Shift" }, "#" .. i + 9, function () if client.focus then local tag = client.focus.screen.tags[i] if tag then client.focus:move_to_tag(tag) end end end, {description = "move focused client to tag #"..i, group = "tag"}), -- Toggle tag on focused client. awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9, function () if client.focus then local tag = client.focus.screen.tags[i] if tag then client.focus:toggle_tag(tag) end end end, {description = "toggle focused client on tag #" .. i, group = "tag"}) ) end clientbuttons = awful.util.table.join( awful.button({ }, 1, function (c) client.focus = c; c:raise() end), awful.button({ modkey }, 1, awful.mouse.client.move), awful.button({ modkey }, 3, awful.mouse.client.resize)) -- Set keys root.keys(globalkeys) -- }}} -- {{{ Rules -- Rules to apply to new clients (through the "manage" signal). awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, keys = clientkeys, buttons = clientbuttons, screen = awful.screen.preferred, placement = awful.placement.no_overlap+awful.placement.no_offscreen} }, { rule = { class = "gimp" }, properties = { floating = true } }, { rule = { class = "Firefox" }, properties = { screen = 1, tag = "9" } }, { rule = { instance = "plugin-container" }, properties = { floating = true } }, { rule = { instance = "Steam" }, properties = { floating = true } }, { rule = { instance = "shoes" }, properties = { floating = true } }, } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.connect_signal("manage", function (c, startup) -- Enable sloppy focus c:connect_signal("mouse::enter", function(c) if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier and awful.client.focus.filter(c) then client.focus = c end end) if not startup then -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. -- awful.client.setslave(c) -- Put windows in a smart way, only if they does not set an initial position. if not c.size_hints.user_position and not c.size_hints.program_position then awful.placement.no_overlap(c) awful.placement.no_offscreen(c) end end local titlebars_enabled = false if titlebars_enabled and (c.type == "normal" or c.type == "dialog") then -- Widgets that are aligned to the left local left_layout = wibox.layout.fixed.horizontal() left_layout:add(awful.titlebar.widget.iconwidget(c)) -- Widgets that are aligned to the right local right_layout = wibox.layout.fixed.horizontal() right_layout:add(awful.titlebar.widget.floatingbutton(c)) right_layout:add(awful.titlebar.widget.maximizedbutton(c)) right_layout:add(awful.titlebar.widget.stickybutton(c)) right_layout:add(awful.titlebar.widget.ontopbutton(c)) right_layout:add(awful.titlebar.widget.closebutton(c)) -- The title goes in the middle local title = awful.titlebar.widget.titlewidget(c) title:buttons(awful.util.table.join( awful.button({ }, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end), awful.button({ }, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end) )) -- Now bring it all together local layout = wibox.layout.align.horizontal() layout:set_left(left_layout) layout:set_right(right_layout) layout:set_middle(title) awful.titlebar(c):set_widget(layout) end end) client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end) client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end) -- }}}
local wkOpts = require("utils.whichkey-plugin") local wk = require("which-key") wk.register( { ["<leader>"] = { t = { name = "+Theme", m = "Material Theme Toggle", } } }, wkOpts.defaultOpts )
local playsession = { {"whollyspokes", {1061175}}, {"helic99", {1228096}}, {"DarkChedarCheese", {76898}}, {"mad58max", {1250805}}, {"BamBamPalli", {400240}}, {"xcube", {1254194}}, {"Spanish", {1097505}}, {"cogito123", {511273}}, {"corbin9228", {1257035}}, {"Jeremykyle", {657299}}, {"soiamglad", {6068}}, {"tyssa", {993418}}, {"moocat12", {120351}}, {"KatanaKiwi", {459421}}, {"StormBreaker", {951713}}, {"safriq", {1157032}}, {"Phishr42", {14325}}, {"rykstar", {79654}}, {"Gorganus", {531970}}, {"CannedHam", {16966}}, {"moqart", {20106}}, {"pixel-perfect", {1164371}}, {"Roeno1997", {456187}}, {"ballbuster", {288906}}, {"MrZaxxxx", {685859}}, {"TNT_MAN1111", {764323}}, {"Bipolar_Bear", {194080}}, {"BubblesAndSuch", {412242}}, {"Biker", {342075}}, {"J7cuxolor", {44968}}, {"Tornado_05", {172176}}, {"ouchie3014", {387388}}, {"Beans_Man_2", {396681}}, {"bogg19", {2858}}, {"MamieTipiak", {320790}}, {"BallisticGamer04", {1089211}}, {"Stoma", {11645}}, {"ausmister", {1026405}}, {"Grooohm", {31028}}, {"beranabus", {362593}}, {"Schallfalke", {1066734}}, {"vanios", {380}}, {"loutanifi", {99037}}, {"RebuffedBrute44", {421229}}, {"flooxy", {368306}}, {"grehak", {310767}}, {"yoyo2380", {1012464}}, {"aj198200", {767799}}, {"therv", {2155}}, {"Mr.Clear", {36940}}, {"chicki2", {525253}}, {"Dowo", {131148}}, {"I_dream_of_corn", {11761}}, {"unknownczar", {22785}}, {"greattohave", {458721}}, {"scifitoga", {12420}}, {"svartakon", {25120}}, {"Random-Dud", {585}}, {"PortalMaster555", {757118}}, {"zbirka", {11369}}, {"Markius", {741069}}, {"brfbrf", {14460}}, {"Abjoe", {7656}}, {"tmoneyfizzle", {2620}}, {"tomcooltc", {6769}}, {"eyepex", {610210}}, {"TheNetworkDoctor", {21192}}, {"Niklasw112", {173532}}, {"Blacksheep436", {15386}}, {"spencer123214", {15840}}, {"Reyand", {1292}}, {"3061867813", {305}}, {"Dysonhive", {35116}}, {"KrotikAE", {1933}}, {"MadClown01", {8026}}, {"Progman", {9063}}, {"I_Am_Shockwave", {7821}}, {"Dofolo", {8033}}, {"FireLeaf", {394120}}, {"Zory", {10835}}, {"bclear", {38915}}, {"Asteroz", {168304}}, {"chilldude.uk", {190866}}, {"redaisenjack", {129156}}, {"best2", {146284}}, {"Breezy.", {116461}}, {"taroxyz", {177089}}, {"JoaoPinga", {130321}}, {"Smochee", {168312}}, {"brandonandpie", {167512}}, {"Schembo", {164466}}, {"xPedion", {114796}}, {"DrinkAlot13", {13856}}, {"Achskelmos", {55532}}, {"Mathilas", {7437}}, {"redlabel", {10202}} } return playsession
local new_zipkin_reporter = require("kong.plugins.zipkin.reporter").new local new_span = require("kong.plugins.zipkin.span").new local utils = require "kong.tools.utils" local to_hex = require "resty.string".to_hex local function gen_trace_id(traceid_byte_count) return to_hex(utils.get_rand_bytes(traceid_byte_count)) end local function gen_span_id() return to_hex(utils.get_rand_bytes(8)) end describe("reporter", function () it("constructs a reporter", function () local reporter = new_zipkin_reporter("http://localhost:1234", "DefaultServiceName", "LocalServiceName") assert.same(reporter.default_service_name, "DefaultServiceName") assert.same(reporter.local_service_name, "LocalServiceName") end) it("pushes spans into the pending spans buffer", function () local reporter = new_zipkin_reporter("http://localhost:1234", "DefaultServiceName", "LocalServiceName") local span = new_span( "SERVER", "test-span", 1, true, gen_trace_id(16), gen_span_id(), gen_span_id(), {} ) reporter:report(span) assert(reporter.pending_spans_n, 1) assert.same(reporter.pending_spans, { { id = to_hex(span.span_id), name = "test-span", kind = "SERVER", localEndpoint = { serviceName = "LocalServiceName" }, remoteEndpoint = { serviceName = "DefaultServiceName" }, timestamp = 1, traceId = to_hex(span.trace_id), parentId = to_hex(span.parent_id), } }) end) end)
-- mediafire --[[ TBTurret ]]-- math.randomseed(tick()) Colors={"Bright red","Really red","Bright yellow","Bright orange","New Yeller","Deep orange","Neon orange"} V3 = Vector3.new C3 = Color3.new BN = BrickColor.new CN = CFrame.new CA = CFrame.Angles MR = math.rad MRA = math.random MP = math.pi MH = math.huge UD = UDim2.new TI = table.insert TR = table.remove CR = coroutine.resume CC = coroutine.create it = Instance.new Sound = "http://www.roblox.com/asset/?id=81116747" Fire="http://www.roblox.com/asset/?id=10209821" cn = CN rd = MR ca = CA rn = MRA v3 = V3 me = game.Players.LocalPlayer Hold = false Sitting = false DecalBulletHole = "http://www.roblox.com/asset/?id=64291961" pcall(function()me.Character.Humanoid.MaxHealth=500 wait() me.Character.Humanoid.Health=500 end) stick = function(hit2,hit) local weld=Instance.new("Weld") weld.Part0=hit2 weld.Part1=hit local HitPos=hit2.Position local CJ=CN(HitPos) local C0=hit2.CFrame:inverse() *CJ local C1=hit.CFrame:inverse() * CJ weld.C0=C0 weld.C1=C1 weld.Parent=hit2 end function Part(Par, Anc, Colli, Tran, Ref, Col, Siz, Mat, Type) local p = it("Part") p.formFactor = "Custom" p.TopSurface = 0 p.BottomSurface = 0 p.Transparency = Tran p.Reflectance = Ref p.Anchored = Anc p.CanCollide = Colli p.BrickColor = Col p.Size = Siz p.Material = Mat or "Plastic" p.Locked = true if Type == "Wedge" then it("SpecialMesh",p).MeshType = "Wedge" elseif Type == "Sphere" then it("SpecialMesh",p).MeshType = "Sphere" elseif Type == "Cylinder" then it("CylinderMesh",p) elseif Type == "Block" then it("BlockMesh",p) end p.Parent = Par p:BreakJoints() return p end RocketExplode=it("Sound",me.Character.Torso) RocketExplode.SoundId=Sound RocketExplode.Volume=1 RocketExplode.Pitch=1 Fiyah=it("Sound",me.Character.Torso) Fiyah.SoundId=Fire Fiyah.Volume=1 Fiyah.Pitch=1 cam=workspace.CurrentCamera for i,v in pairs(cam:children()) do v:Remove() end Crown="http://www.roblox.com/asset/?id=20329976" Spike="http://www.roblox.com/asset/?id=1033714" ray = function(Pos,Dir,xxz) local xxz2=c if not xxz then xxz2=nil end return workspace:FindPartOnRay(Ray.new(Pos, Dir.unit*999),xxz2) end function Blast(Color,Offset) local bp=Part(mod,true,false,0,0.15,BN(Colors[math.random(1,#Colors)]),V3(1,1,1),"Plastic") bp.Name="Blast" local bm=it("SpecialMesh",bp) bm.MeshId=Crown bm.Scale=v3(5,4,5) bp.CFrame=Offset q(function() for i=-0.2,1,0.12 do bp.Transparency=i+0.1 bm.Scale=V3(1+(5*1)*i, (2.4*1)+1*i, 1+(5*1)*i) wait() end game:GetService("Debris"):AddItem(bp) end) end --TURRET BUILDING pcall(function()me.Character["Turret"]:Remove()end) mod = it("Model",me.Character)mod.Name="Turret" base = Part(mod,true,true,0,0,BN("Medium grey"),V3(6,1,6),"Plastic","Cylinder") p1 = Part(mod,true,true,0,0,BN("Medium grey"),V3(1,4,1),"Plastic","Cylinder") seat = Part(mod,true,true,0,0,BN("Medium grey"),V3(2,0.5,2.5),"Plastic","Block") seatb = Part(mod,true,true,0,0,BN("Medium grey"),V3(2,3,.5),"Plastic","Block") seatattachment = Part(mod,true,true,0,0,BN("Medium grey"),V3(1,4,1),"Plastic","Cylinder") seatatball1=Part(mod,true,true,0,0,BN("Medium grey"),V3(2,2,2),"Plastic","Sphere") seatattachment2 = Part(mod,true,true,0,0,BN("Medium grey"),V3(1,5,1),"Plastic","Cylinder") seatatball2=Part(mod,true,true,0,0,BN("Medium grey"),V3(2,2,2),"Plastic","Sphere") seatattachment3 = Part(mod,true,true,0,0,BN("Medium grey"),V3(1,5,1),"Plastic","Cylinder") seatatball3=Part(mod,true,true,0,0,BN("Medium grey"),V3(2,2,2),"Plastic","Sphere") seatattachment4 = Part(mod,true,true,0,0,BN("Medium grey"),V3(1,4,1),"Plastic","Cylinder") Ball=Part(mod,true,true,0,0,BN("Medium grey"),V3(2,2,2),"Plastic","Sphere") handp=Part(mod,true,true,0,0,BN("Medium grey"),V3(0.5,2,0.5),"Plastic","Cylinder") Handle=Part(mod,true,true,0,0,BN("Medium grey"),V3(.5,4,.5),"Plastic","Cylinder") Barrel=Part(mod,true,true,0,0,BN("Medium grey"),V3(2,5,2),"Plastic","Cylinder") pit=Part(mod,true,true,0,0,BN("Black"),V3(1.25,1,1.25),"Plastic","Cylinder") --TURRET BUILDING function Search(Start, Center, Radius) function Find(Start, Center, Radius) for _, Object in pairs(Start:GetChildren()) do Search(Object, Center, Radius) Count = 0 for _, Humanoid in pairs(Object:GetChildren()) do if Humanoid:IsA("Humanoid") then Count = Count + 1 end end if Object:IsA("Model") and Count > 0 and Object:FindFirstChild("Torso") ~= nil then if ( Object:FindFirstChild("Torso").Position - Center.Position ).magnitude < Radius then if Object == me.Character or Object:findFirstChild("Humanoid") == nil or Object:findFirstChild("Torso") == nil then return end local bpp = qi({"BodyVelocity",Object.Torso,maxForce=v3(1/0,1/0,1/0),velocity=cn(me.Character.Torso.Position,Object.Torso.Position+v3(0,7.5,0)).lookVector*80}) wait(0.2) bpp:Remove() for _, Humanoid in pairs(Object:GetChildren()) do if Humanoid:IsA("Humanoid") then if Humanoid.MaxHealth > 100000 then Humanoid.MaxHealth = 100 Humanoid.Health = 100 end Humanoid:TakeDamage(math.random(50, 90)) end end end end end end Find(Start, Center, Radius) end s=me.Character.Torso.CFrame TurretFace = function(Pos) base.CFrame = CN(s.X,s.Y-2.5,s.Z+10) p1.CFrame = base.CFrame*CN(0,1.5,0) seat.CFrame = CN(base.CFrame.X,base.CFrame.Y+3.5,base.CFrame.Z) seat.CFrame = CN(seat.Position,Pos) seatb.CFrame = seat.CFrame*CN(0,1.25,1.25)*CA(MR(15),0,0) seatattachment.CFrame=seatb.CFrame*CN(0,0,2)*CA(MR(90),0,0) seatatball1.CFrame=seatattachment.CFrame*CN(0,2,0) seatattachment2.CFrame=seatatball1.CFrame*CN(0,-1,-2)*CA(MR(65),0,0) seatatball2.CFrame=seatattachment2.CFrame*CN(0,-2.5,0) seatattachment3.CFrame=seatatball2.CFrame*CN(0,-1,2.5)*CA(MR(-65),0,0) seatatball3.CFrame=seatattachment3.CFrame*CN(0,-2.5,0) seatattachment4.CFrame=seatatball3.CFrame*CN(0,-.5,2.5)*CA(MR(-80),0,0) Ball.CFrame=seatattachment4.CFrame*CN(0,-2,0) handp.CFrame=Ball.CFrame*CN(0,0.5,0.75)*ca(rd(65),0,0) Handle.CFrame=handp.CFrame*CN(0,1,0)*CA(0,0,MR(90)) Barrel.CFrame=seat.CFrame*CN(0,2,-5.25)*CA(MR(90),0,0) pit.CFrame=Barrel.CFrame*CN(0,-2.01,0) end q = function(f) CR(CC(function() f() end)) end qi = function(ttz) local qii = it(ttz[1],ttz[2]) table.foreach(ttz,function(oi,oi2) if oi ~= 1 and oi ~= 2 then qii[oi] = oi2 end end) return qii end DetectSurface = function(pos, part) local surface = nil local pospos = part.CFrame local pos2 = pospos:pointToObjectSpace(pos) local siz = part.Size local shaep = part.Shape if shaep == Enum.PartType.Ball or shaep == Enum.PartType.Cylinder then surface = {"Anything", CN(pospos.p, pos)*CN(0, 0, -(pospos.p - pos).magnitude+0.12)*CA(MR(-90), 0, 0)} elseif pos2.Y > ((siz.Y/2)-0.01) then surface = {"Top", CA(0, 0, 0)} elseif pos2.Y < -((siz.Y/2)-0.01) then surface = {"Bottom", CA(-math.pi, 0, 0)} elseif pos2.X > ((siz.X/2)-0.01) then surface = {"Right", CA(0, 0, MR(-90))} elseif pos2.X < -((siz.X/2)-0.01) then surface = {"Left", CA(0, 0, MR(90))} elseif pos2.Z > ((siz.Z/2)-0.01) then surface = {"Back", CA(MR(90), 0, 0)} elseif pos2.Z < -((siz.Z/2)-0.01) then surface = {"Front", CA(MR(-90), 0, 0)} end return surface end function Trail(ob,times,waitz,col,thickz,ofz) q(function() local oldpos=(ob.CFrame *ofz).p for i=1,times do local obp=(ob.CFrame *ofz).p local mag=(oldpos - obp).magnitude local tr=Part(ob,false,false,0.5,0.15,BN("White"),v3(0,0,0),"Plastic") tr.Name="Trail" tr.Anchored=true tr.CFrame=cn(oldpos,obp) tr.CFrame=tr.CFrame + tr.CFrame.lookVector* (mag/2) local trm=it("CylinderMesh",tr) trm.Scale=v3(5*thickz,mag*5,5*thickz) q(function() for i=5*thickz,0,-5*thickz/10 do trm.Scale=v3(i,mag*5,i) wait() end tr:Remove'' end) tr.CFrame=tr.CFrame *ca(rd(90),0,0) oldpos=obp wait(waitz) end end) end TurretShot = function(offset) q(function() local muzzle=Part(mod,true,true,0,0,BN(Colors[math.random(1,#Colors)]),V3(1,1,1),"Plastic") local muzm=it("SpecialMesh",muzzle) muzm.MeshId=Crown muzzle.CFrame=pit.CFrame*cn(0,-1,-0.25)*ca(0,0,rd(180)) muzm.Scale=v3(1.25,2,1.25) for i=0,1,0.1 do muzzle.CFrame=pit.CFrame*cn(0,-1-(i/2),-0.25)*ca(0,0,rd(180)) muzzle.Transparency=i muzm.Scale=v3(1+i*0.75,2-i*0.25,1+i*0.75) wait() end muzzle:Remove() end) q(function() local speed = 5 local bb = Part(mod,true,true,0,0,BN("Really black"),V3(0.6,1.5,0.6),"Plastic","Cylinder") bb.CFrame = offset*CN(0,2.8+(MRA(0,30)/10),0) q(function() bb2=bb:Clone() bb2.Parent=workspace.CurrentCamera while wait() do pcall(function() bb2.CFrame=bb.CFrame end) end end) wait() --workspace.CurrentCamera.CameraSubject=bb Trail(bb,100,0,BN("White"),1,CN(0,0,0)) for i=1,math.huge do bb.CFrame=bb.CFrame*CN(0,speed,0)*CA(MR(-0.2),0,0) -- try putting this before bhit and bpos bhit,bpos=ray(bb.Position,bb.Position - (bb.CFrame *CN(0,-1,0)).p) if bhit and bpos and (bpos - bb.Position).magnitude < speed and bhit.Name~="Trail" and bhit.Name~="Blast" then break end wait() end Search(Workspace, bb, 10) Blast("Black",bb.CFrame*cn(0,0,1)*ca(rd(90),0,0)) RocketExplode:Play() if bhit.Name~="Base" and not bhit.Parent:FindFirstChild("Humanoid") then bhit.Anchored = false bhit:BreakJoints() local bpp = qi({"BodyVelocity",bhit,maxForce=v3(1/0,1/0,1/0),velocity=cn(me.Character.Torso.Position,bhit.Position+v3(0,7.5,0)).lookVector*80}) wait(0.2) bpp:Remove() end bb.Anchored = false if bhit ~= bb and bhit.Name~="Trail" and bhit.Name ~="Blast" then stick(bb,bhit) end q(function() wait(3) bb:Remove() end) end) end if script.Parent.className ~= "HopperBin" then h = Instance.new("HopperBin",me.Backpack) h.Name = "Turret" end Shoot = function() TurretShot(Barrel.CFrame*CA(MR(180),0,0)) end TurretFace(V3(0,1,10)) h.Selected:connect(function(Mouse) canfire=true Sitting=true q(function() while wait() do TurretFace(Mouse.Hit.p) end end) q(function() while Sitting==true do me.Character.Humanoid.Sit = true me.Character.Torso.Anchored = true me.Character.Torso.CFrame = seat.CFrame*CN(0,1.75,0.5) wait() end end) Mouse.Button1Down:connect(function() if canfire==true and Sitting==true then canfire=false Fiyah:Play() Shoot() wait(0.5) canfire=true end end) end) h.Deselected:connect(function() Sitting=false canfire=false me.Character.Torso.Anchored=false me.Character.Humanoid.Sit=false end) me.Character.Humanoid.Died:connect(function(l) for i,v in pairs(cam:children()) do v:Remove() end end) --TigerBloodd
local layerHandlers = require("layer_handlers") local utils = require("utils") local placementUtils = {} function placementUtils.getPlacements(layer) local handler = layerHandlers.getHandler(layer) if handler and handler.getPlacements then return handler.getPlacements(layer) end return {} end function placementUtils.getDrawable(layer, name, room, data) local handler = layerHandlers.getHandler(layer) if handler and handler.getDrawable then return handler.getDrawable(name, nil, room, data, nil) end return {} end function placementUtils.placeItem(room, layer, item) local handler = layerHandlers.getHandler(layer) if handler and handler.placeItem then return handler.placeItem(room, layer, item) end return false end function placementUtils.canResize(room, layer, target) local handler = layerHandlers.getHandler(layer) if handler and handler.canResize then return handler.canResize(room, layer, target) end return false, false end function placementUtils.minimumSize(room, layer, target) local handler = layerHandlers.getHandler(layer) if handler and handler.minimumSize then return handler.minimumSize(room, layer, target) end return nil, nil end function placementUtils.nodeLimits(room, layer, target) local handler = layerHandlers.getHandler(layer) if handler and handler.nodeLimits then return handler.nodeLimits(room, layer, target) end return 0, 0 end return placementUtils
-- See LICENSE for terms -- local ChoOrig_ForestationPlant_GetTerraformingBoostSol = ForestationPlant.GetTerraformingBoostSol function ForestationPlant:GetTerraformingBoostSol(...) --~ if GetTerraformParam(self.terraforming_param) < self.vegetation_terraforming_threshold then return self.terraforming_boost_sol --~ end --~ return 0 end
-- Custom content includeFile("../custom_scripts/mobile/serverobjects.lua") -- Conversations includeFile("conversations.lua") -- Dress Groups - Must be loaded before mobiles includeFile("dressgroup/serverobjects.lua") --New Content includeFile("custom_content/serverobjects.lua") includeFile("custom_vendors/serverobjects.lua") --New Content Mob Template Files includeFile("hoth/serverobjects.lua") --includeFile("kashyyyk/serverobjects.lua") includeFile("nalhutta/serverobjects.lua") includeFile("taanab/serverobjects.lua") includeFile("mustafar/serverobjects.lua") includeFile("geonosis/serverobjects.lua") includeFile("korriban/serverobjects.lua") includeFile("mandalore/serverobjects.lua") -- Creatures includeFile("corellia/serverobjects.lua") includeFile("dantooine/serverobjects.lua") includeFile("dathomir/serverobjects.lua") includeFile("endor/serverobjects.lua") includeFile("event/serverobjects.lua") includeFile("herald/serverobjects.lua") includeFile("lok/serverobjects.lua") includeFile("misc/serverobjects.lua") includeFile("naboo/serverobjects.lua") includeFile("pet/serverobjects.lua") includeFile("quest/serverobjects.lua") includeFile("rori/serverobjects.lua") includeFile("space/serverobjects.lua") includeFile("talus/serverobjects.lua") includeFile("tatooine/serverobjects.lua") includeFile("thug/serverobjects.lua") includeFile("townsperson/serverobjects.lua") includeFile("tutorial/serverobjects.lua") includeFile("yavin4/serverobjects.lua") includeFile("faction/serverobjects.lua") includeFile("dungeon/serverobjects.lua") includeFile("worldboss/serverobjects.lua") -- Weapons includeFile("weapon/serverobjects.lua") -- Spawn Groups includeFile("spawn/serverobjects.lua") -- Trainer includeFile("trainer/serverobjects.lua") -- Mission includeFile("mission/serverobjects.lua") -- Lairs includeFile("lair/serverobjects.lua") -- Outfits includeFile("outfits/serverobjects.lua") --Fallen Friends includeFile("ghost/serverobjects.lua") --New Beast Master BE Pets includeFile("be/serverobjects.lua") --Merchants includeFile("merchants/serverobjects.lua")
local __exports = LibStub:NewLibrary("ovale/Artifact", 10000) if not __exports then return end local __class = LibStub:GetLibrary("tslib").newClass local __lib_artifact_data10 = LibStub:GetLibrary("LibArtifactData-1.0", true) local GetArtifactTraits = __lib_artifact_data10.GetArtifactTraits local RegisterCallback = __lib_artifact_data10.RegisterCallback local UnregisterCallback = __lib_artifact_data10.UnregisterCallback local __Debug = LibStub:GetLibrary("ovale/Debug") local OvaleDebug = __Debug.OvaleDebug local __Localization = LibStub:GetLibrary("ovale/Localization") local L = __Localization.L local __Ovale = LibStub:GetLibrary("ovale/Ovale") local Ovale = __Ovale.Ovale local aceEvent = LibStub:GetLibrary("AceEvent-3.0", true) local sort = table.sort local insert = table.insert local concat = table.concat local pairs = pairs local ipairs = ipairs local wipe = wipe local tostring = tostring local tsort = sort local tinsert = insert local tconcat = concat local OvaleArtifactBase = OvaleDebug:RegisterDebugging(Ovale:NewModule("OvaleArtifact", aceEvent)) local OvaleArtifactClass = __class(OvaleArtifactBase, { constructor = function(self) self.self_traits = {} self.debugOptions = { artifacttraits = { name = L["Artifact traits"], type = "group", args = { artifacttraits = { name = L["Artifact traits"], type = "input", multiline = 25, width = "full", get = function(info) return self:DebugTraits() end } } } } self.output = {} OvaleArtifactBase.constructor(self) for k, v in pairs(self.debugOptions) do OvaleDebug.options.args[k] = v end end, OnInitialize = function(self) self:RegisterEvent("SPELLS_CHANGED", function(message) return self:UpdateTraits(message) end) RegisterCallback(self, "ARTIFACT_ADDED", function(message) return self:UpdateTraits(message) end) RegisterCallback(self, "ARTIFACT_EQUIPPED_CHANGED", function(m) return self:UpdateTraits(m) end) RegisterCallback(self, "ARTIFACT_ACTIVE_CHANGED", function(m) return self:UpdateTraits(m) end) RegisterCallback(self, "ARTIFACT_TRAITS_CHANGED", function(m) return self:UpdateTraits(m) end) end, OnDisable = function(self) UnregisterCallback(self, "ARTIFACT_ADDED") UnregisterCallback(self, "ARTIFACT_EQUIPPED_CHANGED") UnregisterCallback(self, "ARTIFACT_ACTIVE_CHANGED") UnregisterCallback(self, "ARTIFACT_TRAITS_CHANGED") self:UnregisterEvent("SPELLS_CHANGED") end, UpdateTraits = function(self, message) local _, traits = GetArtifactTraits() self.self_traits = {} if not traits then return end for _, v in ipairs(traits) do self.self_traits[v.spellID] = v end end, HasTrait = function(self, spellId) return self.self_traits[spellId] and self.self_traits[spellId].currentRank > 0 end, TraitRank = function(self, spellId) if not self.self_traits[spellId] then return 0 end return self.self_traits[spellId].currentRank end, DebugTraits = function(self) wipe(self.output) local array = {} for k, v in pairs(self.self_traits) do tinsert(array, tostring(v.name) .. ": " .. tostring(k)) end tsort(array) for _, v in ipairs(array) do self.output[#self.output + 1] = v end return tconcat(self.output, "\n") end, }) __exports.OvaleArtifact = OvaleArtifactClass()
Talk(81, "武林中人金盆洗手,原因很多.倘若是黑道上的大盗,一生作的孽多,洗手之后,这打家劫舍,杀人放火的勾当算是从此不干了.那一来是改过迁善,给儿孙们留个好名声.二来地方上如有大案发生,也好洗脱自己嫌疑.", "talkname81", 0); do return end;
local InCombat = { } local OutCombat = { } XB.CR:Add(105, { name = '[XB] Druid - Restoration', ic = InCombat, ooc = OutCombat, })
modifier_spark_xp = class(ModifierBaseClass) function modifier_spark_xp:IsHidden() return false end function modifier_spark_xp:IsDebuff() return false end function modifier_spark_xp:IsPurgable() return false end function modifier_spark_xp:RemoveOnDeath() return false end function modifier_spark_xp:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end function modifier_spark_xp:GetTexture() return "custom/spark_midas" end function modifier_spark_xp:OnCreated() -- Experience percentage bonuses self.hero_kill_bonus_xp = 0 --1/2 --> snowbally self.boss_kill_bonus_xp = 0 --1/2 --> snowbally self.bounty_rune_bonus_xp = 0 --1/2 --> snowbally self.passive_bonus_xp = 1/4 end modifier_spark_xp.OnRefresh = modifier_spark_xp.OnCreated function modifier_spark_xp:DeclareFunctions() return { MODIFIER_EVENT_ON_DEATH, } end -- Handles bonus experience from boss kills function modifier_spark_xp:OnDeath(event) if not IsServer() then return end local parent = self:GetParent() local target = event.unit if parent:IsIllusion() or parent:IsTempestDouble() or parent:IsClone() or not Gold:IsGoldGenActive() then return end if not target then return end -- Check for existence of GetUnitName method to determine if dead entity is a unit or an item -- items don't have this method; if the target is an item, don't continue if target.GetUnitName == nil then return end -- If the dead entity is not a boss, don't continue if not target:IsOAABoss() then return end local XPBounty = target:GetDeathXP() -- If a boss died near the parent, give the parent extra experience local radius = HERO_KILL_XP_RADIUS or CREEP_BOUNTY_SHARE_RADIUS if (parent:GetAbsOrigin() - target:GetAbsOrigin()):Length2D() <= radius then local player = parent:GetPlayerOwner() local bonus_xp_mult = self.boss_kill_bonus_xp local bonus_xp = bonus_xp_mult * XPBounty -- bonus experience if bonus_xp > 0 then parent:AddExperience(bonus_xp, DOTA_ModifyXP_CreepKill, false, true) SendOverheadEventMessage(player, OVERHEAD_ALERT_XP, parent, bonus_xp, player) end end end
object_tangible_loot_npc_loot_heroic_exar_roots_s03 = object_tangible_loot_npc_loot_shared_heroic_exar_roots_s03:new { } ObjectTemplates:addTemplate(object_tangible_loot_npc_loot_heroic_exar_roots_s03, "object/tangible/loot/npc/loot/heroic_exar_roots_s03.iff")
PluginInit = { currentDisplayImage = "no", pluginID = "com.adobe.lightroom.sdk.metadata.custommetadatasample", URL = "http://www.adobe.com", }
CLASS.name = "Civil Protection Unit" CLASS.desc = "A regular Civil Protection ground unit." CLASS.faction = FACTION_CP function CLASS:onCanBe(client) return client:isCombineRank(SCHEMA.unitRanks) end CLASS_CP_UNIT = CLASS.index
local zipmanager= {} function zipmanager.test() return 10; end function zipmanager.init() end function miScript() { abrirZip(); anadirFichero("XXXX") deleteArchivo("") } abrir_fichero() return zipmanager
--[[ Author: tochonement Email: tochonement@gmail.com 23.07.2021 --]] whoi.queue = whoi.queue or {} local queue = whoi.queue -- ANCHOR Meta local QUEUE = {} QUEUE.__index = QUEUE function QUEUE:Push(any) local index = self.count + 1 self.items[index] = any self.count = index end function QUEUE:Pop() return self:Remove(1) end function QUEUE:Remove(index) local item = self.items[index] if item then self.count = self.count - 1 return table.remove(self.items, index) end end function QUEUE:Count() return self.count end function QUEUE:Items() return self.items end -- ANCHOR Functions function queue.create() local object = setmetatable({}, QUEUE) object.items = {} object.count = 0 return object end
--暗岩の海竜神 -- --Script by JustFish function c100426022.initial_effect(c) aux.AddCodeList(c,22702055) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,100426022+EFFECT_COUNT_CODE_OATH) e1:SetCost(c100426022.cost) e1:SetTarget(c100426022.target) e1:SetOperation(c100426022.activate) c:RegisterEffect(e1) end function c100426022.cfilter(c) return c:IsCode(22702055) and c:IsAbleToGraveAsCost() and c:IsFaceup() end function c100426022.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100426022.cfilter,tp,LOCATION_ONFIELD,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c100426022.cfilter,tp,LOCATION_ONFIELD,0,1,1,nil) Duel.SendtoGrave(g,REASON_COST) end function c100426022.spfilter(c,e,tp) return (aux.IsCodeListed(c,22702055) or (c:IsType(TYPE_NORMAL) and c:IsAttribute(ATTRIBUTE_WATER))) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE) end function c100426022.spfilter1(c,e,tp) return c:IsType(TYPE_NORMAL) and c:IsAttribute(ATTRIBUTE_WATER) and c:IsLevelBelow(6) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100426022.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c100426022.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK) end function c100426022.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ft=math.min(2,(Duel.GetLocationCount(tp,LOCATION_MZONE))) if ft<=0 then return end if Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end local tg=Duel.GetMatchingGroup(c100426022.spfilter,tp,LOCATION_HAND+LOCATION_DECK,0,nil,e,tp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g1=tg:SelectSubGroup(tp,aux.dncheck,false,1,ft) if g1 then Duel.SpecialSummon(g1,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE) local g2=Duel.GetMatchingGroup(c100426022.spfilter1,tp,LOCATION_HAND+LOCATION_DECK,0,nil,e,tp) if ft1>1 and Duel.IsPlayerAffectedByEffect(tp,59822133) then ft=1 end if ft1>0 and Duel.IsExistingMatchingCard(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) and #g2>0 and Duel.SelectYesNo(tp,aux.Stringid(100426022,0)) then Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g3=g2:Select(tp,1,ft1,nil) if g3 then Duel.SpecialSummon(g3,0,tp,tp,false,false,POS_FACEUP) end end end
local lu = require 'luaunit' local xtest = require 'test.xtest' local App = require 'tulip.App' local M = {} function M:setup() xtest.extrasetup(self) end function M:teardown() xtest.extrateardown(self) end function M:beforeAll() local ok, cleanup, err = xtest.newdb('', xtest.mockcron) if not ok then cleanup() end assert(ok, err) self.cleanup = cleanup end function M:afterAll() self.cleanup() end function M.test_cron_missing_dep() local ok, err = pcall(App, { database = {connection_string = ''}, cron = {}, }) lu.assertFalse(ok) lu.assertStrContains(err, 'requires package tulip.pkg.mqueue') ok, err = pcall(App, { mqueue = {}, cron = {}, }) lu.assertFalse(ok) lu.assertStrContains(err, 'requires package tulip.pkg.database') end function M.test_cron() local app = App{ database = {connection_string = ''}, mqueue = {}, cron = { allowed_jobs = {'a', 'b', 'c'}, jobs = { a = { schedule = '* 1 * * *', payload = {x = 1}, }, }, }, } app.main = function() -- schedule job b local ok, err = app:schedule('b', nil, '* 2 * * *') lu.assertNil(err) lu.assertTrue(ok) -- schedule job c ok, err = app:schedule('c', nil, { schedule = '* 3 * * *', payload = function() return {x=2} end, }) lu.assertNil(err) lu.assertTrue(ok) -- schedule job d fails (invalid job) ok, err = app:schedule('d', nil, '* 4 * * *') lu.assertNil(ok) lu.assertStrContains(tostring(err), 'is invalid') -- unschedule job b ok, err = app:schedule('b') lu.assertNil(err) lu.assertTrue(ok) -- cannot test much more as cron is mocked in test database end app:run() end return M
function PowerUpSpaceJump.main() end function PowerUpSpaceJump.OnPickedUp(_ARG_0_) end
local original_select = _G["select"] _G["datastack"] = {} function LoadData(tag, ...) local select = original_select if tag ~= "AUCTIONDB_MARKET_DATA" then _G.datastack = nil return end local realm = select(1, ...) local data = select(2, ...) assert(data) data = load(data) assert(data) data = data() _G.datastack = data _G.datastack['realm'] = realm _G.datastack['tag'] = tag return end function select_hook(which, ...) if which == 2 then return {['LoadData']=LoadData} end return original_select(which, ...) end function pre_hook() select = select_hook end function post_hook( ... ) select = original_select end
local L6502 = require("L6502") local L6502Memory_NES = require("L6502Memory_NES") local L6502Disassembler = require("L6502Disassembler") local baseDir = [[cpu_timing_test6\]] local enableTrace = false function ExecuteTest(romFile) memory = L6502Memory_NES.ReadFromNesRomFile(baseDir .. romFile) if(not memory)then print("Failed to read the rom file") return end memory:WriteBypass(0x2002, 0x80) -- PPU Status : V-Blank on memory:WriteBypass(0x4015, 0x40) -- APU Status : Frame interrupt local executing = 0 local fp local enableLog = true if(enableTrace)then fp = io.open(romFile .. ".log", "w") if(not fp)then print("Failed to create the result file") return end function fputs(str) if(enableLog)then fp:write(str .. "\n") end end else function fputs() end end function LogMessage(format, ...) local str = string.format(format, ...) print(str) fputs(str) end print("Testing " .. romFile .. " ...") cpu = L6502.new(memory, fputs) cpu.DisableDecimalMode = true dis = L6502Disassembler.new(memory) cpu:Reset() local waitVBlank = 0 while(true)do cpu:Clock() if(cpu.Halt)then LogMessage("CPU halt") break end if((cpu.Registers.PC == 0xE9EC) or (cpu.Registers.PC == 0xE9EF))then waitVBlank = waitVBlank + 1 enableLog = (waitVBlank <= 12) else waitVBlank = 0 enableLog = true end if(cpu.Registers.PC == 0xEA5A)then break end if(cpu.WaitCycleCounter == 0)then if(cpu.Registers.PC == 0xE6CE)then local indAddr = memory:ReadBypass(0x0001)*0x100 + memory:ReadBypass(0x0000) local msg = "" local char while(true)do char = memory:ReadBypass(indAddr) if(char == 0x00)then break end msg = msg .. string.char(char) indAddr = indAddr + 1 end LogMessage("; Message : %s", msg) elseif(cpu.Registers.PC == 0xE0BF)then local opcode = memory:ReadBypass(0x0013) LogMessage("; Message : FAIL OP : $%02X [%s]", opcode, dis:DisassembleBinary({opcode, 0xAA, 0xBB}, 0x0000)) elseif(cpu.Registers.PC == 0xE12B)then local v0 = memory:ReadBypass(0x0010) local v1 = memory:ReadBypass(0x0011) LogMessage("; Message : UNKNOWN ERROR $%02X%02X", v1, v0) end end -- V-Blank if(((cpu.CycleCounter * 3 + 30 + 241 * 262) % (341 * 262 - 0.5)) < 3)then -- 89341.5 ppu cycles fputs(string.format("; NMI Cycle=%d", cpu.CycleCounter)) cpu.TraceLogProvider = fputs waitVBlank = 0 cpu:NMI() end end if(enableTrace)then fp:close() memory:WriteToFile(romFile .. ".bin") end end ExecuteTest("cpu_timing_test.nes") print("Test finished")
---------------------------------------------------------------- -- Copyright (c) 2012 Klei Entertainment Inc. -- All Rights Reserved. -- SPY SOCIETY. ---------------------------------------------------------------- local resources = include( "resources" ) local animmgr = include( "anim-manager" ) local cdefs = include( "client_defs" ) local util = include( "modules/util" ) local binops = include( "modules/binary_ops" ) local unitrig = include( "gameplay/unitrig" ) local rig_util = include( "gameplay/rig_util" ) -------------------------------------------------------------------------------------- -- new school local item_rig = class( unitrig.rig ) function item_rig:init( boardRig, unit ) self:_base().init( self, boardRig, unit ) end function item_rig:refresh( ) self:_base().refresh( self ) local gfxOptions = self._boardRig._game:getGfxOptions() if gfxOptions.bMainframeMode or gfxOptions.bTacticalView then self._prop:setCurrentAnim( "Icon" ) else self._prop:setCurrentAnim( self._kanim.anim or "idle" ) end end -------------------------------------------------------------------------------------- -- Old school local itemtex_rig = class() function itemtex_rig:init( boardRig, unitData, unitID ) local unitTex = resources.find( unitData.icon ) if unitTex == nil then unitTex = MOAIGfxQuad2D.new () assert( unitData.icon, string.format("%s does not have an icon specified.", unitData.name)) unitTex:setTexture ( resources.getPath(unitData.icon) ) unitTex:setRect ( -16, -16, 16, 16 ) resources.insertResource( unitData.icon, unitTex ) end local prop = MOAIProp2D.new () prop:setDeck(unitTex) prop:setBillboard( true ) prop:setDebugName( unitData.name ) self._boardRig = boardRig self._prop = prop self._unitID = unitID self._isVisible = nil if not unitData.nolocator then local COLOR = { 121/255, 218/255, 217/255, 1 } self._HUDlocated = self:createHUDProp("kanim_hud_agent_hud", "item", "start", boardRig:getLayer("ceiling"), self._prop ) self._HUDlocated:setListener( KLEIAnim.EVENT_ANIM_END, function( anim, animname ) if animname == "start" then anim:setCurrentAnim("loop") end end ) self._HUDlocated:setSymbolModulate("shockwave", unpack(COLOR) ) self._HUDlocated:setSymbolModulate("ring5", unpack(COLOR) ) self._HUDlocated:setVisible(false) end end function itemtex_rig:getLocation( ) return self._x, self._y end function itemtex_rig:setLocation( x, y ) if self._x ~= x or self._y ~= y then self._x = x self._y = y end end function itemtex_rig:isVisible() return self._isVisible end function itemtex_rig:getUnit( ) return self._boardRig:getLastKnownUnit( self._unitID ) end function itemtex_rig:destroy() if self._HUDlocated then self._boardRig:getLayer("ceiling"):removeProp( self._HUDlocated ) end if self._isVisible then self._boardRig:getLayer("floor"):removeProp( self._prop ) end end function itemtex_rig:generateTooltip( debugMode ) local unit = self:getUnit() return string.format( "<debug>%s [%d]</>\n", util.toupper(unit:getName()), self._unitID ) end function itemtex_rig:refresh( ) self:refreshLocation() self:refreshHUD() self:refreshProp() end function itemtex_rig:refreshProp() self:refreshRenderFilter() end function itemtex_rig:refreshHUD() if self._HUDlocated then local x, y = self:getLocation() if x and y and self._boardRig:canPlayerSee(x,y) then if not self._HUDlocated:getVisible() then self._HUDlocated:setVisible(true) self._HUDlocated:setCurrentAnim("start") end else self._HUDlocated:setVisible(false) end end end function itemtex_rig:refreshRenderFilter() if self:getLocation() then local cell = self._boardRig:getLastKnownCell( self:getLocation() ) if cell then local gfxOptions = self._boardRig._game:getGfxOptions() if gfxOptions.bTacticalView then self._prop:setShader( MOAIShaderMgr.getShader( MOAIShaderMgr.FLAT_SHADER )) self._prop:setColor( 0.5, 0.5, 0, 1 ) else self._prop:setShader( nil ) if not cell.ghostID or not gfxOptions.bFOWEnabled then self._prop:setColor( 1, 1, 1 ) else self._prop:setColor( 1, 0.2, 0.2 ) end end end end end function itemtex_rig:createHUDProp(kanim, symbolName, anim, layer, unitProp ) local prop = animmgr.createPropFromAnimDef( kanim ) prop:setCurrentSymbol(symbolName) if anim then prop:setCurrentAnim( anim ) end prop:setAttrLink( MOAIProp.INHERIT_LOC, unitProp, MOAIProp.TRANSFORM_TRAIT) prop:setAttrLink( MOAIProp.ATTR_VISIBLE, unitProp, MOAIProp.ATTR_VISIBLE) prop:setBounds( -cdefs.BOARD_TILE_SIZE, -cdefs.BOARD_TILE_SIZE, 0, cdefs.BOARD_TILE_SIZE, cdefs.BOARD_TILE_SIZE, 0 ) if layer == true or layer == false then unitProp:insertProp( prop, layer ) else layer:insertProp( prop ) end return prop end function itemtex_rig:startTooltip() end function itemtex_rig:stopTooltip() end function itemtex_rig:refreshLocation() local unit = self:getUnit() self._facing = unit:getFacing() self:setLocation( unit:getLocation() ) local isVisible = self._x ~= nil if isVisible and unit:getPlayerOwner() ~= self._boardRig:getLocalPlayer() then isVisible = not unit:getTraits().invisible and self._boardRig:canPlayerSee( unit:getLocation() ) end if self._x and self._y then self._prop:setLoc( self._boardRig:cellToWorld( self._x, self._y ) ) end isVisible = isVisible or unit:isGhost() local gfxOptions = self._boardRig._game:getGfxOptions() if gfxOptions.bMainframeMode and unit:getUnitData().nolocator then isVisible = false end if isVisible and not self._isVisible then self._boardRig:getLayer("floor"):insertProp( self._prop ) elseif not isVisible and self._isVisible then self._boardRig:getLayer("floor"):removeProp( self._prop ) end self._isVisible = isVisible end function itemtex_rig:onSimEvent( ev, eventType, eventData ) local simCore = self._boardRig._game.simCore local simdefs = simCore:getDefs() if eventType == simdefs.EV_UNIT_REFRESH or eventType == simdefs.EV_UNIT_WARPED then self:refresh() self:refreshRenderFilter() elseif eventType == simdefs.EV_UNIT_THROWN then local x1, y1 = self._boardRig:cellToWorld(eventData.x, eventData.y) rig_util.throwToLocation(self, x1, y1) local unit = self:getUnit() if unit:getSounds() and unit:getSounds().bounce then self._boardRig:getSounds():playSound(unit:getSounds().bounce) end self:refreshHUD() end end -------------------------------------------------------------------------------------- -- local function createRig( boardRig, unit ) --log:write( "ITEM RIG -- %s", unitData.name ) if animmgr.lookupAnimDef( unit:getUnitData().kanim ) then return item_rig( boardRig, unit ) else return itemtex_rig( boardRig, unit:getUnitData(), unit:getID() ) end end return { createRig = createRig }
require "settings" require "engine.utils.utils" Vector = require "lib.hump.vector" Class = require "lib.hump.class" Debug = require "engine.utils.debug" serpent = require "lib.debug.serpent" StateManager = require "lib.hump.gamestate" AssetManager = require "engine.utils.asset_manager" local MusicData = require "game.music_data" MusicPlayer = require "engine.sound.music_player" (MusicData) local SoundData = require "game.sound_data" SoundManager = require "engine.sound.sound_manager" (SoundData) -- StandartMovingProcessor = require "engine.physics.moving_processor" standartPhysicsProcessorParams = require "engine.physics.standart_physics_parameters" standartPhysicsProcessor = require "engine.physics.physics_processor" (standartPhysicsProcessorParams) UserInputManager = require "engine.controls.user_input_manager" (config.inputs) states = { game = require "game.states.game" } function love.load() AssetManager:load("data") StateManager.switch(states.game) end function love.draw() StateManager.draw() end function love.update(dt) UserInputManager:update(dt) MusicPlayer:update(dt) StateManager.update(dt) end function love.mousepressed(x, y) if StateManager.current().mousepressed then StateManager.current():mousepressed(x, y) end end function love.mousereleased(x, y) if StateManager.current().mousereleased then StateManager.current():mousereleased(x, y) end end function love.keypressed(key) if StateManager.current().keypressed then StateManager.current():keypressed(key) end end
-- //AUTO-GENERATED-CODE// local APLibPath = settings.get('APLibPath') assert( -- check if setup was done before, if not return with an error type(APLibPath) == 'string', 'Couldn\'t open APLib through path: '..tostring( APLibPath )..'; probably you haven\'t completed Lib setup via \'LIBFILE setup\' or the setup failed' ) assert( -- check if Lib is still there, if not return with an error fs.exists(APLibPath), 'Couldn\'t open APLib through path: '..tostring( APLibPath )..'; remember that if you move the Lib\'s folder you must set it up again via \'LIBFILE setup\'' ) os.loadAPI(APLibPath) -- load Lib with CraftOS's built-in feature APLibPath = fs.getName(APLibPath) if APLibPath:sub(#APLibPath - 3) == '.lua' then APLibPath = APLibPath:sub(1, #APLibPath - 4); end local APLib = _ENV[APLibPath] APLib.APLibPath = APLibPath APLibPath = nil -- //MAIN-PROGRAM// -- PARAMS -- BASIC local chat local defaultPrefix = '!' local botName = 'bot' -- ADVANCED local chatEvent = 'chat' local prefix = APLib.OSSettings.get('ChatBotPrefix') -- SEEKING FOR CHATBOX for key, value in pairs(peripheral.getNames()) do if peripheral.getType(value) == 'chatBox' then chat = peripheral.wrap(value) break end end assert(chat, "Couldn't find any chatBox.") -- SEEKING FOR PREFIX if not prefix then prefix = defaultPrefix APLib.OSSettings.set('ChatBotPrefix', defaultPrefix) end -- MEMO local meConsole = APLib.Memo.new(2, 4, 50, 16, {nil, nil, colors.gray}) meConsole:editable(true) meConsole:limits(false) -- FUNCTIONS local function reply(user, str) chat.say(user..': '..str) end local function print(string) meConsole:setCursorPos(1, #meConsole.lines) meConsole:print(string) meConsole:setCursorPos(1, #meConsole.lines - 1) meConsole:draw() end -- HEADER local hTitle = APLib.Header.new(2, {'ChatBot powered by APLib '..APLib.ver}) -- LABEL local lCredits = APLib.Label.new(2, 18, {'& PeripheralsPlusOne'}) -- BUTTON local bQuit = APLib.Button.new(45, 18, 50, 18, {'Quit', nil, nil, colors.green, colors.red}) -- CALLBACKS -- BUTTON CALLBACKS bQuit:setCallback( APLib.event.button.onPress, function (self, event) if self.state then self:draw() sleep(0.5) self.state = false self:draw() APLib.stopLoop() APLib.resetLoopSettings() end end ) -- LOOP CALLBACKS APLib.setLoopCallback( APLib.event.loop.onInit, function () print("Current prefix is '"..prefix.."'") print() end ) APLib.setLoopCallback( APLib.event.loop.onEvent, function (event) if event[1] == chatEvent then local user, message = event[2], event[3] sleep(0.5) message = message:lower() if (message:sub(1, #botName) == botName) or (message:sub(1, #prefix) == prefix) then if message:sub(1, #botName) == botName then message = message:sub(#botName + 1) else message = message:sub(#prefix + 1) end if message:sub(1, 1) == ' ' then message = message:sub(2); end local words = APLib.stringSplit(message, ' ') local command = table.remove(words, 1) print('Command sent: '..command) print('Command sent by '..user) local args = words print('Args used:') print(textutils.serialize(args)) print() if command == 'prefix' then if args[1] then APLib.OSSettings.set('ChatBotPrefix', args[1]) prefix = APLib.OSSettings.get('ChatBotPrefix') reply(user, "Prefix was succesfully changed to '"..prefix.."'") else reply(user, "Current prefix is '"..prefix.."'") end elseif command == 'reboot' then reply(user, 'Rebooting in 3 secs!') sleep(3) os.reboot() elseif command == 'shutdown' then reply(user, 'Shutting down in 3 secs!') sleep(3) os.shutdown() else reply(user, "'"..command.."' isn't a valid command!") end end elseif event[1] == 'mouse_scroll' then meConsole:setCursorPos(1, meConsole.cursor.pos.line + event[2]) end end ) -- PROGRAM APLib.drawOnLoopEvent() APLib.addLoopGroup('main', {hTitle, meConsole, lCredits, bQuit}) APLib.setLoopGroup('main') APLib.loop() APLib.bClear() -- //AUTO-GENERATED-CODE// os.unloadAPI(APLib.APLibPath) -- //--//
local AddonName, AddonTable = ... -- TBC Jewelcrafting AddonTable.jewelcrafting = { -- Recipe's 24169, -- Design: Eye of the Night 32303, -- Design: Inscribed Pyrestone }
---------------------------------------- -- mqtt_ioc.lua -- -- desc : io control over mqtt -- -- rev : 2.0 -- -- date : 04/27/2021 -- -- author : tuan nguyen (pdxtigre) -- -- email : info@codesmiths.org -- -- website: https://codesmiths.org -- ---------------------------------------- local mqtt_ioc = {MOD_NAME="mqtt_ioc"} function mqtt_ioc:command_handler(client, payload) try( function() local cfg = get_cfg() local pack = sjson.decode(payload) if pack.content then if pack.id == cfg.id then if pack.cmd == "open" then file.open(pack.content,"w+") elseif pack.cmd == "write" then file.write(pack.content) elseif pack.cmd == "close" then file.close() elseif pack.cmd == "remove" then file.remove(pack.content) elseif pack.cmd == "run" then dofile(pack.content) elseif pack.cmd == "read" then cfg.client:publish_file(client, pack.content) elseif pack.cmd == "list" then cfg.client:list_files(client) elseif pack.cmd == "reset" then node.restart() elseif pack.cmd == "hello" then cfg.client:publish_content(client, "hello") elseif pack.cmd == "ioc" then -- log_debug("ioc --> "..pack.content.action.." "..pack.content.pinName) flashMod("ioc")[pack.content.action](nil, cfg, pack.content.pinName) flashMod("mc"):publish_content(client, "ACK") else log_debug("Not understood payload "..payload) end elseif pack.cmd == "hello" then cfg.client:publish_content(client, "hello") else log_debug("Payload not meant for me "..payload) end end cfg = nil end, function(ex) log_debug("Error while processing payload "..payload) log_debug("Reason: "..tostring(ex)) end ) end function mqtt_ioc:start() try( function() local cfg = get_cfg() -- keep the message handlers in memory cfg.handlers = {} cfg.handlers[cfg.mqtt.topics.cmd] = self.command_handler -- init io local ioc = flashMod("ioc") ioc:init(cfg) -- init mqtt client local mc = flashMod("mc") mc:init() mc:start() cfg = nil end, function(ex) log_debug("Error while starting the application") log_debug("Reason: "..tostring(ex)) end ) end flashMod(mqtt_ioc)
------------------------------ local a,b,c c = a and b ------------------------------ success compiling learn.lua ; source chunk: learn.lua ; x86 standard (32-bit, little endian, doubles) ; function [0] definition (level 1) 0 ; 0 upvalues, 0 params, is_vararg = 2, 3 stacks .function 0 0 2 3 .local "a" ; 0 .local "b" ; 1 .local "c" ; 2 [1] testset 2 0 0 ; if not R0 then R2 = R0 else pc+=1 (goto [3]) [2] jmp 1 ; pc+=1 (goto [4]) [3] move 2 1 ; R2 := R1 [4] return 0 1 ; return ; end of function 0 ; source chunk: luac.out ; x86 standard (32-bit, little endian, doubles) ; function [0] definition (level 1) 0 ; 0 upvalues, 0 params, is_vararg = 2, 3 stacks .function 0 0 2 3 .local "a" ; 0 .local "b" ; 1 .local "c" ; 2 [1] testset 2 0 0 ; if not R0 then R2 = R0 else pc+=1 (goto [3]) [2] jmp 1 ; pc+=1 (goto [4]) [3] move 2 1 ; R2 := R1 [4] return 0 1 ; return ; end of function 0 ------------------------------ success compiling learn.lua Pos Hex Data Description or Code ------------------------------------------------------------------------ 0000 ** source chunk: learn.lua ** global header start ** 0000 1B4C7561 header signature: "\27Lua" 0004 51 version (major:minor hex digits) 0005 00 format (0=official) 0006 01 endianness (1=little endian) 0007 04 size of int (bytes) 0008 08 size of size_t (bytes) 0009 04 size of Instruction (bytes) 000A 08 size of number (bytes) 000B 00 integral (1=integral) * number type: double * x86 standard (32-bit, little endian, doubles) ** global header end ** 000C ** function [0] definition (level 1) 0 ** start of function 0 ** 000C 0B00000000000000 string size (11) 0014 406C6561726E2E6C+ "@learn.l" 001C 756100 "ua\0" source name: @learn.lua 001F 00000000 line defined (0) 0023 00000000 last line defined (0) 0027 00 nups (0) 0028 00 numparams (0) 0029 02 is_vararg (2) 002A 03 maxstacksize (3) * code: 002B 04000000 sizecode (4) 002F 9B000000 [1] testset 2 0 0 ; if not R0 then R2 = R0 else pc+=1 (goto [3]) 0033 16000080 [2] jmp 1 ; pc+=1 (goto [4]) 0037 80008000 [3] move 2 1 ; R2 := R1 003B 1E008000 [4] return 0 1 ; return * constants: 003F 00000000 sizek (0) * functions: 0043 00000000 sizep (0) * lines: 0047 04000000 sizelineinfo (4) [pc] (line) 004B 03000000 [1] (3) 004F 03000000 [2] (3) 0053 03000000 [3] (3) 0057 03000000 [4] (3) * locals: 005B 03000000 sizelocvars (3) 005F 0200000000000000 string size (2) 0067 6100 "a\0" local [0]: a 0069 00000000 startpc (0) 006D 03000000 endpc (3) 0071 0200000000000000 string size (2) 0079 6200 "b\0" local [1]: b 007B 00000000 startpc (0) 007F 03000000 endpc (3) 0083 0200000000000000 string size (2) 008B 6300 "c\0" local [2]: c 008D 00000000 startpc (0) 0091 03000000 endpc (3) * upvalues: 0095 00000000 sizeupvalues (0) ** end of function 0 ** 0099 ** end of chunk ** Pos Hex Data Description or Code ------------------------------------------------------------------------ 0000 ** source chunk: luac.out ** global header start ** 0000 1B4C7561 header signature: "\27Lua" 0004 51 version (major:minor hex digits) 0005 00 format (0=official) 0006 01 endianness (1=little endian) 0007 04 size of int (bytes) 0008 08 size of size_t (bytes) 0009 04 size of Instruction (bytes) 000A 08 size of number (bytes) 000B 00 integral (1=integral) * number type: double * x86 standard (32-bit, little endian, doubles) ** global header end ** 000C ** function [0] definition (level 1) 0 ** start of function 0 ** 000C 0B00000000000000 string size (11) 0014 406C6561726E2E6C+ "@learn.l" 001C 756100 "ua\0" source name: @learn.lua 001F 00000000 line defined (0) 0023 00000000 last line defined (0) 0027 00 nups (0) 0028 00 numparams (0) 0029 02 is_vararg (2) 002A 03 maxstacksize (3) * code: 002B 04000000 sizecode (4) 002F 9B000000 [1] testset 2 0 0 ; if not R0 then R2 = R0 else pc+=1 (goto [3]) 0033 16000080 [2] jmp 1 ; pc+=1 (goto [4]) 0037 80008000 [3] move 2 1 ; R2 := R1 003B 1E008000 [4] return 0 1 ; return * constants: 003F 00000000 sizek (0) * functions: 0043 00000000 sizep (0) * lines: 0047 04000000 sizelineinfo (4) [pc] (line) 004B 03000000 [1] (3) 004F 03000000 [2] (3) 0053 03000000 [3] (3) 0057 03000000 [4] (3) * locals: 005B 03000000 sizelocvars (3) 005F 0200000000000000 string size (2) 0067 6100 "a\0" local [0]: a 0069 00000000 startpc (0) 006D 03000000 endpc (3) 0071 0200000000000000 string size (2) 0079 6200 "b\0" local [1]: b 007B 00000000 startpc (0) 007F 03000000 endpc (3) 0083 0200000000000000 string size (2) 008B 6300 "c\0" local [2]: c 008D 00000000 startpc (0) 0091 03000000 endpc (3) * upvalues: 0095 00000000 sizeupvalues (0) ** end of function 0 ** 0099 ** end of chunk **
object_tangible_saga_system_saga_relic_destroy = object_tangible_saga_system_shared_saga_relic_destroy:new { gameObjectType = 4353, } ObjectTemplates:addTemplate(object_tangible_saga_system_saga_relic_destroy, "object/tangible/saga_system/saga_relic_destroy.iff")
return Def.ActorFrame{ LoadActor("star.txt")..{ OnCommand=function(self) self:x(-19):y(20):zoom(0.6):wag():effectmagnitude(0,4,10) end }, LoadActor("star.txt")..{ OnCommand=function(self) self:x(19):y(-20):zoom(0.6):wag():effectmagnitude(0,4,10) end }, }
require('libraries/projectiles') local player = PlayerResource:GetPlayer(0) local hero = player:GetAssignedHero() local projectile = { --EffectName = "particles/test_particle/ranged_tower_good.vpcf", --EffectName = "particles/units/heroes/hero_lina/lina_spell_dragon_slave.vpcf", EffectName = "particles/units/heroes/hero_mirana/mirana_spell_arrow.vpcf", --EeffectName = "", --vSpawnOrigin = hero:GetAbsOrigin(), vSpawnOrigin = hero:GetAbsOrigin() + Vector(0,0,80),--{unit=hero, attach="attach_attack1", offset=Vector(0,0,0)}, fDistance = 3000, fStartRadius = 100, fEndRadius = 100, Source = hero, fExpireTime = 8.0, vVelocity = hero:GetForwardVector() * 900, -- RandomVector(1000), UnitBehavior = PROJECTILES_DESTROY, bMultipleHits = false, bIgnoreSource = true, TreeBehavior = PROJECTILES_NOTHING, bCutTrees = true, bTreeFullCollision = false, WallBehavior = PROJECTILES_NOTHING, GroundBehavior = PROJECTILES_NOTHING, fGroundOffset = 80, nChangeMax = 1, bRecreateOnChange = true, bZCheck = false, bGroundLock = true, bProvidesVision = true, iVisionRadius = 350, iVisionTeamNumber = hero:GetTeam(), bFlyingVision = false, fVisionTickTime = .1, fVisionLingerDuration = 1, draw = true,-- draw = {alpha=1, color=Vector(200,0,0)}, --iPositionCP = 0, --iVelocityCP = 1, --ControlPoints = {[5]=Vector(100,0,0), [10]=Vector(0,0,1)}, --ControlPointForwards = {[4]=hero:GetForwardVector() * -1}, --ControlPointOrientations = {[1]={hero:GetForwardVector() * -1, hero:GetForwardVector() * -1, hero:GetForwardVector() * -1}}, --[[ControlPointEntityAttaches = {[0]={ unit = hero, pattach = PATTACH_ABSORIGIN_FOLLOW, attachPoint = "attach_attack1", -- nil origin = Vector(0,0,0) }},]] --fRehitDelay = .3, --fChangeDelay = 1, --fRadiusStep = 10, --bUseFindUnitsInRadius = false, UnitTest = function(self, unit) return unit:GetUnitName() ~= "npc_dummy_unit" and unit:GetTeamNumber() ~= hero:GetTeamNumber() end, OnUnitHit = function(self, unit) print ('HIT UNIT: ' .. unit:GetUnitName()) end, --OnTreeHit = function(self, tree) ... end, --OnWallHit = function(self, gnvPos) ... end, --OnGroundHit = function(self, groundPos) ... end, --OnFinish = function(self, pos) ... end, } Projectiles:CreateProjectile(projectile)
local ContentProvider = game:GetService("ContentProvider") local towerGuis = { ["Samurai"] = {Price = "$500"}, ["Sniper"] = {Image = "6800030688", Price = "$500"}, ["Soldier"] = {Image = "6804899975", Price = "$300"}, ["Grenadier"] = {Image = "6808160269", Price = "$400"}, ["Jedi"] = {Image = "6808160269", Price = "$600"}, ["Sith"] = {Image = "", Price = "$700"}, ["Boxer"] = {Image = "", Price = "$400"}, ["Cowboy"] = {Image = "", Price = "$600"}, ["Pirate"] = {Image = "", Price = "$650"}, ["Miner"] = {Image = "", Price = "$300"}, ["Alien"] = {Image = "", Price = "$400"}, ["Ninja"] = {Image = "", Price = "$475"}, ["Wizard"] = {Image = "", Price = "$300"}, ["Captain America"] = {Image = "", Price = "$550"}, ["Superman"] = {Image = "", Price = "$500"}, ["Dragon Knight"] = {Image = "", Price = "$500"}, ["Beam"] = {Image = "", Price = "$400"}, ["Crossbow"] = {Image = "", Price = "$550"}, ["Shotgunner"] = {Image = "", Price = "$350"}, ["Minigunner"] = {Image = "", Price = "$450"}, ["Musician"] = {Image = "", Price = "$250"}, } local module = {} function module:CreateTowerIcon(tower) local gui = game.ReplicatedStorage.TowerDefenseLocalPackages.Guis.Towers.Gui:Clone() gui.Price.Text = towerGuis[tower].Price gui.Tower.Text = tower return gui end return module
---------------------------------------- -- -- Copyright (c) 2015, 128 Technology, Inc. -- -- author: Hadriel Kaplan <hadriel@128technology.com> -- -- This code is licensed under the MIT license. -- -- Version: 1.0 -- ------------------------------------------ -- prevent wireshark loading this file as a plugin if not _G['protbuf_dissector'] then return end local Settings = require "settings" local dprint = Settings.dprint local dprint2 = Settings.dprint2 local dassert = Settings.dassert local derror = Settings.derror local Base = require "generic.base" ---------------------------------------- -- BytesDecoder class, for unknown bytes in LENGTH_DELIMITED fields -- local BytesDecoder = {} local BytesDecoder_mt = { __index = BytesDecoder } setmetatable( BytesDecoder, { __index = Base } ) -- make it inherit from Base function BytesDecoder.new(pfield) local new_class = Base.new("LENGTH_DELIMITED", pfield) setmetatable( new_class, BytesDecoder_mt ) return new_class end function BytesDecoder:decode(decoder, tag) dprint2("BytesDecoder:decode() called") return decoder:addFieldBytes(self.pfield) end return BytesDecoder
package.path = "?.lua;../?.lua" local input = require "input" local utils = require "utils" function parse(str) return str:match("Step ([A-Z]) must be finished before step ([A-Z]) can begin.") end function possible_steps(constraints) local steps = {} for k, t in pairs(constraints) do if #t == 0 then utils.array_append(steps, k) end end if #steps > 1 then table.sort(steps) end return steps end function duration(step) return 60 + step:byte(1) - 64 end function finish_step(step, constraints) for _, t in pairs(constraints) do utils.array_remove(t, step) end end function solve(input) local t0 = os.clock() local steps = {} local constraints = {} for _, v in ipairs(input) do local a, b = parse(v) local t = constraints[b] or {} utils.array_append(t, a) constraints[b] = t steps[a] = 1 steps[b] = 1 if not constraints[a] then constraints[a] = {} end -- Creates empty entry for first step end -- Create idle workers local workers = {} for i = 1, 5 do utils.array_append(workers, { done_time = 0 }) end local timer = 0 local steps_done = {} local steps_count = utils.set_count(steps) local min = math.min while #steps_done < steps_count do -- Find idle workers local idle_workers = utils.array_filter(workers, function(a) return not a.step end) -- Find possible next steps local next_steps = possible_steps(constraints) if #next_steps > 0 then -- Assign as many new steps to idle workers as possible local lim = min(#idle_workers, #next_steps) for i = 1, lim do local step = next_steps[i] local worker = idle_workers[i] worker.step = step worker.done_time = timer + duration(step) constraints[step] = nil end end -- Find the worker who finishes his current step the earliest local busy_workers = utils.array_filter(workers, function(a) return a.step end) table.sort(busy_workers, function(a, b) return a.done_time < b.done_time end) local worker = busy_workers[1] -- Finish the worker's step finish_step(worker.step, constraints) utils.array_append(steps_done, worker.step) -- Update the current time timer = worker.done_time -- Mark the worker idle worker.step = nil end local time = os.clock() - t0 print(string.format("Elapsed time: %.4f", time)) return timer end local input = input.read_file("input.txt") print("Solution: " .. (solve(input) or "not found"))
local composer = require( "composer" ) local scene = composer.newScene() local options ={ effect = "fade", time=200 } --------------------------------------------------------------------------------- -- All code outside of the listener functions will only be executed ONCE -- unless "composer.removeScene()" is called. --------------------------------------------------------------------------------- -- local forward references should go here --------------------------------------------------------------------------------- -- "scene:create()" function scene:create( event ) local sceneGroup = self.view -- Initialize the scene here. -- Example: add display objects to "sceneGroup", add touch listeners, etc. -- Create the widget ----------------------------background-------------------------------- local bg=display.newImage("tittle.png") bg.x= display.contentWidth/2 bg.y= display.contentHeight/2 bg:scale(.50,.60) local myText = display.newText("Rock-Paper-Scissor", display.contentCenterX, display.contentCenterY-200, native.systemFont, 25) myText:setFillColor(1,1,0) local myText1 = display.newText("Venika Gaur", display.contentCenterX, display.contentCenterY-150, native.systemFont, 25) myText:setFillColor(1,1,0) local startBtn= display.newImage("Startbutton.png") startBtn.x=display.contentCenterX-70 startBtn.y=display.contentCenterY+150 startBtn:scale(.15,.15) local function button1(event) -- composer.removeScene( "Start" ) audio.pause(startsound); composer.gotoScene( "Enemy1" , options ) end startBtn:addEventListener("tap", button1 ) local setBtn= display.newImage("Setbutton.png") setBtn.x=display.contentCenterX+62 setBtn.y=display.contentCenterY+150 setBtn:scale(.14,.13) local function button2(event) composer.gotoScene( "Settings" , options ) end setBtn:addEventListener("tap", button2 ) sceneGroup:insert(bg) sceneGroup:insert(myText1) sceneGroup:insert(myText) sceneGroup:insert(startBtn) sceneGroup:insert(setBtn) end -- "scene:show()" function scene:show( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is still off screen (but is about to come on screen). elseif ( phase == "did" ) then -- Called when the scene is now on screen. -- Insert code here to make the scene come alive. -- Example: start timers, begin animation, play audio, etc. local startsound = audio.loadSound("Startmusic.mp3") audio.play(startsound); end end -- "scene:hide()" function scene:hide( event ) local sceneGroup = self.view local phase = event.phase if ( phase == "will" ) then -- Called when the scene is on screen (but is about to go off screen). -- Insert code here to "pause" the scene. -- Example: stop timers, stop animation, stop audio, etc. elseif ( phase == "did" ) then -- Called immediately after scene goes off screen. end end -- "scene:destroy()" function scene:destroy( event ) local sceneGroup = self.view -- Called prior to the removal of scene's view ("sceneGroup"). -- Insert code here to clean up the scene. -- Example: remove display objects, save state, etc. end --------------------------------------------------------------------------------- -- Listener setup scene:addEventListener( "create", scene ) scene:addEventListener( "show", scene ) scene:addEventListener( "hide", scene ) scene:addEventListener( "destroy", scene ) --------------------------------------------------------------------------------- return scene
-- title: pong clone -- author: digitsensitive -- desc: a short written pong clone -- script: lua -- global game settings -------------------------------------------------------- local GS = {W = 240, H = 136, S = 8, p1s = 0, p2s = 0, t = 0} -- game objects ---------------------------------------------------------------- local p = { {x = 2 * GS.S, y = 3 * GS.S, s = 4, c = 12}, {x = 27.5 * GS.S, y = 3 * GS.S, s = 4, c = 12} } local b -- general definitions and functions ------------------------------------------- rnd = math.random -- specific definitions and functions ------------------------------------------ function resetBall(dir) b = {x = GS.W / 2, y = GS.H / 2, vx = 1.8 * dir, vy = 1.8, c = 12} end -- input ----------------------------------------------------------------------- function input() if btn(0) and p[1].y > 0 then p[1].y = p[1].y - 1 elseif btn(1) and p[1].y + (p[1].s * GS.S) < GS.H then p[1].y = p[1].y + 1 end end -- update ---------------------------------------------------------------------- function update() b.x = b.x + b.vx b.y = b.y + b.vy if b.y > GS.H or b.y < 0 then b.vy = -b.vy end if b.y > p[2].y and p[2].y + (p[2].s * GS.S) < GS.H then p[2].y = p[2].y + 1.6 elseif p[2].y > 0 then p[2].y = p[2].y - 1.6 end if b.x > GS.W then GS.p1s = GS.p1s + 1 resetBall(-1) elseif b.x < 0 then GS.p2s = GS.p2s + 1 resetBall(1) end end function collide(p) local b = {x = b.x + 1, y = b.y + 1} return b.x > p.x and b.x < p.x + 8 and b.y > p.y and b.y < p.y + (p.s * GS.S) end function collisionsCheck() if collide(p[1]) then p[1].c = 11 b.vx = -b.vx elseif collide(p[2]) then p[2].c = 11 b.vx = -b.vx end end -- draw ------------------------------------------------------------------------ function draw() cls(14) map() circ(b.x, b.y, 2, b.c) for i, v in pairs(p) do for j = 0, v.s - 1 do if v.c == 11 then GS.t = GS.t + 1 if GS.t > 20 then v.c = 12 GS.t = 0 end end rect(v.x, v.y + (j * GS.S), GS.S / 2, GS.S, v.c) end end print(GS.p1s, 6, 6, 0) print(GS.p1s, 5, 5, 12) print(GS.p2s, 230, 6, 0) print(GS.p2s, 229, 5, 12) print("v1.0.0", 200, 130, 5) end -- init ------------------------------------------------------------------------ function init() if rnd() < 0.5 then resetBall(-1) else resetBall(1) end end -- main ------------------------------------------------------------------------ init() function TIC() input() update() collisionsCheck() draw() end
local t = My.Translator.translate My = My or {} My.SideMissions = My.SideMissions or {} local versions = { {"MT52 Hornet", "MT52 Hornet", "MT52 Hornet"}, {"MT52 Hornet", "Adder MK6", "Adder MK6"}, {"Piranha F12", "Adder MK6", "Adder MK6"}, {"Piranha F12", "Nirvana R5", "Adder MK6", "Adder MK6"}, {"Piranha F12", "Nirvana R5", "Nirvana R5", "Adder MK6", "Adder MK6"}, } local maxDifficulty = 1 Cron.regular("pirate_base_progressive_difficulty", function(self) -- progressively make enemies harder if maxDifficulty < Util.size(versions) then maxDifficulty = maxDifficulty + 1 logDebug("Increased maximum difficulty of Pirate Base Mission to " .. maxDifficulty) else logDebug("Pirate Base Mission has reached its maximum difficulty level " .. maxDifficulty) Cron.abort(self) end end, 480, 480) local DefenderTemplate = function(templateName) local ship = My.CpuShip(templateName, "Pirate") return ship end local StationTemplate = function() local station = My.SpaceStation("Small Station", "Pirate") station:addTag("mute") return station end local WarpJammerTemplate = function() local jammer = My.WarpJammer("Pirate") return jammer end My.SideMissions.PirateBase = function(station, x, y, player) local version = Util.random({ "station", "jammer", }) local playerDps = Util.totalLaserDps(player) * 2 -- account for tubes if playerDps < 1 then return nil end local difficulty = math.random(1,maxDifficulty) local payment = My.SideMissions.paymentPerDistance(distance(station, x, y)) + (Util.size(versions[difficulty]) + 1) * (0.5 + 0.1 * difficulty) * My.SideMissions.paymentPerEnemy() local sectorName = Util.sectorName(x, y) -- make the station destroyable in reasonable time or it gets boring local stationShield = (math.random() * 0.4 + 0.8) * playerDps * 25 local stationHull = (math.random() * 0.4 + 0.8) * playerDps * 25 local mission = Missions:destroy(function() local target if version == "station" then target = StationTemplate(): setCallSign(My.pirateStationName()): setHullMax(stationHull): setHull(stationHull): setShieldsMax(stationShield): setShields(stationShield): setScannedDescription(t("side_mission_pirate_base_station_description")) else target = WarpJammerTemplate(): setRange(20000): setScannedDescription(t("side_mission_pirate_base_jammer_description")) end target:setPosition(x, y) local ships = {} for _, template in pairs(versions[difficulty]) do local ship = DefenderTemplate(template): setCallSign(My.pirateShipName()) ship:setScannedDescription(t("pirate_ship_description")) table.insert(ships, ship) Util.spawnAtStation(target, ship) ship:orderDefendTarget(target) end table.insert(ships, target) return ships end, { acceptCondition = function(self, error) if distance(player, x, y) < 15000 then return t("side_mission_pirate_base_comms_too_close") end return true end, onStart = function(self) local hint = t("side_mission_pirate_base_" .. version .. "_start_hint", sectorName) self:setHint(hint) self:getPlayer():addToShipLog(hint, "255,127,0") end, onDestruction = function(self, enemy) local numShips, numStations = 0, 0 for _, thing in pairs(self:getValidEnemies()) do if isEeStation(thing) or isEeWarpJammer(thing) then numStations = numStations + 1 elseif isEeShip(thing) then numShips = numShips + 1 end end if isEeShip(enemy) then if numShips == 0 then self:getPlayer():addToShipLog(t("side_mission_pirate_base_destruction_last_hint"), "255,127,0") else self:getPlayer():addToShipLog(t("side_mission_pirate_base_destruction_ship_hint"), "255,127,0") end elseif isEeStation(enemy) then self:getPlayer():addToShipLog(t("side_mission_pirate_base_destruction_station_hint"), "255,127,0") elseif isEeWarpJammer(enemy) then self:getPlayer():addToShipLog(t("side_mission_pirate_base_destruction_jammer_hint"), "255,127,0") end self:setHint(t("side_mission_pirate_base_" .. version .. "_destruction_hint", numShips, numStations > 0)) end, onSuccess = function(self) station:sendCommsMessage(self:getPlayer(), t("side_mission_pirate_base_success_comms", payment)) self:getPlayer():addReputationPoints(payment) end, onEnd = function(self) for _, enemy in pairs(self:getEnemies() or {}) do if isEeObject(enemy) and enemy:isValid() then enemy:destroy() end end end, }) Mission:withBroker(mission, t("side_mission_pirate_base_" .. version, sectorName), { description = t("side_mission_pirate_base_" .. version .. "_briefing", difficulty, sectorName, payment), acceptMessage = nil, }) return mission end
--[[ UnitAlternatePowerInfo UnitAlternatePowerTextureInfo GetRealEclipseDirection --]] function wipe(t) if type(t) ~= "table" then error(("bad argument #1 to 'wipe' (table expected, got %s)"):format(t and type(t) or "no value"), 2) end for k in pairs(t) do t[k] = nil end return t end table.wipe = wipe ----------- -- print -- ----------- do local LOCAL_ToStringAllTemp = {}; function tostringall(...) local n = select('#', ...); -- Simple versions for common argument counts if (n == 1) then return tostring(...); elseif (n == 2) then local a, b = ...; return tostring(a), tostring(b); elseif (n == 3) then local a, b, c = ...; return tostring(a), tostring(b), tostring(c); elseif (n == 0) then return; end local needfix; for i = 1, n do local v = select(i, ...); if (type(v) ~= "string") then needfix = i; break; end end if (not needfix) then return ...; end wipe(LOCAL_ToStringAllTemp); for i = 1, needfix - 1 do LOCAL_ToStringAllTemp[i] = select(i, ...); end for i = needfix, n do LOCAL_ToStringAllTemp[i] = tostring(select(i, ...)); end return unpack(LOCAL_ToStringAllTemp); end local LOCAL_PrintHandler = function(...) DEFAULT_CHAT_FRAME:AddMessage(strjoin(" ", tostringall(...))); end function setprinthandler(func) if (type(func) ~= "function") then error("Invalid print handler"); else LOCAL_PrintHandler = func; end end function getprinthandler() return LOCAL_PrintHandler; end local geterrorhandler = geterrorhandler; local forceinsecure = forceinsecure; local pcall = pcall; local securecall = securecall; local function print_inner(...) --forceinsecure(); local ok, err = pcall(LOCAL_PrintHandler, ...); if (not ok) then local func = geterrorhandler(); func(err); end end function print(...) securecall(pcall, print_inner, ...); end SlashCmdList["PRINT"] = print SLASH_PRINT1 = "/print" end function UnitAura(unit, indexOrName, rank, filter) --[[ local aura_index, aura_name, aura_type if type(indexOrName) ~= "number" then aura_name = indexOrName else aura_index = indexOrName end if not filter and rank then if type(rank) ~= "number" and rank:find("[HELPFUL,HARMFUL,PLAYER,RAID,CANCELABLE,NOT_CANCELABLE]") then filter = rank rank = nil else filter = "HELPFUL" -- default value https://wowwiki.fandom.com/wiki/API_UnitAura end end if aura_name then local i = 1 while true do name, r, icon, count, duration, expirationTime = UnitBuff(unit, i, filter) i = i + 1 end end --]] if ((filter and filter:find("HARMFUL")) or ((rank and rank:find("HARMFUL")) and filter == nil)) then debuffType = "HARMFUL"; elseif ((filter and filter:find("HELPFUL")) or ((rank and rank:find("HARMFUL")) and filter == nil)) then debuffType = "HELPFUL"; else debuffType = nil; end local x; if(type(indexOrName) == "number") then x = indexOrName else x = 1 end if (debuffType == "HELPFUL" or debuffType == nil) then local castable = filter and filter:find("PLAYER") and 1 or nil; local name, r, icon, count, duration, expirationTime = UnitBuff(unit, x, castable); while (name ~= nil) do if ((name == indexOrName or x == indexOrName) and (rank == nil or rank:find("HARMFUL") or rank:find("HELPFUL") or rank == r)) then return name, r, icon, count, debuffType, duration, GetTime() + (expirationTime or 0), (castable and "player") end x = x + 1; name, r, icon, count, duration, expirationTime = UnitBuff(unit, x, castable); end end if (debuffType == "HARMFUL" or debuffType == nil) then local removable = nil if(type(indexOrName) == "number") then x = indexOrName else x = 1 end local name, r, icon, count, dispelType, duration, expirationTime = UnitDebuff(unit, x, removable); while (name ~= nil) do if ((name == indexOrName or x == indexOrName) and (rank == nil or rank:find("HARMFUL") or rank:find("HELPFUL") or rank == r)) then return name, r, icon, count, debuffType, duration, GetTime() + (expirationTime or 0) end x = x + 1; name, r, icon, count, dispelType, duration, expirationTime = UnitDebuff(unit, x, removable); end end return nil; end function UnitInVehicle(unit) return false end function UnitPower(unit, powerType) return UnitMana(unit, powerType) end function UnitPowerMax(unit, powerType) return UnitManaMax(unit, powerType) end local hooks = {} local function SpellID_to_SpellName(spell) if type(spell) == "number" then return GetSpellInfo(spell) else if tonumber(spell) then return GetSpellInfo(spell) else return spell end end return end hooks.GetSpellCooldown = GetSpellCooldown function GetSpellCooldown(spell, booktype) if booktype and (booktype == BOOKTYPE_SPELL or booktype == BOOKTYPE_PET) then return hooks.GetSpellCooldown(spell, booktype) -- вызываем оригинал else spell = SpellID_to_SpellName(spell) return hooks.GetSpellCooldown(spell) -- вызываем оригинал end end hooks.IsUsableSpell = IsUsableSpell function IsUsableSpell(spell, booktype) if booktype and (booktype == BOOKTYPE_SPELL or booktype == BOOKTYPE_PET) then return hooks.IsUsableSpell(spell, booktype) -- вызываем оригинал else spell = SpellID_to_SpellName(spell) return hooks.IsUsableSpell(spell) -- вызываем оригинал end end hooks.IsSpellInRange = IsSpellInRange function IsSpellInRange(spell, booktype, unit) if booktype then if booktype == BOOKTYPE_SPELL or booktype == BOOKTYPE_PET then return hooks.IsSpellInRange(spell, booktype, unit) -- вызываем оригинал else unit = booktype spell = SpellID_to_SpellName(spell) return hooks.IsSpellInRange(spell, unit) -- вызываем оригинал end else spell = SpellID_to_SpellName(spell) return hooks.IsSpellInRange(spell) -- вызываем оригинал end end hooksecurefunc("CreateFrame", function(frameType, name, parent, template) if template == "GameTooltipTemplate" then local f = getglobal(name) f.SetUnitAura = function(self, unit, index, filter) if filter and filter:match("HARMFUL") then self:SetUnitDebuff(unit, index, filter) else self:SetUnitBuff(unit, index, filter) end end end return f end) function GetSpellBookID(spellID, booktype) booktype = booktype or BOOKTYPE_SPELL local book_id = 1 while true do local link = GetSpellLink(book_id, booktype) if not link then return end local id = tonumber(link:match('H.-:(%d+)|h')) if id == spellID then return book_id end book_id = book_id + 1 end end function IsSpellKnown(spellID, isPetSpell) local book_id = GetSpellBookID(spellID, isPetSpell and BOOKTYPE_PET or BOOKTYPE_SPELL) return book_id ~= nil end function PrintTab(obj, max_depth, level, meta_level) if not obj or obj == "" then print('Root = nil') return end if not level then level = 0 end if not max_depth then max_depth = 299 end if level == 0 then obj = {Root = obj} end local Table_stack if not Table_stack then Table_stack = {} end local inset = strrep(' ', level) inset = '\19'..inset local close_flag = false local meta_flag = false for m_key, m_value in pairs(obj) do key = m_key value = m_value if type(key) == 'table' then key = 'table_key' elseif type(key) == 'function' then key = 'function' elseif type(key) == 'userdata' then key = 'userdata' end if type(value) == 'table' then if not Table_stack[value] and (level < max_depth) then print(inset..'['..key..'] = {') Table_stack[value] = true PrintTab(value, max_depth, level+1, obj, meta_level) else close_flag = true print(inset..'['..key..'] = {...}') end elseif type(value) == 'function' then print(inset..'['..key..'] = function') elseif type(value) == 'userdata' then local user_data = 'userdata' if pcall(function() obj:GetName() end) then user_data = obj:GetName() or '' end print(inset..'['..key..'] = '..user_data) elseif type(value) == 'boolean' then print(inset..'['..key..'] = '..tostring(value)) else print(inset..'['..key..'] = '..value) end end local meta = getmetatable(obj) if meta and meta_level then if not Table_stack[meta] and (level < max_depth) then print(inset..'[metatable] = {') Table_stack[meta] = true PrintTab(meta, max_depth, level+1, obj, meta_level) else meta_flag = true print(inset..'['..key..'] = {...}') end end if not close_flag and level > 0 then inset = strrep(' ', level-1) inset = '\19'..inset print(inset..'}') end if level == 0 then for k, v in pairs(Table_stack) do Table_stack[k] = nil end Table_stack = nil end end
local settings = {} local opt = require('partials/utils').opt vim.opt.title = true vim.opt.number = true vim.opt.relativenumber = true vim.opt.showmode = false vim.opt.gdefault = true vim.opt.cursorline = true vim.opt.smartcase = true vim.opt.ignorecase = true vim.opt.mouse = 'a' vim.opt.showmatch = true vim.opt.startofline = false vim.opt.timeoutlen = 1000 vim.opt.ttimeoutlen = 0 vim.opt.fileencoding = 'utf-8' vim.opt.wrap = false vim.opt.linebreak = true vim.opt.listchars = 'tab:│ ,trail:·' vim.opt.list = true vim.opt.lazyredraw = true vim.opt.hidden = true vim.opt.conceallevel = 2 vim.opt.concealcursor = 'nc' vim.opt.splitright = true vim.opt.splitbelow = true vim.opt.inccommand = 'nosplit' vim.opt.exrc = true vim.opt.secure = true vim.opt.grepprg = 'rg --smart-case --color=never --no-heading -H -n --column' vim.opt.tagcase = 'smart' vim.opt.updatetime = 100 vim.opt.shortmess = vim.o.shortmess .. 'c' vim.opt.undofile = true vim.opt.swapfile = false vim.opt.backup = false vim.opt.writebackup = false vim.opt.fillchars = 'vert:│' vim.opt.breakindent = true vim.opt.smartindent = true vim.opt.expandtab = true vim.opt.shiftwidth = 2 vim.opt.shiftround = true vim.opt.foldmethod = 'syntax' vim.opt.foldenable = false vim.opt.diffopt:append('vertical') vim.opt.scrolloff = 8 vim.opt.sidescrolloff = 15 vim.opt.sidescroll = 5 vim.opt.pyxversion = 3 vim.opt.matchtime = 0 vim.g.python3_host_prog = '/usr/bin/python3' vim.cmd([[augroup vimrc]]) vim.cmd([[autocmd!]]) vim.cmd([[autocmd BufWritePre * call v:lua.kris.settings.strip_trailing_whitespace()]]) vim.cmd([[autocmd InsertEnter * set nocul]]) vim.cmd([[autocmd InsertLeave * set cul]]) vim.cmd([[autocmd FocusGained,BufEnter * silent! exe 'checktime']]) vim.cmd([[autocmd FileType vim inoremap <buffer><silent><C-Space> <C-x><C-v>]]) vim.cmd([[autocmd FileType markdown setlocal spell]]) vim.cmd([[autocmd FileType json setlocal conceallevel=0 formatprg=python\ -m\ json.tool]]) vim.cmd([[autocmd TermOpen * setlocal nonumber norelativenumber]]) vim.cmd([[augroup END]]) vim.cmd([[augroup numbertoggle]]) vim.cmd([[autocmd!]]) vim.cmd([[autocmd BufEnter,FocusGained,InsertLeave,WinEnter * if &nu | set rnu | endif]]) vim.cmd([[autocmd BufLeave,FocusLost,InsertEnter,WinLeave * if &nu | set nornu | endif]]) vim.cmd([[augroup END]]) function settings.strip_trailing_whitespace() if vim.bo.modifiable then local line = vim.fn.line('.') local col = vim.fn.col('.') vim.cmd([[%s/\s\+$//e]]) vim.fn.histdel('/', -1) vim.fn.cursor(line, col) end end local cwd = vim.fn.getcwd() local handle = vim.loop.fs_scandir(cwd) if type(handle) == 'string' then return end local paths = {} while true do local name, t = vim.loop.fs_scandir_next(handle) if not name then break end if t == 'directory' and not vim.o.wildignore:find(name) then table.insert(paths, name .. '/**') end end vim.o.path = vim.o.path .. ',' .. table.concat(paths, ',') _G.kris.settings = settings
SKILL.name = "Orbs of Larraman" SKILL.LevelReq = 5 SKILL.SkillPointCost = 1 SKILL.Incompatible = { } SKILL.RequiredSkills = { } SKILL.icon = "vgui/skills/Dow2r_ig_back_in_the_fight.png" SKILL.category = "Medical"-- Common Passives, Warrior, Lore of Light, Lore of Life SKILL.slot = "RANGED" -- ULT, RANGED, MELEE, AOE, PASSIVE SKILL.class = { "apothecary", "ist_medic", } SKILL.desc = [[ You throw an orb of larraman, rejuvenating any ally near the orb. - Inspired by Wikkyd. Cost: 30 Energy. Cooldown: 60 Seconds Ability Slot: 2 Class Restriction: Apothecary, IST Medic. Level Requirement: ]] .. SKILL.LevelReq .. [[ Skill Point Cost:]] .. SKILL.SkillPointCost .. [[ ]] SKILL.coolDown = 60 local function ability(SKILL, ply ) local nospam = ply:GetNWBool( "nospamRanged" ) if (nospam) then if timer.Exists(ply:SteamID().."nospamRanged") then return end timer.Create(ply:SteamID().."nospamRanged", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamRanged", false ) print("ready") end) return end local pos = ply:GetPos() local mana = ply:getLocalVar("mana", 0) if mana < 50 then return end ply:setLocalVar("mana", mana - 50) if SERVER then ply:SetNWBool( "nospamRanged", true ) print("Cdstart") net.Start( "RangedActivated" ) net.Send( ply ) local Ent = ents.Create("obj_40k_grenade_larraman") local OwnerPos = ply:GetShootPos() local OwnerAng = ply:GetAimVector():Angle() OwnerPos = OwnerPos + OwnerAng:Forward()*-20 + OwnerAng:Up()*-9 + OwnerAng:Right()*10 if ply:IsPlayer() then Ent:SetPos(OwnerPos) end if ply:IsPlayer() then Ent:SetAngles(OwnerAng) else Ent:SetAngles(ply:GetAngles()) end Ent:SetOwner(ply) Ent:Spawn() local phy = Ent:GetPhysicsObject() if phy:IsValid() then if ply:IsPlayer() then phy:ApplyForceCenter(ply:GetAimVector() * 20000) end end if timer.Exists(ply:SteamID().."nospamRanged") then return end timer.Create(ply:SteamID().."nospamRanged", SKILL.coolDown, 1, function() ply:SetNWBool( "nospamRanged", false ) print("ready") end) end end SKILL.ability = ability
-- http://forum.farmanager.com/viewtopic.php?p=127121#p127121 -- This script scrolls the console (where program output goes) -- when the user presses Enter while the panels are hidden and -- the command line is empty. -- Whether the command prompt should be displayed in the inserted lines local leave_prompt = false Macro { description="Line feed via Enter in Userscreen"; area="Shell Tree Info QView"; key="Enter"; uid="3A6A0C4A-BBC8-4751-922D-09B59084DC5A"; condition=function() return not APanel.Visible and CmdLine.Empty end; action=function() local toggleKeyBar = Far.GetConfig"Screen.KeyBar" and "CtrlB" Keys(toggleKeyBar) if not leave_prompt then panel.GetUserScreen() end io.write("\n") panel.SetUserScreen() Keys(toggleKeyBar) end; }
local redis = require '../redis_conn' local async = require 'async' redis.connect({host='localhost', port=6379}, function(client) local list = List.new() local int = async.setInterval(1000,function() client.get("123456543", function(res) list:append(res) end) end) async.setTimeout(2100000, function() client.close() int.clear() for _,res in ipairs(list) do print(pretty.write(res)) end end) end) async.go()
-- vim.g.completion_auto_change_source = 1 -- Change the completion source automatically if no completion availabe vim.g.completion_enable_snippet = "UltiSnips" -- vim.g.completion_matching_strategy_list = {'exact', 'substring', 'fuzzy'} -- vim.g.completion_matching_ignore_case = 1 -- vim.g.completion_trigger_keyword_length = 3 -- default = 1 vim.g.completion_customize_lsp_label = { Function = " [function]", Method = " [method]", Reference = " [refrence]", Enum = " [enum]", Field = "ﰠ [field]", Keyword = " [key]", Variable = " [variable]", Folder = " [folder]", Snippet = " [snippet]", Operator = " [operator]", Module = " [module]", Text = "ﮜ[text]", Class = " [class]", Interface = " [interface]", } vim.g.completion_chain_complete_list = { default = { { complete_items = { "lsp", "snippet" } }, { complete_items = { "buffers" } }, { mode = "<c-p>" }, { mode = "<c-n>" }, }, }
--[[ Copyright 2014 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local tap = require('util/tap') local test = tap.test test("test listenerCount", function() assert( 2 == require('core').Emitter:new():on("foo", function(a) end ):on("foo", function(a, b) end ):on("bar", function(a, b) end ):listenerCount("foo") ) assert(0 == require('core').Emitter:new():listenerCount("non-exist")) end) test("chaining", function(expect) require('core').Emitter:new():on( "foo", expect( function(x) assert(x.a == "b") end ) ):emit("foo", {a = "b"}) end) test("removal", function(expect) local e1 = require('core').Emitter:new() local cnt = 0 local function incr() cnt = cnt + 1 end local function dummy() assert(false, "this should be removed and never fire") end e1:on("t1", incr) e1:on("t1", dummy) e1:on("t1", incr) e1:removeListener("t1", dummy) e1:emit("t1") assert(cnt == 2) assert(e1:listenerCount("t1") == 2) end) test("once removal", function(expect) local e1 = require('core').Emitter:new() local cnt = 0 local function incr() cnt = cnt + 1 end local function dummy() assert(false, "this should be removed and never fire") end e1:once("t1", incr) e1:once("t1", dummy) e1:once("t1", incr) e1:removeListener("t1", dummy) e1:emit("t1") assert(cnt == 2) assert(e1:listenerCount("t1") == 0) end) test("remove all listeners", function(expect) local em = require('core').Emitter:new() em:on("data", function() end) em:removeAllListeners() em:on("data", expect(function() end)) em:emit("data", "Go Fish") assert(#em:listeners("data") == 1) em:removeAllListeners() assert(#em:listeners("data") == 0) end) tap.run()
-- NormalizeStructuredMidiTracks - sets all midi items in structured MIDI -- tracks (with a name starting with "S ") -- to standard note velocity, and removes -- volume, pan and reverb settings -- -- author: Dr. Thomas Tensi, 2019-08 -- ==================== -- IMPORTS -- ==================== local _, scriptPath = reaper.get_action_context() local scriptDirectory = scriptPath:match('^.+[\\//]') package.path = scriptDirectory .. "?.lua" require("math") require("List") require("Logging") require("Map") require("OperatingSystem") require("Reaper") require("Set") -- ======================= function _initialize () Logging:initialize() local directoryPath = OperatingSystem.selectDirectory("/tmp", "REAPERLOGS", "TEMP", "TMP") if directoryPath ~= nil then Logging.setFileName(directoryPath .. "/reaper_normalizeStrMIDI.log") end end -- -------------------- function _finalize () Logging.finalize() end -- ======================= local _programName = "NormalizeStructuredVoiceTracks" local _trackNamePatternVariableName = "structuredMidiTrackNamePattern" local _defaultMidiTrackNamePattern = "S .*" local _defaultNoteVelocity = 80 -- the set of control codes to be removed local _controlCodeSet = Set:make() _controlCodeSet:include( 7) -- volume _controlCodeSet:include(10) -- pan _controlCodeSet:include(91) -- reverb -- ======================= function _adaptToRaster (value, rasterSize) -- Quantizes <value> to raster given by <rasterSize> and returns -- resulting value; the value is adapted to either 2 or 3 times -- the raster size and the value with the minimal distance is -- selected Logging.trace(">>: value = %d, raster = %d", value, rasterSize) local distance = 9999 local result for i = 2, 3 do local currentRasterSize = i * rasterSize local rasteredValue = math.floor(0.5 + value / currentRasterSize) * currentRasterSize local newDistance = math.abs(value - rasteredValue) if newDistance < distance then result = rasteredValue distance = newDistance end end Logging.trace("<<: %d", result) return result end -- -------------------- function _processTake (take) -- Sets events in <take>: adapts note velocity to standard value, -- quantizes notes to 32nds and removes volume, pan and reverb -- settings Logging.trace(">>: take = %s", take) _removeUnwantedControlCodes(take) _setNoteVelocitiesAndPositions(take) Logging.trace("<<") end -- -------------------- function _processVoiceTrack (track) -- Adapts each midi media item in <track>; sets note velocity to -- standard value, quantizes notes according to 32nds and removes -- volume, pan and reverb settings Logging.trace(">>: track = %s", track) local visitedMediaItemSet = Set:make() for _, mediaItem in track:mediaItemList():iterator() do if visitedMediaItemSet:contains(mediaItem) then Logging.trace("--: skipped visited item %s", mediaItem) else -- mark this item as visited visitedMediaItemSet:include(mediaItem) for _, take in mediaItem:takeList():iterator() do if not take:isMIDI() then Logging.trace("--: skipped non-MIDI take %s", take) else _processTake(take) end end end end Logging.trace("<<") end -- -------------------- function _removeUnwantedControlCodes (take) -- Removes control events in <take> as specified in -- <_controlCodeSet> Logging.trace(">>: %s", take) local midiControlEventKind = Reaper.MidiEventKind.controlCode local midiControlEventList = take:midiEventList(midiControlEventKind) Logging.trace("--: ccEventCount[%s] = %d", take, midiControlEventList:count()) for i, controlEvent in midiControlEventList:reversedIterator() do local controlCode = controlEvent.messagePart1 local isRelevant = _controlCodeSet.contains(controlCode) Logging.trace("--: index = %d, cc = %d, isRelevant = %s", i, controlCode, isRelevant) if isRelevant then midiControlEventList:deleteEvent(eventIndex) end end Logging.trace("<<") end -- -------------------- function _setNoteVelocitiesAndPositions (take) -- Adapts note events in <take>: set velocity to default and -- quantize to raster positions Logging.trace(">>: take = %s", take) local midiNoteEventList = take:midiEventList(Reaper.MidiEventKind.note) Logging.trace("--: noteEventCount[%s] = %d", take, midiNoteEventList:count()) local midiResolution = take:midiResolution() / 24 Logging.trace("--: midiResolution = %s", midiResolution) for i, noteEvent in midiNoteEventList:iterator() do Logging.trace("--: event %s", noteEvent) -- adapt velocity noteEvent.velocity = _defaultNoteVelocity -- adapt start and end position to resolution local startPosition = noteEvent.startPosition local duration = noteEvent.endPosition - startPosition startPosition = _adaptToRaster(startPosition, midiResolution) duration = math.max(midiResolution, _adaptToRaster(duration, midiResolution)) noteEvent.startPosition = startPosition noteEvent.endPosition = startPosition + duration Logging.trace("--: new event %s", noteEvent) take:setMidiEvent(i, noteEvent) end Logging.trace("<<") end -- ======================= function main() Logging.trace(">>") local project = Reaper.Project.current() local trackNamePattern = Reaper.ConfigData.get(project, _trackNamePatternVariableName) trackNamePattern = iif(trackNamePattern == nil, _defaultMidiTrackNamePattern, trackNamePattern) Logging.trace("--: pattern = \"%s\"", trackNamePattern) local isStructuredVoiceTrackProc = function (track) return String.findPattern(track:name(), trackNamePattern) end local trackList = project:trackList():filter(isStructuredVoiceTrackProc) Logging.trace("--: trackList = %s", trackList) for _, track in trackList:iterator() do _processVoiceTrack(track) end -- we're done local title = _programName Reaper.UI.showMessageBox("Done.", title, Reaper.UI.MessageBoxKind.ok) Logging.trace("<<") end -- -------------------- _initialize() main() _finalize()
ai_library.aesthetic = {} ai_library.aesthetic.__index = ai_library.aestetic --run on step function ai_library.aesthetic:on_step(self,dtime) self.ai_library.aesthetic:set_animation(self,dtime) self.ai_library.aesthetic:check_for_hurt(self,dtime) self.ai_library.aesthetic:hurt_texture_normalize(self,dtime) self.ai_library.aesthetic:water_particles(self) end --show nametag of id for debug function ai_library.aesthetic:debug_id(self) self.object:set_properties({nametag = self.id,nametag_color = "red"}) end --water particles function ai_library.aesthetic:water_particles(self) --falling into a liquid if self.liquid ~= 0 and (self.old_liquid and self.old_liquid == 0) then if self.vel.y < -3 then local pos = self.object:getpos() pos.y = pos.y + self.center + 0.1 --play splash sound minetest.sound_play("open_ai_falling_into_water", { pos = pos, max_hear_distance = 10, gain = 1.0, }) minetest.add_particlespawner({ amount = 10, time = 0.01, minpos = {x=pos.x-0.5, y=pos.y, z=pos.z-0.5}, maxpos = {x=pos.x+0.5, y=pos.y, z=pos.z+0.5}, minvel = {x=0, y=0, z=0}, maxvel = {x=0, y=0, z=0}, minacc = {x=0, y=0.5, z=0}, maxacc = {x=0, y=2, z=0}, minexptime = 1, maxexptime = 2, minsize = 1, maxsize = 2, collisiondetection = true, vertical = false, texture = "bubble.png", }) end end end --check if mob is hurt and show damage function ai_library.aesthetic:check_for_hurt(self,dtime) local hp = self.object:get_hp() if self.old_hp and hp < self.old_hp then --run texture function self.ai_library.aesthetic:hurt_texture(self,(self.old_hp-hp)/4) --allow user to do something when hurt if self.user_on_hurt then self.user_on_hurt(self,self.old_hp-hp) end end end --makes a mob turn red when hurt function ai_library.aesthetic:hurt_texture(self,punches) self.fall_damaged_timer = 0 self.fall_damaged_limit = punches end --makes a mob turn back to normal after being hurt function ai_library.aesthetic:hurt_texture_normalize(self,dtime) --apply the particle effect if self.fall_damaged_timer ~= nil then minetest.add_particlespawner({ amount = 2, time = 0.01, minpos = self.mpos, maxpos = self.mpos, minvel = {x=-5, y=5, z=-5}, maxvel = {x=5, y=8, z=5}, minacc = {x=0, y=-10, z=0}, maxacc = {x=0, y=-10, z=0}, minexptime = 1, maxexptime = 2, minsize = 1, maxsize = 1, collisiondetection = true, vertical = false, texture = "open_ai_dot_particle.png^[colorize:#" .. self.hit_color .. ":255", }) if self.fall_damaged_timer >= self.fall_damaged_limit then self.fall_damaged_timer = nil self.fall_damaged_limit = nil end end end --how the mob sets it's mesh animation function ai_library.aesthetic:set_animation(self,dtime) local vel = self.object:getvelocity() --only use jump animation for jump only mobs if self.jump_only == true then --set animation if jumping --future note, this is the function that should be used when setting the jump animation for normal mobs if vel.y == 0 and (self.old_vel and self.old_vel.y < 0) then self.object:set_animation({x=self.animation.jump_start,y=self.animation.jump_end}, self.animation.speed_normal, 0, false) minetest.after(self.animation.speed_normal/100, function(self) self.object:set_animation({x=self.animation.stand_start,y=self.animation.stand_end}, self.animation.speed_normal, 0, true) end,self) end --do normal walking animations else local speed = (math.abs(vel.x)+math.abs(vel.z))*self.animation.speed_normal --check this self.object:set_animation({x=self.animation.walk_start,y=self.animation.walk_end}, speed, 0, true) --run this in here because it is part of animation and textures self.ai_library.aesthetic:hurt_texture_normalize(self,dtime) --set the riding player's animation to sitting if self.attached and self.attached:is_player() and self.player_pose then self.attached:set_animation(self.player_pose, 30,0) end end end --a visual of the leash function ai_library.aesthetic:leash_visual(self,distance,pos,vec) --multiply times two if too far distance = math.floor(distance*2) --make this an int for this function --divide the vec into a step to run through in the loop local vec_steps = {x=vec.x/distance,y=vec.y/distance,z=vec.z/distance} --add particles to visualize leash for i = 1,math.floor(distance) do minetest.add_particle({ pos = {x=pos.x-(vec_steps.x*i), y=pos.y-(vec_steps.y*i), z=pos.z-(vec_steps.z*i)}, velocity = {x=0, y=0, z=0}, acceleration = {x=0, y=0, z=0}, expirationtime = 0.01, size = 1, collisiondetection = false, vertical = false, texture = "open_ai_leash_particle.png", }) end end --visual on death function ai_library.aesthetic:on_die(self) minetest.add_particlespawner({ amount = 100, time = 0.01, minpos = self.mpos, maxpos = self.mpos, minvel = {x=-5, y=5, z=-5}, maxvel = {x=5, y=8, z=5}, minacc = {x=0, y=-10, z=0}, maxacc = {x=0, y=-10, z=0}, minexptime = 1, maxexptime = 2, minsize = 1, maxsize = 1, collisiondetection = true, vertical = false, texture = "open_ai_dot_particle.png^[colorize:#" .. self.hit_color .. ":255", }) end --taming visual function ai_library.aesthetic:tamed(self) --add to particles class minetest.add_particlespawner({ amount = 50, time = 0.001, minpos = self.mpos, maxpos = self.mpos, minvel = {x=-6, y=3, z=-6}, maxvel = {x=6, y=8, z=6}, minacc = {x=0, y=-10, z=0}, maxacc = {x=0, y=-10, z=0}, minexptime = 1, maxexptime = 2, minsize = 1, maxsize = 2, collisiondetection = false, vertical = false, texture = "heart.png", }) end --sitting visual function ai_library.aesthetic:sat(self) --add to particles class minetest.add_particlespawner({ amount = 50, time = 0.001, minpos = self.mpos, maxpos = self.mpos, minvel = {x=-6, y=3, z=-6}, maxvel = {x=6, y=8, z=6}, minacc = {x=0, y=-10, z=0}, maxacc = {x=0, y=-10, z=0}, minexptime = 1, maxexptime = 2, minsize = 1, maxsize = 1, collisiondetection = false, vertical = false, texture = "open_ai_slime_particle.png^[colorize:#ff0000:255", }) end --standing visual function ai_library.aesthetic:stood(self) --add to particles class minetest.add_particlespawner({ amount = 50, time = 0.001, minpos = self.mpos, maxpos = self.mpos, minvel = {x=-6, y=3, z=-6}, maxvel = {x=6, y=8, z=6}, minacc = {x=0, y=-10, z=0}, maxacc = {x=0, y=-10, z=0}, minexptime = 1, maxexptime = 2, minsize = 1, maxsize = 1, collisiondetection = false, vertical = false, texture = "open_ai_slime_particle.png^[colorize:#00ff00:255", }) end
local microtest = require('microtest') local suite = microtest.suite local test = microtest.test local equal = microtest.equal local path = require('lettersmith.path') local resolve_up_dir_traverse = path.resolve_up_dir_traverse local remove_trailing_slash = path.remove_trailing_slash suite('path.remove_trailing_slash()', function () test(remove_trailing_slash('..') == '..', "Leaves text without a trailing slash alone") local x = remove_trailing_slash('../') == '..' and remove_trailing_slash('bar/../') == 'bar/..' test(x, "Removes trailing slash") test(remove_trailing_slash('/') == '/', "Leaves strings alone when they only contain a slash") end) suite("path.shift(s)", function () test(path.shift("..") == '..', "Handles .. correctly") local x, y = path.shift("foo/bar/baz") equal(x, "foo", "Handles foo/bar/baz head") equal(y, "bar/baz", "Handles foo/bar/baz tail") local x, y = path.shift("/foo/bar") local z = x == "/" and y == "foo/bar" equal(x, "/", "Handles /foo/bar head, returning /") equal(y, "foo/bar", "Handles /foo/bar tail, returning foo/bar") equal(path.shift("bar/"), "bar", "Handles bar/ correctly, returning bar") -- @fixme handle this case better -- test(path.shift("./")) end) suite('path.normalize(s)', function () test(path.normalize('./foo/././') == 'foo', "Resolved same dir") test(path.normalize('./foo/././bar') == 'foo/bar', "Resolved same dir followed by dir") test(path.normalize('./foo/./.') == 'foo', "Resolved same dir with trailing dot") test(path.normalize("..") == '..', "Handled .. correctly") test(path.normalize("../") == "..", "Resolved ../ correctly") test(path.normalize('bar/../foo') == "foo", "Resolved bar/../foo to foo") test(path.normalize('bar/../') == ".", "Resolved bar/../ to .") test(path.normalize("/../../") == "/", "Resolved /../../ to /") end) suite("path.join()", function () test(path.join("..", "foo") == "../foo", ".., foo joined to ../foo") end) suite("path.parts(location_string)", function () local a = path.parts("foo/bar/baz") equal(a[1], "foo", "Handled part 1") equal(a[2], "bar", "Handled part 2") equal(a[3], "baz", "Handled part 3") end) suite("path.basename(location_string)", function () equal(path.basename("foo/bar/baz"), "baz", "Basename is baz") equal(path.basename("foo/bar/baz.html"), "baz.html", "Basename is baz.html") local basename, rest = path.basename('foo/bar/baz.html') equal(rest, "foo/bar", "The rest of path is foo/bar") end) suite("path.extension(path_string)", function () equal(path.extension("foo/bar/baz"), "", "Returns empty string for no extension") equal(path.extension("foo/bar.md"), ".md", "Returns extension") end) suite("path.replace_extension(path_string, new_extension)", function () local x = path.replace_extension("foo/bar/baz.md", ".html") equal(x, "foo/bar/baz.html", "Replaces extension") local y = path.replace_extension("bing/baz.foo.bar.md", ".html") equal(y, "bing/baz.foo.bar.html", "Replaces only last extension") end)
coSetCppProjectDefaults("test_math") kind "ConsoleApp" coSetProjectDependencies{"container", "test", "memory", "lang", "math"}
return { _type_ = 'DesignDrawing', id = 1110020012, learn_component_id = { 1020809022, }, }
--[[ Carbon for Lua #class Pointers.LookupPointer #description { Provides an interface to referencing a data lookup. LookupPointers themselves are copied, but the data they point to is not. } ]] local Carbon = (...) local Dictionary = Carbon.Collections.Dictionary local indexable = { ["table"] = true, ["userdata"] = true, ["string"] = true } local function nav(parent, path) for i = 1, #path do if (not indexable[type(parent)]) then return nil end parent = parent[path[i]] end return parent end local function getvalue(self) local parent = rawget(self, "__parent") local path = rawget(self, "__path") if (parent and path) then return nav(parent, path) else return self end end local meta = { __add = function(a, b) return (tonumber(a) or getvalue(a)) + (tonumber(b) or getvalue(b)) end, __sub = function(a, b) return (tonumber(a) or getvalue(a)) - (tonumber(b) or getvalue(b)) end, __div = function(a, b) return (tonumber(a) or getvalue(a)) / (tonumber(b) or getvalue(b)) end, __mul = function(a, b) return (tonumber(a) or getvalue(a)) * (tonumber(b) or getvalue(b)) end, __mod = function(a, b) return (tonumber(a) or getvalue(a)) % (tonumber(b) or getvalue(b)) end, __pow = function(a, b) return (tonumber(a) or getvalue(a)) ^ (tonumber(b) or getvalue(b)) end, __concat = function(a, b) return tostring(a) .. tostring(b) end, __eq = function(a, b) return (indexable[type(a)] and getvalue(a) or a) == (indexable[type(b)] and getvalue(b) or b) end, __lt = function(a, b) return (indexable[type(a)] and getvalue(a) or a) < (indexable[type(b)] and getvalue(b) or b) end, __le = function(a, b) return (indexable[type(a)] and getvalue(a) or a) <= (indexable[type(b)] and getvalue(b) or b) end, __unm = function(self) return -getvalue(self) end, __tostring = function(self) return tostring(getvalue(self)) end, __index = function(self, key) return getvalue(self)[key] end, __newindex = function(self, key, value) getvalue(self)[key] = value end, __call = function(self, ...) return getvalue(self)(...) end, __pairs = function(self) return pairs(getvalue(self)) end, __ipairs = function(self) return ipairs(getvalue(self)) end } local LookupPointer = {} --[[#method 1 { class public @LookupPointer LookupPointer:New(@indexable parent, @list<string> path) required parent: The base of the lookup to be performed. required path: A list of strings to navigate through the parent with. Creates a new @LookupPointer pointing at the given parent with a given navigation table. }]] function LookupPointer:New(parent, path) local instance = Dictionary.DeepCopy(self) instance.__parent = parent instance.__path = path setmetatable(instance, meta) return instance end --[[#method 2 { object public @LookupPointer LookupPointer:Copy() Copies the @LookupPointer but not the data it points to. }]] function LookupPointer:Copy() return self:New(self.__parent, self.__path) end --[[#method { object public (@indexable, @list<string>) LookupPointer:Get() Returns the current parent and navigation table. }]] function LookupPointer:Get() return self.__parent, self.__path end --[[#method { object public @void LookupPointer:Get(@indexable parent, @list<string> path) required parent: The base of the lookup to be performed. required path: A list of strings to navigate through the parent with. Sets a new parent and navigation table for the @LookupPointer. }]] function LookupPointer:Set(parent, path) self.__parent = parent self.__path = path end return LookupPointer
function love.conf(t) t.window.title = "Connected Bodies" t.window.icon = "icon.png" t.window.width = 600 t.window.height = 600 t.window.vsync = 1 end
object_mobile_dressed_bofa_treat_female_01 = object_mobile_shared_dressed_bofa_treat_female_01:new { } ObjectTemplates:addTemplate(object_mobile_dressed_bofa_treat_female_01, "object/mobile/dressed_bofa_treat_female_01.iff")
--- The Common Mob Interface -- @module cmi -- @author raymoo cmi = {} --- Types. -- The various data structures used in the API. -- @section types --- Object Identifiers. -- @string type Either "player" or "mob" -- @string identifier For players, is a player name. For mobs, is a unique ID. -- @table Id --- Punch callbacks. -- @tparam ObjectRef mob -- @tparam ?ObjectRef hitter -- @number time_from_last_punch -- @tab tool_capabilities -- @tparam ?vector dir -- @number damage -- @tparam ?Id attacker Any indirect owner of the punch, for example a -- player who fired an arrow. -- @function PunchCallback --- Reasons a mob could die. -- The type field determines what kind of cause a @{DeathCause} is. It can be one -- of those specified here, or a custom one provided by a mod. For custom types, -- the fields should be specified by the mod introducing it. -- @string type The predefined types are "punch" and "environment". -- @tparam ?ObjectRef puncher If type == "punch", contains the puncher. The -- puncher can be nil. -- @tparam ?Id attacker If type == "punch", contains the attacker if it exists -- and is known. -- @tparam ?vector pos If type == "environment", is the position of the damaging -- node. -- @tparam ?node node If type == "environment", describes the damaging node. -- @table DeathCause --- Death callbacks. -- @tparam ObjectRef mob the dying mob -- @tparam DeathCause cause cause of death -- @function DeathCallback --- Activation callbacks. -- @tparam ObjectRef mob the mob being activated -- @number dtime the time since the mob was unloaded -- @function ActivationCallback --- Step callbacks. -- @tparam ObjectRef mob -- @number dtime -- @function StepCallback --- Component definitions. -- @string name a unique name for the component, prefixed with the mod name -- @func initialize a function taking no arguments and returning a new instance -- of the data -- @func serialize a function taking your component's data as an input and -- returning it serialized as a string -- @func deserialize a function taking the serialized form of your data and -- turning it back into the original data -- @table ComponentDef -- Returns a table and the registration callback for it local function make_callback_table() local callbacks = {} local function registerer(entry) table.insert(callbacks, entry) end return callbacks, registerer end -- Returns a notification function local function make_notifier(cb_table) return function(...) for i, cb in ipairs(cb_table) do cb(...) end end end --- Callback Registration. -- Functions for registering mob callbacks. -- @section callbacks --- Register a callback to be run when a mob is punched. -- @tparam PunchCallback func -- @function register_on_punchmob local punch_callbacks punch_callbacks, cmi.register_on_punchmob = make_callback_table() --- Register a callback to be run when a mob dies. -- @tparam DeathCallback func -- @function register_on_diemob local die_callbacks die_callbacks, cmi.register_on_diemob = make_callback_table() --- Register a callback to be run when a mob is activated. -- @tparam ActivationCallback func -- @function register_on_activatemob local activate_callbacks activate_callbacks, cmi.register_on_activatemob = make_callback_table() --- Register a callback to be run on mob step. -- @tparam StepCallback func -- @function register_on_stepmob local step_callbacks step_callbacks, cmi.register_on_stepmob = make_callback_table() --- Querying. -- Functions for getting information about mobs. -- @section misc -- Wraps an entity-accepting function to accept entities or ObjectRefs. local function on_entity(name, func) return function(object, ...) local o_type = type(object) -- luaentities are tables if o_type == "table" then return func(object, ...) end if o_type == "userdata" then local ent = object:get_luaentity() return ent and func(ent, ...) end -- If no error, it's still possible that the input was bad. error("Non-luaentity Non-ObjectRef input to" .. name) end end -- Same as on_entity but for ObjectRefs local function on_object(name, func) return on_entity(function(ent, ...) return func(ent.object, ...) end) end --- Checks if an object is a mob. -- @tparam ObjectRef|luaentity object -- @treturn bool true if the object is a mob, otherwise returns a falsey value -- @function is_mob cmi.is_mob = on_entity("is_mob", function(ent) return ent._cmi_is_mob end) --- Gets a player-readable mob name. -- @tparam ObjectRef|luaentity object -- @treturn string -- @function get_mob_description cmi.get_mob_description = on_entity("get_mob_description", function(mob) local desc = mob.description if desc then return desc end local name = mob.name local colon_pos = string.find(name, ":") if colon_pos then return string.sub(name, colon_pos + 1) else return name end end) --- Health-related. -- Functions related to hurting or healing mobs. -- @section health --- Attack a mob. -- Functions like the punch method of ObjectRef, but takes an additional optional -- argument for an indirect attacker. Also works on non-mob entities that define -- an appropriate _cmi_attack method. -- @tparam ObjectRef|luaentity mob -- @tparam ObjectRef puncher -- @number time_from_last_punch -- @tab tool_capabilities -- @tparam vector direction -- @tparam ?Id attacker An indirect owner of the punch. For example, the player -- who fired an arrow that punches the mob. -- @function attack local function attack_ent(mob, puncher, time_from_last_punch, tool_capabilities, direction, attacker) -- It's a method in the mob but I don't want to index it twice local atk = mob._cmi_attack if not atk then mob.object:punch(puncher, time_from_last_punch, tool_capabilities, direction) else atk(mob, puncher, time_from_last_punch, tool_capabilities, direction, attacker) end end cmi.attack = on_entity("attack", attack_ent) local function bound(x, minb, maxb) if x < minb then return minb elseif x > maxb then return maxb else return x end end --- Punch damage calculator. -- By default, this just calculates damage in the vanilla way. Switch it out for -- something else to change the default damage mechanism for mobs. -- @tparam ObjectRef mob -- @tparam ?ObjectRef puncher -- @tparam number time_from_last_punch -- @tparam table tool_capabilities -- @tparam ?vector direction -- @tparam ?Id attacker -- @treturn number The calculated damage function cmi.damage_calculator(mob, puncher, tflp, caps, direction, attacker) local a_groups = mob:get_armor_groups() or {} local full_punch_interval = caps.full_punch_interval or 1.4 local time_prorate = bound(tflp / full_punch_interval, 0, 1) local damage = 0 for group, damage_rating in pairs(caps.damage_groups or {}) do local armor_rating = a_groups[group] or 0 damage = damage + damage_rating * (armor_rating / 100) end return math.floor(damage * time_prorate) end --- Components. -- Components are data stored in a mob, that every mob is guaranteed to contain. -- You can use them in conjunction with callbacks to extend mobs with new -- functionality, without explicit support from mob mods. -- @section components --- Register a mob component. -- @tparam ComponentDef component_def -- @function register_component local component_defs component_defs, cmi.register_component = make_callback_table() --- Get a component from a mob. -- @tparam mob ObjectRef|luaentity mob -- @string component_name -- @return The requested component, or nil if it doesn't exist -- @function get_mob_component cmi.get_mob_component = on_entity("get_mob_component", function(mob, c_name) return mob._cmi_components.components[c_name] end) --- Set a component in a mob. -- @tparam mob ObjectRef|luaentity mob -- @string component_name -- @param new_value -- @function set_mob_component cmi.set_mob_component = on_entity("set_mob_component", function(mob, c_name, new) mob._cmi_components.components[c_name] = new end) --- Unique Ids. -- Every mob gets a unique ID when they are created. This feature is implemented -- as a component, so you can use it as an example. -- @section uids local function show_hex(str) local len = #str local results = {} for i = 1, len do table.insert(results, string.format("%x", str:byte(i))) end return table.concat(results) end -- This is an ID that will be (probabilistically) unique to this session. local session_id = SecureRandom() and show_hex(SecureRandom():next_bytes(16)) -- Fallback to math.rand with a warning if not session_id then minetest.log("warning", "[cmi] SecureRandom() failed, falling back to math.random for unique IDs") -- Generate 16 1-byte numbers, stringify them, then join them together local id_pieces = {} for i=1, 16 do table.insert(id_pieces, tostring(math.rand(0, 255))) end session_id = table.concat(id_pieces, "-") end -- A unique ID is generated by appending a counter to the session ID. local counter = 0 local function generate_id() counter = counter + 1 return session_id .. "-" .. counter end cmi.register_component({ name = "cmi:uid", initialize = generate_id, serialize = function (x) return x end, deserialize = function (x) return x end, }) --- Get the unique ID of a mob. -- @tparam ObjectRef|luaentity mob -- @treturn string function cmi.get_uid(mob) return cmi.get_mob_component(mob, "cmi:uid") end --- Implementation: event notification. -- Functions used to notify CMI when things happen to your mob. Only necessary -- when you are implementing the interface. -- @section impl_events --- Notify CMI that your mob has been punched. -- Call this before doing any punch handling that is not "read-only". -- @tparam ObjectRef mob -- @tparam ?ObjectRef hitter -- @number time_from_last_punch -- @tab tool_capabilities -- @tparam ?vector dir -- @number damage -- @tparam ?Id attacker -- unknown. -- @return Returns true if punch handling should be aborted. -- @function notify_punch cmi.notify_punch = make_notifier(punch_callbacks) --- Notify CMI that your mob has died. -- Call this right before calling remove. -- @tparam ObjectRef mob the dying mob -- @tparam DeathCause cause cause of death -- @function notify_die cmi.notify_die = make_notifier(die_callbacks) --- Notify CMI that your mob has been activated. -- Call this after all other mob initialization. -- @tparam ObjectRef mob the mob being activated -- @number dtime the time since the mob was unloaded -- @function notify_activate cmi.notify_activate = make_notifier(activate_callbacks) --- Notify CMI that your mob is taking a step. -- Call this on every step. It is suggested to call it before or after all other -- processing, to avoid logic errors caused by callbacks handling the same state -- as your entity's normal step logic. -- @tparam ObjectRef mob -- @number dtime -- @function notify_step cmi.notify_step = make_notifier(step_callbacks) --- Implementation: components. -- Functions related to implementing entity components. Only necessary when you -- are implementing the interface. -- @section impl_components --- Activates component data. -- On mob activation, call this and put the result in the _cmi_components field of -- its luaentity. -- @tparam ?string serialized_data the serialized form of the string, if -- available. If the mob has never had component data, do not pass this argument. -- @return component data function cmi.activate_components(serialized_data) local serial_table = serialized_data and minetest.parse_json(serialized_data) or {} local components = {} for i = 1, #component_defs do local def = component_defs[i] local name = def.name local serialized = serial_table[name] components[name] = serialized and def.deserialize(serialized) or def.initialize() end return { components = components, old_serialization = serial_table, } end --- Serialized component data. -- When serializing your mob data, call this and put the result somewhere safe, -- where it can be retrieved on activation to be passed to -- #{activate_components}. -- @param component_data -- @treturn string function cmi.serialize_components(component_data) local serial_table = component_data.old_serialization local components = component_data.components for i = 1, #component_defs do local def = component_defs[i] local name = def.name local component = components[name] serial_table[name] = def.serialize(component) end return minetest.write_json(serial_table) end --- Implementation: health. -- Functions related to health that are needed for implementation of the -- interface. Only necessary if you are implementing the interface. -- @section impl_damage --- Calculate damage. -- Use this function when you want to calculate the "default" damage. If you -- are a modder who wants to switch out the damage mechanism, do not replace -- this function. Replace #{damage_calculator} instead. -- @tparam ObjectRef mob -- @tparam ?ObjectRef puncher -- @tparam number time_from_last_punch -- @tparam table tool_capabilities -- @tparam ?vector direction -- @tparam ?Id attacker -- @treturn number function cmi.calculate_damage(...) return cmi.damage_calculator(...) end
--[[ A set of position finding utilities for rotatable nodes: * wallmounter * facedir --]] local mounts = { y = { [-1] = {x="x",y="y",z="z"}, [1] = {x="x",y="-y",z="-z"}, }, x = { [-1] = {x="z",y="x",z="y"}, [1] = {x="-z",y="-x",z="y"}, }, z = { [-1] = {x="-x",y="z",z="y"}, [1] = {x="x",y="-z",z="y"}, }, } -- Returns the mapping matrix for each possible dir -- dir - dir in the form {y=-2} circuits.dir_to_mount = function(dir) if dir.x ~= 0 then return mounts.x[dir.x] elseif dir.y ~= 0 then return mounts.y[dir.y] elseif dir.z ~= 0 then return mounts.z[dir.z] end return nil end -- Applies tranformation in the form in mounts matrix -- rot - mapping matrix local function transform_pos(pos,rot) local ret = {} for orig,trans in pairs(rot) do local axis,dir = "", 1 if trans == "x" or trans == "y" or trans == "z" then axis = trans else dir = -1 if trans == "-x" then axis = "x" elseif trans == "-y" then axis = "y" elseif trans == "-z" then axis = "z" end end ret[orig] = pos[axis] * dir end return ret end -- Reverses the transformation applied by transform_pos -- rot - mapping matrix local function reverse_transform(pos,rot) local ret = {} for orig,trans in pairs(rot) do local axis,dir = "", 1 if trans == "x" or trans == "y" or trans == "z" then axis = trans else dir = -1 if trans == "-x" then axis = "x" elseif trans == "-y" then axis = "y" elseif trans == "-z" then axis = "z" end end ret[axis] = pos[orig] * dir end return ret end -- Converts a wallmounted position to a relative pos -- wallmount - param of wallmounted node -- npos - pos of wallmounted node -- pos - real pos of node circuits.pos_wallmount_relative = function(wallmount,npos,pos) local diff = vector.subtract(pos,npos) local rot = circuits.dir_to_mount(minetest.wallmounted_to_dir(wallmount)) return transform_pos(diff,rot) end -- Converts wallmounted relative pos into real pos -- wallmount - param of wallmounted node -- npos - pos of wallmouned node -- rpos - relative pos circuits.wallmount_real_pos = function(wallmount,npos,rpos) local rot = circuits.dir_to_mount(minetest.wallmounted_to_dir(wallmount)) return vector.add(reverse_transform(rpos,rot),npos) end local axis_dirs = { [0] = {x=0,y=-1,z=0}, {x=0,y=0,z=-1}, {x=0,y=0,z=1}, {x=-1,y=0,z=0}, {x=1,y=0,z=0}, {x=0,y=1,z=0}, } local rotations = { [axis_dirs[0]] = { [0] = {x="x",y="y",z="z"}, [1] = {x="-z",y="y",z="x"}, [2] = {x="-x",y="y",z="-z"}, [3] = {x="z",y="y",z="-x"}, }, [axis_dirs[1]] = { [0] = {x="x",y="z",z="-y"}, [1] = {x="y",y="z",z="x"}, [2] = {x="-x",y="z",z="y"}, [3] = {x="-y",y="z",z="-x"}, }, [axis_dirs[2]] = { [0] = {x="x",y="-z",z="y"}, [1] = {x="-y",y="-z",z="x"}, [2] = {x="-x",y="-z",z="-y"}, [3] = {x="y",y="-z",z="-x"}, }, [axis_dirs[3]] = { [0] = {x="-y",y="x",z="z"}, [1] = {x="-z",y="x",z="-y"}, [2] = {x="y",y="x",z="-z"}, [3] = {x="z",y="x",z="y"}, }, [axis_dirs[4]] = { [0] = {x="y",y="-x",z="z"}, [1] = {x="-z",y="-x",z="y"}, [2] = {x="-y",y="-x",z="-z"}, [3] = {x="z",y="-x",z="-y"}, }, [axis_dirs[5]] = { [0] = {x="-x",y="-y",z="z"}, [1] = {x="-z",y="-y",z="-x"}, [2] = {x="x",y="-y",z="-z"}, [3] = {x="z",y="-y",z="x"}, }, } -- Returns the vertical axis and axis transformations of a facedir node circuits.facedir_to_dir = function(facedir) local axis_dir = axis_dirs[math.floor(facedir / 4)] local rotation = facedir % 4 return table.copy(axis_dir),table.copy(rotations[axis_dir][rotation]) end -- Transforms pos to pos relative to a facedir node -- facedir - param of facedir node -- npos - pos of facedir node -- pos - real pos circuits.pos_facedir_relative = function(facedir,npos,pos) local diff = vector.subtract(pos,npos) local _,rot = circuits.facedir_to_dir(facedir) return transform_pos(diff,rot) end -- Transforms a real pos into a pos relative to facedir node -- facedir - param of facedir node -- npos - pos of facedir node -- rpos - real pos circuits.facedir_real_pos = function(facedir,npos,rpos) local _,rot = circuits.facedir_to_dir(facedir) return vector.add(reverse_transform(rpos,rot),npos) end circuits.relative_pos = function(node,pos) return vector.subtract(pos,node) end circuits.relative_real_pos = function(node,rpos) return vector.add(node,rpos) end circuits.invert_relative = function(dir) return vector.multiply(dir, -1) end circuits.rpos_is_dir = function(rpos) local mag if rpos.x ~= 0 then if rpos.y ~= 0 or rpos.z ~= 0 then return nil end mag = rpos.x elseif rpos.y ~= 0 then if rpos.z ~= 0 then return nil end mag = rpos.y elseif rpos.z ~= 0 then mag = rpos.z end if mag then return vector.divide(rpos, math.abs(mag)) end return nil end -- Takes two npos and returns the rpos for a, relative to -- any rotation a might have -- a - npos a -- b - pos b circuits.rot_relative_pos = function(a, b) local a_cd = circuits.get_circuit_def(a.node.name) if a_cd.rot == "wallmounted" then return circuits.pos_wallmount_relative(a.node.param2, a, b) elseif a_cd.rot == "facedir" then return circuits.pos_facedir_relative(a.node.param2, a, b) else return circuits.relative_pos(a, b) end end -- Takes two one npos and an rpos, and returns the real pos, relative to -- any rotation a might have -- a - npos a -- rpos - rpos (b) circuits.rot_relative_real_pos = function(a, rpos) local a_cd = circuits.get_circuit_def(a.node.name) if a_cd.rot == "wallmounted" then return circuits.wallmount_real_pos(a.node.param2, a, rpos) elseif a_cd.rot == "facedir" then return circuits.facedir_real_pos(a.node.param2, a, rpos) else return circuits.relative_real_pos(a, rpos) end end --[[ -- A set of basic connection configs for use -- in node defs --]] circuits.local_area = { x = {1, -1}, y = {1, -1}, z = {1, -1} } circuits.behind = { y = {0, -2} }
-- An implementation of buffered reading data from an arbitrary binary file. -- -- Copyright (C) 2020-2022 LuaVela Authors. See Copyright Notice in COPYRIGHT -- Copyright (C) 2015-2020 IPONWEB Ltd. See Copyright Notice in COPYRIGHT local assert = assert local ffi = require 'ffi' local bit = require 'bit' local ffi_C = ffi.C local band = bit.band local BUFFER_SIZE = 10 * 1024 * 1024 -- 10 megabytes local M = {} ffi.cdef[[ void *memcpy(void *, const void *, size_t); typedef struct FILE_ FILE; FILE *fopen(const char *, const char *); size_t fread(void *, size_t, size_t, FILE *); int feof(FILE *); int fclose(FILE *); ]] local function _read_stream(reader, n) local free_size local tail_size = reader._end - reader._pos if tail_size >= n then -- Enough data to satisfy the request of n bytes... return true end -- ...otherwise carry tail_size bytes from the end of the buffer -- to the start and fill up free_size bytes with fresh data. -- tail_size < n <= free_size (see assert below) ensures that -- we don't copy overlapping memory regions. -- reader._pos == 0 means filling buffer for the first time. free_size = reader._pos > 0 and reader._pos or n assert(n <= free_size, 'Internal buffer is large enough') if tail_size ~= 0 then ffi_C.memcpy(reader._buf, reader._buf + reader._pos, tail_size) end local bytes_read = ffi_C.fread( reader._buf + tail_size, 1, free_size, reader._file ) reader._pos = 0 reader._end = tail_size + bytes_read return reader._end - reader._pos >= n end function M.read_octet(reader) if not _read_stream(reader, 1) then return nil end local oct = reader._buf[reader._pos] reader._pos = reader._pos + 1 return oct end function M.read_octets(reader, n) if not _read_stream(reader, n) then return nil end local octets = ffi.string(reader._buf + reader._pos, n) reader._pos = reader._pos + n return octets end function M.read_uleb128(reader) local value = ffi.new('uint64_t', 0) local shift = 0 repeat local oct = M.read_octet(reader) if oct == nil then break end -- Alas, bit library works only with 32-bit arguments: local oct_u64 = ffi.new('uint64_t', band(oct, 0x7f)) value = value + oct_u64 * (2 ^ shift) shift = shift + 7 until band(oct, 0x80) == 0 return tonumber(value) end function M.read_string(reader) local len = M.read_uleb128(reader) return M.read_octets(reader, len) end function M.eof(reader) local sys_feof = ffi_C.feof(reader._file) if sys_feof == 0 then return false end -- ...otherwise return true only we have reached the end of the buffer: return reader._pos == reader._end end function M.new(fname) local file = ffi_C.fopen(fname, 'rb') if file == nil then error(string.format('fopen, errno: %d', ffi.errno())) end local finalizer = function(f) if ffi_C.fclose(f) ~= 0 then error(string.format('fclose, errno: %d', ffi.errno())) end ffi.gc(f, nil) end local reader = setmetatable({ _file = ffi.gc(file, finalizer), _buf = ffi.new('uint8_t[?]', BUFFER_SIZE), _pos = 0, _end = 0, }, {__index = M}) _read_stream(reader, BUFFER_SIZE) return reader end return M
CaveRDM = {} --// Default //-- CaveRDM.WeaponProtection = true -- Enable blacklisted weapons CaveRDM.TriggersProtection = true -- Enable blacklisted events CaveRDM.WordsProtection = true -- Enable blacklisted words CaveRDM.GiveWeaponsProtection = true -- Enable give weapon CaveRDM.ExplosionProtection = true -- Enable blacklisted explosions CaveRDM.GiveWeaponAsPickupProtection = false -- Give Weapons as pickup CaveRDM.DamageModifierDetection = true -- banning people that are trying to change damage scale CaveRDM.InvisibilityDetection = true -- people cant be invisible when this is enabled CaveRDM.SpectateDetection = true -- banning people that trying to spectate CaveRDM.PickupDetection = true -- deleting pickups like armor and med kits CaveRDM.AntiBlips = true -- Detecting people that are trying to use player blips CaveRDM.AntiSpectate = true -- Detecting people that are trying to spectate people CaveRDM.AntiESX = false -- Only enable this on vrp servers! --// Webhook //-- CaveRDM.LogWebhook = "https://ptb.discord.com/api/webhooks/xxxxxxxxxxxxxxxx" -- your webhook here. CaveRDM.ConnectLogs = "https://ptb.discord.com/api/webhooks/xxxxxxxxxxxxxxx" -- your webhook here to logs connect CaveRDM.BanReason = "Hello, nice to meet you, can you stop cheating? :) \n https://discord.gg/sokin" -- you can edit this uwu CaveRDM.MaxWeaponAmmo = 99999 -- max weapon ammo CaveRDM.DisableAllWeapons = false -- removing all weapons from players CaveRDM.DisableAllUnits = false -- deleting all units on the server --// ClearPedTasksImmediately //-- CaveRDM.ClearPedTasksImmediatelyDetection = true -- Automatically detect ClearPedTasksImmediately (detect cheaters that are kicking out of vehicles other players) NEW! CaveRDM.ClearPedTasksImmediatelyKick = false -- kick CaveRDM.ClearPedTasksImmediatelyBan = true -- ban --// Blacklisted Commands //-- CaveRDM.BlacklistedCommands = { '//', 'killmenu', 'dd' } --// Blacklisted Explosions //-- CaveRDM.BlockedExplosions = { 0, -- Grenade 1, -- GrenadeLauncher 2, -- C4 3, -- Molotov 4, -- Rocket 5, --TankShell 6, -- Hi_Octane 7, -- Car --8, -- Plance --9, -- PetrolPump 12, -- Dir_Flam --14, -- Dir_Gas_Canister 15, -- Boat 16, --Ship_Destroy 17, --Truck 18, -- Bullet 19, -- SmokeGrenadeLauncher 20, -- SmokeGrenade --21, -- BZGAS 22, -- flare 23,--Gas_Canister 24, --Extinguisher --25, --Programmablear 26, -- Train 27, --Barrel 28, -- PROPANE --29, -- Blimp --30, -- Dir_Flame_Explode 31, -- Tanker 32, -- PlaneRocket- 33, -- VehicleBullet 34, -- Gas_Tank 35, -- FireWork 36, -- SnowBall 37, -- ProxMine 38, -- Valkyrie_Cannon 70 -- AutoMizer } --// BlacklistedWords //-- CaveRDM.BlacklistedWords = { "/ooc kogusz menu! Buy at https://discord.gg/BbDMhJe", "/ooc Baggy Menu! Buy at https://discord.gg/AGxGDzg", "/ooc Desudo Menu! Buy at https://discord.gg/hkZgrv3", "/ooc Yo add me Fallen#0811", "BAGGY menu <3 https://discord.gg/AGxGDzg", "KoGuSzMENU <3 https://discord.gg/BbDMhJe", "KoGuSzMENU <3 https://discord.gg/BM5zTvA", "Desudo menu <3 https://discord.gg/hkZgrv3", "Yo add me Fallen#0811", "Lynx 8 ~ www.lynxmenu.com", "Lynx 7 ~ www.lynxmenu.com", "lynxmenu.com", "www.lynxmenu.com", "You got raped by Lynx 8", "^0Lynx 8 ~ www.lynxmenu.com", "^0AlphaV ~ 5391", "^0You got raped by AlphaV", "^0TITO MODZ - Cheats and Anti-Cheat", "^0https://discord.gg/AGxGDzg", "^0https://discord.gg/hkZgrv3", "You just got fucked mate", "Add me Fallen#0811", "Desudo; Plane#000", "BAGGY; baggy#6875", "SKAZAMENU", "skaza", "aries", "killmenu", "youtube.com", 'Desudo', 'Brutan', 'EulenCheats', "discord.gg/", "lynxmenu", "HamHaxia", "ksox", "Ham Mafia", "www.renalua.com", "Fallen#0811", "Rena 8", "HamHaxia", "Ham Mafia", "Xanax#0134", ">:D Player Crash", "discord.gg", "34ByTe Community", "mixas", "lynxmenu.com", "Anti-LRAC", "Baran#8992", "iLostName#7138", "85.190.90.118", "Melon#1379", "hammafia.com", "AlphaV ~ 5391", "vjuton.pl", "Soviet Bear", "XARIES", "xaries", "dc.xaries.pl", "aries", "aries.pl", "youtube.com/c/Aries98/", "Aries98", "yo many", "rape", "dezet", "333", "333GANG" } --// Blacklisted Weapons //-- CaveRDM.BlacklistedWeapons = { "WEAPON_RAYPISTOL", "WEAPON_RAYCARBINE", "WEAPON_ASSAULTSHOTGUN", "WEAPON_SPECIALCARBINE", "WEAPON_COMBATMG", "WEAPON_COMBATMG_MK2", "WEAPON_MG", "WEAPON_HEAVYSNIPER", "WEAPON_HEAVYSNIPER_MK2", "WEAPON_MARKSMANRIFLE", "WEAPON_MARKSMANRIFLE_MK2", "WEAPON_MINIGUN", "WEAPON_RPG", "WEAPON_SMG", "WEAPON_COMPACTLAUNCHER", "WEAPON_HOMINGLAUNCHER", "WEAPON_RAILGUN", "WEAPON_FIREWORK", "WEAPON_GRENADELAUNCHER_SMOKE", "WEAPON_GRENADELAUNCHER", "WEAPON_RPG", "WEAPON_RAYMINIGUN", "WEAPON_GRENADE", "WEAPON_PIPEBOMB", "WEAPON_PROXMINE", "WEAPON_MOLOTOV", "WEAPON_STICKYBOMB", "VEHICLE_WEAPON_ROTORS", "VEHICLE_WEAPON_TANK", "VEHICLE_WEAPON_SPACE_ROCKET", "VEHICLE_WEAPON_PLANE_ROCKET", "VEHICLE_WEAPON_PLAYER_LAZER", "VEHICLE_WEAPON_PLAYER_LASER", "VEHICLE_WEAPON_PLAYER_BULLET", "VEHICLE_WEAPON_PLAYER_BUZZARD", "VEHICLE_WEAPON_PLAYER_HUNTER", "VEHICLE_WEAPON_ENEMY_LASER", "VEHICLE_WEAPON_SEARCHLIGHT", "VEHICLE_WEAPON_RADAR", "VEHICLE_WEAPON_TURRET_INSURGENT", "VEHICLE_WEAPON_TURRET_TECHNICAL", "VEHICLE_WEAPON_NOSE_TURRET_VALKYRIE", "VEHICLE_WEAPON_PLAYER_SAVAGE", "VEHICLE_WEAPON_TURRET_LIMO", "VEHICLE_WEAPON_CANNON_BLAZER", "VEHICLE_WEAPON_TURRET_BOXVILLE", "VEHICLE_WEAPON_RUINER_BULLET", "PICKUP_VEHICLE_WEAPON_ASSAULTSMG", "PICKUP_VEHICLE_WEAPON_PISTOL50", "PICKUP_AMMO_BULLET_MP", "PICKUP_AMMO_MISSILE_MP", "PICKUP_AMMO_GRENADELAUNCHER_MP", "PICKUP_WEAPON_ASSAULTRIFLE", "PICKUP_WEAPON_CARBINERIFLE", "PICKUP_WEAPON_ADVANCEDRIFLE", "PICKUP_WEAPON_MG", "PICKUP_WEAPON_COMBATMG", "PICKUP_WEAPON_SNIPERRIFLE", "PICKUP_WEAPON_HEAVYSNIPER", "PICKUP_WEAPON_MICROSMG", "PICKUP_WEAPON_SMG", "PICKUP_ARMOUR_STANDARD", "PICKUP_WEAPON_RPG", "PICKUP_WEAPON_MINIGUN", "PICKUP_HEALTH_STANDARD", "PICKUP_WEAPON_SAWNOFFSHOTGUN", "PICKUP_WEAPON_ASSAULTSHOTGUN", "PICKUP_WEAPON_GRENADE", "PICKUP_WEAPON_MOLOTOV", "PICKUP_WEAPON_SMOKEGRENADE", "PICKUP_WEAPON_STICKYBOMB", "PICKUP_WEAPON_APPISTOL", "PICKUP_WEAPON_GRENADELAUNCHER", "PICKUP_MONEY_VARIABLE", "PICKUP_WEAPON_STUNGUN", "PICKUP_WEAPON_FIREEXTINGUISHER", "PICKUP_WEAPON_PETROLCAN", "PICKUP_WEAPON_GolfClub", "PICKUP_WEAPON_CROWBAR", "PICKUP_HANDCUFF_KEY", "PICKUP_CUSTOM_SCRIPT", "PICKUP_CAMERA", "PICKUP_PORTABLE_PACKAGE", "PICKUP_PORTABLE_CRATE_UNFIXED", "PICKUP_PORTABLE_CRATE_UNFIXED_INCAR", "PICKUP_MONEY_CASE", "PICKUP_MONEY_WALLET", "PICKUP_MONEY_PURSE", "PICKUP_MONEY_DEP_BAG", "PICKUP_MONEY_MED_BAG", "PICKUP_MONEY_PAPER_BAG", "PICKUP_MONEY_SECURITY_CASE", "PICKUP_VEHICLE_WEAPON_APPISTOL", "PICKUP_VEHICLE_WEAPON_PISTOL", "PICKUP_VEHICLE_WEAPON_GRENADE", "PICKUP_VEHICLE_WEAPON_MOLOTOV", "PICKUP_VEHICLE_WEAPON_SMOKEGRENADE", "PICKUP_VEHICLE_WEAPON_STICKYBOMB", "PICKUP_VEHICLE_HEALTH_STANDARD", "PICKUP_VEHICLE_ARMOUR_STANDARD", "PICKUP_VEHICLE_WEAPON_MICROSMG", "PICKUP_VEHICLE_WEAPON_SMG", "PICKUP_VEHICLE_WEAPON_SAWNOFF", "PICKUP_VEHICLE_CUSTOM_SCRIPT", "PICKUP_VEHICLE_MONEY_VARIABLE", "PICKUP_SUBMARINE", "PICKUP_HEALTH_SNACK", "PICKUP_AMMO_MG", "PICKUP_AMMO_GRENADELAUNCHER", "PICKUP_AMMO_RPG", "PICKUP_AMMO_MINIGUN", "PICKUP_WEAPON_BULLPUPRIFLE", "PICKUP_WEAPON_BOTTLE", "PICKUP_WEAPON_SNSPISTOL", "PICKUP_WEAPON_GUSENBERG", "PICKUP_WEAPON_SPECIALCARBINE", "PICKUP_WEAPON_DAGGER", "PICKUP_WEAPON_FIREWORK", "PICKUP_WEAPON_MUSKET", "PICKUP_AMMO_FIREWORK", "PICKUP_AMMO_FIREWORK_MP", "PICKUP_PORTABLE_DLC_VEHICLE_PACKAGE", "PICKUP_WEAPON_HEAVYSHOTGUN", "PICKUP_WEAPON_MARKSMANRIFLE", "PICKUP_GANG_ATTACK_MONEY", "PICKUP_WEAPON_PROXMINE", "PICKUP_WEAPON_HOMINGLAUNCHER", "PICKUP_AMMO_HOMINGLAUNCHER", "PICKUP_WEAPON_FLAREGUN", "PICKUP_AMMO_FLAREGUN", "PICKUP_WEAPON_MARKSMANPISTOL", } --// Blacklisted Models //-- CaveRDM.BlacklistedModels = { -- Peds/Vehicles --VEHICLES "RHINO", "KHANJALI", "HUNTER", "CARGOBOB", "CARGOBOB2", "AIRBUS", "CARGOBOB3", "CARGOBOB4", "AKULA", "CHERNOBOG", "THRUSTER", "MINITANK", "APC", "DUMP", "LAZER", "TUG", "BUS", "CARBUS", "JET", "HYDRA", "CARGOPLANE", "TITAN", "rhino", "apc", "hydra", "blimp", "blimp2", "blimp3", "avenger", "besra", "bombushka", "lazer", "strikeforce", "insurgent", "insurgent3", "insurgent2", "menacer", "dune4", "dune5", "caracara", "revolter", "barracks", "barracks2", "barracks3", "barrage", "chernobog", "crusader", "halftrack", "khanjali", "minitank", "scarab", "scarab2", "scarab3", "thruster", "trailersmall2", "vetir", "savage", "hunter", "akula", "buzzard", "annihilator", "riot2", "dinghy5", "kosatka", "patrolboat", "avisa", "submersible2", "submersible", "skylift", "bruiser3", "technical", "technical12", "technical13", "zhaba", "cutter", "dump", "cargoplane", "bruiser2", -- PEDS 's_m_y_swat_01', 'u_m_y_zombie_01', 'a_m_o_acult_01', 'ig_wade', 's_m_y_hwaycop_01', 'A_M_Y_ACult_01', 's_m_m_movalien_01', 's_m_m_movallien_01', 'u_m_y_babyd', 'CS_Orleans', 'A_M_Y_ACult_01', 'S_M_M_MovSpace_01', 'U_M_Y_Zombie_01', 's_m_y_blackops_01', 'a_f_y_topless_01', 'a_c_boar', 'a_c_cat_01', 'a_c_chickenhawk', 'a_c_chimp', 's_f_y_hooker_03', 'a_c_chop', 'a_c_cormorant', 'a_c_cow', 'a_c_coyote', 'a_c_crow', 'a_c_dolphin', 'a_c_fish', 's_f_y_hooker_01', 'a_c_hen', 'a_c_humpback', 'a_c_husky', 'a_c_killerwhale', 'a_c_mtlion', 'a_c_pigeon', 'a_c_poodle', 'a_c_pug', 'a_c_rabbit_01', 'a_c_rat', 'a_c_retriever', 'a_c_rhesus', 'a_c_rottweiler', 'a_c_sharkhammer', 'a_c_sharktiger', 'a_c_shepherd', 'a_c_stingray', 'a_c_westy', 'CS_Orleans', 'p_crahsed_heli_s', 'u_m_m_jesus_01', 'u_m_y_imporage', 'u_m_y_juggernaut_01', 'mp_m_weapexp_01', 'ig_chef2', 'mp_m_bogdangoon', 'a_m_y_hasjew_01', } CaveRDM.WhitelistedProps = { "", -- does not work :/ } --// Blacklisted Events //-- CaveRDM.BlacklistedEvents = { "esx_vehicleshop:setVehicleOwned", "esx_mafiajob:confiscatePlayerItem", "vrp_slotmachine:server:2", "Banca:deposit", "esx_jobs:caution", "give_back", "esx_fueldelivery:pay", "esx_carthief:pay", "esx_godirtyjob:pay", "esx_pizza:pay", "antilynx8:anticheat", "antilynxr6:detection", "esx_ranger:pay", "esx_garbagejob:pay", "esx_truckerjob:pay", "redst0nia:checking", "AdminMenu:giveBank", "AdminMenu:giveCash", "esx_gopostaljob:pay", "esx_banksecurity:pay", "esx_slotmachine:sv:2", "NB:recruterplayer", "esx_billing:sendBill", "esx_jailer:sendToJail", "esx_jail:sendToJail", "js:jailuser", "esx-qalle-jail:jailPlayer", "esx_dmvschool:pay", "OG_cuffs:cuffCheckNearest", "CheckHandcuff", "cuffServer", "PICKUP_HEALTH_STANDARD", "cuffGranted", "police:cuffGranted", "esx_handcuffs:cuffing", "esx_policejob:handcuff", "esx_skin:responseSaveSkin", "esx_dmvschool:addLicense", "esx_mechanicjob:startCraft", "esx_drugs:startHarvestWeed", "esx_drugs:startTransformWeed", "esx_drugs:startSellWeed", "esx_drugs:startHarvestCoke", "esx_drugs:startTransformCoke", "esx_drugs:startSellCoke", "esx_drugs:startHarvestMeth", "esx_drugs:startTransformMeth", "esx_drugs:startSellMeth", "esx_drugs:startHarvestOpium", "esx_drugs:startSellOpium", "esx_drugs:startTransformOpium", "esx_blanchisseur:startWhitening", "esx_drugs:stopHarvestCoke", "esx_drugs:stopTransformCoke", "esx_drugs:stopSellCoke", "esx_drugs:stopHarvestMeth", "esx_drugs:stopTransformMeth", "esx_drugs:stopSellMeth", "esx_drugs:stopHarvestWeed", "esx_drugs:stopTransformWeed", "esx_drugs:stopSellWeed", "esx_drugs:stopHarvestOpium", "esx_drugs:stopTransformOpium", "esx_drugs:stopSellOpium", "esx_society:openBossMenu", "esx_jobs:caution", "esx_tankerjob:pay", "esx_vehicletrunk:giveDirty", "gambling:spend", "AdminMenu:giveDirtyMoney", "esx_moneywash:deposit", "esx_moneywash:withdraw", "mission:completed", "99kr-burglary:addMoney", "esx_jailer:unjailTime", "esx_ambulancejob:revive", "DiscordBot:playerDied", "hentailover:xdlol", "antilynx8:anticheat", "antilynxr6:detection", "esx:getSharedObject", -- anti injection! "esx_society:getOnlinePlayers", "antilynx8r4a:anticheat", "antilynxr4:detect", "js:jailuser", "ynx8:anticheat", "lynx8:anticheat", "adminmenu:allowall", "h:xd", "ljail:jailplayer", "adminmenu:setsalary", "adminmenu:cashoutall", "paycheck:bonus", "HCheat:TempDisableDetection", "esx_drugs:pickedUpCannabis", "esx_drugs:processCannabis", "esx-qalle-hunting:reward", "esx-qalle-hunting:sell", "esx_mecanojob:onNPCJobCompleted", "BsCuff:Cuff696999", "esx_carthief:alertcops", "mellotrainer:adminTempBan", "mellotrainer:adminKick", "esx_society:putVehicleInGarage", }
--[[ openwrt-dist-luci: RedSocks2 ]]-- local m, s, o if luci.sys.call("pidof redsocks2 >/dev/null") == 0 then m = Map("redsocks2", translate("RedSocks2"), translate("RedSocks2 is running")) else m = Map("redsocks2", translate("RedSocks2"), translate("RedSocks2 is not running")) end -- General Setting s = m:section(TypedSection, "redsocks2", translate("General Setting")) s.anonymous = true o = s:option(Flag, "enable", translate("Enable")) o.default = 1 o.rmempty = false o = s:option(Value, "local_port", translate("Local Port")) o.datatype = "port" o.rmempty = false o = s:option(ListValue, "proxy_type", translate("Proxy Type")) o:value("socks4", translate("SOCKS4")) o:value("socks5", translate("SOCKS5")) o:value("http-connect", translate("HTTP-CONNECT")) o:value("http-relay", translate("HTTP-RELAY")) o:value("direct", translate("DIRECT")) o.rmempty = false o = s:option(Value, "proxy_ip", translate("Proxy IP")) o.datatype = "ipaddr" o.rmempty = false o = s:option(Value, "proxy_port", translate("Proxy Port")) o.datatype = "port" o.rmempty = false o = s:option(ListValue, "auto_proxy", translate("Auto Proxy")) o:value("1", translate("Enable")) o:value("0", translate("Disable")) o.default = 1 o.rmempty = false o = s:option(Value, "timeout", translate("Wait Timeout")) o.datatype = "uinteger" o.default = 5 o:depends("auto_proxy", 1) return m
-- echo command line arguments for i=0,#arg do print(i,arg[i]) end
local function pchar_to_char(str) return string.char(tonumber(str, 16)) end local function decodeURIComponent(str) return (str:gsub("%%(%x%x)", pchar_to_char)) end function Log(lm) vlc.msg.info("[dailymotion.lua] " .. lm) end local function trim1(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end local function isdef(p,...) if not p then return false else local tb = p for i,v in ipairs(arg) do if tb[v]==nil then return false else tb = tb[v] end end return true end end function find_table_field(tbl,fld,JSON) for k, v in pairs( tbl ) do local h = nil if type(v)=="table" then h = v elseif type(v)=="string" then err,h = pcall(function() return JSON:decode(decodeURIComponent(v)) end) if err==false then h = nil end end if type(h)=="table" then local rv = find_table_field(h,fld,JSON) if rv~=nil then return rv end elseif k==fld then return v end end return nil end function LogT(t,lev) local sp = string.rep(" ", 4*lev) for k, v in pairs( t ) do if type(v)=="table" then Log(sp .. tostring(k) .. " = {") LogT(v,lev+1) Log(sp .. "}") else Log(sp .. tostring(k) .. " = " .. tostring(v)) end end end --"C:\Program Files (x86)\VideoLAN\VLC\vlc.exe" --extraintf=http:logger --verbose=6 --file-logging --logfile=D:\vlc-log.txt "https://httpbin.org/get?user=SuperflyVideomaker&id=655842574572765" function parse() local info = debug.getinfo(1,'S'); local kk,jj,ll = string.match(string.sub(info.source,2), "(.-)([^\\/]-%.?([^%.\\/]*))$") if string.match( vlc.path, "dailymotion.com/video") then a = string.match(vlc.path, 'video/([^?/]+)') if a then return {{path = "https://www.dailymotion.com/player/metadata/video/".. a}} else vlc.msg.err( "Couldn't extract dailymotion video URL, please check for updates to this script" ) return {}; end end Log(kk,jj,ll); JSON = (loadfile (kk.."JSON.lua"))() -- one-time load of the routines local json = '' while true do local line = vlc.readline() if line then json = json .. line else break end end local pall = JSON:decode(json) local title = nil local artist = nil if isdef(pall,"owner","screenname") then artist = pall.owner.screenname end if isdef(pall,"title") then title = pall.title end if isdef(pall,"stream_chromecast_url") then return {{path = pall.stream_chromecast_url, artist = artist, title = title}} end vlc.msg.err( "Couldn't extract dailymotion video URL, please check for updates to this script" ) return {}; end -- Probe function. function probe() Log("sono qui "..vlc.path) if vlc.access ~= "http" and vlc.access ~= "https" then return false end return string.match( vlc.path, "dailymotion.com/video" ) or string.match( vlc.path, "dailymotion.com/player/metadata/video" ) end
local Prop = {} Prop.Name = "Shady Apartments 2-B" Prop.Cat = "Apartments" Prop.Price = 750 Prop.Doors = { Vector( -3880.000000, -7329.000000, -13654.700195 ), Vector( -4272.000000, -7329.000000, -13657.000000 ), Vector( -4184.000000, -7249.000000, -13657.000000 ), } GM.Property:Register( Prop )
require('dealer') require('constants') if dealer.buy_in("POV_DEALER_SPEECH_TEXT_SID", "POV_DEALER_NSF_MESSAGE_SID", "POV_DEALER_DECLINE_MESSAGE_SID", 2) then local bet_val = tonumber(add_char_message("POV_DEALER_WHICH_NUMBER_SID")) if bet_val >= 1 and bet_val <= 6 then add_message_with_pause("POV_DEALER_ROLLING_SID") local actual_val = RNG_range(1, 6) add_message_direct(tostring(actual_val) .. "!") if bet_val == actual_val then add_message("DEALER_WIN_SID") add_object_to_player_tile(CURRENCY_ID, 6) else add_message("DEALER_LOSE_SID") end else clear_and_add_message("POV_DEALER_INVALID_VALUE_SID") add_object_to_player_tile(CURRENCY_ID, 2) end end
object_mobile_nym_themepark_grenz_zittoun = object_mobile_shared_nym_themepark_grenz_zittoun:new { } ObjectTemplates:addTemplate(object_mobile_nym_themepark_grenz_zittoun, "object/mobile/nym_themepark_grenz_zittoun.iff")
local constants = require(".lua.common.constants") local logger = require(".lua.common.logger").new("request_status_cache.lua") local util = require(".lua.common.util") --local redis_service = require(".lua.service.redis_connection_manager").get(constants.REDIS_CLUSTER_DPATH) --~ Sets Key Value Pair for Bucket local function set(key, value) --Currenlty it is seen that in the timer context the module is not preserved --For example reds_service, that is why this is reference at every call. --Since this API is being called in the timer context, the performance impact is not \ --the bottlneck. Need to figure the way of persisting states in timer contexts local redis_service = require(".lua.service.redis_connection_manager").get(constants.REDIS_CLUSTER_DPATH) --TBD Should we get the Old state if present and then log the current v/s previos --state. For now we are logging the new successfull state if value == nil then logger:error("Nil Value Passed for Setting in Request Stats Cache") return false end local result = true value["version"] = 1.0 result = redis_service:hmset(key, value) result = redis_service:hincrby(key, "epoch", 1) return result end return { set = set, }
local zmq = require "lzmq" local context = zmq.init(1) local sub = context:socket(zmq.SUB) sub:set_subscribe("") sub:bind("tcp://*:6677") total = 0 count = 0 while true do header, body = sub:recvx() total = total + header:len() + body:len() count = count + 1 if count % 40000 == 0 then print(string.format("%d bytes received", total)) end end context:term()
global.registered_entities = {} global.stations_count = global.stations_count or {} global.constructrons_count = global.constructrons_count or {} --- for s, surface in pairs(game.surfaces) do global.stations_count[surface.index] = 0 local stations = surface.find_entities_filtered { name = "service_station", force = "player", surface = surface.name } for k, station in pairs(stations) do local unit_number = station.unit_number if not global.service_stations[unit_number] then global.service_stations[unit_number] = station end local registration_number = script.register_on_entity_destroyed(station) global.registered_entities[registration_number] = { name = "service_station", surface = surface.index } global.stations_count[surface.index] = global.stations_count[surface.index] + 1 end game.print('Registered ' .. global.stations_count[surface.index] .. ' stations on ' .. surface.name .. '.') end --- for s, surface in pairs(game.surfaces) do global.constructrons_count[surface.index] = 0 local constructrons = surface.find_entities_filtered { name = "constructron", force = "player", surface = surface.name } for k, constructron in pairs(constructrons) do local unit_number = constructron.unit_number if not global.constructrons[unit_number] then global.constructrons[unit_number] = constructron end local registration_number = script.register_on_entity_destroyed(constructron) global.registered_entities[registration_number] = { name = "constructron", surface = surface.index } global.constructrons_count[surface.index] = global.constructrons_count[surface.index] + 1 end game.print('Registered ' .. global.constructrons_count[surface.index] .. ' constructrons on ' .. surface.name .. '.') end
local visible = ECS.Component(function(e, bool) e.visible = bool end) return visible
--===================================================================== -- State code --===================================================================== function AI:Pushing( state ) if ( self.hero:GetHealth()/self.hero:GetMaxHealth() ) < 0.3 then self.mainStM:GotoState( 'Backing' ) MoveUnitTo( self.hero, self.FOUNTAIN_POS ) AI_Log( 'Going back go base!' ) return end if not self.hero:IsAlive() then self.mainStM:GotoState( 'Buying' ) return end self.pushStates:Think() end function AI:Backing( state ) if DistanceUnitTo( self.hero, self.FOUNTAIN_POS ) < 50 then self.mainStM:GotoState( 'Buying' ) return end if not self.hero:IsAlive() then self.mainStM:GotoState( 'Buying' ) return end MoveUnitTo( self.hero, self.FOUNTAIN_POS ) end function AI:Buying( state ) if ( self.hero:GetHealth()/self.hero:GetMaxHealth() ) > 0.85 then self.mainStM:GotoState( 'ToLane' ) AI_Log('Going to lane now.') self:BuyItems() self:GoToLane() return end end function AI:ToLane( state ) if DistanceUnitTo( self.hero, self.NEAR_TOWER_POS ) < 200 then self.mainStM:GotoState( 'Pushing' ) self.pushStates:GotoState( 'Attacking' ) return end MoveUnitTo( self.hero, self.NEAR_TOWER_POS, true ) if not self.hero:IsAlive() then self.mainStM:GotoState( 'Buying' ) return end end --======================================================================================================== --Push states --======================================================================================================== function AI:Attacking( state ) local friendlyCreeps = FindCreeps( self.LANE_CENTER, 1500, DOTA_UNIT_TARGET_TEAM_FRIENDLY, FIND_ANY_ORDER ) local targets = FindTargets( self.hero:GetAbsOrigin(), 4000, DOTA_UNIT_TARGET_TEAM_ENEMY, FIND_CLOSEST ) if #friendlyCreeps < 1 then self.pushStates:GotoState( 'Waiting' ) MoveUnitTo( self.hero, self.NEAR_TOWER_POS ) return end --Attack the closest target if #targets > 0 and state.attackTarget ~= targets[1] then UnitAttackTarget( self.hero, targets[1] ) state.attackTarget = targets[1] end end function AI:Waiting( state ) local friendlyCreeps = FindCreeps( self.LANE_CENTER, 1500, DOTA_UNIT_TARGET_TEAM_FRIENDLY, FIND_ANY_ORDER ) local enemyCreeps = FindCreeps( self.LANE_CENTER, 1500, DOTA_UNIT_TARGET_TEAM_ENEMY, FIND_ANY_ORDER ) local friendlyWavePos = AverageUnitPos( friendlyCreeps ) local enemyWavePos = AverageUnitPos( enemyCreeps ) if DistanceUnitTo( self.hero, friendlyWavePos ) < DistanceUnitTo( self.hero, enemyWavePos ) then self.pushStates:GotoState( 'Attacking' ) return end AggressiveMoveUnitTo( self.hero, self.NEAR_TOWER_POS, true ) end function AI:SafeRegen( state ) if AI_GetGameTime() - state.entryTime > 1.5 then self.pushStates:GotoState( 'Attacking' ) return end if ( AI_GetGameTime() - state.entryTime ) > 1 and ( self.hero:GetHealth()/self.hero:GetMaxHealth() ) <= 0.7 then local bottle = FindItemByName( self.hero, 'item_bottle' ) if bottle ~= nil and bottle:GetCurrentCharges() > 0 and state.bottled == nil then state.bottled = true CastNoTarget( self.hero, bottle ) end end end
ITEM.name = "Browning Hi-Power" ITEM.description= "A semi-automatic pistol chambered for 9x19mm." ITEM.model = "models/weapons/browninghp/w_browninghp.mdl" ITEM.class = "cw_kk_ins2_browninghp" ITEM.weaponCategory = "secondary" ITEM.width = 2 ITEM.height = 1 ITEM.price = 2200 ITEM.weight = 2
local dpdk = require "dpdk" local memory = require "memory" local ts = require "timestamping" local device = require "device" local filter = require "filter" local histo = require "histogram" function master(...) local txPort, rxPort, rate = tonumberall(...) if not txPort or not rxPort then errorf("usage: txPort rxPort [rate (Mpps)]") end rate = rate or 2 local txDev = device.config(txPort, 2, 2) local rxDev = device.config(rxPort, 2, 2) device.waitFor(txDev, rxDev) dpdk.launchLua("loadSlave", txDev, rxDev, txDev:getTxQueue(0), rate, 60) dpdk.launchLua("timerSlave", txDev, rxDev, txDev:getTxQueue(1), rxDev:getRxQueue(1), 60) dpdk.waitForSlaves() end function loadSlave(dev, rxDev, queue, rate, size) local mem = memory.createMemPool(function(buf) buf:getEthernetPacket():fill{ ethType = 0x1234 } end) rxDev:l2Filter(0x1234, filter.DROP) local lastPrint = dpdk.getTime() local startTime = lastPrint local totalSent = 0 local lastTotal = 0 local lastSent = 0 local totalReceived = 0 local bufs = mem:bufArray(31) while dpdk.running() do bufs:alloc(size) for _, buf in ipairs(bufs) do -- this script uses Mpps instead of Mbit (like the other scripts) buf:setDelay(poissonDelay(10^10 / 8 / (rate * 10^6) - size - 24)) end totalSent = totalSent + queue:sendWithDelay(bufs) local time = dpdk.getTime() if time - lastPrint > 1 then local rx = rxDev:getRxStats() totalReceived = totalReceived + rx local mpps = (totalSent - lastTotal) / (time - lastPrint) / 10^6 printf("Sent,packets=%d,rate=%f", totalSent, mpps) printf("Received %d packets, current rate %.2f Mpps", totalReceived, rx / (time - lastPrint) / 10^6) printf("Received,packets=%d,rate=%f", totalReceived, rx / (time-lastPrint) / 10^6) lastTotal = totalSent lastPrint = time end end local time = dpdk.getTime() local mpps = (totalSent) / (time - startTime) / 10^6 printf("TotalSent,packets=%d,rate=%f", totalSent, mpps) printf("TotalReceived,packets=%d", totalReceived) end function timerSlave(txDev, rxDev, txQueue, rxQueue) local mem = memory.createMemPool() local buf = mem:bufArray(1) local rxBufs = mem:bufArray(2) txQueue:enableTimestamps() rxQueue:enableTimestamps() local hist = histo:create() dpdk.sleepMillis(4000) local ptpseq = 0 local timestamps = {} while dpdk.running() do ptpseq = (ptpseq + 1) % 1000000 buf:alloc(60) ts.fillL2Packet(buf[1], ptpseq) -- sync clocks and send ts.syncClocks(txDev, rxDev) txQueue:send(buf) -- increment the wait time when using large packets or slower links local tx = txQueue:getTimestamp(100) if tx then timestamps[ptpseq] = tx dpdk.sleepMicros(500) -- minimum latency to limit the packet rate -- sent was successful, try to get the packet back (max. 10 ms wait time before we assume the packet is lost) local rx = rxQueue:tryRecv(rxBufs, 10000) if rx > 0 then local nummatched = 0 local tsi = 0 for i = 1, rx do if bit.bor(rxBufs[i].ol_flags, dpdk.PKT_RX_IEEE1588_TMST) ~= 0 then nummatched = nummatched + 1 tsi = i end end local seq = ts.readSeq(rxBufs[tsi]) if timestamps[seq] then local delay = (rxQueue:getTimestamp() - timestamps[seq]) * 6.4 timestamps[seq] = nil if nummatched == 1 and delay > 0 and delay < 100000000 then hist:update(delay) end end rxBufs:freeAll() end end end for v, k in hist:samples() do printf("HistSample,delay=%f,count=%d", v.k, v.v) end local samples, sum, average = hist:totals() local lowerQuart, median, upperQuart = hist:quartiles() printf("HistStats,numSamples=%d,sum=%f,average=%f,lowerQuart=%f,median=%f,upperQuart=%f",samples,sum,average,lowerQuart,median,upperQuart) io.stdout:flush() end
-- -- PubNub : History Example -- require "pubnub" require "PubnubUtil" textout = PubnubUtil.textout -- -- INITIALIZE PUBNUB STATE -- pubnub_obj = pubnub.new({ publish_key = "demo", subscribe_key = "demo", secret_key = nil, ssl = nil, origin = "pubsub.pubnub.com" }) -- -- HIDE STATUS BAR -- display.setStatusBar( display.HiddenStatusBar ) -- -- CALL HISTORY FUNCTION -- function history(channel, count, reverse) pubnub_obj:history({ channel = channel, count = count, reverse = reverse, callback = function(response) textout(response) end, error = function (response) textout(response) end }) end -- -- MAIN TEST -- local my_channel = 'hello_world' history( my_channel, 5, false )
local keys = assert(loadfile "LuaScripts/keycode.lua")() local JSON = assert(loadfile "LuaScripts/JSON.lua")() local batBehaviour = {} batBehaviour["instantiate"] = function(params, entity) local p = JSON:decode(params) local self = {} -- Referencias a componentes self.entity = entity self.transform = nil self.rb = nil -- Posicion inicial para resetar el turno self.startPos = nil -- Contador del tiempo desde que cae el pajaro self.time = 0 -- Contador del tiempo que pasa desde que se puede batear hasta que no self.batTime = 0 -- Variable que indica si el jugador ha bateado self.batted = false -- Variable que representa si el jugador tiene un escudo obtenido por un PelotaRebote self.escudo = false -- Fuerza aplicada al pajaro en Y self.strength = 20.0 -- Multiplicador a la fuerza en X respecto a la fuerza en Y self.xFactor = 10.0 -- Tiempo desde que cae el pajaro en el que la fuerza sera maxima self.sweetspot = 3.0 -- Contador de rebotes self.bounces = 0 self.maxBounces = 2 -- Factor para reducir la recuperacion de hueso self.boneFactor = 0.2 -- Segundos en los que se recargara el hueso self.boneRecharge = 5.0 -- Para impedir el hueso antes de batear self.allowBone = false -- Parametros personalizados desde json if p ~=nil then if p.strength ~= nil then self.strength = p.strength end if p.xFactor ~= nil then self.xFactor = p.xFactor end if p.sweetspot ~= nil then self.sweetspot = p.sweetspot end if p.boneFactor ~= nil then self.boneFactor = p.boneFactor end if p.boneRecharge ~= nil then self.boneRecharge = p.boneRecharge end end -- Variable que indica el rango de tiemo en el que se podrá batear -- margen de tiempo de 2 segundos para batear self.range = 1.0 -- Auxiliar para comprobar si pasamos el sweetspot de golpeo self.passHighestStrenght = false; -- Variables para limitar los tiempos entre los que se puede batear self.topLimit = self.sweetspot - self.range self.botLimit = self.sweetspot + self.range return self end batBehaviour["start"] = function(_self, lua) _self.transform = lua:getTransform(_self.entity) local aux = _self.transform:getPosition() _self.startPos = Vector3(aux.x, aux.y, aux.z) _self.rb = lua:getRigidbody(_self.entity) end batBehaviour["update"] = function(_self, lua, deltaTime) local input = lua:getInputManager() if input:mouseButtonPressed() == 1 then -- Controla el bateo dentro del rango de tiempo y su fuerza segun como de cerca se encuentre el golpeo del sweetspot if not _self.batted and (_self.time < _self.botLimit and _self.time > _self.topLimit) then -- Se calcula y se aplica la fuerza en el pajaro y los objetos spawneados local strength = _self.strength * _self.batTime _self.rb:addForce1(Vector3(0, strength, 0), Vector3(0, 0, 0), 1) lua:getLuaSelf(lua:getEntity("gameManager"), "gameManager").modSpawners(true, _self.xFactor * strength) --velocidad en x inicial de los spawners -- La camara pasa a seguir al pajaro local cameraFollow = lua:getLuaSelf(lua:getEntity("defaultCamera"), "followTarget") cameraFollow.setFollow(true) --Añadimos scroll a la textura del skyplane para simular desplazamiento en z lua:getOgreContext():changeMaterialScroll("SkyPlaneMat2", -0.1, 0) lua:getOgreContext():changeMaterialScroll("cesped_MAT", -0.1, 0) lua:playSound("Assets/Music/Impact.wav") _self.batted = true _self.allowBone = true _self.time = 0 -- Controla el uso del hueso de la suerte siempre que tenga carga else if _self.allowBone and _self.time > 0 then _self.rb:addForce1(Vector3(0, _self.strength * _self.boneFactor, 0), Vector3(0, 0, 0), 0) _self.time = _self.time - deltaTime end end else -- Ajuste del tiempo de bateo para usar la fuerza maxima en el sweetspot if not _self.batted then _self.time = _self.time + deltaTime if _self.time < _self.botLimit and _self.time > _self.topLimit then if _self.passHighestStrenght then _self.batTime = _self.batTime - deltaTime else _self.batTime = _self.batTime + deltaTime _self.passHighestStrenght = _self.batTime >= _self.range end end -- Recarga del hueso de la suerte cuando no se usa elseif _self.time < _self.boneRecharge then _self.time = _self.time + deltaTime --print(_self.time) end end end -- Si toca el suelo no puede batear mas y se cambiara el turno batBehaviour["onCollisionEnter"] = function(_self, lua, other) if other:getName() == "floor" then if _self.escudo == true then lua:getRigidbody(other):addForce1(Vector3(0, _self.strength, 0), Vector3(0, 0, 0), 1) _self.escudo = false end _self.bounces = _self.bounces + 1 if(_self.bounces >= _self.maxBounces) then lua:playSound("Assets/Music/WinTheme.wav") lua:changeScene("gameOver") lua:getLuaSelf(lua:getEntity("gameManager"), "score").registerScore() end _self.batted = true end end return batBehaviour
-- eLua platform interface - timers --[[ // The next 3 functions need to be implemented only if the generic system timer mechanism // (src/common.c:cmn_systimer*) is used by the backend u64 platform_timer_sys_raw_read(); void platform_timer_sys_enable_int(); void platform_timer_sys_disable_int(); --]] data_en = { -- Title title = "eLua platform interface - timers", -- Menu name menu_name = "Timers", -- Overview overview = [[This part of the platform interface groups functions related to the timers of the MCU. It also makes provisions for using $virtual timers$ on any platform, see @#virtual@this section@ for details. Keep in mind that in the following paragraphs a $timer id$ can refer to both a hardware timer or a virtual timer.]], -- Data structures, constants and types structures = { { text = "typedef u64/u32 timer_data_type;", name = "Timer data type", desc = [[This defines the data type used to specify delays and time intervals (which are always specified in $microseconds$). The choice between u64 and u32 for the timer data type depends on the build type, check ^#the_system_timer^here^ for mode details.]] }, { text = [[// Timer operations enum { PLATFORM_TIMER_OP_START, PLATFORM_TIMER_OP_READ, PLATFORM_TIMER_OP_SET_CLOCK, PLATFORM_TIMER_OP_GET_CLOCK, PLATFORM_TIMER_OP_GET_MAX_DELAY, PLATFORM_TIMER_OP_GET_MIN_DELAY, PLATFORM_TIMER_OP_GET_MAX_CNT };]], name = "Timer operations", desc = "This enum lists all the operations that can be executed on a given timer." } }, -- Functions funcs = { { sig = "int #platform_timer_exists#( unsigned id );", desc = [[Checks if the platform has the timer specified as argument. Implemented in %src/common.c%, it uses the $NUM_TIMER$ macro that must be defined in the platform's $platform_conf.h$ file (see @arch_overview.html#platforms@here@ for details) and the virtual timer configuration (@#virtual@here@ for details). For example:</p> ~#define NUM_TIMER 2 $// The platform has 2 hardware timers$~<p>]], args = "$id$ - the timer ID", ret = "1 if the timer exists, 0 otherwise" }, { sig = "void #platform_timer_delay#( unsigned id, timer_data_type delay_us );", desc = [[Waits on a timer, then returns. This function is "split" in two parts: a platform-independent part implemented in %src/common_tmr.c% (that handles virtual timers and the system timer) and a platform-dependent part that must be implemented by each platform in a function named @#platform_s_timer_delay@platform_s_timer_delay@. This function handles both hardware timer IDs and virtual timer IDs.<br> <a name="limitations" /><span class="warning">IMPORTANT NOTE</span>: the real delay after executing this functions depends on a number of variables, most notably the base clock of the timer and the size of the timer counter register (32 bits on some platforms, 16 bits on most platforms, other values are less common). To ensure that the delay you're requesting is achievable, use @#platform_timer_op@platform_timer_op@ with $PLATFORM_TIMER_OP_GET_MAX_DELAY$ and $PLATFORM_TIMER_OP_GET_MIN_DELAY$ to obtain the maximum and the minimum achievable wait times on your timer, respectively. Even if your delay is within these limits, the $precision$ of this function still varies a lot, mainly as a function of the timer base clock.]], args = { "$id$ - the timer ID", "$delay_us$ - the delay time (in microseconds)" } }, { sig = "void #platform_s_timer_delay#( unsigned id, timer_data_type delay_us );", desc = [[This function is identical in functionality to @#platform_timer_delay@platform_timer_delay@, but this is the function that must actually be implemented by a platform port and it must never handle virtual timer IDs or the system timer ID, only hardware timer IDs. It has the same @#limitations@limitations@ as @#platform_timer_delay@platform_timer_delay@.]], args = { "$id$ - the timer ID", "$delay_us$ - the delay time (in microseconds)" } }, { sig = "timer_data_type #platform_timer_op#( unsigned id, int op, timer_data_type data );", desc = [[Executes an operation on a timer. This function is "split" in two parts: a platform-independent part implemented in %src/common_tmr.c% (that handles virtual timers and the system timer) and a platform-dependent part that must be implemented by each platform in a function named @#platform_s_timer_op@platform_s_timer_op@. This function handles both hardware timer IDs and virtual timer IDs.]], args = { "$id$ - the timer ID", [[$op$ - the operation. $op$ can take any value from the @#timer_operations@this enum@, as follows: <ul> <li>$PLATFORM_TIMER_OP_START$: start the specified timer by setting its counter register to a predefined value.</li> <li>$PLATFORM_TIMER_OP_READ$: get the value of the specified timer's counter register.</li> <li>$PLATFORM_TIMER_SET_CLOCK$: set the clock of the specified timer to $data$ (in hertz). You can never set the clock of a virtual timer, which is set at compile time.</li> <li>$PLATFORM_TIMER_GET_CLOCK$: get the clock of the specified timer.</li> <li>$PLATFORM_TIMER_OP_GET_MAX_DELAY$: get the maximum achievable timeout on the specified timer (in us).</li> <li>$PLATFORM_TIMER_OP_GET_MIN_DELAY$: get the minimum achievable timeout on the specified timer (in us).</li> <li>$PLATFORM_TIMER_OP_GET_MAX_CNT$: get the maximum value of the timer's counter register.</li> </ul>]], "$data$ - used to specify the timer clock value when $op = PLATFORM_TIMER_SET_CLOCK$, ignored otherwise", }, ret = { "the predefined value used when starting the clock if $op = PLATFORM_TIMER_OP_START$", "the timer's counter register if $op = PLATFORM_TIMER_OP_READ$", "the actual clock set on the timer, which might be different than the request clock depending on the hardware if $op = PLATFORM_TIMER_SET_CLOCK$", "the timer clock if $op = PLATFORM_TIMER_GET_CLOCK$", "the maximum achievable delay (in microseconds) if $op = PLATFORM_TIMER_OP_GET_MAX_DELAY$", "the minimum achievable delay (in microseconds) if $op = PLATFORM_TIMER_OP_GET_MIN_DELAY$", "the maximum value of the timer's coutner register if $op == PLATFORM_TIMER_OP_GET_MAX_CNT$", } }, { sig = "timer_data_type #platform_s_timer_op#( unsigned id, int op, timer_data_type data );", desc = [[This function is identical in functionality to @#platform_timer_op@platform_timer_op@, but this is the function that must actually be implemented by a platform port and it must never handle virtual timer IDs or the system timer, only hardware timer IDs.]], args = { "$id$ - the timer ID", [[$op$ - the operation. $op$ can take any value from the @#opval@this enum@, as follows: <ul> <li>$PLATFORM_TIMER_OP_START$: start the specified timer by setting its counter register to a predefined value.</li> <li>$PLATFORM_TIMER_OP_READ$: get the value of the specified timer's counter register.</li> <li>$PLATFORM_TIMER_SET_CLOCK$: set the clock of the specified timer to $data$ (in hertz). You can never set the clock of a virtual timer, which is set at compile time.</li> <li>$PLATFORM_TIMER_GET_CLOCK$: get the clock of the specified timer.</li> <li>$PLATFORM_TIMER_OP_GET_MAX_DELAY$: get the maximum achievable timeout on the specified timer (in us).</li> <li>$PLATFORM_TIMER_OP_GET_MIN_DELAY$: get the minimum achievable timeout on the specified timer (in us).</li> <li>$PLATFORM_TIMER_OP_GET_MAX_CNT$: get the maximum value of the timer's counter register.</li> </ul>]], "$data$ - used to specify the timer clock value when $op = PLATFORM_TIMER_SET_CLOCK$, ignored otherwise", }, ret = { "the predefined value used when starting the clock if $op = PLATFORM_TIMER_OP_START$", "the timer's counter register if $op = PLATFORM_TIMER_OP_READ$", "the actual clock set on the timer, which might be different than the request clock depending on the hardware if $op = PLATFORM_TIMER_SET_CLOCK$", "the timer clock if $op = PLATFORM_TIMER_GET_CLOCK$", "the maximum achievable delay (in microseconds) if $op = PLATFORM_TIMER_OP_GET_MAX_DELAY$", "the minimum achievable delay (in microseconds) if $op = PLATFORM_TIMER_OP_GET_MIN_DELAY$", "the maximum value of the timer's coutner register if $op == PLATFORM_TIMER_OP_GET_MAX_CNT$", } }, { sig = "timer_data_type #platform_timer_get_diff_us#( unsigned id, timer_data_type start, timer_data_type end );", desc = [[Return the time difference (in us) between two timer values (as returned by calling @refman_gen_tmr.html#platform_timer_op@platform_timer_op@ with $PLATFORM_TIMER_OP_READ$ or $PLATFORM_TIMER_OP_START$. This function is generic, thus it is implemented in %src/common.c%. <span class="warning">NOTE</span>: the order of $start$ and $end$ is important. $end$ must correspond to a moment in time which came after $start$. The function knows how to deal with $a single$ timer overflow condition ($end$ is less than $start$); if the timer overflowed 2 or more times between $start$ and $end$ the result of this function will be incorrect.]], args = { "$id$ - the timer ID", "$start$ - the initial counter value.", "$end$ - the final counter value.", }, ret = "the time difference (in microseconds)" }, { sig = "int #platform_timer_set_match_int#( unsigned id, timer_data_type period_us, int type );", desc = [[Setup the timer match interrupt. Only available if interrupt support is enabled, check @inthandlers.html@here@ for details.This function is "split" in two parts: a platform-independent part implemented in %src/common_tmr.c% (that handles virtual timers and the system timer) and a platform-dependent part that must be implemented by each platform in a function named @#platform_s_timer_set_math_int@platform_s_timer_set_match_int@. This function handles both hardware timer IDs and virtual timer IDs. <span class="warning">NOTE</span>: the @#the_system_timer@system timer@ can't generate interrupts.]], args = { "$id$ - the timer ID", "$period_us$ - the period (in microseconds) of the timer interrupt. Setting this to 0 disables the timer match interrupt.", [[$type$ - $PLATFORM_TIMER_INT_ONESHOT$ for an interrupt that occurs only once after $period_us$ microseconds, or $PLATFORM_TIMER_INT_CYCLIC$ for an interrupt that occurs every $period_us$ microseconds]] }, ret = { "$PLATFORM_TIMER_INT_OK$ if the operation was successful.", "$PLATFORM_TIMER_INT_TOO_SHORT$ if the specified period is too short.", "$PLATFORM_TIMER_INT_TOO_LONG$ if the specified period is too long.", "$PLATFORM_TIMER_INT_INVALID_ID$ if the specified timer cannot handle this operation." } }, { sig = "int #platform_s_timer_set_match_int#( unsigned id, timer_data_type period_us, int type );", desc = [[This function is identical in functionality to @#platform_timer_set_match_int@platform_timer_set_match_int@, but this is the function that must actually be implemented by a platform port and it must never handle virtual timer IDs or the system timer, only hardware timer IDs.]], args = { "$id$ - the timer ID", "$period_us$ - the period (in microseconds) of the timer interrupt. Setting this to 0 disables the timer match interrupt.", [[$type$ - $PLATFORM_TIMER_INT_ONESHOT$ for an interrupt that occurs only once after $period_us$ microseconds, or $PLATFORM_TIMER_INT_CYCLIC$ for an interrupt that occurs every $period_us$ microseconds]] }, ret = { "$PLATFORM_TIMER_INT_OK$ if the operation was successful.", "$PLATFORM_TIMER_INT_TOO_SHORT$ if the specified period is too short.", "$PLATFORM_TIMER_INT_TOO_LONG$ if the specified period is too long.", "$PLATFORM_TIMER_INT_INVALID_ID$ if the specified timer cannot handle this operation." } }, { sig = "timer_data_type #platform_timer_read_sys#();", desc = "Returns the current value of the system timer, see @#the_system_timer@here@ for more details.", ret = "The current value of the system timer." }, { sig = "int #platform_timer_sys_available#();", desc = [[Used to check the availability of the system timer. This function is platform independent and is implemented in %src/common_tmr.c%. It returns the value of the $PLATFORM_HAS_SYSTIMER$ macro, check @#the_system_timer@here@ for more details.]], ret = "1 if the system timer is implemented, 0 otherwise." }, { sig = "u64 #platform_timer_sys_raw_read#();", desc = [[Return the counter of the timer used to implement the system timer. Needs to be implemented only if eLua's generic system timer mechanism is used, check @#the_system_timer@here@ for details.]], ret = "The counter of the timer used to implement the system timer." }, { sig = "void #platform_timer_sys_enable_int#();", desc = [[Enable the overflow/match interrupt of the timer used to implement the system timer. Needs to be implemented only if eLua's generic system timer mechanism is used, check @#the_system_timer@here@ for details.]], }, { sig = "void #platform_timer_sys_disable_int#();", desc = [[Disable the overflow/match interrupt of the timer used to implement the system timer. Needs to be implemented only if eLua's generic system timer mechanism is used, check @#the_system_timer@here@ for details.]], }, }, auxdata = { { title = "Virtual timers", desc = [[$Virtual timers$ were added to eLua to overcome some limitations:</p> <ul> <li>there are generally few hardware timers available, some of which might be dedicated (thus not usable directly by eLua).</li> <li>many times it is difficult to share a hardware timer between different parts of an application because of conflicting requirements. Generally it's not possible to have timers that can achieve long delays and high accuracy at the same time (this is especially true for systems that have 16 bit or even smaller timers).</li> </ul> <p>In this respect, $virtual timers$ are a set of timers that share a single hardware timer. It is possible, in this way, to have a hardware timer that can implement 4, 8 or more virtual/software timers. There are a few drawbacks to this approach:</p> <ul> <li>the hardware timer used to implement the virtual timers must generally be dedicated. In fact it can still be used in "read only mode", which means that the only operations that can be executed on it are $PLATFORM_TIMER_OP_READ$, $PLATFORM_TIMER_GET_CLOCK$, $PLATFORM_TIMER_OP_GET_MAX_DELAY$ and $PLATFORM_TIMER_OP_GET_MIN_DELAY$. However, since the "read only mode" is not enforced by the code, it is advisable to treat this timer as a dedicated resource and thus make it invisible to eLua by not associating it with an ID.</li> <li>the number of virtual timers and their base frequency are fixed at compile time.</li> <li>virtual timers are generally used for large delays with low accuracy, since their base frequency should be fairly low (see below).</li> </ul> <p>To $enable$ virtual timers:</p> <ol> <li>edit $platform_conf.h$ (see @arch_overview.html#platforms@here@ for details) and set $VTMR_NUM_TIMERS$ to the number of desired virtual timers and $VTMR_FREQ_HZ$ to the base frequency of the virtual timers (in hertz). For example: ~#define VTMR_NUM_TIMERS 4 // we need 4 virtual timers #define VTMR_FREQ_HZ 4 // the base clock for the virtual timers is 4Hz~</li> <li>in your platform port setup a hardware timer to fire an interrupt at $VTMR_FREQ_HZ$ and call the $cmn_virtual_timer_cb$ function (defined in %src/common.c%) in the timer interrupt handler. For example, if the the interrupt handler is called $timer_int_handler$, do this: ~void timer_int_handler( void ) { // add code to clear the timer interrupt flag here if needed cmn_virtual_timer_cb(); }~</li> </ol> <p>Note that because of step 2 above you are limited by practical constraints on the value of $VTMR_FREQ_HZ$. If set too high, the timer interrupt will fire too often, thus taking too much CPU time. The maximum value depends largely on the hardware and the desired behaviour of the virtual timers, but in practice values larger than 10 might visibly change the behaviour of your system.</p> <p>To $use$ a virtual timer, identify it with the constant $VTMR_FIRST_ID$ (defined in %inc/common.h%) plus an offset. For example, $VTMR_FIRST_ID+0$ (or simply $VTMR_FIRST_ID$) is the ID of the first virtual timer in the system, and $VTMR_FIRST_ID+2$ is the ID of the third virtual timer in the system.</p> <p>Virtual timers are capable of generating timer match interrupts just like regular timers, check @#platform_timer_set_match_int@here@ for details. ]] }, { title = "The system timer", desc = [[The system timer was introduced in eLua 0.9 as a simpler alternative to the traditional eLua timers. Working with regular timers in eLua might be challenging for a number of reasons:</p> <ul> <li>depending on the hardware, the timers might have a limited range. Because of this, they might not be able to timeout in the interval requested by the user.</li> <li>the timers might have different ranges even on the same platform (they might have a different base clock, for example). The problem is further aggravated when switching platforms.</li> <li>the timers might be shared with other hardware resources (for example PWMs or ADC triggers) so using them might have unexpected side effects.</li> <li>manual timer management is error prone. The user needs to keep into account the timers he's using, their base frequencies and wether they are shared or not with the C code.</li> </ul> <p>The ^#virtual_timers^virtual timers^ can fix some of the above problems, but their resolution is fairly low and they still require manual management.</p> <p>The $system timer$ attemps to fix (at least partially) these issues. It is a timer with fixed resolution (1us) %on all platforms% and large counters:</p> <ul> <li>if eLua is compiled in floating point mode (default) the counter is 52 bits wide. It will overflow after more than 142 %years%.</li> <li>if eLua is compiled in 32 bit integer-only mode (lualong) the counter is 32 bits wide. It will overflow after about one hour.</li> <li>if eLua is compiled in 64 bit integer-only mode (lualonglong, new in 0.9) the counter is again 52 bits wide and it will also overflow after more than 142 years.</li> </ul> <p>The eLua API was partially modified to take full advantage of this new timer:</p> <ul> <li>all the functions that can operate with a timeout (for example @refman_gen_uart.html#uart.read@uart.read@ or @refman_gen_net.html#net.accept@net.accept@) will default to the system timer is a timer ID is not specified explicitly.</li> <li>all the function in the @refman_gen_tmr.html@timer module@ will default to the system timer if a timer ID is not specified explicitly.</li> <li>timeouts are specified in a more unified manner across the eLua modules as a $[timeout], [timer_id]$ pair: <table class="table_center" style="margin-top: 10px; margin-bottom: 4px;"> <tbody> <tr> <th>timeout</th> <th>timer_id</th> <th>Result</th> </tr> <tr> <td>not specified</td> <td>any value</td> <td>infinite timeout (the function blocks until it completes).</td> </tr> <tr> <td>0</td> <td>any value</td> <td>no timeout (the function returns immediately).<//td> </tr> <tr> <td>a positive value</td> <td>not specified</td> <td>the system timer will be used to measure the function's timeout.</td> </tr> <tr> <td>a positive value</td> <td>a timer ID</td> <td>the specified timer will be used to measure the function's timeout.</td> </tr> </tbody> </table> </li> </ul> <p>Using the system timer as much as possible is also encouraged with C code that uses the eLua C api, not only with Lua programs. The C code can use the system timer by specifying $PLATFORM_TIMER_SYS_ID$ as the timer ID.</p> <p>From an implementation stand point, the system timer is built around a hardware timer with a base clock of at least 1MHz that can generate an interrupt when the timer counter overflows or when it reaches a certain value. The interrupt handler updates the upper part of the system timer counter (basically an overflow counter). eLua has a generic mechanism that can be used to implement a system timer on any platform using this method. To take advantage of this mechanism follow the steps below:</p> <ol> <li>define the $PLATFORM_HAS_SYSTIMER$ macro in your %platform_conf.h% file.</li> <li>implement @#platform_timer_sys_raw_read@platform_timer_sys_raw_read@, @#platform_timer_sys_enable_int@platform_timer_sys_enable_int@ and @#platform_timer_sys_disable_int@platform_timer_sys_disable_int@.</li> <li>include the %common.h% header.</li> <li>setup your hardware timer and its associated interrupt. This should happen an initialization time (for example in %platform_init%).</li> <li>call %cmn_systimer_set_base_freq% with the base frequency of your timer in Hz.</li> <li>call %cmn_systimer_set_interrupt_freq% with the frequency of the timer's overflow/match interrupt in Hz. Alternatively you can call %cmn_systimer_set_interrupt_period_us% to set the timer's overflow/match interrupt %period% (in microseconds) instead of its frequency. Use the latter form if the frequency is not an integer.</li> <li>call %cmn_systimer_periodic% from your timer's overflow interrupt handler.</li> <li>use this implementation for @#platform_timer_read_sys@platform_timer_read_sys@: ~timer_data_type platform_timer_read_sys() { return cmn_systimer_get(); }~</li></ol> <p>Note that the above mechanism is optional. A platform might have a different method to implement the system timer; this is OK as long as the system timer requirements are respected.</p> <p><span class="warning">IMPORTANT NOTE</span>: although system timer support in eLua is optional, implementing the system timer is highly recommended. As already specified, all the timer IDs in various eLua modules default to the system timer. This means that any code that was written under the assumption that a system timer is present (which is a fair assumption) will fail on platforms that don't actually have a system timer. Check @status.html#systmr@here@ for a list of platforms that implement the system timer. If your platform doesn't implement the system timer, you'll get this warning at compile time:</p> ~#warning This platform does not have a system timer. Your eLua image might not work as expected.~ ]] } } }
lines = io.lines("input.txt") stars = {} for line in lines do local star = {pos={}, vel={}} star.pos.x, star.pos.y, star.vel.x, star.vel.y = string.match(line, "position=< *(-?%d+), *(-?%d+)> velocity=< *(-?%d+), *(-?%d+)>") table.insert(stars, star) end -- heuristics start_at = 9999 for _, star in ipairs(stars) do star.pos.x = star.pos.x + star.vel.x * start_at star.pos.y = star.pos.y + star.vel.y * start_at end for second = start_at, math.huge do table.sort(stars, function(star1, star2) if star1.pos.y ~= star2.pos.y then return star1.pos.y < star2.pos.y else return star1.pos.x < star2.pos.x end end) local height = stars[#stars].pos.y - stars[1].pos.y if height > 9 then for _, star in ipairs(stars) do star.pos.x = star.pos.x + star.vel.x star.pos.y = star.pos.y + star.vel.y end else local old_x = stars[1].pos.x - 1 s = "" for _, star in ipairs(stars) do -- points can overlap if old_x > star.pos.x then print(s) s = "#" elseif old_x < star.pos.x then s = s .. string.rep(" ", star.pos.x - old_x - 1) .. "#" end old_x = star.pos.x end print(s) print(second) break end end
require "config" -- Prototype names and types to not alter. local excluded_prototype_names = {} local excluded_prototype_types = {} -- Helper functions to check if a prototype name or type is excluded. local function prototype_name_excluded(name) return excluded_prototype_names[name] end local function prototype_type_excluded(type) return excluded_prototype_types[type] end -- Returns true when an exclusion should be applied or false otherwise. local function exclusion_applies(exclusion) -- Exclusions always apply if no apply_when_object_exists is specified. if not exclusion.apply_when_object_exists then return true else -- Exclusions apply when the apply_when_object_exists object actually exists. if data.raw[exclusion.apply_when_object_exists.type][exclusion.apply_when_object_exists.name] then return true end end -- The apply_when_object_exists object didn't exist (the mod which the exclusion was for is not active). return false end -- Update the exclusion arrays by parsing an exclusion (from config.lua). local function apply_exclusion(exclusion) if exclusion.excluded_prototype_names then for _,n in pairs(exclusion.excluded_prototype_names) do excluded_prototype_names[n] = true end end if exclusion.excluded_prototype_types then for _,t in pairs(exclusion.excluded_prototype_types) do excluded_prototype_types[t] = true end end end -- Parse the exclusions defined in config.lua only applying those which are applicable. local function apply_exclusions() for _,e in pairs(exclusions) do if exclusion_applies(e) then apply_exclusion(e) end end end -- Returns a coordinate reduced where required to form the specified gap between it and the tile boundary. local function adjust_coordinate_to_form_gap(coordinate, required_gap) -- Treat all coordinates as positive to simplify calculations. local is_negative_coordinate = (coordinate < 0) if is_negative_coordinate then coordinate = coordinate * -1 end local tile_width = 0.5 -- Calculate the existing gap (how much space there is to the next tile edge or 0 when the coordinate lies on a tile edge). local distance_past_last_tile_edge = coordinate % tile_width -- This is how far the collision box extends over any tile edge, and should be 0 for a perfect fit. local existing_gap = 0 if distance_past_last_tile_edge > 0 then existing_gap = (tile_width - distance_past_last_tile_edge) end -- Reduce the coordinate to make the gap large enough if it is not already. if existing_gap < required_gap then coordinate = coordinate + existing_gap - required_gap if coordinate < 0 then coordinate = 0 end end -- Make the coordinate negative again if it was originally negative. if is_negative_coordinate then coordinate = coordinate * -1 end return coordinate end -- Checks all existing prototypes listed in prototype_type_gap_requirements and reduces their collision box to make a gap large enough to walk though if it is not already. local function adjust_collision_boxes() for prototype_type, required_gap in pairs(prototype_type_gap_requirements) do -- Don't shrink prototypes of this type if they've been excluded. if not prototype_type_excluded(prototype_type) then for prototype_name, prototype in pairs(data.raw[prototype_type]) do -- If the prototype is not excluded and has a collision box then resize it. if (not prototype_name_excluded(prototype_name)) and prototype["collision_box"] then for y=1,2 do for x=1,2 do prototype.collision_box[x][y] = adjust_coordinate_to_form_gap(prototype.collision_box[x][y], required_gap) end end end end end end end -- Exclude prototypes from alteration for mods that have compatibility issues with modified collision boxes. apply_exclusions() -- Make the adjustments. adjust_collision_boxes()
local Class = require(_G.engineDir .. "middleclass"); local Component = Class("Component") Component.static.components = {} function Component:initialize() -- Component:create(cmpt) end function Component:debug() print("\t"..self.class.name.." {") for k, v in pairs(self.data) do if type(v) == "table" then print("\t\t"..k.." {") for dk, dv in pairs(v) do print("\t\t\t"..dk..": "..dv) end print("\t\t}") else print("\t\t"..k, v) end end print("\t}") end -- Create a child of Component dynamically function Component:create(cmpt) if not Component:doExist(cmpt) then local newComponent = Class(cmpt.name, Component); newComponent.initialize = function (self, data) Component.initialize(self) self.data = data end Component.components[cmpt.name] = newComponent; return newComponent:new(cmpt.data) else return self.components[cmpt.name]:new(cmpt.data) end end function Component:doExist (cmpt) for k, v in pairs(self.components) do if k == cmpt.name then return true end end return false end return Component
local dpdk = require "dpdk" local memory = require "memory" local device = require "device" local stats = require "stats" local timer = require "timer" memory.enableCache() -- TODO: this function master(port1, port2) if not port1 or not port2 then return print("Usage: port1 port2") end local dev2 = device.config(port1) local dev1 = device.config(port2) device.waitForLinks() for size = 60, 1518 do print("Running test for packet size = " .. size) local task = dpdk.launchLua("loadSlave", dev1:getTxQueue(0), dev2:getTxQueue(0), size) local avg = task:wait() if not dpdk.running() then break end end dpdk.waitForSlaves() end function loadSlave(queue1, queue2, size) local mem = memory.createMemPool(function(buf) buf:getEthernetPacket():fill{ pktLength = size, ethSrc = queue, ethDst = "10:11:12:13:14:15", } end) bufs = mem:bufArray() local ctr1 = stats:newDevTxCounter(queue1.dev, "plain") local ctr2 = stats:newDevTxCounter(queue2.dev, "plain") local runtime = timer:new(10) while runtime:running() and dpdk.running() do bufs:alloc(size) queue1:send(bufs) ctr1:update() bufs:alloc(size) queue2:send(bufs) ctr2:update() end ctr1:finalize() ctr2:finalize() return nil -- TODO end
local ThreatLib = LibStub and LibStub("ThreatClassic-1.0", true) if not ThreatLib then return end if select(2, _G.UnitClass("player")) ~= "WARRIOR" then return end local _G = _G local select = _G.select local GetTalentInfo = _G.GetTalentInfo local GetShapeshiftForm = _G.GetShapeshiftForm local GetSpellInfo = _G.GetSpellInfo local pairs, ipairs = _G.pairs, _G.ipairs local GetTime = _G.GetTime local UnitDebuff = _G.UnitDebuff local Warrior = ThreatLib:GetOrCreateModule("Player") -- https://github.com/magey/classic-warrior/wiki/Threat-Mechanics -- maxRankThreatValue / maxRankLevelAvailability = factor -- lowerRankThreatValue = factor * rankN local sunderFactor = 261 / 58 -- ok-ish (between 260 - 270) local shieldBashFactor = 187 / 52 local revengeFactor = 355 / 60 -- maybe look into r5 local heroicStrikeFactor = 220 / 70 -- NEED MORE INFO local shieldSlamFactor = 250 / 60 local cleaveFactor = 100 / 60 -- NEED MORE INFO local hamstringFactor = 145 / 54 -- ok-ish (between 142 - 148) local mockingBlowFactor = 250 / 56 -- NEED MORE INFO local battleShoutFactor = 1 local demoShoutFactor = 43 / 54 local thunderClapFactor = 130 / 58 local threatValues = { sunder = { [7386] = sunderFactor * 10, [7405] = sunderFactor * 22, [8380] = sunderFactor * 34, [11596] = sunderFactor * 46, [11597] = 261 }, shieldBash = { [72] = shieldBashFactor * 12, [1671] = shieldBashFactor * 32, [1672] = 187 }, revenge = { [6572] = revengeFactor * 14, [6574] = revengeFactor * 24, [7379] = revengeFactor * 34, [11600] = revengeFactor * 44, [11601] = revengeFactor * 54, -- (315 - 319) [25288] = 355 }, heroicStrike = { -- needs work [78] = 20, [284] = 39, [285] = 59, [1608] = 78, [11564] = 98, [11565] = 118, [11566] = 137, [11567] = 145, [25286] = 175 }, shieldSlam = { [23922] = shieldSlamFactor * 40, [23923] = shieldSlamFactor * 48, [23924] = shieldSlamFactor * 54, [23925] = 250 }, cleave = { [845] = 10, [7369] = 40, [11608] = 60, [11609] = 70, [20569] = 100 }, hamstring = { [1715] = hamstringFactor * 8, [7372] = hamstringFactor * 32, [7373] = 145, }, --[[ mockingBlow = { [694] = mockingBlowFactor * 16, [7400] = mockingBlowFactor * 26, [7402] = mockingBlowFactor * 36, [20559] = mockingBlowFactor * 46, [20560] = 250 }, --]] battleShout = { [6673] = battleShoutFactor * 1, [5242] = battleShoutFactor * 12, [6192] = battleShoutFactor * 22, [11549] = battleShoutFactor * 32, [11550] = battleShoutFactor * 42, [11551] = battleShoutFactor * 52, [25289] = 60 }, demoShout = { [1160] = demoShoutFactor * 14, [6190] = demoShoutFactor * 24, [11554] = demoShoutFactor * 34, [11555] = demoShoutFactor * 44, [11556] = 43 }, thunderclap = { [6343] = thunderClapFactor * 6, [8198] = thunderClapFactor * 18, [8204] = thunderClapFactor * 28, [8205] = thunderClapFactor * 38, [11580] = thunderClapFactor * 48, [11581] = 130 }, execute = { [5308] = true, [20658] = true, [20660] = true, [20661] = true, [20662] = true }, disarm = { [676] = 104 } } local function init(self, t, f) local func = function(self, spellID, target) self:AddTargetThreat(target, f(self, spellID)) end for k, v in pairs(t) do self.CastLandedHandlers[k] = func end end function Warrior:ClassInit() -- Taunt self.CastLandedHandlers[355] = self.Taunt -- Non-transactional abilities init(self, threatValues.heroicStrike, self.HeroicStrike) init(self, threatValues.shieldBash, self.ShieldBash) init(self, threatValues.shieldSlam, self.ShieldSlam) init(self, threatValues.revenge, self.Revenge) -- init(self, threatValues.mockingBlow, self.MockingBlow) init(self, threatValues.hamstring, self.Hamstring) init(self, threatValues.thunderclap, self.Thunderclap) init(self, threatValues.disarm, self.Disarm) -- Transactional stuff -- Sunder Armor local func = function(self, spellID, target) self:AddTargetThreatTransactional(target, spellID, self:SunderArmor(spellID)) end for k, v in pairs(threatValues.sunder) do self.CastHandlers[k] = func self.MobDebuffHandlers[k] = self.GetSunder end -- Ability damage modifiers for k, v in pairs(threatValues.execute) do self.AbilityHandlers[v] = self.Execute end -- Shouts -- Battle Shout local bShout = function(self, spellID, target) self:AddThreat(threatValues.battleShout[spellID] * self:threatMods()) end for k, v in pairs(threatValues.battleShout) do self.CastHandlers[k] = bShout end -- Demoralizing Shout local demoShout = function(self, spellID, target) self:AddThreat(threatValues.demoShout[spellID] * self:threatMods()) end for k, v in pairs(threatValues.demoShout) do self.CastHandlers[k] = demoShout end local demoShoutMiss = function(self, spellID, target) self:rollbackTransaction(target, spellID) end for k, v in pairs(threatValues.demoShout) do self.CastMissHandlers[k] = demoShoutMiss end -- Set names don't need to be localized. self.itemSets = { ["Might"] = { 16866, 16867, 16868, 16862, 16864, 16861, 16865, 16863 } } end function Warrior:ClassEnable() self:GetStanceThreatMod() self:RegisterEvent("UPDATE_SHAPESHIFT_FORM", "GetStanceThreatMod" ) end function Warrior:ScanTalents() -- Defiance if ThreatLib.Classic then local rank = _G.select(5, GetTalentInfo(3, 9)) self.defianceMod = 1 + (0.05 * rank) else self.defianceMod = 1 -- for when testing in retail end end function Warrior:GetStanceThreatMod() self.isTanking = false if GetShapeshiftForm() == 2 then self.passiveThreatModifiers = 1.3 * self.defianceMod self.isTanking = true elseif GetShapeshiftForm() == 3 then self.passiveThreatModifiers = 0.8 else self.passiveThreatModifiers = 0.8 end self.totalThreatMods = nil -- Needed to recalc total mods end function Warrior:SunderArmor(spellID) local sunderMod = 1 if self:getWornSetPieces("Might") >= 8 then sunderMod = 1.15 end local threat = threatValues.sunder[spellID] return threat * sunderMod * self:threatMods() end function Warrior:Taunt(spellID, target) local targetThreat = ThreatLib:GetThreat(UnitGUID("targettarget"), target) local myThreat = ThreatLib:GetThreat(UnitGUID("player"), target) if targetThreat > 0 and targetThreat > myThreat then pendingTauntTarget = target pendingTauntOffset = targetThreat-myThreat elseif targetThreat == 0 then local maxThreat = ThreatLib:GetMaxThreatOnTarget(target) pendingTauntTarget = target pendingTauntOffset = maxThreat-myThreat end self.nextEventHook = self.TauntNextHook end function Warrior:TauntNextHook(timestamp, subEvent, hideCaster, sourceGUID, sourceName, sourceFlags, sourceRaidFlags, destGUID, destName, destFlags, destRaidFlags, spellID) if pendingTauntTarget and (subEvent ~= "SPELL_MISSED" or spellID ~= 355) then self:AddTargetThreat(pendingTauntTarget, pendingTauntOffset) ThreatLib:PublishThreat() end pendingTauntTarget = nil pendingTauntOffset = nil end function Warrior:HeroicStrike(spellID) return threatValues.heroicStrike[spellID] * self:threatMods() end function Warrior:ShieldBash(spellID) return threatValues.shieldBash[spellID] * self:threatMods() end function Warrior:ShieldSlam(spellID) return threatValues.shieldSlam[spellID] * self:threatMods() end function Warrior:Revenge(spellID) return threatValues.revenge[spellID] * self:threatMods() end --[[ function Warrior:MockingBlow(spellID) return threatValues.mockingBlow[spellID] * self:threatMods() end --]] function Warrior:Hamstring(spellID) return threatValues.hamstring[spellID] * self:threatMods() end function Warrior:Thunderclap(spellID) return threatValues.thunderclap[spellID] * self:threatMods() end function Warrior:Execute(amount) return amount * 1.25 end function Warrior:Disarm(spellID) return threatValues.disarm[spellID] * self:threatMods() end function Warrior:GetSunder(spellID, target) self:AddTargetThreat(target, self:SunderArmor(spellID)) end
return { ACTIONS_MAP = { ["`"] = {{Key.GRAVE}}, ["1"] = {{Key.DIGIT_1}}, ["2"] = {{Key.DIGIT_2}}, ["3"] = {{Key.DIGIT_3}}, ["4"] = {{Key.DIGIT_4}}, ["5"] = {{Key.DIGIT_5}}, ["6"] = {{Key.DIGIT_6}}, ["7"] = {{Key.DIGIT_7}}, ["8"] = {{Key.DIGIT_8}}, ["9"] = {{Key.DIGIT_9}}, ["0"] = {{Key.DIGIT_0}}, ["-"] = {{Key.MINUS}}, ["="] = {{Key.EQUAL}}, ["q"] = {{Key.Q}}, ["w"] = {{Key.W}}, ["e"] = {{Key.E}}, ["r"] = {{Key.R}}, ["t"] = {{Key.T}}, ["y"] = {{Key.Y}}, ["u"] = {{Key.U}}, ["i"] = {{Key.I}}, ["o"] = {{Key.O}}, ["p"] = {{Key.P}}, ["["] = {{Key.LEFTBRACE}}, ["]"] = {{Key.RIGHTBRACE}}, ["\\"] = {{Key.BACKSLASH}}, ["a"] = {{Key.A}}, ["s"] = {{Key.S}}, ["d"] = {{Key.D}}, ["f"] = {{Key.F}}, ["g"] = {{Key.G}}, ["h"] = {{Key.H}}, ["j"] = {{Key.J}}, ["k"] = {{Key.K}}, ["l"] = {{Key.L}}, [";"] = {{Key.SEMICOLON}}, ["'"] = {{Key.APOSTROPHE}}, ["z"] = {{Key.Z}}, ["x"] = {{Key.X}}, ["c"] = {{Key.C}}, ["v"] = {{Key.V}}, ["b"] = {{Key.B}}, ["n"] = {{Key.N}}, ["m"] = {{Key.M}}, [","] = {{Key.COMMA}}, ["."] = {{Key.DOT}}, ["/"] = {{Key.SLASH}}, ["~"] = {{Key.GRAVE, Mod.SHIFT}}, ["!"] = {{Key.DIGIT_1, Mod.SHIFT}}, ["@"] = {{Key.DIGIT_2, Mod.SHIFT}}, ["#"] = {{Key.DIGIT_3, Mod.SHIFT}}, ["$"] = {{Key.DIGIT_4, Mod.SHIFT}}, ["%"] = {{Key.DIGIT_5, Mod.SHIFT}}, ["^"] = {{Key.DIGIT_6, Mod.SHIFT}}, ["&"] = {{Key.DIGIT_7, Mod.SHIFT}}, ["*"] = {{Key.DIGIT_8, Mod.SHIFT}}, ["("] = {{Key.DIGIT_9, Mod.SHIFT}}, [")"] = {{Key.DIGIT_0, Mod.SHIFT}}, ["_"] = {{Key.MINUS, Mod.SHIFT}}, ["+"] = {{Key.EQUAL, Mod.SHIFT}}, ["Q"] = {{Key.Q, Mod.SHIFT}}, ["W"] = {{Key.W, Mod.SHIFT}}, ["E"] = {{Key.E, Mod.SHIFT}}, ["R"] = {{Key.R, Mod.SHIFT}}, ["T"] = {{Key.T, Mod.SHIFT}}, ["Y"] = {{Key.Y, Mod.SHIFT}}, ["U"] = {{Key.U, Mod.SHIFT}}, ["I"] = {{Key.I, Mod.SHIFT}}, ["O"] = {{Key.O, Mod.SHIFT}}, ["P"] = {{Key.P, Mod.SHIFT}}, ["{"] = {{Key.LEFTBRACE, Mod.SHIFT}}, ["}"] = {{Key.RIGHTBRACE, Mod.SHIFT}}, ["|"] = {{Key.BACKSLASH, Mod.SHIFT}}, ["A"] = {{Key.A, Mod.SHIFT}}, ["S"] = {{Key.S, Mod.SHIFT}}, ["D"] = {{Key.D, Mod.SHIFT}}, ["F"] = {{Key.F, Mod.SHIFT}}, ["G"] = {{Key.G, Mod.SHIFT}}, ["H"] = {{Key.H, Mod.SHIFT}}, ["J"] = {{Key.J, Mod.SHIFT}}, ["K"] = {{Key.K, Mod.SHIFT}}, ["L"] = {{Key.L, Mod.SHIFT}}, [":"] = {{Key.SEMICOLON, Mod.SHIFT}}, ["\""] = {{Key.APOSTROPHE, Mod.SHIFT}}, ["Z"] = {{Key.Z, Mod.SHIFT}}, ["X"] = {{Key.X, Mod.SHIFT}}, ["C"] = {{Key.C, Mod.SHIFT}}, ["V"] = {{Key.V, Mod.SHIFT}}, ["B"] = {{Key.B, Mod.SHIFT}}, ["N"] = {{Key.N, Mod.SHIFT}}, ["M"] = {{Key.M, Mod.SHIFT}}, ["<"] = {{Key.COMMA, Mod.SHIFT}}, [">"] = {{Key.DOT, Mod.SHIFT}}, ["?"] = {{Key.SLASH, Mod.SHIFT}}, ["\\|"] = {{Key.BACKSLASH}}, ["\\_"] = {{Key.BACKSLASH}}, ["Shift+0"] = {{Key.DIGIT_0, Mod.SHIFT}}, ["Escape"] = {{Key.ESC}}, ["F1"] = {{Key.F1}}, ["F2"] = {{Key.F2}}, ["F3"] = {{Key.F3}}, ["F4"] = {{Key.F4}}, ["F5"] = {{Key.F5}}, ["F6"] = {{Key.F6}}, ["F7"] = {{Key.F7}}, ["F8"] = {{Key.F8}}, ["F9"] = {{Key.F9}}, ["F10"] = {{Key.F10}}, ["F11"] = {{Key.F11}}, ["F12"] = {{Key.F12}}, ["F13"] = {{Key.F13}}, ["F14"] = {{Key.F14}}, ["F15"] = {{Key.F15}}, ["F16"] = {{Key.F16}}, ["F17"] = {{Key.F17}}, ["F18"] = {{Key.F18}}, ["F19"] = {{Key.F19}}, ["F20"] = {{Key.F20}}, ["F21"] = {{Key.F21}}, ["F22"] = {{Key.F22}}, ["F23"] = {{Key.F23}}, ["F24"] = {{Key.F24}}, ["Backspace"] = {{Key.BACKSPACE}}, ["Tab"] = {{Key.TAB}}, ["Enter"] = {{Key.ENTER}}, ["CapsLock"] = {{Key.CAPSLOCK}}, ["Space"] = {{Key.SPACE}}, ["ContextMenu"] = {{Key.COMPOSE}}, ["PrintScreen"] = {{Key.SYSRQ}}, ["ScrollLock"] = {{Key.SCROLLLOCK}}, ["Pause"] = {{Key.PAUSE}}, ["Insert"] = {{Key.INSERT}}, ["Home"] = {{Key.HOME}}, ["PageUp"] = {{Key.PAGEUP}}, ["Delete"] = {{Key.DELETE}}, ["End"] = {{Key.END}}, ["PageDown"] = {{Key.PAGEDOWN}}, ["Up"] = {{Key.UP}}, ["Left"] = {{Key.LEFT}}, ["Down"] = {{Key.DOWN}}, ["Right"] = {{Key.RIGHT}}, ["NumLock"] = {{Key.NUMLOCK}}, ["Numpad0"] = {{Key.KP0}}, ["Numpad1"] = {{Key.KP1}}, ["Numpad2"] = {{Key.KP2}}, ["Numpad3"] = {{Key.KP3}}, ["Numpad4"] = {{Key.KP4}}, ["Numpad5"] = {{Key.KP5}}, ["Numpad6"] = {{Key.KP6}}, ["Numpad7"] = {{Key.KP7}}, ["Numpad8"] = {{Key.KP8}}, ["Numpad9"] = {{Key.KP9}}, ["NumpadDecimal"] = {{Key.KPDOT}}, ["NumpadAdd"] = {{Key.KPPLUS}}, ["NumpadSubtract"] = {{Key.KPMINUS}}, ["NumpadMultiply"] = {{Key.KPASTERRISK}}, ["NumpadDivide"] = {{Key.KPSLASH}}, ["NumpadEnter"] = {{Key.KPENTER}}, ["ShiftLeft"] = {{0, Mod.SHIFT_LEFT}}, ["ControlLeft"] = {{0, Mod.CONTROL_LEFT}}, ["AltLeft"] = {{0, Mod.ALT_LEFT}}, ["OSLeft"] = {{0, Key.OS_LEFT}}, ["ShiftRight"] = {{0, Mod.SHIFT_RIGHT}}, ["ControlRight"] = {{0, Mod.CONTROL_RIGHT}}, ["AltRight"] = {{0, Mod.ALT_RIGHT}}, ["OSRight"] = {{0, Mod.OS_RIGHT}}, }, }
isLoggedIn = false PlayerData = {} local ClosestTraphouse = nil local InsideTraphouse = false local CurrentTraphouse = nil local TraphouseObj = {} local POIOffsets = nil local IsKeyHolder = false local IsHouseOwner = false local InTraphouseRange = false local CodeNPC = nil local IsRobbingNPC = false -- Code Citizen.CreateThread(function() while true do if isLoggedIn then SetClosestTraphouse() end Citizen.Wait(1000) end end) Citizen.CreateThread(function() Wait(1000) if QBCore.Functions.GetPlayerData() ~= nil then isLoggedIn = true PlayerData = QBCore.Functions.GetPlayerData() QBCore.Functions.TriggerCallback('qb-traphouse:server:GetTraphousesData', function(trappies) Config.TrapHouses = trappies end) end end) RegisterNetEvent('QBCore:Client:OnPlayerLoaded') AddEventHandler('QBCore:Client:OnPlayerLoaded', function() isLoggedIn = true PlayerData = QBCore.Functions.GetPlayerData() QBCore.Functions.TriggerCallback('qb-traphouse:server:GetTraphousesData', function(trappies) Config.TrapHouses = trappies end) end) function SetClosestTraphouse() local pos = GetEntityCoords(PlayerPedId(), true) local current = nil local dist = nil for id, traphouse in pairs(Config.TrapHouses) do if current ~= nil then if #(pos - Config.TrapHouses[id].coords.enter) < dist then current = id dist = #(pos - Config.TrapHouses[id].coords.enter) end else dist = #(pos - Config.TrapHouses[id].coords.enter) current = id end end ClosestTraphouse = current IsKeyHolder = HasKey(PlayerData.citizenid) IsHouseOwner = IsOwner(PlayerData.citizenid) end function HasKey(CitizenId) local haskey = false if ClosestTraphouse ~= nil then if Config.TrapHouses[ClosestTraphouse].keyholders ~= nil and next(Config.TrapHouses[ClosestTraphouse].keyholders) ~= nil then for _, data in pairs(Config.TrapHouses[ClosestTraphouse].keyholders) do if data.citizenid == CitizenId then haskey = true end end end end return haskey end function IsOwner(CitizenId) local retval = false if ClosestTraphouse ~= nil then if Config.TrapHouses[ClosestTraphouse].keyholders ~= nil and next(Config.TrapHouses[ClosestTraphouse].keyholders) ~= nil then for _, data in pairs(Config.TrapHouses[ClosestTraphouse].keyholders) do if data.citizenid == CitizenId then if data.owner then retval = true else retval = false end end end end end return retval end function DrawText3Ds(x, y, z, text) SetTextScale(0.35, 0.35) SetTextFont(4) SetTextProportional(1) SetTextColour(255, 255, 255, 215) SetTextEntry("STRING") SetTextCentre(true) AddTextComponentString(text) SetDrawOrigin(x,y,z, 0) DrawText(0.0, 0.0) local factor = (string.len(text)) / 370 DrawRect(0.0, 0.0+0.0125, 0.017+ factor, 0.03, 0, 0, 0, 75) ClearDrawOrigin() end RegisterNetEvent('qb-traphouse:client:EnterTraphouse') AddEventHandler('qb-traphouse:client:EnterTraphouse', function(code) if ClosestTraphouse ~= nil then if InTraphouseRange then local data = Config.TrapHouses[ClosestTraphouse] if not IsKeyHolder then SendNUIMessage({ action = "open" }) SetNuiFocus(true, true) else EnterTraphouse(data) end end end end) RegisterNUICallback('PinpadClose', function() SetNuiFocus(false, false) end) RegisterNUICallback('ErrorMessage', function(data) QBCore.Functions.Notify(data.message, 'error') end) RegisterNUICallback('EnterPincode', function(d) local data = Config.TrapHouses[ClosestTraphouse] if tonumber(d.pin) == data.pincode then EnterTraphouse(data) else QBCore.Functions.Notify('This Code Is Incorrect', 'error') end end) local CanRob = true function RobTimeout(timeout) SetTimeout(timeout, function() CanRob = true end) end local RobbingTime = 3 Citizen.CreateThread(function() while true do local aiming, targetPed = GetEntityPlayerIsFreeAimingAt(PlayerId(-1)) if targetPed ~= 0 and not IsPedAPlayer(targetPed) then local ped = PlayerPedId() local pos = GetEntityCoords(ped) if ClosestTraphouse ~= nil then local data = Config.TrapHouses[ClosestTraphouse] local dist = #(pos - data.coords["enter"]) if dist < 200 then if aiming then local pcoords = GetEntityCoords(targetPed) local peddist = #(pos - pcoords) if peddist < 4 then InDistance = true if not IsRobbingNPC and CanRob then if IsPedInAnyVehicle(targetPed) then TaskLeaveVehicle(targetPed, GetVehiclePedIsIn(targetPed), 1) end Citizen.Wait(500) InDistance = true local dict = 'random@mugging3' RequestAnimDict(dict) while not HasAnimDictLoaded(dict) do Citizen.Wait(10) end SetEveryoneIgnorePlayer(PlayerId(), true) TaskStandStill(targetPed, RobbingTime * 1000) FreezeEntityPosition(targetPed, true) SetBlockingOfNonTemporaryEvents(targetPed, true) TaskPlayAnim(targetPed, dict, 'handsup_standing_base', 2.0, -2, 15.0, 1, 0, 0, 0, 0) for i = 1, RobbingTime / 2, 1 do PlayAmbientSpeech1(targetPed, "GUN_BEG", "SPEECH_PARAMS_FORCE_NORMAL_CLEAR") Citizen.Wait(2000) end FreezeEntityPosition(targetPed, true) IsRobbingNPC = true SetTimeout(RobbingTime, function() IsRobbingNPC = false RobTimeout(math.random(30000, 60000)) if not IsEntityDead(targetPed) then if CanRob then if InDistance then SetEveryoneIgnorePlayer(PlayerId(), false) SetBlockingOfNonTemporaryEvents(targetPed, false) FreezeEntityPosition(targetPed, false) ClearPedTasks(targetPed) AddShockingEventAtPosition(99, GetEntityCoords(targetPed), 0.5) TriggerServerEvent('qb-traphouse:server:RobNpc', ClosestTraphouse) CanRob = false end end end end) end else if InDistance then InDistance = false end end end end else Citizen.Wait(1000) end end Citizen.Wait(3) end end) Citizen.CreateThread(function() while true do local ped = PlayerPedId() local pos = GetEntityCoords(ped) local inRange = false if ClosestTraphouse ~= nil then local data = Config.TrapHouses[ClosestTraphouse] if InsideTraphouse then local ExitDistance = #(pos - vector3(data.coords["enter"].x + POIOffsets.exit.x, data.coords["enter"].y + POIOffsets.exit.y, data.coords["enter"].z - Config.MinZOffset + POIOffsets.exit.z)) if ExitDistance < 20 then inRange = true if ExitDistance < 1 then DrawText3Ds(data.coords["enter"].x + POIOffsets.exit.x, data.coords["enter"].y + POIOffsets.exit.y, data.coords["enter"].z - Config.MinZOffset + POIOffsets.exit.z, '~b~E~w~ - Leave') if IsControlJustPressed(0, 38) then LeaveTraphouse(data) end end end local InteractDistance = #(pos - vector3(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z)) if InteractDistance < 20 then inRange = true if InteractDistance < 1 then if not IsKeyHolder then DrawText3Ds(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z + 0.2, '~b~H~w~ - View Inventory') DrawText3Ds(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z, '~b~E~w~ - Take Over (~g~$5000~w~)') if IsControlJustPressed(0, 38) then TriggerServerEvent('qb-traphouse:server:TakeoverHouse', CurrentTraphouse) end if IsControlJustPressed(0, 74) then local TraphouseInventory = {} TraphouseInventory.label = "traphouse_"..CurrentTraphouse TraphouseInventory.items = data.inventory TraphouseInventory.slots = 2 TriggerServerEvent("inventory:server:OpenInventory", "traphouse", CurrentTraphouse, TraphouseInventory) end else DrawText3Ds(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z + 0.2, '~b~H~w~ - View Inventory') DrawText3Ds(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z, '~b~E~w~ - Take Cash (~g~$'..data.money..'~w~)') if IsHouseOwner then DrawText3Ds(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z - 0.2, '~b~/multikeys~w~ [id] - To Give Keys') DrawText3Ds(data.coords["interaction"].x, data.coords["interaction"].y, data.coords["interaction"].z - 0.4, '~b~G~w~ - See Pin Code') if IsControlJustPressed(0, 47) then QBCore.Functions.Notify('Pincode: '..data.pincode) end end if IsControlJustPressed(0, 74) then local TraphouseInventory = {} TraphouseInventory.label = "traphouse_"..CurrentTraphouse TraphouseInventory.items = data.inventory TraphouseInventory.slots = 2 TriggerServerEvent("inventory:server:OpenInventory", "traphouse", CurrentTraphouse, TraphouseInventory) end if IsControlJustPressed(0, 38) then TriggerServerEvent("qb-traphouse:server:TakeMoney", CurrentTraphouse) end end end end else local EnterDistance = #(pos - data.coords["enter"]) if EnterDistance < 20 then inRange = true if EnterDistance < 1 then InTraphouseRange = true else if InTraphouseRange then InTraphouseRange = false end end end end else Citizen.Wait(2000) end Citizen.Wait(3) end end) function EnterTraphouse(data) local coords = { x = data.coords["enter"].x, y = data.coords["enter"].y, z= data.coords["enter"].z - Config.MinZOffset} TriggerServerEvent("InteractSound_SV:PlayOnSource", "houses_door_open", 0.25) data = exports['qb-interior']:CreateTrevorsShell(coords) TraphouseObj = data[1] POIOffsets = data[2] CurrentTraphouse = ClosestTraphouse InsideTraphouse = true SetRainLevel(0.0) TriggerEvent('qb-weathersync:client:DisableSync') print('Entered') FreezeEntityPosition(TraphouseObj, true) SetWeatherTypePersist('EXTRASUNNY') SetWeatherTypeNow('EXTRASUNNY') SetWeatherTypeNowPersist('EXTRASUNNY') NetworkOverrideClockTime(23, 0, 0) end function LeaveTraphouse(data) local ped = PlayerPedId() TriggerServerEvent("InteractSound_SV:PlayOnSource", "houses_door_open", 0.25) DoScreenFadeOut(250) Citizen.Wait(250) exports['qb-interior']:DespawnInterior(TraphouseObj, function() TriggerEvent('qb-weathersync:client:EnableSync') DoScreenFadeIn(250) SetEntityCoords(ped, data.coords["enter"].x, data.coords["enter"].y, data.coords["enter"].z + 0.5) SetEntityHeading(ped, 107.71) TraphouseObj = nil POIOffsets = nil CurrentTraphouse = nil InsideTraphouse = false end) end RegisterNetEvent('qb-traphouse:client:TakeoverHouse') AddEventHandler('qb-traphouse:client:TakeoverHouse', function(TraphouseId) local ped = PlayerPedId() QBCore.Functions.Progressbar("takeover_traphouse", "Taking Over", math.random(1000, 3000), false, true, { disableMovement = true, disableCarMovement = true, disableMouse = false, disableCombat = true, }, {}, {}, {}, function() -- Done TriggerServerEvent('qb-traphouse:server:AddHouseKeyHolder', PlayerData.citizenid, TraphouseId, true) end, function() QBCore.Functions.Notify("Acquisitions Canceled", "error") end) end) function HasCitizenIdHasKey(CitizenId, Traphouse) local retval = false for _, data in pairs(Config.TrapHouses[Traphouse].keyholders) do if data.citizenid == CitizenId then retval = true break end end return retval end function AddKeyHolder(CitizenId, Traphouse) if #Config.TrapHouses[Traphouse].keyholders <= 6 then if not HasCitizenIdHasKey(CitizenId, Traphouse) then if #Config.TrapHouses[Traphouse].keyholders == 0 then table.insert(Config.TrapHouses[Traphouse].keyholders, { citizenid = CitizenId, owner = true, }) else table.insert(Config.TrapHouses[Traphouse].keyholders, { citizenid = CitizenId, owner = false, }) end QBCore.Functions.Notify(CitizenId..' Has Been Added To The Traphouse!') else QBCore.Functions.Notify(CitizenId..' This Person Already Has Keys') end else QBCore.Functions.Notify('You Can Give Up To 6 People Access To The Trap House!') end IsKeyHolder = HasKey(CitizenId) IsHouseOwner = IsOwner(CitizenId) end RegisterNetEvent('qb-traphouse:client:SyncData') AddEventHandler('qb-traphouse:client:SyncData', function(k, data) Config.TrapHouses[k] = data IsKeyHolder = HasKey(PlayerData.citizenid) IsHouseOwner = IsOwner(PlayerData.citizenid) end)
-- -*- coding: utf-8 -*- ------------------------------------------------------------------------ -- Copyright © 2011-2015, RedJack, LLC. -- All rights reserved. -- -- Please see the COPYING file in this distribution for license details. ------------------------------------------------------------------------ local A = require "avro" ------------------------------------------------------------------------ -- Helpers -- The following function is from [1], and is MIT/X11-licensed. -- [1] http://snippets.luacode.org/snippets/Deep_Comparison_of_Two_Values_3 function deepcompare(t1,t2,ignore_mt) local ty1 = type(t1) local ty2 = type(t2) if ty1 ~= ty2 then return false end -- non-table types can be directly compared if ty1 ~= 'table' and ty2 ~= 'table' then return t1 == t2 end -- as well as tables which have the metamethod __eq local mt = getmetatable(t1) if not ignore_mt and mt and mt.__eq then return t1 == t2 end for k1,v1 in pairs(t1) do local v2 = t2[k1] if v2 == nil or not deepcompare(v1,v2) then return false end end for k2,v2 in pairs(t2) do local v1 = t1[k2] if v1 == nil or not deepcompare(v1,v2) then return false end end return true end ------------------------------------------------------------------------ -- Schema:type() do local function test_parse(json, expected) local schema = A.Schema:new(json) local actual = schema:type() assert(actual == expected) end local function test_prim(prim_type, expected) test_parse([[{"type": "]]..prim_type..[["}]], expected) end test_prim("boolean", A.BOOLEAN) test_prim("bytes", A.BYTES) test_prim("double", A.DOUBLE) test_prim("float", A.FLOAT) test_prim("int", A.INT) test_prim("long", A.LONG) test_prim("null", A.NULL) test_prim("string", A.STRING) end ------------------------------------------------------------------------ -- Arrays do local function test_array(prim_type, expected) local items_schema = A.Schema:new([[{"type": "]]..prim_type..[["}]]) local schema = A.ArraySchema:new(items_schema) local _, array = schema:new_wrapped_value() for _,val in ipairs(expected) do array:append(val) end local _, array2 = schema:new_wrapped_value() array2:copy_from(array) local actual = {} for _,element in array:iterate() do table.insert(actual, element) end local _, array3 = schema:new_wrapped_value() array3:set_from_ast(expected) assert(deepcompare(actual, expected)) assert(array == array2) assert(array == array3) assert(array:hash() == array2:hash()) for i,e in array:iterate(true) do assert(e:get() == expected[i]) end array:release() array2:release() array3:release() end test_array("int", { 1,2,3,4 }) test_array("string", { "", "a", "hello", "world!" }) end ------------------------------------------------------------------------ -- Maps do local function test_map(prim_type, expected) local schema = A.Schema:new([[{"type": "map", "values": "]]..prim_type..[["}]]) local _, map = schema:new_wrapped_value() for key,val in pairs(expected) do map:set(key, val) end local _, map2 = schema:new_wrapped_value() map2:copy_from(map) local actual = {} for key,element in map:iterate() do actual[key] = element end local _, map3 = schema:new_wrapped_value() map3:set_from_ast(expected) assert(deepcompare(actual, expected)) assert(map == map2) assert(map == map3) assert(map:hash() == map2:hash()) for k,e in map:iterate(true) do assert(e:get() == expected[k]) end map:release() map2:release() map3:release() end test_map("int", { a=1,b=2,c=3,d=4 }) test_map("string", { a="", b="a", c="hello", d="world!" }) end ------------------------------------------------------------------------ -- Records do local schema = A.Schema:new [[ { "type": "record", "name": "test", "fields": [ { "name": "i", "type": "int" }, { "name": "b", "type": "boolean" }, { "name": "s", "type": "string" }, { "name": "ls", "type": { "type": "array", "items": "long" } } ] } ]] local _, rec = schema:new_wrapped_value() rec.i = 1 rec.b = true rec.s = "fantastic" rec.ls:append(1) rec.ls:append(100) local _, rec2 = schema:new_wrapped_value() rec2:copy_from(rec) local _, rec3 = schema:new_wrapped_value() rec3:set_from_ast { i = 1, b = true, s = "fantastic", ls = { 1, 100 }, } assert(rec == rec2) assert(rec == rec3) rec:release() rec2:release() rec3:release() end ------------------------------------------------------------------------ -- Unions do local schema = A.Schema:new [[ [ "null", "int", { "type": "record", "name": "test", "fields": [ {"name": "a", "type": "int" } ] } ] ]] local _, union = schema:new_wrapped_value() local _, union2 = schema:new_wrapped_value() local _, union3 = schema:new_wrapped_value() union.null = nil union2:copy_from(union) union3:set_from_ast(nil) assert(union == union2) assert(union == union3) union.int = 42 union2:copy_from(union) union3:set_from_ast { int = 42 } assert(union == union2) assert(union == union3) union.test.a = 10 union2:copy_from(union) union3:set_from_ast { test = { a = 10 } } assert(union == union2) assert(union == union3) union:release() union2:release() union3:release() end ------------------------------------------------------------------------ -- ResolvedReader() do local function test_good_scalar(json1, json2, scalar) local schema1 = A.Schema:new([[{"type": "]]..json1..[["}]]) local schema2 = A.Schema:new([[{"type": "]]..json2..[["}]]) local resolver = assert(A.ResolvedReader(schema1, schema2)) local raw_value = schema1:new_raw_value() local raw_resolved = resolver:new_raw_value() raw_resolved:set_source(raw_value) raw_value:set(scalar) local wrapper_class = schema2:wrapper_class() local wrapper = wrapper_class:new() local wrapped_resolved = wrapper:wrap(raw_resolved) assert(wrapped_resolved == scalar) raw_value:release() raw_resolved:release() end test_good_scalar("int", "int", 42) test_good_scalar("int", "long", 42) local schema1 = A.Schema:new [[ { "type": "record", "name": "foo", "fields": [ {"name": "a", "type": "int"}, {"name": "b", "type": "double"} ] } ]] local schema2 = A.Schema:new [[ { "type": "record", "name": "foo", "fields": [ {"name": "a", "type": "int"} ] } ]] local resolver = assert(A.ResolvedReader(schema1, schema2)) local _, val1 = schema1:new_wrapped_value() val1.a = 1 val1.b = 42 local _, val2 = schema1:new_wrapped_value() val2.a = 1 val2.b = 100 local resolved1 = resolver:new_raw_value() resolved1:set_source(val1.raw) local resolved2 = resolver:new_raw_value() resolved2:set_source(val2.raw) assert(val1 ~= val2) assert(resolved1 == resolved2) val1:release() val2:release() resolved1:release() resolved2:release() end ------------------------------------------------------------------------ -- ResolvedWriter() do local function test_good_resolver(json1, json2) local schema1 = A.Schema:new(json1) local schema2 = A.Schema:new(json2) local resolver = assert(A.ResolvedWriter(schema1, schema2)) end local function test_good_prim(prim_type1, prim_type2) test_good_resolver([[{"type": "]]..prim_type1..[["}]], [[{"type": "]]..prim_type2..[["}]]) end local function test_bad_resolver(json1, json2) local schema1 = A.Schema:new(json1) local schema2 = A.Schema:new(json2) local resolver = assert(not A.ResolvedWriter(schema1, schema2)) end local function test_bad_prim(prim_type1, prim_type2) test_bad_resolver([[{"type": "]]..prim_type1..[["}]], [[{"type": "]]..prim_type2..[["}]]) end test_good_prim("boolean", "boolean") test_bad_prim ("boolean", "bytes") test_good_prim("bytes", "bytes") test_bad_prim ("bytes", "double") test_good_prim("double", "double") test_bad_prim ("double", "int") test_good_prim("float", "float") test_good_prim("float", "double") test_bad_prim ("float", "int") test_good_prim("int", "int") test_good_prim("int", "long") test_good_prim("int", "float") test_good_prim("int", "double") test_bad_prim ("int", "null") test_good_prim("long", "long") test_good_prim("long", "float") test_good_prim("long", "double") test_bad_prim ("long", "null") test_good_prim("null", "null") test_bad_prim ("null", "string") test_good_prim("string", "string") test_bad_prim ("string", "boolean") end ------------------------------------------------------------------------ -- Resolver:decode() do local function test_boolean(buf, expected_prim) local schema = A.Schema:new([[{"type": "boolean"}]]) local raw_actual = schema:new_raw_value() local resolver = assert(A.ResolvedWriter(schema, schema)) assert(resolver:decode(buf, raw_actual)) local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() local actual = wrapper:wrap(raw_actual) assert(actual == expected_prim) raw_actual:release() end test_boolean("\000", false) test_boolean("\001", true) local function test_int(buf, expected_prim) local schema = A.Schema:new([[{"type": "int"}]]) local raw_actual = schema:new_raw_value() local resolver = assert(A.ResolvedWriter(schema, schema)) assert(resolver:decode(buf, raw_actual)) local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() local actual = wrapper:wrap(raw_actual) assert(actual == expected_prim) raw_actual:release() end test_int("\000", 0) test_int("\001", -1) test_int("\002", 1) end ------------------------------------------------------------------------ -- Resolver:encode() do local function test_boolean(expected_buf, prim_value) local schema = A.Schema:new([[{"type": "boolean"}]]) local raw_value = schema:new_raw_value() local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() wrapper:wrap(raw_value) wrapper:fill_from(prim_value) local actual_buf = assert(raw_value:encode()) assert(actual_buf == expected_buf) raw_value:release() end test_boolean("\000", false) test_boolean("\001", true) local function test_int(expected_buf, prim_value) local schema = A.Schema:new([[{"type": "int"}]]) local raw_value = schema:new_raw_value() local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() wrapper:wrap(raw_value) wrapper:fill_from(prim_value) local actual_buf = assert(raw_value:encode()) assert(actual_buf == expected_buf) raw_value:release() end test_int("\000", 0) test_int("\001", -1) test_int("\002", 1) end ------------------------------------------------------------------------ -- Files do local expected = {1,2,3,4,5,6,7,8,9,10} local filename = "test-data.avro" local schema = A.Schema:new([[{"type": "int"}]]) local writer = A.open(filename, "w", schema) local raw_value = schema:new_raw_value() for _,i in ipairs(expected) do raw_value:set(i) writer:write_raw(raw_value) end writer:close() raw_value:release() local reader, actual -- Read once passing in a value parameter, once without. reader = A.open(filename) actual = {} raw_value = reader:read_raw() while raw_value do local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() local value = wrapper:wrap(raw_value) table.insert(actual, value) raw_value:release() raw_value = reader:read_raw() end reader:close() assert(deepcompare(expected, actual)) reader = A.open(filename) actual = {} raw_value = schema:new_raw_value() local ok = reader:read_raw(raw_value) while ok do local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() local value = wrapper:wrap(raw_value) table.insert(actual, value) ok = reader:read_raw(raw_value) end reader:close() raw_value:release() assert(deepcompare(expected, actual)) -- And cleanup os.remove(filename) end ------------------------------------------------------------------------ -- Recursive do local schema = A.record "list" { {head = A.long}, {tail = A.union {A.null, A.link "list"}}, } local raw0 = schema:new_raw_value() raw0:get("head"):set(0) raw0:get("tail"):set("list"):get("head"):set(1) raw0:get("tail"):get():get("tail"):set("null") local raw1 = schema:new_raw_value() local wrapper_class = schema:wrapper_class() local wrapper = wrapper_class:new() local wrap1 = wrapper:wrap(raw1) wrap1.head = 0 wrap1.tail.list.head = 1 wrap1.tail.list.tail.null = nil assert(raw0 == raw1) raw0:release() raw1:release() end
--Automatically generated by SWGEmu Spawn Tool v0.12 loot editor. armor_marine_chest_plate_rebel = { minimumLevel = 0, maximumLevel = -1, customObjectName = "", directObjectTemplate = "object/tangible/wearables/armor/marine/armor_marine_chest_plate_rebel.iff", craftingValues = { {"armor_rating",1,1,0}, {"armor_special_type",0,0,0}, {"armor_effectiveness",30,30,0}, {"armor_integrity",45000,45000,0}, {"armor_health_encumbrance",150,150,0}, {"armor_action_encumbrance",49,49,0}, {"armor_mind_encumbrance",19,19,0}, }, customizationStringNames = {}, customizationValues = {} } addLootItemTemplate("armor_marine_chest_plate_rebel", armor_marine_chest_plate_rebel)
-- For poking and more complicated stuff gradually. -- Note: reset the server when you change this, -- or it will keep using the old version! local tab = require "alt_require.test.toys.ret_tab" -- Zero arguments is okey. print(tab.no_args()) -- Testing if `pairs` can work. for k,v in pairs(tab) do print(k,v) end -- Calling from tables, accessing tables, calling functions. print(tab.c.d(tab.a(tab.b("1,2"), "3"))) -- Passing received functions back. print(tab.ff(tab.c.d, "75")) -- Passing received tables back. print(tab.gg(tab.c, "@@")) -- Receiving tables with loops. assert(tab.loop == tab.loop.self) -- local x = require "alt_require.test.toys.ret_list" print(x[1], x[2], x[3], x[4]) print(unpack(x))
local _2afile_2a = "fnl/snap/layout/init.fnl" local _0_ do local name_0_ = "snap.layout" local module_0_ do local x_0_ = package.loaded[name_0_] if ("table" == type(x_0_)) then module_0_ = x_0_ else module_0_ = {} end end module_0_["aniseed/module"] = name_0_ module_0_["aniseed/locals"] = ((module_0_)["aniseed/locals"] or {}) do end (module_0_)["aniseed/local-fns"] = ((module_0_)["aniseed/local-fns"] or {}) do end (package.loaded)[name_0_] = module_0_ _0_ = module_0_ end local autoload local function _1_(...) return (require("aniseed.autoload")).autoload(...) end autoload = _1_ local function _2_(...) local ok_3f_0_, val_0_ = nil, nil local function _2_() return {} end ok_3f_0_, val_0_ = pcall(_2_) if ok_3f_0_ then _0_["aniseed/local-fns"] = {} return val_0_ else return print(val_0_) end end local _local_0_ = _2_(...) local _2amodule_2a = _0_ local _2amodule_name_2a = "snap.layout" do local _ = ({nil, _0_, nil, {{}, nil, nil, nil}})[2] end local function lines() return vim.api.nvim_get_option("lines") end local function columns() return vim.api.nvim_get_option("columns") end local function middle(total, size) return math.floor(((total - size) / 2)) end local function from_bottom(size, offset) return (lines() - size - offset) end local function size(_25width, _25height) return {height = math.floor((lines() * _25height)), width = math.floor((columns() * _25width))} end local _25centered do local v_0_ do local v_0_0 local function _25centered0(_25width, _25height) local _let_0_ = size(_25width, _25height) local height = _let_0_["height"] local width = _let_0_["width"] return {col = middle(columns(), width), height = height, row = middle(lines(), height), width = width} end v_0_0 = _25centered0 _0_["%centered"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["%centered"] = v_0_ _25centered = v_0_ end local _25bottom do local v_0_ do local v_0_0 local function _25bottom0(_25width, _25height) local _let_0_ = size(_25width, _25height) local height = _let_0_["height"] local width = _let_0_["width"] return {col = middle(columns(), width), height = height, row = from_bottom(height, 8), width = width} end v_0_0 = _25bottom0 _0_["%bottom"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["%bottom"] = v_0_ _25bottom = v_0_ end local _25top do local v_0_ do local v_0_0 local function _25top0(_25width, _25height) local _let_0_ = size(_25width, _25height) local height = _let_0_["height"] local width = _let_0_["width"] return {col = middle(columns(), width), height = height, row = 5, width = width} end v_0_0 = _25top0 _0_["%top"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["%top"] = v_0_ _25top = v_0_ end local centered do local v_0_ do local v_0_0 local function centered0() return _25centered(0.9, 0.7) end v_0_0 = centered0 _0_["centered"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["centered"] = v_0_ centered = v_0_ end local bottom do local v_0_ do local v_0_0 local function bottom0() return _25bottom(0.9, 0.7) end v_0_0 = bottom0 _0_["bottom"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["bottom"] = v_0_ bottom = v_0_ end local top do local v_0_ do local v_0_0 local function top0() return _25top(0.9, 0.7) end v_0_0 = top0 _0_["top"] = v_0_0 v_0_ = v_0_0 end local t_0_ = (_0_)["aniseed/locals"] t_0_["top"] = v_0_ top = v_0_ end return nil
remote = require('net.box') test_run = require('test_run').new() engine = test_run:get_cfg('engine') box.sql.execute('pragma sql_default_engine=\''..engine..'\'') errinj = box.error.injection fiber = require('fiber') box.sql.execute('create table test (id int primary key, a float, b text)') box.schema.user.grant('guest','read,write,execute', 'universe') cn = remote.connect(box.cfg.listen) cn:ping() -- gh-2601 iproto messages are corrupted errinj = box.error.injection fiber = require('fiber') errinj.set("ERRINJ_WAL_DELAY", true) insert_res = nil select_res = nil function execute_yield() insert_res = cn:execute("insert into test values (100, 1, '1')") end function execute_notyield() select_res = cn:execute('select 1') end f1 = fiber.create(execute_yield) while f1:status() ~= 'suspended' do fiber.sleep(0) end f2 = fiber.create(execute_notyield) while f2:status() ~= 'dead' do fiber.sleep(0) end errinj.set("ERRINJ_WAL_DELAY", false) while f1:status() ~= 'dead' do fiber.sleep(0) end insert_res select_res cn:close() box.sql.execute('drop table test') -- -- gh-3326: after the iproto start using new buffers rotation -- policy, SQL responses could be corrupted, when DDL/DML is mixed -- with DQL. Same as gh-3255. -- box.sql.execute('CREATE TABLE test (id integer primary key)') cn = remote.connect(box.cfg.listen) ch = fiber.channel(200) errinj.set("ERRINJ_IPROTO_TX_DELAY", true) for i = 1, 100 do fiber.create(function() for j = 1, 10 do cn:execute('REPLACE INTO test VALUES (1)') end ch:put(true) end) end for i = 1, 100 do fiber.create(function() for j = 1, 10 do cn.space.TEST:get{1} end ch:put(true) end) end for i = 1, 200 do ch:get() end errinj.set("ERRINJ_IPROTO_TX_DELAY", false) box.sql.execute('DROP TABLE test') box.schema.user.revoke('guest', 'read,write,execute', 'universe') ---- ---- gh-3273: Move SQL TRIGGERs into server. ---- box.sql.execute("CREATE TABLE t1(id INTEGER PRIMARY KEY, a INTEGER);"); box.sql.execute("CREATE TABLE t2(id INTEGER PRIMARY KEY, a INTEGER);"); box.error.injection.set("ERRINJ_WAL_IO", true) box.sql.execute("CREATE TRIGGER t1t INSERT ON t1 BEGIN INSERT INTO t2 VALUES (1, 1); END;") box.sql.execute("CREATE INDEX t1a ON t1(a);") box.error.injection.set("ERRINJ_WAL_IO", false) box.sql.execute("CREATE TRIGGER t1t INSERT ON t1 BEGIN INSERT INTO t2 VALUES (1, 1); END;") box.sql.execute("INSERT INTO t1 VALUES (3, 3);") box.sql.execute("SELECT * from t1"); box.sql.execute("SELECT * from t2"); box.error.injection.set("ERRINJ_WAL_IO", true) box.sql.execute("DROP TRIGGER t1t;") box.error.injection.set("ERRINJ_WAL_IO", false) box.sql.execute("DELETE FROM t1;") box.sql.execute("DELETE FROM t2;") box.sql.execute("INSERT INTO t1 VALUES (3, 3);") box.sql.execute("SELECT * from t1"); box.sql.execute("SELECT * from t2"); box.sql.execute("DROP TABLE t1;") box.sql.execute("DROP TABLE t2;") -- Tests which are aimed at verifying work of commit/rollback -- triggers on _fk_constraint space. -- box.sql.execute("CREATE TABLE t3 (id NUMERIC PRIMARY KEY, a INT REFERENCES t3, b INT UNIQUE);") t = box.space._fk_constraint:select{}[1]:totable() errinj = box.error.injection errinj.set("ERRINJ_WAL_IO", true) -- Make constraint reference B field instead of id. t[9] = {2} box.space._fk_constraint:replace(t) errinj.set("ERRINJ_WAL_IO", false) box.sql.execute("INSERT INTO t3 VALUES (1, 2, 2);") errinj.set("ERRINJ_WAL_IO", true) box.sql.execute("ALTER TABLE t3 ADD CONSTRAINT fk1 FOREIGN KEY (b) REFERENCES t3;") errinj.set("ERRINJ_WAL_IO", false) box.sql.execute("INSERT INTO t3 VALUES(1, 1, 3);") box.sql.execute("DELETE FROM t3;") box.snapshot() box.sql.execute("ALTER TABLE t3 ADD CONSTRAINT fk1 FOREIGN KEY (b) REFERENCES t3;") box.sql.execute("INSERT INTO t3 VALUES(1, 1, 3);") errinj.set("ERRINJ_WAL_IO", true) box.sql.execute("ALTER TABLE t3 DROP CONSTRAINT fk1;") box.sql.execute("INSERT INTO t3 VALUES(1, 1, 3);") errinj.set("ERRINJ_WAL_IO", false) box.sql.execute("DROP TABLE t3;")
-- takeover arguments -- ####################################################### -- local section = arg[1] --m = Map("wireless", translate("Wireless Overview")) --m:chain("network") --m.pageaction = false -- local m = Map("mywebserver", translate("Log view").. " - " .. arg[1]:upper(), translate("Log view test")) -- .. " - " .. arg[1]:upper())) -- m:chain("mywebserver") -- m.pageaction = false -- local fs = require "nixio.fs" local uci = require "luci.model.uci" local mws = require "luci.tools.mywebserver" -- multiused functions --arg[1]:upper() local d = mws.get_fnl(arg[1]) m = SimpleForm("mywebserver", translate("Log view").. " - '" .. d .."'", translate("Log view test")) m.reset = false m.submit = false t = m:field(TextValue, "logview") t.rmempty = true t.rows = 50 t.wrap = "off" function t.cfgvalue() line = "" nl, lines = mws.get_nl(d) if nl>0 then -- fs.readfile(d) -- print all line numbers and their contents --for k,v in pairs(lines) do -- print('line[' .. k .. ']', v) --end ii=1 if nl>t.rows then ii=nl-t.rows end line = lines[ii] for i=ii+1,nl do line = line .."\n".. lines[i] end end return line end function m.handle(self, state, data) -- if state == FORM_VALID then -- if data.crons then -- fs.writefile(cronfile, data.crons:gsub("\r\n", "\n")) -- luci.sys.call("/usr/bin/crontab %q" % cronfile) -- else -- fs.writefile(cronfile, "") -- end -- end return true end m.redirect = luci.dispatcher.build_url("admin/mywebserver/logview") return m
-- Luaver module -- -- Module used to check if the compiler supports the running lua version. local luaver = {} -- Get lua version. function luaver.getversion() return _VERSION:match('%w+ ([0-9.]+)') end -- List of supported lua version. local supported_versions = {'5.3', '5.4'} -- Check if the running lua version is supported, throws an error if not. function luaver.check() local v = luaver.getversion() for i=1,#supported_versions do if supported_versions[i] == v then return end end --luacov:disable error(string.format( '%s is not supported, please a supported Lua version like Lua %s', _VERSION, supported_versions[1])) --luacov:enable end return luaver
local http = require "http" local io = require "io" local json = require "json" local stdnse = require "stdnse" local tab = require "tab" local table = require "table" local ipOps = require "ipOps" description = [[ Lists the geographic locations of each hop in a traceroute and optionally saves the results to a KML file, plottable on Google earth and maps. ]] --- -- @usage -- nmap --traceroute --script traceroute-geolocation -- -- @output -- | traceroute-geolocation: -- | hop RTT ADDRESS GEOLOCATION -- | 1 ... -- | 2 ... -- | 3 ... -- | 4 ... -- | 5 16.76 e4-0.barleymow.stk.router.colt.net (194.68.128.104) 62,15 Sweden (Unknown) -- | 6 48.61 te0-0-2-0-crs1.FRA.router.colt.net (212.74.65.49) 54,-2 United Kingdom (Unknown) -- | 7 57.16 87.241.37.146 42,12 Italy (Unknown) -- | 8 157.85 212.162.64.146 42,12 Italy (Unknown) -- | 9 ... -- |_ 10 ... -- @xmloutput -- <table> -- <elem key="hop">1</elem> -- </table> -- <table> -- <elem key="hop">2</elem> -- </table> -- <table> -- <elem key="hop">3</elem> -- </table> -- <table> -- <elem key="hop">4</elem> -- </table> -- <table> -- <elem key="hop">5</elem> -- <elem key="rtt">16.76</elem> -- <elem key="ip">194.68.128.104</elem> -- <elem key="hostname">e4-0.barleymow.stk.router.colt.net</elem> -- <elem key="lat">62</elem> -- <elem key="lon">15</elem> -- </table> -- <table> -- <elem key="hop">6</elem> -- <elem key="rtt">48.61</elem> -- <elem key="ip">212.74.65.49</elem> -- <elem key="hostname">te0-0-2-0-crs1.FRA.router.colt.net</elem> -- <elem key="lat">54</elem> -- <elem key="lon">-2</elem> -- </table> -- -- @args traceroute-geolocation.kmlfile full path and name of file to write KML -- data to. The KML file can be used in Google earth or maps to plot the -- traceroute data. -- author = "Patrik Karlsson" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = {"safe", "external", "discovery"} local arg_kmlfile = stdnse.get_script_args(SCRIPT_NAME .. ".kmlfile") hostrule = function(host) if ( not(host.traceroute) ) then return false end return true end -- -- GeoPlugin requires no API key and has no limitations on lookups -- local function geoLookup(ip) local response = http.get("www.geoplugin.net", 80, "/json.gp?ip="..ip) local stat, loc = json.parse(response.body:match("geoPlugin%((.+)%)")) if not stat then return nil end local output = {} local regionName = (loc.geoplugin_regionName == json.NULL) and "Unknown" or loc.geoplugin_regionName return loc.geoplugin_latitude, loc.geoplugin_longitude, regionName, loc.geoplugin_countryName end local function createKMLFile(filename, coords) local header = '<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://earth.google.com/kml/2.0"><Document><Placemark><LineString><coordinates>\r\n' local footer = '</coordinates></LineString><Style><LineStyle><color>#ff0000ff</color></LineStyle></Style></Placemark></Document></kml>' local output = "" for _, coord in ipairs(coords) do output = output .. ("%s,%s, 0.\r\n"):format(coord.lon, coord.lat) end local f = io.open(filename, "w") if ( not(f) ) then return false, "Failed to create KML file" end f:write(header .. output .. footer) f:close() return true end -- Tables used to accumulate output. local output_structured = {} local output = tab.new(4) local coordinates = {} local function output_hop(count, ip, name, rtt, lat, lon, ctry, reg) if ip then local label if name then label = ("%s (%s)"):format(name or "", ip) else label = ("%s"):format(ip) end if lat then table.insert(output_structured, { hop = count, ip = ip, hostname = name, rtt = ("%.2f"):format(rtt), lat = lat, lon = lon }) tab.addrow(output, count, ("%.2f"):format(rtt), label, ("%d,%d %s (%s)"):format(lat, lon, ctry, reg)) table.insert(coordinates, { hop = count, lat = lat, lon = lon }) else table.insert(output_structured, { hop = count, ip = ip, hostname = name, rtt = ("%.2f"):format(rtt) }) tab.addrow(output, count, ("%.2f"):format(rtt), label, ("%s,%s"):format("- ", "- ")) end else table.insert(output_structured, { hop = count }) tab.addrow(output, count, "...") end end action = function(host) tab.addrow(output, "HOP", "RTT", "ADDRESS", "GEOLOCATION") for count = 1, #host.traceroute do local hop = host.traceroute[count] -- avoid timedout hops, marked as empty entries -- do not add the current scanned host.ip if hop.ip then local rtt = tonumber(hop.times.srtt) * 1000 if ( not(ipOps.isPrivate(hop.ip) ) ) then local lat, lon, reg, ctry = geoLookup(hop.ip) output_hop(count, hop.ip, hop.name, rtt, lat, lon, ctry, reg) else output_hop(count, hop.ip, hop.name, rtt) end else output_hop(count) end end if (#output_structured > 0) then output = tab.dump(output) if ( arg_kmlfile ) then if ( not(createKMLFile(arg_kmlfile, coordinates)) ) then output = output .. ("\n\nERROR: Failed to write KML to file: %s"):format(arg_kmlfile) end end return output_structured, stdnse.format_output(true, output) end end
local serpent = require("lib.serpent") local disassembler = require("disassembler") local io_util = require("io_util") local Path = require("lib.path") Path.set_main_separator("/") local error_code_util = require("error_code_util") local unsafe = true local print_progress = true local use_regular_lua_compiler = false local use_phobos_compiler = true local use_il = false local do_create_inline_iife = false local do_fold_const = true local do_fold_control_statements = true local eval_instruction_count = true local eval_byte_count = true local create_tokenizer_output = false local create_disassembly = true local show_keys_in_disassembly = false local load_and_run_compiled_funcs = false local run_count = 1 local total_lua_inst_count = 0 local total_pho_inst_count = 0 local total_lua_byte_count = 0 local total_pho_byte_count = 0 -- local ill = require("indexed_linked_list") -- local list = ill.new() -- ill.append(list, "one") -- ill.append(list, "two") -- ill.append(list, "three") -- ill.append(list, "four") -- local function pretty_print() -- local out = {} -- for i = list.first.index, list.last.index do -- if list.lookup[i] then -- out[#out+1] = list.lookup[i].value -- else -- out[#out+1] = "." -- end -- out[#out+1] = " " -- end -- print(table.concat(out)) -- end -- local last_index = list.last.index -- local i = 0 -- local target = list.first.next -- repeat -- pretty_print() -- i = i + 1 -- -- ill.insert_before(list, list.last.prev, i) -- -- ill.insert_after(list, list.first.next, i) -- target = ill.insert_after(list, target, i) -- until list.last.index ~= last_index -- print() -- pretty_print() -- do return end io_util.mkdir_recursive("temp") local function compile(filename) if print_progress then print("compiling '"..filename.."'...") end local file = assert(io.open(filename,"r")) local text = file:read("*a") local lines if create_disassembly then file:seek("set") lines = {} for line in file:lines() do lines[#lines+1] = {line = line} end -- add trailing line because :lines() doesn't return that one if it's empty -- (since regardless of if the previous character was a newline, -- the current one is eof which returns nil) if text:sub(#text) == "\n" then lines[#lines+1] = {line = ""} end end file:close() if create_disassembly then if not lines[1] then -- empty file edge case lines[1] = {line = ""} end lines[1][1] = "-- < line column compiler : func_id pc opcode description params >\n" end local function format_line_num(line_num) -- this didn't work (getting digit count): (math.ceil((#lines) ^ (-10))), so now i cheat: -- local h = ("%"..(#tostring(#lines)).."d") -- local f = string.format("%"..(#tostring(#lines)).."d", line_num) return string.format("%"..(#tostring(#lines)).."d", line_num) end local function get_line(line) return assert(lines[line] or lines[1]) end local instruction_count if eval_instruction_count then instruction_count = {} end local add_func_to_lines do local func_id local function add_func_to_lines_recursive(prefix, func) if eval_instruction_count then instruction_count[prefix] = instruction_count[prefix] or 0 instruction_count[prefix] = instruction_count[prefix] + #func.instructions end if create_disassembly then func_id = func_id + 1 disassembler.get_disassembly(func, function(description) local line = get_line(func.line_defined) line[#line+1] = "-- "..prefix..": "..(description:gsub("\n", "\n-- "..prefix..": ")) end, function(line_num, column_num, instruction_index, padded_opcode, description, description_with_keys, raw_values) description = show_keys_in_disassembly and description_with_keys or description local line = get_line(line_num) local min_description_len = 50 line[#line+1] = string.format("-- %s %3d %s: %2df %4d %s %s%s %s", format_line_num(line_num or 0), column_num or 0, prefix, func_id, instruction_index, padded_opcode, description, (min_description_len - #description > 0) and string.rep(" ", min_description_len - #description) or "", raw_values ) end) end for _, inner_func in ipairs(func.inner_functions) do add_func_to_lines_recursive(prefix, inner_func) end end function add_func_to_lines(prefix, func) func_id = 0 add_func_to_lines_recursive(prefix, func) end end local lua_func, lua_dumped local err if use_regular_lua_compiler then lua_func, err = loadfile(filename) if lua_func then lua_dumped = string.dump(lua_func) add_func_to_lines("lua", disassembler.disassemble(lua_dumped)) else print(err) end end -- for _, token in require("tokenize")(text) do -- print(serpent.block(token)) -- end local pho_dumped do local pcall = pcall -- i added this because the debugger was not breaking on error inside a pcall -- and now it suddenly does break even with this set to false. -- i don't understand if unsafe then pcall = function(f, ...) return true, f(...) end end if create_tokenizer_output then local tokens = {} for _, token in require("tokenize")(text) do tokens[#tokens+1] = token end io_util.write_file("temp/tokens.lua", serpent.dump(tokens, {indent = " ", sortkeys = true})) end local success, main, parser_errors = pcall(require("parser"), text, "@"..filename) if not success then print(main) goto finish end -- print(serpent.block(main)) if parser_errors[1] then error(error_code_util.get_message_for_list(parser_errors, "syntax errors")) end success, err = pcall(require("jump_linker"), main) if not success then print(err) goto finish end if err[1] then error(error_code_util.get_message_for_list(err, "syntax errors")) end if use_il then local il success, il = pcall(require("intermediate_language"), main) if not success then print(il) goto finish end success, err = pcall(function() local il_func_id = 0 local pretty_print = require("il_pretty_print") local function il_add_func_lines(func) il_func_id = il_func_id + 1 -- "-- < line column compiler : func_id pc opcode description params >\n" pretty_print(func, function(pc, label, description, inst) local line = get_line(inst.position and inst.position.line) line[#line+1] = string.format( "-- %s %3d IL1: %2df %4d %s %s", format_line_num(inst.position and inst.position.line or 0), inst.position and inst.position.column or 0, il_func_id, pc, label, description ) end) for _, inner_func in ipairs(func.inner_functions) do il_add_func_lines(inner_func) end end il_add_func_lines(il) end) if not success then print(err) goto finish end end if do_fold_const then success, err = pcall(require("optimize.fold_const"), main) if not success then print(err) goto finish end end if do_fold_control_statements then success, err = pcall(require("optimize.fold_control_statements"), main) if not success then print(err) goto finish end end if do_create_inline_iife then success, err = pcall(require("optimize.create_inline_iife"), main) if not success then print(err) goto finish end end local compiled success, compiled = pcall(require("compiler"), main) if not success then print(compiled) goto finish end -- print(serpent.dump(main,{indent = ' ', sparse = true, sortkeys = false, comment=true})) if eval_byte_count or create_disassembly then add_func_to_lines("pho", compiled) end success, pho_dumped = pcall(require("dump"), compiled) if not success then print(pho_dumped) goto finish end local disassembled success, disassembled = pcall(disassembler.disassemble, pho_dumped) if not success then print(disassembled) goto finish end if load_and_run_compiled_funcs then local pho_func if use_phobos_compiler then pho_func, err = load(pho_dumped) if not pho_func then print(err) goto finish end end if use_regular_lua_compiler and lua_func then print("----------") print("lua:") success, err = pcall(lua_func) if not success then print(err) goto finish end end if use_regular_lua_compiler or use_phobos_compiler then print("----------") end if use_phobos_compiler then print("pho:") success, err = pcall(pho_func) if not success then print(err) goto finish end print("----------") end end end ::finish:: if eval_instruction_count then local diff = instruction_count.lua and instruction_count.pho and instruction_count.pho - instruction_count.lua or nil print(" #instructions: "..serpent.line(instruction_count)..(diff and (" diff: "..diff) or "")) total_lua_inst_count = total_lua_inst_count + (instruction_count.lua or 0) total_pho_inst_count = total_pho_inst_count + (instruction_count.pho or 0) end if eval_byte_count then local lua = use_regular_lua_compiler and lua_dumped and #lua_dumped or nil local pho = use_phobos_compiler and pho_dumped and #pho_dumped or nil local diff = lua and pho and pho - lua or nil print(" #bytes: "..serpent.line{lua = lua, pho = pho} ..(diff and (" diff: "..diff) or "") ) total_lua_byte_count = total_lua_byte_count + (lua or 0) total_pho_byte_count = total_pho_byte_count + (pho or 0) end if create_disassembly then local result = {} for _, line in ipairs(lines) do for _, pre in ipairs(line) do result[#result+1] = pre end result[#result+1] = line.line end io_util.write_file("temp/phobos_disassembly.lua", table.concat(result, "\n")) end end local filenames if ... then filenames = {...} else filenames = require("debugging.debugging_util").find_lua_source_files() end local start_time = os.clock() for i = 1, run_count do for _, filename in ipairs(filenames) do compile(filename) if print_progress then print() end end print((os.clock() - start_time) / i) if print_progress then print() print() end end if eval_instruction_count and use_regular_lua_compiler and use_phobos_compiler then print("total instruction count diff: "..(total_pho_inst_count - total_lua_inst_count) .." ("..total_lua_inst_count.." => "..total_pho_inst_count.."; " ..string.format("%.2f", (total_pho_inst_count / total_lua_inst_count) * 100).."%)" ) end if eval_byte_count and use_regular_lua_compiler and use_phobos_compiler then print("total byte count diff: "..(total_pho_byte_count - total_lua_byte_count) .." ("..total_lua_byte_count.." => "..total_pho_byte_count.."; " ..string.format("%.2f", (total_pho_byte_count / total_lua_byte_count) * 100).."%)" ) end
local migration = {} function migration.player_table(player_table) player_table.preferences.enable_recipe_comments = nil end function migration.subfactory(subfactory) for _, floor in pairs(Subfactory.get_all_floors(subfactory)) do for _, line in pairs(Floor.get_in_order(floor, "Line")) do line.machine.limit = line.machine.count_cap line.machine.count_cap = nil line.machine.hard_limit = false end end end return migration
client_script 'ped_shop.lua' client_script 'ped_bank.lua' client_script 'ped_shopclothes.lua' client_script 'ped_shopfleeca.lua' client_script 'ped_wel_police.lua' client_script 'ped_police.lua' client_script 'ped_sadot.lua' client_script 'tp_client.lua' client_script 'storespnj_client.lua' --client_script 'ped_secu.lua' server_script 'storespnj_server.lua'
vim.g.exchange_no_mappings = 1 fey.editor_exchange.exchange = function() fey.editor_exchange.exchange = nil vim.cmd'packadd vim-exchange' vim.cmd'nmap gx <Plug>(Exchange)' vim.cmd'xmap gx <Plug>(Exchange)' vim.cmd'nmap gx_ <Plug>(ExchangeClear)' vim.cmd'nmap gxx <Plug>(ExchangeLine)' end vim.cmd'nmap gx <Cmd>lua fey.editor_exchange.exchange()<CR>gx' vim.cmd'xmap gx <Cmd>lua fey.editor_exchange.exchange()<CR>gx' vim.cmd'nmap gx_ <Cmd>lua fey.editor_exchange.exchange()<CR>gx' vim.cmd'nmap gxx <Cmd>lua fey.editor_exchange.exchange()<CR>gxx'
object_tangible_wearables_necklace_necklace_ace_pilot_neutral_f = object_tangible_wearables_necklace_shared_necklace_ace_pilot_neutral_f:new { } ObjectTemplates:addTemplate(object_tangible_wearables_necklace_necklace_ace_pilot_neutral_f, "object/tangible/wearables/necklace/necklace_ace_pilot_neutral_f.iff")
local scoreboard local sb_timer = 0 function OnPackageStart() --local width, height = GetScreenSize() --ZOrder = 5 and FrameRate = 10 --scoreboard = CreateWebUI(width / 4.7, height / 4.7, width / 1.3, height / 1.3, 5, 10) scoreboard = CreateWebUI(450.0, 200.0, 700.0, 450.0, 5, 10) LoadWebFile(scoreboard, "http://asset/scoreboard/gui/scoreboard.html") SetWebAlignment(scoreboard, 0.0, 0.0) SetWebAnchors(scoreboard, 0.0, 0.0, 1.0, 1.0) SetWebVisibility(scoreboard, WEB_HIDDEN) end AddEvent("OnPackageStart", OnPackageStart) function OnPackageStop() DestroyTimer(sb_timer) DestroyWebUI(scoreboard) end AddEvent("OnPackageStop", OnPackageStop) function OnResolutionChange(width, height) AddPlayerChat("Resolution changed to "..width.."x"..height) --SetWebSize(scoreboard, width / 1.5, height / 1.5) end AddEvent("OnResolutionChange", OnResolutionChange) function OnKeyPress(key) if key == "Tab" then if IsValidTimer(sb_timer) then DestroyTimer(sb_timer) end sb_timer = CreateTimer(UpdateScoreboardData, 1500) UpdateScoreboardData() SetWebVisibility(scoreboard, WEB_VISIBLE) end end AddEvent("OnKeyPress", OnKeyPress) function OnKeyRelease(key) if key == "Tab" then DestroyTimer(sb_timer) SetWebVisibility(scoreboard, WEB_HIDDEN) end end AddEvent("OnKeyRelease", OnKeyRelease) function UpdateScoreboardData() CallRemoteEvent("UpdateScoreboardData") end function OnGetScoreboardData(servername, count, maxplayers, players) --print(servername, count, maxplayers) ExecuteWebJS(scoreboard, "SetServerName('"..servername.."')") ExecuteWebJS(scoreboard, "SetPlayerCount("..count..", "..maxplayers..")") ExecuteWebJS(scoreboard, "RemovePlayers()") --print("OnGetScoreboardData "..#players) for k, v in ipairs(players) do ExecuteWebJS(scoreboard, "AddPlayer("..k..", '"..v[1].."', '"..v[2].."', '"..v[3].."')") end end AddRemoteEvent("OnGetScoreboardData", OnGetScoreboardData)
--[[ only for debug table_print = require('table_print') table.print = table_print.print_r --]] local wrapClass = {'info', 'tip', 'warn', 'alert', 'help', 'introduction', 'problemset', 'solu'} local solu = false function Meta(meta) solu = meta['ext-wrap-solu'] end function inTable(t, val) for _, v in pairs(t) do if v == val then return true end end return false end function wrap(el, option) e = el.attr.classes[1] ret = pandoc.Div({}) table.insert(ret.content, pandoc.RawBlock("latex", "\\begin{" .. e .. "}" .. option)) -- introduction 和 problemset中 需要以\item开头,因此需要将 BulletList 转换为rawtex if e == 'introduction' or e == 'problemset' then for k,v in pairs(el.content) do if v.t == 'BulletList' then for i,j in pairs(v.content) do for l,m in pairs(j) do if l == 1 then table.insert(ret.content, pandoc.RawBlock("latex", "\\item ")) end table.insert(ret.content, m) end end else table.insert(ret.content, v) end end else for k,v in pairs(el.content) do table.insert(ret.content, v) end end table.insert(ret.content, pandoc.RawBlock("latex", "\\end{" .. e .. "}")) return ret end function Div(el) if inTable(wrapClass, el.attr.classes[1]) then if el.attr.attributes['caption'] ~= nil then option = "[" .. el.attr.attributes['caption'] .. "]" else option = "" end -- 隐藏solu if el.attr.classes[1] == "solu" and not solu then return pandoc.Div({}) end -- 特殊符号转义 option = string.gsub(option, "_", "\\_{}") return wrap(el, option) end end -- Normally, pandoc will run the function in the built-in order Inlines -> -- Blocks -> Meta -> Pandoc. We instead want Meta -> Blocks. Thus, we must -- define our custom order: return { {Meta = Meta}, {Div = Div}, }
-- Routine for NPC "Morgiana" velocity = 50 loadRoutine = function(R, W) if (W:isConditionFulfilled("boss","BossMercenaries")) then R:setDisposed() return end R:setTilePosition(19,5) R:setFacingRight() R:wait(10000) R:goToTile(20,5) R:goToTile(20,7) R:goToTile(18,7) R:goToTile(18,11) R:goToTile(15,11) R:goToTile(15,10) R:setFacingDown() R:wait(10000) R:goToTile(15,11) R:goToTile(18,11) R:goToTile(18,7) R:goToTile(20,7) R:goToTile(20,5) R:goToTile(19,5) end