content
stringlengths
5
1.05M
module("luci.controller.wifidog", package.seeall) function index() local fs = require "nixio.fs" if fs.access("/usr/bin/wifidog") then entry({"admin", "services", "wifidog"}, cbi("wifidog"), "Wifidog", 4) end end
deathspeaker_xunra_rune_of_haste_modifier = class({}) function deathspeaker_xunra_rune_of_haste_modifier:OnCreated( kv ) self.move_speed_percentage = self:GetAbility():GetSpecialValueFor("move_speed_percentage") self.roots_duration = self:GetAbility():GetSpecialValueFor("roots_duration") end function deathspeaker_xunra_rune_of_haste_modifier:DeclareFunctions() local funcs = { MODIFIER_PROPERTY_MOVESPEED_BONUS_PERCENTAGE, MODIFIER_PROPERTY_TOOLTIP, } return funcs end function deathspeaker_xunra_rune_of_haste_modifier:GetModifierMoveSpeedBonus_Percentage( params ) return self.move_speed_percentage end function deathspeaker_xunra_rune_of_haste_modifier:OnTooltip( params ) return self.roots_duration end function deathspeaker_xunra_rune_of_haste_modifier:GetAttributes() return MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE end function deathspeaker_xunra_rune_of_haste_modifier:IsHidden() return false end function deathspeaker_xunra_rune_of_haste_modifier:IsPurgable() return false end function deathspeaker_xunra_rune_of_haste_modifier:IsPurgeException() return false end function deathspeaker_xunra_rune_of_haste_modifier:IsStunDebuff() return false end function deathspeaker_xunra_rune_of_haste_modifier:IsDebuff() return true end
local prototype = require('prototype') local func = require('func') local ffi = require('ffi') local delimiter = '/' local newline = '\n' local executableSuffix = '' if ffi.os == 'Windows' then delimiter = '\\' newline = '\r\n' executableSuffix = '.exe' end local bind = func.bind local Program = prototype {} Program._newline = newline Program._delimiter = delimiter function Program.new (name) return Program { name = name; } end function Program.executableName (self) return string.format('%s%s', self.name, executableSuffix) end function Program.run (self, args, pipeFn) local invocation = string.format( '%s %s', self:executableName(), table.concat(args or {}, ' ') ) local file = io.popen(invocation, 'r') xpcall( bind(pipeFn, file), function (err) file:close() error(err) end ) file:close() end return { Program = Program }
local function is_table(variable) return type(variable) == 'table' end local function is_number(variable) return type(variable) == 'number' end local function split_to_words(s) return s:gmatch('%S+') end local function trim_lines(s) return (s:gsub("\n%s*", "\n"):gsub("%s*\n", "\n")) end local function remove_first_line(s) return (s:gsub("^.*:.*\n", "")) end local function clear_section(section) section = remove_first_line(section) section = trim_lines(section) return section end local function split_section_to_lines(section) section = clear_section(section) return section:gmatch("[^\r\n]+") end local function remove_last_empty_line(s) return (s:gsub('\n%s*$', '')) end local function unify_lines_indentation(s) return (section:gsub("\n(%s+)", "\n ")) end local function match_to_first_empty_line(s) value = s:match('^(.-)\n[ \t]-\n') if value == nil then value = s end return s end local function match_section(s, section_delimiter) section = s:match('(' .. section_delimiter .. '%s*.*)') section = match_to_first_empty_line(section) section = unify_lines_indentation(section) section = remove_last_empty_line(section) return section end local function merge_tables(...) result = {} for i=1, arg['n'], 1 do for key, value in pairs(arg[i]) do result[key] = value end end return result end local function push_to_table(t, element) table.insert(t, table.getn(t) + 1, element) end local function resolve_params(params, default_params) if params == nill then params = {} end return merge_tables(default_params, params) end -- Returns list of arguments given to the program from terminal without program name local function get_cli_arguments() arguments = {} for key, value in pairs(_G.arg) do if is_number(key) and key > 0 then table.insert(arguments, table.getn(arguments) + 1, value) end end return arguments end local function terminate(message) print(message) os.exit(1) end local Rule = { _create = function(self) rule = { name = nil, variable = false } setmetatable(rule, self) self.__index = self return rule end, create_from_string = function(self, s) rule = self:_create() rule.name = s if rule.name:find('^<%w+>$') then rule.variable = true end return rule end, match_argument = function(self, argument) if self.variable then return argument else return argument == self.name end end, get_name = function(self) return self.name end } local Route = { _create = function(self) route = { rules = {} } setmetatable(route, self) self.__index = self return route end, parse_doc_to_words = function(self, s) words = split_to_words(s) words() -- remove first word (name of the program) return words end, create_from_string = function(self, s) route = self:_create() for word in self:parse_doc_to_words(s) do push_to_table(route.rules, Rule:create_from_string(word)) end return route end, match_arguments = function(self, arguments) rule_id = 1 resolved_arguments = {} for key, argument in ipairs(arguments) do rule = self.rules[rule_id] value = rule:match_argument(argument) if value ~= nil then resolved_arguments[rule:get_name()] = value else return end rule_id = rule_id + 1; end if rule_id - 1 < table.getn(self.rules) then return end return resolved_arguments end } local Router = { _create = function(self) router = { routes = {} } setmetatable(router, self) self.__index = self return router end, create_from_string = function(self, section) router = self:_create() lines = split_section_to_lines(section) for line in lines do route = Route:create_from_string(line) push_to_table(router.routes, route) end return router end, match_arguments = function(self, arguments) for key, route in pairs(self.routes) do resolved_arguments = route:match_arguments(arguments) if is_table(resolved_arguments) then return resolved_arguments end end end } local default_params = { argv = get_cli_arguments(), help = true, version = nil, options_first = false } function docopt(doc, params) params = resolve_params(params, default_params) usage_section = match_section(doc, 'Usage:') router = Router:create_from_string(usage_section) resolved_arguments = router:match_arguments(params.argv) if resolved_arguments ~= nil then return resolved_arguments else terminate(usage_section) end end
local R = require "rigel" local RM = require "generators.modules" local types = require("types") local harness = require "generators.harness" local harris = require "harris_core" W = 256 H = 256 T = 8 ITYPE = types.array2d(types.uint(8),T) local inpraw = R.input(R.Handshake(ITYPE)) local inp = R.apply("reducerate", RM.changeRate(types.uint(8),1,8,1), inpraw ) local harrisFn = harris.makeHarris(W,H,false) local out = R.apply("filterfn", harrisFn, inp ) local out = R.apply("incrate", RM.changeRate(types.uint(8),1,1,8), out ) fn = RM.lambda( "harris", inpraw, out ) harness{ outFile="harris_corner", fn=fn, inFile="box_256.raw", inSize={W,H}, outSize={W,H} }
local tl = require("tl") describe("local", function() describe("declaration", function() it("basic inference sets types", function() -- fail local tokens = tl.lex([[ local x = 1 local y = 2 local z: table z = x + y ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.match("in assignment: got number", errors[1].msg, 1, true) -- pass local tokens = tl.lex([[ local x = 1 local y = 2 local z: number z = x + y ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.same({}, errors) end) end) describe("multiple declaration", function() it("basic inference catches errors", function() local tokens = tl.lex([[ local x, y = 1, 2 local z: table z = x + y ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.match("in assignment: got number", errors[1].msg, 1, true) end) it("basic inference sets types", function() -- pass local tokens = tl.lex([[ local x, y = 1, 2 local z: number z = x + y ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.same({}, errors) end) describe("with types", function() it("checks values", function() -- fail local tokens = tl.lex([[ local x, y: string, number = 1, "a" local z z = x + string.byte(y) ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.match("x: got number, expected string", errors[1].msg, 1, true) assert.match("y: got string \"a\", expected number", errors[2].msg, 1, true) end) it("propagates correct type", function() -- fail local tokens = tl.lex([[ local x, y: number, string = 1, "a" local z: table z = x + string.byte(y) ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.match("in assignment: got number", errors[1].msg, 1, true) end) it("uses correct type", function() -- pass local tokens = tl.lex([[ local x, y: number, string = 1, "a" local z: number z = x + string.byte(y) ]]) local _, ast = tl.parse_program(tokens) local errors = tl.type_check(ast) assert.same({}, errors) end) end) it("reports unset and untyped values as errors in tl mode", function() local tokens = tl.lex([[ local T = record x: number y: number end function T:returnsTwo(): number, number return self.x, self.y end function T:method() local a, b = self.returnsTwo and self:returnsTwo() end ]]) local _, ast = tl.parse_program(tokens) local errors, unknowns = tl.type_check(ast) assert.same(1, #errors) end) it("reports unset values as unknown in Lua mode", function() local tokens = tl.lex([[ local T = record x: number y: number end function T:returnsTwo(): number, number return self.x, self.y end function T:method() local a, b = self.returnsTwo and self:returnsTwo() end ]]) local _, ast = tl.parse_program(tokens) local errors, unknowns = tl.type_check(ast, true) assert.same({}, errors) assert.same(1, #unknowns) assert.same("b", unknowns[1].msg) end) end) end)
module(..., package.seeall) function gen_bindings(n_bindings, ports_per_host) local bt = {} local i4 = 0x11223344 local ipv6_prefix = "0102:0304:0406:0708:090a:0b0c:" local start_port = 1024 local port_step = math.floor((0xffff - start_port) / ports_per_host) for i = 1, n_bindings/ports_per_host do local port1 = start_port for p = 1, ports_per_host do local ipv4 = string.format("%i.%i.%i.%i", bit.rshift(bit.band(i4, 0xff000000), 24), bit.rshift(bit.band(i4, 0xff0000), 16), bit.rshift(bit.band(i4, 0xff00), 8), bit.band(i4, 0xff)) local ipv6 = ipv6_prefix .. ipv4 local port2 = port1 + port_step - 1 local binding_entry = {ipv6, ipv4, port1, port2} table.insert(bt, binding_entry) port1 = port1 + port_step end i4 = i4 + 1 end return bt end function print_bindings(bt) printable = {} count = 0 print("{") for _,entry in ipairs(bt) do local entry_parts = {string.format('"%s"', entry[1]), string.format('"%s"', entry[2]), entry[3], entry[4]} table.insert(printable, ' {' .. table.concat(entry_parts, ', ') .. '}') count = count + 1 if count % 10000 == 0 then print(table.concat(printable, ",\n"), ',') printable = {} end end if printable then print(table.concat(printable, ",\n")) end print("}") end -- n_bindings = 1000000 -- ports_per_host = 50 -- print_bindings(gen_bindings(n_bindings, ports_per_host))
fx_version 'cerulean' game 'gta5' author 'MasiBall' description 'Simple standalone teleport resource. Works with and without vehicle' server_scripts { 'server/server.lua', } client_scripts { 'client/client.lua', 'client/config.lua' }
mealCost = 10.25 tipPercent = 17 taxPercent = 5 tip = mealCost * (tipPercent / 100); tax = mealCost * (taxPercent / 100); total = mealCost + tip + tax; rounded = math.floor(total+0.5) print(rounded) print(string.format("The total meal cost is %i dollars.", total))
local HomeRun = {} local function prepareDatabase() SQL.createdatabase('db/home_run.db') SQL.opendatabase('db/home_run.db') SQL.writecommand('CREATE TABLE seed_frame_result (' .. 'id int PRIMARY KEY,' .. 'seed int,' .. 'numberShoot int,' .. 'frame int,' .. 'result int' .. ')' ) end local function insertSeedFrameResult(id, seed, numberShoot, frame, result) SQL.opendatabase('db/home_run.db') SQL.writecommand('INSERT INTO seed_frame_result VALUES (' .. id .. ', ' .. seed .. ', ' .. numberShoot .. ', ' .. frame .. ', ' .. result .. ')') end local function retrieveBestShoot(seed, numberShoot) SQL.opendatabase('db/home_run.db') local bestShoot = SQL.readcommand('SELECT frame, result FROM seed_frame_result WHERE seed = ' .. seed .. ' AND numberShoot = ' .. numberShoot .. ' ORDER BY result desc LIMIT 1') return {['frame'] = bestShoot['frame 0'], ['result'] = bestShoot['result 0']} end local function retrieveAttemptsOf(seed, numberShoot, emptyValue) SQL.opendatabase('db/home_run.db') local attemptRecords = SQL.readcommand('SELECT result FROM seed_frame_result WHERE seed = ' .. seed .. ' AND numberShoot = ' .. numberShoot .. ' ORDER BY id') local attempts = {} for i = 0, 4 do table.insert(attempts, attemptRecords['result ' .. i] or emptyValue) end return attempts end HomeRun.prepareDatabase = prepareDatabase HomeRun.insertSeedFrameResult = insertSeedFrameResult HomeRun.retrieveAttemptsOf = retrieveAttemptsOf HomeRun.retrieveBestShoot = retrieveBestShoot return HomeRun
local game = {} function game.setName(name) game.name = name end return game
local texture = "fx/snow.tex" local shader = "shaders/particle.ksh" local colour_envelope_name = "pollencolourenvelope" local scale_envelope_name = "pollenscaleenvelope" local assets = { Asset( "IMAGE", texture ), Asset( "SHADER", shader ), } local function IntColour( r, g, b, a ) return { r / 255.0, g / 255.0, b / 255.0, a / 255.0 } end local init = false local function InitEnvelope() if EnvelopeManager and not init then init = true EnvelopeManager:AddColourEnvelope( colour_envelope_name, { { 0, IntColour( 255, 255, 0, 0 ) }, { 0.5, IntColour( 255, 255, 0, 127 ) }, { 1, IntColour( 255, 255, 0, 0 ) }, } ) local min_scale = 0.8 local max_scale = 1.0 EnvelopeManager:AddVector2Envelope( scale_envelope_name, { { 0, { min_scale, min_scale } }, { 0.5, { max_scale, max_scale } }, { 1, { min_scale, min_scale } }, } ) end end local max_lifetime = 60 local min_lifetime = 30 local function fn(Sim) local inst = CreateEntity() local trans = inst.entity:AddTransform() local emitter = inst.entity:AddParticleEmitter() inst:AddTag("FX") InitEnvelope() emitter:SetRenderResources( texture, shader ) emitter:SetMaxNumParticles( 1000 ) emitter:SetMaxLifetime( max_lifetime ) emitter:SetColourEnvelope( colour_envelope_name ) emitter:SetScaleEnvelope( scale_envelope_name ); emitter:SetBlendMode( BLENDMODE.Premultiplied ) emitter:SetSortOrder( 3 ) emitter:SetLayer( LAYER_BACKGROUND ) emitter:SetAcceleration( 0, 0.0001, 0 ) emitter:SetDragCoefficient( 0.0001 ) emitter:EnableDepthTest( false ) ----------------------------------------------------- local rng = math.random local tick_time = TheSim:GetTickTime() local desired_particles_per_second = 0--300 inst.particles_per_tick = desired_particles_per_second * tick_time local emitter = inst.ParticleEmitter inst.num_particles_to_emit = inst.particles_per_tick local bx, by, bz = 0, 0.3, 0 local emitter_shape = CreateBoxEmitter( bx, by, bz, bx + 40, by, bz + 40 ) local emit_fn = function() if GetWorld().Map ~= nil then local x, y, z = GetPlayer().Transform:GetWorldPosition() local px, py, pz = emitter_shape() x = x + px z = z + pz -- don't spawn particles over water if GetWorld().Map:GetTileAtPoint( x, y, z ) ~= GROUND.IMPASSABLE then local vx = 0.03 * (math.random() - 0.5) local vy = 0 local vz = 0.03 * (math.random() - 0.5) local lifetime = min_lifetime + ( max_lifetime - min_lifetime ) * UnitRand() emitter:AddParticle( lifetime, -- lifetime px, py, pz, -- position vx, vy, vz -- velocity ) end end end local updateFunc = function() while inst.num_particles_to_emit > 1 do emit_fn( emitter ) inst.num_particles_to_emit = inst.num_particles_to_emit - 1 end inst.num_particles_to_emit = inst.num_particles_to_emit + inst.particles_per_tick -- vary the acceleration with time in a circular pattern -- together with the random initial velocities this should give a variety of motion inst.time = inst.time + tick_time inst.interval = inst.interval + 1 if 10 < inst.interval then inst.interval = 0 local sin_val = 0.006 * math.sin(inst.time/3) local cos_val = 0.006 * math.cos(inst.time/3) emitter:SetAcceleration( sin_val, 0.05 * sin_val, cos_val ) end end inst.time = 0.0 inst.interval = 0 EmitterManager:AddEmitter( inst, nil, updateFunc ) return inst end return Prefab( "common/fx/pollen", fn, assets)
--[[ File handler. ]] local files = {} _libs = _libs or {} _libs.filehelper = files _libs.stringhelper = _libs.stringhelper or require('stringhelper') local createfile = false -- Create a new file object. Accepts a variable number of paths, which it will function files.new(path, create) create = true and (create ~= false) if path == nil then return setmetatable(T{}, {__index = files}) end local f = setmetatable(T{}, {__index = files}) f:set(path, create) return f end -- Creates a new file. Creates path, if necessary. function files.create(f) f:create_path() local fh = io.open(windower.addon_path..f.path, 'w') fh:write('') fh:close() return f end -- Sets the file to a path value. function files.set(f, path, create) create = true and (create ~= false) createfile = create f.path = path return f end -- Check if file exists. There's no better way, it would seem. function files.exists(f) local path if type(f) == 'string' then path = f else if f.path == nil then return nil, 'No file path set, cannot check file.' end path = f.path end return windower.file_exists(windower.addon_path..path) end -- Checks existance of a number of paths, returns the first that exists. function files.check(...) return table.find[2]({...}, files.exists) end -- Read from file and return string of the contents. function files.read(f) local path if type(f) == 'string' then if not files.exists(f) then return nil, 'File \''..f..'\' not found, cannot read.' end path = f else if f.path == nil then return nil, 'No file path set, cannot write.' end if not f:exists() then if createfile then return '' else return nil, 'File \''..f.path..'\' not found, cannot read.' end end path = f.path end local fh = io.open(windower.addon_path..path, 'r') local content = fh:read('*all*') fh:close() -- Remove byte order mark for UTF-8, if present if content:startswith(string.char(0xEF, 0xBB, 0xBF)) then return content:sub(4) end return content end -- Creates a directory. function files.create_path(f) local path if type(f) == 'string' then path = f else if f.path == nil then return nil, 'No file path set, cannot create directories.' end path = f.path:match('(.*)[/\\].-') if not path then return nil, 'File path already in addon directory: '..windower.addon_path..path end end new_path = windower.addon_path for dir in path:psplit('[/\\]'):filter(-''):it() do new_path = new_path..'/'..dir if not windower.dir_exists(new_path) then local res, err = windower.create_dir(new_path) if not res then if err ~= nil then return nil, err..': '..new_path end return nil, 'Unknown error trying to create path '..new_path end end end return new_path end -- Read from file and return lines of the contents in a table. function files.readlines(f) return files.read(f):split('\n') end -- Return an iterator over the lines of a file. function files.it(f) local path if type(f) == 'string' then if not files.exists(f) then return nil, 'File \''..f..'\' not found, cannot read.' end path = f else if f.path == nil then return nil, 'No file path set, cannot write.' end if not f:exists() then if createfile then return '' else return nil, 'File \''..f.path..'\' not found, cannot read.' end end path = f.path end return coroutine.wrap(function() for l in io.lines(windower.addon_path..path) do coroutine.yield(l) end end) end -- Write to file. Overwrites everything within the file, if present. function files.write(f, content, flush) local path if type(f) == 'string' then if not files.exists(f) then return nil, 'File \''..f..'\' not found, cannot write.' end path = f else if f.path == nil then return nil, 'No file path set, cannot write.' end if not f:exists() then if createfile then notice('New file: '..f.path) f:create() else return nil, 'File \''..f.path..'\' not found, cannot write.' end end path = f.path end if type(content) == 'table' then content = table.concat(content) end local fh = io.open(windower.addon_path..path, 'w') fh:write(content) if flush then fh:flush() end fh:close() return f end -- Append to file. Sets a newline per default, unless newline is set to false. function files.append(f, content, flush) local path if type(f) == 'string' then if not files.exists(f) then return nil, 'File \''..f..'\' not found, cannot write.' end path = f else if f.path == nil then return nil, 'No file path set, cannot write.' end if not f:exists() then if createfile then notice('New file: '..f.path) f:create() else return nil, 'File \''..f.path..'\' not found, cannot write.' end end path = f.path end local fh = io.open(windower.addon_path..path, 'a') fh:write(content) if flush then fh:flush() end fh:close() return f end return files --[[ Copyright (c) 2013, Windower 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 Windower 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 Windower 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. ]]
-- TaskQueue -- Stephen Leitnick -- November 20, 2021 --[=[ @class TaskQueue A queue that flushes all objects at the end of the current execution step. This works by scheduling all tasks with `task.defer`. A possible use-case is to batch all requests being sent through a RemoteEvent to help prevent calling it too many times on the same frame. ```lua local bulletQueue = TaskQueue.new(function(bullets) bulletRemoteEvent:FireAllClients(bullets) end) -- Add 3 bullets. Because they're all added on the same -- execution step, they will all be grouped together on -- the next queue flush, which the above function will -- handle. bulletQueue:Add(someBullet) bulletQueue:Add(someBullet) bulletQueue:Add(someBullet) ``` ]=] local TaskQueue = {} TaskQueue.ClassName = "TaskQueue" TaskQueue.__index = TaskQueue --[=[ @param onFlush ({T}) -> nil @return TaskQueue<T> Constructs a new TaskQueue. ]=] function TaskQueue.new<T>(onFlush: ({T}) -> ()) return setmetatable({ _queue = {}; _flushing = false; _flushingScheduled = false; _onFlush = onFlush; }, TaskQueue) end --[=[ @param object T Add an object to the queue. ]=] function TaskQueue:Add(object: any) table.insert(self._queue, object) if not self._flushingScheduled then self._flushingScheduled = true task.defer(function() if not self._flushingScheduled then return end self._flushing = true self._onFlush(self._queue) table.clear(self._queue) self._flushing = false self._flushingScheduled = false end) end end --[=[ Clears the TaskQueue. This will clear any tasks that were scheduled to be flushed on the current execution frame. ```lua queue:Add(something1) queue:Add(something2) queue:Clear() ``` ]=] function TaskQueue:Clear() if self._flushing then return end table.clear(self._queue) self._flushingScheduled = false end --[=[ Destroys the TaskQueue. Just an alias for `Clear()`. ]=] function TaskQueue:Destroy() self:Clear() setmetatable(self, nil) end function TaskQueue:__tostring() return "TaskQueue" end export type TaskQueue<T> = typeof(TaskQueue.new(function() end)) table.freeze(TaskQueue) return TaskQueue
local function addNode(self, node, nextNode, ed) if not self._pathDB[node] then self._pathDB[node] = {} end self._pathDB[node][ed] = (nextNode == ed and node or nextNode) end -- Path lookupTable local lookupTable = {} lookupTable.__index = lookupTable function lookupTable:new() local lut = {_pathDB = {}} return setmetatable(lut, lookupTable) end function lookupTable:addPath(path) local st, ed = path._nodes[1], path._nodes[#path._nodes] for node, count in path:nodes() do local nextNode = path._nodes[count+1] if nextNode then addNode(self, node, nextNode, ed) end end end function lookupTable:hasPath(nodeA, nodeB) local found found = self._pathDB[nodeA] and self._path[nodeA][nodeB] if found then return true, true end found = self._pathDB[nodeB] and self._path[nodeB][nodeA] if found then return true, false end return false end return lookupTable
-- Copyright 2013 Arman Darini local class = {} class.new = function(o) local CameraClass = display.newGroup() CameraClass.layer = nil CameraClass.viewable = {} CameraClass.x = 0 CameraClass.y = 0 CameraClass.frozen = false CameraClass.timers = {} CameraClass.transitions = {} CameraClass.state = "ready" ---------------------------------------------------------- function CameraClass:init(o) self.layer = o.layer self.viewable = o.viewable self.x = o.x or 0 self.y = o.y or 0 self:moveTo(self.x, self.y) self.layer:addEventListener("touch", self) Runtime:addEventListener("cameraPanTo", self) return self end ---------------------------------------------------------- function CameraClass:cameraPanTo(event) print("event panTo", event.x, event.y) self:panTo(event.x, event.y) end ---------------------------------------------------------- function CameraClass:transformToLayerCoordinates(x, y) return -(x - Game.w / 2), -(y - Game.h / 2) end ---------------------------------------------------------- function CameraClass:clamToViewable(x, y) x = math.max((self.viewable.xMin + Game.w / 2), math.min(x, self.viewable.xMax - Game.w / 2)) y = math.max((self.viewable.yMin + Game.h / 2), math.min(y, self.viewable.yMax - Game.h / 2)) return x, y end ---------------------------------------------------------- function CameraClass:moveTo(x, y) if true == self.frozen then p("camera frozen") return end print("moveTo", x, y) self.x, self.y = self:clamToViewable(x, y) x, y = self:transformToLayerCoordinates(self.x, self.y) self.layer.x = x self.layer.y = y end ---------------------------------------------------------- function CameraClass:moveToCenterBottom() self:moveTo(0.5 * (self.viewable.xMin + self.viewable.xMax), self.viewable.yMax) end ---------------------------------------------------------- function CameraClass:moveToCenterTop() self:moveTo(0.5 * (self.viewable.xMin + self.viewable.xMax), self.viewable.yMin) end ---------------------------------------------------------- function CameraClass:panTo(x, y) if true == self.frozen then p("camera frozen") return end self.x, self.y = self:clamToViewable(x, y) x, y = self:transformToLayerCoordinates(self.x, self.y) local d = ((x - self.layer.x)^2 + (y - self.layer.y)^2)^0.5 transition.to(self.layer, { x = x, y = y, time = d * 10 }) end ---------------------------------------------------------- function CameraClass:startDrag() self.startX = self.x self.startY = self.y end ---------------------------------------------------------- function CameraClass:drag(distanceX, distanceY) self:moveTo(self.startX - distanceX, self.startY - distanceY) Runtime:dispatchEvent({ name = "cameraMoved", camera = self, deltaX = distanceX, deltaY = distanceY }) end ---------------------------------------------------------- function CameraClass:endDrag() end ---------------------------------------------------------- function CameraClass:freeze() self.frozen = true self.layer:removeEventListener("touch", self) display.getCurrentStage():setFocus(nil) end ---------------------------------------------------------- function CameraClass:unfreeze() self.frozen = false self.layer:addEventListener("touch", self) end ---------------------------------------------------------- function CameraClass:touch(event) if "began" == event.phase then self:startDrag() display.getCurrentStage():setFocus(event.target) elseif "moved" == event.phase then self:drag(event.x - event.xStart, event.y - event.yStart) elseif "ended" == event.phase or "cancelled" == event.phase then self:endDrag() display.getCurrentStage():setFocus(nil) print("camera", self.x, self.y) end return true end ---------------------------------------------------------- function CameraClass:toStr() end ---------------------------------------------------------- function CameraClass:removeSelf() Runtime:removeEventListener("cameraPanTo", self) for k, _ in pairs(self.timers) do timer.cancel(self.timers[k]) self.timers[k] = nil end for k, _ in pairs(self.transitions) do transition.cancel(self.transitions[k]) self.transitions[k] = nil end end ---------------------------------------------------------- -- CameraClass:init(o) return CameraClass end return class
-- https://phanx.net/addons/tutorials/localize local _, namespace = ... local L = setmetatable({}, { __index = function(t, k) local v = tostring(k) rawset(t, k, v) return v end }) namespace.L = L local LOCALE = GetLocale() if LOCALE == "enUS" then -- The EU English game client also -- uses the US English locale code. return end ---- To add translations, use this block as a starting point -- if LOCALE == "deDE" then -- -- German translations go here -- L["I need to open my cache!"] = "German for 'I need to open my weekly cache still!'" -- L["I have no key."] = "German for 'I have no key, I have been slacking.'" -- return -- end
return { { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65551 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65552 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65553 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65554 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65555 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65556 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65557 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65558 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65559 } } } }, { effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65560 } } } }, uiEffect = "", name = "Z28弹幕", cd = 0, painting = 1, id = 14020, picture = "0", castCV = "skill", desc = "Z28弹幕", aniEffect = { effect = "jineng", offset = { 0, -2, 0 } }, effect_list = { { type = "BattleSkillFire", casterAniEffect = "", target_choise = "TargetNil", targetAniEffect = "", arg_list = { weapon_id = 65551 } } } }
include("shared.lua") language.Add("nature_planet", "Plant") function ENT:DoNormalDraw(bDontDrawModel) local mode = self:GetNWInt("overlaymode") if not bDontDrawModel then self:DrawModel() end local trace = LocalPlayer():GetEyeTrace() if not (trace.Entity == self and EyePos():Distance(self:GetPos()) < 256 and mode ~= 0) then return end local rd = CAF.GetAddon("Resource Distribution") local nettable = rd.GetEntityTable(self) if table.Count(nettable) <= 0 then return end local playername = self:GetPlayerName() if playername == "" then playername = "World" end if not mode or mode ~= 2 then local OverlayText = "" OverlayText = OverlayText .. self.PrintName .. "\n" if nettable.network == 0 then OverlayText = OverlayText .. "Not connected to a network\n" else OverlayText = OverlayText .. "Network " .. nettable.network .. "\n" end OverlayText = OverlayText .. "Owner: " .. playername .. "\n" if self:GetOOO() == 0 then OverlayText = OverlayText .. "This Plant needs water\n" else OverlayText = OverlayText .. "This plant is healthy and has " .. tostring(self:GetNWInt(1)) .. " water left\n" end OverlayText = OverlayText .. "Connected resources:\n" OverlayText = OverlayText .. rd.GetProperResourceName("carbon dioxide") .. ": " .. rd.GetResourceAmount(self, "carbon dioxide") .. "\n" OverlayText = OverlayText .. rd.GetProperResourceName("water") .. ": " .. rd.GetResourceAmount(self, "water") .. "\n" AddWorldTip(self:EntIndex(), OverlayText, 0.5, self:GetPos(), self) return end local TempY = 0 --local pos = self:GetPos() + (self:GetForward() ) + (self:GetUp() * 40 ) + (self:GetRight()) local pos = self:GetPos() + (self:GetUp() * (self:BoundingRadius() + 10)) local angle = (LocalPlayer():GetPos() - trace.HitPos):Angle() angle.r = angle.r + 90 angle.y = angle.y + 90 angle.p = 0 local textStartPos = -375 cam.Start3D2D(pos, angle, 0.03) surface.SetDrawColor(0, 0, 0, 125) surface.DrawRect(textStartPos, 0, 1250, 500) surface.SetDrawColor(155, 155, 155, 255) surface.DrawRect(textStartPos, 0, -5, 500) surface.DrawRect(textStartPos, 0, 1250, -5) surface.DrawRect(textStartPos, 500, 1250, -5) surface.DrawRect(textStartPos + 1250, 0, 5, 500) TempY = TempY + 10 surface.SetFont("ConflictText") surface.SetTextColor(255, 255, 255, 255) surface.SetTextPos(textStartPos + 15, TempY) surface.DrawText(self.PrintName) TempY = TempY + 70 surface.SetFont("Flavour") surface.SetTextColor(155, 155, 255, 255) surface.SetTextPos(textStartPos + 15, TempY) surface.DrawText("Owner: " .. playername) TempY = TempY + 70 surface.SetTextPos(textStartPos + 15, TempY) if nettable.network == 0 then surface.DrawText("Not connected to a network") else surface.DrawText("Network " .. nettable.network) end TempY = TempY + 70 surface.SetTextPos(textStartPos + 15, TempY) if self:GetOOO() == 0 then surface.DrawText("This Plant needs water") else surface.DrawText("This plant is healthy and has " .. tostring(self:GetNWInt(1)) .. " water left") end TempY = TempY + 70 local stringUsage = "" surface.SetTextPos(textStartPos + 15, TempY) stringUsage = stringUsage .. "[" .. rd.GetProperResourceName("water") .. ": " .. rd.GetResourceAmount(self, "water") .. "] " surface.DrawText(stringUsage) TempY = TempY + 70 stringUsage = "" surface.SetTextPos(textStartPos + 15, TempY) stringUsage = stringUsage .. "[" .. rd.GetProperResourceName("carbon dioxide") .. ": " .. rd.GetResourceAmount(self, "carbon dioxide") .. "] " surface.DrawText(stringUsage) TempY = TempY + 70 cam.End3D2D() end
local gameCode = '' local target = '$HOSTNAME' function encodeURI(str) if (str) then str = string.gsub (str, "\n", "\r\n") str = string.gsub (str, "([^%w ])", function (c) return string.format ("%%%02X", string.byte(c)) end) str = string.gsub (str, " ", "+") end return str end function sendToServer () --[[ Build and post JSON regarding users' hands --]] local fullData = {} for key, value in pairs(Player.getColors()) do if value ~= 'Grey' and Player[value] ~= nil and Player[value].getHandCount() > 0 then --[[ Iterate one player's hand --]] fullData[value] = {} for cardIndex, cardValue in pairs(Player[value].getHandObjects()) do local parsed = JSON.decode(cardValue.getJSON()) local custom = cardValue.getCustomObject() table.insert(fullData[value], { face = encodeURI(custom.face), back = encodeURI(custom.back), width = custom.width, height = custom.height, guid = parsed.GUID, offset = parsed.CardID % 100 }) end end end WebRequest.post(target .. '/hands?code=' .. gameCode, { payload = JSON.encode(fullData) }) end function sendDecks () local decks = {} for key, value in pairs(getAllObjects()) do if value.name == 'DeckCustom' or value.name == 'Deck' then local deckInfo = value.getCustomObject()[1] table.insert(decks, { name = value.getName(), back = encodeURI(deckInfo.back), unique = deckInfo.unique_back, guid = value.guid }) end end WebRequest.post(target .. '/decks?code=' .. gameCode, { payload = JSON.encode(decks) }) end function getServerHighlights () WebRequest.get(target .. '/highlights?code=' .. gameCode, processServerHighlights) end function processServerHighlights (data) local function starts_with(str, start) local trim = str:gsub("%s+", "") return trim:sub(1, #start) == start end if data.is_error == false and starts_with(data.text, "{") then local highlights = JSON.decode(data.text) for key, value in pairs(highlights) do -- let's try moving the object rather than highlighting if key == 'play' then local card = getObjectFromGUID(value) local pos = card.getPosition() pos.x = card.getTransformForward().x * 10 + math.random() pos.z = card.getTransformForward().z * 10 + math.random() card.setPosition(pos) card.flip() Wait.time(sendToServer, 0.5) elseif key == 'highlight' then getObjectFromGUID(value).highlightOn({0, 0, 1}, 10) elseif key == 'draw' then getObjectFromGUID(value.guid).deal(1, value.color) Wait.time(sendToServer, 0.5) end end end getServerHighlights() end function onObjectDrop(dropped_object, player_color) if gameCode ~= '' then sendToServer() end end function onObjectPickUp(picked_up_object, player_color) if gameCode ~= '' then sendToServer() end end function onObjectLeaveContainer( container, exit_object) if gameCode ~= '' and exit_object.name == 'Card' then Wait.time(sendToServer, 1.5) end end WebRequest.get(target .. '/create', function (data) if data.is_error == true then print('Something went wonky - please try reloading ambulator') else gameCode = JSON.decode(data.text).code print('Ambulated - go to ' .. target .. ' and enter code ' .. gameCode .. ' to join') getServerHighlights() sendToServer() sendDecks() end end)
-- * Metronome IM * -- -- This file is part of the Metronome XMPP server and is released under the -- ISC License, please see the LICENSE file in this source package for more -- information about copyright and licensing. module:depends("s2s") module:set_global() local hosts = hosts local incoming_s2s = metronome.incoming_s2s local default_hexed_text = "Your server is into this service's HEX List and is therefore forbidden to access it." local guard_blockall = module:get_option_set("host_guard_blockall", {}) local guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {}) local guard_protect = module:get_option_set("host_guard_selective", {}) local guard_block_bl = module:get_option_set("host_guard_blacklist", {}) local guard_hexlist = module:get_option_set("host_guard_hexlist", {}) local guard_hexlist_text = module:get_option_string("host_guard_hexlist_text", default_hexed_text) local error_reply = require "util.stanza".error_reply local tostring = tostring local function filter(origin, from_host, to_host) if not from_host or not to_host then return end if guard_hexlist:contains(from_host) then module:log("error", "remote hexed service %s attempted to access host %s", from_host, to_host) origin:close({condition = "policy-violation", text = guard_hexlist_text}) return true elseif guard_blockall:contains(to_host) and not guard_ball_wl:contains(from_host) or guard_block_bl:contains(from_host) and guard_protect:contains(to_host) then module:log("error", "remote service %s attempted to access restricted host %s", from_host, to_host) origin:close({condition = "policy-violation", text = "You're not authorized, good bye."}) return true end return end local function rr_hook (event) local from_host, to_host, send, stanza = event.from_host, event.to_host, (event.origin and event.origin.send) or function() end, event.stanza if guard_hexlist:contains(to_host) or (guard_blockall:contains(from_host) and not guard_ball_wl:contains(to_host)) or (guard_block_bl:contains(to_host) and guard_protect:contains(from_host)) then module:log("info", "attempted to connect to a filtered remote host %s", to_host) if stanza.attr.type ~= "error" then send(error_reply(event.stanza, "cancel", "policy-violation", "Communicating with a filtered remote server is not allowed.")) end return true end return end function module.add_host(module) local host = module.host if not host.anonymous then module:hook("route/remote", rr_hook, 500) module:hook("stanza/jabber:server:dialback:result", function(event) return filter(event.origin, event.stanza.attr.from, event.stanza.attr.to) end, 500) end end local function close_filtered() for _, host in pairs(hosts) do for name, session in pairs(host.s2sout) do if guard_hexlist:contains(session.to_host) or (guard_blockall:contains(session.host) and not guard_ball_wl:contains(session.to_host)) or (guard_block_bl:contains(session.to_host) and guard_protect:contains(session.host)) then module:log("info", "closing down s2s outgoing stream to filtered entity %s", tostring(session.to_host)) session:close() end end end for session in pairs(incoming_s2s) do if session.to_host and session.from_host and guard_hexlist:contains(session.from_host) or (guard_blockall:contains(session.to_host) and not guard_ball_wl:contains(session.from_host) or guard_block_bl:contains(session.from_host) and guard_protect:contains(session.to_host)) then module:log("info", "closing down s2s incoming stream from filtered entity %s", tostring(session.from_host)) session:close() end end end local function reload() module:log("debug", "reloading filters configuration...") guard_blockall = module:get_option_set("host_guard_blockall", {}) guard_ball_wl = module:get_option_set("host_guard_blockall_exceptions", {}) guard_protect = module:get_option_set("host_guard_selective", {}) guard_block_bl = module:get_option_set("host_guard_blacklist", {}) guard_hexlist = module:get_option_set("host_guard_hexlist", {}) guard_hexlist_text = module:get_option_string("host_guard_hexlist_text", default_hexed_text) close_filtered() end local function setup() module:log("debug", "initializing host guard module...") module:hook("config-reloaded", reload) module:hook("s2s-filter", filter) end if metronome.start_time then setup() else module:hook("server-started", setup) end
adult_pygmy_torton = Creature:new { objectName = "@mob/creature_names:torton_pygmy_adult", socialGroup = "torton", faction = "", level = 20, chanceHit = 0.31, damageMin = 190, damageMax = 200, baseXp = 1609, baseHAM = 2000, baseHAMmax = 2400, armor = 0, resists = {120,120,5,5,5,-1,-1,200,-1}, meatType = "meat_carnivore", meatAmount = 600, hideType = "hide_wooly", hideAmount = 400, boneType = "bone_mammal", boneAmount = 600, milk = 0, tamingChance = 0.25, ferocity = 0, pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY, creatureBitmask = PACK + HERD, optionsBitmask = AIENABLED, diet = HERBIVORE, templates = {"object/mobile/torton_hue.iff"}, hues = { 0, 1, 2, 3, 4, 5, 6, 7 }, scale = .55, lootGroups = {}, weapons = {}, conversationTemplate = "", attacks = { {"stunattack",""}, {"dizzyattack",""} } } CreatureTemplates:addCreatureTemplate(adult_pygmy_torton, "adult_pygmy_torton")
function safe_string(value) if type(value) == "string" then local v = string.gsub(value, "([\\\10\13%c%z\"])([0-9]?)", function(chr, digit) local b = string.byte(chr) if #digit == 1 then if string.len(b) == 1 then return "\\00"..b..digit end if string.len(b) == 2 then return "\\0"..b..digit end end return "\\"..b..digit end) return '"'..v..'"' elseif type(value) == "number" then if not ((value > 0) or (value < 0) or (value == 0)) then -- indeterminate form return "0/0" elseif value == 1/0 then -- infinity return "1/0" elseif value == -1/0 then -- negative infinity return "-1/0" else return value end elseif type(value) == "function" then local ok, dump = pcall(string.dump, value) if ok then return "loadstring("..safe_string(dump)..")" end elseif type(value) == "boolean" then return tostring(value) elseif type(value) == "nil" then return "nil" end return "nil --[=[can't serialize; "..tostring(value).."]=]" end function safe_key(key) local safe_name = string.match(key, "^([A-Za-z_]+[A-Za-z0-9_]*)$") local keywords = { ["and"] = true, ["break"] = true, ["do"] = true, ["else"] = true, ["elseif"] = true, ["end"] = true, ["false"] = true, ["for"] = true, ["function"] = true, ["goto"] = true, ["if"] = true, ["in"] = true, ["local"] = true, ["nil"] = true, ["not"] = true, ["or"] = true, ["repeat"] = true, ["return"] = true, ["then"] = true, ["true"] = true, ["until"] = true, ["while"] = true } if safe_name and not keywords[safe_name] then return safe_name, "." end return "["..safe_string(key).."]", "" end local function testname(name) assert( (type(name) == "table") or (name:sub(1,1) == ".") or (name:sub(1,1) == "[") or (name:sub(1,4) == "root") or (name:sub(1,3) == "key") ) end function serialize(value, name_or_bool_for_return, fnc_write, skip) local buf if not fnc_write then buf = {}; fnc_write = function(data) table.insert(buf, data) end end if ( type(name_or_bool_for_return) == "string" ) then fnc_write(name_or_bool_for_return) fnc_write(" = ") elseif ( type(name_or_bool_for_return) == "boolean" and name_or_bool_for_return == true ) then fnc_write("return ") end if type(value) == "table" then local obj_map = {} local keys = {order = {}, links = {}} local recover = {} local recovery_name = "recovery" local deep = 0 local function add_key_value(tabl, key, value) local links = keys.links[key] if not links then table.insert(keys.order, key) links = {} keys.links[key] = links end table.insert(links, {tabl = tabl, value = value}) end local serialize_table local function serialize_value(value, name, parent) if type(value) == "table" then serialize_table(value, name, parent) else fnc_write(safe_string(value)) if (type(value) == "function") then obj_map[value] = {name = name , parent = parent} end end end local function tbl_new_line(not_empty, deep) return string.format((not_empty and ",\n%s") or "\n%s", string.rep("\t", deep)) end function serialize_table(tabl, name, parent, open) assert(obj_map[tabl] == nil) obj_map[tabl] = {name = name , parent = parent} testname(name) fnc_write("{") deep = deep + 1 local not_empty local last_index for index, value in ipairs(tabl) do if obj_map[value] then break end if (not skip) or not skip(tabl, index, value) then fnc_write(tbl_new_line(not_empty, deep)) serialize_value(value, string.format("[%i]", index), tabl) last_index = index not_empty = true end end for key, value in pairs(tabl) do if (not skip) or not skip(tabl, key, value) then if (type(key) == "table") or (type(key) == "function") then add_key_value(tabl, key, value) elseif (not last_index) or (type(key) ~= "number") or (key > last_index) or (key < 1) or (key > math.floor(key)) then local name, dot = safe_key(key) testname(dot..name) if obj_map[value] then table.insert(recover, {tabl = tabl, name = dot..name, value = value}) else fnc_write(string.format("%s%s=", tbl_new_line(not_empty, deep), name)) serialize_value(value, dot..name, tabl) not_empty = true end end end end deep = deep - 1 if not open then if not_empty then fnc_write(string.format("\n%s}", string.rep("\t", deep))) else fnc_write("}") end end return not_empty end local get_key, format_key function format_key(key) if obj_map[key] then return string.format("[%s]", get_key(key)) else return key end end function get_key(obj) local key = {} local info = obj_map[obj] while info do table.insert(key, 1, format_key(info.name)) info = obj_map[info.parent] end return table.concat(key) end fnc_write("(") if value[recovery_name] then local indx = 0 local new_name repeat new_name = recovery_name..indx indx = indx + 1 until not value[new_name] recovery_name = new_name end local not_empty = serialize_table(value, "root", nil, true) -- recover links if next(keys.order) or next(recover) then deep = deep + 2 local tabs = string.rep("\t", deep) fnc_write(string.format("%s%s=function(root)\n\t\troot.%s=nil;\n\t\tlocal key={};\n", ((not_empty and ",\n\t") or ""), recovery_name, recovery_name)) local idx = 0 while next(keys.order) do local keys_old = keys keys = {order = {}, links = {}} for _, key in ipairs(keys_old.order) do if not obj_map[key] then idx = idx + 1 local key_name = string.format("key[%i]", idx) fnc_write(string.format("%s%s=", tabs, key_name)) serialize_value(key, key_name) fnc_write(";\n") end for _, link in pairs(keys_old.links[key]) do if obj_map[link.value] then testname(key) table.insert(recover, {tabl = link.tabl, name = key, value = link.value}) else fnc_write(string.format("%s%s[%s]=", tabs, get_key(link.tabl), get_key(key))) serialize_value(link.value, key, link.tabl) fnc_write(";\n") end end end end for _, rec in ipairs(recover) do fnc_write(string.format("%s%s%s=%s;\n", tabs, get_key(rec.tabl), format_key(rec.name), get_key(rec.value))) end fnc_write(string.format("\t\treturn root;\n\tend\n}):%s()", recovery_name)) else fnc_write("})") end else fnc_write(safe_string(value)) end if ( buf ) then return table.concat(buf) end end
local class = require 'ext.class' local table = require 'ext.table' local symmath = require 'symmath' local template = require 'template' local CoordinateSystem = require 'hydro.coord.coord' local sin, cos = symmath.sin, symmath.cos local Tensor = symmath.Tensor local Sphere = class(CoordinateSystem) Sphere.name = 'sphere' --[[ args volumeDim = (TODO) change volume element etc to act as if we're in a higher dimension TODO add some other arg for rearranging the coordinate order so we can do 2D simulations of θ and φ alone --]] function Sphere:init(args) self.embedded = table{symmath.vars('x', 'y', 'z')} local r, theta, phi = symmath.vars('r', 'θ', 'φ') self.baseCoords = table{r, theta, phi} -- TODO same as lenExprs self.eHolToE = symmath.Matrix( {1, 0, 0}, {0, 1/r, 0}, {0, 0, 1/(r*symmath.sin(theta))} ) self.chart = function() return Tensor('^I', r * sin(theta) * cos(phi), r * sin(theta) * sin(phi), r * cos(theta) ) end Sphere.super.init(self, args) self.vars = { r = r, x = r * sin(theta) * cos(phi), y = r * sin(theta) * sin(phi), z = r * cos(theta), } end function Sphere:getCoordMapInvModuleCode() return template([[ real3 coordMapInv(real3 x) { <? if solver.dim == 1 then ?> real r = fabs(x.x); real theta = 0.; real phi = 0.; <? elseif solver.dim == 2 then -- xy -> rθ ?> real r = sqrt(x.x*x.x + x.y*x.y); real theta = acos(x.y / r); real phi = 0.; <? elseif solver.dim == 3 then -- xyz - rθφ ?> real r = length(x); real theta = acos(x.z / r); real phi = atan2(x.y, x.x); <? end ?> return _real3(r, theta, phi); } ]], { solver = self.solver, }) end function Sphere:getModuleDepends_coord_parallelPropagate() return {'rotate'} end function Sphere:getParallelPropagatorCode() return template([[ <? if coord.vectorComponent == 'holonomic' then ?> real3 coord_parallelPropagateU0(real3 v, real3 x, real dx) { real rL = x.x; real rR = x.x + dx; v.y *= rL / rR; v.z *= rL / rR; return v; } real3 coord_parallelPropagateL0(real3 v, real3 x, real dx) { real rL = x.x; real rR = x.x + dx; v.y *= rR / rL; v.z *= rR / rL; return v; } real3 coord_parallelPropagateU1(real3 v, real3 x, real dx) { real r = x.x; real thetaL = x.y; real thetaR = x.y + dx; real sinThetaL = sin(thetaL); real sinThetaR = sin(thetaR); v.y *= r; v.z *= sinThetaL; v = real3_rotateZ(v, -dx); v.y /= r; v.z /= sinThetaR; return v; } real3 coord_parallelPropagateL1(real3 v, real3 x, real dx) { real r = x.x; real thetaL = x.y; real thetaR = x.y + dx; real sinThetaL = sin(thetaL); real sinThetaR = sin(thetaR); v.y /= r; v.z /= sinThetaL; v = real3_rotateZ(v, -dx); v.y *= r; v.z *= sinThetaR; return v; } real3 coord_parallelPropagateU2(real3 v, real3 x, real dx) { real r = x.x; real theta = x.y; real sinTheta = sin(theta); real rSinTheta = r * sinTheta; v.y *= r; v.z *= rSinTheta; v = real3_rotateZ(v, theta); v = real3_rotateX(v, -dx); v = real3_rotateZ(v, -theta); v.y /= r; v.z /= rSinTheta; return v; } real3 coord_parallelPropagateL2(real3 v, real3 x, real dx) { real r = x.x; real theta = x.y; real sinTheta = sin(theta); real rSinTheta = r * sinTheta; v.y /= r; v.z /= rSinTheta; v = real3_rotateZ(v, theta); v = real3_rotateX(v, -dx); v = real3_rotateZ(v, -theta); v.y *= r; v.z *= rSinTheta; return v; } <? else ?> #define coord_parallelPropagateU0(v,x,dx) (v) real3 coord_parallelPropagateU1(real3 v, real3 x, real dx) { return real3_rotateZ(v, -dx); } real3 coord_parallelPropagateU2(real3 v, real3 x, real dx) { return real3_rotateX(v, -dx); } <? end ?> ]], { coord = self, }) end function Sphere:createCellStruct() Sphere.super.createCellStruct(self) self.cellStruct.vars:insert{name='r', type='real'} end function Sphere:fillGridCellBuf(cellsCPU) local solver = self.solver local symmath = require 'symmath' local r, theta, phi = self.baseCoords:unpack() local calcR, code = symmath.export.Lua:toFunc{ output = {self.vars.r}, input = {{r=r}, {theta=theta}, {phi=phi}}, } local index = 0 for k=0,tonumber(solver.gridSize.z)-1 do local phi = solver.dim >= 3 and ((k + .5 - solver.numGhost) / (tonumber(solver.gridSize.z) - 2 * solver.numGhost) * (solver.maxs.z - solver.mins.z) + solver.mins.z) or (.5 * (solver.maxs.z + solver.mins.z)) for j=0,tonumber(solver.gridSize.y)-1 do local theta = solver.dim >= 2 and ((j + .5 - solver.numGhost) / (tonumber(solver.gridSize.y) - 2 * solver.numGhost) * (solver.maxs.y - solver.mins.y) + solver.mins.y) or (.5 * (solver.maxs.y + solver.mins.y)) for i=0,tonumber(solver.gridSize.x)-1 do local r = solver.dim >= 1 and ((i + .5 - solver.numGhost) / (tonumber(solver.gridSize.x) - 2 * solver.numGhost) * (solver.maxs.x - solver.mins.x) + solver.mins.x) or (.5 * (solver.maxs.x + solver.mins.x)) cellsCPU[index].pos.x = r cellsCPU[index].pos.y = theta cellsCPU[index].pos.z = phi cellsCPU[index].r = calcR(r, theta, phi) index = index + 1 end end end end return Sphere
local Label = {}; Label.__index = Label function Label:new(x, y, w, h, text, color, align) local this = setmetatable({ position = {x = x or 0, y = y or 0}, w = w, h = h, text = text or "", align = align or "center", color = color or {1, 1, 1, 1} }, Label) return this end function Label:setText(text) self.text = text end function Label:addText(text) self.text = self.text .. text end function Label:draw() local currentFont = love.graphics.getFont() local _, lines = currentFont:getWrap(self.text, self.w) local fontHeight = currentFont:getHeight() local red, green, blue, alpha = love.graphics.getColor() love.graphics.setColor(unpack(self.color)) love.graphics.printf(self.text, self.position.x, self.position.y - (fontHeight /2 * #lines), self.w, self.align) love.graphics.setColor(red, green, blue, alpha) --love.graphics.rectangle("line", self.position.x, self.position.y - self.h /2, self.w, self.h) end return Label
DxLabel = {} DxLabel.__mt = {__index = DxLabel} DxLabel.list = {} function DxLabel:render() if(not self.visible) then return end if(self.buffered) then self:renderBuffer() else self:renderInternal(self.left, self.top, self.right, self.bottom, self.alignX, self.alignY) end end function DxLabel:renderBuffer() if(self.dirty or not self.buffer) then self:updateBuffer() end local x, y = self.left, self.top if(self.alignX == "center") then x = (self.left + self.right - self.bufferW)/2 end if(self.alignY == "center") then y = (self.top + self.bottom - self.bufferH)/2 end dxDrawImage(x, y, self.bufferW, self.bufferH, self.buffer) end function DxLabel:renderInternal(left, top, right, bottom, alignX, alignY) if(self.shadow) then -- render target has alpha channel and doesnt add alpha values local a if(self.buffered) then a = self.shadow else local n = (self.shadowBlur + 1) a = math.floor(255 - ((1 - self.shadow/255)^(1/n))*255) end local color = tocolor(0, 0, 0, a) for offX = self.shadowOffsetX - self.shadowBlur, self.shadowOffsetX + self.shadowBlur do for offY = self.shadowOffsetY - self.shadowBlur, self.shadowOffsetY + self.shadowBlur do dxDrawText(self.textWithoutCodes, left + offX, top + offY, right + offX, bottom + offY, color, self.scale, self.font, alignX, alignY, self.clip) end end end if(self.border) then for offX = -self.border, self.border do for offY = -self.border, self.border do if(offX ~= 0 or offY ~= 0) then dxDrawText(self.textWithoutCodes, left + offX, top + offY, right + offX, bottom + offY, self.borderColor, self.scale, self.font, alignX, alignY, self.clip) end end end end dxDrawText(self.text, left, top, right, bottom, self.color, self.scale, self.font, alignX, alignY, self.clip, false, false, self.colorCoded) end function DxLabel:updateBuffer() if(self.buffer) then destroyElement(self.buffer) end local marginLeft, marginTop, marginRight, marginBottom = 0, 0, 0, 0 if(self.shadow) then marginLeft = math.max(marginLeft, -self.shadowOffsetX + self.shadowBlur) marginRight = math.max(marginRight, self.shadowOffsetX + self.shadowBlur) marginTop = math.max(marginTop, -self.shadowOffsetY + self.shadowBlur) marginBottom = math.max(marginBottom, self.shadowOffsetY + self.shadowBlur) end if(self.border) then marginLeft = math.max(marginLeft, self.border) marginRight = math.max(marginRight, self.border) marginTop = math.max(marginTop, self.border) marginBottom = math.max(marginBottom, self.border) end self.bufferW = dxGetTextWidth(self.text, self.scale, self.font) + marginLeft + marginRight self.bufferH = dxGetFontHeight(self.scale, self.font) + marginTop + marginBottom self.buffer = dxCreateRenderTarget(self.bufferW, self.bufferH, true) dxSetRenderTarget(self.buffer, true) --dxDrawRectangle(0, 0, self.bufferW, self.bufferH, tocolor(255, 128, 128)) --dxDrawRectangle(marginLeft, marginTop, self.bufferW - marginLeft - marginRight, self.bufferH - marginTop - marginBottom, tocolor(255, 255, 128)) self:renderInternal(marginLeft, marginTop, self.bufferW - marginLeft, self.bufferH - marginTop, "left", "top") self.dirty = false dxSetRenderTarget() end function DxLabel:setText(text) if(self.text == text) then return end self.text = text self.textWithoutCodes = self.colorCoded and self.text:gsub("#%x%x%x%x%x%x", "") or self.text self.dirty = true end function DxLabel:setPosition(left, top, right, bottom) self.left = left self.top = top self.right = right or left self.bottom = bottom or top end function DxLabel:setColor(clr) self.color = clr self.dirty = true end function DxLabel:setScale(scale) self.scale = scale self.dirty = true end function DxLabel:setFont(font, scale) self.font = font self.scale = scale or self.scale self.dirty = true end function DxLabel:setShadow(alpha, offsetX, offsetY, blur, color) self.shadow = alpha self.shadowOffsetX = offsetX or 2 self.shadowOffsetY = offsetY or 2 self.shadowBlur = blur or 0 self.dirty = true end function DxLabel:setBorder(value, color) self.border = value self.borderColor = color or tocolor(0, 0, 0) self.dirty = true end function DxLabel:setVisible(visible) self.visible = visible end function DxLabel:setAlign(align) self.alignX = align end function DxLabel:setVerticalAlign(valign) self.alignY = valign end function DxLabel:setColorCoded(colorCoded) self.colorCoded = colorCoded self.textWithoutCodes = self.colorCoded and self.text:gsub("#%x%x%x%x%x%x", "") or self.text self.dirty = true end function DxLabel:setBuffered(buffered) if(not buffered and self.buffer) then destroyElement(self.buffer) self.buffer = false end self.buffered = buffered end function DxLabel:destroy() DxLabel.list[self] = nil if(self.buffer) then destroyElement(self.buffer) self.buffer = false end end function DxLabel.create(text, left, top, right, bottom) local self = setmetatable({}, DxLabel.__mt) self.text = text self.textWithoutCodes = text self.left = left self.top = top self.right = right or left self.bottom = bottom or top self.color = tocolor(255, 255, 255) self.scale = 1 self.font = "default" self.shadow = false self.border = false self.alignX = "left" self.alignY = "top" self.clip = false self.colorCoded = false self.visible = true self.buffered = false DxLabel.list[self] = true return self end function DxLabel.renderAll() for text, _ in pairs(DxLabel.list) do text:render() end end addEventHandler("onClientRender", g_Root, DxLabel.renderAll) --[[ n 1: s*(1-a)+a*c -> a 2: (s*(1-a)+a*c)*(1-a)+a*c -> a+a*(1-a) 3: ((s*(1-a)+a*c)*(1-a)+a*c)*(1-a)+a*c ->a+a*(1-a)+(1-a)*(1-a)*a -> a*(1-(1-a)^n)/(1-(1-a)) = 1-(1-a)^n ok x = 1-(1-a)^n (1-a)^n = 1-x 1-a = (1-x)^(1/n) a = 1 - (1-x)^(1/n) x/255 = 1-(1-a/255)^n ]]
local objects = { --Maxime createObject(18024,877.2999878,164.6000061,1011.5000000,0.0000000,0.0000000,0.0000000,41), --object(int_clothe_ship,41), (1,41), createObject(1967,854.2999878,154.1000061,1009.5999756,0.0000000,0.0000000,90.0000000,41), --object(imcmptrkdrr_las,41), (1,41), createObject(18024,857.3994141,163.8994141,1011.2999878,0.0000000,0.0000000,0.0000000,41), --object(int_clothe_ship,41), (2,41), createObject(5779,860.0000000,154.0000000,1009.9000244,0.0000000,0.0000000,90.0000000,41), --object(garagdoor1_lawn,41), (1,41), createObject(5779,850.0999756,154.0000000,1009.9000244,0.0000000,0.0000000,90.0000000,41), --object(garagdoor1_lawn,41), (2,41), createObject(16151,861.5996094,168.5996094,1008.4920044,0.0000000,0.0000000,0.0000000,41), --object(ufo_bar,41), (1,41), createObject(2188,848.9000244,155.6000061,1009.0999756,0.0000000,0.0000000,135.0000000,41), --object(blck_jack,41), (3,41), createObject(2289,854.5000000,172.6999969,1011.0700073,0.0000000,0.0000000,0.0000000,41), --object(frame_2,41), (1,41), createObject(2287,858.0999756,172.3000031,1010.7069702,0.0000000,0.0000000,0.0000000,41), --object(frame_4,41), (1,41), createObject(2284,849.5999756,172.0000000,1010.6707153,0.0000000,0.0000000,0.0000000,41), --object(frame_6,41), (1,41), createObject(1723,847.8994141,159.8000031,1008.2000122,0.0000000,0.0000000,90.0000000,41), --object(mrk_seating1,41), (1,41), createObject(1824,850.2000122,170.1999969,1009.2000122,0.0000000,0.0000000,0.0000000,41), --object(craps_table,41), (1,41), createObject(2026,855.0100098,155.1999969,1012.1697998,0.0000000,0.0000000,0.0000000,41), --object(mrk_shade_tmp,41), (1,41), createObject(2026,855.0097656,170.1992188,1012.1697998,0.0000000,0.0000000,0.0000000,41), --object(mrk_shade_tmp,41), (2,41), createObject(2026,855.0097656,167.1992188,1012.1697998,0.0000000,0.0000000,0.0000000,41), --object(mrk_shade_tmp,41), (3,41), createObject(2026,855.0097656,163.1992188,1012.1697998,0.0000000,0.0000000,0.0000000,41), --object(mrk_shade_tmp,41), (4,41), createObject(2026,855.0097656,159.1992188,1012.1697998,0.0000000,0.0000000,0.0000000,41), --object(mrk_shade_tmp,41), (5,41), createObject(1723,853.5000000,169.1999969,1008.2000122,0.0000000,0.0000000,90.0000000,41), --object(mrk_seating1,41), (2,41), createObject(1723,854.4000244,172.1699982,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(mrk_seating1,41), (3,41), createObject(1724,851.8994141,167.3099976,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(mrk_seating1b,41), (2,41), createObject(1724,857.7000122,172.1699982,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(mrk_seating1b,41), (3,41), createObject(1724,848.4000244,167.3099976,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(mrk_seating1b,41), (4,41), createObject(1723,847.8994141,164.0996094,1008.2000122,0.0000000,0.0000000,90.0000000,41), --object(mrk_seating1,41), (4,41), createObject(2188,860.8994141,156.0996094,1009.0999756,0.0000000,0.0000000,225.0000000,41), --object(blck_jack,41), (1,41), createObject(2188,864.6992188,159.8999939,1009.4000244,0.0000000,0.0000000,90.0000000,41), --object(blck_jack,41), (1,41), createObject(646,853.2999878,172.3000031,1009.5999756,0.0000000,0.0000000,0.0000000,41), --object(veg_palmkb14,41), (1,41), createObject(646,847.7998047,167.1992188,1009.5999756,0.0000000,0.0000000,0.0000000,41), --object(veg_palmkb14,41), (2,41), createObject(646,857.2000122,172.3999939,1009.5999756,0.0000000,0.0000000,0.0000000,41), --object(veg_palmkb14,41), (3,41), createObject(1892,854.5000000,155.3000031,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(security_gatsh,41), (1,41), createObject(14749,848.5996094,172.8994141,1010.7999878,0.0000000,0.0000000,269.9945068,41), --object(sfhsm1lights,41), (2,41), createObject(1822,847.5000000,162.3999939,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(coffee_swank_6,41), (1,41), createObject(646,847.7999878,159.0000000,1009.5999756,0.0000000,0.0000000,0.0000000,41), --object(veg_palmkb14,41), (4,41), createObject(1723,862.1580200,161.0000000,1008.2000122,0.0000000,0.0000000,270.0000000,41), --object(mrk_seating1,41), (5,41), createObject(646,862.0000000,158.1000061,1009.5999756,0.0000000,0.0000000,0.0000000,41), --object(veg_palmkb14,41), (6,41), createObject(2606,865.5999756,168.6000061,1010.0999756,0.0000000,0.0000000,0.0000000,41), --object(cj_police_counter2,41), (1,41), createObject(2959,865.0996094,165.0996094,1008.4000244,0.0000000,0.0000000,270.0000000,41), --object(rider1_door,41), (1,41), createObject(2959,866.5996094,161.5000000,1008.4000244,0.0000000,0.0000000,90.0000000,41), --object(rider1_door,41), (2,41), createObject(2640,855.5000000,160.0000000,1009.0000000,0.0000000,0.0000000,90.0000000,41), --object(neil_slot,41), (1,41), createObject(2640,854.2999878,160.0500031,1009.0000000,0.0000000,0.0000000,270.0000000,41), --object(neil_slot,41), (2,41), createObject(2640,855.5000000,160.8000031,1009.0000000,0.0000000,0.0000000,90.0000000,41), --object(neil_slot,41), (3,41), createObject(2640,855.5000000,161.6000061,1009.0000000,0.0000000,0.0000000,90.0000000,41), --object(neil_slot,41), (4,41), createObject(2640,855.5000000,162.3999939,1009.0000000,0.0000000,0.0000000,90.0000000,41), --object(neil_slot,41), (5,41), createObject(2640,855.5000000,163.1999969,1009.0000000,0.0000000,0.0000000,90.0000000,41), --object(neil_slot,41), (6,41), createObject(2640,854.2999878,160.8500061,1009.0000000,0.0000000,0.0000000,269.9945068,41), --object(neil_slot,41), (7,41), createObject(2640,854.2999878,161.6499939,1009.0000000,0.0000000,0.0000000,270.0000000,41), --object(neil_slot,41), (8,41), createObject(2640,854.2999878,162.4600067,1009.0000000,0.0000000,0.0000000,269.9945068,41), --object(neil_slot,41), (9,41), createObject(2640,854.2999878,163.2599945,1009.0000000,0.0000000,0.0000000,269.9945068,41), --object(neil_slot,41), (10,41), createObject(1723,850.0000000,161.8000031,1008.2000122,0.0000000,0.0000000,270.0000000,41), --object(mrk_seating1,41), (6,41), createObject(1723,850.0000000,166.0996094,1008.2000122,0.0000000,0.0000000,269.9945068,41), --object(mrk_seating1,41), (7,41), createObject(1724,860.5999756,162.0000000,1008.2000122,0.0000000,0.0000000,0.0000000,41), --object(mrk_seating1b,41), (5,41), createObject(1723,847.8994141,164.0996094,1008.2000122,0.0000000,0.0000000,90.0000000,41), --object(mrk_seating1,41), (8,41), createObject(1723,860.0000000,158.8999939,1008.2000122,0.0000000,0.0000000,90.0000000,41), --object(mrk_seating1,41), (9,41), createObject(1723,856.5000000,168.1999969,1008.2000122,0.0000000,0.0000000,180.0000000,41), --object(mrk_seating1,41), (10,41), createObject(646,853.4000244,168.3999939,1009.5999756,0.0000000,0.0000000,0.0000000,41), --object(veg_palmkb14,41), (7,41), createObject(3440,854.9000244,158.5000000,1010.5000000,0.0000000,0.0000000,0.0000000,41), --object(arptpillar01_lvs,41), (1,41), createObject(3440,854.9000244,165.1000061,1010.5000000,0.0000000,0.0000000,0.0000000,41), --object(arptpillar01_lvs,41), (2,41), createObject(1895,867.2000122,163.3000031,1010.8300171,0.0000000,0.0000000,270.0000000,41), --object(wheel_o_fortune,41), (1,41), createObject(2010,866.7000122,164.6000061,1008.3699951,0.0000000,0.0000000,0.0000000,41), --object(nu_plant3_ofc,41), (1,41), createObject(2010,866.7000122,162.0200043,1008.3699951,0.0000000,0.0000000,0.0000000,41), --object(nu_plant3_ofc,41), (2,41), } local col = createColSphere(855.017578125, 154.5146484375, 1009.151550293, 20) local function watchChanges( ) if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then for key, value in pairs( objects ) do setElementDimension( value, getElementDimension( getLocalPlayer( ) ) ) end elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end end end addEventHandler( "onClientColShapeHit", col, function( element ) if element == getLocalPlayer( ) then addEventHandler( "onClientRender", root, watchChanges ) end end ) addEventHandler( "onClientColShapeLeave", col, function( element ) if element == getLocalPlayer( ) then removeEventHandler( "onClientRender", root, watchChanges ) end end ) -- Put them standby for now. for key, value in pairs( objects ) do setElementDimension( value, 65535 ) end for index, object in ipairs ( objects ) do setElementDoubleSided ( object, true ) -- if getElementModel(object) == 10281 then -- setObjectScale ( object, 0.60000002384186 ) -- end --setElementCollisionsEnabled ( object, true ) end
return function(source_module_inventory, target_entity, player, interact_with_player, create_logistic_request) -- prepare commonly used variables local target_inventory = target_entity.get_module_inventory() if not target_inventory then return end local player_inventory = player.get_main_inventory() -- before start, remove existing logistic requests for modules local target_requests = target_entity.surface.find_entities_filtered({ area = { { target_entity.position.x - 0.01, target_entity.position.y - 0.01 }, { target_entity.position.x + 0.01, target_entity.position.y + 0.01 } }, name = "item-request-proxy", force = player.force }) for _,request in pairs(target_requests) do if request.proxy_target == target_entity then local item_requests = request.item_requests for name,_ in pairs(item_requests) do if game.item_prototypes[name].type == "module" then item_requests[name] = nil end end if next(item_requests) == nil then request.destroy() else request.item_requests = item_requests end end end -- next, prepare the "diff" for message display, positive number indicates direction from player to target local diff = {} -- keep modules from target machine in a variable for now, give them to player (or dump them on the ground) at the end local modules_to_give = target_inventory.get_contents() -- and clear target inventory target_inventory.clear() -- then, (re)insert modules from previous modules or the player to target machine local missing = {} for i=1,math.min(#target_inventory, #source_module_inventory),1 do local currentItem = source_module_inventory[i]; if currentItem.valid_for_read then -- item present local name = currentItem.name local module_taken = false if (modules_to_give[name] or 0) > 0 then -- first, try to take from previous modules modules_to_give[name] = modules_to_give[name] - 1 module_taken = true elseif interact_with_player then -- if that fails, try to take it from the player local taken = player_inventory.remove({ name = name, count = 1 }) if taken > 0 then diff[name] = (diff[name] or 0) + 1 module_taken = true end end if module_taken then -- we took the module and can now give it to the target machine target_inventory[i].set_stack({ name = name, count = 1 }) else -- module is missing: save that info for creating a logistic request later missing[name] = (missing[name] or 0) + 1 end end end -- next, give remaining items to the player or dump them on the ground for name,count in pairs(modules_to_give) do if count > 0 then local given = 0; if interact_with_player then given = player_inventory.insert({ name = name, count = count }) if given > 0 then -- items given to player, save that info to "diff" to display message later diff[name] = (diff[name] or 0) - given end end if given < count then -- not all items could be given, "dump" them the ground if (interact_with_player) then player.print({ "message.kajacx_copy-paste-modules_no-inventory-space", game.item_prototypes[name].localised_name }) end target_entity.surface.spill_item_stack( target_entity.position, { name = name, count = count - given }, true, player.force, false ) end end end -- process the created "diff" to display "items moved" text and play sound if interact_with_player then local message_position = { x = target_entity.position.x, y = target_entity.position.y } local play_sound = false; for name,count in pairs(diff) do if count > 0 then -- moving items from the player to a machine target_entity.surface.create_entity({ name = "flying-text", position = message_position, text = { "message.kajacx_copy-paste-modules_items-removed", count, game.item_prototypes[name].localised_name, player_inventory.get_item_count(name) } }) message_position.y = message_position.y - 0.5 play_sound = true; elseif count < 0 then -- moving items from a machine to the player target_entity.surface.create_entity({ name = "flying-text", position = message_position, text = { "message.kajacx_copy-paste-modules_items-added", -count, game.item_prototypes[name].localised_name, player_inventory.get_item_count(name) } }) message_position.y = message_position.y - 0.5 play_sound = true; end end if play_sound then player.play_sound({ path = "utility/inventory_move" }) end end -- finally, create logistic request in the target entity if next(missing) ~= nil and create_logistic_request then local free_slots = target_inventory.count_empty_stacks() if free_slots > 0 then local request = {} -- fill from missing to request as long as there are free slots avaliable for name,count in pairs(missing) do if count <= free_slots then request[name] = count free_slots = free_slots - count else request[name] = free_slots break end end target_entity.surface.create_entity({ name = "item-request-proxy", position = target_entity.position, force = player.force, target = target_entity, modules = request, raise_built = true }) -- TODO: sort the items once the request is completed? end end end
local ReplicatedStorage = game:GetService('ReplicatedStorage') local Modules = ReplicatedStorage:WaitForChild('Modules') -- local logger = require(Modules.src.utils.Logger) local clientSrc = game:GetService('StarterPlayer'):WaitForChild('StarterPlayerScripts').clientSrc local M = require(Modules.M) local Roact = require(Modules.Roact) local Time = require(Modules.src.Time) local TextLabel = require(clientSrc.Components.common.TextLabel) local createElement = Roact.createElement local Timer = Roact.PureComponent:extend('Timer') function Timer:init() self:setState({ currentTime = self.props.initialTime or 0 }) end function Timer:didMount() self.running = true -- We don't want to block the main thread, so we spawn a new one! spawn(function() while self.running do self:setState(function(state) local updateTime = self.props.key == state.key if updateTime then return { currentTime = state.currentTime + 1, initialTime = self.props.initialTime, } else return { currentTime = 0, initialTime = self.props.initialTime, key = self.props.key, } end end) wait(1) end end) end function Timer:willUnmount() self.running = false end function Timer:render() local props = self.props local initialTime = props.initialTime local increment = props.increment local duration = initialTime - os.time() if increment then duration = os.time() - initialTime end return createElement( TextLabel, M.extend(M.omit(props, 'increment', 'initialTime', 'key'), { Text = Time.FormatTime(duration), }) ) end return Timer
--- -- @module Armor -- -- ------------------------------------------------ -- Required Modules -- ------------------------------------------------ local Item = require( 'src.items.Item' ) -- ------------------------------------------------ -- Module -- ------------------------------------------------ local Armor = Item:subclass( 'Armor' ) -- ------------------------------------------------ -- Public Methods -- ------------------------------------------------ function Armor:initialize( template ) Item.initialize( self, template ) self.armorProtection = template.armor.protection self.armorCoverage = template.armor.coverage end function Armor:getArmorProtection() return self.armorProtection end function Armor:getArmorCoverage() return self.armorCoverage end return Armor
local __exports = LibStub:NewLibrary("ovale/Warlock", 80300) if not __exports then return end local __class = LibStub:GetLibrary("tslib").newClass local aceEvent = LibStub:GetLibrary("AceEvent-3.0", true) local tonumber = tonumber local pairs = pairs local GetTime = GetTime local CombatLogGetCurrentEventInfo = CombatLogGetCurrentEventInfo local find = string.find local pow = math.pow local CUSTOM_AURAS = { [80240] = { customId = -80240, duration = 10, stacks = 1, auraName = "active_havoc" } } local demonData = { [55659] = { duration = 12 }, [98035] = { duration = 12 }, [103673] = { duration = 12 }, [11859] = { duration = 25 }, [89] = { duration = 25 }, [143622] = { duration = 12 }, [135002] = { duration = 15 }, [17252] = { duration = 15 } } local self_demons = {} local self_serial = 1 __exports.OvaleWarlockClass = __class(nil, { constructor = function(self, ovale, ovaleAura, ovalePaperDoll, ovaleSpellBook) self.ovale = ovale self.ovaleAura = ovaleAura self.ovalePaperDoll = ovalePaperDoll self.ovaleSpellBook = ovaleSpellBook self.OnInitialize = function() if self.ovale.playerClass == "WARLOCK" then self.module:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED", self.COMBAT_LOG_EVENT_UNFILTERED) self_demons = {} end end self.OnDisable = function() if self.ovale.playerClass == "WARLOCK" then self.module:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED") end end self.COMBAT_LOG_EVENT_UNFILTERED = function(event, ...) local _, cleuEvent, _, sourceGUID, _, _, _, destGUID, _, _, _, spellId = CombatLogGetCurrentEventInfo() if sourceGUID ~= self.ovale.playerGUID then return end self_serial = self_serial + 1 if cleuEvent == "SPELL_SUMMON" then local _, _, _, _, _, _, _, creatureId = find(destGUID, "(%S+)-(%d+)-(%d+)-(%d+)-(%d+)-(%d+)-(%S+)") creatureId = tonumber(creatureId) local now = GetTime() for id, v in pairs(demonData) do if id == creatureId then self_demons[destGUID] = { id = creatureId, timestamp = now, finish = now + v.duration } break end end for k, d in pairs(self_demons) do if d.finish < now then self_demons[k] = nil end end self.ovale:needRefresh() elseif cleuEvent == "SPELL_CAST_SUCCESS" then if spellId == 196277 then for k, d in pairs(self_demons) do if d.id == 55659 or d.id == 143622 then self_demons[k] = nil end end self.ovale:needRefresh() end local aura = CUSTOM_AURAS[spellId] if aura then self:AddCustomAura(aura.customId, aura.stacks, aura.duration, aura.auraName) end end end self.module = ovale:createModule("OvaleWarlock", self.OnInitialize, self.OnDisable, aceEvent) end, CleanState = function(self) end, InitializeState = function(self) end, ResetState = function(self) end, GetNotDemonicEmpoweredDemonsCount = function(self, creatureId, atTime) local count = 0 for _, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId and not d.de then count = count + 1 end end return count end, GetDemonsCount = function(self, creatureId, atTime) local count = 0 for _, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId then count = count + 1 end end return count end, GetRemainingDemonDuration = function(self, creatureId, atTime) local max = 0 for _, d in pairs(self_demons) do if d.finish >= atTime and d.id == creatureId then local remaining = d.finish - atTime if remaining > max then max = remaining end end end return max end, AddCustomAura = function(self, customId, stacks, duration, buffName) local now = GetTime() local expire = now + duration self.ovaleAura:GainedAuraOnGUID(self.ovale.playerGUID, now, customId, self.ovale.playerGUID, "HELPFUL", false, nil, stacks, nil, duration, expire, false, buffName, nil, nil, nil) end, TimeToShard = function(self, now) local value = 3600 local creepingDeathTalent = 20 local tickTime = 2 / self.ovalePaperDoll:GetHasteMultiplier("spell", self.ovalePaperDoll.next) local activeAgonies = self.ovaleAura:AuraCount(980, "HARMFUL", true, nil, now, nil) if activeAgonies > 0 then value = 1 / (0.184 * pow(activeAgonies, -2 / 3)) * tickTime / activeAgonies if self.ovaleSpellBook:IsKnownTalent(creepingDeathTalent) then value = value * 0.85 end end return value end, })
ITEM.Name = 'Sawblade' ITEM.Price = 1000 ITEM.Model = 'models/props_junk/sawblade001a.mdl' ITEM.Follower = 'sawblade' function ITEM:OnEquip(ply, modifications) ply:Fo_CreateFollower( self.Follower ) end function ITEM:OnHolster(ply) ply:Fo_RemoveFollower( self.Follower ) end
local K = unpack(select(2, ...)) -- Lua API local _G = _G local table_wipe = _G.table.wipe -- GLOBALS: SkinnerDB local SkinnerDB = _G.SkinnerDB function K.LoadSkinnerProfile() if SkinnerDB then table_wipe(SkinnerDB) end _G.SkinnerDB["profiles"]["Default"] = { -- General ["Warnings"] = false, ["Errors"] = false, ["MinimapIcon"] = { ["hide"] = true, ["minimapPos"] = 210, ["radius"] = 80, }, ["DropDownPanels"] = true, ["DropDownButtons"] = false, -- Backdrop Settings ["BdDefault"] = false, ["BdDefault"] = false, ["BdFile"] = "None", ["BdTexture"] = "Blizzard Dialog Background Dark", ["BdTileSize"] = 16, ["BdEdgeFile"] = "None", ["BdBorderTexture"] = "Blizzard Tooltip", ["BdEdgeSize"] = 16, ["BdInset"] = 4, ["StatusBar"] = { ["texture"] = "KkthnxUI_StatusBar", }, -- Background Texture settings ["BgUseTex"] = false, ["BgFile"] = "None", ["BgTexture"] = "None", ["BgTile"] = false, ["LFGTexture"] = false, -- Colours ["ClassClrBd"] = false, ["ClassClrBg"] = false, ["ClassClrGr"] = false, ["ClassClrTT"] = false, ["TooltipBorder"] = { ["r"] = 0.752, ["g"] = 0.752, ["b"] = 0.752, ["a"] = 1, }, ["BackdropBorder"] = { ["r"] = 0.752, ["g"] = 0.752, ["b"] = 0.752, ["a"] = 1, }, ["Backdrop"] = { ["r"] = 0, ["g"] = 0, ["b"] = 0, ["a"] = 0.9, }, ["HeadText"] = { ["r"] = 255/255, ["g"] = 205/255, ["b"] = 4/255, }, ["BodyText"] = { ["r"] = 1, ["g"] = 1, ["b"] = 1, }, ["IgnoredText"] = { ["r"] = 1, ["g"] = 1, ["b"] = 1, }, ["GradientMin"] = { ["r"] = 0.1, ["g"] = 0.1, ["b"] = 0.1, ["a"] = 0, }, ["GradientMax"] = { ["r"] = 0.25, ["g"] = 0.25, ["b"] = 0.25, ["a"] = 1, }, ["BagginsBBC"] = { ["r"] = 0.5, ["g"] = 0.5, ["b"] = 0.5, ["a"] = 1, }, -- Gradient ["Gradient"] = { ["char"] = false, ["npc"] = false, ["enable"] = false, ["ui"] = false, ["skinner"] = false, }, -- Modules -- populated below -- NPC Frames ["DisableAllNPC"] = false, ["AlliedRacesUI"] = true, ["AuctionUI"] = true, ["AzeriteRespecUI"] = true, ["BankFrame"] = false, ["BarbershopUI"] = true, ["BlackMarketUI"] = true, ["FlightMap"] = true, ["GossipFrame"] = true, ["GuildRegistrar"] = true, ["ItemUpgradeUI"] = true, ["MerchantFrame"] = true, ["Petition"] = true, ["PetStableFrame"] = true, ["QuestChoice"] = true, ["QuestFrame"] = true, ["SideDressUpFrame"] = true, ["Tabard"] = true, ["TaxiFrame"] = true, ["TrainerUI"] = true, ["VoidStorageUI"] = true, -- Player Frames ["DisableAllP"] = false, ["AchievementUI"] = { ["skin"] = true, ["style"] = 2, }, ["ArchaeologyUI"] = true, ["AzeriteUI"] = true, ["Buffs"] = true, ["CastingBar"] = { ["skin"] = false, ["glaze"] = true, }, ["CharacterFrames"] = true, ["Collections"] = true, ["CommunitiesUI"] = true, ["CompactFrames"] = true, ["ContainerFrames"] = { ["skin"] = false, ["fheight"] = 100, }, ["DressUpFrame"] = true, ["EncounterJournal"] = true, ["EquipmentFlyout"] = true, ["FriendsFrame"] = true, ["GuildControlUI"] = true, ["GuildUI"] = true, ["GuildInvite"] = true, ["InspectUI"] = true, ["ItemSocketingUI"] = true, ["LookingForGuildUI"] = true, ["LootFrames"] = { ["skin"] = false, ["size"] = 1, }, ["LootHistory"] = true, ["MirrorTimers"] = { ["skin"] = false, ["glaze"] = true, }, ["ObjectiveTracker"] = { ["skin"] = false, ["popups"] = false, }, ["OverrideActionBar"] = true, ["PVPFrame"] = true, ["QuestMap"] = true, ["RaidUI"] = true, ["ReadyCheck"] = true, ["RolePollPopup"] = true, ["ScrollOfResurrection"] = true, ["SpellBookFrame"] = true, ["StackSplit"] = true, ["TalentUI"] = true, ["TradeFrame"] = true, ["TradeSkillUI"] = true, ["VehicleMenuBar"] = true, -- UI Frames ["DisableAllUI"] = false, ["AddonList"] = true, ["AdventureMap"] = true, ["AlertFrames"] = true, ["ArtifactUI"] = true, ["AutoComplete"] = true, ["BattlefieldMap"] = { ["skin"] = true, ["gloss"] = false, }, ["BNFrames"] = false, ["Calendar"] = true, ["ChallengesUI"] = true, ["ChatBubbles"] = false, ["ChatButtons"] = true, ["ChatConfig"] = true, ["ChatEditBox"] = { ["skin"] = false, ["style"] = 1, }, ["ChatFrames"] = false, ["ChatMenus"] = false, ["ChatTabs"] = false, ["ChatTabsFade"] = true, ["CinematicFrame"] = true, ["ClassTrial"] = true, ["CoinPickup"] = true, ["Colours"] = true, ["Console"] = true, ["Contribution"] = true, ["CombatLogQBF"] = false, ["DeathRecap"] = true, ["DebugTools"] = true, ["DestinyFrame"] = true, ["GarrisonUI"] = true, ["GhostFrame"] = false, ["GMChatUI"] = true, ["GMSurveyUI"] = true, ["GuildBankUI"] = false, ["HelpFrame"] = true, ["IslandsPartyPoseUI"] = true, ["IslandsQueueUI"] = true, ["ItemText"] = true, ["LevelUpDisplay"] = true, ["LossOfControl"] = true, ["MailFrame"] = true, ["MainMenuBar"] = { ["skin"] = false, ["glazesb"] = false, ["extraab"] = false, ["altpowerbar"] = false, }, ["MenuFrames"] = true, ["Minimap"] = { ["skin"] = false, ["gloss"] = false, }, ["MinimapButtons"] = { ["skin"] = false, ["style"] = false, }, ["MovePad"] = true, ["MovieFrame"] = true, ["Nameplates"] = false, ["ObliterumUI"] = true, ["OrderHallUI"] = true, ["PetBattleUI"] = true, ["ProductChoiceFrame"] = true, ["PVEFrame"] = true, ["QuestMap"] = true, ["QueueStatusFrame"] = true, ["RaidFrame"] = true, ["ScriptErrors"] = true, ["ScrappingMachineUI"] = true, ["SplashFrame"] = true, ["StaticPopups"] = true, ["TalkingHeadUI"] = false, ["TimeManager"] = true, ["Tooltips"] = { ["skin"] = false, ["style"] = 1, ["glazesb"] = false, ["border"] = 1, }, ["Tutorial"] = true, ["UIWidgets"] = true, ["UnitPopup"] = true, ["WarboardUI"] = true, ["WarfrontsPartyPoseUI"] = true, ["WorldMap"] = { ["skin"] = true, ["size"] = 1, }, ["WorldState"] = true, ["ZoneAbility"] = true, -- Disabled Skins ["DisableAllAS"] = false, ["DisabledSkins"] = { ["Details"] = true, ["Skada"] = true, }, } end
local mysql = require("core.driver.mysql") local cjson = require "cjson" local arg = ngx.req.get_uri_args() local res = mysql:query("select ID as id , NAME as name from DISTRICT order by CREATE_TIME") mysql:closeClient() ngx.say(cjson.encode(res))
-- verify_globals.lua -- ignore things that change on different machines or every release -- the following items still have to exist, but their values don't have to match local filter = { -- differences by machine "DATA_DIR", "USER_DIR", "package.cpath", "package.path", "package.loaded", "run_user_scripts_when_superuser", "running_superuser", -- differences in Lua versions "_VERSION", "package.config", -- differences caused by changes in wireshark 1.11 "NSTime", "Proto", 'Listener["<metatable>"].__index', ".__index" } -- the following items don't have to exist local ignore = { -- not sure why this was removed in wireshark 1.11, but it was "TreeItem.set_expert_flags", -- in Lua 5.1 only "debug.getfenv", "debug.setfenv", "gcinfo", "getfenv", "io.gfind", "setfenv", "math.mod", "newproxy", "string.gfind", "table.foreach", "table.foreachi", "table.getn", "table.setn", -- in Lua 5.2+ only "bit32", "debug.getuservalu", "debug.setuservalu", "debug.upvalueid", "debug.upvaluejoin", "package.searchers", "package.searchpath", "rawlen", "table.pack", "table.unpack", } local arg={...} -- get passed-in args -- arg1 = path to find inspect -- arg2 = filename to read in (optional, unless 'verify' is set) -- arg3 = 'verify' to verify all of read-in file is in _G (default); 'new' to output all items in _G that are not in read-in file -- arg4 = 'nometa' to ignore metatables; 'meta' otherwise (default) local add_path = "lua/?.lua;" if #arg > 0 then add_path = arg[1].."?.lua;" end print("package.path = " .. package.path) -- need the path to find inspect.lua local old_path = package.path package.path = add_path .. package.path local inspect = require("inspect") package.path = old_path -- return path to original print("-- Wireshark version: " .. get_version()) if #arg == 1 then -- no more args, so just output globals print(inspect(_G, { serialize = true, filter = inspect.makeFilter(filter) })) return end local file = assert(io.open(arg[2], "r")) local input = file:read("*all") input = inspect.marshal(input) local nometa = false if #arg > 3 and arg[4] == "nometa" then nometa = true end if #arg == 2 or arg[3] == "verify" then print(string.rep("\n", 2)) print("Verifying input file '"..arg[2].."' is contained within the global table") local ret, diff = inspect.compare(input, _G, { ['filter'] = inspect.makeFilter(filter), ['ignore'] = inspect.makeFilter(ignore), ['nonumber'] = true, ['nometa'] = nometa }) if not ret then print("Comparison failed - global table does not have all the items in the input file!") print(string.rep("\n", 2)) print(string.rep("-", 80)) print("Differences are:") print(inspect(diff)) else print("\n-----------------------------\n") print("All tests passed!\n\n") end return elseif #arg > 2 and arg[3] == "new" then local ret, diff = inspect.compare(_G, input, { ['filter'] = inspect.makeFilter(filter), ['ignore'] = inspect.makeFilter(ignore), ['nonumber'] = true, ['keep'] = true, ['nometa'] = nometa }) if not ret then print(inspect(diff)) else print("\n-----------------------------\n") print("No new items!\n\n") end end
Locales['fr'] = { -- DialogBox Name ['dialogbox_playerid'] = 'ID du Joueur (8 Caractères Maximum):', ['dialogbox_amount'] = 'Montant (8 Caractères Maximum):', ['dialogbox_amount_ammo'] = 'Montant de Munitions (8 Caractères Maximum):', ['dialogbox_vehiclespawner'] = 'Nom du Véhicule (50 Caractères Maximum):', ['dialogbox_xyz'] = 'Position XYZ (50 Caractères Maximum):', -- Menu Default Vars ['default_gps'] = 'Aucun', ['default_demarche'] = 'Normal', ['default_voice'] = 'Normal', -- Menu Notification ['missing_rights'] = 'Vous n\'avez pas les ~r~droits~w~', ['no_vehicle'] = 'Vous n\'êtes pas dans un véhicule', ['players_nearby'] = 'Aucun joueur à proximité', ['amount_invalid'] = 'Montant Invalide', ['in_vehicle_give'] = 'Impossible de donner %s dans un véhicule', ['in_vehicle_drop'] = 'Impossible de jeter %s dans un véhicule', ['not_usable'] = '%s n\'est pas utilisable', ['not_droppable'] = '%s n\'est pas jetable', ['gave_ammo'] = 'Vous avez donné x%s munitions à %s', ['no_ammo'] = 'Vous ne possédez pas de munitions', ['not_enough_ammo'] = 'Vous ne possédez pas autant de munitions', ['accessories_no_ears'] = 'Vous ne possédez pas d\'Accessoire d\'Oreilles', ['accessories_no_glasses'] = 'Vous ne possédez pas de Lunettes', ['accessories_no_helmet'] = 'Vous ne possédez pas de Casque/Chapeau', ['accessories_no_mask'] = 'Vous ne possédez pas de Masque', ['admin_noclipon'] = 'NoClip ~g~activé', ['admin_noclipoff'] = 'NoClip ~r~désactivé', ['admin_godmodeon'] = 'Mode invincible ~g~activé', ['admin_godmodeoff'] = 'Mode invincible ~r~désactivé', ['admin_ghoston'] = 'Mode fantôme ~g~activé', ['admin_ghostoff'] = 'Mode fantôme ~r~désactivé', ['admin_vehicleflip'] = 'Voiture retourné', ['admin_tpmarker'] = 'Téléporté sur le marqueur !', ['admin_nomarker'] = 'Pas de marqueur sur la carte !', -- Main Menu ['mainmenu_subtitle'] = '~o~MENU INTERACTION', ['mainmenu_gps_button'] = 'GPS', ['mainmenu_approach_button'] = 'Démarche', ['mainmenu_voice_button'] = 'Voix', ['gps'] = 'GPS: ~b~%s', ['approach'] = 'Démarche: ~b~%s', ['voice'] = 'Voix: ~b~%s', -- Menu Voice Level ['voice_whisper'] = 'Chuchoter', ['voice_normal'] = 'Normal', ['voice_cry'] = 'Crier', -- Inventory Menu ['inventory_title'] = 'Inventaire', ['inventory_actions_subtitle'] = 'Inventaire: Action', ['inventory_use_button'] = 'Utiliser', ['inventory_give_button'] = 'Donner', ['inventory_drop_button'] = 'Jeter', -- Loadout Menu ['loadout_title'] = 'Gestion des Armes', ['loadout_actions_subtitle'] = 'Armes: Action', ['loadout_give_button'] = 'Donner', ['loadout_givemun_button'] = 'Donner Munitions', ['loadout_drop_button'] = 'Jeter', -- Wallet Menu ['wallet_title'] = 'Portefeuille', ['wallet_option_give'] = 'Donner', ['wallet_option_drop'] = 'Jeter', ['wallet_job_button'] = 'Métier: %s - %s', ['wallet_job2_button'] = 'Organisation: %s - %s', ['wallet_money_button'] = 'Argent: $%s', ['wallet_blackmoney_button'] = 'Argent Sale: $%s', ['wallet_show_idcard_button'] = 'Montrer sa carte d\'identité', ['wallet_check_idcard_button'] = 'Regarder sa carte d\'identité', ['wallet_show_driver_button'] = 'Montrer sa driver', ['wallet_check_driver_button'] = 'Regarder sa driver', -- Bills Menu ['bills_title'] = 'Factures', -- Clothes Menu ['clothes_title'] = 'Vêtements', ['clothes_top'] = 'Haut', ['clothes_pants'] = 'Bas', ['clothes_shoes'] = 'Chaussures', ['clothes_bag'] = 'Sac', ['clothes_bproof'] = 'Gilet par Balle', -- Accessories Menu ['accessories_title'] = 'Accessoires', ['accessories_ears'] = 'Accessoire d\'Oreilles', ['accessories_glasses'] = 'Lunettes', ['accessories_helmet'] = 'Chapeau/Casque', ['accessories_mask'] = 'Masque', -- Animation Menu ['animation_title'] = 'Animations', ['animation_party_title'] = 'Festives', ['animation_party_smoke'] = 'Fumer une cigarette', ['animation_party_playsong'] = 'Jouer de la musique', ['animation_party_dj'] = 'DJ', ['animation_party_dancing'] = 'Faire la Fête', ['animation_party_airguitar'] = 'Air Guitar', ['animation_party_shagging'] = 'Air Shagging', ['animation_party_rock'] = 'Rock\'n\'roll', ['animation_party_drunk'] = 'Bourré sur place', ['animation_party_vomit'] = 'Vomir en voiture', ['animation_salute_title'] = 'Salutations', ['animation_salute_saluate'] = 'Saluer', ['animation_salute_serrer'] = 'Serrer la main', ['animation_salute_tchek'] = 'Tchek', ['animation_salute_bandit'] = 'Salut bandit', ['animation_salute_military'] = 'Salut Militaire', ['animation_work_title'] = 'Travail', ['animation_work_suspect'] = 'Se rendre', ['animation_work_fisherman'] = 'Pêcheur', ['animation_work_inspect'] = 'Police : enquêter', ['animation_work_radio'] = 'Police : parler à la radio', ['animation_work_circulation'] = 'Police : circulation', ['animation_work_binoculars'] = 'Police : jumelles', ['animation_work_harvest'] = 'Agriculture : récolter', ['animation_work_repair'] = 'Dépanneur : réparer le moteur', ['animation_work_observe'] = 'Médecin : observer', ['animation_work_talk'] = 'Taxi : parler au client', ['animation_work_bill'] = 'Taxi : donner la facture', ['animation_work_buy'] = 'Epicier : donner les courses', ['animation_work_shot'] = 'Barman : servir un shot', ['animation_work_picture'] = 'Journaliste : Prendre une photo', ['animation_work_notes'] = 'Tout : Prendre des notes', ['animation_work_hammer'] = 'Tout : Coup de marteau', ['animation_work_beg'] = 'SDF : Faire la manche', ['animation_work_statue'] = 'SDF : Faire la statue', ['animation_mood_title'] = 'Humeurs', ['animation_mood_felicitate'] = 'Féliciter', ['animation_mood_nice'] = 'Super', ['animation_mood_you'] = 'Toi', ['animation_mood_come'] = 'Viens', ['animation_mood_what'] = 'Keskya ?', ['animation_mood_me'] = 'A moi', ['animation_mood_seriously'] = 'Je le savais, putain', ['animation_mood_tired'] = 'Etre épuisé', ['animation_mood_shit'] = 'Je suis dans la merde', ['animation_mood_facepalm'] = 'Facepalm', ['animation_mood_calm'] = 'Calme-toi', ['animation_mood_why'] = 'Qu\'est ce que j\'ai fait ?', ['animation_mood_fear'] = 'Avoir peur', ['animation_mood_fight'] = 'Fight ?', ['animation_mood_notpossible'] = 'C\'est pas Possible !', ['animation_mood_embrace'] = 'Enlacer', ['animation_mood_fuckyou'] = 'Doigt d\'honneur', ['animation_mood_wanker'] = 'Branleur', ['animation_mood_suicide'] = 'Balle dans la tête', ['animation_sports_title'] = 'Sports', ['animation_sports_muscle'] = 'Montrer ses muscles', ['animation_sports_weightbar'] = 'Barre de musculation', ['animation_sports_pushup'] = 'Faire des pompes', ['animation_sports_abs'] = 'Faire des abdos', ['animation_sports_yoga'] = 'Faire du yoga', ['animation_other_title'] = 'Divers', ['animation_other_beer'] = 'Bière en Zik', ['animation_other_sit'] = 'S\'asseoir', ['animation_other_waitwall'] = 'Attendre contre un mur', ['animation_other_ontheback'] = 'Couché sur le dos', ['animation_other_stomach'] = 'Couché sur le ventre', ['animation_other_clean'] = 'Nettoyer', ['animation_other_cooking'] = 'Préparer à manger', ['animation_other_search'] = 'Position de Fouille', ['animation_other_selfie'] = 'Prendre un selfie', ['animation_other_door'] = 'Ecouter à une porte', ['animation_pegi_title'] = 'PEGI 21', ['animation_pegi_hsuck'] = 'Homme se faire suc** en voiture', ['animation_pegi_fsuck'] = 'Femme suc** en voiture', ['animation_pegi_hfuck'] = 'Homme bais** en voiture', ['animation_pegi_ffuck'] = 'Femme bais** en voiture', ['animation_pegi_scratch'] = 'Se gratter les couilles', ['animation_pegi_charm'] = 'Faire du charme', ['animation_pegi_golddigger'] = 'Pose michto', ['animation_pegi_breast'] = 'Montrer sa poitrine', ['animation_pegi_strip1'] = 'Strip Tease 1', ['animation_pegi_strip2'] = 'Strip Tease 2', ['animation_pegi_stripfloor'] = 'Strip Tease au sol', -- Vehicle Menu ['vehicle_title'] = 'Gestion Véhicule', ['vehicle_engine_button'] = 'Allumer/Eteindre le Moteur', ['vehicle_door_button'] = 'Ouvrir/Fermer Porte', ['vehicle_hood_button'] = 'Ouvrir/Fermer Capot', ['vehicle_trunk_button'] = 'Ouvrir/Fermer Coffre', ['vehicle_door_frontleft'] = 'Avant Gauche', ['vehicle_door_frontright'] = 'Avant Droite', ['vehicle_door_backleft'] = 'Arrière Gauche', ['vehicle_door_backright'] = 'Arrière Droite', -- Boss Management Menu ['bossmanagement_title'] = 'Gestion Entreprise: %s', ['bossmanagement_chest_button'] = 'Coffre Entreprise:', ['bossmanagement_hire_button'] = 'Recruter', ['bossmanagement_fire_button'] = 'Virer', ['bossmanagement_promote_button'] = 'Promouvoir', ['bossmanagement_demote_button'] = 'Destituer', -- Boss Management 2 Menu ['bossmanagement2_title'] = 'Gestion Organisation: %s', ['bossmanagement2_chest_button'] = 'Coffre Organisation:', ['bossmanagement2_hire_button'] = 'Recruter', ['bossmanagement2_fire_button'] = 'Virer', ['bossmanagement2_promote_button'] = 'Promouvoir', ['bossmanagement2_demote_button'] = 'Destituer', -- Admin Menu ['admin_title'] = 'Administration', ['admin_goto_button'] = 'TP sur Joueur', ['admin_bring_button'] = 'TP Joueur sur moi', ['admin_tpxyz_button'] = 'TP sur Coordonées', ['admin_noclip_button'] = 'NoClip', ['admin_godmode_button'] = 'Mode Invincible', ['admin_ghostmode_button'] = 'Mode Fantôme', ['admin_spawnveh_button'] = 'Faire apparaître un Véhicule', ['admin_repairveh_button'] = 'Réparer Véhicule', ['admin_flipveh_button'] = 'Retourner le véhicule', ['admin_givemoney_button'] = 'S\'octroyer de l\'argent', ['admin_givebank_button'] = 'S\'octroyer de l\'argent (banque)', ['admin_givedirtymoney_button'] = 'S\'octroyer de l\'argent sale', ['admin_showxyz_button'] = 'Afficher/Cacher Coordonnées', ['admin_showname_button'] = 'Afficher/Cacher Noms des Joueurs', ['admin_tpmarker_button'] = 'TP sur le Marqueur', ['admin_revive_button'] = 'Réanimer un Joueur', ['admin_changeskin_button'] = 'Changer l\'Apparence', ['admin_saveskin_button'] = 'Sauvegarder l\'Apparence', -- Weapons ['weapon_knife'] = 'couteau', ['weapon_nightstick'] = 'matraque', ['weapon_hammer'] = 'marteau', ['weapon_bat'] = 'batte', ['weapon_golfclub'] = 'club de golf', ['weapon_crowbar'] = 'pied de biche', ['weapon_pistol'] = 'pistolet', ['weapon_combatpistol'] = 'pistolet de combat', ['weapon_appistol'] = 'pistolet automatique', ['weapon_pistol50'] = 'pistolet calibre 50', ['weapon_microsmg'] = 'micro smg', ['weapon_smg'] = 'smg', ['weapon_assaultsmg'] = 'smg d\'assaut', ['weapon_assaultrifle'] = 'fusil d\'assaut', ['weapon_carbinerifle'] = 'carabine d\'assaut', ['weapon_advancedrifle'] = 'fusil avancé', ['weapon_mg'] = 'mitrailleuse', ['weapon_combatmg'] = 'mitrailleuse de combat', ['weapon_pumpshotgun'] = 'fusil à pompe', ['weapon_sawnoffshotgun'] = 'carabine à canon scié', ['weapon_assaultshotgun'] = 'carabine d\'assaut', ['weapon_bullpupshotgun'] = 'carabine bullpup', ['weapon_stungun'] = 'tazer', ['weapon_sniperrifle'] = 'fusil de sniper', ['weapon_heavysniper'] = 'fusil de sniper lourd', ['weapon_grenadelauncher'] = 'lance-grenade', ['weapon_rpg'] = 'lance-rocket', ['weapon_stinger'] = 'lance-missile stinger', ['weapon_minigun'] = 'minigun', ['weapon_grenade'] = 'grenade', ['weapon_stickybomb'] = 'bombe collante', ['weapon_smokegrenade'] = 'grenade fumigène', ['weapon_bzgas'] = 'grenade à gaz bz', ['weapon_molotov'] = 'cocktail molotov', ['weapon_fireextinguisher'] = 'extincteur', ['weapon_petrolcan'] = 'jerrican d\'essence', ['weapon_digiscanner'] = 'digiscanner', ['weapon_ball'] = 'balle', ['weapon_snspistol'] = 'pistolet sns', ['weapon_bottle'] = 'bouteille', ['weapon_gusenberg'] = 'balayeuse gusenberg', ['weapon_specialcarbine'] = 'carabine spéciale', ['weapon_heavypistol'] = 'pistolet lourd', ['weapon_bullpuprifle'] = 'fusil bullpup', ['weapon_dagger'] = 'poignard', ['weapon_vintagepistol'] = 'pistolet vintage', ['weapon_firework'] = 'feu d\'artifice', ['weapon_musket'] = 'mousquet', ['weapon_heavyshotgun'] = 'fusil à pompe lourd', ['weapon_marksmanrifle'] = 'fusil marksman', ['weapon_hominglauncher'] = 'lance tête-chercheuse', ['weapon_proxmine'] = 'mine de proximité', ['weapon_snowball'] = 'boule de neige', ['weapon_flaregun'] = 'lance fusée de détresse', ['weapon_garbagebag'] = 'sac poubelle', ['weapon_handcuffs'] = 'menottes', ['weapon_combatpdw'] = 'arme de défense personnelle', ['weapon_marksmanpistol'] = 'pistolet marksman', ['weapon_knuckle'] = 'poing américain', ['weapon_hatchet'] = 'hachette', ['weapon_railgun'] = 'canon éléctrique', ['weapon_machete'] = 'machette', ['weapon_machinepistol'] = 'pistolet mitrailleur', ['weapon_switchblade'] = 'couteau à cran d\'arrêt', ['weapon_revolver'] = 'revolver', ['weapon_dbshotgun'] = 'fusil à pompe double canon', ['weapon_compactrifle'] = 'fusil compact', ['weapon_autoshotgun'] = 'fusil à pompe automatique', ['weapon_battleaxe'] = 'hache de combat', ['weapon_compactlauncher'] = 'lanceur compact', ['weapon_minismg'] = 'mini smg', ['weapon_pipebomb'] = 'bombe tuyau', ['weapon_poolcue'] = 'queue de billard', ['weapon_wrench'] = 'clé', ['weapon_flashlight'] = 'lampe torche', ['gadget_nightvision'] = 'vision nocturne', ['gadget_parachute'] = 'parachute', ['weapon_flare'] = 'fusée Détresse', ['weapon_doubleaction'] = 'double-Action Revolver', -- Weapon Components ['component_clip_default'] = 'chargeur par défaut', ['component_clip_extended'] = 'chargeur grande capacité', ['component_clip_drum'] = 'chargeur tambour', ['component_clip_box'] = 'chargeur très grande capacité', ['component_flashlight'] = 'torche', ['component_scope'] = 'viseur', ['component_scope_advanced'] = 'lunette', ['component_suppressor'] = 'réducteur de son', ['component_grip'] = 'poignée', ['component_luxary_finish'] = 'finition de luxe', }
local json = require "json" local parse = require "parse" local property = require "property" local localization = require "localization" local database = require "database" local exit = require "exit" local exception = require "exception" local exceptionHandler = require "exceptionHandler" local util = require "util" local userService = require "userService" local localeService = require "localeService" local priceService = require "priceService" local cartService = require "cartService" local function process (db, data) local op = db:operators() local locale = localeService.getLocale(db) data.locale = locale local cart = cartService.getCart(db) local user = userService.authenticatedUser(db) if user then local function addAddressTransaction () local address = util.parseForm(util.urldecode(ngx.req.get_body_data())) address.user = user address.carts = {cart} db:add({address = address}) user.addresses = nil -- refresh end local status, res = pcall(db.transaction, db, addAddressTransaction) if not status then exception("user=" .. user.id .. " => " .. res) end end end local data = {} local db = database.connect() local status, err = pcall(process, db, data) db:close() if status then return ngx.redirect(property.shopUrl .. property.checkoutDeliveryMethodUrl) else exceptionHandler.toCookie(err) return ngx.redirect(property.shopUrl .. property.checkoutAddressUrl) end
local ScaleDimension = {} ScaleDimension.__index = ScaleDimension function ScaleDimension:new() local this = { scaleItems = {}, graphicsDimensions = {width = love.graphics.getWidth(), height = love.graphics.getHeight()}, gameScreenScale = {width = 800, height = 600} } return setmetatable(this, ScaleDimension) end function ScaleDimension:setGameScreenScale(width, height) self.gameScreenScale.width, self.gameScreenScale.height = width, height end function ScaleDimension:calculeScales(itemName, width, height, x, y, originalScale) local originalScale = originalScale or self.gameScreenScale if not self.scaleItems[itemName] then self.scaleItems[itemName] = { scaleX = 1, scaleY = 1, x = x, y = y, width = width, height = height, originalInfo = {width, height, x, y, originalScale}, centralizeOptions = {x = false, y = false, isImage = false , centerOffset = false}, relative = nil, aspectRatio = {active = false, centralizeOptions = nil} } end local item = self.scaleItems[itemName] item.scaleX, item.scaleY = self.graphicsDimensions.width / originalScale.width, self.graphicsDimensions.height / originalScale.height if x and y and originalScale then item.x = (x * self.graphicsDimensions.width) / originalScale.width item.y = (y * self.graphicsDimensions.height) / originalScale.height end item.width = (width * self.graphicsDimensions.width) / originalScale.width item.height = (height * self.graphicsDimensions.height) / originalScale.height return self.scaleItems[itemName] end function ScaleDimension:relativeScale(itemName, originalSize) local scales = self.scaleItems[itemName] local newScale = {x = scales.width / originalSize.width, y = scales.height / originalSize.height, originalSize = originalSize} scales.relative = newScale end function ScaleDimension:directScale(width, height) return self.graphicsDimensions.width / width, self.graphicsDimensions.height / height end function ScaleDimension:generateAspectRatio(itemName, centralizeOptions) if self.scaleItems[itemName] then local item = self.scaleItems[itemName] item.aspectRatio.active = true local x, y = false, false if item.scaleX < item.scaleY then item.scaleY = item.scaleX y = true if item.relative then item.relative.y = item.relative.x end else item.scaleX = item.scaleY x = true if item.relative then item.relative.x = item.relative.y end end if centralizeOptions then item.aspectRatio.centralizeOptions = centralizeOptions self:centralize(itemName, x, y, centralizeOptions.isImage, centralizeOptions.centerOffset) end end end function ScaleDimension:centralize(itemName, x, y, isImage, centerOffset) if self.scaleItems[itemName] then local item = self.scaleItems[itemName] item.centralizeOptions.x = x or item.centralizeOptions.x item.centralizeOptions.y = y or item.centralizeOptions.y item.centralizeOptions.isImage = isImage or item.centralizeOptions.isImage item.centralizeOptions.centerOffset = centerOffset or item.centralizeOptions.centerOffset if x then item.x = (self.graphicsDimensions.width / 2) - ((isImage and (type(isImage) == "table" and isImage.width or item.originalInfo[1]) * (item.relative and item.relative.x or item.scaleX) or centerOffset and 0 or item.width) / 2) end if y then item.y = (self.graphicsDimensions.height / 2) - ((isImage and (type(isImage) == "table" and isImage.height or item.originalInfo[2]) * (item.relative and item.relative.y or item.scaleY) or centerOffset and 0 or item.height) / 2) end end end function ScaleDimension:getScale(itemName) return self.scaleItems[itemName] end function ScaleDimension:screenResize(width, height) self.graphicsDimensions.width, self.graphicsDimensions.height = width, height for itemName, item in pairs(self.scaleItems) do self:calculeScales(itemName, unpack(item.originalInfo)) if item.relative then self:relativeScale(itemName, item.relative.originalSize) end if item.aspectRatio.active then self:generateAspectRatio(itemName, item.aspectRatio.centralizeOptions) end self:centralize(itemName, item.centralizeOptions.x, item.centralizeOptions.y, item.centralizeOptions.isImage, item.centralizeOptions.centerOffset) end end return ScaleDimension
includes("GraphicsInterface")
return {--点赞 check = function (data) return (data.msg=="点赞" or data.msg=="赞我") end, run = function (data,sendMessage) if not checkCoolDownTime(data, "like", sendMessage) then return true end --CD时间 local time = os.date("*t",os.time()+3600*24) time.hour = 0 time.min = 0 time.sec = 0 local cdTime = os.time(time) - os.time() setCoolDownTime(data, "like", cdTime) --拒绝 if randNum() > 0.8 then sendMessage(Utils.CQCode_At(data.qq).."\r\n"..Utils.CQCode_Image("jojo\\jujue.gif")) return true end --开始点赞 local msgs = { "\r\n"..Utils.CQCode_Image("jojo\\like.jpg").."\r\n吉良吉影为你点赞", "好了,快给[CQ:emoji,id=128116]爬", "\r\n"..Utils.CQCode_Image("beidou\\百裂拳.gif").."健次郎为你点赞(死兆星在闪闪发光)", "\r\n"..Utils.CQCode_Image("jojo\\觉得很赞.jpg") } CQApi:SendPraise(data.qq, 10) sendMessage(Utils.CQCode_At(data.qq)..msgs[randNum(1, #msgs)]) return true end, explain = function () return "[CQ:emoji,id=128077]点赞" end }
require 'torch' --object declaration local annsp = {} --inits function annsp.init(data, labels) if annsp.verify_dimensions(data) then annsp.x = data annsp.y = labels annsp.eta = 0.01 --annsp.weights = torch.randn(#annsp.x[1]+1) annsp.weights = torch.Tensor({-0.1839, 0.4486, -0.1335, -0.7360}) annsp.bias = 1 annsp.train() else print("data not consistent..terminating") end end --verifies the dimensions and structure of x - if inconsistent, terminate. function annsp.verify_dimensions(x) local sum_length = 0 local random_pick = #x[torch.random(#x)] for i = 1, #x do sum_length = sum_length + #x[i] end if sum_length/#x ~= random_pick then return false else return true end end --basic signum (just for demo - can be replaced with either a sigmoid or hyperbolic tangent function) function annsp.signum(value) if value >= 0 then return 1 else return -1 end end --adder function function annsp.adder(w, x) return torch.dot(w,x) end --adaptation of weight vector - weights updating method function annsp.vector_adapt(current_weights, x, expected_decision, decision) return current_weights + x*(annsp.eta*(expected_decision-decision)) end --main training function (updates weights on every wrong decision) function annsp.train() local n_instances = #annsp.x --prepending associated class to the vector for i=1, n_instances do table.insert(annsp.x[i], 1, annsp.y[i]) end annsp.x = torch.Tensor(annsp.x) --iterate this many times. for l=1, 20 do for i=1, n_instances do local expected_decision = annsp.y[i] local decision = annsp.signum(annsp.adder(annsp.weights, annsp.x[i])) if decision ~= expected_decision then annsp.weights = annsp.vector_adapt(annsp.weights, annsp.x[i], expected_decision, decision) --can add an else condition, which basically will help in terminating the loop over right --set of weigts. end end end end --classifier or predictor function function annsp.classify(v) local j = v table.insert(j, 1, 1) j = torch.Tensor(j) local decision = annsp.signum(annsp.adder(annsp.weights, j)) return decision end return annsp
for n in pairs(_G) do print(n) end
MATSAVPRC_STRINGS = { ["SI_MATSAVPRC_SAVING"] = "Saving materials prices …", }
-- Created by Elfansoer --[[ Ability checklist (erase if done/checked): - Scepter Upgrade - Break behavior - Linken/Reflect behavior - Spell Immune/Invulnerable/Invisible behavior - Illusion behavior - Stolen behavior ]] -------------------------------------------------------------------------------- hoodwink_acorn_shot_lua = class({}) LinkLuaModifier( "modifier_hoodwink_acorn_shot_lua", "lua_abilities/hoodwink_acorn_shot_lua/modifier_hoodwink_acorn_shot_lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_hoodwink_acorn_shot_lua_thinker", "lua_abilities/hoodwink_acorn_shot_lua/modifier_hoodwink_acorn_shot_lua_thinker", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_hoodwink_acorn_shot_lua_debuff", "lua_abilities/hoodwink_acorn_shot_lua/modifier_hoodwink_acorn_shot_lua_debuff", LUA_MODIFIER_MOTION_NONE ) -------------------------------------------------------------------------------- -- Init Abilities function hoodwink_acorn_shot_lua:Precache( context ) PrecacheResource( "soundfile", "soundevents/game_sounds_heroes/game_sounds_hoodwink.vsndevts", context ) PrecacheResource( "particle", "particles/units/heroes/hero_hoodwink/hoodwink_acorn_shot_tracking.vpcf", context ) PrecacheResource( "particle", "particles/units/heroes/hero_hoodwink/hoodwink_acorn_shot_slow.vpcf", context ) PrecacheResource( "particle", "particles/units/heroes/hero_hoodwink/hoodwink_acorn_shot_tree.vpcf", context ) PrecacheResource( "particle", "particles/tree_fx/tree_simple_explosion.vpcf", context ) end function hoodwink_acorn_shot_lua:Spawn() if not IsServer() then return end end -------------------------------------------------------------------------------- -- Custom KV function hoodwink_acorn_shot_lua:GetCastRange( vLocation, hTarget ) return self:GetCaster():Script_GetAttackRange() + self:GetSpecialValueFor( "bonus_range" ) end -------------------------------------------------------------------------------- -- Ability Start function hoodwink_acorn_shot_lua:OnSpellStart() -- unit identifier local caster = self:GetCaster() local target = self:GetCursorTarget() local point = self:GetCursorPosition() -- Hardcoded as it has no kv value self.tree_duration = 20 self.tree_vision = 300 -- create thinker local thinker = CreateModifierThinker( caster, -- player source self, -- ability source "modifier_hoodwink_acorn_shot_lua_thinker", -- modifier name { }, -- kv caster:GetOrigin(), caster:GetTeamNumber(), false ) local mod = thinker:FindModifierByName( "modifier_hoodwink_acorn_shot_lua_thinker" ) if not target then target = thinker thinker:SetOrigin( point ) end mod.source = caster mod.target = target -- play effects local sound_cast = "Hero_Hoodwink.AcornShot.Cast" EmitSoundOn( sound_cast, caster ) end -------------------------------------------------------------------------------- -- Projectile function hoodwink_acorn_shot_lua:OnProjectileHit_ExtraData( target, location, ExtraData ) local caster = self:GetCaster() local thinker = EntIndexToHScript( ExtraData.thinker ) local mod = thinker:FindModifierByName( "modifier_hoodwink_acorn_shot_lua_thinker" ) if not mod then return end -- bounce thinker:SetOrigin( location ) mod:Bounce() -- only on first shot, if target dodges or no target, create tree if ExtraData.first==1 then if target==thinker then self:CreateTree( location ) return end -- if no enemy if not target then self:CreateTree( location ) mod.target = thinker return end if target:TriggerSpellAbsorb( self ) then mod:Destroy() return end end -- check target if not target then mod:Destroy() return end local duration = self:GetSpecialValueFor( "debuff_duration" ) -- attack enemy local mod = caster:AddNewModifier( caster, -- player source self, -- ability source "modifier_hoodwink_acorn_shot_lua", -- modifier name {} -- kv ) caster:PerformAttack( target, true, true, true, true, false, false, true ) mod:Destroy() -- debuff if not target:IsMagicImmune() then target:AddNewModifier( caster, -- player source self, -- ability source "modifier_hoodwink_acorn_shot_lua_debuff", -- modifier name { duration = duration } -- kv ) -- play effects local sound_slow = "Hero_Hoodwink.AcornShot.Slow" EmitSoundOn( sound_slow, target ) end -- play effects local sound_target = "Hero_Hoodwink.AcornShot.Target" EmitSoundOn( sound_target, target ) end function hoodwink_acorn_shot_lua:CreateTree( location ) -- vision AddFOWViewer( self:GetCaster():GetTeamNumber(), location, self.tree_vision, self.tree_duration, false ) -- tree local tree = CreateTempTreeWithModel( location, self.tree_duration, "models/heroes/hoodwink/hoodwink_tree_model.vmdl" ) -- move everyone on tree collision so they don't get stuck local units = FindUnitsInRadius( self:GetCaster():GetTeamNumber(), -- int, your team number location, -- point, center point nil, -- handle, cacheUnit. (not known) 100, -- float, radius. or use FIND_UNITS_EVERYWHERE DOTA_UNIT_TARGET_TEAM_BOTH, -- int, team filter DOTA_UNIT_TARGET_ALL, -- int, type filter DOTA_UNIT_TARGET_FLAG_MAGIC_IMMUNE_ENEMIES, -- int, flag filter 0, -- int, order filter false -- bool, can grow cache ) for _,unit in pairs(units) do FindClearSpaceForUnit( unit, unit:GetOrigin(), true ) end self:PlayEffects1( tree, location ) self:PlayEffects2( tree, location ) end -------------------------------------------------------------------------------- -- Effects function hoodwink_acorn_shot_lua:PlayEffects1( tree, location ) -- Get Resources local particle_cast = "particles/units/heroes/hero_hoodwink/hoodwink_acorn_shot_tree.vpcf" -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_ABSORIGIN_FOLLOW, tree ) ParticleManager:SetParticleControl( effect_cast, 0, tree:GetOrigin() ) ParticleManager:SetParticleControl( effect_cast, 1, Vector( 1, 1, 1 ) ) ParticleManager:ReleaseParticleIndex( effect_cast ) end function hoodwink_acorn_shot_lua:PlayEffects2( tree, location ) -- Get Resources local particle_cast = "particles/tree_fx/tree_simple_explosion.vpcf" -- Create Particle local effect_cast = ParticleManager:CreateParticle( particle_cast, PATTACH_WORLDORIGIN, nil ) ParticleManager:SetParticleControl( effect_cast, 0, tree:GetOrigin()+Vector(1,0,0) ) ParticleManager:ReleaseParticleIndex( effect_cast ) end
function on_msg_receive (msg) status_online(ok_cb, false); -- Uncomment, if debugging, to see all properties of objects -- print ("Message From data...") -- getAllData(msg.from,nil) -- print ("Message To data...") -- getAllData(msg.to,nil) -- print ("Message data...") -- getAllData(msg,nil) -- if (msg.media ~= nil) then -- print ("Message Media data...") -- getAllData(msg.media,nil) -- end if msg.out then return end if (msg.text == nil) and (msg.media == nil) then return end if (msg.to.peer_type == "encr_chat") or (msg.to.peer_type == "chat") then from_name = msg.to.print_name; sleep_timer = 2; else from_name = msg.from.print_name; sleep_timer = 3; end if (msg.text ~= nil) and string.find(msg.text, "INSTANT") then sleep_timer = 0; end if (msg.media ~= nil) then sleep_timer = 3; end if (msg.text ~= nil) then -- wait for sender to run 'sending' confirmation checks sleep(sleep_timer); -- mark the message as read mark_read(from_name, ok_cb, false); if string.find(msg.text, "DO NOT REPLY") then return end -- generate and send an image response, if asked for if string.find(msg.text, "SEND IMAGE") then image_location = (string.sub( debug.getinfo(1).source, 2, string.len(debug.getinfo(1).source) - 25 )); image_file = "canonical-logo.png"; send_photo (from_name, (image_location .. image_file), ok_cb, false); else -- generate and send a text response reply = ("ReplyTo:" .. msg.text); send_msg (from_name, reply, ok_cb, false); end end if (msg.media ~= nil) then -- wait for sender to run 'sending' confirmation checks sleep(sleep_timer); mark_read(from_name, ok_cb, false); end end function ok_cb (extra, success, result) end function on_our_id (id) end function on_secret_chat_created (peer) end function on_user_update (user) -- Change status to online status_online(ok_cb, false); end function on_chat_update (user) -- Change status to online status_online(ok_cb, false); end function on_get_difference_end () -- Change status to online status_online(ok_cb, false); end function on_binlog_replay_end () -- Change status to online status_online(ok_cb, false); end -- Helper Methods -- Sleep function to insert a delay in execution function sleep(n) os.execute("sleep " .. tonumber(n)) end -- Recursive function to obtain properties of an object function getAllData(t, prevData) -- if prevData == nil, start empty, otherwise start with prevData local data = prevData or {} -- copy all the attributes from t for k,v in pairs(t) do data[k] = data[k] or v print(string.format("Key: %s, Value:%s", k, data[k])) end -- get t's metatable, or exit if not existing local mt = getmetatable(t) if type(mt)~='table' then return data end -- get the __index from mt, or exit if not table local index = mt.__index if type(index)~='table' then return data end -- include the data from index into data, recursively, and return return getAllData(index, data) end
stringx = require('pl.stringx') require 'io' opt = { task = "evaluate", model = "queryable_word_model", version = "best_train", device = 1 } require "main" function readline() local line = io.read("*line") if line == nil then error({code="EOF"}) end line = stringx.split(line) if tonumber(line[1]) == nil then error({code="init"}) end local count = tonumber(line[1]) table.remove(line, 1) indices = {} for i = 2, #line do if ptb.vocab_map[line[i]] ~= nil then indices[i - 1] = ptb.vocab_map[line[i]] else indices[i - 1] = ptb.vocab_map["<unk>"] end end return count, line, indices end while true do print("Query: len word1 word2 etc") local ok, count, line, indices = pcall(readline) if not ok then if line.code == "EOF" then break elseif line.code == "init" then print("Line must start with a number.") else print("Unknown error occurred; please try again.") end else process_new_sentence(indices) for i = 1, count do preds = torch.exp(predict_next_word(indices)) local prob, index = preds:max(1) prob = prob[1] index = index[1] table.insert(indices, index) table.insert(line, ptb.index_map[index]) end print(table.concat(line, " ")) io.write('\n') end end
-- Functions for nvim 0.4 compatibility. -- This module will be removed once nvim 0.5 becomes stable. local vfn = vim.api.nvim_call_function local compat = {} function tbl_map(func, t) if vfn('has', {'nvim-0.5'}) == 1 then return vim.tbl_map(func, t) end local rettab = {} for k, v in pairs(t) do rettab[k] = func(v) end return rettab end function tbl_keys(t) if vfn('has', {'nvim-0.5'}) == 1 then return vim.tbl_keys(t) end local rettab = {} for k, _ in pairs(t) do table.insert(rettab, k) end return rettab end function tbl_filter(func, t) if vfn('has', {'nvim-0.5'}) == 1 then return vim.tbl_filter(func, t) end local rettab = {} for _, v in pairs(t) do if func(v) then table.insert(rettab, v) end end return rettab end function list_extend(dst, src, start, finish) if vfn('has', {'nvim-0.5'}) == 1 then return vim.list_extend(dst, src, start, finish) end for i = start or 1, finish or #src do table.insert(dst, src[i]) end return dst end return { tbl_map = tbl_map, tbl_keys = tbl_keys, tbl_filter = tbl_filter, list_extend = list_extend, }
require 'resources.data_stages' _LIFECYCLE = _STAGE.control local GameGui = require 'features.snake.gui' local Game = require 'features.snake.game' local Public = {} --- Starts snake game. -- Note when players join the game they will lose thier character. -- @param surface <LuaSurface> Surface that the board is placed on. -- @param top_left_position <Position> Position where board is placed. Defaults to {x = 1, y = 1}. -- @param size <int> size of board in board tiles. Note that the actual size of the board will be (2 * size) + 1 in -- factorio tiles. Defaults to 15. -- @param update_rate <int> number of ticks between updates. Defaults to 30. -- @param <int> maximun food on the board. Defaults to 6. function Public.start_game(surface, top_left_position, size, update_rate, max_food) Game.start_game(surface, top_left_position, size, update_rate, max_food) GameGui.show() end --- Ends the snake game. This will clean up any snake and food entities but will not restore the tiles nor -- give players thier character back. function Public.end_game() Game.end_game() GameGui.destroy() end remote.add_interface('snake', Public) return Public
local present1, autopairs = pcall(require, "nvim-autopairs") local present2, cmp_autopairs = pcall(require, "nvim-autopairs.completion.cmp") if not (present1 or present2) then return end autopairs.setup() local cmp = require("cmp") cmp.event:on("confirm_done", cmp_autopairs.on_confirm_done())
include "wac/base.lua" wac.input = wac.input or { registerSeat = function(seat) seat.wac = seat.wac or {} --seat.wac.addInput end, }
local t = ... local delay = 0.15 local animframes6 = { {Frame = 0, Delay = delay*2}, {Frame = 1, Delay = delay*2}, {Frame = 2, Delay = delay*2}, {Frame = 3, Delay = delay*2}, {Frame = 4, Delay = delay*2}, {Frame = 5, Delay = delay*2} } local animframes12= { {Frame = 0, Delay = delay}, {Frame = 1, Delay = delay}, {Frame = 2, Delay = delay}, {Frame = 3, Delay = delay}, {Frame = 4, Delay = delay}, {Frame = 5, Delay = delay}, {Frame = 6, Delay = delay}, {Frame = 7, Delay = delay}, {Frame = 8, Delay = delay}, {Frame = 9, Delay = delay}, {Frame = 10, Delay = delay}, {Frame = 11, Delay = delay} } for judgment_filename in ivalues( GetJudgmentGraphics(SL.Global.GameMode) ) do if judgment_filename ~= "None" then t[#t+1] = LoadActor( GetJudgmentGraphicPath(SL.Global.GameMode, judgment_filename) )..{ Name="JudgmentGraphic_"..StripSpriteHints(judgment_filename), InitCommand=function(self) self:visible(false):SetStateProperties(judgment_filename:match("2x6") and animframes12 or animframes6) end } else t[#t+1] = Def.Actor{ Name="JudgmentGraphic_None", InitCommand=function(self) self:visible(false) end } end end
local M = {} function M.collect(self, opts) local lines = vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false) local pattern = opts.pattern if pattern == nil or pattern == "" then local items = vim.tbl_map(function(line) return {value = line} end, lines) if opts.interactive then self:append(items, {items = items}) end return items, nil, self.errors.skip_empty_pattern end local job = self.jobs.new({"jq", pattern}, { on_exit = function(job_self, code) if code ~= 0 then return end local items = vim.tbl_map(function(output) return {value = output} end, job_self:get_stdout()) self:append(items, {items = items}) end, on_stderr = function(job_self) local items = vim.tbl_map(function(output) return {value = output, is_error = true} end, job_self:get_stderr()) if #items == 0 then return end vim.list_extend(items, self.ctx.items) self:reset() self:append(items) end, }) local err = job:start() if err ~= nil then return nil, nil, err end job.stdin:write(lines, function() if not job.stdin:is_closing() then job.stdin:close() end end) return {}, job end vim.cmd("highlight default link ThettoJqError WarningMsg") function M.highlight(self, bufnr, first_line, items) local highlighter = self.highlights:create(bufnr) highlighter:filter("ThettoJqError", first_line, items, function(item) return item.is_error end) end M.kind_name = "word" return M
--- Downward facing proximity sensor. -- This modeule is used to detect when the robot is picked up. -- @module proximity -- @alias M local M = {} local apds9960r = assert(require('apds9960')) assert(apds9960r.init()) assert(apds9960r.enable_power()) --- The native C firmware module. -- This can be used to access low level functionality from `apds9969.proximity`. FIXME: docs M.device = apds9960r.proximity --- The callback module for the proximity sensor. -- This is a callback list attached to the proximity sensor, see @{cb_list}. -- This call triggers on threshold crossing, see @{enable}. -- The parameter of the callback is a boolean which is true when the object is close. -- @usage local local proximity = require 'proximity' --proximity.cb.append( function (v) print("too close:", v) end ) M.cb = require'cb_list'.get_list() apds9960r.proximity.set_callback(M.cb.call) local enables = 0 --- Enables the proximity callback. -- When enabled, proximity changes will trigger @{cb}. -- To correctly handle multiple users of the module, please balance enables and -- disables: if you enable, please disable when you stop neededing it. -- @tparam boolean on true value to enable, false value to disable. -- @tparam[opt=100] integer period Sampling period in ms, if omitted is read -- from `nvs.read("proximity","period")`. -- @tparam[opt=250] integer threshold proximity reference value, if omitted is -- read from `nvs.read("proximity","threshold")` -- @tparam[opt=3] integer hysteresis if omitted is read from -- `nvs.read("proximity","hysteresis")` M.enable = function (on, period, threshold, hysteresis) if on and enables==0 then period = period or nvs.read("proximity","period", 100) or 100 threshold = threshold or nvs.read("proximity","threshold", 250) or 250 hysteresis = hysteresis or nvs.read("proximity","hysteresis", 3) or 3 assert(apds9960r.proximity.enable(period, threshold, hysteresis)) elseif not on and enables==1 then assert(apds9960r.proximity.enable(nil)) end if on then enables=enables+1 elseif enables>0 then enables=enables-1 end end return M
-- Copyright (C) Miracle -- Copyright (C) OpenWAF local _M = { _VERSION = "0.0.1" } function _M.transforms(self, options, values) local func = { base64_decode = function(value) if not value then return nil end local t_val = ngx.decode_base64(tostring(value)) if (t_val) then return t_val else return value end end, base64_encode = function(value) if not value then return nil end return ngx.encode_base64(value) end, compress_whitespace = function(value) if type(value) ~= "string" then return value end return ngx.re.gsub(value, [=[\s+]=], ' ', "oij") end, hex_decode = function(value) if type(value) ~= "string" then return value end local str if (pcall(function() str = value:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end) end)) then return str else return value end end, hex_encode = function(value) if type(value) ~= "string" then return value end return (value:gsub('.', function (c) return string.format('%02x', string.byte(c)) end)) end, html_decode = function(value) if type(value) ~= "string" then return value end local str = ngx.re.gsub(value, [=[&lt;]=], '<', "oij") str = ngx.re.gsub(str, [=[&gt;]=], '>', "oij") str = ngx.re.gsub(str, [=[&quot;]=], '"', "oij") str = ngx.re.gsub(str, [=[&apos;]=], "'", "oij") pcall(function() str = ngx.re.gsub(str, [=[&#(\d+);]=], function(n) return string.char(n[1]) end, "oij") end) pcall(function() str = ngx.re.gsub(str, [=[&#x(\d+);]=], function(n) return string.char(tonumber(n[1],16)) end, "oij") end) str = ngx.re.gsub(str, [=[&amp;]=], '&', "oij") return str end, length = function(value) if not value then return 0 end if type(value) == "table" then local length = 0 for k, v in pairs(value) do length = length + #tostring(k) + #tostring(v) end return length end return #tostring(value) end, lowercase = function(value) if type(value) ~= "string" then return value end return string.lower(value) end, md5 = function(value) if not value then return nil end return ngx.md5_bin(value) end, normalise_path = function(value) if type(value) ~= "string" then return value end while (ngx.re.match(value, [=[[^/][^/]*/\.\./|/\./|/{2,}]=], "oij")) do value = ngx.re.gsub(value, [=[[^/][^/]*/\.\./|/\./|/{2,}]=], '/', "oij") end return value end, remove_comments = function(value) if type(value) ~= "string" then return value end return ngx.re.gsub(value, [=[\/\*(\*(?!\/)|[^\*])*\*\/]=], '', "oij") end, remove_comments_char = function(value) if type(value) ~= "string" then return value end return ngx.re.gsub(value, [=[\/\*|\*\/|--|#]=], '', "oij") end, remove_whitespace = function(value) if type(value) ~= "string" then return value end return ngx.re.gsub(value, [=[\s+]=], '', "oij") end, remove_nulls = function(value) return ngx.re.gsub(value, [=[\0+]=], '', "oij") end, replace_comments = function(value) if type(value) ~= "string" then return value end return ngx.re.gsub(value, [=[\/\*(\*(?!\/)|[^\*])*\*\/]=], ' ', "oij") end, sha1 = function(value) if not value then return nil end return ngx.sha1_bin(value) end, sql_hex_decode = function(value) if type(value) ~= "string" then return value end if (string.find(value, '0x', 1, true)) then value = string.sub(value, 3) local str if (pcall(function() str = value:gsub('..', function (cc) return string.char(tonumber(cc, 16)) end) end)) then return str else return value end else return value end end, trim = function(value) if type(value) ~= "string" then return value end return ngx.re.gsub(value, [=[^\s*|\s+$]=], '') end, trim_left = function(value) if type(value) ~= "string" then return value end return ngx.re.sub(value, [=[^\s+]=], '') end, trim_right = function(value) if type(value) ~= "string" then return value end return ngx.re.sub(value, [=[\s+$]=], '') end, uri_decode = function(value) if type(value) ~= "string" then return value end --Unescape str as an escaped URI component. return ngx.unescape_uri(value) end, uri_decode_uni = function(value) if type(value) ~= "string" then return value end --Unescape str as an escaped URI component. return ngx.unescape_uri(value) end, uri_encode = function(value) if type(value) ~= "string" then return value end --Escape str as a URI component return ngx.escape_uri(value) end, counter = function(value) if not value then return 0 end if type(value) == "table" then return #value end return 1 end, } if not func[options] then ngx.log(ngx.WARN, "Not support transform: ", options) return nil end return func[options](values) end return _M
local function printUsage() print( "Usages:" ) print( "gps host" ) print( "gps host <x> <y> <z>" ) print( "gps locate" ) end local tArgs = { ... } if #tArgs < 1 then printUsage() return end local sCommand = tArgs[1] if sCommand == "locate" then -- "gps locate" -- Just locate this computer (this will print the results) gps.locate( 2, true ) elseif sCommand == "host" then -- "gps host" -- Act as a GPS host if pocket then print( "GPS Hosts must be stationary" ) return end -- Find a modem local sModemSide = nil for n,sSide in ipairs( rs.getSides() ) do if peripheral.getType( sSide ) == "modem" and peripheral.call( sSide, "isWireless" ) then sModemSide = sSide break end end if sModemSide == nil then print( "No wireless modems found. 1 required." ) return end -- Determine position local x,y,z if #tArgs >= 4 then -- Position is manually specified x = tonumber(tArgs[2]) y = tonumber(tArgs[3]) z = tonumber(tArgs[4]) if x == nil or y == nil or z == nil then printUsage() return end print( "Position is "..x..","..y..","..z ) else -- Position is to be determined using locate x,y,z = gps.locate( 2, true ) if x == nil then print( "Run \"gps host <x> <y> <z>\" to set position manually" ) return end end -- Open a channel local modem = peripheral.wrap( sModemSide ) print( "Opening channel on modem "..sModemSide ) modem.open( gps.CHANNEL_GPS ) -- Serve requests indefinately local nServed = 0 while true do local e, p1, p2, p3, p4, p5 = os.pullEvent( "modem_message" ) if e == "modem_message" then -- We received a message from a modem local sSide, sChannel, sReplyChannel, sMessage, nDistance = p1, p2, p3, p4, p5 if sSide == sModemSide and sChannel == gps.CHANNEL_GPS and sMessage == "PING" and nDistance then -- We received a ping message on the GPS channel, send a response modem.transmit( sReplyChannel, gps.CHANNEL_GPS, { x, y, z } ) -- Print the number of requests handled nServed = nServed + 1 if nServed > 1 then local x,y = term.getCursorPos() term.setCursorPos(1,y-1) end print( nServed.." GPS requests served" ) end end end else -- "gps somethingelse" -- Error printUsage() end
Locales['sv'] = { ['you_paid'] = 'du betalade ~r~%s SEK~s~ till körskolan', ['go_next_point'] = 'åk till nästa punkt!', ['in_town_speed'] = 'du åker ni i stan, var uppmärksam på din hastighet! hastighetsgräns: ~y~', ['next_point_speed'] = 'åk till nästa punkt! hastighetsgräns: ~y~%s~s~ km/h', ['stop_for_ped'] = '~r~Stanna~s~ för fotgängare som korsar vägen!', ['good_lets_cont'] = '~g~Bra~s~, fortsätt.', ['stop_look_left'] = '~r~Stanna~s~ och kolla åt ~y~vänster~s~. Hastighetsgräns: ~y~%s~s~ km/h', ['good_turn_right'] = '~g~Bra~s~, sväng höger och följ linjen', ['watch_traffic_lightson'] = 'var vaken i trafiken och ~y~sätt på dina lampor~s~!', ['stop_for_passing'] = '~r~Stanna~s~ för passerande fordon!', ['hway_time'] = 'det är dags att köra på motorväg! Hastighetsgräns: ~y~%s~s~ km/h', ['gratz_stay_alert'] = 'jag är imponerad, glöm inte vara ~r~pigg~s~ när du kör!', ['passed_test'] = 'du ~g~passerade~s~ provet, gratulerar!', ['failed_test'] = 'du ~r~kuggade~s~ provet, bättre lycka nästa gång', ['theory_test'] = 'teoretiskt körningsprov', ['road_test_car'] = 'B-körkort (personbil)', ['road_test_bike'] = 'A-körkort (motorcykel)', ['road_test_truck'] = 'C-körkort (lastbil)', ['driving_school'] = 'körskola', ['press_open_menu'] = 'tryck ~INPUT_CONTEXT~ för att öppna menyn', ['driving_school_blip'] = 'körskola', ['driving_test_complete'] = 'körprovet har avslutats', ['driving_too_fast'] = '~r~Du kör för snabbt,~s~ den nuvarande hastighetsgräns är: ~y~%s~s~ km/h!', ['errors'] = 'misstag: ~r~%s~s~/%s', ['you_damaged_veh'] = 'du skadade fordonet!', }
-- A bit different from cl_plugins, here we set the default value instead. Clockwork.config:Add("jammer_range", 1024, true)
local full_date_formats = { "(%d%d%d%d)%-(1[012])%-([012]%d)", "(%d%d%d%d)%-(1[012])%-(3[01])", "(%d%d%d%d)%-(0%d)%-([012]%d)", "(%d%d%d%d)%-(0%d)%-(3[01])", "(%d%d%d%d)(1[012])([012]%d)", "(%d%d%d%d)(1[012])(3[01])", "(%d%d%d%d)(0%d)([012]%d)", "(%d%d%d%d)(0%d)(3[01])", } local partial_date_formats = { "(%d%d%d%d)%-(1[012])", "(%d%d%d%d)%-(0%d)", "(%d%d%d%d)(1[012])", "(%d%d%d%d)(0%d)", "(%d%d%d%d)", } local time_formats = { "([01]%d):([0-5]%d):([0-5]%d)%.(%d+)", "([2][0-4]):([0-5]%d):([0-5]%d)%.(%d+)", "([01]%d):([0-5]%d):(60)%.(%d+)", "([2][0-4]):([0-5]%d):(60)%.(%d+)", "([01]%d):([0-5]%d):([0-5]%d)", "([2][0-4]):([0-5]%d):([0-5]%d)", "([01]%d):([0-5]%d):(60)", "([2][0-4]):([0-5]%d):(60)", } local offset_formats = { "([+-])([01]%d):([0-5]%d)", "([+-])([2][0-4]):([0-5]%d)", "([+-])([01]%d)([0-5]%d)", "([+-])([2][0-4])([0-5]%d)", "([+-])([01]%d)", "([+-])([2][0-4])", "Z" } local months_w_thirty_one_days = { [1] = true, [3] = true, [5] = true, [7] = true, [8] = true, [10] = true, [12] = true } -- compiling all possible ISO8601 patterns local iso8601_formats = {} for _,date_fmt in ipairs(full_date_formats) do for _,time_fmt in ipairs(time_formats) do for _,offset_fmt in ipairs(offset_formats) do iso8601_formats[#iso8601_formats+1] = "^"..date_fmt.."T"..time_fmt..offset_fmt.."$" end end end local function is_leap_year(year) return 0 == year % 4 and (0 ~= year % 100 or 0 == year % 400) end local function parse_date_time (date_time_str) local year, mon, day, hh, mm, ss, ms, sign, off_h, off_m -- trying to parse a complete ISO8601 date for _,fmt in pairs(iso8601_formats) do year, mon, day, hh, mm, ss, ms, sign, off_h, off_m = date_time_str:match(fmt) if year then break end end -- milliseconds are optional, so offset may be stored in ms if not off_m and ms and ms:match("^[+-]") then off_m, off_h, sign, ms = off_h, sign, ms, 0 end sign, off_h, off_m = sign or "+", off_h or 0, off_m or 0 return year, mon, day, hh, mm, ss, ms, sign, off_h, off_m end local function parse_date (date_str) local year, mon, day for _,fmt in pairs(full_date_formats) do year, mon, day = date_str:match("^"..fmt.."$") if year ~= nil then break end end if not year then for _,fmt in pairs(partial_date_formats) do year, mon, day = date_str:match("^"..fmt.."$") if year ~= nil then break end end end return year, mon, day end local function parse_iso8601 (date_str) local year, mon, day, hh, mm, ss, ms, sign, off_h, off_m = parse_date_time(date_str) if not year then -- trying to parse only a year with optional month and day year, mon, day = parse_date(date_str) end if not year then error(("invalid date '%s': date string doesn't match ISO8601 pattern"):format(date_str), 2) end if is_leap_year(tonumber(year)) and tonumber(mon) == 2 and tonumber(day) == 29 then error(("invalid date '%s': wrong leap year date"):format(date_str), 2) end if mon and tonumber(mon) == 2 and day and tonumber(day) > 28 then error(("invalid date '%s': February has 28 days"):format(date_str), 2) end if mon and day and tonumber(day) == 31 and not months_w_thirty_one_days[mon] then error(("invalid date '%s': month %d has 30 days"):format(date_str, mon), 2) end return { year = tonumber(year), month = tonumber(mon) or 1, day = tonumber(day) or 1, hour = (tonumber(hh) or 0) - (tonumber(sign..off_h) or 0), min = (tonumber(mm) or 0) - (tonumber(sign..off_m) or 0), sec = tonumber(ss or 0), msec = tonumber(ms or 0) } end local function inst (date_str) local date = parse_iso8601(date_str) return setmetatable( date, { __len = function () local str = os.date("#inst \"%Y-%m-%dT%H:%M:%S", os.time(date)) return ("%s.%03d-00:00\""):format(str, date.msec) end } ) end -- tests if nil then local function test(date_str, date_table) local res = os.time(inst(date_str)) local expected = os.time(date_table) assert(res == expected, ("%s: expected %d, got %d"):format(date_str, expected, res)) end test("2021", {year=2021, month=1, day=1, hour=0, min=0, sec=0}) test("2021-02", {year=2021, month=2, day=1, hour=0, min=0, sec=0}) test("202102", {year=2021, month=2, day=1, hour=0, min=0, sec=0}) test("2021-02-21", {year=2021, month=2, day=21, hour=0, min=0, sec=0}) test("20210221", {year=2021, month=2, day=21, hour=0, min=0, sec=0}) test("2021-02-21T23:59:42Z", {year=2021, month=2, day=21, hour=23, min=59, sec=42}) test("20210221T23:59:42Z", {year=2021, month=2, day=21, hour=23, min=59, sec=42}) test("2021-02-21T23:59:42.999Z", {year=2021, month=2, day=21, hour=23, min=59, sec=42}) test("20210221T23:59:42.999Z", {year=2021, month=2, day=21, hour=23, min=59, sec=42}) test("2021-02-21T23:59:42+03:00", {year=2021, month=2, day=21, hour=20, min=59, sec=42}) test("20210221T23:59:42+03:00", {year=2021, month=2, day=21, hour=20, min=59, sec=42}) test("2021-02-21T23:59:42.999+03:00", {year=2021, month=2, day=21, hour=20, min=59, sec=42}) test("20210221T23:59:42.999+03:00", {year=2021, month=2, day=21, hour=20, min=59, sec=42}) assert(not pcall(inst, "20041330")) assert(not pcall(inst, "2004-02-30T23:59:42Z")) assert(not pcall(inst, "2004-02-31T23:59:42Z")) assert(not pcall(inst, "2004-04-31T23:59:42Z")) end return inst
-- example reporting script which demonstrates a custom -- done() function that prints latency percentiles as CSV done = function(summary, latency, requests, connect_time) io.write("------------------------------\n") for _, p in pairs({ 50, 90, 99, 99.999 }) do n = latency:percentile(p) io.write(string.format("%g%%,%d\n", p, n)) end end
local rpc_mgr = require "rpc.rpc_mgr" local cnetwork = require "cerberus.network" -- wrap most core api into cerberus local cerberus = {} function cerberus.start(...) return rpc_mgr:run(...) end function cerberus:connect(ip, port) return rpc_mgr:sync(cnetwork.connect, ip, port) end function cerberus:listen(ip, port) return rpc_mgr:sync(cnetwork.listen, ip, port) end return cerberus
jam = {} jam.globals = {} setmetatable(jam.globals, { __index = function(t, key) return jam_getvar(key) end, __newindex = function(t, key, value) jam_setvar(key, value) end, }) setmetatable(jam, { __index = function(t, key) --print('Generating ' .. key) if jam_evaluaterule('RuleExists', key)[1] == 'true' then local f = function(...) return jam_evaluaterule(key, ...) end rawset(t, key, f) return f else local targetkey = key local target = {} setmetatable(target, { __index = function(t, key) return jam_getvar(targetkey, key) end, __newindex = function(t, key, value) jam_setvar(targetkey, key, value) end, }) rawset(jamtargets, targetkey, target) return target end end, }) jamvar = {} setmetatable(jamvar, { __index = function(t, key) return jam_getvar(key) end, __newindex = function(t, key, value) jam_setvar(key, value) end, }) jamtargets = {} setmetatable(jamtargets, { __index = function(t, targetkey) local target = {} setmetatable(target, { __index = function(t, targetkey) return jam_getvar(targetkey, key) end, __newindex = function(t, key, value) jam_setvar(targetkey, key, value) end, }) rawset(jamtargets, targetkey, target) return target end, })
require('telescope').setup{ defaults = { file_ignore_patterns = {".git/", "node_modules/"}, mappings = { n = { ["q"] = "close", ["<C-d>"] = "delete_buffer", } }, vimgrep_arguments = { "rg", "--hidden", "--color=never", "--no-heading", "--with-filename", "--line-number", "--column", "--smart-case" }, }, pickers = { find_files = { hidden = true } } } vim.api.nvim_set_keymap('n', '<leader>ff', '<cmd>Telescope find_files<cr>', { noremap = true }) vim.api.nvim_set_keymap('n', '<leader>fg', '<cmd>Telescope live_grep<cr>', { noremap = true }) vim.api.nvim_set_keymap('n', '<leader>fb', '<cmd>Telescope buffers<cr>', { noremap = true }) vim.api.nvim_set_keymap('n', '<leader>fh', '<cmd>Telescope help_tags<cr>', { noremap = true })
local Class = require("lib.class") local Lovox = require("lib.lovox") local Vec3 = require("lib.vec3") local Entity = require("src.entity") local World = require("src.world") local Enemy = Class("Enemy", Entity) Enemy.isEnemy = true Enemy.batch = require("src.skeletonbatch") Enemy.animations = { idle = {0}, walking = {3, 1, 4, 1}, stab = {2}, dead1 = {5}, dead2 = {4}, } Enemy.animTimer = 0 Enemy.animIndex = 1 Enemy.state = "idle" function Enemy:initialize(...) Entity.initialize(self, ...) self.shape = World:circle(self.position.x, self.position.y, 35) self.shape.obj = self self.id = self.batch:add(self.position.x, self.position.y, self.position.z, -math.pi/2, 2) self.respawnCD = 0 end function Enemy:idle(dt) Enemy.batch:setFrame(self.id, 1) if self.animIndex > 1 then self.animIndex = 1 end return "idle" end function Enemy:walking(dt) if self.animIndex > 4 then self.animIndex = 1 end self.position = self.position + (Vec3(math.cos(self.rotation), math.sin(self.rotation), 0) * 30) * dt return "walking" end function Enemy:stab(dt) if self.animIndex > 2 then self.animIndex = 1 return "stab" end return "stab" end function Enemy:dead1(dt) if self.animIndex > 1 then self.animIndex = 1 return "dead1" end return "dead1" end function Enemy:dead2(dt) if self.animIndex > 1 then self.animIndex = 1 return "dead2" end return "dead2" end function Enemy:onHit() if self.state == "dead1" or self.state == "dead2" then return false end self.shape:scale(0.25) self.state = "dead"..tostring(love.math.random(1, 2)) self.animIndex = 1 self.respawnCD = 2 + love.math.random() * 2 return true end function Enemy:onDeath() Entity.onDeath(self) self.batch:setTransformation(self.id, 0, 0, 0, 0) end function Enemy:update(dt) Entity.update(self, dt) self.animTimer = self.animTimer + dt if self.animTimer >= 0.15 then self.animTimer = 0 self.animIndex = self.animIndex + 1 end if self.state == "dead1" or self.state == "dead2" then self.respawnCD = self.respawnCD - dt if self.respawnCD <= 0 then self.shape:scale(4) self.state = "idle" self.animIndex = 1 end end self.state = self[self.state](self, dt) Enemy.batch:setFrame(self.id, self.animations[self.state][self.animIndex]) self.batch:setTransformation(self.id, self.position.x, self.position.y, self.position.z, self.rotation - math.pi/2, 2) self.shape:moveTo(self.position.x, self.position.y) end function Enemy.render() Enemy.batch:draw() end return Enemy
local lVector = require 'Q/RUNTIME/VCTR/lua/lVector' local json = require 'Q/UTILS/lua/json' local T = {} local function view_meta () local V = {} for k,v in pairs(_G) do if ( type(v) == "lVector" ) then local x = v:meta() for k2, v2 in pairs(x) do assert( ( ( k2 == "base" ) or ( k2 == "nn") or ( k2 == "aux" ) )) for k3, v3 in pairs(v2) do if ( type(v3) == "Scalar") then v2[k3] = v3:to_str() end end end V[k] = x -- print("Saving ", k, v) end end local jV = json.stringify(V) return V, jV end T.view_meta = view_meta require('Q/q_export').export('view_meta', view_meta) return T
local a=module('_core','libs/Tunnel')local b=module('_core','libs/Proxy')local c=a.getInterface("hpp_craftammo")API=b.getInterface('API')cAPI=a.getInterface('cAPI')local d=module("hpp_craftammo","config/cfg")animApi=module("_core","client/functions/_Anims")local e={"mureta","mafia"}Citizen.CreateThread(function()while true do Citizen.Wait(5*60*1000)collectgarbage("count")collectgarbage("collect")end end)function ToogleCraftAmmoMenu(f)SetNuiFocus(f,f)if f then SendNUIMessage({open=f,crafts=d.crafts})else SendNUIMessage({open=f})end end;RegisterNUICallback("closeMenu",function()ToogleCraftAmmoMenu(false)end)RegisterNUICallback("craftAmmo",function(g)local h=g._AmmoName;local i=tonumber(g._AmmoPrice)c.tryCraftAmmo(h,i)end)local j={}local k=3000;Citizen.CreateThread(function()while true do for l,m in pairs(d.craftspots)do local n=GetPlayerPed(-1)local o,p,q=table.unpack(GetEntityCoords(n))local r,s,t=m[1],m[2],m[3]local u=GetDistanceBetweenCoords(o,p,q,r,s,t,true)if u<20 then if#j>0 then for v,w in pairs(j)do if w[1]==m[1]then else table.insert(j,1,{m[1],m[2],m[3]})end end else table.insert(j,1,{m[1],m[2],m[3]})end else for x=1,#j do if j[x][1]==m[1]then table.remove(j,x)end end end end;Citizen.Wait(k)end end)local y=3000;Citizen.CreateThread(function()while true do for z=1,#j do local n=GetPlayerPed(-1)local A,B,C=table.unpack(GetEntityCoords(n))local r,s,t=j[z][1],j[z][2],j[z][3]local u=GetDistanceBetweenCoords(A,B,C,r,s,t)if u<20 then y=1;DrawMarker(2,r,s,t,0,0,0,0,0,0,0.3,0.3,0.3,255,255,0,30,1,1,1,1)if u<1.5 and IsControlJustPressed(0,38)then local D=false;for E=1,#e do if c.hasGroup(e[E])then D=true end end;if D then ToogleCraftAmmoMenu(true)else TriggerEvent("Notify","negado","Você não tem permissão!")break end end else y=3000 end end;Citizen.Wait(y)end end)
local Behavior = CreateAIBehavior("HeliFireRockets", { Constructor = function (self, entity) entity:SelectPrimaryWeapon() entity:SelectPipe(0, "do_nothing") local postures = { { name = "StandAim", type = POSTURE_AIM, stance = STANCE_STAND, priority = 8.0, { name = "StandAimCenter", lean = 0.0, priority = 0.0, }, }, { name = "CrouchAim", type = POSTURE_AIM, stance = STANCE_CROUCH, priority = 8.0, { name = "CrouchAimCenter", lean = 0.0, priority = 0.0, }, }, } AI.SetPostures(entity.id, postures) end, })
padawan_pannaqa_01_convo_template = ConvoTemplate:new { initialScreen = "", templateType = "Lua", luaClassHandler = "padawan_pannaqa_01_conv_handler", screens = {} } intro = ConvoScreen:new { id = "intro", leftDialog = "@conversation/padawan_pannaqa_01:s_41aab3ed", -- I'm sure someone of your ability will be able to assist me. Do you have a second to spare? stopConversation = "false", options = { {"@conversation/padawan_pannaqa_01:s_df607c49", "cant_leave_village"}, -- I'm listening. {"@conversation/padawan_pannaqa_01:s_fd022a50", "sorry_for_bothering"} -- No, find some sap to bother with your shallow needs. } } padawan_pannaqa_01_convo_template:addScreen(intro); cant_leave_village = ConvoScreen:new { id = "cant_leave_village", leftDialog = "@conversation/padawan_pannaqa_01:s_53c84ebd", -- I can't leave the village.. there's far too much to be done at the moment. But I also need a replacement part for my vibro-tiller. Without it, farming is much more difficult. As you can see, we have not had much luck of late trying to grow our crops. Between the harsh environment and the constant attacks of Mellichae's thugs, we have our hands full. stopConversation = "false", options = { {"@conversation/padawan_pannaqa_01:s_dd5fc3e4", "find_shendo"}, -- Sure, why not. How can I help? {"@conversation/padawan_pannaqa_01:s_ed2f6bdb", "sorry_for_bothering"} -- What kind of mup do you take me for? I'm not doing you menial labor. } } padawan_pannaqa_01_convo_template:addScreen(cant_leave_village); find_shendo = ConvoScreen:new { id = "find_shendo", leftDialog = "@conversation/padawan_pannaqa_01:s_194a6a4b", -- Shendo, an extremely unreliable acquaintance of mine was supposed to have delivered it many hours ago but has yet to show up. Would you be willing to find him and retrieve the part? stopConversation = "false", options = { {"@conversation/padawan_pannaqa_01:s_69af28a6", "ill_be_here"}, -- I would be more than willing to help. {"@conversation/padawan_pannaqa_01:s_ad0eb2bb", "sorry_for_bothering"} -- Tasks like this are for the servants, bother someone else. } } padawan_pannaqa_01_convo_template:addScreen(find_shendo); ill_be_here = ConvoScreen:new { id = "ill_be_here", leftDialog = "@conversation/padawan_pannaqa_01:s_bbfeec70", -- Thank you kindly, I'll be here when you return. stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(ill_be_here); sorry_for_bothering = ConvoScreen:new { id = "sorry_for_bothering", leftDialog = "@conversation/padawan_pannaqa_01:s_72d5a837", -- Sorry for bothering, I didn't mean to offend. stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(sorry_for_bothering); intro_spoke_to_second_npc = ConvoScreen:new { id = "intro_spoke_to_second_npc", leftDialog = "@conversation/padawan_pannaqa_01:s_b2216c3", -- Do you have the part? Did you find Shendo? stopConversation = "false", options = { {"@conversation/padawan_pannaqa_01:s_3a3e0d5d", "gardens_in_shape"}, -- Yes, Shendo wasn't difficult to find... just to deal with. } } padawan_pannaqa_01_convo_template:addScreen(intro_spoke_to_second_npc); gardens_in_shape = ConvoScreen:new { id = "gardens_in_shape", leftDialog = "@conversation/padawan_pannaqa_01:s_42e0a11e", -- Thank you so much. Hopefully this will help me get the gardens around here into shape. stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(gardens_in_shape); intro_spoke_to_first_npc = ConvoScreen:new { id = "intro_spoke_to_first_npc", leftDialog = "@conversation/padawan_pannaqa_01:s_b9c3a3be", -- Any luck finding Shendo? stopConversation = "false", options = { {"@conversation/padawan_pannaqa_01:s_30546869", "please_return"}, -- Not yet, but don't worry... I will. {"@conversation/padawan_pannaqa_01:s_b336be8b", "find_your_way"} -- I've decided that you're on your own. Find another servant. } } padawan_pannaqa_01_convo_template:addScreen(intro_spoke_to_first_npc); intro_in_progress = ConvoScreen:new { id = "intro_in_progress", leftDialog = "@conversation/padawan_pannaqa_01:s_6d11135b", -- Did you find Shendo with the vibro-tiller part? stopConversation = "false", options = { {"@conversation/padawan_pannaqa_01:s_30546869", "please_return"}, -- Not yet, but don't worry... I will. {"@conversation/padawan_pannaqa_01:s_387d18ec", "find_your_way"} -- I've decided that I'm done being your slave boy. You're on your own. } } padawan_pannaqa_01_convo_template:addScreen(intro_in_progress); please_return = ConvoScreen:new { id = "please_return", leftDialog = "@conversation/padawan_pannaqa_01:s_52da7aa", -- Ahh, thank you. Please return when you have the part. stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(please_return); find_your_way = ConvoScreen:new { id = "find_your_way", leftDialog = "@conversation/padawan_pannaqa_01:s_24a1738d", -- I see. I thank you for the consideration you've given and trust that you find your way. stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(find_your_way); completed_quest = ConvoScreen:new { id = "completed_quest", leftDialog = "@conversation/padawan_pannaqa_01:s_be0f3920", -- Now maybe instead of just dead trees, I'll grow some vegetables. Or flowers. Or maybe just more trees. stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(completed_quest); not_on_quest = ConvoScreen:new { id = "not_on_quest", leftDialog = "@conversation/padawan_pannaqa_01:s_1843ab7e", -- One dead tree. That's pretty much all I've got to show for my farming skills. As if I should call them skills even. [*sigh*] stopConversation = "true", options = {} } padawan_pannaqa_01_convo_template:addScreen(not_on_quest); addConversationTemplate("padawan_pannaqa_01_convo_template", padawan_pannaqa_01_convo_template);
--[[ © 2020 TERRANOVA do not share, re-distribute or modify without permission of its author. --]] local CHAR = ix.meta.character function CHAR:GetKevlar() for k, v in pairs(self:GetCharPanel():GetItems()) do if(v.outfitCategory == "kevlar") then return v end end return nil end
--[[ ?)]] -- ################################################## FLY MOD ACTIVE ################################################## -- Charge: 1 room. -- While held, a robotic fly will orbit Isaac, dealing light contact damage and blocking enemy shots. -- After activating the item, Fly Mod will leave the orbit and dash for a few seconds, dealing a high amount of damage. -- After the fly slows down, it will bounce off the walls for the remainder of the room, dealing a medium amount of damage. -- Fly Mod confuses fly enemies that get close to it. It also turns Blue Flies into Locusts if they stay close to it for a few seconds. -- Every time Fly Mod kills an enemy, there is 50% for a Blue Fly to spawn. -- Synergizes with BFFS: increased area of effect for enemies and Blue Flies + the number of Blue Flies spawned after killing an enemy is increased by the amount of BFFS! items. local mod = RegisterMod("fly mod", 1) local game = Game() local ZERO_VECTOR = Vector(0, 0) local FlyModStates = { STATE_ORBIT = 0, -- orbiting the player (default state) STATE_DASH = 1, -- initial speed boost after activating the item STATE_LAUNCHED = 2 -- after slowing down from the boost above; goes back to ORBIT on a new room or if the active item charges again (batteries, 9 Volt, etc) } local FlyMod = { COLLECTIBLE_FLY_MOD = Isaac.GetItemIdByName("Fly Mod"), -- item ID VARIANT_FLY_MOD = Isaac.GetEntityVariantByName("Fly Mod"), -- familiar variant ORBIT_LAYER = 763, -- hopefully unique to this orbital (the number of familiars in a layer adjusts the orbiting speed and placement); 853 no longer works for some reason? ORBIT_SPEED = 0.03, -- how fast it orbits (should be less than 0.1) ORBIT_DISTANCE = Vector(120.0, 120.0), -- circular orbit of radius 120 LAUNCH_VELOCITY = 10.0, -- how fast Fly Mod moves while bouncing around the room (locked at this speed because of friction) DASH_VELOCITY = 25.0, -- initial boost when the active item is used (slows down to the speed above) DASH_FRICTION = 0.97, -- increase to decrease how quickly the boost above goes does to LAUNCH_VELOCITY (slow Fly Mod down) -- ^ percentage of the speed that is kept every frame (new = old * DASH_FRICTION) while in the DASH state DASH_FLASH_COLOR = Color(2.5, 2.5, 2.5, 1.0, 0, 0, 0), -- color to be set for dash visual (fades out); see below for *CONT. DASH_FLASH_DURATION = 5, -- how long each flash last for while dashing (in frames) ORBIT_DAMAGE = 1.00, -- how much collision damage Fly Mod deals when in the orbit state (original damage from the XMLs) LAUNCHED_DAMAGE = 5.00, -- how much collision damage Fly Mod deals when it is flying across the room DASH_DAMAGE_MULTIPLIER = 2.0, -- how much damage is dealt while first dashing (this * LAUNCHED_DAMAGE) MAX_CONFUSION_DISTANCE = 80.0, -- confusion range for fly monsters BFFS_CONFUSION_DISTANCE_MULTIPLIER = 1.2, -- (BFFS synergy) above is multiplied by this CONFUSION_DURATION = 2, -- how long each confusion effect added last for (should be low since they will stack every frame) -- Both of the following two values are squared (distance = 90.0, mult = 1.05) MAX_BLUE_FLY_DISTANCE = 8100.0, -- a blue fly would have to be a <= of this distance to a Fly Mod for it to turn into a random Locust BFFS_BLUE_FLY_DISTANCE_MULTIPLIER = 1.1025, -- (BFFS synergy) above is multiplied by this FRAMES_IN_RANGE = 40.0, -- how many frames does a blue fly have to be in range (above) of a Fly Mod for it to turn into a random Locust ENEMY_FLY_TYPES = { -- maps an EntityType to a boolean teling us whether this of type of entity should be confused when it gets close to the Fly [EntityType.ENTITY_FLY] = true, [EntityType.ENTITY_POOTER] = true, [EntityType.ENTITY_ATTACKFLY] = true, [EntityType.ENTITY_BOOMFLY] = true, [EntityType.ENTITY_SUCKER] = true, [EntityType.ENTITY_MOTER] = true, [EntityType.ENTITY_ETERNALFLY] = true, [EntityType.ENTITY_FLY_L2] = true, [EntityType.ENTITY_RING_OF_FLIES] = true, [EntityType.ENTITY_FULL_FLY] = true, [EntityType.ENTITY_DART_FLY] = true, [EntityType.ENTITY_SWARM] = true, [EntityType.ENTITY_DUKIE] = true, [EntityType.ENTITY_HUSH_FLY] = true, [EntityType.ENTITY_SWARMER] = true, [EntityType.ENTITY_DUKE] = true } } -- *CONT. (color was based on the Pony's dash color) FlyMod.DASH_FLASH_COLOR:SetOffset(0.7, 0.7, 0.7) -- now this is just silly: color constructor expects integers for offsets (while the attributes are floats) if not __eidItemDescriptions then __eidItemDescriptions = {}; end -- External Item Descriptions compatibility __eidItemDescriptions[FlyMod.COLLECTIBLE_FLY_MOD] = "While held, gives Isaac an orbiting fly#When used, the fly is launched, dealing contact damage#Converts blue flies into locusts and confuses enemy flies"; -- Called every time an entity takes damage local function entity_take_damage(_, dmg_target, dmg_amount, dmg_flags, dmg_source, dmg_countdown_frames) -- if something was killed by Fly Mod, there is a 50% chance to spawn a blue fly if dmg_source.Type == EntityType.ENTITY_FAMILIAR and dmg_source.Variant == FlyMod.VARIANT_FLY_MOD and dmg_target.HitPoints - dmg_amount <= 0 and math.random(2) == 1 and dmg_target:GetData().CheckedFlyModDeath == nil then dmg_target:GetData().CheckedFlyModDeath = true local player = Isaac.GetPlayer(0) player:AddBlueFlies(player:GetCollectibleNum(CollectibleType.COLLECTIBLE_BFFS) + 1, player.Position, nil) end end mod:AddCallback(ModCallbacks.MC_ENTITY_TAKE_DMG, entity_take_damage) -- Called when the orbital first spawns or when we come back after an exit/continue local function init_fly_mod(_, fly_mod) -- EntityFamiliar fly_mod:AddToOrbit(FlyMod.ORBIT_LAYER) -- sets OrbitLayer attribute + initial states fly_mod.OrbitDistance = FlyMod.ORBIT_DISTANCE fly_mod.OrbitSpeed = FlyMod.ORBIT_SPEED fly_mod.State = FlyModStates.STATE_ORBIT fly_mod.GridCollisionClass = EntityGridCollisionClass.GRIDCOLL_NONE end mod:AddCallback(ModCallbacks.MC_FAMILIAR_INIT, init_fly_mod, FlyMod.VARIANT_FLY_MOD) -- Called every frame for each Fly Mod orbital local function update_fly_mod(_, fly_mod) -- EntityFamiliar local fly_mod_data = fly_mod:GetData() -- Things to change depending on state: Damage, Grid collision type, Velocity vector if fly_mod.State == FlyModStates.STATE_ORBIT then -- in orbit fly_mod.CollisionDamage = FlyMod.ORBIT_DAMAGE fly_mod.GridCollisionClass = EntityGridCollisionClass.GRIDCOLL_NONE -- fly over everything like an orbital should fly_mod.OrbitDistance = FlyMod.ORBIT_DISTANCE -- these two MUST be here (tested) fly_mod.OrbitSpeed = FlyMod.ORBIT_SPEED local orbit_pos = fly_mod:GetOrbitPosition(fly_mod.Player.Position + fly_mod.Player.Velocity) -- get orbit position from center_pos based on some attributes (OrbitDistance, OrbitSpeed, OrbitAngleOffset) fly_mod.Velocity = orbit_pos - fly_mod.Position -- to_pos - from_pos elseif fly_mod.State == FlyModStates.STATE_DASH then -- initial dash after being launched fly_mod.CollisionDamage = FlyMod.LAUNCHED_DAMAGE * FlyMod.DASH_DAMAGE_MULTIPLIER fly_mod.GridCollisionClass = EntityGridCollisionClass.GRIDCOLL_WALLS -- to bounce off walls -- the lower bound here is the normal speed at which it moves (Fly Mod slows down after the initial boost) local vel_length = math.max(FlyMod.LAUNCH_VELOCITY, fly_mod.Velocity:Length() * FlyMod.DASH_FRICTION) if vel_length <= FlyMod.LAUNCH_VELOCITY then -- if it slows down (dash finished) fly_mod.State = FlyModStates.STATE_LAUNCHED end fly_mod.Velocity = fly_mod.Velocity:Resized(vel_length) -- dash visual flash if fly_mod:IsFrame(FlyMod.DASH_FLASH_DURATION, 0) then fly_mod:SetColor(FlyMod.DASH_FLASH_COLOR, FlyMod.DASH_FLASH_DURATION, 0, true, false) -- true = fades out end elseif fly_mod.State == FlyModStates.STATE_LAUNCHED then -- bouncing across the room (after dash) fly_mod.CollisionDamage = FlyMod.LAUNCHED_DAMAGE fly_mod.GridCollisionClass = EntityGridCollisionClass.GRIDCOLL_WALLS -- to bounce off walls fly_mod.Velocity = fly_mod.Velocity:Resized(FlyMod.LAUNCH_VELOCITY) end -- Things to do when not orbiting if fly_mod.State ~= FlyModStates.STATE_ORBIT then if not game:GetRoom():IsPositionInRoom(fly_mod.Position, 0.0) then -- in case it somehow ends up outside the room fly_mod.Position = fly_mod.Player.Position -- prevents those annoying log messages end -- if the one charge item becomes filled again (Lil' Batteries, 9 Volt or Sharp Plug) if fly_mod.Player:HasCollectible(FlyMod.COLLECTIBLE_FLY_MOD) and not fly_mod.Player:NeedsCharge() then Isaac.Spawn(EntityType.ENTITY_EFFECT, EffectVariant.POOF01, 0, fly_mod.Position, ZERO_VECTOR, nil) -- visual poof fly_mod.State = FlyModStates.STATE_ORBIT -- back to orbiting end end -- Apply certain effects to some Entity Types (Blue Flies and Enemies) local confusion_range_multiplier = 1.0 if fly_mod.Player ~= nil and fly_mod.Player:HasCollectible(CollectibleType.COLLECTIBLE_BFFS) then confusion_range_multiplier = FlyMod.BFFS_CONFUSION_DISTANCE_MULTIPLIER end local blue_fly_range_multiplier = 1.0 if fly_mod.Player ~= nil and fly_mod.Player:HasCollectible(CollectibleType.COLLECTIBLE_BFFS) then blue_fly_range_multiplier = FlyMod.BFFS_BLUE_FLY_DISTANCE_MULTIPLIER end -- Blue Flies (SubType 0) in the room (looks at how long they've been in blue-fly range and converts them into locusts) for _, blue_fly in pairs(Isaac.FindByType(EntityType.ENTITY_FAMILIAR, FamiliarVariant.BLUE_FLY, 0, false, false)) do -- SubType = 0 (Blue Flies only) blue_fly = blue_fly:ToFamiliar() local fly_data = blue_fly:GetData() if fly_data.InRangeDuration == nil then fly_data.InRangeDuration = 0 end -- how many frames has it been in range? (resets when outside) if blue_fly.Position:DistanceSquared(fly_mod.Position) <= FlyMod.MAX_BLUE_FLY_DISTANCE * blue_fly_range_multiplier then -- in range fly_data.InRangeDuration = fly_data.InRangeDuration + 1 elseif fly_data.InRangeDuration ~= 0 then -- drifted out of range fly_data.InRangeDuration = 0 end if fly_data.InRangeDuration >= FlyMod.FRAMES_IN_RANGE then -- exceded time in range fly_data.InRangeDuration = 0 -- spawn random locust Isaac.Spawn(EntityType.ENTITY_FAMILIAR, FamiliarVariant.BLUE_FLY, math.random(LocustSubtypes.LOCUST_OF_CONQUEST), blue_fly.Position, blue_fly.Velocity, nil) blue_fly:Remove() -- Morph() doesn't exist for familiars end end -- Enemies in Fly Mod's confusion radius for _, npc in pairs(Isaac.FindInRadius(fly_mod.Position, FlyMod.MAX_CONFUSION_DISTANCE * confusion_range_multiplier, EntityPartition.ENEMY)) do if FlyMod.ENEMY_FLY_TYPES[npc.Type] then npc:AddConfusion(EntityRef(fly_mod), FlyMod.CONFUSION_DURATION, true) -- true = include bosses end end end mod:AddCallback(ModCallbacks.MC_FAMILIAR_UPDATE, update_fly_mod, FlyMod.VARIANT_FLY_MOD) local function pre_fly_mod_collision(_, fly_mod, collider, low) if collider.Type == EntityType.ENTITY_PROJECTILE then -- stop enemy bullets collider:Die() end end mod:AddCallback(ModCallbacks.MC_PRE_FAMILIAR_COLLISION, pre_fly_mod_collision, FlyMod.VARIANT_FLY_MOD) -- Called when the player uses the active item to launch a Fly Mod local function use_fly_mod_item(_, collectible_type, rng) for _, fly_mod in pairs(Isaac.FindByType(EntityType.ENTITY_FAMILIAR, FlyMod.VARIANT_FLY_MOD, -1, false, false)) do fly_mod = fly_mod:ToFamiliar() -- 1. orbiting + inside the room + not inside a wall -- 2. launched (for The Battery synergy) if (fly_mod.State == FlyModStates.STATE_ORBIT and game:GetRoom():IsPositionInRoom(fly_mod.Position, 0.0) and game:GetRoom():GetGridCollisionAtPos(fly_mod.Position) ~= GridCollisionClass.COLLISION_WALL) or fly_mod.State == FlyModStates.STATE_LAUNCHED then fly_mod.Velocity = fly_mod.Velocity:Resized(FlyMod.DASH_VELOCITY) fly_mod.State = FlyModStates.STATE_DASH end end return true -- show holding active item animation end mod:AddCallback(ModCallbacks.MC_USE_ITEM, use_fly_mod_item, FlyMod.COLLECTIBLE_FLY_MOD) local has_fly_mod_item = false -- are/were we holding the active item? (used to check for swaps) -- Called every player frame to check for active item swaps local function post_player_update(_, player) -- Active item swaps: -- Reevaluate cache for familiars if we now have it (and we previously didn't) or we lost it (don't have it now but had it just before) if (player:HasCollectible(FlyMod.COLLECTIBLE_FLY_MOD) and not has_fly_mod_item) or (not player:HasCollectible(FlyMod.COLLECTIBLE_FLY_MOD) and has_fly_mod_item) then has_fly_mod_item = not has_fly_mod_item player:AddCacheFlags(CacheFlag.CACHE_FAMILIARS) -- reevaluate cache for familiars only player:EvaluateItems() end end mod:AddCallback(ModCallbacks.MC_POST_PLAYER_UPDATE, post_player_update, 0) -- Variant = 0 (Isaac and not coop babies) -- Called every new room to set any Fly Mod back to the initial orbiting state local function post_new_room(_) if Isaac.GetPlayer(0):HasCollectible(FlyMod.COLLECTIBLE_FLY_MOD) then for _, fly_mod in pairs(Isaac.FindByType(EntityType.ENTITY_FAMILIAR, FlyMod.VARIANT_FLY_MOD, -1, false, false)) do -- send any existing ones back to orbiting fly_mod:ToFamiliar().State = FlyModStates.STATE_ORBIT end end end mod:AddCallback(ModCallbacks.MC_POST_NEW_ROOM, post_new_room) -- Called every time the cache is reevaluated to add/remove a Fly Mod local function update_cache(_, player, cache_flag) --Isaac.DebugString(string.format("############################# CACHE EVALUATED WITH FLAG: %d", cache_flag)) if cache_flag == CacheFlag.CACHE_FAMILIARS then player:CheckFamiliar(FlyMod.VARIANT_FLY_MOD, player:GetCollectibleNum(FlyMod.COLLECTIBLE_FLY_MOD), player:GetCollectibleRNG(FlyMod.COLLECTIBLE_FLY_MOD)) end end mod:AddCallback(ModCallbacks.MC_EVALUATE_CACHE, update_cache)
local _type = type local string = string local _ipairs = ipairs local _osdate = os.date local _ostime = os.time local _osdifftime = os.difftime local _mathceil = math.ceil local _mathfloor = math.floor local socket = require("socket") local json = require("json") local composer = require("composer") local clientVersion = require("configNetwork").clientVersion local jwt = require('util.jwt') local isDebug = true local print = isDebug and Runtime._G.print or function() end composer.setVariable("pubSubRoomLatency",-1) --[[ implementation -- from gamesparks on __init__ -- We send a packet with our client’s local timestamp to the server. from server -- The server takes this timestamp and adds new data with their own local time to a packet, and sends this back to the original sender. roundTripTime -- The client receives this packet and compares their original sent time to their current time to get the round-trip time. clientLatency -- Half the round-trip calculates the latency. serverDelta -- Subtract the server-time from the client’s local time to get the difference between server’s time and client’s time (that is: serverDelta). trueTime -- We can then use the serverDelta plus the latency to find and adjust any time coming from the server to what it is when we received it, therefore syncing all clients to the same time. ]] local console = { log = print} local function hasSessionId(self) return type(self._sessionId) == 'string' and (#self._sessionId > 10) --and has at least 10 chars in there. end local function disconnect(self, disconnectType, cb) disconnectType = disconnectType or 'unknown' cb = cb or function() end if self.sock then self.sock:close() end self.sock = nil self.buffer = '' self.startConnection = nil if(disconnectType) then local room = "Server" if( disconnectType == "closed" and composer.getVariable('playerIdleTime') and composer.getVariable('playerIdleTime') > 0 and not composer.getVariable('isGameIdle')) then room = nil end end self.paused = true self.state = "init" cb(nil, true) end local function connect(self, params, cb) params = params or {} local instance = self local hadSocket = false if(not params.forced and instance.state ~= "init" and instance.state == "connecting") then cb('SOCKET INVALID STATE'); return false end --disconnect any existing sockets and then connect if(instance.sock) then hadSocket = true instance:disconnect('init', function() connect(self, params,cb) end) instance = nil return false end instance.paused = false local connectStatus = socket.protect(function() local serverIP = instance.server local serverPort = instance.port local isValid = true local token instance.state = "connecting" instance.startConnection = system.getTimer() cb(nil, {status="CONNECTING", message="Preparing..", timeout=5000}) -- connect somewhere local client = socket.try(socket.tcp()) --todo: this may need to be adjusted depending on how much lag could be caused on reconnection. socket.try(client:settimeout(10000,'t')) --set to 4000 miliseconds for overall timeout (t) socket.try(client:settimeout(100,'b')) --set to 100 miliseconds for blocking timeout (b) -- create a try function that closes 'client' on error local try = socket.newtry(function(err) client:close() if(instance) then instance:disconnect('reconnect') end isValid = false cb('CONNECT FAIL') end) try(client:connect(serverIP, serverPort)) try(client:setoption('tcp-nodelay', true)) try(client:setoption('keepalive', true)) try(client:setoption('reuseaddr', true)) try(client:settimeout(0,'b')) local _, output = try(socket.select(nil,{ client }, 4)) instance.needHandshake = true --handshake it --v1, theres no way to verify the init was recieved, processed, and sent back for i,v in _ipairs(output) do --set delay to 0 to not be blocking anymore. --add client timestamp params.clientTime = socket.gettime() --set token to verify authenticity token = jwt.encode(params, 'lasjdflkasdfjkasdjfl') --TODO: use user id or user auth for first init params.jwt = token print('token is', token) cb(nil, {status="CONNECTED", message="Sending..", timeout=5000}) self._callbacks[token] = cb try(v:send("__INIT__"..json.encode(params).."__ENDINIT__")); end instance.sock = client return isValid end) local status = connectStatus() status = _type(status) == "boolean" and status or false return status end local function publish(self, message, cb, attempts) local token, send_result, send_resp, num_bytes cb = cb or function() end attempts = attempts and attempts or 0 if(not hasSessionId(self)) then cb('NO SESSION'); return false end if(attempts > 0) then print('[RETRY ATTEMPT] #', attempts) end --print attempt number if(attempts >= 5) then cb('MAX ATTEMPTS FAILURE'); return false end --check max attempts if (not self.sock) then cb('SOCKET DISCONNECTED'); return false end --check socket exists if(not message.sessionId) then message.sessionId = self._sessionId end --add current sessionId if not passed in if(message.params) then message.params.clientTime = socket.gettime() end --add client time to sync if has 'params' field token = jwt.encode(message, message.sessionId) --set token to verify authenticity print('token publish is', token, 'for publish', message) message.jwt = token self._callbacks[token] = cb --use token to also figure out the callback to call when server sends a response back send_result, send_resp, num_bytes = self.sock:send("__JSON__START__"..json.encode(message).."__JSON__END__") --send message if(not send_result or send_result == 0) then print("Server publish error: "..message..' sent '..num_bytes..' bytes') return publish(self,message,cb, attempts+1) --retry end return send_result and send_result > 0 end local function destroy(self) self:disconnect('destroyed') if(self.responseHandler) then timer.cancel(self.responseHandler) self.responseHandler = nil end self = nil end local function clientError(error) return { } end local receiving = false local function enterFrame(self, event) if(composer.getVariable("isExiting") or receiving) then return end if(self and self.paused) then return end --check for init timeout if(self.state == "connecting" and (self.startConnection and (system.getTimer() - self.startConnection) > 320000)) then print('TIMED OUT WHILE CONNECTING') self.state = 'fail' Runtime:dispatchEvent({name = "rawServerResponse", phase = "error", response = { error = "Problem with connecting to server" }}) if(self.callback) then self.callback({ error = "Problem with connecting to server"}) end receiving = false self:disconnect('timeout') return end receiving = true local input,output = socket.select({ self.sock },nil, 0) -- this is a way not to block runtime while reading socket. zero timeout does the trick for i,v in _ipairs(input) do local got_something_new = false while true do local skt, e, p = v:receive() if (skt) then self.buffer = self.buffer .. skt; got_something_new=true; end if (p) then self.buffer = self.buffer .. p; got_something_new=true; end if (not skt or e) then if(e and e == "closed") then self:disconnect('closed') end break end end -- /while-do -- now, checking if a message is present in buffer... while got_something_new do -- this is for a case of several messages stocker in the buffer local start = string.find(self.buffer,'__JSON__START__') local finish = string.find(self.buffer,'__JSON__END__') if (start and finish) then -- found a message! local message = string.sub(self.buffer, start+15, finish-1) self.buffer = string.sub(self.buffer, 1, start-1) .. string.sub(self.buffer, finish + 13 ) -- cutting our message from buffer local data = json.decode(message) if(data) then local req = data.req local jwt = data.jwt local room = data.room local phase = data.phase local serverTime = data.serverTime and tonumber(data.serverTime) or false local response = data.response local clientTime = (response and response.clientTime) and tonumber(response.clientTime) or false if(not serverTime) then if(clientVersion > 1) then print('WARNING: invalid server time') end serverTime = -1 end --account for serverDelta and latency if(clientTime) then --update the latency and serverDelta print('response update latency serverDelta') print('response.clienttime', socket.gettime(), response.clientTime, socket.gettime()-response.clientTime) self.roundTripTime = socket.gettime() - response.clientTime self.latency = self.roundTripTime*.5 --half rtt is the latency --convert time to seconds from server (miliseconds) self.serverDelta = socket.gettime() - serverTime composer.setVariable('serverDelta', self.serverDelta) composer.setVariable('latency', self.latency) composer.setVariable("pubSubRoomLatency", _mathceil(self.latency * 1000)) print('latency', self.latency) print('serverDelta', self.serverDelta) print('roundTripTime', self.roundTripTime) end local adjustedTime = serverTime + self.serverDelta + self.latency if(adjustedTime > socket.gettime()) then --possible out of sync print('adjustedTime', adjustedTime) print('serverTime', serverTime) print('socketTime', socket.gettime()) end if(phase and phase == 'init') then print(data) self.state = "connected" self._sessionId = response.sessionId end self.state = (phase and phase == "init") and "connected" or self.state local serverMsg = { name = self.eventName, room = room, phase = phase, rawTime = adjustedTime, time = _mathfloor(adjustedTime), response = response } if(req and self._callbacks[req]) then if(data.error) then self._callbacks[req](data.error, serverMsg) else self._callbacks[req](nil, serverMsg) end self._callbacks[req] = nil end self.callback(data) end self.callback({error = 'no message'}) else break end end -- /while-do end -- / for-do receiving = false end -- /enterFrame local function checkIfActive(self, timeout) local instance = self local input, output = socket.select(nil,{ instance.sock }, 0.5) return input,output end local Server = { new = function(params) -- constructor method params = params or {} if (not params.server or not params.port) then print("Server requires server and port to be specified"); return false end local instance = {} instance.needHandshake = false instance.state = "init" instance.buffer = '' instance.server = params.server instance.port = params.port instance.latency = 0 instance.roundTripTime = 0 instance.serverDelta = 0 instance.eventName = params.eventName or "rawServerResponse" instance._callbacks = {} instance.callback = params.callback instance.enterFrame = enterFrame instance.connect = connect instance.publish = publish instance.destroy = destroy instance.disconnect = disconnect instance.checkIfActive = checkIfActive local onResponse = function(event) if(not instance or not instance.enterFrame) then event.source = nil end instance:enterFrame(event) end instance.responseHandler = timer.performWithDelay(5,onResponse,-1) return instance end -- /new } return Server
--Pre-made areas --Waves AREA_SHORTWAVE3 = { {1, 1, 1}, {1, 1, 1}, {0, 3, 0} } AREA_WAVE4 = { {1, 1, 1, 1, 1}, {0, 1, 1, 1, 0}, {0, 1, 1, 1, 0}, {0, 0, 3, 0, 0} } AREA_WAVE6 = { {0, 0, 0, 0, 0}, {0, 1, 3, 1, 0}, {0, 0, 0, 0, 0} } AREA_SQUAREWAVE5 = { {1, 1, 1}, {1, 1, 1}, {1, 1, 1}, {0, 1, 0}, {0, 3, 0} } AREA_SQUAREWAVE6 = { {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0} } AREA_SQUAREWAVE7 = { {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0} } --Diagonal waves AREADIAGONAL_WAVE4 = { {0, 0, 0, 0, 1, 0}, {0, 0, 0, 1, 1, 0}, {0, 0, 1, 1, 1, 0}, {0, 1, 1, 1, 1, 0}, {1, 1, 1, 1, 1, 0}, {0, 0, 0, 0, 0, 3} } AREADIAGONAL_SQUAREWAVE5 = { {1, 1, 1, 0, 0}, {1, 1, 1, 0, 0}, {1, 1, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 3} } AREADIAGONAL_WAVE6 = { {0, 0, 1}, {0, 3, 0}, {1, 0, 0} } --Beams AREA_BEAM1 = { {3} } AREA_BEAM5 = { {1}, {1}, {1}, {1}, {3} } AREA_BEAM7 = { {1}, {1}, {1}, {1}, {1}, {1}, {3} } AREA_BEAM8 = { {1}, {1}, {1}, {1}, {1}, {1}, {1}, {3} } --Diagonal Beams AREADIAGONAL_BEAM5 = { {1, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 1, 0, 0}, {0, 0, 0, 1, 0}, {0, 0, 0, 0, 3} } AREADIAGONAL_BEAM7 = { {1, 0, 0, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0}, {0, 0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 0, 0, 3} } --Circles AREA_CIRCLE2X2 = { {0, 1, 1, 1, 0}, {1, 1, 1, 1, 1}, {1, 1, 3, 1, 1}, {1, 1, 1, 1, 1}, {0, 1, 1, 1, 0} } AREA_CIRCLE3X3 = { {0, 0, 1, 1, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 0}, {1, 1, 1, 1, 1, 1, 1}, {1, 1, 1, 3, 1, 1, 1}, {1, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 0}, {0, 0, 1, 1, 1, 0, 0} } -- Crosses AREA_CROSS1X1 = { {0, 1, 0}, {1, 3, 1}, {0, 1, 0} } AREA_CROSS5X5 = { {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0} } AREA_CROSS6X6 = { {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1}, {0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0}, {0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0}, {0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 1, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0} } --Squares AREA_SQUARE1X1 = { {1, 1, 1}, {1, 3, 1}, {1, 1, 1} } -- Walls AREA_WALLFIELD = { {1, 1, 3, 1, 1} } AREADIAGONAL_WALLFIELD = { {0, 0, 0, 0, 1}, {0, 0, 0, 1, 1}, {0, 1, 3, 1, 0}, {1, 1, 0, 0, 0}, {1, 0, 0, 0, 0}, } -- Spells-only arrays --This HUGE array contains all corpses of the game, until protocol 8.0 -- It is used on animate dead rune and on undead legion spell. No unmoveable corpses are there. CORPSES = { 2806,2807,2808,2809,2810,2811,2812,2813,2814,2815,2816,2817,2818,2819,2820,2821,2822,2823, 2824,2825,2826,2827,2828,2829,2830,2831,2832,2833,2834,2835,2836,2837,2838,2839,2840,2841, 2842,2843,2844,2845,2846,2847,2848,2849,2850,2851,2852,2853,2854,2855,2856,2857,2858,2859, 2879,2880,2881,2882,2883,2884,2885,2886,2887,2888,2889,2890,2891,2892,2893,2894,2895,2896, 2897,2898,2899,2900,2901,2902,2903,2904,2905,2906,2907,2908,2909,2910,2911,2912,2913,2914, 2915,2916,2917,2918,2919,2920,2921,2922,2923,2924,2925,2926,2927,2928,2929,2930,2931,2932, 2933,2934,2935,2936,2937,2938,2939,2940,2941,2942,2943,2944,2945,2946,2947,2948,2949,2950, 2951,2952,2953,2954,2955,2956,2957,2958,2959,2960,2961,2962,2963,2964,2965,2966,2967,2968, 2969,2970,2971,2972,2973,2974,2975,2976,2977,2978,2979,2980,2981,2982,2983,2984,2985,2986, 2987,2988,2989,2990,2991,2992,2993,2994,2995,2996,2997,2998,2999,3000,3001,3002,3003,3004, 3005,3006,3007,3008,3009,3010,3011,3012,3013,3014,3015,3016,3017,3018,3019,3020,3021,3022, 3023,3024,3025,3026,3027,3028,3029,3030,3031,3032,3033,3034,3035,3036,3037,3038,3039,3040, 3041,3042,3043,3044,3045,3046,3047,3048,3049,3050,3051,3052,3053,3054,3055,3056,3057,3058, 3059,3060,3061,3062,3063,3064,3065,3066,3067,3068,3069,3070,3071,3072,3073,3074,3075,3076, 3077,3078,3079,3080,3081,3082,3083,3084,3085,3086,3087,3088,3089,3090,3091,3092,3093,3094, 3095,3096,3097,3098,3099,3100,3101,3102,3103,3104,3105,3106,3107,3108,3109,3110,3111,3112, 3113,3114,3115,3116,3117,3118,3119,3120,3121,3128,3129,3130,3131,3132,3133,3134,4252,4253, 4254,4255,4256,4257,4258,4259,4260,4261,4262,4263,4264,4265,4266,4267,4268,4269,4270,4271, 4272,4273,4274,4275,4276,4277,4278,4279,4280,4281,4282,4283,4284,4285,4286,4287,4288,4289, 4290,4291,4292,4293,4294,4295,4296,4297,4298,4299,4300,4301,4302,4303,4304,4305,4306,4307, 4308,4309,4310,4311,4312,4313,4314,4315,4316,4317,4318,4319,4320,4321,4322,4323,4324,4325, 4326,4327,5522,5523,5524,5525,5526,5527,5528,5529,5530,5531,5532,5533,5534,5535,5536,5537, 5538,5540,5541,5542,5565,5566,5567,5568,5625,5626,5627,5628,5629,5630,5666,5667,5668,5688, 5689,5690,5727,5728,5729,5762,5765,5766,5767,5931,5932,5933,5934,5935,5936,5965,6022,6082, 6083,6084,6303,6304,6305,6307,6308,6309,6310,6313,6314,6315,6317,6318,6319,6321,6322,6323, 6325,6326,6327,6328,6329,6330,6333,6334,6335,6337,6338,6339,6341,6342,6343,6345,6346,6347, 6349,6350,6351,6355,6365,6366,6367,6520,6521,6522,6560,7092,7093,7094,7256,7257,7258,7283, 7284,7285,7317,7318,7319,7321,7322,7323,7325,7326,7328,7329,7331,7332,7333,7335,7336,7337, 7339,7340,7341,7345,7346,7347,7623,7624,7625,7626,7627,7629,7630,7631,7638,7639,7640,7741, 7742,7743,7848,7849,7908,7927,7928,7929,7931,7970,7971,8272} -- This array contains all destroyable field items FIELDS = {1487,1488,1489,1490,1491,1492,1493,1494,1495,1496,1500,1501,1502,1503,1504}
--------------------------------------------------------------------------------------------------- -- func: getmobaction -- desc: Prints mob's current action to the command user. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "i" } function error(player, msg) player:PrintToPlayer(msg) player:PrintToPlayer("!getmobaction {mobID}") end function onTrigger(player, mobId) -- validate mobid local targ if (mobId == nil) then targ = player:getCursorTarget() if (not targ:isMob()) then error(player, "You must either provide a mobID or target a mob with your cursor.") return end else targ = GetMobByID(mobId) if (targ == nil) then error(player, "Invalid mobID.") return end end -- report mob action player:PrintToPlayer(string.format("%s %i current action ID is %i.", targ:getName(), targ:getID(), targ:getCurrentAction())) end
-- Generated By protoc-gen-lua Do not Edit local protobuf = require "protobuf" module('BceUserRoleList_pb', package.seeall) local BCEUSERROLELIST = protobuf.Descriptor(); local BCEUSERROLELIST_SERVERID_FIELD = protobuf.FieldDescriptor(); BCEUSERROLELIST_SERVERID_FIELD.name = "serverid" BCEUSERROLELIST_SERVERID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BceUserRoleList.serverid" BCEUSERROLELIST_SERVERID_FIELD.number = 1 BCEUSERROLELIST_SERVERID_FIELD.index = 0 BCEUSERROLELIST_SERVERID_FIELD.label = 1 BCEUSERROLELIST_SERVERID_FIELD.has_default_value = false BCEUSERROLELIST_SERVERID_FIELD.default_value = "" BCEUSERROLELIST_SERVERID_FIELD.type = 9 BCEUSERROLELIST_SERVERID_FIELD.cpp_type = 9 BCEUSERROLELIST.name = "BceUserRoleList" BCEUSERROLELIST.full_name = ".com.xinqihd.sns.gameserver.proto.BceUserRoleList" BCEUSERROLELIST.nested_types = {} BCEUSERROLELIST.enum_types = {} BCEUSERROLELIST.fields = {BCEUSERROLELIST_SERVERID_FIELD} BCEUSERROLELIST.is_extendable = false BCEUSERROLELIST.extensions = {} BceUserRoleList = protobuf.Message(BCEUSERROLELIST) _G.BCEUSERROLELIST_PB_BCEUSERROLELIST = BCEUSERROLELIST
-- Copyright (C) Izio, Inc - All Rights Reserved -- Unauthorized copying of this file, via any medium is strictly prohibited -- Proprietary and confidential -- Written by Romain Billot <romainbillot3009@gmail.com>, Jully 2017 local Records = {} RegisterServerEvent("print:serverArray") RegisterServerEvent("police:armurerieToServer") RegisterServerEvent("police:retrieveArmurerieToServer") RegisterServerEvent("police:refreshService") AddEventHandler("onMySQLReady", function() TriggerEvent("iCops:startLoading") end) AddEventHandler("iCops:loadingAfterRestart", function() TriggerEvent("iCops:startLoading") end) AddEventHandler("iCops:startLoading", function() local result = MySQL.Sync.fetchAll("SELECT * FROM records WHERE access=@j1 or access=@j2",{ ["@j1"] = "LSPD", ["@j2"] = "LSSD" }) for i=1, #result do table.insert(Records, { creator = result[i].creator, access = result[i].access, infos = json.decode(result[i].infos), new = false, id = result[i].id, note = json.decode(result[i].note) }) end end) AddEventHandler("print:serverArray", function(toPrint) print(json.encode(toPrint)) end) AddEventHandler("police:refreshService", function(isInService) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) user.setSessionVar("isInService", isInService) end) end) AddEventHandler("police:armurerieToServer", function(result) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) local treatWeapons = {} local treatQuantity = {} local treatWaitingWeapons = {} local allItemInfos = user.get('item') local allWeapon = allItemInfos.weapons local inventory = user.get('inventory') for i = 1, #inventory do for j = 1 , #allWeapon do if inventory[i].id == allWeapon[j].id then if inventory[i].quantity > 0 then table.insert(treatWeapons, inventory[i].id) table.insert(treatQuantity, inventory[i].quantity) end end end end if #treatQuantity ~= 0 then user.removeQuantityArray(treatWeapons, treatQuantity) user.refreshInventory() for i = 1, #treatWeapons do table.insert(treatWaitingWeapons,{ quantity = treatQuantity[i], id = treatWeapons[i] }) end MySQL.Async.execute("UPDATE users SET `waitingWeapons`=@weapons WHERE `identifier`=@identifier AND `id`=@id", { ['@identifier'] = user.get('identifier'), ['@id'] = user.get('id'), ['@weapons'] = json.encode(treatWaitingWeapons) }) user.notify("Bon ".. user.get('displayName') .. " tu connais la procédure, je prend tes armes personnelles, je te donnes des armes de service et tu viens les reprendre après avoir quitté ton service.", "success", "topCenter", true, 5000) else user.notify("Tiens tes armes de service.. et euh, je suppose que tu n'as pas d'armes personnelles sur toi " .. user.get('displayName').. '?', "success", "topCenter", true, 5000) end TriggerClientEvent("icops:giveServiceWeapons", source, result) end) end) AddEventHandler("police:retrieveArmurerieToServer", function() local source = source TriggerEvent("es:getPlayerFromId", source, function(user) local result = MySQL.Sync.fetchAll("SELECT * FROM users WHERE `identifier`=@identifier AND `id`=@id", { ["@identifier"] = user.get('identifier'), ["@id"] = user.get('id') }) print(json.encode(result)) if result[1].waitingWeapons ~= nil then -- il a des armes en attente local nulled = 0 local waitingWeapons = json.decode(result[1].waitingWeapons) for i = 1, #waitingWeapons do if waitingWeapons[i].quantity < 1 then nulled = nulled + 1 end end if nulled == #waitingWeapons then user.notify("Contacter izio, nulled waitingWeapons l.72 iCops_server.lua", "warning", "topCenter", true, 20000) else user.notify("Je te rend tes armes comme prévu " .. user.get('displayName').. ".", "success", "topCenter", true, 5000) for i = 1, #waitingWeapons do user.addQuantity(waitingWeapons[i].id, waitingWeapons[i].quantity) end user.refreshInventory() MySQL.Async.execute("UPDATE users SET `waitingWeapons`=@weapons WHERE `identifier`=@identifier AND `id`=@id", { ['@identifier'] = user.get('identifier'), ['@id'] = user.get('id'), ['@weapons'] = nil }) TriggerClientEvent("police:returnFromServerRetreiving", user.get('source')) end else user.notify("Oh attend... Je ne trouve pas tes armes, t'es sur d'en avoir déposé " .. user.get('displayName') .. "?", "error", "topCenter", true, 5000) end end) end) AddEventHandler("es:playerLoaded", function(source) TriggerEvent("es:getPlayerFromId", source, function(user) if user.get('waitingWeapons') ~= nil and (user.get('job') == "lspd" or user.get('job') == "lssd")then local weapons = user.get('waitingWeapons') for i = 1, #weapons do user.addQuantity(weapons[i].id, weapons[i].quantity) end MySQL.Async.execute("UPDATE users SET `waitingWeapons`=@weapons WHERE `identifier`=@identifier AND `id`=@id", { ['@identifier'] = user.get('identifier'), ['@id'] = user.get('id'), ['@weapons'] = nil }) end end) end) -- Garage : RegisterServerEvent("police:spawnVehGarage") AddEventHandler("police:spawnVehGarage", function(carPrice) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("ijob:getJobFromName", user.get('job'), function(policeJob) if not(user.getSessionVar('caution', carPrice)) then print(carPrice) policeJob.removeCapital(carPrice) policeJob.addLost(user, carPrice, "prise de véhicule de fonction.") user.setSessionVar('caution', carPrice) user.notify("La police te prete un véhicule. Si tu ne le ramène pas, ils te demandront de payer la moitié du prix de la voiture. Prends en soin!", "error", "topCenter", true, 5000) end end) end) end) RegisterServerEvent("police:retreiveCaution") AddEventHandler("police:retreiveCaution", function(carPrice) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("ijob:getJobFromName", user.get('job'), function(policeJob) policeJob.addCapital(user.getSessionVar('caution')) policeJob.addBenefit(user, user.getSessionVar('caution'), "Ajout du véhicule au garage.") user.setSessionVar("caution", nil) user.notify("Tu viens de ramener le véhicule au garage.", "success", "topCenter", true, 5000) end) end) end) AddEventHandler("is:playerDropped", function(user) if user.get('job') == "lspd" or user.get('job') == "lssd" then if user.getSessionVar("caution") ~= nil then user.removeBank(user.getSessionVar("caution")/2) end end end) -- Fonctions du menu policier : -- Partie checkID RegisterServerEvent("police:checkId") AddEventHandler("police:checkId", function(psid) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) if targetUser~=nil then if targetUser.getSessionVar("cuffed") == true then targetUser.notify("Un agent de police est en train de regarder ton identitié, tu ne peux pas réagir, tu es menotté.", "error", "topCenter", true, 5000) user.notify("Tu es en train de regarder la carte d'identité d'une personne. </br> <ul> <li><strong>Nom: </strong>".. targetUser.get('lastName') ..".</li> <li> <strong>Prénom: </strong>".. targetUser.get('firstName') .." </li> <li><strong>Age: </strong>".. targetUser.get('age') .. " </li> <li><strong>Matricule: </strong>".. "TODO" .." </li> </ul>", "success", "topCenter", true, 10000) else user.notify("Le citoyen n'est pas menotté, tu viens de lui demandé de te montrer sa carte d'identité", "error", "topCenter", true, 10000) targetUser.notify("Un agent de police vient de te demander ta carte d'identité. Aide: Appuies sur Y pour lui donner et sur T pour refuser de lui donner.", "success", "topCenter", true, 5000) TriggerClientEvent("police:checkId", psid, source) end else user.notify("Contacter Izio iCops_server can't retreive PSID", "error", "topCenter", true, 5000) end end) end) end) RegisterServerEvent("police:accptedToGiveCard") AddEventHandler("police:accptedToGiveCard", function(officerPsid) local source = source TriggerEvent("es:getPlayerFromId", officerPsid, function(officerUser) TriggerEvent("es:getPlayerFromId", source, function(user) officerUser.notify("Tu es en train de regarder la carte d'identité d'une personne. </br> <ul> <li><strong>Nom: </strong>".. user.get('lastName') ..".</li> <li> <strong>Prénom: </strong>".. user.get('firstName') .." </li> <li><strong>Age: </strong>".. user.get('age') .. " </li> <li><strong>Matricule: </strong>".. "TODO" .." </li> </ul>", "success", "topCenter", true, 10000) end) end) end) RegisterServerEvent("police:refusedToGiveCard") AddEventHandler("police:refusedToGiveCard", function(officerPsid) local source = source TriggerEvent("es:getPlayerFromId", officerPsid, function(officerUser) officerUser.notify("Le citoyen vient de refuser de te montrer sa carte d'identité.", "error", "topCenter", true, 10000) end) end) -- Partie Check Inv RegisterServerEvent("police:targetCheckInventory") AddEventHandler("police:targetCheckInventory", function(psid) local source = source -- FxServer TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) -- if targetUser~=nil then if targetUser.getSessionVar("cuffed") == true then targetUser.notify("Un agent de police est en train de regarder ton inventaire, tu ne peux pas réagir, tu es menotté.", "error", "topCenter", true, 5000) local message = GetInventoryMessage(targetUser) user.notify("Tu es en train de regarder l'inventaire d'une personne. </br>" .. message, "success", "topCenter", true, 15000) else user.notify("Le citoyen n'est pas menotté, tu viens de lui demandé de te montrer ses poches.", "error", "topCenter", true, 10000) targetUser.notify("Un agent de police vient de te demander de fouiller tes poches. </br> Aide: Appuies sur Y pour lui donner. </br>Appuies sur T pour refuser de lui donner.", "success", "topCenter", true, 5000) TriggerClientEvent("police:checkInventory", psid, source) end else user.notify("Contacter Izio iCops_server can't retreive PSID", "error", "topCenter", true, 5000) end end) end) end) RegisterServerEvent("police:refusedToShowPoached") AddEventHandler("police:refusedToShowPoached", function(officerPsid) local source = source TriggerEvent("es:getPlayerFromId", officerPsid, function(officerUser) officerUser.notify("Le citoyen vient de refuser de te montrer ses poches.", "error", "topCenter", true, 10000) end) end) RegisterServerEvent("police:acceptedToShowPoached") AddEventHandler("police:acceptedToShowPoached", function(officerPsid) local source = source TriggerEvent("es:getPlayerFromId", officerPsid, function(officerUser) TriggerEvent("es:getPlayerFromId", source, function(user) local message = GetInventoryMessage(user) officerUser.notify("Tu es en train de regarder l'inventaire d'une personne. </br>" .. message, "success", "topCenter", true, 15000) end) end) end) function GetInventoryMessage(user) -- local allItem = user.get('item') local userInventory = user.get('inventory') local message = "<ul>" for i=1, #userInventory do message = message .. "<li><strong> " .. userInventory[i].quantity .. " " .. allItem[userInventory[i].id].name .. "</strong></li>" end return message .. "</ul>" end -- Partie cuff RegisterServerEvent("police:cuffPlayer") AddEventHandler("police:cuffPlayer", function(psid) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) if targetUser~=nil then if targetUser.getSessionVar("cuffed") == true then TriggerClientEvent("police:coffPlayerReturnFromServer", psid, false) targetUser.setSessionVar("cuffed", false) user.notify("Tu viens de démenotter la personne devant toi.", "success", "topCenter", true, 5000) targetUser.notify("Tu viens d'etre démenotter par un agent de police.", "success", "topCenter", true, 5000) else TriggerClientEvent("police:coffPlayerReturnFromServer", psid, true) targetUser.setSessionVar("cuffed", true) user.notify("Tu viens de menotter la personne devant toi.", "success", "topCenter", true, 5000) targetUser.notify("Tu viens d'etre menotter par un agent de police.", "success", "topCenter", true, 5000) end else user.notify("Contacter Izio iCops_server can't retreive PSID", "error", "topCenter", true, 5000) end end) end) end) -- Partie Getout / put into veh: RegisterServerEvent("police:setPlayerIntoVeh") -- TODO, vérifier que le véhicule soit un véhicule de police (plate : PO) AddEventHandler("police:setPlayerIntoVeh", function(psid) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) user.notify("Tu as forcé le citoyen à rentrer dans ton véhicule", "success", "topCenter", true, 5000) targetUser.notify("Un agent de police vient de vous forcer à rentrer dans le véhicule", "success", "topCenter", true, 5000) TriggerClientEvent("police:forcedEnteringVeh", psid) end) end) end) RegisterServerEvent("police:unSetPlayerIntoVeh") -- TODO, vérifier que le véhicule soit un véhicule de police (plate : PO) AddEventHandler("police:unSetPlayerIntoVeh", function(psid) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) user.notify("Tu as forcé le citoyen à sortir de ton véhicule", "success", "topCenter", true, 5000) targetUser.notify("Un agent de police vient de vous forcer à sortir du le véhicule", "success", "topCenter", true, 5000) TriggerClientEvent("police:forcedLeavingVeh", psid) end) end) end) --Partie Fines : RegisterServerEvent("police:setFineToPlayer") AddEventHandler("police:setFineToPlayer", function(psid, amount) local amount = math.abs(amount) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) user.notify("Tu viens de mettre un amande à un citoyen d'un montant de " .. amount .. '$.', "success", "topCenter", true, 5000) targetUser.notify("Un agent de police vient de vous mettre une amande d'un montant de ".. amount .. '$.', "success", "topCenter", true, 5000) targetUser.removeBank(amount) TriggerEvent("ijob:getJobFromName", user.get('job'),function(police) police.addCapital(amount) police.addBenefit(user, amount, "Amende sur un citoyen.") end) end) end) end) -- Partie DragPlayer: RegisterServerEvent("police:dragRequest") AddEventHandler("police:dragRequest", function(psid, isDragged) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) TriggerEvent("es:getPlayerFromId", psid, function(targetUser) if targetUser.getSessionVar("cuffed") == true then if not(isDragged) then user.notify("Tu escortes le citoyen.", "success", "topCenter", true, 5000) targetUser.notify("Un agent de police est en train de t'escorter.", "success", "topCenter", true, 5000) TriggerClientEvent("police:dragAnswer", psid, source) else user.notify("Tu laches le citoyen.", "success", "topCenter", true, 5000) targetUser.notify("Un agent de police vient de vous lacher.", "success", "topCenter", true, 5000) TriggerClientEvent("police:dragAnswer", psid, source) end else user.notify("Le citoyen concerné n'est pas menotté.", "success", "topCenter", true, 5000) targetUser.notify("Un agent de police à essayé de t'escorter, mais tu n'étais pas menotté.", "success", "topCenter", true, 5000) end end) end) end) ----------Partie UI: RegisterServerEvent("iCops:registerNewCar") AddEventHandler("iCops:registerNewCar", function(data) local source = source local nowTime = os.time() data.type = "vehicle" data.time = nowTime TriggerEvent("es:getPlayerFromId", source, function(user) for i = 1, #Records do if data.matricule == Records[i].infos.matricule and user.get('job') == Records[i].access and Records[i].infos.type == data.type then user.notify("Il y a déjà un casier de crée pour cette voiture", "error", "topCenter", true, 5000) return end end table.insert(Records, { creator = user.get('identifier'), access = user.get('job'), infos = data, new = true, id = #Records + 1, note = {} }) user.notify("Tu viens d'enregistrer un véhicule.", "success", "topCenter", true, 5000) end) -- carManufacturer -- carModel -- carColor -- carDate -- carPlate -- carOwner -- carAdress -- carOthers end) RegisterServerEvent("iCops:registerNewCitizen") AddEventHandler("iCops:registerNewCitizen", function(data) local source = source local nowTime = os.time() data.type = "citizen" data.time = nowTime TriggerEvent("es:getPlayerFromId", source, function(user) for i = 1, #Records do print(data.matricule) print(Records[i].infos.matricule) if data.matricule == Records[i].infos.matricule and user.get('job') == Records[i].access and Records[i].infos.type == data.type then user.notify("Il y a déjà un casier de crée pour ce citoyen", "error", "topCenter", true, 5000) return end end table.insert(Records, { creator = user.get('identifier'), access = user.get('job'), infos = data, new = true, id = #Records + 1, note = {} }) user.notify("Tu viens d'ajouter un nouveau casier.", "success", "topCenter", true, 5000) end) -- lastname -- firstname -- age -- adress -- phoneNumber -- permis -- criminalRecord end) RegisterServerEvent("iCops:askForCitizenSearch") AddEventHandler("iCops:askForCitizenSearch", function(data) local source = source local returnedResult = {} TriggerEvent("es:getPlayerFromId", source, function(user) for k,v in pairs(Records) do if v.infos.matricule == data.matricule and v.infos.type == "citizen" and user.get('job') == v.access then table.insert(returnedResult, v) end end end) if #returnedResult == 0 then returnedResult = nil end TriggerClientEvent("iCops:returnCitizenSearch", source, returnedResult[1]) end) RegisterServerEvent("iCops:askForCarSearch") AddEventHandler("iCops:askForCarSearch", function(data) local source = source local returnedResult = {} TriggerEvent("es:getPlayerFromId", source, function(user) for k,v in pairs(Records) do if v.infos.plate == data.plate and v.infos.type == "vehicle" and user.get('job') == v.access then table.insert(returnedResult, v) end end end) if #returnedResult == 0 then returnedResult = nil else returnedResult = returnedResult[1] end print(json.encode(returnedResult)) TriggerClientEvent("iCops:returnCarSearch", source, returnedResult) end) RegisterServerEvent("iCops:addNoteToCitizen") AddEventHandler("iCops:addNoteToCitizen", function(data) local source = source TriggerEvent("es:getPlayerFromId", source, function(user) for i = 1, #Records do print(data.id) print(Records[i].id) if Records[i].id == data.id then table.insert(Records[i].note, {text = data.data, creator = user.get('displayName'), time = os.time()}) Records[i].haveChanged = true user.notify("Tu viens d'ajouter une note au casier.", "success", "topCenter", true, 5000) break end end end) end) function SaveRecords() SetTimeout(1000000, function() for k,v in pairs(Records) do if v.new then MySQL.Sync.execute("INSERT INTO records (`creator`, `infos`, `access`, `id`, `note`) VALUES (@creator, @infos, @access, @id, @note)",{ ["@creator"] = v.creator, ["@infos"] = json.encode(v.infos), ["@access"] = v.access, ["@id"] = v.id, ["@note"] = json.encode(v.note) }) v.new = false end end SaveRecords() end) end SaveRecords() function SaveNote() SetTimeout(1000000, function() for k,v in pairs(Records) do if v.haveChanged then MySQL.Sync.execute("UPDATE records SET `note`=@note WHERE id=@id ",{ ["@note"] = json.encode(v.note), ["@id"] = v.id }) v.new = false end end SaveNote() end) end SaveNote()
mlp = nn.Sequential() mlp:add(nn.Convert('bchw', 'bf')) -- collapse 3D to 1D mlp:add(nn.Linear(1*28*28, 200)) mlp:add(nn.Tanh()) mlp:add(nn.Linear(200, 200)) mlp:add(nn.Tanh()) mlp:add(nn.Linear(200, 10)) mlp:add(nn.LogSoftMax()) -- for classification problems
--[[------------------------------------------------ -- Love Frames - A GUI library for LOVE -- -- Copyright (c) 2012-2014 Kenny Shields -- --]]------------------------------------------------ return function(loveframes) ---------- module start ---------- -- panel object local newobject = loveframes.newObject("panel", "loveframes_object_panel", true) --[[--------------------------------------------------------- - func: initialize() - desc: initializes the object --]]--------------------------------------------------------- function newobject:initialize() self.type = "panel" self.width = 200 self.height = 50 self.internal = false self.children = {} self:setDrawFunc() end --[[--------------------------------------------------------- - func: update(deltatime) - desc: updates the element --]]--------------------------------------------------------- function newobject:_update(dt) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local alwaysupdate = self.alwaysupdate if not visible then if not alwaysupdate then return end end local children = self.children local parent = self.parent local base = loveframes.base local update = self.update -- move to parent if there is a parent if parent ~= base and parent.type ~= "list" then self.x = self.parent.x + self.staticx self.y = self.parent.y + self.staticy end self:checkHover() for k, v in ipairs(children) do v:_update(dt) end if update then update(self, dt) end end --[[--------------------------------------------------------- - func: mousepressed(x, y, button) - desc: called when the player presses a mouse button --]]--------------------------------------------------------- function newobject:mousepressed(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible if not visible then return end local children = self.children local hover = self.hover if hover and button == 1 then local baseparent = self:getBaseParent() if baseparent and baseparent.type == "frame" then baseparent:makeTop() end end for k, v in ipairs(children) do v:mousepressed(x, y, button) end end --[[--------------------------------------------------------- - func: mousereleased(x, y, button) - desc: called when the player releases a mouse button --]]--------------------------------------------------------- function newobject:mousereleased(x, y, button) local state = loveframes.state local selfstate = self.state if state ~= selfstate then return end local visible = self.visible local children = self.children if not visible then return end for k, v in ipairs(children) do v:mousereleased(x, y, button) end end ---------- module end ---------- end
--[=====[ script to cycle commands with a keybind, accomplished through script messages available at: https://github.com/CogentRedTester/mpv-scripts syntax: script-message cycle-commands "command1" "command2" "command3" The syntax of each command is identical to the standard input.conf syntax, but each command must be within a pair of double quotes. Commands with mutiword arguments require you to send double quotes just like normal command syntax, however, you will need to escape the quotes with a backslash so that they are sent as part of the string. Semicolons also work exactly like they do normally, so you can easily send multiple commands each cycle. Here is an example of a standard input.conf entry: script-message cycle-commands "show-text one 1000 ; print-text two" "show-text \"three four\"" This would, on keypress one, print 'one' to the OSD for 1 second and 'two' to the console, and on keypress two 'three four' would be printed to the OSD. Notice how the quotation marks around 'three four' are escaped using backslashes. All other syntax details should be exactly the same as usual input commands. There are no limits to the number of commands, and the script message can be used as often as one wants, the script stores the current iteration for each unique cycle command, so there should be no overlap unless one binds the exact same command string (including spacing) ]=====]-- local mp = require 'mp' local msg = require 'mp.msg' --keeps track of the current position for a specific cycle local iterators = {} --main function to identify and run the cycles local function main(...) local commands = {...} --to identify the specific cycle we'll concatenate all the strings together to use as our table key local str = table.concat(commands, " | ") msg.trace('recieved:', str) if iterators[str] == nil then msg.debug('unknown cycle, creating iterator') iterators[str] = 1 else iterators[str] = iterators[str] + 1 if iterators[str] > #commands then iterators[str] = 1 end end --mp.command should run the commands exactly as if they were entered in input.conf. --This should provide universal support for all input.conf command syntax local cmd = commands[ iterators[str] ] msg.verbose('sending command:', cmd) mp.command(cmd) end mp.register_script_message('cycle-commands', main)
AI = require(PATH_GAME .. "ai") dofile(PATH_CONFIGS .. "animation_config.lua") dofile(PATH_CONFIGS .. "bestiar_config.lua") dofile(PATH_CONFIGS .. "npc_config.lua") dofile(PATH_GAME .. "game_machine.lua") dofile(PATH_GAME .. "hero.lua") dofile(PATH_GAME .. "gui_game_config.lua") dofile(PATH_GAME .. "inventory.lua") dofile(PATH_CONFIGS .. "items_config.lua") dofile(PATH_GAME .. "matricies_mask.lua") dofile(PATH_CONFIGS .. "dialogs_config.lua") dofile(PATH_CONFIGS .. "spells_config.lua") dofile(PATH_CONFIGS .. "palet_config.lua") dofile(PATH_CONFIGS .. "objects_config.lua") IdG = require(PATH_GAME .. "IdGenerator") Item = require(PATH_GAME .. "items") Attack = require(PATH_GAME .. "attack_scripts") HeroDialog = require(PATH_GAME .. "hero_dialog") UserUI = require(PATH_GAME .. "UserUI") Map = require( PATH_GAME .. "map") Character = require(PATH_GAME .. "character") Bar = require(PATH_GAME .. "progress_bar") NPC = require(PATH_GAME .. "npc") Pattern_text = require(PATH_GAME .. "pattern_text") Spells = require(PATH_GAME .. "spells") Client = require(PATH_GAME .. "client") MConstants = require(PATH_GAME .. "multiplayer_constants") Server = require(PATH_GAME .. "server") ServerChars = require(PATH_GAME .. "serverChars") ClientChars = require(PATH_GAME .. "clientChars") _PORT = 5641 local GameStarter = {} function profiler(func, arg) local calls, total, this = {}, {}, {} debug.sethook(function(event) local i = debug.getinfo(2, "Sln") if i.what ~= 'Lua' then return end local func = i.name or (i.source..':'..i.linedefined) if event == 'call' then this[func] = os.clock() else this[func] = this[func] or 0 local time = os.clock() - this[func] total[func] = (total[func] or 0) + time calls[func] = (calls[func] or 0) + 1 end end, "cr") func(arg) debug.sethook() -- print the results for f,time in pairs(total) do print(("Function %s took %.3f seconds after %d calls"):format(f, time, calls[f])) end end local function loading_picture() local sp = GUI.make_sprite(PATH_GUI_IMG .. "loading.png") sp:move(GUI.SCREEN.width/2- sp.bound_box.w/2, GUI.SCREEN.height/2 - sp.bound_box.h/2) local load_txt = GUI.make_element_text((sp.bound_box.x+sp.bound_box.w)/2, (sp.bound_box.y+sp.bound_box.h)/2, 30,"Načítám...",{255,0,0,255}, PATH_FONTS .. "Ubuntu-B.ttf") sp.sprite:set_alpha(100,1) GUI.compose_object(GUI.main_window, sp) GUI.compose_object(sp, load_txt) return sp end --function on_loading_corutine(func,frame,args) --[[ local tmp = {} for k,v in ipairs(GUI.main_window.objects) do tmp[k]=v end local pic = loading_picture() local co = coroutine.create(func(frame,args)) ERPG_window.prepare_renderer() main() ERPG_window.update_renderer() coroutine.resume(co) pic.sprite:set_alpha(200,1) ERPG_window.prepare_renderer() main() ERPG_window.update_renderer() coroutine.resume(co) table.remove(GUI.main_window.objects, 1) GUI.main_window.objects = tmp ]] --end function GameStarter.loading_game(frame,args) return function (userUI) Map.load("result2") -- coroutine.yield() local stats = args.stats local items = args.items local item_tab = {} for k,v in ipairs(items) do item_tab[#item_tab + 1 ] = v.item.name end local conf = { ["experience"] = 0, ["stats"] = { ["strengh"] = stats[1][2], ["dexterity"] = stats[2][2], ["health"] = stats[1][2]*3, ["wisdom"] = stats[3][2], ["mana"] = stats[3][2]*3}, ["level_points"] = stats.level_points, ["items"] = item_tab, ["level"] = 1, ["health"] = stats[1][2]*3, ["mana"] = stats[3][2]*3 } hero = make_hero() hero:setConfiguration(conf) hero:insert(95,242) userUI:connectHero(hero) end end function GameStarter.startServer(frame, args) return function (userUI) local x = ERPG_Network_server.create(_PORT) local gm = get_game_machine() GameStarter.loading_game(frame, args)(userUI) ServerChars.setHero(userUI.connectedHero) gm:setServer(true) end end --[[function print() end]] function GameStarter.connectServer(frame, args) return function (userUI) local x = ERPG_Network.network_connect("localhost",_PORT) print("Connected? ", x) local gm = get_game_machine() if x == nil then ERPG_Network.network_close_connection() return true end gm:setClient(true) GameStarter.loading_game(frame, args)(userUI) local gm = get_game_machine() ERPG_Network.add_data("ahoj") Client.sendHero(hero) --[[local output ="" output = Serialization.serializeToString(hero:dump()) print("huh" .. output) ERPG_Network.add_data("Connect;" .. output .. ";") ERPG_Network.add_data("move;" .. hero:getId() .. ";move_up_right;" )]] -- ERPG_Network.add_data("points;95;242") end end function GameStarter.in_loading_game(frame,path) local gm = get_game_machine() return function (userUI) for k,v in ipairs(gm.callbacks_iter) do if v.type and v.type == "dynamic" then v:destroy_self() end end Map.get_id = get_ids() _HeroObject=nil dofile(PATH_SAVE .. path .. ".sav") Map["name"] = _HeroObject.map_name local w, h = Tiles.load_map( PATH_MAPS .. Map.name .. ".map") --coroutine.yield() MpR.load_map( path , nil, PATH_SAVE) local hero = make_hero(1,1) Tiles.screen_box(0,0) Map.x = 0 Map.y = 0 hero:load(_HeroObject) userUI:connectHero(hero) gm:set_time(_HeroObject.time) Map["size_map"] = {w,h} end end function GameStarter.start(frame, args, loadingFunction, type) local _POSITION = GUI.SCREEN.width - 400 local t_w, t_h = 64,32 local w, h = math.floor((_POSITION)/t_w)*t_w, math.floor((GUI.SCREEN.height-280)/t_h)*t_h _POSITION = w local game_machine = make_game_machine(frame, w, h) local canvas_frame = game_machine:get_canvas_frame() local screen_w,screen_h = game_machine.canvas:get_size() local userUI = UserUI.make(type) userUI:initializeUI(screen_w) game_machine:setUserUI(userUI) local render_map = make_graphic_element(w,h) game_machine:create_layer() game_machine:create_layer() game_machine:create_layer() Map.Initialize_map(render_map) game_machine:set_layer({render_map}, 1) GUI.add_event(frame, "on_wheel", function () end) local function on_input_key(self, press_key) for k, v in ipairs(self.objects) do GUI.send_event(v,"on_input_key", press_key) end end GUI.add_event(frame, "on_input_key", on_input_key) GUI.compose_object(frame, canvas_frame) --on_loading_corutine(loading_game,frame, args) local what = loadingFunction(frame, args)(userUI) if what then GUI.send_event(game_machine:get_main_frame(),"on_resume") return end return function(self) game_machine:refresh_game_mouse(frame) game_machine:apply_callbacks() end end return GameStarter
local Prop = {} Prop.Name = "Arcadia Apartments 2c" Prop.Cat = "Apartments" Prop.Price = 900 Prop.Doors = { Vector( 4069, -68, 502 ), Vector( 4156, -133, 502 ), } GM.Property:Register( Prop )
local Prop = {} Prop.Name = "Subs Market 203" Prop.Cat = "Stores" Prop.Price = 500 Prop.Doors = { Vector( 10628, -12058, -1664.75 ), Vector( 10492, -11586, -1664.75 ), } GM.Property:Register( Prop )
local Surfaces = require('script.surfaces') local Portal = require('script.portal') local portal_spec_example = { type = "entity", -- Types: entity, energy, item type_params = {}, -- Parameters depending on the type, used to add restrictions relative_target = -1, -- Interger, defines how many layers we should shift absolute_target = nil, -- Integer, overrides relatiive_target is defined, target layer from = { prototype = "", -- Prototype of from portal restrictions = { main_surface = nil, -- On which surface should this be placed? Empty for any layer = nil -- On which layer can this be placed? Empty for any (not implemented yet) } }, to = { prototype = "", -- Prototype of portal on other side main_surface = nil, -- To which surface should this point? Empty for same as from clear_radius = 10 -- Radius that should be cleared around the portal in the target dimension -- Defaults to the raduis of the prototype + 1 }, allow_reverse = false -- Can this portal be used in 2 directions? } local portal_example = { type = "entity", type_params = {}, from_entity = {}, to_entity = {}, } local function register_surface(name, main_surface, layers, owner) Surfaces.register_surface(main_surface, layers, owner, name) end local function get_main_surfaces() local result = {} for k, _ in pairs(global.surfaces) do table.insert(result, k) end return result end local function add_main_surface(name) Surfaces.add_main_surface(name) end local function add_replaceable_tiles(tiles) for k, v in pairs(tiles) do global.replaceable_tiles[k] = v end end local function add_replaceable_entities(entities) for k, v in pairs(entities) do global.replaceable_entities[k] = v end end local function register_portal(portal) Portal.register(portal) end local function add_pair(portal_spec, from_entity, to_entity) Portal.add_pair(portal_spec, from_entity, to_entity) end local function setup_interface() remote.add_interface("SurfacesAPI", { register_surface = register_surface, get_main_surfaces = get_main_surfaces, add_main_surface = add_main_surface, add_replaceable_tiles = add_replaceable_tiles, add_replaceable_entities = add_replaceable_entities, register_portal = register_portal, add_pair = add_pair, }) end return setup_interface
data:extend({ { type = 'autoplace-control', name = 'nm-pre-spice-mass-ore', localised_name = {"", "[entity=nm-pre-spice-mass-ore] ", {"entity-name.nm-pre-spice-mass-ore"}}, richness = true, order = 'b-a', category = 'resource' }, { type = 'autoplace-control', name = 'nm-worm-hole', localised_name = {"", "[entity=nm-worm-hole] ", {"entity-name.nm-worm-hole"}}, richness = true, order = 'c-a', category = 'resource' }, })
-- config storage.shovel = 9596 storage.rope = 9596 storage.machete = 9596 storage.scythe = 9596 local useId = {6264, 5282, 20453, 20454, 20474, 11708, 11705, 6257, 6256, 2772, 27260, 2773, 1632, 1633, 1948, 435, 6252, 6253, 5007, 4911, 1629, 1630, 5108, 5107, 5281, 1968, 435, 1948, 5542, 31116, 31120, 30742, 31115, 31118, 20474, 5737, 5736, 5734, 5733, 31202, 31228, 31199, 31200, 33262, 30824, 5125, 5126, 5116, 5117, 8257, 8258, 8255, 8256} local shovelId = {593, 867} local ropeId = {12935, 386, 421, 21966, 14238} local macheteId = {2130, 3696} local scytheId = {3653} setDefaultTab("Tools") -- script hotkey("space", "Use All", function() if not modules.game_walking.wsadWalking then return end for _, tile in pairs(g_map.getTiles(posz())) do if distanceFromPlayer(tile:getPosition()) < 2 then for _, item in pairs(tile:getItems()) do -- use if table.find(useId, item:getId()) then use(item) return elseif table.find(shovelId, item:getId()) then useWith(storage.shovel, item) return elseif table.find(ropeId, item:getId()) then useWith(storage.rope, item) return elseif table.find(macheteId, item:getId()) then useWith(storage.machete, item) return elseif table.find(scytheId, item:getId()) then useWith(storage.scythe, item) return end end end end end)
local Linear, parent = torch.class('nn.Linear', 'nn.Module') function Linear:__init(inputSize, outputSize) parent.__init(self) self.weight = torch.Tensor(outputSize, inputSize) self.bias = torch.Tensor(outputSize) self.gradWeight = torch.Tensor(outputSize, inputSize) self.gradBias = torch.Tensor(outputSize) self:reset() end function Linear:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) self.bias[i] = torch.uniform(-stdv, stdv) end else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end return self end function Linear:updateOutput(input) if input:dim() == 1 then self.output:resize(self.bias:size(1)) self.output:copy(self.bias) self.output:addmv(1, self.weight, input) elseif input:dim() == 2 then local nframe = input:size(1) local nElement = self.output:nElement() self.output:resize(nframe, self.bias:size(1)) if self.output:nElement() ~= nElement then self.output:zero() end if not self.addBuffer or self.addBuffer:nElement() ~= nframe then self.addBuffer = input.new(nframe):fill(1) end self.output:addmm(0, self.output, 1, input, self.weight:t()) self.output:addr(1, self.addBuffer, self.bias) else error('input must be vector or matrix') end return self.output end function Linear:updateGradInput(input, gradOutput) if self.gradInput then local nElement = self.gradInput:nElement() self.gradInput:resizeAs(input) if self.gradInput:nElement() ~= nElement then self.gradInput:zero() end if input:dim() == 1 then self.gradInput:addmv(0, 1, self.weight:t(), gradOutput) elseif input:dim() == 2 then self.gradInput:addmm(0, 1, gradOutput, self.weight) end return self.gradInput end end function Linear:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 1 then self.gradWeight:addr(scale, gradOutput, input) self.gradBias:add(scale, gradOutput) elseif input:dim() == 2 then self.gradWeight:addmm(scale, gradOutput:t(), input) self.gradBias:addmv(scale, gradOutput:t(), self.addBuffer) end end -- we do not need to accumulate parameters when sharing Linear.sharedAccUpdateGradParameters = Linear.accUpdateGradParameters function Linear:__tostring__() return torch.type(self) .. string.format('(%d -> %d)', self.weight:size(2), self.weight:size(1)) end
phy={} player.weight=6 player.jumpspeed=1 player.jumpairtime=10 player.jumpairtimeC=0 player.airtime=10 player.inair=0 player.gravity=0 local LoseHp = 0 local fallen = 0 phy.world = bump.newWorld(128) phy.blocks = {} phy.player = {type='player'} phy.nocollosion = {5,8} function phy.playerFilter(item, other) if other.type=='entity' then return 'cross' end return 'slide' end function phy.entFilter(item, other) if other.type=='player' then return 'cross' end return 'slide' end function phy.init() phy.world:add(phy.player,(px or w/2),(py or h/2),world.tile.w-4,(world.tile.h*2)-4) end function phy.loop() if nf(phy.relc)==0 then phy.reloadBlocks() phy.relc=5 --PHYSICS RELOAD EVERY x FRAMES // 0-EVERY FRAME else phy.relc=phy.relc-1 end local rpx2, rpy2, cols, len = phy.world:move(phy.player,px,py+player.gravity+(phy.player.Drop or 0),phy.playerFilter) rpx=rpx2 rpy=rpy2 --[[local enableShittyGravity=true if(phy.entities and entities and enableShittyGravity)then for i,v in ipairs(phy.entities) do local gx,gy=entities.spawned[i].pos.x,entities.spawned[i].pos.y+1 local rx,ry,cols,colc=phy.world:move(v,gx,gy,phy.entFilter) entities.spawned[i].pos.y=ry entities.spawned[i].pos.x=rx end end]] phy.jump() if phy.player.isOnGround(5) then phy.player.Drop=0 if fallen > 30 then player.hp = player.hp - LoseHp LoseHp = 0 end fallen = 0 LoseHp = 0 else if not(player.jump) then LoseHp = LoseHp + 0.15 fallen = fallen + 1 end end end function phy.reloadBlocks() phy.clrBlock() phy.entities={} local et=entities if(et)then for i=1,#et.spawned do local etbox=api.entities.getPosition(i) phy.entities[i]=phy.addBlock(etbox.x+etbox.w,etbox.y+etbox.h,etbox.w,etbox.h,'entity') end end for i=1,world.h*world.w do if world.chunk.data[i]>0 then local tmpx2,tmpy2=t2d1d(i,world.w) if(tmpx2*world.tile.w>0)then if table.has_value(blocksOnScreen or {i},i) then if table.has_value(phy.nocollosion, world.chunk.data[i]) == false then phy.addBlock(tmpx2*world.tile.w,tmpy2*world.tile.h,world.tile.w,world.tile.h,'block') end end end end end end function phy.addBlock(x,y,w,h,type) type=type or 'block' local block = {x=x,y=y,w=w,h=h,type=type} phy.blocks[#phy.blocks+1] = block phy.world:add(block, x,y,w,h) phy.uu=true return block end function phy.clrBlock() if phy.uu then for i=1,table.count(phy.blocks) do phy.world:remove(phy.blocks[i]) end phy.blocks={} end end function phy.jump() if player.jump then player.gravity=-player.weight player.inair=player.inair+player.jumpspeed if(player.inair>player.airtime)then player.jumpairtimeC=player.jumpairtime player.jump=false end else if(player.jumpairtimeC>0) then player.jumpairtimeC=player.jumpairtimeC-1 player.gravity=0.1 else player.jumpairtimeC=0 player.gravity=player.weight player.inair=0 inair=0 end end end function phy.player.isOnGround(s) s=s or 4 local actualX, actualY, cols, len = phy.world:check(phy.player, nf(rpx), nf(rpy)+world.tile.h/2+s) if len>0 then return true else return false end end function phy.player.dropOnGround() phy.player.Drop=64 end --phy.entities={} --[[function phy.entityUpdate() local e=entities if(e)then for i=1,#phy.entities do phy.world:remove(phy.entities[i]) end phy.entities={} for i=1,#e.spawned do if(e.spawned[i].pos.cx==world.chunk.id.x and e.spawned[i].pos.cy==world.chunk.id.y)then phy.entities[i]={ type='entity', NotPlCol=true, x=e.spawned[i].pos.x, y=e.spawned[i].pos.y, w=e.list[e.spawned[i].id].size.w, h=e.list[e.spawned[i].id].size.h, } ce=phy.entities[i] phy.world:add(ce,ce.x,ce.y,ce.w,ce.h) phy.world:check(ce) print(phy.world:getRect(ce)) end end end end]]
--- Common functions that are needed by almost any good strategy. local util = require 'lib.util' local isin = util.isin local slice = util.slice local simulation = require 'simulation' local T = simulation.T local calcDrivingDistance = simulation.calcDrivingDistance local compareCodes = simulation.compareCodes local function _createAllCodes(codes, code, length) if length == 0 then codes[#codes+1] = {unpack(code)} else for i=0,7 do code[length] = T[i] _createAllCodes(codes, code, length-1) end end end --- Create a list of all possible codes with a length of 'length'. local function createAllCodes(length) local codes = {} _createAllCodes(codes, {}, length) return codes end --- Return a list of all codes in 'set' that might be the secret code. local function getConsistentCodes(codes, guess, blacks, whites) local res = {} for _,code in ipairs(codes) do local answer = compareCodes(guess, code) if answer.blacks == blacks and answer.whites == whites then res[#res+1] = code end end return res end --- Return the code from 'codes' that would result in the shortest travel --- distance. local function getShortestCode(lastPosition, codes) local minDistance = math.huge local shortestCode = nil for _,code in ipairs(codes) do local distance = calcDrivingDistance(lastPosition, code) if distance < minDistance then minDistance = distance shortestCode = code end end return shortestCode end --- List of all *possible* blacks and whites combinations. -- Especially useful for the more sophisticated algorithms. local function createAllAnswers(length) local res = {} for blacks=0,length do for whites=0,length do if blacks + whites <= length and not (blacks == length-1 and whites == 1) -- impossible then res[#res+1] = {blacks=blacks, whites=whites} end end end return res end return { createAllAnswers = createAllAnswers, createAllCodes = createAllCodes, getConsistentCodes = getConsistentCodes, getShortestCode = getShortestCode }
--[[ Tube-enabled frames (API) Omikhleia 2020. MIT-lisenced. --]] tubeframe = { version = 1.0, } -- Node registration local nodeparts = { tube = { insert_object = function(pos, node, stack, direction, owner) local meta = minetest.get_meta(pos) local s = stack:take_item(1) meta:set_string("item", s:to_string()) framing_api.core.update_item(pos, node) return stack end, can_insert = function(pos, node, stack, direction, owner) local meta = minetest.get_meta(pos) return meta:get_string("item") == "" end, connect_sides = { bottom=1 }, }, on_rightclick = function(pos, node, clicker, itemstack) local meta = minetest.get_meta(pos) framing_api.core.drop_item(pos, node) minetest.sound_play("tubeframe_tap", { pos = pos, max_hear_distance = 5 }, true) return itemstack end, on_punch = function(pos,node,puncher) local meta = minetest.get_meta(pos) framing_api.core.drop_item(pos, node) end, after_place_node = pipeworks.after_place, after_dig_node = pipeworks.after_dig, on_destruct = function(pos) local meta = minetest.get_meta(pos) local node = minetest.get_node(pos) if meta:get_string("item") ~= "" then framing_api.core.drop_item(pos, node) end end, } tubeframe.register_node = function(itemname, nodedata) -- Add behaviors for k, v in pairs(nodeparts) do nodedata[k] = v end -- Ensure the tubeframe group is set (default to frame-like) nodedata.groups = nodedata.groups or {} nodedata.groups.tubeframe = nodedata.groups.tubeframe or 1 nodedata.groups.framing = nodedata.groups.tubeframe nodedata.groups.tubedevice = 1 nodedata.groups.tubedevice_receiver = 1 framing_api.register_node(itemname, nodedata) end -- EOF
local mod_storage = minetest.get_mod_storage() local channels = minetest.parse_json(mod_storage:get_string("channels")) -- -- Mod settings -- Change these to your liking -- local main_channel_name = "main" -- The main channel is the one you send messages to when no channel is specified local main_channel_owner = "Ganome" -- The owner of the main channel, usually ADMIN local main_channel_color = "#b4ead3" -- The color in hex of the main channel local default_channel_color = "#1858ce" -- The default color of channels when no color is specified local enable_sounds = true -- Global flag to enable/ disable sounds local channel_management_sound = "beerchat_chirp" -- General sound when managing channels like /cc, /dc etc local join_channel_sound = "beerchat_chirp" -- Sound when you join a channel local leave_channel_sound = "beerchat_chirp" -- Sound when you leave a channel local channel_invite_sound = "beerchat_chirp" -- Sound when sending/ receiving an invite to a channel local channel_message_sound = "beerchat_chime" -- Sound when a message is sent to a channel local private_message_sound = "beerchat_chime" -- Sound when you receive a private message local self_message_sound = "beerchat_utter" -- Sound when you send a private message to yourself local whisper_default_range = 32 -- Default whisper range when whispering without specifying a radius local whisper_max_range = 200 -- Maximum whisper range that can be specified when whispering local whisper_color = "#1acd1a" -- Whisper color override -- Message string formats -- Change these if you would like different formatting -- -- These can be changed to show "~~~#mychannel~~~ <player01> message" instead of "|#mychannel| or any -- other format you like such as removing the channel name from the main channel, putting channel or -- player names at the end of the chat message, etc. -- -- The following parameters are available and can be specified : -- ${channel_name} name of the channel -- ${channel_owner} owner of the channel -- ${channel_password} password to use when joining the channel, used e.g. for invites -- ${from_player} the player that is sending the message -- ${to_player} player to which the message is sent, will contain multiple player names e.g. when sending a PM to multiple players -- ${message} the actual message that is to be sent -- ${time} the current time in 24 hour format, as returned from os.date("%X") -- local channel_invitation_string = "|#${channel_name}| Channel invite from (${from_player}), to join the channel, do /jc ${channel_name},${channel_password} after which you can send messages to the channel via #${channel_name}: message" local channel_invited_string = "|#${channel_name}| Invite sent to ${to_player}" local channel_created_string = "|#${channel_name}| Channel created" local channel_deleted_string = "|#${channel_name}| Channel deleted" local channel_joined_string = "|#${channel_name}| Joined channel" local channel_left_string = "|#${channel_name}| Left channel" local channel_already_deleted_string = "|#${channel_name}| Channel seems to have already been deleted, will unregister channel from your list of channels" local private_message_string = "[PM] from (${from_player}) ${message}" local self_message_string = "(${from_player} utters to him/ herself) ${message}" local private_message_sent_string = "[PM] sent to @(${to_player}) ${message}" local me_message_string = "|#${channel_name}| * ${from_player} ${message}" local channel_message_string = "|#${channel_name}| <${from_player}> ${message}" local main_channel_message_string = "|#${channel_name}| <${from_player}> ${message}" local whisper_string = "|#${channel_name}| <${from_player}> whispers: ${message}" function format_message(s, tab) local owner local password local color = default_channel_color if tab.channel_name and channels[tab.channel_name] then owner = channels[tab.channel_name].owner password = channels[tab.channel_name].password color = channels[tab.channel_name].color end if tab.color then color = tab.color end local params = { channel_name = tab.channel_name, channel_owner = owner, channel_password = password, from_player = tab.from_player, to_player = tab.to_player, message = tab.message, time = os.date("%X") } return string.char(0x1b).."(c@"..color..")"..format_string(s, params) end function format_string(s, tab) return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end)) end if mod_storage:get_string("channels") == "" then minetest.log("action", "[beerchat] One off initializing mod storage") channels[main_channel_name] = { owner = main_channel_owner, color = main_channel_color } mod_storage:set_string("channels", minetest.write_json(channels)) end chachannels = minetest.parse_json(mod_storage:get_string("channels")) channels[main_channel_name] = { owner = main_channel_owner, color = main_channel_color } playersChannels = {} local currentPlayerChannel = {} minetest.register_on_joinplayer(function(player) local str = player:get_attribute("beerchat:channels") if str and str ~= "" then playersChannels[player:get_player_name()] = {} playersChannels[player:get_player_name()] = minetest.parse_json(str) else playersChannels[player:get_player_name()] = {} playersChannels[player:get_player_name()][main_channel_name] = "joined" player:set_attribute("beerchat:channels", minetest.write_json(playersChannels[player:get_player_name()])) end local current_channel = player:get_attribute("beerchat:current_channel") if current_channel and current_channel ~= "" then currentPlayerChannel[player:get_player_name()] = current_channel else currentPlayerChannel[player:get_player_name()] = main_channel_name end end) minetest.register_on_leaveplayer(function(player) playersChannels[player:get_player_name()] = nil atchat_lastrecv[player:get_player_name()] = nil currentPlayerChannel[player:get_player_name()] = nil end) local create_channel = { params = "<Channel Name>,<Password (optional)>,<Color (optional, default is #ffffff)>", description = "Create a channel named <Channel Name> with optional <Password> and hexadecimal <Color> ".. "starting with # (e.g. #00ff00 for green). Use comma's to separate the arguments, e.g. ".. "/cc my secret channel,#0000ff for a blue colored my secret channel without password", func = function(lname, param) local lowner = lname if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the channel name as a minimum" end local str = string.split(param, ",") if #str > 3 then return false, "ERROR: Invalid number of arguments. 4 parameters passed, maximum of 3 allowed: <Channel Name>,<Password>,<Color>" end local lchannel_name = string.trim(str[1]) if lchannel_name == "" then return false, "ERROR: You must supply a channel name" end if lchannel_name == main_channel_name then return false, "ERROR: You cannot use channel name \""..main_channel_name.."\"" end if channels[lchannel_name] then return false, "ERROR: Channel "..lchannel_name.." already exists, owned by player "..channels[lchannel_name].owner end local arg2 = str[2] local lcolor = default_channel_color local lpassword = "" if arg2 then if string.sub(arg2, 1, 1) ~= "#" then lpassword = arg2 else lcolor = string.lower(str[2]) end end if #str == 3 then lcolor = string.lower(str[3]) end channels[lchannel_name] = { owner = lowner, name = lchannel_name, password = lpassword, color = lcolor } mod_storage:set_string("channels", minetest.write_json(channels)) playersChannels[lowner][lchannel_name] = "owner" minetest.get_player_by_name(lowner):set_attribute("beerchat:channels", minetest.write_json(playersChannels[lowner])) if enable_sounds then minetest.sound_play(channel_management_sound, { to_player = lowner, gain = 1.0 } ) end minetest.chat_send_player(lowner, format_message(channel_created_string, { channel_name = lchannel_name })) return true end } local delete_channel = { params = "<Channel Name>", description = "Delete channel named <Channel Name>. You must be the owner of the channel or you are not allowed to delete the channel", func = function(name, param) local owner = name if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the channel name" end if param == main_channel_name then return false, "ERROR: Cannot delete the main channel!!" end if not channels[param] then return false, "ERROR: Channel "..param.." does not exist" end if name ~= channels[param].owner then return false, "ERROR: You are not the owner of channel "..param end local color = channels[param].color channels[param] = nil mod_storage:set_string("channels", minetest.write_json(channels)) playersChannels[name][param] = nil minetest.get_player_by_name(name):set_attribute("beerchat:channels", minetest.write_json(playersChannels[name])) if enable_sounds then minetest.sound_play(channel_management_sound, { to_player = name, gain = 1.0 } ) end minetest.chat_send_player(name, format_message(channel_deleted_string, { channel_name = param, color = color })) return true end } local my_channels = { params = "<Channel Name optional>", description = "List the channels you have joined or are the owner of, or show channel information when passing channel name as argument", func = function(name, param) if not param or param == "" then if enable_sounds then minetest.sound_play(channel_management_sound, { to_player = name, gain = 1.0 } ) end minetest.chat_send_player(name, dump2(playersChannels[name])) else if playersChannels[name][param] then if enable_sounds then minetest.sound_play(channel_management_sound, { to_player = name, gain = 1.0 } ) end minetest.chat_send_player(name, dump2(channels[param])) else minetest.chat_send_player(name, "ERROR: Channel not in your channel list") return false end end return true end } local join_channel = { params = "<Channel Name>,<Password (only mandatory if channel was created using a password)>", description = "Join channel named <Channel Name>. After joining you will see messages sent to that channel (in addition to the other channels you have joined)", func = function(name, param) if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the channel name as a minimum" end local str = string.split(param, ",") local channel_name = str[1] if not channels[channel_name] then return false, "ERROR: Channel "..channel_name.." does not exist" end if playersChannels[name][channel_name] then return false, "ERROR: You already joined "..channel_name..", no need to rejoin" end if channels[channel_name].password and channels[channel_name].password ~= "" then if #str == 1 then return false, "ERROR: This channel requires that you supply a password. Supply it in the following format: /jc my channel,password01" end if str[2] ~= channels[channel_name].password then return false, "ERROR: Invalid password" end end playersChannels[name][channel_name] = "joined" minetest.get_player_by_name(name):set_attribute("beerchat:channels", minetest.write_json(playersChannels[name])) if enable_sounds then minetest.sound_play(join_channel_sound, { to_player = name, gain = 1.0 } ) end minetest.chat_send_player(name, format_message(channel_joined_string, { channel_name = channel_name })) return true end } local leave_channel = { params = "<Channel Name>", description = "Leave channel named <Channel Name>. When you leave the channel you can no longer send/ receive messages from that channel. NOTE: You can also leave the main channel", func = function(name, param) if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the channel name" end local channel_name = param if not playersChannels[name][channel_name] then return false, "ERROR: You are not member of "..channel_name..", no need to leave" end playersChannels[name][channel_name] = nil minetest.get_player_by_name(name):set_attribute("beerchat:channels", minetest.write_json(playersChannels[name])) if enable_sounds then minetest.sound_play(leave_channel_sound, { to_player = name, gain = 1.0 } ) end if not channels[channel_name] then minetest.chat_send_player(name, format_message(channel_already_deleted_string, { channel_name = channel_name })) else minetest.chat_send_player(name, format_message(channel_left_string, { channel_name = channel_name })) end return true end } local invite_channel = { params = "<Channel Name>,<Player Name>", description = "Invite player named <Player Name> to channel named <Channel Name>. You must be the owner of the channel in order to do invites", func = function(name, param) local owner = name if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the channel name and the player name" end local channel_name, player_name = string.match(param, "(.*),(.*)") if not channel_name or channel_name == "" then return false, "ERROR: Channel name is empty" end if not player_name or player_name == "" then return false, "ERROR: Player name not supplied or empty" end if not channels[channel_name] then return false, "ERROR: Channel "..channel_name.." does not exist" end if name ~= channels[channel_name].owner then return false, "ERROR: You are not the owner of channel "..param end if not minetest.get_player_by_name(player_name) then return false, "ERROR: "..player_name.." does not exist or is not online" else if not minetest.get_player_by_name(player_name):get_attribute("beerchat:muted:"..name) then if enable_sounds then minetest.sound_play(channel_invite_sound, { to_player = player_name, gain = 1.0 } ) end -- Sending the message minetest.chat_send_player(player_name, format_message(channel_invitation_string, { channel_name = channel_name, from_player = name })) end if enable_sounds then minetest.sound_play(channel_invite_sound, { to_player = name, gain = 1.0 } ) end minetest.chat_send_player(name, format_message(channel_invited_string, { channel_name = channel_name, to_player = player_name })) end return true end } local mute_player = { params = "<Player Name>", description = "Mute a player. After muting a player, you will no longer see chat messages of this user, regardless of what channel his user sends messages to", func = function(name, param) if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the name of the user to mute" end minetest.get_player_by_name(name):set_attribute("beerchat:muted:"..param, "true") minetest.chat_send_player(name, "Muted player "..param) return true end } local unmute_player = { params = "<Player Name>", description = "Unmute a player. After unmuting a player, you will again see chat messages of this user", func = function(name, param) if not param or param == "" then return false, "ERROR: Invalid number of arguments. Please supply the name of the user to mute" end minetest.get_player_by_name(name):set_attribute("beerchat:muted:"..param, nil) minetest.chat_send_player(name, "Unmuted player "..param) return true end } minetest.register_chatcommand("cc", create_channel) minetest.register_chatcommand("create_channel", create_channel) minetest.register_chatcommand("dc", delete_channel) minetest.register_chatcommand("delete_channel", delete_channel) minetest.register_chatcommand("mc", my_channels) minetest.register_chatcommand("my_channels", my_channels) minetest.register_chatcommand("jc", join_channel) minetest.register_chatcommand("join_channel", join_channel) minetest.register_chatcommand("lc", leave_channel) minetest.register_chatcommand("leave_channel", leave_channel) minetest.register_chatcommand("ic", invite_channel) minetest.register_chatcommand("invite_channel", invite_channel) minetest.register_chatcommand("mute", mute_player) minetest.register_chatcommand("ignore", mute_player) minetest.register_chatcommand("unmute", unmute_player) minetest.register_chatcommand("unignore", unmute_player) -- @ chat a.k.a. at chat/ PM chat code, to PM players using @player1 only you can read this player1!! atchat_lastrecv = {} minetest.register_on_chat_message(function(name, message) local players, msg = string.match(message, "^@([^%s:]*)[%s:](.*)") if players and msg then if msg == "" then minetest.chat_send_player(name, "Please enter the private message you would like to send") else if players == "" then--reply -- We need to get the target players = atchat_lastrecv[name] end if players and players ~= "" then local atleastonesent = false local successplayers = "" for target in string.gmatch(","..players..",", ",([^,]+),") do -- Checking if the target exists if not minetest.get_player_by_name(target) then minetest.chat_send_player(name, ""..target.." is not online") else if not minetest.get_player_by_name(target):get_attribute("beerchat:muted:"..name) then if target ~= name then -- Sending the message minetest.chat_send_player(target, format_message(private_message_string, { from_player = name, message = msg })) if enable_sounds then minetest.sound_play(private_message_sound, { to_player = target, gain = 1.0 } ) end else minetest.chat_send_player(target, format_message(self_message_string, { from_player = name, message = msg })) if enable_sounds then minetest.sound_play(self_message_sound, { to_player = target, gain = 1.0 } ) end end end atleastonesent = true successplayers = successplayers..target.."," end end -- Register the chat in the target persons last spoken to table atchat_lastrecv[name] = players if atleastonesent then successplayers = successplayers:sub(1, -2) if (successplayers ~= name) then minetest.chat_send_player(name, format_message(private_message_sent_string, { to_player = successplayers, message = msg })) end end else minetest.chat_send_player(name, "You have not sent private messages to anyone yet, please specify player names to send message to") end end return true end end) local msg_override = { params = "<Player Name> <Message>", description = "Send private message to player, for compatibility with the old chat command but with new style chat muting support ".. "(players will not receive your message if they muted you) and multiple (comma separated) player support", func = function(name, param) local players, msg = string.match(param, "^(.-) (.*)") if players and msg then if players == "" then minetest.chat_send_player(name, "ERROR: Please enter the private message you would like to send") return false elseif msg == "" then minetest.chat_send_player(name, "ERROR: Please enter the private message you would like to send") return false else if players and players ~= "" then local atleastonesent = false local successplayers = "" for target in string.gmatch(","..players..",", ",([^,]+),") do -- Checking if the target exists if not minetest.get_player_by_name(target) then minetest.chat_send_player(name, ""..target.." is not online") else if not minetest.get_player_by_name(target):get_attribute("beerchat:muted:"..name) then if target ~= name then -- Sending the message minetest.chat_send_player(target, format_message(private_message_string, { from_player = name, message = msg })) if enable_sounds then minetest.sound_play(private_message_sound, { to_player = target, gain = 1.0 } ) end else minetest.chat_send_player(target, format_message(self_message_string, { from_player = name, message = msg })) if enable_sounds then minetest.sound_play(self_message_sound, { to_player = target, gain = 1.0 } ) end end end atleastonesent = true successplayers = successplayers..target.."," end end -- Register the chat in the target persons last spoken to table atchat_lastrecv[name] = players if atleastonesent then successplayers = successplayers:sub(1, -2) if (successplayers ~= name) then minetest.chat_send_player(name, format_message(private_message_sent_string, { to_player = successplayers, message = msg })) end end end end return true end end } minetest.register_chatcommand("msg", msg_override) local me_override = { params = "<Message>", description = "Send message in the \"* player message\" format, e.g. /me eats pizza becomes |#"..main_channel_name.."| * Player01 eats pizza", func = function(name, param) local msg = param local channel_name = main_channel_name if not channels[channel_name] then minetest.chat_send_player(name, "Channel "..channel_name.." does not exist") elseif msg == "" then minetest.chat_send_player(name, "Please enter the message you would like to send to the channel") elseif not playersChannels[name][channel_name] then minetest.chat_send_player(name, "You need to join this channel in order to be able to send messages to it") else for _,player in ipairs(minetest.get_connected_players()) do local target = player:get_player_name() -- Checking if the target is in this channel if playersChannels[target][channel_name] then if not minetest.get_player_by_name(target):get_attribute("beerchat:muted:"..name) then minetest.chat_send_player(target, format_message(me_message_string, { channel_name = channel_name, from_player = name, message = msg })) end end end end return true end } minetest.register_chatcommand("me", me_override) -- # chat a.k.a. hash chat/ channel chat code, to send messages in chat channels using # e.g. #my channel: hello everyone in my channel! hashchat_lastrecv = {} minetest.register_on_chat_message(function(name, message) local channel_name, msg = string.match(message, "^#(.-): (.*)") if not channels[channel_name] then channel_name, msg = string.match(message, "^#(.-) (.*)") end if channel_name == "" then channel_name = hashchat_lastrecv[name] end if channel_name and msg then if not channels[channel_name] then minetest.chat_send_player(name, "Channel "..channel_name.." does not exist. Make sure the channel still ".. "exists and you format its name properly, e.g. #channel message or #my channel: message") elseif msg == "" then minetest.chat_send_player(name, "Please enter the message you would like to send to the channel") elseif not playersChannels[name][channel_name] then minetest.chat_send_player(name, "You need to join this channel in order to be able to send messages to it") else if channel_name == "" then--use last used channel -- We need to get the target channel_name = hashchat_lastrecv[name] end if channel_name and channel_name ~= "" then for _,player in ipairs(minetest.get_connected_players()) do local target = player:get_player_name() -- Checking if the target is in this channel if playersChannels[target][channel_name] then if not minetest.get_player_by_name(target):get_attribute("beerchat:muted:"..name) then if channel_name == main_channel_name then minetest.chat_send_player(target, format_message(main_channel_message_string, { channel_name = channel_name, from_player = name, message = msg })) else minetest.chat_send_player(target, format_message(channel_message_string, { channel_name = channel_name, from_player = name, message = msg })) if enable_sounds then minetest.sound_play(channel_message_sound, { to_player = target, gain = 1.0 } ) end end end end end -- Register the chat in the target persons last spoken to table hashchat_lastrecv[name] = channel_name else return false end end return true else channel_name = string.match(message, "^#(.*)") if channel_name then if not channels[channel_name] then minetest.chat_send_player(name, "Channel "..channel_name.." does not exist") elseif not playersChannels[name][channel_name] then minetest.chat_send_player(name, "You need to join this channel in order to be able to switch to it") else currentPlayerChannel[name] = channel_name minetest.get_player_by_name(name):set_attribute("beerchat:current_channel", channel_name) if channel_name == main_channel_name then minetest.chat_send_player(name, "Switched to channel "..channel_name..", messages will now be sent to this channel") else minetest.chat_send_player(name, "Switched to channel "..channel_name..", messages will now be sent to this channel. To switch back ".. "to the main channel, type #"..main_channel_name) end if enable_sounds then minetest.sound_play(channel_management_sound, { to_player = name, gain = 1.0 } ) end end return true end end end) -- $ chat a.k.a. dollar chat code, to whisper messages in chat to nearby players only using $, optionally supplying a radius e.g. $32 Hello minetest.register_on_chat_message(function(name, message) local dollar, sradius, msg = string.match(message, "^($)(.-) (.*)") if dollar == "$" then local radius = tonumber(sradius) if not radius then radius = whisper_default_range end if radius > whisper_max_range then minetest.chat_send_player(name, "You cannot whisper outside of a radius of "..whisper_max_range.." blocks") elseif msg == "" then minetest.chat_send_player(name, "Please enter the message you would like to whisper to nearby players") else local pl = minetest.get_player_by_name(name) local all_objects = minetest.get_objects_inside_radius({x=pl:getpos().x, y=pl:getpos().y, z=pl:getpos().z}, radius) for _,player in ipairs(all_objects) do if player:is_player() then local target = player:get_player_name() -- Checking if the target is in this channel if playersChannels[target][main_channel_name] then if not minetest.get_player_by_name(target):get_attribute("beerchat:muted:"..name) then minetest.chat_send_player(target, format_message(whisper_string, { channel_name = main_channel_name, from_player = name, message = msg, color = whisper_color })) end end end end return true end end end) minetest.register_on_chat_message(function(name, message) local msg = message local channel_name = currentPlayerChannel[name] if not channels[channel_name] then minetest.chat_send_player(name, "Channel "..channel_name.." does not exist, switching back to "..main_channel_name..". Please resend your message") currentPlayerChannel[name] = main_channel_name minetest.get_player_by_name(name):set_attribute("beerchat:current_channel", main_channel_name) return true end if not channels[channel_name] then minetest.chat_send_player(name, "Channel "..channel_name.." does not exist") elseif msg == "" then minetest.chat_send_player(name, "Please enter the message you would like to send to the channel") elseif not playersChannels[name][channel_name] then minetest.chat_send_player(name, "You need to join this channel in order to be able to send messages to it") else for _,player in ipairs(minetest.get_connected_players()) do local target = player:get_player_name() -- Checking if the target is in this channel if playersChannels[target][channel_name] then if not minetest.get_player_by_name(target):get_attribute("beerchat:muted:"..name) then minetest.chat_send_player(target, format_message(main_channel_message_string, { channel_name = channel_name, from_player = name, message = message })) if channel_name ~= main_channel_name and enable_sounds then minetest.sound_play(channel_message_sound, { to_player = target, gain = 1.0 } ) end end end end end return true end)
local pairs = pairs local ogetenv = os.getenv local utils = require 'bin.scaffold.utils' local app_run_env = ogetenv("FW_ENV") or 'dev' local ngx_conf = {} ngx_conf.common = { -- directives FW_ENV = app_run_env, -- INIT_BY_LUA_FILE = './app/nginx/init.lua', -- LUA_PACKAGE_PATH = '', -- LUA_PACKAGE_CPATH = '', CONTENT_BY_LUA_FILE = './app/app.lua', STATIC_FILE_DIRECTORY = './app/static' } ngx_conf.env = {} ngx_conf.env.dev = { LUA_CODE_CACHE = false, PORT = 8888 } ngx_conf.env.test = { LUA_CODE_CACHE = true, PORT = 9999 } ngx_conf.env.prod = { LUA_CODE_CACHE = true, PORT = 80 } local function getNgxConf(conf_arr) if conf_arr['common'] ~= nil then local common_conf = conf_arr['common'] local env_conf = conf_arr['env'][app_run_env] for directive, info in pairs(common_conf) do env_conf[directive] = info end return env_conf elseif conf_arr['env'] ~= nil then return conf_arr['env'][app_run_env] end return {} end local function buildConf() local sys_ngx_conf = getNgxConf(ngx_conf) return sys_ngx_conf end local ngx_directive_handle = require('bin.scaffold.nginx.directive'):new(app_run_env) local ngx_directives = ngx_directive_handle:directiveSets() local ngx_run_conf = buildConf() local NgxConf = {} for directive, func in pairs(ngx_directives) do if type(func) == 'function' then local func_rs = func(ngx_directive_handle, ngx_run_conf[directive]) if func_rs ~= false then NgxConf[directive] = func_rs end else NgxConf[directive] = ngx_run_conf[directive] end end return NgxConf
local Native = require('lib.stdlib.native') ---@class Hashtable : Agent local Hashtable = class('Hashtable', require('lib.stdlib.oop.agent')) ---<static> create ---@return Hashtable function Hashtable:create() return Hashtable:fromUd(Native.InitHashtable()) end ---saveInteger ---@param parentKey integer ---@param childKey integer ---@param value integer ---@return void function Hashtable:saveInteger(parentKey, childKey, value) --@debug@ checkobject(self, Hashtable, 'saveInteger', 'self') checktype(parentKey, 'integer', 'saveInteger', 1) checktype(childKey, 'integer', 'saveInteger', 2) checktype(value, 'integer', 'saveInteger', 3) --@end-debug@ return Native.SaveInteger(getUd(self), parentKey, childKey, value) end ---saveReal ---@param parentKey integer ---@param childKey integer ---@param value float ---@return void function Hashtable:saveReal(parentKey, childKey, value) --@debug@ checkobject(self, Hashtable, 'saveReal', 'self') checktype(parentKey, 'integer', 'saveReal', 1) checktype(childKey, 'integer', 'saveReal', 2) checktype(value, 'float', 'saveReal', 3) --@end-debug@ return Native.SaveReal(getUd(self), parentKey, childKey, value) end ---saveBoolean ---@param parentKey integer ---@param childKey integer ---@param value boolean ---@return void function Hashtable:saveBoolean(parentKey, childKey, value) --@debug@ checkobject(self, Hashtable, 'saveBoolean', 'self') checktype(parentKey, 'integer', 'saveBoolean', 1) checktype(childKey, 'integer', 'saveBoolean', 2) checktype(value, 'boolean', 'saveBoolean', 3) --@end-debug@ return Native.SaveBoolean(getUd(self), parentKey, childKey, value) end ---saveStr ---@param parentKey integer ---@param childKey integer ---@param value string ---@return boolean function Hashtable:saveStr(parentKey, childKey, value) --@debug@ checkobject(self, Hashtable, 'saveStr', 'self') checktype(parentKey, 'integer', 'saveStr', 1) checktype(childKey, 'integer', 'saveStr', 2) checktype(value, 'string', 'saveStr', 3) --@end-debug@ return Native.SaveStr(getUd(self), parentKey, childKey, value) end ---savePlayerHandle ---@param parentKey integer ---@param childKey integer ---@param player Player ---@return boolean function Hashtable:savePlayerHandle(parentKey, childKey, player) --@debug@ checkobject(self, Hashtable, 'savePlayerHandle', 'self') checktype(parentKey, 'integer', 'savePlayerHandle', 1) checktype(childKey, 'integer', 'savePlayerHandle', 2) checkobject(player, require('lib.stdlib.oop.player'), 'savePlayerHandle', 3) --@end-debug@ return Native.SavePlayerHandle(getUd(self), parentKey, childKey, getUd(player)) end ---saveWidgetHandle ---@param parentKey integer ---@param childKey integer ---@param widget Widget ---@return boolean function Hashtable:saveWidgetHandle(parentKey, childKey, widget) --@debug@ checkobject(self, Hashtable, 'saveWidgetHandle', 'self') checktype(parentKey, 'integer', 'saveWidgetHandle', 1) checktype(childKey, 'integer', 'saveWidgetHandle', 2) checkobject(widget, require('lib.stdlib.oop.widget'), 'saveWidgetHandle', 3) --@end-debug@ return Native.SaveWidgetHandle(getUd(self), parentKey, childKey, getUd(widget)) end ---saveDestructableHandle ---@param parentKey integer ---@param childKey integer ---@param destructable Destructable ---@return boolean function Hashtable:saveDestructableHandle(parentKey, childKey, destructable) --@debug@ checkobject(self, Hashtable, 'saveDestructableHandle', 'self') checktype(parentKey, 'integer', 'saveDestructableHandle', 1) checktype(childKey, 'integer', 'saveDestructableHandle', 2) checkobject(destructable, require('lib.stdlib.oop.destructable'), 'saveDestructableHandle', 3) --@end-debug@ return Native.SaveDestructableHandle(getUd(self), parentKey, childKey, getUd(destructable)) end ---saveItemHandle ---@param parentKey integer ---@param childKey integer ---@param item Item ---@return boolean function Hashtable:saveItemHandle(parentKey, childKey, item) --@debug@ checkobject(self, Hashtable, 'saveItemHandle', 'self') checktype(parentKey, 'integer', 'saveItemHandle', 1) checktype(childKey, 'integer', 'saveItemHandle', 2) checkobject(item, require('lib.stdlib.oop.item'), 'saveItemHandle', 3) --@end-debug@ return Native.SaveItemHandle(getUd(self), parentKey, childKey, getUd(item)) end ---saveUnitHandle ---@param parentKey integer ---@param childKey integer ---@param unit Unit ---@return boolean function Hashtable:saveUnitHandle(parentKey, childKey, unit) --@debug@ checkobject(self, Hashtable, 'saveUnitHandle', 'self') checktype(parentKey, 'integer', 'saveUnitHandle', 1) checktype(childKey, 'integer', 'saveUnitHandle', 2) checkobject(unit, require('lib.stdlib.oop.unit'), 'saveUnitHandle', 3) --@end-debug@ return Native.SaveUnitHandle(getUd(self), parentKey, childKey, getUd(unit)) end ---saveAbilityHandle ---@param parentKey integer ---@param childKey integer ---@param ability Ability ---@return boolean function Hashtable:saveAbilityHandle(parentKey, childKey, ability) --@debug@ checkobject(self, Hashtable, 'saveAbilityHandle', 'self') checktype(parentKey, 'integer', 'saveAbilityHandle', 1) checktype(childKey, 'integer', 'saveAbilityHandle', 2) checkobject(ability, require('lib.stdlib.oop.ability'), 'saveAbilityHandle', 3) --@end-debug@ return Native.SaveAbilityHandle(getUd(self), parentKey, childKey, getUd(ability)) end ---saveTimerHandle ---@param parentKey integer ---@param childKey integer ---@param timer Timer ---@return boolean function Hashtable:saveTimerHandle(parentKey, childKey, timer) --@debug@ checkobject(self, Hashtable, 'saveTimerHandle', 'self') checktype(parentKey, 'integer', 'saveTimerHandle', 1) checktype(childKey, 'integer', 'saveTimerHandle', 2) checkobject(timer, require('lib.stdlib.oop.timer'), 'saveTimerHandle', 3) --@end-debug@ return Native.SaveTimerHandle(getUd(self), parentKey, childKey, getUd(timer)) end ---saveTriggerHandle ---@param parentKey integer ---@param childKey integer ---@param trigger Trigger ---@return boolean function Hashtable:saveTriggerHandle(parentKey, childKey, trigger) --@debug@ checkobject(self, Hashtable, 'saveTriggerHandle', 'self') checktype(parentKey, 'integer', 'saveTriggerHandle', 1) checktype(childKey, 'integer', 'saveTriggerHandle', 2) checkobject(trigger, require('lib.stdlib.oop.trigger'), 'saveTriggerHandle', 3) --@end-debug@ return Native.SaveTriggerHandle(getUd(self), parentKey, childKey, getUd(trigger)) end ---saveTriggerConditionHandle ---@param parentKey integer ---@param childKey integer ---@param triggercondition TriggerCondition ---@return boolean function Hashtable:saveTriggerConditionHandle(parentKey, childKey, triggercondition) --@debug@ checkobject(self, Hashtable, 'saveTriggerConditionHandle', 'self') checktype(parentKey, 'integer', 'saveTriggerConditionHandle', 1) checktype(childKey, 'integer', 'saveTriggerConditionHandle', 2) checkobject(triggercondition, require('lib.stdlib.oop.triggercondition'), 'saveTriggerConditionHandle', 3) --@end-debug@ return Native.SaveTriggerConditionHandle(getUd(self), parentKey, childKey, getUd(triggercondition)) end ---saveTriggerActionHandle ---@param parentKey integer ---@param childKey integer ---@param triggeraction TriggerAction ---@return boolean function Hashtable:saveTriggerActionHandle(parentKey, childKey, triggeraction) --@debug@ checkobject(self, Hashtable, 'saveTriggerActionHandle', 'self') checktype(parentKey, 'integer', 'saveTriggerActionHandle', 1) checktype(childKey, 'integer', 'saveTriggerActionHandle', 2) checkuserdata(triggeraction, 'triggeraction', 'saveTriggerActionHandle', 3) --@end-debug@ return Native.SaveTriggerActionHandle(getUd(self), parentKey, childKey, triggeraction) end ---saveTriggerEventHandle ---@param parentKey integer ---@param childKey integer ---@param event Event ---@return boolean function Hashtable:saveTriggerEventHandle(parentKey, childKey, event) --@debug@ checkobject(self, Hashtable, 'saveTriggerEventHandle', 'self') checktype(parentKey, 'integer', 'saveTriggerEventHandle', 1) checktype(childKey, 'integer', 'saveTriggerEventHandle', 2) checkobject(event, require('lib.stdlib.oop.event'), 'saveTriggerEventHandle', 3) --@end-debug@ return Native.SaveTriggerEventHandle(getUd(self), parentKey, childKey, getUd(event)) end ---saveForceHandle ---@param parentKey integer ---@param childKey integer ---@param force Force ---@return boolean function Hashtable:saveForceHandle(parentKey, childKey, force) --@debug@ checkobject(self, Hashtable, 'saveForceHandle', 'self') checktype(parentKey, 'integer', 'saveForceHandle', 1) checktype(childKey, 'integer', 'saveForceHandle', 2) checkobject(force, require('lib.stdlib.oop.force'), 'saveForceHandle', 3) --@end-debug@ return Native.SaveForceHandle(getUd(self), parentKey, childKey, getUd(force)) end ---saveGroupHandle ---@param parentKey integer ---@param childKey integer ---@param group Group ---@return boolean function Hashtable:saveGroupHandle(parentKey, childKey, group) --@debug@ checkobject(self, Hashtable, 'saveGroupHandle', 'self') checktype(parentKey, 'integer', 'saveGroupHandle', 1) checktype(childKey, 'integer', 'saveGroupHandle', 2) checkobject(group, require('lib.stdlib.oop.group'), 'saveGroupHandle', 3) --@end-debug@ return Native.SaveGroupHandle(getUd(self), parentKey, childKey, getUd(group)) end ---saveRectHandle ---@param parentKey integer ---@param childKey integer ---@param rect Rect ---@return boolean function Hashtable:saveRectHandle(parentKey, childKey, rect) --@debug@ checkobject(self, Hashtable, 'saveRectHandle', 'self') checktype(parentKey, 'integer', 'saveRectHandle', 1) checktype(childKey, 'integer', 'saveRectHandle', 2) checkobject(rect, require('lib.stdlib.oop.rect'), 'saveRectHandle', 3) --@end-debug@ return Native.SaveRectHandle(getUd(self), parentKey, childKey, getUd(rect)) end ---saveBooleanExprHandle ---@param parentKey integer ---@param childKey integer ---@param boolexpr BoolExpr ---@return boolean function Hashtable:saveBooleanExprHandle(parentKey, childKey, boolexpr) --@debug@ checkobject(self, Hashtable, 'saveBooleanExprHandle', 'self') checktype(parentKey, 'integer', 'saveBooleanExprHandle', 1) checktype(childKey, 'integer', 'saveBooleanExprHandle', 2) checkobject(boolexpr, require('lib.stdlib.oop.boolexpr'), 'saveBooleanExprHandle', 3) --@end-debug@ return Native.SaveBooleanExprHandle(getUd(self), parentKey, childKey, getUd(boolexpr)) end ---saveSoundHandle ---@param parentKey integer ---@param childKey integer ---@param sound Sound ---@return boolean function Hashtable:saveSoundHandle(parentKey, childKey, sound) --@debug@ checkobject(self, Hashtable, 'saveSoundHandle', 'self') checktype(parentKey, 'integer', 'saveSoundHandle', 1) checktype(childKey, 'integer', 'saveSoundHandle', 2) checkobject(sound, require('lib.stdlib.oop.sound'), 'saveSoundHandle', 3) --@end-debug@ return Native.SaveSoundHandle(getUd(self), parentKey, childKey, getUd(sound)) end ---saveEffectHandle ---@param parentKey integer ---@param childKey integer ---@param effect Effect ---@return boolean function Hashtable:saveEffectHandle(parentKey, childKey, effect) --@debug@ checkobject(self, Hashtable, 'saveEffectHandle', 'self') checktype(parentKey, 'integer', 'saveEffectHandle', 1) checktype(childKey, 'integer', 'saveEffectHandle', 2) checkobject(effect, require('lib.stdlib.oop.effect'), 'saveEffectHandle', 3) --@end-debug@ return Native.SaveEffectHandle(getUd(self), parentKey, childKey, getUd(effect)) end ---saveUnitPoolHandle ---@param parentKey integer ---@param childKey integer ---@param unitpool UnitPool ---@return boolean function Hashtable:saveUnitPoolHandle(parentKey, childKey, unitpool) --@debug@ checkobject(self, Hashtable, 'saveUnitPoolHandle', 'self') checktype(parentKey, 'integer', 'saveUnitPoolHandle', 1) checktype(childKey, 'integer', 'saveUnitPoolHandle', 2) checkobject(unitpool, require('lib.stdlib.oop.unitpool'), 'saveUnitPoolHandle', 3) --@end-debug@ return Native.SaveUnitPoolHandle(getUd(self), parentKey, childKey, getUd(unitpool)) end ---saveItemPoolHandle ---@param parentKey integer ---@param childKey integer ---@param itempool ItemPool ---@return boolean function Hashtable:saveItemPoolHandle(parentKey, childKey, itempool) --@debug@ checkobject(self, Hashtable, 'saveItemPoolHandle', 'self') checktype(parentKey, 'integer', 'saveItemPoolHandle', 1) checktype(childKey, 'integer', 'saveItemPoolHandle', 2) checkobject(itempool, require('lib.stdlib.oop.itempool'), 'saveItemPoolHandle', 3) --@end-debug@ return Native.SaveItemPoolHandle(getUd(self), parentKey, childKey, getUd(itempool)) end ---saveQuestHandle ---@param parentKey integer ---@param childKey integer ---@param quest Quest ---@return boolean function Hashtable:saveQuestHandle(parentKey, childKey, quest) --@debug@ checkobject(self, Hashtable, 'saveQuestHandle', 'self') checktype(parentKey, 'integer', 'saveQuestHandle', 1) checktype(childKey, 'integer', 'saveQuestHandle', 2) checkobject(quest, require('lib.stdlib.oop.quest'), 'saveQuestHandle', 3) --@end-debug@ return Native.SaveQuestHandle(getUd(self), parentKey, childKey, getUd(quest)) end ---saveQuestItemHandle ---@param parentKey integer ---@param childKey integer ---@param questitem QuestItem ---@return boolean function Hashtable:saveQuestItemHandle(parentKey, childKey, questitem) --@debug@ checkobject(self, Hashtable, 'saveQuestItemHandle', 'self') checktype(parentKey, 'integer', 'saveQuestItemHandle', 1) checktype(childKey, 'integer', 'saveQuestItemHandle', 2) checkobject(questitem, require('lib.stdlib.oop.questitem'), 'saveQuestItemHandle', 3) --@end-debug@ return Native.SaveQuestItemHandle(getUd(self), parentKey, childKey, getUd(questitem)) end ---saveDefeatConditionHandle ---@param parentKey integer ---@param childKey integer ---@param defeatcondition DefeatCondition ---@return boolean function Hashtable:saveDefeatConditionHandle(parentKey, childKey, defeatcondition) --@debug@ checkobject(self, Hashtable, 'saveDefeatConditionHandle', 'self') checktype(parentKey, 'integer', 'saveDefeatConditionHandle', 1) checktype(childKey, 'integer', 'saveDefeatConditionHandle', 2) checkobject(defeatcondition, require('lib.stdlib.oop.defeatcondition'), 'saveDefeatConditionHandle', 3) --@end-debug@ return Native.SaveDefeatConditionHandle(getUd(self), parentKey, childKey, getUd(defeatcondition)) end ---saveTimerDialogHandle ---@param parentKey integer ---@param childKey integer ---@param timerdialog TimerDialog ---@return boolean function Hashtable:saveTimerDialogHandle(parentKey, childKey, timerdialog) --@debug@ checkobject(self, Hashtable, 'saveTimerDialogHandle', 'self') checktype(parentKey, 'integer', 'saveTimerDialogHandle', 1) checktype(childKey, 'integer', 'saveTimerDialogHandle', 2) checkobject(timerdialog, require('lib.stdlib.oop.timerdialog'), 'saveTimerDialogHandle', 3) --@end-debug@ return Native.SaveTimerDialogHandle(getUd(self), parentKey, childKey, getUd(timerdialog)) end ---saveLeaderboardHandle ---@param parentKey integer ---@param childKey integer ---@param leaderboard LeaderBoard ---@return boolean function Hashtable:saveLeaderboardHandle(parentKey, childKey, leaderboard) --@debug@ checkobject(self, Hashtable, 'saveLeaderboardHandle', 'self') checktype(parentKey, 'integer', 'saveLeaderboardHandle', 1) checktype(childKey, 'integer', 'saveLeaderboardHandle', 2) checkobject(leaderboard, require('lib.stdlib.oop.leaderboard'), 'saveLeaderboardHandle', 3) --@end-debug@ return Native.SaveLeaderboardHandle(getUd(self), parentKey, childKey, getUd(leaderboard)) end ---saveMultiboardHandle ---@param parentKey integer ---@param childKey integer ---@param multiboard MultiBoard ---@return boolean function Hashtable:saveMultiboardHandle(parentKey, childKey, multiboard) --@debug@ checkobject(self, Hashtable, 'saveMultiboardHandle', 'self') checktype(parentKey, 'integer', 'saveMultiboardHandle', 1) checktype(childKey, 'integer', 'saveMultiboardHandle', 2) checkobject(multiboard, require('lib.stdlib.oop.multiboard'), 'saveMultiboardHandle', 3) --@end-debug@ return Native.SaveMultiboardHandle(getUd(self), parentKey, childKey, getUd(multiboard)) end ---saveMultiboardItemHandle ---@param parentKey integer ---@param childKey integer ---@param multiboarditem MultiBoardItem ---@return boolean function Hashtable:saveMultiboardItemHandle(parentKey, childKey, multiboarditem) --@debug@ checkobject(self, Hashtable, 'saveMultiboardItemHandle', 'self') checktype(parentKey, 'integer', 'saveMultiboardItemHandle', 1) checktype(childKey, 'integer', 'saveMultiboardItemHandle', 2) checkobject(multiboarditem, require('lib.stdlib.oop.multiboarditem'), 'saveMultiboardItemHandle', 3) --@end-debug@ return Native.SaveMultiboardItemHandle(getUd(self), parentKey, childKey, getUd(multiboarditem)) end ---saveTrackableHandle ---@param parentKey integer ---@param childKey integer ---@param trackable Trackable ---@return boolean function Hashtable:saveTrackableHandle(parentKey, childKey, trackable) --@debug@ checkobject(self, Hashtable, 'saveTrackableHandle', 'self') checktype(parentKey, 'integer', 'saveTrackableHandle', 1) checktype(childKey, 'integer', 'saveTrackableHandle', 2) checkobject(trackable, require('lib.stdlib.oop.trackable'), 'saveTrackableHandle', 3) --@end-debug@ return Native.SaveTrackableHandle(getUd(self), parentKey, childKey, getUd(trackable)) end ---saveDialogHandle ---@param parentKey integer ---@param childKey integer ---@param dialog Dialog ---@return boolean function Hashtable:saveDialogHandle(parentKey, childKey, dialog) --@debug@ checkobject(self, Hashtable, 'saveDialogHandle', 'self') checktype(parentKey, 'integer', 'saveDialogHandle', 1) checktype(childKey, 'integer', 'saveDialogHandle', 2) checkobject(dialog, require('lib.stdlib.oop.dialog'), 'saveDialogHandle', 3) --@end-debug@ return Native.SaveDialogHandle(getUd(self), parentKey, childKey, getUd(dialog)) end ---saveButtonHandle ---@param parentKey integer ---@param childKey integer ---@param button Button ---@return boolean function Hashtable:saveButtonHandle(parentKey, childKey, button) --@debug@ checkobject(self, Hashtable, 'saveButtonHandle', 'self') checktype(parentKey, 'integer', 'saveButtonHandle', 1) checktype(childKey, 'integer', 'saveButtonHandle', 2) checkobject(button, require('lib.stdlib.oop.button'), 'saveButtonHandle', 3) --@end-debug@ return Native.SaveButtonHandle(getUd(self), parentKey, childKey, getUd(button)) end ---saveTextTagHandle ---@param parentKey integer ---@param childKey integer ---@param texttag TextTag ---@return boolean function Hashtable:saveTextTagHandle(parentKey, childKey, texttag) --@debug@ checkobject(self, Hashtable, 'saveTextTagHandle', 'self') checktype(parentKey, 'integer', 'saveTextTagHandle', 1) checktype(childKey, 'integer', 'saveTextTagHandle', 2) checkobject(texttag, require('lib.stdlib.oop.texttag'), 'saveTextTagHandle', 3) --@end-debug@ return Native.SaveTextTagHandle(getUd(self), parentKey, childKey, getUd(texttag)) end ---saveLightningHandle ---@param parentKey integer ---@param childKey integer ---@param lightning Lightning ---@return boolean function Hashtable:saveLightningHandle(parentKey, childKey, lightning) --@debug@ checkobject(self, Hashtable, 'saveLightningHandle', 'self') checktype(parentKey, 'integer', 'saveLightningHandle', 1) checktype(childKey, 'integer', 'saveLightningHandle', 2) checkobject(lightning, require('lib.stdlib.oop.lightning'), 'saveLightningHandle', 3) --@end-debug@ return Native.SaveLightningHandle(getUd(self), parentKey, childKey, getUd(lightning)) end ---saveImageHandle ---@param parentKey integer ---@param childKey integer ---@param image Image ---@return boolean function Hashtable:saveImageHandle(parentKey, childKey, image) --@debug@ checkobject(self, Hashtable, 'saveImageHandle', 'self') checktype(parentKey, 'integer', 'saveImageHandle', 1) checktype(childKey, 'integer', 'saveImageHandle', 2) checkobject(image, require('lib.stdlib.oop.image'), 'saveImageHandle', 3) --@end-debug@ return Native.SaveImageHandle(getUd(self), parentKey, childKey, getUd(image)) end ---saveUbersplatHandle ---@param parentKey integer ---@param childKey integer ---@param ubersplat Ubersplat ---@return boolean function Hashtable:saveUbersplatHandle(parentKey, childKey, ubersplat) --@debug@ checkobject(self, Hashtable, 'saveUbersplatHandle', 'self') checktype(parentKey, 'integer', 'saveUbersplatHandle', 1) checktype(childKey, 'integer', 'saveUbersplatHandle', 2) checkobject(ubersplat, require('lib.stdlib.oop.ubersplat'), 'saveUbersplatHandle', 3) --@end-debug@ return Native.SaveUbersplatHandle(getUd(self), parentKey, childKey, getUd(ubersplat)) end ---saveRegionHandle ---@param parentKey integer ---@param childKey integer ---@param region Region ---@return boolean function Hashtable:saveRegionHandle(parentKey, childKey, region) --@debug@ checkobject(self, Hashtable, 'saveRegionHandle', 'self') checktype(parentKey, 'integer', 'saveRegionHandle', 1) checktype(childKey, 'integer', 'saveRegionHandle', 2) checkobject(region, require('lib.stdlib.oop.region'), 'saveRegionHandle', 3) --@end-debug@ return Native.SaveRegionHandle(getUd(self), parentKey, childKey, getUd(region)) end ---saveFogStateHandle ---@param parentKey integer ---@param childKey integer ---@param fogState FogState ---@return boolean function Hashtable:saveFogStateHandle(parentKey, childKey, fogState) --@debug@ checkobject(self, Hashtable, 'saveFogStateHandle', 'self') checktype(parentKey, 'integer', 'saveFogStateHandle', 1) checktype(childKey, 'integer', 'saveFogStateHandle', 2) checkuserdata(fogState, 'fogstate', 'saveFogStateHandle', 3) --@end-debug@ return Native.SaveFogStateHandle(getUd(self), parentKey, childKey, fogState) end ---saveFogModifierHandle ---@param parentKey integer ---@param childKey integer ---@param fogModifier FogModifier ---@return boolean function Hashtable:saveFogModifierHandle(parentKey, childKey, fogModifier) --@debug@ checkobject(self, Hashtable, 'saveFogModifierHandle', 'self') checktype(parentKey, 'integer', 'saveFogModifierHandle', 1) checktype(childKey, 'integer', 'saveFogModifierHandle', 2) checkobject(fogModifier, require('lib.stdlib.oop.fogmodifier'), 'saveFogModifierHandle', 3) --@end-debug@ return Native.SaveFogModifierHandle(getUd(self), parentKey, childKey, getUd(fogModifier)) end ---saveAgentHandle ---@param parentKey integer ---@param childKey integer ---@param agent Agent ---@return boolean function Hashtable:saveAgentHandle(parentKey, childKey, agent) --@debug@ checkobject(self, Hashtable, 'saveAgentHandle', 'self') checktype(parentKey, 'integer', 'saveAgentHandle', 1) checktype(childKey, 'integer', 'saveAgentHandle', 2) checkobject(agent, require('lib.stdlib.oop.agent'), 'saveAgentHandle', 3) --@end-debug@ return Native.SaveAgentHandle(getUd(self), parentKey, childKey, getUd(agent)) end ---saveHashtableHandle ---@param parentKey integer ---@param childKey integer ---@param hashtable Hashtable ---@return boolean function Hashtable:saveHashtableHandle(parentKey, childKey, hashtable) --@debug@ checkobject(self, Hashtable, 'saveHashtableHandle', 'self') checktype(parentKey, 'integer', 'saveHashtableHandle', 1) checktype(childKey, 'integer', 'saveHashtableHandle', 2) checkobject(hashtable, require('lib.stdlib.oop.hashtable'), 'saveHashtableHandle', 3) --@end-debug@ return Native.SaveHashtableHandle(getUd(self), parentKey, childKey, getUd(hashtable)) end ---saveFrameHandle ---@param parentKey integer ---@param childKey integer ---@param frameHandle Frame ---@return boolean function Hashtable:saveFrameHandle(parentKey, childKey, frameHandle) --@debug@ checkobject(self, Hashtable, 'saveFrameHandle', 'self') checktype(parentKey, 'integer', 'saveFrameHandle', 1) checktype(childKey, 'integer', 'saveFrameHandle', 2) checkobject(frameHandle, require('lib.stdlib.oop.frame'), 'saveFrameHandle', 3) --@end-debug@ return Native.SaveFrameHandle(getUd(self), parentKey, childKey, getUd(frameHandle)) end ---loadInteger ---@param parentKey integer ---@param childKey integer ---@return integer function Hashtable:loadInteger(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadInteger', 'self') checktype(parentKey, 'integer', 'loadInteger', 1) checktype(childKey, 'integer', 'loadInteger', 2) --@end-debug@ return Native.LoadInteger(getUd(self), parentKey, childKey) end ---loadReal ---@param parentKey integer ---@param childKey integer ---@return float function Hashtable:loadReal(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadReal', 'self') checktype(parentKey, 'integer', 'loadReal', 1) checktype(childKey, 'integer', 'loadReal', 2) --@end-debug@ return Native.LoadReal(getUd(self), parentKey, childKey) end ---loadBoolean ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:loadBoolean(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadBoolean', 'self') checktype(parentKey, 'integer', 'loadBoolean', 1) checktype(childKey, 'integer', 'loadBoolean', 2) --@end-debug@ return Native.LoadBoolean(getUd(self), parentKey, childKey) end ---loadStr ---@param parentKey integer ---@param childKey integer ---@return string function Hashtable:loadStr(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadStr', 'self') checktype(parentKey, 'integer', 'loadStr', 1) checktype(childKey, 'integer', 'loadStr', 2) --@end-debug@ return Native.LoadStr(getUd(self), parentKey, childKey) end ---loadPlayerHandle ---@param parentKey integer ---@param childKey integer ---@return Player function Hashtable:loadPlayerHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadPlayerHandle', 'self') checktype(parentKey, 'integer', 'loadPlayerHandle', 1) checktype(childKey, 'integer', 'loadPlayerHandle', 2) --@end-debug@ return require('lib.stdlib.oop.player'):fromUd(Native.LoadPlayerHandle(getUd(self), parentKey, childKey)) end ---loadWidgetHandle ---@param parentKey integer ---@param childKey integer ---@return Widget function Hashtable:loadWidgetHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadWidgetHandle', 'self') checktype(parentKey, 'integer', 'loadWidgetHandle', 1) checktype(childKey, 'integer', 'loadWidgetHandle', 2) --@end-debug@ return require('lib.stdlib.oop.widget'):fromUd(Native.LoadWidgetHandle(getUd(self), parentKey, childKey)) end ---loadDestructableHandle ---@param parentKey integer ---@param childKey integer ---@return Destructable function Hashtable:loadDestructableHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadDestructableHandle', 'self') checktype(parentKey, 'integer', 'loadDestructableHandle', 1) checktype(childKey, 'integer', 'loadDestructableHandle', 2) --@end-debug@ return require('lib.stdlib.oop.destructable'):fromUd(Native.LoadDestructableHandle(getUd(self), parentKey, childKey)) end ---loadItemHandle ---@param parentKey integer ---@param childKey integer ---@return Item function Hashtable:loadItemHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadItemHandle', 'self') checktype(parentKey, 'integer', 'loadItemHandle', 1) checktype(childKey, 'integer', 'loadItemHandle', 2) --@end-debug@ return require('lib.stdlib.oop.item'):fromUd(Native.LoadItemHandle(getUd(self), parentKey, childKey)) end ---loadUnitHandle ---@param parentKey integer ---@param childKey integer ---@return Unit function Hashtable:loadUnitHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadUnitHandle', 'self') checktype(parentKey, 'integer', 'loadUnitHandle', 1) checktype(childKey, 'integer', 'loadUnitHandle', 2) --@end-debug@ return require('lib.stdlib.oop.unit'):fromUd(Native.LoadUnitHandle(getUd(self), parentKey, childKey)) end ---loadAbilityHandle ---@param parentKey integer ---@param childKey integer ---@return Ability function Hashtable:loadAbilityHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadAbilityHandle', 'self') checktype(parentKey, 'integer', 'loadAbilityHandle', 1) checktype(childKey, 'integer', 'loadAbilityHandle', 2) --@end-debug@ return require('lib.stdlib.oop.ability'):fromUd(Native.LoadAbilityHandle(getUd(self), parentKey, childKey)) end ---loadTimerHandle ---@param parentKey integer ---@param childKey integer ---@return Timer function Hashtable:loadTimerHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTimerHandle', 'self') checktype(parentKey, 'integer', 'loadTimerHandle', 1) checktype(childKey, 'integer', 'loadTimerHandle', 2) --@end-debug@ return require('lib.stdlib.oop.timer'):fromUd(Native.LoadTimerHandle(getUd(self), parentKey, childKey)) end ---loadTriggerHandle ---@param parentKey integer ---@param childKey integer ---@return Trigger function Hashtable:loadTriggerHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTriggerHandle', 'self') checktype(parentKey, 'integer', 'loadTriggerHandle', 1) checktype(childKey, 'integer', 'loadTriggerHandle', 2) --@end-debug@ return require('lib.stdlib.oop.trigger'):fromUd(Native.LoadTriggerHandle(getUd(self), parentKey, childKey)) end ---loadTriggerConditionHandle ---@param parentKey integer ---@param childKey integer ---@return TriggerCondition function Hashtable:loadTriggerConditionHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTriggerConditionHandle', 'self') checktype(parentKey, 'integer', 'loadTriggerConditionHandle', 1) checktype(childKey, 'integer', 'loadTriggerConditionHandle', 2) --@end-debug@ return require('lib.stdlib.oop.triggercondition'):fromUd(Native.LoadTriggerConditionHandle(getUd(self), parentKey, childKey)) end ---loadTriggerActionHandle ---@param parentKey integer ---@param childKey integer ---@return TriggerAction function Hashtable:loadTriggerActionHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTriggerActionHandle', 'self') checktype(parentKey, 'integer', 'loadTriggerActionHandle', 1) checktype(childKey, 'integer', 'loadTriggerActionHandle', 2) --@end-debug@ return Native.LoadTriggerActionHandle(getUd(self), parentKey, childKey) end ---loadTriggerEventHandle ---@param parentKey integer ---@param childKey integer ---@return Event function Hashtable:loadTriggerEventHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTriggerEventHandle', 'self') checktype(parentKey, 'integer', 'loadTriggerEventHandle', 1) checktype(childKey, 'integer', 'loadTriggerEventHandle', 2) --@end-debug@ return require('lib.stdlib.oop.event'):fromUd(Native.LoadTriggerEventHandle(getUd(self), parentKey, childKey)) end ---loadForceHandle ---@param parentKey integer ---@param childKey integer ---@return Force function Hashtable:loadForceHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadForceHandle', 'self') checktype(parentKey, 'integer', 'loadForceHandle', 1) checktype(childKey, 'integer', 'loadForceHandle', 2) --@end-debug@ return require('lib.stdlib.oop.force'):fromUd(Native.LoadForceHandle(getUd(self), parentKey, childKey)) end ---loadGroupHandle ---@param parentKey integer ---@param childKey integer ---@return Group function Hashtable:loadGroupHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadGroupHandle', 'self') checktype(parentKey, 'integer', 'loadGroupHandle', 1) checktype(childKey, 'integer', 'loadGroupHandle', 2) --@end-debug@ return require('lib.stdlib.oop.group'):fromUd(Native.LoadGroupHandle(getUd(self), parentKey, childKey)) end ---loadLocationHandle ---@param parentKey integer ---@param childKey integer ---@return Location function Hashtable:loadLocationHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadLocationHandle', 'self') checktype(parentKey, 'integer', 'loadLocationHandle', 1) checktype(childKey, 'integer', 'loadLocationHandle', 2) --@end-debug@ return require('lib.stdlib.oop.location'):fromUd(Native.LoadLocationHandle(getUd(self), parentKey, childKey)) end ---loadRectHandle ---@param parentKey integer ---@param childKey integer ---@return Rect function Hashtable:loadRectHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadRectHandle', 'self') checktype(parentKey, 'integer', 'loadRectHandle', 1) checktype(childKey, 'integer', 'loadRectHandle', 2) --@end-debug@ return require('lib.stdlib.oop.rect'):fromUd(Native.LoadRectHandle(getUd(self), parentKey, childKey)) end ---loadBooleanExprHandle ---@param parentKey integer ---@param childKey integer ---@return BoolExpr function Hashtable:loadBooleanExprHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadBooleanExprHandle', 'self') checktype(parentKey, 'integer', 'loadBooleanExprHandle', 1) checktype(childKey, 'integer', 'loadBooleanExprHandle', 2) --@end-debug@ return require('lib.stdlib.oop.boolexpr'):fromUd(Native.LoadBooleanExprHandle(getUd(self), parentKey, childKey)) end ---loadSoundHandle ---@param parentKey integer ---@param childKey integer ---@return Sound function Hashtable:loadSoundHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadSoundHandle', 'self') checktype(parentKey, 'integer', 'loadSoundHandle', 1) checktype(childKey, 'integer', 'loadSoundHandle', 2) --@end-debug@ return require('lib.stdlib.oop.sound'):fromUd(Native.LoadSoundHandle(getUd(self), parentKey, childKey)) end ---loadEffectHandle ---@param parentKey integer ---@param childKey integer ---@return Effect function Hashtable:loadEffectHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadEffectHandle', 'self') checktype(parentKey, 'integer', 'loadEffectHandle', 1) checktype(childKey, 'integer', 'loadEffectHandle', 2) --@end-debug@ return require('lib.stdlib.oop.effect'):fromUd(Native.LoadEffectHandle(getUd(self), parentKey, childKey)) end ---loadUnitPoolHandle ---@param parentKey integer ---@param childKey integer ---@return UnitPool function Hashtable:loadUnitPoolHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadUnitPoolHandle', 'self') checktype(parentKey, 'integer', 'loadUnitPoolHandle', 1) checktype(childKey, 'integer', 'loadUnitPoolHandle', 2) --@end-debug@ return require('lib.stdlib.oop.unitpool'):fromUd(Native.LoadUnitPoolHandle(getUd(self), parentKey, childKey)) end ---loadItemPoolHandle ---@param parentKey integer ---@param childKey integer ---@return ItemPool function Hashtable:loadItemPoolHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadItemPoolHandle', 'self') checktype(parentKey, 'integer', 'loadItemPoolHandle', 1) checktype(childKey, 'integer', 'loadItemPoolHandle', 2) --@end-debug@ return require('lib.stdlib.oop.itempool'):fromUd(Native.LoadItemPoolHandle(getUd(self), parentKey, childKey)) end ---loadQuestHandle ---@param parentKey integer ---@param childKey integer ---@return Quest function Hashtable:loadQuestHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadQuestHandle', 'self') checktype(parentKey, 'integer', 'loadQuestHandle', 1) checktype(childKey, 'integer', 'loadQuestHandle', 2) --@end-debug@ return require('lib.stdlib.oop.quest'):fromUd(Native.LoadQuestHandle(getUd(self), parentKey, childKey)) end ---loadQuestItemHandle ---@param parentKey integer ---@param childKey integer ---@return QuestItem function Hashtable:loadQuestItemHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadQuestItemHandle', 'self') checktype(parentKey, 'integer', 'loadQuestItemHandle', 1) checktype(childKey, 'integer', 'loadQuestItemHandle', 2) --@end-debug@ return require('lib.stdlib.oop.questitem'):fromUd(Native.LoadQuestItemHandle(getUd(self), parentKey, childKey)) end ---loadDefeatConditionHandle ---@param parentKey integer ---@param childKey integer ---@return DefeatCondition function Hashtable:loadDefeatConditionHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadDefeatConditionHandle', 'self') checktype(parentKey, 'integer', 'loadDefeatConditionHandle', 1) checktype(childKey, 'integer', 'loadDefeatConditionHandle', 2) --@end-debug@ return require('lib.stdlib.oop.defeatcondition'):fromUd(Native.LoadDefeatConditionHandle(getUd(self), parentKey, childKey)) end ---loadTimerDialogHandle ---@param parentKey integer ---@param childKey integer ---@return TimerDialog function Hashtable:loadTimerDialogHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTimerDialogHandle', 'self') checktype(parentKey, 'integer', 'loadTimerDialogHandle', 1) checktype(childKey, 'integer', 'loadTimerDialogHandle', 2) --@end-debug@ return require('lib.stdlib.oop.timerdialog'):fromUd(Native.LoadTimerDialogHandle(getUd(self), parentKey, childKey)) end ---loadLeaderboardHandle ---@param parentKey integer ---@param childKey integer ---@return LeaderBoard function Hashtable:loadLeaderboardHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadLeaderboardHandle', 'self') checktype(parentKey, 'integer', 'loadLeaderboardHandle', 1) checktype(childKey, 'integer', 'loadLeaderboardHandle', 2) --@end-debug@ return require('lib.stdlib.oop.leaderboard'):fromUd(Native.LoadLeaderboardHandle(getUd(self), parentKey, childKey)) end ---loadMultiboardHandle ---@param parentKey integer ---@param childKey integer ---@return MultiBoard function Hashtable:loadMultiboardHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadMultiboardHandle', 'self') checktype(parentKey, 'integer', 'loadMultiboardHandle', 1) checktype(childKey, 'integer', 'loadMultiboardHandle', 2) --@end-debug@ return require('lib.stdlib.oop.multiboard'):fromUd(Native.LoadMultiboardHandle(getUd(self), parentKey, childKey)) end ---loadMultiboardItemHandle ---@param parentKey integer ---@param childKey integer ---@return MultiBoardItem function Hashtable:loadMultiboardItemHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadMultiboardItemHandle', 'self') checktype(parentKey, 'integer', 'loadMultiboardItemHandle', 1) checktype(childKey, 'integer', 'loadMultiboardItemHandle', 2) --@end-debug@ return require('lib.stdlib.oop.multiboarditem'):fromUd(Native.LoadMultiboardItemHandle(getUd(self), parentKey, childKey)) end ---loadTrackableHandle ---@param parentKey integer ---@param childKey integer ---@return Trackable function Hashtable:loadTrackableHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTrackableHandle', 'self') checktype(parentKey, 'integer', 'loadTrackableHandle', 1) checktype(childKey, 'integer', 'loadTrackableHandle', 2) --@end-debug@ return require('lib.stdlib.oop.trackable'):fromUd(Native.LoadTrackableHandle(getUd(self), parentKey, childKey)) end ---loadDialogHandle ---@param parentKey integer ---@param childKey integer ---@return Dialog function Hashtable:loadDialogHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadDialogHandle', 'self') checktype(parentKey, 'integer', 'loadDialogHandle', 1) checktype(childKey, 'integer', 'loadDialogHandle', 2) --@end-debug@ return require('lib.stdlib.oop.dialog'):fromUd(Native.LoadDialogHandle(getUd(self), parentKey, childKey)) end ---loadButtonHandle ---@param parentKey integer ---@param childKey integer ---@return Button function Hashtable:loadButtonHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadButtonHandle', 'self') checktype(parentKey, 'integer', 'loadButtonHandle', 1) checktype(childKey, 'integer', 'loadButtonHandle', 2) --@end-debug@ return require('lib.stdlib.oop.button'):fromUd(Native.LoadButtonHandle(getUd(self), parentKey, childKey)) end ---loadTextTagHandle ---@param parentKey integer ---@param childKey integer ---@return TextTag function Hashtable:loadTextTagHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadTextTagHandle', 'self') checktype(parentKey, 'integer', 'loadTextTagHandle', 1) checktype(childKey, 'integer', 'loadTextTagHandle', 2) --@end-debug@ return require('lib.stdlib.oop.texttag'):fromUd(Native.LoadTextTagHandle(getUd(self), parentKey, childKey)) end ---loadLightningHandle ---@param parentKey integer ---@param childKey integer ---@return Lightning function Hashtable:loadLightningHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadLightningHandle', 'self') checktype(parentKey, 'integer', 'loadLightningHandle', 1) checktype(childKey, 'integer', 'loadLightningHandle', 2) --@end-debug@ return require('lib.stdlib.oop.lightning'):fromUd(Native.LoadLightningHandle(getUd(self), parentKey, childKey)) end ---loadImageHandle ---@param parentKey integer ---@param childKey integer ---@return Image function Hashtable:loadImageHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadImageHandle', 'self') checktype(parentKey, 'integer', 'loadImageHandle', 1) checktype(childKey, 'integer', 'loadImageHandle', 2) --@end-debug@ return require('lib.stdlib.oop.image'):fromUd(Native.LoadImageHandle(getUd(self), parentKey, childKey)) end ---loadUbersplatHandle ---@param parentKey integer ---@param childKey integer ---@return Ubersplat function Hashtable:loadUbersplatHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadUbersplatHandle', 'self') checktype(parentKey, 'integer', 'loadUbersplatHandle', 1) checktype(childKey, 'integer', 'loadUbersplatHandle', 2) --@end-debug@ return require('lib.stdlib.oop.ubersplat'):fromUd(Native.LoadUbersplatHandle(getUd(self), parentKey, childKey)) end ---loadRegionHandle ---@param parentKey integer ---@param childKey integer ---@return Region function Hashtable:loadRegionHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadRegionHandle', 'self') checktype(parentKey, 'integer', 'loadRegionHandle', 1) checktype(childKey, 'integer', 'loadRegionHandle', 2) --@end-debug@ return require('lib.stdlib.oop.region'):fromUd(Native.LoadRegionHandle(getUd(self), parentKey, childKey)) end ---loadFogStateHandle ---@param parentKey integer ---@param childKey integer ---@return FogState function Hashtable:loadFogStateHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadFogStateHandle', 'self') checktype(parentKey, 'integer', 'loadFogStateHandle', 1) checktype(childKey, 'integer', 'loadFogStateHandle', 2) --@end-debug@ return Native.LoadFogStateHandle(getUd(self), parentKey, childKey) end ---loadFogModifierHandle ---@param parentKey integer ---@param childKey integer ---@return FogModifier function Hashtable:loadFogModifierHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadFogModifierHandle', 'self') checktype(parentKey, 'integer', 'loadFogModifierHandle', 1) checktype(childKey, 'integer', 'loadFogModifierHandle', 2) --@end-debug@ return require('lib.stdlib.oop.fogmodifier'):fromUd(Native.LoadFogModifierHandle(getUd(self), parentKey, childKey)) end ---loadHandle ---@param parentKey integer ---@param childKey integer ---@return Hashtable function Hashtable:loadHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadHandle', 'self') checktype(parentKey, 'integer', 'loadHandle', 1) checktype(childKey, 'integer', 'loadHandle', 2) --@end-debug@ return Hashtable:fromUd(Native.LoadHashtableHandle(getUd(self), parentKey, childKey)) end ---loadFrameHandle ---@param parentKey integer ---@param childKey integer ---@return Frame function Hashtable:loadFrameHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'loadFrameHandle', 'self') checktype(parentKey, 'integer', 'loadFrameHandle', 1) checktype(childKey, 'integer', 'loadFrameHandle', 2) --@end-debug@ return require('lib.stdlib.oop.frame'):fromUd(Native.LoadFrameHandle(getUd(self), parentKey, childKey)) end ---haveSavedInteger ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedInteger(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'haveSavedInteger', 'self') checktype(parentKey, 'integer', 'haveSavedInteger', 1) checktype(childKey, 'integer', 'haveSavedInteger', 2) --@end-debug@ return Native.HaveSavedInteger(getUd(self), parentKey, childKey) end ---haveSavedReal ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedReal(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'haveSavedReal', 'self') checktype(parentKey, 'integer', 'haveSavedReal', 1) checktype(childKey, 'integer', 'haveSavedReal', 2) --@end-debug@ return Native.HaveSavedReal(getUd(self), parentKey, childKey) end ---haveSavedBoolean ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedBoolean(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'haveSavedBoolean', 'self') checktype(parentKey, 'integer', 'haveSavedBoolean', 1) checktype(childKey, 'integer', 'haveSavedBoolean', 2) --@end-debug@ return Native.HaveSavedBoolean(getUd(self), parentKey, childKey) end ---haveSavedString ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedString(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'haveSavedString', 'self') checktype(parentKey, 'integer', 'haveSavedString', 1) checktype(childKey, 'integer', 'haveSavedString', 2) --@end-debug@ return Native.HaveSavedString(getUd(self), parentKey, childKey) end ---haveSavedHandle ---@param parentKey integer ---@param childKey integer ---@return boolean function Hashtable:haveSavedHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'haveSavedHandle', 'self') checktype(parentKey, 'integer', 'haveSavedHandle', 1) checktype(childKey, 'integer', 'haveSavedHandle', 2) --@end-debug@ return Native.HaveSavedHandle(getUd(self), parentKey, childKey) end ---removeSavedInteger ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedInteger(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'removeSavedInteger', 'self') checktype(parentKey, 'integer', 'removeSavedInteger', 1) checktype(childKey, 'integer', 'removeSavedInteger', 2) --@end-debug@ return Native.RemoveSavedInteger(getUd(self), parentKey, childKey) end ---removeSavedReal ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedReal(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'removeSavedReal', 'self') checktype(parentKey, 'integer', 'removeSavedReal', 1) checktype(childKey, 'integer', 'removeSavedReal', 2) --@end-debug@ return Native.RemoveSavedReal(getUd(self), parentKey, childKey) end ---removeSavedBoolean ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedBoolean(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'removeSavedBoolean', 'self') checktype(parentKey, 'integer', 'removeSavedBoolean', 1) checktype(childKey, 'integer', 'removeSavedBoolean', 2) --@end-debug@ return Native.RemoveSavedBoolean(getUd(self), parentKey, childKey) end ---removeSavedString ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedString(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'removeSavedString', 'self') checktype(parentKey, 'integer', 'removeSavedString', 1) checktype(childKey, 'integer', 'removeSavedString', 2) --@end-debug@ return Native.RemoveSavedString(getUd(self), parentKey, childKey) end ---removeSavedHandle ---@param parentKey integer ---@param childKey integer ---@return void function Hashtable:removeSavedHandle(parentKey, childKey) --@debug@ checkobject(self, Hashtable, 'removeSavedHandle', 'self') checktype(parentKey, 'integer', 'removeSavedHandle', 1) checktype(childKey, 'integer', 'removeSavedHandle', 2) --@end-debug@ return Native.RemoveSavedHandle(getUd(self), parentKey, childKey) end ---flushParent ---@return void function Hashtable:flushParent() --@debug@ checkobject(self, Hashtable, 'flushParent', 'self') --@end-debug@ return Native.FlushParentHashtable(getUd(self)) end ---flushChild ---@param parentKey integer ---@return void function Hashtable:flushChild(parentKey) --@debug@ checkobject(self, Hashtable, 'flushChild', 'self') checktype(parentKey, 'integer', 'flushChild', 1) --@end-debug@ return Native.FlushChildHashtable(getUd(self), parentKey) end return Hashtable
local Class = require 'class' local Window = require 'window.window' local Menubar = Class({ __includes = Window}) function Menubar:draw() Window.draw(self) local x = 1 for _,v in pairs(self.items) do self:printat(x,0,v.name) x = x + #v.name + 3 end end function Menubar:mouseDown(mx,my) local x = 1 for _,v in pairs(self.items) do local l = #v.name if mx >= x and mx <= x+l then v.action(self) break end x = x + l + 3 end end return Menubar
require("neogen").setup({ enabled = true, languages = { python = { template = { annotation_convention = "numpydoc", }, }, }, })
local FS = require("fs") local Json = require("json") local Path = require("path") local Logger = require("Logger") local FetchPackage = require("LIT/FetchPackage") return function(PackagePath, Log, IsMain) local FilePos = PackagePath -- Path.normalize(PackagePath) local FileBase = Path.basename(FilePos) local Extension = Path.extname(FileBase) local Exists = FS.existsSync(FilePos) local CorrectExtension = Extension == ".dua" Logger.Debug("Trying to load file " .. FilePos) Logger.Debug("File name is: " .. FileBase) Logger.Debug("Is Correct Extension: " .. tostring(CorrectExtension)) Logger.Debug("Extension: '" .. (Extension or "") .. "'") Logger.Debug("Exists: " .. tostring(Exists)) if not Exists or not Extension then Logger.Error("'" .. FileBase .. "' is not a valid DUA archive!") process:exit(1) end local DuaData = FS.readFileSync(FilePos) local UnpackedData = Json.decode(DuaData) local PackageInfo = UnpackedData.PackageInfo for Index, Dep in pairs(PackageInfo.Dependencies.Luvit) do FetchPackage(Dep) end LoadedPackages[PackageInfo.ID] = UnpackedData if IsMain then _G.ProcessInfo = PackageInfo end if PackageInfo.Entrypoints.OnLoad then Logger.Debug("Loading entrypoint Onload from " .. PackageInfo.Name) Import(PackageInfo.Entrypoints.OnLoad) end return PackageInfo end
-- https://wiki.navercorp.com/display/LFS/AnimationKit -- Update Date : 210401 -- Writer : June Kim --[[ Reference - https://wiki.navercorp.com/display/LFS/Property+Animation - https://wiki.navercorp.com/display/LFS/Kuru+Features#KuruFeatures-KuruScene.getSnapshotNodeOfScene,StickerConfig::getFirstScene(),MultilineValue ]] AnimationType = { Scale = "Scale", Rotate = "Rotate", Translate = "Translate", Alpha = "Alpha" } AnimateObject = {} function AnimateObject:create(paramNode) local newObject = {} setmetatable(newObject, self) self.__index = self newObject.AnimationItems = {} newObject.Clips = {} newObject.TargetNode = paramNode return newObject end function AnimateObject:setAnimationItem(animationType, item) self.AnimationItems[animationType] = item return self end function AnimateObject:build() local animTypes = { [AnimationType.Scale] = TransformAnimationType.ANIMATE_SCALE_UNIT, [AnimationType.Rotate] = TransformAnimationType.ANIMATE_ROTATE, [AnimationType.Translate] = TransformAnimationType.ANIMATE_TRANSLATE, [AnimationType.Alpha] = MaterialParameterAnimationType.ANIMATE_UNIFORM } for type, item in pairs(self.AnimationItems) do local keyTimes = {} local keyValues = {} for i, v in ipairs(item) do keyTimes[i] = v.keyTime keyValues[i] = v.keyValue end local curves = {} for i=2, #item do --curve는 item의 index 2부터 적용 if item[i].curveType ~= nil then curves[i-1] = item[i].curveType else curves[i-1] = CurveInterpolationType.LINEAR end end keyTimes = IntArray.create():setFromLuaArray(keyTimes) keyValues = self:convertKeyValues(type, keyValues) --AnimationType별로 KeyValue 전처리가 필요함 curves = IntArray.create():setFromLuaArray(curves) local animation = nil local animationTarget = nil if type == AnimationType.Alpha then self.TargetNode:getQuadMeshModel():getDefaultMaterial():getParameter("u_modulateAlpha"):setFloat(1.0) self.TargetNode:getQuadMeshModel():getDefaultMaterial():getParameter("u_modulateAlpha").isUpdatableByOnlyAnimation = true animationTarget = self.TargetNode:getQuadMeshModel():getDefaultMaterial():getParameter("u_modulateAlpha") else animationTarget = self.TargetNode end --MultiCurve를 사용할 수 도 있기때문에, Curve 유무에 따라 분기 if curves:size() > 0 then animation = animationTarget:createAnimationWithCurves( type, animTypes[type], keyTimes:size(), keyTimes:getAsUnsigned(), keyValues:get(), curves:getAsUnsigned() ) else animation = animationTarget:createAnimation( type, animTypes[type], keyTimes:size(), keyTimes:getAsUnsigned(), keyValues:get(), CurveInterpolationType.LINEAR ) end self.Clips[type] = animation:getDefaultClip() end return self end function AnimateObject:convertKeyValues(type, keyValues) local resultsKeyValues = nil if type == AnimationType.Rotate then local axis = Vector3.create(0, 0, 1) local quaternions = {} resultsKeyValues = {} for i=1, #self.AnimationItems[AnimationType.Rotate] do quaternions[i] = Quaternion.createFromAxisAngle(axis, math.rad(keyValues[i])) table.insert(resultsKeyValues, quaternions[i].x) table.insert(resultsKeyValues, quaternions[i].y) table.insert(resultsKeyValues, quaternions[i].z) table.insert(resultsKeyValues, quaternions[i].w) end elseif type == AnimationType.Translate then resultsKeyValues = {} for i=1, #self.AnimationItems[type] do table.insert(resultsKeyValues, keyValues[i].x) table.insert(resultsKeyValues, keyValues[i].y) table.insert(resultsKeyValues, keyValues[i].z) end else --if type == AnimationType.Scale or type == AnimationType.Alpha then resultsKeyValues = keyValues end return FloatArray.create():setFromLuaArray(resultsKeyValues) end function AnimateObject:getClipByAnimationType(type) return self.Clips[type] end function AnimateObject:setRepeatCount(repeatCount) for _, clip in pairs(self.Clips) do clip:setRepeatCount(repeatCount) end end function AnimateObject:setSpeed(speed) for _, clip in pairs(self.Clips) do clip:setSpeed(speed) end end function AnimateObject:pause() for _, clip in pairs(self.Clips) do clip:pause() end end function AnimateObject:stop() for _, clip in pairs(self.Clips) do clip:stop() end end function AnimateObject:play() for _, clip in pairs(self.Clips) do clip:play() end end function AnimateObject:isPlaying() for _, clip in pairs(self.Clips) do if clip:isPlaying() then return true end end return false end
--[[ SAVE GAME local data = { _fileName = "test.txt", players } success = jupiter.save( data ) print( success ) --]] --[[ I DON'T KNOW players = {} -- load players from file -- so this looks horrible but it works so I'll change it later file ,error= io.open( "files/players.txt" ) local n = file:read() for i = 1, n do players[i] = {} local line = file:read() words = {} for i in string.gmatch( line, "%S+" ) do words[#words + 1] = i end players[i].name = words[1] players[i].keybind = {} players[i].keybind.forward = words[2] players[i].keybind.left = words[3] players[i].keybind.right = words[4] players[i].keybind.back = words[5] players[i].keybind.shoot = words[6] players[i].color = {} players[i].color.red = words[7] players[i].color.green = words[8] players[i].color.blue = words[9] players[i].score = 0 end --]] --[[ for i = 1, 10 do -- random border local border = love.math.random( 1, 4 ) local x, y = love.math.random( left, right ), love.math.random( top, down ) if( border == 1 ) then y = top end if( border == 2 ) then x = right end if( border == 3 ) then y = down end if( border == 4 ) then x = left end local turns = love.math.random( 2, 5 ) for j = 1, turns do -- generate next point local nx, ny verhol = love.math.random( 1, 2 ) if( verhol == 1 ) then nx = x ny = y + love.math.random( math.max( -60, left - x + 10 ), math.min( 60, right - x - 10 ) ) --ny = love.math.random( x -20, x + 20 ) end if( verhol == 2 ) then ny = y nx = x + love.math.random( math.max( -60, top - y + 10 ), math.min( 60, down - y - 10 ) ) end newWall( lineToRect( x, y, nx, ny, 5 ) ) x, y = nx, ny end end --]]-- fail lel
local countryName = { O1 = "Other Country", AD = "Andorra", AE = "United Arab Emirates", AF = "Afghanistan", AG = "Antigua and Barbuda", AI = "Anguilla", AL = "Albania", AM = "Armenia", AO = "Angola", AP = "Asia/Pacific Region", AQ = "Antarctica", AR = "Argentina", AS = "American Samoa", AT = "Austria", AU = "Australia", AW = "Aruba", AX = "Aland Islands", AZ = "Azerbaijan", BA = "Bosnia and Herzegovina", BB = "Barbados", BD = "Bangladesh", BE = "Belgium", BF = "Burkina Faso", BG = "Bulgaria", BH = "Bahrain", BI = "Burundi", BJ = "Benin", BL = "Saint Bartelemey", BM = "Bermuda", BN = "Brunei Darussalam", BO = "Bolivia", BQ = "Bonaire, Saint Eustatius and Saba", BR = "Brazil", BS = "Bahamas", BT = "Bhutan", BV = "Bouvet Island", BW = "Botswana", BY = "Belarus", BZ = "Belize", CA = "Canada", CC = "Cocos (Keeling) Islands", CD = "Congo, The Democratic Republic of the", CF = "Central African Republic", CG = "Congo", CH = "Switzerland", CI = "Cote d'Ivoire", CK = "Cook Islands", CL = "Chile", CM = "Cameroon", CN = "China", CO = "Colombia", CR = "Costa Rica", CU = "Cuba", CV = "Cape Verde", CW = "Curacao", CX = "Christmas Island", CY = "Cyprus", CZ = "Czech Republic", DE = "Germany", DJ = "Djibouti", DK = "Denmark", DM = "Dominica", DO = "Dominican Republic", DZ = "Algeria", EC = "Ecuador", EE = "Estonia", EG = "Egypt", EH = "Western Sahara", ER = "Eritrea", ES = "Spain", ET = "Ethiopia", EU = "Europe", FI = "Finland", FJ = "Fiji", FK = "Falkland Islands (Malvinas)", FM = "Micronesia, Federated States of", FO = "Faroe Islands", FR = "France", GA = "Gabon", GB = "United Kingdom", GD = "Grenada", GE = "Georgia", GF = "French Guiana", GG = "Guernsey", GH = "Ghana", GI = "Gibraltar", GL = "Greenland", GM = "Gambia", GN = "Guinea", GP = "Guadeloupe", GQ = "Equatorial Guinea", GR = "Greece", GS = "South Georgia and the South Sandwich Islands", GT = "Guatemala", GU = "Guam", GW = "Guinea-Bissau", GY = "Guyana", HK = "Hong Kong", HM = "Heard Island and McDonald Islands", HN = "Honduras", HR = "Croatia", HT = "Haiti", HU = "Hungary", ID = "Indonesia", IE = "Ireland", IL = "Israel", IM = "Isle of Man", IN = "India", IO = "British Indian Ocean Territory", IQ = "Iraq", IR = "Iran, Islamic Republic of", IS = "Iceland", IT = "Italy", JE = "Jersey", JM = "Jamaica", JO = "Jordan", JP = "Japan", KE = "Kenya", KG = "Kyrgyzstan", KH = "Cambodia", KI = "Kiribati", KM = "Comoros", KN = "Saint Kitts and Nevis", KP = "Korea, Democratic People's Republic of", KR = "Korea, Republic of", KW = "Kuwait", KY = "Cayman Islands", KZ = "Kazakhstan", LA = "Lao People's Democratic Republic", LB = "Lebanon", LC = "Saint Lucia", LI = "Liechtenstein", LK = "Sri Lanka", LR = "Liberia", LS = "Lesotho", LT = "Lithuania", LU = "Luxembourg", LV = "Latvia", LY = "Libyan Arab Jamahiriya", MA = "Morocco", MC = "Monaco", MD = "Moldova, Republic of", ME = "Montenegro", MF = "Saint Martin", MG = "Madagascar", MH = "Marshall Islands", MK = "Macedonia", ML = "Mali", MM = "Myanmar", MN = "Mongolia", MO = "Macao", MP = "Northern Mariana Islands", MQ = "Martinique", MR = "Mauritania", MS = "Montserrat", MT = "Malta", MU = "Mauritius", MV = "Maldives", MW = "Malawi", MX = "Mexico", MY = "Malaysia", MZ = "Mozambique", NA = "Namibia", NC = "New Caledonia", NE = "Niger", NF = "Norfolk Island", NG = "Nigeria", NI = "Nicaragua", NL = "Netherlands", NO = "Norway", NP = "Nepal", NR = "Nauru", NU = "Niue", NZ = "New Zealand", OM = "Oman", PA = "Panama", PE = "Peru", PF = "French Polynesia", PG = "Papua New Guinea", PH = "Philippines", PK = "Pakistan", PL = "Poland", PM = "Saint Pierre and Miquelon", PN = "Pitcairn", PR = "Puerto Rico", PS = "Palestinian Territory", PT = "Portugal", PW = "Palau", PY = "Paraguay", QA = "Qatar", RE = "Reunion", RO = "Romania", RS = "Serbia", RU = "Russian Federation", RW = "Rwanda", SA = "Saudi Arabia", SB = "Solomon Islands", SC = "Seychelles", SD = "Sudan", SE = "Sweden", SG = "Singapore", SH = "Saint Helena", SI = "Slovenia", SJ = "Svalbard and Jan Mayen", SK = "Slovakia", SL = "Sierra Leone", SM = "San Marino", SN = "Senegal", SO = "Somalia", SR = "Suriname", ST = "Sao Tome and Principe", SV = "El Salvador", SX = "Sint Maarten", SY = "Syrian Arab Republic", SZ = "Swaziland", TC = "Turks and Caicos Islands", TD = "Chad", TF = "French Southern Territories", TG = "Togo", TH = "Thailand", TJ = "Tajikistan", TK = "Tokelau", TL = "Timor-Leste", TM = "Turkmenistan", TN = "Tunisia", TO = "Tonga", TR = "Turkey", TT = "Trinidad and Tobago", TV = "Tuvalu", TW = "Taiwan", TZ = "Tanzania, United Republic of", UA = "Ukraine", UG = "Uganda", UM = "United States Minor Outlying Islands", US = "United States", UY = "Uruguay", UZ = "Uzbekistan", VA = "Holy See (Vatican City State)", VC = "Saint Vincent and the Grenadines", VE = "Venezuela", VG = "Virgin Islands, British", VI = "Virgin Islands, U.S.", VN = "Vietnam", VU = "Vanuatu", WF = "Wallis and Futuna", WS = "Samoa", YE = "Yemen", YT = "Mayotte", ZA = "South Africa", ZM = "Zambia", ZW = "Zimbabwe" } local sqlite_geo_db = dbConnect( "sqlite", "GeoIP.db" ) local function toIPNum( ip ) local nums = split( ip, 46 ) local ipnum = ( nums[ 1 ] * 16777216 ) + ( nums[ 2 ] * 65536 ) + ( nums[ 3 ] * 256 ) + ( nums[ 4 ] ) return ipnum end --[[local function toIP( ipnum ) local w = math.floor( math.fmod( ipnum / 16777216, 256 ) ) local x = math.floor( math.fmod( ipnum / 65536, 256 ) ) local y = math.floor( math.fmod( ipnum / 256, 256 ) ) local z = math.floor( math.fmod( ipnum, 256 ) ) local ip = tostring( w ) ..".".. tostring( x ) ..".".. tostring( y ) ..".".. tostring( z ) return ip, w, x, y, z end]] function getCountry( ip ) local num = tostring( toIPNum( ip ) ) local qh = dbQuery( sqlite_geo_db, "SELECT country FROM geoIPCountry WHERE ".. num .." BETWEEN begin_num AND end_num LIMIT 1" ) local res = dbPoll( qh, -1 ) if not res then return false end if res[ 1 ] then return res[ 1 ].country, countryName[ res[ 1 ].country ] end return false end function getCountryCity( ip ) local num = tostring( toIPNum( ip ) ) local qh = dbQuery( sqlite_geo_db, "SELECT city,region FROM geoIPCityLocation_RU WHERE locId = (SELECT locId FROM geoIPCityBlocks_RU WHERE ".. num .." BETWEEN begin_num AND end_num LIMIT 1) LIMIT 1" ) local res = dbPoll( qh, -1 ) if not res then return false end if res[ 1 ] then return res[ 1 ].city, res[ 1 ].region, "RU", "Russian Federation" end return false end
local create_gui = require 'gui' renoise.tool():add_menu_entry { name = 'Main Menu:Tools:Partial Quantize...', invoke = function() create_gui(true, 'all_tracks') end, } renoise.tool():add_menu_entry { name = 'Pattern Editor:Pattern:Partial Quantize...', invoke = function() create_gui(false, 'all_tracks') end, } renoise.tool():add_menu_entry { name = 'Pattern Editor:Track:Partial Quantize...', invoke = function() create_gui(false, 'track') end, } renoise.tool():add_menu_entry { name = 'Pattern Editor:Column:Partial Quantize...', invoke = function() create_gui(false, 'column') end, } renoise.tool():add_menu_entry { name = 'Pattern Editor:Selection:Partial Quantize...', invoke = function() create_gui(false, 'selection') end, } renoise.tool():add_keybinding { name = 'Pattern Editor:Selection:Partially Quantize Selection', invoke = function(repeated) if not repeated then create_gui(false, 'selection') end end, } renoise.tool():add_keybinding { name = 'Pattern Editor:Column Operations:Partially Quantize Column', invoke = function(repeated) if not repeated then create_gui(false, 'column') end end, } renoise.tool():add_keybinding { name = 'Pattern Editor:Track Operations:Partially Quantize Track', invoke = function(repeated) if not repeated then create_gui(false, 'track') end end, } renoise.tool():add_keybinding { name = 'Pattern Editor:Pattern Operations:Partially Quantize Pattern', invoke = function(repeated) if not repeated then create_gui(false, 'all_tracks') end end, }
function on_activate(parent, ability) local targets = parent:targets():friendly():touchable() local targeter = parent:create_targeter(ability) targeter:set_selection_touchable() targeter:add_all_selectable(targets) targeter:add_all_effectable(targets) targeter:activate() end function on_target_select(parent, ability, targets) local target = targets:first() local stats = parent:stats() local amount = 12 + stats.caster_level + stats.intellect_bonus / 4 target:heal_damage(amount) local anim = target:create_particle_generator("heal", 1.0) anim:set_moves_with_parent() anim:set_position(anim:param(-0.5), anim:param(-1.5)) anim:set_particle_size_dist(anim:fixed_dist(1.0), anim:fixed_dist(1.0)) anim:set_gen_rate(anim:param(3.0)) anim:set_initial_gen(2.0) anim:set_particle_position_dist(anim:dist_param(anim:uniform_dist(-0.7, 0.7), anim:uniform_dist(-0.1, 0.1)), anim:dist_param(anim:fixed_dist(0.0), anim:uniform_dist(-1.5, -1.0))) anim:set_particle_duration_dist(anim:fixed_dist(0.75)) anim:activate() ability:activate(parent) game:play_sfx("sfx/spell2") end
local t = { who={ f = function(player, parts) local s = "Online:"..NEWL for k, client in pairs(clients) do if (not client.state:match("^login")) and client.name then s = s..tostring(client.name)..NEWL end end player:send(s, "") end }, quit = { f = function(player, parts) player:send("Goodbye!"..NEWL) -- TODO: Some commands should be intercepted by the client first clients[player.__puppeteer.sock] = nil player.__puppeteer:close() end, aliases = { "exit" } }, look = { f = function(player, parts) local obj, name if #parts < 2 then obj = player.room else name = table.concat(parts, " ", 2) obj = player.room:search(name)[1] end if not obj then return player:send("Could not find "..name) end player:send(obj:getDesc(player)) end, aliases = { "ex", "exa", "exam", "exami", "examin", "examine", "l", "lo", "loo" } }, go = { f = function(player, parts) local dir = (parts[1]=="go" or parts[1]=="walk" or parts[1]=="climb") and parts[2] or parts[1] dir = dirFromShort(dir) if player.room.exits[dir] then player.room:doMove(player, dir) else player:send("Invalid direction!") end end, aliases = { "d", "down", "e", "ea", "eas", "east", "n", "no", "nor", "nort", "north", "ne", "northe", "northea", "northeas", "northeast", "nw", "northw", "northwe", "northwes", "northwest", "s", "so", "sou", "sout", "south", "se", "southe", "southea", "southeas", "southeast", "sw", "southw", "southwe", "southwes", "southwest", "u", "up", "w", "we", "wes", "west", "walk", "climb" } }, say = { f = function(player, parts, data) if #parts < 2 then return {"error", "Please supply a sentence to say"} end local msg = data:match("[^ ]+ (.+)") local third = xml.wrapText(xml.wrapText(player.name, "char", {id=player.identifier})..' says "'..xml.wrapText(msg, "msg")..'"', "say") player.room:broadcast(third, player) local second = xml.wrapText('You say "'..xml.wrapText(msg, "msg")..'"', "say") player:send(second) end, }, pose = { f = function(player, parts, data) local msg = "" if not parts[1]:find("^%..+") then if #parts < 2 then return {"error", "Please supply a phrase to pose"} end msg = data:match("[^ ]+ (.+)") else msg = data end msg = msg msg = player.name.." "..msg for i,p in ipairs(player.room.objects) do local newmsg = msg:gsub("%.(%a+)", function(v) -- for verb in gmatch(%.%S+) do verb..s or verb[conjugations] -- ShinMojo @ sindome.org ([^aeiouy]|qu)y$"-> "$1ies" and (x|ch|ss|sh)$ -> "$1es" -- Adds an s. e.g. .walk briskly becomes "walks briskly" -- v = v:gsub(ShinMojo pattern (need RegEx or custom pattern builder)) -- If pronouns.neutral and last used pronoun ~= nil if p == player then return v end -- secondPersonOfVerb(v) local cap = v:multimatch({"([^aeiouy]y)$","(quy)$"}) if cap then return v:sub(1, #v-1).."ies" end cap = nil cap = v:multimatch({"(x)$", "(ch)$", "(ss)$","(sh)$"}) if cap then return v.."es" end return v.."s" end):gsub("(\\?)(%a+)", function(except, v) if except ~= "" then return v end if p == player then return PRONOUNS.second[v:lower()] end return player.pronouns[v:lower()] end ):gsub( utils.case_insensitive_pattern(p.name), "you" ):gsub( "([%.%?%!]) (%a)", function(punctuation, letter) return punctuation.." "..letter:upper() end ):gsub( "^%a", function(l) return l:upper() end ) p:call("send", {newmsg}) end end, aliases = { "%.", "%..+" } }, emote = { f = function(player, parts, data) if #parts < 2 then return {"error", "Please supply a phrase to emote"} end player.room:broadcast(player.name.." "..data:match("%S+ (.+)")) end, aliases = { "/me" } }, stop = { f = function(player, parts) player:setMenu("Are you sure you want to stop the server? ", function(p,_,i) if i == 1 then error("STOP COMMAND") else p:setState("chat") end end) end }, set = { f = function(player, parts, data) if #parts < 2 then return {"error", "Please supply an object to modify"} elseif #parts < 3 then return {"error", "Please supply what value you want to change"} elseif #parts < 4 then return {"error", "Please supply a new value"} end local name = parts[2] obj = player.room:search(name)[1] if not obj then return "object not found!" end local key = parts[3] local obj, k = utils.resolve(obj, key) if not obj then return player:send("Invalid keypath "..key) end print("Setting "..(obj.name or tostring(obj)).." at "..k) -- e.g. set hobo pronouns.myself "xirself" local payload_parts = {} for i = 4,#parts do payload_parts[#payload_parts+1] = parts[i] end local payload = table.concat(payload_parts, " ") payload = "return "..payload -- PLEASE SANDBOX THIS FOR THE LOVE OF GOD --local success, newval = pcall(loadstring(payload, {})) if not success then player:send(newval); return end if type(newval) == "function" then obj[k.."_str"] = payload end obj[k] = newval end }, inspect = { f = function(player, parts) if #parts < 2 then return {"error", "Please supply an object to inspect"} end local name = parts[2] local obj = player.room:search(name)[1] obj = obj or db.get_or_load(tonumber(name)) if not obj then return player:send("Object not found") end player:send(ser(obj, NEWL)) end }, social = { f = function(player, parts) end }, save = { f = function(player, parts) for i, obj in pairs(objects) do db.store_object(obj) end end }, help = { f = function(player, parts) if #parts < 2 then local s = "Available commands are:"..NEWL for k,v in pairs(player.cmdset) do -- If permitted(player, v) s = s .. k .. NEWL end return player:send(s) end local keyword = parts[2] local helpfile = helpfiles[keyword] if not helpfile then -- Log(player.name.." tried to find helpfile "..keyword) player:send("Helpfile '"..keyword.."' not found.") -- soundex it upppp! local s1 = soundex(keyword) -- Starting letter local l1 = s1:sub(1,1) -- Soundex number local n1 = s1:sub(2,4) local potential = {} for k,v in pairs(helpfiles) do -- TODO: add tags to helpfiles, soundex those as well local s2 = soundex(k) local l2 = s2:sub(1,1) local n2 = s2:sub(2,4) -- If the words start with the same letter if l1 == l2 then dif = math.abs(n1 - n2) if dif <= 5 then table.insert(potential, k) end end end if #potential == 1 then player:send("Showing helpfile for "..colour("%{yellow}"..potential[1])) helpfile = helpfiles[potential[1]] elseif #potential > 1 then local s = "Did you mean" for i,v in ipairs(potential) do s = s.." "..colour("%{yellow}"..v)..(i == #potential and "?" or ",") end player:send(s) end end if helpfile then player:send(helpfile) end end, aliases = {"?"} }, create = { f = function(player, parts, data) if #parts < 2 then return {"error", "Please supply a type to create!"} end local t = parts[2] local obj = template(t) obj._type = t objects[obj.identifier] = obj player._editing_obj = obj player:setState("edit") if utils.contains(obj.scripts, "room") then player:pushMenu(unpack(menus.room_dir)) else player.room:add(obj) end end }, bore = { f = function(player, parts, data) if #parts < 2 then return {"error", "Please supply a direction"} end local dir = dirFromShort(parts[2]) local room = {name="Blank", desc="Nothing here"} room.scripts = { "object", "room", } room = Object:new(room) db.store_object(room) objects[room.identifier] = room player.room:attach(room, dir) player.room:doMove(player, dir) end, }, reload = { f = function(player, parts, data) if #parts < 2 then return {"error", "Please specify an object"} end local name = parts[2] local obj = player.room:search(name)[1] if not obj then return {"error", "Object not found"} end db.reload(obj) end, }, ["load"] = { f = function(player, parts, data) local id = tonumber(parts[2]) if id then db.get_or_load(id) end end }, attr_type = { f = function(player, parts, data) local obj if not parts[2] then return player:send("Missing object") end if not parts[3] then return player:send("Missing path") end obj = player.room:search(parts[2])[1] if not obj then return player:send("Couldn't find object") end local t, k = utils.resolve(obj, parts[3]) player:send(type(t[k])) end }, edit = { f = function(player, parts, data) name = table.concat(parts, " ", 2) local obj = player.room:search(name)[1] obj = obj or db.get_or_load(tonumber(name)) if obj then player._editing_obj = obj player:setState("edit") return elseif #parts < 2 then return {"error", "Please supply a type to edit, or the name of a visible object!"} elseif #parts < 3 then return {"error", "Please supply an identifier to use"} end local t = parts[2] local class = types[t] if not class then return player:send("Invalid type!") end local list = _G[t.."s"] player._editing_obj = list[tonumber(parts[3])] if not player._editing_obj then player:send(t.." #"..parts[3].." not found, creating new "..t) player._editing_obj = class:new() list[player._editing_obj.identifier] = player._editing_obj player:send(string.format("New %s created with identifier #%i", t, player._editing_obj.identifier)) end player:setState("edit") end }, --[[attack = { f = function(player, parts) local target = player.room:search(parts[2]) if target then -- check if it's a mobile? if target.hp then if player.room.flags:sub(1,1) == "1" then player:send("Cannot start a fight here!") elseif target.arena then target.arena:add(player) else local arena = Arena:new() arena:add(player) arena:add(target) target:setState("combat") end player:setState("combat") else player:send("That target is not combattable!") end elseif parts[2] then player:send(parts[2].." not found!") else return {"error", "Please provide a target to attack!"} end end },]] exits = { f = function(player, parts) player:send("The available exits are:") player:send("%{yellow}["..player.room:getExitsDesc(player).."]") end }, ident = { f = function(player, parts) if not parts[2] then obj = player.room else obj = player.room:search(parts[2])[1] end if obj then player:send(("Identifier of %q is %i"):format(obj.name, obj.identifier)) else player:send("Object not found!") end end }, manual = { f = function(player, parts) player:send( [[INTRODUCTION To interact with the world, type commands into the prompt in the following format >command argument1 argument2 argument3 ... e.g. >walk north Type 'help' to show a list of available commands, and type 'help command' to read a more detailed helpfile. ]]) end }, take = { f = function(player, parts) local obj = player.room:search(parts[2])[1] if obj then if obj:getMovable(player) then player.room:remove(obj) player:add(obj) player:send(obj:call("onPickup") or obj:getName().." taken!") else player:send("Can't pick up "..obj:getName()) end else player:send("Object not found") end end }, drop = { f = function(player, parts) local obj = player:search(parts[2])[1] if obj and obj ~= player then player:remove(obj) player.room:add(obj) obj:call("onDrop", {player, player.room}) player:send("Dropped "..obj.name) else player:send("Can't find object to drop") end end }, tp = { f = function(player, parts) if #parts < 3 then return {"error", "Please supply two IDs"} end local obj, destination = db.get_or_load(tonumber(parts[2])), db.get_or_load(tonumber(parts[3])) if obj and destination then if obj:getRoom() then obj:getRoom():remove(obj) end obj.room = destination destination:add(obj) elseif not obj then player:send("Invalid object") else player:send("Invalid desination") end end }, unlock = { f = function(player, parts) local dir = dirFromShort(parts[2]) local locks = player.room:getLocks() if locks and locks[dir] then if locks[dir]:unlock(player) then player:send("Your key fits!") return else player:send("Your keys don't fit") end else player:send("Nothing to unlock") end end, }, attach = { f = function(player, parts) local dir, dest, room if #parts < 2 then for _,dir in ipairs({"north", "south", "east", "west"}) do verbs.attach.f(player, {"attach ", dir}) end return else dir = dirFromShort(parts[2]) room = player.room if #parts == 2 then local target = dirvecs[dir] if target then dest = bfs(target, room) end else dest = db.get_or_load(tonumber(parts[3])) end if not dest then -- verbs should maybe return a string to be printed? player:send("Destination not found") return end end -- room:attach(dir, dest) room.exits[dir] = dest if oppdirs[dir] then local opp = oppdirs[dir] dest.exits[opp] = room end end, }, } for k,v in pairs(t) do v.aliases = v.aliases or {} table.insert(v.aliases, k) v.name = k end return t
--- 模块功能:串口功能测试(非TASK版,串口帧有自定义的结构) -- @author openLuat -- @module uart.testUartTask -- @license MIT -- @copyright openLuat -- @release 2018.05.24 module(...,package.seeall) require"utils" require"pm" --[[ 功能定义: uart接收数据,如果100毫秒没有收到新数据,则打印出来所有已收到的数据,清空数据缓冲区,回复received x frame给对端,然后等待下次数据接收 注意: 串口帧没有定义结构,仅靠软件延时,无法保证帧的完整性,如果对帧接收的完整性有严格要求,必须自定义帧结构(参考testUart.lua) 因为在整个GSM模块软件系统中,软件定时器的精确性无法保证,例如本demo配置的是100毫秒,在系统繁忙时,实际延时可能远远超过100毫秒,达到200毫秒、300毫秒、400毫秒等 设置的延时时间越短,误差越大 ]] --串口ID,2对应uart2 --如果要修改为uart1,把UART_ID赋值为2即可 local UART_ID = 2 local function taskRead() local cacheData,frameCnt = "",0 while true do local s = uart.read(UART_ID,"*l") if s == "" then uart.on(UART_ID,"receive",function() sys.publish("UART_RECEIVE") end) if not sys.waitUntil("UART_RECEIVE",100) then --uart接收数据,如果100毫秒没有收到数据,则打印出来所有已收到的数据,清空数据缓冲区,等待下次数据接收 --注意: --串口帧没有定义结构,仅靠软件延时,无法保证帧的完整性,如果对帧接收的完整性有严格要求,必须自定义帧结构(参考testUart.lua) --因为在整个GSM模块软件系统中,软件定时器的精确性无法保证,例如本demo配置的是100毫秒,在系统繁忙时,实际延时可能远远超过100毫秒,达到200毫秒、300毫秒、400毫秒等 --设置的延时时间越短,误差越大 if cacheData:len()>0 then log.info("testUartTask.taskRead","100ms no data, received length",cacheData:len()) --数据太多,如果全部打印,可能会引起内存不足的问题,所以此处仅打印前1024字节 log.info("testUartTask.taskRead","received data",cacheData:sub(1,1024)) cacheData = "" frameCnt = frameCnt+1 write("uart"..UART_ID.." received "..frameCnt.." frame") end end uart.on(UART_ID,"receive") else cacheData = cacheData..s end end end --[[ 函数名:write 功能 :通过串口发送数据 参数 : s:要发送的数据 返回值:无 ]] function write(s) log.info("testUartTask.write",s) uart.write(UART_ID,s.."\r\n") end local function writeOk() log.info("testUartTask.writeOk") end --保持系统处于唤醒状态,此处只是为了测试需要,所以此模块没有地方调用pm.sleep("testUartTask")休眠,不会进入低功耗休眠状态 --在开发“要求功耗低”的项目时,一定要想办法保证pm.wake("testUartTask")后,在不需要串口时调用pm.sleep("testUartTask") pm.wake("testUartTask") --注册串口的数据发送通知函数 uart.on(UART_ID,"sent",writeOk) --配置并且打开串口 uart.setup(UART_ID,115200,8,uart.PAR_NONE,uart.STOP_1) --如果需要打开“串口发送数据完成后,通过异步消息通知”的功能,则使用下面的这行setup,注释掉上面的一行setup --uart.setup(UART_ID,115200,8,uart.PAR_NONE,uart.STOP_1,nil,1) --启动串口数据接收任务 sys.taskInit(taskRead)