content
stringlengths
5
1.05M
local M = {} function M.config() require('filetype').setup({ overrides = { complex = { ["Dockerfile.*"] = "dockerfile" } } }) end return M
local MainScene = class("MainScene", cc.load("mvc").ViewBase) function MainScene:onCreate() -- add background image display.newSprite("MainSceneBg.jpg") :move(display.center) :addTo(self) -- add play button local playButton = cc.MenuItemImage:create("PlayButton.png", "PlayButton.png") :onClicked(function() self:getApp():enterScene("PlayScene") end) cc.Menu:create(playButton) :move(display.cx, display.cy - 200) :addTo(self) end return MainScene
local ts_query = require 'vim.treesitter.query' local nts_parsers = require('nvim-treesitter.parsers') local ts_utils = require('nvim-treesitter.ts_utils') --DELETE --local parser = vim.treesitter.get_parser(py_bufnr, 'python') --tstree = parser:parse() --local root_node = tstree:root() --query = ts_query.get_query('python', 'locals') local M = {} local TSOutline = {} TSOutline.__index = TSOutline -- Contains definition and/or scope information. -- At least one of `def` or `scope` must be populated. -- @param def {definition_name, definition_node} -- @param scope {scope_name, scope_node} function TSOutline.new(def, scope, associated) local has_def = not vim.tbl_isempty(def) local has_scope = not vim.tbl_isempty(scope) local def_type = has_def and def[1][1] or nil local def_node = has_def and def[1][2] or nil local scope_node = has_scope and scope[1][2] or nil return setmetatable({ --If this definition defines a scope, this contains the node. --This is needed to allow checking whether or not children are in this definition. scope_node = scope_node, --This is a pointer to the containing scope or def. parent = nil, --This is a pointer to scopes or def that belong in our scope. children = {}, --This contains the specific node for the definition capture. --This allows us to print the definition. definition_node = def_node, --This is the type of definition (e.g. definition.function or definition.parameters) definition_type = def_type, --This will give us the associated node for a definition, if it exists. e.g. --MyLuaClass.some_method will have a definition for `some_method` and an --associated node of `MyLuaClass` associated = associated, }, TSOutline) end -- STEP 1A) -- Iterates over the captures in a match to find defintion -- or scope captures. -- @param match Match value as returned by `query:iter_matches(...)` function M.get_definitions_and_scopes_in_match(match, query) local defs = {} local scopes = {} local associated = nil local capture_names = {} for id, node in pairs(match) do local capture_name = query.captures[id] if string.match(capture_name, 'definition') then if string.match(capture_name, 'associated') then associated = node end table.insert(defs, {capture_name, node}) table.insert(capture_names, capture_name) end if string.match(capture_name, 'scope') then table.insert(scopes, {capture_name, node}) end end if #capture_names >= 2 then -- N.B. In cases where we have multiple definitions within a match, it -- becomes impossible to tell to which definition children of the match -- belong. So far the only time where we see two definitions inside of a -- scope (which means there could be children) is in -- `queries/lua/locals.scm` In this case, it doesn't actually make sense to -- even use the `associated` capture as a definition so we simply delete it -- and save it as a separate type for display purposes. if vim.tbl_contains(capture_names, 'definition.associated') then defs = vim.tbl_filter( function(x) return not string.match(x[1], 'associated') end, defs ) end else associated = nil end return defs, scopes, associated end -- Convenience method. function M.can_parse_buffer(bufnr) local lang = nts_parsers.get_buf_lang(bufnr) return nts_parsers.has_parser(lang) end --STEP 1) function M.get_scope_and_definition_captures(bufnr, query_group) local lang = nts_parsers.get_buf_lang(bufnr) local parser = vim.treesitter.get_parser(bufnr, lang) -- TODO(elpiloto): Add safety checks here. local tstree = parser:parse()[1] query_group = query_group or 'locals' local query = ts_query.get_query(lang, query_group) local root = tstree:root() -- Return values local scopes_to_tsdef = {} local defs_to_tsdef = {} local all_defs = {} local start_row, _, end_row, _ = root:range() for _, match in query:iter_matches(root, bufnr, start_row, end_row+1) do --NB: Currently we assume there's only a single definition that lives --in the same match as a scope. If this assumption is violated, please --send @ElPIloto an example. local defs, scopes, associated = M.get_definitions_and_scopes_in_match(match, query) if #scopes + #defs > 0 then local ts_def = TSOutline.new(defs, scopes, associated) table.insert(all_defs, ts_def) if #scopes > 0 then scopes_to_tsdef[scopes[1][2]:id()] = ts_def end if #defs > 0 then for i, def in ipairs(defs) do local ts_def2 = TSOutline.new({def}, scopes) defs_to_tsdef[def[2]:id()] = ts_def2 --defs_to_tsdef[defs[1][2]:id()] = ts_def2 if #defs >= 2 then print(tostring(i), 'Multiple definitions in a scope', M.get_definition_info(ts_def2), vim.inspect(defs)) end end end end end return scopes_to_tsdef, defs_to_tsdef, all_defs end --STEP 2A) local function find_parent(tsdef, scopes_to_tsdef) local node = nil if tsdef.scope_node then node = tsdef.scope_node:parent() else node = tsdef.definition_node:parent() end local found_parent = false while node and not found_parent do if scopes_to_tsdef[node:id()] then found_parent = true else node = node:parent() end end return node, found_parent end --STEP 2) function M.find_parents(all_defs, scopes_to_tsdef) local root_tsdef = nil for _, tsdef in pairs(all_defs) do local parent, found_parent = find_parent(tsdef, scopes_to_tsdef) if found_parent then local containing_tsdef = scopes_to_tsdef[parent:id()] table.insert(containing_tsdef.children, tsdef) tsdef.parent = containing_tsdef else root_tsdef = tsdef end end return root_tsdef end -- TODO (elpiloto): Hang this on TSOutline function M.get_definition_info(tsdef) local def_name = ts_utils.get_node_text(tsdef.definition_node)[1] if tsdef['associated'] then -- This was motivated by lua (M['someCrazyFunctionName'] = function()). May -- break other places or need to be generalized. if string.match(def_name, "'") or string.match(def_name, '"') then def_name = ts_utils.get_node_text(tsdef.associated)[1] .. '[' .. def_name .. ']' else def_name = ts_utils.get_node_text(tsdef.associated)[1] .. '.' .. def_name end end local def_type = tsdef.definition_type:gsub('definition%.', '') return def_name, def_type end local function should_ignore(def_type, def_text) local ignores = vim.g.sidekick_ignore_by_def_type def_type = def_type:gsub("definition.", "") return ignores[def_type] and ignores[def_type][def_text] end -- Dict: key = definition_type, value = list of definition identifiers function M.build_outline(root) local highlight_info = {} local ranges = {} -- Builds objects needed for an outline. -- @param tsdef current_tsdef being processed local function _build_outline(tsdef, indent) if tsdef.definition_node then local def_text = ts_utils.get_node_text(tsdef.definition_node)[1] local def_type = tsdef.definition_type local ignore = should_ignore(def_type, def_text) if not ignore then if not highlight_info[def_type] then highlight_info[def_type] = {def_text} else table.insert(highlight_info[def_type], def_text) end local start_row, start_col, end_row, end_col = tsdef.definition_node:range() local def_name, def_type = M.get_definition_info(tsdef) -- N.B. Add + 1 to rows because TreeSitter is 0-based and Vim lines are -- 1-based table.insert(ranges, {def_name, def_type, indent, start_row + 1, start_col, end_row + 1, end_col}) end indent = indent + 1 end if tsdef.children then for _, child in pairs(tsdef.children) do _build_outline(child, indent) end end end _build_outline(root, 0) return ranges, highlight_info end function M.set_highlight(highlight_info) local syntax_groups = {} local highlight_links = {} for def_type, def_type_defs in pairs(highlight_info) do -- Create syntax group called sidekick$sanitize(def_type) local str = "sidekick" .. def_type:gsub("%.", "_") local syntax_group = "syntax keyword " .. str .. " " .. table.concat(def_type_defs, " ") table.insert(syntax_groups, str) vim.cmd(syntax_group) -- Associate that syntax group with existing types -- TODO (elpiloto): Make "String" configurable. local highlight_link = "highlight default link " .. str .. " String" table.insert(highlight_links, str) vim.cmd(highlight_link) end end return M
rook = createPed (21, 2512.3154296875, -1710.4619140625, 13.468574523926) exports.pool:allocateElement(rook) setPedRotation(rook, 270) setPedFrozen(rook, true) setElementData (rook, "activeConvo", 0) -- Set the convo state to 0 so people can start talking to him. setElementData(rook, "name", "Rook") setElementData(rook, "talk", true) setElementData(rook, "rotation", getPedRotation(rook), false) function rookIntro () -- When player enters the colSphere create GUI with intro output to all local players as local chat. -- Give the player the "Find Hunter" achievement. if(getElementData( rook, "activeConvo" )==1)then outputChatBox("Rook doesn't want to talk to you.", source, 255, 0, 0) else local theTeam = getPlayerTeam(source) local factionType = getElementData(theTeam, "type") local query = mysql:query_fetch_object("SELECT rook FROM characters WHERE charactername='" .. mysql:escape_string(getPlayerName(source)) .."'") local rooksFriend = tonumber(query["rook"]) local factionLeader = tonumber( getElementData(source, "factionleader") ) if not(factionType==0) or factionLeader==0 then exports.global:sendLocalText(source, "Rook says: Keep on walkin'. Grown men tryin' to talk around here.", 255, 255, 255, 10) else if(rooksFriend==1)then -- If they are already a friend. exports.global:sendLocalText(source, "Rook says: Whats good, my nigga? You gettin' that paper now, right?", 255, 255, 255, 10) else -- If they are not a frient. triggerClientEvent( source, "rookIntroEvent", getRootElement()) -- Trigger Client side function to create GUI. exports.global:sendLocalText(source, "Rook says: What up, Homie? You lookin' to make some real green?", 255, 255, 255, 10) setElementData (rook, "activeConvo", 1) -- set the NPCs conversation state to active so no one else can begin to talk to him. talkingToRook = source addEventHandler("onPlayerQuit", talkingToRook, resetRookConvoStateDelayed) addEventHandler("onPlayerWasted", talkingToRook, resetRookConvoStateDelayed) end end end end addEvent( "startRookConvo", true ) addEventHandler( "startRookConvo", getRootElement(), rookIntro ) -- Statement 2 function rookStatement2_S() -- Output the text from the last option to all player in radius local name = string.gsub(getPlayerName(source), "_", " ") exports.global:sendLocalText(source, name .. " says: Hell yeah, I'm always lookin' for that paper.", 255, 255, 255, 5) exports.global:sendLocalText(source, "Rook whispers: Economies all fucked up, right? There's only one market that isn't goin' down like a high school cheerleader.", 255, 255, 255, 5) exports.global:sendLocalText(source, "Rook whispers: I'm talkin' about that dope money.", 255, 255, 255, 5) end addEvent( "rookStatement2ServerEvent", true ) addEventHandler( "rookStatement2ServerEvent", getRootElement(), rookStatement2_S ) -- Statement 3 function rookStatement3_S() -- Output the text from the last option to all player in radius exports.global:sendLocalText(source, "Rook says: Whatever, homie. I was just tryin' to help a brother out.", 255, 255, 255, 10) end addEvent( "rookStatement3ServerEvent", true ) addEventHandler( "rookStatement3ServerEvent", getRootElement(), rookStatement3_S ) -- Statement 4 function rookStatement4_S() -- Output the text from the last option to all player in radius local name = string.gsub(getPlayerName(source), "_", " ") exports.global:sendLocalText(source, name .. " whispers: What do you know about it?", 255, 255, 255, 5) exports.global:sendLocalText(source, "Rook whispers: I know a guy that's looking to reach out. He got connects but no soldiers to push his product.", 255, 255, 255, 5) end addEvent( "rookStatement4ServerEvent", true ) addEventHandler( "rookStatement4ServerEvent", getRootElement(), rookStatement4_S ) -- Statement 5 function rookStatement5_S() -- Output the text from the last option to all player in radius local name = string.gsub(getPlayerName(source), "_", " ") exports.global:sendLocalText(source, name .. " whispers: Where's he at?", 255, 255, 255, 5) exports.global:sendLocalText(source, "Rook whispers: His names Tyrese and lives somewhere south-east where those chicanos live. Tell him Rook sent you.", 255, 255, 255, 5) end addEvent( "rookStatement5ServerEvent", true ) addEventHandler( "rookStatement5ServerEvent", getRootElement(), rookStatement5_S ) -- Statement 6 function rookStatement6_S() -- Output the text from the last option to all player in radius local name = string.gsub(getPlayerName(source), "_", " ") exports.global:sendLocalText(source, name .. " whispers: And you're just telling me this because you're feelin' charitable.", 255, 255, 255, 5) exports.global:sendLocalText(source, "Rook whispers: If a brother doesn't look out for his own who will? The white man?", 255, 255, 255, 5) end addEvent( "rookStatement6ServerEvent", true ) addEventHandler( "rookStatement6ServerEvent", getRootElement(), rookStatement6_S ) -- Statement 7 function rookStatement7_S() -- Output the text from the last option to all player in radius local name = string.gsub(getPlayerName(source), "_", " ") exports.global:sendLocalText(source, name .. " whispers: I hear that.", 255, 255, 255, 5) exports.global:sendLocalText(source, "Rook whispers: Peace, homie.", 255, 255, 255, 5) mysql:query_free("UPDATE characters SET rook='1' WHERE charactername='" .. mysql:escape_string(getPlayerName(source)) .. "' LIMIT 1") resetRookConvoStateDelayed() end addEvent( "rookStatement7ServerEvent", true ) addEventHandler( "rookStatement7ServerEvent", getRootElement(), rookStatement7_S ) function resetRookConvoState() setElementData(rook,"activeConvo", 0) end function resetRookConvoStateDelayed() if talkingToRook then removeEventHandler("onPlayerQuit", talkingToRook, resetTyConvoStateDelayed) removeEventHandler("onPlayerWasted", talkingToRook, resetTyConvoStateDelayed) talkingToRook = nil end setTimer(resetRookConvoState, 120000, 1) end
-- UI local ui = require "tek.ui" local List = require "tek.class.list" -- Scopes local scopes = require "plugins.copy_totals.scopes" -- Constants local TASK_TAGS = { "@TASK_DESCRIPTION", "@TASK_PROJECT", "@TASK_DURATION", "@TASK_START_DATE", "@TASK_END_DATE" } local GROUPED_TASKS_TAGS = { "@TASK_DESCRIPTION", "@TASK_PROJECT", "@TASK_DURATION", } local SCOPE_TAGS = { [scopes.TASK_SCOPE] = {"@TASKS"}, [scopes.PROJECT_SCOPE] = {"@TASKS", "@PROJECT", "@TIME_PROJECT"}, [scopes.DAY_SCOPE] = {"@TASKS", "@DAY", "@MONTH", "@YEAR", "@TIME_DAY"} } -- Data local scope = scopes.PROJECT_SCOPE -- Default scope local group_tasks = false local sort_by_duration = false -- Private helper methods local get_tags_text = function(tags) local tags_text = "Available Tags: " for i, tag in ipairs(tags) do if i > 1 then tags_text = tags_text..", " end tags_text = tags_text..tag end return tags_text end local refresh_according_to_scope = function(self) -- Set template description self:getById("scope-template-title"):setValue("Text", scope.." Template:") -- Present available tags local task_tags = group_tasks and GROUPED_TASKS_TAGS or TASK_TAGS self:getById("task-format-tags"):setValue("Text", get_tags_text(task_tags)) local tags_text = get_tags_text(SCOPE_TAGS[scope]) self:getById("template-format-tags"):setValue("Text", tags_text) end local apply_changes = function(self, storage) local task_format = self:getById("copy-task-formatting"):getText() local template_format = self:getById("copy-template-formatting"):getText() storage.data.group_tasks = group_tasks storage.data.task_format = task_format storage.data.template_format = template_format storage.data.copy_scope = scope storage.data.sort_by_duration = sort_by_duration storage:save() self:getById("copy-totals-window"):setValue("Status", "hide") end -- Public window creation method return function(storage) scope = storage.data.copy_scope or scope group_tasks = storage.data.group_tasks or group_tasks sort_by_duration = storage.data.sort_by_duration or sort_by_duration local window = ui.Window:new{ Title = "Copy Totals", Id = "copy-totals-window", Status = "hide", Style = "margin: 15;", Orientation = "vertical", Width = "free", Height = "free", Children = { ui.Group:new{ Width = 600 }, ui.Group:new{ Style = "margin-bottom: 15;", Children = { ui.Text:new{ Width = "auto", Text = "Scope: ", Class = "caption label", Style = "font: 14/b;", }, ui.PopList:new{ Id = "scope-combo", Text = scope, Width = 75, ListObject = List:new{ Items = { { { "Task" } }, { { "Project" } }, { { "Day" } }, } }, onSelect = function(self) ui.PopList.onSelect(self) local item = self.ListObject:getItem(self.SelectedLine) if item then scope = item[1][1] refresh_according_to_scope(self) end end, }, } }, ui.Group:new{ Style = "margin-bottom: 15;", Children = { ui.Text:new{ Width = "auto", Text = "Group Tasks: ", Class = "caption label", Style = "font: 14/b;", }, ui.CheckMark:new{ Selected = group_tasks, onSelect = function(self) group_tasks = self.Selected refresh_according_to_scope(self) end }, } }, ui.Group:new{ Style = "margin-bottom: 15;", Children = { ui.Text:new{ Width = "auto", Text = "Sort By Duration: ", Class = "caption label", Style = "font: 14/b;", }, ui.CheckMark:new{ Selected = sort_by_duration, onSelect = function(self) sort_by_duration = self.Selected end }, } }, ui.Text:new{ Width = "auto", Text = "Task Format:", Class = "caption label", Style = "font: 14/b;", }, ui.Input:new{ Id = "copy-task-formatting", Width = "fill", MultiLine = true, Height = 40, Text = storage.data.task_format, }, ui.Text:new{ Id = "task-format-tags", Width = "auto", Class = "caption", Style = [[ margin-bottom: 15; font: sans-serif,helvetica,Vera:10; ]], Text = get_tags_text(group_tasks and GROUPED_TASKS_TAGS or TASK_TAGS) }, ui.Text:new{ Id = "scope-template-title", Width = "auto", Text = scope.." Template:", Class = "caption label", Style = "font: 14/b;", }, ui.Input:new{ Id = "copy-template-formatting", MultiLine = true, Width = "fill", Height = "free", Text = storage.data.template_format, }, ui.Text:new{ Id = "template-format-tags", Width = "auto", Class = "caption", Style = "font: sans-serif,helvetica,Vera:10;", Text = get_tags_text(SCOPE_TAGS[scope]) }, ui.Button:new{ Text = "Apply", Width = 80, HAlign = "center", Style = "margin-top: 20;", onClick = function(self) apply_changes(self, storage) end } } } return window end
-- -- -- dofile("common.inc"); delay = 100; pumpcount = 0; function doit() askForWindow("Macro will pump the aqueduct towers.\n\nMake sure the Skills window is visible. Macro needs to see the word \"Endurance\" in the Skills window.\n\nPress Shift over ATITD to continue."); while 1 do checkBreak(); srReadScreen(); local tired = srFindImage("Endurance-Red.png"); -- Verifies tired and skills window is showing local skills = srFindImage("dexterity_black_small.png"); -- Verifies skill window is showing. Use Dex (black) to verify because Endurance will change colors local pump = srFindImage("pump1.png"); -- "Pump the Acqueduct" window if not pump then sleepWithStatus(delay, "Pump Count: " .. pumpcount .. "\n\nWARNING, Can not find pump window!", 0xffff40ff); elseif tired then sleepWithStatus(delay, "Pump Count: " .. pumpcount .. "\n\nPAUSING, You are tired!", 0xff8080ff); elseif not skills then sleepWithStatus(delay, "Pump Count: " .. pumpcount .. "\n\nWARNING, Can't find skills window!", 0xffff40ff); else pumpcount = pumpcount + 1; srClickMouseNoMove(pump[0]+5, pump[1], 0); sleepWithStatus(delay, "Pump Count: " .. pumpcount .."\n\nREADY, Pumping...", 0x40ff40ff); lsSleep(300); end end end
--///////////////////////////////////////////////////////// --// World Boss Dynamic Spawn System // --// Created By TOXIC:11/20/2019 // --//////////////////////////////////////////////////////// --// Change your world boss under WORLDBOSS // --//Spawn Points Will Determain The Boss Spawn location // --//////////////////////////////////////////////////////// --// Current World Boss Planet naboo // --// Current World Boss Type CREATURE // --/////////////////////////////////////////////////////// worldboss_twoScreenplay = ScreenPlay:new { numberOfActs = 1, planet = "naboo", } registerScreenPlay("worldboss_twoScreenplay", true) ----------------------------- --Start World Boss ScreenPlay ----------------------------- function worldboss_twoScreenplay:start() if (isZoneEnabled(self.planet)) then self:spawnMobiles() print("World Boss Two Loaded") end end ----------------------- --The Boss Has Spawned ----------------------- function worldboss_twoScreenplay:spawnMobiles() local pBoss = spawnMobile("naboo", "worldboss_2", -1, 5894.31, 70.7582, -4638.72, 196, 0)--Spawn World Boss local creature = CreatureObject(pBoss) print("World Boss Two Spawned") createObserver(OBJECTDESTRUCTION, "worldboss_twoScreenplay", "bossDead", pBoss)--World Boss Has Died Trigger Respawn Function end --------------------------------------------------------------- --The Boss Has Died Respawn WorldBoss With A New Dynamic Spawn --------------------------------------------------------------- function worldboss_twoScreenplay:bossDead(pBoss) print("World Boss One Has Died") local creature = CreatureObject(pBoss) createEvent(120 * 1000, "worldboss_twoScreenplay", "KillBoss", pBoss, "")--Despawn Corpse createEvent(10800 * 1000, "worldboss_twoScreenplay", "KillSpawn", pBoss, "")--Respawn Boss In 3 Hours createEvent(1 * 1000, "worldboss_twoScreenplay", "BroadcastDead", pBoss, "")--Broadcast Dead createEvent(10800 * 1000, "worldboss_twoScreenplay", "KillSpawnCast3", pBoss, "")--Broadcast Respawn 1 return 0 end ----------------------- --Respawn World Boss ----------------------- function worldboss_twoScreenplay:KillSpawn() local pBoss = spawnMobile("naboo", "worldboss_2", -1, 5894.31, 70.7582, -4638.72, 196, 0)--Spawn WorldBoss After Death 3 Hour Timer local creature = CreatureObject(pBoss) print("World Boss Spawned 2") createObserver(OBJECTDESTRUCTION, "worldboss_twoScreenplay", "bossDead", pBoss) end ----------------------------------------------------------------------------- --The Boss Has Died Without Being Looted, "Abandon" Destroy NPC, Destroy Loot ----------------------------------------------------------------------------- function worldboss_twoScreenplay:KillBoss(pBoss) dropObserver(pBoss, OBJECTDESTRUCTION) if SceneObject(pBoss) then print("Unlooted World Boss One Destroyed") SceneObject(pBoss):destroyObjectFromWorld() end return 0 end ---------------------------- --Broadcast Dead ---------------------------- function worldboss_twoScreenplay:BroadcastDead(bossObject) local boss = LuaCreatureObject(bossObject) CreatureObject(bossObject):broadcastToServer("\\#63C8F9 Giant Tomb Wriath World Boss Has Died.") CreatureObject(bossObject):broadcastToDiscord("Giant Tomb Wriath World Boss Has Died.") end ----------------------- --Broadcast Respawn 1 ----------------------- function worldboss_twoScreenplay:KillSpawnCast3(bossObject) local boss = LuaCreatureObject(bossObject) CreatureObject(bossObject):broadcastToServer("\\#63C8F9 Giant Tomb Wriath World Boss Respawning.") CreatureObject(bossObject):broadcastToDiscord("Giant Tomb Wriath World Boss Respawning.") end
---@class GenericA<A> local GenericA ---@class GenericB<B> : GenericA<B> local GenericB ---@class GenericC<C> : GenericB<C> local GenericC ---@type GenericA<string> local genericA ---@type GenericB<string> local genericB ---@type GenericC<string> local genericC genericA = genericB genericA = genericC genericB = genericA -- Expect error genericB = genericC genericC = genericA -- Expect error genericC = genericB -- Expect error ---@class ClassA : GenericA<string> local ClassA ---@class ClassB : ClassA local ClassB ---@class ClassC : ClassB local ClassC ---@type ClassA local classA ---@type ClassB local classB ---@type ClassC local classC classA = classB classA = classC classB = classA -- Expect error classB = classC classC = classA -- Expect error classC = classB -- Expect error genericA = classA genericA = classB genericA = classC ---@class ClassGenA<T> local ClassGenA ---@class ClassGenB<T> : ClassGenA<string> local ClassGenB ---@class ClassGenC<T> : ClassGenB<string> local ClassGenC ---@type ClassGenA<string> local classGenA ---@type ClassGenB<string> local classGenB ---@type ClassGenC<string> local classGenC classGenA = classGenB classGenA = classGenC classGenB = classGenA -- Expect error classGenB = classGenC classGenC = classGenA -- Expect error classGenC = classGenB -- Expect error
local gui = require('util.Gspot') local menu = {} local start local gui = gui() local width = love.graphics.getWidth() local height = love.graphics.getHeight() function menu.load() font = love.graphics.newFont('assets/truthwillout.ttf', 50) love.graphics.setFont(font) love.graphics.setBackgroundColor(255,25,255) start = gui:button('START', {x = width * .2, y = 250, w = 256, h = gui.style.unit * 1.5}) quit = gui:button('QUIT', {x = width * .2, y = 250 + gui.style.unit * 1.5, w = 256, h = gui.style.unit * 1.5}) start.style.font = love.graphics.newFont(20) quit.style.font = love.graphics.newFont(20) start.style.default = {0, 255, 153} quit.style.default = {0, 255, 153} start.style.fg = {0, 0, 0} quit.style.fg = {0, 0, 0} function start:click(x, y) print('Ouch!') end function quit:click(x,y) love.quit() end end function menu.draw() love.graphics.setColor(0, 255, 153) local rect_x = width * .2 local rect_y = height * .1 love.graphics.rectangle('fill', rect_x, rect_y, .6 * width, .2 * height) love.graphics.setColor(0,0,0) love.graphics.printf('LIT FAM GAMING', rect_x * 2, rect_y * 1.7, 200, 'center') gui:draw() end function menu.update(dt) width = love.graphics.getWidth() height = love.graphics.getHeight() gui:update(dt) end function menu.keypressed(key) if gui.focus then gui:keypress(key) -- only sending input to the gui if we're not using it for something else end end function menu.mousepressed(x, y, button) gui:mousepress(x, y, button) -- pretty sure you want to register mouse events end function menu.mousereleased(x, y, button) gui:mouserelease(x, y, button) end function menu.quit() os.exit() end function menu.keypressed(key) if key == 'escape' then love.quit() end end return menu
local plymeta = FindMetaTable( "Player" ) if SERVER then util.AddNetworkString( "Losses" ) function plymeta:AddLoss( amount ) local losses = self:GetWins() self:SetLosses(losses + amount) end function plymeta:SetLosses( amount ) self.losses = amount net.Start("Losses") net.WriteEntity(self) net.WriteDouble(amount) net.Broadcast() end else net.Receive( "Losses", function( len, pl ) local ent = net.ReadEntity() if not ent.losses then ent.losses = 0 end ent.losses = net.ReadDouble() end) end function plymeta:GetLosses() if !self.losses then self.losses = 0 end return self.losses || 0 end
UIPanelManager = {} local tPanels = {} local tWaitOpenQuene = {} local loadingloader = nil local loadingUIDef = nil local uiRootCanvas = nil local tLayerCanvas = {} function UIPanelManager.OpenUI(uiDef, ...) local view = tPanels[uiDef] if view then view:OnOpen(...) view:Show() view:OnDoAnimationShow(Handler(view, view.OnViewShow)) return end if #tWaitOpenQuene > 0 then table.insert(tWaitOpenQuene, { Def = uiDef, Args = {...} }) return end local assetPath = uiDef.AssetPath local layer = uiDef.Layer local args = {...} loadingUIDef = uiDef local layerCanvas = UIPanelManager.GetLayer(layer) loadingloader = AssetsUtility.LoadPrefabAsync(assetPath, function(go) loadingUIDef = nil loadingloader = nil local name = go.name go = GameObject.Instantiate(go) go.name = name local flag, panel = go:TryGetComponent(typeof(CS.UIPanel)) assert(flag, "can not find lua behaviour component") view = panel.behavior tPanels[uiDef] = view layerCanvas.transform:AddChild(view.transform) view.transform:ResetRTS() view.transform:SetAnchoredMin(0, 0) view.transform:SetAnchoredMax(1, 1) view.transform:SetOffsetMin(0, 0) view.transform:SetOffsetMax(0, 0) view:OnOpen(table.unpack(args)) view:Show() view:OnDoAnimationShow(Handler(view, view.OnViewShow)) local nextUI = table.remove(tWaitOpenQuene, 1) if nextUI then UIPanelManager.OpenUI(nextUI.Def, table.unpack(nextUI.Args)) end end) end local function IfLoadingStopAndOpenNextUI(uiDef) if loadingUIDef == uiDef then loadingUIDef = nil if loadingloader then loadingloader:Stop() loadingloader = nil local nextUI = table.remove(tWaitOpenQuene, 1) if nextUI then UIPanelManager.OpenUI(nextUI.Def, table.unpack(nextUI.Args)) end end end end function UIPanelManager.CloseUI(uiDef, bNoAnimation) IfLoadingStopAndOpenNextUI(uiDef) local view = tPanels[uiDef] if not view then return end if not bNoAnimation then view:OnDoAnimationHide(Handler(view, view.OnViewHide)) else view:Hide() end end function UIPanelManager.DestroyUI(uiDef) IfLoadingStopAndOpenNextUI(uiDef) local view = tPanels[uiDef] if view then GameObject.Destroy(view.gameObject) end tPanels[uiDef] = nil end function UIPanelManager.GetRootCanvas() if not uiRootCanvas then local loader = AssetsUtility.LoadPrefab("Assets/Art/UI/Prefab/UIRootCanvas.prefab") local go = GameObject.Instantiate(loader.request.asset) GameObject.DontDestroyOnLoad(go) local _, component = go:TryGetComponent(typeof(Canvas)) uiRootCanvas = component uiRootCanvas.gameObject.name = loader.request.asset.name end return uiRootCanvas end function UIPanelManager.GetLayer(layer) local canvas = tLayerCanvas[layer] if not canvas then local rootCanvas = UIPanelManager.GetRootCanvas() local go = GameObject(layer) go:AddComponent(typeof(RectTransform)) GameObject.DontDestroyOnLoad(go) local transform = go.transform rootCanvas.transform:AddChild(transform) transform:ResetRTS() transform:SetAnchoredMin(0, 0) transform:SetAnchoredMax(1, 1) transform:SetOffsetMin(0, 0) transform:SetOffsetMax(0, 0) go:AddComponent(typeof(GraphicRaycaster)) canvas = go:GetComponent(typeof(Canvas)) canvas.overrideSorting = true canvas.sortingOrder = UILayers.SortOrder[layer] tLayerCanvas[layer] = canvas end return canvas end return UIPanelManager
CFactory = CFactory or {} function CFactory:CItemConfigData(itemid, num, isbind) return C_ItemConfigData:new_local(itemid, isbind, num) end function CFactory:CMailContentParam() if nil ~= CFactory.MailContentParam then CFactory.MailContentParam:Reset() return CFactory.MailContentParam end CFactory.MailContentParam = C_MailContentParam:new_local() return CFactory.MailContentParam end function CFactory:CCharIntAttrs() return C_CharIntAttrs:new_local() end function CFactory:CConsumeStuffList() return C_ConsumeStuffList:new_local() end function CFactory:CMonsterDropList() return C_MonsterDropList:new_local() end function CFactory:CLuaPos(x, y) return C_LuaPos:new_local(x, y) end function CFactory:CActivity(activity_type) return C_Activity:new_local(C_ActivityManager:Instance(), activity_type) end
local g = vim.g g.NERDCreateDefaultMappings = 1 g.NERDSpaceDelims = 1 g.NERDCompactSexyComs = 1 g.NERDDefaultAlign = 'left' g.NERDAltDelims_java = 1 g.NERDCommentEmptyLines = 1 g.NERDTrimTrailingWhitespace = 1 g.NERDToggleCheckAllLines = 1
simulation = { mesh = { index_extents = {71}, domain_bounds = {2} }, domain_boundaries = { xmin = "dirichlet" }, shapes = { { type = "yz_rect", psi = 0.1, normal = 1, boundary_condition = "dirichlet" } }, scheme = { order = 1, type = "E2", alpha = {-1.47956280234494, 0.261900367793859, -0.145072532538541, -0.224665713988644} }, system = { type = "scalar wave", center = {-1}, radius = 0 -- diffusivity = 1 / 30 }, integrator = { type = "rk4" }, step_controller = { max_time = 10, --max_step = 2, cfl = { hyperbolic = 0.8, parabolic = 0.2 } }, io = { --write_every_step = 1 write_every_time = 0.8 } }
require("firecast.lua"); local __o_rrpgObjs = require("rrpgObjs.lua"); require("rrpgGUI.lua"); require("rrpgDialogs.lua"); require("rrpgLFM.lua"); require("ndb.lua"); require("locale.lua"); local __o_Utils = require("utils.lua"); local function constructNew_frmDiceRoll() local obj = GUI.fromHandle(_obj_newObject("form")); local self = obj; local sheet = nil; rawset(obj, "_oldSetNodeObjectFunction", rawget(obj, "setNodeObject")); function obj:setNodeObject(nodeObject) sheet = nodeObject; self.sheet = nodeObject; self:_oldSetNodeObjectFunction(nodeObject); end; function obj:setNodeDatabase(nodeObject) self:setNodeObject(nodeObject); end; _gui_assignInitialParentForForm(obj.handle); obj:beginUpdate(); obj:setName("frmDiceRoll"); obj:setAlign("client"); obj.scrollBox1 = GUI.fromHandle(_obj_newObject("scrollBox")); obj.scrollBox1:setParent(obj); obj.scrollBox1:setAlign("client"); obj.scrollBox1:setName("scrollBox1"); local function rolagemCallback(rolagem) local msg = ""; for i = 1, #rolagem.ops, 1 do local operacao = rolagem.ops[i]; -- Vamos verificar que tipo de operação é esta. if operacao.tipo == "dado" then -- Adicionar à mensagem informações sobre este conjunto de dados. msg = msg .. operacao.quantidade .. "d" .. operacao.face .. ": \n "; -- Loop percorrendo cada um dos resultados individuais deste conjunto de dados. for j = 1, #operacao.resultados, 1 do msg = msg .. " " .. math.floor(operacao.resultados[j]); end; msg = msg .. "\n"; elseif operacao.tipo == "imediato" then msg = msg .. "Valor imediato: " .. operacao.valor .. "\n"; end; end; -- Concatenar à mensagem o resultado final da rolagem msg = msg .. "------------------- \nResultado Final: " .. rolagem.resultado; -- Escrever resultado na mesa só para o usuario local mesa = Firecast.getMesaDe(sheet); mesa.activeChat:escrever(msg); end; obj.button1 = GUI.fromHandle(_obj_newObject("button")); obj.button1:setParent(obj.scrollBox1); obj.button1:setLeft(0); obj.button1:setTop(0); obj.button1:setWidth(25); obj.button1:setHeight(25); obj.button1:setText("R"); obj.button1:setHint("Botao que faz rolagem de teste"); obj.button1:setName("button1"); obj.edit1 = GUI.fromHandle(_obj_newObject("edit")); obj.edit1:setParent(obj.scrollBox1); obj.edit1:setLeft(25); obj.edit1:setTop(0); obj.edit1:setWidth(75); obj.edit1:setHeight(25); obj.edit1:setField("roll"); obj.edit1:setName("edit1"); obj._e_event0 = obj.button1:addEventListener("onClick", function (_) local roll = sheet.roll or "1d1-1"; local rolagem = Firecast.interpretarRolagem(roll); local mesa = Firecast.getMesaDe(sheet); mesa.activeChat:rolarDados(rolagem, "Teste de Exemplo", rolagemCallback); end, obj); function obj:_releaseEvents() __o_rrpgObjs.removeEventListenerById(self._e_event0); end; obj._oldLFMDestroy = obj.destroy; function obj:destroy() self:_releaseEvents(); if (self.handle ~= 0) and (self.setNodeDatabase ~= nil) then self:setNodeDatabase(nil); end; if self.scrollBox1 ~= nil then self.scrollBox1:destroy(); self.scrollBox1 = nil; end; if self.button1 ~= nil then self.button1:destroy(); self.button1 = nil; end; if self.edit1 ~= nil then self.edit1:destroy(); self.edit1 = nil; end; self:_oldLFMDestroy(); end; obj:endUpdate(); return obj; end; function newfrmDiceRoll() local retObj = nil; __o_rrpgObjs.beginObjectsLoading(); __o_Utils.tryFinally( function() retObj = constructNew_frmDiceRoll(); end, function() __o_rrpgObjs.endObjectsLoading(); end); assert(retObj ~= nil); return retObj; end; local _frmDiceRoll = { newEditor = newfrmDiceRoll, new = newfrmDiceRoll, name = "frmDiceRoll", dataType = "", formType = "undefined", formComponentName = "form", title = "", description=""}; frmDiceRoll = _frmDiceRoll; Firecast.registrarForm(_frmDiceRoll); return _frmDiceRoll;
require 'nn' require 'rnn' vocab_size = 4 embeddings_dim = 3 torch.manualSeed(420) print("**********************************************************************") print(" Example 1 ") print("**********************************************************************") -- Input is batch size x max sequence length. The first example has -- words 1, 4, and 2 and is shorter than the max sequence length so -- we pad it with zeros. input = torch.LongTensor{ {1, 4, 2, 0}, {1, 3, 3, 2} } print("Format of data in Example 1 is") print(input) -- Here we add the look up table which will produce output of size -- (batch size x max sequence length x embedding dim size) -- In this example ouptut O[1][4] is a vector of zeros because -- of the zero pad. net = nn.Sequential() net:add(nn.LookupTableMaskZero(vocab_size, embeddings_dim)) print("Dimensions of lookup table layer:") print(#net:forward(input)) print("Lookup table layer output") print(net:forward(input)) -- Now add the summation layer. The arguments are which dimension to -- sum over, the total number of input dimensions, and a boolean flag -- indicating whether or not to average the sum. -- We are summing over the sequence which corresponds to dimension 2. -- The input has 3 dimensions (output of lookup layer is -- batch x sequence x embedding) and we want to average the sum so -- flag is true. This is more or less what we want but there is an -- issue with the averaging part of the sum layer. -- What is it? (You can ignore it for now and throw the output of this -- into an mlp. We can discuss how to fix it on Tuesday.) net:add(nn.Sum(2, 3, false)) print("Dimensions after lookup table layer and averaging layer:") print(#net:forward(input)) print("nn.sum(2,3,true) output") print(net:forward(input)) print("**********************************************************************") print(" Example 1 -- Modified ") print("**********************************************************************") net2 = nn.Sequential() net2:add(nn.LookupTableMaskZero(vocab_size, embeddings_dim)) net2:add(nn.Sum(2, 3, false)) net:add(nn.Identity()) print(#net2:forward(input))
local log = require("vimrc.log") local ok, nvimtree = pcall(require, "nvim-tree") local function toggle_builtin() if ok then nvimtree.toggle(true) else log.warn("nvim-tree not found") end end local map = require("vimrc.config.mapping").map map("n", "<Leader>k", toggle_builtin) if ok then nvimtree.setup { auto_close = true, open_on_tab = true, update_cwd = true, update_focused_file = { enable = true, update_cwd = false, }, filters = { custom = { '.git', 'node_modules', '.cache' } } } end
-- nick-h@yandex.ru -- Glukk Inc © local w32 = require("w32") CLASS_CODE = '' --класс в файле настроек --CLASS_CODE = 'TQBR' -- Код класса --CLASS_CODE = 'SPBFUT' -- Код класса --CLASS_CODE = 'QJSIM' SEC_CODE = '' -- бумаги в файле настроек SEC_CODES = {} INTERVAL = 15 -- --текущий интервал START_TIME = '10:00:00' -- Начало торговли STOP_TIME = '18:50:00' -- Окончание торговли -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- --/*РАБОЧИЕ ПЕРЕМЕННЫЕ РОБОТА (менять не нужно)*/ isRun = true -- Флаг поддержания работы скрипта is_Connected = 0 PrevDayNumber = 0 trans_id = os.time() -- Задает начальный номер ID транзакций trans_Status = nil -- Статус текущей транзакции из функции OnTransPeply trans_result_msg = '' -- Сообщение по текущей транзакции из функции OnTransPeply numberOfFixedColumns = 0 -- Число фиксированных колонок до периодов numberOfVisibleColumns = 0 -- Число видимых колонок периодов tableIndex = {} -- Индексы колонок созданной таблицы openedDS = {} t_id = nil tv_id = nil thist_id = nil SeaGreen=12713921 -- RGB(193, 255, 193) нежно-зеленый RosyBrown=12698111 -- RGB(255, 193, 193) нежно-розовый SEC_PRICE_STEP = 0 -- ШАГ ЦЕНЫ ИНСТРУМЕНТА DS = nil -- Источник данных графика (DataSource) g_previous_time = os.time() -- помещение в переменную времени сервера в формате HHMMSS SEC_CODE_INDEX = {} -- last interval index isDayInterval = false -- есть дневной интервал dayIntervalIndex = nil UpdateDataSecQty = 10 -- Количество секунд ожидания подгрузки данных с сервера после возобновления подключения ----------------------------- -- Основные функции -- ----------------------------- function DataSource(i,cell) local seccode = SEC_CODES['sec_codes'][i] local classcode = SEC_CODES['class_codes'][i] local interval = INTERVALS['values'][cell] if openedDS[i][interval] ~= nil then return openedDS[i][interval] end local ds = CreateDataSource(classcode,seccode,interval) if ds == nil then message('NRTR monitor: ОШИБКА получения доступа к свечам! '..Error) myLog('NRTR monitor: ОШИБКА получения доступа к свечам! '..Error) -- Завершает выполнение скрипта isRun = false return end if ds:Size() == 0 then ds:SetEmptyCallback() SEC_CODES['isEmpty'][i] = true end openedDS[i][interval] = ds return ds end do---- ДАТА/ВРЕМЯ -- Ждет подключения к серверу, после чего ждет еще UpdateDataSecQty секунд подгрузки пропущенных данных с сервера function WaitUpdateDataAfterReconnect() while isRun and isConnected() == 0 do sleep(100) end if isRun then sleep(UpdateDataSecQty * 1000) end -- Повторяет операцию если соединение снова оказалось разорвано if isRun and isConnected() == 0 then WaitUpdateDataAfterReconnect() end end -- Возвращает текущую дату/время сервера в виде таблицы datetime function GetServerDateTime() local dt = {} -- Пытается получить дату/время сервера while isRun and dt.day == nil do dt.day,dt.month,dt.year,dt.hour,dt.min,dt.sec = string.match(getInfoParam('TRADEDATE')..' '..getInfoParam('SERVERTIME'),"(%d*).(%d*).(%d*) (%d*):(%d*):(%d*)") -- Если не удалось получить, или разрыв связи, ждет подключения и подгрузки с сервера актуальных данных --if dt.day == nil or isConnected() == 0 then WaitUpdateDataAfterReconnect() end if dt.day == nil or isConnected() == 0 then return os.date('*t', os.time()) --WaitUpdateDataAfterReconnect() end end -- Если во время ожидания скрипт был остановлен пользователем, возвращает таблицу datetime даты/времени компьютера, чтобы не вернуть пустую таблицу и не вызвать ошибку в алгоритме if not isRun then return os.date('*t', os.time()) end -- Приводит полученные значения к типу number for key,value in pairs(dt) do dt[key] = tonumber(value) end -- Возвращает итоговую таблицу return dt end -- Приводит время из строкового формата ЧЧ:ММ:CC к формату datetime function StrToTime(str_time) if type(str_time) ~= 'string' then return os.date('*t') end local sdt = GetServerDateTime() while isRun and sdt.day == nil do sleep(100) sdt = GetServerDateTime() end if not isRun then return os.date('*t') end local dt = sdt local h,m,s = string.match( str_time, "(%d%d):(%d%d):(%d%d)") dt.hour = tonumber(h) dt.min = tonumber(m) dt.sec = s==nil and 0 or tonumber(s) return dt end end--- ДАТА/ВРЕМЯ -- Функция первичной инициализации скрипта (ВЫЗЫВАЕТСЯ ТЕРМИНАЛОМ QUIK в самом начале) function OnInit() dofile (getScriptPath().."\\monitorStepNRTR.lua") --stepNRTR алгоритм. Инициализация - initstepNRTR, расчет - stepNRTR dofile (getScriptPath().."\\monitorEMA.lua") --EMA алгоритм. Инициализация - initEMA, расчет - EMA, allEMA dofile (getScriptPath().."\\monitorRSI.lua") --EMA алгоритм. Инициализация - initRSI, расчет - RSI dofile (getScriptPath().."\\monitorReg.lua") --Регрессия алгоритм. Инициализация - initReg, расчет - Reg dofile (getScriptPath().."\\monitorVolume.lua") --RT алгоритм контроль повышенного объема. Инициализация - initVolume, расчет - Volume dofile (getScriptPath().."\\monitorVSA.lua") --VSA алгоритм. Инициализация - initVSA, расчет - VSA dofile (getScriptPath().."\\monitorRange.lua") --range --Должен быть ниже модулей расчета dofile (getScriptPath().."\\scriptMonitorPar.lua") --stepNRTR алгоритм. Инициализация - initstepNRTR, расчет - stepNRTR logFile = io.open(FILE_LOG_NAME, "a+") -- открывает файл local ParamsFile = io.open(PARAMS_FILE_NAME,"r") if ParamsFile == nil then isRun = false message("Не удалость прочитать файл настроек!!!") return false end --is_Connected = isConnected() -- --if is_Connected ~= 1 then -- isRun = false -- message("Нет подключения к серверу!!!") -- return false --end SEC_CODES['class_codes'] = {} -- CLASS_CODE SEC_CODES['names'] = {} -- имена бумаг SEC_CODES['sec_codes'] = {} -- коды бумаг SEC_CODES['isMessage'] = {} -- выводить сообщения SEC_CODES['isPlaySound'] = {} -- проигрывать звук SEC_CODES['volume'] = {} -- рабочий объем SEC_CODES['isEmpty'] = {} -- признак заказа данных SEC_CODES['DS'] = {} -- данные по инструменту SEC_CODES['calcAlgoValues'] = {} -- рассчитанные данные SEC_CODES['dayATR'] = {} -- рассчитанные данные ATR SEC_CODES['dayDS'] = {} -- данные для ATR SEC_CODES['dayATR_Period'] = {} -- период данных ATR SEC_CODES['D_minus5'] = {} -- цена 5 дней назад SEC_CODES['lastTimeCalculated'] = {} -- время последнего рассчета SEC_CODES['lastrealTimeCalculated'] = {} -- время последнего рассчета realtime алгоритма myLog("______________________________________________________") myLog("Читаем файл параметров") local lineCount = 0 for line in ParamsFile:lines() do --myLog("Строка параметров "..line) lineCount = lineCount + 1 if lineCount > 1 and line ~= "" then local per1, per2, per3, per4, per5, per6, per7 = line:match("%s*(.*);%s*(.*);%s*(.*);%s*(.*);%s*(.*);%s*(.*);%s*(.*)") SEC_CODES['class_codes'][lineCount-1] = per1 SEC_CODES['names'][lineCount-1] = per2 SEC_CODES['sec_codes'][lineCount-1] = per3 SEC_CODES['isMessage'][lineCount-1] = tonumber(per4) SEC_CODES['isPlaySound'][lineCount-1] = tonumber(per5) SEC_CODES['volume'][lineCount-1] = tonumber(per6) SEC_CODES['isEmpty'][lineCount-1] = false SEC_CODES['DS'][lineCount-1] = {} SEC_CODES['calcAlgoValues'][lineCount-1] = {} SEC_CODES['dayATR'][lineCount-1] = 0 SEC_CODES['dayDS'][lineCount-1] = nil SEC_CODES['dayATR_Period'][lineCount-1] = tonumber(per7) SEC_CODES['D_minus5'][lineCount-1] = 0 SEC_CODES['lastTimeCalculated'][lineCount-1] = {} SEC_CODES['lastrealTimeCalculated'][lineCount-1] = {} end end ParamsFile:close() myLog("Intervals "..tostring(#INTERVALS["names"])) myLog("Sec codes "..tostring(#SEC_CODES['sec_codes'])) CreateTable() -- Создает таблицу myLog("realTime functions "..tostring(#realtimeAlgorithms["functions"])) for i,v in ipairs(SEC_CODES['sec_codes']) do SEC_CODE_INDEX[i] = {} SEC_CODE = v CLASS_CODE =SEC_CODES['class_codes'][i] openedDS[i] = {} if getSecurityInfo(CLASS_CODE, SEC_CODE) == nil then isRun = false message("Не удалость получить данные по инструменту: "..SEC_CODE.."/"..tostring(CLASS_CODE)) myLog("Не удалость получить данные по инструменту: "..SEC_CODE.."/"..tostring(CLASS_CODE)) return false end SEC_PRICE_STEP = getParamEx(CLASS_CODE, SEC_CODE, "SEC_PRICE_STEP").param_value local status = getParamEx(CLASS_CODE, SEC_CODE, "last").param_value local last_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"last").param_value) local open_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"prevprice").param_value) local highest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"high").param_value) local lowest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"low").param_value) local waprice = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"WAPRICE").param_value) if last_price == 0 or last_price == nil then last_price = open_price end SetCell(t_id, i, tableIndex["Текущая цена"], tostring(last_price), last_price) --i строка, 1 - колонка, v - значение local lastchange = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"lastchange").param_value) Str(i, tableIndex["%"], lastchange, 0, 0) --i строка, 1 - колонка, v - значение SetCell(t_id, i, tableIndex["Цена открытия"], tostring(open_price), open_price) --i строка, 1 - колонка, v - значение SetCell(t_id, i, tableIndex["VWAP"], tostring(waprice), wapprice) --i строка, 1 - колонка, v - значение local delta = round(last_price-open_price,5) SetCell(t_id, i, tableIndex["Дельта"], tostring(delta), delta) --i строка, 1 - колонка, v - значение local openCount, awg_price = GetTotalnet(CLASS_CODE, SEC_CODE) SetCell(t_id, i, tableIndex["Позиция"], tostring(openCount), openCount) --i строка, 1 - колонка, v - значение if tonumber(awg_price)==0 then SetCell(t_id, i, tableIndex["Средняя"], '', 0) --i строка, 1 - колонка, v - значение White(i, tableIndex["Средняя"]) else Str(i, tableIndex["Средняя"], tonumber(awg_price), last_price) --i строка, 1 - колонка, v - значение end --Команды if showTradeCommands == true then SetCell(t_id, i, tableIndex["<"], "-") --i строка, 1 - колонка, v - значение SetCell(t_id, i, tableIndex["Объем сделки"], tostring(SEC_CODES['volume'][i]), SEC_CODES['volume'][i]) --i строка, 1 - колонка, v - значение SetCell(t_id, i, tableIndex[">"], "+") --i строка, 1 - колонка, v - значение SetCell(t_id, i, tableIndex["Команда BUY"], "BUY") --i строка, 1 - колонка, v - значение Green(i, tableIndex["Команда BUY"]) SetCell(t_id, i, tableIndex["Команда SELL"], "SELL") --i строка, 1 - колонка, v - значение Red(i, tableIndex["Команда SELL"]) if openCount~=0 then Red(i, tableIndex["Команда CLOSE"]) SetCell(t_id, i, tableIndex["Команда CLOSE"], "CLOSE") --i строка, 0 - колонка, v - значение else White(i, tableIndex["Команда CLOSE"]) SetCell(t_id, i, tableIndex["Команда CLOSE"], "") --i строка, 0 - колонка, v - значение end end for kk,algo in pairs(realtimeAlgorithms["functions"]) do local initrf = realtimeAlgorithms["initAlgorithms"][kk] if initrf~=nil then initrf() end SEC_CODES['lastrealTimeCalculated'][i][kk] = g_previous_time end for cell,INTERVAL in pairs(INTERVALS["values"]) do --myLog(SEC_CODE.." interval "..tostring(INTERVAL)) DS = DataSource(i,cell) SEC_CODES['DS'][i][cell] = DS SEC_CODES['lastTimeCalculated'][i][cell] = os.time() SEC_CODE_INDEX[i][cell] = DS:Size() --myLog("Всего свечей ".. SEC_CODE..", интервала "..INTERVALS["names"][cell].." "..tostring(SEC_CODE_INDEX[i][cell])) if status ~= nil and status ~= 0 then --interval algorithms local initf = INTERVALS["initAlgorithms"][cell] local calcf = INTERVALS["algorithms"][cell] local signalf = INTERVALS["signalAlgorithms"][cell] local settings = INTERVALS["settings"][cell] calcAlgoValue = {} if initf~=nil then initf() end if calcf~=nil then -- расчет параметров для каждого интервала calcAlgoValue = calcf(i, DS:Size(), settings, DS, INTERVAL) end SEC_CODES['calcAlgoValues'][i][cell] = calcAlgoValue[DS:Size()] or 0 if signalf~=nil then signalf(i, cell, settings, DS, false) elseif calcf~=nil then up_downTest(i, cell, settings, DS, false) end end --ATR if INTERVAL == INTERVAL_D1 and isDayInterval == false then isDayInterval = true dayIntervalIndex = cell end end --ATR getATR(i, dayIntervalIndex) local lastATR = round(SEC_CODES['dayATR'][i], 5) if highest_price ==0 then highest_price = open_price end if lowest_price ==0 then lowest_price = open_price end local atrDelta = math.max(math.abs(highest_price - open_price), math.abs(open_price-lowest_price)) if lastATR<math.abs(atrDelta) then Red(i, tableIndex["D ATR"]) else White(i, tableIndex["D ATR"]) end --ATR --W% local changeW = round((last_price - SEC_CODES['D_minus5'][i])*100/SEC_CODES['D_minus5'][i], 2) Str(i, tableIndex["%W"], changeW, 0, 0) --W% end myLog("================================================") myLog("Initialization finished") end function main() -- Функция, реализующая основной поток выполнения в скрипте SetTableNotificationCallback(t_id, event_callback) SetTableNotificationCallback(tv_id, volume_event_callback) -- Цикл по дням while isRun do -- Ждет начала следующего дня while isRun and GetServerDateTime().day == PrevDayNumber do sleep(100) end -- Получает время в секундах для всех временных промежутков local StartTime_sec = os.time(StrToTime(START_TIME)) local StopTime_sec = os.time(StrToTime(STOP_TIME)) -- Ждет начала торгового дня while isRun and os.time(GetServerDateTime()) <= StartTime_sec do sleep(100) end --myLog(' GetServerDateTime() '..tostring(os.time(GetServerDateTime()))..' StartTime_sec '..tostring(StartTime_sec)..' StopTime_sec '..tostring(StopTime_sec)) -- Цикл внутри дня while isRun do -- Цикл будет выполнятся, пока isRun == true -- Получает время сервера local ServerDT = GetServerDateTime() local ServerDT_sec = os.time(ServerDT) -- Если торговый день закончился, выходит в цикл по дням if ServerDT_sec >= StopTime_sec then PrevDayNumber = ServerDT.day break end for i,v in ipairs(SEC_CODES['sec_codes']) do if isRun == false then break end SEC_CODE = v CLASS_CODE =SEC_CODES['class_codes'][i] -- Получает ШАГ ЦЕНЫ ИНСТРУМЕНТА, последнюю цену, открытые позиции SEC_PRICE_STEP = getParamEx(CLASS_CODE, SEC_CODE, "SEC_PRICE_STEP").param_value local status = getParamEx(CLASS_CODE, SEC_CODE, "last").param_value local last_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"last").param_value) local open_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"prevprice").param_value) local highest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"high").param_value) local lowest_price = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"low").param_value) local waprice = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"WAPRICE").param_value) if last_price == 0 or last_price == nil then last_price = open_price end local lp = GetCell(t_id, i, tableIndex["Текущая цена"]).value or last_price if lp < last_price then Highlight(t_id, i, tableIndex["Текущая цена"], SeaGreen, QTABLE_DEFAULT_COLOR,1000) -- подсветка мягкий, зеленый elseif lp > last_price then Highlight(t_id, i, tableIndex["Текущая цена"], RosyBrown, QTABLE_DEFAULT_COLOR,1000) -- подсветка мягкий розовый end SetCell(t_id, i, tableIndex["Текущая цена"], tostring(last_price), last_price) --i строка, 1 - колонка, v - значение Str(i, tableIndex["VWAP"], waprice, last_price) local lastchange = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"lastchange").param_value) Str(i, tableIndex["%"], lastchange, 0, 0) --i строка, 1 - колонка, v - значение SetCell(t_id, i, tableIndex["Цена открытия"], tostring(open_price), open_price) --i строка, 1 - колонка, v - значение local delta = round(last_price-open_price,5) SetCell(t_id, i, tableIndex["Дельта"], tostring(delta), delta) --i строка, 1 - колонка, v - значение if IsWindowClosed(t_id) == false then local awg_price = GetCell(t_id, i, tableIndex["Средняя"]).value or 0 if tonumber(awg_price)==0 then White(i, tableIndex["Средняя"]) else Str(i, tableIndex["Средняя"], tonumber(awg_price), last_price) end end local current_time=ServerDT_sec --myLog(tostring(status)) if status ~= nil and status ~= "0.000000" then for kk,algo in pairs(realtimeAlgorithms["functions"]) do local realf = realtimeAlgorithms["functions"][kk] if realf~=nil then local lastrealTimeCalculated = SEC_CODES['lastrealTimeCalculated'][i][kk] or current_time local newrealTimeToCalculate = current_time local realperiod = realtimeAlgorithms["recalculatePeriod"][kk] or 0 if realperiod ~= 0 then newrealTimeToCalculate = lastrealTimeCalculated + realperiod if current_time>newrealTimeToCalculate then --myLog(SEC_CODE.." realperiod "..tostring(realperiod).." lastrealTimeCalculated "..tostring(lastrealTimeCalculated)) --myLog("newrealTimeToCalculate "..tostring(newrealTimeToCalculate)) --myLog("current_time "..tostring(current_time)) SEC_CODES['lastrealTimeCalculated'][i][kk] = current_time realf(i) end end end end for cell,INTERVAL in pairs(INTERVALS["values"]) do DS = SEC_CODES['DS'][i][cell] local lastTimeCalculated = SEC_CODES['lastTimeCalculated'][i][cell] local newTimeToCalculate = ServerDT_sec local period = INTERVALS["recalculatePeriod"][cell] or 0 newTimeToCalculate = current_time if period ~= 0 then --newTimeToCalculate = lastTimeCalculated + 100*math.floor(period/60) + period%60 newTimeToCalculate = lastTimeCalculated + period*60 end local timeCandle = DS:T(DS:Size()) --myLog(SEC_CODE.." - timeCandle "..tostring(os.time(timeCandle)).." - INTERVAL "..tostring(INTERVAL).." - period "..tostring(period)) --myLog(SEC_CODE.." - current_time "..tostring(current_time).." - lastTimeCalculated "..tostring(lastTimeCalculated).." - newTimeToCalculate "..tostring(newTimeToCalculate)) --myLog(SEC_CODE.." - current_time "..tostring(current_time)) --myLog(SEC_CODE.." - newtimeCandle "..tostring(os.time(timeCandle) + INTERVAL*60)) if SEC_CODE_INDEX[i][cell]<DS:Size() or current_time>newTimeToCalculate and current_time < (os.time(timeCandle) + INTERVAL*60) then --new candle --myLog(SEC_CODE.." - Перерасчет данных за интервал "..INTERVALS["names"][cell]) SEC_CODES['lastTimeCalculated'][i][cell] = current_time --interval algorithms local initf = INTERVALS["initAlgorithms"][cell] local calcf = INTERVALS["algorithms"][cell] local signalf = INTERVALS["signalAlgorithms"][cell] local settings = INTERVALS["settings"][cell] calcAlgoValue = {} if initf~=nil then initf() end if calcf~=nil then --myLog(SEC_CODE.." - INTERVAL "..tostring(INTERVAL)) calcAlgoValue = calcf(i, DS:Size(), settings, DS) end SEC_CODES['calcAlgoValues'][i][cell] = calcAlgoValue[DS:Size()] or 0 if signalf~=nil then signalf(i, cell, settings, DS, true) elseif calcf~=nil then up_downTest(i, cell, settings, DS, true) end SEC_CODE_INDEX[i][cell] = DS:Size() --last candle end end end --ATR if SEC_CODES['D_minus5'][i]==0 or SEC_CODES['D_minus5'][i]==nil or SEC_CODES['dayATR'][i]==0 or SEC_CODES['dayATR'][i]==nil then getATR(i, dayIntervalIndex) end local lastATR = round(SEC_CODES['dayATR'][i], 5) if highest_price ==0 then highest_price = open_price end if lowest_price ==0 then lowest_price = open_price end local atrDelta = math.max(math.abs(highest_price - open_price), math.abs(open_price-lowest_price)) if lastATR<math.abs(atrDelta) then Red(i, tableIndex["D ATR"]) else White(i, tableIndex["D ATR"]) end --ATR --W% local changeW = round((last_price - SEC_CODES['D_minus5'][i])*100/SEC_CODES['D_minus5'][i], 2) Str(i, tableIndex["%W"], changeW, 0, 0) --W% end sleep(100) end end end -- Функция ВЫЗЫВАЕТСЯ ТЕРМИНАЛОМ QUIK при остановке скрипта function OnStop() isRun = false myLog("Script Stoped") if t_id~= nil then DestroyTable(t_id) end if tv_id~= nil then DestroyTable(tv_id) end if thist_id~= nil then DestroyTable(thist_id) end calcAlgoValue = nil if logFile~=nil then logFile:close() end -- Закрывает файл end ----------------------------- -- РАБОТА С ТАБЛИЦЕЙ -- ----------------------------- function CreateTable() -- Функция создает таблицу t_id = AllocTable() -- Получает доступный id для создания -- Добавляет колонки AddColumn(t_id, 0, "Инструмент", true, QTABLE_STRING_TYPE, 22) tableIndex["Инструмент"] = 0 AddColumn(t_id, 1, "%", true, QTABLE_DOUBLE_TYPE, 9) tableIndex["%"] = 1 AddColumn(t_id, 2, "Цена", true, QTABLE_DOUBLE_TYPE, 13) tableIndex["Текущая цена"] = 2 AddColumn(t_id, 3, "%W", true, QTABLE_DOUBLE_TYPE, 9) tableIndex["%W"] = 3 AddColumn(t_id, 4, "Открытие", true, QTABLE_DOUBLE_TYPE, 13) tableIndex["Цена открытия"] = 4 AddColumn(t_id, 5, "VWAP", true, QTABLE_DOUBLE_TYPE, 13) tableIndex["VWAP"] = 5 AddColumn(t_id, 6, "Дельта", true, QTABLE_DOUBLE_TYPE, 13) tableIndex["Дельта"] = 6 AddColumn(t_id, 7, "D ATR", true, QTABLE_DOUBLE_TYPE, 13) tableIndex["D ATR"] = 7 AddColumn(t_id, 8, "Поз.", true, QTABLE_INT_TYPE, 7) tableIndex["Позиция"] = 8 AddColumn(t_id, 9, "Средняя", true, QTABLE_DOUBLE_TYPE, 13) tableIndex["Средняя"] = 9 numberOfFixedColumns = 9 numberOfVisibleColumns = 0 local width = 0 for i,v in ipairs(INTERVALS["names"]) do if INTERVALS["visible"][i] then numberOfVisibleColumns = numberOfVisibleColumns + 1 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns, v, true, QTABLE_DOUBLE_TYPE, INTERVALS["width"][i]) tableIndex[i] = numberOfVisibleColumns+numberOfFixedColumns width = width + INTERVALS["width"][i] end end local columns = numberOfFixedColumns if showTradeCommands == true then AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+1, "Цена", true, QTABLE_DOUBLE_TYPE, 15) --Price tableIndex["Цена сделки"] = numberOfVisibleColumns+numberOfFixedColumns+1 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+2, "<", true, QTABLE_STRING_TYPE, 5) --Decrease volume tableIndex["<"] = numberOfVisibleColumns+numberOfFixedColumns+2 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+3, "Vol", true, QTABLE_INT_TYPE, 7) --Volume tableIndex["Объем сделки"] = numberOfVisibleColumns+numberOfFixedColumns+3 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+4, ">", true, QTABLE_STRING_TYPE, 5) --Increase volume tableIndex[">"] = numberOfVisibleColumns+numberOfFixedColumns+4 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+5, "BUY", true, QTABLE_STRING_TYPE, 10) --BUY tableIndex["Команда BUY"] = numberOfVisibleColumns+numberOfFixedColumns+5 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+6, "SELL", true, QTABLE_STRING_TYPE, 10) --SELL tableIndex["Команда SELL"] = numberOfVisibleColumns+numberOfFixedColumns+6 AddColumn(t_id, numberOfVisibleColumns+numberOfFixedColumns+7, "CLOSE", true, QTABLE_STRING_TYPE, 10) --CLOSE ALL tableIndex["Команда CLOSE"] = numberOfVisibleColumns+numberOfFixedColumns+7 columns = columns + 2.3 end t = CreateWindow(t_id) -- Создает таблицу SetWindowCaption(t_id, "Monitor") -- Устанавливает заголовок SetWindowPos(t_id, 90, 60, 87*columns + width*5.8, #SEC_CODES['sec_codes']*17.2) -- Задает положение и размеры окна таблицы -- Добавляет строки for i,v in ipairs(SEC_CODES['names']) do InsertRow(t_id, i) SetCell(t_id, i, tableIndex["Инструмент"], v) --i строка, 0 - колонка, v - значение end tv_id = AllocTable() -- таблица ввода значения thist_id = AllocTable() --таблица истории сделок -- Добавляет колонки AddColumn(thist_id, 0, "Инструмент", true, QTABLE_STRING_TYPE, 20) AddColumn(thist_id, 1, "Номер сделки", true, QTABLE_INT_TYPE, 20) AddColumn(thist_id, 2, "Дата сделки", true, QTABLE_STRING_TYPE, 29) AddColumn(thist_id, 3, "Тип", true, QTABLE_STRING_TYPE, 15) AddColumn(thist_id, 4, "Количество", true, QTABLE_INT_TYPE, 17) AddColumn(thist_id, 5, "Цена", true, QTABLE_DOUBLE_TYPE, 17) AddColumn(thist_id, 6, "Комментарий", true, QTABLE_STRING_TYPE, 130) end function Str(str, num, value, testvalue, dir) -- Функция выводит и окрашивает строки в таблице if dir == nil then dir = 1 end SetCell(t_id, str, num, tostring(value), value) -- Выводит значение в таблицу: строка, коллонка, значение if (value < testvalue and dir == 1) or (value > testvalue and dir == 0) then Green(str, num) elseif value == testvalue then Gray(str, num) else Red(str, num) end -- Окрашивает строку в зависимости от значения профита end ----------------------------- -- Функции по раскраске строк/ячеек таблицы -- ----------------------------- function Green(Line, Col) -- Зеленый if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку SetColor(t_id, Line, Col, RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0)) end function Gray(Line, Col) -- Серый if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку SetColor(t_id, Line, Col, RGB(200,200,200), RGB(0,0,0), RGB(200,200,200), RGB(0,0,0)) end function Red(Line, Col) -- Красный if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку SetColor(t_id, Line, Col, RGB(255,168,164), RGB(0,0,0), RGB(255,168,164), RGB(0,0,0)) end function White(Line, Col) -- Белый if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку SetColor(t_id, Line, Col, RGB(255,255,255), RGB(0,0,0), RGB(255,255,255), RGB(0,0,0)) end function cellSetColor(Line, Col, Color, textColor) if Col == nil then Col = QTABLE_NO_INDEX end -- Если индекс столбца не указан, окрашивает всю строку if Color == nil then Color = RGB(255,255,255) end -- Если цвет не указан, окрашивает в белый if textColor == nil then textColor = RGB(0,0,0) end -- Если цвет не указан, цвет черный SetColor(t_id, Line, Col, Color, textColor, Color, textColor) end ----------------------------- -- Обработка команд таблицы -- ----------------------------- function volume_event_callback(tv_id, msg, par1, par2) if par1 == -1 then return end if msg == QTABLE_CHAR then if tostring(par2) == "8" then local newPrice = string.sub(GetCell(tv_id, par1, 0).image, 1, string.len(GetCell(tv_id, par1, 0).image)-1) SetCell(tv_id, par1, 0, tostring(newPrice)) SetCell(t_id, tstr, tcell, GetCell(tv_id, par1, 0).image, tonumber(GetCell(tv_id, par1, 0).image)) else local inpChar = string.char(par2) local newPrice = GetCell(tv_id, par1, 0).image..string.char(par2) SetCell(tv_id, par1, 0, tostring(newPrice)) SetCell(t_id, tstr, tcell, GetCell(tv_id, par1, 0).image, tonumber(GetCell(tv_id, par1, 0).image)) end end end function event_callback(t_id, msg, par1, par2) if msg == QTABLE_LBUTTONDBLCLK and showTradeCommands == true then if par2 == tableIndex["Инструмент"] then --Выводим сделки createDealsTable(par1) end if par2 == tableIndex["Текущая цена"] or par2 == tableIndex["Цена открытия"] or par2 == tableIndex["Средняя"] or (par2 > numberOfFixedColumns and par2 <= numberOfVisibleColumns+numberOfFixedColumns) then --Берем цену local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1] local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1] local newPrice = GetCorrectPrice(GetCell(t_id, par1, par2).value, TRADE_CLASS_CODE, TRADE_SEC_CODE) local stringPrice = string.gsub(tostring(newPrice),',', '.') local numberPrice = tonumber(stringPrice) if numberPrice~=nil and numberPrice~=0 then SetCell(t_id, par1, tableIndex["Цена сделки"], stringPrice, numberPrice) --i строка, 1 - колонка, v - значение end end if par2 == tableIndex["Цена сделки"] and IsWindowClosed(tv_id) then --Вводим цену tstr = par1 tcell = par2 AddColumn(tv_id, 0, "Значение", true, QTABLE_DOUBLE_TYPE, 25) tv = CreateWindow(tv_id) SetWindowCaption(tv_id, "Введите цену") SetWindowPos(tv_id, 290, 260, 250, 100) InsertRow(tv_id, 1) SetCell(tv_id, 1, 0, GetCell(t_id, par1, tableIndex["Цена сделки"]).image, GetCell(t_id, par1, tableIndex["Цена сделки"]).value) --i строка, 0 - колонка, v - значение end if par2 == tableIndex["Объем сделки"] and IsWindowClosed(tv_id) then --Вводим объем tstr = par1 tcell = par2 AddColumn(tv_id, 0, "Значение", true, QTABLE_INT_TYPE, 25) tv = CreateWindow(tv_id) SetWindowCaption(tv_id, "Введите объем") SetWindowPos(tv_id, 290, 260, 250, 100) InsertRow(tv_id, 1) SetCell(tv_id, 1, 0, GetCell(t_id, par1, tableIndex["Объем сделки"]).image, GetCell(t_id, par1, tableIndex["Объем сделки"]).value) --i строка, 0 - колонка, v - значение end if par2 == tableIndex["Команда CLOSE"] then -- All Close local TRADE_SEC_NAME = SEC_CODES['names'][par1] local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1] local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1] local QTY_LOTS = GetCell(t_id, par1, tableIndex["Позиция"]).value if QTY_LOTS == 0 or QTY_LOTS==nil then message("Некорректно указан объем!!!") return end if QTY_LOTS ~=0 then local CurrentDirect = 'SELL' message(TRADE_SEC_NAME.." Закрытие всей позиции, Объем: "..tostring(QTY_LOTS)..", по рынку") MakeTransaction(CurrentDirect, QTY_LOTS, 0, TRADE_CLASS_CODE, TRADE_SEC_CODE) end end if par2 == tableIndex["Команда BUY"] then --BUY volume local TRADE_SEC_NAME = SEC_CODES['names'][par1] local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1] local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1] local CurrentDirect = 'BUY' local QTY_LOTS = GetCell(t_id, par1, tableIndex["Объем сделки"]).value if QTY_LOTS == 0 or QTY_LOTS==nil then message("Некорректно указан объем!!!") return end local TRADE_PRICE = GetCell(t_id, par1, tableIndex["Цена сделки"]).value local checkString = GetCell(t_id, par1, tableIndex["Цена сделки"]).image if (TRADE_PRICE==nil or TRADE_PRICE==0) and string.len(checkString) ~= 0 then message("Некорректно указана цена: "..tostring(TRADE_PRICE)) return end message(TRADE_SEC_NAME.." Покупка, Объем: "..tostring(QTY_LOTS)..", Цена: "..tostring(TRADE_PRICE)) MakeTransaction(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE) end if par2 == tableIndex["Команда SELL"] then --SELL volume local TRADE_SEC_NAME = SEC_CODES['names'][par1] local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1] local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1] local CurrentDirect = 'SELL' local QTY_LOTS = GetCell(t_id, par1, tableIndex["Объем сделки"]).value if QTY_LOTS == 0 or QTY_LOTS==nil then message("Некорректно указан объем!!!") return end local TRADE_PRICE = GetCell(t_id, par1, tableIndex["Цена сделки"]).value local checkString = GetCell(t_id, par1, tableIndex["Цена сделки"]).image if (TRADE_PRICE==nil or TRADE_PRICE==0) and string.len(checkString) ~= 0 then message("Некорректно указана цена: "..tostring(TRADE_PRICE)) return end message(TRADE_SEC_NAME.." Продажа, Объем: "..tostring(QTY_LOTS)..", Цена: "..tostring(TRADE_PRICE)) MakeTransaction(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE) end if par2 == tableIndex["<"] then local newVolume = GetCell(t_id, par1, tableIndex["Объем сделки"]).value - SEC_CODES['volume'][par1] SetCell(t_id, par1, tableIndex["Объем сделки"], tostring(newVolume), newVolume) --i строка, 1 - колонка, v - значение end if par2 == tableIndex[">"] then local newVolume = GetCell(t_id, par1, tableIndex["Объем сделки"]).value + SEC_CODES['volume'][par1] SetCell(t_id, par1, tableIndex["Объем сделки"], tostring(newVolume), newVolume) --i строка, 1 - колонка, v - значение end end if msg == QTABLE_CHAR and showTradeCommands == true then --message("Клавиша "..tostring(par2)) if tostring(par2) == "8" then --BackSpace SetCell(t_id, par1, tableIndex["Цена сделки"], "") end if tostring(par2) == "68" or tostring(par2) == "194" then --Shift+D local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1] local TRADE_SEC_NAME = SEC_CODES['names'][par1] local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1] message("Удаляем все заявки "..TRADE_SEC_NAME) KillAllOrders("orders", TRADE_CLASS_CODE, TRADE_SEC_CODE) end if tostring(par2) == "83" or tostring(par2) == "219" then --Shift+S local TRADE_SEC_CODE = SEC_CODES['sec_codes'][par1] local TRADE_SEC_NAME = SEC_CODES['names'][par1] local TRADE_CLASS_CODE = SEC_CODES['class_codes'][par1] message("Удаляем все стоп заявки "..TRADE_SEC_NAME) KillAllOrders("stop_orders", TRADE_CLASS_CODE, TRADE_SEC_CODE) end if tostring(par2) == "65" or tostring(par2) == "212" then --sound --Shift+A local curSound = SEC_CODES['isPlaySound'][par1] if curSound == 1 then SEC_CODES['isPlaySound'][par1] = 0 message("Выключаем звук у "..SEC_CODES['names'][par1]) else SEC_CODES['isPlaySound'][par1] = 1 message("Включаем звук у "..SEC_CODES['names'][par1]) end end end if (msg==QTABLE_CLOSE) then --закрытие окна isRun = false end end ----------------------------- -- Обработка команд таблицы -- ----------------------------- --Создание таблицы истоии сделок function createDealsTable(iSec) Clear(thist_id) local secCode = SEC_CODES['sec_codes'][iSec] local classCode = SEC_CODES['class_codes'][iSec] local secTradesFilePath = TradesFilePath..ACCOUNT.."\\"..secCode..".csv" TradesFile = io.open(secTradesFilePath,"r") if TradesFile ~= nil then if IsWindowClosed(thist_id) then thist = CreateWindow(thist_id) SetWindowCaption(thist_id, "Сделки") SetWindowPos(thist_id, 290, 260, 1400, 800) end TradesFile:seek('set',0) local tradeTable = {} -- Перебирает строки файла, считывает содержимое в массив сделок local Count = 0 -- Счетчик строк for line in TradesFile:lines() do Count = Count + 1 if Count > 1 and line ~= "" then InsertRow(thist_id, Count - 1) SetCell(thist_id, Count - 1, 0, SEC_CODES['names'][iSec]) local i = 0 -- счетчик элементов строки local dateDeal = '' local timeDeal = '' local prefix = 1 for str in line:gmatch("[^;^\n]+") do i = i + 1 if i == 3 then SetCell(thist_id, Count - 1, 1, str, tonumber(str)) elseif i == 4 then dateDeal = string.sub(str, 1, 4).."/"..string.sub(str, 5, 6).."/"..string.sub(str, 7, 8) elseif i == 5 then timeDeal = string.sub(str, 1, 2)..":"..string.sub(str, 3, 4)..":"..string.sub(str, 5, 6) SetCell(thist_id, Count - 1, 2, dateDeal.." "..timeDeal) elseif i == 6 then if str == "B" then SetCell(thist_id, Count - 1, 3, "Покупка") prefix = 1 --SetColor(thist_id, Count - 1, QTABLE_NO_INDEX, RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0)) else SetCell(thist_id, Count - 1, 3, "Продажа") prefix = -1 end elseif i == 7 then SetCell(thist_id, Count - 1, 4, str, tonumber(str)) tradeTable[Count] = prefix*tonumber(str) elseif i == 8 then SetCell(thist_id, Count - 1, 5, str, tonumber(str)) elseif i == 9 then SetCell(thist_id, Count - 1, 6, str) end end end end local netCount = GetTotalnet(classCode, secCode) local netSell = 0 if netCount > 0 then for tN=#tradeTable,1,-1 do if netCount == 0 then break end if tradeTable[tN] ~= nil then if tradeTable[tN] < 0 then netSell = netSell - tradeTable[tN] end if tradeTable[tN] > 0 and netSell ==0 then SetColor(thist_id, tN - 1, QTABLE_NO_INDEX, RGB(165,227,128), RGB(0,0,0), RGB(165,227,128), RGB(0,0,0)) netCount = math.max(netCount - tradeTable[tN], 0) netSell = math.max(netSell - tradeTable[tN], 0) end if tradeTable[tN] > 0 and netSell ~=0 then netSell = math.max(netSell - tradeTable[tN], 0) end end end end else message("Сделок по инструменту нет") end end ------------------------------------- --Торговля-- ------------------------------------- -- Функция вызывается терминалом QUIK при получении ответа на транзакцию пользователя function OnTransReply(trans_reply) -- Если поступила информация по текущей транзакции if trans_reply.trans_id == trans_id then -- Передает статус в глобальную переменную trans_Status = trans_reply.status -- Передает сообщение в глобальную переменную trans_result_msg = trans_reply.result_msg if Status == 2 then message("Ошибка при передаче транзакции в торговую систему. Так как отсутствует подключение шлюза Московской Биржи, повторно транзакция не отправляется") myLog("Ошибка при передаче транзакции в торговую систему. Так как отсутствует подключение шлюза Московской Биржи, повторно транзакция не отправляется") end if trans_Status > 3 then if trans_Status == 4 then messageText = "Транзакция не исполнена" end if trans_Status == 5 then messageText = "Транзакция не прошла проверку сервера QUIK" end if trans_Status == 6 then messageText = "Транзакция не прошла проверку лимитов сервера QUIK" end if trans_Status == 7 then messageText = "Транзакция не поддерживается торговой системой" end message('NRTR monitor: Транзакция вернула ошибку: '..messageText) myLog('NRTR monitor: Транзакция вернула ошибку: '..messageText) end myLog("OnTransReply "..tostring(trans_id).." "..trans_result_msg) end --[[ for i=0,getNumberOf('orders')-1 do local order = getItem('orders', i) myLog("trans_id = " .. tostring(order["trans_id"]).." order: num = " .. tostring(order["order_num"]) .." qty=" ..tostring(order["qty"]).." value= "..tostring(order["value"]).." brokerref= "..tostring(order["brokerref"])) end ]]-- end function MakeTransaction(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE) return Trade(CurrentDirect, QTY_LOTS, TRADE_PRICE, TRADE_CLASS_CODE ,TRADE_SEC_CODE) end -- Совершает СДЕЛКУ указанного типа (Type) ["BUY", или "SELL"] function Trade(Type, qnt, TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE) --Получает ID транзакции trans_id = trans_id + 1 if TRADE_PRICE == nil then TRADE_PRICE = 0 end local TRADE_TYPE = 'M'-- по рынку (MARKET) if TRADE_PRICE ~= 0 then TRADE_TYPE = 'L' end local Operation = '' --Устанавливает цену и операцию, в зависимости от типа сделки и от класса инструмента TRADE_SEC_PRICE_STEP = tonumber(getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, "SEC_PRICE_STEP").param_value) if Type == 'BUY' then Operation = 'B' if TRADE_PRICE == 0 and TRADE_CLASS_CODE ~= 'QJSIM' and TRADE_CLASS_CODE ~= 'TQBR' then TRADE_PRICE = getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, 'offer').param_value + 10*TRADE_SEC_PRICE_STEP end -- по цене, завышенной на 10 мин. шагов цены else Operation = 'S' if TRADE_PRICE == 0 and TRADE_CLASS_CODE ~= 'QJSIM' and TRADE_CLASS_CODE ~= 'TQBR' then TRADE_PRICE = getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, 'bid').param_value - 10*TRADE_SEC_PRICE_STEP end -- по цене, заниженной на 10 мин. шагов цены end -- Заполняет структуру для отправки транзакции --TRADE_PRICE = GetCorrectPrice(TRADE_PRICE, TRADE_CLASS_CODE, TRADE_SEC_CODE) myLog("script Monitor: "..TRADE_TYPE.." Transaction "..Type..' '..TRADE_PRICE) local Transaction={ ['TRANS_ID'] = tostring(trans_id), ['ACTION'] = 'NEW_ORDER', ['CLASSCODE'] = TRADE_CLASS_CODE, ['SECCODE'] = TRADE_SEC_CODE, ['CLIENT_CODE'] = CLIENT_CODE, ['OPERATION'] = Operation, -- операция ("B" - buy, или "S" - sell) ['TYPE'] = TRADE_TYPE, ['QUANTITY'] = tostring(qnt), -- количество ['ACCOUNT'] = ACCOUNT, ['PRICE'] = tostring(TRADE_PRICE), ['COMMENT'] = 'script Monitor' -- Комментарий к транзакции, который будет виден в транзакциях, заявках и сделках } -- Отправляет транзакцию local res = sendTransaction(Transaction) if string.len(res) ~= 0 then message('Script monitor: Транзакция вернула ошибку: '..res) myLog('Script monitor: Транзакция вернула ошибку: '..res) return false end return true end --TAKE_PROFIT - минимальных шагов цены профита --STOP_LOSS - минимальных шагов цены стоп-лосса --TRADE_PRICE - уровень цены, на котором выстадяется стоп-заявка --TakeProfitPrice - предыдущий тейк, для трейлинга function SL_TP(TRADE_PRICE, TakeProfitPrice, Type, STOP_LOSS, TAKE_PROFIT ,TRADE_CLASS_CODE, TRADE_SEC_CODE) -- ID транзакции trans_id = trans_id + 1 -- Находит направление для заявки local operation = "" local price = "0" -- Цена, по которой выставится заявка при срабатывании Стоп-Лосса (для рыночной заявки по акциям должна быть 0) local stopprice = "" -- Цена Тейк-Профита local stopprice2 = "" -- Цена Стоп-Лосса local market = "YES" -- После срабатывания Тейка, или Стопа, заявка сработает по рыночной цене local direction TRADE_SEC_PRICE_STEP = tonumber(getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, "SEC_PRICE_STEP").param_value) -- Если открыт BUY, то направление стоп-лосса и тейк-профита SELL, иначе направление стоп-лосса и тейк-профита BUY if Type == 'BUY' then operation = "S" -- Тейк-профит и Стоп-лосс на продажу(чтобы закрыть BUY, нужно открыть SELL) direction = "5" -- Направленность стоп-цены. «5» - больше или равно -- Если не акции if TRADE_CLASS_CODE ~= 'QJSIM' and TRADE_CLASS_CODE ~= 'TQBR' then price = tostring(math.floor(getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, 'PRICEMIN').param_value)) -- Цена выставляемой заявки после страбатывания Стопа минимально возможная, чтобы не проскользнуло market = "YES" -- После срабатывания Тейка, или Стопа, заявка сработает НЕ по рыночной цене end if (TakeProfitPrice or 0) == 0 then stopprice = tostring(TRADE_PRICE + TAKE_PROFIT*TRADE_SEC_PRICE_STEP) -- Уровень цены, когда активируется Тейк-профит TakeProfitPrice = stopprice else stopprice = TakeProfitPrice + math.floor(STOP_LOSS*TRADE_SEC_PRICE_STEP/2) -- немного сдвигаем тейк-профит end stopprice2 = tostring(TRADE_PRICE - STOP_LOSS*TRADE_SEC_PRICE_STEP) -- Уровень цены, когда активируется Стоп-лосс price = stopprice2 - 2*TRADE_SEC_PRICE_STEP else -- открыт SELL operation = "B" -- Тейк-профит и Стоп-лосс на покупку(чтобы закрыть SELL, нужно открыть BUY) direction = "4" -- Направленность стоп-цены. «4» - меньше или равно -- Если не акции if TRADE_CLASS_CODE ~= 'QJSIM' and TRADE_CLASS_CODE ~= 'TQBR' then price = tostring(math.floor(getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, 'PRICEMAX').param_value)) -- Цена выставляемой заявки после страбатывания Стопа максимально возможная, чтобы не проскользнуло market = "YES" -- После срабатывания Тейка, или Стопа, заявка сработает НЕ по рыночной цене end if (TakeProfitPrice or 0) == 0 then stopprice = tostring(TRADE_PRICE - TAKE_PROFIT*TRADE_SEC_PRICE_STEP) -- Уровень цены, когда активируется Тейк-профит TakeProfitPrice = stopprice else stopprice = TakeProfitPrice - math.floor(STOP_LOSS*TRADE_SEC_PRICE_STEP/2) -- немного сдвигаем тейк-профит end stopprice2 = tostring(TRADE_PRICE + STOP_LOSS*TRADE_SEC_PRICE_STEP) -- Уровень цены, когда активируется Стоп-лосс price = stopprice2 + 2*TRADE_SEC_PRICE_STEP end -- Заполняет структуру для отправки транзакции на Стоп-лосс и Тейк-профит myLog('Script monitor: Установка ТЕЙК-ПРОФИТ: '..stopprice..' и СТОП-ЛОСС: '..stopprice2) local Transaction = { ["ACTION"] = "NEW_STOP_ORDER", -- Тип заявки ["TRANS_ID"] = tostring(trans_id), ["CLASSCODE"] = TRADE_CLASS_CODE, ["SECCODE"] = TRADE_SEC_CODE, ["ACCOUNT"] = ACCOUNT, ['CLIENT_CODE'] = CLIENT_CODE, -- Комментарий к транзакции, который будет виден в транзакциях, заявках и сделках ["OPERATION"] = operation, -- Операция ("B" - покупка(BUY), "S" - продажа(SELL)) ["QUANTITY"] = tostring(QTY_LOTS), -- Количество в лотах ["PRICE"] = GetCorrectPrice(price), -- Цена, по которой выставится заявка при срабатывании Стоп-Лосса (для рыночной заявки по акциям должна быть 0) ["STOPPRICE"] = GetCorrectPrice(stopprice), -- Цена Тейк-Профита ["STOP_ORDER_KIND"] = "TAKE_PROFIT_AND_STOP_LIMIT_ORDER", -- Тип стоп-заявки ["EXPIRY_DATE"] = "GTC", -- Срок действия стоп-заявки ("GTC" – до отмены,"TODAY" - до окончания текущей торговой сессии, Дата в формате "ГГММДД") -- "OFFSET" - (ОТСТУП)Если цена достигла Тейк-профита и идет дальше в прибыль, -- то Тейк-профит сработает только когда цена вернется минимум на 2 шага цены назад, -- это может потенциально увеличить прибыль ["OFFSET"] = tostring(2*TRADE_SEC_PRICE_STEP), ["OFFSET_UNITS"] = "PRICE_UNITS", -- Единицы измерения отступа ("PRICE_UNITS" - шаг цены, или "PERCENTS" - проценты) -- "SPREAD" - Когда сработает Тейк-профит, выставится заявка по цене хуже текущей на 100 шагов цены, -- которая АВТОМАТИЧЕСКИ УДОВЛЕТВОРИТСЯ ПО ТЕКУЩЕЙ ЛУЧШЕЙ ЦЕНЕ, -- но то, что цена значительно хуже, спасет от проскальзывания, -- иначе, сделка может просто не закрыться (заявка на закрытие будет выставлена, но цена к тому времени ее уже проскочит) ["SPREAD"] = tostring(100*TRADE_SEC_PRICE_STEP), ["SPREAD_UNITS"] = "PRICE_UNITS", -- Единицы измерения защитного спрэда ("PRICE_UNITS" - шаг цены, или "PERCENTS" - проценты) -- "MARKET_TAKE_PROFIT" = ("YES", или "NO") должна ли выставится заявка по рыночной цене при срабатывании Тейк-Профита. -- Для рынка FORTS рыночные заявки, как правило, запрещены, -- для лимитированной заявки на FORTS нужно указывать заведомо худшую цену, чтобы она сработала сразу же, как рыночная ["MARKET_TAKE_PROFIT"] = market, ["STOPPRICE2"] = GetCorrectPrice(stopprice2), -- Цена Стоп-Лосса ["IS_ACTIVE_IN_TIME"] = "NO", -- "MARKET_TAKE_PROFIT" = ("YES", или "NO") должна ли выставится заявка по рыночной цене при срабатывании Стоп-Лосса. -- Для рынка FORTS рыночные заявки, как правило, запрещены, -- для лимитированной заявки на FORTS нужно указывать заведомо худшую цену, чтобы она сработала сразу же, как рыночная ["MARKET_STOP_LIMIT"] = market, ['CONDITION'] = direction, -- Направленность стоп-цены. Возможные значения: «4» - меньше или равно, «5» – больше или равно ["COMMENT"] = "Script monitor ТЕЙК-ПРОФИТ и СТОП-ЛОСС" } -- Отправляет транзакцию на установку ТЕЙК-ПРОФИТ и СТОП-ЛОСС local res = sendTransaction(Transaction) if string.len(res) ~= 0 then message('Script monitor: Установка ТЕЙК-ПРОФИТ и СТОП-ЛОСС не удалась!\nОШИБКА: '..res) myLog('Script monitor: Установка ТЕЙК-ПРОФИТ и СТОП-ЛОСС не удалась!\nОШИБКА: '..res) return false else -- Выводит сообщение message('Script monitor: ВЫСТАВЛЕНА заявка ТЕЙК-ПРОФИТ и СТОП-ЛОСС: '..trans_id) myLog('Script monitor: ВЫСТАВЛЕНА заявка ТЕЙК-ПРОФИТ и СТОП-ЛОСС: '..trans_id) return true end end --ordtable = "stop_orders" --ordtable = "orders" function KillAllOrders(ordtable, TRADE_CLASS_CODE, TRADE_SEC_CODE) function myFind(C,S,F) return (C == TRADE_CLASS_CODE) and (S == TRADE_SEC_CODE) and (bit.band(F, 0x1) ~= 0) end local res=1 local action = "KILL_ORDER" local order_key = "ORDER_KEY" if ordtable == "stop_orders" then action = "KILL_STOP_ORDER" order_key = "STOP_ORDER_KEY" end local orders = SearchItems(ordtable, 0, getNumberOf(ordtable)-1, myFind, "class_code,sec_code,flags") if (orders ~= nil) and (#orders > 0) then for i=1,#orders do -- Получает ID для следующей транзакции trans_id = trans_id + 1 -- Заполняет структуру для отправки транзакции на снятие стоп-заявки local Transaction = { ["ACTION"] = action, -- Тип заявки ["TRANS_ID"] = tostring(trans_id), ["CLASSCODE"] = TRADE_CLASS_CODE, ["SECCODE"] = TRADE_SEC_CODE, ["ACCOUNT"] = ACCOUNT, ['CLIENT_CODE'] = CLIENT_CODE, -- Комментарий к транзакции, который будет виден в транзакциях, заявках и сделках [order_key] = tostring(getItem(ordtable,orders[i]).order_num) -- Номер заявки, снимаемой из торговой системы } -- Отправляет транзакцию local Res = sendTransaction(Transaction) -- Если при отправке транзакции возникла ошибка if string.len(Res) ~= 0 then -- Выводит ошибку message('Ошибка снятия заявки: '..Res) myLog('Ошибка снятия заявки: '..Res) return false end local order = getItem(ordtable, orders[i]) -- Если стоп-заявка не активна myLog('прверка заявки: '..order.sec_code..' number: '..tostring(order.order_num)) if not bit.test(order.flags, 0) then -- Если заявка успела исполниться if not bit.test(order.flags, 1) then return true else message('Возникла неизвестная ошибка при снятии ЗАЯВКИ '..tostring(order.order_num)) myLog('Возникла неизвестная ошибка при снятии ЗАЯВКИ '..tostring(order.order_num)) return false end end end else message("Не найдены активные заявки "..TRADE_SEC_CODE) myLog("Не найдены активные заявки "..TRADE_SEC_CODE) end return true end -- Получение таблицы стоп-ордера по его номеру -- Возвращает таблицу стоп-зявки или nil function getStopOrderByNumber(stop_order_number,from,to) local index_table = SearchItems("stop_orders", from or 0, to or getNumberOf("stop_orders")-1, function(t) return t.order_num == stop_order_number end) if index_table then return getItem("stop_orders",index_table[1]) end end -- Получение таблицы стоп-ордера по номеру порожденной им заявки -- Возвращает таблицу стоп-заявки или nil function getStopOrderByOrderNumber(order_number,from,to) local index_table = SearchItems("stop_orders", from or 0, to or getNumberOf("stop_orders")-1, function(t) return t.linkedorder == order_number end) if index_table then return getItem("stop_orders",index_table[1]) end end ------------------------------------- --Торговля-- ------------------------------------- ----------------------------- -- Алгоритм -- ----------------------------- function up_downTest(i, cell, settings, DS, signal) --local testvalue = tonumber(getParamEx(CLASS_CODE,SEC_CODE,"last").param_value) or 0 local index = DS:Size() local testvalue = GetCell(t_id, i, tableIndex["Текущая цена"]).value local price_step = tonumber(getParamEx(CLASS_CODE, SEC_CODE, "SEC_PRICE_STEP").param_value) or 0 local scale = getSecurityInfo(CLASS_CODE, SEC_CODE).scale local signaltestvalue1 = calcAlgoValue[index-1] or 0 local signaltestvalue2 = calcAlgoValue[index-2] or 0 local testZone = settings.testZone or 10 if calcAlgoValue[index] == nil or index == 0 then return end local calcVal = round(calcAlgoValue[index] or 0, scale) local testSignalZone = price_step*testZone local downTestZone = calcVal-testSignalZone local upTestZone = calcVal+testSignalZone if INTERVALS["visible"][cell] then local Color = RGB(255, 255, 255) if testvalue > downTestZone and testvalue < calcVal then Color = RGB(255, 220, 220) elseif testvalue < upTestZone and testvalue > calcVal then Color = RGB(220, 255, 220) elseif testvalue < downTestZone then Color = RGB(255,168,164) elseif testvalue > upTestZone then Color = RGB(165,227,128) end SetCell(t_id, i, tableIndex[cell], tostring(calcVal), calcVal) cellSetColor(i, tableIndex[cell], Color, RGB(0,0,0)) end if signal then local isMessage = SEC_CODES['isMessage'][i] local isPlaySound = SEC_CODES['isPlaySound'][i] local mes0 = tostring(SEC_CODES['names'][i]).." timescale "..INTERVALS["names"][cell] local mes = "" if signaltestvalue1 < DS:C(index-1) and signaltestvalue2 > DS:C(index-2) then mes = mes0..": Сигнал Buy" myLog(mes) --myLog("Значение алгоритма -1 "..tostring(signaltestvalue1).." Закрытие свечи-1 "..DS:C(index-1)) --myLog("Значение алгоритма -2 "..tostring(signaltestvalue2).." Закрытие свечи-2 "..DS:C(index-2)) if isMessage == 1 then message(mes) end if isPlaySound == 1 then PaySoundFile(soundFileName) end end if signaltestvalue1 > DS:C(index-1) and signaltestvalue2 < DS:C(index-2) then mes = mes0..": Сигнал Sell" myLog(mes) --myLog("Значение алгоритма -1 "..tostring(signaltestvalue1).." Закрытие свечи-1 "..DS:C(index-1)) --myLog("Значение алгоритма -2 "..tostring(signaltestvalue2).." Закрытие свечи-2 "..DS:C(index-2)) if isMessage == 1 then message(mes) end if isPlaySound == 1 then PaySoundFile(soundFileName) end end if testvalue < upTestZone and DS:C(index-1) > upTestZone then mes = mes0..": Цена опустилась к зоне "..tostring(upTestZone) myLog(mes) if isMessage == 1 then message(mes) end if isPlaySound == 1 then PaySoundFile(soundFileName) end end if testvalue > downTestZone and DS:C(index-1) < downTestZone then mes = mes0..": Цена поднялась к зоне "..tostring(downTestZone) myLog(mes) if isMessage == 1 then message(mes) end if isPlaySound == 1 then PaySoundFile(soundFileName) end end if testvalue > upTestZone and DS:C(index-1) < upTestZone then mes = mes0..": Цена оттолкнулась от зоны "..tostring(upTestZone) myLog(mes) if isMessage == 1 then message(mes) end if isPlaySound == 1 then PaySoundFile(soundFileName) end end if testvalue < downTestZone and DS:C(index-1) > downTestZone then mes = mes0..": Цена опустилась от зоны "..tostring(downTestZone) myLog(mes) if isMessage == 1 then message(mes) end if isPlaySound == 1 then PaySoundFile(soundFileName) end end end end function addDeal(index, ChartId, openLong, openShort, closeLong, closeShort, time) label = { DATE = 0, TIME = 0, TEXT="***********", HINT="", FONT_FACE_NAME = "Arial", FONT_HEIGHT = 10, R = 64, G = 192, B = 64, TRANSPARENT_BACKGROUND = 1, YVALUE = 0, } label.DATE = (time.year*10000+time.month*100+time.day) label.TIME = ((time.hour)*10000+(time.min)*100) local IMAGE_PATH = getScriptPath()..'\\Pictures\\' if openLong ~= nil then label.YVALUE = openLong label.IMAGE_PATH = IMAGE_PATH..'МоиСделки_buy.bmp' ALIGNMENT = "BOTTOM" label.R = 0 label.G = 0 label.B = 0 label.TEXT = tostring(openLong) label.HINT = "open Long "..tostring(openLong) elseif openShort ~=nil then label.YVALUE = openShort label.IMAGE_PATH = IMAGE_PATH..'МоиСделки_sell.bmp' label.R = 0 label.G = 0 label.B = 0 ALIGNMENT = "TOP" label.TEXT = tostring(openShort) label.HINT = "open Short "..tostring(openShort) elseif closeLong ~=nil then label.YVALUE = closeLong label.IMAGE_PATH = IMAGE_PATH..'МоиСделки_sell.bmp' ALIGNMENT = "TOP" label.R = 0 label.G = 0 label.B = 0 label.TEXT = tostring(closeLong) label.HINT = "close Long "..tostring(closeLong) elseif closeShort ~=nil then label.YVALUE = closeShort label.IMAGE_PATH = IMAGE_PATH..'МоиСделки_buy.bmp' ALIGNMENT = "BOTTOM" label.R = 0 label.G = 0 label.B = 0 label.TEXT = tostring(closeShort) label.HINT = "close Short "..tostring(closeShort) end AddLabel(ChartId, label) end function noSignal() return {} end function getATR(i, dayIntervalIndex) local dayDS = nil if isDayInterval == false then SEC_CODES['dayDS'][i] = CreateDataSource(SEC_CODES['class_codes'][i],SEC_CODES['sec_codes'][i],INTERVAL_D1) dayDS = SEC_CODES['dayDS'][i] else dayDS = SEC_CODES['DS'][i][dayIntervalIndex] end local scale = getSecurityInfo(SEC_CODES['class_codes'][i],SEC_CODES['sec_codes'][i]).scale local dayATR_Period = SEC_CODES['dayATR_Period'][i] local lastATR = round(calcDayATR(dayATR_Period, DS), scale) SEC_CODES['dayATR'][i] = lastATR --myLog("Day ATR ".. SEC_CODE.." "..tostring(lastATR)) SetCell(t_id, i, tableIndex["D ATR"], tostring(lastATR), lastATR) --i строка, 1 - колонка, v - значение SEC_CODES['D_minus5'][i] = dayDS:C(dayDS:Size()-5) end function calcDayATR(dayATR_Period, DS) local ATR = {} local ind = DS:Size() - 200 ATR[1] = 0 --myLog("Day ATR ".. SEC_CODE.." DS:Size() ".. tostring(DS:Size()).." ind "..tostring(ind)) for index = 2, 200 do ATR[index] = ATR[index-1] if DS:C(index+ind) ~= nil then if index==dayATR_Period then local sum=0 for i = 1, dayATR_Period do sum = sum + dValue(ind+i) end ATR[index]=sum / dayATR_Period elseif index>dayATR_Period then ATR[index]=(ATR[index-1] * (dayATR_Period-1) + dValue(index+ind)) / dayATR_Period end --myLog("Day ATR ".. SEC_CODE.."index ".. tostring(index+ind)..": "..tostring(lastATR)) end end return ATR[200] or 0 end function dValue(i) local previous = i-1 if DS:C(i) == nil then previous = FindExistCandle(previous) end return math.max(math.abs(DS:H(i) - DS:L(i)), math.abs(DS:H(i) - DS:C(previous)), math.abs(DS:C(previous) - DS:L(i))) end ----------------------------- -- ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ -- ----------------------------- function OnDepoLimit(dlimit) if dlimit.limit_kind~=2 then return end for i=1,#SEC_CODES['sec_codes'] do if SEC_CODES['sec_codes'][i] == dlimit.sec_code then local class_code = SEC_CODES['class_codes'][i] local lotsize = tonumber(getParamEx(class_code,dlimit.sec_code,"lotsize").param_value) if lotsize == 0 or lotsize == nil then lotsize = 1 end SetCell(t_id, i, tableIndex["Позиция"], tostring(dlimit.currentbal/lotsize), dlimit.currentbal/lotsize) --i строка, 1 - колонка, v - значение local awg_price = GetCorrectPrice(dlimit.awg_position_price, class_code, dlimit.sec_code) awg_price = string.gsub(tostring(awg_price),',', '.') local last_price = GetCell(t_id, i, tableIndex["Текущая цена"]).value or 0 if tonumber(awg_price)==0 then SetCell(t_id, i, tableIndex["Средняя"], '', 0) --i строка, 1 - колонка, v - значение White(i, tableIndex["Средняя"]) else Str(i, tableIndex["Средняя"], tonumber(awg_price), last_price) --i строка, 1 - колонка, v - значение end if showTradeCommands == true then if dlimit.currentbal~=0 then Red(i, tableIndex["Команда CLOSE"]) SetCell(t_id, i, tableIndex["Команда CLOSE"], "CLOSE") --i строка, 0 - колонка, v - значение else White(i, tableIndex["Команда CLOSE"]) SetCell(t_id, i, tableIndex["Команда CLOSE"], "") --i строка, 0 - колонка, v - значение end end break end end end function OnFuturesClientHolding(fut_limit) for i=1,#SEC_CODES['sec_codes'] do if SEC_CODES['sec_codes'][i] == fut_limit.sec_code then local class_code = SEC_CODES['class_codes'][i] local lotsize = tonumber(getParamEx(class_code,fut_limit.sec_code,"lotsize").param_value) if lotsize == 0 or lotsize == nil then lotsize = 1 end SetCell(t_id, i, tableIndex["Позиция"], tostring(fut_limit.totalnet/lotsize), fut_limit.totalnet/lotsize) --i строка, 1 - колонка, v - значение local awg_price = GetCorrectPrice(fut_limit.avrposnprice, class_code, fut_limit.sec_code) awg_price = string.gsub(tostring(awg_price),',', '.') local last_price = GetCell(t_id, i, tableIndex["Текущая цена"]).value or 0 if tonumber(awg_price)==0 then SetCell(t_id, i, tableIndex["Средняя"], '', 0) --i строка, 1 - колонка, v - значение White(i, tableIndex["Средняя"]) else Str(i, tableIndex["Средняя"], tonumber(awg_price), last_price) --i строка, 1 - колонка, v - значение end if showTradeCommands == true then if fut_limit.totalnet~=0 then Red(i, tableIndex["Команда CLOSE"]) SetCell(t_id, i, tableIndex["Команда CLOSE"], "CLOSE") --i строка, 0 - колонка, v - значение else White(i, tableIndex["Команда CLOSE"]) SetCell(t_id, i, tableIndex["Команда CLOSE"], "") --i строка, 0 - колонка, v - значение end end break end end end function GetTotalnet(class_code, sec_code) -- ФЬЮЧЕРСЫ, ОПЦИОНЫ local opencount = 0 local awg_position_price = 0 if class_code == 'SPBFUT' or class_code == 'SPBOPT' then for i = 0,getNumberOf('futures_client_holding') - 1 do local futures_client_holding = getItem('futures_client_holding',i) if futures_client_holding.sec_code == sec_code then opencount = futures_client_holding.totalnet awg_position_price = GetCorrectPrice(futures_client_holding.avrposnprice, class_code, futures_client_holding.sec_code) end end -- АКЦИИ elseif class_code == 'TQBR' or class_code == 'QJSIM' then local lotsize = tonumber(getParamEx(class_code,sec_code,"lotsize").param_value) if lotsize == 0 or lotsize == nil then lotsize = 1 end --myLog("sec_code "..sec_code.." class_code "..class_code.." lotsize "..tostring(lotsize)) for i = 0,getNumberOf('depo_limits') - 1 do local depo_limit = getItem("depo_limits", i) --myLog("trdaccid "..depo_limit.trdaccid.." sec_code "..depo_limit.sec_code.." limit kind "..tostring(depo_limit.limit_kind).." pos: "..tostring(depo_limit.currentbal)) if depo_limit.sec_code == sec_code and depo_limit.trdaccid == ACCOUNT and depo_limit.limit_kind == 2 then -- T+2 opencount = depo_limit.currentbal/lotsize awg_position_price = GetCorrectPrice(depo_limit.awg_position_price, class_code, sec_code) end end end awg_position_price = string.gsub(tostring(awg_position_price),',', '.') --myLog("awg_position_price "..tostring(awg_position_price)) --myLog("sec_code "..sec_code.." class_code "..class_code.." pos: "..tostring(opencount)) -- Если позиция по инструменту в таблице не найдена, возвращает 0 return opencount, awg_position_price end function mysplit(inputstr, sep) if sep == nil then sep = "%s" end local t={} local i=1 for str in string.gmatch(inputstr, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end -- функция записывает в лог строчку с временем и датой function myLog(str) if logFile==nil then return end local current_time=os.time()--tonumber(timeformat(getInfoParam("SERVERTIME"))) -- помещене в переменную времени сервера в формате HHMMSS if (current_time-g_previous_time)>1 then -- если текущая запись произошла позже 1 секунды, чем предыдущая logFile:write("\n") -- добавляем пустую строку для удобства чтения end g_previous_time = current_time logFile:write(os.date().."; ".. str .. ";\n") if str:find("Script Stoped") ~= nil then logFile:write("======================================================================================================================\n\n") logFile:write("======================================================================================================================\n") end logFile:flush() -- Сохраняет изменения в файле end -- удаление точки и нулей после нее function removeZero(str) while (string.sub(str,-1) == "0" and str ~= "0") do str = string.sub(str,1,-2) end if (string.sub(str,-1) == ".") then str = string.sub(str,1,-2) end return str end -- Получает точность цены по инструменту function GetCorrectPrice(price, TRADE_CLASS_CODE, TRADE_SEC_CODE) -- STRING local scale = getSecurityInfo(TRADE_CLASS_CODE, TRADE_SEC_CODE).scale -- Получает минимальный шаг цены инструмента local PriceStep = tonumber(getParamEx(TRADE_CLASS_CODE, TRADE_SEC_CODE, "SEC_PRICE_STEP").param_value) -- Если после запятой должны быть цифры if scale > 0 then price = tostring(price) -- Ищет в числе позицию запятой, или точки local dot_pos = price:find('.') local comma_pos = price:find(',') -- Если передано целое число if dot_pos == nil and comma_pos == nil then -- Добавляет к числу ',' и необходимое количество нулей и возвращает результат price = price..',' for i=1,scale do price = price..'0' end return price else -- передано вещественное число -- Если нужно, заменяет запятую на точку if comma_pos ~= nil then price:gsub(',', '.') end -- Округляет число до необходимого количества знаков после запятой price = round(tonumber(price), scale) --message(TRADE_SEC_CODE.." price step "..PriceStep.." scale: "..tostring(scale).." price old: "..tostring(price)) -- Корректирует на соответствие шагу цены price = price - price % PriceStep --message("price new: "..tostring(price)) --price = string.gsub(tostring(price),'[\.]+', ',') return price end else -- После запятой не должно быть цифр -- Корректирует на соответствие шагу цены price = price - price % PriceStep return tostring(math.floor(price)) end end function PaySoundFile(file_name) w32.mciSendString("CLOSE QUIK_MP3") w32.mciSendString("OPEN \"" .. file_name .. "\" TYPE MpegVideo ALIAS QUIK_MP3") w32.mciSendString("PLAY QUIK_MP3") end function round(num, idp) if num then local mult = 10^(idp or 0) if num >= 0 then return math.floor(num * mult + 0.5) / mult else return math.ceil(num * mult - 0.5) / mult end else return num end end function FindExistCandle(I) local out = I while DS:C(out) == nil and out > 0 do out = out -1 end return out end function toYYYYMMDDHHMMSS(datetime) if type(datetime) ~= "table" then --message("в функции toYYYYMMDDHHMMSS неверно задан параметр: datetime="..tostring(datetime)) return "" else local Res = tostring(datetime.year) if #Res == 1 then Res = "000"..Res end local month = tostring(datetime.month) if #month == 1 then Res = Res.."/0"..month; else Res = Res..'/'..month; end local day = tostring(datetime.day) if #day == 1 then Res = Res.."/0"..day; else Res = Res..'/'..day; end local hour = tostring(datetime.hour) if #hour == 1 then Res = Res.." 0"..hour; else Res = Res..' '..hour; end local minute = tostring(datetime.min) if #minute == 1 then Res = Res..":0"..minute; else Res = Res..':'..minute; end local sec = tostring(datetime.sec); if #sec == 1 then Res = Res..":0"..sec; else Res = Res..':'..sec; end; return Res end end --toYYYYMMDDHHMMSS function isnil(a,b) if a == nil then return b else return a end; end
local class = require 'middleclass' local util = require 'util' -- クラス:現在位置 local Whereabouts = class 'Whereabouts' -- 組み込み Whereabouts:include(require 'Readonly') -- 初期化 function Whereabouts:initialize(t) t = t or {} self.place = t.place or '' self.x = t.x or 0 self.y = t.y or 0 self.level = t.level or '' end -- オーバーライド:比較 function Whereabouts:__eq(other) return util.equaltable(self, other, { 'place', 'x', 'y', 'level' }) end return Whereabouts
local dex = {} dex.startup = "For the Clockworkpi Gameshell with Lightkeys" dex.chapter1 = {} dex.chapter1.title = "test" return dex
local vec2 = require "math.vector.vec2" local a = vec2(0, 0) assert(a:isZero(), "a is a zero vector") local b = vec2(1, 1) a:assign(b) assert(a == b, "a is equal to b") local c = a + b assert(c:eq(vec2(1, 1)))
--[[ ============================================================================================================ Author: Rook Date: January 26, 2015 Called when Dagon is cast. Damages the target. Additional parameters: keys.Damage ================================================================================================================= ]] function item_dagon_datadriven_on_spell_start(keys) local dagon_level = keys.ability:GetLevel() local dagon_particle = ParticleManager:CreateParticle("particles/items_fx/dagon.vpcf", PATTACH_ABSORIGIN_FOLLOW, keys.caster) ParticleManager:SetParticleControlEnt(dagon_particle, 1, keys.target, PATTACH_POINT_FOLLOW, "attach_hitloc", keys.target:GetAbsOrigin(), false) local particle_effect_intensity = 300 + (100 * dagon_level) --Control Point 2 in Dagon's particle effect takes a number between 400 and 800, depending on its level. ParticleManager:SetParticleControl(dagon_particle, 2, Vector(particle_effect_intensity)) keys.caster:EmitSound("DOTA_Item.Dagon.Activate") keys.target:EmitSound("DOTA_Item.Dagon5.Target") ApplyDamage({victim = keys.target, attacker = keys.caster, damage = keys.Damage, damage_type = DAMAGE_TYPE_MAGICAL,}) end
Base = require('src/lib/base') Utils = require('src/lib/utils') require('src/Event') require('src/Player') require('src/Enemy') require('src/EnemyGroup') require('src/Beam')
-- local export = {} local smt = getmetatable("") smt.__index = function (this, index) return string.sub(this, index, index) end
local sandbox = require("sandbox") local socket = require("cqueues.socket") local function fork() local s1, s2 = socket.pair() local pid, errn, errs = assert(sandbox.fork()) if not pid then return errn, errs else return pid, s1, s2 end end return { fork = fork }
-- Constructed with love by ImogenOC. Shared and Used under the MIT Licensing. -- Grace of Air (Mastery) { "116956", { "!player.buff(155522)", -- Power of the Grave "!player.buff(24907)", -- Moonkin Aura "!player.buff(19740)", -- Blessing of Might "!player.buff(116956)", -- Grace of Air "!player.buff(93435)", -- Hunter: Cat Pet Species Type - Roar of Courage "!player.buff(160039)", -- Hunter: Hydra Pet Species Type - Keen Senses "!player.buff(128997)", -- Hunter: Spirit Beast Pet Species Type - Spirit Beast Blessing "!player.buff(160073)", -- Hunter: Tallstrider Pet Species Type - Plainswalking }}, -- Grace of Air Time Critical { "116956", { "player.buff(155522).duration <= 900", -- Power of the Grave "player.buff(24907).duration <= 900", -- Moonkin Aura "player.buff(19740).duration <= 900", -- Blessing of Might "player.buff(116956).duration <= 900", -- Grace of Air "player.buff(93435).duration <= 900", -- Hunter: Cat Pet Species Type - Roar of Courage "player.buff(160039).duration <= 900", -- Hunter: Hydra Pet Species Type - Keen Senses "player.buff(128997).duration <= 900", -- Hunter: Spirit Beast Pet Species Type - Spirit Beast Blessing "player.buff(160073).duration <= 900", -- Hunter: Tallstrider Pet Species Type - Plainswalking }}, -- Grace of Air (Haste) { "116956", { "!player.buff(55610)", -- Unhola Aura "!player.buff(49868)", -- Mind Quickening "!player.buff(113742)", -- Swiftblade's Cunning "!player.buff(116956)", -- Grace of Air "!player.buff(128432)", -- Hunter: Hyena Pet Species Type - Cackling Howl "!player.buff(160003)", -- Hunter: Rylak Pet Species Type - Savage Vigor "!player.buff(135678)", -- Hunter: Sporebat Pet Species Type - Energizing Spores "!player.buff(160074)", -- Hunter: Wasp Pet Species Type - Speed of the Swarm }}, -- Grace of Air - Time Remaining Critical { "116959", { "!player.buff(55610).duration <= 900", -- Unhola Aura "!player.buff(49868).duration <= 900", -- Mind Quickening "!player.buff(113742).duration <= 900", -- Swiftblade's Cunning "!player.buff(116956).duration <= 900", -- Grace of Air "!player.buff(128432).duration <= 900", -- Hunter: Hyena Pet Species Type - Cackling Howl "!player.buff(160003).duration <= 900", -- Hunter: Rylak Pet Species Type - Savage Vigor "!player.buff(135678).duration <= 900", -- Hunter: Sporebat Pet Species Type - Energizing Spores "!player.buff(160074).duration <= 900", -- Hunter: Wasp Pet Species Type - Speed of the Swarm }},
data.raw.recipe["5d-transport-belt-05"].ingredients = { {"iron-plate", 10}, {"steel-plate", 10}, {"processing-unit", 2}, {"5d-transport-belt-04", 2} } data.raw.recipe["5d-transport-belt-04"].ingredients = { {"iron-plate", 10}, {"steel-plate", 10}, {"advanced-circuit", 2}, {"express-transport-belt", 2} } if storage == true then data.raw.recipe["5d-storage-tank-02"].ingredients = { {"storage-tank", 1}, {"tin-plate", 15}, {"lead-plate", 7}, {"stone", 5} } end data.raw.recipe["5d-splitter-05"].ingredients = { {"5d-splitter-04", 5}, {"processing-unit", 5}, {"iron-plate", 5}, {"transport-belt", 4} } data.raw.recipe["5d-splitter-04"].ingredients = { {"express-splitter", 1}, {"advanced-circuit", 15}, {"iron-plate", 5}, {"express-transport-belt", 4} } data.raw.recipe["5d-pipe-to-ground-mk1-50"].ingredients = { {"pipe", 50}, {"iron-plate", 5} } data.raw.recipe["5d-pipe-to-ground-mk1-30"].ingredients = { {"pipe", 30}, {"iron-plate", 5} } data.raw.recipe["5d-underground-belt-50-05"].ingredients = { {"iron-plate", 10}, {"5d-transport-belt-05", 50} } data.raw.recipe["5d-underground-belt-30-05"].ingredients = { {"iron-plate", 10}, {"5d-transport-belt-05", 30} } data.raw.recipe["5d-underground-belt-05"].ingredients = { {"iron-plate", 10}, {"5d-transport-belt-05", 5} } data.raw.recipe["5d-underground-belt-50-04"].ingredients = { {"iron-plate", 10}, {"5d-transport-belt-04", 50} } data.raw.recipe["5d-underground-belt-30-04"].ingredients = { {"iron-plate", 10}, {"5d-transport-belt-04", 30} } data.raw.recipe["5d-underground-belt-04"].ingredients = { {"iron-plate", 10}, {"5d-transport-belt-04", 5} } data.raw.recipe["5d-express-underground-belt-50-03"].ingredients = { {"iron-plate", 10}, {"express-transport-belt", 50} } data.raw.recipe["5d-express-underground-belt-30-03"].ingredients = { {"iron-plate", 10}, {"express-transport-belt", 30} } data.raw.recipe["5d-fast-underground-belt-50-02"].ingredients = { {"iron-plate", 10}, {"fast-transport-belt", 50} } data.raw.recipe["5d-fast-underground-belt-30-02"].ingredients = { {"iron-plate", 10}, {"fast-transport-belt", 30} } data.raw.recipe["5d-underground-belt-50-01"].ingredients = { {"iron-plate", 10}, {"transport-belt", 50} } data.raw.recipe["5d-underground-belt-30-01"].ingredients = { {"iron-plate", 10}, {"transport-belt", 30} }
local cosock = require "cosock" local socket = cosock.socket local channel = cosock.channel cosock.spawn(function() print("receiver spawn") local sender, receiver = channel.new() cosock.spawn(function() sender:send(true) end) -- sleep to force ^ thread to finish socket.sleep(0.01) -- call select after send in thread has finished socket.select({receiver}, {}) assert(true == receiver:receive()) print("server exit") end, "receiver") cosock.run() print("--------------- SUCCESS ----------------")
-- This file is automatically generated, do not edit! -- Item data (c) Grinding Gear Games return { ["Ancestral Cry"] = { ["MERCILESS"] = { "Attacks Exerted by Ancestral Cry deal 35% increased Damage ", }, ["ENDGAME"] = { "Attacks Exerted by Ancestral Cry deal 50% increased Damage ", "Ancestral Cry has a minimum of 10 Power", }, }, ["Ancestral Protector"] = { ["MERCILESS"] = { "Ancestral Protector Totem deals 25% increased Damage", "12% increased Ancestral Protector Totem Placement Speed", "+24% to Ancestral Protector Totem Elemental Resistances", "Ancestral Protector Totem grants 12% increased Attack Speed while Active", }, ["ENDGAME"] = { "Ancestral Protector Totem deals 40% increased Damage", "18% increased Ancestral Protector Totem Placement Speed", "+36% to Ancestral Protector Totem Elemental Resistances", "Ancestral Protector Totem grants 18% increased Attack Speed while Active", }, }, ["Ancestral Warchief"] = { ["MERCILESS"] = { "25% increased Ancestral Warchief Totem Damage", "16% increased Ancestral Warchief Totem Area of Effect", "Ancestral Warchief Totem grants 20% increased Melee Damage while Active", }, ["ENDGAME"] = { "40% increased Ancestral Warchief Totem Damage", "24% increased Ancestral Warchief Totem Area of Effect", "Ancestral Warchief Totem grants 30% increased Melee Damage while Active", }, }, ["Anger"] = { ["MERCILESS"] = { "Anger has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Anger has 15% reduced Mana Reservation", }, }, ["Animate Guardian"] = { ["MERCILESS"] = { "Animated Guardians deal 25% increased Damage", "+24% to Animated Guardian Elemental Resistances", }, ["ENDGAME"] = { "Animated Guardians deal 40% increased Damage", "+36% to Animated Guardian Elemental Resistances", }, }, ["Animate Weapon"] = { ["MERCILESS"] = { "Animated Weapons deal 25% increased Damage", "20% increased Animate Weapon Duration", "16% chance to create an additional Animate Weapon copy", }, ["ENDGAME"] = { "Animated Weapons deal 40% increased Damage", "30% increased Animate Weapon Duration", "24% chance to create an additional Animate Weapon copy", }, }, ["Arc"] = { ["MERCILESS"] = { "25% increased Arc Damage", "Arc has +20% chance to Shock", "Arc deals 8% increased Damage for each time it has Chained", }, ["ENDGAME"] = { "40% increased Arc Damage", "Arc Chains an additional time", "Arc has +30% chance to Shock", "Arc deals 12% increased Damage for each time it has Chained", }, }, ["Arcane Cloak"] = { ["MERCILESS"] = { "Arcane Cloak Spends an additional 10% of current Mana", }, ["ENDGAME"] = { "Arcane Cloak Spends an additional 15% of current Mana", "Arcane Cloak grants Life Regeneration equal to 15% of Mana Spent per Second", }, }, ["Arcanist Brand"] = { ["MERCILESS"] = { "Arcanist Brand has 8% increased Cast Speed", }, ["ENDGAME"] = { "Arcanist Brand has 12% increased Cast Speed", "Spells Triggered by Arcanist Brand Unnerve enemies on Hit for 4 seconds", }, }, ["Arctic Armour"] = { ["MERCILESS"] = { "24% increased Arctic Armour Buff Effect", "Arctic Armour has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "36% increased Arctic Armour Buff Effect", "Arctic Armour has 30% reduced Mana Reservation", }, }, ["Armageddon Brand"] = { ["MERCILESS"] = { "Armageddon Brand deals 25% increased Damage", "Armageddon Brand has 8% increased Activation Frequency", "Armageddon Brand Damage Penetrates 8% of Branded Enemy's Fire Resistance", }, ["ENDGAME"] = { "Armageddon Brand deals 40% increased Damage", "Armageddon Brand has 12% increased Activation Frequency", "Armageddon Brand Damage Penetrates 12% of Branded Enemy's Fire Resistance", }, }, ["Artillery Ballista"] = { ["MERCILESS"] = { "Artillery Ballista Damage Penetrates 6% Fire Resistance", "Artillery Ballista fires an additional Arrow", }, ["ENDGAME"] = { "Artillery Ballista Damage Penetrates 10% Fire Resistance", "Artillery Ballista fires 2 additional Arrows", "Artillery Ballista Projectiles fall in two perpendicular lines instead", }, }, ["Assassin's Mark"] = { ["MERCILESS"] = { "20% increased Assassin's Mark Curse Effect", "30% increased Assassin's Mark Duration", }, ["ENDGAME"] = { "30% increased Assassin's Mark Curse Effect", "45% increased Assassin's Mark Duration", }, }, ["Ball Lightning"] = { ["MERCILESS"] = { "25% increased Ball Lightning Damage", "16% increased Ball Lightning Area of Effect", }, ["ENDGAME"] = { "40% increased Ball Lightning Damage", "24% increased Ball Lightning Area of Effect", "Ball Lightning fires an additional Projectile", }, }, ["Bane"] = { ["MERCILESS"] = { "Bane deals 25% increased Damage", "Bane has 16% increased Area of Effect", "10% increased Effect of Curses applied by Bane", }, ["ENDGAME"] = { "Bane deals 40% increased Damage", "Bane has 24% increased Area of Effect", "15% increased Effect of Curses applied by Bane", }, }, ["Barrage"] = { ["MERCILESS"] = { "25% increased Barrage Damage", "10% increased Barrage Attack Speed", }, ["ENDGAME"] = { "40% increased Barrage Damage", "15% increased Barrage Attack Speed", "Barrage fires an additional Projectile", }, }, ["Bear Trap"] = { ["MERCILESS"] = { "25% increased Bear Trap Damage", "Bear Trap has 10% increased Cooldown Recovery Rate", "Enemies affected by Bear Trap take 5% increased Damage from Trap or Mine Hits", }, ["ENDGAME"] = { "40% increased Bear Trap Damage", "Bear Trap has 15% increased Cooldown Recovery Rate", "Enemies affected by Bear Trap take 10% increased Damage from Trap or Mine Hits", }, }, ["Berserk"] = { ["MERCILESS"] = { "Berserk has 25% reduced Rage loss per second", "Berserk has 20% increased Buff Effect", }, ["ENDGAME"] = { "Berserk has 40% reduced Rage loss per second", "Berserk has 30% increased Buff Effect", }, }, ["Blade Blast"] = { ["MERCILESS"] = { "Blade Blast has 16% increased Area of Effect", "Blade Blast detonates other Lingering Blades within an 50% increased Area", "Blade Blast deals 25% increased Damage", }, ["ENDGAME"] = { "Blade Blast has 24% increased Area of Effect", "Blade Blast detonates other Lingering Blades within an 75% increased Area", "Blade Blast deals 40% increased Damage", }, }, ["Blade Flurry"] = { ["MERCILESS"] = { "25% increased Blade Flurry Damage", "16% increased Blade Flurry Area of Effect", "6% chance to Dodge Attack Hits while at maximum Blade Flurry stages", }, ["ENDGAME"] = { "40% increased Blade Flurry Damage", "24% increased Blade Flurry Area of Effect", "9% chance to Dodge Attack Hits while at maximum Blade Flurry stages", }, }, ["Blade Vortex"] = { ["MERCILESS"] = { "25% increased Blade Vortex Spell Damage", "20% increased Blade Vortex Duration", "16% increased Blade Vortex Area of Effect", "Blade Vortex has +2% to Critical Strike Multiplier for each blade", }, ["ENDGAME"] = { "40% increased Blade Vortex Spell Damage", "30% increased Blade Vortex Duration", "24% increased Blade Vortex Area of Effect", "Blade Vortex has +3% to Critical Strike Multiplier for each blade", }, }, ["Bladefall"] = { ["MERCILESS"] = { "25% increased Bladefall Damage", "60% increased Bladefall Critical Strike Chance", "16% increased Bladefall Area of Effect", }, ["ENDGAME"] = { "40% increased Bladefall Damage", "90% increased Bladefall Critical Strike Chance", "24% increased Bladefall Area of Effect", "Bladefall has an additional Volley", }, }, ["Bladestorm"] = { ["MERCILESS"] = { "Sand Bladestorms move with 50% increased speed", "Bladestorm deals 25% increased Damage", }, ["ENDGAME"] = { "+1 to maximum number of Bladestorms", "Sand Bladestorms move with 75% increased speed", "Bladestorm deals 40% increased Damage", }, }, ["Blast Rain"] = { ["MERCILESS"] = { "Blast Rain deals 25% increased Damage", "Blast Rain has 16% increased Area of Effect", }, ["ENDGAME"] = { "Blast Rain deals 40% increased Damage", "Blast Rain has 24% increased Area of Effect", "Blast Rain fires an additional Arrow", }, }, ["Blazing Salvo"] = { ["MERCILESS"] = { "Blazing Salvo deals 25% increased Damage", "Blazing Salvo Projectiles land in a 20% increased Area", }, ["ENDGAME"] = { "Blazing Salvo deals 40% increased Damage", "Blazing Salvo fires an additional Projectile", "Blazing Salvo Projectiles land in a 30% increased Area", }, }, ["Blight"] = { ["MERCILESS"] = { "25% increased Blight Damage", "16% increased Blight Area of Effect", "Blight has 20% increased Hinder Duration", }, ["ENDGAME"] = { "40% increased Blight Damage", "24% increased Blight Area of Effect", "Blight has 30% increased Hinder Duration", }, }, ["Blink Arrow"] = { ["MERCILESS"] = { "Blink Arrow and Blink Arrow Clones have 25% increased Damage", "Blink Arrow and Blink Arrow Clones have 10% increased Attack Speed", "Blink Arrow has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Blink Arrow and Blink Arrow Clones have 40% increased Damage", "Blink Arrow and Blink Arrow Clones have 15% increased Attack Speed", "Blink Arrow has 30% increased Cooldown Recovery Rate", }, }, ["Blood Rage"] = { ["MERCILESS"] = { "Blood Rage grants additional 8% increased Attack Speed", "Blood Rage grants additional 20% chance to gain a Frenzy Charge on Kill", }, ["ENDGAME"] = { "Blood Rage grants additional 12% increased Attack Speed", "Blood Rage grants additional 30% chance to gain a Frenzy Charge on Kill", }, }, ["Blood and Sand"] = { ["MERCILESS"] = { "Blood and Sand has 25% increased Buff Effect", }, ["ENDGAME"] = { "Blood and Sand has 40% increased Buff Effect", }, }, ["Bodyswap"] = { ["MERCILESS"] = { "25% increased Bodyswap Damage", "8% increased Bodyswap Cast Speed", }, ["ENDGAME"] = { "40% increased Bodyswap Damage", "12% increased Bodyswap Cast Speed", }, }, ["Bone Offering"] = { ["MERCILESS"] = { "30% increased Bone Offering Duration", "Bone Offering grants an additional +6% Chance to Block Attack Damage", }, ["ENDGAME"] = { "45% increased Bone Offering Duration", "Bone Offering grants an additional +9% Chance to Block Attack Damage", }, }, ["Burning Arrow"] = { ["MERCILESS"] = { "25% increased Burning Arrow Damage", "Burning Arrow has +20% chance to Ignite", "10% of Burning Arrow Physical Damage gained as Extra Fire Damage", "Burning Arrow has 16% increased Debuff Effect", }, ["ENDGAME"] = { "40% increased Burning Arrow Damage", "Burning Arrow has +30% chance to Ignite", "15% of Burning Arrow Physical Damage gained as Extra Fire Damage", "Burning Arrow has 24% increased Debuff Effect", }, }, ["Caustic Arrow"] = { ["MERCILESS"] = { "25% increased Caustic Arrow Damage", "20% increased Caustic Arrow Duration", "16% increased Caustic Arrow Area of Effect", "Caustic Arrow has 14% chance to inflict Withered on Hit for 2 seconds base Duration", }, ["ENDGAME"] = { "40% increased Caustic Arrow Damage", "30% increased Caustic Arrow Duration", "24% increased Caustic Arrow Area of Effect", "Caustic Arrow has 20% chance to inflict Withered on Hit for 2 seconds base Duration", }, }, ["Chain Hook"] = { ["MERCILESS"] = { "Chain Hook has a 25% chance to grant +1 Rage if it Hits Enemies", "Chain Hook deals 25% increased Damage", }, ["ENDGAME"] = { "Chain Hook has a 40% chance to grant +1 Rage if it Hits Enemies", "Chain Hook has +1 Radius per 12 Rage", "Chain Hook deals 40% increased Damage", }, }, ["Charged Dash"] = { ["MERCILESS"] = { "25% increased Charged Dash Damage", "4% chance to Dodge Attack Hits if you have finished Channelling Charged Dash Recently", "Charged Dash has +4 to Radius of each Wave's last damage Area", "Charged Dash has 10% more Movement Speed", }, ["ENDGAME"] = { "40% increased Charged Dash Damage", "6% chance to Dodge Attack Hits if you have finished Channelling Charged Dash Recently", "Charged Dash has +6 to Radius of each Wave's last damage Area", "Charged Dash has 15% more Movement Speed", }, }, ["Clarity"] = { ["MERCILESS"] = { "Clarity has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "Clarity has 30% reduced Mana Reservation", }, }, ["Cleave"] = { ["MERCILESS"] = { "25% increased Cleave Damage", "10% increased Cleave Attack Speed", "16% increased Cleave Area of Effect", }, ["ENDGAME"] = { "40% increased Cleave Damage", "15% increased Cleave Attack Speed", "24% increased Cleave Area of Effect", }, }, ["Cobra Lash"] = { ["MERCILESS"] = { "Cobra Lash deals 25% increased Damage", "Cobra Lash has 20% increased Projectile Speed", "Cobra Lash Chains 2 additional times", }, ["ENDGAME"] = { "Cobra Lash deals 40% increased Damage", "Cobra Lash has 30% increased Projectile Speed", "Cobra Lash Chains 3 additional times", }, }, ["Cold Snap"] = { ["MERCILESS"] = { "25% increased Cold Snap Damage", "Cold Snap has 20% increased Cooldown Recovery Rate", "16% increased Cold Snap Area of Effect", }, ["ENDGAME"] = { "40% increased Cold Snap Damage", "Cold Snap has 30% increased Cooldown Recovery Rate", "24% increased Cold Snap Area of Effect", }, }, ["Combust"] = { ["ENDGAME"] = { "Combust has 30% increased Area of Effect", }, }, ["Conductivity"] = { ["MERCILESS"] = { "20% increased Conductivity Curse Effect", "30% increased Conductivity Duration", }, ["ENDGAME"] = { "30% increased Conductivity Curse Effect", "45% increased Conductivity Duration", }, }, ["Consecrated Path"] = { ["MERCILESS"] = { "Consecrated Path deals 25% increased Damage", "Consecrated Path has 10% increased teleport range", "Consecrated Path has 16% increased Area of Effect", }, ["ENDGAME"] = { "Consecrated Path deals 40% increased Damage", "Consecrated Path has 15% increased teleport range", "Consecrated Path has 24% increased Area of Effect", }, }, ["Contagion"] = { ["MERCILESS"] = { "25% increased Contagion Damage", "20% increased Contagion Duration", "16% increased Contagion Area of Effect", }, ["ENDGAME"] = { "40% increased Contagion Damage", "30% increased Contagion Duration", "24% increased Contagion Area of Effect", }, }, ["Conversion Trap"] = { ["MERCILESS"] = { "Converted Enemies have 25% increased Damage", "Conversion Trap 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Converted Enemies have 40% increased Damage", "Conversion Trap 30% increased Cooldown Recovery Rate", }, }, ["Convocation"] = { ["MERCILESS"] = { "Convocation has 20% increased Cooldown Recovery Rate", "24% increased Convocation Buff Effect", }, ["ENDGAME"] = { "Convocation has 30% increased Cooldown Recovery Rate", "36% increased Convocation Buff Effect", }, }, ["Crackling Lance"] = { ["MERCILESS"] = { "Crackling Lance deals 25% increased Damage", "Crackling Lance has 8% increased Cast Speed", "Crackling Lance has 24% increased branching angle", }, ["ENDGAME"] = { "Crackling Lance deals 40% increased Damage", "Crackling Lance has 16% increased Cast Speed", "Crackling Lance has 18% increased branching angle", }, }, ["Creeping Frost"] = { ["MERCILESS"] = { "25% increased Creeping Frost Damage", "24% increased Creeping Frost Duration", "16% increased Creeping Frost Area of Effect", }, ["ENDGAME"] = { "40% increased Creeping Frost Damage", "36% increased Creeping Frost Duration", "24% increased Creeping Frost Area of Effect", "Creeping Frost's Chilling Area has 38% increased Movement Speed", }, }, ["Cremation"] = { ["MERCILESS"] = { "25% increased Cremation Damage", "8% increased Cremation Cast Speed", }, ["ENDGAME"] = { "Cremation can have up to 1 additional Geyser at a time", "40% increased Cremation Damage", "12% increased Cremation Cast Speed", }, }, ["Cyclone"] = { ["MERCILESS"] = { "25% increased Cyclone Damage", "10% increased Cyclone Attack Speed", }, ["ENDGAME"] = { "40% increased Cyclone Damage", "15% increased Cyclone Attack Speed", }, }, ["Dark Pact"] = { ["MERCILESS"] = { "25% increased Dark Pact Damage", "8% increased Dark Pact Cast Speed", "16% increased Dark Pact Area of Effect", }, ["ENDGAME"] = { "40% increased Dark Pact Damage", "12% increased Dark Pact Cast Speed", "24% increased Dark Pact Area of Effect", }, }, ["Dash"] = { ["MERCILESS"] = { "Dash travels 65% increased distance", "Dash has +1 Cooldown Use", }, ["ENDGAME"] = { "Dash travels 100% increased distance", "Dash has +2 Cooldown Uses", }, }, ["Decoy Totem"] = { ["MERCILESS"] = { "40% increased Decoy Totem Life", "16% increased Decoy Totem Area of Effect", }, ["ENDGAME"] = { "60% increased Decoy Totem Life", "24% increased Decoy Totem Area of Effect", }, }, ["Desecrate"] = { ["MERCILESS"] = { "Desecrate Spawns 2 additional corpses", }, ["ENDGAME"] = { "Desecrate Spawns 3 additional corpses", }, }, ["Despair"] = { ["MERCILESS"] = { "30% increased Despair Duration", "20% increased Despair Curse Effect", }, ["ENDGAME"] = { "45% increased Despair Duration", "30% increased Despair Curse Effect", }, }, ["Determination"] = { ["MERCILESS"] = { "Determination has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Determination has 15% reduced Mana Reservation", }, }, ["Detonate Dead"] = { ["MERCILESS"] = { "25% increased Detonate Dead Damage", "Detonate Dead has a 30% chance to detonate an additional corpse", "16% increased Detonate Dead Area of Effect", }, ["ENDGAME"] = { "40% increased Detonate Dead Damage", "Detonate Dead has a 45% chance to detonate an additional corpse", "24% increased Detonate Dead Area of Effect", }, }, ["Devouring Totem"] = { ["MERCILESS"] = { "Devouring Totem has 40% Chance to Consume an additional corpse", "24% increased Devouring Totem Leech per second", }, ["ENDGAME"] = { "Devouring Totem has 60% Chance to Consume an additional corpse", "36% increased Devouring Totem Leech per second", }, }, ["Discharge"] = { ["MERCILESS"] = { "20% chance for Discharge to deal Damage without removing Charges", "Discharge has +3 to Radius", "25% increased Discharge Damage", }, ["ENDGAME"] = { "30% chance for Discharge to deal Damage without removing Charges", "Discharge has +5 to Radius", "40% increased Discharge Damage", }, }, ["Discipline"] = { ["MERCILESS"] = { "Discipline has 14% reduced Mana Reservation", }, ["ENDGAME"] = { "Discipline has 20% reduced Mana Reservation", }, }, ["Divine Ire"] = { ["MERCILESS"] = { "Divine Ire deals 25% increased Damage", "Divine Ire's beam has 10% increased width", "Divine Ire Damages an additional nearby Enemy when gaining Stages", }, ["ENDGAME"] = { "Divine Ire deals 40% increased Damage", "Divine Ire's beam has 15% increased width", "Divine Ire Damages 2 additional nearby Enemies when gaining Stages", }, }, ["Dominating Blow"] = { ["MERCILESS"] = { "20% increased Sentinel of Dominance Duration", "Dominating Blow can summon 2 additional Magic Sentinels of Dominance", }, ["ENDGAME"] = { "30% increased Sentinel of Dominance Duration", "Dominating Blow can summon 3 additional Magic Sentinels of Dominance", "Dominating Blow can summon an additional Rare Sentinel of Dominance", }, }, ["Double Strike"] = { ["MERCILESS"] = { "25% increased Double Strike Damage", "10% increased Double Strike Attack Speed", "60% increased Double Strike Critical Strike Chance", "Double Strike has a 10% chance to deal Double Damage to Bleeding Enemies", }, ["ENDGAME"] = { "40% increased Double Strike Damage", "15% increased Double Strike Attack Speed", "90% increased Double Strike Critical Strike Chance", "Double Strike has a 15% chance to deal Double Damage to Bleeding Enemies", }, }, ["Dread Banner"] = { ["MERCILESS"] = { "Dread Banner has 25% increased Aura Effect", }, ["ENDGAME"] = { "Dread Banner has 40% increased Aura Effect", }, }, ["Dual Strike"] = { ["MERCILESS"] = { "25% increased Dual Strike Damage", "10% increased Dual Strike Attack Speed", "60% increased Dual Strike Critical Strike Chance", }, ["ENDGAME"] = { "40% increased Dual Strike Damage", "15% increased Dual Strike Attack Speed", "90% increased Dual Strike Critical Strike Chance", }, }, ["Earthquake"] = { ["MERCILESS"] = { "25% increased Earthquake Damage", "16% increased Earthquake Area of Effect", "Earthquake deals 5% increased Damage per 0.1 seconds Duration", }, ["ENDGAME"] = { "40% increased Earthquake Damage", "24% increased Earthquake Area of Effect", "Earthquake deals 8% increased Damage per 0.1 seconds Duration", }, }, ["Earthshatter"] = { ["MERCILESS"] = { "Earthshatter deals 25% increased Damage", "Earthshatter has 16% increased Area of Effect", }, ["ENDGAME"] = { "Earthshatter deals 40% increased Damage", "Earthshatter has 24% increased Area of Effect", "Earthshatter creates +1 fissures", }, }, ["Elemental Hit"] = { ["MERCILESS"] = { "Elemental Hit deals 25% increased Damage", "10% increased Elemental Hit Attack Speed", "Elemental Hit has +20% chance to Freeze, Shock and Ignite", }, ["ENDGAME"] = { "Elemental Hit deals 40% increased Damage", "15% increased Elemental Hit Attack Speed", "Elemental Hit has +30% chance to Freeze, Shock and Ignite", }, }, ["Elemental Weakness"] = { ["MERCILESS"] = { "20% increased Elemental Weakness Curse Effect", "30% increased Elemental Weakness Duration", }, ["ENDGAME"] = { "30% increased Elemental Weakness Curse Effect", "45% increased Elemental Weakness Duration", }, }, ["Enduring Cry"] = { ["MERCILESS"] = { "Enduring Cry has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Enduring Cry has 30% increased Cooldown Recovery Rate", "Enduring Cry grants 1 additional Endurance Charge", }, }, ["Enfeeble"] = { ["MERCILESS"] = { "20% increased Enfeeble Curse Effect", "30% increased Enfeeble Duration", }, ["ENDGAME"] = { "30% increased Enfeeble Curse Effect", "45% increased Enfeeble Duration", }, }, ["Ensnaring Arrow"] = { ["MERCILESS"] = { "Ensnaring Arrow has 20% increased Debuff Effect", "Ensnaring Arrow has 60% increased Area of Effect", }, ["ENDGAME"] = { "Ensnaring Arrow has 30% increased Debuff Effect", "Ensnaring Arrow has 90% increased Area of Effect", }, }, ["Essence Drain"] = { ["MERCILESS"] = { "25% increased Essence Drain Damage", "20% increased Essence Drain Duration", }, ["ENDGAME"] = { "40% increased Essence Drain Damage", "30% increased Essence Drain Duration", }, }, ["Ethereal Knives"] = { ["MERCILESS"] = { "25% increased Ethereal Knives Damage", "20% increased Ethereal Knives Projectile Speed", }, ["ENDGAME"] = { "40% increased Ethereal Knives Damage", "30% increased Ethereal Knives Projectile Speed", "Ethereal Knives Pierces an additional Target ", }, }, ["Explosive Arrow"] = { ["MERCILESS"] = { "Explosive Arrow deals 25% increased Damage", "Explosive Arrow has 16% increased Area of Effect", "Explosive Arrow has 10% increased Attack Speed", "Explosive Arrow has 25% increased Duration", "Explosive Arrow has 20% reduced Duration", }, ["ENDGAME"] = { "Explosive Arrow deals 40% increased Damage", "Explosive Arrow has 24% increased Area of Effect", "Explosive Arrow has 15% increased Attack Speed", "Explosive Arrow has 40% increased Duration", "Explosive Arrow has 30% reduced Duration", }, }, ["Explosive Trap"] = { ["MERCILESS"] = { "Explosive Trap deals 25% increased Damage", "Explosive Trap has 16% increased Area of Effect", "Explosive Trap causes an additional smaller explosion", }, ["ENDGAME"] = { "Explosive Trap deals 40% increased Damage", "Explosive Trap has 24% increased Area of Effect", "Explosive Trap causes 2 additional smaller explosions", }, }, ["Fire Trap"] = { ["MERCILESS"] = { "25% increased Fire Trap Damage", "40% increased Fire Trap Burning Damage", "30% increased Fire Trap Burning Ground Duration", }, ["ENDGAME"] = { "40% increased Fire Trap Damage", "60% increased Fire Trap Burning Damage", "45% increased Fire Trap Burning Ground Duration", }, }, ["Fireball"] = { ["MERCILESS"] = { "25% increased Fireball Damage", "8% increased Fireball Cast Speed", "Fireball has +20% chance to Ignite", }, ["ENDGAME"] = { "40% increased Fireball Damage", "12% increased Fireball Cast Speed", "Fireball has +30% chance to Ignite", }, }, ["Firestorm"] = { ["MERCILESS"] = { "25% increased Firestorm Damage", "20% increased Firestorm Duration", "16% increased Firestorm explosion Area of Effect", }, ["ENDGAME"] = { "40% increased Firestorm Damage", "30% increased Firestorm Duration", "24% increased Firestorm explosion Area of Effect", }, }, ["Flame Dash"] = { ["MERCILESS"] = { "25% increased Flame Dash Damage", "Flame Dash has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "40% increased Flame Dash Damage", "Flame Dash has 30% increased Cooldown Recovery Rate", }, }, ["Flame Surge"] = { ["MERCILESS"] = { "25% increased Flame Surge Damage", "60% increased Flame Surge Critical Strike Chance", "40% increased Flame Surge Damage against Burning Enemies", }, ["ENDGAME"] = { "40% increased Flame Surge Damage", "90% increased Flame Surge Critical Strike Chance", "60% increased Flame Surge Damage against Burning Enemies", }, }, ["Flame Wall"] = { ["MERCILESS"] = { "Flame Wall deals 25% increased Damage", "Flame Wall grants 19 to 28 Added Fire Damage to Projectiles", }, ["ENDGAME"] = { "Flame Wall deals 40% increased Damage", "Flame Wall grants 31 to 47 Added Fire Damage to Projectiles", }, }, ["Flameblast"] = { ["MERCILESS"] = { "25% increased Flameblast Damage", "60% increased Flameblast Critical Strike Chance", "16% increased Flameblast Area of Effect", }, ["ENDGAME"] = { "40% increased Flameblast Damage", "90% increased Flameblast Critical Strike Chance", "24% increased Flameblast Area of Effect", }, }, ["Flamethrower Trap"] = { ["MERCILESS"] = { "Flamethrower Trap deals 25% increased Damage", "Flamethrower Trap has 8% increased Cast Speed", "Flamethrower Trap has 10% increased Cooldown Recovery Rate", "Flamethrower Trap has 20% increased Skill Effect Duration", "Flamethrower Trap has an additional Flame", }, ["ENDGAME"] = { "Flamethrower Trap deals 40% increased Damage", "Flamethrower Trap has 12% increased Cast Speed", "Flamethrower Trap has 15% increased Cooldown Recovery Rate", "Flamethrower Trap has 30% increased Skill Effect Duration", "Flamethrower Trap has 2 additional Flames", }, }, ["Flammability"] = { ["MERCILESS"] = { "20% increased Flammability Curse Effect", "30% increased Flammability Duration", }, ["ENDGAME"] = { "30% increased Flammability Curse Effect", "45% increased Flammability Duration", }, }, ["Flesh Offering"] = { ["MERCILESS"] = { "30% increased Flesh Offering Duration", "Flesh Offering grants an additional 14% increased Attack Speed", }, ["ENDGAME"] = { "45% increased Flesh Offering Duration", "Flesh Offering grants an additional 21% increased Attack Speed", }, }, ["Flesh and Stone"] = { ["MERCILESS"] = { "Flesh and Stone has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "Flesh and Stone has 30% reduced Mana Reservation", }, }, ["Flicker Strike"] = { ["MERCILESS"] = { "25% increased Flicker Strike Damage", "Flicker Strike has 20% increased Cooldown Recovery Rate", "6% increased Flicker Strike Damage per Frenzy Charge", }, ["ENDGAME"] = { "40% increased Flicker Strike Damage", "Flicker Strike has 30% increased Cooldown Recovery Rate", "9% increased Flicker Strike Damage per Frenzy Charge", }, }, ["Freezing Pulse"] = { ["MERCILESS"] = { "25% increased Freezing Pulse Damage", "8% increased Freezing Pulse Cast Speed", "20% increased Freezing Pulse Projectile Speed", }, ["ENDGAME"] = { "40% increased Freezing Pulse Damage", "12% increased Freezing Pulse Cast Speed", "30% increased Freezing Pulse Projectile Speed", }, }, ["Frenzy"] = { ["MERCILESS"] = { "25% increased Frenzy Damage", "20% Chance on Frenzy to gain an additional Frenzy Charge", "6% increased Frenzy Damage per Frenzy Charge", }, ["ENDGAME"] = { "40% increased Frenzy Damage", "30% Chance on Frenzy to gain an additional Frenzy Charge", "9% increased Frenzy Damage per Frenzy Charge", }, }, ["Frost Blades"] = { ["MERCILESS"] = { "25% increased Frost Blades Damage", "20% increased Frost Blades Projectile Speed", }, ["ENDGAME"] = { "40% increased Frost Blades Damage", "30% increased Frost Blades Projectile Speed", }, }, ["Frost Bomb"] = { ["MERCILESS"] = { "25% increased Frost Bomb Damage", "Frost Bomb has 20% increased Cooldown Recovery Rate", "16% increased Frost Bomb Area of Effect", "Frost Bomb has 20% increased Debuff Duration", }, ["ENDGAME"] = { "40% increased Frost Bomb Damage", "Frost Bomb has 30% increased Cooldown Recovery Rate", "24% increased Frost Bomb Area of Effect", "Frost Bomb has 30% increased Debuff Duration", }, }, ["Frost Shield"] = { ["ENDGAME"] = { "Frost Shield has +1 Cooldown Use", }, }, ["Frost Wall"] = { ["MERCILESS"] = { "Frost Wall has 20% increased Cooldown Recovery Rate", "24% increased Frost Wall Duration", }, ["ENDGAME"] = { "Frost Wall has 30% increased Cooldown Recovery Rate", "36% increased Frost Wall Duration", }, }, ["Frostbite"] = { ["MERCILESS"] = { "20% increased Frostbite Curse Effect", "30% increased Frostbite Duration", }, ["ENDGAME"] = { "30% increased Frostbite Curse Effect", "45% increased Frostbite Duration", }, }, ["Frostblink"] = { ["MERCILESS"] = { "Frostblink has 20% increased Cooldown Recovery Rate", "Frostblink has 50% increased maximum travel distance", }, ["ENDGAME"] = { "Frostblink has 30% increased Cooldown Recovery Rate", "Frostblink has 75% increased maximum travel distance", }, }, ["Frostbolt"] = { ["MERCILESS"] = { "25% increased Frostbolt Damage", "10% increased Frostbolt Cast Speed", "Frostbolt has +10% chance to Freeze", }, ["ENDGAME"] = { "40% increased Frostbolt Damage", "15% increased Frostbolt Cast Speed", "Frostbolt has +15% chance to Freeze", }, }, ["Galvanic Arrow"] = { ["MERCILESS"] = { "25% increased Galvanic Arrow Damage", "10% of Galvanic Arrow Physical Damage gained as extra Lightning Damage", "Galvanic Arrow has 20% increased Projectile Speed", }, ["ENDGAME"] = { "40% increased Galvanic Arrow Damage", "15% of Galvanic Arrow Physical Damage gained as extra Lightning Damage", "Galvanic Arrow has 30% increased Projectile Speed", }, }, ["General's Cry"] = { ["MERCILESS"] = { "General's Cry has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "General's Cry has 30% increased Cooldown Recovery Rate", "General's Cry has +1 to maximum number of Mirage Warriors", }, }, ["Glacial Cascade"] = { ["MERCILESS"] = { "25% increased Glacial Cascade Damage", "16% increased Glacial Cascade Area of Effect", "Glacial Cascade gains 6% of Physical Damage as Extra Cold Damage", }, ["ENDGAME"] = { "40% increased Glacial Cascade Damage", "24% increased Glacial Cascade Area of Effect", "Glacial Cascade gains 10% of Physical Damage as Extra Cold Damage", }, }, ["Glacial Hammer"] = { ["MERCILESS"] = { "25% increased Glacial Hammer Damage", "Glacial Hammer has +20% chance to Freeze", "10% of Glacial Hammer Physical Damage gained as Extra Cold Damage", }, ["ENDGAME"] = { "40% increased Glacial Hammer Damage", "Glacial Hammer has +30% chance to Freeze", "15% of Glacial Hammer Physical Damage gained as Extra Cold Damage", }, }, ["Grace"] = { ["MERCILESS"] = { "Grace has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Grace has 15% reduced Mana Reservation", }, }, ["Ground Slam"] = { ["MERCILESS"] = { "25% increased Ground Slam Damage", "16% increased Ground Slam Area of Effect", "Ground Slam has a 16% increased angle", }, ["ENDGAME"] = { "40% increased Ground Slam Damage", "24% increased Ground Slam Area of Effect", "Ground Slam has a 24% increased angle", }, }, ["Haste"] = { ["MERCILESS"] = { "Haste has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Haste has 15% reduced Mana Reservation", }, }, ["Hatred"] = { ["MERCILESS"] = { "Hatred has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Hatred has 15% reduced Mana Reservation", }, }, ["Heavy Strike"] = { ["MERCILESS"] = { "25% increased Heavy Strike Damage", "10% increased Heavy Strike Attack Speed", "Heavy Strike has a 8% chance to deal Double Damage", }, ["ENDGAME"] = { "40% increased Heavy Strike Damage", "15% increased Heavy Strike Attack Speed", "Heavy Strike has a 12% chance to deal Double Damage", }, }, ["Herald of Agony"] = { ["MERCILESS"] = { "Herald of Agony has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "Herald of Agony has 30% reduced Mana Reservation", "Summoned Agony Crawler fires 2 additional Projectiles", }, }, ["Herald of Ash"] = { ["MERCILESS"] = { "25% increased Herald of Ash Damage", "Herald of Ash has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "40% increased Herald of Ash Damage", "Herald of Ash has 30% reduced Mana Reservation", }, }, ["Herald of Ice"] = { ["MERCILESS"] = { "25% increased Herald of Ice Damage", "Herald of Ice has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "40% increased Herald of Ice Damage", "Herald of Ice has 30% reduced Mana Reservation", }, }, ["Herald of Purity"] = { ["MERCILESS"] = { "Herald of Purity has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "Herald of Purity has 30% reduced Mana Reservation", "+1 to maximum number of Sentinels of Purity", }, }, ["Herald of Thunder"] = { ["MERCILESS"] = { "25% increased Herald of Thunder Damage", "Herald of Thunder has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "40% increased Herald of Thunder Damage", "Herald of Thunder has 30% reduced Mana Reservation", }, }, ["Hexblast"] = { ["MERCILESS"] = { "Hexblast deals 25% increased Damage", "Hexblast has 16% increased Area of Effect", "Hexblast has 10% chance to not remove a Hex", }, ["ENDGAME"] = { "Hexblast deals 40% increased Damage", "Hexblast has 24% increased Area of Effect", "Hexblast has 15% chance to not remove a Hex", }, }, ["Holy Flame Totem"] = { ["MERCILESS"] = { "Holy Flame Totem deals 25% increased Damage", "Holy Flame Totem fires an additional Projectile", "Holy Flame Totem has 20% increased Projectile Speed", "Consecrated Ground from Holy Flame Totem applies 6% increased Damage taken to Enemies", }, ["ENDGAME"] = { "Holy Flame Totem deals 40% increased Damage", "Holy Flame Totem fires 2 additional Projectiles", "Holy Flame Totem has 30% increased Projectile Speed", "Consecrated Ground from Holy Flame Totem applies 9% increased Damage taken to Enemies", }, }, ["Ice Crash"] = { ["MERCILESS"] = { "25% increased Ice Crash Damage", "10% of Ice Crash Physical Damage gained as Extra Cold Damage", "16% increased Ice Crash Area of Effect", }, ["ENDGAME"] = { "40% increased Ice Crash Damage", "15% of Ice Crash Physical Damage gained as Extra Cold Damage", "24% increased Ice Crash Area of Effect", }, }, ["Ice Nova"] = { ["MERCILESS"] = { "25% increased Ice Nova Damage", "Ice Nova has +20% chance to Freeze", "16% increased Ice Nova Area of Effect", "Chills from Ice Nova Hits always reduce Action Speed by at least 6%", }, ["ENDGAME"] = { "40% increased Ice Nova Damage", "Ice Nova has +30% chance to Freeze", "24% increased Ice Nova Area of Effect", "Chills from Ice Nova Hits always reduce Action Speed by at least 8%", }, }, ["Ice Shot"] = { ["MERCILESS"] = { "25% increased Ice Shot Damage", "16% increased Ice Shot Area of Effect", "Ice Shot has 30% increased Area of Effect angle", }, ["ENDGAME"] = { "40% increased Ice Shot Damage", "24% increased Ice Shot Area of Effect", "Ice Shot has 60% increased Area of Effect angle", }, }, ["Ice Spear"] = { ["MERCILESS"] = { "10% Chance to gain a Power Charge on Critical Strike with Ice Spear", "200% increased Ice Spear Critical Strike Chance in second form", "Ice Spear travels 20% reduced distance before changing forms", }, ["ENDGAME"] = { "15% Chance to gain a Power Charge on Critical Strike with Ice Spear", "300% increased Ice Spear Critical Strike Chance in second form", "Ice Spear fires an additional Projectile", "Ice Spear travels 30% reduced distance before changing forms", }, }, ["Ice Trap"] = { ["MERCILESS"] = { "25% increased Ice Trap Damage", "16% increased Ice Trap Area of Effect", "Ice Trap Damage Penetrates 6% Cold Resistance", }, ["ENDGAME"] = { "40% increased Ice Trap Damage", "24% increased Ice Trap Area of Effect", "Ice Trap Damage Penetrates 10% Cold Resistance", }, }, ["Icicle Mine"] = { ["MERCILESS"] = { "Icicle Mine deals 25% increased Damage", "Icicle Mine has 10% increased Throwing Speed", "Icicle Mine has +20% to Critical Strike Multiplier", }, ["ENDGAME"] = { "Icicle Mine deals 40% increased Damage", "Icicle Mine has 15% increased Throwing Speed", "Icicle Mine has +30% to Critical Strike Multiplier", }, }, ["Immortal Call"] = { ["MERCILESS"] = { "34% increased Immortal Call Duration", }, ["ENDGAME"] = { "36% increased Immortal Call Duration", }, }, ["Incinerate"] = { ["MERCILESS"] = { "25% increased Incinerate Damage", "Incinerate has 16% increased Area of Effect", "Incinerate has +1 to maximum stages", }, ["ENDGAME"] = { "40% increased Incinerate Damage", "Incinerate has 24% increased Area of Effect", "Incinerate has +2 to maximum stages", "10% increased Incinerate Damage for each stage", }, }, ["Infernal Blow"] = { ["MERCILESS"] = { "25% increased Infernal Blow Damage", "10% of Infernal Blow Physical Damage gained as Extra Fire Damage", "16% increased Infernal Blow Area of Effect", "Infernal Blow Debuff deals an additional 3% of Damage per Charge", }, ["ENDGAME"] = { "40% increased Infernal Blow Damage", "15% of Infernal Blow Physical Damage gained as Extra Fire Damage", "24% increased Infernal Blow Area of Effect", "Infernal Blow Debuff deals an additional 5% of Damage per Charge", }, }, ["Infernal Cry"] = { ["MERCILESS"] = { "Infernal Cry has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Infernal Cry has 30% increased Cooldown Recovery Rate", }, }, ["Intimidating Cry"] = { ["MERCILESS"] = { "Intimidating Cry has 20% increased Cooldown Recovery Rate", "Intimidating Cry has 16% increased Area of Effect", }, ["ENDGAME"] = { "Intimidating Cry has 30% increased Cooldown Recovery Rate", "Intimidating Cry has 24% increased Area of Effect", }, }, ["Kinetic Blast"] = { ["MERCILESS"] = { "25% increased Kinetic Blast Damage", "16% increased Kinetic Blast Area of Effect", "Kinetic Blast has a 50% chance for an additional explosion", }, ["ENDGAME"] = { "40% increased Kinetic Blast Damage", "24% increased Kinetic Blast Area of Effect", "Kinetic Blast has a 75% chance for an additional explosion", }, }, ["Kinetic Bolt"] = { ["MERCILESS"] = { "Kinetic Bolt has 10% increased Attack Speed", "Kinetic Bolt has 20% increased Projectile Speed", "Kinetic Bolt changes direction 1 additional time", }, ["ENDGAME"] = { "Kinetic Bolt has 15% increased Attack Speed", "Kinetic Bolt has 30% increased Projectile Speed", "Kinetic Bolt changes direction 2 additional times", }, }, ["Lacerate"] = { ["MERCILESS"] = { "25% increased Lacerate Damage", "40% increased Lacerate Critical Strike Chance", "16% increased Lacerate Area of Effect", "Lacerate deals (4-8) to (10-15) added Physical Damage against Bleeding Enemies", }, ["ENDGAME"] = { "40% increased Lacerate Damage", "60% increased Lacerate Critical Strike Chance", "24% increased Lacerate Area of Effect", "Lacerate deals (14-18) to (20-25) added Physical Damage against Bleeding Enemies", }, }, ["Lancing Steel"] = { ["MERCILESS"] = { "Lancing Steel deals 25% increased Damage", "Lancing Steel has 20% chance count as consumeing Steel Shards without Consuming them", }, ["ENDGAME"] = { "Lancing Steel deals 40% increased Damage", "Lancing Steel has 30% chance count as consumeing Steel Shards without Consuming them", "Lancing Steel fires an additional Projectile", }, }, ["Leap Slam"] = { ["MERCILESS"] = { "25% increased Leap Slam Damage", "10% increased Leap Slam Attack Speed", "16% increased Leap Slam Area of Effect", }, ["ENDGAME"] = { "40% increased Leap Slam Damage", "15% increased Leap Slam Attack Speed", "24% increased Leap Slam Area of Effect", }, }, ["Lightning Arrow"] = { ["MERCILESS"] = { "25% increased Lightning Arrow Damage", "16% increased Lightning Arrow Area of Effect", "Lightning Arrow hits an additional Enemy", }, ["ENDGAME"] = { "40% increased Lightning Arrow Damage", "24% increased Lightning Arrow Area of Effect", "Lightning Arrow hits 2 additional Enemies", }, }, ["Lightning Spire Trap"] = { ["MERCILESS"] = { "Lightning Spire Trap deals 25% increased Damage", "Lightning Spire Trap has 8% increased Cast Speed", "Lightning Spire Trap has 20% increased Skill Effect Duration", "Lightning Spire Trap has 10% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Lightning Spire Trap deals 40% increased Damage", "Lightning Spire Trap has 12% increased Cast Speed", "Lightning Spire Trap has 30% increased Skill Effect Duration", "Lightning Spire Trap has 15% increased Cooldown Recovery Rate", "Lightning Spire Trap strikes an additional area", }, }, ["Lightning Strike"] = { ["MERCILESS"] = { "25% increased Lightning Strike Damage", "Lightning Strike fires 2 additional Projectiles", "Lightning Strike pierces 2 additional Targets", }, ["ENDGAME"] = { "40% increased Lightning Strike Damage", "Lightning Strike fires 3 additional Projectiles", "Lightning Strike pierces 3 additional Targets", }, }, ["Lightning Tendrils"] = { ["MERCILESS"] = { "25% increased Lightning Tendrils Damage", "16% increased Lightning Tendrils Area of Effect", "40% increased Lightning Tendrils Critical Strike Chance", }, ["ENDGAME"] = { "40% increased Lightning Tendrils Damage", "24% increased Lightning Tendrils Area of Effect", "60% increased Lightning Tendrils Critical Strike Chance", }, }, ["Lightning Trap"] = { ["MERCILESS"] = { "25% increased Lightning Trap Damage", "Lightning Trap pierces 2 additional Targets", "Lightning Trap Damage Penetrates 6% Lightning Resistance", "25% increased Lightning Trap Lightning Ailment Effect", }, ["ENDGAME"] = { "40% increased Lightning Trap Damage", "Lightning Trap pierces 3 additional Targets", "Lightning Trap Damage Penetrates 10% Lightning Resistance", "40% increased Lightning Trap Lightning Ailment Effect", }, }, ["Lightning Warp"] = { ["MERCILESS"] = { "25% increased Lightning Warp Damage", "8% increased Lightning Warp Cast Speed", "20% reduced Lightning Warp Duration", }, ["ENDGAME"] = { "40% increased Lightning Warp Damage", "12% increased Lightning Warp Cast Speed", "30% reduced Lightning Warp Duration", }, }, ["Magma Orb"] = { ["MERCILESS"] = { "25% increased Magma Orb Damage", "16% increased Magma Orb Area of Effect", }, ["ENDGAME"] = { "40% increased Magma Orb Damage", "Magma Orb Chains an additional time", "24% increased Magma Orb Area of Effect", }, }, ["Malevolence"] = { ["MERCILESS"] = { "Malevolence has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Malevolence has 15% reduced Mana Reservation", }, }, ["Mirror Arrow"] = { ["MERCILESS"] = { "Mirror Arrow and Mirror Arrow Clones deal 25% increased Damage", "Mirror Arrow and Mirror Arrow Clones have 10% increased Attack Speed", "Mirror Arrow has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Mirror Arrow and Mirror Arrow Clones deal 40% increased Damage", "Mirror Arrow and Mirror Arrow Clones have 15% increased Attack Speed", "Mirror Arrow has 30% increased Cooldown Recovery Rate", }, }, ["Molten Shell"] = { ["MERCILESS"] = { "Molten Shell has 25% increased Skill Effect Duration", "100% increased Molten Shell Buff Effect", }, ["ENDGAME"] = { "Molten Shell has 40% increased Skill Effect Duration", "150% increased Molten Shell Buff Effect", }, }, ["Molten Strike"] = { ["MERCILESS"] = { "25% increased Molten Strike Damage", "Molten Strike fires an additional Projectile", "16% increased Molten Strike Area of Effect", }, ["ENDGAME"] = { "40% increased Molten Strike Damage", "Molten Strike fires 2 additional Projectiles", "24% increased Molten Strike Area of Effect", }, }, ["Orb of Storms"] = { ["MERCILESS"] = { "25% increased Orb of Storms Damage", "Orb of Storms has 20% increased Cast Speed", "60% increased Orb of Storms Critical Strike Chance", "16% increased Orb of Storms Area of Effect", }, ["ENDGAME"] = { "40% increased Orb of Storms Damage", "Orb of Storms has 30% increased Cast Speed", "90% increased Orb of Storms Critical Strike Chance", "24% increased Orb of Storms Area of Effect", }, }, ["Penance Brand"] = { ["MERCILESS"] = { "Penance Brand deals 25% increased Damage", "Penance Brand has 8% increased Cast Speed", "Penance Brand has 16% increased Area of Effect", }, ["ENDGAME"] = { "Penance Brand deals 40% increased Damage", "Penance Brand has 12% increased Cast Speed", "Penance Brand has 24% increased Area of Effect", }, }, ["Perforate"] = { ["MERCILESS"] = { "Perforate creates +1 Spike", "Perforate has 16% increased Area of Effect", "Perforate deals 25% increased Damage", }, ["ENDGAME"] = { "Perforate creates +2 Spikes", "Perforate has 24% increased Area of Effect", "Perforate deals 40% increased Damage", }, }, ["Pestilent Strike"] = { ["MERCILESS"] = { "Pestilent Strike deals 25% increased Damage", "Pestilent Strike has 25% increased Duration", "Pestilent Strike has 16% increased Area of Effect", }, ["ENDGAME"] = { "Pestilent Strike deals 40% increased Damage", "Pestilent Strike has 40% increased Duration", "Pestilent Strike has 24% increased Area of Effect", }, }, ["Phase Run"] = { ["MERCILESS"] = { "20% chance for Phase Run to increase Duration without removing Frenzy Charges", "24% increased Phase Run Duration", }, ["ENDGAME"] = { "30% chance for Phase Run to increase Duration without removing Frenzy Charges", "36% increased Phase Run Duration", }, }, ["Plague Bearer"] = { ["MERCILESS"] = { "Plague Bearer Buff grants +12% to Poison Damage over Time Multiplier while Infecting", "Plague Bearer deals Damage based on an additional 3% of Plague Value", }, ["ENDGAME"] = { "Plague Bearer Buff grants +20% to Poison Damage over Time Multiplier while Infecting", "Plague Bearer deals Damage based on an additional 5% of Plague Value", }, }, ["Poacher's Mark"] = { ["MERCILESS"] = { "20% increased Poacher's Mark Curse Effect", "30% increased Poacher's Mark Duration", }, ["ENDGAME"] = { "30% increased Poacher's Mark Curse Effect", "45% increased Poacher's Mark Duration", }, }, ["Power Siphon"] = { ["MERCILESS"] = { "25% increased Power Siphon Damage", "30% Chance to gain an additional Power Charge on Kill with Power Siphon", "10% increased Power Siphon Attack Speed", "Power Siphon fires an additional Projectile", }, ["ENDGAME"] = { "40% increased Power Siphon Damage", "45% Chance to gain an additional Power Charge on Kill with Power Siphon", "15% increased Power Siphon Attack Speed", "Power Siphon fires 2 additional Projectiles", }, }, ["Precision"] = { ["MERCILESS"] = { "Precision has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "Precision has 30% reduced Mana Reservation", }, }, ["Pride"] = { ["MERCILESS"] = { "Pride has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Pride has 15% reduced Mana Reservation", }, }, ["Puncture"] = { ["MERCILESS"] = { "25% increased Puncture Damage", "30% increased Puncture Duration", "20% Chance for Puncture to Maim on hit", }, ["ENDGAME"] = { "40% increased Puncture Damage", "45% increased Puncture Duration", "30% Chance for Puncture to Maim on hit", }, }, ["Punishment"] = { ["MERCILESS"] = { "20% increased Punishment Curse Effect", "30% increased Punishment Duration", }, ["ENDGAME"] = { "30% increased Punishment Curse Effect", "45% increased Punishment Duration", }, }, ["Purifying Flame"] = { ["MERCILESS"] = { "Purifying Flame deals 25% increased Damage", "Purifying Flame has 20% increased Area of Effect if targeting Consecrated Ground", "Consecrated Ground from Purifying Flame applies 6% increased Damage taken to Enemies", }, ["ENDGAME"] = { "Purifying Flame deals 40% increased Damage", "Purifying Flame has 30% increased Area of Effect if targeting Consecrated Ground", "Consecrated Ground from Purifying Flame applies 9% increased Damage taken to Enemies", }, }, ["Purity of Elements"] = { ["MERCILESS"] = { "Purity of Elements has 14% reduced Mana Reservation", }, ["ENDGAME"] = { "Purity of Elements has 20% reduced Mana Reservation", }, }, ["Purity of Fire"] = { ["MERCILESS"] = { "Purity of Fire has 14% reduced Mana Reservation", }, ["ENDGAME"] = { "Purity of Fire has 20% reduced Mana Reservation", }, }, ["Purity of Ice"] = { ["MERCILESS"] = { "Purity of Ice has 14% reduced Mana Reservation", }, ["ENDGAME"] = { "Purity of Ice has 20% reduced Mana Reservation", }, }, ["Purity of Lightning"] = { ["MERCILESS"] = { "Purity of Lightning has 14% reduced Mana Reservation", }, ["ENDGAME"] = { "Purity of Lightning has 20% reduced Mana Reservation", }, }, ["Pyroclast Mine"] = { ["MERCILESS"] = { "Pyroclast Mine deals 25% increased Damage", "Pyroclast Mine has 10% increased Throwing Speed", }, ["ENDGAME"] = { "Pyroclast Mine deals 40% increased Damage", "Pyroclast Mine has 15% increased Throwing Speed", "Pyroclast Mine fires an additional Projectile", }, }, ["Rain of Arrows"] = { ["MERCILESS"] = { "25% increased Rain of Arrows Damage", "10% increased Rain of Arrows Attack Speed", "16% increased Rain of Arrows Area of Effect", "Rain of Arrows has 10% chance to fire an additional sequence of arrows", }, ["ENDGAME"] = { "40% increased Rain of Arrows Damage", "15% increased Rain of Arrows Attack Speed", "24% increased Rain of Arrows Area of Effect", "Rain of Arrows has 15% chance to fire an additional sequence of arrows", }, }, ["Raise Spectre"] = { ["MERCILESS"] = { "Spectres have 25% increased Damage", "Spectres have 8% increased Attack and Cast Speed", "+24% to Raised Spectre Elemental Resistances", }, ["ENDGAME"] = { "Spectres have 40% increased Damage", "Spectres have 12% increased Attack and Cast Speed", "+36% to Raised Spectre Elemental Resistances", }, }, ["Raise Zombie"] = { ["MERCILESS"] = { "Raised Zombies deal 25% increased Damage", "Raised Zombies have 10% increased Attack Speed", "Raised Zombies have +24% to Elemental Resistances", }, ["ENDGAME"] = { "Raised Zombies deal 40% increased Damage", "Raised Zombies have 15% increased Attack Speed", "Raised Zombies have +36% to Elemental Resistances", }, }, ["Rallying Cry"] = { ["MERCILESS"] = { "10% increased Rallying Cry Buff Effect", }, ["ENDGAME"] = { "15% increased Rallying Cry Buff Effect", "Rallying Cry Exerts 1 additional Attack", }, }, ["Reave"] = { ["MERCILESS"] = { "25% increased Reave Damage", "16% increased Reave Radius", }, ["ENDGAME"] = { "40% increased Reave Damage", "24% increased Reave Radius", }, }, ["Reckoning"] = { ["MERCILESS"] = { "25% increased Reckoning Damage", "Reckoning has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "40% increased Reckoning Damage", "Reckoning has 30% increased Cooldown Recovery Rate", }, }, ["Rejuvenation Totem"] = { ["MERCILESS"] = { "Gain 10% of Rejuvenation Totem Life Regeneration as extra Mana Regeneration", "30% increased Rejuvenation Totem Aura Effect", }, ["ENDGAME"] = { "Gain 15% of Rejuvenation Totem Life Regeneration as extra Mana Regeneration", "45% increased Rejuvenation Totem Aura Effect", }, }, ["Righteous Fire"] = { ["MERCILESS"] = { "25% increased Righteous Fire Damage", "16% increased Righteous Fire Area of Effect", "Righteous Fire grants 20% increased Spell Damage", }, ["ENDGAME"] = { "40% increased Righteous Fire Damage", "24% increased Righteous Fire Area of Effect", "Righteous Fire grants 30% increased Spell Damage", }, }, ["Riposte"] = { ["MERCILESS"] = { "25% increased Riposte Damage", "Riposte has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "40% increased Riposte Damage", "Riposte has 30% increased Cooldown Recovery Rate", }, }, ["Scorching Ray"] = { ["MERCILESS"] = { "25% increased Scorching Ray Damage", "8% increased Scorching Ray Cast Speed", "10% increased Scorching Ray beam length", }, ["ENDGAME"] = { "40% increased Scorching Ray Damage", "12% increased Scorching Ray Cast Speed", "15% increased Scorching Ray beam length", }, }, ["Scourge Arrow"] = { ["MERCILESS"] = { "Scourge Arrow deals 25% increased Damage", "Scourge Arrow has 6% chance to Poison per Stage", }, ["ENDGAME"] = { "Scourge Arrow deals 40% increased Damage", "Scourge Arrow has 8% chance to Poison per Stage", "Scourge Arrow creates an additional spore pod at Maximum Stages", }, }, ["Searing Bond"] = { ["MERCILESS"] = { "25% increased Searing Bond Damage", "40% increased Searing Bond Totem Placement Speed", "24% increased Searing Bond Totem Elemental Resistances", }, ["ENDGAME"] = { "40% increased Searing Bond Damage", "60% increased Searing Bond Totem Placement Speed", "36% increased Searing Bond Totem Elemental Resistances", }, }, ["Seismic Cry"] = { ["MERCILESS"] = { "Attacks Exerted by Seismic Cry deal 35% increased Damage ", }, ["ENDGAME"] = { "Attacks Exerted by Seismic Cry deal 50% increased Damage ", "Seismic Cry has a minimum of 10 Power", }, }, ["Seismic Trap"] = { ["MERCILESS"] = { "Seismic Trap deals 25% increased Damage", "Seismic Trap has 20% increased Skill Effect Duration", "Seismic Trap has 10% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Seismic Trap deals 40% increased Damage", "Seismic Trap has 30% increased Skill Effect Duration", "Seismic Trap has 15% increased Cooldown Recovery Rate", "Seismic Trap releases an additional Wave", }, }, ["Shattering Steel"] = { ["MERCILESS"] = { "Shattering Steel deals 25% increased Damage", "Shattering Steel has 20% chance to not consume Steel Shards", }, ["ENDGAME"] = { "Shattering Steel deals 40% increased Damage", "Shattering Steel grants Fortify on Hitting an Enemy at Close Range", "Shattering Steel has 30% chance to not consume Steel Shards", }, }, ["Shield Charge"] = { ["MERCILESS"] = { "25% increased Shield Charge Damage", "10% increased Shield Charge Attack Speed", }, ["ENDGAME"] = { "40% increased Shield Charge Damage", "15% increased Shield Charge Attack Speed", }, }, ["Shock Nova"] = { ["MERCILESS"] = { "25% increased Shock Nova Damage", "Shock Nova ring deals 40% increased Damage", "16% increased Shock Nova Area of Effect", }, ["ENDGAME"] = { "40% increased Shock Nova Damage", "Shock Nova ring deals 60% increased Damage", "24% increased Shock Nova Area of Effect", }, }, ["Shockwave Totem"] = { ["MERCILESS"] = { "25% increased Shockwave Totem Damage", "10% increased Shockwave Totem Cast Speed", "16% increased Shockwave Totem Area of Effect", }, ["ENDGAME"] = { "40% increased Shockwave Totem Damage", "15% increased Shockwave Totem Cast Speed", "24% increased Shockwave Totem Area of Effect", }, }, ["Shrapnel Ballista"] = { ["MERCILESS"] = { "Shrapnel Ballista Pierces 4 additional Targets", "Shrapnel Ballista has 20% increased Projectile Speed", }, ["ENDGAME"] = { "Shrapnel Ballista fires an additional Arrow", "Shrapnel Ballista Pierces 6 additional Targets", "Shrapnel Ballista has 30% increased Projectile Speed", }, }, ["Siege Ballista"] = { ["MERCILESS"] = { "Siege Ballista deals 25% increased Damage", "Siege Ballista has 10% increased Attack Speed", "Siege Ballista has 30% increased Totem Placement Speed", }, ["ENDGAME"] = { "Siege Ballista deals 40% increased Damage", "Siege Ballista has 15% increased Attack Speed", "Siege Ballista has 45% increased Totem Placement Speed", }, }, ["Sigil of Power"] = { ["MERCILESS"] = { "Sigil of Power requires 10% reduced Mana Spent to gain a Stage", "Sigil of Power's Buff also grants 20% increased Critical Strike Chance per Stage", }, ["ENDGAME"] = { "Sigil of Power requires 20% reduced Mana Spent to gain a Stage", "Sigil of Power's Buff also grants 30% increased Critical Strike Chance per Stage", }, }, ["Siphoning Trap"] = { ["MERCILESS"] = { "Siphoning Trap deals 25% increased Damage", "Siphoning Trap has 30% increased Skill Effect Duration", "Siphoning Trap has 25% increased Chill Effect", }, ["ENDGAME"] = { "Siphoning Trap deals 40% increased Damage", "Siphoning Trap has 45% increased Skill Effect Duration", "Siphoning Trap's beam to you grants 1% reduced Damage taken for each other beam", "Siphoning Trap has 40% increased Chill Effect", }, }, ["Smite"] = { ["MERCILESS"] = { "Smite deals 25% increased Damage", "Smite has a 10% chance for lightning to strike another target", "Smite has 20% increased Aura Effect", }, ["ENDGAME"] = { "Smite deals 40% increased Damage", "Smite has a 15% chance for lightning to strike another target", "Smite has 30% increased Aura Effect", }, }, ["Smoke Mine"] = { ["MERCILESS"] = { "20% increased Smoke Mine Duration", "Smoke Mine grants additional 20% increased Movement Speed", }, ["ENDGAME"] = { "30% increased Smoke Mine Duration", "Smoke Mine grants additional 30% increased Movement Speed", }, }, ["Sniper's Mark"] = { ["MERCILESS"] = { "Sniper's Mark has 20% increased Curse Effect", "Sniper's Mark has 30% increased Duration", }, ["ENDGAME"] = { "Sniper's Mark has 30% increased Curse Effect", "Sniper's Mark has 45% increased Duration", }, }, ["Soulrend"] = { ["MERCILESS"] = { "Soulrend deals 25% increased Damage", "Soulrend also Hinders Enemies, with 25% reduced Movement Speed", }, ["ENDGAME"] = { "Soulrend deals 40% increased Damage", "Soulrend also Hinders Enemies, with 40% reduced Movement Speed", "Soulrend fires an additional Projectile", }, }, ["Spark"] = { ["MERCILESS"] = { "25% increased Spark Damage", "Spark fires 2 additional Projectiles", "20% increased Spark Projectile Speed", }, ["ENDGAME"] = { "40% increased Spark Damage", "Spark fires 3 additional Projectiles", "30% increased Spark Projectile Speed", }, }, ["Spectral Shield Throw"] = { ["MERCILESS"] = { "25% increased Spectral Shield Throw Damage", "20% increased Spectral Shield Throw Projectile Speed", "Spectral Shield Throw fires 3 additional Shard Projectiles", }, ["ENDGAME"] = { "40% increased Spectral Shield Throw Damage", "30% increased Spectral Shield Throw Projectile Speed", "Spectral Shield Throw fires 5 additional Shard Projectiles", }, }, ["Spectral Throw"] = { ["MERCILESS"] = { "25% increased Spectral Throw Damage", "20% reduced Spectral Throw Projectile Deceleration", "20% increased Spectral Throw Projectile Speed", }, ["ENDGAME"] = { "40% increased Spectral Throw Damage", "30% reduced Spectral Throw Projectile Deceleration", "30% increased Spectral Throw Projectile Speed", }, }, ["Spellslinger"] = { ["MERCILESS"] = { "Skills Supported by Spellslinger have 10% reduced Mana Reservation", "Skills Supported by Spellslinger have 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "Skills Supported by Spellslinger have 15% reduced Mana Reservation", "Skills Supported by Spellslinger have 30% increased Cooldown Recovery Rate", }, }, ["Spirit Offering"] = { ["MERCILESS"] = { "30% increased Spirit Offering Duration", "Spirit Offering grants +8% of Physical Damage as Extra Chaos Damage", }, ["ENDGAME"] = { "45% increased Spirit Offering Duration", "Spirit Offering grants +12% of Physical Damage as Extra Chaos Damage", }, }, ["Split Arrow"] = { ["MERCILESS"] = { "25% increased Split Arrow Damage", "60% increased Split Arrow Critical Strike Chance", "Split Arrow fires 2 additional Projectiles", }, ["ENDGAME"] = { "40% increased Split Arrow Damage", "90% increased Split Arrow Critical Strike Chance", "Split Arrow fires 3 additional Projectiles", }, }, ["Splitting Steel"] = { ["MERCILESS"] = { "Splitting Steel deals 25% increased Damage", "Splitting Steel has 16% increased Area of Effect", "Splitting Steel has 20% chance to not consume Steel Shards", }, ["ENDGAME"] = { "Splitting Steel deals 40% increased Damage", "Splitting Steel has 24% increased Area of Effect", "Splitting Steel has 30% chance to not consume Steel Shards", }, }, ["Static Strike"] = { ["MERCILESS"] = { "25% increased Static Strike Damage", "30% increased Static Strike Duration", "16% increased Static Strike Area of Effect", "Static Strike has +1 maximum Beam Targets", }, ["ENDGAME"] = { "40% increased Static Strike Damage", "45% increased Static Strike Duration", "24% increased Static Strike Area of Effect", "Static Strike has +2 maximum Beam Targets", }, }, ["Steelskin"] = { ["MERCILESS"] = { "Steelskin grants 8% additional Physical Damage Reduction", "Steelskin Buff can take 30% increased amount of Damage", }, ["ENDGAME"] = { "Steelskin grants 12% additional Physical Damage Reduction", "Steelskin Buff can take 45% increased amount of Damage", }, }, ["Storm Brand"] = { ["MERCILESS"] = { "Storm Brand deals 25% increased Damage", "Storm Brand has a 12% chance to Chain an additional time", "Storm Brand Damage Penetrates 8% of Branded Enemy's Lightning Resistance", }, ["ENDGAME"] = { "Storm Brand deals 40% increased Damage", "Storm Brand has a 18% chance to Chain an additional time", "Storm Brand Damage Penetrates 12% of Branded Enemy's Lightning Resistance", }, }, ["Storm Burst"] = { ["MERCILESS"] = { "25% increased Storm Burst Damage", "16% increased Storm Burst Area of Effect", "Storm Burst has a 10% chance to create an additional Orb", }, ["ENDGAME"] = { "40% increased Storm Burst Damage", "24% increased Storm Burst Area of Effect", "Storm Burst has a 15% chance to create an additional Orb", }, }, ["Storm Call"] = { ["MERCILESS"] = { "25% increased Storm Call Damage", "20% reduced Storm Call Duration", "16% increased Storm Call Area of Effect", }, ["ENDGAME"] = { "40% increased Storm Call Damage", "30% reduced Storm Call Duration", "24% increased Storm Call Area of Effect", }, }, ["Stormbind"] = { ["MERCILESS"] = { "Stormbind has 16% increased Area of Effect", "Stormbind deals 25% increased Damage", "Rune Blast teleports you to the detonated Rune if you have not detonated Runes in the past 1 second", }, ["ENDGAME"] = { "Stormbind has 24% increased Area of Effect", "Stormbind deals 40% increased Damage", "Rune Blast teleports you to the detonated Rune if you have not detonated Runes in the past 1.5 seconds", }, }, ["Stormblast Mine"] = { ["MERCILESS"] = { "Stormblast Mine deals 25% increased Damage", "Stormblast Mine has 10% increased Throwing Speed", "Stormblast Mine has 20% increased Aura Effect", }, ["ENDGAME"] = { "Stormblast Mine deals 40% increased Damage", "Stormblast Mine has 15% increased Throwing Speed", "Stormblast Mine has 40% increased Aura Effect", }, }, ["Summon Carrion Golem"] = { ["MERCILESS"] = { "Summoned Carrion Golems deal 25% increased Damage", "100% increased Effect of the Buff granted by your Carrion Golems", "Summoned Carrion Golems have +24% to all Elemental Resistances", }, ["ENDGAME"] = { "Summoned Carrion Golems deal 40% increased Damage", "150% increased Effect of the Buff granted by your Carrion Golems", "Summoned Carrion Golems have +36% to all Elemental Resistances", }, }, ["Summon Chaos Golem"] = { ["MERCILESS"] = { "Chaos Golems deal 25% increased Damage", "75% increased Effect of the Buff granted by your Chaos Golems", "+24% to Chaos Golem Elemental Resistances", }, ["ENDGAME"] = { "Chaos Golems deal 40% increased Damage", "100% increased Effect of the Buff granted by your Chaos Golems", "+36% to Chaos Golem Elemental Resistances", }, }, ["Summon Flame Golem"] = { ["MERCILESS"] = { "Flame Golems have 25% increased Damage", "+24% to increased Flame Golem Elemental Resistances", "100% increased Effect of the Buff granted by your Flame Golems", }, ["ENDGAME"] = { "Flame Golems have 40% increased Damage", "+36% to increased Flame Golem Elemental Resistances", "150% increased Effect of the Buff granted by your Flame Golems", }, }, ["Summon Holy Relic"] = { ["MERCILESS"] = { "Summoned Holy Relics deal 25% increased Damage", "Summoned Holy Relics have 16% increased Area of Effect", "Summoned Holy Relics have 75% increased Buff Effect", }, ["ENDGAME"] = { "Summoned Holy Relics deal 40% increased Damage", "Summoned Holy Relics have 24% increased Area of Effect", "Summoned Holy Relics have 100% increased Buff Effect", }, }, ["Summon Ice Golem"] = { ["MERCILESS"] = { "Ice Golems deal 25% increased Damage", "+24% to Ice Golem Elemental Resistances", "100% increased Effect of the Buff granted by your Ice Golems", }, ["ENDGAME"] = { "Ice Golems deal 40% increased Damage", "+36% to Ice Golem Elemental Resistances", "150% increased Effect of the Buff granted by your Ice Golems", }, }, ["Summon Lightning Golem"] = { ["MERCILESS"] = { "Lightning Golems deal 25% increased Damage", "100% increased Effect of the Buff granted by your Lightning Golems", "+24% to Lightning Golem Elemental Resistances", }, ["ENDGAME"] = { "Lightning Golems deal 40% increased Damage", "150% increased Effect of the Buff granted by your Lightning Golems", "+36% to Lightning Golem Elemental Resistances", }, }, ["Summon Raging Spirit"] = { ["MERCILESS"] = { "Summon Raging Spirit has 20% increased Duration", "Summon Raging Spirit has 12% chance to summon an extra Minion", "Summoned Raging Spirits deal 25% increased Damage", }, ["ENDGAME"] = { "Summon Raging Spirit has 30% increased Duration", "Summon Raging Spirit has 18% chance to summon an extra Minion", "Summoned Raging Spirits deal 40% increased Damage", }, }, ["Summon Skeleton"] = { ["MERCILESS"] = { "Skeletons deal 25% increased Damage", "20% chance to Summon an additional Skeleton Warrior with Summon Skeleton", }, ["ENDGAME"] = { "Skeletons deal 40% increased Damage", "40% chance to Summon an additional Skeleton Warrior with Summon Skeleton", }, }, ["Summon Skitterbots"] = { ["MERCILESS"] = { "Summoned Skitterbots have 60% increased Area of Effect", "Summon Skitterbots has 14% reduced Mana Reservation", }, ["ENDGAME"] = { "Summoned Skitterbots have 90% increased Area of Effect", "Summon Skitterbots has 20% reduced Mana Reservation", }, }, ["Summon Stone Golem"] = { ["MERCILESS"] = { "Stone Golems deal 25% increased Damage", "+24% to Stone Golem Elemental Resistances", "100% increased Effect of the Buff granted by your Stone Golems", }, ["ENDGAME"] = { "Stone Golems deal 40% increased Damage", "+36% to Stone Golem Elemental Resistances", "150% increased Effect of the Buff granted by your Stone Golems", }, }, ["Sunder"] = { ["MERCILESS"] = { "Sunder has 25% increased Damage", "Sunder has 16% increased Area of Effect", "Sunder has 15% reduced delay between Areas in the Wave", }, ["ENDGAME"] = { "Sunder has 40% increased Damage", "Sunder has 24% increased Area of Effect", "Sunder has 20% reduced delay between Areas in the Wave", }, }, ["Sweep"] = { ["MERCILESS"] = { "25% increased Sweep Damage", "Sweep has a 20% chance to grant an Endurance Charge on Hit", "16% increased Sweep Area of Effect", }, ["ENDGAME"] = { "40% increased Sweep Damage", "Sweep has a 30% chance to grant an Endurance Charge on Hit", "24% increased Sweep Area of Effect", }, }, ["Tectonic Slam"] = { ["MERCILESS"] = { "Tectonic Slam deals 25% increased Damage", "Tectonic Slam has 16% increased Area of Effect", "Tectonic Slam has +12% fissure branching chance", }, ["ENDGAME"] = { "Tectonic Slam deals 40% increased Damage", "Tectonic Slam has 24% increased Area of Effect", "Tectonic Slam has +20% fissure branching chance", }, }, ["Tempest Shield"] = { ["MERCILESS"] = { "25% increased Tempest Shield Damage", "Tempest Shield chains an additional 2 times", }, ["ENDGAME"] = { "40% increased Tempest Shield Damage", "Tempest Shield chains an additional 3 times", }, }, ["Temporal Chains"] = { ["MERCILESS"] = { "20% increased Temporal Chains Curse Effect", "30% increased Temporal Chains Duration", }, ["ENDGAME"] = { "30% increased Temporal Chains Curse Effect", "45% increased Temporal Chains Duration", }, }, ["Tornado Shot"] = { ["MERCILESS"] = { "25% increased Tornado Shot Damage", "60% increased Tornado Shot Critical Strike Chance", }, ["ENDGAME"] = { "40% increased Tornado Shot Damage", "90% increased Tornado Shot Critical Strike Chance", "Tornado Shot fires an additional secondary Projectile", }, }, ["Toxic Rain"] = { ["MERCILESS"] = { "Toxic Rain deals 25% increased Damage", "Toxic Rain gains 6% of Physical Damage as Extra Chaos Damage", }, ["ENDGAME"] = { "Toxic Rain deals 40% increased Damage", "Toxic Rain gains 10% of Physical Damage as Extra Chaos Damage", "Toxic Rain fires 1 additional Arrow", }, }, ["Unearth"] = { ["MERCILESS"] = { "Unearth Spawns corpses with +3 Level", "25% increased Unearth Damage", "8% increased Unearth Cast Speed", }, ["ENDGAME"] = { "Unearth Spawns corpses with +5 Level", "40% increased Unearth Damage", "12% increased Unearth Cast Speed", }, }, ["Vengeance"] = { ["MERCILESS"] = { "25% increased Vengeance Damage", "Vengeance has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "40% increased Vengeance Damage", "Vengeance has 30% increased Cooldown Recovery Rate", }, }, ["Venom Gyre"] = { ["MERCILESS"] = { "Venom Gyre deals 25% increased Damage", "Venom Gyre has a 12% chance to inflict Withered for 2 seconds on Hit", }, ["ENDGAME"] = { "Venom Gyre deals 40% increased Damage", "Venom Gyre has a 20% chance to inflict Withered for 2 seconds on Hit", "Venom Gyre has a 35% chance to keep caught Projectiles fired by using Whirling Blades", }, }, ["Vigilant Strike"] = { ["MERCILESS"] = { "25% increased Vigilant Strike Damage", "30% increased Vigilant Strike Fortify Duration", }, ["ENDGAME"] = { "40% increased Vigilant Strike Damage", "45% increased Vigilant Strike Fortify Duration", }, }, ["Viper Strike"] = { ["MERCILESS"] = { "25% increased Viper Strike Damage", "60% increased Viper Strike Critical Strike Chance", "20% increased Viper Strike Duration", }, ["ENDGAME"] = { "40% increased Viper Strike Damage", "90% increased Viper Strike Critical Strike Chance", "30% increased Viper Strike Duration", }, }, ["Vitality"] = { ["MERCILESS"] = { "Vitality has 20% reduced Mana Reservation", }, ["ENDGAME"] = { "Vitality has 30% reduced Mana Reservation", }, }, ["Void Sphere"] = { ["MERCILESS"] = { "Void Sphere has 20% increased Cooldown Recovery Rate", "Enemies in Void Sphere's range take up to 6% increased Damage, based on distance from the Void Sphere", "Void Sphere has 12% increased Pulse Frequency", }, ["ENDGAME"] = { "Void Sphere has 30% increased Cooldown Recovery Rate", "Enemies in Void Sphere's range take up to 10% increased Damage, based on distance from the Void Sphere", "Void Sphere has 18% increased Pulse Frequency", }, }, ["Volatile Dead"] = { ["MERCILESS"] = { "25% increased Volatile Dead Damage", "8% increased Volatile Dead Cast Speed", }, ["ENDGAME"] = { "Volatile Dead Consumes up to 1 additional corpse", "40% increased Volatile Dead Damage", "12% increased Volatile Dead Cast Speed", }, }, ["Vortex"] = { ["MERCILESS"] = { "25% increased Vortex Damage", "20% increased Vortex Duration", "Vortex has 30% increased Area of Effect when Cast on Frostbolt", "Vortex has 20% increased Cooldown Recovery Rate", }, ["ENDGAME"] = { "40% increased Vortex Damage", "30% increased Vortex Duration", "Vortex has 45% increased Area of Effect when Cast on Frostbolt", "Vortex has 30% increased Cooldown Recovery Rate", }, }, ["Vulnerability"] = { ["MERCILESS"] = { "20% increased Vulnerability Curse Effect", "30% increased Vulnerability Duration", }, ["ENDGAME"] = { "30% increased Vulnerability Curse Effect", "45% increased Vulnerability Duration", }, }, ["War Banner"] = { ["MERCILESS"] = { "War Banner has 25% increased Aura Effect", }, ["ENDGAME"] = { "War Banner has 40% increased Aura Effect", }, }, ["Warlord's Mark"] = { ["MERCILESS"] = { "20% increased Warlord's Mark Curse Effect", "30% increased Warlord's Mark Duration", }, ["ENDGAME"] = { "30% increased Warlord's Mark Curse Effect", "45% increased Warlord's Mark Duration", }, }, ["Wave of Conviction"] = { ["MERCILESS"] = { "Wave of Conviction deals 25% increased Damage", "Wave of Conviction's Exposure applies -4% Elemental Resistance", "Wave of Conviction has 20% increased Duration", }, ["ENDGAME"] = { "Wave of Conviction deals 40% increased Damage", "Wave of Conviction's Exposure applies -6% Elemental Resistance", "Wave of Conviction has 30% increased Duration", }, }, ["Whirling Blades"] = { ["MERCILESS"] = { "25% increased Whirling Blades Damage", "10% increased Whirling Blades Attack Speed", }, ["ENDGAME"] = { "40% increased Whirling Blades Damage", "15% increased Whirling Blades Attack Speed", }, }, ["Wild Strike"] = { ["MERCILESS"] = { "25% increased Wild Strike Damage", "Wild Strike's Beam Chains an additional 4 times", "24% increased Wild Strike Area of Effect", }, ["ENDGAME"] = { "40% increased Wild Strike Damage", "Wild Strike's Beam Chains an additional 6 times", "36% increased Wild Strike Area of Effect", }, }, ["Winter Orb"] = { ["MERCILESS"] = { "Winter Orb deals 25% increased Damage", "Winter Orb has 2% increased Area of Effect per Stage", }, ["ENDGAME"] = { "Winter Orb deals 40% increased Damage", "Winter Orb has +2 Maximum Stages", "Winter Orb has 3% increased Area of Effect per Stage", }, }, ["Wintertide Brand"] = { ["MERCILESS"] = { "Wintertide Brand deals 25% increased Damage", "Wintertide Brand has +2 to maximum Stages", "Wintertide Brand has 25% increased Chill Effect", }, ["ENDGAME"] = { "Wintertide Brand deals 40% increased Damage", "Wintertide Brand has +4 to maximum Stages", "Wintertide Brand has 40% increased Chill Effect", }, }, ["Wither"] = { ["MERCILESS"] = { "Wither has 24% increased Duration", "Wither has 16% increased Area of Effect", }, ["ENDGAME"] = { "Wither has 36% increased Duration", "Wither has 24% increased Area of Effect", }, }, ["Withering Step"] = { ["MERCILESS"] = { "Withering Step inflicts 2 additional Withered Debuffs", "Withering Step has 20% increased Elusive Effect", }, ["ENDGAME"] = { "Withering Step inflicts 3 additional Withered Debuffs", "Withering Step has 30% increased Elusive Effect", }, }, ["Wrath"] = { ["MERCILESS"] = { "Wrath has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Wrath has 15% reduced Mana Reservation", }, }, ["Zealotry"] = { ["MERCILESS"] = { "Zealotry has 10% reduced Mana Reservation", }, ["ENDGAME"] = { "Zealotry has 15% reduced Mana Reservation", }, }, }
if not modules then modules = { } end modules ['lpdf-res'] = { version = 1.001, comment = "companion to lpdf-ini.mkiv", author = "Hans Hagen, PRAGMA-ADE, Hasselt NL", copyright = "PRAGMA ADE / ConTeXt Development Team", license = "see context related readme files" } local codeinjections = backends.codeinjections local implement = interfaces.implement local nuts = nodes.nuts local tonut = nodes.tonut local setfield = nuts.setfield local setlist = nuts.setlist local new_hlist = nuts.pool.hlist local saveboxresource = tex.saveboxresource local useboxresource = tex.useboxresource local getboxresource = tex.getboxresourcedimensions function codeinjections.registerboxresource(n) return saveboxresource(n,nil,lpdf.collectedresources(),true) -- direct, todo: accept functions as attr/resources end function codeinjections.restoreboxresource(index) local hbox = new_hlist() local list, wd, ht, dp = useboxresource(index) setlist(hbox,tonut(list)) setfield(hbox,"width", wd) setfield(hbox,"height", ht) setfield(hbox,"depth", dp) return hbox -- so we return a nut ! end function codeinjections.boxresourcedimensions(index) return getboxresource(index) end
--Code for generating vizualization of labels require 'paths' require 'hdf5' projectDir = paths.concat(os.getenv('HOME'),'pose-hg-train') paths.dofile('ref.lua') paths.dofile('util/eval.lua') paths.dofile('util/pose.lua') paths.dofile('util/dataloader.lua') paths.dofile('util/img.lua') function drawOutput(input, hms) local im = input:clone() local colorHms = {} local inp64 = image.scale(input,64):mul(.3) for i = 1,18 do colorHms[i] = colorHM(hms[i]) colorHms[i]:mul(.7):add(inp64) end local totalHm = compileImages18(colorHms, 5, 4, 64) --im = compileImages({im,totalHm}, 1, 2, 256) totalHm = image.scale(totalHm,756) return totalHm end idxs = torch.range(1, 886) local a = hdf5.open('../data/harpe/annot_corrected.h5') annot = {} local tags = {'imgname','center','scale'} for _,tag in ipairs(tags) do annot[tag] = a:read(tag):all() end local nsamples = idxs:nElement() __, labels = loadData(nil , idxs) labels = labels[#labels] --print(labels[#labels]:size()) for i =1,nsamples do local im = image.load('../data/harpe/images/' .. ffi.string(annot['imgname'][idxs[i]]:char():data())) local center = annot['center'][idxs[i]] local scale = annot['scale'][idxs[i]] scale = scale * 1.8 local inp = crop(im, center, scale, 0, 256) labels[i]:mul(4) local dispImg = drawOutput(inp, labels[i]) image.save('labels/' .. ffi.string(annot['imgname'][idxs[i]]:char():data()) , dispImg) xlua.progress(i,nsamples) --sys.sleep(3) end
--ペンデュラム・エクシーズ --Scripted by nekrozar function c100260016.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,100260016+EFFECT_COUNT_CODE_OATH) e1:SetTarget(c100260016.target) e1:SetOperation(c100260016.activate) c:RegisterEffect(e1) end function c100260016.spfilter1(c,e,tp) return c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingTarget(c100260016.spfilter2,tp,LOCATION_PZONE,0,1,c,e,tp,c) end function c100260016.xyzlv(e,c,rc) return e:GetHandler():GetLevel()+e:GetLabel()*0x10000 end function c100260016.spfilter2(c,e,tp,mc) if not c:IsCanBeSpecialSummoned(e,0,tp,false,false) then return false end local e1=nil local e2=nil if c:IsLevelAbove(1) and mc:IsLevelAbove(1) then e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_XYZ_LEVEL) e1:SetValue(c100260016.xyzlv) e1:SetLabel(mc:GetLevel()) c:RegisterEffect(e1,true) e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_XYZ_LEVEL) e2:SetValue(c100260016.xyzlv) e2:SetLabel(c:GetLevel()) mc:RegisterEffect(e2,true) end local res=Duel.IsExistingMatchingCard(Card.IsXyzSummonable,tp,LOCATION_EXTRA,0,1,nil,Group.FromCards(c,mc),2,2) if e1 then e1:Reset() end if e2 then e2:Reset() end return res end function c100260016.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return Duel.IsPlayerCanSpecialSummonCount(tp,2) and not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 and Duel.GetLocationCountFromEx(tp)>0 and Duel.IsExistingTarget(c100260016.spfilter1,tp,LOCATION_PZONE,0,1,nil,e,tp) end local g=Duel.GetFieldGroup(tp,LOCATION_PZONE,0) Duel.SetTargetCard(g) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,2,0,0) end function c100260016.spfilter3(c,e,tp) return c:IsRelateToEffect(e) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100260016.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.IsPlayerAffectedByEffect(tp,59822133) then return end if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(c100260016.spfilter3,nil,e,tp) if g:GetCount()<2 then return end local tc1=g:GetFirst() local tc2=g:GetNext() Duel.SpecialSummonStep(tc1,0,tp,tp,false,false,POS_FACEUP) Duel.SpecialSummonStep(tc2,0,tp,tp,false,false,POS_FACEUP) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+RESETS_STANDARD) tc1:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_DISABLE_EFFECT) tc1:RegisterEffect(e2) local e3=e1:Clone() tc2:RegisterEffect(e3) local e4=e2:Clone() tc2:RegisterEffect(e4) Duel.SpecialSummonComplete() if Duel.GetLocationCountFromEx(tp,tp,g)<=0 then return end local e5=nil local e6=nil if tc1:IsLevelAbove(1) and tc2:IsLevelAbove(1) then e5=Effect.CreateEffect(e:GetHandler()) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_XYZ_LEVEL) e5:SetValue(c100260016.xyzlv) e5:SetLabel(tc2:GetLevel()) tc1:RegisterEffect(e5,true) e6=Effect.CreateEffect(e:GetHandler()) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetCode(EFFECT_XYZ_LEVEL) e6:SetValue(c100260016.xyzlv) e6:SetLabel(tc1:GetLevel()) tc2:RegisterEffect(e6,true) end local xyzg=Duel.GetMatchingGroup(Card.IsXyzSummonable,tp,LOCATION_EXTRA,0,nil,g,2,2) if xyzg:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local xyz=xyzg:Select(tp,1,1,nil):GetFirst() Duel.XyzSummon(tp,xyz,g) end if e5 then e5:Reset() end if e6 then e5:Reset() end end
minetest.register_tool("random_place_tool:random_place_tool", { description = "Random Place Tool", inventory_image = "random_place_tool.png", wield_image = "random_place_tool.png", on_place = function(itemstack, placer, pointed_thing) local inv = placer:get_inventory() local items = {} for i=1,8 do local itemstack = inv:get_stack("main", i) if not itemstack:is_empty() then local name = itemstack:get_name() local item = minetest.registered_items[name] if name ~= "random_place_tool:random_place_tool" and item then table.insert(items, {itemstack, item.on_place, i}) end end end if items[1] then local item = items[math.random(#items)] local func = item[2] local var = func(item[1], placer, pointed_thing) if type(var) == "userdata" and var:is_known() then inv:set_stack("main", item[3], var) end end end }) if minetest.get_modpath("default") then minetest.register_craft({ output = "random_place_tool:random_place_tool", recipe = { {"", "", "default:mese_crystal"}, {"", "group:stick", "default:mese_crystal"}, {"group:stick", "", ""} } }) end
--*********************************************************** --** ROBERT JOHNSON ** --*********************************************************** ---@class ISAdminTicketsUI : ISPanel ISAdminTicketsUI = ISPanel:derive("ISAdminTicketsUI"); ISAdminTicketsUI.messages = {}; local FONT_HGT_SMALL = getTextManager():getFontHeight(UIFont.Small) local FONT_HGT_MEDIUM = getTextManager():getFontHeight(UIFont.Medium) local FONT_HGT_LARGE = getTextManager():getFontHeight(UIFont.Large) local HEADER_HGT = FONT_HGT_SMALL + 2 * 2 --************************************************************************-- --** ISAdminTicketsUI:initialise --** --************************************************************************-- function ISAdminTicketsUI:initialise() ISPanel.initialise(self); local btnWid = 100 local btnHgt = math.max(25, FONT_HGT_SMALL + 3 * 2) local btnHgt2 = 18 local padBottom = 10 self.no = ISButton:new(10, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("UI_Cancel"), self, ISAdminTicketsUI.onClick); self.no.internal = "CANCEL"; self.no.anchorTop = false self.no.anchorBottom = true self.no:initialise(); self.no:instantiate(); self.no.borderColor = {r=1, g=1, b=1, a=0.1}; self:addChild(self.no); local y = 20 + FONT_HGT_MEDIUM + HEADER_HGT self.datas = ISScrollingListBox:new(10, y, self.width - 20, self.height - padBottom - btnHgt - padBottom - y) self.datas:initialise(); self.datas:instantiate(); self.datas.itemheight = FONT_HGT_SMALL + 2 * 2; self.datas.selected = 0; self.datas.joypadParent = self; self.datas.font = UIFont.NewSmall; self.datas.doDrawItem = self.drawDatas; self.datas.drawBorder = true; self:addChild(self.datas); self.answerTicketBtn = ISButton:new(self:getWidth() - btnWid - 10, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("IGUI_TicketUI_AnswerTicket"), self, ISAdminTicketsUI.onClick); self.answerTicketBtn.internal = "ANSWERTICKET"; self.answerTicketBtn.anchorTop = false self.answerTicketBtn.anchorBottom = true self.answerTicketBtn:initialise(); self.answerTicketBtn:instantiate(); self.answerTicketBtn.borderColor = {r=1, g=1, b=1, a=0.1}; self.answerTicketBtn:setWidthToTitle(btnWid) self.answerTicketBtn:setX(self.width - self.answerTicketBtn.width - 10) self:addChild(self.answerTicketBtn); self.removeBtn = ISButton:new(self.answerTicketBtn.x - btnWid - 25, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("IGUI_TicketUI_RemoveTicket"), self, ISAdminTicketsUI.onClick); self.removeBtn.internal = "REMOVE"; self.removeBtn.anchorTop = false self.removeBtn.anchorBottom = true self.removeBtn:initialise(); self.removeBtn:instantiate(); self.removeBtn.borderColor = {r=1, g=1, b=1, a=0.1}; self:addChild(self.removeBtn); self.refreshBtn = ISButton:new(self.removeBtn.x - btnWid - 25, self:getHeight() - padBottom - btnHgt, btnWid, btnHgt, getText("IGUI_DbViewer_Refresh"), self, ISAdminTicketsUI.onClick); self.refreshBtn.internal = "REFRESH"; self.refreshBtn.anchorTop = false self.refreshBtn.anchorBottom = true self.refreshBtn:initialise(); self.refreshBtn:instantiate(); self.refreshBtn.borderColor = {r=1, g=1, b=1, a=0.1}; self:addChild(self.refreshBtn); self:getTickets(); end function ISAdminTicketsUI:getTickets() getTickets(nil); end function ISAdminTicketsUI:populateList() self.datas:clear(); self.selectedTicket = nil; for i=0,self.tickets:size()-1 do local ticket = self.tickets:get(i); local item = {} item.ticket = ticket item.richText = ISRichTextLayout:new(self.datas:getWidth() - 200 - 10 * 2) item.richText.marginLeft = 0 item.richText.marginTop = 0 item.richText.marginRight = 0 item.richText.marginBottom = 0 item.richText:setText(ticket:getMessage()) item.richText:initialise() item.richText:paginate() if ticket:getAnswer() then item.richText2 = ISRichTextLayout:new(self.datas:getWidth() - 20 - 10 * 2) item.richText2.marginLeft = 0 item.richText2.marginTop = 0 item.richText2.marginRight = 0 item.richText2.marginBottom = 0 item.richText2:setText(ticket:getAnswer():getAuthor() .. ": " .. ticket:getAnswer():getMessage()) item.richText2:initialise() item.richText2:paginate() end self.datas:addItem(ticket:getAuthor(), item); if i == 0 then self.selectedTicket = ticket; end end end function ISAdminTicketsUI:update() self.answerTicketBtn.enable = false; if self.selectedTicket then if not self.selectedTicket:getAnswer() then self.answerTicketBtn.enable = true; end end end function ISAdminTicketsUI:drawDatas(y, item, alt) local a = 0.9; local answerHeight = 0; -- self.parent.selectedTicket = nil; self:drawRectBorder(0, (y), self:getWidth(), item.height - 1, a, self.borderColor.r, self.borderColor.g, self.borderColor.b); local ticket = item.item.ticket if self.selected == item.index then self:drawRect(0, (y), self:getWidth(), item.height - 1, 0.3, 0.7, 0.35, 0.15); self.parent.selectedTicket = ticket; end self:drawText(ticket:getAuthor(), 10, y + 2, 1, 1, 1, a, self.font); self:drawText(ticket:getTicketID() .. "", 105, y + 2, 1, 1, 1, a, self.font); item.item.richText:render(205, y + 2, self) local messageHeight = math.max(item.item.richText:getHeight() + 4, self.itemheight) -- self:drawText(ticket:getMessage(), 205, y + 2, 1, 1, 1, a, self.font); if ticket:getAnswer() then answerHeight = math.max(item.item.richText2:getHeight() + 4, self.itemheight) -- self:drawText("Answer", 30, y + 2 + messageHeight, 1, 1, 1, a, self.font); item.item.richText2:render(20, y + 2 + messageHeight, self) -- self:drawText(item.item:getAnswer():getAuthor() .. ": " .. item.item:getAnswer():getMessage(), 100, y + self.itemheight + 2, 1, 1, 1, a, self.font); self:drawRect(0, (y + messageHeight), self:getWidth(), answerHeight - 1, 0.15, 1, 1, 1); end self:drawRect(100, y, 1, messageHeight-1,1,self.borderColor.r, self.borderColor.g, self.borderColor.b); self:drawRect(200, y, 1, messageHeight-1,1,self.borderColor.r, self.borderColor.g, self.borderColor.b); return y + messageHeight + answerHeight; end function ISAdminTicketsUI:prerender() local z = 10; self:drawRect(0, 0, self.width, self.height, self.backgroundColor.a, self.backgroundColor.r, self.backgroundColor.g, self.backgroundColor.b); self:drawRectBorder(0, 0, self.width, self.height, self.borderColor.a, self.borderColor.r, self.borderColor.g, self.borderColor.b); self:drawText(getText("IGUI_AdminPanel_SeeTickets"), self.width/2 - (getTextManager():MeasureStringX(UIFont.Medium, getText("IGUI_AdminPanel_SeeTickets")) / 2), z, 1,1,1,1, UIFont.Medium); self.datas.doDrawItem = self.drawDatas end function ISAdminTicketsUI:render() self:drawRectBorder(self.datas.x, self.datas.y - HEADER_HGT, self.datas:getWidth(), HEADER_HGT + 1, 1, self.borderColor.r, self.borderColor.g, self.borderColor.b); self:drawRect(self.datas.x, 1 + self.datas.y - HEADER_HGT, self.datas.width, HEADER_HGT,self.listHeaderColor.a,self.listHeaderColor.r, self.listHeaderColor.g, self.listHeaderColor.b); self:drawRect(self.datas.x + 100, 1 + self.datas.y - HEADER_HGT, 1, HEADER_HGT,1,self.borderColor.r, self.borderColor.g, self.borderColor.b); self:drawRect(self.datas.x + 200, 1 + self.datas.y - HEADER_HGT, 1, HEADER_HGT,1,self.borderColor.r, self.borderColor.g, self.borderColor.b); self:drawText("Author", self.datas.x + 5, self.datas.y - HEADER_HGT + 2, 1,1,1,1,UIFont.Small); self:drawText("TicketID", self.datas.x + 105, self.datas.y - HEADER_HGT + 2, 1,1,1,1,UIFont.Small); self:drawText("Message", self.datas.x + 205, self.datas.y - HEADER_HGT + 2, 1,1,1,1,UIFont.Small); end function ISAdminTicketsUI:onClick(button) if button.internal == "CANCEL" then self:setVisible(false); self:removeFromUIManager(); end if button.internal == "ANSWERTICKET" then local inset = 2 local btnHgt = math.max(25, FONT_HGT_SMALL + 3 * 2) local titleBarHeight = 16 local height = titleBarHeight + 8 + FONT_HGT_SMALL + 8 + FONT_HGT_MEDIUM * 5 + inset * 2 + btnHgt + 10 * 2 height = math.max(height, 200) local modal = ISTextBox:new(self.x + 50, 200, 400, height, getText("IGUI_TicketUI_AnswerTicket"), "", self, ISAdminTicketsUI.onAnswerTicket); modal:setNumberOfLines(5) modal:setMaxLines(5) modal:setMultipleLine(true) modal.changedName = button.changedName; modal:initialise(); modal.ticketID = self.selectedTicket:getTicketID(); modal:addToUIManager(); end if button.internal == "REFRESH" then self.datas:clear(); self.selectedTicket = nil; self:getTickets(); end if button.internal == "REMOVE" then local modal = ISModalDialog:new(0,0, 250, 150, getText("IGUI_TicketUI_RemoveTicketPopup"), true, self, ISAdminTicketsUI.onRemoveTicket, nil); modal:initialise() modal:addToUIManager() end end function ISAdminTicketsUI:onRemoveTicket(button) if button.internal == "YES" then removeTicket(self.selectedTicket:getTicketID()); end end ISAdminTicketsUI.gotTickets = function(tickets) if ISAdminTicketsUI.instance and ISAdminTicketsUI.instance:isVisible() then ISAdminTicketsUI.instance.tickets = tickets; ISAdminTicketsUI.instance:populateList(); end end function ISAdminTicketsUI:onAnswerTicket(button) if button.internal == "OK" then if (button.parent.entry:getText() and button.parent.entry:getText() ~= "")then addTicket(self.player:getUsername(), button.parent.entry:getText(),button.parent.ticketID); end end end --************************************************************************-- --** ISAdminTicketsUI:new --** --************************************************************************-- function ISAdminTicketsUI:new(x, y, width, height, player) local o = {} x = getCore():getScreenWidth() / 2 - (width / 2); y = getCore():getScreenHeight() / 2 - (height / 2); o = ISPanel:new(x, y, width, height); setmetatable(o, self) self.__index = self o.borderColor = {r=0.4, g=0.4, b=0.4, a=1}; o.backgroundColor = {r=0, g=0, b=0, a=0.8}; o.listHeaderColor = {r=0.4, g=0.4, b=0.4, a=0.3}; o.width = width; o.height = height; o.player = player; o.selectedFaction = nil; o.moveWithMouse = true; o.tickets = nil; ISAdminTicketsUI.instance = o; return o; end Events.ViewTickets.Add(ISAdminTicketsUI.gotTickets)
core.register_craftitem(":creatures:rotten_flesh", { description = "Rotten Flesh", inventory_image = "creatures_rotten_flesh.png", on_use = core.item_eat(1), })
--======================================================================-- --== Coronium GS Client --== @copyright Chris Byerley @develephant --== @year 2014 --== @version 1 --== @license Apache License 2.0 --======================================================================-- local table = require( 'table' ) local math = require( 'math' ) local utils = require( 'utils' ) local json = require( 'json' ) local os = require( 'os' ) local tools = require( 'Tools' ) local Emitter = require( 'core' ).Emitter --- Coronium GS Client/Player. -- A socket client connected to the server. -- @author Chris Byerley -- @copyright 2014 develephant -- @license Apache License 2.0 -- @module Client local Client = Emitter:extend() Client.timeout = 120 --== 2 mins --======================================================================-- --== Client Instance --======================================================================-- ---Create a new Client instance. __This is handled automatically.__ -- @tparam Socket client_sock The incoming socket connection. -- @tparam int timeout_seconds The number of seconds before -- the Client connection will time out. -- @treturn Client The newly wrapped socket connection. -- @usage local client = Client:new( socket, 30 ) -- @function new -- @local function Client:initialize( client_sock, timeout_seconds ) self.player_id = tools.uuid() local timeout = timeout_seconds or Client.timeout self.client = client_sock self.client:on( "data", utils.bind( self._handleData, self ) ) self.client:on( "close", function() self:emit( "ClientClose", self.client ) end) self.client:on( "timeout", function ( e ) self:emit( "ClientTimeout", self.client ) self.client:done() end) self.client:on( "error", function( e ) self:emit( "ClientError", self.client, e ) end) self:setTimeout( timeout ) self.buffer = "" --== Set from outside ==-- --== Auto-gen random player handle self.player_handle = 'user' .. tools.uuid() self.player_num = nil self.player_data = nil self.game_id = nil end ---Get the `Client`/Player identifier. -- @treturn string player_id. function Client:getId() return self.player_id end --- Set the players connection handle. -- @tparam string player_handle The `Client`/Players name. -- @usage client:setPlayerHandle( "player-handle" ) -- @local function Client:_setPlayerHandle( player_handle ) if not player_handle then self.player_handle = 'users' .. tools.uuid() else self.player_handle = player_handle end end --- Gets the players connection handle. -- This can represent a name, or any other identifier. -- @treturn string The `Client`/Players name. -- @usage local player_handle = client:getPlayerHandle() function Client:getPlayerHandle() return self.player_handle end --- Get the players game position number. -- @treturn int `Client`/Player position. -- @usage local player_num = client:getPlayerNum() function Client:getPlayerNum() return self.player_num end --- Get the players game identifier. -- @treturn string The game id the player belongs to. -- @usage local game_id = client:getGameId() function Client:getGameId() return self.game_id end --- Checks to see if the `Client`/Player is in a `Game` -- @treturn boolean -- @usage local in_game = client:isInGame() function Client:isInGame() if self.game_id then return true end return false end --- Get the client host address. -- @treturn string Host address. -- @usage local host_addr = client:getHost() function Client:getHost() if self.client then return self.client:address().address end end --- Get the client port. -- @treturn int Port number. -- @usage local port_num = client:getPort() function Client:getPort() if self.client then return self.client:address().port end end --- Set the Client timeout. -- @tparam int seconds The seconds before timeout occurs. -- @usage client:setTimeout( 300 ) function Client:setTimeout( seconds ) if self.client then self.client:setTimeout( ( 1000 * seconds ) ) end end ---Set the players custom data table. -- -- You should be sure to get the current data table -- using `getPlayerData` and make your changes -- on that table before using this method. -- @tparam table data The player data table to save/update. -- @usage --== Get the current player data -- local pd = client:getPlayerData() -- --== Do work -- pb.fav_color = "Red" -- --== Store it -- client:setPlayerData( pb ) -- --== Clear player data -- client:setPlayerData( {} ) function Client:setPlayerData( data ) if data then self.player_data = data end end --- Get the players custom data table. -- Custom data can be included at connection time -- or during runtime by using `setPlayerData`. -- @treturn[1] table The custom `Client`/Player data. -- @return[2] nil function Client:getPlayerData() return self.player_data end function Client:_handleData( data ) local inputs = {} table.insert( inputs, data ) for i, chunk in ipairs( inputs ) do local s,f = chunk:find("<<END>>") if s then local d = self.buffer .. chunk:sub(1,s-1) local reply = self:json2tbl( d ) if reply then if reply._ping then self:send( { _pong = 1, ts = reply.ts } ) --return pong else --== Internals self:emit( "ClientData", self.client, reply ) end end self.buffer = "" else self.buffer = self.buffer .. chunk end end end --- Send data to the Client. -- @tparam table data_tbl A table of data to send. -- @usage client:send( { points = 12, update = 1 } ) function Client:send( data_tbl ) local data = self:tbl2json( data_tbl ) if data then if self.client.writable then return self.client:write( data .. "\r\n" ) end end return nil end --- Destroy the client connection. -- You normally let the system handle -- the socket closing. This will close -- the connection without delay and end -- the game. __The engine automatically handles the client closing. This can be used for custom functionality__. -- @usage client:destroy() -- @local function Client:destroy() self.client:destroy() end --- Check if the client socket can send data. -- __Usually used for custom functionality__. -- @usage local is_writable = client:isWritable() -- @local function Client:isWritable() return self.client.writable end --- Convert a Lua table to JSON string. -- __Usually used for custom functionality__. -- @tparam table tbl The table to convert. -- @treturn string The JSON string result. -- @local function Client:tbl2json( tbl ) local success, result = pcall( json.stringify, tbl ) if success then return result end return nil end --- Convert a JSON string to a Lua table. -- __Usually used for custom functionality__. -- @tparam string str The JSON string to convert. -- @treturn table The Lua table result. -- @local function Client:json2tbl( str ) local success, result = pcall( json.parse, str ) if success then return result end return nil end --== Return Class return Client
p = Plane(0,1,0) p.col = "#111111" v:add(p) cube = Cube() cube.pos = btVector3(0, 0.5, 0); cube.col = "#ff0000" v:add(cube) v:preDraw(function(n) -- print(n) i = n / 100 * math.pi * 2 r = 8 z = 8 cam = Cam() cam.pos = btVector3( r*math.sin(i), z, r*math.cos(i)) cam.look = btVector3(0,1,0) v:cam(cam) end) -- All callback functions: -- * v:preDraw(function) called about 25 times / sec. -- * v:postDraw(function) called 25 times / sec. -- * v:preSim(function) called before every simulation step. -- * v:postSim(function) called after every simulation step.
__nowaiting = true -- If you turn this flag off, cluster.call would block when node name is absent db = "127.0.0.1:2528" db2 = "127.0.0.1:2529"
local stub = require('luassert.stub') describe('utils.isfile()', function() local isfile = require('utils.isfile') describe('when the file does not exist', function() before_each(function() stub(vim.loop, 'fs_stat', function() return nil end) end) it('returns false', function() assert.is_false(isfile('foo.md')) end) end) describe('when the file does exist', function() before_each(function() stub(vim.loop, 'fs_stat', function() return { type = true } end) end) it('returns true', function() assert.is_true(isfile('foo.md')) end) end) end)
-- mods/default/nodes.lua --[[ Node name convention: Although many node names are in combined-word form, the required form for new node names is words separated by underscores. If both forms are used in written language (for example pinewood and pine wood) the underscore form should be used. --]] --[[ Index: Stone ----- (1. Material 2. Cobble variant 3. Brick variant 4. Modified forms) default:stone default:cobble default:stonebrick default:stone_block default:mossycobble default:desert_stone default:desert_cobble default:desert_stonebrick default:desert_stone_block default:sandstone default:sandstonebrick default:sandstone_block default:desert_sandstone default:desert_sandstone_brick default:desert_sandstone_block default:silver_sandstone default:silver_sandstone_brick default:silver_sandstone_block default:obsidian default:obsidianbrick default:obsidian_block Soft / Non-Stone ---------------- (1. Material 2. Modified forms) default:dirt default:dirt_with_grass default:dirt_with_grass_footsteps default:dirt_with_dry_grass default:dirt_with_snow default:dirt_with_rainforest_litter default:dirt_with_coniferous_litter default:sand default:desert_sand default:silver_sand default:gravel default:clay default:snow default:snowblock default:ice Trees ----- (1. Trunk 2. Fabricated trunk 3. Leaves 4. Sapling 5. Fruits) default:tree default:wood default:leaves default:sapling default:apple default:jungletree default:junglewood default:jungleleaves default:junglesapling default:pine_tree default:pine_wood default:pine_needles default:pine_sapling default:acacia_tree default:acacia_wood default:acacia_leaves default:acacia_sapling default:aspen_tree default:aspen_wood default:aspen_leaves default:aspen_sapling Ores ---- (1. In stone 2. Blocks) default:stone_with_coal default:coalblock default:stone_with_iron default:steelblock default:stone_with_copper default:copperblock default:stone_with_tin default:tinblock default:bronzeblock default:stone_with_gold default:goldblock default:stone_with_mese default:mese default:stone_with_diamond default:diamondblock Plantlife --------- default:cactus default:papyrus default:dry_shrub default:junglegrass default:grass_1 default:grass_2 default:grass_3 default:grass_4 default:grass_5 default:dry_grass_1 default:dry_grass_2 default:dry_grass_3 default:dry_grass_4 default:dry_grass_5 default:fern_1 default:fern_2 default:fern_3 default:bush_stem default:bush_leaves default:bush_sapling default:acacia_bush_stem default:acacia_bush_leaves default:acacia_bush_sapling default:sand_with_kelp Corals ------ default:coral_brown default:coral_orange default:coral_skeleton Liquids ------- (1. Source 2. Flowing) default:water_source default:water_flowing default:river_water_source default:river_water_flowing default:lava_source default:lava_flowing Tools / "Advanced" crafting / Non-"natural" ------------------------------------------- default:chest default:chest_locked default:bookshelf default:sign_wall_wood default:sign_wall_steel default:ladder_wood default:ladder_steel default:fence_wood default:fence_acacia_wood default:fence_junglewood default:fence_pine_wood default:fence_aspen_wood default:glass default:obsidian_glass default:brick default:meselamp default:mese_post_light Misc ---- default:cloud --]] minetest.register_node("default:kinzoku_block", { description = "Stone", tiles = {"default_kinzoku_block.png"}, groups = {cracky = 1, level = 2}, is_ground_content = false, light_source = 4, paramtype = "light", sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:steelblock", { description = "Steel Block", tiles = {"default_steel_block.png"}, is_ground_content = false, groups = {cracky = 1, level = 2}, sounds = default.node_sound_metal_defaults(), }) minetest.register_node("default:apple", { description = "Apple", --drawtype = "plantlike", drawtype = "nodebox", node_box = { type = "fixed", fixed = {-0.5, -0.5, 0, 0, 0, 0.5} }, --tiles = {"default_apple.png"}, tiles = {"default_steel_block.png^[colorize:#FF0000:200"}, --inventory_image = "default_apple.png", paramtype = "light", sunlight_propagates = true, walkable = false, is_ground_content = false, selection_box = { type = "fixed", fixed = {-0.5, -0.5, 0, 0, 0, 0.5} }, groups = {fleshy = 3, dig_immediate = 3, flammable = 2, leafdecay = 3, leafdecay_drop = 1, dig_by_water = 1}, on_use = minetest.item_eat(2), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer, itemstack) minetest.set_node(pos, {name = "default:apple", param2 = 1}) end, }) -- -- Liquids -- minetest.register_node("default:water_source", { description = "Water Source", drawtype = "liquid", tiles = { { --name = "default_water_source_animated.png", name = "default_steel_block.png^[colorize:#015dbb70", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, }, }, special_tiles = { -- New-style water source material (mostly unused) { --name = "default_water_source_animated.png", name = "default_steel_block.png^[colorize:#015dbb70", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, backface_culling = false, }, }, alpha = 160, paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = 1, post_effect_color = {a = 103, r = 30, g = 60, b = 90}, groups = {water = 3, liquid = 3, puts_out_fire = 1, cools_lava = 1}, sounds = default.node_sound_water_defaults(), }) minetest.register_node("default:water_flowing", { description = "Flowing Water", drawtype = "flowingliquid", tiles = {"default_water.png"}, special_tiles = { { --name = "default_water_flowing_animated.png", name = "default_steel_block.png^[colorize:#015dbb70", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, { --name = "default_water_flowing_animated.png", name = "default_steel_block.png^[colorize:#015dbb70", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, }, alpha = 160, paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = 1, post_effect_color = {a = 103, r = 30, g = 60, b = 90}, groups = {water = 3, liquid = 3, puts_out_fire = 1, not_in_creative_inventory = 1, cools_lava = 1}, sounds = default.node_sound_water_defaults(), }) minetest.register_node("default:lava_source", { description = "Lava Source", drawtype = "liquid", tiles = { { --name = "default_lava_source_animated.png", name = "default_steel_block.png^[colorize:#FFBB00:200", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, special_tiles = { -- New-style lava source material (mostly unused) { --name = "default_lava_source_animated.png", name = "default_steel_block.png^[colorize:#FFBB00:200", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, backface_culling = false, }, }, paramtype = "light", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a = 191, r = 255, g = 64, b = 0}, groups = {lava = 3, liquid = 2, igniter = 1}, }) minetest.register_node("default:lava_flowing", { description = "Flowing Lava", drawtype = "flowingliquid", tiles = {"default_lava.png"}, special_tiles = { { --name = "default_lava_flowing_animated.png", name = "default_steel_block.png^[colorize:#FFBB00:200", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, { --name = "default_lava_flowing_animated.png", name = "default_steel_block.png^[colorize:#FFBB00:200", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, }, paramtype = "light", paramtype2 = "flowingliquid", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a = 191, r = 255, g = 64, b = 0}, groups = {lava = 3, liquid = 2, igniter = 1, not_in_creative_inventory = 1}, }) -- -- Tools / "Advanced" crafting / Non-"natural" -- default.chest = {} function default.chest.get_chest_formspec(pos) local spos = pos.x .. "," .. pos.y .. "," .. pos.z local formspec = "size[8,9]" .. default.gui_bg .. default.gui_bg_img .. default.gui_slots .. "list[nodemeta:" .. spos .. ";main;0,0.3;8,4;]" .. "list[current_player;main;0,4.85;8,1;]" .. "list[current_player;main;0,6.08;8,3;8]" .. "listring[nodemeta:" .. spos .. ";main]" .. "listring[current_player;main]" .. default.get_hotbar_bg(0,4.85) return formspec end function default.chest.chest_lid_obstructed(pos) local above = {x = pos.x, y = pos.y + 1, z = pos.z} local def = minetest.registered_nodes[minetest.get_node(above).name] -- allow ladders, signs, wallmounted things and torches to not obstruct if def and (def.drawtype == "airlike" or def.drawtype == "signlike" or def.drawtype == "torchlike" or (def.drawtype == "nodebox" and def.paramtype2 == "wallmounted")) then return false end return true end function default.chest.chest_lid_close(pn) local chest_open_info = default.chest.open_chests[pn] local pos = chest_open_info.pos local sound = chest_open_info.sound local swap = chest_open_info.swap default.chest.open_chests[pn] = nil for k, v in pairs(default.chest.open_chests) do if v.pos.x == pos.x and v.pos.y == pos.y and v.pos.z == pos.z then return true end end local node = minetest.get_node(pos) minetest.after(0.2, minetest.swap_node, pos, { name = "default:" .. swap, param2 = node.param2 }) minetest.sound_play(sound, {gain = 0.3, pos = pos, max_hear_distance = 10}) end default.chest.open_chests = {} minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "default:chest" then return end if not player or not fields.quit then return end local pn = player:get_player_name() if not default.chest.open_chests[pn] then return end default.chest.chest_lid_close(pn) return true end) minetest.register_on_leaveplayer(function(player) local pn = player:get_player_name() if default.chest.open_chests[pn] then default.chest.chest_lid_close(pn) end end) function default.chest.register_chest(name, d) local def = table.copy(d) def.drawtype = "mesh" def.visual = "mesh" def.paramtype = "light" def.paramtype2 = "facedir" def.legacy_facedir_simple = true def.is_ground_content = false if def.protected then def.on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", "Locked Chest") meta:set_string("owner", "") local inv = meta:get_inventory() inv:set_size("main", 8*4) end def.after_place_node = function(pos, placer) local meta = minetest.get_meta(pos) meta:set_string("owner", placer:get_player_name() or "") meta:set_string("infotext", "Locked Chest (owned by " .. meta:get_string("owner") .. ")") end def.can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("main") and default.can_interact_with_node(player, pos) end def.allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) if not default.can_interact_with_node(player, pos) then return 0 end return count end def.allow_metadata_inventory_put = function(pos, listname, index, stack, player) if not default.can_interact_with_node(player, pos) then return 0 end return stack:get_count() end def.allow_metadata_inventory_take = function(pos, listname, index, stack, player) if not default.can_interact_with_node(player, pos) then return 0 end return stack:get_count() end def.on_rightclick = function(pos, node, clicker, itemstack, pointed_thing) if not default.can_interact_with_node(clicker, pos) then return itemstack end minetest.sound_play(def.sound_open, {gain = 0.3, pos = pos, max_hear_distance = 10}) if not default.chest.chest_lid_obstructed(pos) then minetest.swap_node(pos, { name = "default:" .. name .. "_open", param2 = node.param2 }) end minetest.after(0.2, minetest.show_formspec, clicker:get_player_name(), "default:chest", default.chest.get_chest_formspec(pos)) default.chest.open_chests[clicker:get_player_name()] = { pos = pos, sound = def.sound_close, swap = name } end def.on_blast = function() end def.on_key_use = function(pos, player) local secret = minetest.get_meta(pos):get_string("key_lock_secret") local itemstack = player:get_wielded_item() local key_meta = itemstack:get_meta() if key_meta:get_string("secret") == "" then key_meta:set_string("secret", minetest.parse_json(itemstack:get_metadata()).secret) itemstack:set_metadata("") end if secret ~= key_meta:get_string("secret") then return end minetest.show_formspec( player:get_player_name(), "default:chest_locked", default.chest.get_chest_formspec(pos) ) end def.on_skeleton_key_use = function(pos, player, newsecret) local meta = minetest.get_meta(pos) local owner = meta:get_string("owner") local pn = player:get_player_name() -- verify placer is owner of lockable chest if owner ~= pn then minetest.record_protection_violation(pos, pn) minetest.chat_send_player(pn, "You do not own this chest.") return nil end local secret = meta:get_string("key_lock_secret") if secret == "" then secret = newsecret meta:set_string("key_lock_secret", secret) end return secret, "a locked chest", owner end else def.on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("infotext", "Chest") local inv = meta:get_inventory() inv:set_size("main", 8*4) end def.can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("main") end def.on_rightclick = function(pos, node, clicker) minetest.sound_play(def.sound_open, {gain = 0.3, pos = pos, max_hear_distance = 10}) if not default.chest.chest_lid_obstructed(pos) then minetest.swap_node(pos, { name = "default:" .. name .. "_open", param2 = node.param2 }) end minetest.after(0.2, minetest.show_formspec, clicker:get_player_name(), "default:chest", default.chest.get_chest_formspec(pos)) default.chest.open_chests[clicker:get_player_name()] = { pos = pos, sound = def.sound_close, swap = name } end def.on_blast = function(pos) local drops = {} default.get_inventory_drops(pos, "main", drops) drops[#drops+1] = "default:" .. name minetest.remove_node(pos) return drops end end def.on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name() .. " moves stuff in chest at " .. minetest.pos_to_string(pos)) end def.on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " moves " .. stack:get_name() .. " to chest at " .. minetest.pos_to_string(pos)) end def.on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name() .. " takes " .. stack:get_name() .. " from chest at " .. minetest.pos_to_string(pos)) end local def_opened = table.copy(def) local def_closed = table.copy(def) def_opened.mesh = "chest_open.obj" for i = 1, #def_opened.tiles do if type(def_opened.tiles[i]) == "string" then def_opened.tiles[i] = {name = def_opened.tiles[i], backface_culling = true} elseif def_opened.tiles[i].backface_culling == nil then def_opened.tiles[i].backface_culling = true end end def_opened.drop = "default:" .. name def_opened.groups.not_in_creative_inventory = 1 def_opened.selection_box = { type = "fixed", fixed = { -1/2, -1/2, -1/2, 1/2, 3/16, 1/2 }, } def_opened.can_dig = function() return false end def_opened.on_blast = function() end def_closed.mesh = nil def_closed.drawtype = nil def_closed.tiles[6] = def.tiles[5] -- swap textures around for "normal" def_closed.tiles[5] = def.tiles[3] -- drawtype to make them match the mesh def_closed.tiles[3] = def.tiles[3].."^[transformFX" minetest.register_node("default:" .. name, def_closed) minetest.register_node("default:" .. name .. "_open", def_opened) -- convert old chests to this new variant minetest.register_lbm({ label = "update chests to opening chests", name = "default:upgrade_" .. name .. "_v2", nodenames = {"default:" .. name}, action = function(pos, node) local meta = minetest.get_meta(pos) meta:set_string("formspec", nil) local inv = meta:get_inventory() local list = inv:get_list("default:chest") if list then inv:set_size("main", 8*4) inv:set_list("main", list) inv:set_list("default:chest", nil) end end }) end default.chest.register_chest("chest", { description = "Chest", tiles = { "default_chest_top.png", "default_chest_top.png", "default_chest_side.png", "default_chest_side.png", "default_chest_front.png", "default_chest_inside.png" }, sounds = default.node_sound_wood_defaults(), sound_open = "default_chest_open", sound_close = "default_chest_close", groups = {choppy = 2, oddly_breakable_by_hand = 2}, }) default.chest.register_chest("chest_locked", { description = "Locked Chest", tiles = { "default_chest_top.png", "default_chest_top.png", "default_chest_side.png", "default_chest_side.png", "default_chest_lock.png", "default_chest_inside.png" }, sounds = default.node_sound_wood_defaults(), sound_open = "default_chest_open", sound_close = "default_chest_close", groups = {choppy = 2, oddly_breakable_by_hand = 2}, protected = true, }) local function register_sign(material, desc, def) minetest.register_node("default:sign_wall_" .. material, { description = desc .. " Sign", drawtype = "nodebox", tiles = {"default_sign_wall_" .. material .. ".png"}, inventory_image = "default_sign_" .. material .. ".png", wield_image = "default_sign_" .. material .. ".png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, is_ground_content = false, walkable = false, node_box = { type = "wallmounted", wall_top = {-0.4375, 0.4375, -0.3125, 0.4375, 0.5, 0.3125}, wall_bottom = {-0.4375, -0.5, -0.3125, 0.4375, -0.4375, 0.3125}, wall_side = {-0.5, -0.3125, -0.4375, -0.4375, 0.3125, 0.4375}, }, groups = def.groups, legacy_wallmounted = true, sounds = def.sounds, on_construct = function(pos) --local n = minetest.get_node(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", "field[text;;${text}]") end, on_receive_fields = function(pos, formname, fields, sender) --print("Sign at "..minetest.pos_to_string(pos).." got "..dump(fields)) local player_name = sender:get_player_name() if minetest.is_protected(pos, player_name) then minetest.record_protection_violation(pos, player_name) return end local meta = minetest.get_meta(pos) if not fields.text then return end minetest.log("action", (player_name or "") .. " wrote \"" .. fields.text .. "\" to sign at " .. minetest.pos_to_string(pos)) meta:set_string("text", fields.text) meta:set_string("infotext", '"' .. fields.text .. '"') end, }) end register_sign("steel", "Steel", { sounds = default.node_sound_wood_defaults(), groups = {choppy = 2, attached_node = 1, flammable = 2, oddly_breakable_by_hand = 3} }) minetest.register_node("default:ladder_steel", { description = "Steel Ladder", drawtype = "signlike", tiles = {"default_ladder_steel.png"}, inventory_image = "default_ladder_steel.png", wield_image = "default_ladder_steel.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, climbable = true, is_ground_content = false, selection_box = { type = "wallmounted", --wall_top = = <default> --wall_bottom = = <default> --wall_side = = <default> }, groups = {choppy = 2, oddly_breakable_by_hand = 3, flammable = 2}, legacy_wallmounted = true, sounds = default.node_sound_metal_defaults(), }) default.register_fence("default:fence_steel", { description = "Steel Fence", texture = "default_fence_steel.png", inventory_image = "default_fence_overlay.png^default_steel_block.png^default_fence_overlay.png^[makealpha:255,126,126", wield_image = "default_fence_overlay.png^default_steel_block.png^default_fence_overlay.png^[makealpha:255,126,126", material = "default:steelblock", groups = {choppy = 2, oddly_breakable_by_hand = 2, flammable = 2}, sounds = default.node_sound_wood_defaults() })
------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Debugger using DBGp protocol. ------------------------------------------------------------------------------- -- The module returns a single init function which takes 6 parameters (IDEHOST, IDEPORT, IDEKEY, TRANSPORT, PLATFORM, WORKINGDIR). -- -- IDEHOST: the host name or the ip address of the DBGP server (so your ide) -- if HOST is nil, the DBGP_IDEHOST env var is used. -- if the env var is nil, the default value '127.0.0.1' is used. -- -- IDEPORT: the port of the DBGP server (must be configure in the IDE) -- if PORT is nil, the DBGP_IDEPORT env var is used. -- if the env var is nil, the default value '10000' is used. -- -- IDEIDEKEY: a string which is used as session key -- if IDEKEY is nil, the DBGP_IDEKEY env var is used. -- if the env var is nil, the default value 'luaidekey' is used. -- -- TRANSPORT: (advanced optional parameter) the module name of which implement the transport interface used to do the connection with the server. -- by default the debugger use an internal implementation based on luasocket, but if can not use it, you could implement or use another transport layer implementation. -- if TRANSPORT is nil, the DBGP_TRANSPORT env var is used. -- if the env var is nil, the default value 'debugger.transport.luasocket' is used : this is the default implementation based on luasocket. -- -- PLATFORM: (advanced optional parameter) 'unix' or 'win32' string which define the kind of platform on which the program to debug is executed. -- by default the debugger will try to guess it and surely success, if for some reasons it fails you could help it by precise the execution platform. -- if PLATFORM is nil, the DBGP_PLATFORM env var is used. -- if the env var is nil, the debugger will try to guess it. -- -- WORKINGDIR: (advanced optional parameter) the working directory in which the program to debug is executed. -- by default the debugger will try to guess it and surely success, if for some reasons it fails you could help it by precise the working directory. -- if WORKINGDIR is nil, the DBGP_WORKINGDIR env var is used. -- if the env var is nil, the debugger will try to guess it. -- ------------------------------------------------------------------------------- -- Known Issues: -- * Functions cannot be created using the debugger and then called in program because their environment is mapped directly to -- a debugger internal structure which cannot be persisted (i.e. used outside of the debug_hook). -- * The DLTK client implementation does not handle context for properties. As a workaround, the context is encoded into the -- fullname attribute of each property and is used likewise in property_get commands. The syntax is "<context ID>|<full name>" -- * Dynamic code (compiled with load or loadstring) is not handled (the debugger will step over it, like C code) -- Design notes: -- * The whole debugger state is kept in a (currently) unique session table in order to ease eventual adaptation to a multi-threaded -- model, as DBGp needs one connection per thread. -- * Full names of properties are base64 encoded because they can contain arbitrary data (spaces, escape characters, ...), this makes -- command parsing munch easier and faster -- * This debugger supports asynchronous commands: any command can be done at any time, but some of them (continuations) can lead to -- inconsistent states. In addition, this have a quite big overhead (~66%), if performance is an issue, a custom command to disable -- async mode could be done. -- * All commands are implemented in table commands, see this comments on this table to additional details about commands implementation -- * The environments in which are evaluated user code (property_* and eval commands, conditional breakpoints, ...) is a read/write -- mapping of the local environment of a given stack level (can be accessed with variable names). See Context for additional details. -- Context instantiation is pooled inside a debugging loop with ContextManager (each stack level is instantiated only once). -- * Output redirection is done by redefining print and some values inside the io table. See "Output redirection handling" for details. -- Todo list: -- * Override I/O in init function instead of on module loading. -- * Allow to break programatically (debugger.break()). -- * Break-on-error feature (break if an error is thrown and there is no pcall in stack to handle it). -- * Use new 5.2 facilities to provide informations about function (arguments names, vararg, ...) -- * Allow to see ... content for vararg functions (5.2 only) -- * Inspect LuaJIT C data (http://lua-users.org/lists/lua-l/2011-02/msg01012.html)-- /!\ This file is auto-generated. Do not alter manually /!\ -------------------------------------------------------------------------------- -- Submodules body -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.transport.apr package.preload["debugger.transport.apr"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Apache Portable Runtime backend for DBGP debugger. ------------------------------------------------------------------------------- local apr = require "apr" -- base 64 wrapping function b64_wrap(src) t = {} local b64_src = mime.b64(src) for i=1, #b64_src, 76 do t[#t+1] = b64_src:sub(i, i+75).."\r\n" end return table.concat(t) end -- implements a subset of LuaSocket API using APR local SOCKET_MT = { connect = function(self, address, port) return self.skt:connect(address, port) end, receive = function(self, n) return self.skt:read(n) end, -- only numeric read is used send = function(self, data) return self.skt:write(data) end, close = function(self) return self.skt:close() end, settimeout = function(self, sec) if sec == nil then self.skt:timeout_set(true) elseif sec == 0 then self.skt:timeout_set(false) else self.skt:timeout_set(math.floor(sec * 1000000)) end end } SOCKET_MT.__index = SOCKET_MT return { create = function() local skt, err = apr.socket_create('tcp') if not skt then return nil, err end return setmetatable({skt = skt}, SOCKET_MT) end, sleep = apr.sleep, -- exact same API as LuaSocket -- Base64 related functions --- Encodes a string into Base64 with line wrapping -- @param data (string) data to encode -- @return base64 encoded string b64 = function(data) t = {} local b64_data = apr.base64_encode(data) for i=1, #b64_data, 76 do t[#t+1] = b64_data:sub(i, i+75).."\r\n" end return table.concat(t) end, --- Encodes a string into Base64, without any extra parsing (wrapping, ...) -- @param data (string) data to encode -- @return decoded string rawb64 = apr.base64_encode, --- Decodes base64 data -- @param data (string) base64 encoded data -- @return decoded string unb64 = apr.base64_decode, } end -------------------------------------------------------------------------------- -- End of moduledebugger.transport.apr -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.transport.luasocket package.preload["debugger.transport.luasocket"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- LuaSocket backend for DBGP debugger. ------------------------------------------------------------------------------- -- in order to be as lightweight as possible with Luasocket, core API is used -- directly (to no add yet another layer) --FIXME: remove this hack as soon as luasocket officially support 5.2 if _VERSION == "Lua 5.2" then table.getn = function(t) return t and #t end end local socket = require "socket" local mime = require "mime" local ltn12 = require "ltn12" local reg = debug.getregistry() return { create = socket.tcp, sleep = socket.sleep, -- Base64 related functions --- Encodes a string into Base64 with line wrapping -- @param data (string) data to encode -- @return base64 encoded string b64 = function(data) local filter = ltn12.filter.chain(mime.encode("base64"), mime.wrap("base64")) local sink, output = ltn12.sink.table() ltn12.pump.all(ltn12.source.string(data), ltn12.sink.chain(filter, sink)) return table.concat(output) end, --- Encodes a string into Base64, without any extra parsing (wrapping, ...) -- @param data (string) data to encode -- @return decoded string rawb64 = function(data) return (mime.b64(data)) -- first result of the low-level function is fine here end, --- Decodes base64 data -- @param data (string) base64 encoded data -- @return decoded string unb64 = function(data) return (mime.unb64(data)) -- first result of the low-level function is fine here end, } end -------------------------------------------------------------------------------- -- End of moduledebugger.transport.luasocket -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.transport.luasocket_sched package.preload["debugger.transport.luasocket_sched"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- LuaSocket with LuaSched backend for DBGP debugger. ------------------------------------------------------------------------------- -- As LuaShed totally hides blocking functions, this module MUST be loaded on the very start of the program -- (before loading sched) to catch references to blocking functions. local socketcore = require"socket.core" local debug = require "debug" local reg = debug.getregistry() local blockingcreate = socketcore.tcp local blockingsleep = socketcore.sleep local blockingconnect = reg["tcp{master}"].__index.connect local blockingreceive = reg["tcp{client}"].__index.receive local blockingsend = reg["tcp{client}"].__index.send local blockingsettimeout = reg["tcp{master}"].__index.settimeout local blockingclose = reg["tcp{master}"].__index.close -- we cannot set a new metatable directly on socket object, so wrap it into a new table -- and forward all calls. local blockingtcp = { connect = function(self, address, port) return blockingconnect(self.skt, address, port) end, receive = function(self, n) return blockingreceive(self.skt, n) end, send = function(self, data) return blockingsend(self.skt, data) end, settimeout = function(self, sec) return blockingsettimeout(self.skt, sec) end, close = function(self) return blockingclose(self.skt) end, } blockingtcp.__index = blockingtcp local mime = require "mime" local ltn12 = require "ltn12" -- verify that the socket function are the real ones and not sched not blocking versions assert(debug.getinfo(blockingcreate, "S").what == "C", "The debugger needs the real socket functions !") -- cleanup the package.loaded table (socket.core adds socket field into it) package.loaded.socket = nil return { create = function() return setmetatable({ skt = blockingcreate() }, blockingtcp) end, sleep = blockingsleep, -- Base64 related functions --- Encodes a string into Base64 with line wrapping -- @param data (string) data to encode -- @return base64 encoded string b64 = function(data) local filter = ltn12.filter.chain(mime.encode("base64"), mime.wrap("base64")) local sink, output = ltn12.sink.table() ltn12.pump.all(ltn12.source.string(data), ltn12.sink.chain(filter, sink)) return table.concat(output) end, --- Encodes a string into Base64, without any extra parsing (wrapping, ...) -- @param data (string) data to encode -- @return decoded string rawb64 = function(data) return (mime.b64(data)) -- first result of the low-level function is fine here end, --- Decodes base64 data -- @param data (string) base64 encoded data -- @return decoded string unb64 = function(data) return (mime.unb64(data)) -- first result of the low-level function is fine here end, } end -------------------------------------------------------------------------------- -- End of moduledebugger.transport.luasocket_sched -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.commands package.preload["debugger.commands"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Commands handlers for DBGp protocol. ------------------------------------------------------------------------------- -- Debugger command functions. Each function handle a different command. -- A command function is called with 3 arguments -- 1. the debug session instance -- 2. the command arguments as table -- 3. the command data, if any -- The result is either : -- * true (or any value evaluated to true) : the debugger will resume the execution of the application (continuation command) -- * false : only in async mode, the debugger WILL wait for further commands instead of continuing (typically, break command) -- * nil/no return : in sync mode, the debugger will wait for another command. In async mode the debugger will continue the execution local cowrap, coyield = coroutine.wrap, coroutine.yield local debug = require "debug" local core = require "debugger.core" local dbgp = require "debugger.dbgp" local util = require "debugger.util" local platform = require "debugger.platform" local introspection = require "debugger.introspection" local context = require "debugger.context" local log = util.log local M = { } -- command handlers table --- Gets the coroutine behind an id -- Throws errors on unknown identifiers -- @param coro_id (string or nil) Coroutine identifier or nil (current coroutine) -- @return Coroutine instance or nil (if coro_id was nil or if coroutine is the current coroutine) local function get_coroutine(self, coro_id) if coro_id then local coro = dbgp.assert(399, core.active_coroutines.from_id[tonumber(coro_id)], "No such coroutine") dbgp.assert(399, coroutine.status(coro) ~= "dead", "Coroutine is dead") if coro ~= self.coro[1] then return util.ForeignThread(coro) end end return self.coro end M["break"] = function(self, args) self.state = "break" -- send response to previous command core.previous_context_response(self) -- and then response to break command itself dbgp.send_xml(self.skt, { tag = "response", attr = { command = "break", transaction_id = args.i, success = 1 } } ) return false end function M.status(self, args) dbgp.send_xml(self.skt, { tag = "response", attr = { command = "status", reason = "ok", status = self.state, transaction_id = args.i } } ) end function M.stop(self, args) dbgp.send_xml(self.skt, { tag = "response", attr = { command = "stop", reason = "ok", status = "stopped", transaction_id = args.i } } ) self.skt:close() os.exit(1) end function M.feature_get(self, args) local name = args.n local response = util.features[name] or (not not M[name]) dbgp.send_xml(self.skt, { tag = "response", attr = { command = "feature_get", feature_name = name, supported = response and "1" or "0", transaction_id = args.i }, tostring(response) } ) end function M.feature_set(self, args) local name, value = args.n, args.v local success = pcall(function() util.features[name] = value end) dbgp.send_xml(self.skt, { tag = "response", attr = { command = "feature_set", feature = name, success = success and 1 or 0, transaction_id = args.i } } ) end function M.typemap_get(self, args) local function gentype(name, type, xsdtype) return { tag = "map", atts = { name = name, type = type, ["xsi:type"] = xsdtype } } end dbgp.send_xml(self.skt, { tag = "response", attr = { command = "typemap_get", transaction_id = args.i, ["xmlns:xsi"] = "http://www.w3.org/2001/XMLSchema-instance", ["xmlns:xsd"] = "http://www.w3.org/2001/XMLSchema", }, gentype("nil", "null"), gentype("boolean", "bool", "xsd:boolean"), gentype("number", "float", "xsd:float"), gentype("string", "string", "xsd:string"), gentype("function", "resource"), gentype("userdata", "resource"), gentype("thread", "resource"), gentype("table", "hash"), gentype("sequence", "array"), -- artificial type to represent sequences (1-n continuous indexes) gentype("multival", "array"), -- used to represent return values } ) end function M.run(self) return true end function M.step_over(self) core.events.register("over") return true end function M.step_out(self) core.events.register("out") return true end function M.step_into(self) core.events.register("into") return true end function M.eval(self, args, data) log("DEBUG", "Going to eval "..data) local result, err, success local env = self.stack(self.coro, 0) -- first, try to load as expression -- DBGp does not support stack level here, see http://bugs.activestate.com/show_bug.cgi?id=81178 local func, err = util.loadin("return "..data, env) -- if it is not an expression, try as statement (assignment, ...) if not func then func, err = util.loadin(data, env) end if func then success, result = pcall(function() return introspection.Multival(func()) end) if not success then err = result end end local response = { tag = "response", attr = { command = "eval", transaction_id = args.i } } if not err then response.attr.success = 1 -- As of Lua 5.1, the maximum stack size (and result count) is 8000, this limit is used to fit all results in one page response[1] = introspection.make_property(0, result, data, "", 1, 8000, 0, nil) else response.attr.success = 0 response[1] = dbgp.make_error(206, err) end dbgp.send_xml(self.skt, response) end function M.breakpoint_set(self, args, data) if args.o and not core.breakpoints.hit_conditions[args.o] then dbgp.error(200, "Invalid hit_condition operator: "..args.o) end local filename, lineno = args.f, tonumber(args.n) local bp = { type = args.t, state = args.s or "enabled", temporary = args.r == "1", -- "0" or nil makes this property false hit_count = 0, filename = filename, lineno = lineno, hit_value = tonumber(args.h or 0), hit_condition = args.o or ">=", } if args.t == "conditional" then bp.expression = data -- the expression is compiled only once bp.condition = dbgp.assert(207, loadstring("return (" .. data .. ")")) elseif args.t ~= "line" then dbgp.error(201, "BP type " .. args.t .. " not yet supported") end local bpid = core.breakpoints.insert(bp) dbgp.send_xml(self.skt, { tag = "response", attr = { command = "breakpoint_set", transaction_id = args.i, state = bp.state, id = bpid } } ) end function M.breakpoint_get(self, args) dbgp.send_xml(self.skt, { tag = "response", attr = { command = "breakpoint_get", transaction_id = args.i }, dbgp.assert(205, core.breakpoints.get_xml(tonumber(args.d))) }) end function M.breakpoint_list(self, args) local bps = { tag = "response", attr = { command = "breakpoint_list", transaction_id = args.i } } for id, bp in pairs(core.breakpoints.get()) do bps[#bps + 1] = core.breakpoints.get_xml(id) end dbgp.send_xml(self.skt, bps) end function M.breakpoint_update(self, args) local bp = core.breakpoints.get(tonumber(args.d)) if not bp then dbgp.error(205, "No such breakpint "..args.d) end if args.o and not core.breakpoints.hit_conditions[args.o] then dbgp.error(200, "Invalid hit_condition operator: "..args.o) end local response = { tag = "response", attr = { command = "breakpoint_update", transaction_id = args.i } } bp.state = args.s or bp.state bp.lineno = tonumber(args.n or bp.lineno) bp.hit_value = tonumber(args.h or bp.hit_value) bp.hit_condition = args.o or bp.hit_condition dbgp.send_xml(self.skt, response) end function M.breakpoint_remove(self, args) local response = { tag = "response", attr = { command = "breakpoint_remove", transaction_id = args.i } } if not core.breakpoints.remove(tonumber(args.d)) then dbgp.error(205, "No such breakpint "..args.d) end dbgp.send_xml(self.skt, response) end function M.stack_depth(self, args) local depth = 0 local coro = get_coroutine(self, args.o) for level = 0, math.huge do local info = coro:getinfo(level, "St") if not info then break end -- end of stack depth = depth + 1 if info.istailcall then depth = depth + 1 end -- a 'fake' level is added in that case if info.what == "main" then break end -- levels below main chunk are not interesting end dbgp.send_xml(self.skt, { tag = "response", attr = { command = "stack_depth", transaction_id = args.i, depth = depth} } ) end function M.stack_get(self, args) -- TODO: dynamic code -- special URIs to identify unreachable stack levels local what2uri = { tail = "tailreturn:/", C = "ccode:/", } local function make_level(info, level) local attr = { level = level, where = info.name, type="file" } local uri = platform.get_uri(info.source) if uri and info.currentline then -- reachable level attr.filename = uri attr.lineno = info.currentline else attr.filename = what2uri[info.what] or "unknown:/" attr.lineno = -1 end return { tag = "stack", attr = attr } end local node = { tag = "response", attr = { command = "stack_get", transaction_id = args.i} } local coro = get_coroutine(self, args.o) if args.d then local stack_level = tonumber(args.d) node[#node+1] = make_level(coro:getinfo(stack_level, "nSl"), stack_level) else for i=0, math.huge do local info = coro:getinfo(i, "nSlt") if not info then break end node[#node+1] = make_level(info, i) -- add a fake level of stack for tail calls (tells user that the function has not been called directly) if info.istailcall then node[#node+1] = { tag = "stack", attr = { level=i, type="file", filename="tailreturn:/", lineno=-1 } } end if info.what == "main" then break end -- levels below main chunk are not interesting end end dbgp.send_xml(self.skt, node) end --- Lists all active coroutines. -- Returns a list of active coroutines with their id (an arbitrary string) to query stack and properties. The id is -- guaranteed to be unique and stable for all coroutine life (they can be reused as long as coroutine exists). -- Others commands such as stack_get or property_* commands takes an additional -o switch to query a particular cOroutine. -- If the switch is not given, running coroutine will be used. -- In case of error on coroutines (most likely coroutine not found or dead), an error 399 is thrown. -- Note there is an important limitation due to Lua 5.1 coroutine implementation: you cannot query main "coroutine" from -- another one, so main coroutine is not in returned list (this will change with Lua 5.2). -- -- This is a non-standard command. The returned XML has the following strucuture: -- <response command="coroutine_list" transaction_id="0"> -- <coroutine name="<some printtable name>" id="<coroutine id>" running="0|1" /> -- ... -- </response> function M.coroutine_list(self, args) local running = self.coro[1] local coroutines = { tag = "response", attr = { command = "coroutine_list", transaction_id = args.i } } -- as any operation on main coroutine will fail, it is not yet listed -- coroutines[1] = { name = "coroutine", attr = { id = 0, name = "main", running = (running == nil) and "1" or "0" } } for id, coro in pairs(core.active_coroutines.from_id) do if id ~= "n" then coroutines[#coroutines + 1] = { tag = "coroutine", attr = { id = id, name = tostring(coro), running = (coro == running) and "1" or "0" } } end end dbgp.send_xml(self.skt, coroutines) end function M.context_names(self, args) local coro = get_coroutine(self, args.o) local level = tonumber(args.d or 0) local info = coro:getinfo(level, "f") or dbgp.error(301, "No such stack level "..tostring(level)) -- All contexts are always passed, even if empty. This is how DLTK expect context, what about others ? local contexts = { tag = "response", attr = { command = "context_names", transaction_id = args.i }, { tag = "context", attr = { name = "Local", id = 0 } }, { tag = "context", attr = { name = "Upvalue", id = 2 } }, { tag = "context", attr = { name = "Global", id = 1 } }, } dbgp.send_xml(self.skt, contexts) end function M.context_get(self, args) local cxt_num = tonumber(args.c or 0) local cxt_id = context.Context[cxt_num] or dbgp.error(302, "No such context: "..tostring(cxt_num)) local level = tonumber(args.d or 0) local coro = get_coroutine(self, args.o) local cxt = self.stack(coro, level) local properties = { tag = "response", attr = { command = "context_get", transaction_id = args.i, context = context} } -- iteration over global is different (this could be unified in Lua 5.2 thanks to __pairs metamethod) for name, val in (cxt_num == 1 and next or getmetatable(cxt[cxt_id]).iterator), cxt[cxt_id], nil do -- the DBGp specification is not clear about the depth of a context_get, but a recursive get could be *really* slow in Lua properties[#properties + 1] = introspection.make_property(cxt_num, val, name, nil, 0, util.features.max_children, 0, util.features.max_data, cxt_num ~= 1) end dbgp.send_xml(self.skt, properties) end ------------------------------------------------------------------------------- -- Property_* commands ------------------------------------------------------------------------------- -- This in the environment in which properties are get or set. -- It notably contain a collection of proxy table which handle transparentely get/set operations on special fields -- and the cache of complex keys. local property_evaluation_environment = { key_cache = introspection.key_cache, metatable = setmetatable({ }, { __index = function(self, tbl) return getmetatable(tbl) end, __newindex = function(self, tbl, mt) return setmetatable(tbl, mt) end, }), environment = util.eval_env, } -- to allows to be set as metatable property_evaluation_environment.__index = property_evaluation_environment function M.property_get(self, args) --TODO BUG ECLIPSE TOOLSLINUX-99 352316 local cxt_num, name = assert(util.unb64(args.n):match("^(%d+)|(.*)$")) cxt_num = tonumber(args.c or cxt_num) local cxt_id = context.Context[cxt_num] or dbgp.error(302, "No such context: "..tostring(cxt_num)) local level = tonumber(args.d or 0) local coro = get_coroutine(self, args.o) local size = tonumber(args.m or util.features.max_data) if size < 0 then size = nil end -- call from property_value local page = tonumber(args.p or 0) local cxt = self.stack(coro, level) local chunk = dbgp.assert(206, util.loadin("return "..name, property_evaluation_environment)) local prop = select(2, dbgp.assert(300, pcall(chunk, cxt[cxt_id]))) local response = introspection.make_property(cxt_num, prop, name, name, util.features.max_depth, util.features.max_children, page, size) -- make_property is not able to flag special variables as such when they are at root of property -- special variables queries are in the form "<proxy name>[(...)[a][b]<...>]" -- TODO: such parsing is far from perfect if name:match("^[%w_]+%[.-%b[]%]$") == name then response.attr.type = "special" end dbgp.send_xml(self.skt, { tag = "response", attr = { command = "property_get", transaction_id = args.i, context = context}, response } ) end function M.property_value(self, args) args.m = -1 M.property_get(self, args) end function M.property_set(self, args, data) local cxt_num, name = assert(util.unb64(args.n):match("^(%d+)|(.*)$")) cxt_num = tonumber(args.c or cxt_num) local cxt_id = context.Context[cxt_num] or dbgp.error(302, "No such context: "..tostring(cxt_num)) local level = tonumber(args.d or 0) local coro = get_coroutine(self, args.o) local cxt = self.stack(coro, level) -- evaluate the new value in the local context local value = select(2, dbgp.assert(206, pcall(dbgp.assert(206, util.loadin("return "..data, cxt))))) local chunk = dbgp.assert(206, util.loadin(name .. " = value", setmetatable({ value = value }, property_evaluation_environment))) dbgp.assert(206, pcall(chunk, cxt[cxt_id])) dbgp.send_xml(self.skt, { tag = "response", attr = { success = 1, transaction_id = args.i } } ) end --TODO dynamic code handling -- The DBGp specification is not clear about the line number meaning, this implementation is 1-based and numbers are inclusive function M.source(self, args) local path if args.f then path = platform.get_path(args.f) else path = self.coro:getinfo(0, "S").source assert(path:sub(1,1) == "@") path = path:sub(2) end local file, err = io.open(path) if not file then dbgp.error(100, err, { success = 0 }) end -- Try to identify compiled files if file:read(1) == "\033" then dbgp.error(100, args.f.." is bytecode", { success = 0 }) end file:seek("set", 0) local srclines = { } local beginline, endline, currentline = tonumber(args.b or 0), tonumber(args.e or math.huge), 0 for line in file:lines() do currentline = currentline + 1 if currentline >= beginline and currentline <= endline then srclines[#srclines + 1] = line elseif currentline >= endline then break end end file:close() srclines[#srclines + 1] = "" -- to add a trailing \n dbgp.send_xml(self.skt, { tag = "response", attr = { command = "source", transaction_id = args.i, success = 1}, util.b64(table.concat(srclines, "\n")) }) end -- Factory for both stdout and stderr commands, change file descriptor in io local function output_command_handler_factory(mode) return function(self, args) if args.c == "0" then -- disable io[mode] = io.base[mode] else io[mode] = setmetatable({ skt = self.skt, mode = mode }, args.c == "1" and core.copy_output or core.redirect_output) end dbgp.send_xml(self.skt, { tag = "response", attr = { command = mode, transaction_id = args.i, success = "1" } } ) end end M.stdout = output_command_handler_factory("stdout") M.stderr = output_command_handler_factory("stderr") return M end -------------------------------------------------------------------------------- -- End of moduledebugger.commands -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.context package.preload["debugger.context"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Context handling: allows to evaluate code snippets in the context of a function ------------------------------------------------------------------------------- local M = { } local dbgp = require "debugger.dbgp" local util = require "debugger.util" -- make unique object to access contexts local LOCAL, UPVAL, GLOBAL, STORE, HANDLE = {}, {}, {}, {}, {} local getglobals if _VERSION == "Lua 5.1" then getglobals = function(f) return getfenv(f) end elseif _VERSION == "Lua 5.2" then getglobals = function(f, cxt) -- 'global' environment: this is either the local _ENV or upvalue _ENV. A special case happen when a -- function does not reference any global variable: the upvalue _ENV may not exist at all. In this case, -- global environment is not relevant so it is fixed to an empty table. Another solution would be to set it -- to the environment from above stack level but it would require some overhead (especially if multiple -- levels must be instantiated) if cxt[LOCAL][STORE]["_ENV"] then return cxt[LOCAL]["_ENV"] elseif cxt[UPVAL][STORE]["_ENV"] then return cxt[UPVAL]["_ENV"] else return { } end end end --- Captures variables for given stack level. The capture contains local, upvalues and global variables. -- The capture can be seen as a proxy table to the stack level: any value can be queried or set no matter -- it is a local or an upvalue. -- The individual local and upvalues context are also available and can be queried and modified with indexed notation too. -- These objects are NOT persistant and must not be used outside the debugger loop which instanciated them ! M.Context = { -- Context identifiers can be accessed by their DBGp context ID [0] = LOCAL, [1] = GLOBAL, -- DLTK internal ID for globals is 1 [2] = UPVAL, STORE = STORE, -- gets a variable by name with correct handling of Lua scope chain -- the or chain does not work here beacause __index metamethod would raise an error instead of returning nil __index = function(self, k) if self[LOCAL][STORE][k] then return self[LOCAL][k] elseif self[UPVAL][STORE][k] then return self[UPVAL][k] else return self[GLOBAL][k] end end, __newindex = function(self, k, v) if self[LOCAL][STORE][k] then self[LOCAL][k] = v elseif self[UPVAL][STORE][k] then self[UPVAL][k] = v else self[GLOBAL][k] = v end end, -- debug only !! __tostring = function(self) local buf = { "Locals: \n" } for k,v in pairs(self[LOCAL][STORE]) do buf[#buf+1] = "\t"..tostring(k).."("..tostring(v)..")="..tostring(self[LOCAL][k]).."\n" end buf[#buf+1] = "Upvalues: \n" for k,v in pairs(self[UPVAL][STORE]) do buf[#buf+1] = "\t"..tostring(k).."("..tostring(v)..")="..tostring(self[UPVAL][k]).."\n" end return table.concat(buf) end, LocalContext = { __index = function(self, k) local index = self[STORE][k] if not index then error("The local "..tostring(k).." does not exists.") end local handle = self[HANDLE] return select(2, handle.coro:getlocal(handle.level, index)) end, __newindex = function(self, k, v) local index = self[STORE][k] if index then local handle = self[HANDLE] handle.coro:setlocal(handle.level, index, v) else error("Cannot set local " .. k) end end, -- Lua 5.2 ready :) --__pairs = function(self) return getmetatable(self).iterator, self, nil end, iterator = function(self, prev) local key, index = next(self[STORE], prev) if key then return key, self[key] else return nil end end, }, UpvalContext = { __index = function(self, k) local index = self[STORE][k] if not index then error("The local "..tostring(k).." does not exitsts.") end return select(2, debug.getupvalue(self[HANDLE], index)) end, __newindex = function(self, k, v) local index = self[STORE][k] if index then debug.setupvalue(self[HANDLE], index, v) else error("Cannot set upvalue " .. k) end end, -- Lua 5.2 ready :) -- __pairs = function(self) return getmetatable(self).iterator, self, nil end, iterator = function(self, prev) local key, index = next(self[STORE], prev) if key then return key, self[key] else return nil end end, }, --- Context constructor -- @param coro (util.*Thread instance) coroutine to map to -- @param level (number) stack level do dump (script stack level) new = function(cls, coro, level) local locals, upvalues = {}, {} if level < 0 then dbgp.error(301, "No such stack level: "..tostring(level)) end local func = (coro:getinfo(level, "f") or dbgp.error(301, "No such stack level: "..tostring(level))).func -- local variables for i=1, math.huge do local name, val = coro:getlocal(level, i) if not name then break elseif name:sub(1,1) ~= "(" then -- skip internal values locals[name] = i end end -- upvalues for i=1, math.huge do local name, val = debug.getupvalue(func, i) if not name then break end upvalues[name] = i end locals = setmetatable({ [STORE] = locals, [HANDLE] = { level = level, coro = coro } }, cls.LocalContext) upvalues = setmetatable({ [STORE] = upvalues, [HANDLE] = func }, cls.UpvalContext) local result = setmetatable({ [LOCAL] = locals, [UPVAL] = upvalues }, cls) rawset(result, GLOBAL, getglobals(func, result)) return result end, } --- Handle caching of all instantiated context. -- Returns a function which takes 2 parameters: thread and stack level and returns the corresponding context. If this -- context has been already queried there is no new instantiation. A ContextManager is valid only during the debug loop -- on which it has been instantiated. References to a ContextManager must be lost after the end of debug loop (so -- threads can be collected). -- If a context cannot be instantiated, an 301 DBGP error is thrown. function M.ContextManager() local cache = { } return function(thread, level) -- the real coroutine is used as key (not the wrapped instance as its unicity is not guaranteed) -- otherwise, true is used to identify current thread (as nil is not a valid table key) local key = thread[1] or true local thread_contexts = cache[key] if not thread_contexts then thread_contexts = { } cache[key] = thread_contexts end local context = thread_contexts[level] if not context then context = M.Context:new(thread, level) thread_contexts[level] = context end return context end end return M end -------------------------------------------------------------------------------- -- End of moduledebugger.context -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.dbgp package.preload["debugger.dbgp"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- DBGp protocol utility function (parsing, error handling, XML generation). ------------------------------------------------------------------------------- local util = require "debugger.util" local error, setmetatable, type, pairs, ipairs, tostring, tconcat = error, setmetatable, type, pairs, ipairs, tostring, table.concat local M = { } --- Parses the DBGp command arguments and returns it as a Lua table with key/value pairs. -- For example, the sequence <code>-i 5 -j foo</code> will result in <code>{i=5, j=foo}</code> -- @param cmd_args (string) sequence of arguments -- @return table described above function M.arg_parse(cmd_args) local args = {} for arg, val in cmd_args:gmatch("%-(%w) (%S+)") do args[arg] = val end return args end --- Parses a command line -- @return commande name (string) -- @retrun arguments (table) -- @return data (string, optional) function M.cmd_parse(cmd) local cmd_name, args, data if cmd:find("--", 1, true) then -- there is a data part cmd_name, args, data = cmd:match("^(%S+)%s+(.*)%s+%-%-%s*(.*)$") data = util.unb64(data) else cmd_name, args = cmd:match("^(%S+)%s+(.*)$") end return cmd_name, M.arg_parse(args), data end --- Returns the packet read from socket, or nil followed by an error message on errors. function M.read_packet(skt) local size = {} while true do local byte, err = skt:receive(1) if not byte then return nil, err end if byte == "\000" then break end size[#size+1] = byte end return tconcat(size) end M.DBGP_ERR_METATABLE = {} -- unique object used to identify DBGp errors --- Throws a correct DBGp error which result in a fine tuned error message to the server. -- It is intended to be called into a command to make a useful error message, a standard Lua error -- result in a code 998 error (internal debugger error). -- @param code numerical error code -- @param message message string (optional) -- @param attr extra attributes to add to the response tag (optional) function M.error(code, message, attr) error(setmetatable({ code = code, message = message, attr = attr or {} }, M.DBGP_ERR_METATABLE), 2) end --- Like core assert but throws a DBGp error if condition is not met. -- @param code numerical error code thrown if condition is not met. -- @param message condition to test -- @param ... will be used as error message if test fails. function M.assert(code, success, ...) if not success then M.error(code, (...)) end return success, ... end -- ----------------- -- Outgoing data -- ----------------- local xmlattr_specialchars = { ['"'] = "&quot;", ["<"] = "&lt;", ["&"] = "&amp;" } --- Very basic XML generator -- Generates a XML string from a Lua Object Model (LOM) table. -- See http://matthewwild.co.uk/projects/luaexpat/lom.html function M.lom2str(xml) local pieces = { } -- string buffer local function generate(node) pieces[#pieces + 1] = "<"..node.tag pieces[#pieces + 1] = " " -- attribute ordering is not honored here for attr, val in pairs(node.attr or {}) do if type(attr) == "string" then pieces[#pieces + 1] = attr .. '="' .. tostring(val):gsub('["&<]', xmlattr_specialchars) .. '"' pieces[#pieces + 1] = " " end end pieces[#pieces] = nil -- remove the last separator (useless) if node[1] then pieces[#pieces + 1] = ">" for _, child in ipairs(node) do if type(child) == "table" then generate(child) else pieces[#pieces + 1] = "<![CDATA[" .. tostring(child) .. "]]>" end end pieces[#pieces + 1] = "</" .. node.tag .. ">" else pieces[#pieces + 1] = "/>" end end generate(xml) return tconcat(pieces) end function M.send_xml(skt, resp) if not resp.attr then resp.attr = {} end resp.attr.xmlns = "urn:debugger_protocol_v1" local data = '<?xml version="1.0" encoding="UTF-8" ?>\n'..M.lom2str(resp) util.log("DEBUG", "Send " .. data) skt:send(tostring(#data).."\000"..data.."\000") end --- Return an XML tag describing a debugger error, with an optional message -- @param code (number) error code (see DBGp specification) -- @param msg (string, optional) textual description of error -- @return table, suitable to be converted into XML function M.make_error(code, msg) local elem = { tag = "error", attr = { code = code } } if msg then elem[1] = { tostring(msg), tag = "message" } end return elem end return M end -------------------------------------------------------------------------------- -- End of moduledebugger.dbgp -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.introspection package.preload["debugger.introspection"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Properties generation. Generate a LOM table with data from introspection. ------------------------------------------------------------------------------- -- This module defines a single "class" which allows to dump arbitrary values by gathering as munch data as -- possible on it for debugging purposes. -- -- Recursions are avoided by "flatten" all tables in the structure and referencing them by their ID. -- The dump format is documented in Confluence Wiki: -- https://confluence.anyware-tech.com/display/ECLIPSE/Lua+IDE+Internship#LuaIDEInternship-Datadumpformat -- -- It has two major parts : -- dump : Result data structure: keys are numbers which are IDs for all dumped tables. -- Values are table structures. -- tables : Table dictionary, used to register all dumped tables, keys are tables, -- values are their ID. Functions upvalues are also stored here in the same way. -- -- The dump itself is done by type functions, one for each Lua type. For example a complete dump of the VM is done with: -- local introspection = require"debugintrospection" -- local dump = introspection:new() -- dump.dump.root = dump:table(_G) -- so dump.root will be a number which point to the result of _G introspection -- -- WARNING: do never keep any direct reference to internal fields (dump or tables): a dump object is not re-dumped to -- avoid making huge data structures (and potentially overflow l2b) local debug = require "debug" local platform = require "debugger.platform" local util = require "debugger.util" local M = { } local dump_pool = {} dump_pool.__index = dump_pool M.dump_pool = dump_pool local all_dumps = setmetatable({ }, { __mode = "k" }) -- register all dumps to avoid to re-dump them (see above warning) --- Creates a new dump pool with specified options -- @param dump_locales (boolean) whether local values are dumped -- @param dump_upvalues (boolean) whether function upvalues are dumped -- @param dump_metatables (boolean) whether metatables (for tables and userdata) are dumped -- @param dump_stacks (boolean) whether thread stacks are dumped -- @param dump_fenv (boolean) whether function environments are dumped function dump_pool:new(dump_locales, dump_upvalues, dump_metatables, dump_stacks, dump_fenv, keep_reference) local dump = setmetatable({ current_id = 1, tables = { }, dump = { }, -- set switches, force a boolean value because nil would mess with __index metamethod dump_locales = dump_locales and true or false, dump_upvalues = dump_upvalues and true or false, dump_metatables = dump_metatables and true or false, dump_stacks = dump_stacks and true or false, dump_fenv = dump_fenv and true or false, keep_reference = keep_reference and true or false, }, self) all_dumps[dump] = true return dump end function dump_pool:_next_id() local id = self.current_id self.current_id = id + 1 return id end function dump_pool:_register_new(value) local id = self.current_id self.current_id = id + 1 self.tables[value] = id return id end --- Utility function to factorize all metatable handling function dump_pool:_metatable(value, result, depth) --TODO: add support for __pairs and __ipairs ? if self.dump_metatables then local mt = getmetatable(value) if mt then result.metatable = self[type(mt)](self, mt, depth-1) if mt.__len then result.length = #value end end end return result end --- Adds a field into destination table, if both key and value has been successfully dumped function dump_pool:_field(dest, key, value, depth) local dkey, dvalue = self[type(key)](self, key, depth-1), self[type(value)](self, value, depth-1) if dkey and dvalue then dest[#dest + 1] = { dkey, dvalue } end end --- Functions used to extract debug informations from different data types. -- each function takes the value to debug as parameter and returns its -- debugging structure (or an id, for tables), modifying the pool if needed. function dump_pool:table(value, depth) depth = depth or math.huge if depth < 0 then return nil end if all_dumps[value] then return nil end local id = self.tables[value] if not id then -- this is a new table: register it id = self:_register_new(value) local t = { type = "table", repr = tostring(value), ref = self.keep_reference and value or nil } -- iterate over table values and detect arrays at the same time -- next is used to circumvent __pairs metamethod in 5.2 local isarray, i = true, 1 for k,v in next, value, nil do self:_field(t, k, v, depth) -- array detection: keys should be accessible by 1..n keys isarray = isarray and rawget(value, i) ~= nil i = i + 1 end t.array = i > 1 and isarray -- FIXME: sort fields for arrays ? -- The registered length refers to # result because if actual element count -- can be known with dumped values t.length = #value self:_metatable(value, t, depth) self.dump[id] = t end return id end function dump_pool:userdata(value, depth) depth = depth or math.huge if depth < 0 then return nil end local result = { type = "userdata", repr = tostring(value), ref = self.keep_reference and value or nil } --TODO support uservalues return self:_metatable(value, result, depth) end function dump_pool:thread(value, depth) depth = depth or math.huge if depth < 0 then return nil end local result = { type = "thread", repr = tostring(value), status = coroutine.status(value), ref = self.keep_reference and value or nil } local stack = self.tables[value] if self.dump_stacks and not stack then stack = self:_register_new(value) local stack_table = { type="special" } for i=1, math.huge do if not debug.getinfo(value, i, "f") then break end -- _filed is not used here because i is not a function and there is no risk to get a nil from number or function stack_table[#stack_table+1] = { self:number(i, depth - 1), self["function"](self, i, depth - 1, value) } end stack_table.repr = tostring(#stack_table).." levels" self.dump[stack] = stack_table end result.stack = stack return result end dump_pool["function"] = function(self, value, depth, thread) -- function is a keyword... depth = depth or math.huge if depth < 0 then return nil end local info = thread and debug.getinfo(thread, value, "nSfl") or debug.getinfo(value, "nSfl") local func = info.func -- in case of value is a stack index local result = { type = "function", ref = self.keep_reference and func or nil } result.kind = info.what if info.name and #info.name > 0 then result.repr = "function: "..info.name -- put natural name, if available elseif func then result.repr = tostring(func) -- raw tostring otherwise else result.repr = "<tail call>" end -- nothing is available for tail calls if not func then return result end -- there is no more info to gather for tail calls if info.what ~= "C" then --TODO: do something if function is not defined in a file if info.source:sub(1,1) == "@" then result.file = info.source:sub(2) result.repr = result.repr .. "\n" .. platform.get_uri("@" .. result.file) .. "\n" .. tostring(result.line_from) result.type = "function (Lua)" end result.line_from = info.linedefined result.line_to = info.lastlinedefined if info.currentline >= 0 then result.line_current = info.currentline end end -- Dump function upvalues (if any), trated as a table (recursion is handled in the same way) local upvalues = self.tables[func] if self.dump_upvalues and not upvalues and func and debug.getupvalue(func, 1) then -- Register upvalues table into result local ups_table = { type="special" } upvalues = self:_register_new(func) for i=1, math.huge do local name, val = debug.getupvalue(func, i) if not name then break end self:_field(ups_table, name, val, depth) end ups_table.repr = tostring(#ups_table) self.dump[upvalues] = ups_table end result.upvalues = upvalues -- Dump function locales (only for running function, recursion not handled) if self.dump_locales and type(value) == "number" then local getlocal = thread and function(...) return debug.getlocal(thread, ...) end or debug.getlocal if getlocal(value, 1) then local locales = { type="special" } local locales_id = self:_next_id() for i=1, math.huge do local name, val = getlocal(value, i) if not name then break elseif name:sub(1,1) ~= "(" and val ~= self then -- internal values are ignored self:_field(locales, name, val, depth) end end locales.repr = tostring(#locales) self.dump[locales_id] = locales result.locales = locales_id end end return result end function dump_pool:string(value, depth) depth = depth or math.huge if depth < 0 then return nil end -- make the string printable (%q pattern keeps real newlines and adds quotes) return { type = "string", repr = string.format("%q", value):gsub("\\\n", "\\n"), length = #value, ref = self.keep_reference and value or nil } end if _VERSION == "Lua 5.1" then local oldfunc = dump_pool["function"] dump_pool["function"] = function(self, value, depth, thread) depth = depth or math.huge local result = oldfunc(self, value, depth, thread) if not result then return result end -- Dump function env (if different from _G) local env = getfenv(value) if self.dump_fenv and env ~= getfenv(0) then result.environment = self:table(env, depth - 1) end return result end end -- default debug function for other types setmetatable(dump_pool, { __index = function(cls, vtype) return function(self, value, depth) return (depth == nil or depth >= 0) and { repr = tostring(value), type=vtype, ref = self.keep_reference and value or nil } or nil end end }) -- ---------------------------------------------------------------------------- -- Public API. -- ---------------------------------------------------------------------------- -- Used to store complex keys (other than string and number) as they cannot be passed in text -- For these keys, the resulting expression will not be the key itself but "key_cache[...]" -- where key_cache must be mapped to this table to resolve key correctly. M.key_cache = setmetatable({ n=0 }, { __mode = "v" }) local MULTIVAL_MT = { __tostring = function() return "" end } -- Used to inspect "multival" or "vararg" values. The typical use is to pack function result(s) in a single -- value to inspect. The Multival instances can be passed to make_property as a single value, they will be -- correctly reported to debugger function M.Multival(...) return setmetatable({ n=select("#", ...), ... }, MULTIVAL_MT) end local function generate_key(name) if type(name) == "string" then return string.format("%q", name) elseif type(name) == "number" or type(name) == "boolean" then return tostring(name) else -- complex key, use key_cache for lookup local i = M.key_cache.n M.key_cache[i] = name M.key_cache.n = i+1 return "key_cache["..tostring(i).."]" end end local function generate_printable_key(name) return "[" .. (type(name) == "string" and string.format("%q", name) or tostring(name)) .. "]" end --- Makes a property form a name/value pair (and fullname), see DBGp spec 7.11 for details -- It has a pretty basic handling of complex types (function, table, userdata), relying to Lua Inspector for advanced stuff. -- @param cxt_id (number) context ID in which this value resides (workaround bug 352316) -- @param value (any) the value to debug -- @param name (any) the name associated with value, passed through tostring -- @param fullname (string) a Lua expression to eval to get that property again (if nil, computed automatically) -- @param depth (number) the maximum property depth (recursive calls) -- @param pagesize (number) maximum children to include -- @param page (number) the page to generate (0 based) -- @param size_limit (number, optional) if set, the maximum size of the string representation (in bytes) -- @param safe_name (boolean) if true, does not encode the name as table key --TODO BUG ECLIPSE TOOLSLINUX-99 352316 : as a workaround, context is encoded into the fullname property function M.make_property(cxt_id, value, name, fullname, depth, pagesize, page, size_limit, safe_name) local dump = dump_pool:new(false, false, true, false, true, true) -- build XML local function build_xml(node, name, fullname, page, depth) local data = tostring(node.repr) local specials = { } if node.metatable then specials[#specials + 1] = "metatable" end if node.environment then specials[#specials + 1] = "environment" end local numchildren = #node + #specials local attr = { type = node.array and "sequence" or node.type, name=name, fullname=util.rawb64(tostring(cxt_id).."|"..fullname), encoding="base64", children = 0, size=#data } if numchildren > 0 then attr.children = 1 attr.numchildren = numchildren attr.pagesize = pagesize attr.page = page end local xmlnode = { tag = "property", attr = attr, util.b64(size_limit and data:sub(1, size_limit) or data) } if depth > 0 then local from, to = page * pagesize + 1, (page + 1) * (pagesize) for i = from, math.min(#node, to) do local key, value = unpack(node[i]) key = type(key) == "number" and dump.dump[key] or key value = type(value) == "number" and dump.dump[value] or value xmlnode[#xmlnode + 1] = build_xml(value, "[" .. key.repr .. "]", fullname .. "[" .. generate_key(key.ref) .. "]", 0, depth - 1) end for i = #node + 1, math.min(to, numchildren) do local special = specials[i - #node] local prop = build_xml(dump.dump[node[special]], special, special .. "[" .. fullname .. "]", 0, depth - 1) prop.attr.type = "special" xmlnode[#xmlnode + 1] = prop end end return xmlnode end fullname = fullname or ("(...)[" .. generate_key(name) .. "]") if not safe_name then name = generate_printable_key(name) end if getmetatable(value) == MULTIVAL_MT then local node = { tag = "property" } for i=1, value.n do local val = dump[type(value[i])](dump, value[i], depth) val = type(val) == "number" and dump.dump[val] or val -- Since fullname is impossible to build for multivals and they are read only, -- generate_key is used to retireve reference to the object node[#node + 1] = build_xml(val, "["..i.."]", generate_key(val.ref), 0, depth - 1) end -- return just the value in case of single result if #node == 1 then return node[1] end -- when there are multiple results, they a wrapped into a multival node.attr = { type="multival", name=name, fullname=tostring(cxt_id).."|"..fullname, encoding="base64", numchildren=value.n, children=value.n > 0 and 1 or 0, size=0, pagesize=pagesize } return node else local root = dump[type(value)](dump, value, depth + 1) return build_xml(type(root) == "number" and dump.dump[root] or root, name, fullname, page, depth) end end return M end -------------------------------------------------------------------------------- -- End of moduledebugger.introspection -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.platform package.preload["debugger.platform"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Platform/OS specific features and path handling. ------------------------------------------------------------------------------- local url = require "debugger.url" local util = require "debugger.util" local M = { } -- Get the execution plaform os (could be win or unix) -- Used to manage file path difference between the 2 platform local platform = nil -- keep all computed URIs in cache (as they are quite long to compute) local uri_cache = { } -- parse a normalized path and return a table of each segment -- you could precise the path seperator. local function split(path,sep) local t = {} for w in path:gmatch("[^"..(sep or "/").."]+")do table.insert(t, w) end return t end --- Returns a RFC2396 compliant URI for given source, or false if the mapping failed local function get_abs_file_uri (source) local uri if source:sub(1,1) == "@" then -- real source file local sourcepath = source:sub(2) local normalizedpath = M.normalize(sourcepath) if not M.is_path_absolute(normalizedpath) then normalizedpath = M.normalize(M.base_dir .. "/" .. normalizedpath) end return M.to_file_uri(normalizedpath) else -- dynamic code, stripped bytecode, tail return, ... return false end end --FIXME: as result is cached, changes in package.path that modify the module name are missed -- (mostly affect main module when Lua interpreter is launched with an absolute path) local function get_module_uri (source) if source:sub(1,1) == "@" then -- real source file local uri local sourcepath = source:sub(2) local normalizedpath = M.normalize(sourcepath) local luapathtable = split (package.path, ";") local is_source_absolute = M.is_path_absolute(sourcepath) -- workarround : Add always the ?.lua entry to support -- the case where file was loaded by : "lua myfile.lua" table.insert(luapathtable,"?.lua") for i,var in ipairs(luapathtable) do -- avoid relative patterns matching absolute ones (e.g. ?.lua matches anything) if M.is_path_absolute(var) == is_source_absolute then local escaped = string.gsub(M.normalize(var),"[%^%$%(%)%%%.%[%]%*%+%-%?]",function(c) return "%"..c end) local pattern = string.gsub(escaped,"%%%?","(.+)") local modulename = string.match(normalizedpath,pattern) if modulename then modulename = string.gsub(modulename,"/","."); -- if we find more than 1 possible modulename return the shorter if not uri or string.len(uri)>string.len(modulename) then uri = modulename end end end end if uri then return "module:///"..uri end end return false end function M.get_uri (source) -- search in cache local uri = uri_cache[source] if uri ~= nil then return uri end -- not found, create uri if util.features.uri == "module" then uri = get_module_uri(source) if not uri then uri = get_abs_file_uri (source) end else uri = get_abs_file_uri (source) end uri_cache[source] = uri return uri end -- get path file from uri function M.get_path (uri) local parsed_path = assert(url.parse(uri)) if parsed_path.scheme == "file" then return M.to_path(parsed_path) else -- search in cache -- we should surely calculate it instead of find in cache for k,v in pairs(uri_cache)do if v == uri then assert(k:sub(1,1) == "@") return k:sub(2) end end end end function M.normalize(path) local parts = { } for w in path:gmatch("[^/]+") do if w == ".." then table.remove(parts) elseif w ~= "." then table.insert(parts, w) end end return (path:sub(1,1) == "/" and "/" or "") .. table.concat(parts, "/") end function M.init(executionplatform,workingdirectory) -------------------------- -- define current platform -------------------------- -- check parameter if executionplatform and executionplatform ~= "unix" and executionplatform ~="win" then error("Unable to initialize platform module : execution platform should be 'unix' or 'win'.") end -- use parameter as current platform if executionplatform then platform = executionplatform else --if not define try to guess it. local function iswindows() local p = io.popen("echo %os%") if p then local result =p:read("*l") p:close() return result == "Windows_NT" end return false end status, iswin = pcall(iswindows) if status and iswin then platform = "win" else platform = "unix" end end -------------------------- -- platform dependent function -------------------------- if platform == "unix" then -- The Path separator character M.path_sep = "/" -- TODO the way to get the absolute path can be wrong if the program loads new source files by relative path after a cd. -- currently, the directory is registered on start, this allows program to load any source file and then change working dir, -- which is the most common use case. M.base_dir = workingdirectory or os.getenv("PWD") or "/tmp" -- convert parsed URL table to file path for the current OS (see url.parse from luasocket) M.to_file_uri = function (path) return url.build{scheme="file",authority="", path=path} end -- return true is the path is absolute -- the path must be normalized M.is_path_absolute = function (path) return path:sub(1,1) == "/" end -- convert absolute normalized path file to uri M.to_path = function (parsed_url) return url.unescape(parsed_url.path) end else -- Implementations for Windows, see UNIX versions for documentation. M.path_sep = "\\" M.is_path_absolute = function (path) return path:match("^%a:/") end M.to_file_uri = function (path) return url.build{scheme="file",authority="", path="/"..path} end M.to_path = function (parsed_url) return url.unescape(parsed_url.path):gsub("^/", "") end local unixnormalize = M.normalize M.normalize = function(path) return unixnormalize(path:gsub("\\","/"):lower()) end -- determine base dir local function getworkingdirectory() local p = io.popen("echo %cd%") if p then local res = p:read("*l") p:close() return M.normalize(res) end end M.base_dir = workingdirectory or getworkingdirectory() end if not M.base_dir then error("Unable to determine the working directory.") end end return M end -------------------------------------------------------------------------------- -- End of moduledebugger.platform -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.util package.preload["debugger.util"] = function(...) ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- -- Utility functions. ------------------------------------------------------------------------------- local M = { } -- log system local LEVELS = { ERROR = 0, WARNING = 1, INFO = 2, DETAIL = 3, DEBUG = 4 } local LOG_LEVEL = LEVELS.WARNING -- Debugger features handling. Any feature can be get like any regular table, setting features result in -- error for unknown or read-only features. M.features = setmetatable({ }, { -- functions that format/validate data. If function is not provided, the feature cannot be modified. validators = { multiple_sessions = tonumber, encoding = tostring, max_children = tonumber, max_data = tonumber, max_depth = tonumber, show_hidden = tonumber, uri = tostring, log_level = function(level_name) -- set numerical index in internal var LOG_LEVEL = assert(LEVELS[level_name], "No such level") return level_name -- the displayed level is still the name end, }, __index = { multiple_sessions = 0, encoding ="UTF-8", max_children = 32, max_data = 0xFFFF, max_depth = 1, show_hidden = 1, uri = "file", log_level = "WARNING", -- read only features language_supports_threads = 0, language_name = "Lua", language_version = _VERSION, protocol_version = 1, supports_async = 1, data_encoding = "base64", breakpoint_languages = "Lua", breakpoint_types = "line conditional", }, __newindex = function(self, k, v) local mt = getmetatable(self) local values, validator = mt.__index, mt.validators[k] if values[k] == nil then error("No such feature " .. tostring(k)) end if not validator then error("The feature " .. tostring(k) .. " is read-only") end v = assert(validator(v)) values[k] = v end, }) -- Wraps debug function and an attached thread -- also handle stack & coroutine management differencies between Lua versions local getinfo, getlocal, setlocal = debug.getinfo, debug.getlocal, debug.setlocal -- Foreign thread is used to debug paused thread local ForeignThreadMT = { getinfo = function(self, level, what) return getinfo(self[1], level, what) end, getlocal = function(self, level, idx) return getlocal(self[1], level, idx) end, setlocal = function(self, level, idx, val) return setlocal(self[1], level, idx, val) end, } ForeignThreadMT.__index = ForeignThreadMT function M.ForeignThread(coro) return setmetatable({ coro }, ForeignThreadMT) end -- Current thread is used to debug the thread that caused the hook -- intended to be used *ONLY* in debug loop (executed in a new thread) local CurrentThreadMT = { getinfo = function(self, level, what) return getinfo(self[1], level + 2, what) end, getlocal = function(self, level, idx) return getlocal(self[1], level + 2, idx) end, setlocal = function(self, level, idx, val) return setlocal(self[1], level + 2, idx, val) end, } CurrentThreadMT.__index = CurrentThreadMT function M.CurrentThread(coro) return setmetatable({ coro }, CurrentThreadMT) end -- Fallback method to inspect running thread (only for main thread in 5.1 or for conditional breakpoints) --- Gets a script stack level with additional debugger logic added -- @param l (number) stack level to get for debugged script (0 based) -- @return real Lua stack level suitable to be passed through deubg functions local function get_script_level(l) local hook = debug.gethook() for i=2, math.huge do if assert(debug.getinfo(i, "f")).func == hook then return i + l -- the script to level is just below, but because of the extra call to this function, the level is ok for callee end end end M.MainThread = { [1] = "main", -- as the raw thread object is used as table keys, provide a replacement. getinfo = function(self, level, what) return getinfo(get_script_level(level), what:gsub("t", "", 1)) end, getlocal = function(self, level, idx) return getlocal(get_script_level(level), idx) end, setlocal = function(self, level, idx, val) return setlocal(get_script_level(level), idx, val) end, } -- Some version dependant functions if _VERSION == "Lua 5.1" then local loadstring, getfenv, setfenv, debug_getinfo = loadstring, getfenv, setfenv, debug.getinfo -- in 5.1 "t" flag does not exist and trigger an error so remove it from what CurrentThreadMT.getinfo = function(self, level, what) return getinfo(self[1], level + 2, what:gsub("t", "", 1)) end ForeignThreadMT.getinfo = function(self, level, what) return getinfo(self[1], level, what:gsub("t", "", 1)) end -- If the VM is vanilla Lua 5.1, there is no way to get a reference to the main coroutine, so fall back to direct mode: -- the debugger loop is started on the top of main thread and the actual level is recomputed each time if not jit then -- allow CurrentThread to take a nil parameter local oldCurrentThread = M.CurrentThread M.CurrentThread = function(coro) return coro and oldCurrentThread(coro) or M.MainThread end end -- load a piece of code alog with its environment function M.loadin(code, env) local f = loadstring(code) return f and setfenv(f, env) end -- table that maps [gs]et environment to index M.eval_env = setmetatable({ }, { __index = function(self, func) return getfenv(func) end, __newindex = function(self, func, env) return setfenv(func, env) end, }) elseif _VERSION == "Lua 5.2" then local load, debug_getinfo = load, debug.getinfo function M.getinfo(coro, level, what) if coro then return debug_getinfo(coro, level, what) else return debug_getinfo(level + 1, what) end end function M.loadin(code, env) return load(code, nil, nil, env) end -- no eval_env for 5.2 as functions does not have environments anymore end -- ---------------------------------------------------------------------------- -- Bare minimal log system. -- ---------------------------------------------------------------------------- function M.log(level, msg, ...) if (LEVELS[level] or -1) > LOG_LEVEL then return end if select("#", ...) > 0 then msg = msg:format(...) end io.base.stderr:write(string.format("DEBUGGER\t%s\t%s\n", level, msg)) end return M end -------------------------------------------------------------------------------- -- End of moduledebugger.util -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Module debugger.url package.preload["debugger.url"] = function(...) ----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local base = _G local table = require("table") local _ENV = { } if setfenv then setfenv(1, _ENV) end ----------------------------------------------------------------------------- -- Module version ----------------------------------------------------------------------------- _VERSION = "URL 1.0.1" ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end ----------------------------------------------------------------------------- -- Protects a path segment, to prevent it from interfering with the -- url parsing. -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end -- these are allowed withing a path segment, along with alphanum -- other characters must be escaped local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end ----------------------------------------------------------------------------- -- Builds a path from a base path and a relative path -- Input -- base_path -- relative_path -- Returns -- corresponding absolute path ----------------------------------------------------------------------------- local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function build(parsed) local ppath = parse_path(parsed.path or "") local url = build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end ----------------------------------------------------------------------------- -- Builds a absolute URL from a base and a relative URL according to RFC 2396 -- Input -- base_url -- relative_url -- Returns -- corresponding absolute url ----------------------------------------------------------------------------- function absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = build(base_parsed) else base_parsed = parse(base_url) end local relative_parsed = parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return build(relative_parsed) end end ----------------------------------------------------------------------------- -- Breaks a path into its segments, unescaping the segments -- Input -- path -- Returns -- segment: a table with one entry per segment ----------------------------------------------------------------------------- function parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end ----------------------------------------------------------------------------- -- Builds a path component from its segments, escaping protected characters. -- Input -- parsed: path segments -- unsafe: if true, segments are not protected before path is built -- Returns -- path: corresponding path stringing ----------------------------------------------------------------------------- function build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return _ENV end -------------------------------------------------------------------------------- -- End of moduledebugger.url -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Main content -------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- Copyright (c) 2011-2012 Sierra Wireless and others. -- All rights reserved. This program and the accompanying materials -- are made available under the terms of the Eclipse Public License v1.0 -- which accompanies this distribution, and is available at -- http://www.eclipse.org/legal/epl-v10.html -- -- Contributors: -- Sierra Wireless - initial API and implementation ------------------------------------------------------------------------------- local debug = require "debug" -- To avoid cyclic dependency, internal state of the debugger that must be accessed -- elsewhere (in commands most likely) will be stored in a fake module "debugger.core" local core = { } package.loaded["debugger.core"] = core local util = require "debugger.util" local platform = require "debugger.platform" local dbgp = require "debugger.dbgp" local commands = require "debugger.commands" local context = require "debugger.context" local url = require "debugger.url" local log = util.log -- TODO complete the stdlib access local corunning, cocreate, cowrap, coyield, coresume, costatus = coroutine.running, coroutine.create, coroutine.wrap, coroutine.yield, coroutine.resume, coroutine.status -- register the URI of the debugger, to not jump into with redefined function or coroutine bootstrap stuff local debugger_uri = nil -- set in init function local transportmodule_uri = nil -- set in init function -- will contain the session object, and possibly a list of all sessions if a multi-threaded model is adopted -- this is only used for async commands. local active_session = nil -- tracks all active coroutines and associate an id to them, the table from_id is the id=>coro mapping, the table from_coro is the reverse core.active_coroutines = { n = 0, from_id = setmetatable({ }, { __mode = "v" }), from_coro = setmetatable({ }, { __mode = "k" }) } -- "BEGIN VERSION DEPENDENT CODE" local setbpenv -- set environment of a breakpoint (compiled function) if _VERSION == "Lua 5.1" then local setfenv = setfenv setbpenv = setfenv elseif _VERSION == "Lua 5.2" then local setupvalue = debug.setupvalue -- _ENV is the first upvalue setbpenv = function(f, t) return setupvalue(f, 1, t) end else error(_VERSION .. "is not supported.") end -- "END VERSION DEPENDENT CODE" ------------------------------------------------------------------------------- -- Output redirection handling ------------------------------------------------------------------------------- -- Override standard output functions & constants to redirect data written to these files to IDE too. -- This works only for output done in Lua, output written by C extensions is still go to system output file. -- references to native values io.base = { output = io.output, stdin = io.stdin, stdout = io.stdout, stderr = io.stderr } function print(...) local buf = {...} for i=1, select("#", ...) do buf[i] = tostring(buf[i]) end io.stdout:write(table.concat(buf, "\t") .. "\n") end -- Actually change standard output file but still return the "fake" stdout function io.output(output) io.base.output(output) return io.stdout end local dummy = function() end -- metatable for redirecting output (not printed at all in actual output) core.redirect_output = { write = function(self, ...) local buf = {...} for i=1, select("#", ...) do buf[i] = tostring(buf[i]) end buf = table.concat(buf):gsub("\n", "\r\n") dbgp.send_xml(self.skt, { tag = "stream", attr = { type=self.mode }, util.b64(buf) } ) end, flush = dummy, close = dummy, setvbuf = dummy, seek = dummy } core.redirect_output.__index = core.redirect_output -- metatable for cloning output (outputs to actual system and send to IDE) core.copy_output = { write = function(self, ...) core.redirect_output.write(self, ...) io.base[self.mode]:write(...) end, flush = function(self, ...) return self.out:flush(...) end, close = function(self, ...) return self.out:close(...) end, setvbuf = function(self, ...) return self.out:setvbuf(...) end, seek = function(self, ...) return self.out:seek(...) end, } core.copy_output.__index = core.copy_output ------------------------------------------------------------------------------- -- Breakpoint registry ------------------------------------------------------------------------------- -- Registry of current stack levels of all running threads local stack_levels = setmetatable( { }, { __mode = "k" } ) -- File/line mapping for breakpoints (BP). For a given file/line, a list of BP is associated (DBGp specification section 7.6.1 -- require that multiple BP at same place must be handled) -- A BP is a table with all additional properties (type, condition, ...) the id is the string representation of the table. core.breakpoints = { -- functions to call to match hit conditions hit_conditions = { [">="] = function(value, target) return value >= target end, ["=="] = function(value, target) return value == target end, ["%"] = function(value, target) return (value % target) == 0 end, } } -- tracks events such as step_into or step_over core.events = { } do local file_mapping = { } local id_mapping = { } local waiting_sessions = { } -- sessions that wait for an event (over, into, out) local step_into = nil -- session that registered a step_into event, if any local sequence = 0 -- used to generate breakpoint IDs --- Inserts a new breakpoint into registry -- @param bp (table) breakpoint data -- @param uri (string, optional) Absolute file URI, for line breakpoints -- @param line (number, optional) Line where breakpoint stops, for line breakpoints -- @return breakpoint identifier function core.breakpoints.insert(bp) local bpid = sequence sequence = bpid + 1 bp.id = bpid -- re-encode the URI to avoid any mismatch (with authority for example) local uri = url.parse(bp.filename) bp.filename = url.build{ scheme=uri.scheme, authority="", path=platform.normalize(uri.path)} local filereg = file_mapping[bp.filename] if not filereg then filereg = { } file_mapping[bp.filename] = filereg end local linereg = filereg[bp.lineno] if not linereg then linereg = {} filereg[bp.lineno] = linereg end table.insert(linereg, bp) id_mapping[bpid] = bp return bpid end --- If breakpoint(s) exists for given file/line, uptates breakpoint counters -- and returns whether a breakpoint has matched (boolean) function core.breakpoints.at(file, line) local bps = file_mapping[file] and file_mapping[file][line] if not bps then return nil end local do_break = false for _, bp in pairs(bps) do if bp.state == "enabled" then local match = true if bp.condition then -- TODO: this is not the optimal solution because Context can be instantiated twice if the breakpoint matches local cxt = context.Context:new(active_session.coro, 0) setbpenv(bp.condition, cxt) local success, result = pcall(bp.condition) if not success then log("ERROR", "Condition evaluation failed for breakpoint at %s:%d: %s", file, line, result) end -- debugger always stops if an error occurs match = (not success) or result end if match then bp.hit_count = bp.hit_count + 1 if core.breakpoints.hit_conditions[bp.hit_condition](bp.hit_count, bp.hit_value) then if bp.temporary then core.breakpoints.remove(bp.id) end do_break = true -- there is no break to handle multiple breakpoints: all hit counts must be updated end end end end return do_break end function core.breakpoints.get(id) if id then return id_mapping[id] else return id_mapping end end function core.breakpoints.remove(id) local bp = id_mapping[id] if bp then id_mapping[id] = nil local linereg = file_mapping[bp.filename][bp.lineno] for i=1, #linereg do if linereg[i] == bp then table.remove(linereg, i) break end end -- cleanup file_mapping if not next(linereg) then file_mapping[bp.filename][bp.lineno] = nil end if not next(file_mapping[bp.filename]) then file_mapping[bp.filename] = nil end return true end return false end --- Returns an XML data structure that describes given breakpoint -- @param id (number) breakpoint ID -- @return Table describing a <breakpooint> tag or nil followed by an error message function core.breakpoints.get_xml(id) local bp = id_mapping[id] if not bp then return nil, "No such breakpoint: "..tostring(id) end local response = { tag = "breakpoint", attr = { } } for k,v in pairs(bp) do response.attr[k] = v end if bp.expression then response[1] = { tag = "expression", bp.expression } end -- internal use only response.attr.expression = nil response.attr.condition = nil response.attr.temporary = nil -- TODO: the specification is not clear whether this should be provided, see other implementations return response end --- Register an event to be triggered. -- @param event event name to register (must be "over", "out" or "into") function core.events.register(event) local thread = active_session.coro[1] log("DEBUG", "Registered %s event for %s (%d)", event, tostring(thread), stack_levels[thread]) if event == "into" then step_into = true else waiting_sessions[thread] = { event, stack_levels[thread] } end end --- Returns if an event (step into, over, out) is triggered. -- Does *not* discard events (even if they match) as event must be discarded manually if a breakpoint match before anyway. -- @return true if an event has matched, false otherwise function core.events.does_match() if step_into then return true end local thread = active_session.coro[1] local event = waiting_sessions[thread] if event then local event_type, target_level = unpack(event) local current_level = stack_levels[thread] if (event_type == "over" and current_level <= target_level) or -- step over (event_type == "out" and current_level < target_level) then -- step out log("DEBUG", "Event %s matched!", event_type) return true end end return false end --- Discards event for current thread (if any) function core.events.discard() waiting_sessions[active_session.coro[1]] = nil step_into = nil end end ------------------------------------------------------------------------------- -- Debugger main loop ------------------------------------------------------------------------------- --- Send the XML response to the previous continuation command and clear the previous context function core.previous_context_response(self, reason) self.previous_context.status = self.state self.previous_context.reason = reason or "ok" dbgp.send_xml(self.skt, { tag = "response", attr = self.previous_context } ) self.previous_context = nil end --- This function handles the debugger commands while the execution is paused. This does not use coroutines because there is no -- way to get main coro in Lua 5.1 (only in 5.2) local function debugger_loop(self, async_packet) self.skt:settimeout(nil) -- set socket blocking -- in async mode, the debugger does not wait for another command before continuing and does not modify previous_context local async_mode = async_packet ~= nil if self.previous_context and not async_mode then self.state = "break" core.previous_context_response(self) end self.stack = context.ContextManager(self.coro) -- will be used to mutualize context allocation for each loop while true do -- reads packet local packet = async_packet or assert(dbgp.read_packet(self.skt)) async_packet = nil log("DEBUG", packet) local cmd, args, data = dbgp.cmd_parse(packet) -- FIXME: command such as continuations sent in async mode could lead both engine and IDE in inconsistent state : -- make a blacklist/whitelist of forbidden or allowed commands in async ? -- invoke function local func = commands[cmd] if func then local ok, cont = xpcall(function() return func(self, args, data) end, debug.traceback) if not ok then -- internal exception local code, msg, attr if type(cont) == "table" and getmetatable(cont) == dbgp.DBGP_ERR_METATABLE then code, msg, attr = cont.code, cont.message, cont.attr else code, msg, attr = 998, tostring(cont), { } end log("ERROR", "Command %s caused: (%d) %s", cmd, code, tostring(msg)) attr.command, attr.transaction_id = cmd, args.i dbgp.send_xml(self.skt, { tag = "response", attr = attr, dbgp.make_error(code, msg) } ) elseif cont then self.previous_context = { command = cmd, transaction_id = args.i } break elseif cont == nil and async_mode then break elseif cont == false then -- In case of commands that fully resumes debugger loop, the mode is sync async_mode = false end else log("Got unknown command: "..cmd) dbgp.send_xml(self.skt, { tag = "response", attr = { command = cmd, transaction_id = args.i, }, dbgp.make_error(4) } ) end end self.stack = nil -- free allocated contexts self.state = "running" self.skt:settimeout(0) -- reset socket to async end -- Stack handling can be pretty complex sometimes, especially with LuaJIT (as tail-call optimization are -- more aggressive as stock Lua). So all debugger stuff is done in another coroutine, which leave the program -- stack in a clean state and allow faster and clearer stack operations (no need to remove all debugger calls -- from stack for each operation). -- However, this does not always work with stock Lua 5.1 as the main coroutine cannot be referenced -- (coroutine.running() return nil). For this particular case, the debugger loop is started on the top of -- program stack and every stack operation is relative the the hook level (see MainThread in util.lua). local function line_hook(line) local do_break, packet = nil, nil local info = active_session.coro:getinfo(0, "S") local uri = platform.get_uri(info.source) if uri and uri ~= debugger_uri and uri ~= transportmodule_uri then -- the debugger does not break if the source is not known do_break = core.breakpoints.at(uri, line) or core.events.does_match() if do_break then core.events.discard() end -- check for async commands if not do_break then packet = dbgp.read_packet(active_session.skt) if packet then do_break = true end end end if do_break then local success, err = pcall(debugger_loop, active_session, packet) if not success then log("ERROR", "Error while debug loop: "..err) end end end local line_hook_coro = cocreate(function(line) while true do line_hook(line) line = coyield() end end) local function debugger_hook(event, line) local thread = corunning() or "main" if event == "call" then stack_levels[thread] = stack_levels[thread] + 1 elseif event == "tail call" then -- tail calls has no effects on stack handling: it is only used only for step commands but a such even does not -- interfere with any of them elseif event == "return" or event == "tail return" then stack_levels[thread] = stack_levels[thread] - 1 else -- line event: check for breakpoint active_session.coro = util.CurrentThread(corunning()) if active_session.coro[1] == "main" then line_hook(line) else -- run the debugger loop in another thread on the other cases (simplifies stack handling) assert(coresume(line_hook_coro, line)) end active_session.coro = nil end end if jit then debugger_hook = function(event, line) local thread = corunning() if event == "call" then if debug.getinfo(2, "S").what == "C" then return end stack_levels[thread] = stack_levels[thread] + 1 elseif event == "return" or event == "tail return" then -- Return hooks are not called for tail calls in JIT (but unlike 5.2 there is no way to know whether a call is tail or not). -- So the only reliable way to know stack depth is to walk it. local depth = 2 -- TODO: find the fastest way to call getinfo ('what' parameter) while debug.getinfo(depth, "f") do depth = depth + 1 end stack_levels[thread] = depth - 2 elseif event == "line" then active_session.coro = util.CurrentThread(corunning()) assert(coresume(line_hook_coro, line)) active_session.coro = nil end end end local function init(host, port, idekey, transport, executionplatform, workingdirectory) -- get connection data local host = host or os.getenv "DBGP_IDEHOST" or "127.0.0.1" local port = port or os.getenv "DBGP_IDEPORT" or "10000" local idekey = idekey or os.getenv("DBGP_IDEKEY") or "luaidekey" -- init plaform module local executionplatform = executionplatform or os.getenv("DBGP_PLATFORM") or nil local workingdirectory = workingdirectory or os.getenv("DBGP_WORKINGDIR") or nil platform.init(executionplatform,workingdirectory) -- get transport layer local transportpath = transport or os.getenv("DBGP_TRANSPORT") or "debugger.transport.luasocket" local transport = require(transportpath) -- install base64 functions into util util.b64, util.rawb64, util.unb64 = transport.b64, transport.rawb64, transport.unb64 local skt = assert(transport.create()) skt:settimeout(nil) -- try to connect several times: if IDE launches both process and server at same time, first connect attempts may fail local ok, err for i=1, 5 do ok, err = skt:connect(host, port) if ok then break end transport.sleep(0.5) end if err then error(string.format("Cannot connect to %s:%d : %s", host, port, err)) end -- get the debugger and transport layer URI debugger_uri = platform.get_uri(debug.getinfo(1).source) transportmodule_uri = platform.get_uri(debug.getinfo(transport.create).source) -- get the root script path (the highest possible stack index) local source for i=2, math.huge do local info = debug.getinfo(i) if not info then break end source = platform.get_uri(info.source) or source end if not source then source = "unknown:/" end -- when loaded before actual script (with a command line switch) -- generate some kind of thread identifier local thread = corunning() or "main" stack_levels[thread] = 1 -- the return event will set the counter to 0 local sessionid = tostring(os.time()) .. "_" .. tostring(thread) dbgp.send_xml(skt, { tag = "init", attr = { appid = "Lua DBGp", idekey = idekey, session = sessionid, thread = tostring(thread), parent = "", language = "Lua", protocol_version = "1.0", fileuri = source } }) local sess = { skt = skt, state = "starting", id = sessionid, coro = util.CurrentThread(corunning) } active_session = sess debugger_loop(sess) -- set debug hooks debug.sethook(debugger_hook, "rlc") -- install coroutine collecting functions. -- TODO: maintain a list of *all* coroutines can be overkill (for example, the ones created by copcall), make a extension point to -- customize debugged coroutines -- coroutines are referenced during their first resume (so we are sure that they always have a stack frame) local function resume_handler(coro, ...) if costatus(coro) == "dead" then local coro_id = core.active_coroutines.from_coro[coro] core.active_coroutines.from_id[coro_id] = nil core.active_coroutines.from_coro[coro] = nil stack_levels[coro] = nil end return ... end function coroutine.resume(coro, ...) if not stack_levels[coro] then -- first time referenced stack_levels[coro] = 0 core.active_coroutines.n = core.active_coroutines.n + 1 core.active_coroutines.from_id[core.active_coroutines.n] = coro core.active_coroutines.from_coro[coro] = core.active_coroutines.n debug.sethook(coro, debugger_hook, "rlc") end return resume_handler(coro, coresume(coro, ...)) end -- coroutine.wrap uses directly C API for coroutines and does not trigger our overridden coroutine.resume -- so this is an implementation of wrap in pure Lua local function wrap_handler(status, ...) if not status then error((...)) end return ... end function coroutine.wrap(f) local coro = coroutine.create(f) return function(...) return wrap_handler(coroutine.resume(coro, ...)) end end return sess end return init
local function startup() autopid = require("autopidlib") fs = require("filesystem") configlocation = "/etc/autopid_autostart.txt" if fs.exists(configlocation) == false then f = io.open(configlocation, "w") f.write("false") f.close() end config = io.open(configlocation, "r") status = config:read() config:close() if status == "true" then print("[autopid] Scanning for machines...") if pcall(autopid.scan) then print("[autopid] Done.") else print("[autopid] crashed while scanning") end end end status, perror = pcall(startup) if status == false then print("[autopid] Unknown error while running the startup script!") print(perror) end
local M = {} local strwidth = vim.api.nvim_strwidth M.current = {} local valid = "abcdefghijklmopqrstuvwxyzABCDEFGHIJKLMOPQRSTUVWXYZ" function M.reset() M.current = {} end ---@param element Tabpage|Buffer ---@return string? function M.get(element) local first_letter = element.name:sub(1, 1) -- should only match alphanumeric characters local invalid_char = first_letter:match("[^%w]") if not M.current[first_letter] and not invalid_char then M.current[first_letter] = element.id return first_letter end for letter in valid:gmatch(".") do if not M.current[letter] then M.current[letter] = element.id return letter end end end ---@param ctx RenderContext function M.component(ctx) local utils = require("bufferline.utils") local padding = require("bufferline.constants").padding local options = require("bufferline.config").get("options") local element = ctx.tab local length = ctx.length local component = ctx.component local hl = ctx.current_highlights local letter = element.letter if options.show_buffer_icons and element.icon then local right = string.rep(padding, math.ceil((strwidth(element.icon) - 1) / 2)) local left = string.rep(padding, math.floor((strwidth(element.icon) - 1) / 2)) letter = left .. element.letter .. right end component = utils.join(hl.pick, letter, padding, hl.background, component) length = utils.sum(length, strwidth(letter), strwidth(padding)) return component, length end return M
--[[ Title: Keepwork Applies API Author(s): big Date: 2020.08.17 Place: Foshan use the lib: ------------------------------------------------------------ local KeepworkAppliesApi = NPL.load("(gl)Mod/WorldShare/api/Keepwork/Applies.lua") ------------------------------------------------------------ ]] local KeepworkBaseApi = NPL.load('./BaseApi.lua') local KeepworkAppliesApi = NPL.export() -- /applies?objectId={ojectId}&objectType={objectType}&applyType={applyType} -- method: GET -- params: --[[ objectId number necessary object id objectType number necessary ENTITY_TYPE_USER: 0, // 用户类型 ENTITY_TYPE_SITE: 1, // 站点类型 ENTITY_TYPE_PAGE: 2, // 页面类型 ENTITY_TYPE_GROUP: 3, // 组 ENTITY_TYPE_ISSUE: 4, // 问题 ENTITY_TYPE_PROJECT: 5, // 项目 applyType number 0 ]] -- return: object function KeepworkAppliesApi:Applies(objectId, objectType, applyType, success, error) if not objectId or not objectType or not applyType then return false end KeepworkBaseApi:Get( '/applies?objectId=' .. objectId .. '&objectType=' .. objectType .. '&applyType=' .. applyType, nil, nil, success, error ) end -- url: /applies/:id -- method: PUT -- params: --[[ id number necessary apply id state number necessary 1 通过 2 拒绝 ]] -- return: object function KeepworkAppliesApi:AppliesId(id, isAllow, success, error) if not id then return false end local state if isAllow == true then state = 1 elseif isAllow == false then state = 2 else return false end KeepworkBaseApi:Put("/applies/" .. id, { state = state }, nil, success, error) end -- url: /applies -- method: POST -- params: --[[ objectId integer necessary objectType integer necessary 枚举: 5 mock: 5 applyType integer necessary 枚举: 0 mock: 0 applyId integer necessary legend string not necessary 最大长度: 255 ]] -- return: object function KeepworkAppliesApi:PostApplies(objectId, objectType, applyType, applyId, legend, success, error) if not objectId or not objectType or not applyType or not applyId then return false end local params = { objectId = objectId, objectType = objectType, applyType = applyType, applyId = applyId, legend = legend } KeepworkBaseApi:Post("/applies", params, nil, success, error) end
local DS = game:GetService("DataStoreService") local RunService = game:GetService("RunService") local store = { PlayerDS = RunService:IsStudio() and {} or DS:GetDataStore("GA_PlayerDS_1.0.0"), AutoSaveData = 180, --Set to 0 to disable BasePlayerData = { Sessions = 0, Transactions = 0, ProgressionTries = {}, CurrentCustomDimension01 = "", CurrentCustomDimension02 = "", CurrentCustomDimension03 = "", ConfigsHash = "", AbId = "", AbVariantId = "", InitAuthorized = false, SdkConfig = {}, ClientServerTimeOffset = 0, Configurations = {}, RemoteConfigsIsReady = false, PlayerTeleporting = false, OwnedGamepasses = nil, --nil means a completely new player. {} means player with no game passes CountryCode = "", CustomUserId = "" }, DataToSave = { "Sessions", "Transactions", "ProgressionTries", "CurrentCustomDimension01", "CurrentCustomDimension02", "CurrentCustomDimension03", "OwnedGamepasses", }, --Cache PlayerCache = {}, EventsQueue = {}, } function store:GetPlayerData(Player) local PlayerData local success = pcall(function() PlayerData = RunService:IsStudio() and {} or (store.PlayerDS:GetAsync(Player.UserId) or {}) end) if not success then PlayerData = {} end return PlayerData end function store:GetPlayerDataFromCache(userId) local playerData = store.PlayerCache[tonumber(userId)] if playerData then return playerData end playerData = store.PlayerCache[tostring(userId)] return playerData end function store:GetErrorDataStore(scope) local ErrorDS local success = pcall(function() ErrorDS = RunService:IsStudio() and {} or DS:GetDataStore("GA_ErrorDS_1.0.0", scope) end) if not success then ErrorDS = {} end return ErrorDS end function store:SavePlayerData(Player) --Variables local PlayerData = store:GetPlayerDataFromCache(Player.UserId) local SavePlayerData = {} if not PlayerData then return end --Fill for _, key in pairs(store.DataToSave) do SavePlayerData[key] = PlayerData[key] end --Save if not RunService:IsStudio() then pcall(function() store.PlayerDS:SetAsync(Player.UserId, SavePlayerData) end) end end function store:IncrementErrorCount(ErrorDS, ErrorKey, step) if not ErrorKey then return end local count = 0 --Increment count if not RunService:IsStudio() then pcall(function() count = ErrorDS:IncrementAsync(ErrorKey, step) end) end return count end return store
package.cpath = '../unix/?.so;'..package.cpath package.cpath = '../carray/?.so;'..package.cpath package.path = '../../Util/?.lua;'..package.path local unix = require 'unix' local msgpack = require 'msgpack' local util = require 'util' function TEST_NUM(num_in) local pack_str = msgpack.pack(num_in) local num_out = msgpack.unpack(pack_str) print("test case:", num_out == num_in, "input:", num_in, "output:", num_out, 'with pack length:', #pack_str) end print("\n================= Test msgpack on Num ==================") TEST_NUM(3.1415926 + 10^200) TEST_NUM(-3.1415926 + 10) TEST_NUM(2^8 - 2) TEST_NUM(2^16 - 2) TEST_NUM(2^32 - 2) TEST_NUM(2^64 - 2) TEST_NUM(-2^8 + 2) TEST_NUM(-2^16 + 2) TEST_NUM(-2^32 + 2) TEST_NUM(-2^64 + 2) function TEST_TABLE(tbl_in) local print_table = function(t) for k, v in pairs(tbl_in) do print("key:", k, 'value:', v, 'key type:'..type(k), 'value type:'..type(v)) end end local pack_str = msgpack.pack(tbl_in) print('input table') print_table(tbl_in) local tbl_out = msgpack.unpack(pack_str) print('output table') print_table(tbl_out) end print("\n================= Test msgpack on Table ==================") a = {1,2,3,4,5,'hello', ['num'] = 3234} TEST_TABLE(a) b = {['num'] = 3234, ['table'] = {1,2,3,4}} TEST_TABLE(b) a = {['num'] = 3234, ['table'] = {1,2,3,4}} b = {['table'] = {1,2,3,4}, ['tbl'] = {3.4,2,4,'helo'}} b.a = a TEST_TABLE(b) function TEST_STRING(str_in) local pack_str = msgpack.pack(str_in) local str_out = msgpack.unpack(pack_str) print("test case", str_in == str_out, "input "..str_in) print("output "..str_out) print('Pack length '..#pack_str) end print("\n================= Test msgpack on String ==================") TEST_STRING("\"License\" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. ") TEST_STRING('hello') TEST_STRING('') -- unpacker ----[[ print("\n================= Test unpacker ==================") local file = io.open('dummy_mp_data.msg', 'r'); local dataset = {} if file then --local file_str = file:read('*a') local t0 = unix.time() local unpacker = msgpack.unpacker(2048) local buf,nbuf = file:read(512),0 while buf do nbuf = nbuf + #buf local res,left = unpacker:feed(buf) local tbl = unpacker:pull() --print(res,left,nbuf,type(tbl)) while tbl do --util.ptable(tbl) dataset[#dataset+1] = tbl tbl = unpacker:pull() end buf = file:read(left) end print("streaming unpack ", #dataset, (unix.time() - t0)) print("with pack length ",nbuf) file:close() end t0 = unix.time() local len = 0 for i = 1, #dataset do local pack_str = msgpack.pack(dataset[i]) len = len + #pack_str end print("pack "..#dataset.." tables takes "..(unix.time() - t0).."with pack length "..len) --[[ print("\n================= Test Msgpack for lightuserdata ==================") package.cpath = '../carray/?.so;'..package.cpath local carray = require 'carray' local ud = carray.float(1081) for i = 1, 1081 do ud[i] = math.pi * i end -- lightuserdata, len = ud:pointer() local pack_str = msgpack.pack(ud:pointer()) local dp = carray.float(msgpack.unpack(pack_str)) print("test case ", ud == dp) --]] --[[ function TEST_TORCH(aa) local pack_str = msgpack.pack(aa) local tbl = msgpack.unpack(pack_str) for k, v in pairs(tbl) do print('Key:', k, 'Value:', v) end print('pack size:',#pack_str) end print("\n================= Test Msgpack for Torch ==================") local torch = require 'torch' aa = torch.DoubleTensor({{3.0, 4.0, 5.24, 6.123, 7.90}, {1,2,3,4,5}}) TEST_TORCH(aa) aa = torch.CharTensor({{-1,4,-6},{7,8,9},{-10, -30, -40}}) TEST_TORCH(aa) aa = torch.IntTensor(3,3):fill(1) TEST_TORCH(aa) aa = torch.DoubleTensor(3,3,3):rand(3,3,3) TEST_TORCH(aa) package.path = '../../Util/?.lua;'..package.path local torch = require 'torch' local util = require 'util' local aa = torch.DoubleTensor({{3.0, 4.0, 5.24, 6.123, 7.90}, {1,2,3,4,5}}) local pack_str = msgpack.pack(aa) local tbl = msgpack.unpack(pack_str) util.ptable(tbl) local ttbl = msgpack.unpack(pack_str, 'torch') print("\n Print Torch") util.ptorch(ttbl) local aa = 12 local pack_str = msgpack.pack(aa) local na = msgpack.unpack(pack_str, 'torch') print("\n Print Torch") util.ptorch(na) --]]
--[[-- Copyright 2022 brunoais Licensed under the Apache License with acknowledgement, Version 1.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://github.com/brunoais/Transport-fever-event-log/blob/master/License 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. ]] require "serialize" local modules = require "utils.modules" local MAIN_MODULE = "main" local mainLoaded = modules.tryRequire(MAIN_MODULE) modules.defaultAllReload() local script = { handleEvent = function(src, id, name, param) return mainLoaded.handleEvent(src, id, name, param) end, save = function() return mainLoaded.save() end, load = function(data) return mainLoaded.load(data) end, guiUpdate = function() return mainLoaded.guiUpdate() end, guiHandleEvent = function(src, name, param) -- Reload when user opens the game menu local doreload = src == "ingameMenu.quitButton" and name == "visibilityChange" if doreload then mainLoaded = modules.tryRequire(MAIN_MODULE) end mainLoaded.guiHandleEvent(src, name, param) end } function data() print("Eventlog request for data") return script end
BattleGroundEnemiesDB = { ["profileKeys"] = { ["Хагаки - Гордунни"] = "Default", ["Антижив - Гордунни"] = "Default", ["Индиписатель - Гордунни"] = "Default", ["Килком - Гордунни"] = "Default", ["Антипохер - Гордунни"] = "Default", }, ["profiles"] = { ["Default"] = { ["Enemies"] = { ["15"] = { ["Position_Y"] = 768.000045072113, ["Position_X"] = 199.220212114033, }, }, ["Allies"] = { ["Enabled"] = false, ["15"] = { ["Position_Y"] = 768.000045072113, ["Position_X"] = 2.74038724384354, }, }, }, }, }
local shared = require("scripts.stageapi.shared") function StageAPI.LevelRoomArgPacker(layoutName, roomsList, seed, shape, roomType, isExtraRoom, fromSaveData, requireRoomType, ignoreDoors, doors, levelIndex, ignoreRoomRules) return { LayoutName = layoutName, RoomsList = roomsList, SpawnSeed = seed, Shape = shape, RoomType = roomType, IsExtraRoom = isExtraRoom, FromSave = fromSaveData, RequireRoomType = requireRoomType, IgnoreDoors = ignoreDoors, Doors = doors, LevelIndex = levelIndex, IgnoreRoomRules = ignoreRoomRules } end local levelRoomCopyFromArgs = {"IsExtraRoom","LevelIndex", "IgnoreDoors","Doors", "IgnoreShape","Shape","RoomType","SpawnSeed","LayoutName","RequireRoomType","IgnoreRoomRules","DecorationSeed","AwardSeed","VisitCount","IsClear","ClearCount","IsPersistentRoom","HasWaterPits","ChallengeDone","FromData","Dimension","RoomsListName","RoomsListID"} StageAPI.LevelRoom = StageAPI.Class("LevelRoom") StageAPI.NextUniqueRoomIdentifier = 0 function StageAPI.LevelRoom:Init(args, ...) if type(args) ~= "table" then args = StageAPI.LevelRoomArgPacker(args, ...) end StageAPI.LogMinor("Initializing room") StageAPI.CurrentlyInitializing = self self.UniqueRoomIdentifier = StageAPI.NextUniqueRoomIdentifier StageAPI.NextUniqueRoomIdentifier = StageAPI.NextUniqueRoomIdentifier + 1 if args.FromSave then StageAPI.LogMinor("Loading from save data") self:LoadSaveData(args.FromSave) else StageAPI.LogMinor("Generating room") local roomDesc = args.RoomDescriptor self.Data = {} self.PersistentData = {} self.AvoidSpawning = {} self.ExtraSpawn = {} self.PersistenceData = {} self.FirstLoad = true for _, v in ipairs(levelRoomCopyFromArgs) do if args[v] ~= nil then self[v] = args[v] end end self.RoomType = self.RoomType or (roomDesc and roomDesc.Data.Type) or RoomType.ROOM_DEFAULT self.Shape = self.Shape or (roomDesc and roomDesc.Data.Shape) or RoomShape.ROOMSHAPE_1x1 self.SpawnSeed = self.SpawnSeed or (roomDesc and roomDesc.SpawnSeed) or Random() self.DecorationSeed = self.DecorationSeed or (roomDesc and roomDesc.DecorationSeed) or Random() self.AwardSeed = self.AwardSeed or (roomDesc and roomDesc.AwardSeed) or Random() self.SurpriseMiniboss = self.SurpriseMiniboss or (roomDesc and roomDesc.SurpriseMiniboss) or false self.Doors = self.Doors or (roomDesc and StageAPI.GetDoorsForRoomFromData(roomDesc.Data)) or StageAPI.Copy(StageAPI.AllDoorsOpen) self.VisitCount = self.VisitCount or (roomDesc and roomDesc.VisitedCount) or 0 self.ClearCount = self.ClearCount or (roomDesc and roomDesc.ClearCount) or 0 self.Dimension = self.Dimension or StageAPI.GetDimension(roomDesc) if args.RoomsList then self.RoomsListName = self.RoomsListName or args.RoomsList.Name end -- backwards compatibility self.Seed = self.SpawnSeed self:GetLayout() self:PostGetLayout(self.SpawnSeed) end StageAPI.CallCallbacks("POST_ROOM_INIT", false, self, not not fromSaveData, fromSaveData) StageAPI.CurrentlyInitializing = nil end function StageAPI.LevelRoom:Copy(roomDesc) local args = { RoomDescriptor = roomDesc, Layout = self.Layout, LayoutName = self.LayoutName, RoomsListName = self.RoomsListName } for _, v in ipairs(levelRoomCopyFromArgs) do args[v] = args[v] or self[v] end local newLevelRoom = StageAPI.LevelRoom(args) newLevelRoom.PersistentData = StageAPI.DeepCopy(self.PersistentData) newLevelRoom.Data = StageAPI.DeepCopy(self.Data) return newLevelRoom end function StageAPI.LevelRoom:GetLayout() if self.FromData and not self.Layout then local roomDesc = shared.Level:GetRooms():Get(self.FromData) if roomDesc then self.Layout = StageAPI.GenerateRoomLayoutFromData(roomDesc.Data) end end if self.LayoutName and not self.Layout then self.Layout = StageAPI.Layouts[self.LayoutName] end if self.RoomsListName and self.RoomsListID and not self.Layout then local roomsList = StageAPI.RoomsLists[self.RoomsListName] if roomsList then local layouts = roomsList:GetRooms(self.Shape) if layouts and layouts[self.RoomsListID] then self.Layout = layouts[self.RoomsListID] end end end if self.RoomsListName and not self.Layout then local roomsList = StageAPI.CallCallbacks("PRE_ROOMS_LIST_USE", true, self) or StageAPI.RoomsLists[self.RoomsListName] if roomsList then self.RoomsListName = roomsList.Name local retLayout = StageAPI.CallCallbacks("PRE_ROOM_LAYOUT_CHOOSE", true, self, roomsList) if retLayout then self.Layout = retLayout else self.Layout = StageAPI.ChooseRoomLayout{ RoomList = roomsList, Seed = self.SpawnSeed, IgnoreShape = self.IgnoreShape, Shape = self.Shape, RoomType = self.RoomType, RequireRoomType = self.RequireRoomType, IgnoreDoors = self.IgnoreDoors, Doors = self.Doors } if self.IgnoreShape then self.Shape = self.Layout.Shape end if self.IgnoreDoors then self.Doors = {} for _, door in ipairs(self.Layout.Doors) do self.Doors[door.Slot] = door.Exists end end end end end end function StageAPI.LevelRoom:PostGetLayout(seed) if not self.Layout then if self.Shape == -1 then self.Shape = RoomShape.ROOMSHAPE_1x1 end self.Layout = StageAPI.CreateEmptyRoomLayout(self.Shape) StageAPI.LogErr("No layout!") end StageAPI.LogMinor("Initialized room " .. self.Layout.Name .. "." .. tostring(self.Layout.Variant) .. " from file " .. tostring(self.Layout.RoomFilename) .. (roomsList and (' from list ' .. roomsList.Name) or '')) if self.Shape == -1 then self.Shape = self.Layout.Shape end self.SpawnEntities, self.SpawnGrids, self.EntityTakenIndices, self.GridTakenIndices, self.LastPersistentIndex, self.Metadata = StageAPI.ObtainSpawnObjects(self.Layout, seed) self.Metadata.LevelRoom = self end function StageAPI.LevelRoom:IsGridIndexFree(index, ignoreEntities, ignoreGrids) return (ignoreEntities or not self.EntityTakenIndices[index]) and (ignoreGrids or not self.GridTakenIndices[index]) end function StageAPI.LevelRoom:SaveGridInformation() self.GridInformation = StageAPI.GetGridInformation() end function StageAPI.LevelRoom:GetPersistenceData(index, setIfNot) if type(index) ~= "number" then if index.Metadata then index = index.PersistentIndex else index = StageAPI.GetEntityPersistenceData(index) end end if index then if setIfNot and not self.PersistenceData[index] then self.PersistenceData[index] = {} end return self.PersistenceData[index] end end function StageAPI.LevelRoom:GetNextPersistentIndex() self.LastPersistentIndex = self.LastPersistentIndex + 1 return self.LastPersistentIndex end function StageAPI.LevelRoom:SavePersistentEntities() local checkExistenceOf = {} for hash, entityPersistData in pairs(StageAPI.ActiveEntityPersistenceData) do if entityPersistData.Data.RemoveOnRemove then checkExistenceOf[hash] = entityPersistData end end for _, entity in ipairs(Isaac.GetRoomEntities()) do checkExistenceOf[GetPtrHash(entity)] = nil local data = entity:GetData() local persistentIndex, persistData = StageAPI.GetEntityPersistenceData(entity) if persistentIndex then local changedSpawn local entityPersistData = self:GetPersistenceData(persistentIndex, true) if persistData.UpdateType then if entity.Type ~= entityPersistData.Type then entityPersistData.Type = entity.Type changedSpawn = true end end if persistData.UpdateVariant then if entity.Variant ~= entityPersistData.Variant then entityPersistData.Variant = entity.Variant changedSpawn = true end end if persistData.UpdateSubType then if entity.SubType ~= entityPersistData.SubType then entityPersistData.SubType = entity.SubType changedSpawn = true end end if persistData.UpdateHealth then if entity.HitPoints ~= entityPersistData.Health then entityPersistData.Health = entity.HitPoints end end if persistData.UpdatePosition then entityPersistData.Position = {X = entity.Position.X, Y = entity.Position.Y} end if persistData.StoreCheck and persistData.StoreCheck(entity, data) then self.AvoidSpawning[persistentIndex] = true end if changedSpawn then local newPersistData = StageAPI.CheckPersistence(entity.Type, entity.Variant, entity.SubType) if not newPersistData then StageAPI.RemovePersistentEntity(entity) else StageAPI.SetEntityPersistenceData(entity, persistentIndex, newPersistData) end end else local persistData = StageAPI.CheckPersistence(entity.Type, entity.Variant, entity.SubType) if persistData then if not persistData.StoreCheck or not persistData.StoreCheck(entity, data) then local index = self:GetNextPersistentIndex() local grindex = shared.Room:GetGridIndex(entity.Position) if not self.ExtraSpawn[grindex] then self.ExtraSpawn[grindex] = {} end local spawnData = { Type = entity.Type, Variant = entity.Variant, SubType = entity.SubType, Index = grindex } local spawnInfo = { Data = spawnData, Persistent = true, PersistentIndex = index } self.ExtraSpawn[grindex][#self.ExtraSpawn[grindex] + 1] = spawnInfo local entityPersistData = self:GetPersistenceData(index, true) if persistData.UpdateHealth then entityPersistData.Health = entity.HitPoints end if persistData.UpdatePosition then entityPersistData.Position = {X = entity.Position.X, Y = entity.Position.Y} end StageAPI.SetEntityPersistenceData(entity, index, persistData) end end end end for hash, entityPersistData in pairs(checkExistenceOf) do self.AvoidSpawning[entityPersistData.Index] = true end end function StageAPI.LevelRoom:RemovePersistentIndex(persistentIndex) self.AvoidSpawning[persistentIndex] = true end function StageAPI.LevelRoom:RemovePersistentEntity(entity) local index, data = StageAPI.GetEntityPersistenceData(entity) if index and data then self:RemovePersistentIndex(index) end end function StageAPI.LevelRoom:Load(isExtraRoom, noIncrementVisit) StageAPI.LogMinor("Loading room " .. self.Layout.Name .. "." .. tostring(self.Layout.Variant) .. " from file " .. tostring(self.Layout.RoomFilename)) if isExtraRoom == nil then isExtraRoom = self.IsExtraRoom end shared.Room:SetClear(true) if not noIncrementVisit then self.VisitCount = self.VisitCount + 1 end local wasFirstLoad = self.FirstLoad StageAPI.ClearRoomLayout(false, self.FirstLoad or isExtraRoom, true, self.FirstLoad or isExtraRoom, self.GridTakenIndices, nil, nil, not self.FirstLoad) if self.FirstLoad then StageAPI.LoadRoomLayout(self.SpawnGrids, {self.SpawnEntities, self.ExtraSpawn}, true, true, self.IsClear, true, self.GridInformation, self.AvoidSpawning, self.PersistenceData) self.WasClearAtStart = shared.Room:IsClear() self.IsClear = self.WasClearAtStart self.FirstLoad = false self.HasEnemies = shared.Room:GetAliveEnemiesCount() > 0 else StageAPI.LoadRoomLayout(self.SpawnGrids, {self.SpawnEntities, self.ExtraSpawn}, isExtraRoom, true, self.IsClear, isExtraRoom, self.GridInformation, self.AvoidSpawning, self.PersistenceData) self.IsClear = shared.Room:IsClear() end StageAPI.CalledRoomUpdate = true shared.Room:Update() StageAPI.CalledRoomUpdate = false if not self.IsClear then StageAPI.CloseDoors() end self.Loaded = true StageAPI.CallCallbacks("POST_ROOM_LOAD", false, self, wasFirstLoad, isExtraRoom) StageAPI.StoreRoomGrids() end function StageAPI.LevelRoom:Save() self:SavePersistentEntities() self:SaveGridInformation() end local saveDataCopyDirectly = { "IsClear","WasClearAtStart","RoomsListName","RoomsListID","LayoutName","SpawnSeed","AwardSeed","DecorationSeed", "FirstLoad","Shape","RoomType","TypeOverride","PersistentData","IsExtraRoom","LastPersistentIndex", "RequireRoomType", "IgnoreRoomRules", "VisitCount", "ClearCount", "LevelIndex","HasWaterPits","ChallengeDone", "SurpriseMiniboss", "FromData", "Dimension" } function StageAPI.LevelRoom:GetSaveData(isExtraRoom) if isExtraRoom == nil then isExtraRoom = self.IsExtraRoom end local saveData = {} for _, v in ipairs(saveDataCopyDirectly) do saveData[v] = self[v] end if isExtraRoom ~= nil then saveData.IsExtraRoom = isExtraRoom end if self.Doors then saveData.Doors = {} for i = 0, 7 do if self.Doors[i] then saveData.Doors[#saveData.Doors + 1] = i end end end if self.GridInformation then for index, gridInfo in pairs(self.GridInformation) do if not saveData.GridInformation then saveData.GridInformation = {} end saveData.GridInformation[tostring(index)] = gridInfo end end for index, avoid in pairs(self.AvoidSpawning) do if avoid then if not saveData.AvoidSpawning then saveData.AvoidSpawning = {} end saveData.AvoidSpawning[#saveData.AvoidSpawning + 1] = index end end for pindex, persistData in pairs(self.PersistenceData) do if not saveData.PersistenceData then saveData.PersistenceData = {} end saveData.PersistenceData[tostring(pindex)] = persistData end for index, entities in pairs(self.ExtraSpawn) do if not saveData.ExtraSpawn then saveData.ExtraSpawn = {} end saveData.ExtraSpawn[tostring(index)] = entities end return saveData end function StageAPI.LevelRoom:LoadSaveData(saveData) self.Data = {} self.AvoidSpawning = {} self.PersistenceData = {} self.ExtraSpawn = {} for _, v in ipairs(saveDataCopyDirectly) do self[v] = saveData[v] end self.Seed = self.AwardSeed -- backwards compatibility self.PersistentData = self.PersistentData or {} if saveData.Doors then self.Doors = {} for _, door in ipairs(saveData.Doors) do self.Doors[door] = true end for i = 0, 7 do if not self.Doors[i] then self.Doors[i] = false end end end self:GetLayout() self:PostGetLayout(self.SpawnSeed) self.LastPersistentIndex = self.LastPersistentIndex or self.LastPersistentIndex if saveData.GridInformation then for strindex, gridInfo in pairs(saveData.GridInformation) do if not self.GridInformation then self.GridInformation = {} end self.GridInformation[tonumber(strindex)] = gridInfo end end if saveData.AvoidSpawning then for _, index in ipairs(saveData.AvoidSpawning) do self.AvoidSpawning[index] = true end end if saveData.PersistenceData then for pindex, persistData in pairs(saveData.PersistenceData) do self.PersistenceData[tonumber(strindex)] = persistData end end if saveData.ExtraSpawn then for strindex, entities in pairs(saveData.ExtraSpawn) do self.ExtraSpawn[tonumber(strindex)] = entities end end end function StageAPI.LevelRoom:SetTypeOverride(override) self.TypeOverride = override end function StageAPI.LevelRoom:GetType() return self.TypeOverride or self.RoomType end
PLUGIN.name = 'Interaction Generator' PLUGIN.author = 'TomSL #1104 / ZeMysticalTaco' PLUGIN.description = 'Dave, why do you do the things you do?' ix.interaction = {} ix.interaction.entities = {} ix.interaction.markers = {} PLUGIN.markers = ix.interaction.markers PLUGIN.markerIndex = 1 PLUGIN.interactables = {} --Markers are used with the Interaction Generator. They're used to mark specific points in the world that local playerMeta = FindMetaTable('Player') local PLUGIN = PLUGIN ix.util.Include('sh_trigger.lua') ix.util.Include('sh_event.lua') if SERVER then util.AddNetworkString('MarkerSendMarker') util.AddNetworkString('MarkerRequestMarkers') util.AddNetworkString('MarkerSendMarkers') --SendMarkers is a more efficient version of SendMarker. util.AddNetworkString('InteractionGenerator_RequestCurrentEvent') util.AddNetworkString('InteractionGenerator_SendCurrentEvent') net.Receive('MarkerRequestMarkers', function(len, ply) if ply.requestedMarkers then return end --no lag here sir. for k, v in pairs(PLUGIN.markers) do PLUGIN:SendMarker(ply, v) end ix.log.AddRaw('Sent all markers to ' .. ply:Name()) ply.requestedMarkers = true end) end function PLUGIN:SendMarker(target, marker, bBroadcast) net.Start('MarkerSendMarkers') net.WriteString(marker.name) net.WriteVector(marker.pos) net.WriteAngle(marker.ang) net.WriteAngle(marker.eyeAng) net.WriteUInt(marker.index, 16) if bBroadcast then net.Broadcast() return end net.Send(target) end ix.command.Add('Marker', { description = 'Creates a marker at the position and direction you are facing.', privilege = 'Production', arguments = { ix.type.string, bit.bor(ix.type.bool, ix.type.optional) }, alias = { 'M' }, OnRun = function(self, client, markerName, bSendToClients) local marker = { pos = client:GetPos(), eyeAng = client:EyeAngles(), ang = client:GetAngles(), name = markerName, bSendToClients = bSendToClients, index = PLUGIN.markerIndex } PLUGIN.markerIndex = PLUGIN.markerIndex + 1 //increment index for marker UI ID PLUGIN.markers[markerName] = marker PLUGIN:SendMarker(client, marker) if bSendToClients then PLUGIN:SendMarker(nil, marker, true) end end }) ix.command.Add('MarkerInfo', { description = 'Output info about a marker.', arguments = ix.type.string, privilege = 'Production', OnRun = function(self, client, markerName) local marker = PLUGIN.markers[markerName] if not marker then client:Notify('That marker does not exist!') return end local output = { pos = 'Marker position: %s', ang = 'Marker angles: %s', eyeAng = 'Marker eye angles: %s', name = 'Marker name: %s', index = 'Marker index: %s' } client:ChatPrint(Format('--MARKER INFO: %s--', marker.name)) for k, v in pairs(output) do client:ChatPrint(Format(v, tostring(marker[k]))) end client:ChatPrint('--END MARKER INFO--') end }) function PLUGIN:SaveMarkers(name) end function PLUGIN:LoadMarkers(name) end ix.command.Add('SaveMarkers', { description = 'Save all currently active markers under a name.', arguments = ix.type.text, privilege = 'Production', OnRun = function(self, client, saveName) PLUGIN:SaveMarkers(saveName) end }) ix.command.Add('LoadMarkers', { description = 'Load markers from a save file.', arguments = ix.type.text, privilege = 'Production', OnRun = function(self, client, saveName) PLUGIN:LoadMarkers(saveName) end }) ix.command.Add('ClearMarkers', { description = 'Kills all active markers.', privilege = 'Production', OnRun = function(self, client) PLUGIN.markers = { } net.Start('MarkerClearMarkers') net.Broadcast() ix.log.AddRaw(client:Name() .. ' cleared all markers.') end }) if CLIENT then net.Receive('MarkerSendMarker', function(len, ply) local marker = net.ReadTable() PLUGIN.markers[marker.name] = marker end) hook.Add('InitPostEntity', 'MarkerLoadActiveMarkers', function() net.Start('MarkerRequestMarkers') net.SendToServer() end) net.Receive('MarkerSendMarkers', function() local n = net.ReadString() local p = net.ReadVector() local ang = net.ReadAngle() local eyeAng = net.ReadAngle() local index = net.ReadUInt(16) PLUGIN.markers[n] = { pos = p, ang = ang, eyeAng = eyeAng, name = n, index = index } end) end ix.util.Include('sh_tests.lua')
require('vimp') local assert = require("vimp.util.assert") local log = require("vimp.util.log") local helpers = require("vimp.testing.helpers") local TestKeys1 = '<F4>' local TestKeys2 = '<F5>' local Tester do local _class_0 local _base_0 = { test_multiple_lhs = function(self) helpers.unlet('foo') vimp.nnoremap({ TestKeys1, TestKeys2 }, [[:let g:foo = 5<cr>]]) assert.is_equal(vim.g.foo, nil) helpers.rinput(TestKeys1) assert.is_equal(vim.g.foo, 5) helpers.unlet('foo') assert.is_equal(vim.g.foo, nil) helpers.rinput(TestKeys2) return assert.is_equal(vim.g.foo, 5) end, test_multiple_modes = function(self) vimp.bind('nx', { TestKeys1, TestKeys2 }, '<right>') helpers.set_lines({ "abc def" }) helpers.input('0') helpers.rinput(TestKeys1) assert.is_equal(helpers.get_cursor_character(), 'b') helpers.rinput(TestKeys2) assert.is_equal(helpers.get_cursor_character(), 'c') helpers.input("0v") helpers.rinput(TestKeys1) helpers.rinput(TestKeys2) helpers.input("d") return assert.is_equal(helpers.get_line(), ' def') end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function() end, __base = _base_0, __name = "Tester" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Tester = _class_0 return _class_0 end
pg = pg or {} pg.enemy_data_statistics_57 = { [10033] = { cannon = 0, battle_unit_type = 35, rarity = 1, speed_growth = 0, pilot_ai_template_id = 20001, air = 0, luck = 0, dodge = 0, wave_fx = "danchuanlanghuaxiao2", cannon_growth = 0, speed = 15, reload_growth = 0, dodge_growth = 0, id = 10033, star = 1, hit = 8, antisub_growth = 0, air_growth = 0, reload = 150, base = 70, durability = 930, armor_growth = 0, torpedo_growth = 1000, luck_growth = 0, hit_growth = 120, armor = 0, torpedo = 100, durability_growth = 2550, antisub = 0, antiaircraft = 0, antiaircraft_growth = 0, appear_fx = { "appearsmall" }, equipment_list = { 319070 } }, [10034] = { cannon = 180, reload = 150, speed_growth = 0, cannon_growth = 0, pilot_ai_template_id = 80000, air = 0, rarity = 1, dodge = 0, torpedo = 300, durability_growth = 2550, antiaircraft = 0, reload_growth = 0, dodge_growth = 0, hit_growth = 1200, star = 2, hit = 81, antisub_growth = 0, air_growth = 0, battle_unit_type = 15, base = 80, durability = 360, armor_growth = 0, torpedo_growth = 1200, luck_growth = 0, speed = 30, luck = 0, id = 10034, antiaircraft_growth = 0, antisub = 0, armor = 0, appear_fx = { "appearsmall" }, equipment_list = { 319071 } }, [10035] = { cannon = 100, reload = 150, speed_growth = 0, cannon_growth = 600, pilot_ai_template_id = 70015, air = 0, rarity = 4, dodge = 18, torpedo = 220, durability_growth = 0, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 159, durability = 42000, armor_growth = 0, torpedo_growth = 4400, luck_growth = 0, speed = 36, luck = 0, id = 10035, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 319005, 319006, 319007 } }, [10036] = { cannon = 100, reload = 150, speed_growth = 0, cannon_growth = 600, pilot_ai_template_id = 70016, air = 0, rarity = 4, dodge = 0, torpedo = 220, durability_growth = 0, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 4, hit = 5, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 158, durability = 42000, armor_growth = 0, torpedo_growth = 4400, luck_growth = 0, speed = 15, luck = 0, id = 10036, antiaircraft_growth = 2200, antisub = 0, armor = 6, equipment_list = { 319072, 319073, 319074 } }, [10037] = { cannon = 190, reload = 150, speed_growth = 0, cannon_growth = 1650, rarity = 3, air = 0, torpedo = 260, dodge = 7, durability_growth = 0, antiaircraft = 125, luck = 0, reload_growth = 0, dodge_growth = 102, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 201, durability = 1, armor_growth = 0, torpedo_growth = 2700, luck_growth = 0, speed = 18, armor = 0, id = 10037, antiaircraft_growth = 3280, antisub = 0, equipment_list = { 319036, 319037, 319038, 319039 } }, [10038] = { cannon = 260, reload = 150, speed_growth = 0, cannon_growth = 1750, pilot_ai_template_id = 20001, air = 0, rarity = 4, dodge = 7, torpedo = 320, durability_growth = 0, antiaircraft = 180, reload_growth = 0, dodge_growth = 102, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 208, durability = 42000, armor_growth = 0, torpedo_growth = 3200, luck_growth = 0, speed = 18, luck = 0, id = 10038, antiaircraft_growth = 2820, antisub = 0, armor = 0, equipment_list = { 100562 } }, [10039] = { cannon = 260, reload = 150, speed_growth = 0, cannon_growth = 1750, pilot_ai_template_id = 20001, air = 0, rarity = 4, dodge = 7, torpedo = 320, durability_growth = 0, antiaircraft = 180, reload_growth = 0, dodge_growth = 102, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 207, durability = 42000, armor_growth = 0, torpedo_growth = 3200, luck_growth = 0, speed = 18, luck = 0, id = 10039, antiaircraft_growth = 2820, antisub = 0, armor = 0, equipment_list = { 100562 } }, [10040] = { cannon = 210, reload = 150, speed_growth = 0, cannon_growth = 1550, rarity = 3, air = 0, torpedo = 280, dodge = 7, durability_growth = 0, antiaircraft = 135, luck = 0, reload_growth = 0, dodge_growth = 102, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 203, durability = 1, armor_growth = 0, torpedo_growth = 2800, luck_growth = 0, speed = 18, armor = 0, id = 10040, antiaircraft_growth = 3380, antisub = 0, appear_fx = { "appearQ" }, equipment_list = { 319046, 319047, 319048, 319049 } }, [10041] = { cannon = 120, reload = 150, speed_growth = 0, cannon_growth = 600, pilot_ai_template_id = 30000, air = 0, rarity = 3, dodge = 18, torpedo = 260, durability_growth = 0, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 60, base = 171, durability = 40000, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 10041, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 319526 } }, [10042] = { cannon = 120, reload = 150, speed_growth = 0, cannon_growth = 600, pilot_ai_template_id = 30001, air = 0, rarity = 3, dodge = 18, torpedo = 260, durability_growth = 0, antiaircraft = 105, reload_growth = 0, dodge_growth = 270, hit_growth = 210, star = 3, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 50, base = 175, durability = 40000, armor_growth = 0, torpedo_growth = 5200, luck_growth = 0, speed = 36, luck = 0, id = 10042, antiaircraft_growth = 2200, antisub = 0, armor = 0, appear_fx = { "appearQ" }, equipment_list = { 319526 } }, [10043] = { cannon = 280, name = "强化自爆船", antiaircraft_growth = 0, speed_growth = 0, pilot_ai_template_id = 80000, air = 0, speed = 30, dodge = 0, id = 10043, cannon_growth = 0, air_growth = 0, reload_growth = 0, dodge_growth = 0, luck = 0, star = 2, hit = 81, antisub_growth = 0, rarity = 1, reload = 150, base = 80, durability = 1600, armor_growth = 0, torpedo_growth = 1200, antiaircraft = 0, hit_growth = 1200, armor = 0, torpedo = 400, durability_growth = 2550, antisub = 0, luck_growth = 0, battle_unit_type = 15, appear_fx = { "appearsmall" }, equipment_list = { 319071 } }, [10044] = { cannon = 320, reload = 150, speed_growth = 0, cannon_growth = 3350, pilot_ai_template_id = 10001, air = 0, rarity = 4, dodge = 7, torpedo = 0, durability_growth = 80000, antiaircraft = 175, reload_growth = 0, dodge_growth = 102, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 65, base = 219, durability = 30800, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 0, luck = 0, id = 10044, antiaircraft_growth = 4280, antisub = 0, armor = 0, equipment_list = { 319053 }, buff_list = { { ID = 50510, LV = 4 } } }, [10045] = { cannon = 320, reload = 150, speed_growth = 0, cannon_growth = 3350, pilot_ai_template_id = 10001, air = 0, rarity = 4, dodge = 7, torpedo = 0, durability_growth = 80000, antiaircraft = 175, reload_growth = 0, dodge_growth = 102, hit_growth = 210, star = 4, hit = 20, antisub_growth = 0, air_growth = 0, battle_unit_type = 65, base = 221, durability = 30800, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 0, luck = 0, id = 10045, antiaircraft_growth = 4280, antisub = 0, armor = 0, equipment_list = { 319057 }, buff_list = { { ID = 50510, LV = 4 } } }, [10046] = { cannon = 15, reload = 150, speed_growth = 0, cannon_growth = 0, pilot_ai_template_id = 10002, air = 0, rarity = 1, dodge = 0, torpedo = 200, durability_growth = 0, antiaircraft = 0, reload_growth = 0, dodge_growth = 0, hit_growth = 120, star = 2, hit = 8, antisub_growth = 0, air_growth = 0, battle_unit_type = 65, base = 129, durability = 450, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 8, luck = 0, id = 10046, antiaircraft_growth = 0, antisub = 0, armor = 0, equipment_list = { 100581, 100584 } }, [10047] = { cannon = 200, reload = 150, speed_growth = 0, cannon_growth = 0, rarity = 1, air = 0, torpedo = 850, dodge = 5, durability_growth = 0, antiaircraft = 0, luck = 0, reload_growth = 0, dodge_growth = 72, hit_growth = 210, star = 2, hit = 14, antisub_growth = 0, air_growth = 0, battle_unit_type = 95, base = 268, durability = 3960, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 12, armor = 0, id = 10047, antiaircraft_growth = 0, antisub = 0, scale = 150, equipment_list = { 319523, 319524, 319525 } }, [1005101] = { cannon = 360, reload = 150, speed_growth = 0, cannon_growth = 0, pilot_ai_template_id = 50006, air = 0, rarity = 4, dodge = 70, torpedo = 320, durability_growth = 0, antiaircraft = 280, reload_growth = 0, dodge_growth = 0, hit_growth = 0, star = 5, hit = 45, antisub_growth = 0, air_growth = 0, battle_unit_type = 95, base = 168, durability = 46000, armor_growth = 0, torpedo_growth = 0, luck_growth = 0, speed = 26, luck = 0, id = 1005101, antiaircraft_growth = 0, antisub = 0, armor = 0, appear_fx = { "bossguangxiao", "appearQ" }, equipment_list = { 319528, 319501 } } } return
-- local M = {} local _TYPEDEF = require('tf.c.ctypes').typedef local _ENUMDEF = require('tf.c.ctypes').enumdef local _CALL = require('tf.c.ctypes').caller(require('tf.c._lib')) local _FUNCDEF = require('tf.c.ctypes').addDef -- header/c_api.h -- --- -------------------------------------------------------------------------- --- -------------------------------------------------------------------------- --- TF_Version returns a string describing version information of the --- TensorFlow library. TensorFlow using semantic versioning. --- ---@return string @(const char *) function M.TF_Version() return _CALL("TF_Version") end _FUNCDEF("TF_Version", { }, "const char *") -- --- -------------------------------------------------------------------------- --- TF_Buffer holds a pointer to a block of data and its associated length. --- Typically, the data consists of a serialized protocol buffer, but other data --- may also be held in a buffer. --- By default, TF_Buffer itself does not do any memory management of the --- pointed-to block. If need be, users of this struct should specify how to --- deallocate the block by setting the `data_deallocator` function pointer. --- _TYPEDEF("TF_Buffer", "struct TF_Buffer { const void * data ; size_t length ; void ( * data_deallocator ) ( void * data , size_t length ) ; }") -- --- Makes a copy of the input and sets an appropriate deallocator. Useful for --- passing in read-only, input protobufs. --- ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@return ffi.cdata @(TF_Buffer *) function M.TF_NewBufferFromString(proto, proto_len) return _CALL("TF_NewBufferFromString", proto, proto_len) end _FUNCDEF("TF_NewBufferFromString", { "const void *", "size_t" }, "TF_Buffer *") -- --- Useful for passing *out* a protobuf. --- ---@return ffi.cdata @(TF_Buffer *) function M.TF_NewBuffer() return _CALL("TF_NewBuffer") end _FUNCDEF("TF_NewBuffer", { }, "TF_Buffer *") -- ---@param buffer ffi.cdata @(TF_Buffer *) function M.TF_DeleteBuffer(buffer) return _CALL("TF_DeleteBuffer", buffer) end _FUNCDEF("TF_DeleteBuffer", { "TF_Buffer *" }, "void") -- ---@param buffer ffi.cdata @(TF_Buffer *) ---@return TF_Buffer @(TF_Buffer) function M.TF_GetBuffer(buffer) return _CALL("TF_GetBuffer", buffer) end _FUNCDEF("TF_GetBuffer", { "TF_Buffer *" }, "TF_Buffer") -- --- -------------------------------------------------------------------------- --- Used to return strings across the C API. The caller does not take ownership --- of the underlying data pointer and is not responsible for freeing it. --- _TYPEDEF("TF_StringView", "struct TF_StringView { const char * data ; size_t len ; }") -- --- -------------------------------------------------------------------------- --- TF_SessionOptions holds options that can be passed during session creation. --- _TYPEDEF("TF_SessionOptions", "struct TF_SessionOptions") -- --- Return a new options object. --- ---@return ffi.cdata @(TF_SessionOptions *) function M.TF_NewSessionOptions() return _CALL("TF_NewSessionOptions") end _FUNCDEF("TF_NewSessionOptions", { }, "TF_SessionOptions *") -- --- Set the target in TF_SessionOptions.options. --- target can be empty, a single entry, or a comma separated list of entries. --- Each entry is in one of the following formats : --- "local" --- ip:port --- host:port --- ---@param options ffi.cdata @(TF_SessionOptions *) ---@param target string @(const char *) function M.TF_SetTarget(options, target) return _CALL("TF_SetTarget", options, target) end _FUNCDEF("TF_SetTarget", { "TF_SessionOptions *", "const char *" }, "void") -- --- Set the config in TF_SessionOptions.options. --- config should be a serialized tensorflow.ConfigProto proto. --- If config was not parsed successfully as a ConfigProto, record the --- error information in *status. --- ---@param options ffi.cdata @(TF_SessionOptions *) ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_SetConfig(options, proto, proto_len, status) return _CALL("TF_SetConfig", options, proto, proto_len, status) end _FUNCDEF("TF_SetConfig", { "TF_SessionOptions *", "const void *", "size_t", "TF_Status *" }, "void") -- --- Destroy an options object. --- ---@param options ffi.cdata @(TF_SessionOptions *) function M.TF_DeleteSessionOptions(options) return _CALL("TF_DeleteSessionOptions", options) end _FUNCDEF("TF_DeleteSessionOptions", { "TF_SessionOptions *" }, "void") -- --- TODO(jeff,sanjay): --- - export functions to set Config fields --- -------------------------------------------------------------------------- --- The new graph construction API, still under development. --- Represents a computation graph. Graphs may be shared between sessions. --- Graphs are thread-safe when used as directed below. --- _TYPEDEF("TF_Graph", "struct TF_Graph") -- --- Return a new graph object. --- ---@return ffi.cdata @(TF_Graph *) function M.TF_NewGraph() return _CALL("TF_NewGraph") end _FUNCDEF("TF_NewGraph", { }, "TF_Graph *") -- --- Destroy an options object. Graph will be deleted once no more --- TFSession's are referencing it. --- ---@param graph ffi.cdata @(TF_Graph *) function M.TF_DeleteGraph(graph) return _CALL("TF_DeleteGraph", graph) end _FUNCDEF("TF_DeleteGraph", { "TF_Graph *" }, "void") -- --- Operation being built. The underlying graph must outlive this. --- _TYPEDEF("TF_OperationDescription", "struct TF_OperationDescription") -- --- Operation that has been added to the graph. Valid until the graph is --- deleted -- in particular adding a new operation to the graph does not --- invalidate old TF_Operation* pointers. --- _TYPEDEF("TF_Operation", "struct TF_Operation") -- --- Represents a specific input of an operation. --- The index of the input within oper. --- _TYPEDEF("TF_Input", "struct TF_Input { TF_Operation * oper ; int index ; }") -- --- Represents a specific output of an operation. --- The index of the output within oper. --- _TYPEDEF("TF_Output", "struct TF_Output { TF_Operation * oper ; int index ; }") -- --- TF_Function is a grouping of operations with defined inputs and outputs. --- Once created and added to graphs, functions can be invoked by creating an --- operation whose operation type matches the function name. --- _TYPEDEF("TF_Function", "struct TF_Function") -- --- Function definition options. TODO(iga): Define and implement --- _TYPEDEF("TF_FunctionOptions", "struct TF_FunctionOptions") -- --- Sets the shape of the Tensor referenced by `output` in `graph` to --- the shape described by `dims` and `num_dims`. --- If the number of dimensions is unknown, `num_dims` must be set to --- -1 and `dims` can be null. If a dimension is unknown, the --- corresponding entry in the `dims` array must be -1. --- This does not overwrite the existing shape associated with `output`, --- but merges the input shape with the existing shape. For example, --- setting a shape of [-1, 2] with an existing shape [2, -1] would set --- a final shape of [2, 2] based on shape merging semantics. --- Returns an error into `status` if: --- `output` is not in `graph`. --- An invalid shape is being set (e.g., the shape being set --- is incompatible with the existing shape). --- ---@param graph ffi.cdata @(TF_Graph *) ---@param output TF_Output @(TF_Output) ---@param dims ffi.cdata @(const int64_t *) ---@param num_dims number @(const int) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphSetTensorShape(graph, output, dims, num_dims, status) return _CALL("TF_GraphSetTensorShape", graph, output, dims, num_dims, status) end _FUNCDEF("TF_GraphSetTensorShape", { "TF_Graph *", "TF_Output", "const int64_t *", "const int", "TF_Status *" }, "void") -- --- Returns the number of dimensions of the Tensor referenced by `output` --- in `graph`. --- If the number of dimensions in the shape is unknown, returns -1. --- Returns an error into `status` if: --- `output` is not in `graph`. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param output TF_Output @(TF_Output) ---@param status ffi.cdata @(TF_Status *) ---@return number @(int) function M.TF_GraphGetTensorNumDims(graph, output, status) return _CALL("TF_GraphGetTensorNumDims", graph, output, status) end _FUNCDEF("TF_GraphGetTensorNumDims", { "TF_Graph *", "TF_Output", "TF_Status *" }, "int") -- --- Returns the shape of the Tensor referenced by `output` in `graph` --- into `dims`. `dims` must be an array large enough to hold `num_dims` --- entries (e.g., the return value of TF_GraphGetTensorNumDims). --- If the number of dimensions in the shape is unknown or the shape is --- a scalar, `dims` will remain untouched. Otherwise, each element of --- `dims` will be set corresponding to the size of the dimension. An --- unknown dimension is represented by `-1`. --- Returns an error into `status` if: --- `output` is not in `graph`. --- `num_dims` does not match the actual number of dimensions. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param output TF_Output @(TF_Output) ---@param dims ffi.cdata @(int64_t *) ---@param num_dims number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphGetTensorShape(graph, output, dims, num_dims, status) return _CALL("TF_GraphGetTensorShape", graph, output, dims, num_dims, status) end _FUNCDEF("TF_GraphGetTensorShape", { "TF_Graph *", "TF_Output", "int64_t *", "int", "TF_Status *" }, "void") -- --- Operation will only be added to *graph when TF_FinishOperation() is --- called (assuming TF_FinishOperation() does not return an error). --- graph must not be deleted until after TF_FinishOperation() is --- called. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param op_type string @(const char *) ---@param oper_name string @(const char *) ---@return ffi.cdata @(TF_OperationDescription *) function M.TF_NewOperation(graph, op_type, oper_name) return _CALL("TF_NewOperation", graph, op_type, oper_name) end _FUNCDEF("TF_NewOperation", { "TF_Graph *", "const char *", "const char *" }, "TF_OperationDescription *") -- --- Specify the device for `desc`. Defaults to empty, meaning unconstrained. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param device string @(const char *) function M.TF_SetDevice(desc, device) return _CALL("TF_SetDevice", desc, device) end _FUNCDEF("TF_SetDevice", { "TF_OperationDescription *", "const char *" }, "void") -- --- The calls to TF_AddInput and TF_AddInputList must match (in number, --- order, and type) the op declaration. For example, the "Concat" op --- has registration: --- REGISTER_OP("Concat") --- .Input("concat_dim: int32") --- .Input("values: N * T") --- .Output("output: T") --- .Attr("N: int >= 2") --- .Attr("T: type"); --- that defines two inputs, "concat_dim" and "values" (in that order). --- You must use TF_AddInput() for the first input (since it takes a --- single tensor), and TF_AddInputList() for the second input (since --- it takes a list, even if you were to pass a list with a single --- tensor), as in: --- TF_OperationDescription* desc = TF_NewOperation(graph, "Concat", "c"); --- TF_Output concat_dim_input = {...}; --- TF_AddInput(desc, concat_dim_input); --- TF_Output values_inputs[5] = {{...}, ..., {...}}; --- TF_AddInputList(desc, values_inputs, 5); --- For inputs that take a single tensor. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param input TF_Output @(TF_Output) function M.TF_AddInput(desc, input) return _CALL("TF_AddInput", desc, input) end _FUNCDEF("TF_AddInput", { "TF_OperationDescription *", "TF_Output" }, "void") -- --- For inputs that take a list of tensors. --- inputs must point to TF_Output[num_inputs]. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param inputs ffi.cdata @(const TF_Output *) ---@param num_inputs number @(int) function M.TF_AddInputList(desc, inputs, num_inputs) return _CALL("TF_AddInputList", desc, inputs, num_inputs) end _FUNCDEF("TF_AddInputList", { "TF_OperationDescription *", "const TF_Output *", "int" }, "void") -- --- Call once per control input to `desc`. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param input ffi.cdata @(TF_Operation *) function M.TF_AddControlInput(desc, input) return _CALL("TF_AddControlInput", desc, input) end _FUNCDEF("TF_AddControlInput", { "TF_OperationDescription *", "TF_Operation *" }, "void") -- --- Request that `desc` be co-located on the device where `op` --- is placed. --- Use of this is discouraged since the implementation of device placement is --- subject to change. Primarily intended for internal libraries --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param op ffi.cdata @(TF_Operation *) function M.TF_ColocateWith(desc, op) return _CALL("TF_ColocateWith", desc, op) end _FUNCDEF("TF_ColocateWith", { "TF_OperationDescription *", "TF_Operation *" }, "void") -- --- Call some TF_SetAttr*() function for every attr that is not --- inferred from an input and doesn't have a default value you wish to --- keep. --- `value` must point to a string of length `length` bytes. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(const void *) ---@param length number @(size_t) function M.TF_SetAttrString(desc, attr_name, value, length) return _CALL("TF_SetAttrString", desc, attr_name, value, length) end _FUNCDEF("TF_SetAttrString", { "TF_OperationDescription *", "const char *", "const void *", "size_t" }, "void") -- --- `values` and `lengths` each must have lengths `num_values`. --- `values[i]` must point to a string of length `lengths[i]` bytes. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(const void * const *) ---@param lengths ffi.cdata @(const size_t *) ---@param num_values number @(int) function M.TF_SetAttrStringList(desc, attr_name, values, lengths, num_values) return _CALL("TF_SetAttrStringList", desc, attr_name, values, lengths, num_values) end _FUNCDEF("TF_SetAttrStringList", { "TF_OperationDescription *", "const char *", "const void * const *", "const size_t *", "int" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value number @(int64_t) function M.TF_SetAttrInt(desc, attr_name, value) return _CALL("TF_SetAttrInt", desc, attr_name, value) end _FUNCDEF("TF_SetAttrInt", { "TF_OperationDescription *", "const char *", "int64_t" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(const int64_t *) ---@param num_values number @(int) function M.TF_SetAttrIntList(desc, attr_name, values, num_values) return _CALL("TF_SetAttrIntList", desc, attr_name, values, num_values) end _FUNCDEF("TF_SetAttrIntList", { "TF_OperationDescription *", "const char *", "const int64_t *", "int" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value number @(float) function M.TF_SetAttrFloat(desc, attr_name, value) return _CALL("TF_SetAttrFloat", desc, attr_name, value) end _FUNCDEF("TF_SetAttrFloat", { "TF_OperationDescription *", "const char *", "float" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(const float *) ---@param num_values number @(int) function M.TF_SetAttrFloatList(desc, attr_name, values, num_values) return _CALL("TF_SetAttrFloatList", desc, attr_name, values, num_values) end _FUNCDEF("TF_SetAttrFloatList", { "TF_OperationDescription *", "const char *", "const float *", "int" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value number @(unsigned char) function M.TF_SetAttrBool(desc, attr_name, value) return _CALL("TF_SetAttrBool", desc, attr_name, value) end _FUNCDEF("TF_SetAttrBool", { "TF_OperationDescription *", "const char *", "unsigned char" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(const unsigned char *) ---@param num_values number @(int) function M.TF_SetAttrBoolList(desc, attr_name, values, num_values) return _CALL("TF_SetAttrBoolList", desc, attr_name, values, num_values) end _FUNCDEF("TF_SetAttrBoolList", { "TF_OperationDescription *", "const char *", "const unsigned char *", "int" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value TF_DataType @(TF_DataType) function M.TF_SetAttrType(desc, attr_name, value) return _CALL("TF_SetAttrType", desc, attr_name, value) end _FUNCDEF("TF_SetAttrType", { "TF_OperationDescription *", "const char *", "TF_DataType" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(const TF_DataType *) ---@param num_values number @(int) function M.TF_SetAttrTypeList(desc, attr_name, values, num_values) return _CALL("TF_SetAttrTypeList", desc, attr_name, values, num_values) end _FUNCDEF("TF_SetAttrTypeList", { "TF_OperationDescription *", "const char *", "const TF_DataType *", "int" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param placeholder string @(const char *) function M.TF_SetAttrPlaceholder(desc, attr_name, placeholder) return _CALL("TF_SetAttrPlaceholder", desc, attr_name, placeholder) end _FUNCDEF("TF_SetAttrPlaceholder", { "TF_OperationDescription *", "const char *", "const char *" }, "void") -- --- Set a 'func' attribute to the specified name. --- `value` must point to a string of length `length` bytes. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value string @(const char *) ---@param length number @(size_t) function M.TF_SetAttrFuncName(desc, attr_name, value, length) return _CALL("TF_SetAttrFuncName", desc, attr_name, value, length) end _FUNCDEF("TF_SetAttrFuncName", { "TF_OperationDescription *", "const char *", "const char *", "size_t" }, "void") -- --- Set `num_dims` to -1 to represent "unknown rank". Otherwise, --- `dims` points to an array of length `num_dims`. `dims[i]` must be --- >= -1, with -1 meaning "unknown dimension". --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param dims ffi.cdata @(const int64_t *) ---@param num_dims number @(int) function M.TF_SetAttrShape(desc, attr_name, dims, num_dims) return _CALL("TF_SetAttrShape", desc, attr_name, dims, num_dims) end _FUNCDEF("TF_SetAttrShape", { "TF_OperationDescription *", "const char *", "const int64_t *", "int" }, "void") -- --- `dims` and `num_dims` must point to arrays of length `num_shapes`. --- Set `num_dims[i]` to -1 to represent "unknown rank". Otherwise, --- `dims[i]` points to an array of length `num_dims[i]`. `dims[i][j]` --- must be >= -1, with -1 meaning "unknown dimension". --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param dims ffi.cdata @(const int64_t * const *) ---@param num_dims ffi.cdata @(const int *) ---@param num_shapes number @(int) function M.TF_SetAttrShapeList(desc, attr_name, dims, num_dims, num_shapes) return _CALL("TF_SetAttrShapeList", desc, attr_name, dims, num_dims, num_shapes) end _FUNCDEF("TF_SetAttrShapeList", { "TF_OperationDescription *", "const char *", "const int64_t * const *", "const int *", "int" }, "void") -- --- `proto` must point to an array of `proto_len` bytes representing a --- binary-serialized TensorShapeProto. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_SetAttrTensorShapeProto(desc, attr_name, proto, proto_len, status) return _CALL("TF_SetAttrTensorShapeProto", desc, attr_name, proto, proto_len, status) end _FUNCDEF("TF_SetAttrTensorShapeProto", { "TF_OperationDescription *", "const char *", "const void *", "size_t", "TF_Status *" }, "void") -- --- `protos` and `proto_lens` must point to arrays of length `num_shapes`. --- `protos[i]` must point to an array of `proto_lens[i]` bytes --- representing a binary-serialized TensorShapeProto. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param protos ffi.cdata @(const void * const *) ---@param proto_lens ffi.cdata @(const size_t *) ---@param num_shapes number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_SetAttrTensorShapeProtoList(desc, attr_name, protos, proto_lens, num_shapes, status) return _CALL("TF_SetAttrTensorShapeProtoList", desc, attr_name, protos, proto_lens, num_shapes, status) end _FUNCDEF("TF_SetAttrTensorShapeProtoList", { "TF_OperationDescription *", "const char *", "const void * const *", "const size_t *", "int", "TF_Status *" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(TF_Tensor *) ---@param status ffi.cdata @(TF_Status *) function M.TF_SetAttrTensor(desc, attr_name, value, status) return _CALL("TF_SetAttrTensor", desc, attr_name, value, status) end _FUNCDEF("TF_SetAttrTensor", { "TF_OperationDescription *", "const char *", "TF_Tensor *", "TF_Status *" }, "void") -- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(TF_Tensor * const *) ---@param num_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_SetAttrTensorList(desc, attr_name, values, num_values, status) return _CALL("TF_SetAttrTensorList", desc, attr_name, values, num_values, status) end _FUNCDEF("TF_SetAttrTensorList", { "TF_OperationDescription *", "const char *", "TF_Tensor * const *", "int", "TF_Status *" }, "void") -- --- `proto` should point to a sequence of bytes of length `proto_len` --- representing a binary serialization of an AttrValue protocol --- buffer. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param attr_name string @(const char *) ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_SetAttrValueProto(desc, attr_name, proto, proto_len, status) return _CALL("TF_SetAttrValueProto", desc, attr_name, proto, proto_len, status) end _FUNCDEF("TF_SetAttrValueProto", { "TF_OperationDescription *", "const char *", "const void *", "size_t", "TF_Status *" }, "void") -- --- If this function succeeds: --- *status is set to an OK value, --- a TF_Operation is added to the graph, --- a non-null value pointing to the added operation is returned -- --- this value is valid until the underlying graph is deleted. --- Otherwise: --- *status is set to a non-OK value, --- the graph is not modified, --- a null value is returned. --- In either case, it deletes `desc`. --- ---@param desc ffi.cdata @(TF_OperationDescription *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Operation *) function M.TF_FinishOperation(desc, status) return _CALL("TF_FinishOperation", desc, status) end _FUNCDEF("TF_FinishOperation", { "TF_OperationDescription *", "TF_Status *" }, "TF_Operation *") -- --- TF_Operation functions. Operations are immutable once created, so --- these are all query functions. --- ---@param oper ffi.cdata @(TF_Operation *) ---@return string @(const char *) function M.TF_OperationName(oper) return _CALL("TF_OperationName", oper) end _FUNCDEF("TF_OperationName", { "TF_Operation *" }, "const char *") -- ---@param oper ffi.cdata @(TF_Operation *) ---@return string @(const char *) function M.TF_OperationOpType(oper) return _CALL("TF_OperationOpType", oper) end _FUNCDEF("TF_OperationOpType", { "TF_Operation *" }, "const char *") -- ---@param oper ffi.cdata @(TF_Operation *) ---@return string @(const char *) function M.TF_OperationDevice(oper) return _CALL("TF_OperationDevice", oper) end _FUNCDEF("TF_OperationDevice", { "TF_Operation *" }, "const char *") -- ---@param oper ffi.cdata @(TF_Operation *) ---@return number @(int) function M.TF_OperationNumOutputs(oper) return _CALL("TF_OperationNumOutputs", oper) end _FUNCDEF("TF_OperationNumOutputs", { "TF_Operation *" }, "int") -- ---@param oper_out TF_Output @(TF_Output) ---@return TF_DataType @(TF_DataType) function M.TF_OperationOutputType(oper_out) return _CALL("TF_OperationOutputType", oper_out) end _FUNCDEF("TF_OperationOutputType", { "TF_Output" }, "TF_DataType") -- ---@param oper ffi.cdata @(TF_Operation *) ---@param arg_name string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return number @(int) function M.TF_OperationOutputListLength(oper, arg_name, status) return _CALL("TF_OperationOutputListLength", oper, arg_name, status) end _FUNCDEF("TF_OperationOutputListLength", { "TF_Operation *", "const char *", "TF_Status *" }, "int") -- ---@param oper ffi.cdata @(TF_Operation *) ---@return number @(int) function M.TF_OperationNumInputs(oper) return _CALL("TF_OperationNumInputs", oper) end _FUNCDEF("TF_OperationNumInputs", { "TF_Operation *" }, "int") -- ---@param oper_in TF_Input @(TF_Input) ---@return TF_DataType @(TF_DataType) function M.TF_OperationInputType(oper_in) return _CALL("TF_OperationInputType", oper_in) end _FUNCDEF("TF_OperationInputType", { "TF_Input" }, "TF_DataType") -- ---@param oper ffi.cdata @(TF_Operation *) ---@param arg_name string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return number @(int) function M.TF_OperationInputListLength(oper, arg_name, status) return _CALL("TF_OperationInputListLength", oper, arg_name, status) end _FUNCDEF("TF_OperationInputListLength", { "TF_Operation *", "const char *", "TF_Status *" }, "int") -- --- In this code: --- TF_Output producer = TF_OperationInput(consumer); --- There is an edge from producer.oper's output (given by --- producer.index) to consumer.oper's input (given by consumer.index). --- ---@param oper_in TF_Input @(TF_Input) ---@return TF_Output @(TF_Output) function M.TF_OperationInput(oper_in) return _CALL("TF_OperationInput", oper_in) end _FUNCDEF("TF_OperationInput", { "TF_Input" }, "TF_Output") -- --- Get list of all inputs of a specific operation. `inputs` must point to --- an array of length at least `max_inputs` (ideally set to --- TF_OperationNumInputs(oper)). Beware that a concurrent --- modification of the graph can increase the number of inputs of --- an operation. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param inputs ffi.cdata @(TF_Output *) ---@param max_inputs number @(int) function M.TF_OperationAllInputs(oper, inputs, max_inputs) return _CALL("TF_OperationAllInputs", oper, inputs, max_inputs) end _FUNCDEF("TF_OperationAllInputs", { "TF_Operation *", "TF_Output *", "int" }, "void") -- --- Get the number of current consumers of a specific output of an --- operation. Note that this number can change when new operations --- are added to the graph. --- ---@param oper_out TF_Output @(TF_Output) ---@return number @(int) function M.TF_OperationOutputNumConsumers(oper_out) return _CALL("TF_OperationOutputNumConsumers", oper_out) end _FUNCDEF("TF_OperationOutputNumConsumers", { "TF_Output" }, "int") -- --- Get list of all current consumers of a specific output of an --- operation. `consumers` must point to an array of length at least --- `max_consumers` (ideally set to --- TF_OperationOutputNumConsumers(oper_out)). Beware that a concurrent --- modification of the graph can increase the number of consumers of --- an operation. Returns the number of output consumers (should match --- TF_OperationOutputNumConsumers(oper_out)). --- ---@param oper_out TF_Output @(TF_Output) ---@param consumers ffi.cdata @(TF_Input *) ---@param max_consumers number @(int) ---@return number @(int) function M.TF_OperationOutputConsumers(oper_out, consumers, max_consumers) return _CALL("TF_OperationOutputConsumers", oper_out, consumers, max_consumers) end _FUNCDEF("TF_OperationOutputConsumers", { "TF_Output", "TF_Input *", "int" }, "int") -- --- Get the number of control inputs to an operation. --- ---@param oper ffi.cdata @(TF_Operation *) ---@return number @(int) function M.TF_OperationNumControlInputs(oper) return _CALL("TF_OperationNumControlInputs", oper) end _FUNCDEF("TF_OperationNumControlInputs", { "TF_Operation *" }, "int") -- --- Get list of all control inputs to an operation. `control_inputs` must --- point to an array of length `max_control_inputs` (ideally set to --- TF_OperationNumControlInputs(oper)). Returns the number of control --- inputs (should match TF_OperationNumControlInputs(oper)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param control_inputs ffi.cdata @(TF_Operation * *) ---@param max_control_inputs number @(int) ---@return number @(int) function M.TF_OperationGetControlInputs(oper, control_inputs, max_control_inputs) return _CALL("TF_OperationGetControlInputs", oper, control_inputs, max_control_inputs) end _FUNCDEF("TF_OperationGetControlInputs", { "TF_Operation *", "TF_Operation * *", "int" }, "int") -- --- Get the number of operations that have `*oper` as a control input. --- Note that this number can change when new operations are added to --- the graph. --- ---@param oper ffi.cdata @(TF_Operation *) ---@return number @(int) function M.TF_OperationNumControlOutputs(oper) return _CALL("TF_OperationNumControlOutputs", oper) end _FUNCDEF("TF_OperationNumControlOutputs", { "TF_Operation *" }, "int") -- --- Get the list of operations that have `*oper` as a control input. --- `control_outputs` must point to an array of length at least --- `max_control_outputs` (ideally set to --- TF_OperationNumControlOutputs(oper)). Beware that a concurrent --- modification of the graph can increase the number of control --- outputs. Returns the number of control outputs (should match --- TF_OperationNumControlOutputs(oper)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param control_outputs ffi.cdata @(TF_Operation * *) ---@param max_control_outputs number @(int) ---@return number @(int) function M.TF_OperationGetControlOutputs(oper, control_outputs, max_control_outputs) return _CALL("TF_OperationGetControlOutputs", oper, control_outputs, max_control_outputs) end _FUNCDEF("TF_OperationGetControlOutputs", { "TF_Operation *", "TF_Operation * *", "int" }, "int") -- --- TF_AttrMetadata describes the value of an attribute on an operation. --- A boolean: 1 if the attribute value is a list, 0 otherwise. --- Length of the list if is_list is true. Undefined otherwise. --- Type of elements of the list if is_list != 0. --- Type of the single value stored in the attribute if is_list == 0. --- Total size the attribute value. --- The units of total_size depend on is_list and type. --- (1) If type == TF_ATTR_STRING and is_list == 0 --- then total_size is the byte size of the string --- valued attribute. --- (2) If type == TF_ATTR_STRING and is_list == 1 --- then total_size is the cumulative byte size --- of all the strings in the list. --- (3) If type == TF_ATTR_SHAPE and is_list == 0 --- then total_size is the number of dimensions --- of the shape valued attribute, or -1 --- if its rank is unknown. --- (4) If type == TF_ATTR_SHAPE and is_list == 1 --- then total_size is the cumulative number --- of dimensions of all shapes in the list. --- (5) Otherwise, total_size is undefined. --- _TYPEDEF("TF_AttrMetadata", "struct TF_AttrMetadata { unsigned char is_list ; int64_t list_size ; TF_AttrType type ; int64_t total_size ; }") -- --- Returns metadata about the value of the attribute `attr_name` of `oper`. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return TF_AttrMetadata @(TF_AttrMetadata) function M.TF_OperationGetAttrMetadata(oper, attr_name, status) return _CALL("TF_OperationGetAttrMetadata", oper, attr_name, status) end _FUNCDEF("TF_OperationGetAttrMetadata", { "TF_Operation *", "const char *", "TF_Status *" }, "TF_AttrMetadata") -- --- Fills in `value` with the value of the attribute `attr_name`. `value` must --- point to an array of length at least `max_length` (ideally set to --- TF_AttrMetadata.total_size from TF_OperationGetAttrMetadata(oper, --- attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(void *) ---@param max_length number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrString(oper, attr_name, value, max_length, status) return _CALL("TF_OperationGetAttrString", oper, attr_name, value, max_length, status) end _FUNCDEF("TF_OperationGetAttrString", { "TF_Operation *", "const char *", "void *", "size_t", "TF_Status *" }, "void") -- --- Get the list of strings in the value of the attribute `attr_name`. Fills in --- `values` and `lengths`, each of which must point to an array of length at --- least `max_values`. --- The elements of values will point to addresses in `storage` which must be at --- least `storage_size` bytes in length. Ideally, max_values would be set to --- TF_AttrMetadata.list_size and `storage` would be at least --- TF_AttrMetadata.total_size, obtained from TF_OperationGetAttrMetadata(oper, --- attr_name). --- Fails if storage_size is too small to hold the requested number of strings. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(void * *) ---@param lengths ffi.cdata @(size_t *) ---@param max_values number @(int) ---@param storage ffi.cdata @(void *) ---@param storage_size number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrStringList(oper, attr_name, values, lengths, max_values, storage, storage_size, status) return _CALL("TF_OperationGetAttrStringList", oper, attr_name, values, lengths, max_values, storage, storage_size, status) end _FUNCDEF("TF_OperationGetAttrStringList", { "TF_Operation *", "const char *", "void * *", "size_t *", "int", "void *", "size_t", "TF_Status *" }, "void") -- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(int64_t *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrInt(oper, attr_name, value, status) return _CALL("TF_OperationGetAttrInt", oper, attr_name, value, status) end _FUNCDEF("TF_OperationGetAttrInt", { "TF_Operation *", "const char *", "int64_t *", "TF_Status *" }, "void") -- --- Fills in `values` with the value of the attribute `attr_name` of `oper`. --- `values` must point to an array of length at least `max_values` (ideally set --- TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, --- attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(int64_t *) ---@param max_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrIntList(oper, attr_name, values, max_values, status) return _CALL("TF_OperationGetAttrIntList", oper, attr_name, values, max_values, status) end _FUNCDEF("TF_OperationGetAttrIntList", { "TF_Operation *", "const char *", "int64_t *", "int", "TF_Status *" }, "void") -- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(float *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrFloat(oper, attr_name, value, status) return _CALL("TF_OperationGetAttrFloat", oper, attr_name, value, status) end _FUNCDEF("TF_OperationGetAttrFloat", { "TF_Operation *", "const char *", "float *", "TF_Status *" }, "void") -- --- Fills in `values` with the value of the attribute `attr_name` of `oper`. --- `values` must point to an array of length at least `max_values` (ideally set --- to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, --- attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(float *) ---@param max_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrFloatList(oper, attr_name, values, max_values, status) return _CALL("TF_OperationGetAttrFloatList", oper, attr_name, values, max_values, status) end _FUNCDEF("TF_OperationGetAttrFloatList", { "TF_Operation *", "const char *", "float *", "int", "TF_Status *" }, "void") -- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(unsigned char *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrBool(oper, attr_name, value, status) return _CALL("TF_OperationGetAttrBool", oper, attr_name, value, status) end _FUNCDEF("TF_OperationGetAttrBool", { "TF_Operation *", "const char *", "unsigned char *", "TF_Status *" }, "void") -- --- Fills in `values` with the value of the attribute `attr_name` of `oper`. --- `values` must point to an array of length at least `max_values` (ideally set --- to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, --- attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(unsigned char *) ---@param max_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrBoolList(oper, attr_name, values, max_values, status) return _CALL("TF_OperationGetAttrBoolList", oper, attr_name, values, max_values, status) end _FUNCDEF("TF_OperationGetAttrBoolList", { "TF_Operation *", "const char *", "unsigned char *", "int", "TF_Status *" }, "void") -- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(TF_DataType *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrType(oper, attr_name, value, status) return _CALL("TF_OperationGetAttrType", oper, attr_name, value, status) end _FUNCDEF("TF_OperationGetAttrType", { "TF_Operation *", "const char *", "TF_DataType *", "TF_Status *" }, "void") -- --- Fills in `values` with the value of the attribute `attr_name` of `oper`. --- `values` must point to an array of length at least `max_values` (ideally set --- to TF_AttrMetadata.list_size from TF_OperationGetAttrMetadata(oper, --- attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(TF_DataType *) ---@param max_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrTypeList(oper, attr_name, values, max_values, status) return _CALL("TF_OperationGetAttrTypeList", oper, attr_name, values, max_values, status) end _FUNCDEF("TF_OperationGetAttrTypeList", { "TF_Operation *", "const char *", "TF_DataType *", "int", "TF_Status *" }, "void") -- --- Fills in `value` with the value of the attribute `attr_name` of `oper`. --- `values` must point to an array of length at least `num_dims` (ideally set to --- TF_Attr_Meta.size from TF_OperationGetAttrMetadata(oper, attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(int64_t *) ---@param num_dims number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrShape(oper, attr_name, value, num_dims, status) return _CALL("TF_OperationGetAttrShape", oper, attr_name, value, num_dims, status) end _FUNCDEF("TF_OperationGetAttrShape", { "TF_Operation *", "const char *", "int64_t *", "int", "TF_Status *" }, "void") -- --- Fills in `dims` with the list of shapes in the attribute `attr_name` of --- `oper` and `num_dims` with the corresponding number of dimensions. On return, --- for every i where `num_dims[i]` > 0, `dims[i]` will be an array of --- `num_dims[i]` elements. A value of -1 for `num_dims[i]` indicates that the --- i-th shape in the list is unknown. --- The elements of `dims` will point to addresses in `storage` which must be --- large enough to hold at least `storage_size` int64_ts. Ideally, `num_shapes` --- would be set to TF_AttrMetadata.list_size and `storage_size` would be set to --- TF_AttrMetadata.total_size from TF_OperationGetAttrMetadata(oper, --- attr_name). --- Fails if storage_size is insufficient to hold the requested shapes. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param dims ffi.cdata @(int64_t * *) ---@param num_dims ffi.cdata @(int *) ---@param num_shapes number @(int) ---@param storage ffi.cdata @(int64_t *) ---@param storage_size number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrShapeList(oper, attr_name, dims, num_dims, num_shapes, storage, storage_size, status) return _CALL("TF_OperationGetAttrShapeList", oper, attr_name, dims, num_dims, num_shapes, storage, storage_size, status) end _FUNCDEF("TF_OperationGetAttrShapeList", { "TF_Operation *", "const char *", "int64_t * *", "int *", "int", "int64_t *", "int", "TF_Status *" }, "void") -- --- Sets `value` to the binary-serialized TensorShapeProto of the value of --- `attr_name` attribute of `oper`'. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrTensorShapeProto(oper, attr_name, value, status) return _CALL("TF_OperationGetAttrTensorShapeProto", oper, attr_name, value, status) end _FUNCDEF("TF_OperationGetAttrTensorShapeProto", { "TF_Operation *", "const char *", "TF_Buffer *", "TF_Status *" }, "void") -- --- Fills in `values` with binary-serialized TensorShapeProto values of the --- attribute `attr_name` of `oper`. `values` must point to an array of length at --- least `num_values` (ideally set to TF_AttrMetadata.list_size from --- TF_OperationGetAttrMetadata(oper, attr_name)). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(TF_Buffer * *) ---@param max_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrTensorShapeProtoList(oper, attr_name, values, max_values, status) return _CALL("TF_OperationGetAttrTensorShapeProtoList", oper, attr_name, values, max_values, status) end _FUNCDEF("TF_OperationGetAttrTensorShapeProtoList", { "TF_Operation *", "const char *", "TF_Buffer * *", "int", "TF_Status *" }, "void") -- --- Gets the TF_Tensor valued attribute of `attr_name` of `oper`. --- Allocates a new TF_Tensor which the caller is expected to take --- ownership of (and can deallocate using TF_DeleteTensor). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param value ffi.cdata @(TF_Tensor * *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrTensor(oper, attr_name, value, status) return _CALL("TF_OperationGetAttrTensor", oper, attr_name, value, status) end _FUNCDEF("TF_OperationGetAttrTensor", { "TF_Operation *", "const char *", "TF_Tensor * *", "TF_Status *" }, "void") -- --- Fills in `values` with the TF_Tensor values of the attribute `attr_name` of --- `oper`. `values` must point to an array of TF_Tensor* of length at least --- `max_values` (ideally set to TF_AttrMetadata.list_size from --- TF_OperationGetAttrMetadata(oper, attr_name)). --- The caller takes ownership of all the non-null TF_Tensor* entries in `values` --- (which can be deleted using TF_DeleteTensor(values[i])). --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param values ffi.cdata @(TF_Tensor * *) ---@param max_values number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrTensorList(oper, attr_name, values, max_values, status) return _CALL("TF_OperationGetAttrTensorList", oper, attr_name, values, max_values, status) end _FUNCDEF("TF_OperationGetAttrTensorList", { "TF_Operation *", "const char *", "TF_Tensor * *", "int", "TF_Status *" }, "void") -- --- Sets `output_attr_value` to the binary-serialized AttrValue proto --- representation of the value of the `attr_name` attr of `oper`. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param attr_name string @(const char *) ---@param output_attr_value ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationGetAttrValueProto(oper, attr_name, output_attr_value, status) return _CALL("TF_OperationGetAttrValueProto", oper, attr_name, output_attr_value, status) end _FUNCDEF("TF_OperationGetAttrValueProto", { "TF_Operation *", "const char *", "TF_Buffer *", "TF_Status *" }, "void") -- --- Returns the operation in the graph with `oper_name`. Returns nullptr if --- no operation found. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param oper_name string @(const char *) ---@return ffi.cdata @(TF_Operation *) function M.TF_GraphOperationByName(graph, oper_name) return _CALL("TF_GraphOperationByName", graph, oper_name) end _FUNCDEF("TF_GraphOperationByName", { "TF_Graph *", "const char *" }, "TF_Operation *") -- --- Iterate through the operations of a graph. To use: --- size_t pos = 0; --- TF_Operation* oper; --- while ((oper = TF_GraphNextOperation(graph, &pos)) != nullptr) { --- DoSomethingWithOperation(oper); --- } --- ---@param graph ffi.cdata @(TF_Graph *) ---@param pos ffi.cdata @(size_t *) ---@return ffi.cdata @(TF_Operation *) function M.TF_GraphNextOperation(graph, pos) return _CALL("TF_GraphNextOperation", graph, pos) end _FUNCDEF("TF_GraphNextOperation", { "TF_Graph *", "size_t *" }, "TF_Operation *") -- --- Write out a serialized representation of `graph` (as a GraphDef protocol --- message) to `output_graph_def` (allocated by TF_NewBuffer()). --- `output_graph_def`'s underlying buffer will be freed when TF_DeleteBuffer() --- is called. --- May fail on very large graphs in the future. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param output_graph_def ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphToGraphDef(graph, output_graph_def, status) return _CALL("TF_GraphToGraphDef", graph, output_graph_def, status) end _FUNCDEF("TF_GraphToGraphDef", { "TF_Graph *", "TF_Buffer *", "TF_Status *" }, "void") -- --- Returns the serialized OpDef proto with name `op_name`, or a bad status if no --- such op exists. This can return OpDefs of functions copied into the graph. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param op_name string @(const char *) ---@param output_op_def ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphGetOpDef(graph, op_name, output_op_def, status) return _CALL("TF_GraphGetOpDef", graph, op_name, output_op_def, status) end _FUNCDEF("TF_GraphGetOpDef", { "TF_Graph *", "const char *", "TF_Buffer *", "TF_Status *" }, "void") -- --- Returns the serialized VersionDef proto for this graph. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param output_version_def ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphVersions(graph, output_version_def, status) return _CALL("TF_GraphVersions", graph, output_version_def, status) end _FUNCDEF("TF_GraphVersions", { "TF_Graph *", "TF_Buffer *", "TF_Status *" }, "void") -- --- TF_ImportGraphDefOptions holds options that can be passed to --- TF_GraphImportGraphDef. --- _TYPEDEF("TF_ImportGraphDefOptions", "struct TF_ImportGraphDefOptions") -- ---@return ffi.cdata @(TF_ImportGraphDefOptions *) function M.TF_NewImportGraphDefOptions() return _CALL("TF_NewImportGraphDefOptions") end _FUNCDEF("TF_NewImportGraphDefOptions", { }, "TF_ImportGraphDefOptions *") -- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) function M.TF_DeleteImportGraphDefOptions(opts) return _CALL("TF_DeleteImportGraphDefOptions", opts) end _FUNCDEF("TF_DeleteImportGraphDefOptions", { "TF_ImportGraphDefOptions *" }, "void") -- --- Set the prefix to be prepended to the names of nodes in `graph_def` that will --- be imported into `graph`. `prefix` is copied and has no lifetime --- requirements. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param prefix string @(const char *) function M.TF_ImportGraphDefOptionsSetPrefix(opts, prefix) return _CALL("TF_ImportGraphDefOptionsSetPrefix", opts, prefix) end _FUNCDEF("TF_ImportGraphDefOptionsSetPrefix", { "TF_ImportGraphDefOptions *", "const char *" }, "void") -- --- Set the execution device for nodes in `graph_def`. --- Only applies to nodes where a device was not already explicitly specified. --- `device` is copied and has no lifetime requirements. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param device string @(const char *) function M.TF_ImportGraphDefOptionsSetDefaultDevice(opts, device) return _CALL("TF_ImportGraphDefOptionsSetDefaultDevice", opts, device) end _FUNCDEF("TF_ImportGraphDefOptionsSetDefaultDevice", { "TF_ImportGraphDefOptions *", "const char *" }, "void") -- --- Set whether to uniquify imported operation names. If true, imported operation --- names will be modified if their name already exists in the graph. If false, --- conflicting names will be treated as an error. Note that this option has no --- effect if a prefix is set, since the prefix will guarantee all names are --- unique. Defaults to false. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param uniquify_names number @(unsigned char) function M.TF_ImportGraphDefOptionsSetUniquifyNames(opts, uniquify_names) return _CALL("TF_ImportGraphDefOptionsSetUniquifyNames", opts, uniquify_names) end _FUNCDEF("TF_ImportGraphDefOptionsSetUniquifyNames", { "TF_ImportGraphDefOptions *", "unsigned char" }, "void") -- --- If true, the specified prefix will be modified if it already exists as an --- operation name or prefix in the graph. If false, a conflicting prefix will be --- treated as an error. This option has no effect if no prefix is specified. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param uniquify_prefix number @(unsigned char) function M.TF_ImportGraphDefOptionsSetUniquifyPrefix(opts, uniquify_prefix) return _CALL("TF_ImportGraphDefOptionsSetUniquifyPrefix", opts, uniquify_prefix) end _FUNCDEF("TF_ImportGraphDefOptionsSetUniquifyPrefix", { "TF_ImportGraphDefOptions *", "unsigned char" }, "void") -- --- Set any imported nodes with input `src_name:src_index` to have that input --- replaced with `dst`. `src_name` refers to a node in the graph to be imported, --- `dst` references a node already existing in the graph being imported into. --- `src_name` is copied and has no lifetime requirements. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param src_name string @(const char *) ---@param src_index number @(int) ---@param dst TF_Output @(TF_Output) function M.TF_ImportGraphDefOptionsAddInputMapping(opts, src_name, src_index, dst) return _CALL("TF_ImportGraphDefOptionsAddInputMapping", opts, src_name, src_index, dst) end _FUNCDEF("TF_ImportGraphDefOptionsAddInputMapping", { "TF_ImportGraphDefOptions *", "const char *", "int", "TF_Output" }, "void") -- --- Set any imported nodes with control input `src_name` to have that input --- replaced with `dst`. `src_name` refers to a node in the graph to be imported, --- `dst` references an operation already existing in the graph being imported --- into. `src_name` is copied and has no lifetime requirements. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param src_name string @(const char *) ---@param dst ffi.cdata @(TF_Operation *) function M.TF_ImportGraphDefOptionsRemapControlDependency(opts, src_name, dst) return _CALL("TF_ImportGraphDefOptionsRemapControlDependency", opts, src_name, dst) end _FUNCDEF("TF_ImportGraphDefOptionsRemapControlDependency", { "TF_ImportGraphDefOptions *", "const char *", "TF_Operation *" }, "void") -- --- Cause the imported graph to have a control dependency on `oper`. `oper` --- should exist in the graph being imported into. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param oper ffi.cdata @(TF_Operation *) function M.TF_ImportGraphDefOptionsAddControlDependency(opts, oper) return _CALL("TF_ImportGraphDefOptionsAddControlDependency", opts, oper) end _FUNCDEF("TF_ImportGraphDefOptionsAddControlDependency", { "TF_ImportGraphDefOptions *", "TF_Operation *" }, "void") -- --- Add an output in `graph_def` to be returned via the `return_outputs` output --- parameter of TF_GraphImportGraphDef(). If the output is remapped via an input --- mapping, the corresponding existing tensor in `graph` will be returned. --- `oper_name` is copied and has no lifetime requirements. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param oper_name string @(const char *) ---@param index number @(int) function M.TF_ImportGraphDefOptionsAddReturnOutput(opts, oper_name, index) return _CALL("TF_ImportGraphDefOptionsAddReturnOutput", opts, oper_name, index) end _FUNCDEF("TF_ImportGraphDefOptionsAddReturnOutput", { "TF_ImportGraphDefOptions *", "const char *", "int" }, "void") -- --- Returns the number of return outputs added via --- TF_ImportGraphDefOptionsAddReturnOutput(). --- ---@param opts ffi.cdata @(const TF_ImportGraphDefOptions *) ---@return number @(int) function M.TF_ImportGraphDefOptionsNumReturnOutputs(opts) return _CALL("TF_ImportGraphDefOptionsNumReturnOutputs", opts) end _FUNCDEF("TF_ImportGraphDefOptionsNumReturnOutputs", { "const TF_ImportGraphDefOptions *" }, "int") -- --- Add an operation in `graph_def` to be returned via the `return_opers` output --- parameter of TF_GraphImportGraphDef(). `oper_name` is copied and has no --- lifetime requirements. --- ---@param opts ffi.cdata @(TF_ImportGraphDefOptions *) ---@param oper_name string @(const char *) function M.TF_ImportGraphDefOptionsAddReturnOperation(opts, oper_name) return _CALL("TF_ImportGraphDefOptionsAddReturnOperation", opts, oper_name) end _FUNCDEF("TF_ImportGraphDefOptionsAddReturnOperation", { "TF_ImportGraphDefOptions *", "const char *" }, "void") -- --- Returns the number of return operations added via --- TF_ImportGraphDefOptionsAddReturnOperation(). --- ---@param opts ffi.cdata @(const TF_ImportGraphDefOptions *) ---@return number @(int) function M.TF_ImportGraphDefOptionsNumReturnOperations(opts) return _CALL("TF_ImportGraphDefOptionsNumReturnOperations", opts) end _FUNCDEF("TF_ImportGraphDefOptionsNumReturnOperations", { "const TF_ImportGraphDefOptions *" }, "int") -- --- TF_ImportGraphDefResults holds results that are generated by --- TF_GraphImportGraphDefWithResults(). --- _TYPEDEF("TF_ImportGraphDefResults", "struct TF_ImportGraphDefResults") -- --- Fetches the return outputs requested via --- TF_ImportGraphDefOptionsAddReturnOutput(). The number of fetched outputs is --- returned in `num_outputs`. The array of return outputs is returned in --- `outputs`. `*outputs` is owned by and has the lifetime of `results`. --- ---@param results ffi.cdata @(TF_ImportGraphDefResults *) ---@param num_outputs ffi.cdata @(int *) ---@param outputs ffi.cdata @(TF_Output * *) function M.TF_ImportGraphDefResultsReturnOutputs(results, num_outputs, outputs) return _CALL("TF_ImportGraphDefResultsReturnOutputs", results, num_outputs, outputs) end _FUNCDEF("TF_ImportGraphDefResultsReturnOutputs", { "TF_ImportGraphDefResults *", "int *", "TF_Output * *" }, "void") -- --- Fetches the return operations requested via --- TF_ImportGraphDefOptionsAddReturnOperation(). The number of fetched --- operations is returned in `num_opers`. The array of return operations is --- returned in `opers`. `*opers` is owned by and has the lifetime of `results`. --- ---@param results ffi.cdata @(TF_ImportGraphDefResults *) ---@param num_opers ffi.cdata @(int *) ---@param opers ffi.cdata @(TF_Operation * * *) function M.TF_ImportGraphDefResultsReturnOperations(results, num_opers, opers) return _CALL("TF_ImportGraphDefResultsReturnOperations", results, num_opers, opers) end _FUNCDEF("TF_ImportGraphDefResultsReturnOperations", { "TF_ImportGraphDefResults *", "int *", "TF_Operation * * *" }, "void") -- --- Fetches any input mappings requested via --- TF_ImportGraphDefOptionsAddInputMapping() that didn't appear in the GraphDef --- and weren't used as input to any node in the imported graph def. The number --- of fetched mappings is returned in `num_missing_unused_input_mappings`. The --- array of each mapping's source node name is returned in `src_names`, and the --- array of each mapping's source index is returned in `src_indexes`. --- `*src_names`, `*src_indexes`, and the memory backing each string in --- `src_names` are owned by and have the lifetime of `results`. --- ---@param results ffi.cdata @(TF_ImportGraphDefResults *) ---@param num_missing_unused_input_mappings ffi.cdata @(int *) ---@param src_names ffi.cdata @(const char * * *) ---@param src_indexes ffi.cdata @(int * *) function M.TF_ImportGraphDefResultsMissingUnusedInputMappings(results, num_missing_unused_input_mappings, src_names, src_indexes) return _CALL("TF_ImportGraphDefResultsMissingUnusedInputMappings", results, num_missing_unused_input_mappings, src_names, src_indexes) end _FUNCDEF("TF_ImportGraphDefResultsMissingUnusedInputMappings", { "TF_ImportGraphDefResults *", "int *", "const char * * *", "int * *" }, "void") -- --- Deletes a results object returned by TF_GraphImportGraphDefWithResults(). --- ---@param results ffi.cdata @(TF_ImportGraphDefResults *) function M.TF_DeleteImportGraphDefResults(results) return _CALL("TF_DeleteImportGraphDefResults", results) end _FUNCDEF("TF_DeleteImportGraphDefResults", { "TF_ImportGraphDefResults *" }, "void") -- --- Import the graph serialized in `graph_def` into `graph`. Returns nullptr and --- a bad status on error. Otherwise, returns a populated --- TF_ImportGraphDefResults instance. The returned instance must be deleted via --- TF_DeleteImportGraphDefResults(). --- ---@param graph ffi.cdata @(TF_Graph *) ---@param graph_def ffi.cdata @(const TF_Buffer *) ---@param options ffi.cdata @(const TF_ImportGraphDefOptions *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_ImportGraphDefResults *) function M.TF_GraphImportGraphDefWithResults(graph, graph_def, options, status) return _CALL("TF_GraphImportGraphDefWithResults", graph, graph_def, options, status) end _FUNCDEF("TF_GraphImportGraphDefWithResults", { "TF_Graph *", "const TF_Buffer *", "const TF_ImportGraphDefOptions *", "TF_Status *" }, "TF_ImportGraphDefResults *") -- --- Import the graph serialized in `graph_def` into `graph`. --- Convenience function for when only return outputs are needed. --- `num_return_outputs` must be the number of return outputs added (i.e. the --- result of TF_ImportGraphDefOptionsNumReturnOutputs()). If --- `num_return_outputs` is non-zero, `return_outputs` must be of length --- `num_return_outputs`. Otherwise it can be null. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param graph_def ffi.cdata @(const TF_Buffer *) ---@param options ffi.cdata @(const TF_ImportGraphDefOptions *) ---@param return_outputs ffi.cdata @(TF_Output *) ---@param num_return_outputs number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphImportGraphDefWithReturnOutputs(graph, graph_def, options, return_outputs, num_return_outputs, status) return _CALL("TF_GraphImportGraphDefWithReturnOutputs", graph, graph_def, options, return_outputs, num_return_outputs, status) end _FUNCDEF("TF_GraphImportGraphDefWithReturnOutputs", { "TF_Graph *", "const TF_Buffer *", "const TF_ImportGraphDefOptions *", "TF_Output *", "int", "TF_Status *" }, "void") -- --- Import the graph serialized in `graph_def` into `graph`. --- Convenience function for when no results are needed. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param graph_def ffi.cdata @(const TF_Buffer *) ---@param options ffi.cdata @(const TF_ImportGraphDefOptions *) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphImportGraphDef(graph, graph_def, options, status) return _CALL("TF_GraphImportGraphDef", graph, graph_def, options, status) end _FUNCDEF("TF_GraphImportGraphDef", { "TF_Graph *", "const TF_Buffer *", "const TF_ImportGraphDefOptions *", "TF_Status *" }, "void") -- --- Adds a copy of function `func` and optionally its gradient function `grad` --- to `g`. Once `func`/`grad` is added to `g`, it can be called by creating --- an operation using the function's name. --- Any changes to `func`/`grad` (including deleting it) done after this method --- returns, won't affect the copy of `func`/`grad` in `g`. --- If `func` or `grad` are already in `g`, TF_GraphCopyFunction has no --- effect on them, but can establish the function->gradient relationship --- between them if `func` does not already have a gradient. If `func` already --- has a gradient different from `grad`, an error is returned. --- `func` must not be null. --- If `grad` is null and `func` is not in `g`, `func` is added without a --- gradient. --- If `grad` is null and `func` is in `g`, TF_GraphCopyFunction is a noop. --- `grad` must have appropriate signature as described in the doc of --- GradientDef in tensorflow/core/framework/function.proto. --- If successful, status is set to OK and `func` and `grad` are added to `g`. --- Otherwise, status is set to the encountered error and `g` is unmodified. --- ---@param g ffi.cdata @(TF_Graph *) ---@param func ffi.cdata @(const TF_Function *) ---@param grad ffi.cdata @(const TF_Function *) ---@param status ffi.cdata @(TF_Status *) function M.TF_GraphCopyFunction(g, func, grad, status) return _CALL("TF_GraphCopyFunction", g, func, grad, status) end _FUNCDEF("TF_GraphCopyFunction", { "TF_Graph *", "const TF_Function *", "const TF_Function *", "TF_Status *" }, "void") -- --- Returns the number of TF_Functions registered in `g`. --- ---@param g ffi.cdata @(TF_Graph *) ---@return number @(int) function M.TF_GraphNumFunctions(g) return _CALL("TF_GraphNumFunctions", g) end _FUNCDEF("TF_GraphNumFunctions", { "TF_Graph *" }, "int") -- --- Fills in `funcs` with the TF_Function* registered in `g`. --- `funcs` must point to an array of TF_Function* of length at least --- `max_func`. In usual usage, max_func should be set to the result of --- TF_GraphNumFunctions(g). In this case, all the functions registered in --- `g` will be returned. Else, an unspecified subset. --- If successful, returns the number of TF_Function* successfully set in --- `funcs` and sets status to OK. The caller takes ownership of --- all the returned TF_Functions. They must be deleted with TF_DeleteFunction. --- On error, returns 0, sets status to the encountered error, and the contents --- of funcs will be undefined. --- ---@param g ffi.cdata @(TF_Graph *) ---@param funcs ffi.cdata @(TF_Function * *) ---@param max_func number @(int) ---@param status ffi.cdata @(TF_Status *) ---@return number @(int) function M.TF_GraphGetFunctions(g, funcs, max_func, status) return _CALL("TF_GraphGetFunctions", g, funcs, max_func, status) end _FUNCDEF("TF_GraphGetFunctions", { "TF_Graph *", "TF_Function * *", "int", "TF_Status *" }, "int") -- --- Note: The following function may fail on very large protos in the future. --- ---@param oper ffi.cdata @(TF_Operation *) ---@param output_node_def ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_OperationToNodeDef(oper, output_node_def, status) return _CALL("TF_OperationToNodeDef", oper, output_node_def, status) end _FUNCDEF("TF_OperationToNodeDef", { "TF_Operation *", "TF_Buffer *", "TF_Status *" }, "void") -- --- The number of inputs to the while loop, i.e. the number of loop variables. --- This is the size of cond_inputs, body_inputs, and body_outputs. --- The while condition graph. The inputs are the current values of the loop --- variables. The output should be a scalar boolean. --- The loop body graph. The inputs are the current values of the loop --- variables. The outputs are the updated values of the loop variables. --- Unique null-terminated name for this while loop. This is used as a prefix --- for created operations. --- _TYPEDEF("TF_WhileParams", "struct TF_WhileParams { const int ninputs ; TF_Graph * const cond_graph ; const TF_Output * const cond_inputs ; TF_Output cond_output ; TF_Graph * const body_graph ; const TF_Output * const body_inputs ; TF_Output * const body_outputs ; const char * name ; }") -- --- Creates a TF_WhileParams for creating a while loop in `g`. `inputs` are --- outputs that already exist in `g` used as initial values for the loop --- variables. --- The returned TF_WhileParams will have all fields initialized except --- `cond_output`, `body_outputs`, and `name`. The `body_outputs` buffer will be --- allocated to size `ninputs`. The caller should build `cond_graph` and --- `body_graph` starting from the inputs, and store the final outputs in --- `cond_output` and `body_outputs`. --- If `status` is OK, the caller must call either TF_FinishWhile or --- TF_AbortWhile on the returned TF_WhileParams. If `status` isn't OK, the --- returned TF_WhileParams is not valid, and the caller should not call --- TF_FinishWhile() or TF_AbortWhile(). --- Missing functionality (TODO): --- - Gradients --- - Reference-type inputs --- - Directly referencing external tensors from the cond/body graphs (this is --- possible in the Python API) --- ---@param g ffi.cdata @(TF_Graph *) ---@param inputs ffi.cdata @(TF_Output *) ---@param ninputs number @(int) ---@param status ffi.cdata @(TF_Status *) ---@return TF_WhileParams @(TF_WhileParams) function M.TF_NewWhile(g, inputs, ninputs, status) return _CALL("TF_NewWhile", g, inputs, ninputs, status) end _FUNCDEF("TF_NewWhile", { "TF_Graph *", "TF_Output *", "int", "TF_Status *" }, "TF_WhileParams") -- --- Builds the while loop specified by `params` and returns the output tensors of --- the while loop in `outputs`. `outputs` should be allocated to size --- `params.ninputs`. --- `params` is no longer valid once this returns. --- Either this or TF_AbortWhile() must be called after a successful --- TF_NewWhile() call. --- ---@param params ffi.cdata @(const TF_WhileParams *) ---@param status ffi.cdata @(TF_Status *) ---@param outputs ffi.cdata @(TF_Output *) function M.TF_FinishWhile(params, status, outputs) return _CALL("TF_FinishWhile", params, status, outputs) end _FUNCDEF("TF_FinishWhile", { "const TF_WhileParams *", "TF_Status *", "TF_Output *" }, "void") -- --- Frees `params`s resources without building a while loop. `params` is no --- longer valid after this returns. Either this or TF_FinishWhile() must be --- called after a successful TF_NewWhile() call. --- ---@param params ffi.cdata @(const TF_WhileParams *) function M.TF_AbortWhile(params) return _CALL("TF_AbortWhile", params) end _FUNCDEF("TF_AbortWhile", { "const TF_WhileParams *" }, "void") -- --- Adds operations to compute the partial derivatives of sum of `y`s w.r.t `x`s, --- i.e., d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2... --- `dx` are used as initial gradients (which represent the symbolic partial --- derivatives of some loss function `L` w.r.t. `y`). --- `dx` must be nullptr or have size `ny`. --- If `dx` is nullptr, the implementation will use dx of `OnesLike` for all --- shapes in `y`. --- The partial derivatives are returned in `dy`. `dy` should be allocated to --- size `nx`. --- Gradient nodes are automatically named under the "gradients/" prefix. To --- guarantee name uniqueness, subsequent calls to the same graph will --- append an incremental tag to the prefix: "gradients_1/", "gradients_2/", ... --- See TF_AddGradientsWithPrefix, which provides a means to specify a custom --- name prefix for operations added to a graph to compute the gradients. --- WARNING: This function does not yet support all the gradients that python --- supports. See --- https://www.tensorflow.org/code/tensorflow/cc/gradients/README.md --- for instructions on how to add C++ more gradients. --- ---@param g ffi.cdata @(TF_Graph *) ---@param y ffi.cdata @(TF_Output *) ---@param ny number @(int) ---@param x ffi.cdata @(TF_Output *) ---@param nx number @(int) ---@param dx ffi.cdata @(TF_Output *) ---@param status ffi.cdata @(TF_Status *) ---@param dy ffi.cdata @(TF_Output *) function M.TF_AddGradients(g, y, ny, x, nx, dx, status, dy) return _CALL("TF_AddGradients", g, y, ny, x, nx, dx, status, dy) end _FUNCDEF("TF_AddGradients", { "TF_Graph *", "TF_Output *", "int", "TF_Output *", "int", "TF_Output *", "TF_Status *", "TF_Output *" }, "void") -- --- Adds operations to compute the partial derivatives of sum of `y`s w.r.t `x`s, --- i.e., d(y_1 + y_2 + ...)/dx_1, d(y_1 + y_2 + ...)/dx_2... --- This is a variant of TF_AddGradients that allows to caller to pass a custom --- name prefix to the operations added to a graph to compute the gradients. --- `dx` are used as initial gradients (which represent the symbolic partial --- derivatives of some loss function `L` w.r.t. `y`). --- `dx` must be nullptr or have size `ny`. --- If `dx` is nullptr, the implementation will use dx of `OnesLike` for all --- shapes in `y`. --- The partial derivatives are returned in `dy`. `dy` should be allocated to --- size `nx`. --- `prefix` names the scope into which all gradients operations are being added. --- `prefix` must be unique within the provided graph otherwise this operation --- will fail. If `prefix` is nullptr, the default prefixing behaviour takes --- place, see TF_AddGradients for more details. --- WARNING: This function does not yet support all the gradients that python --- supports. See --- https://www.tensorflow.org/code/tensorflow/cc/gradients/README.md --- for instructions on how to add C++ more gradients. --- ---@param g ffi.cdata @(TF_Graph *) ---@param prefix string @(const char *) ---@param y ffi.cdata @(TF_Output *) ---@param ny number @(int) ---@param x ffi.cdata @(TF_Output *) ---@param nx number @(int) ---@param dx ffi.cdata @(TF_Output *) ---@param status ffi.cdata @(TF_Status *) ---@param dy ffi.cdata @(TF_Output *) function M.TF_AddGradientsWithPrefix(g, prefix, y, ny, x, nx, dx, status, dy) return _CALL("TF_AddGradientsWithPrefix", g, prefix, y, ny, x, nx, dx, status, dy) end _FUNCDEF("TF_AddGradientsWithPrefix", { "TF_Graph *", "const char *", "TF_Output *", "int", "TF_Output *", "int", "TF_Output *", "TF_Status *", "TF_Output *" }, "void") -- --- Create a TF_Function from a TF_Graph --- Params: --- fn_body - the graph whose operations (or subset of whose operations) will be --- converted to TF_Function. --- fn_name - the name of the new TF_Function. Should match the operation --- name (OpDef.name) regexp [A-Z][A-Za-z0-9_.\\-/]*. --- If `append_hash_to_fn_name` is false, `fn_name` must be distinct --- from other function and operation names (at least those --- registered in graphs where this function will be used). --- append_hash_to_fn_name - Must be 0 or 1. If set to 1, the actual name --- of the function will be `fn_name` appended with --- '_<hash_of_this_function's_definition>'. --- If set to 0, the function's name will be `fn_name`. --- num_opers - `num_opers` contains the number of elements in the `opers` array --- or a special value of -1 meaning that no array is given. --- The distinction between an empty array of operations and no --- array of operations is necessary to distinguish the case of --- creating a function with no body (e.g. identity or permutation) --- and the case of creating a function whose body contains all --- the nodes in the graph (except for the automatic skipping, see --- below). --- opers - Array of operations to become the body of the function or null. --- - If no array is given (`num_opers` = -1), all the --- operations in `fn_body` will become part of the function --- except operations referenced in `inputs`. These operations --- must have a single output (these operations are typically --- placeholders created for the sole purpose of representing --- an input. We can relax this constraint if there are --- compelling use cases). --- - If an array is given (`num_opers` >= 0), all operations --- in it will become part of the function. In particular, no --- automatic skipping of dummy input operations is performed. --- ninputs - number of elements in `inputs` array --- inputs - array of TF_Outputs that specify the inputs to the function. --- If `ninputs` is zero (the function takes no inputs), `inputs` --- can be null. The names used for function inputs are normalized --- names of the operations (usually placeholders) pointed to by --- `inputs`. These operation names should start with a letter. --- Normalization will convert all letters to lowercase and --- non-alphanumeric characters to '_' to make resulting names match --- the "[a-z][a-z0-9_]*" pattern for operation argument names. --- `inputs` cannot contain the same tensor twice. --- noutputs - number of elements in `outputs` array --- outputs - array of TF_Outputs that specify the outputs of the function. --- If `noutputs` is zero (the function returns no outputs), `outputs` --- can be null. `outputs` can contain the same tensor more than once. --- output_names - The names of the function's outputs. `output_names` array --- must either have the same length as `outputs` --- (i.e. `noutputs`) or be null. In the former case, --- the names should match the regular expression for ArgDef --- names - "[a-z][a-z0-9_]*". In the latter case, --- names for outputs will be generated automatically. --- opts - various options for the function, e.g. XLA's inlining control. --- description - optional human-readable description of this function. --- status - Set to OK on success and an appropriate error on failure. --- Note that when the same TF_Output is listed as both an input and an output, --- the corresponding function's output will equal to this input, --- instead of the original node's output. --- Callers must also satisfy the following constraints: --- - `inputs` cannot refer to TF_Outputs within a control flow context. For --- example, one cannot use the output of "switch" node as input. --- - `inputs` and `outputs` cannot have reference types. Reference types are --- not exposed through C API and are being replaced with Resources. We support --- reference types inside function's body to support legacy code. Do not --- use them in new code. --- - Every node in the function's body must have all of its inputs (including --- control inputs). In other words, for every node in the body, each input --- must be either listed in `inputs` or must come from another node in --- the body. In particular, it is an error to have a control edge going from --- a node outside of the body into a node in the body. This applies to control --- edges going from nodes referenced in `inputs` to nodes in the body when --- the former nodes are not in the body (automatically skipped or not --- included in explicitly specified body). --- Returns: --- On success, a newly created TF_Function instance. It must be deleted by --- calling TF_DeleteFunction. --- On failure, null. --- ---@param fn_body ffi.cdata @(const TF_Graph *) ---@param fn_name string @(const char *) ---@param append_hash_to_fn_name number @(unsigned char) ---@param num_opers number @(int) ---@param opers ffi.cdata @(const TF_Operation * const *) ---@param ninputs number @(int) ---@param inputs ffi.cdata @(const TF_Output *) ---@param noutputs number @(int) ---@param outputs ffi.cdata @(const TF_Output *) ---@param output_names ffi.cdata @(const char * const *) ---@param opts ffi.cdata @(const TF_FunctionOptions *) ---@param description string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Function *) function M.TF_GraphToFunction(fn_body, fn_name, append_hash_to_fn_name, num_opers, opers, ninputs, inputs, noutputs, outputs, output_names, opts, description, status) return _CALL("TF_GraphToFunction", fn_body, fn_name, append_hash_to_fn_name, num_opers, opers, ninputs, inputs, noutputs, outputs, output_names, opts, description, status) end _FUNCDEF("TF_GraphToFunction", { "const TF_Graph *", "const char *", "unsigned char", "int", "const TF_Operation * const *", "int", "const TF_Output *", "int", "const TF_Output *", "const char * const *", "const TF_FunctionOptions *", "const char *", "TF_Status *" }, "TF_Function *") -- --- Similar to TF_GraphToFunction but allows specifying control outputs of the --- function. --- The arguments of TF_GraphToFunction have the same meaning, but the new --- arguments are as follows: --- ncontrol_outputs: Number of control outputs of the function. --- control_outputs: vector of TF_Operation objects to be marked as control --- outputs of the function. Operations marked as control outputs are --- guaranteed to execute. --- control_output_names: Optional. If not nullptr, vector of strings, one --- per control output, with their names to be added to the function's --- OpDef. --- ---@param fn_body ffi.cdata @(const TF_Graph *) ---@param fn_name string @(const char *) ---@param append_hash_to_fn_name number @(unsigned char) ---@param num_opers number @(int) ---@param opers ffi.cdata @(const TF_Operation * const *) ---@param ninputs number @(int) ---@param inputs ffi.cdata @(const TF_Output *) ---@param noutputs number @(int) ---@param outputs ffi.cdata @(const TF_Output *) ---@param output_names ffi.cdata @(const char * const *) ---@param ncontrol_outputs number @(int) ---@param control_outputs ffi.cdata @(const TF_Operation * const *) ---@param control_output_names ffi.cdata @(const char * const *) ---@param opts ffi.cdata @(const TF_FunctionOptions *) ---@param description string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Function *) function M.TF_GraphToFunctionWithControlOutputs(fn_body, fn_name, append_hash_to_fn_name, num_opers, opers, ninputs, inputs, noutputs, outputs, output_names, ncontrol_outputs, control_outputs, control_output_names, opts, description, status) return _CALL("TF_GraphToFunctionWithControlOutputs", fn_body, fn_name, append_hash_to_fn_name, num_opers, opers, ninputs, inputs, noutputs, outputs, output_names, ncontrol_outputs, control_outputs, control_output_names, opts, description, status) end _FUNCDEF("TF_GraphToFunctionWithControlOutputs", { "const TF_Graph *", "const char *", "unsigned char", "int", "const TF_Operation * const *", "int", "const TF_Output *", "int", "const TF_Output *", "const char * const *", "int", "const TF_Operation * const *", "const char * const *", "const TF_FunctionOptions *", "const char *", "TF_Status *" }, "TF_Function *") -- --- Returns the name of the graph function. --- The return value points to memory that is only usable until the next --- mutation to *func. --- ---@param func ffi.cdata @(TF_Function *) ---@return string @(const char *) function M.TF_FunctionName(func) return _CALL("TF_FunctionName", func) end _FUNCDEF("TF_FunctionName", { "TF_Function *" }, "const char *") -- --- Write out a serialized representation of `func` (as a FunctionDef protocol --- message) to `output_func_def` (allocated by TF_NewBuffer()). --- `output_func_def`'s underlying buffer will be freed when TF_DeleteBuffer() --- is called. --- May fail on very large graphs in the future. --- ---@param func ffi.cdata @(TF_Function *) ---@param output_func_def ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_FunctionToFunctionDef(func, output_func_def, status) return _CALL("TF_FunctionToFunctionDef", func, output_func_def, status) end _FUNCDEF("TF_FunctionToFunctionDef", { "TF_Function *", "TF_Buffer *", "TF_Status *" }, "void") -- --- Construct and return the function whose FunctionDef representation is --- serialized in `proto`. `proto_len` must equal the number of bytes --- pointed to by `proto`. --- Returns: --- On success, a newly created TF_Function instance. It must be deleted by --- calling TF_DeleteFunction. --- On failure, null. --- ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Function *) function M.TF_FunctionImportFunctionDef(proto, proto_len, status) return _CALL("TF_FunctionImportFunctionDef", proto, proto_len, status) end _FUNCDEF("TF_FunctionImportFunctionDef", { "const void *", "size_t", "TF_Status *" }, "TF_Function *") -- --- Sets function attribute named `attr_name` to value stored in `proto`. --- If this attribute is already set to another value, it is overridden. --- `proto` should point to a sequence of bytes of length `proto_len` --- representing a binary serialization of an AttrValue protocol --- buffer. --- ---@param func ffi.cdata @(TF_Function *) ---@param attr_name string @(const char *) ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_FunctionSetAttrValueProto(func, attr_name, proto, proto_len, status) return _CALL("TF_FunctionSetAttrValueProto", func, attr_name, proto, proto_len, status) end _FUNCDEF("TF_FunctionSetAttrValueProto", { "TF_Function *", "const char *", "const void *", "size_t", "TF_Status *" }, "void") -- --- Sets `output_attr_value` to the binary-serialized AttrValue proto --- representation of the value of the `attr_name` attr of `func`. --- If `attr_name` attribute is not present, status is set to an error. --- ---@param func ffi.cdata @(TF_Function *) ---@param attr_name string @(const char *) ---@param output_attr_value ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_FunctionGetAttrValueProto(func, attr_name, output_attr_value, status) return _CALL("TF_FunctionGetAttrValueProto", func, attr_name, output_attr_value, status) end _FUNCDEF("TF_FunctionGetAttrValueProto", { "TF_Function *", "const char *", "TF_Buffer *", "TF_Status *" }, "void") -- --- Frees the memory used by the `func` struct. --- TF_DeleteFunction is a noop if `func` is null. --- Deleting a function does not remove it from any graphs it was copied to. --- ---@param func ffi.cdata @(TF_Function *) function M.TF_DeleteFunction(func) return _CALL("TF_DeleteFunction", func) end _FUNCDEF("TF_DeleteFunction", { "TF_Function *" }, "void") -- --- Attempts to evaluate `output`. This will only be possible if `output` doesn't --- depend on any graph inputs (this function is safe to call if this isn't the --- case though). --- If the evaluation is successful, this function returns true and `output`s --- value is returned in `result`. Otherwise returns false. An error status is --- returned if something is wrong with the graph or input. Note that this may --- return false even if no error status is set. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param output TF_Output @(TF_Output) ---@param result ffi.cdata @(TF_Tensor * *) ---@param status ffi.cdata @(TF_Status *) ---@return number @(unsigned char) function M.TF_TryEvaluateConstant(graph, output, result, status) return _CALL("TF_TryEvaluateConstant", graph, output, result, status) end _FUNCDEF("TF_TryEvaluateConstant", { "TF_Graph *", "TF_Output", "TF_Tensor * *", "TF_Status *" }, "unsigned char") -- --- TODO(josh11b): Register OpDef, available to all operations added --- to this graph. --- -------------------------------------------------------------------------- --- API for driving Graph execution. --- _TYPEDEF("TF_Session", "struct TF_Session") -- --- Return a new execution session with the associated graph, or NULL on --- error. Does not take ownership of any input parameters. --- `graph` must be a valid graph (not deleted or nullptr). `graph` will be be --- kept alive for the lifetime of the returned TF_Session. New nodes can still --- be added to `graph` after this call. --- ---@param graph ffi.cdata @(TF_Graph *) ---@param opts ffi.cdata @(const TF_SessionOptions *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Session *) function M.TF_NewSession(graph, opts, status) return _CALL("TF_NewSession", graph, opts, status) end _FUNCDEF("TF_NewSession", { "TF_Graph *", "const TF_SessionOptions *", "TF_Status *" }, "TF_Session *") -- --- This function creates a new TF_Session (which is created on success) using --- `session_options`, and then initializes state (restoring tensors and other --- assets) using `run_options`. --- Any NULL and non-NULL value combinations for (`run_options, `meta_graph_def`) --- are valid. --- - `export_dir` must be set to the path of the exported SavedModel. --- - `tags` must include the set of tags used to identify one MetaGraphDef in --- the SavedModel. --- - `graph` must be a graph newly allocated with TF_NewGraph(). --- If successful, populates `graph` with the contents of the Graph and --- `meta_graph_def` with the MetaGraphDef of the loaded model. --- ---@param session_options ffi.cdata @(const TF_SessionOptions *) ---@param run_options ffi.cdata @(const TF_Buffer *) ---@param export_dir string @(const char *) ---@param tags ffi.cdata @(const char * const *) ---@param tags_len number @(int) ---@param graph ffi.cdata @(TF_Graph *) ---@param meta_graph_def ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Session *) function M.TF_LoadSessionFromSavedModel(session_options, run_options, export_dir, tags, tags_len, graph, meta_graph_def, status) return _CALL("TF_LoadSessionFromSavedModel", session_options, run_options, export_dir, tags, tags_len, graph, meta_graph_def, status) end _FUNCDEF("TF_LoadSessionFromSavedModel", { "const TF_SessionOptions *", "const TF_Buffer *", "const char *", "const char * const *", "int", "TF_Graph *", "TF_Buffer *", "TF_Status *" }, "TF_Session *") -- --- Close a session. --- Contacts any other processes associated with the session, if applicable. --- May not be called after TF_DeleteSession(). --- ---@param session ffi.cdata @(TF_Session *) ---@param status ffi.cdata @(TF_Status *) function M.TF_CloseSession(session, status) return _CALL("TF_CloseSession", session, status) end _FUNCDEF("TF_CloseSession", { "TF_Session *", "TF_Status *" }, "void") -- --- Destroy a session object. --- Even if error information is recorded in *status, this call discards all --- local resources associated with the session. The session may not be used --- during or after this call (and the session drops its reference to the --- corresponding graph). --- ---@param session ffi.cdata @(TF_Session *) ---@param status ffi.cdata @(TF_Status *) function M.TF_DeleteSession(session, status) return _CALL("TF_DeleteSession", session, status) end _FUNCDEF("TF_DeleteSession", { "TF_Session *", "TF_Status *" }, "void") -- --- Run the graph associated with the session starting with the supplied inputs --- (inputs[0,ninputs-1] with corresponding values in input_values[0,ninputs-1]). --- Any NULL and non-NULL value combinations for (`run_options`, --- `run_metadata`) are valid. --- - `run_options` may be NULL, in which case it will be ignored; or --- non-NULL, in which case it must point to a `TF_Buffer` containing the --- serialized representation of a `RunOptions` protocol buffer. --- - `run_metadata` may be NULL, in which case it will be ignored; or --- non-NULL, in which case it must point to an empty, freshly allocated --- `TF_Buffer` that may be updated to contain the serialized representation --- of a `RunMetadata` protocol buffer. --- The caller retains ownership of `input_values` (which can be deleted using --- TF_DeleteTensor). The caller also retains ownership of `run_options` and/or --- `run_metadata` (when not NULL) and should manually call TF_DeleteBuffer on --- them. --- On success, the tensors corresponding to outputs[0,noutputs-1] are placed in --- output_values[]. Ownership of the elements of output_values[] is transferred --- to the caller, which must eventually call TF_DeleteTensor on them. --- On failure, output_values[] contains NULLs. --- RunOptions --- Input tensors --- Output tensors --- Target operations --- RunMetadata --- Output status --- ---@param session ffi.cdata @(TF_Session *) ---@param run_options ffi.cdata @(const TF_Buffer *) ---@param inputs ffi.cdata @(const TF_Output *) ---@param input_values ffi.cdata @(TF_Tensor * const *) ---@param ninputs number @(int) ---@param outputs ffi.cdata @(const TF_Output *) ---@param output_values ffi.cdata @(TF_Tensor * *) ---@param noutputs number @(int) ---@param target_opers ffi.cdata @(const TF_Operation * const *) ---@param ntargets number @(int) ---@param run_metadata ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_SessionRun(session, run_options, inputs, input_values, ninputs, outputs, output_values, noutputs, target_opers, ntargets, run_metadata, status) return _CALL("TF_SessionRun", session, run_options, inputs, input_values, ninputs, outputs, output_values, noutputs, target_opers, ntargets, run_metadata, status) end _FUNCDEF("TF_SessionRun", { "TF_Session *", "const TF_Buffer *", "const TF_Output *", "TF_Tensor * const *", "int", "const TF_Output *", "TF_Tensor * *", "int", "const TF_Operation * const *", "int", "TF_Buffer *", "TF_Status *" }, "void") -- --- Set up the graph with the intended feeds (inputs) and fetches (outputs) for a --- sequence of partial run calls. --- On success, returns a handle that is used for subsequent PRun calls. The --- handle should be deleted with TF_DeletePRunHandle when it is no longer --- needed. --- On failure, out_status contains a tensorflow::Status with an error --- message. *handle is set to nullptr. --- Input names --- Output names --- Target operations --- Output handle --- Output status --- ---@param session ffi.cdata @(TF_Session *) ---@param inputs ffi.cdata @(const TF_Output *) ---@param ninputs number @(int) ---@param outputs ffi.cdata @(const TF_Output *) ---@param noutputs number @(int) ---@param target_opers ffi.cdata @(const TF_Operation * const *) ---@param ntargets number @(int) ---@param handle ffi.cdata @(const char * *) ---@param status ffi.cdata @(TF_Status *) function M.TF_SessionPRunSetup(session, inputs, ninputs, outputs, noutputs, target_opers, ntargets, handle, status) return _CALL("TF_SessionPRunSetup", session, inputs, ninputs, outputs, noutputs, target_opers, ntargets, handle, status) end _FUNCDEF("TF_SessionPRunSetup", { "TF_Session *", "const TF_Output *", "int", "const TF_Output *", "int", "const TF_Operation * const *", "int", "const char * *", "TF_Status *" }, "void") -- --- Continue to run the graph with additional feeds and fetches. The --- execution state is uniquely identified by the handle. --- Input tensors --- Output tensors --- Target operations --- Output status --- ---@param session ffi.cdata @(TF_Session *) ---@param handle string @(const char *) ---@param inputs ffi.cdata @(const TF_Output *) ---@param input_values ffi.cdata @(TF_Tensor * const *) ---@param ninputs number @(int) ---@param outputs ffi.cdata @(const TF_Output *) ---@param output_values ffi.cdata @(TF_Tensor * *) ---@param noutputs number @(int) ---@param target_opers ffi.cdata @(const TF_Operation * const *) ---@param ntargets number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_SessionPRun(session, handle, inputs, input_values, ninputs, outputs, output_values, noutputs, target_opers, ntargets, status) return _CALL("TF_SessionPRun", session, handle, inputs, input_values, ninputs, outputs, output_values, noutputs, target_opers, ntargets, status) end _FUNCDEF("TF_SessionPRun", { "TF_Session *", "const char *", "const TF_Output *", "TF_Tensor * const *", "int", "const TF_Output *", "TF_Tensor * *", "int", "const TF_Operation * const *", "int", "TF_Status *" }, "void") -- --- Deletes a handle allocated by TF_SessionPRunSetup. --- Once called, no more calls to TF_SessionPRun should be made. --- ---@param handle string @(const char *) function M.TF_DeletePRunHandle(handle) return _CALL("TF_DeletePRunHandle", handle) end _FUNCDEF("TF_DeletePRunHandle", { "const char *" }, "void") -- --- -------------------------------------------------------------------------- --- The deprecated session API. Please switch to the above instead of --- TF_ExtendGraph(). This deprecated API can be removed at any time without --- notice. --- _TYPEDEF("TF_DeprecatedSession", "struct TF_DeprecatedSession") -- ---@param session ffi.cdata @(const TF_SessionOptions *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_DeprecatedSession *) function M.TF_NewDeprecatedSession(session, status) return _CALL("TF_NewDeprecatedSession", session, status) end _FUNCDEF("TF_NewDeprecatedSession", { "const TF_SessionOptions *", "TF_Status *" }, "TF_DeprecatedSession *") -- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param status ffi.cdata @(TF_Status *) function M.TF_CloseDeprecatedSession(session, status) return _CALL("TF_CloseDeprecatedSession", session, status) end _FUNCDEF("TF_CloseDeprecatedSession", { "TF_DeprecatedSession *", "TF_Status *" }, "void") -- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param status ffi.cdata @(TF_Status *) function M.TF_DeleteDeprecatedSession(session, status) return _CALL("TF_DeleteDeprecatedSession", session, status) end _FUNCDEF("TF_DeleteDeprecatedSession", { "TF_DeprecatedSession *", "TF_Status *" }, "void") -- ---@param opt ffi.cdata @(const TF_SessionOptions *) ---@param containers ffi.cdata @(const char * *) ---@param ncontainers number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_Reset(opt, containers, ncontainers, status) return _CALL("TF_Reset", opt, containers, ncontainers, status) end _FUNCDEF("TF_Reset", { "const TF_SessionOptions *", "const char * *", "int", "TF_Status *" }, "void") -- --- Treat the bytes proto[0,proto_len-1] as a serialized GraphDef and --- add the nodes in that GraphDef to the graph for the session. --- Prefer use of TF_Session and TF_GraphImportGraphDef over this. --- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_ExtendGraph(session, proto, proto_len, status) return _CALL("TF_ExtendGraph", session, proto, proto_len, status) end _FUNCDEF("TF_ExtendGraph", { "TF_DeprecatedSession *", "const void *", "size_t", "TF_Status *" }, "void") -- --- See TF_SessionRun() above. --- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param run_options ffi.cdata @(const TF_Buffer *) ---@param input_names ffi.cdata @(const char * *) ---@param inputs ffi.cdata @(TF_Tensor * *) ---@param ninputs number @(int) ---@param output_names ffi.cdata @(const char * *) ---@param outputs ffi.cdata @(TF_Tensor * *) ---@param noutputs number @(int) ---@param target_oper_names ffi.cdata @(const char * *) ---@param ntargets number @(int) ---@param run_metadata ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) function M.TF_Run(session, run_options, input_names, inputs, ninputs, output_names, outputs, noutputs, target_oper_names, ntargets, run_metadata, status) return _CALL("TF_Run", session, run_options, input_names, inputs, ninputs, output_names, outputs, noutputs, target_oper_names, ntargets, run_metadata, status) end _FUNCDEF("TF_Run", { "TF_DeprecatedSession *", "const TF_Buffer *", "const char * *", "TF_Tensor * *", "int", "const char * *", "TF_Tensor * *", "int", "const char * *", "int", "TF_Buffer *", "TF_Status *" }, "void") -- --- See TF_SessionPRunSetup() above. --- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param input_names ffi.cdata @(const char * *) ---@param ninputs number @(int) ---@param output_names ffi.cdata @(const char * *) ---@param noutputs number @(int) ---@param target_oper_names ffi.cdata @(const char * *) ---@param ntargets number @(int) ---@param handle ffi.cdata @(const char * *) ---@param status ffi.cdata @(TF_Status *) function M.TF_PRunSetup(session, input_names, ninputs, output_names, noutputs, target_oper_names, ntargets, handle, status) return _CALL("TF_PRunSetup", session, input_names, ninputs, output_names, noutputs, target_oper_names, ntargets, handle, status) end _FUNCDEF("TF_PRunSetup", { "TF_DeprecatedSession *", "const char * *", "int", "const char * *", "int", "const char * *", "int", "const char * *", "TF_Status *" }, "void") -- --- See TF_SessionPRun above. --- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param handle string @(const char *) ---@param input_names ffi.cdata @(const char * *) ---@param inputs ffi.cdata @(TF_Tensor * *) ---@param ninputs number @(int) ---@param output_names ffi.cdata @(const char * *) ---@param outputs ffi.cdata @(TF_Tensor * *) ---@param noutputs number @(int) ---@param target_oper_names ffi.cdata @(const char * *) ---@param ntargets number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_PRun(session, handle, input_names, inputs, ninputs, output_names, outputs, noutputs, target_oper_names, ntargets, status) return _CALL("TF_PRun", session, handle, input_names, inputs, ninputs, output_names, outputs, noutputs, target_oper_names, ntargets, status) end _FUNCDEF("TF_PRun", { "TF_DeprecatedSession *", "const char *", "const char * *", "TF_Tensor * *", "int", "const char * *", "TF_Tensor * *", "int", "const char * *", "int", "TF_Status *" }, "void") -- _TYPEDEF("TF_DeviceList", "struct TF_DeviceList") -- --- Lists all devices in a TF_Session. --- Caller takes ownership of the returned TF_DeviceList* which must eventually --- be freed with a call to TF_DeleteDeviceList. --- ---@param session ffi.cdata @(TF_Session *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_DeviceList *) function M.TF_SessionListDevices(session, status) return _CALL("TF_SessionListDevices", session, status) end _FUNCDEF("TF_SessionListDevices", { "TF_Session *", "TF_Status *" }, "TF_DeviceList *") -- --- Lists all devices in a TF_Session. --- Caller takes ownership of the returned TF_DeviceList* which must eventually --- be freed with a call to TF_DeleteDeviceList. --- ---@param session ffi.cdata @(TF_DeprecatedSession *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_DeviceList *) function M.TF_DeprecatedSessionListDevices(session, status) return _CALL("TF_DeprecatedSessionListDevices", session, status) end _FUNCDEF("TF_DeprecatedSessionListDevices", { "TF_DeprecatedSession *", "TF_Status *" }, "TF_DeviceList *") -- --- Deallocates the device list. --- ---@param list ffi.cdata @(TF_DeviceList *) function M.TF_DeleteDeviceList(list) return _CALL("TF_DeleteDeviceList", list) end _FUNCDEF("TF_DeleteDeviceList", { "TF_DeviceList *" }, "void") -- --- Counts the number of elements in the device list. --- ---@param list ffi.cdata @(const TF_DeviceList *) ---@return number @(int) function M.TF_DeviceListCount(list) return _CALL("TF_DeviceListCount", list) end _FUNCDEF("TF_DeviceListCount", { "const TF_DeviceList *" }, "int") -- --- Retrieves the full name of the device (e.g. /job:worker/replica:0/...) --- The return value will be a pointer to a null terminated string. The caller --- must not modify or delete the string. It will be deallocated upon a call to --- TF_DeleteDeviceList. --- If index is out of bounds, an error code will be set in the status object, --- and a null pointer will be returned. --- ---@param list ffi.cdata @(const TF_DeviceList *) ---@param index number @(int) ---@param status ffi.cdata @(TF_Status *) ---@return string @(const char *) function M.TF_DeviceListName(list, index, status) return _CALL("TF_DeviceListName", list, index, status) end _FUNCDEF("TF_DeviceListName", { "const TF_DeviceList *", "int", "TF_Status *" }, "const char *") -- --- Retrieves the type of the device at the given index. --- The caller must not modify or delete the string. It will be deallocated upon --- a call to TF_DeleteDeviceList. --- If index is out of bounds, an error code will be set in the status object, --- and a null pointer will be returned. --- ---@param list ffi.cdata @(const TF_DeviceList *) ---@param index number @(int) ---@param status ffi.cdata @(TF_Status *) ---@return string @(const char *) function M.TF_DeviceListType(list, index, status) return _CALL("TF_DeviceListType", list, index, status) end _FUNCDEF("TF_DeviceListType", { "const TF_DeviceList *", "int", "TF_Status *" }, "const char *") -- --- Retrieve the amount of memory associated with a given device. --- If index is out of bounds, an error code will be set in the status object, --- and -1 will be returned. --- ---@param list ffi.cdata @(const TF_DeviceList *) ---@param index number @(int) ---@param status ffi.cdata @(TF_Status *) ---@return number @(int64_t) function M.TF_DeviceListMemoryBytes(list, index, status) return _CALL("TF_DeviceListMemoryBytes", list, index, status) end _FUNCDEF("TF_DeviceListMemoryBytes", { "const TF_DeviceList *", "int", "TF_Status *" }, "int64_t") -- --- Retrieve the incarnation number of a given device. --- If index is out of bounds, an error code will be set in the status object, --- and 0 will be returned. --- ---@param list ffi.cdata @(const TF_DeviceList *) ---@param index number @(int) ---@param status ffi.cdata @(TF_Status *) ---@return number @(uint64_t) function M.TF_DeviceListIncarnation(list, index, status) return _CALL("TF_DeviceListIncarnation", list, index, status) end _FUNCDEF("TF_DeviceListIncarnation", { "const TF_DeviceList *", "int", "TF_Status *" }, "uint64_t") -- --- -------------------------------------------------------------------------- --- Load plugins containing custom ops and kernels --- TF_Library holds information about dynamically loaded TensorFlow plugins. --- _TYPEDEF("TF_Library", "struct TF_Library") -- --- Load the library specified by library_filename and register the ops and --- kernels present in that library. --- Pass "library_filename" to a platform-specific mechanism for dynamically --- loading a library. The rules for determining the exact location of the --- library are platform-specific and are not documented here. --- On success, place OK in status and return the newly created library handle. --- The caller owns the library handle. --- On failure, place an error status in status and return NULL. --- ---@param library_filename string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Library *) function M.TF_LoadLibrary(library_filename, status) return _CALL("TF_LoadLibrary", library_filename, status) end _FUNCDEF("TF_LoadLibrary", { "const char *", "TF_Status *" }, "TF_Library *") -- --- Get the OpList of OpDefs defined in the library pointed by lib_handle. --- Returns a TF_Buffer. The memory pointed to by the result is owned by --- lib_handle. The data in the buffer will be the serialized OpList proto for --- ops defined in the library. --- ---@param lib_handle ffi.cdata @(TF_Library *) ---@return TF_Buffer @(TF_Buffer) function M.TF_GetOpList(lib_handle) return _CALL("TF_GetOpList", lib_handle) end _FUNCDEF("TF_GetOpList", { "TF_Library *" }, "TF_Buffer") -- --- Frees the memory associated with the library handle. --- Does NOT unload the library. --- ---@param lib_handle ffi.cdata @(TF_Library *) function M.TF_DeleteLibraryHandle(lib_handle) return _CALL("TF_DeleteLibraryHandle", lib_handle) end _FUNCDEF("TF_DeleteLibraryHandle", { "TF_Library *" }, "void") -- --- Get the OpList of all OpDefs defined in this address space. --- Returns a TF_Buffer, ownership of which is transferred to the caller --- (and can be freed using TF_DeleteBuffer). --- The data in the buffer will be the serialized OpList proto for ops registered --- in this address space. --- ---@return ffi.cdata @(TF_Buffer *) function M.TF_GetAllOpList() return _CALL("TF_GetAllOpList") end _FUNCDEF("TF_GetAllOpList", { }, "TF_Buffer *") -- --- TF_ApiDefMap encapsulates a collection of API definitions for an operation. --- This object maps the name of a TensorFlow operation to a description of the --- API to generate for it, as defined by the ApiDef protocol buffer ( --- https://www.tensorflow.org/code/tensorflow/core/framework/api_def.proto) --- The ApiDef messages are typically used to generate convenience wrapper --- functions for TensorFlow operations in various language bindings. --- _TYPEDEF("TF_ApiDefMap", "struct TF_ApiDefMap") -- --- Creates a new TF_ApiDefMap instance. --- Params: --- op_list_buffer - TF_Buffer instance containing serialized OpList --- protocol buffer. (See --- https://www.tensorflow.org/code/tensorflow/core/framework/op_def.proto --- for the OpList proto definition). --- status - Set to OK on success and an appropriate error on failure. --- ---@param op_list_buffer ffi.cdata @(TF_Buffer *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_ApiDefMap *) function M.TF_NewApiDefMap(op_list_buffer, status) return _CALL("TF_NewApiDefMap", op_list_buffer, status) end _FUNCDEF("TF_NewApiDefMap", { "TF_Buffer *", "TF_Status *" }, "TF_ApiDefMap *") -- --- Deallocates a TF_ApiDefMap. --- ---@param apimap ffi.cdata @(TF_ApiDefMap *) function M.TF_DeleteApiDefMap(apimap) return _CALL("TF_DeleteApiDefMap", apimap) end _FUNCDEF("TF_DeleteApiDefMap", { "TF_ApiDefMap *" }, "void") -- --- Add ApiDefs to the map. --- `text` corresponds to a text representation of an ApiDefs protocol message. --- (https://www.tensorflow.org/code/tensorflow/core/framework/api_def.proto). --- The provided ApiDefs will be merged with existing ones in the map, with --- precedence given to the newly added version in case of conflicts with --- previous calls to TF_ApiDefMapPut. --- ---@param api_def_map ffi.cdata @(TF_ApiDefMap *) ---@param text string @(const char *) ---@param text_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) function M.TF_ApiDefMapPut(api_def_map, text, text_len, status) return _CALL("TF_ApiDefMapPut", api_def_map, text, text_len, status) end _FUNCDEF("TF_ApiDefMapPut", { "TF_ApiDefMap *", "const char *", "size_t", "TF_Status *" }, "void") -- --- Returns a serialized ApiDef protocol buffer for the TensorFlow operation --- named `name`. --- ---@param api_def_map ffi.cdata @(TF_ApiDefMap *) ---@param name string @(const char *) ---@param name_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Buffer *) function M.TF_ApiDefMapGet(api_def_map, name, name_len, status) return _CALL("TF_ApiDefMapGet", api_def_map, name, name_len, status) end _FUNCDEF("TF_ApiDefMapGet", { "TF_ApiDefMap *", "const char *", "size_t", "TF_Status *" }, "TF_Buffer *") -- --- -------------------------------------------------------------------------- --- Kernel definition information. --- Returns a serialized KernelList protocol buffer containing KernelDefs for all --- registered kernels. --- ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Buffer *) function M.TF_GetAllRegisteredKernels(status) return _CALL("TF_GetAllRegisteredKernels", status) end _FUNCDEF("TF_GetAllRegisteredKernels", { "TF_Status *" }, "TF_Buffer *") -- --- Returns a serialized KernelList protocol buffer containing KernelDefs for all --- kernels registered for the operation named `name`. --- ---@param name string @(const char *) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Buffer *) function M.TF_GetRegisteredKernelsForOp(name, status) return _CALL("TF_GetRegisteredKernelsForOp", name, status) end _FUNCDEF("TF_GetRegisteredKernelsForOp", { "const char *", "TF_Status *" }, "TF_Buffer *") -- --- Update edge, switch input/ output in a node --- ---@param graph ffi.cdata @(TF_Graph *) ---@param new_src TF_Output @(TF_Output) ---@param dst TF_Input @(TF_Input) ---@param status ffi.cdata @(TF_Status *) function M.TF_UpdateEdge(graph, new_src, dst, status) return _CALL("TF_UpdateEdge", graph, new_src, dst, status) end _FUNCDEF("TF_UpdateEdge", { "TF_Graph *", "TF_Output", "TF_Input", "TF_Status *" }, "void") -- --- -------------------------------------------------------------------------- --- In-process TensorFlow server functionality, for use in distributed training. --- A Server instance encapsulates a set of devices and a Session target that --- can participate in distributed training. A server belongs to a cluster --- (specified by a ClusterSpec), and corresponds to a particular task in a --- named job. The server can communicate with any other server in the same --- cluster. --- In-process TensorFlow server. --- _TYPEDEF("TF_Server", "struct TF_Server") -- --- Creates a new in-process TensorFlow server configured using a serialized --- ServerDef protocol buffer provided via `proto` and `proto_len`. --- The server will not serve any requests until TF_ServerStart is invoked. --- The server will stop serving requests once TF_ServerStop or --- TF_DeleteServer is invoked. --- ---@param proto ffi.cdata @(const void *) ---@param proto_len number @(size_t) ---@param status ffi.cdata @(TF_Status *) ---@return ffi.cdata @(TF_Server *) function M.TF_NewServer(proto, proto_len, status) return _CALL("TF_NewServer", proto, proto_len, status) end _FUNCDEF("TF_NewServer", { "const void *", "size_t", "TF_Status *" }, "TF_Server *") -- --- Starts an in-process TensorFlow server. --- ---@param server ffi.cdata @(TF_Server *) ---@param status ffi.cdata @(TF_Status *) function M.TF_ServerStart(server, status) return _CALL("TF_ServerStart", server, status) end _FUNCDEF("TF_ServerStart", { "TF_Server *", "TF_Status *" }, "void") -- --- Stops an in-process TensorFlow server. --- ---@param server ffi.cdata @(TF_Server *) ---@param status ffi.cdata @(TF_Status *) function M.TF_ServerStop(server, status) return _CALL("TF_ServerStop", server, status) end _FUNCDEF("TF_ServerStop", { "TF_Server *", "TF_Status *" }, "void") -- --- Blocks until the server has been successfully stopped (via TF_ServerStop or --- TF_ServerClose). --- ---@param server ffi.cdata @(TF_Server *) ---@param status ffi.cdata @(TF_Status *) function M.TF_ServerJoin(server, status) return _CALL("TF_ServerJoin", server, status) end _FUNCDEF("TF_ServerJoin", { "TF_Server *", "TF_Status *" }, "void") -- --- Returns the target string that can be provided to TF_SetTarget() to connect --- a TF_Session to `server`. --- The returned string is valid only until TF_DeleteServer is invoked. --- ---@param server ffi.cdata @(TF_Server *) ---@return string @(const char *) function M.TF_ServerTarget(server) return _CALL("TF_ServerTarget", server) end _FUNCDEF("TF_ServerTarget", { "TF_Server *" }, "const char *") -- --- Destroy an in-process TensorFlow server, frees memory. If server is running --- it will be stopped and joined. --- ---@param server ffi.cdata @(TF_Server *) function M.TF_DeleteServer(server) return _CALL("TF_DeleteServer", server) end _FUNCDEF("TF_DeleteServer", { "TF_Server *" }, "void") -- --- Register a listener method that processes printed messages. --- If any listeners are registered, the print operator will call all listeners --- with the printed messages and immediately return without writing to the --- logs. --- ---@param listener ffi.cdata @(void *) function M.TF_RegisterLogListener(listener) return _CALL("TF_RegisterLogListener", listener) end _FUNCDEF("TF_RegisterLogListener", { "void *" }, "void") -- --- void TF_RegisterLogListener(void (*listener)(const char*)); --- Register a FileSystem plugin from filename `plugin_filename`. --- On success, place OK in status. --- On failure, place an error status in status. --- ---@param plugin_filename string @(const char *) ---@param status ffi.cdata @(TF_Status *) function M.TF_RegisterFilesystemPlugin(plugin_filename, status) return _CALL("TF_RegisterFilesystemPlugin", plugin_filename, status) end _FUNCDEF("TF_RegisterFilesystemPlugin", { "const char *", "TF_Status *" }, "void") -- ------------------------------------------------------------------------------ -- header/tf_datatype.h ------------------------------------------------------------------------------ -- --- TF_DataTypeSize returns the sizeof() for the underlying type corresponding --- to the given TF_DataType enum value. Returns 0 for variable length types --- (eg. TF_STRING) or on failure. --- ---@param dt TF_DataType @(TF_DataType) ---@return number @(size_t) function M.TF_DataTypeSize(dt) return _CALL("TF_DataTypeSize", dt) end _FUNCDEF("TF_DataTypeSize", { "TF_DataType" }, "size_t") -- ------------------------------------------------------------------------------ -- header/tf_status.h ------------------------------------------------------------------------------ -- _TYPEDEF("TF_Status", "struct TF_Status") -- -- --- -------------------------------------------------------------------------- --- Return a new status object. --- ---@return ffi.cdata @(TF_Status *) function M.TF_NewStatus() return _CALL("TF_NewStatus") end _FUNCDEF("TF_NewStatus", { }, "TF_Status *") -- --- Delete a previously created status object. --- ---@param s ffi.cdata @(TF_Status *) function M.TF_DeleteStatus(s) return _CALL("TF_DeleteStatus", s) end _FUNCDEF("TF_DeleteStatus", { "TF_Status *" }, "void") -- --- Record <code, msg> in *s. Any previous information is lost. --- A common use is to clear a status: TF_SetStatus(s, TF_OK, ""); --- ---@param s ffi.cdata @(TF_Status *) ---@param code TF_Code @(TF_Code) ---@param msg string @(const char *) function M.TF_SetStatus(s, code, msg) return _CALL("TF_SetStatus", s, code, msg) end _FUNCDEF("TF_SetStatus", { "TF_Status *", "TF_Code", "const char *" }, "void") -- --- Convert from an I/O error code (e.g., errno) to a TF_Status value. --- Any previous information is lost. Prefer to use this instead of TF_SetStatus --- when the error comes from I/O operations. --- ---@param s ffi.cdata @(TF_Status *) ---@param error_code number @(int) ---@param context string @(const char *) function M.TF_SetStatusFromIOError(s, error_code, context) return _CALL("TF_SetStatusFromIOError", s, error_code, context) end _FUNCDEF("TF_SetStatusFromIOError", { "TF_Status *", "int", "const char *" }, "void") -- --- Return the code record in *s. --- ---@param s ffi.cdata @(const TF_Status *) ---@return TF_Code @(TF_Code) function M.TF_GetCode(s) return _CALL("TF_GetCode", s) end _FUNCDEF("TF_GetCode", { "const TF_Status *" }, "TF_Code") -- --- Return a pointer to the (null-terminated) error message in *s. The --- return value points to memory that is only usable until the next --- mutation to *s. Always returns an empty string if TF_GetCode(s) is --- TF_OK. --- ---@param s ffi.cdata @(const TF_Status *) ---@return string @(const char *) function M.TF_Message(s) return _CALL("TF_Message", s) end _FUNCDEF("TF_Message", { "const TF_Status *" }, "const char *") -- ------------------------------------------------------------------------------ -- header/tf_tensor.h ------------------------------------------------------------------------------ _TYPEDEF("TF_Bool", "unsigned char") -- --- Allocator Attributes used for tensor allocation. --- Set boolean to 1 for CPU allocation, else 0. --- _TYPEDEF("TF_AllocatorAttributes", "struct TF_AllocatorAttributes { size_t struct_size ; TF_Bool on_host ; }") -- --- #define TF_ALLOCATOR_ATTRIBUTES_STRUCT_SIZE \ --- // TF_OFFSET_OF_END(TF_AllocatorAttributes, on_host) --- -------------------------------------------------------------------------- --- TF_Tensor holds a multi-dimensional array of elements of a single data type. --- For all types other than TF_STRING, the data buffer stores elements --- in row major order. E.g. if data is treated as a vector of TF_DataType: --- element 0: index (0, ..., 0) --- element 1: index (0, ..., 1) --- ... --- The format for TF_STRING tensors is: --- start_offset: array[uint64] --- data: byte[...] --- The string length (as a varint, start_offset[i + 1] - start_offset[i]), --- followed by the contents of the string is encoded at data[start_offset[i]]. --- TF_StringEncode and TF_StringDecode facilitate this encoding. --- _TYPEDEF("TF_Tensor", "struct TF_Tensor") -- --- Return a new tensor that holds the bytes data[0,len-1]. --- The data will be deallocated by a subsequent call to TF_DeleteTensor via: --- (*deallocator)(data, len, deallocator_arg) --- Clients must provide a custom deallocator function so they can pass in --- memory managed by something like numpy. --- May return NULL (and invoke the deallocator) if the provided data buffer --- (data, len) is inconsistent with a tensor of the given TF_DataType --- and the shape specified by (dima, num_dims). --- ---@param type TF_DataType @(TF_DataType) ---@param dims ffi.cdata @(const int64_t *) ---@param num_dims number @(int) ---@param data ffi.cdata @(void *) ---@param len number @(size_t) ---@param deallocator ffi.cdata @(void *) ---@param deallocator_arg ffi.cdata @(void *) ---@return ffi.cdata @(TF_Tensor *) function M.TF_NewTensor(type, dims, num_dims, data, len, deallocator, deallocator_arg) return _CALL("TF_NewTensor", type, dims, num_dims, data, len, deallocator, deallocator_arg) end _FUNCDEF("TF_NewTensor", { "TF_DataType", "const int64_t *", "int", "void *", "size_t", "void *", "void *" }, "TF_Tensor *") -- --- Allocate and return a new Tensor. --- This function is an alternative to TF_NewTensor and should be used when --- memory is allocated to pass the Tensor to the C API. The allocated memory --- satisfies TensorFlow's memory alignment preferences and should be preferred --- over calling malloc and free. --- The caller must set the Tensor values by writing them to the pointer returned --- by TF_TensorData with length TF_TensorByteSize. --- ---@param type TF_DataType @(TF_DataType) ---@param dims ffi.cdata @(const int64_t *) ---@param num_dims number @(int) ---@param len number @(size_t) ---@return ffi.cdata @(TF_Tensor *) function M.TF_AllocateTensor(type, dims, num_dims, len) return _CALL("TF_AllocateTensor", type, dims, num_dims, len) end _FUNCDEF("TF_AllocateTensor", { "TF_DataType", "const int64_t *", "int", "size_t" }, "TF_Tensor *") -- --- Deletes `tensor` and returns a new TF_Tensor with the same content if --- possible. Returns nullptr and leaves `tensor` untouched if not. --- ---@param tensor ffi.cdata @(TF_Tensor *) ---@return ffi.cdata @(TF_Tensor *) function M.TF_TensorMaybeMove(tensor) return _CALL("TF_TensorMaybeMove", tensor) end _FUNCDEF("TF_TensorMaybeMove", { "TF_Tensor *" }, "TF_Tensor *") -- --- Destroy a tensor. --- ---@param tensor ffi.cdata @(TF_Tensor *) function M.TF_DeleteTensor(tensor) return _CALL("TF_DeleteTensor", tensor) end _FUNCDEF("TF_DeleteTensor", { "TF_Tensor *" }, "void") -- --- Return the type of a tensor element. --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@return TF_DataType @(TF_DataType) function M.TF_TensorType(tensor) return _CALL("TF_TensorType", tensor) end _FUNCDEF("TF_TensorType", { "const TF_Tensor *" }, "TF_DataType") -- --- Return the number of dimensions that the tensor has. --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@return number @(int) function M.TF_NumDims(tensor) return _CALL("TF_NumDims", tensor) end _FUNCDEF("TF_NumDims", { "const TF_Tensor *" }, "int") -- --- Return the length of the tensor in the "dim_index" dimension. --- REQUIRES: 0 <= dim_index < TF_NumDims(tensor) --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@param dim_index number @(int) ---@return number @(int64_t) function M.TF_Dim(tensor, dim_index) return _CALL("TF_Dim", tensor, dim_index) end _FUNCDEF("TF_Dim", { "const TF_Tensor *", "int" }, "int64_t") -- --- Return the size of the underlying data in bytes. --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@return number @(size_t) function M.TF_TensorByteSize(tensor) return _CALL("TF_TensorByteSize", tensor) end _FUNCDEF("TF_TensorByteSize", { "const TF_Tensor *" }, "size_t") -- --- Return a pointer to the underlying data buffer. --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@return ffi.cdata @(void *) function M.TF_TensorData(tensor) return _CALL("TF_TensorData", tensor) end _FUNCDEF("TF_TensorData", { "const TF_Tensor *" }, "void *") -- --- Returns the number of elements in the tensor. --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@return number @(int64_t) function M.TF_TensorElementCount(tensor) return _CALL("TF_TensorElementCount", tensor) end _FUNCDEF("TF_TensorElementCount", { "const TF_Tensor *" }, "int64_t") -- --- Copy the internal data representation of `from` to `to`. `new_dims` and --- `num_new_dims` specify the new shape of the `to` tensor, `type` specifies its --- data type. On success, *status is set to TF_OK and the two tensors share the --- same data buffer. --- This call requires that the `from` tensor and the given type and shape (dims --- and num_dims) are "compatible" (i.e. they occupy the same number of bytes). --- Specifically, given from_type_size = TF_DataTypeSize(TF_TensorType(from)): --- ShapeElementCount(dims, num_dims) * TF_DataTypeSize(type) --- must equal --- TF_TensorElementCount(from) * from_type_size --- where TF_ShapeElementCount would be the number of elements in a tensor with --- the given shape. --- In addition, this function requires: --- TF_DataTypeSize(TF_TensorType(from)) != 0 --- TF_DataTypeSize(type) != 0 --- If any of the requirements are not met, *status is set to --- TF_INVALID_ARGUMENT. --- ---@param from ffi.cdata @(const TF_Tensor *) ---@param type TF_DataType @(TF_DataType) ---@param to ffi.cdata @(TF_Tensor *) ---@param new_dims ffi.cdata @(const int64_t *) ---@param num_new_dims number @(int) ---@param status ffi.cdata @(TF_Status *) function M.TF_TensorBitcastFrom(from, type, to, new_dims, num_new_dims, status) return _CALL("TF_TensorBitcastFrom", from, type, to, new_dims, num_new_dims, status) end _FUNCDEF("TF_TensorBitcastFrom", { "const TF_Tensor *", "TF_DataType", "TF_Tensor *", "const int64_t *", "int", "TF_Status *" }, "void") -- --- Returns bool iff this tensor is aligned. --- ---@param tensor ffi.cdata @(const TF_Tensor *) ---@return boolean @(bool) function M.TF_TensorIsAligned(tensor) return _CALL("TF_TensorIsAligned", tensor) end _FUNCDEF("TF_TensorIsAligned", { "const TF_Tensor *" }, "bool") -- return M
-- Copyright 2004-present Facebook. All Rights Reserved. -- Author: Michael Mathieu <myrhev@fb.com> require 'fbcunn.layers.HSM' require 'fbcunn.layers.cpu' local function test_finite_diff_gradInput(model, input, target) local eps = 1e-3 local output = model:updateOutput(input, target) local gradInput = model:updateGradInput(input, target):clone() local gradInput2 = torch.Tensor(input:size()) if input:dim() == 1 then for i = 1,input:size(1) do input[i] = input[i] + eps local outputP = model:updateOutput(input, target) input[i] = input[i] - 2*eps local outputM = model:updateOutput(input, target) input[i] = input[i] + eps gradInput2[i] = (outputP - outputM) / (2*eps) end else assert(input:dim() == 2) for i = 1,input:size(1) do for j = 1,input:size(2) do input[i][j] = input[i][j] + eps local outputP = model:updateOutput(input, target) input[i][j] = input[i][j] - 2*eps local outputM = model:updateOutput(input, target) input[i][j] = input[i][j] + eps gradInput2[i][j] = (outputP - outputM) / (2*eps) end end end return (gradInput - gradInput2):abs():max() end local function test_finite_diff_accGrads(model, input, target, scale) local eps = 1e-3 scale = scale or 1 local w, dw = model:getParameters() dw:zero() local output = model:updateOutput(input, target) local gradInput = model:updateGradInput(input, target):clone() model:accGradParameters(input, target, scale) local gradParams = dw:clone() local gradParams2 = torch.Tensor(w:size(1)) for i = 1,w:size(1) do w[i] = w[i] + eps local outputP = model:updateOutput(input, target) w[i] = w[i] - 2*eps local outputM = model:updateOutput(input, target) w[i] = w[i] + eps gradParams2[i] = scale * (outputP - outputM) / (2*eps) end return (gradParams - gradParams2):abs():max() end for i = 1,100 do print("Iteration " .. i) local n_clusters = torch.random(10) local n_class = torch.random(50) + n_clusters - 1 local mapping = {} local n_class_in_cluster = {} for i = 1, n_class do local cluster = torch.random(n_clusters) n_class_in_cluster[cluster] = n_class_in_cluster[cluster] or 0 n_class_in_cluster[cluster] = n_class_in_cluster[cluster] + 1 mapping[i] = {cluster, n_class_in_cluster[cluster]} end for i = 1,n_clusters do if n_class_in_cluster[i] == nil then n_class_in_cluster[i] = 1 mapping[1+#mapping] = {i, 1} n_class = n_class + 1 end end local input_size = torch.random(100) + 1 local model = nn.HSM(mapping, input_size) local input = torch.randn(input_size) local target = torch.LongTensor(1) target[1] = torch.random(n_class) local err = test_finite_diff_gradInput(model, input, target) assert(err < 1e-2) err = test_finite_diff_accGrads(model, input, target) assert(err < 1e-2) local scale = torch.rand(1)[1] err = test_finite_diff_accGrads(model, input, target, scale) assert(err < 1e-2) local batch_size = torch.random(10) input = torch.randn(batch_size, input_size) target = torch.LongTensor(batch_size) for i = 1, batch_size do target[i] = torch.random(n_class) end err = test_finite_diff_gradInput(model, input, target); assert(err < 1e-2) err = test_finite_diff_accGrads(model, input, target) assert(err < 1e-2) err = test_finite_diff_accGrads(model, input, target, scale) assert(err < 1e-2) -- test directUpdate local w, dw = model:getParameters() dw:normal() local initdw = dw:clone() model:updateOutput(input, target) model:updateGradInput(input, target) model:accGradParameters(input, target, scale, false) local w1 = w:clone():add(dw) model:updateOutput(input, target) model:updateGradInput(input, target) model:accGradParameters(input, target, scale, true) w:add(initdw) err = w:add(-1, w1):abs():max() assert(err < 1e-5) end
ESX = nil TriggerEvent('esx:getSharedObject', function(obj) ESX = obj end) -- Make sure all Vehicles are Stored on restart MySQL.ready(function() ParkVehicles() end) function ParkVehicles() MySQL.Async.execute('UPDATE owned_vehicles SET `stored` = true WHERE `stored` = @stored', { ['@stored'] = false }, function(rowsChanged) if rowsChanged > 0 then print(('esx_advancedgarage: %s vehicle(s) have been stored!'):format(rowsChanged)) end end) end -- Get Owned Properties ESX.RegisterServerCallback('esx_advancedgarage:getOwnedProperties', function(source, cb) local _source = source local xPlayer = ESX.GetPlayerFromId(_source) local properties = {} MySQL.Async.fetchAll('SELECT * FROM owned_properties WHERE owner = @owner', { ['@owner'] = xPlayer.getIdentifier() }, function(data) for _,v in pairs(data) do table.insert(properties, v.name) end cb(properties) end) end) -- Fetch Owned Aircrafts ESX.RegisterServerCallback('esx_advancedgarage:getOwnedAircrafts', function(source, cb) local ownedAircrafts = {} if Config.DontShowPoundCarsInGarage == true then MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'aircraft', ['@job'] = '', ['@stored'] = true }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedAircrafts, {vehicle = vehicle, stored = v.stored, plate = v.plate}) end cb(ownedAircrafts) end) else MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'aircraft', ['@job'] = '' }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedAircrafts, {vehicle = vehicle, stored = v.stored, plate = v.plate}) end cb(ownedAircrafts) end) end end) -- Fetch Owned Boats ESX.RegisterServerCallback('esx_advancedgarage:getOwnedBoats', function(source, cb) local ownedBoats = {} if Config.DontShowPoundCarsInGarage == true then MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'boat', ['@job'] = '', ['@stored'] = true }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedBoats, {vehicle = vehicle, stored = v.stored, plate = v.plate}) end cb(ownedBoats) end) else MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'boat', ['@job'] = '' }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedBoats, {vehicle = vehicle, stored = v.stored, plate = v.plate}) end cb(ownedBoats) end) end end) -- Fetch Owned Cars ESX.RegisterServerCallback('esx_advancedgarage:getOwnedCars', function(source, cb) local ownedCars = {} if Config.DontShowPoundCarsInGarage == true then MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'car', ['@job'] = '', ['@stored'] = true }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedCars, {vehicle = vehicle, stored = v.stored, plate = v.plate}) end cb(ownedCars) end) else MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'car', ['@job'] = '' }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedCars, {vehicle = vehicle, stored = v.stored, plate = v.plate}) end cb(ownedCars) end) end end) -- Store Vehicles ESX.RegisterServerCallback('esx_advancedgarage:storeVehicle', function (source, cb, vehicleProps) local ownedCars = {} local vehplate = vehicleProps.plate:match("^%s*(.-)%s*$") local vehiclemodel = vehicleProps.model local xPlayer = ESX.GetPlayerFromId(source) MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND @plate = plate', { ['@owner'] = xPlayer.identifier, ['@plate'] = vehicleProps.plate }, function (result) if result[1] ~= nil then local originalvehprops = json.decode(result[1].vehicle) if originalvehprops.model == vehiclemodel then MySQL.Async.execute('UPDATE owned_vehicles SET vehicle = @vehicle WHERE owner = @owner AND plate = @plate', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@vehicle'] = json.encode(vehicleProps), ['@plate'] = vehicleProps.plate }, function (rowsChanged) if rowsChanged == 0 then print(('esx_advancedgarage: %s attempted to store an vehicle they don\'t own!'):format(GetPlayerIdentifiers(source)[1])) end cb(true) end) else if Config.KickPossibleCheaters == true then if Config.UseCustomKickMessage == true then print(('esx_advancedgarage: %s attempted to Cheat! Tried Storing: '..vehiclemodel..'. Original Vehicle: '..originalvehprops.model):format(GetPlayerIdentifiers(source)[1])) DropPlayer(source, _U('custom_kick')) cb(false) else print(('esx_advancedgarage: %s attempted to Cheat! Tried Storing: '..vehiclemodel..'. Original Vehicle: '..originalvehprops.model):format(GetPlayerIdentifiers(source)[1])) DropPlayer(source, 'You have been Kicked from the Server for Possible Garage Cheating!!!') cb(false) end else print(('esx_advancedgarage: %s attempted to Cheat! Tried Storing: '..vehiclemodel..'. Original Vehicle: '..originalvehprops.model):format(GetPlayerIdentifiers(source)[1])) cb(false) end end else print(('esx_advancedgarage: %s attempted to store an vehicle they don\'t own!'):format(GetPlayerIdentifiers(source)[1])) cb(false) end end) end) -- Fetch Pounded Aircrafts ESX.RegisterServerCallback('esx_advancedgarage:getOutOwnedAircrafts', function(source, cb) local ownedAircrafts = {} MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'aircraft', ['@job'] = '', ['@stored'] = false }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedAircrafts, vehicle) end cb(ownedAircrafts) end) end) -- Fetch Pounded Boats ESX.RegisterServerCallback('esx_advancedgarage:getOutOwnedBoats', function(source, cb) local ownedBoats = {} MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'boat', ['@job'] = '', ['@stored'] = false }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedBoats, vehicle) end cb(ownedBoats) end) end) -- Fetch Pounded Cars ESX.RegisterServerCallback('esx_advancedgarage:getOutOwnedCars', function(source, cb) local ownedCars = {} MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND Type = @Type AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@Type'] = 'car', ['@job'] = '', ['@stored'] = false }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedCars, vehicle) end cb(ownedCars) end) end) -- Fetch Pounded Policing Vehicles ESX.RegisterServerCallback('esx_advancedgarage:getOutOwnedPolicingCars', function(source, cb) local ownedPolicingCars = {} MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@job'] = 'police', ['@stored'] = false }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedPolicingCars, vehicle) end cb(ownedPolicingCars) end) end) -- Fetch Pounded Ambulance Vehicles ESX.RegisterServerCallback('esx_advancedgarage:getOutOwnedAmbulanceCars', function(source, cb) local ownedAmbulanceCars = {} MySQL.Async.fetchAll('SELECT * FROM owned_vehicles WHERE owner = @owner AND job = @job AND `stored` = @stored', { ['@owner'] = GetPlayerIdentifiers(source)[1], ['@job'] = 'ambulance', ['@stored'] = false }, function(data) for _,v in pairs(data) do local vehicle = json.decode(v.vehicle) table.insert(ownedAmbulanceCars, vehicle) end cb(ownedAmbulanceCars) end) end) -- Check Money for Pounded Aircrafts ESX.RegisterServerCallback('esx_advancedgarage:checkMoneyAircrafts', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= Config.AircraftPoundPrice then cb(true) else cb(false) end end) -- Check Money for Pounded Boats ESX.RegisterServerCallback('esx_advancedgarage:checkMoneyBoats', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= Config.BoatPoundPrice then cb(true) else cb(false) end end) -- Check Money for Pounded Cars ESX.RegisterServerCallback('esx_advancedgarage:checkMoneyCars', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= Config.CarPoundPrice then cb(true) else cb(false) end end) -- Check Money for Pounded Policing ESX.RegisterServerCallback('esx_advancedgarage:checkMoneyPolicing', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= Config.PolicingPoundPrice then cb(true) else cb(false) end end) -- Check Money for Pounded Ambulance ESX.RegisterServerCallback('esx_advancedgarage:checkMoneyAmbulance', function(source, cb) local xPlayer = ESX.GetPlayerFromId(source) if xPlayer.get('money') >= Config.AmbulancePoundPrice then cb(true) else cb(false) end end) -- Pay for Pounded Aircrafts RegisterServerEvent('esx_advancedgarage:payAircraft') AddEventHandler('esx_advancedgarage:payAircraft', function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeMoney(Config.AircraftPoundPrice) TriggerClientEvent('esx:showNotification', source, _U('you_paid') .. Config.AircraftPoundPrice) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mechanic', function(account) account.addMoney(Config.AircraftPoundPrice) end) end) -- Pay for Pounded Boats RegisterServerEvent('esx_advancedgarage:payBoat') AddEventHandler('esx_advancedgarage:payBoat', function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeMoney(Config.BoatPoundPrice) TriggerClientEvent('esx:showNotification', source, _U('you_paid') .. Config.BoatPoundPrice) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mechanic', function(account) account.addMoney(Config.BoatPoundPrice) end) end) -- Pay for Pounded Cars RegisterServerEvent('esx_advancedgarage:payCar') AddEventHandler('esx_advancedgarage:payCar', function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeMoney(Config.CarPoundPrice) TriggerClientEvent('esx:showNotification', source, _U('you_paid') .. Config.CarPoundPrice) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mechanic', function(account) account.addMoney(Config.CarPoundPrice) end) end) -- Pay for Pounded Policing RegisterServerEvent('esx_advancedgarage:payPolicing') AddEventHandler('esx_advancedgarage:payPolicing', function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeMoney(Config.PolicingPoundPrice) TriggerClientEvent('esx:showNotification', source, _U('you_paid') .. Config.PolicingPoundPrice) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mechanic', function(account) account.addMoney(Config.PolicingPoundPrice) end) end) -- Pay for Pounded Ambulance RegisterServerEvent('esx_advancedgarage:payAmbulance') AddEventHandler('esx_advancedgarage:payAmbulance', function() local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeMoney(Config.AmbulancePoundPrice) TriggerClientEvent('esx:showNotification', source, _U('you_paid') .. Config.AmbulancePoundPrice) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mechanic', function(account) account.addMoney(Config.AmbulancePoundPrice) end) end) -- Pay to Return Broken Vehicles RegisterServerEvent('esx_advancedgarage:payhealth') AddEventHandler('esx_advancedgarage:payhealth', function(price) local xPlayer = ESX.GetPlayerFromId(source) xPlayer.removeMoney(price) TriggerClientEvent('esx:showNotification', source, _U('you_paid') .. price) TriggerEvent('esx_addonaccount:getSharedAccount', 'society_mechanic', function(account) account.addMoney(price) end) end) -- Modify State of Vehicles RegisterServerEvent('esx_advancedgarage:setVehicleState') AddEventHandler('esx_advancedgarage:setVehicleState', function(plate, state) local xPlayer = ESX.GetPlayerFromId(source) MySQL.Async.execute('UPDATE owned_vehicles SET `stored` = @stored WHERE plate = @plate', { ['@stored'] = state, ['@plate'] = plate }, function(rowsChanged) if rowsChanged == 0 then print(('esx_advancedgarage: %s exploited the garage!'):format(xPlayer.identifier)) end end) end)
#!/usr/bin/env th -- Copyright (c) 2017, The OctNet authors -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the <organization> nor the -- names of its contributors may be used to endorse or promote products -- derived from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -- DISCLAIMED. IN NO EVENT SHALL OCTNET AUTHORS BE LIABLE FOR ANY -- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. local test_utils = require('test_utils') local nn = require('nn') local mytester = torch.Tester() local octest = torch.TestSuite() function octest.VolumetricNNUpsampling() local function vol_upsample(input, factor) local N = input:size(1) local fs = input:size(2) local in_depth, in_height, in_width = input:size(3), input:size(4), input:size(5) local out_height, out_width, out_depth = factor*in_height, factor*in_width, factor*in_depth local out = torch.zeros(N, fs, out_depth, out_height, out_width):float() local in_data = input:data() local out_data = out:data() for n = 0, N-1 do for f = 0, fs-1 do for od = 0, out_depth-1 do for oh = 0, out_height-1 do for ow = 0, out_width-1 do local id, ih, iw = math.floor(od/factor), math.floor(oh/factor), math.floor(ow/factor) local out_idx = (((n * fs + f) * out_depth + od) * out_height + oh) * out_width + ow local in_idx = (((n * fs + f) * in_depth + id) * in_height + ih) * in_width + iw local in_val = in_data[in_idx] out_data[out_idx] = in_val end end end end end return out end local function vol_upsample_bwd(input, factor) local N = input:size(1) local fs = input:size(2) local in_depth, in_height, in_width = input:size(3), input:size(4), input:size(5) local out_height, out_width, out_depth = math.floor(in_height/factor), math.floor(in_width/factor), math.floor(in_depth/factor) local out = torch.zeros(N, fs, out_depth, out_height, out_width):float() local in_data = input:data() local out_data = out:data() for n = 0, N-1 do for f = 0, fs-1 do for id = 0, in_depth-1 do for ih = 0, in_height-1 do for iw = 0, in_width-1 do local od, oh, ow = math.floor(id/factor), math.floor(ih/factor), math.floor(iw/factor) local out_idx = (((n * fs + f) * out_depth + od) * out_height + oh) * out_width + ow local in_idx = (((n * fs + f) * in_depth + id) * in_height + ih) * in_width + iw out_data[out_idx] = out_data[out_idx] + in_data[in_idx] end end end end end return out end local function test(input, factor) local mod = oc.VolumetricNNUpsampling(factor):float() local mod_out = mod:forward(input) local tst_out = vol_upsample(input, factor) local err = torch.abs(mod_out - tst_out):max() mytester:assert(err < 1e-6, 'VolumetricNNUpsampling forward factor='..factor) local grad = tst_out:clone() grad:apply(function() torch.uniform(-1,1) end) local mod_out = mod:backward(input, grad) local tst_out = vol_upsample_bwd(grad, factor) local err = torch.abs(mod_out - tst_out):max() mytester:assert(err < 1e-6, 'VolumetricNNUpsampling backward factor='..factor) end for _, factor in ipairs{2, 1, 3, 4} do test(torch.randn(1, 1, 1,1,1):float(), factor) test(torch.randn(1, 2, 1,1,1):float(), factor) test(torch.randn(1, 4, 4,5,6):float(), factor) test(torch.randn(3, 4, 4,5,6):float(), factor) end end function octest.copy_sup_to_sub() local function test(sup) local sub = sup:clone() for grid_idx = 1, sup:n_blocks() do for bit_idx = 1, 73 do local pa_bit_idx = sup:tree_parent_bit_idx(bit_idx) if (bit_idx == 1 or sub:tree_isset_bit(grid_idx, pa_bit_idx)) and torch.uniform(0,1) > 0.5 then sub:tree_set_bit(grid_idx, bit_idx) end end end -- sub:tree_set_bit(1,1) sub:update_n_leafs() sub:update_prefix_leafs() sub:resize_as(sub) sub:apply(function() torch.uniform(-1,1) end) sub:copy_from_sup(sup) local dsup = oc.OctreeToCDHW():float():forward(sup) local dsub = oc.OctreeToCDHW():float():forward(sub) local err = torch.abs(dsup - dsub):max() mytester:assert(err < 1e-6, 'copy_sup_to_sub error='..err) end for _, n in ipairs{1, 4} do test( test_utils.octree_rand(n, 1,1,1, 1, 0,0,0) ) test( test_utils.octree_rand(n, 2,4,6, 3, 0,0,0) ) test( test_utils.octree_rand(n, 2,4,6, 3, 1,0,0) ) test( test_utils.octree_rand(n, 2,4,6, 3, 1,1,0) ) test( test_utils.octree_rand(n, 2,4,6, 3, 1,1,1) ) test( test_utils.octree_rand(n, 2,4,6, 3, 0.5,0.5,0.5) ) test( test_utils.octree_rand(n, 2,4,6, 3, 0.5,0.5,0.5) ) end end function octest.combine_extract_n() local function test(grid, reps) local grids = { } for idx = 1, reps do table.insert(grids, grid) end local grid_cmb = grid:combine_n(grids) for idx = 1, #grids do local grid_ext = grid_cmb:extract_n(idx, idx+1) mytester:assert(grid_ext:equals(grids[idx], 1e-4, true), 'combine_extract_n') end end test( test_utils.octree_rand(1, 1,1,1, 1, 0,0,0), 1 ) test( test_utils.octree_rand(1, 1,1,1, 1, 0,0,0), 4 ) test( test_utils.octree_rand(1, 2,3,4, 1, 0,0,0), 4 ) test( test_utils.octree_rand(1, 2,3,4, 3, 0,0,0), 4 ) test( test_utils.octree_rand(1, 2,3,4, 3, 0.5,0.5,0.5), 4 ) test( test_utils.octree_rand(1, 4,5,6, 5, 0,0,0), 13 ) test( test_utils.octree_rand(1, 8,16,32, 8, 0,0,0), 16 ) local grids = { test_utils.octree_rand(1, 2,3,4, 3, 1,1,0), test_utils.octree_rand(2, 2,3,4, 3, 1,1,0), test_utils.octree_rand(1, 2,3,4, 3, 1,1,0), test_utils.octree_rand(3, 2,3,4, 3, 1,1,0) } local grid_cmb = grid:combine_n(grids) mytester:assert(grid_cmb:extract_n(1,2):equals(grids[1], 1e-4, true), 'combine_extract_n') mytester:assert(grid_cmb:extract_n(2,4):equals(grids[2], 1e-4, true), 'combine_extract_n') mytester:assert(grid_cmb:extract_n(4,5):equals(grids[3], 1e-4, true), 'combine_extract_n') mytester:assert(grid_cmb:extract_n(5,8):equals(grids[4], 1e-4, true), 'combine_extract_n') end function octest.IO() local function test_oc(n, grid_depth, grid_height, grid_width, feature_size, n_threads) print('') local grids = {} local oc_paths = {} for idx = 1, n do local oc_path = string.format('test_grid_%d.oc', idx) table.insert(oc_paths, oc_path) local grid = test_utils.octree_rand(1,grid_depth,grid_height,grid_width, feature_size, 0.5,0.5,0.5) print(string.format('grid_gt %d: %d, %d,%d,%d, %d, %d', idx, grid:n(), grid:grid_depth(),grid:grid_height(),grid:grid_width(), grid:feature_size(), grid:n_leafs())) table.insert(grids, grid) grid:write_to_bin(oc_path) end for idx = 1, n do local grid = oc.FloatOctree() grid:read_from_bin( oc_paths[idx] ) print(string.format('grid_read %d: %d, %d,%d,%d, %d, %d', idx, grid:n(), grid:grid_depth(),grid:grid_height(),grid:grid_width(), grid:feature_size(), grid:n_leafs())) mytester:assert(grid:equals(grids[idx], 1e-4, true), 'read_from_bin') end local grid_b = oc.FloatOctree() print('read batch') grid_b:read_from_bin_batch(oc_paths, n_threads) print(string.format('grid_b: %d, %d,%d,%d, %d, %d', grid_b:n(), grid_b:grid_depth(),grid_b:grid_height(),grid_b:grid_width(), grid_b:feature_size(), grid_b:n_leafs())) for idx = 1, n do -- print('split '..idx) local grid = grid_b:extract_n(idx, idx+1) print(string.format('grid_ext %d: %d, %d,%d,%d, %d, %d', idx, grid:n(), grid:grid_depth(),grid:grid_height(),grid:grid_width(), grid:feature_size(), grid:n_leafs())) mytester:assert(grid:equals(grids[idx], 1e-4, true), 'read_from_bin_batch') end end local function test_dense(n, depth, height, width, feature_size, n_threads) local tensors = {} local tensor_paths = {} for idx = 1, n do local tensor = torch.randn(1, feature_size, depth,height,width):float() table.insert(tensors, tensor) local tensor_path = string.format('test_tensor_%d.cdhw', idx) table.insert(tensor_paths, tensor_path) oc.write_dense_to_bin(tensor_path, tensor) end for idx = 1, n do local tensor = torch.FloatTensor(1, feature_size, depth,height,width) oc.read_dense_from_bin(tensor_paths[idx], tensor) mytester:assert(torch.abs(tensor - tensors[idx]):max() < 1e-6, 'read_dense_from_bin') end local tensor_b = torch.FloatTensor(n, feature_size, depth,height,width) oc.read_dense_from_bin_batch(tensor_paths, tensor_b, n_threads) for idx = 1, n do local tensor = tensor_b[idx] mytester:assert(torch.abs(tensor - tensors[idx]):max() < 1e-6, 'read_dense_from_bin_batch') end end for _, n_threads in ipairs{1, 4} do test_oc(1, 1,1,1, 1, n_threads) test_oc(2, 1,1,1, 1, n_threads) test_oc(1, 1,1,1, 2, n_threads) test_oc(2, 1,1,1, 2, n_threads) test_oc(3, 2,3,4, 2, n_threads) test_oc(4, 3,4,5, 4, n_threads) test_oc(8, 8,16,32, 8, n_threads) test_dense(1, 1,1,1, 1, n_threads) test_dense(2, 1,1,1, 1, n_threads) test_dense(1, 1,1,1, 2, n_threads) test_dense(2, 1,1,1, 2, n_threads) test_dense(3, 2,3,4, 2, n_threads) test_dense(4, 3,4,5, 4, n_threads) test_dense(8, 8,16,32, 8, n_threads) end end function octest.OctreeCDHW() local function test(grid, dense_depth, dense_height, dense_width) local input = grid local o2d = oc.OctreeToCDHW(dense_depth, dense_height, dense_width) local d2o = oc.CDHWToOctree(o2d, 'avg') local o2d_output = o2d:forward(input) local d2o_output = d2o:forward(o2d_output) mytester:assert(d2o_output:equals(grid, 1e-4, true), 'error in OctreeCDHW forward') local d2o_bwd_output = d2o:backward(o2d_output, d2o_output) local o2d_bwd_output = o2d:backward(input, d2o_bwd_output) mytester:assert(o2d_bwd_output:equals(grid, 1e-4, true), 'error in OctreeCDHW backward') end local function test_battery(dense_depth, dense_height, dense_width) for _, n in ipairs{1,4} do test(test_utils.octree_rand(n,1,1,1, 1, 0,0,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,1,1,1, 3, 0,0,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,1,1,1, 1, 1,0,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,1,1,1, 1, 1,1,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,1,1,1, 1, 1,1,1), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,2,3,4, 3, 0,0,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,2,3,4, 3, 1,0,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,2,3,4, 3, 1,1,0), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,2,3,4, 3, 1,1,1), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,2,3,4, 2, 0.5,0.5,0.5), dense_depth, dense_height, dense_width) test(test_utils.octree_rand(n,2,3,4, 2, 0.5,0.5,0.5), dense_depth, dense_height, dense_width) end end test_battery() test_battery(32,32,32) test_battery(64,64,64) end function octest.Octree2CDHWBwd() -- takes a lot of time local function test(grid) local input = grid local o2d = oc.OctreeToCDHW() local output = o2d:forward(input) local grad_output = output:clone() o2d:backward(input, grad_output) local fwd_fcn = function() o2d:forward(input) end local jac_fwd = test_utils.jacobian_forward(grid.grid.data, grid:n_elems(), output:data(), output:nElement(), fwd_fcn, 1e-2) local bwd_fcn = function() o2d:backward(input, grad_output) end local jac_bwd = test_utils.jacobian_backward(o2d.gradInput.grid.data, o2d.gradInput:n_elems(), grad_output:data(), grad_output:nElement(), bwd_fcn) local max_err = torch.abs(jac_fwd - jac_bwd):max() mytester:assert(max_err < 1e-5, 'Octree2DenseBwd error '..max_err) end for _, n in ipairs{1,4} do test(test_utils.octree_rand(n,1,1,1, 1, 0,0,0)) test(test_utils.octree_rand(n,1,1,1, 1, 1,0,0)) test(test_utils.octree_rand(n,1,1,1, 1, 1,1,0)) test(test_utils.octree_rand(n,1,1,1, 1, 1,1,1)) test(test_utils.octree_rand(n,2,3,4, 2, 0.5,0.5,0.5)) end end function octest.OctreeDenseConvolutionBwd() -- takes a lot of time local function test(grid) local out_channels = 1 local input = grid local in_channels = grid:feature_size() local conv_dense = oc.OctreeDenseConvolution(in_channels, out_channels, 'avg', false, nn):float() local output = conv_dense:forward(input) local grad_output = output:clone() conv_dense:backward(input, grad_output) local fwd_fcn = function() conv_dense:forward(input) end local jac_fwd = test_utils.jacobian_forward(grid.grid.data, grid:n_elems(), output.grid.data, output:n_elems(), fwd_fcn, 1e-2) local bwd_fcn = function() conv_dense:zeroGradParameters(); conv_dense:backward(input, grad_output) end local jac_bwd = test_utils.jacobian_backward(conv_dense.gradInput.grid.data, conv_dense.gradInput:n_elems(), grad_output.grid.data, grad_output:n_elems(), bwd_fcn) local max_err = torch.abs(jac_fwd - jac_bwd):max() -- print(jac_fwd, jac_bwd) mytester:assert(max_err < 1e-2, 'Octree2DenseBwd error '..max_err) end for _, n in ipairs{1,4} do test(test_utils.octree_rand(n,1,1,1, 1, 0,0,0)) test(test_utils.octree_rand(n,1,1,1, 1, 1,0,0)) test(test_utils.octree_rand(n,1,1,1, 1, 1,1,0)) test(test_utils.octree_rand(n,1,1,1, 1, 1,1,1)) test(test_utils.octree_rand(n,2,3,4, 2, 0.5,0.5,0.5)) end end function octest.OctreeConvolution3x3x3() for _, out_channels in ipairs{2} do for _, grid in ipairs{test_utils.octree_rand(1, 3,2,2, 3, 0.5,0.5,0.5)} do print('') local input = grid local in_channels = grid:feature_size() local rdc_fcn = 'avg' local conv = oc.OctreeConvolution3x3x3(in_channels, out_channels, rdc_fcn):float() local conv_dense = oc.OctreeDenseConvolution(in_channels, out_channels, rdc_fcn, true):float() conv.weight:copy(conv_dense.weight) conv.bias:copy(conv_dense.bias) -- compare forward to OctreeDenseConvolution local conv_out = conv:forward(input) local conv_dense_out = conv_dense:forward(input) print('min/max input : '..input:min()..','..input:max()) print('min/max output: '..conv_dense_out:min()..','..conv_dense_out:max()) print('min/max output: '..conv_out:min()..','..conv_out:max()) if rdc_fcn == 'sum' then mytester:assert(conv_out:equals(conv_dense_out, 1e-2, true), 'error in OctreeConvolution3x3x3 forward') elseif rdc_fcn == 'avg' then mytester:assert(conv_out:equals(conv_dense_out, 1e-5, true), 'error in OctreeConvolution3x3x3 forward') end -- compare backward to OctreeDenseConvolution conv:zeroGradParameters() conv_dense:zeroGradParameters() local grad_out = conv_out:mul(1e-3) local conv_bwd_out = conv:backward(input, grad_out) local conv_dense_bwd_out = conv_dense:backward(input, grad_out) if rdc_fcn == 'sum' then mytester:assert(conv_bwd_out:equals(conv_dense_bwd_out, 1e-2, true), 'error in OctreeConvolution3x3x3 backward (sum)') elseif rdc_fcn == 'avg' then mytester:assert(conv_bwd_out:equals(conv_dense_bwd_out, 1e-5, true), 'error in OctreeConvolution3x3x3 backward (avg)') end local werr = torch.abs(conv.gradWeight - conv_dense.gradWeight):max() local berr = torch.abs(conv.gradBias - conv_dense.gradBias):max() if rdc_fcn == 'sum' then mytester:assert(werr < 1e-1, 'error in OctreeConvolution3x3x3 weight backward') mytester:assert(berr < 1e-1, 'error in OctreeConvolution3x3x3 bias backward') elseif rdc_fcn == 'avg' then mytester:assert(werr < 1e-4, 'error in OctreeConvolution3x3x3 weight backward') mytester:assert(berr < 1e-4, 'error in OctreeConvolution3x3x3 bias backward') end end end end function octest.OctreePool2x2x2() -- check gradient with finite differences -- takes a lot of time local function test_pool_fd(pool, input) local output = pool:forward(input) local grad_output = output:clone() for idx = 0, grad_output:n_elems()-1 do grad_output.grid.data[idx] = idx + 1 end pool:backward(input, grad_output) local fwd_fcn = function() pool:forward(input) end local jac_fwd = test_utils.jacobian_forward(grid.grid.data, grid:n_elems(), output.grid.data, output:n_elems(), fwd_fcn, 1e-3) local bwd_fcn = function() pool:zeroGradParameters(); pool:backward(input, grad_output) end local jac_bwd = test_utils.jacobian_backward(pool.gradInput.grid.data, pool.gradInput:n_elems(), grad_output.grid.data, grad_output:n_elems(), bwd_fcn) local max_err = torch.abs(jac_fwd - jac_bwd):max() -- print('') -- print(jac_fwd) -- print(jac_bwd) mytester:assert(max_err < 1e-4, 'Octree2DenseBwd error '..max_err) end for _, level_0 in ipairs{false, true} do for _, level_1 in ipairs{false, true} do for _, level_2 in ipairs{false, true} do test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 0,0,0)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 1,0,0)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 1,1,0)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 1,1,1)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 0.5,0,0)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 0.5,0.5,0)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(1, 2,2,3, 3, 0.5,0.5,0.5)) test_pool_fd(oc.OctreePool2x2x2('avg', leve_0, level_1, level_2):float(), test_utils.octree_rand(2, 2,2,3, 3, 0.5,0.5,0.5)) end end end end function octest.OctreeGridPool2x2x2() local function test(pool_fcn, grid, fd) local pool = oc.OctreeGridPool2x2x2(pool_fcn):float() local o2d = oc.OctreeToCDHW() local dp if pool_fcn == 'avg' then dp = nn.VolumetricAveragePooling(2,2,2, 2,2,2) elseif pool_fcn == 'max' then dp = nn.VolumetricMaxPooling(2,2,2, 2,2,2) else error('unknown pool fcn') end local d2o = oc.CDHWToOctree(pool, pool_fcn) o2d = o2d:float() dp = dp:float() d2o = d2o:float() -- test fwd local gp_out = pool:forward(grid) pool.received_input = gp_out local cdhw = o2d:forward(grid) local cdhw_pool = dp:forward(cdhw) local dn_out = d2o:forward(cdhw_pool) -- print('------ input ------') -- grid:print() -- print('------ oc out ------') -- gp_out:print() -- print('------ dense out ------') -- dn_out:print() mytester:assert(gp_out:equals(dn_out, 1e-6, true), 'error in OctreeGridPool2x2x2 forward') -- test bwd local grad_out = gp_out:clone() local gp_grad_in = pool:backward(grid, grad_out) local d2o_grad_in = d2o:backward(cdhw_pool, grad_out) local cdhw_pool_grad_in = dp:backward(cdhw, d2o_grad_in) local dn_grad_in = o2d:backward(grid, cdhw_pool_grad_in) mytester:assert(gp_grad_in:equals(dn_grad_in, 1e-4, true), 'error in OctreeGridPool2x2x2 backward') -- check gradient with finite differences if fd then local output = pool:forward(grid) local grad_output = output:clone() for idx = 0, grad_output:n_elems()-1 do grad_output.grid.data[idx] = math.random(-2, 2) end pool:backward(grid, grad_output) local fwd_fcn = function() pool:forward(grid) end local jac_fwd = test_utils.jacobian_forward(grid.grid.data, grid:n_elems(), output.grid.data, output:n_elems(), fwd_fcn, 1e-3) local bwd_fcn = function() pool:zeroGradParameters(); pool:backward(grid, grad_output) end local jac_bwd = test_utils.jacobian_backward(pool.gradInput.grid.data, pool.gradInput:n_elems(), grad_output.grid.data, grad_output:n_elems(), bwd_fcn) local max_err = torch.abs(jac_fwd - jac_bwd):max() -- print('') -- print(jac_fwd) -- print(jac_bwd) mytester:assert(max_err < 1e-4, 'OctreeGridPool2x2x2 fd error '..max_err) end end local pool_fcn = 'avg' for _, n in ipairs{1, 4} do test(pool_fcn, test_utils.octree_rand(n, 2,2,2, 2, 0,0,0), true) test(pool_fcn, test_utils.octree_rand(n, 2,2,2, 2, 1,1,1), true) test(pool_fcn, test_utils.octree_rand(n, 2,2,2, 2, 0.5,0.5,0.5), true) test(pool_fcn, test_utils.octree_rand(n, 2,4,6, 2, 0.5,0.5,0.5)) test(pool_fcn, test_utils.octree_rand(n, 4,8,6, 8, 0.5,0.5,0.5)) end end function octest.OctreeGridUnpoolGuided2x2x2() local function test(grid_in) local function fwd(grid_data, grid_struct) local vup = oc.VolumetricNNUpsampling(2):float() local o2d = oc.OctreeToCDHW():float() local d2o = oc.CDHWToOctree(o2d, 'avg'):float() local out_cdhw = o2d:forward(grid_data) local out_up = vup:forward(out_cdhw) o2d.received_input = grid_struct local out = d2o:forward(out_up) return out end local function bwd(grid_data, grid_struct, grad) local vup = oc.VolumetricNNUpsampling(2):float() local o2d = oc.OctreeToCDHW():float() local d2o = oc.CDHWToOctree(o2d, 'avg'):float() local out_cdhw = o2d:forward(grid_data) local out_up = vup:forward(out_cdhw) o2d.received_input = grid_struct local out = d2o:forward(out_up) local grad_d2o = d2o:backward(out_up, grad) local grad_down = vup:backward(out_cdhw, grad_d2o) local grad_out = o2d:backward(grid_data, grad_down) return grad_out end local struct = nn.Identity() struct:forward(grid) local pooling = oc.OctreeGridPool2x2x2('max') local grid_pooled = pooling:forward(grid) local test_out = fwd(grid_pooled, grid_in) local test_grad = bwd(grid_pooled, grid_in, test_out) local mod = oc.OctreeGridUnpoolGuided2x2x2(struct) local mod_out = mod:forward(grid_pooled) local mod_grad = mod:backward(grid_pooled, test_out) mytester:assert(test_out:equals(mod_out, 1e-4, true), 'error in OctreeGridUnpoolGuided2x2x2 forward') mytester:assert(test_grad:equals(mod_grad, 1e-4, true), 'error in OctreeGridUnpoolGuided2x2x2 backward') end for _, n in ipairs{1, 4} do for _, fs in ipairs{1, 3} do test(test_utils.octree_rand(n, 2,2,2, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 1.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 1.0,1.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 1.0,1.0,1.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 1.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 1.0,1.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 1.0,1.0,1.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 2,4,6, fs, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 4,4,6, fs, 0.5,0.5,0.5)) end end end function octest.OctreeGridUnpool2x2x2() local function test(grid_big) local grid_big_cpy = grid_big:clone() local grid_small = oc.OctreeGridPool2x2x2('max'):float():forward(grid_big) for grid_idx = 1, grid_big:n_blocks() do for bit_idx = 10, 73 do grid_big:tree_unset_bit(grid_idx, bit_idx) end end grid_big:update_n_leafs() grid_big:update_prefix_leafs() local mod_struct = nn.Identity():float() mod_struct:forward(grid_big) local mod_guided = oc.OctreeGridUnpoolGuided2x2x2(mod_struct) local mod = oc.OctreeGridUnpool2x2x2() local test_out = mod_guided:forward(grid_small) local mod_out = mod:forward(grid_small) local test_grad = mod_guided:backward(grid_small, test_out) local mod_grad = mod:backward(grid_small, test_out) mytester:assert(test_out:equals(mod_out, 1e-4, true), 'error in OctreeGridUnpool2x2x2 forward') mytester:assert(test_grad:equals(mod_grad, 1e-4, true), 'error in OctreeGridUnpool2x2x2 backward') end for _, n in ipairs{1, 4} do for _, fs in ipairs{1, 3} do test(test_utils.octree_rand(n, 2,2,2, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 1.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 1.0,1.0,0.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 1.0,1.0,1.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 0.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 1.0,0.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 1.0,1.0,0.0)) test(test_utils.octree_rand(n, 2,4,6, fs, 1.0,1.0,1.0)) test(test_utils.octree_rand(n, 2,2,2, fs, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 2,4,6, fs, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 4,4,6, fs, 0.5,0.5,0.5)) end end end function octest.OctreeAdd() local function test(oc1) local todense = function(x) return oc.OctreeToCDHW():forward(x) end local oc2 = oc1:clone():apply(function() torch.uniform(-1,1) end) local de1 = todense(oc1) local de2 = todense(oc2) local add1 = torch.uniform(-1,1) local ocr = oc1:add(add1) local der = de1:add(add1) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-6, 'add1') local ocr = oc1:add(oc2) local der = de1:add(de2) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-6, 'add oc2') local ocr = oc1:add(oc1, oc2) local der = de1:add(de1, de2) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-6, 'add oc1 and oc2') local fac = torch.uniform(-2, 2) local ocr = oc1:add(fac, oc2) local der = de1:add(fac, de2) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-6, 'add fac oc2') local fac = torch.uniform(-2, 2) local ocr = oc1:add(oc1, fac, oc2) local der = de1:add(de1, fac, de2) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-6, 'add oc1 and fac oc2') local fac1 = torch.uniform(-2, 2) local fac2 = torch.uniform(-2, 2) local ocr = oc1:add(fac1, oc1, fac2, oc2) local der = de1:add(de1:mul(fac1), fac2, de2) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-5, 'add fac oc1 and fac oc2') for _, ip in ipairs{true, false} do local err_str = 'CAddTable' if ip then err_str = err_str..'(ip)' end local cadd_oc = nn.CAddTable(ip):oc() local cadd_de = nn.CAddTable(ip):float() local ocr = cadd_oc:forward({oc1, oc2}) local der = cadd_de:forward({de1, de2}) mytester:assert(torch.abs(todense(ocr) - der):max() < 1e-5, err_str..' forward') local ocr = cadd_oc:backward({oc1, oc2}, oc2) local der = cadd_de:backward({de1, de2}, de2) mytester:assert(torch.abs(todense(ocr[1]) - der[1]):max() < 1e-6, err_str..' backward') mytester:assert(torch.abs(todense(ocr[2]) - der[2]):max() < 1e-6, err_str..' backward') end end for _, n in ipairs{1, 4} do test( test_utils.octree_rand(n, 1,1,1, 1, 0,0,0) ) test( test_utils.octree_rand(n, 2,3,4, 2, 0,0,0) ) test( test_utils.octree_rand(n, 2,3,4, 2, 1,0,0) ) test( test_utils.octree_rand(n, 2,3,4, 2, 1,1,0) ) test( test_utils.octree_rand(n, 2,3,4, 2, 1,1,1) ) test( test_utils.octree_rand(n, 2,3,4, 2, 0.5,0.5,0.5) ) end end function octest.OctreeConcat() local function test(grid_in1) local grid_in2 = grid_in1:clone() grid_in2:resize(grid_in1:n(), grid_in1:grid_depth(), grid_in1:grid_height(), grid_in1:grid_width(), grid_in1:feature_size()*2, grid_in1:n_leafs()) grid_in2:update_prefix_leafs() for didx = 0, grid_in2:n_elems()-1 do grid_in2.grid.data[didx] = didx % 7 end local mod = oc.OctreeConcat(true):float() local grid_out = mod:forward({grid_in1, grid_in2}) local grid_i1 = grid_in1.grid local grid_i2 = grid_in2.grid local grid_o = grid_out.grid for lidx = 0, grid_in1:n_leafs()-1 do for f = 0, grid_in1:feature_size()-1 do local err = math.abs(grid_i1.data[lidx * grid_in1:feature_size() + f] - grid_o.data[lidx * grid_out:feature_size() + f]) mytester:assertlt(err, 1e-6, 'error in OctreeConcat fwd') end for f = 0, grid_in2:feature_size()-1 do local err = math.abs(grid_i2.data[lidx * grid_in2:feature_size() + f] - grid_o.data[lidx * grid_out:feature_size() + grid_in1:feature_size() + f]) mytester:assertlt(err, 1e-6, 'error in OctreeConcat fwd') end end local grid_out = grid_out:clone() local grad_in = mod:backward({grid_in1, grid_in2}, grid_out) local grid_o = grid_out.grid local grid_i1 = grad_in[1].grid local grid_i2 = grad_in[2].grid for lidx = 0, grid_in1:n_leafs()-1 do for f = 0, grid_in1:feature_size()-1 do local err = math.abs(grid_i1.data[lidx * grid_in1:feature_size() + f] - grid_o.data[lidx * grid_out:feature_size() + f]) mytester:assertlt(err, 1e-6, 'error in OctreeConcat bwd') end for f = 0, grid_in2:feature_size()-1 do local err = math.abs(grid_i2.data[lidx * grid_in2:feature_size() + f] - grid_o.data[lidx * grid_out:feature_size() + grid_in1:feature_size() + f]) mytester:assertlt(err, 1e-6, 'error in OctreeConcat bwd') end end end function test_dense(in1, fs2, do_grad_in2) local in2 = torch.zeros(in1:size(1), fs2, in1:size(3), in1:size(4), in1:size(5)) in2:apply(function() torch.uniform(-1,1) end) in2 = in2:float() local o2c = oc.OctreeToCDHW():float() o2c:forward(in1) local c2o = oc.CDHWToOctree(o2c):float() local in2_o = c2o:forward(in2) local mod1 = oc.OctreeConcat(false, do_grad_in2):float() local mod2 = oc.OctreeConcat(false, do_grad_in2):float() local out1 = mod1:forward({in1, in2_o}) local out2 = mod2:forward({in1, in2}) mytester:assert(out1:equals(out2, 1e-6, true), 'error in OctreeConcat(dense) fwd') local test_a = oc.OctreeToCDHW():forward(out2) local test_b = torch.cat(oc.OctreeToCDHW():forward(in1), in2, 2) local err = torch.abs(test_a - test_b):max() mytester:assert(err < 1e-6, 'error in OctreeConcat(dense) fwd test') local grad_out = out1:clone() grad_out:apply(function() torch.uniform(-1,1) end) local out1 = mod1:backward({in1, in2_o}, grad_out) local out2 = mod2:backward({in1, in2}, grad_out) mytester:assert(out1[1]:equals(out2[1], 1e-6, true), 'error in OctreeConcat(dense) bwd1') if do_grad_in2 then local err = torch.abs(o2c:forward(out1[2]) - out2[2]):max() mytester:assertlt(err, 1e-6, 'error in OctreeConcat(dense) bwd2') end local test_a = oc.OctreeToCDHW():forward(out2[1]) local test_b = oc.OctreeToCDHW():forward(grad_out)[{{}, {1,in1:feature_size()}}] local err = torch.abs(test_a - test_b):max() mytester:assert(err < 1e-6, 'error in OctreeConcat(dense) bwd1 test') if do_grad_in2 then local test_a = out2[2] local test_b = oc.OctreeToCDHW():forward(grad_out)[{{}, {in1:feature_size()+1, in1:feature_size()+in2:size(2)}}] local err = torch.abs(test_a - test_b):max() mytester:assert(err < 1e-6, 'error in OctreeConcat(dense) bwd1 test') end end for _, n in ipairs{1, 4} do for fs = 1, 3 do for _, do_grad_in2 in ipairs{true, false} do test( test_utils.octree_rand(n, 1,1,1, fs, 0,0,0) ) test( test_utils.octree_rand(n, 2,3,4, fs, 0,0,0) ) test( test_utils.octree_rand(n, 2,3,4, fs, 1,0,0) ) test( test_utils.octree_rand(n, 2,3,4, fs, 1,1,0) ) test( test_utils.octree_rand(n, 2,3,4, fs, 1,1,1) ) test( test_utils.octree_rand(n, 2,3,4, fs, 0.5,0.5,0.5) ) test_dense( test_utils.octree_rand(n, 1,1,1, fs, 0,0,0), 4, do_grad_in2 ) test_dense( test_utils.octree_rand(n, 2,3,4, fs, 0,0,0), 4, do_grad_in2 ) test_dense( test_utils.octree_rand(n, 2,3,4, fs, 1,0,0), 4, do_grad_in2 ) test_dense( test_utils.octree_rand(n, 2,3,4, fs, 1,1,0), 4, do_grad_in2 ) test_dense( test_utils.octree_rand(n, 2,3,4, fs, 1,1,1), 4, do_grad_in2 ) test_dense( test_utils.octree_rand(n, 2,3,4, fs, 0.5,0.5,0.5), 4, do_grad_in2 ) end end end end function octest.OctreeReLU() local function test(inplace, grid_in) local mod_oc = oc.OctreeReLU(inplace):float() local mod_de = nn.ReLU():float() local out_de = mod_de:forward( oc.OctreeToCDHW():forward(grid_in) ) local out_oc = mod_oc:forward(grid_in) local err = torch.abs(oc.OctreeToCDHW():forward(out_oc) - out_de):max() mytester:assert(err < 1e-6, 'error in OctreeReLU forward') if inplace then mytester:assert(out_oc.grid == grid_in.grid, 'error in OctreeReLU forward') end local grad_out = grid_in:clone():apply(function() return torch.uniform(-1,1) end) local grad_de = mod_de:backward(oc.OctreeToCDHW():forward(grid_in), oc.OctreeToCDHW():forward(grad_out)) local grad_oc = mod_oc:backward(grid_in, grad_out) local err = torch.abs(oc.OctreeToCDHW():forward(out_oc) - out_de):max() mytester:assert(err < 1e-6, 'error in OctreeReLU backward') if inplace then mytester:assert(out_oc.gradInput == grid_in.gradInput, 'error in OctreeReLU backward') end end for _, n in ipairs{1, 4} do for _, inplace in ipairs{false, true} do test(inplace, test_utils.octree_rand(n, 1,1,1, 1, 0,0,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 0,0,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 1,0,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 1,1,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 1,1,1, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 0.5,0.5,0.5, -1,1)) end end end function octest.OctreeSigmoid() local function test(inplace, grid_in) local mod_oc = oc.OctreeSigmoid(inplace):float() local mod_de = nn.Sigmoid():float() local out_de = mod_de:forward( oc.OctreeToCDHW():forward(grid_in) ) local out_oc = mod_oc:forward(grid_in) local err = torch.abs(oc.OctreeToCDHW():forward(out_oc) - out_de):max() mytester:assert(err < 1e-6, 'error in OctreeReLU forward err='..err) if inplace then mytester:assert(out_oc.grid == grid_in.grid, 'error in OctreeReLU forward (ip)') end local grad_out = grid_in:clone():apply(function() return torch.uniform(-1,1) end) local grad_de = mod_de:backward(oc.OctreeToCDHW():forward(grid_in), oc.OctreeToCDHW():forward(grad_out)) local grad_oc = mod_oc:backward(grid_in, grad_out) local err = torch.abs(oc.OctreeToCDHW():forward(out_oc) - out_de):max() mytester:assert(err < 1e-6, 'error in OctreeReLU backward err='..err) if inplace then mytester:assert(out_oc.gradInput == grid_in.gradInput, 'error in OctreeReLU backward (ip)') end end test(true, test_utils.octree_rand(1, 1,1,1, 1, 0,0,0, -1,1)) for _, n in ipairs{1, 4} do for _, inplace in ipairs{false, true} do test(inplace, test_utils.octree_rand(n, 1,1,1, 1, 0,0,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 0,0,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 1,0,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 1,1,0, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 1,1,1, -1,1)) test(inplace, test_utils.octree_rand(n, 2,3,4, 2, 0.5,0.5,0.5, -1,1)) end end end function octest.OctreeLogSoftMax() local function test(in1) local o2d = oc.OctreeToCDHW() local d2o = oc.CDHWToOctree(o2d, 'avg') local dense_mod = nn.LogSoftMax():float() local dense_in = o2d:forward(in1):clone() local dense_size = dense_in:size() local dense_out = dense_mod:forward(dense_in:view(dense_size[1], dense_size[2], dense_size[3]*dense_size[4], dense_size[5])) dense_out = dense_out:view(dense_size) local oc_mod = oc.OctreeLogSoftMax() local oc_out = oc_mod:forward(in1) local oc_out_d = o2d:forward(oc_out) local max_err = torch.abs(dense_out - oc_out_d):max() mytester:assert(max_err < 1e-6, 'error in OctreeLogSoftMax forward') local dense_grad = dense_mod:backward(dense_in, o2d:forward(oc_out):clone()) dense_grad = dense_grad:view(dense_size) local oc_dense_grad = d2o:forward(dense_grad) local oc_grad = oc_mod:backward(in1, oc_out) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-4, true), 'error in OctreeLogSoftMax backward') end for _, n in ipairs{1, 4} do test(test_utils.octree_rand(n, 2,2,2, 3, 0,0,0)) test(test_utils.octree_rand(n, 2,2,2, 3, 1,0,0)) test(test_utils.octree_rand(n, 2,2,2, 3, 1,1,0)) test(test_utils.octree_rand(n, 2,2,2, 3, 1,1,1)) test(test_utils.octree_rand(n, 2,2,2, 3, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 2,4,6, 3, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 4,8,6, 8, 0.5,0.5,0.5)) end end function octest.OctreeSplit() local function bwd(data, struct, grad_out) local o2d = oc.OctreeToCDHW():float() local d2o = oc.CDHWToOctree(o2d, 'avg'):float() local out_cdhw = o2d:forward(data) o2d.received_input = struct local out = d2o:forward(out_cdhw) local grad_d2o = d2o:backward(out_cdhw, grad_out) local grad_in = o2d:backward(data, grad_d2o) return grad_in end local function test_by_prob(prob, data) local threshold = 0 local mod_prob = nn.Identity():float() local mod = oc.OctreeSplitByProb(mod_prob, threshold, true):float() mod_prob:forward(prob) local mod_out = mod:forward(data) -- test structure for grid_idx = 1, prob:n_blocks() do for bit_idx = 1, 73 do local in_bit = prob:tree_isset_bit(grid_idx, bit_idx) local in_pa_bit = prob:tree_isset_bit(grid_idx, prob:tree_parent_bit_idx(bit_idx)) local out_bit = mod_out:tree_isset_bit(grid_idx, bit_idx) local out_pa_bit = mod_out:tree_isset_bit(grid_idx, mod_out:tree_parent_bit_idx(bit_idx)) if in_bit == true then mytester:assert( out_bit == true, 'OctreeSplit: split node in in is not replicated in mod_out' ) end if in_bit == false and (bit_idx == 1 or in_pa_bit == true) then local in_data_idx = prob:tree_data_idx(grid_idx, bit_idx) -- local p = prob.grid.data_ptrs[grid_idx-1][in_data_idx] local p = prob.grid.data[prob.grid.prefix_leafs[grid_idx-1] * prob.grid.feature_size + in_data_idx] if p >= threshold then mytester:assert( out_bit == true, string.format('OctreeSplitByProb: there should be a split because p (%f) > threshold (%f)', p, threshold) ) end end if out_bit == true then mytester:assert(bit_idx == 1 or out_pa_bit == true, ' OctreeSplitByProb: there can not be a split without a parent split') end end end -- test fwd content local oc_out = oc.OctreeToCDHW():forward(mod_out) local de_out = oc.OctreeToCDHW():forward(data) local err = torch.abs(oc_out - de_out):max() mytester:assert(err < 1e-6, 'error in OctreeSplitByProb forward err='..err) local grad_out = mod_out:clone():apply(function() return torch.uniform(-1,1) end) local oc_grad = bwd(data, mod_out, grad_out:clone()) local de_grad = mod:backward(data, grad_out) mytester:assert(oc_grad:equals(de_grad, 1e-4, true), 'error in OctreeSplitByProb backward') end local function test_full(data) local mod = oc.OctreeSplitFull():float() local mod_out = mod:forward(data) -- test structure mytester:assert(mod_out:n_leafs() == mod_out:n_blocks()*512, 'error in OctreeSplitFull struct') -- test fwd content local oc_out = oc.OctreeToCDHW():forward(mod_out) local de_out = oc.OctreeToCDHW():forward(data) local err = torch.abs(oc_out - de_out):max() mytester:assert(err < 1e-6, 'error in OctreeSplitFull forward err='..err) local grad_out = mod_out:clone():apply(function() return torch.uniform(-1,1) end) local oc_grad = bwd(data, mod_out, grad_out:clone()) local de_grad = mod:backward(data, grad_out) mytester:assert(oc_grad:equals(de_grad, 1e-4, true), 'error in OctreeSplitFull backward') end local function test_densesurfrecfres(n, fs, vx_res, band) local features = torch.rand(n, fs, vx_res,vx_res,vx_res):float() local rec = torch.rand(n, 1, vx_res,vx_res,vx_res):float() local rec_mod = nn.Identity() rec_mod:forward(rec) local mod = oc.OctreeDenseSplitSurfFres(rec_mod, 0.95, 1.0, band):float() local out = mod:forward(features) local test_mod = nn.Sequential() :add( oc.CDHWToOctree(mod, 'avg') ) test_mod = test_mod:float() mod.received_input = out local test_out = test_mod:forward(features) -- out = out:float() -- test_out = test_out:float() -- print(features) -- print(rec) -- out:print() -- test_out:print() mytester:assert(out:equals(test_out, 1e-6, true), 'error in OctreeDenseSplitSurfFres forward') local grad_out = out:clone() grad_out:apply(function(x) return math.random() end) -- grad_out = grad_out:float() local out = mod:backward(features, grad_out) local test_out = mod:backward(features, grad_out) -- print(out) -- print(test_out) local err = torch.abs(out - test_out):max() mytester:assert(err < 1e-6, 'error in OctreeDenseSplitSurfFres backward') end for _, band in ipairs{0,1,3} do test_densesurfrecfres(1, 1, 8, band) test_densesurfrecfres(1, 1, 16, band) test_densesurfrecfres(1, 3, 16, band) test_densesurfrecfres(4, 5, 32, band) end for n in ipairs{1, 4} do for _, fs in ipairs{1,3,5} do local data = test_utils.octree_rand(n, 1,1,1, fs, 0,0,0, -1,1) test_by_prob(test_utils.octree_alter_fs(data, 1), data) test_full(data) local data = test_utils.octree_rand(n, 1,1,1, fs, 1,0,0, -1,1) test_by_prob(test_utils.octree_alter_fs(data, 1), data) test_full(data) local data = test_utils.octree_rand(n, 1,1,1, fs, 1,1,0, -1,1) test_by_prob(test_utils.octree_alter_fs(data, 1), data) test_full(data) local data = test_utils.octree_rand(n, 1,1,1, fs, 1,1,1, -1,1) test_by_prob(test_utils.octree_alter_fs(data, 1), data) test_full(data) local data = test_utils.octree_rand(n, 1,1,1, fs, 0.5,0.5,0.5, -1,1) test_by_prob(test_utils.octree_alter_fs(data, 1), data) test_full(data) local data = test_utils.octree_rand(n, 2,3,4, fs, 0.5,0.5,0.5, -1,1) test_by_prob(test_utils.octree_alter_fs(data, 1), data) test_full(data) end end end function octest.OctreeMaskByLabel() local function test(input) local labels = input:clone() labels.grid.feature_size = 1 labels:update_prefix_leafs() local data = torch.FloatTensor(labels:n_leafs() * labels:feature_size()) data:apply(function() return torch.random(1, 3) end) labels:cpy_data(data) local mask_label = 1 local input_d = oc.OctreeToCDHW():forward(input) local labels_d = oc.OctreeToCDHW():forward(labels) local out = input:mask_by_label(labels, mask_label, true) local out_d = oc.OctreeToCDHW():forward(out) for b = 1, input_d:size(1) do for c = 1, input_d:size(2) do for d = 1, input_d:size(3) do for h = 1, input_d:size(4) do for w = 1, input_d:size(5) do local l = labels_d[{b,1,d,h,w}] local i = input_d[{b,c,d,h,w}] local o = out_d[{b,c,d,h,w}] if l == mask_label then mytester:assert(o == 0, 'error in OctreeMaskByLabel') else mytester:assert(o == i, 'error in OctreeMaskByLabel') end end end end end end end for _, n in ipairs{1, 4} do test(test_utils.octree_rand(n, 2,2,2, 3, 0,0,0)) test(test_utils.octree_rand(n, 2,2,2, 3, 1,0,0)) test(test_utils.octree_rand(n, 2,2,2, 3, 1,1,0)) test(test_utils.octree_rand(n, 2,2,2, 3, 1,1,1)) test(test_utils.octree_rand(n, 2,2,2, 3, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 2,4,6, 3, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 4,8,6, 8, 0.5,0.5,0.5)) end end function octest.OctreeMSECriterion() local function test(in1) local in2 = in1:clone() local data = torch.FloatTensor(in2:n_leafs() * in2:feature_size()) data:apply(function() return torch.uniform(-1, 1) end) in2:cpy_data(data) local o2d1 = oc.OctreeToCDHW() local o2d2 = oc.OctreeToCDHW() local d2o = oc.CDHWToOctree(o2d1, 'sum') local dense_crit = nn.MSECriterion(true):float() local dense_out = dense_crit:forward(o2d1:forward(in1), o2d2:forward(in2)) local oc_crit = oc.OctreeMSECriterion(true, true) local oc_out = oc_crit:forward(in1, in2) -- print(dense_out, oc_out, torch.abs(dense_out - oc_out)) mytester:assert(torch.abs(dense_out - oc_out) < 1e-3, 'error in OctreeMSECriterion forward') local dense_grad = dense_crit:backward(o2d1:forward(in1), o2d2:forward(in2)) local oc_dense_grad = d2o:forward(dense_grad) local oc_grad = oc_crit:backward(in1, in2) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-5, true), 'error in OctreeMSECriterion backward') end for _, n in ipairs{1, 4} do test(test_utils.octree_rand(n, 2,2,2, 2, 0,0,0)) test(test_utils.octree_rand(n, 2,2,2, 2, 1,0,0)) test(test_utils.octree_rand(n, 2,2,2, 2, 1,1,0)) test(test_utils.octree_rand(n, 2,2,2, 2, 1,1,1)) test(test_utils.octree_rand(n, 2,2,2, 2, 0.5,0.5,0.5)) test(test_utils.octree_rand(n, 2,4,6, 2, 0.5,0.5,0.5)) end end function octest.OctreeClassNLLCriterion() local function test(in1, weights) local in2 = in1:clone() local data = torch.FloatTensor(in2:n_leafs() * in2:feature_size()) data:apply(function() return torch.random(1, in1:feature_size()) end) in2:cpy_data(data) in2.grid.feature_size = 1 local o2d1 = oc.OctreeToCDHW() local o2d2 = oc.OctreeToCDHW() local d2o = oc.CDHWToOctree(o2d1, 'sum') local dense_crit = nn.SpatialClassNLLCriterion(weights):float() local dense_in = o2d1:forward(in1) local dense_ta = o2d2:forward(in2) local dense_in_size = dense_in:size() local dense_ta_size = dense_ta:size() dense_in = dense_in:view(dense_in_size[1], dense_in_size[2], dense_in_size[3]*dense_in_size[4], dense_in_size[5]) dense_ta = dense_ta:view(dense_ta_size[1], dense_ta_size[3]*dense_ta_size[4], dense_ta_size[5]) local dense_out = dense_crit:forward(dense_in, dense_ta) local oc_crit = oc.OctreeClassNLLCriterion(weights, true) local oc_out = oc_crit:forward(in1, in2) mytester:assert(torch.abs(dense_out - oc_out) < 1e-3, 'error in OctreeClassNLLCriterion forward') local dense_grad = dense_crit:backward(dense_in, dense_ta) local oc_dense_grad = d2o:forward(dense_grad:view(dense_in_size)) local oc_grad = oc_crit:backward(in1, in2) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-5, true), 'error in OctreeClassNLLCriterion backward') end local fs = 8 for _, n in ipairs{1, 4} do for _, weights in ipairs{torch.ones(fs):float(), torch.rand(fs):float()} do test(test_utils.octree_rand(n, 2,2,2, fs, 0,0,0), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 1,0,0), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 1,1,0), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 1,1,1), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 0.5,0.5,0.5), weights) test(test_utils.octree_rand(n, 2,4,6, fs, 0.5,0.5,0.5), weights) test(test_utils.octree_rand(n, 4,8,6, fs, 0.5,0.5,0.5), weights) end end end function octest.OctreeCrossEntropyCriterion() local function test(in1, weights) local in2 = in1:clone() local data = torch.FloatTensor(in2:n_leafs() * in2:feature_size()) data:apply(function() return torch.random(1, in1:feature_size()) end) in2:cpy_data(data) in2.grid.feature_size = 1 local o2d1 = oc.OctreeToCDHW() local o2d2 = oc.OctreeToCDHW() local d2o = oc.CDHWToOctree(o2d1, 'sum') local dense_crit = nn.CrossEntropyCriterion(weights):float() local dense_in = o2d1:forward(in1) local dense_ta = o2d2:forward(in2) dense_in = dense_in:transpose(2,3):transpose(3,4):transpose(4,5):contiguous() -- bcdhw - bdchw - bdhcw - bdhwc local dense_in_size = dense_in:size() dense_in = dense_in:view(dense_in:size(1) * dense_in:size(2) * dense_in:size(3) * dense_in:size(4), dense_in:size(5)) dense_ta = dense_ta:view(dense_ta:size(1) * dense_ta:size(3) * dense_ta:size(4) * dense_ta:size(5)) local dense_out = dense_crit:forward(dense_in, dense_ta) local oc_crit = oc.OctreeCrossEntropyCriterion(weights, true) local oc_out = oc_crit:forward(in1, in2) -- print(dense_out, oc_out, torch.abs(dense_out - oc_out)) mytester:assert(torch.abs(dense_out - oc_out) < 1e-3, 'error in OctreeClassNLLCriterion forward') local dense_grad = dense_crit:backward(dense_in, dense_ta) dense_grad = dense_grad:view(dense_in_size):transpose(4,5):transpose(3,4):transpose(2,3):contiguous() -- bdhwc - bdhcw - bdchw - bcdhw local oc_dense_grad = d2o:forward(dense_grad) local oc_grad = oc_crit:backward(in1, in2) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-5, true), 'error in OctreeClassNLLCriterion backward') end local fs = 8 for _, n in ipairs{1, 4} do for _, weights in ipairs{torch.ones(fs):float(), torch.rand(fs):float()} do test(test_utils.octree_rand(n, 2,2,2, fs, 0,0,0), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 1,0,0), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 1,1,0), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 1,1,1), weights) test(test_utils.octree_rand(n, 2,2,2, fs, 0.5,0.5,0.5), weights) test(test_utils.octree_rand(n, 2,4,6, fs, 0.5,0.5,0.5), weights) end end end function octest.OctreeBCECriterion() local function test_grid_grid(in1) local in2 = in1:clone() local data = torch.FloatTensor(in2:n_leafs() * in2:feature_size()) data:apply(function() return torch.uniform(0, 1) end) in2:cpy_data(data) local o2d1 = nn.Sequential() :add( oc.OctreeToCDHW() ) :float() local o2d2 = oc.OctreeToCDHW() local dense_crit = nn.BCECriterion(nil, true):float() local dense_out = dense_crit:forward(o2d1:forward(in1), o2d2:forward(in2)) local oc_crit = oc.OctreeBCECriterion(true, true) local oc_out = oc_crit:forward(in1, in2) local err = torch.abs(dense_out - oc_out) -- print(dense_out, oc_out, err) mytester:assert(err < 1e-3, 'error in OctreeBCECriterion grid-grid forward: err='..err) local dense_grad = dense_crit:backward(o2d1:forward(in1), o2d2:forward(in2)) local oc_dense_grad = o2d1:backward(in1, dense_grad) local oc_grad = oc_crit:backward(in1, in2) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-4, true), 'error in OctreeBCECriterion grid-grid backward') end local function test_grid_dense(in1) local in2 = torch.FloatTensor(in1:n(), in1:feature_size(), in1:dense_depth(), in1:dense_height(), in1:dense_width()) in2:apply(function() return torch.uniform(0, 1) end) local o2d1 = nn.Sequential() :add( oc.OctreeToCDHW() ) :float() local o2d2 = oc.OctreeToCDHW() local dense_crit = nn.BCECriterion(nil, true):float() local dense_out = dense_crit:forward(o2d1:forward(in1), in2) local oc_crit = oc.OctreeBCECriterion(true, true) local oc_out = oc_crit:forward(in1, in2) local err = torch.abs(dense_out - oc_out) -- print(dense_out, oc_out, err) mytester:assert(err < 1e-3, 'error in OctreeBCECriterion grid-dense forward: err='..err) local dense_grad = dense_crit:backward(o2d1:forward(in1), in2) local oc_dense_grad = o2d1:backward(in1, dense_grad) local oc_grad = oc_crit:backward(in1, in2) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-5, true), 'error in OctreeBCECriterion grid-dense backward') end local function test_grid_grid_ds(in1, in2) local o2d1 = nn.Sequential() :add( oc.OctreeToCDHW() ) :float() local o2d2 = oc.OctreeToCDHW() local dense_crit = nn.BCECriterion(nil, true):float() local dense_out = dense_crit:forward(o2d1:forward(in1), o2d2:forward(in2)) local oc_crit = oc.OctreeBCECriterion(true, true, true) local oc_out = oc_crit:forward(in1, in2) local err = torch.abs(dense_out - oc_out) -- print(dense_out, oc_out, err) mytester:assert(err < 1e-3, 'error in OctreeBCECriterion grid-grid-ds forward: err='..err) local dense_grad = dense_crit:backward(o2d1:forward(in1), o2d2:forward(in2)) local oc_dense_grad = o2d1:backward(in1, dense_grad) local oc_grad = oc_crit:backward(in1, in2) mytester:assert(oc_grad:equals(oc_dense_grad, 1e-5, true), 'error in OctreeBCECriterion grid-grid-ds backward') end local ocrand = test_utils.octree_rand for _, n in ipairs{1, 4} do test_grid_grid(ocrand(n, 1,1,1, 1, 0,0,0)) test_grid_grid(ocrand(n, 2,2,2, 2, 0,0,0)) test_grid_grid(ocrand(n, 2,2,2, 2, 1,0,0)) test_grid_grid(ocrand(n, 2,2,2, 2, 1,1,0)) test_grid_grid(ocrand(n, 2,2,2, 2, 1,1,1)) test_grid_grid(ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_grid(ocrand(n, 2,4,6, 2, 0.5,0.5,0.5)) test_grid_grid(ocrand(n, 4,8,6, 6, 0.5,0.5,0.5)) test_grid_dense(ocrand(n, 1,1,1, 1, 0,0,0)) test_grid_dense(ocrand(n, 2,2,2, 2, 0,0,0)) test_grid_dense(ocrand(n, 2,2,2, 2, 1,0,0)) test_grid_dense(ocrand(n, 2,2,2, 2, 1,1,0)) test_grid_dense(ocrand(n, 2,2,2, 2, 1,1,1)) test_grid_dense(ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_dense(ocrand(n, 2,4,6, 2, 0.5,0.5,0.5)) test_grid_dense(ocrand(n, 4,8,6, 6, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 1,1,1, 1, 0,0,0), ocrand(n, 1,1,1, 1, 0,0,0)) test_grid_grid_ds(ocrand(n, 1,1,1, 1, 0,0,0), ocrand(n, 1,1,1, 1, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 0,0,0), ocrand(n, 2,2,2, 2, 0,0,0)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 0,0,0), ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 1,0,0), ocrand(n, 2,2,2, 2, 1,0,0)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 1,0,0), ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 1,1,0), ocrand(n, 2,2,2, 2, 1,1,0)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 1,1,0), ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 1,1,1), ocrand(n, 2,2,2, 2, 1,1,1)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 1,1,1), ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 2,2,2, 2, 0.5,0.5,0.5), ocrand(n, 2,2,2, 2, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 2,4,6, 2, 0.5,0.5,0.5), ocrand(n, 2,4,6, 2, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 4,8,6, 6, 0.5,0.5,0.5), ocrand(n, 4,8,6, 6, 0.5,0.5,0.5)) test_grid_grid_ds(ocrand(n, 4,8,6, 6, 0.5,0.5,0.5), ocrand(n, 4,8,6, 6, 1,1,1)) end end local seed = os.time() print('seed: '..seed) math.randomseed(seed) torch.manualSeed(seed) mytester:add(octest) -- mytester:run() mytester:run('OctreeBCECriterion')
------------------------------------------------------------------------------------------------------------------------------------------------------------- -- VEAF remote callback functions for DCS World -- By zip (2020) -- -- Features: -- --------- -- * This module offers support for calling script from a web server -- -- Prerequisite: -- ------------ -- * This script requires DCS 2.5.1 or higher and MIST 4.3.74 or higher. -- * It also requires NIOD ! -- * It also requires all the veaf scripts ! -- -- Basic Usage: -- ------------ -- TODO -- ------------------------------------------------------------------------------------------------------------------------------------------------------------- veafRemote = {} ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Global settings. Stores the script constants ------------------------------------------------------------------------------------------------------------------------------------------------------------- --- Identifier. All output in DCS.log will start with this. veafRemote.Id = "REMOTE - " --- Version. veafRemote.Version = "2.1.0" -- trace level, specific to this module veafRemote.Debug = false veafRemote.Trace = false -- if false, SLMOD will not be called for regular commands veafRemote.USE_SLMOD = false -- if false, SLMOD will never be called veafRemote.USE_SLMOD_FOR_SPECIAL_COMMANDS = false veafRemote.SecondsBetweenFlagMonitorChecks = 5 veafRemote.CommandStarter = "_remote" veafRemote.MIN_LEVEL_FOR_MARKER = 10 ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Do not change anything below unless you know what you are doing! ------------------------------------------------------------------------------------------------------------------------------------------------------------- veafRemote.monitoredFlags = {} veafRemote.monitoredCommands = {} veafRemote.maxMonitoredFlag = 27000 veafRemote.remoteUsers = {} ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Utility methods ------------------------------------------------------------------------------------------------------------------------------------------------------------- function veafRemote.logError(message) veaf.logError(veafRemote.Id .. message) end function veafRemote.logWarning(message) veaf.logWarning(veafRemote.Id .. message) end function veafRemote.logInfo(message) veaf.logInfo(veafRemote.Id .. message) end function veafRemote.logDebug(message) if message and veafRemote.Debug then veaf.logDebug(veafRemote.Id .. message) end end function veafRemote.logTrace(message) if message and veafRemote.Trace then veaf.logTrace(veafRemote.Id .. message) end end ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- SLMOD monitoring ------------------------------------------------------------------------------------------------------------------------------------------------------------- function veafRemote.monitorWithSlModSpecialCommand(command, script, requireAdmin, flag, coalition) -- don't schedule because it causes problems with interpreter commands that are being executed too soon -- mist.scheduleFunction(veafRemote._monitorWithSlMod, {command, script, flag, coalition, requireAdmin, true}, timer.getTime()+5) veafRemote._monitorWithSlMod(command, script, flag, coalition, requireAdmin, true) end function veafRemote.monitorWithSlMod(command, script, requireAdmin, flag, coalition) -- don't schedule because it causes problems with interpreter commands that are being executed too soon --mist.scheduleFunction(veafRemote._monitorWithSlMod, {command, script, flag, coalition, requireAdmin, false}, timer.getTime()+5) veafRemote._monitorWithSlMod(command, script, flag, coalition, requireAdmin, false) end function veafRemote._monitorWithSlMod(command, script, flag, coalition, requireAdmin, isSpecialCommand) local actualFlag = flag if not actualFlag then actualFlag = veafRemote.maxMonitoredFlag + 1 veafRemote.maxMonitoredFlag = actualFlag end local actualCoalition = coalition or "all" local actualRequireAdmin = requireAdmin if actualRequireAdmin == nil then actualRequireAdmin = true end local isSpecialCommand = isSpecialCommand if isSpecialCommand == nil then isSpecialCommand = false end veafRemote.logTrace(string.format("setting remote configuration for command=[%s], script=[%s], flag=[%d], requireAdmin=[%s], coalition=[%s]",tostring(command), tostring(script), actualFlag, tostring(actualRequireAdmin), tostring(actualCoalition))) veafRemote.monitoredCommands[command:lower()] = {script=script, requireAdmin=requireAdmin} if veafRemote.USE_SLMOD or (veafRemote.USE_SLMOD_FOR_SPECIAL_COMMANDS and isSpecialCommand) then if slmod then slmod.chat_cmd(command, actualFlag, -1, actualCoalition, actualRequireAdmin) veafRemote.startMonitoringFlag(actualFlag, script) end end end function veafRemote.startMonitoringFlag(flag, scriptToExecute) -- reset the flag trigger.action.setUserFlag(flag, false) veafRemote.monitoredFlags[flag] = scriptToExecute veafRemote._monitorFlags() end function veafRemote._monitorFlags() --veafRemote.logTrace("veafRemote._monitorFlags()") for flag, scriptToExecute in pairs(veafRemote.monitoredFlags) do --veafRemote.logTrace(string.format("veafRemote._monitorFlags() - checking flag %s", flag)) local flagValue = trigger.misc.getUserFlag(flag) --veafRemote.logTrace(string.format("veafRemote._monitorFlags() - flagValue = [%d]", flagValue)) if flagValue > 0 then -- call the script veafRemote.logDebug(string.format("veafRemote._monitorFlags() - flag %s was TRUE", flag)) veafRemote.logDebug(string.format("veafRemote._monitorFlags() - calling lua code [%s]", scriptToExecute)) local result, err = mist.utils.dostring(scriptToExecute) if result then veafRemote.logDebug(string.format("veafRemote._monitorFlags() - lua code was successfully called for flag [%s]", flag)) else veafRemote.logError(string.format("veafRemote._monitorFlags() - error [%s] calling lua code for flag [%s]", err, flag)) end -- reset the flag trigger.action.setUserFlag(flag, false) veafRemote.logDebug(string.format("veafRemote._monitorFlags() - flag [%s] was reset", flag)) else --veafRemote.logTrace(string.format("veafRemote._monitorFlags() - flag %s was FALSE or not set", flag)) end end mist.scheduleFunction(veafRemote._monitorFlags, nil, timer.getTime()+veafRemote.SecondsBetweenFlagMonitorChecks) end ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- NIOD callbacks ------------------------------------------------------------------------------------------------------------------------------------------------------------- function veafRemote.addNiodCallback(name, parameters, code) if niod then veafRemote.logInfo("Adding NIOD function "..name) niod.functions[name] = function(payload) -- start of inline function veafRemote.logDebug(string.format("niod callback [%s] was called with payload %s", veaf.p(name), veaf.p(payload))) local errors = {} -- check mandatory parameters presence for parameterName, parameterData in pairs(parameters) do veafRemote.logTrace(string.format("checking if parameter [%s] is mandatory", veaf.p(parameterName))) if parameterData and parameterData.mandatory then if not (payload and payload[parameterName]) then local text = "missing mandatory parameter "..parameterName veafRemote.logTrace(text) table.insert(errors, text) end end end -- check parameters type if payload then for parameterName, value in pairs(payload) do local parameter = parameters[parameterName] if not parameter then table.insert(errors, "unknown parameter "..parameterName) elseif value and not(type(value) == parameter.type) then local text = string.format("parameter %s should have type %s, has %s ", parameterName, parameter.type, type(value)) veafRemote.logTrace(text) table.insert(errors, text) end end end -- stop on error if #errors > 0 then local errorMessage = "" for _, error in pairs(errors) do errorMessage = errorMessage .. "\n" .. error end veafRemote.logError(string.format("niod callback [%s] was called with incorrect parameters :", veaf.p(name), errorMessage)) return errorMessage else veafRemote.logTrace(string.format("payload = %s", veaf.p(payload))) veafRemote.logTrace(string.format("unpacked payload = %s", veaf.p(veaf.safeUnpack(payload)))) local status, retval = pcall(code,veaf.safeUnpack(payload)) if status then return retval else return "an error occured : "..veaf.p(status) end end end -- of inline function else veafRemote.logError("NIOD is not loaded !") end end function veafRemote.addNiodCommand(name, command) veafRemote.addNiodCallback( name, { parameters={ mandatory=false, type="string"}, x={ mandatory=false, type="number"}, y={ mandatory=false, type="number"}, z={ mandatory=false, type="number"}, silent={ mandatory=false, type="boolean"} }, function(parameters, x, y, z, silent) veaf.logDebug(string.format("niod->command %s (%s, %s, %s, %s, %s)", veaf.p(parameters), veaf.p(x), veaf.p(y), veaf.p(z), veaf.p(silent))) return veafRemote.executeCommand({x=x or 0, y=y or 0, z=z or 0}, command..parameters, 99) end ) end ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- default endpoints list ------------------------------------------------------------------------------------------------------------------------------------------------------------- function veafRemote.buildDefaultList() local TEST = false -- add all the combat missions if veafCombatMission then for _, mission in pairs(veafCombatMission.missionsDict) do local missionName = mission:getName() veafRemote.logTrace(string.format("Adding %s", missionName)) veafRemote.monitorWithSlMod("-veaf start-silent-" .. missionName, [[ veafCombatMission.ActivateMission("]] .. missionName .. [[", true) ]]) veafRemote.monitorWithSlMod("-veaf stop-silent-" .. missionName, [[ veafCombatMission.DesactivateMission("]] .. missionName .. [[", true) ]]) veafRemote.monitorWithSlMod("-veaf start-" .. missionName, [[ veafCombatMission.ActivateMission("]] .. missionName .. [[", false) ]]) veafRemote.monitorWithSlMod("-veaf stop-" .. missionName, [[ veafCombatMission.DesactivateMission("]] .. missionName .. [[", false) ]]) end end -- add all the combat zones if veafCombatZone then for _, zone in pairs(veafCombatZone.zonesDict) do local zoneName = zone:getMissionEditorZoneName() veafRemote.logTrace(string.format("Adding %s", zoneName)) veafRemote.monitorWithSlMod("-veaf start-silent-" .. zoneName, [[ veafCombatZone.ActivateZone("]] .. zoneName .. [[", true) ]]) veafRemote.monitorWithSlMod("-veaf stop-silent-" .. zoneName, [[ veafCombatZone.DesactivateZone("]] .. zoneName .. [[", true) ]]) veafRemote.monitorWithSlMod("-veaf start-" .. zoneName, [[ veafCombatZone.ActivateZone("]] .. zoneName .. [[", false) ]]) veafRemote.monitorWithSlMod("-veaf stop-" .. zoneName, [[ veafCombatZone.DesactivateZone("]] .. zoneName .. [[", false) ]]) end end if TEST then -- test veafRemote.addNiodCallback( "test", { param1S_M={ mandatory=true, type="string"}, param2S={ mandatory=false, type="string"}, param3N={ mandatory=false, type="number"}, param4B={ mandatory=false, type="boolean"}, }, function(param1S_M, param2S, param3N, param4B) local text = string.format("niod.test(%s, %s, %s, %s)", veaf.p(param1S_M), veaf.p(param2S), veaf.p(param3N), veaf.p(param4B)) veafRemote.logDebug(text) trigger.action.outText(text, 15) end ) -- login veafRemote.addNiodCallback( "login", { password={ mandatory=true, type="string"}, timeout={ mandatory=false, type="number"}, silent={ mandatory=false, type="boolean"} }, function(password, timeout, silent) veafRemote.logDebug(string.format("niod.login(%s, %s, %s)",veaf.p(password), veaf.p(timeout),veaf.p(silent))) -- TODO remove password from log if veafSecurity.checkPassword_L1(password) then veafSecurity.authenticate(silent, timeout) return "Mission is unlocked" else return "wrong password" end end ) end end ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- Event handler functions. ------------------------------------------------------------------------------------------------------------------------------------------------------------- --- Function executed when a mark has changed. This happens when text is entered or changed. function veafRemote.onEventMarkChange(eventPos, event) if veafRemote.executeCommand(eventPos, event.text) then -- Delete old mark. veafRemote.logTrace(string.format("Removing mark # %d.", event.idx)) trigger.action.removeMark(event.idx) end end function veafRemote.executeCommand(eventPos, eventText) veafRemote.logDebug(string.format("veafRemote.executeCommand(eventText=[%s])", tostring(eventText))) -- Check if marker has a text and the veafRemote.CommandStarter keyphrase. if eventText ~= nil and eventText:lower():find(veafRemote.CommandStarter) then -- Analyse the mark point text and extract the keywords. local command, password = veafRemote.markTextAnalysis(eventText) if command then -- do the magic return veafRemote.executeRemoteCommand(command, password) end end end --- Extract keywords from mark text. function veafRemote.markTextAnalysis(text) veafRemote.logTrace(string.format("veafRemote.markTextAnalysis(text=[%s])", tostring(text))) if text then -- extract command and password local password, command = text:match(veafRemote.CommandStarter.."#?([^%s]*)%s+(.+)") if command then veafRemote.logTrace(string.format("command = [%s]", command)) return command, password end end return nil end -- execute a command function veafRemote.executeRemoteCommand(command, password) local command = command or "" local password = password or "" veafRemote.logDebug(string.format("veafRemote.executeRemoteCommand([%s])",command)) if not(veafSecurity.checkPassword_L1(password)) then veafRemote.logError(string.format("veafRemote.executeRemoteCommand([%s]) - bad or missing password",command)) trigger.action.outText("Bad or missing password",5) return false end local commandData = veafRemote.monitoredCommands[command:lower()] if commandData then local scriptToExecute = commandData.script veafRemote.logTrace(string.format("found script [%s] for command [%s]", scriptToExecute, command)) local authorized = (not(commandData.requireAdmin)) or (veafSecurity.checkSecurity_L9(password)) if not authorized then return false else local result, err = mist.utils.dostring(scriptToExecute) if result then veafRemote.logDebug(string.format("veafRemote.executeRemoteCommand() - lua code was successfully called for script [%s]", scriptToExecute)) return true else veafRemote.logError(string.format("veafRemote.executeRemoteCommand() - error [%s] calling lua code for script [%s]", err, scriptToExecute)) return false end end else veafRemote.logWarning(string.format("veafRemote.executeRemoteCommand : cannot find command [%s]",command or "")) end return false end -- execute command from the remote interface (see VEAF-server-hook.lua) function veafRemote.executeCommandFromRemote(username, level, unitName, veafModule, command) veafRemote.logDebug(string.format("veafRemote.executeCommandFromRemote([%s], [%s], [%s], [%s], [%s])", veaf.p(username), veaf.p(level), veaf.p(unitName), veaf.p(veafModule), veaf.p(command))) --local _user = veafRemote.getRemoteUser(username) --veafRemote.logTrace(string.format("_user = [%s]",veaf.p(_user))) --if not _user then -- return false --end if not veafModule or not username or not command then return false end local _user = { name = username, level = tonumber(level or "-1")} local _parameters = { _user, username, unitName, command } local _status, _retval local _module = veafModule:lower() if _module == "air" then veafRemote.logDebug(string.format("running veafCombatMission.executeCommandFromRemote")) _status, _retval = pcall(veafCombatMission.executeCommandFromRemote, _parameters) elseif _module == "point" then veafRemote.logDebug(string.format("running veafNamedPoints.executeCommandFromRemote")) _status, _retval = pcall(veafNamedPoints.executeCommandFromRemote, _parameters) elseif _module == "alias" then veafRemote.logDebug(string.format("running veafShortcuts.executeCommandFromRemote")) _status, _retval = pcall(veafShortcuts.executeCommandFromRemote, _parameters) elseif _module == "carrier" then veafRemote.logDebug(string.format("running veafShortcuts.executeCommandFromRemote")) _status, _retval = pcall(veafCarrierOperations.executeCommandFromRemote, _parameters) elseif _module == "secu" then veafRemote.logDebug(string.format("running veafSecurity.executeCommandFromRemote")) _status, _retval = pcall(veafSecurity.executeCommandFromRemote, _parameters) else veafRemote.logError(string.format("Module not found : [%s]", veaf.p(veafModule))) return false end veafRemote.logTrace(string.format("_status = [%s]",veaf.p(_status))) veafRemote.logTrace(string.format("_retval = [%s]",veaf.p(_retval))) if not _status then veafRemote.logError(string.format("Error when [%s] tried running [%s] : %s", veaf.p(_user.name), veaf.p(_code), veaf.p(_retval))) else veafRemote.logInfo(string.format("[%s] ran [%s] : %s", veaf.p(_user.name), veaf.p(_code), veaf.p(_retval))) end return _status end -- register a user from the server function veafRemote.registerUser(username, userpower, ucid) veafRemote.logDebug(string.format("veafRemote.registerUser([%s], [%s], [%s])",veaf.p(username), veaf.p(userpower), veaf.p(ucid))) if not username or not ucid then return false end veafRemote.remoteUsers[username:lower()] = { name = username, level = tonumber(userpower or "-1"), ucid = ucid } end -- return a user from the server table function veafRemote.getRemoteUser(username) veafRemote.logDebug(string.format("veafRemote.getRemoteUser([%s])",veaf.p(username))) veafRemote.logTrace(string.format("veafRemote.remoteUsers = [%s]",veaf.p(veafRemote.remoteUsers))) if not username then return nil end return veafRemote.remoteUsers[username:lower()] end ------------------------------------------------------------------------------------------------------------------------------------------------------------- -- initialisation ------------------------------------------------------------------------------------------------------------------------------------------------------------- function veafRemote.initialize() veafRemote.logInfo("Initializing module") veafRemote.buildDefaultList() veafMarkers.registerEventHandler(veafMarkers.MarkerChange, veafRemote.onEventMarkChange) end veafRemote.logInfo(string.format("Loading version %s", veafRemote.Version))
--Children folder includes includeFile("custom_content/tangible/container/drum/serverobjects.lua") includeFile("custom_content/tangible/container/food/serverobjects.lua") includeFile("custom_content/tangible/container/general/serverobjects.lua") includeFile("custom_content/tangible/container/loot/serverobjects.lua") includeFile("custom_content/tangible/container/vendor/serverobjects.lua")
-- @Author:pandayu -- @Version:1.0 -- @DateTime:2018-09-09 -- @Project:pandaCardServer CardGame -- @Contact: QQ:815099602 local CRank = require "include.rank" local mysql = require "include.mysql" local roleMgr = require "manager.roleMgr" local _M = {} _M.rank_list = {} function _M:init(db_config,rank_config) if self.binit then return end self.db_config = db_config for k,v in pairs(rank_config) do self.rank_list[v.type or k] = CRank:new(k,v.asc) self:init_rank(v.type or k) end self.binit = true end function _M:init_rank(rank_type) local rank = self:get(rank_type) if not rank then return end local con = mysql:new(self.db_config.ip,self.db_config.port,self.db_config.user,self.db_config.pw,self.db_config.db) if not rank:load(con) then for i,id in ipairs(roleMgr:get_all_role_ids()) do local role = roleMgr:get_role(id) if role then local rank_info = role:get_rank_info(rank_type) if rank_info and rank_info.pt and rank_info.pt > 0 then rank:update(rank_info) end end end end con:close() end function _M:append_new_rank(type,asc) if not self.rank_list[type] then self.rank_list[type] = CRank:new(type,asc) self:init_rank(type) end end function _M:del_rank(type) self.rank_list[type] = nil end function _M:get(rank_type) return self.rank_list[rank_type] end function _M:clean() for i,v in pairs(self.rank_list) do if v:clean() then return; end end end function _M:save() local con = mysql:new(self.db_config.ip,self.db_config.port,self.db_config.user,self.db_config.pw,self.db_config.db) for i,v in pairs(self.rank_list) do v:save(con); end con:close() end function _M:append(rank_type,role) local rank = self.rank_list[rank_type] if not rank or not role or not role.get_rank_info then return false end return rank:update(role:get_rank_info(rank_type)) end function _M:remove(rank_type,role_id) local rank = self.rank_list[rank_type] if not rank then return false end return rank:remove(role_id) end function _M:update(rank_type,role) local rank = self.rank_list[rank_type] if not rank or not role or not role.get_rank_info then return false end return rank:update(role:get_rank_info(rank_type)) end return _M
-- Library of common/shared methods local L = Grid2Options.L -- Grid2Options:MakeStatusEnabledOptions() do local ClassesValues = { [''] = L["All Classes"] } for class, translation in pairs(LOCALIZED_CLASS_NAMES_MALE) do ClassesValues[class] = translation end local function StatusSetPlayerClass(status, playerClass) local suspended = status:IsSuspended() status.dbx.playerClass = playerClass~='' and playerClass or nil if suspended ~= status:IsSuspended() then local name = status.name for key, map in pairs(Grid2.db.profile.statusMap) do local indicator = Grid2.indicators[key] if indicator then local priority = map[name] if priority then if suspended then indicator:RegisterStatus(status, priority) else indicator:UnregisterStatus(status) end Grid2Frame:WithAllFrames(indicator, "Update") Grid2Options:RefreshIndicatorOptions(indicator) end end end local group = Grid2Options:GetStatusGroup(status) if suspended then group.order = group.order - 500 group.name = strsub(group.name,11,-3) else group.order = group.order + 500 group.name = string.format('|cFF808080%s|r',group.name) end status:Refresh() end end function Grid2Options:MakeStatusEnabledOptions(status, options, optionParams, headerKey) options.playerClass = { type = "select", width = "full", name = L["Enabled for"], desc = L["Enable the status only if your toon belong to the specified class."], order = 1.5, get = function() return status.dbx.playerClass or '' end, set = function(_,v) StatusSetPlayerClass(status, v) end, values = ClassesValues, } if headerKey~=false then self:MakeHeaderOptions( options, headerKey or "General" ) end end end -- Grid2Options:MakeStatusDeleteOptions() do local function DeleteStatus(info) local status = info.arg.status local category = Grid2Options:GetStatusCategory(status) Grid2.db.profile.statuses[status.name] = nil Grid2:UnregisterStatus(status) Grid2Frame:UpdateIndicators() Grid2Options:DeleteStatusOptions(category, status) Grid2Options:SelectGroup('statuses', category) end function Grid2Options:MakeStatusDeleteOptions(status, options, optionParams) self:MakeHeaderOptions( options, "Delete") options.delete = { type = "execute", order = 500, width = "half", name = L["Delete"], desc = L["Delete this element"], func = DeleteStatus, confirm = function() return "Are you sure you want to delete this status ?" end, disabled = function() return next(status.indicators)~=nil or status:IsSuspended() end, arg = { status = status }, } options.deletemsg = { type = "description", order = 510, fontSize = "small", width = "double", name = L["There are indicators linked to this status or the status is not enabled for this character."], hidden = function() return next(status.indicators)==nil and not status:IsSuspended() end, } end end -- Grid2Options:MakeStatusColorOptions() do local function GetStatusColor(info) local c = info.arg.status.dbx["color"..(info.arg.colorIndex)] return c.r, c.g, c.b, c.a end local function SetStatusColor(info, r, g, b, a) local status = info.arg.status local c = status.dbx["color"..(info.arg.colorIndex)] c.r, c.g, c.b, c.a = r, g, b, a status:UpdateDB() status:UpdateAllUnits() end function Grid2Options:MakeStatusColorOptions(status, options, optionParams) local colorCount = status.dbx.colorCount or 1 local name = L["Color"] local desc = L["Color for %s."]:format(status.name) local width = optionParams and optionParams.width or "half" for i = 1, colorCount do local colorKey = "color" .. i if optionParams and optionParams[colorKey] then name = optionParams[colorKey] elseif colorCount > 1 then name = L["Color %d"]:format(i) end local colorDescKey = "colorDesc" .. i if optionParams and optionParams[colorDescKey] then desc = optionParams[colorDescKey] elseif colorCount > 1 then desc = name end options[optionParams and optionParams.optionKey or colorKey] = { type = "color", order = (10 + i), width = width, name = name, desc = desc, get = GetStatusColor, set = SetStatusColor, hasAlpha = true, arg = {status = status, colorIndex = i }, } end end end -- Grid2Options:MakeStatusColorThresholdOptions() function Grid2Options:MakeStatusColorThresholdOptions(status, options, optionParams) self:MakeStatusColorOptions(status, options, optionParams) self:MakeStatusThresholdOptions(status, options, optionParams, nil, nil, nil, true) end -- Grid2Options:MakeStatusThresholdOptions() function Grid2Options:MakeStatusThresholdOptions(status, options, optionParams, min, max, step, percent) options.threshold = { type = "range", order = 20, name = optionParams and optionParams.threshold or L["Threshold"], desc = optionParams and optionParams.thresholdDesc or L["Threshold at which to activate the status."], min = min or 0, max = max or 1, step = step or 0.01, isPercent = percent or nil, get = function () return status.dbx.threshold end, set = function (_, v) status.dbx.threshold = v status:UpdateAllUnits() end, } end -- Grid2Options:MakeStatusMissingOptions() function Grid2Options:MakeStatusMissingOptions(status, options, optionParams) options.threshold = { type = "toggle", name = L["Show if missing"], desc = L["Display status only if the buff is not active."], order = 110, tristate = false, get = function ()return status.dbx.missing end, set = function (_, v) status.dbx.missing = v or nil status:UpdateDB() status:UpdateAllUnits() end, } end -- Grid2Options:MakeStatusToggleOptions() function Grid2Options:MakeStatusToggleOptions(status, options, optionParams, toggleKey) local name = optionParams and optionParams[toggleKey] or L[toggleKey] or toggleKey options[toggleKey] = { type = "toggle", name = name, tristate = false, width = optionParams and optionParams.width or nil, get = function () return status.dbx[toggleKey] end, set = function (_, v) status.dbx[toggleKey] = v or nil status:UpdateDB() status:UpdateAllUnits() end, } end -- Grid2Options:MakeStatusStandardOptions() Grid2Options.MakeStatusStandardOptions = Grid2Options.MakeStatusColorOptions
-- LibBabble-3.0 is hereby placed in the Public Domain -- Credits: ckknight local LIBBABBLE_MAJOR, LIBBABBLE_MINOR = "LibBabble-3.0", 2 local LibBabble = LibStub:NewLibrary(LIBBABBLE_MAJOR, LIBBABBLE_MINOR) if not LibBabble then return end local data = LibBabble.data or {} for k,v in pairs(LibBabble) do LibBabble[k] = nil end LibBabble.data = data local tablesToDB = {} for namespace, db in pairs(data) do for k,v in pairs(db) do tablesToDB[v] = db end end local function warn(message) local _, ret = pcall(error, message, 3) geterrorhandler()(ret) end local lookup_mt = { __index = function(self, key) local db = tablesToDB[self] local current_key = db.current[key] if current_key then self[key] = current_key return current_key end local base_key = db.base[key] local real_MAJOR_VERSION for k,v in pairs(data) do if v == db then real_MAJOR_VERSION = k break end end if not real_MAJOR_VERSION then real_MAJOR_VERSION = LIBBABBLE_MAJOR end if base_key then warn(("%s: Translation %q not found for locale %q"):format(real_MAJOR_VERSION, key, GetLocale())) rawset(self, key, base_key) return base_key end warn(("%s: Translation %q not found."):format(real_MAJOR_VERSION, key)) rawset(self, key, key) return key end } local function initLookup(module, lookup) local db = tablesToDB[module] for k in pairs(lookup) do lookup[k] = nil end setmetatable(lookup, lookup_mt) tablesToDB[lookup] = db db.lookup = lookup return lookup end local function initReverse(module, reverse) local db = tablesToDB[module] for k in pairs(reverse) do reverse[k] = nil end for k,v in pairs(db.current) do reverse[v] = k end tablesToDB[reverse] = db db.reverse = reverse db.reverseIterators = nil return reverse end local prototype = {} local prototype_mt = {__index = prototype} --[[--------------------------------------------------------------------------- Notes: * If you try to access a nonexistent key, it will warn but allow the code to pass through. Returns: A lookup table for english to localized words. Example: local B = LibStub("LibBabble-Module-3.0") -- where Module is what you want. local BL = B:GetLookupTable() assert(BL["Some english word"] == "Some localized word") DoSomething(BL["Some english word that doesn't exist"]) -- warning! -----------------------------------------------------------------------------]] function prototype:GetLookupTable() local db = tablesToDB[self] local lookup = db.lookup if lookup then return lookup end return initLookup(self, {}) end --[[--------------------------------------------------------------------------- Notes: * If you try to access a nonexistent key, it will return nil. Returns: A lookup table for english to localized words. Example: local B = LibStub("LibBabble-Module-3.0") -- where Module is what you want. local B_has = B:GetUnstrictLookupTable() assert(B_has["Some english word"] == "Some localized word") assert(B_has["Some english word that doesn't exist"] == nil) -----------------------------------------------------------------------------]] function prototype:GetUnstrictLookupTable() local db = tablesToDB[self] return db.current end --[[--------------------------------------------------------------------------- Notes: * If you try to access a nonexistent key, it will return nil. * This is useful for checking if the base (English) table has a key, even if the localized one does not have it registered. Returns: A lookup table for english to localized words. Example: local B = LibStub("LibBabble-Module-3.0") -- where Module is what you want. local B_hasBase = B:GetBaseLookupTable() assert(B_hasBase["Some english word"] == "Some english word") assert(B_hasBase["Some english word that doesn't exist"] == nil) -----------------------------------------------------------------------------]] function prototype:GetBaseLookupTable() local db = tablesToDB[self] return db.base end --[[--------------------------------------------------------------------------- Notes: * If you try to access a nonexistent key, it will return nil. * This will return only one English word that it maps to, if there are more than one to check, see :GetReverseIterator("word") Returns: A lookup table for localized to english words. Example: local B = LibStub("LibBabble-Module-3.0") -- where Module is what you want. local BR = B:GetReverseLookupTable() assert(BR["Some localized word"] == "Some english word") assert(BR["Some localized word that doesn't exist"] == nil) -----------------------------------------------------------------------------]] function prototype:GetReverseLookupTable() local db = tablesToDB[self] local reverse = db.reverse if reverse then return reverse end return initReverse(self, {}) end local blank = {} local weakVal = {__mode='v'} --[[--------------------------------------------------------------------------- Arguments: string - the localized word to chek for. Returns: An iterator to traverse all English words that map to the given key Example: local B = LibStub("LibBabble-Module-3.0") -- where Module is what you want. for word in B:GetReverseIterator("Some localized word") do DoSomething(word) end -----------------------------------------------------------------------------]] function prototype:GetReverseIterator(key) local db = tablesToDB[self] local reverseIterators = db.reverseIterators if not reverseIterators then reverseIterators = setmetatable({}, weakVal) db.reverseIterators = reverseIterators elseif reverseIterators[key] then return pairs(reverseIterators[key]) end local t for k,v in pairs(db.current) do if v == key then if not t then t = {} end t[k] = true end end reverseIterators[key] = t or blank return pairs(reverseIterators[key]) end --[[--------------------------------------------------------------------------- Returns: An iterator to traverse all translations English to localized. Example: local B = LibStub("LibBabble-Module-3.0") -- where Module is what you want. for english, localized in B:Iterate() do DoSomething(english, localized) end -----------------------------------------------------------------------------]] function prototype:Iterate() local db = tablesToDB[self] return pairs(db.current) end -- #NODOC -- modules need to call this to set the base table function prototype:SetBaseTranslations(base) local db = tablesToDB[self] local oldBase = db.base if oldBase then for k in pairs(oldBase) do oldBase[k] = nil end for k, v in pairs(base) do oldBase[k] = v end base = oldBase else db.base = base end for k,v in pairs(base) do if v == true then base[k] = k end end end local function init(module) local db = tablesToDB[module] if db.lookup then initLookup(module, db.lookup) end if db.reverse then initReverse(module, db.reverse) end db.reverseIterators = nil end -- #NODOC -- modules need to call this to set the current table. if current is true, use the base table. function prototype:SetCurrentTranslations(current) local db = tablesToDB[self] if current == true then db.current = db.base else local oldCurrent = db.current if oldCurrent then for k in pairs(oldCurrent) do oldCurrent[k] = nil end for k, v in pairs(current) do oldCurrent[k] = v end current = oldCurrent else db.current = current end end init(self) end for namespace, db in pairs(data) do setmetatable(db.module, prototype_mt) init(db.module) end -- #NODOC -- modules need to call this to create a new namespace. function LibBabble:New(namespace, minor) local module, oldminor = LibStub:NewLibrary(namespace, minor) if not module then return end if not oldminor then local db = { module = module, } data[namespace] = db tablesToDB[module] = db else for k,v in pairs(module) do module[k] = nil end end setmetatable(module, prototype_mt) return module end
hskill = { SKILL_TOKEN = hslk.unit_token, SKILL_LEAP = hslk.unit_token_leap, --leap的token模式,需导入模型:https://github.com/hunzsig-warcraft3/assets-models/blob/master/interface/interface_token.mdx SKILL_BREAK = hslk.skill_break, --table[0.05~0.5] SKILL_SWIM_UNLIMIT = hslk.skill_swim_unlimit, SKILL_INVISIBLE = hslk.skill_invisible, SKILL_AVOID_PLUS = hslk.attr.avoid.add, SKILL_AVOID_MIUNS = hslk.attr.avoid.sub, BUFF_SWIM = string.char2id("BPSE"), BUFF_INVULNERABLE = string.char2id("Avul") } --- 获取原生SLK数据集 ---@param abilityId string|number ---@return table|nil hskill.getSlk = function(abilityId) if (abilityId == nil) then return end if (type(abilityId) == "number") then abilityId = string.id2char(abilityId) end return slk.ability[abilityId] end --- 获取HSLK数据集 ---@param idOrName string|number ---@return table|nil hskill.getHSlk = function(idOrName) if (idOrName == nil) then return end local id = idOrName if (type(idOrName) == "number") then id = string.id2char(idOrName) end if (hslk.i2v.ability[id]) then return hslk.i2v.ability[id] elseif (hslk.n2v.ability[id]) then return hslk.n2v.ability[id] end return nil end --- 获取属性加成,需要注册 ---@param abilityId string|number ---@return table|nil hskill.getAttribute = function(abilityId) if (type(abilityId) == "number") then abilityId = string.id2char(abilityId) end local slk = hslk.i2v.ability[abilityId] if (slk ~= nil) then return slk._attr else return nil end end --- 根据技能名称获取技能ID字符串 ---@param name string ---@return string hskill.n2i = function(name) if (hslk.n2v.ability[name] ~= nil) then return hslk.n2v.ability[name]._id end return nil end --- 附加单位获得技能后的属性 ---@protected hskill.addProperty = function(whichUnit, abilityId) hattribute.caleAttribute(CONST_DAMAGE_SRC.skill, true, whichUnit, hskill.getAttribute(abilityId), 1) hring.insert(whichUnit, abilityId) end --- 削减单位获得技能后的属性 ---@protected hskill.subProperty = function(whichUnit, abilityId) hattribute.caleAttribute(CONST_DAMAGE_SRC.skill, false, whichUnit, hskill.getAttribute(abilityId), 1) hring.remove(whichUnit, abilityId) end --- 添加技能 ---@param whichUnit userdata ---@param abilityId string|number ---@param during number hskill.add = function(whichUnit, abilityId, during) local id = abilityId if (type(abilityId) == "string") then id = string.char2id(id) end if (during == nil or during <= 0) then cj.UnitAddAbility(whichUnit, id) cj.UnitMakeAbilityPermanent(whichUnit, true, id) hskill.addProperty(whichUnit, id) else cj.UnitAddAbility(whichUnit, id) hskill.addProperty(whichUnit, id) htime.setTimeout(during, function(t) htime.delTimer(t) cj.UnitRemoveAbility(whichUnit, id) hskill.subProperty(whichUnit, id) end) end end --- 删除技能 ---@param whichUnit userdata ---@param abilityId string|number ---@param delay number hskill.del = function(whichUnit, abilityId, delay) local id = abilityId if (type(abilityId) == "string") then id = string.char2id(id) end if (delay == nil or delay <= 0) then cj.UnitRemoveAbility(whichUnit, id) hskill.subProperty(whichUnit, id) else cj.UnitRemoveAbility(whichUnit, id) hskill.subProperty(whichUnit, id) htime.setTimeout(delay, function(t) htime.delTimer(t) cj.UnitAddAbility(whichUnit, id) hskill.addProperty(whichUnit, id) end) end end --- 设置技能的永久使用性 ---@param whichUnit userdata ---@param abilityId string|number hskill.forever = function(whichUnit, abilityId) local id = abilityId if (type(abilityId) == "string") then id = string.char2id(id) end cj.UnitMakeAbilityPermanent(whichUnit, true, id) end --- 是否拥有技能 ---@param whichUnit userdata ---@param abilityId string|number hskill.has = function(whichUnit, abilityId) if (whichUnit == nil or abilityId == nil) then return false end local id = abilityId if (type(abilityId) == "string") then id = string.char2id(id) end if (cj.GetUnitAbilityLevel(whichUnit, id) >= 1) then return true end return false end
local LogLevels = { debug = 1, info = 2, warning = 3, error = 4, all = { 1, 2, 3, 4 }, strings = { "debug", "info", "warning", "error" } } local PrintLogStream do local _class_0 local _base_0 = { log = function(self, message, level) if level >= self.min_log_level then return vim.api.nvim_out_write("[vimp] " .. tostring(LogLevels.strings[level]) .. ": " .. tostring(message) .. "\n") end end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function(self) self.min_log_level = LogLevels.warning end, __base = _base_0, __name = "PrintLogStream" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 PrintLogStream = _class_0 end local print_log_stream = PrintLogStream() local log do local _class_0 local _base_0 = { levels = LogLevels, streams = { print_log_stream }, print_log_stream = print_log_stream, log = function(message, level) if message == nil then message = "nil" elseif type(message) ~= 'string' then message = tostring(message) end local _list_0 = log.streams for _index_0 = 1, #_list_0 do local stream = _list_0[_index_0] stream:log(message, level) end end, debug = function(message) return log.log(message, LogLevels.debug) end, info = function(message) return log.log(message, LogLevels.info) end, warning = function(message) return log.log(message, LogLevels.warning) end, error = function(message) return log.log(message, LogLevels.error) end, convert_log_level_string_to_level = function(log_level_str) for i = 1, #LogLevels.strings do if log_level_str == LogLevels.strings[i] then return i end end return error("Invalid log level '" .. tostring(log_level_str) .. "'") end } _base_0.__index = _base_0 _class_0 = setmetatable({ __init = function() end, __base = _base_0, __name = "log" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 log = _class_0 return _class_0 end
--- @class Player Player = setmetatable({}, nil) Player.__index = Player Player.__call = function() return "Player" end function Player.new() local _Player = { } local ped = Ped.new(PlayerPedId()) for k,v in pairs(ped) do print("assigning", k, v) _Player[k] = v end local mt = getmetatable(ped) for k,v in pairs(mt) do if k ~= "__call" and k ~= "__index" and k ~= "new" then print("assigning", k) _Player[k] = v end end return setmetatable(_Player, Player) end Player = Player.new()
local slotRune = { Amulet = "RuneEffectAmulet", Belt = "RuneEffectUpperbody", Boots = "RuneEffectUpperbody", Breast = "RuneEffectUpperbody", Gloves = "RuneEffectUpperbody", Helmet = "RuneEffectUpperbody", Horns = "RuneEffectUpperbody", Leggings = "RuneEffectUpperbody", Overhead = "RuneEffectUpperbody", Ring = "RuneEffectAmulet", Shield = "RuneEffectUpperbody", Weapon = "RuneEffectWeapon", Wings = "RuneEffectUpperbody", } local runeTagDescription = { LX_RUNE_CLEAR_MIND = "Set Clear Minded for 2 turns at the beginning of combat.", LX_RUNE_DARLAN = "When you cast a Geomancy skill, your physical armour is restored by 5% + 1% per Geomancy point.", LX_RUNE_FIRSTBLOOD = "During your turn, the first direct attack will have its damage increased by 25%, but the following attacks will do 20% less damage.", LX_RUNE_STOICISM = "If Walk it Off is active, at the end of your turn you are granted 1 turn of a random status in the following list: Fortified, Magic Shell, Mend Metal, Soothing Cold, Hasted, Clear Minded, Breathing Bubble or Vampiric Hunger.", LX_RUNE_KAMLAN = "When you cast a Hydrosophist skill, your magic armour is restored by 5% + 1% per Hydrosophist point.", } local customRunes = { "LX_LOOT_Rune_Special_Clear_Mind", "LX_LOOT_Rune_Special_Darlan", "LX_LOOT_Rune_Special_FirstBlood", "LX_LOOT_Rune_Special_Stoicism", "LX_LOOT_Rune_Special_Kamlan" } local tooltipRuneSlots = { Rune1 = "RuneEffectWeapon", Rune2 = "RuneEffectUpperbody", Rune3 = "RuneEffectAmulet", } local function GetRunesRestrictions(runes) local boosts = {} for i,rune in pairs(runes) do end end ---@param item EsvItem ---@param tooltip TooltipData local function RuneChangeTooltipsSlot(item, tooltip, ...) local slots = tooltip:GetElements("RuneSlot") for i,slot in pairs(slots) do local statsId = item.Stats.DynamicStats[i+2].BoostName local tag = Ext.GetStat(Ext.GetStat(statsId)[slotRune[item.Stats.Slot]]).Tags if tag ~= "" then slot.Value = runeTagDescription[tag].."\n"..slot.Value end end local effects = tooltip:GetElements("RuneEffect") for i, effect in pairs(effects) do for tooltipSlot,statSlot in pairs(tooltipRuneSlots) do local tag = Ext.GetStat(Ext.GetStat(item.StatsId)[statSlot]).Tags if tag ~= "" then effect[tooltipSlot] = runeTagDescription[tag].."\n"..effect[tooltipSlot] elseif effect[tooltipSlot] == "" then effect[tooltipSlot] = "-" end end end end -- ---@param item EsvItem -- ---@param tooltip TooltipData -- local function RuneChangeTooltipsEffect(item, tooltip, ...) -- Ext.Print(item, tooltip) -- end local function RuneRegisterTooltips() Game.Tooltip.RegisterListener("Item", nil, RuneChangeTooltipsSlot) end Ext.RegisterListener("SessionLoaded", RuneRegisterTooltips)
local config do local _obj_0 = require("lapis.config") config = _obj_0.config end config("development", function() end) return config("production", function() port(80) num_workers(4) lua_code_cache("on") return postgres({ backend = "pgmoon", database = "hello_world", user = "benchmarkdbuser", password = "benchmarkdbpass", host = "DBHOSTNAME" }) end)
-- normally, I would only restrict items belonging to the player's race -- however, in this case I want every race's ships restricted since there's a chance a player might get some motherships from other races (i.e. Defined Roles' capital role) -- unfortunately, the way HWU is set up, a subsystem can appear in multiple races, resulting in a possible conflict -- this is also why there are so many "luaplayer 334" subsystem errors in HW2.log -- -- the AI likely can't play this game mode properly -- RolesNumber = 3 -- the number of different roles (must be the same for all races) RolesCapital = 1 -- affects RU transfer, so set this to a job that can spend RUs. if noone on a team selects this role, then everyone gets this job's benefits RolesResource = 2 -- affects AI resource collection RolesFrigate = 2 -- affects AI demand values RolesCorvette = 3 -- affects AI demand values RolesFighter = 3 -- affects AI demand values -- List of jobtypes and corresponding ship/research/subsystem classes they control. RolesTable = { { name = "capital", label = "Capital/Production", techclasses = { "mothership", "cruiser", "carrier", "destroyer", "noncombat", }, }, { name = "frigate", label = "Frigate/Platform", techclasses = { "frigate", "platform", "resource", }, }, { name = "fighter", label = "Fighter/Corvette", techclasses = { "fighter", "corvette", }, }, }
local M = {} return require("thetto.core.kind").extend(M, "vim.anonymous_autocmd", "file")
local function RoundToNearestInteger( value ) local floor = math.floor(value) if value-floor < 0.5 then return floor else return floor+1 end end local function RenderBar( width, completion, blocks ) local function Block( completion ) return blocks[RoundToNearestInteger((#blocks-1) * completion)+1] end local filled = width*completion local filledFloor = math.floor(filled) local filledCeil = math.ceil(filled) local halfFilled = filled-filledFloor local buffer = {} local filledBlock = Block(1) table.insert(buffer, string.rep(Block(1), filledFloor)) if halfFilled > 0 then table.insert(buffer, Block(halfFilled)) end local emptyBlock = Block(0) table.insert(buffer, string.rep(Block(0), width-filledCeil)) return table.concat(buffer) end local UnicodeBlocks = {' ', '▏', '▎', '▍', '▌', '▋', '▊', '▉', '█'} local function RenderUnicodeBar( width, completion ) return RenderBar(width, completion, UnicodeBlocks) end local SimpleBlocks = {' ', '='} local function RenderSimpleBar( width, completion ) return RenderBar(width, completion, SimpleBlocks) end return {renderUnicodeBar = RenderUnicodeBar, renderSimpleBar = RenderSimpleBar}
local colors = require('colors') local rainbowStripes = require('rainbowStripes') local rectangleEngine = require('rectangleEngine') local resolutionEngine = require('resolutionEngine') local textEngine = require('textEngine') local ui = require('ui') local unscaleF = resolutionEngine.unscaleFloat local function paintLines(color, lines) local separator = textEngine.getTextObject('big', '/') local margin = 22 local separatorLeft = 267 local top = 155 local lineHeight = 70 for i, line in ipairs(lines) do local lineTop = top + (i - 1) * lineHeight local name = textEngine.getTextObject('big', line[1]) local nameLeft = separatorLeft - margin - unscaleF(name:getWidth()) local text = textEngine.getTextObject('big', line[2]) local textLeft = separatorLeft + unscaleF(separator:getWidth()) + margin textEngine.paintTextObject(color, name, nameLeft, lineTop) textEngine.paintTextObject(color, separator, separatorLeft, lineTop) textEngine.paintTextObject(color, text, textLeft, lineTop) end end local screen = ui.screen:extend({ backgroundColor = colors.inverseText, paint = function (self) ui.cursor:clickable() rainbowStripes.stripes:paint() local width, height = resolutionEngine.getUnscaledDimensions() rectangleEngine.paint( colors.textBox, 100, 100, width - 200, height - 200) paintLines(colors.inverseText, self.lines) end, }) return { screen = screen, }
--[[--------------------------------------------------------------------------------- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! !!! IF YOU DO NOT KNOW WHAT YOU ARE DOING, DO NOT TOUCH THIS FILE! IT IS LIKELY !!! !!! THAT YOU DO NOT WANT TO CHANGE SOMETHING IN HERE BUT IN THE CONFIG FOLDER !!! !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Now, that we got that bombshell out of the way, let me explain you this file. All it really does is including/AddCSLuaFile'ing files from the core folders based on their file tag. The load order, in which files are loaded, is important. The file tag stands in front of a file that is to be loaded (eg. 'sv_myscript.lua'). These are the file tags to use: sv_ - for a serversided file sh_ - for a shared file cl_ - for a clientsided file You also can disable certain contributions/plugins by adding the foldername or filename to the specific table here. -----------------------------------------------------------------------------------]] -- Make print really cool function print(...) MsgC(Color(255, 255, 0), ...) -- Need to use ... as the input can be varargs MsgC("\n") -- After ... must not be anything end -- Initializing notice if SERVER then print("[RP] Initializing shared on serverside") else print("[RP] Initializing shared on clientside") end -- GM Info GM.Name = "Roleplay" GM.Author = "Arkten" GM.Email = "n/a" GM.Website = "n/a" GM_FOLDERNAME = GM.FolderName -- Create global tables rp = {} rp.cfg = {} db = {} -- Enable/disable plugins/contributions local USE_PLUGINS = false local USE_CONTRIBUTIONS = false -- Loop through core files/folders and include them local function includeCore(path) local files, folders = file.Find(GM_FOLDERNAME .. "/gamemode/" .. path .. "/*", "LUA") print(Color(255, 0, 0), "\n[RP] Loading " .. path .. "/") for _, v in pairs(files) do if string.sub(v, 1 , 3) == "cl_" or string.sub(v, 1 , 3) == "sh_" or string.sub(v, 1 , 3) == "sv_" then print(Color(0, 255, 0), "[RP] Loading " .. path .. "/" .. v) if SERVER then if string.sub(v, 1, 3) == "cl_" or string.sub(v, 1, 3) == "sh_" then AddCSLuaFile(path .. "/" .. v) end if string.sub(v, 1, 3) == "sv_" or string.sub(v, 1, 3) == "sh_" then include(path .. "/" .. v) end else if string.sub(v, 1, 3) == "cl_" or string.sub(v, 1, 3) == "sh_" then include(path .. "/" .. v) end end end end for _, v in pairs(folders) do if v != "." and v != ".." then includeCore(path .. "/" .. v) end end end -- Load essential gamemode files includeCore("config") includeCore("core") includeCore("libraries") includeCore("metatables") includeCore("commands") includeCore("vgui") includeCore("items") -- Loop through special files/folders and include them local function includeSpecial(path, exceptions, datatable) local files, folders = file.Find(GM_FOLDERNAME .. "/gamemode/" .. path .. "/*", "LUA") print(Color(255, 0, 0), "\n[RP] Loading " .. path .. "/") for _, v in pairs(files) do if (string.sub(v, 1 , 3) == "cl_" or string.sub(v, 1 , 3) == "sh_" or string.sub(v, 1 , 3) == "sv_") and not exceptions[v] then print(Color(0, 255, 0), "[RP] Loading " .. path .. "/" .. v) if SERVER then if string.sub(v, 1, 3) == "cl_" or string.sub(v, 1, 3) == "sh_" then AddCSLuaFile(path .. "/" .. v) end if string.sub(v, 1, 3) == "sv_" or string.sub(v, 1, 3) == "sh_" then include(path .. "/" .. v) end else if string.sub(v, 1, 3) == "cl_" or string.sub(v, 1, 3) == "sh_" then include(path .. "/" .. v) end end end end for _, v in pairs(folders) do if v != "." and v != ".." and not exceptions[v] then table.insert(datatable, v) includeSpecial(path .. "/" .. v, exceptions, datatable) end end end -- Load plugins if enabled if USE_PLUGINS then PLUGINS = {} DISABLED_PLUGINS = {} includeSpecial("plugins", DISABLED_PLUGINS, PLUGINS) -- Needs to be the plugins foldername end -- Load contributions if enabled if USE_CONTRIBUTIONS then CONTRIBUTIONS = {} DISABLED_CONTRIBUTIONS = {} includeSpecial("contributors", DISABLED_CONTRIBUTIONS, CONTRIBUTIONS) -- Needs to be the contributors foldername end
local Butterfly = ... -- Retrieve the ComponentScriptT instance that is responsible for this script. Butterfly.Trafo = Butterfly:GetEntity():GetTransform() Butterfly.ArcCenter = { Butterfly.Trafo:get("Origin") } Butterfly.ArcRadius = 20.0 Butterfly.ArcPos = 0.0 Butterfly.Trafo:InitClientApprox("Origin") Butterfly.Trafo:InitClientApprox("Orientation") -- A bit overkill for tiny butterflies... ;-) -- If still at default (-1), pick a custom model skin. local Model = Butterfly:GetEntity():GetComponent("Model") if Model:get("Skin") == -1 and Model:GetNumSkins() > 0 then Model:set("Skin", Butterfly:GetEntity():GetID() % Model:GetNumSkins()) end function Butterfly:Think(FrameTime) -- Console.Print("Butterfly-Thinking...\n") local RadPerSecond = math.rad(40.0) -- The angular speed on the arc is 40 degrees per second. self.ArcPos = (self.ArcPos + RadPerSecond * FrameTime) % (math.pi * 2.0) self.Trafo:set("Origin", self.ArcCenter[1] + math.sin(self.ArcPos) * self.ArcRadius, self.ArcCenter[2] + math.cos(self.ArcPos) * self.ArcRadius, self.ArcCenter[3] + math.sin(self.ArcPos * 2.0) * self.ArcRadius * 0.2) self.Trafo:SetAngles(-math.deg(self.ArcPos)) end
module(..., package.seeall) function onCreate(params) layer = Layer {scene = scene} mapsprite = MapSprite {texture = "numbers.png", layer = layer, left = 0, top = 0} mapsprite:setMapSize(8, 8, 32, 32) mapsprite:setMapSheets(32, 32, 8, 8) mapsprite:setRows({ {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8}}) end
-- Copyright (C) 2018 The Dota IMBA Development Team -- Copyright (C) 2015 bmddota -- -- 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. -- -- Editors: -- lolle -- Firetoad -- EarthSalamander #42 -- local PlayerResource = CDOTA_PlayerResource PlayerResource.PlayerData = {} -- Initializes a player's data function PlayerResource:InitPlayerData(player_id) self.PlayerData[player_id] = {} self.PlayerData[player_id]["current_deathstreak"] = 0 self.PlayerData[player_id]["has_abandoned_due_to_long_disconnect"] = false self.PlayerData[player_id]["distribute_gold_to_allies"] = false self.PlayerData[player_id]["has_repicked"] = false log.debug("player data set up for player with ID "..player_id) end -- Verifies if this player ID already has player data assigned to it function PlayerResource:IsImbaPlayer(player_id) if self.PlayerData[player_id] then return true else return false end end -- Assigns a hero to a player function PlayerResource:SetPickedHero(player_id, hero_entity) if self:IsImbaPlayer(player_id) then self.PlayerData[player_id].hero = hero_entity self.PlayerData[player_id].hero_name = hero_entity:GetUnitName() log.debug("assigned "..self.PlayerData[player_id].hero_name.." to player with ID "..player_id) end end -- Fetches a player's hero function PlayerResource:GetPickedHero(player_id) if self:IsImbaPlayer(player_id) then return self.PlayerData[player_id].hero end return nil end -- Fetches a player's hero name function PlayerResource:GetPickedHeroName(player_id) if self:IsImbaPlayer(player_id) then return self.PlayerData[player_id].hero_name end return nil end -- Set a player's repick status function PlayerResource:CustomSetHasRepicked(player_id, state) if self:IsImbaPlayer(player_id) then self.PlayerData[player_id]["has_repicked"] = state end end -- Fetch a player's repick state function PlayerResource:CustomGetHasRepicked(player_id) if self:IsImbaPlayer(player_id) then return self.PlayerData[player_id]["has_repicked"] else return false end end -- Set a player's abandonment due to long disconnect status function PlayerResource:SetHasAbandonedDueToLongDisconnect(player_id, state) if self:IsImbaPlayer(player_id) then self.PlayerData[player_id]["has_abandoned_due_to_long_disconnect"] = state log.debug("Set player "..player_id.." 's abandon due to long disconnect state as "..tostring(state)) end end -- Fetch a player's abandonment due to long disconnect status function PlayerResource:GetHasAbandonedDueToLongDisconnect(player_id) if self:IsImbaPlayer(player_id) then return self.PlayerData[player_id]["has_abandoned_due_to_long_disconnect"] else return false end end -- Increase a player's current deathstreak count function PlayerResource:IncrementDeathstreak(player_id) if self:IsImbaPlayer(player_id) then self.PlayerData[player_id]["current_deathstreak"] = self.PlayerData[player_id]["current_deathstreak"] + 1 log.debug("Current deathstreak for player "..player_id..": "..self.PlayerData[player_id]["current_deathstreak"]) end end -- Reset a player's current deathstreak count function PlayerResource:ResetDeathstreak(player_id) if self:IsImbaPlayer(player_id) then self.PlayerData[player_id]["current_deathstreak"] = 0 log.debug("Current deathstreak for player "..player_id.." reset to zero.") end end -- Fetch a player's current deathstreak count function PlayerResource:GetDeathstreak(player_id) if self:IsImbaPlayer(player_id) then return self.PlayerData[player_id]["current_deathstreak"] end return nil end -- While active, redistributes a player's gold to its allies function PlayerResource:StartAbandonGoldRedistribution(player_id) -- Set redistribution as active self.PlayerData[player_id]["distribute_gold_to_allies"] = true log.debug("player "..player_id.." is now redistributing gold to its allies.") -- Fetch this player's team local player_team = self:GetTeam(player_id) local current_gold = self:GetGold(player_id) local current_allies = {} local ally_amount = 0 local custom_gold_bonus = tonumber(CustomNetTables:GetTableValue("game_options", "bounty_multiplier")["1"]) local gold_per_interval = 3 * (custom_gold_bonus / 100 ) / GOLD_TICK_TIME -- Distribute initial gold for id = 0, PlayerResource:GetPlayerCount() -1 do if self:IsImbaPlayer(id) and (not self.PlayerData[id]["distribute_gold_to_allies"]) and self:GetTeam(id) == player_team then current_allies[#current_allies + 1] = id end end -- If there is at least one ally to redirect gold to, do it ally_amount = #current_allies if ally_amount >= 1 and current_gold >= ally_amount then local gold_to_share = current_gold - (current_gold % ally_amount) local gold_per_ally = gold_to_share / ally_amount for _,ally_id in pairs(current_allies) do self:ModifyGold(ally_id, gold_per_ally, false, DOTA_ModifyGold_AbandonedRedistribute) end log.debug("distributed "..gold_to_share.." gold initially ("..gold_per_ally.." per ally)") end -- Update the variables to start the cycle current_gold = current_gold % ally_amount ally_amount = 0 current_allies = {} -- Start the redistribution cycle Timers:CreateTimer(3, function() -- Update gold according to passive gold gain current_gold = current_gold + gold_per_interval -- Update active ally amount for id = 0, PlayerResource:GetPlayerCount() -1 do if self:IsImbaPlayer(id) and (not self.PlayerData[id]["distribute_gold_to_allies"]) and self:GetTeam(id) == player_team then current_allies[#current_allies + 1] = id end end -- If there is at least one ally to redirect gold to, do it ally_amount = #current_allies if ally_amount >= 1 and current_gold >= ally_amount then local gold_to_share = current_gold - (current_gold % ally_amount) local gold_per_ally = gold_to_share / ally_amount for _,ally_id in pairs(current_allies) do self:ModifyGold(ally_id, gold_per_ally, false, DOTA_ModifyGold_AbandonedRedistribute) end log.debug("distributed "..gold_to_share.." gold ("..gold_per_ally.." per ally)") end -- Update variables current_gold = current_gold % ally_amount current_allies = {} ally_amount = 0 -- Keep going, if applicable if self.PlayerData[player_id]["distribute_gold_to_allies"] then return 3 end end) end -- Stops a specific player from redistributing their gold to its allies function PlayerResource:StopAbandonGoldRedistribution(player_id) self.PlayerData[player_id]["distribute_gold_to_allies"] = false self:ModifyGold(player_id, -self:GetGold(player_id), false, DOTA_ModifyGold_AbandonedRedistribute) log.debug("player "..player_id.." is no longer redistributing gold to its allies.") end
return function() local ChangedSignalModule = require(script.Parent.EventModule) describe("new", function() it("should construct from nothing", function() local Table = ChangedSignalModule.new() expect(Table).to.be.ok() end) it("should construct from something", function() local Table = ChangedSignalModule.new({a = 1}) expect(Table.a).to.equal(1) end) it("should turn all newly assigned tables into objects", function() local Table = ChangedSignalModule.new() Table.a = {} expect(Table.a.mutated).never.to.equal(nil) end) it("Inserted EventModule Objects should work, Add .Parent if previoustly nil", function() local Table = ChangedSignalModule.new() local Table2 = ChangedSignalModule.new() Table3 = ChangedSignalModule.new({ b = {} }) Table.a = Table2 expect(Table.a).to.equal(Table2) expect(Table2.Parent).to.equal(Table) Table.b = Table3.b expect(Table.b).to.equal(Table3.b) expect(Table3.b.Parent).never.to.equal(Table) end) end) describe("mutated Event", function() it("should fire connected mutated events upon mutation", function() local Table = ChangedSignalModule.new({a = 1, b = {}}) local callCount = 0 local callback = function(oldTable, newTable) expect(oldTable).never.to.equal(nil) expect(newTable).never.to.equal(nil) callCount = callCount + 1 end Table.mutated:Connect(callback) Table.a = 2 expect(callCount).to.equal(1) Table.c = 3 expect(callCount).to.equal(2) Table.b[1] = "HELLO" expect(callCount).to.equal(3) end) it("should only fire when a property is changed", function() local Table = ChangedSignalModule.new({a = 1}) local callCount = 0 Table.mutated:Connect(function(oldTable, newTable) callCount = callCount + 1 end) Table.a = 1 wait(1) expect(callCount).to.equal(0) end) it("should pass an independant oldTable and self object as newTable", function() local Table = ChangedSignalModule.new() local callCount = 0 Table.mutated:Connect(function(oldTable, newTable) callCount = callCount + 1 wait() newTable.a = 2 wait() expect(newTable.a).to.equal(Table.a) expect(callCount).never.to.equal(1) expect(oldTable.a).never.to.equal(2) end) Table.a = 1 end) it("should be available on nested tables too", function() local Table = ChangedSignalModule.new({a = {}}) local callCount = 0 Table.a.mutated:Connect(function(oldTable, newTable) callCount = callCount + 1 end) -- Should fire when mutated Table.a[1] = 1 expect(callCount).to.equal(1) -- Should not fire when parent table mutates Table.b = 2 expect(callCount).to.equal(1) end) it("newTable and oldTable should be from the hiarchy perspective of the listening Object", function() local Table = ChangedSignalModule.new({a = {1}}) Table.mutated:Connect(function(oldTable, newTable) expect(newTable).to.equal(Table) expect(newTable.a[1]).to.equal(2) expect(oldTable.a[1]).to.equal(1) end) Table.a.mutated:Connect(function(oldTable, newTable) expect(newTable).to.equal(Table.a) expect(newTable[1]).to.equal(2) expect(oldTable[1]).to.equal(1) end) Table.a[1] = 2 end) end) describe("Cleanup", function() it("self:Disconnect(), self:DisconnectDescendants(), self:DisconnectAllParents() should disconnect signals accordingly", function() local Table = ChangedSignalModule.new({ a = { b = {} } }) local callCount = 0 Table.mutated:Connect(function() callCount = callCount + 1 end) Table.a.mutated:Connect(function() callCount = callCount + 1 end) Table.a.b.mutated:Connect(function() callCount = callCount + 1 end) -- self:DisconnectDescendants() should disconnnect all descendant object's events Table.a:DisconnectDescendants() Table.a.b[1] = true -- +2 expect(callCount).to.equal(2) callCount = 0 -- self:Disconnect() should disconnect all of the objects events Table.a:Disconnect() Table.a[1] = true -- +1 expect(callCount).to.equal(1) callCount = 0 -- self:DisconnectAllParents() should disconnnect all of the object's parants events Table.a:DisconnectAllParents() Table[1] = true -- +0 expect(callCount).to.equal(0) callCount = 0 end) it("self:Destroy() should disconnect all events, and return properties in normal table form", function() local Table = ChangedSignalModule.new({a = {}, b = 2}) local callCount = 0 Table.mutated:Connect(function() callCount = callCount + 1 end) Table = Table:Destroy() -- should return table expect(Table).to.be.a("table") -- Values should remain expect(Table.b).to.equal(2) -- should no longer include object properties expect(Table.mutated).to.equal(nil) expect(Table.properties).to.equal(nil) expect(Table.events).to.equal(nil) -- Descendant tables should also no longer include object properties expect(Table.a.mutated).to.equal(nil) expect(Table.a.properties).to.equal(nil) expect(Table.a.events).to.equal(nil) end) it("should disconnect events and deschendantEvents when object is no longer indexed", function() local Table = ChangedSignalModule.new({ a = { b = {} } }) local callCount = 0 Table.a.mutated:Connect(function() callCount = callCount + 1 end) Table.a.b.mutated:Connect(function() callCount = callCount + 1 end) local ref = Table.a.b -- un-Indexing Table.a object Table.a = 1 ref[1] = true expect(callCount).to.equal(0) end) end) describe("GetPropertyChangedSignal", function() it("should provide a signal that fires on a specific properties change, creation or removal", function() local Table = ChangedSignalModule.new({a = 1}) local callCount = 0 Table:GetPropertyChangedSignal("a"):Connect(function(oldVal, newVal) expect(oldVal).never.to.equal(newVal) callCount = callCount + 1 end) Table:GetPropertyChangedSignal("b"):Connect(function() callCount = callCount + 1 end) Table.a = 2 expect(callCount).to.equal(1) Table.b = true expect(callCount).to.equal(2) Table.a = nil expect(callCount).to.equal(3) end) end) describe(":GetProperties()", function() it("should return raw table copy of the object's properties, accounting for nested tables too", function() local Table = ChangedSignalModule.new({1,2,3, a = {4,5,6}}) local properties = Table:GetProperties() -- expect Raw tables expect(properties.mutated).to.equal(nil) expect(properties.a.mutated).to.equal(nil) -- properties stay the same expect(properties[1]).to.equal(Table[1]) --Event nested once expect(properties.a[1]).to.equal(Table.a[1]) end) end) describe("Looping", function() it("Object loopable with self:pairs() and self:ipairs()", function() local Table = ChangedSignalModule.new({1,2,3, a = {4,5,6}}) local callCount = 0 Table.a.Mutated:Connect(function() callCount = callCount + 1 end) expect(function() --ipairs should loop numarically for i,v in Table:ipairs() do expect(i).to.equal(v) end --loop should return nested tables as objects for i,v in Table:pairs() do if typeof(v) == "table" then -- Object values need to be available expect(v[1]).to.equal(4) --Parent Object exists expect(v.Parent).to.equal(Table) -- mutations fires event v[1] = true expect(callCount).to.equal(1) --Parent object should not excist when looping through nested Tables for k,t in Table.a:pairs() do expect(k).never.to.equal("Parent") end end end end).never.to.throw() end) end) describe(":len()", function() it("should return the length of the table", function() local Table = ChangedSignalModule.new({1,2,3, a = {4,5}}) expect(Table:len()).to.equal(3) expect(Table.a:len()).to.equal(2) end) end) describe(":insert()", function() it("should insert value at end of list if pos not passed", function() local Table = ChangedSignalModule.new({1,2,3}) Table:insert(10) expect(Table[4]).to.equal(10) end) it("should push previous values uppward in array to clear space for specified insert position", function() local Table = ChangedSignalModule.new({1,3,4}) Table:insert(2, 2) local expectedTable = {1,2,3,4} for i,v in Table:pairs() do expect(v).to.equal(expectedTable[i]) end end) it("should only fire .mutated event once when value inserted into middle of array (not for every pushing action)", function() local t = ChangedSignalModule.new({"a", "c", "d"}) local callCount = 0 t.mutated:Connect(function(old, new) callCount += 1 end) t:insert("b", 2) print(callCount, " INSERT CALLCOUNT") expect(callCount).to.equal(1) end) end) describe(":find()", function() it("should return index of value if found, with respect to init index", function() local Table = ChangedSignalModule.new({1,2,3,2,1}) -- unspesified init expect(Table:find(2)).to.equal(2) -- specified init expect(Table:find(2, 4)).to.equal(4) end) end) describe(":remove()", function() it("should collapse values above the removed value down to fill the gap", function() local Table = ChangedSignalModule.new({1,2,2,3}) Table:remove(2) local expectedTable = {1,2,3} for i,v in Table:pairs() do expect(v).to.equal(expectedTable[i]) end end) it("should only fire .mutated event once when value removing val from middle of array (not for every filling action)", function() local t = ChangedSignalModule.new({"a", "b", "c", "d"}) local callCount = 0 t.mutated:Connect(function(old, new) callCount += 1 end) t:remove(2) print(callCount, " REMOVE CALLCOUNT") expect(callCount).to.equal(1) end) end) end
--[[ Copyright (c) 2018-2021 The Forge Interactive Inc. ]]-- local TEXTURE_RESOLUTION = "2K" local groundTextures = { "PBR/snow_white_tiles_02/" .. TEXTURE_RESOLUTION .. "/Albedo", "PBR/snow_white_tiles_02/" .. TEXTURE_RESOLUTION .. "/Normal", "PBR/Metallic_off", "PBR/snow_white_tiles_02/" .. TEXTURE_RESOLUTION .. "/Roughness2", "PBR/snow_white_tiles_02/" .. TEXTURE_RESOLUTION .. "/AO" } loader.LoadTextureMaps(groundTextures)
_G.biosVersion = 1 _G.biosVersionString = "1.0" --- Default Functions to ONLY use here local fsopen = fs.open local ioopen = io.open local fsronly = fs.isReadOnly local fsmv = fs.move local fsexists = fs.exists local fslist = fs.list local fsdel = fs.delete --- Restoreables (will be set on unlock to allow re-locking) local LOCKfsopen = nil local LOCKioopen = nil local LOCKfsronly = nil local LOCKfsmv = nil local LOCKfsexists = nil local LOCKfslist = nil local LOCKfsdel = nil --- Bios config Entries local biosPassword = "0000" local defaultBootEntry = 0 local bootEntries = "CRAFTOS,/startup_os,/disk/os,/disk/startup" function BIOSunlockRoot(passwd) if passwd == biosPassword then if LOCKfsdel == nil or LOCKioopen == nil or LOCKfsronly == nil or LOCKfsmv == nil or LOCKfsexists == nil or LOCKfslist == nil or LOCKfsopen == nil then LOCKfsopen = fs.open LOCKfslist = fs.list LOCKfsdel = fs.delete LOCKfsexists = fs.exists LOCKfsmv = fs.move LOCKioopen = io.open LOCKfsronly = io.isReadOnly fs.open = fsopen fs.list = fslist fs.delete = fsdel fs.exists = fsexists fs.move = fsmv io.open = ioopen fs.isReadOnly = fsronly else error("BIOS is already unlocked!", 2) end end end function BIOSlockRoot() if LOCKfsdel == nil or LOCKioopen == nil or LOCKfsronly == nil or LOCKfsmv == nil or LOCKfsexists == nil or LOCKfslist == nil or LOCKfsopen == nil then error("BIOS is already locked!", 2) else fs.open = LOCKfsopen fs.list = LOCKfslist fs.delete = LOCKfsdel fs.exists = LOCKfsexists fs.move = LOCKfsmv io.open = LOCKioopen fs.isReadOnly = LOCKfsronly LOCKfsopen = nil LOCKfslist = nil LOCKfsdel = nil LOCKfsexists = nil LOCKfsmv = nil LOCKioopen = nil LOCKfsronly = nil end end --- Settings File API used to parse and interpret and save settings files. --- Entirely created by bwhodle --- Forum post: http://www.computercraft.info/forums2/index.php?/topic/14311-preferences-settings-configuration-store-them-all-settings-file-api/ --- Modified to write to protected files local function trimComments(line) local commentstart = string.len(line) for i = 1, string.len(line) do if string.byte(line, i) == string.byte(";") then commentstart = i - 1 break end end return string.sub(line, 0, commentstart) end local function split(line) local equalssign = nil for i = 1, string.len(line) do if string.byte(line, i) == string.byte("=") or string.byte(line, i) == string.byte(":") then equalssign = i - 1 end end if equalssign == nil then return nil, nil end return string.sub(line, 1, equalssign - 1), string.sub(line, equalssign + 2) end local function Trim(s) return (s:gsub("^%s*(.-)%s*$", "%1")) end local function RemoveQuotes(s) if string.byte(s, 1) == string.byte("\"") and string.byte(s, string.len(s)) == string.byte("\"") then return string.sub(s, 2, -2) end return s end local function openSettingsFile(path) --print("Attempted to load settings file at "..path) local settings = {} local currentsection = {} local currentsectionname = nil local file = fsopen(path, "r") local lines = true settings["content"] = {} while lines do local currentline = file.readLine() if currentline == nil then lines = false break end currentline = trimComments(currentline) if Trim(currentline) ~= "" then if string.byte(currentline, 1) == string.byte("[") then if currentsectionname ~= nil then settings["content"][currentsectionname] = currentsection currentsection = {} elseif currentsectionname == nil then settings["content"][1] = currentsection currentsection = {} end currentsectionname = string.sub(currentline, 2, -2) else local key, value = split(currentline) if Trim(key) ~= nil and Trim(value) ~= nil then local x = Trim(value) if tonumber(x) then x = tonumber(x) else x = RemoveQuotes(x) end if x ~= nil and tostring(Trim(key)) ~= nil then currentsection[Trim(key)] = x end end end end end if currentsectionname ~= nil then settings["content"][currentsectionname] = currentsection currentsection = {} elseif currentsectionname == nil then settings["content"][1] = currentsection currentsection = {} end function settings.addSection(name) settings["content"][name] = {} end function settings.getValue(key) local x = settings["content"][1] return x[key] end function settings.getSectionedValue(section, key) return settings["content"][section][key] end function settings.setValue(key, value) settings["content"][1][key] = value end function settings.setSectionedValue(section, key, value) settings["content"][section][key] = value end function settings.save(path) local file = fsopen(path, "w") local d = settings["content"][1] if d ~= nil then for k, v in pairs(d) do local x = v if string.byte(v, 1) == string.byte(" ") or string.byte(v, string.len(v)) == string.byte(" ") then x = "\"" .. v .. "\"" end file.writeLine(k .. " = " .. x) end end for k, v in pairs(settings["content"]) do if k ~= 1 then file.writeLine("") file.writeLine("[" .. k .. "]") for j, l in pairs(v) do local x = l if string.byte(l, 1) == string.byte(" ") or string.byte(l, string.len(l)) == string.byte(" ") then x = "\"" .. l .. "\"" end file.writeLine(j .. " = " .. x) end end end file.close() end return settings end -------- Replacement of default calls and adding new ones local function getAttribute(file, attr) local setfile = "" if file == nil or file == "" or attr == nil or attr == "" then return false end if fs.isDir(file) then setfile = file .. "/attrib.cfg" else setfile = file .. ".attrib.cfg" end if fsexists(setfile) and setfile ~= "" and fs.isDir(setfile) == false then local s = openSettingsFile(setfile) local att = s.getValue(attr, 0) else return false end if att == nil then return false end if att > 0 then return true else return false end end local function getAttribPath(file) local attribpath = "" if fs.isDir(file) then attribpath = file .. "/attrib.cfg" else attribpath = file .. ".attrib.cfg" end return attribpath end function setAttribute(file, attr, val) if file == nil or file == "" or attr == nil or attr == "" then return end local setfile = getAttribPath(file) if fsexists(setfile) == false then local file = fsopen(setfile, "w") file.close() end local s = openSettingsFile(setfile) local att = s.setValue(attr, val) s.save(setfile) end function fs.open(file, mode) if (fs.getName(file) == "startup" and fs.getDir(file) == "") then file = "startup_os" end if fs.isSystem(file) then return {} end return fsopen(file, mode) end function io.open(file, mode) if (fs.getName(file) == "startup" and fs.getDir(file) == "") then file = "startup_os" end if fs.isSystem(file) then return {} end return ioopen(file, mode) end function fs.isHidden(file) if getAttribute(file, "hidden") then return true end if fs.isSystem(file) then return true end return false end function fs.isSystem(file) if getAttribute(file, "system") then return true end if fs.getName(file) == "attrib.cfg" or string.find(file, ".attrib.cfg") or (fs.getName(file) == "startup" and fs.getDir(file) == "") or (fs.getName(file) == "bios.cfg" and fs.getDir(file) == "") then return true end if fs.getDir(file) ~= "" then return fs.isSystem(fs.getDir(file)) end return false end function fs.list(dir) return fs.list(dir, false) end function fs.list(dir, showHidden) local rawlist = fslist(dir) local newlist = {} for k, v in pairs(rawlist) do if fs.isSystem(dir .. "/" .. v) == false or (showHidden and fs.isHidden(dir .. "/" .. v)) == false then table.insert(newlist, v) end end return newlist end function fs.isReadOnly(file) if (fs.getName(file) == "startup" and fs.getDir(file) == "") then file = "startup_os" end if fsronly(file) then return true else if getAttribute(file, "read-only") then return true end end if fs.isSystem(file) then return true end if fs.getDir(file) ~= "" then return fs.isReadOnly(fs.getDir(file)) end return false end function fs.exists(file) if (fs.getName(file) == "startup" and fs.getDir(file) == "") then file = "startup_os" end if getAttribute(file, "system") or fs.getName(file) == "attrib.cfg" or (fs.getName(file) == "startup" and fs.getDir(file) == "") or string.find(file, ".attrib.cfg") then return false end return fsexists(file) end function fs.move(src, dst) if (fs.getName(src) == "startup" and fs.getDir(src) == "") then src = "startup_os" elseif (fs.getName(dst) == "startup" and fs.getDir(dst) == "") then src = "startup_os" end if fs.isReadOnly(src) then error("Source is read only", 2) end if fs.isReadOnly(dst) then error("Destination is read-only", 2) end fsmv(src, dst) if fsexists(getAttribPath(src)) then fsmv(getAttribPath(src), getAttribPath(dst)) end end function fs.delete(file) if (fs.getName(file) == "startup" and fs.getDir(file) == "") then file = "startup_os" end if not fs.isReadOnly(file) then fsdel(file) end end function fs.download(url, file) local attempts = 0 while attempts < 10 do local conn = http.get(url) if conn then local handler = io.open(file, "w") handler:write(conn.readAll()) handler:close() return true else attempts = attempts + 1 end end end local function fsdownload(url, file) local attempts = 0 while attempts < 10 do local conn = http.get(url) if conn then local handler = ioopen(file, "w") handler:write(conn.readAll()) handler:close() return true else attempts = attempts + 1 end end end function shell.runURL(url) if (fsexists("/tmp")) then fsdel("/tmp") end fsdownload(url, "/tmp") shell.run("/tmp") fsdel("/tmp") end -- Util functions function string.split(inputstr, sep) if sep == nil then sep = "%s" end local t = {} for str in string.gmatch(inputstr, "([^" .. sep .. "]+)") do table.insert(t, str) end return t end --- Boot script for configs and such -- Prevent disk/startup being run on newer CC versions local function preventDiskStartup() settings.set("shell.allow_disk_startup", false) end local function biosError(ms) term.setBackgroundColor(colors.blue) term.clear() term.setCursorPos(11, 5) term.setBackgroundColor(colors.white) term.setTextColor(colors.blue) print(" Looks like an Error occured...") term.setBackgroundColor(colors.blue) term.setTextColor(colors.white) term.setCursorPos(14, 8) print("For more information, see") term.setCursorPos(15, 9) print("the below error message") term.setCursorPos(5, 12) local s, msg = pcall(function() error(ms, 4) end) printError(msg) term.setCursorPos(13, 14) term.setBackgroundColor(colors.white) term.setTextColor(colors.blue) pcall(function() term.setCursorBlink(false) print(" Press any key to shutdown") os.pullEvent("key") os.shutdown() end) end --- On Boot term.clear() term.setCursorPos(1, 1) pcall(preventDiskStartup) -- Load BIOS Config or create new one local isnew = false if not fsexists("/bios.cfg") then local tmpfile = fsopen("/bios.cfg", "w") tmpfile.close() end if not fsexists("/bios.cfg") then biosError("Fatal Boot Error!\nCould not create new BIOS configuration") end local sett = openSettingsFile("/bios.cfg") if not isnew then -- Check if config is older and update it if it is if sett.getValue("version") == nil or sett.getValue("version") < biosVersion then isnew = true end -- Load config if sett.getValue("bios-passwd") ~= nil then biosPassword = sett.getValue("bios-passwd") end if sett.getValue("default-boot-entry") ~= nil then defaultBootEntry = sett.getValue("default-boot-entry") end if sett.getValue("boot-entries") ~= nil then bootEntries = sett.getValue("boot-entries") end end --Write default or updated values to config if isnew then sett.setValue("bios-passwd", biosPassword) sett.setValue("default-boot-entry", defaultBootEntry) sett.setValue("boot-entries", bootEntries) sett.setValue("version", biosVersion) sett.save("/bios.cfg") -- Load config again in case it was not already loaded biosPassword = sett.getValue("biosPasswd") defaultBootEntry = sett.getValue("default-boot-entry") bootEntries = sett.getValue("boot-entries") end -- Check if an update disk is inserted and run BIOS update if it does if fsexists("/disk/bios.bin") then print("Update disk detected!") print("Enter BIOS password to install the update") write("> ") local pwd = read("*") if pwd == biosPassword then print("Installing update from disk. DO NOT REMOVE DISK!") BIOSunlockRoot(pwd) fs.move("/disk/bios.bin", "/startup") fs.delete("/disk/startup") fs.delete(getAttribPath("/disk/bios.bin")) fs.move("/disk/startupOS", "/disk/startup") print("Installation successful, rebooting") BIOSlockRoot() sleep(2) os.reboot() else print("Invalid Password.") sleep(2) os.reboot() end sleep(3) end local bootoptions = string.split(bootEntries, ",") if defaultBootEntry > #bootoptions or defaultBootEntry < 0 then defaultBootEntry = 0 end print("Boot options:") for k, entry in pairs(bootoptions) do if i == defaultBootEntry then write("->") end print(entry) end sleep(5) term.clear() term.setCursorPos(1, 1) if bootoptions[defaultBootEntry + 1] == "CRAFTOS" then shell.run("shell") sleep(4) biosError("OS did not shut down") else if fs.exists(bootoptions[defaultBootEntry + 1]) then shell.run(bootoptions[defaultBootEntry + 1]) sleep(4) biosError("OS did not shut down") end for k, entry in pairs(bootoptions) do if k ~= defaultBootEntry + 1 then if entry == "CRAFTOS" then shell.run("shell") sleep(4) biosError("OS did not shut down") end if fs.exists(entry) then shell.run(entry) sleep(4) biosError("OS did not shut down") end end end end biosError("No bootable device/file found!")
--------------------------------------------------------------------------------------------- -- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/1912 -- Description -- SDL must respond NACK in case navigation app connected over protocol v2 sends StartService for audio service -- Preconditions -- SDL and HMI are started. -- Steps to reproduce -- navigation app connects over protocol v2 and this app sends StartService for audio service -- Actual result -- N/A -- Expected result -- SDL must respond StartService_NACK to this app --------------------------------------------------------------------------------------------- --[[ Required Shared libraries ]] local runner = require("user_modules/script_runner") local constants = require('protocol_handler/ford_protocol_constants') local commonDefects = require('test_scripts/Defects/4_5/commonDefects') local events = require('events') --[[ General configuration parameters ]] config.defaultProtocolVersion = 2 config.application1.registerAppInterfaceParams.appHMIType = {"NAVIGATION"} --[[ Local Functions ]] --! @StartAudioServiceVia2Protocol: Start audio service via 2 protocol --! @parameters: --! self - test object --! @return: none local function StartAudioServiceVia2Protocol(self) local StartServiceResponseEvent = events.Event() StartServiceResponseEvent.matches = function(_, data) return data.frameType == constants.FRAME_TYPE.CONTROL_FRAME and data.serviceType == constants.SERVICE_TYPE.PCM and data.sessionId == self.mobileSession1.sessionId and (data.frameInfo == constants.FRAME_INFO.START_SERVICE_NACK or data.frameInfo == constants.FRAME_INFO.START_SERVICE_ACK) end -- Send Audio service start from mobile app to SDL self.mobileSession1:Send({ frameType = constants.FRAME_TYPE.CONTROL_FRAME, serviceType = constants.SERVICE_TYPE.PCM, frameInfo = constants.FRAME_INFO.START_SERVICE }) -- Expect StartServiceNACK on mobile app from SDL, it means service is not started self.mobileSession1:ExpectEvent(StartServiceResponseEvent, "Expect StartServiceNACK") :ValidIf(function(_, data) if data.frameInfo == constants.FRAME_INFO.START_SERVICE_NACK then return true else return false, "StartService ACK received" end end) commonDefects.delayedExp() end --[[ Scenario ]] runner.Title("Preconditions") runner.Step("Clean environment", commonDefects.preconditions) runner.Step("Start SDL, HMI", commonDefects.start) runner.Step("RAI, PTU", commonDefects.rai_ptu) runner.Step("Activate App", commonDefects.activate_app) runner.Title("Test") runner.Step("Start audio service via 2 protocol with expectation of StartServiceNACK", StartAudioServiceVia2Protocol) runner.Title("Postconditions") runner.Step("Stop SDL", StopSDL)
function NobleFilter(c,exclude) return IsSetCode(c.setcode,0x107a) and (exclude == nil or c.id~=exclude) end function NobleMonsterFilter(c,exclude) return bit32.band(c.type,TYPE_MONSTER)>0 and NobleFilter(c,exclude) end function ArmsFilter(c,exclude) return IsSetCode(c.setcode,0x207a) and (exclude == nil or c.id~=exclude) end function UseableArmsFilter(c,exclude) return ArmsFilter(c,exclude) and (bit32.band(c.location,LOCATION_SZONE)==0 or bit32.band(c.position,POS_FACEDOWN)>0) end function NobleOrArmsFilter(c,exclude) return NobleFilter(c,exclude) or ArmsFilter(c,exclude) end function RequipCheck(id) return id == 07452945 and OPTCheck(07452945) or id == 14745409 and OPTCheck(14745409) or id == 23562407 and OPTCheck(23562407) or id == 83438826 and OPTCheck(83438826) end function ArmsCount(cards,requip,skipgwen,raw) local result = 0 if requip then for i=1,#cards do if RequipCheck(cards[i].id) and (bit32.band(cards[i].location,LOCATION_SZONE)==0 or bit32.band(cards[i].position,POS_FACEDOWN)>0 or raw) then result = result + 1 end end else result = CardsMatchingFilter(cards,UseableArmsFilter,19748583) if not skipgwen and OPTCheck(19748583) and HasID(UseLists({AIHand(),AIGrave()}),19748583,true) then result = result+1 end if raw then if skipgwen then result = CardsMatchingFilter(cards,ArmsFilter,19748583) else result = CardsMatchingFilter(cards,ArmsFilter) end end end return result end function ArmsAvailable(requip,skipgwen,raw,grave) local cards = UseLists({AIHand(),AIST()}) if grave then cards = UseLists({AIHand(),AIST(),AIGrave()}) end result = ArmsCount(cards,requip,skipgwen,raw) return result end function ArmsRequip() return ArmsCount(AIST(),true,false,true)>0 end function KnightCount(cards) return CardsMatchingFilter(cards,NobleFilter) end function EquipCheck(c) return c.equip_count and c.equip_count>0 and CardsMatchingFilter(c:get_equipped_cards(),ArmsFilter)>0 end function DarkCheck(id) return id==95772051 or id==93085839 or id==59057152 or id==47120245 or id==73359475 or id==83519853 end function GwenCheck() return HasID(UseLists({AIHand(),AIGrave()}),19748583,true) and OPTCheck(19748583) end function NobleATKBoost(mode) -- calculates the maximum ATK boost for available arms local result = 0 local cards = AIHand() local gallatin = false local caliburn = false local destiny = false if mode then if mode == 1 or mode == 3 then -- for High Sally local cards2 = AIDeck() if mode == 3 then cards2 = AIGrave() --for Chapter end if HasID(cards2,14745409,true) then result = result + 1000 elseif HasID(cards2,23562407,true) then result = result + 500 elseif HasID(cards2,07452945,true) then result = result + 1 end if HasID(cards,07452945,true) and result ~= 1 then result = result + 1 end if HasID(cards,23562407,true) and result ~= 500 and result ~= 501 then result = result + 500 end if HasID(cards,14745409,true) and result<1000 then result = result + 1000 end if GwenCheck() then result = result + 300 end return result elseif mode == 2 then -- for a King cards = UseLists({AIHand(),AIGrave()}) end end if HasID(cards,07452945,true) then result = result + 1 end if HasID(cards,23562407,true) then result = result + 500 end if HasID(cards,14745409,true) then result = result + 1000 end end function ArmsByAtk(cards,baseatk) local atk=OppGetStrongestAttDef() if GwenCheck() then baseatk = baseatk + 300 end if GetMultiple(14745409)>0 then baseatk = baseatk + 1000 end if GetMultiple(23562407)>0 then baseatk = baseatk + 500 end if GetMultiple(07452945)>0 then baseatk = baseatk + 1 end if atk==baseatk and HasID(cards,07452945,true) and GetMultiple(07452945)==0 then SetMultiple(07452945) return {IndexByID(cards,07452945)} elseif atk>=baseatk and atk<baseatk+500 and HasID(cards,23562407,true) and GetMultiple(23562407)==0 then SetMultiple(23562407) return {IndexByID(cards,23562407)} elseif atk>=baseatk and HasID(cards,14745409,true) and GetMultiple(14745409)==0 then SetMultiple(14745409) return {IndexByID(cards,14745409)} elseif atk>=baseatk and HasID(cards,23562407,true) and GetMultiple(23562407)==0 then SetMultiple(23562407) return {IndexByID(cards,23562407)} elseif atk>=baseatk and HasID(cards,07452945,true) and GetMultiple(07452945)==0 then SetMultiple(07452945) return {IndexByID(cards,07452945)} else return Add(cards,PRIO_TOFIELD) end end function TableCount() local cards = UseLists({AIField(),AIGrave()}) local result = 0 local check = {} for i=1,#cards do if NobleFilter(cards[i]) and not check[cards[i].id] then result = result +1 check[cards[i].id]=true end end return result end function KingArmsCount() local cards = AIGrave() local result = 0 local check = {} for i=1,#cards do if ArmsFilter(cards[i],19748583) and not check[cards[i].id] then result = result +1 check[cards[i].id]=true end end return result end function EquipFilter(c) if (c.id == 59057152 and UseMedraut() or c.id == 47120245 and ArmsCount(AIDeck())>2 or c.id == 13391185 and UseChad() or c.id == 53550467 and OPTCheck(53550467) and DestroyCheck(OppField(),false,false,false,FilterPosition,POS_FACEUP)>0 or c.id == 73359475) and not EquipCheck(c) then return true end return false end function NobleSSCheck() return GlobalNobleSS ~= Duel.GetTurnCount() end function BlackCheck(c) return NotNegated(c) and (c.id == 59057152 or c.id == 47120245 or c.id == 73359475) end function Lvl5Check(c) return HasID(UseLists({AIHand(),AIGrave()}),95772051,true) and PriorityCheck(AIGrave(),2,PRIO_TOGRAVE,NobleMonsterFilter)>1 and NormalCheck(c) or BlackCheck(c) and ArmsAvailable()>0 end function NormalCheck(c) if FilterLocation(c,LOCATION_MZONE) then return BlackSallyFilter(c) else return c.id==59057152 or c.id==47120245 or c.id==13391185 end end function DualUseArmsCheck() return ArmsAvailable(true)>0 or ArmsAvailable()>1 end function PlayCheck() return (HasID(AIHand(),59057152,true) and UseMedraut(true,true) and (DualUseArmsCheck() or HasID(AIHand(),46008667,true) and HasID(AIHand(),19680539,true)) or HasID(AIHand(),47120245,true) and UseBorz(true) and (ArmsAvailable()>0 or CardsMatchingFilter(AIHand(),FilterID,19680539)>1) or HasID(AIHand(),03580032,true) --and (ArmsAvailable()>0 or HasID(AIHand(),19680539,true) and CardsMatchingFilter(AIHand(),NormalCheck)>0 and ArmsAvailable(false,false,true)==0 and not HasID(AIHand(),47120245,true)) or NormalSummonCheck(player_ai) end GlobalGallatinTurn={} GlobalTableDump=0 GlobalNobleSS = 0 GlobalNobleExtra = nil function MedrautCond(loc,c) if loc == PRIO_TOHAND then return SummonMedraut() and not HasID(AIHand(),59057152,true) and (ArmsAvailable(true)>0 or ArmsAvailable()>1 or CardsMatchingFilter(AIDeck(),ArmsFilter)<2) end if loc == PRIO_TOFIELD then return (not FilterLocation(c,LOCATION_REMOVED) and (SummonMedraut(true) or CardsMatchingFilter(AIDeck(),ArmsFilter)<2) and Duel.GetCurrentPhase()~=PHASE_END) and #AIMon()==0 end if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_DECK) then return not HasID(AIGrave(),59057152,true) end if FilterLocation(c,LOCATION_MZONE) then return not UseMedraut() end return false end if loc == PRIO_BANISH then if HasID(AIMon(),68618157,true) then return true end return false end return true end function BorzCond(loc,c) if loc == PRIO_TOHAND then return SummonBorz() and not HasID(AIHand(),47120245,true) and Duel.GetCurrentPhase()~=PHASE_END and not (OTKCheck() and HasID(AIHand(),59057152,true) and DualUseArmsCheck()) and not FilterLocation(c,LOCATION_REMOVED) end if loc == PRIO_TOFIELD then return ArmsCount(AIDeck(),false,false,true)>3 and Duel.GetCurrentPhase()~=PHASE_END and not OTKCheck() end if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_DECK) then return not HasID(AIGrave(),47120245,true) end if FilterLocation(c,LOCATION_MZONE) then return not UseBorz(true) end return false end return true end function ChadCond(loc,c) if loc == PRIO_TOHAND then if FilterLocation(c,LOCATION_REMOVED) then return not AmaterasuCheck() else return UseChad(true) and not HasID(AIHand(),13391185,true) and not OTKCheck() end end if loc == PRIO_TOFIELD then return FilterLocation(c,LOCATION_REMOVED) or SummonChad(true) and Duel.GetCurrentPhase()~=PHASE_END or OTKCheck() and FieldCheck(4)==1 end if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_DECK) then return not HasID(AIGrave(),13391185,true) end return false end if loc == PRIO_BANISH then return HasID(AIMon(),68618157,true) end return true end function BedwyrCond(loc,c) if loc == PRIO_TOHAND then return true end if loc == PRIO_TOFIELD then return (ArmsAvailable(false,false,false,true)==0 and not ArmsRequip() and not (HasID(AIMon(),59057152,true) and SummonChainNoble() or HasID(AIHand(),19680539,true) and NobleSSCheck())) and Duel.GetCurrentPhase()~=PHASE_END and not OTKCheck() end if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_DECK) then return not HasID(AIGrave(),30575681,true) end return false end if loc == PRIO_BANISH then return HasID(AIMon(),68618157,true) end return true end function DrystanCond(loc,c) if loc == PRIO_TOHAND then return not HasID(AIHand(),53550467,true) end if loc == PRIO_TOFIELD then return SummonDrystan(true) or Duel.GetCurrentPhase()==PHASE_END end if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_DECK) then return not HasID(AIGrave(),53550467,true) end return false end end function PeredurCond(loc,c) if loc == PRIO_TOHAND then return not HasID(AIHand(),73359475,true) end if loc == PRIO_TOFIELD then return bit32.band(c.location,LOCATION_HAND)>0 or Duel.GetCurrentPhase()==PHASE_END end if loc == PRIO_TOGRAVE then if bit32.band(c.location,LOCATION_DECK)>0 then return not HasID(AIGrave(),73359475,true) end if bit32.band(c.location,LOCATION_MZONE)>0 and EquipCheck(c) then return true end return false end end function GawaynCond(loc,c) if loc == PRIO_TOHAND then return (not HasID(AIHand(),19680539,true) or FilterLocation(c,LOCATION_REMOVED) or OTKCheck() or (HasID(AIHand(),47120245,true) and ArmsAvailable()==0 or HasID(AIHand(),59057152,true) and UseMedraut(true) and ArmsAvailable()==1 and HasID(AIHand(),46008667,true)) and not (NormalSummonCheck(player_ai) and UseBorz(true))) and Duel.GetCurrentPhase()~=PHASE_END end if loc == PRIO_TOFIELD then return Duel.GetCurrentPhase()~=PHASE_END end if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_DECK) then return not HasID(AIGrave(),19680539,true) end if FilterLocation(c,LOCATION_MZONE) then return true end if FilterLocation(c,LOCATION_OVERLAY) then return true end return false end if loc == PRIO_BANISH then return HasID(AIMon(),68618157,true) end end function BlackSallyCond(loc,c) if loc == PRIO_TOHAND then return bit32.band(c.location,LOCATION_REMOVED)>0 end if loc == PRIO_TOFIELD then return bit32.band(c.location,LOCATION_HAND+LOCATION_REMOVED)>0 or (ArmsAvailable(false,false,false,true)==0 and not ArmsRequip() and not (HasID(AIMon(),59057152,true) and SummonChainNoble() or HasID(AIHand(),19680539,true) and NobleSSCheck())) or ArmsAvailable()==0 and HasID(AIMon(),59057152,true) and ArmsCount(AIST(),false,false,true)==1 and not ArmsRequip() and ArmsCount(AIGrave(),false,true,true)<2 and not (HasID(AIHand(),19680539,true) or #AIMon()>1) or Duel.GetCurrentPhase()==PHASE_END end if loc == PRIO_TOGRAVE and bit32.band(c.location,LOCATION_DECK)>0 then return not HasID(AIGrave(),95772051,true) end return true end function EachtarCond(loc,c) if loc == PRIO_TOHAND then return bit32.band(c.location,LOCATION_REMOVED)>0 end if loc == PRIO_TOFIELD then return bit32.band(c.location,LOCATION_REMOVED)>0 or bit32.band(c.location,LOCATION_HAND)>0 and (Duel.GetCurrentPhase()==PHASE_END or not (HasID(AIHand(),47120245,true) and HasID(AIHand(),93085839,true))) end if loc == PRIO_TOGRAVE and bit32.band(c.location,LOCATION_DECK)>0 then return not HasID(AIGrave(),93085839,true) end return true end function ArtorigusCond(loc,c) if loc == PRIO_TOFIELD then return bit32.band(c.location,LOCATION_HAND+LOCATION_REMOVED)>0 end if loc == PRIO_TOGRAVE then if bit32.band(c.location,LOCATION_DECK)>0 then return not HasID(AIGrave(),92125819,true) end if bit32.band(c.location,LOCATION_MZONE)>0 then return true end end return true end function BrothersCond(loc,c) if loc == PRIO_TOHAND then return SummonBrothers() or bit32.band(c.location,LOCATION_REMOVED)>0 or Duel.GetCurrentPhase()==PHASE_END end if loc == PRIO_TOFIELD then return SummonBrothers(ss) and not OTKCheck() or Duel.GetCurrentPhase()==PHASE_END end if loc == PRIO_TOGRAVE and bit32.band(c.location,LOCATION_DECK)>0 then return not HasID(AIGrave(),57690191,true) end return true end function ExcaliburnCond(loc,c) if loc == PRIO_TOHAND then return not HasAccess(c.id) and GetMultiple(c.id)==0 and (bit32.band(c.location,LOCATION_REMOVED)==0 or ArmsAvailable()==0) end return true end function GwenCond(loc,c) if loc == PRIO_TOHAND then local cards=UseLists({AIHand(),AIMon()}) return not HasAccess(c.id) and GetMultiple(c.id)==0 and OPTCheck(19748583) and not ((HasID(cards,59057152,true) or HasID(AIHand(),03580032,true)or HasID(AIHand(),32807846,true)) and not HasID(AIMon(),47120245,true)) and not FilterLocation(c,LOCATION_GRAVE) and (bit32.band(c.location,LOCATION_REMOVED)==0 or ArmsAvailable()==0) end if loc == PRIO_TOGRAVE then if bit32.band(c.location,LOCATION_SZONE)==0 then return ArmsAvailable()==0 and OPTCheck(19748583) --and not (HasID(AIHand(),66970385,true) and ArmsAvailable(true,false,true,true)==0) else return not ArmsRequip() or OPTCheck(19748583) end end return true end function RequipArmsCond(loc,c) if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_SZONE) then return OPTCheck(c.id) end if FilterLocation(c,LOCATION_DECK) then return HasID(AIHand(),66970385,true) and ArmsAvailable(true,false,true,true)==0 end return false end if loc == PRIO_TOFIELD then return GetMultiple(c.id)==0 end if loc == PRIO_TOHAND then return not HasAccess(c.id) and GetMultiple(c.id)==0 and (bit32.band(c.location,LOCATION_REMOVED)==0 or ArmsAvailable()==0) end return true end function ArfFilter(c) return bit32.band(c.position,POS_FACEDOWN)>0 and DestroyFilter(c) end function ArfCond(loc,c) if loc == PRIO_TOGRAVE then if FilterLocation(c,LOCATION_SZONE) then return OPTCheck(c.id) and CardsMatchingFilter(OppField(),ArfFilter)>0 end return false end if loc == PRIO_TOFIELD then return GetMultiple(c.id)==0 end if loc == PRIO_TOHAND then return not HasAccess(c.id) and GetMultiple(c.id)==0 end return true end function LadyCond(loc,c) if loc == PRIO_TOGRAVE then return (FieldCheck(5,NobleFilter)>0 or CardsMatchingFilter(AIMon(),Lvl5Check)>0 or EachtarCheck()) and SummonHighSally() and NobleSSCheck() end if loc == PRIO_TOHAND then return HasID(AIGrave(),92125819,true) end end function R5torigusCond(loc,c) if loc == PRIO_TOGRAVE then return c.xyz_material_count==0 and PriorityCheck(AIGrave(),PRIO_TOFIELD,1,NobleMonsterFilter)>4 end end function TableCond(loc,c) if loc == PRIO_TOHAND then return not HasID(UseLists({AIHand(),AIST()}),55742055,true) end end function GawaynCheck() return HasID(AIHand(),19680539,true) and DualityCheck() and Duel.GetCurrentPhase()~=PHASE_END and not UseMedraut() end function EachtarCheck() return HasID(UseLists({AIHand(),AIGrave()}),93085839,true) and PriorityCheck(AIGrave(),PRIO_BANISH,2,NobleMonsterFilter)>1 and DualityCheck() end function SummonBorz(ss) return (((ArmsAvailable()>0 or ArmsRequip()) and OPTCheck(47120245) and ArmsCount(AIDeck(),false,false,true)>3 or GawaynCheck() and not ss or ArmsAvailable()>0 and FieldCheck(5,NobleMonsterFilter,95772051)==1 and SummonR5torigus() or HasID(UseLists({AIHand(),AIGrave()}),95772051,true) and not HasID(AIHand(),57690191,true)) and (ss or not NormalSummonCheck(player_ai))) and not UseMedraut() end function SummonMedraut(ss) return ((ArmsAvailable(true)>0 or ArmsAvailable()>1 or (ArmsAvailable()>0 and not ss and not HasID(AIHand(),47120245,true) and not HasID(AIHand(),03580032,true))) and #AIMon()==0 and OPTCheck(59057152) and DualityCheck() and (ss or not NormalSummonCheck(player_ai))) or GawaynCheck() and not ss and not HasID(AIHand(),47120245,true) or ArmsAvailable()>0 and FieldCheck(5,NobleMonsterFilter,95772051)==1 and SummonR5torigus() end function SummonChad(ss) return (((OPTCheck(13391185) and (ss or not NormalSummonCheck(player_ai))) and ArmsAvailable()>0 and PriorityCheck(AIGrave(),PRIO_TOHAND,1,NobleMonsterFilter)>2) or GawaynCheck()) and not UseMedraut() end function SummonBedwyr(ss) return (OPTCheck(30575681) and (ss or not NormalSummonCheck(player_ai))) and ArmsAvailable()==0 and not UseMedraut() end function SummonPeredur(ss) return (ArmsAvailable()>0 and (ss or not NormalSummonCheck(player_ai)) or FieldCheck(5,NobleMonsterFilter,83519853)==1 and SummonR5torigus()) and not UseMedraut() and not UseChad() end function BlackSallyFilter(c) return NobleMonsterFilter(c) and bit32.band(c.type,TYPE_NORMAL)>0 end function UseBlackSally() return MP2Check(2000) and (ArmsAvailable()==0 or PriorityCheck(AIMon(),PRIO_TOGRAVE,1,NobleMonsterFilter)>2) end function SummonBlackSally() return (HasID(AIGrave(),10736540,true) and SummonHighSally() and FieldCheck(5,NobleMonsterFilter)==0 and not (HasID(AIMon(),47120245,true) and UseBorz() or HasID(AIMon(),73359475,true) and ArmsAvailable>0 and ArmsCount(AIGrave,false,true,true)>0) or FieldCheck(5,NobleMonsterFilter,83519853)==1 and SummonR5torigus() --or ArmsAvailable()==0 and not ArmsRequip() and OPTCheck(19748583) or ArmsAvailable()==0 and HasID(AIMon(),47120245,true) and UseBorz(true) and CardsMatchingFilter(AIMon(),NormalCheck)>1 and not (FieldCheck(4,NobleMonsterFilter)==2 and (SummonR4torigus() or SummonChainNoble()))) and not UseMedraut() and not AmaterasuCheck() and not UseChad() and not (HighSallyCheck(4) and HasID(AIHand(),19680539,true)) end function UseBrothers() return PriorityCheck(AIGrave(),PRIO_TODECK,3,NobleFilter)>1 and OPTCheck(57690191) end function ChainBrothers() return HasID(AIHand(),95772051,true) or HasID(AIHand(),93085839,true) or CardsMatchingFilter(AIHand(),LevelFilter,4)>1 and SummonR4torigus() end function SummonBrothers(ss) return OPTCheck(57690191) and (PriorityCheck(AIGrave(),PRIO_TODECK,6,NobleFilter)>1 or PriorityCheck(AIGrave(),PRIO_TODECK,3,NobleFilter)>4 or ChainBrothers() and not ss) and (ss or not NormalSummonCheck(player_ai)) and not UseMedraut() end function SetBrothers() return ((Duel.GetCurrentPhase()==PHASE_MAIN2 or not GlobalBPAllowed)) and (not HasID(AIST(),55742055,true) or TableCount()<6) end function UseArfDestroy() return CardsMatchingFilter(OppField(),ArfFilter)>0 end function SummonEachtar() return ( HasID(AIMon(),68618157,true) or (PriorityCheck(AIGrave(),PRIO_BANISH,2,NobleMonsterFilter)>1 and (FieldCheck(5,NobleFilter)==1 and not HasID(AIMon(),83519853,true) or FieldCheck(5,NobleFilter)==2) and SummonR5torigus() or HasID(AIGrave(),10736540,true) and SummonHighSally() or #AIMon()==0)) and not UseMedraut() and Duel.GetLocationCount(player_ai,LOCATION_MZONE)>0 end function UseCaliburn(facedown) return (EquipTargetCheck(AIMon(),true) or ArmsCount(AIHand(),false,true)>1 or OppHasStrongestMonster() or facedown) and not AmaterasuCheck() and CardsMatchingFilter(AIMon(),FilterRace,RACE_WARRIOR)>0 end function UseArf(facedown) return UseArfDestroy() and not AmaterasuCheck() or (EquipTargetCheck(AIMon(),true) and ArmsCount(AIHand(),true,true)==1) end function UseDestiny(facedown) return CardsMatchingFilter(AIMon(),FilterRace,RACE_WARRIOR)>0 and not AmaterasuCheck() --and (ArmsCount(AIHand(),false,true)>1 or EquipTargetCheck(AIMon(),true) --or #AIMon()==1 or facedown) end function UseGallatin(facedown) return (ArmsCount(AIHand(),false,true)>1 or EquipTargetCheck(AIMon(),true) or OppHasStrongestMonster() or facedown) and CardsMatchingFilter(AIMon(),FilterRace,RACE_WARRIOR)>0 and not AmaterasuCheck() end function UseGwen() return not AmaterasuCheck() end function UseExcaliburn(facedown) return CardsMatchingFilter(AIMon(),NobleMonsterFilter)>0 and not AmaterasuCheck() --and (facedown or ArmsCount(AIHand(),false,true)>1 or EquipTargetCheck(AIMon(),true)) end function ExcaliburnFilter(c) return NobleMonsterFilter(c) and FilterType(c,TYPE_XYZ) and (c.xyz_material_count==0 or c.equip_count<2 and ArmsCount(AIGrave(),false,true,true)>1) end function UseExcaliburnGrave() return CardsMatchingFilter(AIMon(),ExcaliburnFilter)>0 end function BorzFilter(c) return c.id == 47120245 and c.equip_count>0 and CardsMatchingFilter(c:get_equipped_cards(),ArmsFilter)>0 end function UseBorz(skiparms) return OPTCheck(47120245) and (HasID(AIMon(),47120245,true,nil,nil,nil,BorzFilter) or ArmsAvailable()>0 or skiparms) and CardsMatchingFilter(AIDeck(),ArmsFilter)>2 end function ChadFilter(c) return NobleMonsterFilter(c) and c.id~=95772051 and c.id~=93085839 and c.id~=83519853 and c.id~=21223277 and c.id~=10613952 end function ChadFilter2(c) return c.id == 13391185 and c.equip_count>0 and CardsMatchingFilter(c:get_equipped_cards(),ArmsFilter)>0 end function UseChad(skiparms) return OPTCheck(13391185) and (HasID(AIMon(),13391185,true,nil,nil,nil,ChadFilter2) or HasID(AIMon(),13391185,true) and ArmsAvailable()>0 or skiparms) and CardsMatchingFilter(AIGrave(),ChadFilter)>0 and not (OTKCheck() and not HasID(AIGrave(),19680539,true)) end function UseBedwyr() return false end GlobalBedwyrID = 0 function ChainBedwyr() local e = Duel.GetChainInfo(Duel.GetCurrentChain(), CHAININFO_TRIGGERING_EFFECT) if e and e:GetHandler():IsType(TYPE_EQUIP) then return false end if not UnchainableCheck(30575681) then return false end if HasID(AIST(),07452945,true,FilterPosition,POS_FACEUP) then local destiny = FindID(07452945,AIST()) local eq = destiny:get_equip_target()[1] local targets = {} for i=1,#AIMon() do local c=AIMon()[i] if RemovalCheckCard(c,CATEGORY_DESTROY) and not RemovalCheckCard(eq,CATEGORY_DESTROY) and not CardsEqual(c,eq) and not (HasID(c:get_equipped_cards(),19748583,true) and FilterAttribute(c,ATTRIBUTE_LIGHT)) then targets[#targets+1]=c end end if #targets>0 then BestTargets(targets,1,TARGET_PROTECT) GlobalBedwyrID = 07452945 GlobalTargetSet(targets[1]) return true end end if HasID(AIST(),19748583,true,FilterPosition,POS_FACEUP) then local gwen = FindID(19748583,AIST()) local eq = gwen:get_equip_target()[1] local targets = {} for i=1,#AIMon() do local c=AIMon()[i] if RemovalCheckCard(c,CATEGORY_DESTROY) and FilterAttribute(c,ATTRIBUTE_LIGHT) and not DarkCheck(c.id) and not RemovalCheckCard(eq,CATEGORY_DESTROY) and not CardsEqual(c,eq) and not (HasID(c:get_equipped_cards(),19748583,true) and FilterAttribute(c,ATTRIBUTE_LIGHT)) then targets[#targets+1]=c end end if #targets>0 then BestTargets(targets,1,TARGET_PROTECT) GlobalBedwyrID = 19748583 GlobalTargetSet(targets[1]) return true end local aimon,oppmon=GetBattlingMons() if Duel.GetTurnPlayer()==1-player_ai and WinsBattle(oppmon,aimon) and aimon:GetEquipGroup():FilterCount(function(c)return c:GetCode()==19748583 end,nil)==0 and (DarkCheck(aimon:GetCode()) and Affected(oppmon,TYPE_SPELL) and DestroyFilterIgnore(oppmon,true) or AttackBoostCheck(300)) then GlobalBedwyrID = 19748583 GlobalTargetSet(aimon) return true end end if HasID(AIST(),23562407,true,FilterPosition,POS_FACEUP) then local aimon,oppmon=GetBattlingMons() if Duel.GetTurnPlayer()==1-player_ai and WinsBattle(oppmon,aimon) and aimon:GetEquipGroup():FilterCount(function(c)return c:GetCode()==23562407 end,nil)==0 and AttackBoostCheck(500) then GlobalBedwyrID = 23562407 GlobalTargetSet(aimon) return true end end if HasID(AIST(),14745409,true,FilterPosition,POS_FACEUP) then local gallatin=FindID(14745409,AIST()) local drop = 0 local turn = GlobalGallatinTurn[gallatin.cardid] if turn then drop = Duel.GetTurnCount()-turn*200 end local atk = 1000-drop local aimon,oppmon=GetBattlingMons() if atk>0 and Duel.GetTurnPlayer()==1-player_ai and WinsBattle(oppmon,aimon) and aimon:GetEquipGroup():FilterCount(function(c)return c:GetCode()==14745409 end,nil)==0 and AttackBoostCheck(atk) then GlobalBedwyrID = 14745409 GlobalTargetSet(aimon) return true end end if HasID(AIST(),07452945,true,FilterPosition,POS_FACEUP) then local aimon,oppmon=GetBattlingMons() if Duel.GetTurnPlayer()==1-player_ai and WinsBattle(oppmon,aimon) and aimon:GetEquipGroup():FilterCount(function(c)return c:GetCode()==07452945 end,nil)==0 and not (aimon:GetEquipGroup():FilterCount(function(c)return c:GetCode()==19748583 end,nil)>0 and DarkCheck(aimon:GetCode()) and Affected(oppmon,TYPE_SPELL) and DestroyFilterIgnore(oppmon,true)) then GlobalBedwyrID = 07452945 GlobalTargetSet(aimon) return true end end return false --return Duel.GetCurrentPhase()==PHASE_MAIN1 and Duel.GetTurnPlayer()==1-player_ai end function SummonMerlin() return DualityCheck() and OPTCheck(03580032) and not UseMedraut() and not (HasID(AIHand(),59057152,true) and SummonMedraut()) and not (HasID(AIHand(),47120245,true) and SummonBorz() and not SummonMedraut(true)) end function SummonDrystan() return ArmsAvailable()>0 and OPTCheck(53550467) and DestroyCheck(OppField(),false,false,false,FilterPosition,POS_FACEUP)>0 and not UseMedraut() end function HighSallyFilter(c) return c:is_affected_by(EFFECT_INDESTRUCTABLE_BATTLE)==0 and c:is_affected_by(EFFECT_CANNOT_BE_BATTLE_TARGET)==0 and DestroyCountCheck(c,TYPE_MONSTER,true) and FilterPendulum(c) and not ((c.id == 48739166 or c.id == 78156759 or c.id == 10002346) and c.xyz_material_count>0) end function HighSallySummonFilter(c,mode) return HighSallyFilter(c) and c.attack<2100+NobleATKBoost(mode) end function UseHighSally(mode) if mode == nil then mode = 1 end ApplyATKBoosts(OppMon()) return Duel.GetCurrentPhase()== PHASE_MAIN1 and GlobalBPAllowed and CardsMatchingFilter(OppMon(),HighSallySummonFilter,mode)>0 end function SummonHighSally() return DualityCheck() and HasID(AIExtra(),83519853,true) and UseHighSally() end function SummonLady() return (FieldCheck(4,NobleKnightFilter)==1 or HasID(AIGrave(),92125819,true)) and SummonHighSally() and not UseMedraut() and not UseChad() end function UseLady() return FieldCheck(5,NobleKnightFilter)>0 and not UseMedraut() end function UseMedraut(skiparms,skipmon) return DualityCheck() and OPTCheck(59057152) and (skipmon or #AIMon()==1 and HasID(AIMon(),59057152,true) and (skiparms or ArmsAvailable()>0 or #AIMon()==1 and EquipCheck(AIMon()[1]))) end function SummonGawayn() return ((SummonR4torigus() or SummonChainNoble() or SummonTsukuyomiNK()) and (FieldCheck(4,NobleFilter)==1 or FieldCheck(4,NobleFilter)==2 and HasID(AIMon(),47120245,true,nil,nil,nil,HasEquips,0) and UseBorz(true)) or SummonAmaterasu() and FieldCheck(4,NobleFilter)==2 or HighSallyCheck(4) or OTKCheck()) and not UseMedraut() end function SummonR4torigus() return HasID(AIExtra(),21223277,true) and ArmsCount(UseLists({AIST(),AIGrave()}),false,true,true)>1 and (OppHasStrongestMonster() or #OppST()>1) and not (HasID(AIMon(),13391185,true) and ArmsAvailable()>0 and UseChad()) end function UseR4torigus() return DestroyCheck(OppST())>0 and not (HasID(AIMon(),13391185,true) and UseChad() and ArmsAvailable()>0) end function SummonR5torigus() return HasID(AIExtra(),10613952,true) and ArmsCount(UseLists({AIST(),AIGrave()}),false,true,true)>1 and (OppHasStrongestMonster() or Duel.GetCurrentPhase()==PHASE_MAIN2 or ArmsCount(AIGrave(),false,true,true)>2 and ArmsCount(AIST(),false,true,true)<2) and DestroyCheck(OppMon())>0 end function UseR5torigus() return DestroyCheck(OppMon())>0 end function UseTable() return not HasID(AIST(),55742055,true) and CardsMatchingFilter(UseLists({AIField(),AIGrave()}),NobleFilter)>1 and (Duel.GetCurrentPhase()==PHASE_MAIN2 or not GlobalBPAllowed) end function SummonChainNoble() return HasID(AIExtra(),34086406,true) and NobleSSCheck() and ((SummonHighSally() and HasID(AIDeck(),10736540,true) and (FieldCheck(5,NobleFilter)>0 or (FieldCheck(4,NobleFilter)>2 and CardsMatchingFilter(AIMon(),Lvl5Check)>0))) or HasID(AIDeck(),19748583,true) and OPTCheck(19748583) and ArmsAvailable(false,false,true,true)==0 or HasID(AIMon(),47120245,true) and (FieldCheck(4,NobleFilter)>=2 or FieldCheck(4,NobleFilter)==1 and CardsMatchingFilter(AIHand(),FilterID,19680539)>1) and ArmsAvailable()==0 and OPTCheck(19748583) and UseBorz(true)) and not (ArmsAvailable()==0 and HasID(AIMon(),47120245,true) and UseBorz(true) and CardsMatchingFilter(AIMon(),NormalCheck)>1 and HasID(UseLists({AIHand(),AIMon()}),95772051,true)) and not ( UseChad() or UseBorz() or SummonAmaterasu() or OTKCheck()) end function UseChapter() return HasID(AIGrave(),83519853,true) or HasID(AIGrave(),59057152,true) and UseMedraut(true,true) or HasID(AIGrave(),13391185,true) and UseChad(true) or HasID(AIGrave(),47120245,true) and ArmsCount(AIDeck(),false,false,true)>3 end function SetAdvice() return CardsMatchingFilter(AIST(),FilterPosition,POS_FACEDOWN)==0 and (Duel.GetCurrentPhase()==PHASE_MAIN2 or not GlobalBPAllowed) and AI.GetPlayerLP(1)>3000 end function HighSallyCheck(level) return SummonHighSally() and (HasID(AIDeck(),10736540,true) and HasID(AIExtra(),34086406,true) or HasID(AIHand(),10736540,true) and HasID(AIExtra(),73289035,true)) and (level == 4 and FieldCheck(4,NobleFilter) == 1 and FieldCheck(5,NobleFilter) == 1 or level == 5 and FieldCheck(4,NobleFilter)>1) end function AmaterasuCheck() return SummonAmaterasu() and HasID(UseLists({AIGrave(),AIBanish()}),19680539,true) and FieldCheck(4,NobleMonsterFilter)>=2 end function AmaterasuFilterNK(c) return NobleMonsterFilter(c) and c.level<5 end function SummonAmaterasu() return HasID(AIExtra(),68618157,true) and (CardsMatchingFilter(AIBanish(),AmaterasuFilterNK)>1 or HasID(AIMon(),93085839,true) and CardsMatchingFilter(AIBanish(),AmaterasuFilterNK)>0 or EachtarCheck()) and (FieldCheck(4)>2 or HasID(AIHand(),19680539,true) or HasID(AIMon(),13391185,true,nil,nil,nil,HasEquips) and HasID(AIGrave(),19680539,true) ) and DualityCheck() and NobleSSCheck() and not (UseChad()) end function SummonExcalibur() return OTKCheck() and (FieldCheck(4)==3 and (HasID(AIMon(),19680539,true) and HasID(AIMon(),13391185,true,nil,nil,nil,HasEquips) or HasID(AIHand(),19680539,true)) or FieldCheck(4)>3) or HasID(OppMon(),27279764,true) and not (HasAccess(14745409) and HasAccess(23562407)) end function UseExcalibur() return Duel.GetCurrentPhase()==PHASE_MAIN1 and GlobalBPAllowed end function SummonBladeArmor() return OTKCheck() and HasID(AIMon(),60645181,true) end function UseBladeArmor() return Duel.GetCurrentPhase()==PHASE_MAIN1 and GlobalBPAllowed end function TsukuyomiHandCheck() local AdviceCheck=false local result = 0 local setable = 0 for i=1,#AIHand() do local c = AIHand()[i] if c.id == 92512625 then if not AdviceCheck and not HasID(AIST(),92512625,true) then AdviceCheck = true else return false end end if FilterType(c,TYPE_SPELL+TYPE_TRAP) then setable = setable + 1 else result = result + 1 end end return setable <= Duel.GetLocationCount(player_ai,LOCATION_SZONE) and result < 3 and PriorityCheck(AIHand(),PRIO_TOGRAVE,math.max(1,result-1),FilterType,TYPE_MONSTER)>4 end function SummonTsukuyomiNK() return DeckCheck(DECK_NOBLEKNIGHT) and HasID(AIExtra(),73289035,true) and HasID(AIHand(),10736540,true) and SummonHighSally() and TsukuyomiHandCheck() and (FieldCheck(5,NobleMonsterFilter)>0 or EachtarCheck()) and not UseChad() and not AmaterasuCheck() and DualityCheck() and NobleSSCheck() and not SummonAmaterasu() end function UseTsukuyomiNK() return DeckCheck(DECK_NOBLEKNIGHT) and (#AIHand()<4 and PriorityCheck(AIHand(),PRIO_TOGRAVE,math.max(#AIHand()-1,1),FilterType,TYPE_MONSTER)>4 or #AIHand()==1) end function TsukuyomiFilter(c) return HasMaterials(c) and NotNegated(c) and OPTCheck(c.cardid) end function OTKCheck() local cards=UseLists({AIMon(),AIExtra()}) return Duel.GetCurrentPhase()==PHASE_MAIN1 and GlobalBPAllowed and DualityCheck() and NobleSSCheck() and AI.GetPlayerLP(2)<=8400 and AI.GetPlayerLP(2)>3000 and #OppField()==0 and HasID(cards,60645181,true) and HasID(cards,82944432,true) end function UseRotA() if DeckCheck(DECK_NOBLEKNIGHT) then local cards = UseLists({AIMon(),AIHand()}) return (not PlayCheck() or (OTKCheck() or SummonHighSally()) and not HasAccess(19680539)) and #AIMon()<2 and (HasID(AIHand(),19680539,true) or CardsMatchingFilter(cards,NormalCheck)>0 or ArmsAvailable()>0) or CardsMatchingFilter(AIHand(),NobleMonsterFilter)==0 and not NormalSummonCheck(player_ai) and not HasID(AIHand(),03580032,true) end if DeckCheck(DECK_HERO) then return false end return true end function CastelNKFilter(c) return c:is_affected_by(EFFECT_CANNOT_BE_EFFECT_TARGET)==0 and c:is_affected_by(EFFECT_INDESTRUCTABLE_EFFECT)>0 and (c:is_affected_by(EFFECT_INDESTRUCTABLE_BATTLE)>0 or c.attack>=4000) end function SummonCastelNK() local targets=SubGroup(OppMon(),CastelNKFilter) if #targets > 0 and OPTCheck(82633039) then return true end return false end function UseChainNK() return DeckCheck(DECK_NOBLEKNIGHT) end function NobleInit(cards) local Act = cards.activatable_cards local Sum = cards.summonable_cards local SpSum = cards.spsummonable_cards local Rep = cards.repositionable_cards local SetMon = cards.monster_setable_cards local SetST = cards.st_setable_cards if HasID(AIMon(),73289035,true,nil,nil,nil,TsukuyomiFilter) and #SetST>0 and #AIHand()>1 and TsukuyomiHandCheck() then return {COMMAND_SET_ST,1} end if HasIDNotNegated(Act,73289035) and UseTsukuyomiNK() then OPTSet(Act[CurrentIndex].cardid) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,68618157) then -- Amaterasu return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,23562407,false,nil,LOCATION_SZONE,POS_FACEUP) then -- Caliburn LP Recovery return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,83438826,false,nil,LOCATION_SZONE,POS_FACEUP) and UseArfDestroy() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,66970385) and UseChapter() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,82944432) and UseExcalibur() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,60645181) and UseBladeArmor() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,32807846) and UseRotA() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,34086406,false,545382497) and UseChainNK() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,10736540) and UseLady() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Sum,10736540) and SummonLady() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Act,19748583,false,nil,LOCATION_GRAVE) and HasID(AIMon(),21223277,true) then OPTSet(19748583) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,21223277) and UseR4torigus() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,10613952) and UseR5torigus() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,03580032,false,nil,LOCATION_MZONE) then -- Merlin OPTSet(03580032) GlobalNobleSS = Duel.GetTurnCount() return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,59057152) and UseMedraut() then -- Medraut GlobalMedraut = 1 OPTSet(59057152) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,47120245) then -- Borz OPTSet(47120245) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,13391185) and UseChad() then OPTSet(13391185) return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,30575681) and UseBedwyr() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasIDNotNegated(Act,57690191) and UseBrothers() then OPTSet(57690191) return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Sum,03580032) and SummonMerlin() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,59057152) and SummonMedraut() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,47120245) and SummonBorz() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,13391185) and SummonChad() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,30575681) and SummonBedwyr() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,53550467) and SummonDrystan() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(SpSum,48739166) and SummonSharkKnightBujin() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,82633039) and SummonCastelNK() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,60645181) and SummonExcalibur() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,82944432) and SummonBladeArmor() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,19680539) and SummonGawayn() then return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(Act,93085839) and SummonEachtar() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(SpSum,83519853) and SummonHighSally() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,34086406) and SummonChainNoble() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,73289035) and SummonTsukuyomiNK() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,68618157) and SummonAmaterasu() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(Act,95772051,false,nil,LOCATION_HAND+LOCATION_GRAVE) and SummonBlackSally() then GlobalCardMode = 1 return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(SpSum,21223277) and SummonR4torigus() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(SpSum,10613952) and SummonR5torigus() then GlobalNobleExtra = 1 return {COMMAND_SPECIAL_SUMMON,CurrentIndex} end if HasID(Act,46008667,false,nil,LOCATION_GRAVE) and UseExcaliburnGrave() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Sum,57690191) and SummonBrothers() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,73359475) and SummonPeredur() then return {COMMAND_SUMMON,CurrentIndex} end if HasID(Act,95772051,false,nil,LOCATION_MZONE) and UseBlackSally() then GlobalCardMode = 1 return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,83438826,false,nil,LOCATION_SZONE,POS_FACEDOWN) and UseArf(true) then GlobalCardMode = 1 return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,83438826,false,nil,LOCATION_HAND) and UseArf() then GlobalCardMode = 1 return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,23562407,false,nil,LOCATION_SZONE,POS_FACEDOWN) and UseCaliburn(true) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,23562407,false,nil,LOCATION_HAND) and UseCaliburn() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,07452945,false,nil,LOCATION_SZONE,POS_FACEDOWN) and UseDestiny(true) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,07452945,false,nil,LOCATION_HAND) and UseDestiny() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,14745409,false,nil,LOCATION_SZONE,POS_FACEDOWN) and UseGallatin(true) then GlobalGallatinTurn[Act[CurrentIndex].cardid]=Duel.GetTurnCount() return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,14745409,false,nil,LOCATION_HAND) and UseGallatin() then GlobalGallatinTurn[Act[CurrentIndex].cardid]=Duel.GetTurnCount() return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,46008667,false,nil,LOCATION_SZONE,POS_FACEDOWN) and UseExcaliburn(true) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,46008667,false,nil,LOCATION_HAND) and UseExcaliburn() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,19748583,false,nil,LOCATION_GRAVE) and UseGwen() then OPTSet(19748583) return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Act,19748583,false,nil,LOCATION_HAND) and UseGwen() then OPTSet(19748583) return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Sum,73359475) and OverExtendCheck() then -- Peredur return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,92125819) and OverExtendCheck() then -- Artorigus return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,53550467) and OverExtendCheck() then -- Drystan return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,47120245) and OverExtendCheck() then -- Borz return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,59057152) and OverExtendCheck() then -- Medraut return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,13391185) and OverExtendCheck() then -- Chad return {COMMAND_SUMMON,CurrentIndex} end if HasID(Sum,30575681) and OverExtendCheck() then -- Bedwyr return {COMMAND_SUMMON,CurrentIndex} end if HasID(Act,66970385) then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(Sum,19680539) and #AIMon() == 0 then -- Gawayn return {COMMAND_SUMMON,CurrentIndex} end if HasID(Act,55742055) and UseTable() then return {COMMAND_ACTIVATE,CurrentIndex} end if HasID(SetMon,57690191) and SetBrothers() then return {COMMAND_SET_MONSTER,CurrentIndex} end if HasID(SetMon,10736540) and SetMonster() then return {COMMAND_SET_MONSTER,CurrentIndex} end if HasID(SetMon,19748583) and SetMonster() then return {COMMAND_SET_MONSTER,CurrentIndex} end if HasID(SetST,92512625) and SetAdvice() then return {COMMAND_SET_ST,CurrentIndex} end return nil end function MedrautTarget(cards) if GlobalMedraut == 1 then GlobalMedraut = nil return Add(cards,PRIO_TOFIELD) else return Add(cards,PRIO_TOGRAVE) end end function EquipTargetCheckFunc(cards,id,func,opt,skipeqcheck,skipmultiple) for i=1,#cards do if (((id== nil or cards[i].id == id and (opt==nil and func() or opt and func(opt))) and GetMultiple(cards[i].cardid)==0) and (skipeqcheck or not EquipCheck(cards[i]))) and CurrentMonOwner(cards[i].cardid) == 1 then if skipmultiple~=true then SetMultiple(cards[i].cardid) end return {i} end end return nil end function EquipTargetCheck(cards,skipmultiple) local result = nil result = EquipTargetCheckFunc(cards,59057152,UseMedraut,true,false,skipmultiple) if result then return result end result = EquipTargetCheckFunc(cards,47120245,function() return ArmsCount(AIDeck(),false,false,true)>2 end,nil,false,skipmultiple) if result then return result end result = EquipTargetCheckFunc(cards,13391185,UseChad,true,false,skipmultiple) if result then return result end result = EquipTargetCheckFunc(cards,53550467,function() return DestroyCheck(OppField(),false,false,false,FilterPosition,POS_FACEUP)>0 and OPTCheck(53550467) end,nil,true,skipmultiple) if result then return result end result = EquipTargetCheckFunc(cards,73359475,function() return true end,nil,false,skipmultiple) if result then return result end if OppHasStrongestMonster() then end return nil end function EquipTarget(cards,id) result = EquipTargetCheck(cards) if result then return result end result = EquipTargetCheckFunc(cards) if result then return result end local count = 999 for i=1,#cards do local c = cards[i] if CurrentMonOwner(c.cardid) == 1 and c.equip_count<count then count = c.equip_count result = i end end if result then return {result} end return {math.random(#cards)} end function BorzTarget(cards,min) if min == 3 then return Add(cards,PRIO_TOHAND,3) else return {math.random(#cards)} end end function ArfTarget(cards,c) if GlobalCardMode == 1 then GlobalCardMode = nil return EquipTarget(cards) else return BestTargets(cards) end end function ExcaliburnTarget(cards,c) if FilterLocation(cards[1],LOCATION_MZONE) then return EquipTarget(cards) end return Add(cards,PRIO_TOFIELD) end function MerlinTarget(cards,min) if FilterLocation(cards[1],LOCATION_MZONE) then result = {} if GlobalMerlinID and #GlobalMerlinID>0 then for i=1,#cards do for j=1,#GlobalMerlinID do if cards[i].id == GlobalMerlinID[j] then result[j]=i end end end else result = Add(cards,PRIO_TOGRAVE,min) end for i=1,#cards do if result[#result]~=i and #result<min then result[#result+1]=i end end return result end return Add(cards,PRIO_TOFIELD,min) end function LadyTarget(cards) return {math.random(#cards)} end function HighSallyTarget(cards) if IsBattlePhase() then return Add(cards) else local result = ArmsByAtk(cards,2100) if result then return result end return Add(cards,PRIO_TOFIELD) end return {math.random(#cards)} end function DrystanTarget(cards) OPTSet(53550467) return BestTargets(cards,1,TARGET_DESTROY) end function BrothersTarget(cards,min) if min == 3 then return Add(cards,PRIO_TODECK,3) else if HasID(cards,47120245,true) and HasID(AIHand(),95772051,true) then return Add(cards,PRIO_TOFIELD,2) end return Add(cards,PRIO_TOFIELD,math.min(min,2)) end end function ArmsTargets(cards,max) local result = {} for i=1,#cards do local c = cards[i] if c.owner == 1 and ArmsFilter(c) and c:get_equip_target() and (c.id == 23562407 and OPTCheck(23562407) or c.id == 14745409 and OPTCheck(14745409) and GlobalGallatinTurn[c.cardid] and GlobalGallatinTurn[c.cardid]<Duel.GetTurnCount() or CurrentOwner(c:get_equip_target()[1])==2) then result[#result+1]=i if #result >= max then break end end end return result end function R4torigusTarget(cards,max) if ArmsFilter(cards[1]) and FilterLocation(cards[1],LOCATION_GRAVE) then local result = ArmsByAtk(cards,2000) if result ~= nil then return result end return Add(cards,PRIO_TOFIELD) end if FilterLocation(cards[1],LOCATION_OVERLAY) then return Add(cards,PRIO_TOGRAVE) end local count = DestroyCheck(OppST(),true) local targets = {} if count >= max then count = max end if count < max then targets = ArmsTargets(cards,max-count) end return UseLists({BestTargets(cards,count,TARGET_DESTROY),targets}) end function R5torigusTarget(cards,c) if ArmsFilter(cards[1]) and FilterLocation(cards[1],LOCATION_GRAVE) then local result = ArmsByAtk(cards,2000) if result ~= nil then return result end return Add(cards,PRIO_TOFIELD) end if FilterLocation(cards[1],LOCATION_OVERLAY) then return Add(cards,PRIO_TOGRAVE) end if NobleMonsterFilter(cards[1]) and FilterLocation(cards[1],LOCATION_GRAVE) then return Add(cards,PRIO_TOFIELD) end return BestTargets(cards,1,TARGET_DESTROY) end function TableTarget(cards) if FilterLocation(cards[1],LOCATION_DECK) then return Add(cards,PRIO_TOGRAVE) elseif FilterLocation(cards[1],LOCATION_GRAVE) then return Add(cards) elseif FilterLocation(cards[1],LOCATION_HAND) then return Add(cards,PRIO_TOFIELD) end if result == nil then result = {math.random(#cards)} end return result end function ChadTarget(cards) if FilterLocation(cards[1],LOCATION_GRAVE) then return Add(cards,PRIO_TOHAND) end return Add(cards,PRIO_TOGRAVE) end function BedwyrTarget(cards) if FilterLocation(cards[1],LOCATION_DECK) then return Add(cards) elseif FilterLocation(cards[1],LOCATION_MZONE) then return GlobalTargetGet(cards,true) elseif FilterLocation(cards[1],LOCATION_SZONE) then return BestTargets(cards,1,TARGET_PROTECT,FilterID,GlobalBedwyrID) end return BestTargets(cards,1,TARGET_PROTECT) end function BlackSallyTarget(cards,c) if GlobalCardMode == 1 then GlobalCardMode = nil return Add(cards,PRIO_TOGRAVE) end return Add(cards,PRIO_TOHAND) end function ChapterTarget(cards) if NobleMonsterFilter(cards[1]) then if HasID(cards,83519853,true) and UseHighSally() then return {IndexByID(cards,83519853)} end if HasID(cards,59057152,true) and UseMedraut(true,true) then return {IndexByID(cards,59057152)} end if HasID(cards,13391185,true) and UseChad(true) then return {IndexByID(cards,13391185)} end if HasID(cards,47120245,true) and ArmsCount(AIDeck(),false,false,true)>3 then return {IndexByID(cards,47120245)} end return Add(cards,PRIO_TOFIELD) else return Add(cards,PRIO_TOFIELD) end end function EachtarTarget(cards) return Add(cards,PRIO_BANISH,2) end function PeredurTarget(cards) Add(cards,PRIO_TOHAND) end function AmaterasuTarget(cards) if FilterLocation(cards[1],LOCATION_OVERLAY) then return Add(cards,PRIO_TOGRAVE) end if Duel.GetTurnPlayer()==player_ai then return Add(cards,PRIO_TOFIELD) else return Add(cards,PRIO_TOHAND) end end function NobleCard(cards,min,max,id,c) if GlobalNobleExtra and GlobalNobleExtra>0 then GlobalNobleExtra = GlobalNobleExtra - 1 if GlobalNobleExtra <=0 then GlobalNobleExtra = nil end return Add(cards,PRIO_TOGRAVE,min) end if c then id = c.id end if id == 47120245 then -- Borz return BorzTarget(cards,min) end if id == 59057152 then return MedrautTarget(cards) end if id == 23562407 or id == 19748583 or id == 07452945 or id == 14745409 then return EquipTarget(cards,id) end if id == 83438826 then return ArfTarget(cards,c) end if id == 46008667 then return ExcaliburnTarget(cards,c) end if id == 03580032 then return MerlinTarget(cards,min) end if id == 10736540 then return LadyTarget(cards) end if id == 83519853 then return HighSallyTarget(cards) end if id == 53550467 then return DrystanTarget(cards) end if id == 57690191 then return BrothersTarget(cards,min) end if id == 21223277 then return R4torigusTarget(cards,max) end if id == 10613952 then return R5torigusTarget(cards,c) end if id == 55742055 then return TableTarget(cards) end if id == 13391185 then return ChadTarget(cards) end if id == 30575681 then return BedwyrTarget(cards) end if id == 95772051 then return BlackSallyTarget(cards,c) end if id == 66970385 then return ChapterTarget(cards) end if id == 93085839 then return EachtarTarget(cards) end if id == 73359475 then return PeredurTarget(cards) end if id == 68618157 then return AmaterasuTarget(cards) end return nil end function ChainCaliburn() OPTSet(23562407) SetMultiple(23562407) return true end function ChainArf() OPTSet(83438826) SetMultiple(83438826) return true end function ChainDestiny() OPTSet(07452945) SetMultiple(07452945) return true end function ChainGallatin(c) OPTSet(14745409) SetMultiple(14745409) GlobalGallatinTurn[c.cardid]=Duel.GetTurnCount() return true end function TableSummon() return OverExtendCheck() or HasID(AIHand(),95772051,true) or HasID(AIHand(),93085839,true) or HasID(AIHand(),57690191,true) or HasID(AIHand(),92125819,true) end function ChainAmaterasu() if RemovalCheck(68618157) then return true end if NegateCheck(68618157) then return true end if Duel.GetTurnPlayer()==1-player_ai then return Duel.GetCurrentPhase()==PHASE_END end end function MerlinFilter(c) return c:IsSetCard(0x107a) and c:IsType(TYPE_MONSTER) and c:IsPosition(POS_FACEUP) and FilterLocation(c,LOCATION_MZONE) and c:IsControler(player_ai) and (FieldCheck(c:GetLevel(),NobleMonsterFilter)>0 or c:GetLevel()==4 and HasID(AIMon(),10736540,true,nil,nil,POS_FACEUP)) end function UseMerlinBP() if Duel.GetTurnPlayer() == player_ai and ExpectedDamage(2)==0 then return true end end function ChainMerlin() local cg = RemovalCheck() local tg = Duel.GetChainInfo(Duel.GetCurrentChain(), CHAININFO_TARGET_CARDS) if cg and EffectCheck(1-player_ai) then if tg and tg:GetCount()>0 then GlobalMerlinID ={} for i=1,tg:GetCount() do tg=tg:Filter(MerlinFilter,nil) if tg then tg=tg:GetMaxGroup(Card.GetAttack) end local c=nil if tg then c=tg:GetFirst() end if c then GlobalMerlinID[i]=c:GetCode() tg:RemoveCard(c) end end return #GlobalMerlinID>0 elseif cg and cg:GetCount()==1 then GlobalMerlinID ={} for i=1,cg:GetCount() do local c=cg:Filter(MerlinFilter,nil):GetMaxGroup(Card.GetAttack):GetFirst() if c then GlobalMerlinID[i]=c:GetCode() cg:RemoveCard(c) end end return #GlobalMerlinID>0 end end if IsBattlePhase() then if Duel.GetTurnPlayer() == player_ai then if ExpectedDamage(2)==0 then --return true end else local source = Duel.GetAttacker() local target = Duel.GetAttackTarget() if WinsBattle(source,target) then GlobalMerlinID = {target:GetCode()} return true end end end return false end function NobleChain(cards) if HasID(cards,03580032) and ChainMerlin() then return {1,CurrentIndex} end if HasIDNotNegated(cards,68618157) and ChainAmaterasu() then return {1,CurrentIndex} end if HasID(cards,23562407) and ChainCaliburn() then return {1,CurrentIndex} end if HasID(cards,83438826) and ChainArf() then return {1,CurrentIndex} end if HasID(cards,07452945) and ChainDestiny() then return {1,CurrentIndex} end if HasID(cards,14745409) and ChainGallatin(cards[CurrentIndex]) then return {1,CurrentIndex} end if HasID(cards,10736540) then -- Lady return {1,CurrentIndex} end if HasIDNotNegated(cards,83519853) then -- High Sally return {1,CurrentIndex} end if HasID(cards,21223277) then -- R4torigus return {1,CurrentIndex} end if HasID(cards,10613952) then -- R5torigus return {1,CurrentIndex} end if HasID(cards,55742055,false,891872883) then -- Table draw return {1,CurrentIndex} end if HasID(cards,55742055,false,891872880) then -- Table dump return {1,CurrentIndex} end if HasID(cards,55742055,false,891872882) then -- Table recover return {1,CurrentIndex} end if HasID(cards,55742055,false,891872881) and TableSummon() then -- Table summon return {1,CurrentIndex} end if HasIDNotNegated(cards,57690191) and ChainBrothers() then GlobalNobleSS = Duel.GetTurnCount() return {1,CurrentIndex} end if HasID(cards,19748583) and ChainGwen() then return {1,CurrentIndex} end if HasID(cards,30575681) and ChainBedwyr() then return {1,CurrentIndex} end return nil end function HasGwen(c) return NobleMonsterFilter(c) and FilterAttribute(c,ATTRIBUTE_DARK) and HasID(c:get_equipped_cards(),19748583,true) end function GwenFilter(c,atk) -- for attack boosts return Affected(c,TYPE_SPELL) and DestroyFilter(c,true) and DestroyCountCheck(c,TYPE_SPELL,false) and atk<c.attack end function ChainGwen() local source = Duel.GetAttacker() local target = Duel.GetAttackTarget() if source and target then if source:IsControler(player_ai) then target = Duel.GetAttacker() source = Duel.GetAttackTarget() else end if (target:IsPosition(POS_ATTACK) and source:IsPosition(POS_ATTACK) and (source:GetAttack() > target:GetAttack() or source:GetAttack() == target:GetAttack() and not target:IsHasEffect(EFFECT_INDESTRUCTIBLE_COUNT)) or target:IsPosition(POS_ATTACK) and source:IsPosition(POS_DEFENSE) and source:GetDefense() >= target:GetAttack() or target:IsPosition(POS_DEFENSE) and source:IsPosition(POS_ATTACK) and source:GetAttack() >= target:GetDefense() or source:IsPosition(POS_FACEDOWN) and not target:IsCode(83519853) or source:IsHasEffect(EFFECT_INDESTRUCTABLE_BATTLE) or source:IsHasEffect(EFFECT_INDESTRUCTABLE_COUNT)) and not source:IsHasEffect(EFFECT_IMMUNE_EFFECT) and not source:IsHasEffect(EFFECT_INDESTRUCTABLE_EFFECT) then return true end end return false end function NobleEffectYesNo(id,card) local result = nil if id==23562407 and ChainCaliburn() then result = 1 end if id==83438826 and ChainArf() then result = 1 end if id==07452945 and ChainDestiny() then result = 1 end if id==14745409 and ChainGallatin(card) then result = 1 end if id == 10736540 or id == 83519853 -- Lady, High Sally then result = 1 end if id == 21223277 or id == 10613952 then -- R4torigus, R5torigus result = 1 end if id == 55742055 and card.description == 891872883 then -- Table Draw result = 1 end if id == 55742055 and card.description == 891872880 then -- Table Dump result = 1 end if id == 55742055 and card.description == 891872882 then -- Table Recover result = 1 end if id == 55742055 and card.description == 891872881 and TableSummon() then -- Table Summon result = 1 end if id == 57690191 and ChainBrothers() then result = 1 end if id == 19748583 and ChainGwen() then result = 1 end if id == 30575681 then -- Bedwyr Dump result = 1 end return result end NobleAtt={ 95772051, -- Black Sally 19680539, -- Gawayn 53550467, -- Drystan 59057152, -- Medraut 47120245, -- Borz 92125819, -- Artorigus 73359475, -- Peredur 03580032, -- Merlin 30575681, -- Bedwyr 48009503, -- Gandiva 82944432, -- Blade Armor Ninja 60645181, -- Excalibur 21223277, -- R4torigus 10613952, -- R5torigus 83519853, -- High Sally } NobleDef={ 93085839, -- Eachtar 13391185, -- Chad 57690191, -- Brothers 19748583, -- Gwen 10736540, -- Lady } function NoblePosition(id,available) result = nil for i=1,#NobleAtt do if NobleAtt[i]==id then result=POS_FACEUP_ATTACK end end for i=1,#NobleDef do if NobleDef[i]==id then result=POS_FACEUP_DEFENSE end end if id == 93085839 and Duel.GetCurrentPhase()==PHASE_MAIN1 and GlobalBPAllowed and (GwenCheck() or OppGetStrongestAttDef()<1600) then result=POS_FACEUP_ATTACK end return result end
function CreateInputs(a_ClassName, a_FunctionName, a_Params) local inputs = {} for _, tbParams in ipairs(a_Params) do local tbTemp = CreateValidParams(a_ClassName, a_FunctionName, tbParams) if tbTemp == nil then LOG(string.format("%s, %s", a_ClassName, a_FunctionName)) Abort("Got nil, expected a table!") end local key = table.concat(tbParams, ", ") tbTemp.key = key table.insert(inputs, tbTemp) end -- Add IsStatic flag, if necessary for i = 1,#inputs do -- Add IsStatic flag if a_Params[i].IsStatic then inputs[i].IsStatic = true end end -- If we are not fuzzing. Check if a param has value nil if not(g_IsFuzzing) then for i = 1,#inputs do for index, param in ipairs(inputs[i]) do if param == "nil" then -- Not handled for now if a_Params[i][index] == "..." or a_Params[i][index] == "<unknown>" or a_Params[i][index] == "any" or a_Params[i][index] == "cBlockArea" or a_Params[i][index] == "cClientHandle" or a_Params[i][index] == "cEntity" or a_Params[i][index] == "cIniFile" or a_Params[i][index] == "cMonster" or a_Params[i][index] == "cPlayer" or a_Params[i][index] == "cTeam" or a_Params[i][index] == "function" or a_Params[i][index] == "HTTPRequest" then return nil end LOG(string.format("%s, %s", a_ClassName, a_FunctionName)) Abort("The param " .. a_Params[i][index] .. " has value nil.") end end end return inputs end local tbRes = {} for _, tb in ipairs(inputs) do table.insert(tbRes, CopyTable(tb)) end CreateAndFill(inputs, "nil", tbRes) CreateAndFill(inputs, "true", tbRes) CreateAndFill(inputs, "false", tbRes) CreateAndFill(inputs, "E_BLOCK_STONE_BRICKS", tbRes) CreateAndFill(inputs, "E_ITEM_BED", tbRes) CreateAndFill(inputs, "1", tbRes) CreateAndFill(inputs, "{}", tbRes) CreateAndFill(inputs, "\"\"", tbRes) CreateAndFill(inputs, "Vector3d(200, 100, 200)", tbRes) CreateAndFill(inputs, "Vector3i(200, 100, 200)", tbRes) CreateAndFill(inputs, "Vector3f(200, 100, 200)", tbRes) CreateAndFill(inputs, "Vector3d(200, -100, 200)", tbRes) CreateAndFill(inputs, "Vector3i(200, -100, 200)", tbRes) CreateAndFill(inputs, "Vector3f(200, -100, 200)", tbRes) CreateAndFill(inputs, "Vector3d(200, 1000, 200)", tbRes) CreateAndFill(inputs, "Vector3i(200, 1000, 200)", tbRes) CreateAndFill(inputs, "Vector3f(200, 1000, 200)", tbRes) CreateAndFill(inputs, "'text'", tbRes) CreateAndFill(inputs, "' '", tbRes) CreateAndFill(inputs, "0.0000000000000000000000000000000000000000000000000001", tbRes) CreateAndFill(inputs, "-0.0000000000000000000000000000000000000000000000000001", tbRes) CreateAndFill(inputs, "'\\n'", tbRes) CreateAndFill(inputs, "'\\r'", tbRes) CreateAndFill(inputs, "'\\t'", tbRes) CreateAndFill(inputs, "''", tbRes) CreateAndFill(inputs, "'\\n1\\n2\\n3'", tbRes) CreateAndFill(inputs, "'\\n\\r\\t\\0'", tbRes) -- Char characters -- for i = 1, 255 do -- CreateAndFill(inputs, "string.char(" .. tostring(i) .. ")", tbRes) -- end -- Pass a very, very long string -- CreateAndFill(inputs, "'" .. g_Infinity .. "'", tbRes) -- Don't use this two params. Using them will always crash the server, #4408 -- CreateAndFill(inputs, "'nan'", tbRes) -- CreateAndFill(inputs, "'infinity'", tbRes) -- This params will overload the chunk generator and can cause false positives due to a deadlock -- for _ = 1, 10 do -- CreateAndFill(inputs, math.random(-10000, 10000), tbRes) -- end -- Testing this params can take a long time -- for i = -100, 100 do -- CreateAndFill(inputs, i, tbRes) -- end return tbRes end function CreateAndFill(a_Inputs, a_Value, a_Output) for _, tbInput in ipairs(a_Inputs) do local tmp = tbInput for i = 1, #tmp do local val = tmp[i] tmp[i] = a_Value table.insert(a_Output, CopyTable(tmp)) tmp[i] = val end end end function CreateValidParams(a_ClassName, a_FunctionName, a_Params) if g_Params[a_ClassName] ~= nil then if g_Params[a_ClassName][a_FunctionName] ~= nil then if type(g_Params[a_ClassName][a_FunctionName]) == "string" or type(g_Params[a_ClassName][a_FunctionName]) == "number" then if #a_Params > 1 then LOG(string.format("%s, %s", a_ClassName, a_FunctionName)) Abort("Expected a table with " .. #a_Params .. " items") end return { g_Params[a_ClassName][a_FunctionName] } elseif type(g_Params[a_ClassName][a_FunctionName]) == "table" then return g_Params[a_ClassName][a_FunctionName] elseif type(g_Params[a_ClassName][a_FunctionName]) == "function" then return g_Params[a_ClassName][a_FunctionName](a_Params) end LOG(string.format("%s, %s", a_ClassName, a_FunctionName)) Abort("Type not handled: " .. type(g_Params[a_ClassName][a_FunctionName])) end end local inputs = {} for index, param in ipairs(a_Params) do if g_EnumValues[param] ~= nil then inputs[index] = g_EnumValues[param] elseif (string.find(param, "#") ~= nil) or (string.find(param, "^e") ~= nil) or (string.find(param, "*") ~= nil) then inputs[index] = GetEnumValue(param) elseif param == "cUUID" then inputs[index] = "cUUID()" elseif param == "string" then if inputs[index] == nil then -- If reached here return JustAString. -- If an error occurs add special handling above inputs[index] = "'JustAString'" end elseif param == "number" then inputs[index] = 1 elseif param == "boolean" then inputs[index] = "false" elseif param == "cItem" then inputs[index] = "cItem(1, 2)" elseif param == "function" then inputs[index] = "nil" elseif param == "cPlayer" then inputs[index] = "nil" elseif param == "cClientHandle" then inputs[index] = "nil" elseif param == "cMonster" then inputs[index] = "nil" elseif param == "cItems" then inputs[index] = "cItems()" elseif param == "table" then inputs[index] = "{ }" elseif param == "Vector3i" then inputs[index] = "Vector3i(1, 1, 1)" elseif param == "Vector3d" then inputs[index] = "Vector3d(1, 1, 1)" elseif param == "Vector3f" then inputs[index] = "Vector3f(1, 1, 1)" elseif param == "cEntity" then inputs[index] = "nil" elseif param == "cBoundingBox" then inputs[index] = "cBoundingBox(Vector3d(2, 1, 2), Vector3d(10, 256, 10))" elseif param == "cCuboid" then inputs[index] = "cCuboid(10, 10, 10)" elseif param == "cWorld" then inputs[index] = "cRoot:Get():GetWorld('world')" elseif param == "cEnchantments" then inputs[index] = "cEnchantments()" elseif param == "cBlockArea" then inputs[index] = "nil" elseif param == "..." then inputs[index] = "nil" elseif param == "HTTPRequest" then inputs[index] = "nil" elseif param == "cCompositeChat" then inputs[index] = "cCompositeChat()" elseif param == "cIniFile" then inputs[index] = "nil" elseif param == "cTeam" then inputs[index] = "nil" elseif param == "any" then -- Different source different entity inputs[index] = "nil" elseif param == "<unknown>" then -- TODO inputs[index] = "nil" elseif param == "cCraftingGrid" then inputs[index] = "nil" end if inputs[index] == nil then LOG(string.format("%s, %s", a_ClassName, a_FunctionName)) Abort("Param not handled: " .. param) end end return inputs end
---@class ui.SplitViewV:ccui.Layout local M = class('ui.SplitViewV', ccui.Layout) function M:ctor(top, bottom, param) param = param or {} table.deploy(self, param, { color = cc.WHITE, size = cc.size(100, 100), margin = { l = 0, r = 0, b = 0, t = 0, m = 0 }, }) ---@type ccui.Widget self._top = top ---@type ccui.Widget self._bottom = bottom if self._top then self._top:addTo(self) end if self._bottom then self._bottom:addTo(self) end self:setBackGroundColorType(1):setBackGroundColor(self.color) self._tparam = param.tparam or {} self._bparam = param.bparam or {} self:setContentSize(self.size) end function M:setTop(widget, param) CC_SET_PROP_CHILDREN(self, '_top', widget) if param then self._tparam = require('cc.ui.helper').parseConstrainParam(param) end self:updateLayout() end function M:setBottom(widget, param) CC_SET_PROP_CHILDREN(self, '_bottom', widget) if param then self._bparam = require('cc.ui.helper').parseConstrainParam(param) end self:updateLayout() end function M:setMargin(l, r, b, t, m) l = l or 0 r = r or l b = b or l t = t or l m = m or l self.margin = { l = l, r = r, b = b, t = t, m = m } end function M:_setSize(th, bh, w) local xx = self.margin.l local yy = self.margin.t if self._top then self._top:setContentSize(cc.size(w, th)):alignLeft(xx):alignTop(yy) end yy = yy + th + self.margin.m if self._bottom then self._bottom:setContentSize(cc.size(w, bh)):alignLeft(xx):alignTop(yy) end end local function _to_px(val, total) if val and val <= 1 then return val * total end return val end ---@param size size_table function M:setContentSize(size) self.super.setContentSize(self, size) self.size = size local ww, hh = size.width, size.height ww = ww - self.margin.l - self.margin.r hh = hh - self.margin.b - self.margin.t - self.margin.m if ww < 0 then ww = 0 end if hh < 0 then hh = 0 end local tpref = _to_px(self._tparam.preffered, ww) local bpref = _to_px(self._bparam.preffered, ww) local tmin = _to_px(self._tparam.min, ww) or tpref or 0 local tmax = _to_px(self._tparam.max, ww) or tpref or ww local bmin = _to_px(self._bparam.min, ww) or bpref or 0 local bmax = _to_px(self._bparam.max, ww) or bpref or ww if tpref then tpref = math.clamp(tpref, tmin, tmax) end if bpref then bpref = math.clamp(bpref, bmin, bmax) end local th, bh = require('cc.ui.helper').solveConstrain(hh, tpref, tmin, tmax, bpref, bmin, bmax) self:_setSize(th, bh, ww) end function M:updateLayout() self:setContentSize(self:getContentSize()) end return M
local table_remove = table.remove local table_concat = table.concat local table_insert = table.insert local table = setmetatable( {}, { __index = table, __call = function(self, onTable) return setmetatable(self.copy(onTable), {__index = table}) end } ) function table.map(t, mapFn) assert(type(t) == "table", "Argument #1 to table.map - expected table got " .. type(t)) assert(type(mapFn) == "function", "Argument #2 to table.map - expected function got " .. type(mapFn)) local mapped = {} for i = 1, #t do local nextValue, nextKey = mapFn(t[i], i) if nextKey then mapped[nextKey] = nextValue else table.insert(mapped, nextValue) end end return mapped end function table.filter(t, filterFn) assert(type(t) == "table", "Argument #1 to table.filter - expected table got " .. type(t)) assert(type(filterFn) == "function", "Argument #2 to table.filter - expected function got " .. type(filterFn)) local filtered = {} for i = 1, #t do local value = t[i] if filterFn(value) then table_insert(filtered, value) end end return filtered end function table.contains(t, value) assert(type(t) == "table", "Argument #1 to table.contains - expected table got " .. type(t)) assert(value ~= nil, "Argument #2 to table.contains - expected non-nil value got " .. type(value)) for i = 1, #t do local tvalue = t[i] if tvalue == value then return true end end return false end function table.find(t, findFn) assert(type(t) == "table", "Argument #1 to table.find - expected table got " .. type(t)) assert(type(findFn) == "function", "Argument #2 to table.find - expected function got " .. type(findFn)) for i = 1, #t do local value = t[i] if findFn(value, i) then return value, i end end end local indent = 0 local function table_to_str(t, options) options = options or {} local prettyPrint = options.pretty and options.whitespace or nil local displayTableString = options.showTableString local values = {} local char = type(prettyPrint) == "string" and prettyPrint or "\t" for k, value in next, t do local isNumericKey = type(k) == "number" if type(value) == "table" then indent = indent + 1 if displayTableString then -- luacov: enable -- luacov: disable value = "(" .. tostring(value) .. ") " .. table_to_str(value, options) else value = table_to_str(value, options) end indent = indent - 1 elseif type(value) == "string" then value = '"' .. value .. '"' elseif type(value) == "function" then value = "<function>" elseif typeof(value) == "Instance" then value = "<" .. value:GetFullName() .. ">" elseif type(value) == "userdata" then value = "<" .. tostring(value) .. ">" end table.insert( values, (prettyPrint and "%s" .. char .. "%s = %s" or "%s%s = %s"):format( prettyPrint and (char):rep(indent) or "", isNumericKey and "[" .. tostring(k) .. "]" or k, tostring(value) ) ) end return "{" .. (prettyPrint and "\n" or "") .. table_concat(values, prettyPrint and ",\n" or ", ") .. (prettyPrint and "\n" .. (char):rep(indent) or "") .. "}" end function table.tostring(t, options) if typeof(options) == "table" then return table_to_str(t, options) else return table_to_str(t, {pretty = options ~= nil, whitespace = type(options) == "string" and options or "\t"}) end end -- Improved table.concat function table.concat(t, sep) local values = {} for i = 1, #t do local value = t[i] if type(value) == "table" then table_insert(values, "[ " .. table.concat(value, sep) .. " ]") else table_insert(values, tostring(value)) end end return table_concat(values, sep) end -- Improved table.remove function table.remove(t, query) if type(query) == "number" then return table_remove(t, query) elseif type(query) == "function" then for index, value in next, t do if (query(value, index)) then table_remove(t, index) end end else for index, value in next, t do if (value == query) then return table_remove(t, index) end end end end function table.copy(t) assert(type(t) == "table", "Invalid Argument #1 to table.copy - expected table got" .. typeof(t)) local newTable = {} for key, value in next, t do if type(value) == "table" then newTable[key] = table.copy(value) else newTable[key] = value end end return newTable end function table.sub(tbl, start, finish) assert(type(tbl) == "table", "Invalid Argument #1 to table.copy - expected table got" .. typeof(tbl)) assert( type(start) == "number" or start == nil, "Invalid Argument #2 to table.copy - expected number got" .. typeof(start) ) assert( type(finish) == "number" or finish == nil, "Invalid Argument #3 to table.copy - expected number got" .. typeof(finish) ) finish = finish or #tbl start = start or 1 local result = {} for i = start, finish do table_insert(result, tbl[i]) end return result end function table.truncate(t) assert(type(t) == "table", "Argument #1 to table.truncate - expected table got " .. typeof(t)) for i = 1, #t do if t[i] == nil then table.remove(t, i) -- luacheck: ignore i = i - 1 end end end function table.insert(t, value, rep) assert(type(t) == "table", "Argument #1 to table.insert - expected table got " .. typeof(t)) assert(type(rep) == "number" or rep == nil, "Argument #3 to table.insert - expected number got " .. typeof(rep)) if rep then for _ = 1, #rep do --table_insert(t, value) t[#t + 1] = value end else t[#t + 1] = value end end function table.join(...) local tables = {...} local newTable = {} for _, t in next, tables do assert(type(t) == "table") for k, v in next, t do if (type(k) == "string") then newTable[k] = v else table_insert(newTable, v) end end end return newTable end function table.keys(tbl) local targetTable = {} for key in next, tbl do table.insert(targetTable, key); end return targetTable end function table.values(tbl) local targetTable = {} for _, value in next, tbl do table.insert(targetTable, value); end return targetTable end return table
GameObject = { _instCount = 0, components = {}, Transform = nil, Name = nil, AddComponent = function(self, component) if component ~= nil then table.insert(self.components, component) component.Owner = self print("Added component") else print("Component was nil") end end, RemoveComponent = function(self, component) for idx, value in ipairs(self.components) do if value == component then table.remove(self.components, idx) component.Owner = nil return true end end return false end, Start = function(self) for _, value in pairs(self.components) do value:OnStart() end end, Update = function(self) for _, value in pairs(self.components) do value:OnUpdate() end end, new = function(self, name, obj) obj = obj or {} setmetatable(obj, self) self.__index = self name = name or obj.Name or "GameObject_" .. GameObject._instCount obj.Name = tostring(name) GameObject._instCount = GameObject._instCount + 1; if obj.Transform == nil then obj.Transform = Transform() end return obj end } Component = { Owner = nil, OnStart = function(self) print("OnStart called from Component") end, OnUpdate = function(self) print("OnUpdate called from Component") end, new = function(self, obj) obj = obj or {} setmetatable(obj, self) self.__index = self return obj end }
--[[ --]] local c = cc c.affineTransformMake = function (a, b, c, d, tx, ty) local t = {a = a, b = b, c = c, d = d, tx = tx, ty = ty} return t end c.pointApplyAffineTransform = function(point, t) local x = t.a*point.x + t.c*point.y + t.tx local y = t.b*point.x + t.d*point.y + t.ty return cc.p(x, y) end c.sizeApplyAffineTransform = function (size, t) local width = t.a*size.width + t.c*size.height local height = t.b*size.height + t.d*size.height return cc.size(width, height) end
--local proto = require('app.net.proto') local tools = {} local display = require('cocos.framework.display') local transition = require('cocos.framework.transition') function tools.flyAction(path, sPos, ePos, func) local app = require("app.App"):instance() local loop = 20 if loop <= 0 then loop = 1 end for i = 1,loop do local spr = cc.Sprite:create(path) app.layers.ui:addChild(spr) spr:setPosition(sPos) local delay = 0.2 + math.random(5) * 0.1 local mv = cc.MoveTo:create(delay,ePos) spr:runAction(cc.Sequence:create(mv,cc.CallFunc:create(function() if func and i == 1 then func() end end),cc.RemoveSelf:create())) spr:setScale(0.1) local sc = cc.ScaleTo:create(delay * 0.9,1.0) spr:runAction(sc) end end function tools.showRemind(text, delay) delay = delay or 1.9 local layer = cc.Layer:create() layer:ignoreAnchorPointForPosition(false) layer:setAnchorPoint(cc.p(0.5, 0.5)) local label = cc.Label:createWithTTF(text,'views/font/fangzheng.ttf',35, cc.size(620,0),cc.TEXT_ALIGNMENT_CENTER) label:setOpacity(0) local size = label:getContentSize() layer:setContentSize(cc.size(size.width + 10, size.height + 10)) layer:setPosition(cc.p(display.cx, display.cy + 50)) local image = ccui.ImageView:create('views/public/123.png') label:setPosition(cc.p((size.width + 10) / 2, (size.height + 10) / 2)) image:setPosition(cc.p((size.width + 10) / 2, (size.height + 10) / 2)) layer:addChild(image) layer:addChild(label) layer:runAction(cc.Sequence:create({ cc.CallFunc:create(function() layer:runAction(cc.FadeTo:create(0.4, 190)) label:runAction(cc.FadeIn:create(0.4)) end), -- cc.DelayTime:create(0.4), cc.DelayTime:create(delay), -- cc.CallFunc:create(function() -- layer:runAction(cc.MoveTo:create(0.4, cc.p(display.cx, display.height + 20))) -- end), cc.CallFunc:create(function() layer:runAction(cc.FadeOut:create(0.2)) label:runAction(cc.FadeOut:create(0.2)) end), cc.DelayTime:create(0.2), cc.RemoveSelf:create() })) require('app.App'):instance().layers.top:addChild(layer) return label end function tools.showMsgBox(title, content, btnCount) return require('app.App'):instance().layers.top:switch('MsgBoxController', title or '', content or '', btnCount) end function tools.hideMsgBox() return require('app.App'):instance().layers.top:switch('MsgBoxController') end function tools.numberChangeTo(label, org, dis,time) tools.schedule(label, function() label:setString(org) org = org + 1 if org > dis then label:stopAllActions() end end, time) end function tools.labelChange(label, string) label:setString(string) label:stopAllActions() label:runAction(transition.sequence({ cc.ScaleTo:create(0.1, 1.5), cc.ScaleTo:create(0.1, 1.0), })) end function tools.nodeScaleAction(node) node:stopAllActions() node:runAction(cc.RepeatForever:create(transition.sequence({ cc.ScaleTo:create(0.3, 1.3), cc.ScaleTo:create(0.3, 1.0), }))) end function tools.schedule(node,callback,interval) local seq = transition.sequence({ cc.DelayTime:create(interval), cc.CallFunc:create(callback), }) local action = cc.RepeatForever:create(seq) node:runAction(action) return action end function tools.tableInclude(tb, value) for _, v in pairs(tb) do if v == value then return true end end return false end function tools.tableRemove(tbl, key) for i = 1,#tbl do if tbl[i] == key then table.remove(tbl,i) break end end end function tools.actionRestore(rcall) local function began(_) return true end local function ended(_) if rcall then rcall() end end local winSize = cc.Director:getInstance():getWinSize() local cancel = cc.LayerColor:create(cc.c4b(0,0,0,200),winSize.width,winSize.height) local listener = cc.EventListenerTouchOneByOne:create() listener:setSwallowTouches(true) listener:registerScriptHandler(ended,cc.Handler.EVENT_TOUCH_ENDED ) listener:registerScriptHandler(began,cc.Handler.EVENT_TOUCH_BEGAN ) local eventDispatcher = cancel:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, cancel) return cancel end function tools.gcnode(func) local node = display.newNode():hide() node:registerScriptHandler(function(event) if "exit" == event then func() end end) return node end function tools.androidBackKey(runner) -- avoid unmeant back runner:setKeypadEnabled(true) runner:addNodeEventListener(cc.KEYPAD_EVENT, function (event) if event.key == "back" then print("press back") if not runner.__is_open then local window = require('app.views.MessageBoxShowView').new():show() runner.__is_open = true local ok = tools.scaleButton({ img = "public/Button/GreenButtonShort.png", text = TEXT.YES, size = 30 }):onButtonClicked(function() --audio.playSound("Audio/Effect/BtnClick.mp3", false) window:close() end ) local cancel = tools.scaleButton({ img = "public/Button/RedButtonShort.png", text = TEXT.NO, size = 30 }):onButtonClicked(function() --cc.Director:getInstance():endToLua() --audio.stopAllSounds() --audio.stopMusic(true) app:exit() end ) window:onClose(function() runner.__is_open = false end) window:setString( TEXT.PLAYAGAIN ) window:setDown({cancel,{x=100,y=0}, ok}) end end end) end function tools.numberToStander(num) local result = "" local needSign = false while num / 1000 >= 1 do needSign = true if result == "" then result = string.format("%03d", (num % 1000)) else result = string.format("%03d", (num % 1000))..","..result end num = math.floor(num / 1000) end if needSign then result = (num % 1000)..","..result else result = (num % 1000)..result end return result end local function loadCsb(csb) print('Loading "'..csb..'"...') if not cc.FileUtils:getInstance():isFileExist(csb) then print('Not exists. Skippd.') return cc.Node:create() end local node = cc.CSLoader:createLocalizedNode(csb) if not node then print(string.format('Failed to load View node from "%s" ', csb)) return cc.Node:create() end return node end function tools.loadChatNode(func, noOpacity) local node = loadCsb("views/teach/ChatNode.csb") node:setPositionX(display.cx) local layer = node:getChildByName("layer") layer:setVisible(true) layer:addClickEventListener(function() func() end) layer:setContentSize(cc.size(display.width, display.height)) if noOpacity then layer:setOpacity(0) end require('app.App'):instance().layers.top:addChild(node) return node end function tools.loadChatContent(chatNode, cfg) local app = require("app.App"):instance() local user = app.session.user local left = chatNode:getChildByName("left") local right = chatNode:getChildByName("right") if cfg.l == "" then cfg.l = "mainhero_"..(user:getMainHeroIndex() - 1).."_0" end if cfg.r == "" then cfg.r = "mainhero_"..(user:getMainHeroIndex() - 1).."_0" end left:loadTexture("heros/"..cfg.l..".png") left:setColor(cfg.pos == 1 and cc.c3b(255,255,255) or cc.c3b(88,88,88)) right:loadTexture("heros/"..cfg.r..".png") right:setColor(cfg.pos == 2 and cc.c3b(255,255,255) or cc.c3b(88,88,88)) if cfg.name == "" then chatNode:getChildByName("name"):setString(user.name..":") else chatNode:getChildByName("name"):setString(cfg.name..":") end chatNode:getChildByName("content"):setString(cfg.ct) end function tools.loadArrow(pos, func) local node = loadCsb("views/teach/DownArrow.csb") local layer = node:getChildByName("layer") local arrow = node:getChildByName("arrow") arrow:setPosition(pos) layer:setVisible(true) layer:addClickEventListener(function() func() end) layer:setPosition(cc.p(display.cx,display.cy)) layer:setContentSize(cc.size(display.width, display.height)) arrow:runAction(cc.RepeatForever:create( cc.Sequence:create( cc.MoveTo:create(0.4,cc.p(pos.x, pos.y + 20)), cc.MoveTo:create(0.4,cc.p(pos.x, pos.y)) ) )) require('app.App'):instance().layers.top:addChild(node) return node end function tools.createEditBox(sprite,param,inputSprite,scaleRect) if not param then param = {} end if not inputSprite then inputSprite = 'views/public/shurukuang.png'--'views/exchange/kuang.png' end local sprSize = sprite:getContentSize() local rect = cc.rect(11,11,20,30) if scaleRect then rect = scaleRect end local s9pr = ccui.Scale9Sprite:create(rect,inputSprite) local editbox = ccui.EditBox:create(sprSize, s9pr) editbox:setPosition(cc.p(sprite:getPosition())) editbox:setPlaceHolder(param.defaultString or "") editbox:setPlaceholderFontSize(param.holderSize or 30) editbox:setPlaceholderFontColor(param.holderColor or cc.c3b(255,255,255)) editbox:setFontColor(param.fontColor or cc.c3b(0,0,0)) editbox:setFontSize(param.size or 30) editbox:setMaxLength(param.maxCout or 20) editbox:setInputMode(param.inputMode or cc.EDITBOX_INPUT_MODE_SINGLELINE) editbox:setInputFlag(param.inputFlag or cc.EDITBOX_INPUT_FLAG_INITIAL_CAPS_ALL_CHARACTERS) if param.fontType then editbox:setFontName(param.fontType) end if param.holderfontType then editbox:setPlaceholderFontName(param.holderfontType) end editbox:setAnchorPoint(sprite:getAnchorPoint()) sprite:getParent():addChild(editbox) sprite:removeSelf() return editbox end return tools
description = [[ Attempts to exploit an authentication bypass vulnerability in Adobe Coldfusion servers to retrieve a valid administrator's session cookie. Reference: * APSA13-01: http://www.adobe.com/support/security/advisories/apsa13-01.html ]] --- -- @usage nmap -sV --script http-adobe-coldfusion-apsa1301 <target> -- @usage nmap -p80 --script http-adobe-coldfusion-apsa1301 --script-args basepath=/cf/adminapi/ <target> -- -- @output -- PORT STATE SERVICE -- 80/tcp open http -- | http-adobe-coldfusion-apsa1301: -- |_ admin_cookie: aW50ZXJhY3RpdmUNQUEyNTFGRDU2NzM1OEYxNkI3REUzRjNCMjJERTgxOTNBNzUxN0NEMA1jZmFkbWlu -- -- @args http-adobe-coldfusion-apsa1301.basepath URI path to administrator.cfc. Default: /CFIDE/adminapi/ -- --- author = "Paulino Calderon <calderon@websec.mx>" license = "Same as Nmap--See https://nmap.org/book/man-legal.html" categories = {"exploit", "vuln"} local http = require "http" local shortport = require "shortport" local stdnse = require "stdnse" local url = require "url" portrule = shortport.http local DEFAULT_PATH = "/CFIDE/adminapi/" local MAGIC_URI = "administrator.cfc?method=login&adminpassword=&rdsPasswordAllowed=true" --- -- Extracts the admin cookie by reading CFAUTHORIZATION_cfadmin from the header 'set-cookie' -- local function get_admin_cookie(host, port, basepath) local req = http.get(host, port, url.absolute(basepath, MAGIC_URI)) if not req then return nil end for _, ck in ipairs(req.cookies or {}) do stdnse.debug2("Set-Cookie for %q detected in response.", ck.name) if ck.name == "CFAUTHORIZATION_cfadmin" and ck.value:len() > 79 then stdnse.debug1("Extracted cookie:%s", ck.value) return ck.value end end return nil end action = function(host, port) local output_tab = stdnse.output_table() local basepath = stdnse.get_script_args(SCRIPT_NAME..".basepath") or DEFAULT_PATH local cookie = get_admin_cookie(host, port, basepath) if cookie then output_tab.admin_cookie = cookie else return nil end return output_tab end
description = [[ Searches for web virtual hostnames by making a large number of HEAD requests against http servers using common hostnames. Each HEAD request provides a different <code>Host</code> header. The hostnames come from a built-in default list. Shows the names that return a document. Also shows the location of redirections. The domain can be given as the <code>http-vhosts.domain</code> argument or deduced from the target's name. For example when scanning www.example.com, various names of the form <name>.example.com are tried. ]] --- -- @usage -- nmap --script http-vhosts -p 80,8080,443 <target> -- @arg http-vhosts.domain The domain that hostnames will be prepended to, for -- example <code>example.com</code> yields www.example.com, www2.example.com, -- etc. If not provided, a guess is made based on the hostname. -- @arg http-vhosts.path The path to try to retrieve. Default <code>/</code>. -- @arg http-vhosts.collapse The limit to start collapsing results by status code. Default <code>20</code> -- @output -- PORT STATE SERVICE REASON -- 80/tcp open http syn-ack -- | http-vhosts: -- | example.com: 301 -> http://www.example.com/ -- | www.example.com: 200 -- | docs.example.com: 302 -> https://www.example.com/docs/ -- |_images.example.com: 200 -- -- @todo feature: move hostnames to an external file and allow the user to use another one -- @internal: see http://seclists.org/nmap-dev/2010/q4/401 and http://seclists.org/nmap-dev/2010/q4/445 -- -- -- @todo feature: add option report and implement it -- @internal after stripping sensitive info like ip, domain names, hostnames -- and redirection targets from the result, append it to a file -- that can then be uploaded. If enough info is gathered, the names -- will be weighted. It can be shared with metasploit -- -- @todo feature: fill nsedoc -- -- @todo feature: register results for other scripts (external help needed) -- -- @todo feature: grow names list (external help needed) -- author = "Carlos Pantelides" license = "Same as Nmap--See http://nmap.org/book/man-legal.html" categories = { "discovery", "intrusive" } require "http" require "stdnse" require "string" require "shortport" -- List of domains to try. (Will become names like example.com, -- abbot.example.com, admin.example.com, etc.) The list is derived from -- Wikipedia lists of software with a web interface. local HOSTNAMES = { "", "abbot", "admin", "adserver", "alpha", "api", "aptest", "arch", "artifactory", "assembla", "atd", "athena", "atollon", "attask", "attix", "attix5", "automatedqa", "backend", "backup", "bacula", "badboy", "basecamp", "bazaar", "beta", "bitkeeper", "bkp", "branch", "brightwork", "broadwave", "bromine", "bugtracker", "bugzilla", "build", "businessdriver", "campus", "catchlimited", "ccc", "centraldesktop", "cerebro", "civicrm", "clarizen", "clearcase", "clearquest", "clif", "clockingit", "codebeamer", "codendi", "codesourcery", "codeville", "collabtive", "compuware", "concordion", "conformiq", "cppunit", "crm", "cruisecontrol", "cubictest", "cucumber", "cunit", "cvs", "cvsnt", "darcs", "dartenium", "dcvs", "debbugs", "dev", "devel", "development", "devtest", "dieseltest", "digitaltester", "distract", "dolibarr", "dotproject", "dune", "durable", "duxqa", "dynamics", "easy", "egroupware", "eload", "elvior", "empirix", "endeavour", "enterprise", "epesi", "epesibim", "etester", "eventum", "fasttrack", "feng", "firefly", "flumotion", "flyspray", "fogbugz", "foro", "forum", "fossil", "frankenstein", "freecast", "froglogic", "frontend", "ftp", "functional", "functionaltester", "fwptt", "game", "games", "gamma", "gemini", "geniesys", "genietcms", "genius", "git", "glasscubes", "gnats", "goplan", "grinder", "guitar", "gurock", "hammerhead", "hammerora", "harvest", "helix", "help", "helpdesk", "home", "htmlunit", "httpunit", "huddle", "hudson", "hyperoffice", "icecast", "ikiwiki", "images", "incisif", "inflectra", "info", "informup", "intra", "intranet", "issuenet", "isupport", "it", "itcampus", "jabber", "jadeliquid", "jbehave", "jboss", "jcrawler", "jemmy", "jfunc", "jira", "jite", "jmeter", "jotbug", "journyx", "jtest", "jtrack", "junit", "jwebunit", "kayako", "kforge", "kkoop", "launchpad", "liberum", "libresource", "liquidplanner", "liquidtest", "list", "lista", "listas", "listman", "lists", "loadrunner", "magnetic", "mail", "mailman", "mantis", "mantisbt", "manual", "marathon", "matchware", "maven", "mbt", "media", "mercurial", "mercury", "merlin", "messagemagic", "mingle", "mks", "mksintegrity", "mojo", "monotone", "mvn", "nuevosoft", "objentis", "opengoo", "opengroup", "openload", "openproj", "openqa", "opensta", "openwebload", "optimaltest", "orcanos", "origsoft", "otmgr", "otrs", "passmark", "peercast", "perforce", "performancetester", "phpgroupware", "phprojekt", "phpunit", "pivotal", "pjsip", "planisware", "plastic", "postfix", "practitest", "primavera", "principal", "prod", "project", "projecthq", "projectpier", "projectplace", "projectspaces", "projektron", "projistics", "psnext", "pureagent", "pureload", "puretest", "pylot", "qadirector", "qaliber", "qaload", "qamanager", "qatraq", "qmetry", "qmtest", "qpack", "qtest", "qtronic", "qualify", "quickbase", "quicktest", "quicktestpro", "quotium", "rcs", "realese", "redmine", "remedy", "request", "research", "robot", "roundup", "rth", "s3", "sahi", "salome", "sap", "scarab", "sccs", "seam", "seapine", "search", "selenium", "sendmail", "services", "severa", "sharpforge", "shoutcast", "siebel", "silk", "silkcentral", "silkperformer", "simpletest", "simpletestmanagement", "simpleticket", "simulator", "sipp", "sipr", "smartesoft", "smartload", "smartqm", "smartscript", "smartsheet", "soap", "soapui", "software", "softwareresearch", "sourcesafe", "specflow", "spiceworks", "spiratest", "spring", "squish", "staff", "stage", "stagging", "static", "storytestiq", "streaming", "stub", "sugar", "sugarcrm", "supportworks", "svk", "svn", "synergy", "tag", "team", "teamcenter", "teamware", "teamwork", "teamworkpm", "techexcel", "telerik", "tenrox", "test", "test1", "test2", "testbench", "testcase", "testcomplete", "testdirector", "testdrive", "tester", "testing", "testitools", "testlink", "testlog", "testman", "testmanager", "testmaster", "testmasters", "testopia", "testoptimal", "testpartner", "testrail", "testrun", "testsuite", "testtrack", "testuff", "testup", "testworks", "texttest", "tigris", "tomcat", "tplan", "trac", "track", "tracker", "trackersuite", "tricentis", "trunk", "twist", "ubidesk", "unawave", "unreal", "utest", "vault", "verisium", "vnc", "vncrobot", "vperformer", "vpmi", "vtest", "watin", "watir", "web", "web2project", "web2test", "webaii", "webdriver", "webking", "webload", "webspoc", "wiki", "windmill", "winrunner", "wit", "workbook", "workengine", "worklenz", "workspace", "wowza", "wrike", "ws", "www", "www2", "xhtmlunit", "xml-simulator", "xplanner", "xqual", "xstudio", "youtrack", "zentrack", "zephyr", "zoho" } -- uncomment and modify this for shorter scans -- local HOSTNAMES = { -- "", -- "www", -- "docs", -- "images" -- } -- Defines domain to use, first from user and then from host defineDomain = function(host) if stdnse.get_script_args("http-vhosts.domain") then return stdnse.get_script_args("http-vhosts.domain") end name = stdnse.get_hostname(host) if name and name ~= host.ip then local pos = string.find (name, ".",1,true) if not pos then return name end return string.sub (name, pos + 1) end end --- -- Makes a target name with a name and a domain -- @param name string -- @param domain string -- @return string local makeTargetName = function(name,domain) if name == "" and domain == "" then return nil end if name == "" then return domain end if domain == "" then return name end return name .. "." .. domain end --- -- Collapses a result -- key -> table -- @param result table -- @return string local collapse = function(result) local collapsed = {""} local limit = tonumber(stdnse.get_script_args("http-vhosts.collapse")) or 10 for code, group in next, result do if #group > limit then collapsed[#collapsed + 1] = #group .. " names had status " .. code else for _,name in ipairs(group) do collapsed[#collapsed + 1] = name end end end return table.concat(collapsed,"\n") end portrule = shortport.http --- -- Script action -- @param host table -- @param port table action = function(host, port) local service = "http" local domain = defineDomain(host) local path = stdnse.get_script_args("http-vhosts.path") or "/" local result = {} for _,name in ipairs(HOSTNAMES) do local http_response local targetname targetname = makeTargetName(name , domain) if targetname ~= nil then http_response = http.head(host, port, path, {header={Host=targetname}, bypass_cache=true}) if not http_response.status then if not http_response["ERROR"] then result["ERROR"]={} end result["ERROR"][#result["ERROR"] + 1] = targetname else local status = tostring(http_response.status) if not result[status] then result[status]={} end if 300 <= http_response.status and http_response.status < 400 then result[status][#result[status] + 1] = targetname .. " : " .. status .. " -> " .. (http_response.header.location or "(no Location provided)") else result[status][#result[status] + 1] = targetname .. " : " .. status end end end end return collapse(result) end
---@type cobitarray local bitarray = require "colibc.bitarray" return bitarray
local mock_loop = require 'spec.mock_loop' describe("textDocument/hover", function() it("handles string returns", function() mock_loop(function(rpc) local text = [[ local function myfun() return "hi" end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> "hi"\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles number returns", function() mock_loop(function(rpc) local text = [[ local function myfun() return 42 end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> 42\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles true returns", function() mock_loop(function(rpc) local text = [[ local function myfun() return true end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> true\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles false returns", function() mock_loop(function(rpc) local text = [[ local function myfun() return false end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> false\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles nil returns", function() mock_loop(function(rpc) local text = [[ local function myfun() return nil end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> nil\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles table returns #atm", function() mock_loop(function(rpc) local text = [[ local function myfun() return {} end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> <table>\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles function returns", function() mock_loop(function(rpc) local text = [[ local function myfun() return function() end end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> <function>\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles named returns", function() mock_loop(function(rpc) local text = [[ local function myfun() local mystring = "hi" return mystring end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> mystring\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles multireturns", function() mock_loop(function(rpc) local text = [[ local function myfun() return 1, 2, 3 end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> 1, 2, 3\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("handles multireturns with multiple sites", function() mock_loop(function(rpc) local text = [[ local function myfun() if ok then return ok else return nil, "oops" end end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'myfun() -> ok | nil, "oops"\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("deduplicates function return names", function() mock_loop(function(rpc) local text = [[ local function branchy() local myvar if true then return myvar else return myvar end end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'branchy() -> myvar\n'} }, out) callme = true end) assert.truthy(callme) end) end) it("deduplicates function return literals", function() mock_loop(function(rpc) local text = [[ local function branchy() local myvar if true then return "yeah" else return "yeah" end return "nah" end ]] local doc = { uri = "file:///tmp/fake.lua" } rpc.notify("textDocument/didOpen", { textDocument = {uri = doc.uri, text = text} }) local callme rpc.request("textDocument/hover", { textDocument = doc, position = {line = 0, character = 16} }, function(out) assert.same({ contents = {'branchy() -> "yeah" | "nah"\n'} }, out) callme = true end) assert.truthy(callme) end) end) end)
-- Copyright (c) 2021 Trevor Redfern -- -- This software is released under the MIT License. -- https://opensource.org/licenses/MIT local indexOf = require "moonpie.tables.index_of" return function(tbl, item) local i = indexOf(tbl, item) table.remove(tbl, i) return tbl end
local L --------------------------- -- Ra'wani Kanae/Frida Ironbellows (Both) -- -- Same exact enoucnter, diff names --------------------------- L= DBM:GetModLocalization(2344)--Ra'wani Kanae (Alliance) L= DBM:GetModLocalization(2333)--Frida Ironbellows (Horde) --------------------------- -- King Grong/Grong the Revenant (Both) -- --------------------------- L= DBM:GetModLocalization(2325)--King Grong (Horde) L= DBM:GetModLocalization(2340)--Grong the Revenant (Alliance) --------------------------- -- Grimfang and Firecaller/Flamefist and the Illuminated (Both) -- -- Same exact enoucnter, diff names --------------------------- L= DBM:GetModLocalization(2323)--Grimfang and Firecaller (Alliance) L= DBM:GetModLocalization(2341)--Flamefist and the Illuminated (Horde) --------------------------- -- Opulence (Alliance) -- --------------------------- L= DBM:GetModLocalization(2342) L:SetWarningLocalization({ }) L:SetTimerLocalization({ }) L:SetOptionLocalization({ }) L:SetMiscLocalization({ Bulwark = "Bulwark", Hand = "Hand" }) --------------------------- -- Loa Council (Alliance) -- --------------------------- L= DBM:GetModLocalization(2330) L:SetMiscLocalization({ BwonsamdiWrath = "Well, if ya so eager for death, ya shoulda come see me sooner!", BwonsamdiWrath2 = "Sooner or later... everybody serves me!", Bird = "Bird" }) --------------------------- -- King Rastakhan (Alliance) -- --------------------------- L= DBM:GetModLocalization(2335) L:SetOptionLocalization({ AnnounceAlternatePhase = "Show general warnings for phase you aren't in as well (timers will always be shown regardless of this option)" }) --------------------------- -- High Tinker Mekkatorgue (Horde) -- --------------------------- L= DBM:GetModLocalization(2332) --------------------------- -- Sea Priest Blockade (Horde) -- --------------------------- L= DBM:GetModLocalization(2337) --------------------------- -- Jaina Proudmoore (Horde) -- --------------------------- L= DBM:GetModLocalization(2343) L:SetOptionLocalization({ ShowOnlySummary2 = "Hide player names on reverse range check and show only the summary info (the total nearby player count)", InterruptBehavior = "Set elemental interrupt behavior (Will override everyone elses setting if you are raid leader)", Three = "3 person rotation ",--Default Four = "4 person rotation ", Five = "5 person rotation ", SetWeather = "Automatically turn weather density setting to lowest when boss is engaged and restore on combat end", }) L:SetMiscLocalization({ Port = "port side", Starboard = "starboard side", Freezing = "Freezing in %s" }) ------------- -- Trash -- ------------- L = DBM:GetModLocalization("ZuldazarRaidTrash") L:SetGeneralLocalization({ name = "Dazar'alor Trash" })
local collection = {} local function parseFileName(p) local ret = {} local slashy = p:split('/') for i, v in pairs(slashy) do if i ~= #slashy then table.insert(ret, {v, "folder"}) else if #v:split('.') > 1 then table.insert(ret, {v, "file"}) else table.insert(ret, {v, "folder"}) end end end return ret end collection.pathExists = function(f, callback) local pathParsed = parseFileName(f) if pathParsed[#pathParsed][2] == "folder" then local is = isfolder(f) if callback then callback(nil, is) end; return is else local is = isfile(f) if callback then callback(nil, is) end; return is end end collection.readFile = function(f, callback) if not collection.pathExists(f) then if callback then callback("File does not exist.", nil) end; return nil end local ran, err = pcall(function() return readfile(f) end) if not err or string.len(err) < 1 then if callback then return callback("Failed to read file.", nil) else return end end if ran then if callback then callback(nil, err) end; return err end end collection.makeFile = function(f, callback) local pathParsed = parseFileName(f) local pathCompleted = "" for _, v in pairs(pathParsed) do pathCompleted = pathCompleted.. "/".. v[1] if v[2] == "folder" then makefolder(pathCompleted) else writefile(pathCompleted, "") end end if callback then callback(nil, true) end; return true end collection.writeFile = function(f, c, callback) if not collection.pathExists(f) then collection.makeFile(f) end writefile(f, c) if callback then callback(nil, true) end; return true end return collection
target("console") set_languages("cxx11") add_includedirs("..") add_includedirs("../third/OSPlatformUtil/src") if not is_os("windows") then add_links("pthread") end set_kind("binary") add_files("console.cc") target_end() target("base") set_languages("cxx11") add_includedirs("..") add_includedirs("../third/OSPlatformUtil/src") set_kind("binary") add_files("base.cc") target_end()
local lib = require "resty.libxl.library" local setmetatable = setmetatable local rawget = rawget local type = type local ffi = require "ffi" local C = ffi.C local ffi_new = ffi.new local ffi_str = ffi.string local pictures = {} local d = ffi_new "const char*[1]" local l = ffi_new("unsigned[1]", 0) local s = ffi_new("int[1]", 0) function pictures.new(opts) return setmetatable(opts, pictures) end function pictures:add(file, len) if len then lib.xlBookAddPicture2A(self.book.context, file, len) else lib.xlBookAddPictureA(self.book.context, file) end return self[self.size] end function pictures:__len() return lib.xlBookPictureSizeA(self.book.context) end function pictures:__index(n) if n == "size" or n == "count" or n == "n" then return lib.xlBookPictureSizeA(self.book.context) elseif type(n) == "number" then local t = lib.xlBookGetPictureA(self.book.context, n - 1, d, l) if t == C.PICTURETYPE_ERROR then return nil, self.book.error else return { index = n, type = t, data = ffi_str(d[0], l[0]), size = l[0], offset = { x = 0, y = 0 } } end else return rawget(pictures, n) end end return pictures
--Settings-- RegisterServerEvent('carwash:checkmoney') AddEventHandler('carwash:checkmoney', function(dirt) local user = vRP.users_by_source[source] if parseFloat(dirt) > parseFloat(1.0) then if user:tryPayment(25, false) then TriggerClientEvent('carwash:success', user.source) vRP.EXT.Base.remote._notify(user.source, "You paid ~g~25$ ~w~for clean car.") else TriggerClientEvent('carwash:notenough', user.source) vRP.EXT.Base.remote._notify(user.source, "You need ~r~25$~w~ for a carwash.") end else vRP.EXT.Base.remote._notify(user.source, "You car is not dirty.") TriggerClientEvent('carwash:alreadyclean', user.source) end end)
local isCarpaint = false local textureVol local textureCube local myShader local tec function startCarpaint() if getVersion ().sortable < "1.1.0" then return end myShader, tec = dxCreateShader ( "files/data/options/carpaint/car_paint.fx" ) if not myShader then else textureVol = dxCreateTexture ( "files/data/options/carpaint/images/smallnoise3d.dds" ); textureCube = dxCreateTexture ( "files/data/options/carpaint/images/cube_env256.dds" ); dxSetShaderValue ( myShader, "sRandomTexture", textureVol ); dxSetShaderValue ( myShader, "sReflectionTexture", textureCube ); engineApplyShaderToWorldTexture ( myShader, "vehiclegrunge256" ) engineApplyShaderToWorldTexture ( myShader, "?emap*" ) end end function stopCarpaint() if isElement( myShader ) then destroyElement( myShader ) end if isElement( textureVol ) then destroyElement( textureVol ) end if isElement( textureCube ) then destroyElement( textureCube ) end end function toggleCarpainShader() if not isCarpaint then isCarpaint = true startCarpaint() else isCarpaint = false stopCarpaint() end end
--[[ -- Game code -- ]]-- local game = {} game.testing = false game.view = {x=love.graphics.getWidth()/2, y=love.graphics.getHeight()/2, xratio = 1, yratio = 1} game.portraits = {} game.creatures = {} game.projectiles = {} game.loot = {} game.inputScripts = {} function game.setup() game.portraits.default = love.graphics.newImage('gfx/portrait_default.png'); game.portraits.hurt = love.graphics.newImage('gfx/portrait_hurt.png'); game.portraits.attack = love.graphics.newImage('gfx/portrait_attack.png'); game.portraits.quad = love.graphics.newImage('gfx/portrait_quad.png'); end game.adjusting = {amount=0, direction=0} function game.adjustObjectPositions() if (game.adjusting.amount ~=0) then for i, to in ipairs(game.creatures) do to.y = to.y + game.adjusting.direction end for i, to in ipairs(game.projectiles) do to.y = to.y + game.adjusting.direction end for i, to in ipairs(game.loot) do to.y = to.y + game.adjusting.direction end character.y = character.y + game.adjusting.direction game.view.y = game.view.y - game.adjusting.direction game.adjusting.amount = game.adjusting.amount -1 else if character.y > 2*love.graphics.getHeight()/3 then game.adjusting.amount = 16--love.graphics.getHeight()/8 game.adjusting.direction = -1 end if character.y < 32 then --love.graphics.getHeight()/8 then game.adjusting.amount = 32--love.graphics.getHeight()/8 game.adjusting.direction = 1 end end end function game.adjustY(origy) return origy - game.view.y + love.graphics.getHeight()/2 end function game.keydown(key, character) local x = character.x local y = character.y if key == 'w' then y = character.y -character.speed end if key == 's' then y = character.y +character.speed end if key == 'a' then x = character.x -character.speed end if key == 'd' then x = character.x +character.speed end if game.isWalkableTile(x,y) or game.isWalkableObject(x, y) then character.x = x character.y = y end return character end function game.handleMouse(character, angle) if love.mouse.isDown(1) then local x, y, wx, wy x, y = math.translate(character.x, character.y, angle, character.speed) wx, wy = math.translate(x, y, angle, character.size/2) if (game.isWalkableTile(wx,wy)) or game.isWalkableObject(wx,wy) then character.x = x character.y = y end end if love.mouse.isDown(2) then character.portrait = game.portraits.attack if character.attack.cooldown > 0 then character.attack.cooldown = character.attack.cooldown -1 game.sfxplaying = game.sfxplaying -1 else local projectile = game.createProjectile(character.x, character.y, character.direction) character.attack.cooldown = 60/projectile.rate --love.audio.play(game.sfx.attack) if 0 >= game.sfxplaying then game.sfx.attack:stop() game.sfx.attack:play() game.sfxplaying = 6 end end end return character end function game.isWalkableTile(x, y, size) if nil == size then size = 0 end local tx, ty = TiledMap_GetTilePosUnderMouse(x+size/2, y+size/2, game.view.x, game.view.y) local gid = TiledMap_GetMapTile(tx, ty, 1) --FIXME magic tile type local tiletype = TiledMap_GetTileProperties(gid).type if "walkable" == tiletype then return true else return false end end function game.isWalkableObject(x,y) for i, obj in ipairs(game.tiledobjects) do -- for walkables, width and height exist -- if obj.type ~= nil and (obj.type == "walkable") then if (tonumber(obj.x) <= x) and (tonumber(game.adjustY(obj.y)) <= y) and ((obj.x + obj.width) >= x) and ((game.adjustY(obj.y)+obj.height) >= y) then return true; end end end return false; end game.sfxplaying = 0 function game.createProjectile(x, y, direction) local projectile = {x = x, y = y, direction = direction, age = 0, speed=4, rate =30 } table.insert(game.projectiles, projectile) return projectile end -- TODO: Distinct creatures game.crgfx = { spider = "gfx/spidercreature_320.png", goblin = "gfx/goblincreature_320.png", colossus = "gfx/colossuscreature_320.png", dragon = "gfx/bosscreature_320.png", } game.animationsources = { spider = "gfx/spidercreature_strip.png" } function game.createCreature(x,y,direction, size, health, crtype) local creature = { x=x, y=y, direction=direction, size=size, health=health, speed=1.5, damage=0.5, gfx = love.graphics.newImage(game.crgfx[crtype]), animation = game.createCreatureAnimation(crtype), } table.insert(game.creatures, creature) return creature end function game.createCreatureAnimation(crtype) local animation = nil local src = game.animationsources[crtype] if (nil ~= src) then --print(src) local image = love.graphics.newImage(src) local canvas = love.graphics.newCanvas(320*3, 320) canvas:renderTo(function() love.graphics.draw(image, 0, 0, 0, canvas:getWidth()/image:getWidth(), canvas:getHeight()/image:getHeight()) end) if crtype == "spider" then animation = newAnimation(canvas, 320, 320, 0.2, 2, 1 ) end animation:play(); print ("framecount: " .. #animation.frames) end return animation end function game.createLoot(x,y) --FIXME: do not create loot inside a wall if not game.isWalkableTile(x, y) then -- get nearest valid tile. half_tile = 32 if game.isWalkableTile(x + half_tile, y) then x = x + half_tile elseif game.isWalkableTile(x - half_tile, y) then x = x - half_tile elseif game.isWalkableTile(x, y + half_tile) then y = y + half_tile elseif game.isWalkableTile(x, y - half_tile) then y = y - half_tile end end local val = math.random(5) local loot = { x = x, y = y, value = val, size = 3 + val * 2 } table.insert(game.loot, loot) end -- let's test if this is universal -- function game.collision(creature, creature2) local size = creature.size / 2 local cx = creature.x + size local cy = creature.y + size if creature2.size == nil then creature2.size = 0 end local size2 = creature2.size / 2 local cx2 = creature2.x + size2 local cy2 = creature2.y + size2 --optimization if (cx-cx2)*(cx-cx2)+(cy-cy2)*(cy-cy2) > (size+size2)*(size+size2) then return false end --get accurate distance if the above passed --print (projectile.x, projectile.y) if math.dist(cx, cy, cx2, cy2) <= size+size2 then return true end return false end function game.getCharacterObjectArea(character, object) local charx = character.x --+ game.view.x --- (love.graphics.getWidth()/2) local chary = character.y local objy = object.y - game.view.y + love.graphics.getHeight()/2 -- draw box around area if game.testing then love.graphics.rectangle("line", object.x, object.y - game.view.y + love.graphics.getHeight()/2, object.width, object.height) end if charx > tonumber(object.x) and chary > tonumber(objy) and charx < object.x + object.width and chary < objy + object.height then return object.name end return nil end function game.setupCharacter(chr) local character = chr if nil == chr then character = {} end if game.testing then character.loot = 9999 end local objects = TiledMap_Objects(game.levels.currentlevel) for k, object in pairs(objects) do objects[k].x = object.x - game.view.x + (love.graphics.getWidth()/2 ) objects[k].y = object.y - game.view.y + (love.graphics.getHeight()/2 ) if object.name == "Start" then character.x = object.x + object.width/2 + 6 character.y = object.y + object.height/2 + 6 end end game.tiledobjects = objects --local image = love.graphics.newImage('gfx/blank_strip.png') local image = love.graphics.newImage('gfx/test_char2_strip.png') image:setFilter('linear', 'nearest') local wh = 32 -- width, height of target frame local framecountx = 2 character.size = 16 character.gfx = love.graphics.newCanvas(wh * framecountx,wh) character.gfx:renderTo(function() r, g, b, a = love.graphics.getColor() --[[ love.graphics.circle('fill', 6,6,5,30) ]]-- -- lots of extra space per frame, so... love.graphics.draw(image, 0, 0, 0, (framecountx * (wh)/(image:getWidth())), ((wh)/image:getHeight()), 0, 0) love.graphics.setColor(r, g, b, a) --love.graphics.line(5,1, 6,2) end) --character.gfx = image character.animation = newAnimation(character.gfx, 32,32,0.5, 2) character.area = {} if nil == chr then character.loot = 0 character.speed = 1.5 character.health = 6 character.attack = {damage=1, range=1, cooldown = 0} character.portrait = game.portraits.default end character.invincibility = 0 return character end game.tiledobjects = {} game.sfx = {} game.shop = {} game.levels = require("first.levels") game.levels.init(game) function game.loadLevelByIndex(index, character) game.loot = {} game.creatures = {} game.view = {x=love.graphics.getWidth()/2, y=love.graphics.getHeight()/2, xratio = 1, yratio = 1} game.levels.seekByIndex(index) local tilesize = 32 print (game.levels.currentlevel) TiledMap_Load(game.levels.currentlevel, tilesize, '/', "tiled/", 1, 1) game.view.xratio = love.graphics.getWidth() / (TiledMap_GetMapW() * tilesize ) game.view.yratio = love.graphics.getHeight() / (TiledMap_GetMapH() * tilesize ) character = game.setupCharacter(character) local levelfunction = game.levels.getFunction(index) if nil ~= levelfunction then character, game = levelfunction(character, "init", game) end return character, game end -- FIXME hacky shop function game.inShop() -- print ("inshop " .. character.area) --character.area = "Shop" local r, g, b, a = love.graphics.getColor() local shop = { attack = (character.attack.damage + 0.5) *6, range = (character.attack.range + 0.5) *6, speed = (character.speed + 0.5) *6, health = 5 } love.graphics.setColor(0,0,16,144) love.graphics.rectangle("fill", 6, 60, 128, 80) love.graphics.setColor(255,212,0,255) love.graphics.print("Sacrifice Loot", 10, 64) love.graphics.print("[1]attack " .. shop.attack, 10, 80) love.graphics.print("[2]range " .. shop.range, 10, 96) love.graphics.print("[3]speed " .. shop.speed, 10, 112) love.graphics.print("[4]health " .. shop.health, 10, 128) game.shop = shop love.graphics.setColor(r,g,b,a) return game end return game
function showTaiFighterUI() setWindowVisible("TaiFighterWindow", true) setWindowVisible("PauseWindow", false) setWindowVisible("PushButton", false) setWindowVisible("ExitButton", false) changeText("Title","Payum") setUIMouseCursorVisible(false); end function showPauseUI() setWindowVisible("TaiFighterWindow", false) setWindowVisible("PauseWindow", true) setWindowVisible("PushButton", true) setWindowVisible("ExitButton", true) changeText("Title","TaiFighter") setUIMouseCursorVisible(true); end function exitCallback() LOG("EXIT place holder") end
-- import extension and initialize lanes = require "lanes".configure() -- thread 1 function local function loop1( ) while true do print("+ loop1") os.execute("sleep 0.1") end end -- thread 2 function function loop2() while true do print("- loop2") os.execute("sleep 0.1") end end -- create and start the threads, notice the ‘()’ to start the thread. you can parameters to the function. thread1 = lanes.gen("*", loop1)() thread2 = lanes.gen("*", loop2)()
modalmgr_keys = modalmgr_keys or {{"alt"}, "space"} modalmgr = hs.hotkey.modal.new(modalmgr_keys[1], modalmgr_keys[2], 'Enter Main Mode') local modalpkg = {} modalpkg.id = "mainM" modalpkg.modal = modalmgr table.insert(modal_list, modalpkg) function modalmgr:entered() for i=1,#modal_list do if modal_list[i].id == "mainM" then table.insert(activeModals, modal_list[i]) end end showavailableHotkey() end function modalmgr:exited() if modal_tray then modal_tray:hide() end if hotkeytext then hotkeytext:delete() hotkeytext=nil hotkeybg:delete() hotkeybg=nil end end modalmgr:bind("", "space", "Alfred 3", function() exit_others() activateApp("Alfred 3") end) modalmgr:bind("", "escape", "Exit Main Mode", function() modalmgr:exit() end) modalmgr:bind("", "Q", "Exit Main Mode", function() modalmgr:exit() end) if appM then appM_keys = appM_keys or {"", "A"} if string.len(appM_keys[2]) > 0 then appM:bind(modalmgr_keys[1], modalmgr_keys[2], "Enter Main Mode", function() exit_others() modalmgr:enter() end) modalmgr:bind(appM_keys[1], appM_keys[2], 'Enter Application Mode', function() exit_others() appM:enter() end) end end if clipboardM then clipboardM_keys = clipboardM_keys or {"", "C"} if string.len(clipboardM_keys[2]) > 0 then clipboardM:bind(modalmgr_keys[1], modalmgr_keys[2], "Enter Main Mode", function() exit_others() modalmgr:enter() end) modalmgr:bind(clipboardM_keys[1], clipboardM_keys[2], 'Enter Clipboard Mode', function() exit_others() clipboardM:enter() end) end end if aria2_loaded then aria2_keys = aria2_keys or {"", "D"} if string.len(aria2_keys[2]) > 0 then modalmgr:bind('', 'D', 'Launch aria2 Frontend', function() exit_others() if aria2_drawer then aria2_drawer:delete() aria2_drawer = nil end aria2_Init() end) end end if hsearch_loaded then hsearch_keys = hsearch_keys or {"", "G"} if string.len(hsearch_keys[2]) > 0 then modalmgr:bind(hsearch_keys[1], hsearch_keys[2], 'Launch Hammer Search', function() exit_others() launchChooser() end) end end if timerM then timerM_keys = timerM_keys or {"", "I"} if string.len(timerM_keys[2]) > 0 then timerM:bind(modalmgr_keys[1], modalmgr_keys[2], "Enter Main Mode", function() exit_others() modalmgr:enter() end) modalmgr:bind(timerM_keys[1], timerM_keys[2], 'Enter Timer Mode', function() exit_others() timerM:enter() end) end end if resizeM then resizeM_keys = resizeM_keys or {"", "R"} if string.len(resizeM_keys[2]) > 0 then resizeM:bind(modalmgr_keys[1], modalmgr_keys[2], "Enter Main Mode", function() exit_others() modalmgr:enter() end) modalmgr:bind(resizeM_keys[1], resizeM_keys[2], 'Enter Resize Mode', function() exit_others() resizeM:enter() end) end end if cheatsheetM then cheatsheetM_keys = cheatsheetM_keys or {"", "S"} if string.len(cheatsheetM_keys[2]) > 0 then cheatsheetM:bind(modalmgr_keys[1], modalmgr_keys[2], "Enter Main Mode", function() exit_others() modalmgr:enter() end) modalmgr:bind(cheatsheetM_keys[1], cheatsheetM_keys[2], 'Enter Cheatsheet Mode', function() exit_others() cheatsheetM:enter() end) end end showtime_keys = showtime_keys or {"", "T"} if string.len(showtime_keys[2]) > 0 then modalmgr:bind(showtime_keys[1], showtime_keys[2], 'Show Digital Clock', function() exit_others() show_time() end) end show_screen_numbers_keys = show_screen_numbers_keys or {"", "N"} if string.len(show_screen_numbers_keys[2]) > 0 then modalmgr:bind(show_screen_numbers_keys[1], show_screen_numbers_keys[2], 'Show Screen Numbers', function() exit_others() show_screen_numbers() end) end if viewM then viewM_keys = viewM_keys or {"", "V"} if string.len(viewM_keys[2]) > 0 then viewM:bind(modalmgr_keys[1], modalmgr_keys[2], "Enter Main Mode", function() exit_others() modalmgr:enter() end) modalmgr:bind(viewM_keys[1], viewM_keys[2], 'Enter View Mode', function() exit_others() viewM:enter() end) end end toggleconsole_keys = toggleconsole_keys or {"", "Z"} if string.len(toggleconsole_keys[2]) > 0 then modalmgr:bind(toggleconsole_keys[1], toggleconsole_keys[2], 'Toggle Hammerspoon Console', function() exit_others() hs.toggleConsole() end) end winhints_keys = winhints_keys or {"", "tab"} if string.len(winhints_keys[2]) > 0 then modalmgr:bind(winhints_keys[1], winhints_keys[2], 'Show Windows Hint', function() exit_others() hs.hints.windowHints() end) end