content stringlengths 5 1.05M |
|---|
ACL = {
lastError = ""
}
local playersConnecting = {}
local lastConnectedIdent = nil
-- Checks whether the player is whitelisted
-- @param1 integer NetID of the player connecting. NetID = PlayerID << 16
-- @param2 string Name of the player connecting
-- @return
function ACL:canConnect( netID, playerName )
local ids = GetPlayerIdentifiers( netID )
local png = GetPlayerPing( netID )
-- Bug: GetPlayerIdentifiers sometimes returns identity of previously connected player.
-- this piece of code instructs players to try again when this is detected, because dropping
-- connections 'fixes' the bug.
-- Reportedly supposedly fixed in 01/30 bug. Set ACL.useIdentBugWorkaround to false to stop using this workaround.
if ACL.useIdentBugWorkaround and lastConnectedIdent ~= nil then
if ids[1] == lastConnectedIdent[1] then
lastConnectedIdent = nil
self.lastError = "Please try again."
return false
end
end
lastConnectedIdent = ids
-- Banlist has highest priority
if self:isBanned( netID, playerName ) then
return false
end
-- Everyone else can connect if whitelisting is disabled
if not self.enableWhitelist then
return true
end
-- Always allow moderators and administrators to connect
if self:isModerator( netID ) then
return true
end
-- Disallow players with high ping when configured
if self.maxPing > 0 and png > self.maxPing then
self.lastError = "Your ping is too high for this server (" .. png .. "ms / " .. self.maxPing .. "ms)."
return false
end
for k,v in pairs( self.whitelist ) do
-- Check for whitelisted tags
if string.find( playerName, v, 1, true ) ~= nil then
return true
end
-- Check for whitelisted GUIDS
if findi( ids, v ) ~= nil then
return true
end
end
self.lastError = "This is a private server. Ask the administrator to be whitelisted."
return false
end
-- Checks whether player is blacklisted or has disallowed name
-- @param1 integer PlayerID
-- @param2 string Player name
-- @return
function ACL:isBanned( playerID, playerName )
local ids = GetPlayerIdentifiers( playerID )
-- Check for reserved names
if string.upper( playerName ) == "SERVER" or string.upper( playerName ) == "USAGE" then
self.lastError = string.format( "The name '%s' is reserved. Please change it.", playerName )
return true
end
for k,v in pairs( self.banlist ) do
-- Check for banned words
if string.find( playerName, v, 1, true ) ~= nil then
self.lastError = "Your name or a part of it is not allowed."
return true
end
-- Check for banned individuals
if findi( ids, v ) ~= nil then
self.lastError = "You are banned."
return true
end
end
return false
end
-- Checks whether the given IP is on the blacklist
-- @param1 string Player IP in 'GetPlayerIdentifiers' format (eg. "ip:127.0.0.1")
-- @return
function ACL:isBannedIP( ip )
return findi( self.banlist, ip ) ~= nil
end
-- Checks whether player is listed as moderator or adminstrator
-- @param1 integer PlayerID
-- @return
function ACL:isModerator( playerID )
local ids = GetPlayerIdentifiers( playerID )
for k,v in pairs( self.mods ) do
if findi( ids, v ) ~= nil then
return true
end
end
return self:isAdministrator( playerID )
end
-- Checks whether player is listed as administrator
-- @param1 integer PlayerID
-- @return
function ACL:isAdministrator( playerID )
local ids = GetPlayerIdentifiers( playerID )
for k,v in pairs( self.admins ) do
if findi( ids, v ) ~= nil then
return true
end
end
return false
end
-- Returns a list of players and their IDs
-- Kicks a player off the server
-- @param1 integer NetID of the person issuing the command, or -1 if source is RCON
-- @param2 table Array of arguments provided
-- @return
-- @arg1
OnCmd:register( "playerlist", function( source, args )
if not ACL.enablePlayerManagement then
-- Aborts the command, allowing other resources to handle it
return true
end
for i = 0, 31 do
local player = GetPlayerName( i )
if player ~= nil then
if ACL:isAdministrator( i ) then
OnCmd:feedback( source, "", {255, 255, 255}, string.format( "%d - %s [admin]", i, player ) )
elseif ACL:isModerator( i ) then
OnCmd:feedback( source, "", {255, 255, 255}, string.format( "%d - %s [mod]", i, player ) )
else
OnCmd:feedback( source, "", {255, 255, 255}, string.format( "%d - %s", i, player ) )
end
end
end
end)
-- Kicks a player off the server
-- @param1 integer NetID of the person issuing the command, or -1 if source is RCON
-- @param2 table Array of arguments provided
-- @return
-- @arg1 integer NetID of the player to kick
OnCmd:register( "kick", function( source, args )
if not ACL.enablePlayerManagement then
-- Aborts the command, allowing other resources to handle it
return true
end
-- Check for permissions if ACL is enabled
if not ACL:isModerator( source ) then
return
end
-- Process command
local toKick = table.remove( args, 1 )
local reason = table.remove( args, 1 )
reason = reason ~= nil and reason or "Kicked."
if toKick ~= nil then
DropPlayer( tonumber( toKick ), reason )
return
end
-- Invalid command syntax, provide help
OnCmd:feedback( source, "Usage", {255, 255, 255}, "/kick PlayerID [Reason]" )
OnCmd:feedback( source, "Usage", {255, 255, 255}, "/playerlist (show players and their IDs)" )
end)
-- Called when the client initially connects to the server
AddEventHandler( "playerConnecting", function( playerName, setCallback )
local ident = GetPlayerIdentifiers( source )
if ident == nil then
setCallback( "Server is starting. Please try again in a few seconds." )
CancelEvent()
return
end
print( string.format( "'%s' connecting. (%s)", playerName, table.concat( ident, ", " ) ) )
table.insert( playersConnecting, bit32.band( source, 0xFFFF ) + 1 )
if not ACL:canConnect( source, playerName ) then
print( "Connection rejected for: " .. playerName .. " (reason: " .. ACL.lastError .. ")" )
setCallback( ACL.lastError )
CancelEvent()
return
end
end)
-- GetPlayerEP does not handle NetIDs, only PlayerIDs. Server LUA does not have Citizen.CreateThread nor Wait
-- so we use this method to periodically check NetIDs converted to PlayerIDs (NetID & 0xFFFF + 1).
-- Usually triggered when the PlayerID is actually added to the server ~600ms after connecting.
-- 01/31: Apparently fixed in the 01/30 patch, however GetPlayerEP on 'playerConnecting' will result in ERROR_WINHTTP_TIMEOUT.
local function checkPlayersConnecting()
if #playersConnecting > 0 then
local EP = GetPlayerEP( playersConnecting[1] )
if EP ~= nil then
EP = "ip:" .. EP:Split( ":" )[0]
if ACL:isBannedIP( EP ) then
DropPlayer( playersConnecting[1], "You are banned." )
end
table.remove( playersConnecting, 1 )
end
end
SetTimeout( 175, checkPlayersConnecting )
end
SetTimeout( 1, checkPlayersConnecting ) |
-- Nncachebuilder-test.lua
-- unit test
require 'all'
setRandomSeeds(27)
tester = Tester()
test = {}
function test.cache()
local v, isVerbose = makeVerbose(false, 'test.cache')
local chatty = isVerbose
local nObs = 10
local nDims = 1
local xs = torch.Tensor(nObs, nDims)
for i = 1, nObs do
xs[i][1] = i
end
local nShards = 1
local nncb = Nncachebuilder(xs, nShards)
local filePathPrefix = '/tmp/Knn-test-cache'
nncb:createShard(1, filePathPrefix, chatty)
Nncachebuilder.mergeShards(nShards, filePathPrefix, chatty)
local cache = Nncache.loadUsingPrefix(filePathPrefix, chatty)
v('cache', cache)
if isVerbose then
local function p(key,value)
print(string.format('cache[%d] = %s', key, tostring(value)))
end -- p
cache:apply(p)
end
-- first element should be the obs index
for i = 1, 10 do
tester:asserteq(i, cache:getLine(i)[1])
end
-- test last element in cache line
tester:asserteq(10, cache:getLine(1)[10])
tester:asserteq(10, cache:getLine(2)[10])
tester:asserteq(10, cache:getLine(3)[10])
tester:asserteq(10, cache:getLine(4)[10])
tester:asserteq(10, cache:getLine(5)[10])
tester:asserteq(1, cache:getLine(6)[10])
tester:asserteq(1, cache:getLine(7)[10])
tester:asserteq(1, cache:getLine(8)[10])
tester:asserteq(1, cache:getLine(9)[10])
tester:asserteq(1, cache:getLine(10)[10])
end -- test.cache
function test.integrated()
local v, isVerbose = makeVerbose(false, 'test.integrated')
local chatty = isVerbose
v('chatty', chatty)
local nObs = 300
local nDims = 10
local xs = torch.rand(nObs, nDims)
local nShards = 5
local nnc = Nncachebuilder(xs, nShards)
tester:assert(nnc ~= nil)
local filePathPrefix = '/tmp/Nncache-test'
for n = 1, nShards do
nnc:createShard(n, filePathPrefix, chatty)
end
Nncachebuilder.mergeShards(nShards, filePathPrefix, chatty)
local cache = Nncache.loadUsingPrefix(filePathPrefix, chatty)
--print('cache', cache)
--print('type(cache)', type(cache))
v('cache', cache)
tester:assert(check.isTable(cache))
local count = 0
local function examine(key, value)
count = count + 1
tester:assert(check.isIntegerPositive(key))
tester:assert(check.isTensor1D(value))
tester:asserteq(math.min(nObs,256), value:size(1))
tester:asserteq(key, value[1]) -- obsIndex always nearest to itself
end
cache:apply(examine)
tester:asserteq(nObs, count)
end -- test.integrated
print('**********************************************************************')
tester:add(test)
tester:run(true) -- true ==> verbose
|
local function setup ()
vim.keymap.set('n', '<leader>bk', '<cmd>BufDel<CR>', {desc = 'Delete current buffer, keeping layout'})
vim.keymap.set('n', '<leader>bK', '<cmd>BufDel!<CR>', {desc = 'Force delete current buffer, keeping layout'})
end
return {
setup = setup
}
|
ModifyEvent(-2, 0, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 14, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 15, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 16, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 17, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 18, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 19, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 20, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 21, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 22, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 23, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 28, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 29, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 30, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 31, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 32, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 33, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 34, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
jyx2_ReplaceSceneObject("","NPC/嵩山派","");
ModifyEvent(-2, 51, 1, 1, 217, -1, -1, 5202, 5202, 5202, -2, -2, -2);
ModifyEvent(-2, 52, 1, 1, 217, -1, -1, 5202, 5202, 5202, -2, -2, -2);
ModifyEvent(-2, 53, 1, 1, -1, -1, -1, 5704, 5704, 5704, -2, -2, -2);
ModifyEvent(-2, 54, 1, 1, 208, -1, -1, 5706, 5706, 5706, -2, -2, -2);
jyx2_ReplaceSceneObject("","NPC/嵩山弟子51","1");
jyx2_ReplaceSceneObject("","NPC/嵩山弟子52","1");
jyx2_ReplaceSceneObject("","NPC/zuolengchan","1");
ModifyEvent(-2, 58, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(-2, 59, 0, 0, -1, -1, -1, -1, -1, -1, -2, -2, -2);
ModifyEvent(31, 0, -2, -2, 173, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(31, 2, -2, -2, 172, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(31, 3, -2, -2, 172, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(31, 4, -2, -2, 172, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(31, 5, -2, -2, 172, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(31, 6, -2, -2, 172, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(31, 7, -2, -2, 172, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(29, 1, -2, -2, 179, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(29, 2, -2, -2, 178, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(29, 3, -2, -2, 178, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(29, 4, -2, -2, 178, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(29, 5, -2, -2, 178, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(29, 6, -2, -2, 178, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(58, 20, -2, -2, 221, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(58, 1, -2, -2, 221, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(58, 2, -2, -2, 223, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(58, 11, -2, -2, 224, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(57, 1, -2, -2, 197, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(57, 2, -2, -2, 213, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(57, 3, -2, -2, 213, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(57, 4, -2, -2, 213, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(57, 5, -2, -2, 213, -1, -1, -2, -2, -2, -2, -2, -2);
ModifyEvent(57, 6, -2, -2, 213, -1, -1, -2, -2, -2, -2, -2, -2);
do return end;
|
uuid = argv[1];
another_session = freeswitch.Session(uuid)
callerid = another_session:getVariable("caller_id_number");
--file = io.open("logtest1.txt", "a+")
--file:write("\n:"..callerid..":\n")
--file:close()
another_session:consoleLog("info", "callerid: " .. callerid .. "\n");
stream:write(callerid); |
--[[**********************************
*
* Multi Theft Auto - Admin Panel
*
* client\widgets\admin_editor.lua
*
* Original File by lil_Toady
*
**************************************]]
function nothing ()
end |
local sides = {
bottom = 0,
top = 1,
back = 2,
front = 3,
right = 4,
left = 5
}
sides["down"] = sides["bottom"]
sides["up"] = sides["top"]
sides["north"] = sides["back"]
sides["south"] = sides["front"]
sides["west"] = sides["right"]
sides["east"] = sides["left"]
sides["negy"] = sides["bottom"]
sides["posy"] = sides["top"]
sides["negz"] = sides["back"]
sides["posz"] = sides["front"]
sides["negx"] = sides["right"]
sides["posx"] = sides["left"]
sides["forward"] = sides["front"]
return setmetatable(sides, {
__index = function(self, key)
for k, v in pairs(j) do
if key == v then
return k
end
end
end
});
|
signal = require 'signal'
a=torch.Tensor({12,2,9,16})
b=torch.poly(a)
print(a)
print(b)
print('-- Expected: 1 -39 518 -2616 3456')
a=torch.Tensor({{12,2,9,16},{12,2,9,16},{12,2,9,16},{12,2,9,16}})
b=torch.poly(a)
print(a)
print(b)
print('-- Expected: 1.0000 -39.0000 0.0000 0 0')
|
-- automatic conversion of input parameters
function autonumber(input)
local base = 10
local orig_input = input
if (type(input) == "string") then
input = input:gsub("[\(\)\"uUlL]", "")
if string.find(input,"[bxhBXH]") ~= nil then
if string.find(string.lower(input), "0b") == 1 then
input = input:gsub("[bB]","")
base = 2
elseif string.find(string.lower(input), "0x") == 1 then
input = input:gsub("[xXhH]","")
base = 16
end
elseif string.find(input, "0") == 1 then
base = 8
end
elseif (type(input) == "number") then
return input
else
logit("autonumber() expects either a string or a number!")
return nil
end
local result = tonumber(input, base)
if result == nil then
logit("Configured value is not valid: \"" .. tostring(orig_input) .. "\" - modify it to a numeric value!")
end
return result
end
-- simple_timer_freertos validation for configUSE_TIMERS
local cfg_value = autonumber(slc.config("configUSE_TIMERS").value)
if cfg_value ~= nil and cfg_value == 0 then
validation.error("Kernel configUSE_TIMERS config needs to be enabled",
validation.target_for_defines({"configUSE_TIMERS"}),
nil,
nil)
end
|
local on_attach = function(client, bufnr)
vim.api.nvim_buf_set_option(bufnr, "omnifunc", "v:lua.lsp.omnifunc")
-- autoformat on save
if client.resolved_capabilities.document_formatting then
vim.cmd("au BufWritePre <buffer> lua vim.lsp.buf.formatting_sync(nil, 1000)")
end
end
local default_options = {
on_attach = on_attach
}
require("nvim-lsp-installer").on_server_ready(function (server)
local status, opts = pcall(require, string.format("lsp.%s", server.name))
if not status then
opts = default_options
end
-- can we merge the default options?
server:setup(opts)
end)
-- symbols for autocomplete
vim.lsp.protocol.CompletionItemKind = {
" (Text) ",
" (Method)",
" (Function)",
" (Constructor)",
" ﴲ (Field)",
"[] (Variable)",
" (Class)",
" ﰮ (Interface)",
" (Module)",
" 襁 (Property)",
" (Unit)",
" (Value)",
" 練 (Enum)",
" (Keyword)",
" (Snippet)",
" (Color)",
" (File)",
" (Reference)",
" (Folder)",
" (EnumMember)",
" ﲀ (Constant)",
" ﳤ (Struct)",
" (Event)",
" (Operator)",
" (TypeParameter)"
}
|
require "premake_modules"
local ProjectName = "RaycastedMetaBalls"
function AddSourceFiles(DirectoryPath)
files
{
("../" .. DirectoryPath .. "/**.h"),
("../" .. DirectoryPath .. "/**.hpp"),
("../" .. DirectoryPath .. "/**.cpp"),
("../" .. DirectoryPath .. "/**.inl"),
("../" .. DirectoryPath .. "/**.c"),
}
end
workspace (ProjectName)
location "../"
basedir "../"
language "C++"
configurations {"Debug", "Release"}
platforms {"x64"}
warnings "default"
characterset ("MBCS")
rtti "Off"
toolset "v142"
cppdialect "C++latest"
--flags {"FatalWarnings"}
filter { "configurations:Debug" }
runtime "Debug"
defines { "_DEBUG" }
symbols "On"
optimize "Off"
debugdir "$(SolutionDir)"
filter { "configurations:Release" }
runtime "Release"
defines { "_RELEASE", "NDEBUG" }
symbols "Off"
optimize "Full"
project (ProjectName)
location ("../")
targetdir ("../Build/" .. ProjectName .. "$(Configuration)_$(Platform)")
objdir "!../Build/Intermediate/$(ProjectName)_$(Configuration)_$(Platform)"
kind "ConsoleApp"
AddSourceFiles("src")
includedirs { "$(ProjectDir)" }
disablewarnings
{
"4100", -- unreferenced formal paramter
"4189" -- local variable initalized but not referenced
}
AddOpenGL()
AddGLFW()
AddGLM()
AddGLEW()
filter "files:**/ThirdParty/**.*"
flags "NoPCH"
disablewarnings { "4100" }
|
--
-- Project: wiola
-- User: Konstantin Burkalev
-- Date: 16.03.14
--
local _M = {
_VERSION = '0.13.3',
}
_M.__index = _M
setmetatable(_M, {
__call = function(cls, ...)
return cls.new(...)
end
})
local wamp_features = {
agent = "wiola/Lua v" .. _M._VERSION,
roles = {
broker = {
features = {
pattern_based_subscription = true,
publisher_exclusion = true,
publisher_identification = true,
subscriber_blackwhite_listing = true
-- meta api are exposing if they are configured (see below)
--session_meta_api = true,
--subscription_meta_api = true
-- trust level feature is exposing if it is configured (see below)
-- publication_trustlevels = true
}
},
dealer = {
features = {
call_canceling = true,
call_timeout = true,
caller_identification = true,
pattern_based_registration = true,
progressive_call_results = true
-- meta api are exposing if they are configured (see below)
--session_meta_api = true,
--registration_meta_api = true
-- trust level feature is exposing if it is configured (see below)
-- call_trustlevels = true
}
}
}
}
local config = require("wiola.config").config()
local serializers = {
json = require('wiola.serializers.json_serializer'),
msgpack = require('wiola.serializers.msgpack_serializer')
}
local store = require('wiola.stores.' .. config.store)
-- Add Meta API features announcements if they are configured
if config.metaAPI.session == true then
wamp_features.roles.broker.features.session_meta_api = true
wamp_features.roles.dealer.features.session_meta_api = true
end
if config.metaAPI.subscription == true then
wamp_features.roles.broker.features.subscription_meta_api = true
end
if config.metaAPI.registration == true then
wamp_features.roles.dealer.features.registration_meta_api = true
end
-- Add trustLevels features announcements if they are configured
if config.trustLevels.authType ~= "none" then
wamp_features.roles.broker.features.publication_trustlevels = true
wamp_features.roles.dealer.features.call_trustlevels = true
end
local WAMP_MSG_SPEC = {
HELLO = 1,
WELCOME = 2,
ABORT = 3,
CHALLENGE = 4,
AUTHENTICATE = 5,
GOODBYE = 6,
ERROR = 8,
PUBLISH = 16,
PUBLISHED = 17,
SUBSCRIBE = 32,
SUBSCRIBED = 33,
UNSUBSCRIBE = 34,
UNSUBSCRIBED = 35,
EVENT = 36,
CALL = 48,
CANCEL = 49,
RESULT = 50,
REGISTER = 64,
REGISTERED = 65,
UNREGISTER = 66,
UNREGISTERED = 67,
INVOCATION = 68,
INTERRUPT = 69,
YIELD = 70
}
---
--- Check for a value in table
---
--- @param tab table Source table
--- @param val any Value to search
---
local has = function(tab, val)
for _, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
---
--- Create a new instance
---
--- @return table wiola instance
---
function _M.new()
local self = setmetatable({}, _M)
local ok, err = store:init(config)
if not ok then
return ok, err
end
return self
end
---
--- Generate a random string
---
--- @param length number String length
--- @return string random string
---
function _M:_randomString(length)
local str = {};
for _ = 1, length do
table.insert(str, string.char(math.random(32, 126)))
end
return table.concat(str)
end
---
--- Validate uri for WAMP requirements
---
--- @param uri string uri to validate
--- @param patternBased boolean allow wamp pattern based syntax or no
--- @param allowWAMP boolean allow wamp special prefixed uris or no
--- @return boolean is uri valid?
---
function _M:_validateURI(uri, patternBased, allowWAMP)
local re = "^([0-9a-zA-Z_]+\\.)*([0-9a-zA-Z_]+)$"
local rePattern = "^([0-9a-zA-Z_]+\\.{1,2})*([0-9a-zA-Z_]+)$"
if patternBased == true then
re = rePattern
end
local m, err = ngx.re.match(uri, re)
if not m then
return false
elseif string.find(uri, 'wamp%.') == 1 then
if allowWAMP ~= true then
return false
else
return true, true
end
else
return true
end
end
---
--- Add connection to wiola
---
--- @param sid number nginx session connection ID
--- @param wampProto string chosen WAMP protocol
---
--- @return number, string WAMP session registration ID, connection data type
---
function _M:addConnection(sid, wampProto)
local regId, dataType
if wampProto == nil or wampProto == "" then
wampProto = 'wamp.2.json' -- Setting default protocol for encoding/decodig use
end
if wampProto == 'wamp.2.msgpack' then
dataType = 'binary'
else
dataType = 'text'
end
regId = store:addSession({
connId = sid,
sessId = 0,
isWampEstablished = 0,
-- realm = nil,
-- wamp_features = nil,
wamp_protocol = wampProto,
encoding = string.match(wampProto, '.*%.([^.]+)$'),
dataType = dataType
})
return regId, dataType
end
---
--- Prepare data for sending to client
---
--- @param session table Session object
--- @param data any Client data
---
function _M:_putData(session, data)
local dataObj = serializers[session.encoding].encode(data)
store:putData(session, dataObj)
end
---
--- Publish event to sessions
---
--- @param sessRegIds table Array of session Ids
--- @param subId number Subscription Id
--- @param pubId number Publication Id
--- @param details table Details hash-table
--- @param args table Array-like payload
--- @param argsKW table Object-like payload
---
function _M:_publishEvent(sessRegIds, subId, pubId, details, args, argsKW)
-- WAMP SPEC: [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict]
-- WAMP SPEC: [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict,
-- PUBLISH.Arguments|list]
-- WAMP SPEC: [EVENT, SUBSCRIBED.Subscription|id, PUBLISHED.Publication|id, Details|dict,
-- PUBLISH.Arguments|list, PUBLISH.ArgumentKw|dict]
local data
if not args and not argsKW then
data = { WAMP_MSG_SPEC.EVENT, subId, pubId, setmetatable(details, { __jsontype = 'object' }) }
elseif args and not argsKW then
data = { WAMP_MSG_SPEC.EVENT, subId, pubId, setmetatable(details, { __jsontype = 'object' }),
setmetatable(args, { __jsontype = 'array' }) }
else
data = { WAMP_MSG_SPEC.EVENT, subId, pubId, setmetatable(details, { __jsontype = 'object' }),
setmetatable(args, { __jsontype = 'array' }), argsKW }
end
for _, v in ipairs(sessRegIds) do
local session = store:getSession(v)
self:_putData(session, data)
end
end
---
--- Publish META event to sessions
---
--- @param part string META API section name
--- @param eventUri string event uri
--- @param session table session object
---
function _M:_publishMetaEvent(part, eventUri, session, ...)
if not config.metaAPI[part] then
return
end
local subId = store:getSubscriptionId(session.realm, eventUri)
if not subId then
return
end
local pubId = store:getRegId('Publications')
local recipients = store:getTopicSessions(session.realm, eventUri)
local parameters = {n = select('#', ...), ...}
local argsL, argsKW = { session.sessId }, nil
local details = {}
if eventUri == 'wamp.session.on_join' then
argsL = {{ session = session.sessId }}
if parameters[1] then
argsL[1].authid = parameters[1].authid
argsL[1].authrole = parameters[1].authrole
argsL[1].authmethod = parameters[1].authmethod
argsL[1].authprovider = parameters[1].authprovider
end
-- TODO Add information about transport
--elseif eventUri == 'wamp.session.on_leave' then
-- nothing to add :)
elseif eventUri == 'wamp.subscription.on_create' then
local details = {
id = parameters[1],
created = parameters[2],
uri = parameters[3],
match = parameters[4]
}
table.insert(argsL, details)
elseif eventUri == 'wamp.subscription.on_subscribe' then
table.insert(argsL, parameters[1])
elseif eventUri == 'wamp.subscription.on_unsubscribe' then
table.insert(argsL, parameters[1])
elseif eventUri == 'wamp.subscription.on_delete' then
table.insert(argsL, parameters[1])
elseif eventUri == 'wamp.registration.on_create' then
local details = {
id = parameters[1],
created = parameters[2],
uri = parameters[3],
match = parameters[4],
invoke = parameters[5]
}
table.insert(argsL, details)
elseif eventUri == 'wamp.registration.on_register' then
table.insert(argsL, parameters[1])
elseif eventUri == 'wamp.registration.on_unregister' then
table.insert(argsL, parameters[1])
elseif eventUri == 'wamp.registration.on_delete' then
table.insert(argsL, parameters[1])
end
self:_publishEvent(recipients, subId, pubId, details, argsL, argsKW)
end
---
--- Process Call META RPC
---
--- @param part string META API section name
--- @param rpcUri string rpc uri
--- @param session table session object
--- @param requestId number request Id
--- @param rpcArgsL table Array-like payload
-- - @ param rpcArgsKw table Object-like payload
---
function _M:_callMetaRPC(part, rpcUri, session, requestId, rpcArgsL) --, rpcArgsKw)
local data
local details = setmetatable({}, { __jsontype = 'object' })
if config.metaAPI[part] == true then
if rpcUri == 'wamp.session.count' then
local count = store:getSessionCount(session.realm, rpcArgsL)
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { count } }
elseif rpcUri == 'wamp.session.list' then
local _, sessList = store:getSessionCount(session.realm, rpcArgsL)
data = { WAMP_MSG_SPEC.RESULT, requestId, details, sessList }
elseif rpcUri == 'wamp.session.get' then
local sessionInfo = store:getSession(rpcArgsL[1])
if sessionInfo ~= nil then
local res = {}
if sessionInfo.authInfo then
res = sessionInfo.authInfo
end
res.session = sessionInfo.sessId
-- TODO Add transport info
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { res } }
else
data = { WAMP_MSG_SPEC.ERROR, WAMP_MSG_SPEC.CALL, requestId, details, "wamp.error.no_such_session" }
end
elseif rpcUri == 'wamp.subscription.list' then
-- TODO Implement rpcUri == 'wamp.subscription.list'
-- need to count subs due to matching policy
--local subsIds = store:getSubscriptions(session.realm)
--data = { WAMP_MSG_SPEC.RESULT, requestId, details, subsIds }
elseif rpcUri == 'wamp.subscription.lookup' then
-- TODO Implement rpcUri == 'wamp.subscription.lookup'
elseif rpcUri == 'wamp.subscription.match' then
local subId = store:getSubscriptionId(session.realm, rpcArgsL[1])
if subId then
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { subId } }
else
data = { WAMP_MSG_SPEC.RESULT, requestId, details}
end
elseif rpcUri == 'wamp.subscription.get' then
-- TODO Implement rpcUri == 'wamp.subscription.get'
elseif rpcUri == 'wamp.subscription.list_subscribers' then
local sessList = store:getTopicSessionsBySubId(session.realm, rpcArgsL[1])
if sessList ~= nil then
data = { WAMP_MSG_SPEC.RESULT, requestId, details, sessList }
else
data = {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
requestId,
details,
"wamp.error.no_such_subscription"
}
end
elseif rpcUri == 'wamp.subscription.count_subscribers' then
local sessCount = store:getTopicSessionsCountBySubId(session.realm, rpcArgsL[1])
if sessCount ~= nil then
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { sessCount } }
else
data = {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
requestId,
details,
"wamp.error.no_such_subscription"
}
end
elseif rpcUri == 'wamp.registration.list' then
-- TODO Implement rpcUri == 'wamp.registration.list'
elseif rpcUri == 'wamp.registration.lookup' then
-- TODO Implement rpcUri == 'wamp.registration.lookup'
elseif rpcUri == 'wamp.registration.match' then
local rpcInfo = store:getRPC(session.realm, rpcArgsL[1])
if rpcInfo then
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { rpcInfo.registrationId } }
else
data = { WAMP_MSG_SPEC.RESULT, requestId, details}
end
elseif rpcUri == 'wamp.registration.get' then
-- TODO Implement rpcUri == 'wamp.registration.get'
elseif rpcUri == 'wamp.registration.list_callees' then
-- TODO Do not forget to update 'wamp.registration.list_callees' while implementing SHARED/SHARDED RPCs
local rpcInfo = store:getRPC(session.realm, rpcArgsL[1])
if rpcInfo then
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { rpcInfo.calleeSesId } }
else
data = {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
requestId,
details,
"wamp.error.no_such_registration"
}
end
elseif rpcUri == 'wamp.registration.count_callees' then
-- TODO Do not forget to update 'wamp.registration.count_callees' while implementing SHARED/SHARDED RPCs
local rpcInfo = store:getRPC(session.realm, rpcArgsL[1])
if rpcInfo then
data = { WAMP_MSG_SPEC.RESULT, requestId, details, { 1 } }
else
data = {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
requestId,
details,
"wamp.error.no_such_registration"
}
end
else
data = { WAMP_MSG_SPEC.ERROR, WAMP_MSG_SPEC.CALL, requestId, details, "wamp.error.invalid_uri" }
end
else
data = { WAMP_MSG_SPEC.ERROR, WAMP_MSG_SPEC.CALL, requestId, details, "wamp.error.no_suitable_callee" }
end
self:_putData(session, data)
end
---
--- Assing trust level for request
---
--- @param session table WAMP session issuing request data
---
--- @return number Assigned trust level for request
---
function _M:_assignTrustLevel(session)
local trustlevel, wasFound
local clientIp = ngx.var.remote_addr
if config.trustLevels.authType == "static" then
if session.authInfo and session.authInfo.authid then
for _, value in ipairs(config.trustLevels.staticCredentials.byAuthid) do
if session.authInfo.authid == value.authid then
trustlevel = value.trustlevel
wasFound = true
end
end
if wasFound then
return trustlevel
end
end
if session.authInfo and session.authInfo.authrole then
for _, value in ipairs(config.trustLevels.staticCredentials.byAuthRole) do
if session.authInfo.authrole == value.authrole then
trustlevel = value.trustlevel
wasFound = true
end
end
if wasFound then
return trustlevel
end
end
for _, value in ipairs(config.trustLevels.staticCredentials.byClientIp) do
if clientIp == value.clientip then
trustlevel = value.trustlevel
wasFound = true
end
end
if wasFound then
return trustlevel
end
else
-- config.trustLevels.authType == "dynamic"
local authid, authrole
if session.authInfo and session.authInfo.authid then
authid = session.authInfo.authid
end
if session.authInfo and session.authInfo.authrole then
authrole = session.authInfo.authrole
end
return config.trustLevels.authCallback(clientIp, session.realm, authid, authrole)
end
return config.trustLevels.defaultTrustLevel
end
---
--- Receive data from client
---
--- @param regId number WAMP session registration ID
--- @param data any data, received through websocket
---
function _M:receiveData(regId, data)
local session = store:getSession(regId)
if type(session) == 'nil' then
return
end
local dataObj = serializers[session.encoding].decode(data)
-- Analyze WAMP message ID received
if dataObj[1] == WAMP_MSG_SPEC.HELLO then -- WAMP SPEC: [HELLO, Realm|uri, Details|dict]
if session.isWampEstablished == 1 then
-- Protocol error: received second hello message - aborting
-- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received WELCOME message after session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
else
local realm = dataObj[2]
if not has(config.realms, realm) and config.realms[1] ~= "*" then
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.no_such_realm"
})
elseif self:_validateURI(realm, false, false) then
if config.wampCRA.authType ~= "none" then
if dataObj[3].authmethods and has(dataObj[3].authmethods, "wampcra") and dataObj[3].authid then
local challenge, challengeString, signature
store:changeChallenge(regId, {
realm = realm,
wampFeatures = serializers.json.encode(dataObj[3])
})
if config.wampCRA.authType == "static" then
if config.wampCRA.staticCredentials[dataObj[3].authid] then
challenge = {
authid = dataObj[3].authid,
authrole = config.wampCRA.staticCredentials[dataObj[3].authid].authrole,
authmethod = "wampcra",
authprovider = "wiolaStaticAuth",
nonce = self:_randomString(16),
timestamp = os.date("!%FT%TZ"), -- without ms. "!%FT%T.%LZ"
session = regId
}
challengeString = serializers.json.encode(challenge)
local hmac = require "resty.hmac"
local hm = hmac:new(config.wampCRA.staticCredentials[dataObj[3].authid].secret)
signature = hm:generate_signature("sha256", challengeString)
if signature then
challenge.signature = signature
store:changeChallenge(regId, challenge)
-- WAMP SPEC: [CHALLENGE, AuthMethod|string, Extra|dict]
self:_putData(session, {
WAMP_MSG_SPEC.CHALLENGE,
"wampcra",
{ challenge = challengeString }
})
else
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.authorization_failed"
})
end
else
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.authorization_failed"
})
end
elseif config.wampCRA.authType == "dynamic" then
challenge = config.wampCRA.challengeCallback(regId, dataObj[3].authid)
-- WAMP SPEC: [CHALLENGE, AuthMethod|string, Extra|dict]
self:_putData(session, { WAMP_MSG_SPEC.CHALLENGE, "wampcra", { challenge = challenge } })
end
else
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.authorization_failed"
})
end
else
session.isWampEstablished = 1
session.realm = realm
session.wampFeatures = dataObj[3]
store:changeSession(regId, session)
store:addSessionToRealm(regId, realm)
-- WAMP SPEC: [WELCOME, Session|id, Details|dict]
self:_putData(session, { WAMP_MSG_SPEC.WELCOME, regId, wamp_features })
self:_publishMetaEvent('session', 'wamp.session.on_join', session)
end
else
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.invalid_uri"
})
end
end
elseif dataObj[1] == WAMP_MSG_SPEC.AUTHENTICATE then -- WAMP SPEC: [AUTHENTICATE, Signature|string, Extra|dict]
if session.isWampEstablished == 1 then
-- Protocol error: received second message - aborting
-- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received AUTHENTICATE message after session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
else
local challenge = store:getChallenge(regId)
local authInfo
if config.wampCRA.authType == "static" then
if dataObj[2] == challenge.signature then
authInfo = {
authid = challenge.authid,
authrole = challenge.authrole,
authmethod = challenge.authmethod,
authprovider = challenge.authprovider
}
end
elseif config.wampCRA.authType == "dynamic" then
authInfo = config.wampCRA.authCallback(regId, dataObj[2])
end
if authInfo then
session.isWampEstablished = 1
session.realm = challenge.realm
session.wampFeatures = challenge.wampFeatures
session.authInfo = authInfo
store:changeSession(regId, session)
store:addSessionToRealm(regId, challenge.realm)
local details = wamp_features
details.authid = authInfo.authid
details.authrole = authInfo.authrole
details.authmethod = authInfo.authmethod
details.authprovider = authInfo.authprovider
-- WAMP SPEC: [WELCOME, Session|id, Details|dict]
self:_putData(session, { WAMP_MSG_SPEC.WELCOME, regId, details })
self:_publishMetaEvent('session', 'wamp.session.on_join', session, authInfo)
else
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.authorization_failed"
})
end
end
-- Clean up Challenge data in any case
store:removeChallenge(regId)
-- elseif dataObj[1] == WAMP_MSG_SPEC.ABORT then -- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
-- No response is expected
elseif dataObj[1] == WAMP_MSG_SPEC.GOODBYE then -- WAMP SPEC: [GOODBYE, Details|dict, Reason|uri]
if session.isWampEstablished == 1 then
self:_putData(session, {
WAMP_MSG_SPEC.GOODBYE,
setmetatable({}, { __jsontype = 'object' }),
"wamp.close.goodbye_and_out"
})
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received GOODBYE message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
end
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
elseif dataObj[1] == WAMP_MSG_SPEC.ERROR then
-- WAMP SPEC: [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri]
-- WAMP SPEC: [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri,
-- Arguments|list]
-- WAMP SPEC: [ERROR, REQUEST.Type|int, REQUEST.Request|id, Details|dict, Error|uri,
-- Arguments|list, ArgumentsKw|dict]
if session.isWampEstablished == 1 then
if dataObj[2] == WAMP_MSG_SPEC.INVOCATION then
-- WAMP SPEC: [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri]
-- WAMP SPEC: [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri,
-- Arguments|list]
-- WAMP SPEC: [ERROR, INVOCATION, INVOCATION.Request|id, Details|dict, Error|uri,
-- Arguments|list, ArgumentsKw|dict]
local invoc = store:getInvocation(dataObj[3])
local callerSess = store:getSession(invoc.callerSesId)
if invoc and callerSess then
if #dataObj == 6 then
-- WAMP SPEC: [ERROR, CALL, CALL.Request|id, Details|dict, Error|uri, Arguments|list]
self:_putData(callerSess, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
invoc.CallReqId,
setmetatable({}, { __jsontype = 'object' }),
dataObj[5],
setmetatable(dataObj[6], { __jsontype = 'array' })
})
elseif #dataObj == 7 then
-- WAMP SPEC: [ERROR, CALL, CALL.Request|id, Details|dict, Error|uri,
-- Arguments|list, ArgumentsKw|dict]
self:_putData(callerSess, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
invoc.CallReqId,
setmetatable({}, { __jsontype = 'object' }),
dataObj[5],
setmetatable(dataObj[6], { __jsontype = 'array' }),
dataObj[7]
})
else
-- WAMP SPEC: [ERROR, CALL, CALL.Request|id, Details|dict, Error|uri]
self:_putData(callerSess, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
invoc.CallReqId,
setmetatable({}, { __jsontype = 'object' }),
dataObj[5]
})
end
end
store:removeInvocation(dataObj[3])
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received ERROR message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
end
elseif dataObj[1] == WAMP_MSG_SPEC.PUBLISH then
-- WAMP SPEC: [PUBLISH, Request|id, Options|dict, Topic|uri]
-- WAMP SPEC: [PUBLISH, Request|id, Options|dict, Topic|uri, Arguments|list]
-- WAMP SPEC: [PUBLISH, Request|id, Options|dict, Topic|uri, Arguments|list, ArgumentsKw|dict]
if session.isWampEstablished == 1 then
if self:_validateURI(dataObj[4], false, false) then
local pubId = store:getRegId('Publications')
local options = dataObj[3]
if config.trustLevels.authType ~= "none" then
local trustlevel = self:_assignTrustLevel(session)
if trustlevel ~= nil then
options.trustlevel = trustlevel
end
end
local recipients = store:getEventRecipients(session.realm, dataObj[4], regId, options)
for _, v in ipairs(recipients) do
self:_publishEvent(v.sessions, v.subId, pubId, v.details, dataObj[5], dataObj[6])
end
if dataObj[3].acknowledge and dataObj[3].acknowledge == true then
-- WAMP SPEC: [PUBLISHED, PUBLISH.Request|id, Publication|id]
self:_putData(session, { WAMP_MSG_SPEC.PUBLISHED, dataObj[2], pubId })
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.PUBLISH,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.invalid_uri"
})
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received PUBLISH message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.SUBSCRIBE then -- WAMP SPEC: [SUBSCRIBE, Request|id, Options|dict, Topic|uri]
if session.isWampEstablished == 1 then
local patternBased = false
if dataObj[3].match then
patternBased = true
end
if self:_validateURI(dataObj[4], patternBased, true) then
local subscriptionId, isNewSubscription = store:subscribeSession(
session.realm, dataObj[4], dataObj[3], regId)
-- WAMP SPEC: [SUBSCRIBED, SUBSCRIBE.Request|id, Subscription|id]
self:_putData(session, { WAMP_MSG_SPEC.SUBSCRIBED, dataObj[2], subscriptionId })
if isNewSubscription then
self:_publishMetaEvent('subscription', 'wamp.subscription.on_create', session,
subscriptionId, os.date("!%Y-%m-%dT%TZ"), dataObj[4], "exact")
end
self:_publishMetaEvent('subscription', 'wamp.subscription.on_subscribe', session,
subscriptionId)
else
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.SUBSCRIBE,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.invalid_uri"
})
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received SUBSCRIBE message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.UNSUBSCRIBE then
-- WAMP SPEC: [UNSUBSCRIBE, Request|id, SUBSCRIBED.Subscription|id]
if session.isWampEstablished == 1 then
local isSesSubscrbd, wasTopicRemoved = store:unsubscribeSession(session.realm, dataObj[3], regId)
if isSesSubscrbd ~= ngx.null then
-- WAMP SPEC: [UNSUBSCRIBED, UNSUBSCRIBE.Request|id]
self:_putData(session, { WAMP_MSG_SPEC.UNSUBSCRIBED, dataObj[2] })
self:_publishMetaEvent('subscription', 'wamp.subscription.on_unsubscribe', session, dataObj[3])
if wasTopicRemoved then
self:_publishMetaEvent('subscription', 'wamp.subscription.on_delete', session, dataObj[3])
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.UNSUBSCRIBE,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.no_such_subscription"
})
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received UNSUBSCRIBE message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.CALL then
-- WAMP SPEC: [CALL, Request|id, Options|dict, Procedure|uri]
-- WAMP SPEC: [CALL, Request|id, Options|dict, Procedure|uri, Arguments|list]
-- WAMP SPEC: [CALL, Request|id, Options|dict, Procedure|uri, Arguments|list, ArgumentsKw|dict]
if session.isWampEstablished == 1 then
local isUriValid, isWampSpecial = self:_validateURI(dataObj[4], false, true)
if isUriValid then
if isWampSpecial then
-- Received a call for WAMP meta RPCs
local metapart = string.match(dataObj[4], "wamp.(%a+)")
self:_callMetaRPC(metapart, dataObj[4], session, dataObj[2], dataObj[5], dataObj[6])
else
local rpcInfo = store:getRPC(session.realm, dataObj[4])
if not rpcInfo then
-- WAMP SPEC: [ERROR, CALL, CALL.Request|id, Details|dict, Error|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.no_suitable_callee"
})
else
local details = setmetatable({}, { __jsontype = 'object' })
if config.callerIdentification == "always" or
(config.callerIdentification == "auto" and
((dataObj[3].disclose_me ~= nil and dataObj[3].disclose_me == true) or
(rpcInfo.disclose_caller == true))) then
details.caller = regId
end
if dataObj[3].receive_progress ~= nil and dataObj[3].receive_progress == true then
details.receive_progress = true
end
local calleeSess = store:getSession(rpcInfo.calleeSesId)
local invReqId = store:getRegId('Invocations')
if rpcInfo.options and rpcInfo.options.procedure then
details.procedure = rpcInfo.options.procedure
end
if config.trustLevels.authType ~= "none" then
local trustlevel = self:_assignTrustLevel(session)
if trustlevel ~= nil then
details.trustlevel = trustlevel
end
end
if dataObj[3].timeout ~= nil and
dataObj[3].timeout > 0 and
calleeSess.wampFeatures.callee.features.call_timeout == true and
calleeSess.wampFeatures.callee.features.call_canceling == true then
-- Caller specified Timeout for CALL processing and callee support this feature
local function callCancel(_, calleeSession, invocReqId)
-- WAMP SPEC: [INTERRUPT, INVOCATION.Request|id, Options|dict]
self:_putData(calleeSession, {
WAMP_MSG_SPEC.INTERRUPT,
invocReqId,
setmetatable({}, { __jsontype = 'object' })
})
end
local ok, err = ngx.timer.at(dataObj[3].timeout, callCancel, calleeSess, invReqId)
if not ok then
end
end
store:addCallInvocation(dataObj[2], session.sessId, invReqId, calleeSess.sessId)
if #dataObj == 5 then
-- WAMP SPEC: [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict,
-- CALL.Arguments|list]
self:_putData(calleeSess, {
WAMP_MSG_SPEC.INVOCATION,
invReqId,
rpcInfo.registrationId,
details,
setmetatable(dataObj[5], { __jsontype = 'array' })
})
elseif #dataObj == 6 then
-- WAMP SPEC: [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict,
-- CALL.Arguments|list, CALL.ArgumentsKw|dict]
self:_putData(calleeSess, {
WAMP_MSG_SPEC.INVOCATION,
invReqId,
rpcInfo.registrationId,
details,
setmetatable(dataObj[5], { __jsontype = 'array' }),
dataObj[6]
})
else
-- WAMP SPEC: [INVOCATION, Request|id, REGISTERED.Registration|id, Details|dict]
self:_putData(calleeSess, {
WAMP_MSG_SPEC.INVOCATION,
invReqId,
rpcInfo.registrationId,
details
})
end
end
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.CALL,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.invalid_uri"
})
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received CALL message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.REGISTER then
-- WAMP SPEC: [REGISTER, Request|id, Options|dict, Procedure|uri]
if session.isWampEstablished == 1 then
local patternBased = false
if dataObj[3].match then
patternBased = true
end
if self:_validateURI(dataObj[4], patternBased, false) then
local registrationId = store:registerSessionRPC(session.realm, dataObj[4], dataObj[3], regId)
if not registrationId then
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.REGISTER,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.procedure_already_exists"
})
else
-- WAMP SPEC: [REGISTERED, REGISTER.Request|id, Registration|id]
self:_putData(session, { WAMP_MSG_SPEC.REGISTERED, dataObj[2], registrationId })
-- TODO Refactor this in case of implementing shared registrations
self:_publishMetaEvent('registration', 'wamp.registration.on_create', session,
registrationId, os.date("!%Y-%m-%dT%TZ"), dataObj[4], "exact", "single")
self:_publishMetaEvent('registration', 'wamp.registration.on_register', session,
registrationId)
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.REGISTER,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.invalid_uri"
})
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received REGISTER message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.UNREGISTER then
-- WAMP SPEC: [UNREGISTER, Request|id, REGISTERED.Registration|id]
if session.isWampEstablished == 1 then
local rpc = store:unregisterSessionRPC(session.realm, dataObj[3], regId)
if rpc ~= ngx.null then
-- WAMP SPEC: [UNREGISTERED, UNREGISTER.Request|id]
self:_putData(session, { WAMP_MSG_SPEC.UNREGISTERED, dataObj[2] })
self:_publishMetaEvent('registration', 'wamp.registration.on_unregister', session, dataObj[3])
-- TODO Refactor this in case of implementing shared registrations
self:_publishMetaEvent('registration', 'wamp.registration.on_delete', session, dataObj[3])
else
self:_putData(session, {
WAMP_MSG_SPEC.ERROR,
WAMP_MSG_SPEC.UNREGISTER,
dataObj[2],
setmetatable({}, { __jsontype = 'object' }),
"wamp.error.no_such_registration"
})
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received UNREGISTER message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.YIELD then
-- WAMP SPEC: [YIELD, INVOCATION.Request|id, Options|dict]
-- WAMP SPEC: [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list]
-- WAMP SPEC: [YIELD, INVOCATION.Request|id, Options|dict, Arguments|list, ArgumentsKw|dict]
if session.isWampEstablished == 1 then
local invoc = store:getInvocation(dataObj[2])
if invoc then
local callerSess = store:getSession(invoc.callerSesId)
if callerSess then
local details = setmetatable({}, { __jsontype = 'object' })
if dataObj[3].progress ~= nil and dataObj[3].progress == true then
details.progress = true
else
store:removeInvocation(dataObj[2])
store:removeCall(invoc.CallReqId)
end
if #dataObj == 4 then
-- WAMP SPEC: [RESULT, CALL.Request|id, Details|dict, YIELD.Arguments|list]
self:_putData(callerSess, { WAMP_MSG_SPEC.RESULT, invoc.CallReqId, details,
setmetatable(dataObj[4], { __jsontype = 'array' }) })
elseif #dataObj == 5 then
-- WAMP SPEC: [RESULT, CALL.Request|id, Details|dict, YIELD.Arguments|list, YIELD.ArgumentsKw|dict]
self:_putData(callerSess, { WAMP_MSG_SPEC.RESULT, invoc.CallReqId, details,
setmetatable(dataObj[4], { __jsontype = 'array' }), dataObj[5] })
else
-- WAMP SPEC: [RESULT, CALL.Request|id, Details|dict]
self:_putData(callerSess, { WAMP_MSG_SPEC.RESULT, invoc.CallReqId, details })
end
end
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received YIELD message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
elseif dataObj[1] == WAMP_MSG_SPEC.CANCEL then
-- WAMP SPEC: [CANCEL, CALL.Request|id, Options|dict]
if session.isWampEstablished == 1 then
local wiCall = store:getCall(dataObj[2])
local calleeSess = store:getSession(wiCall.calleeSesId)
if calleeSess.wampFeatures.callee.features.call_canceling == true then
local details = setmetatable({}, { __jsontype = 'object' })
if dataObj[3].mode ~= nil then
details.mode = dataObj[3].mode
end
-- WAMP SPEC: [INTERRUPT, INVOCATION.Request|id, Options|dict]
self:_putData(calleeSess, { WAMP_MSG_SPEC.INTERRUPT, wiCall.wiInvocId, details })
end
else
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received CANCEL message before session was established' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
self:_publishMetaEvent('session', 'wamp.session.on_leave', session)
end
else
-- Received non-compliant WAMP message
-- WAMP SPEC: [ABORT, Details|dict, Reason|uri]
self:_putData(session, {
WAMP_MSG_SPEC.ABORT,
{ message = 'Received non-compliant WAMP message' },
"wamp.error.protocol_violation"
})
store:setHandlerFlags(regId, { close = true, sendLast = true })
end
end
---
--- Retrieve data, available for session
---
--- @param regId number WAMP session registration ID
--- @param last boolean return from the end of a queue
---
--- @return any first WAMP message from the session data queue
---
function _M:getPendingData(regId, last)
return store:getPendingData(regId, last)
end
---
--- Retrieve connection handler flags, set up for session
---
--- @param regId number WAMP session registration ID
---
--- @return table flags data table
---
function _M:getHandlerFlags(regId)
return store:getHandlerFlags(regId)
end
---
--- Process lightweight publish POST data from client
---
--- @param sid number nginx session connection ID
--- @param realm string WAMP Realm to operate in
--- @param data any data, received through POST
---
function _M:processPostData(sid, realm, data)
local dataObj = serializers.json.decode(data)
local res
local httpCode
if dataObj[1] == WAMP_MSG_SPEC.PUBLISH then
local regId = self.addConnection(sid, nil)
-- Make a session legal :)
local session = store:getSession(regId)
session.isWampEstablished = 1
session.realm = realm
store:changeSession(regId, session)
self.receiveData(regId, data)
local cliData = self.getPendingData(regId)
if cliData ~= ngx.null then
res = cliData
httpCode = ngx.HTTP_FORBIDDEN
else
res = serializers.json.encode({ result = true, error = nil })
httpCode = ngx.HTTP_OK
end
store:removeSession(regId)
else
res = serializers.json.encode({ result = false, error = "Message type not supported" })
httpCode = ngx.HTTP_FORBIDDEN
end
return res, httpCode
end
return _M
|
object_tangible_loot_beast_beast_steroid_mantis_monkey = object_tangible_loot_beast_shared_beast_steroid_mantis_monkey:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_beast_beast_steroid_mantis_monkey, "object/tangible/loot/beast/beast_steroid_mantis_monkey.iff")
|
test_run = require('test_run').new()
engine = test_run:get_cfg('engine')
box.execute('pragma sql_default_engine=\''..engine..'\'')
-- create space
box.execute("CREATE TABLE foobar (foo INT PRIMARY KEY, bar TEXT)")
-- prepare data
box.execute("INSERT INTO foobar VALUES (1, 'foo')")
box.execute("INSERT INTO foobar VALUES (2, 'bar')")
box.execute("INSERT INTO foobar VALUES (1000, 'foobar')")
box.execute("INSERT INTO foobar VALUES (1, 'duplicate')")
-- simple select
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar LIMIT 2")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo=2")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo>2")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo>=2")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo=10000")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo>10000")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo<2")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo<2.001")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo<=2")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE foo<100")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar WHERE bar='foo'")
box.execute("SELECT count(*) FROM foobar")
box.execute("SELECT count(*) FROM foobar WHERE bar='foo'")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar ORDER BY bar")
box.execute("SELECT bar, foo, 42, 'awesome' FROM foobar ORDER BY bar DESC")
-- updates
box.execute("REPLACE INTO foobar VALUES (1, 'cacodaemon')")
box.execute("SELECT COUNT(*) FROM foobar WHERE foo=1")
box.execute("SELECT COUNT(*) FROM foobar WHERE bar='cacodaemon'")
box.execute("DELETE FROM foobar WHERE bar='cacodaemon'")
box.execute("SELECT COUNT(*) FROM foobar WHERE bar='cacodaemon'")
-- multi-index
-- create space
box.execute("CREATE TABLE barfoo (bar TEXT, foo NUMBER PRIMARY KEY)")
box.execute("CREATE UNIQUE INDEX barfoo2 ON barfoo(bar)")
-- prepare data
box.execute("INSERT INTO barfoo VALUES ('foo', 1)")
box.execute("INSERT INTO barfoo VALUES ('bar', 2)")
box.execute("INSERT INTO barfoo VALUES ('foobar', 1000)")
-- prove barfoo2 was created
box.execute("INSERT INTO barfoo VALUES ('xfoo', 1)")
box.execute("SELECT foo, bar FROM barfoo")
box.execute("SELECT foo, bar FROM barfoo WHERE foo==2")
box.execute("SELECT foo, bar FROM barfoo WHERE bar=='foobar'")
box.execute("SELECT foo, bar FROM barfoo WHERE foo>=2")
box.execute("SELECT foo, bar FROM barfoo WHERE foo<=2")
-- cleanup
box.execute("DROP INDEX barfoo2 ON barfoo")
box.execute("DROP TABLE foobar")
box.execute("DROP TABLE barfoo")
-- attempt to create a table lacking PRIMARY KEY
box.execute("CREATE TABLE without_rowid_lacking_primary_key(x SCALAR)")
-- create a table with implicit indices (used to SEGFAULT)
box.execute("CREATE TABLE implicit_indices(a INT PRIMARY KEY,b INT,c INT,d TEXT UNIQUE)")
box.execute("DROP TABLE implicit_indices")
|
--
local M = {}
local enum_type = require('xe.node.enum_type')
M.any = {
}
M.audio_pan = {
'string',
'const',
const = {
{ 'default', "self.x / 256" },
},
}
M.bgstage = {
'enum',
enum = enum_type.bgstage
}
M.blend = {
'enum',
enum = enum_type.blend
}
M.bool = {
'bool'
}
M.bulletstyle = {
'bullet_style'
}
M.color = {
'color_enum',
--'color',
}
M.difficulty = {
'enum',
enum = enum_type.difficulty
}
M.directmode = {
'enum',
enum = enum_type.directmode
}
M.event = {
-- only used in callbackfunc
'enum',
enum = enum_type.event
}
M.gop = {
-- game object property
}
M.group = {
'enum',
enum = enum_type.group
}
M.image = {
'image'
}
M.item = {
-- used in dropitem
'enum',
enum = enum_type.item
}
M.layer = {
'enum',
enum = enum_type.layer
}
M.leftright = {
'enum',
enum = enum_type.leftright
}
M.movetomode = {
'enum',
enum = enum_type.movetomode
}
M.number = {
--'number'
}
M.param = {
'param'
}
M.pos = {
'vec2',
'const',
const = {
{ 'follow_self', "self.x, self.y" },
{ 'follow_player', "player.x, player.y" },
{ 'follow_boss', "_boss.x, _boss.y" },
},
vec2 = { 'x', 'y' }
}
M.resfile = {
'path',
loadsound = { "wav,ogg" },
loadbgm = { "wav,ogg" },
loadimage = { "png,jpg,bmp" },
loadani = { "png,jpg,bmp" },
bossdefine = { "png,jpg,bmp" },
loadparticle = "psi",
patch = "lua",
loadFX = { "fx,vert,frag" },
}
M.selectenemystyle = {
'enemy_style'
}
M.selecttype = {
'type_name'
}
M.sound = {
'sound_effect'
}
M.stagegroup = {
'enum',
enum = enum_type.stagegroup
}
M.string = {
}
M.typename = {
-- define an editor class
'type_define'
}
M.vec2 = {
'vec2'
}
--
M.tween_type = {
'tween_type',
--'enum',
--enum = enum_type.tween_type
}
for k, v in pairs(M) do
if not table.has(v, 'string') then
table.insert(v, 'string')
end
end
M.code_lua = {
'code',
code = {
lang = 'lua',
}
}
return M
|
module("time", package.seeall)
local meta = FindMetaTable("Player")
if not meta then return end
function meta:GetTime()
return self:GetNWFloat("TotalTime")
end
function meta:SetTime(num)
self:SetNWFloat("TotalTime", num)
end
function meta:GetTimeStart()
return self:GetNWFloat("TimeStart")
end
function meta:SetTimeStart( num )
self:SetNWFloat("TimeStart", num)
end
function meta:GetTimeSessionTime()
return CurTime() - self:GetTimeStart()
end
function meta:GetTimeTotalTime()
return self:GetTime() + CurTime() - self:GetTimeStart()
end
function timeToStr(time)
local tmp = time
local s = tmp % 60
tmp = math.floor(tmp/60)
local m = tmp % 60
tmp = math.floor(tmp/60)
local h = tmp % 24
tmp = math.floor(tmp/24)
local d = tmp % 7
local w = math.floor(tmp/7)
return string.format("%02iw %id %02ih %02im %02is", w, d, h, m, s)
end |
-- code browser plugin
local aerial = require('aerial')
local on_attach = function(client, bufnr)
aerial.on_attach(client)
-- aerial does not set any mappings by default
-- toggle the aerial window with <leader>a
vim.api.nvim_buf_set_keymap(0, 'n', '<leader>a', '<cmd>AerialToggle!<CR>', {})
-- jump forwards/backwards with '{' and '}'
vim.api.nvim_buf_set_keymap(0, 'n', '{', '<cmd>AerialPrev<CR>', {})
vim.api.nvim_buf_set_keymap(0, 'n', '}', '<cmd>AerialNext<CR>', {})
-- jump up the tree with '[[' or ']]'
vim.api.nvim_buf_set_keymap(0, 'n', '[[', '<cmd>AerialPrevUp<CR>', {})
vim.api.nvim_buf_set_keymap(0, 'n', ']]', '<cmd>AerialNextUp<CR>', {})
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
local opts = {noremap = true, silent = true }
local map = function(this, that)
vim.api.nvim_buf_set_keymap(bufnr, 'n', this, that, opts)
end
map('gD', '<cmd>lua vim.lsp.buf.declaration()<CR>')
map('gd', '<cmd>lua vim.lsp.buf.definition()<CR>')
map('K', '<cmd>lua vim.lsp.buf.hover()<CR>')
map('gi', '<cmd>lua vim.lsp.buf.implementation()<CR>')
map('<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>')
map('<leader>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>')
map('<leader>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>')
map('<leader>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>')
map('<leader>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>')
map('<leader>rn', '<cmd>lua vim.lsp.buf.rename()<CR>')
map('gr', '<cmd>lua vim.lsp.buf.references()<CR>')
map('<leader>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>')
-- vim.api.nvim_buf_set_keymap(bufnr, 'v', '<leader>ca', '<cmd>lua vim.lsp.buf.range_code_action()<CR>')
map('<leader>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>')
map('[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>')
map(']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>')
map('<leader>Q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>')
map('<leader>so', [[<cmd>lua require('telescope.builtin').lsp_document_symbols()<CR>]])
map('<leader>so', [[<cmd>lua require('telescope.builtin').lsp_document_symbols()<CR>]])
vim.cmd [[ command! Format execute 'lua vim.lsp.buf.formatting()' ]]
end
return on_attach
|
BTN_L = 0
BTN_R = 1
BTN_U = 2
BTN_D = 3
BTN_O = 4
BTN_X = 5
CLR_BLK = 0
CLR_DBL = 1
CLR_PRP = 2
CLR_DGN = 3
CLR_BRN = 4
CLR_DGY = 5
CLR_GRY = 6
CLR_WHT = 7
CLR_RED = 8
CLR_ORN = 9
CLR_YLW = 10
CLR_GRN = 11
CLR_BLU = 12
CLR_IND = 13
CLR_PNK = 14
CLR_PCH = 15
RESOLUTION_X = 128
RESOLUTION_Y = 120
MAX_VEL = 0.8
FRAME_RATE = 60
COUNTDOWN_TIMEOUT = 59
ENT_BOX = 0
ENT_ITEM = 1
ENT_BEAM = 2
FLAG_PLAYER = 0
FLAG_FLOOR = 1
FLAG_ABSORBED_BY_GRAV = 2
FLAG_COLLIDES_SELF = 3
FLAG_COLLIDES_PLAYER = 4
FLAG_GAP = 5
DIRECTION_UP = 0
DIRECTION_RIGHT = 1
DIRECTION_DOWN = 2
DIRECTION_LEFT = 3
PLAYER_STATE_GROUNDED = "GROUNDED"
PLAYER_STATE_FLOATING = "FLOATING"
PLAYER_STATE_SLIDING = "SLIDING"
PLAYER_STATE_DEAD_FALLING = "DEAD_FALLING"
PLAYER_STATE_DEAD_ZAPPED = "DEAD_ZAPPED"
|
RegisterNetEvent("npc-jobmanager:playerBecameJob")
AddEventHandler("npc-jobmanager:playerBecameJob", function(job, name, notify)
local LocalPlayer = exports["npc-core"]:getModule("LocalPlayer")
LocalPlayer:setVar("job", job)
if notify ~= false then
TriggerEvent("DoLongHudText", job ~= "unemployed" and "New Job: " .. tostring(name) or "You're now unemployed", 1)
end
if name == "Entertainer" then
TriggerEvent('DoLongHudText',"College DJ and Comedy Club pay per person around you",1)
end
if name == "Broadcaster" then
TriggerEvent('DoLongHudText',"(RadioButton + LeftCtrl for radio toggle)",3)
TriggerEvent('DoLongHudText',"Broadcast from this room and give out the vibes to los santos on 1982.9",1)
end
if job == "unemployed" then
SetPedRelationshipGroupDefaultHash(PlayerPedId(),`PLAYER`)
SetPoliceIgnorePlayer(PlayerPedId(),false)
TriggerEvent("ResetRadioChannel");
end
if job == "trucker" then
end
if job == "towtruck" then
TriggerEvent("DoLongHudText","Use /tow to tow cars to your truck.",1)
end
if job == "news" then
TriggerEvent('DoLongHudText',"'H' to use item, F1 change item. (/light r g b)",1)
end
if job == "driving instructor" then
TriggerEvent('DoLongHudText',"'/driving' to use access driving instructor systems",1)
end
if job == "pdm" then
TriggerEvent('DoLongHudText',"Go Sell Some Cars",1)
end
-- TriggerServerEvent("npc-items:updateID",job,exports["isPed"]:retreiveBusinesses())
end)
RegisterNetEvent("npc-core:characterLoaded")
AddEventHandler("npc-core:characterLoaded", function(character)
local LocalPlayer = exports["npc-core"]:getModule("LocalPlayer")
LocalPlayer:setVar("job", "unemployed")
end)
RegisterNetEvent("npc-core:exportsReady")
AddEventHandler("npc-core:exportsReady", function()
exports["npc-core"]:addModule("JobManager", NPC.Jobs)
end) |
--[[
File: LuaNativeUIExample.lua
Author: Mikael Kindborg
Description:
Demo that uses a high-level Lua UI library to create a NativeUI.
The object NativeUI is defined in file: projects/common/LuaLib.lua
Here are some things to try in the LuaLive editor.
First press "Run program" in the editor to run all of the
code in this file. That will create the UI.
Then select a line of code below and press "Do selection".
MessageLabel:SetProp(mosync.MAW_LABEL_FONT_SIZE, "60")
mosync.maWidgetRemoveChild(MessageLabel.GetHandle())
mosync.maWidgetAddChild(MainLayout.GetHandle(), MessageLabel.GetHandle())
--]]
Screen = mosync.NativeUI:CreateWidget
{
type = "Screen"
}
MainLayout = mosync.NativeUI:CreateWidget
{
type = "VerticalLayout",
parent = Screen,
width = mosync.FILL_PARENT,
height = mosync.FILL_PARENT,
backgroundColor = "FF8800"
}
MessageLabel = mosync.NativeUI:CreateWidget
{
type = "Label",
parent = MainLayout,
width = mosync.FILL_PARENT,
height = mosync.WRAP_CONTENT,
fontSize = "36",
fontColor = "FFFFFF",
text = "Demo of MoSync NativeUI"
}
ButtonSayHello = mosync.NativeUI:CreateButton
{
parent = MainLayout,
width = mosync.FILL_PARENT,
height = mosync.WRAP_CONTENT,
text = "Say Hello",
eventFun = function(self, widgetEvent)
MessageLabel:SetProp("text", "Hello World!")
end
}
ButtonSayHi = mosync.NativeUI:CreateButton
{
parent = MainLayout,
width = mosync.FILL_PARENT,
height = mosync.WRAP_CONTENT,
text = "Say Hi",
eventFun = function(self, widgetEvent)
MessageLabel:SetProp("text", "Hi there!")
end
}
mosync.NativeUI:ShowScreen(Screen)
-- Exit on BACK key on Android
mosync.EventMonitor:OnKeyDown(function(key)
if mosync.MAK_BACK == key then
mosync.maExit(0)
end
end)
|
local INSTANCE_ID = string.match(arg[0], "gh%-6035%-(.+)%.lua")
local function unix_socket(name)
return "unix/:./" .. name .. '.sock';
end
require('console').listen(os.getenv('ADMIN'))
if INSTANCE_ID == "master" then
box.cfg({
listen = unix_socket("master"),
})
elseif INSTANCE_ID == "replica1" then
box.cfg({
listen = unix_socket("replica1"),
replication = {
unix_socket("master"),
unix_socket("replica1")
},
election_mode = 'voter'
})
else
assert(INSTANCE_ID == "replica2")
box.cfg({
replication = {
unix_socket("master"),
},
election_mode = 'voter'
})
end
box.once("bootstrap", function()
box.schema.user.grant('guest', 'super')
end)
|
gamestats = {}
function gamestats:enter(previous)
self.previous = previous
self.yModPerc = 100
self.screen = "stats"
self.cursorX,self.cursorY=1,1
tween(0.2,self,{yModPerc=0})
output:sound('stoneslideshort',2)
self.transY = 0
self.maxTransY = 0
self.sideTransY = 0
self.maxSideTransY = 0
local graveyard = load_graveyard()
local wins = load_wins()
local gravesayings = {"R.I.P","Here Lies","In Memorium","Always Remembered"}
self.graveyard = {}
self.wins = {}
self.stats = {}
--Sorting functions:
local sortByDate = function(a,b)
return (a.date and a.date or 0) > (b.date and b.date or 0)
end
local sortByMost = function(a,b)
return (a.sortBy and a.sortBy or 0) > (b.sortBy and b.sortBy or 0)
end
local sortByLeast = function(a,b)
return (a.sortBy and a.sortBy or 0) < (b.sortBy and b.sortBy or 0)
end
--Deal with Stats:
self.stats[1] = {id="achievements",header="Achievements",label = "Achievements",stats={},expand=true}
local abilityStats = {}
if totalstats.ability_used then
for abil,uses in pairs(totalstats.ability_used) do
local id = #abilityStats+1
abilityStats[id] = {}
abilityStats[id].ability = abil
abilityStats[id].uses = uses
abilityStats[id].sortBy = uses
end
table.sort(abilityStats,sortByMost)
local whichAbil = abilityStats[1] and (abilityStats[1].ability == "Possession" or abilityStats[1].ability == "Repair Body") and (abilityStats[2] and (abilityStats[2].ability == "Possession" or abilityStats[2].ability == "Repair Body") and 3 or 2) or 1
end
self.stats[2] = {id="abilities",header="Ability Usage",label = (abilityStats[whichAbil] and "Favorite Ability: " .. abilityStats[whichAbil].ability .. " (" .. abilityStats[whichAbil].uses .. " uses)" or "Favorite Abilities"),stats=abilityStats,expand=true}
local creatTurns,fav=0,nil
local creatureStats = {}
if totalstats.turns_as_creature then
for creat,turns in pairs(totalstats.turns_as_creature) do
local id = #creatureStats+1
creatureStats[id] = {}
creatureStats[id].creat = creat
creatureStats[id].turns = turns
if creat ~= "ghost" then
creatureStats[id].kills = (totalstats.kills_as_creature and totalstats.kills_as_creature[creat] or 0)
creatureStats[id].possessions = (totalstats.creature_possessions and totalstats.creature_possessions[creat] or 0)
creatureStats[id].explosions = (totalstats.exploded_creatures and totalstats.exploded_creatures[creat] or 0)
creatureStats[id].explosionPercent = round((creatureStats[id].explosions / creatureStats[id].possessions)*100)
local ratio = round(turns/(totalstats.creature_possessions[creat] or 1))
creatureStats[id].ratio = ratio
creatureStats[id].sortBy = ratio
creatureStats[id].killRatio = round((creatureStats[id].kills or 0)/((creatureStats[id].possessions and creatureStats[id].possessions > 0 and creatureStats[id].possessions) or 1))
if ratio > creatTurns or fav==nil then
creatTurns,fav=ratio,creat
end
end --end if creat ~= ghost
end --end creat for
table.sort(creatureStats,sortByMost)
end
self.stats[3] = {id="creatures",header="Creature Possession Stats",label = (fav and "Favorite Creature: " .. ucfirst(possibleMonsters[fav].name) .. " (" .. creatTurns .. " average turns per possession)" or "Favorite Creatures"),stats=creatureStats,expand=true}
local killStats = {}
if totalstats.creature_kills then
for creat,kills in pairs(totalstats.creature_kills) do
local id = #killStats+1
killStats[id] = {}
killStats[id].creat = creat
killStats[id].kills = kills
killStats[id].sortBy = kills
end
table.sort(killStats,sortByMost)
end
self.stats[4] = {id="kills",header="Creature Kills",label=(killStats[1] and "Most Killed Creature: " .. ucfirst(possibleMonsters[killStats[1].creat].name) .. " (" .. killStats[1].kills .. " kills)" or "Kills"),stats=killStats,expand=true}
--[[local explosionStats = {}
for creat,explosions in pairs(totalstats.exploded_creatures) do
local id = #explosionStats+1
explosionStats[id] = {}
explosionStats[id].creat = creat
explosionStats[id].explosions = explosions
explosionStats[id].sortBy = explosions
end
table.sort(explosionStats,sortByMost)
self.stats[5] = {id="explosions",header="Creature Explosions",label=(killStats[1] and "Most Exploded Creature: " .. ucfirst(possibleMonsters[explosionStats[1].creat].name) .. " (" .. explosionStats[1].explosions .. " explosions)" or "Explosions"),stats=explosionStats,expand=true}]]
local leaderStats = {}
if totalstats.ally_kills_as_creature then
for leader,kills in pairs(totalstats.ally_kills_as_creature) do
if leader ~= "ghost" then
local id = #leaderStats+1
local deaths = (totalstats.ally_deaths_as_creature and totalstats.ally_deaths_as_creature[leader] or 0)
local possessions = (totalstats.creature_possessions and totalstats.creature_possessions[leader] or 1)
local thralls = (totalstats.thralls_by_body and totalstats.thralls_by_body[leader] or 1)
local killsPerPossession = round(kills/(possessions or 1))
local thrallsPerPossession = round(thralls/(possessions or 1))
local killsPerFollower = round(kills/(thralls or 1))
leaderStats[id] = {}
leaderStats[id].creat = leader
leaderStats[id].kills = kills
leaderStats[id].thralls = thralls
leaderStats[id].followerDeaths = deaths
leaderStats[id].possessions = possessions
leaderStats[id].killsPerFollower = killsPerFollower
leaderStats[id].killsPerPossession = killsPerPossession
leaderStats[id].thrallsPerPossession = thrallsPerPossession
leaderStats[id].sortBy = killsPerFollower
end
end
table.sort(leaderStats,sortByMost)
end
self.stats[5] = {id="leader_kills",header = "Follower Kills as Leader",label=(leaderStats[1] and "Most Effective Leader Body: " .. ucfirst(possibleMonsters[leaderStats[1].creat].name) .. " (" .. leaderStats[1].killsPerFollower .. " Average Follower Kills)" or "Follower Kills as Leader"),stats=leaderStats,expand=true}
local followerStats = {}
if totalstats.thralls then
for follower,thralls in pairs(totalstats.thralls) do
local id = #followerStats+1
local deaths = (totalstats.creature_ally_deaths and totalstats.creature_ally_deaths[follower] or 0)
local kills = (totalstats.allied_creature_kills and totalstats.allied_creature_kills[follower] or 0)
local killsPer = round(kills/(thralls or 1))
followerStats[id] = {}
followerStats[id].creat = follower
followerStats[id].thralls = thralls
followerStats[id].kills = kills
followerStats[id].deaths = deaths
followerStats[id].killsPer = killsPer
followerStats[id].sortBy = killsPer
end
table.sort(followerStats,sortByMost)
end
self.stats[6] = {id="follower_kills",header="Kills by Followers",label=(followerStats[1] and "Most Effective Follower: " .. ucfirst(possibleMonsters[followerStats[1].creat].name) .. " (" .. followerStats[1].kills .. " Average Kills per Follower)" or "Kills by Followers"),stats=followerStats,expand=true}
local levelStats = {}
if totalstats.level_reached then
for level,reached in pairs(totalstats.level_reached) do
local id = #levelStats+1
levelStats[#levelStats+1] = {}
local beaten = (totalstats.level_beaten and totalstats.level_beaten[level] or 0)
local turns = (totalstats.turns_on_level and totalstats.turns_on_level[level] or 0)
levelStats[id].reached = reached
levelStats[id].beaten = beaten
levelStats[id].losses = (totalstats.losses_per_level and totalstats.losses_per_level[level] or 0)
levelStats[id].beatPercent = round((beaten/reached or 1)*100)
levelStats[id].turns = turns
levelStats[id].avgTurns = round(turns/(reached or 1))
levelStats[id].avgTurnsBeat = beaten > 0 and round(turns/beaten) or "N/A"
levelStats[id].name = (specialLevels[level] and (specialLevels[level].genericName or specialLevels[level].generateName()) or false)
levelStats[id].depth = (specialLevels[level] and specialLevels[level].depth or false)
if not levelStats[id].name then
local depth = string.sub(level,8)
levelStats[id].name = "Non-Special Level"
levelStats[id].depth = tonumber(depth)
end
levelStats[id].sortBy = levelStats[id].depth
end
table.sort(levelStats,sortByLeast)
end
self.stats[7] = {id="levels",label="Stats by Level",header="Stats by Level",stats=levelStats,expand=true}
self.stats[8] = {id="games",label="Total Games Started: " .. (totalstats.games or 0)}
self.stats[9] = {id="wins",label="Games Won: " .. (totalstats.wins or 0)}
self.stats[10] = {id="losses",label="Games Lost: " .. (totalstats.losses or 0)}
self.stats[11] = {id="turns",label="Total Turns Played: " .. (totalstats.turns or 0)}
self.stats[12] = {id="turnspergame",label="Average Turns/Game: " .. round((totalstats.turns or 0)/(totalstats.games or 1))}
--Deal with Wins:
for _, win in pairs(wins) do
self.wins[#self.wins+1] = win
if win.stats and win.stats.turns_as_creature then
win.stats.turns_as_creature.ghost = nil
win.stats.favoriteCreatTurns,win.stats.favoriteCreat = get_largest(win.stats.turns_as_creature)
if win.stats.creature_possessions then win.stats.favoriteCreatPossessions = win.stats.creature_possessions[win.stats.favoriteCreat] end
end
if win.stats and win.stats.ability_used then
win.stats.ability_used.Possession = nil
win.stats.ability_used['Repair Body'] = nil
win.stats.favoriteAbilityTurns,win.stats.favoriteAbility = get_largest(win.stats.ability_used)
end
if win.stats and win.stats.turns_on_level then
win.stats.favoriteLevelTurns,win.stats.favoriteLevelID = get_largest(win.stats.turns_on_level)
win.stats.favoriteLevel = (specialLevels[win.stats.favoriteLevelID] and specialLevels[win.stats.favoriteLevelID].generateName() or false)
if not win.stats.favoriteLevel then
local depth = (type(level) == "string" and string.sub(win.stats.favoriteLevelID,8) or win.stats.favoriteLevelID)
win.stats.favoriteLevel = "Generic Level " .. depth
end
end
win.stats.killPossessionAverage = (win.stats.total_possessions and round((win.stats.kills or 0)/win.stats.total_possessions) or "N/A")
end
table.sort(self.wins,sortByDate)
--Deal with Deaths:
for depth,level in pairs(graveyard) do
for _, grave in pairs(level) do
grave.saying = gravesayings[random(#gravesayings)]
grave.depth = depth
self.graveyard[#self.graveyard+1] = grave
if grave.stats and grave.stats.turns_as_creature then
grave.stats.turns_as_creature.ghost = nil
grave.stats.favoriteCreatTurns,grave.stats.favoriteCreat = get_largest(grave.stats.turns_as_creature)
if grave.stats.creature_possessions then grave.stats.favoriteCreatPossessions = grave.stats.creature_possessions[grave.stats.favoriteCreat] end
end
if grave.stats and grave.stats.ability_used then
grave.stats.ability_used.Possession = nil
grave.stats.favoriteAbilityTurns,grave.stats.favoriteAbility = get_largest(grave.stats.ability_used)
end
if grave.stats and grave.stats.turns_on_level then
grave.stats.favoriteLevelTurns,grave.stats.favoriteLevelID = get_largest(grave.stats.turns_on_level)
grave.stats.favoriteLevel = (specialLevels[grave.stats.favoriteLevelID] and specialLevels[grave.stats.favoriteLevelID].generateName() or false)
if not grave.stats.favoriteLevel then
local depth = (type(level) == "string" and string.sub(grave.stats.favoriteLevelID,8) or grave.stats.favoriteLevelID)
grave.stats.favoriteLevel = "Generic Level " .. depth
end
end
grave.stats.killPossessionAverage = (grave.stats.total_possessions and round((grave.stats.kills or 0)/grave.stats.total_possessions) or "N/A")
end
end
table.sort(self.graveyard,sortByDate)
--Last two stats, that depend on wins and losses
local totalWinTurns = 0
for _,win in pairs(self.wins) do
totalWinTurns = totalWinTurns+win.stats.turns
end
self.stats[13] = {id="turnsperwin",label="Average Turns/Win: " .. (totalstats.wins and round(totalWinTurns/totalstats.wins) or "N/A"),stats={}}
local totalLossTurns = 0
for _,grave in pairs(self.graveyard) do
totalLossTurns = totalLossTurns+grave.stats.turns
end
self.stats[14] = {id="turnsperloss",label="Average Turns/Loss: " .. round(totalLossTurns/(totalstats.losses or 1)),stats={}}
end
function gamestats:draw()
self.previous:draw()
local width, height = love.graphics:getWidth(),love.graphics:getHeight()
local padding=prefs['noImages'] and 14 or 32
local fontSize = prefs['fontSize']
love.graphics.push()
love.graphics.translate(0,height*(self.yModPerc/100))
--Draw top nav bar:
output:draw_window(0,0,width-padding,64)
self.closebutton = output:closebutton(math.floor(padding/2),math.floor(padding/2))
love.graphics.setFont(fonts.graveFontBig)
local buttonWidth = fonts.graveFontBig:getWidth("Stats")
self.statsbutton = output:button(padding,padding,buttonWidth,false,(self.cursorY == 1 and self.cursorX == 1 and "hover" or nil),"Stats")
buttonWidth = fonts.graveFontBig:getWidth("Wins" .. (totalstats.wins and "(" .. totalstats.wins .. ")" or ""))
self.winsbutton = output:button(math.floor((width-padding-buttonWidth)/2),padding,buttonWidth,false,(self.cursorY == 1 and self.cursorX == 2 and "hover" or nil),"Wins" .. (totalstats.wins and "(" .. totalstats.wins .. ")" or ""))
buttonWidth = fonts.graveFontBig:getWidth("Losses" .. (totalstats.losses and "(" .. totalstats.losses .. ")" or ""))
self.lossesbutton = output:button(width-padding-buttonWidth,padding,buttonWidth,false,(self.cursorY == 1 and self.cursorX == 3 and "hover" or nil),"Losses" .. (totalstats.losses and "(" .. totalstats.losses .. ")" or ""))
--[[if self.cursorY == 1 and self.cursorX == 1 then
local w = fonts.graveFontBig:getWidth("Stats")
setColor(100,100,100,255)
love.graphics.rectangle("fill",math.floor(padding/3)*2,math.floor(padding/3)*2,w+math.floor(padding/3)*2,48)
setColor(255,255,255,255)
end
love.graphics.printf("Stats",padding,math.floor(padding/3)*2,width-padding*2,"left")
if self.cursorY == 1 and self.cursorX == 2 then
local w = fonts.graveFontBig:getWidth("Wins (" .. (totalstats.wins or 0) .. ")")
setColor(100,100,100,255)
love.graphics.rectangle("fill",math.floor(width/2)-w,math.floor(padding/3)*2,w+padding,48)
setColor(255,255,255,255)
end
love.graphics.printf("Wins (" .. (totalstats.wins or 0) .. ")",padding,math.floor(padding/3)*2,width-padding*2,"center")
if self.cursorY == 1 and self.cursorX == 3 then
local w = fonts.graveFontBig:getWidth("Losses (" .. (totalstats.losses or 0) .. ")")
setColor(100,100,100,255)
love.graphics.rectangle("fill",width-(w+math.floor(padding/3)*2)-padding,math.floor(padding/3)*2,w+padding,48)
setColor(255,255,255,255)
end
love.graphics.printf("Losses (" .. (totalstats.losses or 0) .. ")",padding,math.floor(padding/3)*2,width-padding*2,"right")]]
if self.screen == "stats" then
local sidebarX = round(width/2)+padding
local stopSelect = sidebarX-padding*2
output:draw_window(0,64+padding,sidebarX-padding,height-padding)
output:draw_window(sidebarX,64+padding,width-padding,height-padding)
love.graphics.setFont(fonts.graveFontBig)
love.graphics.printf("Statistics",1,80+padding,sidebarX,"center")
love.graphics.setFont(fonts.textFont)
love.graphics.push()
love.graphics.translate(0,self.transY)
local printY = 80+padding*3
local mouseX,mouseY = love.mouse.getPosition()
local mouseMoved = false
if mouseX ~= output.mouseX or mouseY ~= output.mouseY then
mouseMoved = true
output.mouseX,output.mouseY=mouseX,mouseY
end
--Display the stat list:
for id,stat in ipairs(self.stats) do
if self.cursorY-1 == id then
setColor(100,100,100,255)
love.graphics.rectangle("fill",padding,printY,stopSelect,2+fontSize)
setColor(255,255,255,255)
elseif mouseX > padding and mouseX < sidebarX-padding and mouseY > printY and mouseY < printY+fontSize and stat.expand then
setColor(50,50,50,255)
love.graphics.rectangle("fill",padding,printY,stopSelect,2+fontSize)
setColor(255,255,255,255)
end
if printY+self.transY >= 80+padding*3 then
local expand = false
if stat.expand then
expand = true
end
love.graphics.print(stat.label .. (expand and " > " or ""),padding,printY)
end
printY = printY + fontSize
self.maxTransY = 0 --height-printY
end--end stat for
love.graphics.pop()
--Display the selected stat:
local stat = self.stats[self.cursorY-1]
if stat and stat.expand then
love.graphics.setFont(fonts.graveFontBig)
love.graphics.printf(stat.header or "Stat?",sidebarX,80+padding,width-sidebarX,"center")
love.graphics.setFont(fonts.textFont)
local function stencilFunc()
love.graphics.rectangle("fill",sidebarX,80+padding*2,width-sidebarX,height-padding*2-98)
end
love.graphics.stencil(stencilFunc,"replace",1)
love.graphics.setStencilTest("greater",0)
if stat.id == "achievements" then
if self.maxSideTransY < 0 then
local scrollAmt = self.sideTransY / self.maxSideTransY
self.sideScrollPositions = output:scrollbar(width-padding*2,96+padding*2,height-padding,scrollAmt)
end
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
local printY = 96+padding*(prefs['noImages'] and 6 or 3)
local printX = sidebarX+64
local gridX,gridY=1,1
local maxGridX=nil
for id,achiev in pairs(achievementList) do
local isMouse = (mouseX > printX-32 and mouseX < printX+96 and mouseY > printY-32+self.sideTransY and mouseY < printY+96+self.sideTransY)
local selected = (gridX == self.cursorX-1 and gridY == (self.achievementCursorY or 1)) or (mouseMoved and isMouse)
if selected then
self.cursorX,self.achievementCursorY = gridX+1,gridY
setColor(100,100,100,255)
love.graphics.rectangle('fill',printX-32,printY-32,128,128)
setColor(255,255,255,255)
local _, tlines = fonts.descFont:getWrap(achiev.description,128)
love.graphics.printf(achiev.description,printX-32,math.max(printY-32,math.floor(printY+64-8-(#tlines*fontSize))),128,"center")
if not isMouse then
if printY-32+self.sideTransY < 80+padding*2 then self:sidebarScrollUp()
elseif printY+96+self.sideTransY > height then self:sidebarScrollDown() end
end
else
local has = achievements:has_achievement(id)
local img = (has and (images['achievement' .. id] and images['achievement' .. id] or images['achievementunknown']) or (images['achievement' .. id .. 'locked'] and images['achievement' .. id .. 'locked'] or images['achievementunknownlocked']))
if prefs['noImages'] then
if not has then
setColor(125,125,125,255)
love.graphics.printf(achiev.name,printX-32,printY+16,128,"center")
setColor(255,255,255,255)
else
love.graphics.printf(achiev.name,printX-32,printY+16,128,"center")
end
else
setColor(33,33,33,255)
love.graphics.rectangle('fill',printX,printY-8,66,66)
setColor(255,255,255,255)
love.graphics.rectangle('line',printX-1,printY-9,66,66)
love.graphics.draw(img,printX,printY-8)
love.graphics.printf(achiev.name,printX-32,printY+64-8,128,"center")
end
end
printX = printX+128
gridX = gridX+1
if printX+128 > width then
printX = sidebarX+64
printY = printY + 128
maxGridX = gridX
gridX = 1
gridY = gridY+1
end
end --end achiev for
local maxGridY = gridY
local lastGridX = gridX
if self.cursorX > maxGridX or ((self.achievementCursorY or 1) == maxGridY and self.cursorX > lastGridX) then
if self.achievementCursorY < maxGridY then
self.cursorX = maxGridX
else
self.cursorX = math.min(maxGridX,lastGridX)
end
end
if (self.achievementCursorY or 1) > maxGridY then self.achievementCursorY = maxGridY end
self.maxSideTransY = height-printY-128
love.graphics.pop()
elseif stat.id == "abilities" then
if self.maxSideTransY < 0 then
local scrollAmt = self.sideTransY / self.maxSideTransY
self.sideScrollPositions = output:scrollbar(width-padding*2,96+padding*2,height-padding,scrollAmt)
end
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
local printY = 80+padding*3
for _,abil in pairs(stat.stats) do
love.graphics.print(abil.ability .. ": " .. abil.uses,sidebarX+padding,printY)
printY = printY+fontSize
end
self.maxSideTransY = height-printY
love.graphics.pop()
elseif stat.id == "creatures" then
if self.maxSideTransY < 0 then
if self.cursorX == 2 then
setColor(50,50,50,255)
love.graphics.rectangle("fill",width-padding*2,96+padding*2,padding,height-padding-96-padding*2)
setColor(255,255,255,255)
end
local scrollAmt = self.sideTransY / self.maxSideTransY
self.sideScrollPositions = output:scrollbar(width-padding*2,96+padding*2,height-padding,scrollAmt)
end
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
love.graphics.printf("Total Possessions: " .. (totalstats.total_possessions or 0) .. ", Total Explosions: " .. (totalstats.explosions or 0),sidebarX,80+padding+fontSize*3,width-sidebarX,"center")
local printY = 80+padding*3
for _,creat in pairs(stat.stats) do
local name = ucfirst(possibleMonsters[creat.creat].name)
if creat.possessions then
love.graphics.print("Total " .. name.. " possessions: " .. creat.possessions,sidebarX+padding*2,printY)
printY = printY+fontSize
end
if creat.explosions then
love.graphics.print("Total " .. name.. " explosions: " .. creat.explosions,sidebarX+padding*2,printY)
printY = printY+fontSize
end
if creat.explosionPercent then
love.graphics.print("Explosion ratio: " .. creat.explosionPercent .. "%",sidebarX+padding*2,printY)
printY = printY+fontSize
end
love.graphics.print("Turns as " .. name.. ": " .. creat.turns,sidebarX+padding*2,printY)
if creat.ratio then
printY = printY+fontSize
love.graphics.print("Average turns per possession: " .. creat.ratio,sidebarX+padding*2,printY)
end
if creat.kills then
printY = printY+fontSize
love.graphics.print("Kills as " .. name.. ": " .. creat.kills,sidebarX+padding*2,printY)
end
if creat.killRatio then
printY = printY+fontSize
love.graphics.print("Average Kills per possession: " .. creat.killRatio,sidebarX+padding*2,printY)
end
local c = possibleMonsters[creat.creat]
c.image_frame = 1
c.baseType = "creature"
if c.id == nil then c.id = creat.creat end
output.display_entity(c,sidebarX+padding-8,printY-round(fontSize*(creat.creat == "ghost" and 0.5 or 3.5)),"force")
printY = printY+fontSize*2
end
self.maxSideTransY = height-printY-fontSize
love.graphics.pop()
elseif stat.id == "kills" then
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
love.graphics.printf("Total Kills: " .. (totalstats.kills or 0),sidebarX,80+padding+fontSize*3,width-sidebarX,"center")
local printY = 80+padding*3
for _,creat in pairs(stat.stats) do
love.graphics.print(ucfirst(possibleMonsters[creat.creat].name) .. "s Killed: " .. creat.kills,sidebarX+padding,printY)
printY = printY+fontSize
end
self.maxSideTransY = height-printY
love.graphics.pop()
elseif stat.id == "explosions" then
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
love.graphics.printf("Total Explosions: " .. totalstats.explosions,sidebarX,80+padding+fontSize*3,width-sidebarX,"center")
local printY = 80+padding*3
for _,creat in pairs(stat.stats) do
love.graphics.print(ucfirst(possibleMonsters[creat.creat].name) .. "s Exploded: " .. creat.explosions,sidebarX+padding,printY)
printY = printY+fontSize
end
self.maxSideTransY = height-printY
love.graphics.pop()
elseif stat.id == "leader_kills" then
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
local printY = 80+padding*3
for _,creat in pairs(stat.stats) do
local name = ucfirst(possibleMonsters[creat.creat].name)
love.graphics.print("Total Followers as " .. name .. ": " .. creat.thralls,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Follower kills as " .. name .. ": " .. creat.kills,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Average Kills per Follower as " .. name .. ": " .. creat.killsPerFollower,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print(name .. " Possessions: " .. creat.possessions,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Average Number of Followers per " .. name .. " Possession: " .. creat.thrallsPerPossession,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Average Kills by Followers per " .. name .. " Possession: " .. creat.killsPerPossession,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Follower deaths as " .. name .. ": " .. creat.followerDeaths,sidebarX+padding*2,printY)
local c = possibleMonsters[creat.creat]
c.image_frame = 1
c.baseType = "creature"
if c.id == nil then c.id = creat.creat end
output.display_entity(c,sidebarX+padding-8,printY-round(fontSize*(creat.creat == "ghost" and 0.5 or 3.5)),"force")
printY = printY+fontSize*2
end
self.maxSideTransY = height-printY
love.graphics.pop()
elseif stat.id == "follower_kills" then
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
local printY = 80+padding*3
for _,creat in pairs(stat.stats) do
local name = ucfirst(possibleMonsters[creat.creat].name)
love.graphics.print("Number of " .. name .. " Followers: " .. creat.thralls,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Kills by " .. name .. " Followers: " .. creat.kills,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print("Average Kills per " .. name .. " Follower: " .. creat.killsPer,sidebarX+padding*2,printY)
printY = printY+fontSize
love.graphics.print(name .. " Follower Deaths: " .. creat.deaths,sidebarX+padding*2,printY)
local c = possibleMonsters[creat.creat]
c.image_frame = 1
c.baseType = "creature"
if c.id == nil then c.id = creat.creat end
output.display_entity(c,sidebarX+padding-8,printY-round(fontSize*(creat.creat == "ghost" and 0.5 or 2)),"force")
printY = printY+fontSize*2
end
self.maxSideTransY = height-printY
love.graphics.pop()
elseif stat.id == "levels" then
if self.maxSideTransY < 0 then
if self.cursorX == 2 then
setColor(50,50,50,255)
love.graphics.rectangle("fill",width-padding*2,96+padding*2,padding,height-padding-96-padding*2)
setColor(255,255,255,255)
end
local scrollAmt = self.sideTransY / self.maxSideTransY
self.sideScrollPositions = output:scrollbar(width-padding*2,96+padding*2,height-padding,scrollAmt)
end
love.graphics.push()
love.graphics.translate(0,self.sideTransY)
local printY = 80+padding*3
for level,stat in ipairs(stat.stats) do
love.graphics.printf((stat.depth and "Depth " .. tostring(11-stat.depth) .. ": " or "") .. tostring(stat.name),sidebarX,printY,width-sidebarX,"center")
printY=printY+fontSize
love.graphics.print("Times Reached: " .. stat.reached,sidebarX+padding*2,printY)
printY=printY+fontSize
love.graphics.print("Times Beaten: " .. stat.beaten,sidebarX+padding*2,printY)
printY=printY+fontSize
love.graphics.print("Beaten Ratio: " .. stat.beatPercent .. "%",sidebarX+padding*2,printY)
printY=printY+fontSize
love.graphics.print("Total Turns on Level: " .. stat.turns,sidebarX+padding*2,printY)
printY=printY+fontSize
love.graphics.print("Average Turns on Level: " .. stat.avgTurns,sidebarX+padding*2,printY)
printY=printY+fontSize
love.graphics.print("Average Turns to Beat Level: " .. stat.avgTurnsBeat,sidebarX+padding*2,printY)
printY=printY+fontSize*2
end
self.maxSideTransY = height-printY
love.graphics.pop()
end
love.graphics.setStencilTest()
end
elseif self.screen == "wins" then
local w1end,w2start,w2end = math.floor(width/2),math.ceil(width/2)+padding,math.ceil(width/2)+math.floor(width/2)-padding
local windowY = 64+padding
output:draw_window(0,windowY,w1end,height-padding)
output:draw_window(w2start,windowY,w2end,height-padding)
love.graphics.setFont(fonts.graveFontBig)
love.graphics.printf("Wins",1,windowY+math.floor(padding/2),math.floor(width/2),"center")
love.graphics.line(padding,windowY+math.floor(padding/2)+fontSize*3,w1end-padding,windowY+math.floor(padding/2)+fontSize*3)
love.graphics.setFont(fonts.textFont)
if self.maxTransY < 0 then
local scrollAmt = self.transY / self.maxTransY
self.scrollPositions = output:scrollbar(w1end-padding,96+padding*2,height-padding,scrollAmt)
end
love.graphics.push()
local function stencilFunc()
love.graphics.rectangle("fill",padding,windowY+math.floor(padding/2)+fontSize*3,w1end,height-padding-(windowY+math.floor(padding/2)+fontSize*2))
end
love.graphics.stencil(stencilFunc,"replace",1)
love.graphics.setStencilTest("greater",0)
love.graphics.translate(0,self.transY)
local printY = windowY+padding*(prefs['noImages'] and 4 or 2)
for id,grave in ipairs(self.wins) do
local dateWidth = fonts.textFont:getWidth("Won " .. os.date("%H:%M, %b %d, %Y",grave.date))
if self.cursorY-1 == id then
setColor(100,100,100,255)
love.graphics.rectangle("fill",padding,printY,w1end-padding*2,2+fontSize)
setColor(255,255,255,255)
else
local mouseX,mouseY = love.mouse.getPosition()
if mouseY-self.transY > printY and mouseY-self.transY < printY+fontSize and mouseX > padding and mouseX < w1end-padding then
setColor(66,66,66,255)
love.graphics.rectangle("fill",padding,printY,w1end-padding*2,2+fontSize)
setColor(255,255,255,255)
end
end
grave.printY = printY
love.graphics.print(grave.name,padding,printY)
love.graphics.printf("Won " .. os.date("%H:%M, %b %d, %Y",grave.date),w1end-padding-dateWidth,printY,dateWidth,"right")
printY = printY+fontSize
end
self.maxTransY = height-printY-fontSize-padding
love.graphics.setStencilTest()
love.graphics.pop()
if self.wins[self.cursorY-1] then
local win = self.wins[self.cursorY-1]
local printY = windowY+math.floor(padding/2)
love.graphics.setFont(fonts.graveFontBig)
love.graphics.printf(win.name,w2start,printY,w2end-w2start,"center")
local _,lines = fonts.graveFontBig:getWrap(win.name,w2end-w2start+padding)
printY = printY+padding*#lines
love.graphics.setFont(fonts.graveFontSmall)
love.graphics.printf("Won at " .. os.date("%H:%M, %b %d, %Y",win.date),w2start,printY,w2end-w2start,"center")
printY = printY+padding
if win.stats then
love.graphics.setFont(fonts.textFont)
love.graphics.print("Turns played: " .. (win.stats.turns or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Kills: " .. (win.stats.kills or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Possessions: " .. (win.stats.total_possessions or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Average Kills per Body: " .. (win.stats.killPossessionAverage or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Bodies exploded: " .. (win.stats.explosions or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Most Time As: " .. (win.stats.favoriteCreat and ucfirst(possibleMonsters[win.stats.favoriteCreat].name) .. " (" .. win.stats.favoriteCreatTurns .. " turns, " .. (win.stats.favoriteCreatPossessions or "Unknown") .. " possessions)" or "Unknown"),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Favorite Ability: " .. (win.stats.favoriteAbility and win.stats.favoriteAbility .. " (" .. win.stats.favoriteAbilityTurns .. " uses)" or "Unknown"),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Most Time Spent On: " .. (win.stats.favoriteLevel and win.stats.favoriteLevel .. " (" .. win.stats.favoriteLevelTurns .. " turns)" or "Unknown"),w2start+padding,printY)
end
end
elseif self.screen == "losses" then
local w1end,w2start,w2end = math.floor(width/2),math.ceil(width/2)+padding,math.ceil(width/2)+math.floor(width/2)-padding
local windowY = 64+padding
output:draw_window(0,windowY,w1end,height-padding)
output:draw_window(w2start,windowY,w2end,height-padding)
love.graphics.setFont(fonts.graveFontBig)
love.graphics.printf("Losses",1,windowY+math.floor(padding/2),math.floor(width/2),"center")
love.graphics.line(padding,windowY+math.floor(padding/2)+fontSize*3,w1end-padding,windowY+math.floor(padding/2)+fontSize*3)
love.graphics.setFont(fonts.textFont)
if self.maxTransY < 0 then
local scrollAmt = self.transY / self.maxTransY
self.scrollPositions = output:scrollbar(w1end-padding,96+padding*2,height-padding,scrollAmt)
end
love.graphics.push()
local function stencilFunc()
love.graphics.rectangle("fill",padding,windowY+math.floor(padding/2)+fontSize*3,w1end,height-padding-(windowY+math.floor(padding/2)+fontSize*2))
end
love.graphics.stencil(stencilFunc,"replace",1)
love.graphics.setStencilTest("greater",0)
love.graphics.translate(0,self.transY)
local printY = windowY+padding*(prefs['noImages'] and 4 or 2)
for id,grave in ipairs(self.graveyard) do
local dateWidth = fonts.textFont:getWidth("Died " .. os.date("%H:%M, %b %d, %Y",grave.date))
if self.cursorY-1 == id then
setColor(100,100,100,255)
love.graphics.rectangle("fill",padding,printY,w1end-padding*2,2+fontSize)
setColor(255,255,255,255)
else
local mouseX,mouseY = love.mouse.getPosition()
if mouseY-self.transY > printY and mouseY-self.transY < printY+fontSize and mouseX > padding and mouseX < w1end-padding then
setColor(66,66,66,255)
love.graphics.rectangle("fill",padding,printY,w1end-padding*2,2+fontSize)
setColor(255,255,255,255)
end
end
grave.printY = printY
love.graphics.print(grave.name,padding,printY)
love.graphics.printf("Died " .. os.date("%H:%M, %b %d, %Y",grave.date),w1end-padding-dateWidth,printY,dateWidth,"right")
printY = printY+fontSize
end
self.maxTransY = height-printY-fontSize-padding
love.graphics.setStencilTest()
love.graphics.pop()
if self.graveyard[self.cursorY-1] then
local grave = self.graveyard[self.cursorY-1]
local printY = windowY+math.floor(padding/2)
love.graphics.setFont(fonts.graveFontBig)
love.graphics.printf(grave.saying,w2start,printY,w2end-w2start,"center")
printY = printY+padding
love.graphics.printf(grave.name,w2start,printY,w2end-w2start,"center")
local _,lines = fonts.graveFontBig:getWrap(grave.name,w2end-w2start+padding)
printY = printY+padding*#lines
love.graphics.setFont(fonts.graveFontSmall)
love.graphics.printf("Killed by " .. grave.killer,w2start,printY,w2end-w2start,"center")
_,lines = fonts.graveFontBig:getWrap("Killed by " .. grave.killer,w2end-w2start+padding)
printY = printY+math.floor(padding/3)*2*#lines
love.graphics.printf("at " .. os.date("%H:%M, %b %d, %Y",grave.date),w2start,printY,w2end-w2start,"center")
_,lines = fonts.graveFontBig:getWrap("at " .. os.date("%H:%M, %b %d, %Y",grave.date),w2end-w2start+padding)
printY = printY+math.floor(padding/3)*2*#lines
love.graphics.printf((grave.levelname and grave.levelname .. ", " or "") .. "Depth " .. grave.depth,w2start,printY,w2end-w2start,"center")
printY = printY+padding
if grave.stats then
love.graphics.setFont(fonts.textFont)
love.graphics.print("Turns played: " .. (grave.stats.turns or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Kills: " .. (grave.stats.kills or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Possessions: " .. (grave.stats.total_possessions or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Average Kills per Body: " .. (grave.stats.killPossessionAverage or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Bodies exploded: " .. (grave.stats.explosions or 0),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Most Time As: " .. (grave.stats.favoriteCreat and ucfirst(possibleMonsters[grave.stats.favoriteCreat].name) .. " (" .. grave.stats.favoriteCreatTurns .. " turns, " .. (grave.stats.favoriteCreatPossessions or "Unknown") .. " possessions)" or "Unknown"),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Favorite Ability: " .. (grave.stats.favoriteAbility and grave.stats.favoriteAbility .. " (" .. grave.stats.favoriteAbilityTurns .. " uses)" or "Unknown"),w2start+padding,printY)
printY = printY + fontSize
love.graphics.print("Most Time Spent On: " .. (grave.stats.favoriteLevel and grave.stats.favoriteLevel .. " (" .. grave.stats.favoriteLevelTurns .. " turns)" or "Unknown"),w2start+padding,printY)
end
end
end
love.graphics.pop()
end
function gamestats:keypressed(key)
if key == "escape" then
self:switchBack()
elseif key == "up" then
if self.screen == "stats" and self.cursorX > 1 and self.cursorY ~= 1 then
if self.stats[self.cursorY-1] and self.stats[self.cursorY-1].id == "achievements" then
self.achievementCursorY = math.max(self.achievementCursorY and self.achievementCursorY-1 or 1,1)
else
self:sidebarScrollUp()
--self.sideTransY = math.min(self.sideTransY+prefs['fontSize']*5,0)
end
else
self.cursorY = math.max(self.cursorY-1,1)
end
elseif key == "down" then
local maxY = (self.screen == "losses" and #self.graveyard+1) or (self.screen == "stats" and #self.stats+1) or (self.screen == "wins" and #self.wins+1)
if self.screen == "stats" and self.cursorX > 1 and self.cursorY ~= 1 then
if self.stats[self.cursorY-1] and self.stats[self.cursorY-1].id == "achievements" then
self.achievementCursorY = (self.achievementCursorY and self.achievementCursorY+1 or 2)
else
self:sidebarScrollDown()
--self.sideTransY = math.max(self.sideTransY-prefs['fontSize']*5,self.maxSideTransY)
end
else
if self.screen ~= "stats" or self.stats[self.cursorY].expand then
self.cursorY = math.min(self.cursorY+1,(maxY or 1))
if self.screen == "stats" then self.cursorX = 1 self.sideTransY = 0 end
end
end
elseif key == "left" then
if self.cursorY == 1 then
self.cursorX = math.max(self.cursorX-1,1)
else
if self.screen == "stats" then
self.cursorX = math.max(self.cursorX-1,1)
else
self.cursorY = 1
self.cursorX = (self.screen == "losses" and 2 or 1)
end
end
elseif key == "right" then
if self.cursorY == 1 then
self.cursorX = math.min(self.cursorX+1,3)
else
if self.screen == "stats" then
if self.stats[self.cursorY-1] and self.stats[self.cursorY-1].expand and self.maxSideTransY < 0 then
self.cursorX = self.cursorX + 1
if not self.stats[self.cursorY-1] or self.stats[self.cursorY-1].id ~= "achievements" then
self.cursorX = 2
end
end
elseif self.screen == "wins" then
self.cursorY = 1
self.cursorX = 3
end
end
elseif key == "return" or key == "kpenter" then
if self.cursorY == 1 then
if self.cursorX == 1 then
self.screen = "stats"
self.transY = 0
self.cursorY = 1
elseif self.cursorX == 2 then
self.screen = "wins"
self.transY = 0
self.cursorY = 1
elseif self.cursorX == 3 then
self.screen = "losses"
self.transY = 0
self.cursorY = 1
end --end cursorX if
end --end cursorY if
end --end key if
end
function gamestats:wheelmoved(x,y)
local padding=prefs['noImages'] and 14 or 32
local sidebarX = round(love.graphics:getWidth()/2)+padding
if self.screen ~= "stats" or love.mouse.getX() < sidebarX then
if y < 0 then
self:scrollDown()
elseif y > 0 then
self:scrollUp()
end
else
if y > 0 then
self:sidebarScrollUp()
output.mouseX,output.mouseY=0,0
elseif y < 0 then
self:sidebarScrollDown()
output.mouseX,output.mouseY=0,0
end
end
end
function gamestats:scrollDown()
self.transY = math.max(self.transY-prefs['fontSize']*5,self.maxTransY)
end
function gamestats:scrollUp()
self.transY = math.min(self.transY+prefs['fontSize']*5,0)
end
function gamestats:sidebarScrollDown()
if self.maxSideTransY < 0 then self.sideTransY = math.max(self.sideTransY-prefs['fontSize']*5,self.maxSideTransY) end
end
function gamestats:sidebarScrollUp()
if self.maxSideTransY < 0 then self.sideTransY = math.min(self.sideTransY+prefs['fontSize']*5,0) end
end
function gamestats:update(dt)
if self.switchNow == true then
self.switchNow = nil
Gamestate.switch(self.previous)
Gamestate.update(dt)
return
end
--Handle scrolling:
if (love.mouse.isDown(1)) and self.sideScrollPositions then
local x,y = love.mouse.getPosition()
local upArrow = self.sideScrollPositions.upArrow
local downArrow = self.sideScrollPositions.downArrow
local elevator = self.sideScrollPositions.elevator
if x>upArrow.startX and x<upArrow.endX and y>upArrow.startY and y<upArrow.endY then
self:sidebarScrollUp()
elseif x>downArrow.startX and x<downArrow.endX and y>downArrow.startY and y<downArrow.endY then
self:sidebarScrollDown()
elseif x>elevator.startX and x<elevator.endX and y>upArrow.endY and y<downArrow.startY then
if y<elevator.startY then self:sidebarScrollUp()
elseif y>elevator.endY then self:sidebarScrollDown() end
end --end clicking on arrow
end
if (love.mouse.isDown(1)) and self.scrollPositions then
local x,y = love.mouse.getPosition()
local upArrow = self.scrollPositions.upArrow
local downArrow = self.scrollPositions.downArrow
local elevator = self.scrollPositions.elevator
if x>upArrow.startX and x<upArrow.endX and y>upArrow.startY and y<upArrow.endY then
self:scrollUp()
elseif x>downArrow.startX and x<downArrow.endX and y>downArrow.startY and y<downArrow.endY then
self:scrollDown()
elseif x>elevator.startX and x<elevator.endX and y>upArrow.endY and y<downArrow.startY then
if y<elevator.startY then self:scrollUp()
elseif y>elevator.endY then self:scrollDown() end
end --end clicking on arrow
end
end
function gamestats:switchBack()
tween(0.2,self,{yModPerc=100})
output:sound('stoneslideshortbackwards',2)
Timer.after(0.2,function() self.switchNow=true end)
end
function gamestats:mousepressed(x,y,button)
if button == 2 or (x > self.closebutton.minX and x < self.closebutton.maxX and y > self.closebutton.minY and y < self.closebutton.maxY) then
self:switchBack()
elseif x > self.statsbutton.minX and x < self.statsbutton.maxX and y > self.statsbutton.minY and y < self.statsbutton.maxY then
self.screen = "stats"
self.transY = 0
self.cursorY = 1
self.cursorX = 1
elseif x > self.winsbutton.minX and x < self.winsbutton.maxX and y > self.winsbutton.minY and y < self.winsbutton.maxY then
self.screen = "wins"
self.transY = 0
self.cursorY = 1
self.cursorX = 2
elseif x > self.lossesbutton.minX and x < self.lossesbutton.maxX and y > self.lossesbutton.minY and y < self.lossesbutton.maxY then
self.screen = "losses"
self.transY = 0
self.cursorY = 1
self.cursorX = 3
end
local padding=prefs['noImages'] and 14 or 32
local fontSize = prefs['fontSize']
local width = love.graphics:getWidth()
local sidebarX = (self.screen == "stats" and round(width/2)+padding or math.ceil(width/2)+padding)
local loopThrough = {}
if self.screen == "stats" then
loopThrough = self.stats
elseif self.screen == "wins" then
loopThrough = self.wins
elseif self.screen == "losses" then
loopThrough = self.graveyard
end
for id,item in ipairs(loopThrough) do
local printY = (self.screen == "stats" and 80+padding*3+(id-1)*fontSize+self.transY or (item.printY and item.printY+self.transY or -1000))
if x > padding and x < sidebarX-padding-(self.screen == "stats" and 0 or padding) and y > printY and y < printY+fontSize and (item.expand or self.screen ~= "stats") then
self.cursorY = id+1
self.cursorX = 1
self.sideTransY = 0
self.achievementCursorY=0
end
end
end |
plugin =
{
type = "piglet",
name = "piglet::codec_data",
test = function()
dofile(SCRIPT_DIR .. "/../common.lua")
return run_tests(tests)
end
}
INIT_PROTO = 1
DEFAULT_VALUES =
{
next_prot_id = 0,
lyr_len = 0,
invalid_bytes = 0,
proto_bits = 0,
codec_flags = 0,
ip_layer_cnt = 0,
ip6_extension_count = 0,
curr_ip6_extension = 0,
ip6_csum_proto = 0
}
VALUES =
{
next_prot_id = 1,
lyr_len = 2,
invalid_bytes = 3,
proto_bits = 4,
codec_flags = 5,
ip_layer_cnt = 6,
ip6_extension_count = 7,
curr_ip6_extension = 8,
ip6_csum_proto = 9
}
tests =
{
initialize_default = function()
local cd = CodecData.new()
assert(cd)
assert(cd:get().next_prot_id == 0)
end,
initialize_with_number = function()
local cd = CodecData.new(INIT_PROTO)
assert(cd:get().next_prot_id == INIT_PROTO)
end,
initialize_with_table = function()
local cd = CodecData.new()
check.tables_equal(DEFAULT_VALUES, cd:get())
cd:set(VALUES)
check.tables_equal(VALUES, cd:get())
end
}
|
--------------------------------------------------------------------------------------------------
-- Localized messages and options in English
--------------------------------------------------------------------------------------------------
--Slash Commands
MYREP_CMD_STATUS = "status";
MYREP_CMD_DEBUG = "debug";
--Messages
MYREP_MSG_ON = "On";
MYREP_MSG_OFF = "Off";
MYREP_MSG_MORE = "Additional infos";
MYREP_MSG_BLIZZ = "Blizzard messages";
MYREP_MSG_SPLASH = "Splash screen";
MYREP_MSG_PERCENT = "Percent";
MYREP_MSG_FRAME = "Chatframe";
MYREP_MSG_TPL = "Template";
MYREP_MSG_DEBUG = "Debug";
MYREP_INFO = "Standard View";
MYREP_TOOLTIP = "Tooltip View";
MYREP_INFO_TEXT = "Rank";
MYREP_INFO_PERCENT = "Percent";
MYREP_INFO_ABSOLUTE = "Absolute";
MYREP_INFO_DIFFERENCE = "Session";
MYREP_INFO_PARA_REWARDS = "Rewards";
MYREP_MSG_NOTIFY = "Reputation notification now set to this frame.";
MYREP_MSG_INVALID_FRAME = MYREP_MSG_FRAME.." is invalid. Valid values: 1-%d.";
--Tooltips
MYREP_TOOLTIP_ENABLED = "Enables/disables myReputation.";
MYREP_TOOLTIP_SPLASH = "Toggles the splash screen on reaching next standing.";
MYREP_TOOLTIP_BLIZZ = "Toggles blizzards reputation messages.";
MYREP_TOOLTIP_MORE = "Toggles additional chat messages.";
--Notifications
MYREP_NOTIFICATION_GAINED = "Your reputation with %s has increased by %d (%d/%d).";
MYREP_NOTIFICATION_LOST = "Your reputation with %s has decreased by %d (%d/%d).";
MYREP_NOTIFICATION_NEEDED = "%d reputation (%d repetitions) needed until %s.";
MYREP_NOTIFICATION_LEFT = "%d reputation (%d repetitions) left until %s.";
MYREP_NOTIFICATION_REACHED = "%s reputation reached with %s.";
--Friend Levels
MYREP_FRIEND_LEVEL_STRANGER = "Stranger";
MYREP_FRIEND_LEVEL_ACQUAINTANCE = "Acquaintance";
MYREP_FRIEND_LEVEL_BUDDY = "Buddy";
MYREP_FRIEND_LEVEL_FRIEND = "Friend";
MYREP_FRIEND_LEVEL_GOODFRIEND = "Good Friend";
MYREP_FRIEND_LEVEL_BESTFRIEND = "Best Friend";
MYREP_FRIEND_LEVEL_PAL = "Pal";
--Follower Levels
MYREP_FOLLOWER_LEVEL_BODYGUARD = "Bodyguard";
MYREP_FOLLOWER_LEVEL_TRUSTED_BODYGUARD = "Trusted Bodyguard";
MYREP_FOLLOWER_LEVEL_PERSONAL_WINGMAN = "Personal Wingman";
|
function API.ItemData(id, name, weight, subTitle, type, hungerVar, thirstVar, droppable)
local self = {}
self.id = id
self.name = name
self.weight = weight
self.type = type
self.subTitle = subTitle or "NULL"
self.hungerVar = hungerVar or 0
self.thirstVar = thirstVar or 0
self.droppable = droppable
-- self.worldModel = 'default_prop'
self.getId = function()
return self.id
end
self.getName = function(this)
return self.name
end
self.isDroppable = function(this)
return self.droppable
end
self.getSubTitle = function(this)
return self.subTitle
end
self.getWeight = function()
return self.weight
end
self.getType = function()
return self.type
end
self.getHungerVar = function()
return self.hungerVar
end
self.getThirstVar = function()
return self.thirstVar
end
-- # Caso queria fazer um ItemDrop com um prop
--
-- self.getWorldModel = function()
-- return self.worldModel
-- end
self.onUse = function(this, v)
self.use = v
end
self.use = function(this, User)
return false
end
return self
end |
--- LPeg PEG pattern matching.
-- @module lpeg
local lpeg = {}
---
-- The matching function. It attempts to match the given pattern against the
-- subject string. If the match succeeds, returns the index in the subject of
-- the first character after the match, or the captured values (if the pattern
-- captured any value).
--
-- An optional numeric argument init makes the match starts at that position in
-- the subject string. As usual in Lua libraries, a negative value counts from
-- the end.
--
-- Unlike typical pattern-matching functions, match works only in anchored mode;
-- that is, it tries to match the pattern with a prefix of the given subject
-- string (at position init), not with an arbitrary substring of the subject.
-- So, if we want to find a pattern anywhere in a string, we must either write a
-- loop in Lua or write a pattern that matches anywhere. This second approach is
-- easy and quite efficient; see examples.
function lpeg.match(pattern, subject , init) end
---
-- If the given value is a pattern, returns the string "pattern". Otherwise
-- returns nil.
function lpeg.type(value) end
---
-- Returns a string with the running version of LPeg.
function lpeg.version() end
---
-- Sets the maximum size for the backtrack stack used by LPeg to track calls and
-- choices. Most well-written patterns need little backtrack levels and
-- therefore you seldom need to change this maximum; but a few useful patterns
-- may need more space. Before changing this maximum you should try to rewrite
-- your pattern to avoid the need for extra space.
function lpeg.setmaxstack(max) end
---
-- Converts the given value into a proper pattern, according to the following
-- rules:
-- * If the argument is a pattern, it is returned unmodified.
-- * If the argument is a string, it is translated to a pattern that matches
-- literally the string.
-- * If the argument is a non-negative number n, the result is a pattern that
-- matches exactly n characters.
-- * If the argument is a negative number -n, the result is a pattern that
-- succeeds only if the input string does not have n characters: lpeg.P(-n)
-- is equivalent to -lpeg.P(n) (see the unary minus operation).
-- * If the argument is a boolean, the result is a pattern that always
-- succeeds or always fails (according to the boolean value), without
-- consuming any input.
-- * If the argument is a table, it is interpreted as a grammar (see
-- Grammars).
-- * If the argument is a function, returns a pattern equivalent to a
-- match-time capture over the empty string.
function lpeg.P(value) end
---
-- Returns a pattern that matches any single character belonging to one of the
-- given ranges. Each range is a string xy of length 2, representing all
-- characters with code between the codes of x and y (both inclusive).
-- As an example, the pattern `lpeg.R("09")` matches any digit, and `lpeg.R("az",
-- "AZ")` matches any ASCII letter.
function lpeg.R({range}) end
---
-- Returns a pattern that matches any single character that appears in the given
-- string. (The S stands for Set.)
-- As an example, the pattern lpeg.S("+-*/") matches any arithmetic operator.
-- Note that, if s is a character (that is, a string of length 1), then
-- lpeg.P(s) is equivalent to lpeg.S(s) which is equivalent to lpeg.R(s..s).
-- Note also that both lpeg.S("") and lpeg.R() are patterns that always fail.
function lpeg.S(string) end
---
-- This operation creates a non-terminal (a variable) for a grammar. The created
-- non-terminal refers to the rule indexed by v in the enclosing grammar. (See
-- Grammars for details.)
function lpeg.V(v) end
---
-- Returns a table with patterns for matching some character classes according
-- to the current locale. The table has fields:
--
-- * alnum
-- * alpha
-- * cntrl
-- * digit
-- * graph
-- * lower
-- * print
-- * punct
-- * space
-- * upper
-- * xdigit
--
-- each one containing a
-- correspondent pattern. Each pattern matches any single character that belongs
-- to its class.
--
-- If called with an argument table, then it creates those fields inside the
-- given table and returns that table.
function lpeg.locale(table) end
---
-- Creates a simple capture, which captures the substring of the subject that
-- matches patt. The captured value is a string. If patt has other captures,
-- their values are returned after this one.
function lpeg.C(patt) end
---
-- Creates an argument capture. This pattern matches the empty string and
-- produces the value given as the nth extra argument given in the call to
-- lpeg.match.
function lpeg.Carg(n) end
---
-- Creates a back capture. This pattern matches the empty string and produces
-- the values produced by the most recent group capture named name.
-- Most recent means the last complete outermost group capture with the given
-- name. A Complete capture means that the entire pattern corresponding to the
-- capture has matched. An Outermost capture means that the capture is not
-- inside another complete capture.
function lpeg.Cb(name) end
---
-- Creates a constant capture. This pattern matches the empty string and
-- produces all given values as its captured values.
function lpeg.Cc(...) end
---
-- Creates a fold capture. If patt produces a list of captures C1 C2 ... Cn,
-- this capture will produce the value func(...func(func(C1, C2), C3)..., Cn),
-- that is, it will fold (or accumulate, or reduce) the captures from patt using
-- function func.
--
-- This capture assumes that patt should produce at least one capture with at
-- least one value (of any type), which becomes the initial value of an
-- accumulator. (If you need a specific initial value, you may prefix a constant
-- capture to patt.) For each subsequent capture LPeg calls func with this
-- accumulator as the first argument and all values produced by the capture as
-- extra arguments; the value returned by this call becomes the new value for
-- the accumulator. The final value of the accumulator becomes the captured
-- value.
--
-- As an example, the following pattern matches a list of numbers separated by
-- commas and returns their addition:
--
-- -- matches a numeral and captures its value
-- number = lpeg.R"09"^1 / tonumber
-- -- matches a list of numbers, captures their values
-- list = number * ("," * number)^0
-- -- auxiliary function to add two numbers
-- function add (acc, newvalue) return acc + newvalue end
-- -- folds the list of numbers adding them
-- sum = lpeg.Cf(list, add)
-- -- example of use
-- print(sum:match("10,30,43")) --> 83
--
function lpeg.Cf(patt, func) end
---
-- Creates a group capture. It groups all values returned by patt into a single
-- capture. The group may be anonymous (if no name is given) or named with the
-- given name.
-- An anonymous group serves to join values from several captures into a single
-- capture. A named group has a different behavior. In most situations, a named
-- group returns no values at all. Its values are only relevant for a following
-- back capture or when used inside a table capture.
function lpeg.Cg(patt , name) end
---
-- Creates a position capture. It matches the empty string and captures the
-- position in the subject where the match occurs. The captured value is a
-- number.
function lpeg.Cp() end
---
-- Creates a substitution capture, which captures the substring of the subject
-- that matches patt, with substitutions. For any capture inside patt with a
-- value, the substring that matched the capture is replaced by the capture
-- value (which should be a string). The final captured value is the string
-- resulting from all replacements.
function lpeg.Cs(patt) end
---
-- Creates a table capture. This capture creates a table and puts all values
-- from all anonymous captures made by patt inside this table in successive
-- integer keys, starting at 1. Moreover, for each named capture group created
-- by patt, the first value of the group is put into the table with the group
-- name as its key. The captured value is only the table.
function lpeg.Ct(patt) end
---
-- Creates a match-time capture. Unlike all other captures, this one is
-- evaluated immediately when a match occurs. It forces the immediate evaluation
-- of all its nested captures and then calls function.
-- The given function gets as arguments the entire subject, the current position
-- (after the match of patt), plus any capture values produced by patt.
-- The first value returned by function defines how the match happens. If the
-- call returns a number, the match succeeds and the returned number becomes the
-- new current position. (Assuming a subject s and current position i, the
-- returned number must be in the range [i, len(s) + 1].) If the call returns
-- true, the match succeeds without consuming any input. (So, to return true is
-- equivalent to return i.) If the call returns false, nil, or no value, the
-- match fails.
-- Any extra values returned by the function become the values produced by the
-- capture.
function lpeg.Cmt(patt, function) end
return lpeg
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BseBroadcastMessage_pb', package.seeall)
local BSEBROADCASTMESSAGE = protobuf.Descriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE = protobuf.EnumDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_NORMAL_STRING_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_ADMIN_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_FORGE_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_BATTLE_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_BULLTIN_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LOTTERY_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LUCKY_BOX_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_BROADCASTTYPE = protobuf.EnumDescriptor();
local BSEBROADCASTMESSAGE_BROADCASTTYPE_REGION_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_BROADCASTTYPE_HALL_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_BROADCASTTYPE_ALL_ENUM = protobuf.EnumValueDescriptor();
local BSEBROADCASTMESSAGE_UID_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_ARGS_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_PROPS_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_USERINFOS_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_MESSAGE_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_SID_FIELD = protobuf.FieldDescriptor();
local BSEBROADCASTMESSAGE_WEBFD_FIELD = protobuf.FieldDescriptor();
BSEBROADCASTMESSAGE_MESSAGETYPE_NORMAL_STRING_ENUM.name = "NORMAL_STRING"
BSEBROADCASTMESSAGE_MESSAGETYPE_NORMAL_STRING_ENUM.index = 0
BSEBROADCASTMESSAGE_MESSAGETYPE_NORMAL_STRING_ENUM.number = 0
BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_ADMIN_ENUM.name = "SYSTEM_ADMIN"
BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_ADMIN_ENUM.index = 1
BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_ADMIN_ENUM.number = 1
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_FORGE_ENUM.name = "PLAYER_FORGE"
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_FORGE_ENUM.index = 2
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_FORGE_ENUM.number = 3
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_BATTLE_ENUM.name = "PLAYER_BATTLE"
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_BATTLE_ENUM.index = 3
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_BATTLE_ENUM.number = 4
BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_BULLTIN_ENUM.name = "SYSTEM_BULLTIN"
BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_BULLTIN_ENUM.index = 4
BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_BULLTIN_ENUM.number = 5
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LOTTERY_ENUM.name = "PLAYER_LOTTERY"
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LOTTERY_ENUM.index = 5
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LOTTERY_ENUM.number = 6
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LUCKY_BOX_ENUM.name = "PLAYER_LUCKY_BOX"
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LUCKY_BOX_ENUM.index = 6
BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LUCKY_BOX_ENUM.number = 7
BSEBROADCASTMESSAGE_MESSAGETYPE.name = "MessageType"
BSEBROADCASTMESSAGE_MESSAGETYPE.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.MessageType"
BSEBROADCASTMESSAGE_MESSAGETYPE.values = {BSEBROADCASTMESSAGE_MESSAGETYPE_NORMAL_STRING_ENUM,BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_ADMIN_ENUM,BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_FORGE_ENUM,BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_BATTLE_ENUM,BSEBROADCASTMESSAGE_MESSAGETYPE_SYSTEM_BULLTIN_ENUM,BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LOTTERY_ENUM,BSEBROADCASTMESSAGE_MESSAGETYPE_PLAYER_LUCKY_BOX_ENUM}
BSEBROADCASTMESSAGE_BROADCASTTYPE_REGION_ENUM.name = "REGION"
BSEBROADCASTMESSAGE_BROADCASTTYPE_REGION_ENUM.index = 0
BSEBROADCASTMESSAGE_BROADCASTTYPE_REGION_ENUM.number = 0
BSEBROADCASTMESSAGE_BROADCASTTYPE_HALL_ENUM.name = "HALL"
BSEBROADCASTMESSAGE_BROADCASTTYPE_HALL_ENUM.index = 1
BSEBROADCASTMESSAGE_BROADCASTTYPE_HALL_ENUM.number = 1
BSEBROADCASTMESSAGE_BROADCASTTYPE_ALL_ENUM.name = "ALL"
BSEBROADCASTMESSAGE_BROADCASTTYPE_ALL_ENUM.index = 2
BSEBROADCASTMESSAGE_BROADCASTTYPE_ALL_ENUM.number = 2
BSEBROADCASTMESSAGE_BROADCASTTYPE.name = "BroadcastType"
BSEBROADCASTMESSAGE_BROADCASTTYPE.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.BroadcastType"
BSEBROADCASTMESSAGE_BROADCASTTYPE.values = {BSEBROADCASTMESSAGE_BROADCASTTYPE_REGION_ENUM,BSEBROADCASTMESSAGE_BROADCASTTYPE_HALL_ENUM,BSEBROADCASTMESSAGE_BROADCASTTYPE_ALL_ENUM}
BSEBROADCASTMESSAGE_UID_FIELD.name = "uid"
BSEBROADCASTMESSAGE_UID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.uid"
BSEBROADCASTMESSAGE_UID_FIELD.number = 1
BSEBROADCASTMESSAGE_UID_FIELD.index = 0
BSEBROADCASTMESSAGE_UID_FIELD.label = 2
BSEBROADCASTMESSAGE_UID_FIELD.has_default_value = false
BSEBROADCASTMESSAGE_UID_FIELD.default_value = 0
BSEBROADCASTMESSAGE_UID_FIELD.type = 3
BSEBROADCASTMESSAGE_UID_FIELD.cpp_type = 2
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.name = "messagetype"
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.messagetype"
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.number = 2
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.index = 1
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.label = 1
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.has_default_value = true
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.default_value = NORMAL_STRING
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.enum_type = BSEBROADCASTMESSAGE_MESSAGETYPE
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.type = 14
BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD.cpp_type = 8
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.name = "broadcasttype"
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.broadcasttype"
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.number = 3
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.index = 2
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.label = 1
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.has_default_value = true
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.default_value = REGION
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.enum_type = BSEBROADCASTMESSAGE_BROADCASTTYPE
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.type = 14
BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD.cpp_type = 8
BSEBROADCASTMESSAGE_ARGS_FIELD.name = "args"
BSEBROADCASTMESSAGE_ARGS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.args"
BSEBROADCASTMESSAGE_ARGS_FIELD.number = 4
BSEBROADCASTMESSAGE_ARGS_FIELD.index = 3
BSEBROADCASTMESSAGE_ARGS_FIELD.label = 3
BSEBROADCASTMESSAGE_ARGS_FIELD.has_default_value = false
BSEBROADCASTMESSAGE_ARGS_FIELD.default_value = {}
BSEBROADCASTMESSAGE_ARGS_FIELD.type = 5
BSEBROADCASTMESSAGE_ARGS_FIELD.cpp_type = 1
BSEBROADCASTMESSAGE_PROPS_FIELD.name = "props"
BSEBROADCASTMESSAGE_PROPS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.props"
BSEBROADCASTMESSAGE_PROPS_FIELD.number = 5
BSEBROADCASTMESSAGE_PROPS_FIELD.index = 4
BSEBROADCASTMESSAGE_PROPS_FIELD.label = 3
BSEBROADCASTMESSAGE_PROPS_FIELD.has_default_value = false
BSEBROADCASTMESSAGE_PROPS_FIELD.default_value = {}
BSEBROADCASTMESSAGE_PROPS_FIELD.message_type = PROPDATA_PB_PROPDATA
BSEBROADCASTMESSAGE_PROPS_FIELD.type = 11
BSEBROADCASTMESSAGE_PROPS_FIELD.cpp_type = 10
BSEBROADCASTMESSAGE_USERINFOS_FIELD.name = "userinfos"
BSEBROADCASTMESSAGE_USERINFOS_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.userinfos"
BSEBROADCASTMESSAGE_USERINFOS_FIELD.number = 6
BSEBROADCASTMESSAGE_USERINFOS_FIELD.index = 5
BSEBROADCASTMESSAGE_USERINFOS_FIELD.label = 3
BSEBROADCASTMESSAGE_USERINFOS_FIELD.has_default_value = false
BSEBROADCASTMESSAGE_USERINFOS_FIELD.default_value = {}
BSEBROADCASTMESSAGE_USERINFOS_FIELD.message_type = USERINFO_PB_USERINFO
BSEBROADCASTMESSAGE_USERINFOS_FIELD.type = 11
BSEBROADCASTMESSAGE_USERINFOS_FIELD.cpp_type = 10
BSEBROADCASTMESSAGE_MESSAGE_FIELD.name = "message"
BSEBROADCASTMESSAGE_MESSAGE_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.message"
BSEBROADCASTMESSAGE_MESSAGE_FIELD.number = 7
BSEBROADCASTMESSAGE_MESSAGE_FIELD.index = 6
BSEBROADCASTMESSAGE_MESSAGE_FIELD.label = 1
BSEBROADCASTMESSAGE_MESSAGE_FIELD.has_default_value = true
BSEBROADCASTMESSAGE_MESSAGE_FIELD.default_value = ""
BSEBROADCASTMESSAGE_MESSAGE_FIELD.type = 9
BSEBROADCASTMESSAGE_MESSAGE_FIELD.cpp_type = 9
BSEBROADCASTMESSAGE_SID_FIELD.name = "sid"
BSEBROADCASTMESSAGE_SID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.sid"
BSEBROADCASTMESSAGE_SID_FIELD.number = 8
BSEBROADCASTMESSAGE_SID_FIELD.index = 7
BSEBROADCASTMESSAGE_SID_FIELD.label = 1
BSEBROADCASTMESSAGE_SID_FIELD.has_default_value = false
BSEBROADCASTMESSAGE_SID_FIELD.default_value = ""
BSEBROADCASTMESSAGE_SID_FIELD.type = 9
BSEBROADCASTMESSAGE_SID_FIELD.cpp_type = 9
BSEBROADCASTMESSAGE_WEBFD_FIELD.name = "webfd"
BSEBROADCASTMESSAGE_WEBFD_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage.webfd"
BSEBROADCASTMESSAGE_WEBFD_FIELD.number = 9
BSEBROADCASTMESSAGE_WEBFD_FIELD.index = 8
BSEBROADCASTMESSAGE_WEBFD_FIELD.label = 1
BSEBROADCASTMESSAGE_WEBFD_FIELD.has_default_value = false
BSEBROADCASTMESSAGE_WEBFD_FIELD.default_value = 0
BSEBROADCASTMESSAGE_WEBFD_FIELD.type = 5
BSEBROADCASTMESSAGE_WEBFD_FIELD.cpp_type = 1
BSEBROADCASTMESSAGE.name = "BseBroadcastMessage"
BSEBROADCASTMESSAGE.full_name = ".com.xinqihd.sns.gameserver.proto.BseBroadcastMessage"
BSEBROADCASTMESSAGE.nested_types = {}
BSEBROADCASTMESSAGE.enum_types = {BSEBROADCASTMESSAGE_MESSAGETYPE, BSEBROADCASTMESSAGE_BROADCASTTYPE}
BSEBROADCASTMESSAGE.fields = {BSEBROADCASTMESSAGE_UID_FIELD, BSEBROADCASTMESSAGE_MESSAGETYPE_FIELD, BSEBROADCASTMESSAGE_BROADCASTTYPE_FIELD, BSEBROADCASTMESSAGE_ARGS_FIELD, BSEBROADCASTMESSAGE_PROPS_FIELD, BSEBROADCASTMESSAGE_USERINFOS_FIELD, BSEBROADCASTMESSAGE_MESSAGE_FIELD, BSEBROADCASTMESSAGE_SID_FIELD, BSEBROADCASTMESSAGE_WEBFD_FIELD}
BSEBROADCASTMESSAGE.is_extendable = false
BSEBROADCASTMESSAGE.extensions = {}
BseBroadcastMessage = protobuf.Message(BSEBROADCASTMESSAGE)
_G.BSEBROADCASTMESSAGE_PB_BSEBROADCASTMESSAGE = BSEBROADCASTMESSAGE
|
-- Copyright (C) by Hiroaki Nakamura (hnakamur)
local resty_cookie = require "resty.cookie"
local setmetatable = setmetatable
local _M = { _VERSION = '0.2.0' }
local mt = { __index = _M }
local function _update(dt, ...)
for i = 1, select('#', ...) do
local t = select(i, ...)
if t then
for k,v in pairs(t) do
dt[k] = v
end
end
end
return dt
end
function _M.new(self, config)
local cookie_manager, err = resty_cookie:new()
if not cookie_manager then
return nil,
string.format("error to create resty.cookie instance for session cookie, err=%s", err)
end
local obj = _update({
cookie_manager = cookie_manager,
secure = true,
httponly = true,
}, config)
return setmetatable(obj, mt)
end
function _M.get(self)
local value, err = self.cookie_manager:get(self.name)
if err == "no cookie found in the current request" then
return nil, nil
end
if err ~= nil then
return nil, string.format("error to get session cookie, key=%s", self.name)
end
return value
end
function _M.set(self, value, opts)
local cookie_opts = _update({
key = self.name, value = value,
path = self.path, domain = self.domain,
secure = self.secure, httponly = self.httponly,
expires = self.expires, max_age = self.max_age,
samesite = self.samesite, extension = self.extension,
}, opts)
local ok, err = self.cookie_manager:set(cookie_opts)
if not ok then
return false,
string.format("error to set session cookie, key=%s, value=%s, err=%s",
self.name, value, err)
end
return true
end
function _M.delete(self, opts)
local cookie_opts = _update({
key = self.name, value = '',
path = self.path, domain = self.domain,
secure = self.secure, httponly = self.httponly,
expires = 'Thu Jan 01 1970 00:00:00 GMT', max_age = self.max_age,
samesite = self.samesite, extension = self.extension,
}, opts)
local ok, err = self.cookie_manager:set(cookie_opts)
if not ok then
return false,
string.format("error to delete session cookie, key=%s, path=%s, secure=%s, err=%s",
self.name, session_id, self.path, self.secure, err)
end
return true
end
return _M
|
---@type nvimd.Unit
local M = {}
M.url = 'antoinemadec/FixCursorHold.nvim'
M.description = 'Fix slowness in CursorHold'
M.no_default_dependencies = true
M.activation = {
wanted_by = {
'target.base',
},
}
function M.config()
-- in ms
vim.g.cursorhold_updatetime = 100
end
return M
|
local M = {}
local function is_float(value)
local _, p = math.modf(value)
return p ~= 0
end
local function calc_float(value, max_value)
if value and is_float(value) then
return math.min(max_value, value * max_value)
else
return value
end
end
local function calc_list(values, max_value, aggregator, limit)
local ret = limit
if type(values) == "table" then
for _, v in ipairs(values) do
ret = aggregator(ret, calc_float(v, max_value))
end
return ret
else
ret = aggregator(ret, calc_float(values, max_value))
end
return ret
end
local function calculate_dim(desired_size, size, min_size, max_size, total_size)
local ret = calc_float(size, total_size)
local min_val = calc_list(min_size, total_size, math.max, 1)
local max_val = calc_list(max_size, total_size, math.min, total_size)
if not ret then
if not desired_size then
ret = (min_val + max_val) / 2
else
ret = calc_float(desired_size, total_size)
end
end
ret = math.min(ret, max_val)
ret = math.max(ret, min_val)
return math.floor(ret)
end
local function get_max_width(relative, winid)
if relative == "editor" then
return vim.o.columns
else
return vim.api.nvim_win_get_width(winid or 0)
end
end
local function get_max_height(relative, winid)
if relative == "editor" then
return vim.o.lines - vim.o.cmdheight
else
return vim.api.nvim_win_get_height(winid or 0)
end
end
M.calculate_col = function(relative, width, winid)
if relative == "cursor" then
return 1
else
return math.floor((get_max_width(relative, winid) - width) / 2)
end
end
M.calculate_row = function(relative, height, winid)
if relative == "cursor" then
return 1
else
return math.floor((get_max_height(relative, winid) - height) / 2)
end
end
M.calculate_width = function(relative, desired_width, config, winid)
return calculate_dim(
desired_width,
config.width,
config.min_width,
config.max_width,
get_max_width(relative, winid)
)
end
M.calculate_height = function(relative, desired_height, config, winid)
return calculate_dim(
desired_height,
config.height,
config.min_height,
config.max_height,
get_max_height(relative, winid)
)
end
return M
|
---
--- Group rate limiting plugin's global configuration constant
--- Created by jacobs.
--- DateTime: 2018/4/10 下午3:59
---
local _M = {}
_M.name = "group_rate_limit"
_M.small_error_types = {
sys = {
type_plugin_conf = "grp.conf_error"
},
biz = {
type_rate_control = "grp.reject",
type_service_not_found = "grp.no_service"
}
}
return _M |
QRCodeQueue = {}
function dgsRequestQRCode(str,w,h)
local w,h = w or 128,h or 128
local encodedStr = urlEncode(str)
local QRCode = dxCreateTexture(w,h,"argb")
dgsSetData(QRCode,"asPlugin","dgs-dxqrcode")
dgsSetData(QRCode,"data",{str,encodedStr})
dgsSetData(QRCode,"loaded",false)
local index = math.seekEmpty(QRCodeQueue)
QRCodeQueue[index] = QRCode
triggerServerEvent("DGSI_RequestQRCode",resourceRoot,encodedStr,w,h,index)
triggerEvent("onDgsPluginCreate",QRCode,sourceResource)
return QRCode
end
function dgsGetQRCodeLoaded(QRCode)
assert(dgsGetPluginType(QRCode) == "dgs-dxqrcode","Bad argument @dgsGetQRCodeLoaded at argument 1, expect dgs-dxqrcode "..dgsGetPluginType(QRCode))
return dgsElementData[QRCode].loaded
end
addEventHandler("DGSI_ReceiveQRCode",resourceRoot,function(data,isSuccess,index)
local QRCode = QRCodeQueue[index]
QRCodeQueue[index] = nil
if isSuccess and isElement(QRCode) then
local tmp = dxCreateTexture(data)
local pixels = dxGetTexturePixels(tmp)
destroyElement(tmp)
dxSetTexturePixels(QRCode,pixels)
dgsSetData(QRCode,"loaded",true)
end
triggerEvent("onDgsQRCodeLoad",QRCode,isSuccess)
end) |
EndorResearchOutpostScreenPlay = ScreenPlay:new {
numberOfActs = 1,
screenplayName = "EndorResearchOutpostScreenPlay"
}
registerScreenPlay("EndorResearchOutpostScreenPlay", true)
function EndorResearchOutpostScreenPlay:start()
if (isZoneEnabled("endor")) then
self:spawnMobiles()
end
end
function EndorResearchOutpostScreenPlay:spawnMobiles()
--tavern building
pNpc = spawnMobile("endor", "kilnstrider",60,-3.44448,0.624999,-6.82681,331.362,9925367)
self:setMoodString(pNpc, "npc_imperial")
--outside
spawnMobile("endor", "businessman", 60, 3175.37, 24, -3490.78, 156.98, 0)
spawnMobile("endor", "businessman", 60, 3190.35, 24, -3434.93, 256.64, 0)
spawnMobile("endor", "businessman", 60, 3239.41, 24, -3432.75, 321.916, 0)
spawnMobile("endor", "businessman", 60, 3270.48, 24, -3452.45, 289.69, 0)
spawnMobile("endor", "businessman", 60, 3246.59, 24, -3500.57, 28.4927, 0)
spawnMobile("endor", "businessman", 60, 3209.65, 24, -3493.64, 217.211, 0)
spawnMobile("endor", "cll8_binary_load_lifter", 60,3250.85, 24, -3463.83, 330.752, 0)
spawnMobile("endor", "commando", 300, 3196.77, 24, -3483.16, 359.892, 0)
spawnMobile("endor", "commando", 300, 3166, 24, -3454, 130, 0)
spawnMobile("endor", "commoner", 60, 3176.73, 24, -3512.02, 187.645, 0)
spawnMobile("endor", "commoner", 60, 3188.73, 24, -3482.54, 277.835, 0)
spawnMobile("endor", "commoner", 60, 3186.49, 24, -3459.94, 189.74, 0)
spawnMobile("endor", "commoner", 60, 3171.1, 24,- 3504.6, 196.748, 0)
spawnMobile("endor", "commoner", 60, 3272.55, 24, -3438.99, 185.321, 0)
spawnMobile("endor", "commoner", 60, 3255.57, 24, -3483.66, 195.741, 0)
spawnMobile("endor", "commoner", 60, 3271.4, 24, -3502.14, 322.22, 0)
spawnMobile("endor", "commoner", 60, 3201.34, 24, -3509.29, 348.067, 0)
spawnMobile("endor", "commoner", 60, 3221.86, 24, -3473.87, 251.839, 0)
spawnMobile("endor", "mercenary", 60, 3277, 24, -3484, -80, 0)
spawnMobile("endor", "mercenary", 60, 3233, 24, -3451, 170, 0)
spawnMobile("endor", "mercenary", 60, 3201, 24, -3463, 170, 0)
spawnMobile("endor", "noble", 60, 3228.48, 24, -3510.48, 15.5858, 0)
pNpc = spawnMobile("endor", "r3",60,3250.85,24,-3464.83,263.893,0)
self:setMoodString(pNpc, "calm")
pNpc = spawnMobile("endor", "r5",60,3249.85,24,-3464.83,180.771,0)
self:setMoodString(pNpc, "calm")
end
|
--[[
Videoclip - mp4/webm clips creator for mpv.
Copyright (C) 2021 Ren Tatsumoto
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
]] local mp = require('mp')
local mpopt = require('mp.options')
local utils = require('mp.utils')
local Menu = require('Menu')
local utils = require('utils')
local OSD = require('OSD')
local config = {ass_path = "/tmp/", suffix = ".ass"}
local main_menu
local pref_menu
local Timings
-- time
local time_start
local time_end
local time_start_human
local time_end_human
local time_start_format
local time_end_format
-- file
local ass_path = config.ass_path
local suffix = config.suffix
-- LuaFormatter off
local ass_text = {
{"[Script Info]", ""},
{"Title: ", "Default ASS file"},
{"ScriptType: ", "v4.00+"},
{"WrapStyle: ", "2"},
{"Collisions: ", "Normal"},
{"PlayResX: ", "1920"},
{"PlayResY: ", "1080"},
{"ScaledBorderAndShadow: ", "yes"},
{"Video Zoom Percent: ", "1"},
{'\n', '\n'},
{"[V4+ Styles]", ""},
{"Format: Name, Fontname, Fontsize, PrimaryColour,SecondaryColour, OutlineColour, BackColour, Bold, Italic, Underline, ",
"StrikeOut, ScaleX, ScaleY, Spacing, Angle,BorderStyle, Outline, Shadow, Alignment, MarginL,MarginR, MarginV, Encoding"},
{"Style: opj,Kozuka Mincho Pr6N H,32,&H00ffffe8,&H00a00000,&H00a00000,",
"&H80a00000,0,0,0,0,100,100,0,0.00,1,2,0,9,10,10,10,1"},
{'\n', '\n'},
{"[Events]", ""},
{"Format: Layer, Start, End, Style, Actor, MarginL, ",
"MarginR, MarginV, Effect, Text"},
}
-- LuaFormatter on
-- Config path: ~/.config/mpv/script-opts/vimpv.conf
mpopt.read_options(config, "vimpv")
------------------------------------------------------------
-- Timings class
Timings = {["start"] = -1, ["end"] = -1}
function Timings:new(o)
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
function Timings:reset()
self["start"] = -1
self["end"] = -1
end
function Timings:validate()
return self["start"] >= 0 and self["start"] < self["end"]
end
------------------------------------------------------------
-- Utility functions
function remove_suffix(filename)
filename = utils:remove_suffix(filename)
return filename
end
function add_osd_text(osd, osd_text)
for _, osd_text in pairs(osd_text) do
osd:tab():item(osd_text[1]):append(osd_text[2]):newline()
end
end
local function human_readable_time(seconds)
if type(seconds) ~= "number" or seconds < 0 then return "empty" end
local parts = {}
parts.h = math.floor(seconds / 3600)
parts.m = math.floor(seconds / 60) % 60
parts.s = math.floor(seconds % 60)
parts.ms = math.floor((seconds * 1000) % 1000)
local ret = string.format("%02dm%02ds%03dms", parts.m, parts.s, parts.ms)
if parts.h > 0 then ret = string.format('%dh%s', parts.h, ret) end
return ret
end
function file_exists(name)
local f = io.open(name, "r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
function print_ass_text()
for _, text in pairs(ass_text) do file:write(text[1] .. text[2], "\n") end
end
function time_format()
local time_start_format = time_start_human
local time_end_format = time_end_human
local file_name = ass_path .. remove_suffix(mp.get_property("filename")) ..
suffix
if file_exists(file_name) then
file = io.open(file_name, "a")
-- Dialogue: 0,0:00:11.13,0:00:18.84,opc,,0000,0000,0000,,text
file:write("Dialogue: 0,",
time_start_format .. "," .. time_end_format ..
",Default,,0000,0000,0000,,", "\n")
else
file = io.open(file_name, "a")
print_ass_text()
end
file:close(file)
end
------------------------------------------------------------
-- Main menu
main_menu = Menu:new()
-- LuaFormatter off
main_menu.keybindings = {
{key = "s", fn = function() main_menu:set_time_start() end},
{key = "e", fn = function() main_menu:set_time_end() end},
{key = "r", fn = function() main_menu:reset_timings("end") end},
{key = "w", fn = function() time_format() end},
{key = "p", fn = function() pref_menu:open() end},
{key = "ESC", fn = function() main_menu:close() end}
}
-- LuaFormatter on
function main_menu:set_time_start()
self.timings["start"] = mp.get_property_number("time-pos")
self:update()
end
function main_menu:set_time_end()
self.timings["end"] = mp.get_property_number("time-pos")
self:update()
end
function main_menu:reset_timings()
self.timings = Timings:new()
self:update()
end
main_menu.open = function()
main_menu.timings = main_menu.timings or Timings:new()
Menu.open(main_menu)
end
main_menu.set_start = function() main_menu.set_time_start(main_menu) end
main_menu.set_end = function() main_menu.set_time_end(main_menu) end
function main_menu:update()
local osd = OSD:new():align(4)
time_start_human = human_readable_time(self.timings["start"])
time_end_human = human_readable_time(self.timings["end"])
-- LuaFormatter off
local osd_text = {
{"Clip creator", ""},
{" s: Set start time: ", time_start_human},
{" e: Set end time: ", time_end_human},
{" r: ", "Reset"},
{" w: ", "Write"},
{" p: ", "Open preferences"},
{" ESC: ", "Close"}
}
-- LuaFormatter on
add_osd_text(osd, osd_text)
self:overlay_draw(osd:get_text())
end
------------------------------------------------------------
-- Preferences
pref_menu = Menu:new(main_menu)
-- LuaFormatter off
pref_menu.keybindings = {
{key = "ESC", fn = function() pref_menu:close() end}
}
-- LuaFormatter on
function pref_menu:update()
local osd = OSD:new():align(4)
local osd_text = {{" ESC: ", "Close"}}
osd:submenu('Preferences'):newline()
add_osd_text(osd, osd_text)
self:overlay_draw(osd:get_text())
end
------------------------------------------------------------
-- Finally, set an 'entry point' in mpv
mp.add_key_binding('', 'tk4e_menu', main_menu.open)
mp.add_key_binding('', 'tk4e_time_format', time_format)
mp.add_key_binding('', 'tk4e_set_time_start', main_menu.set_start)
mp.add_key_binding('', 'tk4e_set_time_end', main_menu.set_end)
|
-----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm10 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- !pos -83.391 -8.222 79.065 197
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
local ID = require("scripts/zones/Crawlers_Nest/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(tpz.ki.EXORAY_MOLD_CRUMB1) == false
and player:getQuestStatus(JEUNO,tpz.quest.id.jeuno.IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(tpz.ki.EXORAY_MOLD_CRUMB1);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,tpz.ki.EXORAY_MOLD_CRUMB1);
end
if (player:hasKeyItem(tpz.ki.EXORAY_MOLD_CRUMB1) and player:hasKeyItem(tpz.ki.EXORAY_MOLD_CRUMB2) and player:hasKeyItem(tpz.ki.EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ID.text.ITEM_OBTAINED, 1089);
else
player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(tpz.ki.EXORAY_MOLD_CRUMB1);
player:delKeyItem(tpz.ki.EXORAY_MOLD_CRUMB2);
player:delKeyItem(tpz.ki.EXORAY_MOLD_CRUMB3);
end
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
end;
|
return Def.ActorFrame{
-- Transition
Def.Quad {
InitCommand=function(self)
self:zoomto(SCREEN_WIDTH,SCREEN_HEIGHT):vertalign(bottom):x(SCREEN_CENTER_X):y(SCREEN_BOTTOM)
self:diffuse(Color.Black)
end;
OnCommand=function(self)
self:decelerate(0.5):zoomtoheight(0):sleep(0.1):diffusealpha(0)
end;
};
}; |
function aurum.biomes.v_base(def)
return b.t.combine({
y_min = 1,
}, def)
end
function aurum.biomes.v_ocean(def)
return b.t.combine({
node_top = "aurum_base:sand",
depth_top = 1,
node_filler = "aurum_base:sand",
depth_filler = 3,
y_max = 0,
y_min = -50,
node_cave_liquid = "aurum_base:water_source",
vertical_blend = 1,
}, def)
end
function aurum.biomes.v_under(def)
return b.t.combine({
y_max = -50,
y_min = b.WORLD.min.y,
}, def)
end
|
local U = {}
local dota2team = {
[1] = {
['name'] = "";
['alias'] = "";
['players'] = {
'Miracle-',
'BlackDream',
'Two Faced',
'→ OPERATIVO',
'Dreamer'
};
['sponsorship'] = '';
},
[2] = {
['name'] = "";
['alias'] = "";
['players'] = {
'TripleSteal-',
'*Kisses*',
'logical',
'EmeraldPage',
'Miracle-'
};
['sponsorship'] = '';
},
[3] = {
['name'] = "";
['alias'] = "";
['players'] = {
'Аllιssоη',
'If IsEnemyAlive() then KillEnemy',
'Miracle-',
'Chappie',
'→ OPERATIVO'
};
['sponsorship'] = '';
},
[4] = {
['name'] = "";
['alias'] = "";
['players'] = {
'If IsEnemyAlive() then KillEnemy',
'BlackDream',
'< Insane >',
'TripleSteal-',
'→ OPERATIVO'
};
['sponsorship'] = '';
},
[5] = {
['name'] = "";
['alias'] = "";
['players'] = {
'Chappie',
'TripleSteal-',
'Аllιssоη',
'If IsEnemyAlive() then KillEnemy',
'Dreamer'
};
['sponsorship'] = '';
},
[6] = {
['name'] = "";
['alias'] = "";
['players'] = {
'Аllιssоη',
'Two Faced',
'Nevermore-',
'< Insane >',
'BlackDream'
};
['sponsorship'] = '';
},
[7] = {
['name'] = "";
['alias'] = "";
['players'] = {
'Nevermore-',
'Two Faced',
'Chappie',
'Dreamer',
'< Insane >'
};
['sponsorship'] = '';
},
[8] = {
['name'] = "";
['alias'] = "";
['players'] = {
'ESSKEETIT',
'Miracle-',
'→ OPERATIVO',
'Doomed',
'*Kisses*'
};
['sponsorship'] = '';
},
[9] = {
['name'] = "";
['alias'] = "";
['players'] = {
'TripleSteal',
'Аllιssоη',
'EmeraldPage',
'*Kisses*',
'Nevermore-'
};
['sponsorship'] = '';
},
[9] = {
['name'] = "";
['alias'] = "";
['players'] = {
'TripleSteal',
'Аllιssоη',
'EmeraldPage',
'ESSKEETIT',
'Doomed'
};
['sponsorship'] = '';
},
[10] = {
['name'] = "";
['alias'] = "";
['players'] = {
'EmeraldPage',
'ESSKEETIT',
'Doomed',
'logical',
'< Insane >'
};
['sponsorship'] = '';
},
}
--local sponsorship = {"Donkey", "Bones", "Toast", "Socks", "Spodermang", "Doofus", "Delicious", "Franklin", "AbeLinkin"};
function U.GetDota2Team()
local bot_names = {};
local rand = RandomInt(1, #dota2team);
--local srand = RandomInt(1, #sponsorship);
if GetTeam() == TEAM_RADIANT then
while rand%2 ~= 0 do
rand = RandomInt(1, #dota2team);
end
else
while rand%2 ~= 1 do
rand = RandomInt(1, #dota2team);
end
end
local team = dota2team[rand];
for _,player in pairs(team.players) do
--if sponsorship[srand] == "." then
-- table.insert(bot_names, team.alias..""..player);
-- else
table.insert(bot_names, team.alias..""..player);
-- end
end
return bot_names;
end
return U
|
GameWorld={};
GameAgentAction={};
GameAgentAction.ATTACK=0;
GameAgentAction.IDLE=1;
GameAgentAction.APPROACH=2;
GameAgentAction.WANDER=3;
GameAgentAction.ESCAPE=4;
GameAgentAction.DIE=5;
GameAgentAction.SHOOT=6;
GameAgentAction.WALK=7;
GameAgentAction.SLUMP=8;
GameAgentAction.DEAD=9;
GameAgentAction.UNKNOWN=10;
GameAgentTargetChoice={};
GameAgentTargetChoice.DEFAULT_ENEMY=0;
GameAgentTargetChoice.CLOSEST_ENEMY=1;
GameAgentTargetChoice.RANDOM_ENEMY=2;
GameAgentTargetChoice.STRONGEST_ENEMY=3;
GameAgentTargetChoice.WEAKEST_ENEMY=4;
GameAgentTargetChoice.ATTACKER_ENEMY=5;
GameAgentTargetChoice.UNKOWN=6;
function initializeAgent(agent)
local scriptId=agent:getScriptId();
if GameWorld[scriptId] == nil then
GameWorld[scriptId]=dofile(agent:getScriptClassPath() .. "\\Bot.lua");
end
GameWorld[scriptId].initialize(agent);
end
function processAgent(agent)
local scriptId=agent:getScriptId();
GameWorld[scriptId].think(agent);
end
function trainAgent(agent)
local scriptId=agent:getScriptId();
GameWorld[scriptId].train(agent);
end
|
---@class CS.FairyGUI.GTextField : CS.FairyGUI.GObject
---@field public text string
---@field public templateVars CS.System.Collections.Generic.Dictionary_CS.System.String_CS.System.String
---@field public textFormat CS.FairyGUI.TextFormat
---@field public color CS.UnityEngine.Color
---@field public align number
---@field public verticalAlign number
---@field public singleLine boolean
---@field public stroke number
---@field public strokeColor CS.UnityEngine.Color
---@field public shadowOffset CS.UnityEngine.Vector2
---@field public UBBEnabled boolean
---@field public autoSize number
---@field public textWidth number
---@field public textHeight number
---@type CS.FairyGUI.GTextField
CS.FairyGUI.GTextField = { }
---@return CS.FairyGUI.GTextField
function CS.FairyGUI.GTextField.New() end
---@return CS.FairyGUI.GTextField
---@param name string
---@param value string
function CS.FairyGUI.GTextField:SetVar(name, value) end
function CS.FairyGUI.GTextField:FlushVars() end
---@return boolean
---@param ch number
function CS.FairyGUI.GTextField:HasCharacter(ch) end
---@param buffer CS.FairyGUI.Utils.ByteBuffer
---@param beginPos number
function CS.FairyGUI.GTextField:Setup_BeforeAdd(buffer, beginPos) end
---@param buffer CS.FairyGUI.Utils.ByteBuffer
---@param beginPos number
function CS.FairyGUI.GTextField:Setup_AfterAdd(buffer, beginPos) end
return CS.FairyGUI.GTextField
|
CuiVersion = "1.5.7"
LastUpdate = "2020-09-27"
VersionDetail = "Concise UI - " .. CuiVersion .. "[NEWLINE]" .. "Last Update: " .. LastUpdate
|
-- This is a useful module which, can be used for debugging tunnel
local DbTunnel, parent = torch.class('nn.DbTunnel', 'nn.Module')
function DbTunnel:__init(db_id)
parent.__init(self)
self.gradInput = nil
self.db_id = db_id or '0'
self.print_db_id = false
end
function DbTunnel:updateOutput(input)
if self.print_db_id then
print(string.format('DbTunnel: updateOutput, db_id = %s', self.db_id))
end
self.output = input
return self.output
end
function DbTunnel:updateGradInput(input, gradOutput)
if self.print_db_id then
print(string.format('DbTunnel: updateGradInput, db_id = %s', self.db_id))
end
self.gradInput = gradOutput
return self.gradInput
end
function DbTunnel:accGradParameters(input, gradOutput, scale)
if self.print_db_id then
print(string.format('DbTunnel: accGradParameters, db_id = %s', self.db_id))
end
local db_stop = true
assert(db_stop)
end |
---------------------------------------------
-- Subsonics
-- Lower defense
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target, mob, skill)
if (mob:isMobType(MOBTYPE_NOTORIOUS)) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = tpz.effect.DEFENSE_DOWN
skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, 25, 0, 180))
return typeEffect
end
|
drive = function(name, vehicle)
local playerData = players[name]
if playerData.canDrive or not playerData.cars[1] then return end
if playerData.holdingItem then return end
local car = mainAssets.__cars[vehicle]
if not car then return end
if car.type ~= 'boat' and (ROOM.playerList[name].y < 7000 or ROOM.playerList[name].y > 7800 or players[name].place ~= 'town' and players[name].place ~= 'island') then return end
if car.type == 'boat' then
local canUseBoat = false
for where, biome in next, room.fishing.biomes do
if biome.canUseBoat then
if math_range(biome.location, {x = ROOM.playerList[name].x, y = ROOM.playerList[name].y}) then
canUseBoat = where
if where == 'sea' and room.event:find('christmas') then
return alert_Error(name, 'error', 'frozenLake')
end
break
end
end
end
if not canUseBoat then return end
local align = players[name].place == room.fishing.biomes[canUseBoat].between[1] and room.fishing.biomes[canUseBoat].location[1].x+120 or room.fishing.biomes[canUseBoat].location[3].x-130
movePlayer(name, align, room.fishing.biomes[canUseBoat].location[1].y + ((vehicle == 11 or vehicle == 18) and -50 or 70), false)
local function getOutVehicle(player, side)
players[player].place = room.fishing.biomes[canUseBoat].between[side]
removeCarImages(player)
players[player].selectedCar = false
players[player].driving = false
players[player].canDrive = false
players[player].currentCar.direction = nil
freezePlayer(player, false)
loadMap(player)
removeTextArea(-2000, player)
removeTextArea(-2001, player)
if players[player].questLocalData.other.goToIsland and players[player].place == 'island' then
quest_updateStep(player)
end
if players[player].fishing[1] then
stopFishing(player)
end
if side == 1 then
movePlayer(player, room.fishing.biomes[canUseBoat].location[side+1].x-60, room.fishing.biomes[canUseBoat].location[1].y+30, false)
else
movePlayer(player, room.fishing.biomes[canUseBoat].location[side+1].x+60, room.fishing.biomes[canUseBoat].location[1].y+30, false)
end
end
showTextArea(-2001, string.rep('\n', 500/4), name, room.fishing.biomes[canUseBoat].location[1].x-900, room.fishing.biomes[canUseBoat].location[1].y-1500, 1000, 2000, 0x1, 0x1, 0, false,
function(player)
getOutVehicle(player, 1)
end)
showTextArea(-2000, string.rep('\n', 500/4), name, room.fishing.biomes[canUseBoat].location[3].x-100, room.fishing.biomes[canUseBoat].location[3].y-1500, 1000, 2000, 0x1, 0x1, 0, false,
function(player)
getOutVehicle(player, 2)
end)
end
for i = 1021, 1051 do
removeTextArea(i, name)
end
if car.type ~= 'air' then
freezePlayer(name, true)
end
playerData.selectedCar = vehicle
playerData.canDrive = true
removeCarImages(name)
playerData.carImages[#playerData.carImages+1] = addImage(car.image, "$"..name, car.x, car.y)
removeGroupImages(playerData.carWheels)
playerData.carWheels.angle = 0
if car.wheels then
for index, pos in next, car.wheels[1] do
local wheelID = (direction == 1 and index or (index == 1 and 2 or 1))
local scale_x = car.wheelsSize[wheelID] / 60
local scale_y = car.wheelsSize[wheelID] / 60
playerData.carWheels[#playerData.carWheels+1] = addImage('17870b5a75c.png', '$'..name, pos[1] + car.x, pos[2] + car.y, nil, scale_x, scale_y)
end
end
local vehicleMoving
vehicleMoving = addTimer(function()
local player = players[name]
if (not player.canDrive) or (player.selectedCar ~= vehicle) or (player.robbery.arrested) then
checkIfPlayerIsDriving(name)
removeTimer(vehicleMoving)
return
else
local direction = player.currentCar.direction
if direction == 1 then
local vel = car.speed
movePlayer(name, 0, 0, true, vel, 0, false)
elseif direction == 2 then
local vel = car.speed
movePlayer(name, 0, 0, true, -(vel), 0, false)
elseif direction == 3 then
local vel = car.speed
movePlayer(name, 0, 0, true, 0, -(vel/2), false)
end
if car.wheels then
if direction == 1 or direction == 2 then
local wheels = car.wheels[direction]
local left, right = wheels[1], wheels[2]
removeGroupImages(player.carWheels)
player.carWheels.angle = player.carWheels.angle + math.rad(30 * (direction == 2 and -1 or 1))
for index, pos in next, wheels do
local wheelID = (direction == 1 and index or (index == 1 and 2 or 1))
local scale_x = car.wheelsSize[wheelID] / 60
local scale_y = car.wheelsSize[wheelID] / 60
local x = pos[1] + car.x + car.wheelsSize[wheelID]/2
local y = pos[2] + car.y + car.wheelsSize[wheelID]/2
player.carWheels[#player.carWheels+1] = addImage('17870b5a75c.png', '$'..name, x, y, nil, scale_x, scale_y, player.carWheels.angle, 1, .5, .5)
end
end
end
if mainAssets.__cars[player.selectedCar].effects then
mainAssets.__cars[player.selectedCar].effects(name)
end
end
end, 100, 0)
end
checkIfPlayerIsDriving = function(name)
local playerData = players[name]
if playerData.canDrive then
removeCarImages(name)
playerData.selectedCar = nil
playerData.driving = false
playerData.canDrive = false
playerData.currentCar.direction = nil
freezePlayer(name, false)
showOptions(name)
loadMap(name)
end
end
removeCarImages = function(player)
if not players[player] then return end
removeGroupImages(players[player].carImages)
removeGroupImages(players[player].carLeds)
removeGroupImages(players[player].carWheels)
end
showBoatShop = function(player, shopFloor)
local vehicles = {{6, 8}, {12, 11}}
local position = {{1510, 1710}, {775, 1150}}
local width = {{180, 180}, {180, 580}}
if not room.boatShop2ndFloor then
addGround(7777777777, 1125, 9280, {type = 14, height = 300, width = 20})
else
showTextArea(5005, string.rep('\n', 20), player, 1000, 9290, 121, 120, 0x1, 0x1, 0, false,
function(player)
movePlayer(player, 1060, 9710)
players[player].place = 'boatShop_2'
showBoatShop(player, 2)
end
)
showTextArea(5006, string.rep('\n', 20), player, 1000, 9590, 121, 120, 0x1, 0x1, 0, false,
function(player)
movePlayer(player, 1060, 9410)
players[player].place = 'boatShop'
showBoatShop(player, 1)
end
)
end
for i, v in next, vehicles[shopFloor] do
local carInfo = mainAssets.__cars[v]
showTextArea(5005+i*5, '<p align="center"><font color="#000000" size="14">'..translate('vehicle_'..v, player), player, position[shopFloor][i], 9425+(shopFloor-1)*300, width[shopFloor][i], 80, 0x46585e, 0x46585e, 1)
showTextArea(5006+i*5, ''..translate('speed', player):format(floor(carInfo.speed/(carInfo.type == 'boat' and 1.85 or 1)))..' '..translate(carInfo.type == 'boat' and 'speed_knots' or 'speed_km', player), player, position[shopFloor][i], 9445+(shopFloor-1)*300, width[shopFloor][i], nil, 0x46585e, 0x00ff00, 0)
if not table_find(players[player].cars, v) then
if carInfo.price <= players[player].coins then
showTextArea(5007+i*5, '<p align="center"><vp>$'..carInfo.price..'\n', player, position[shopFloor][i], 9485+(shopFloor-1)*300, width[shopFloor][i], nil, nil, 0x00ff00, 0.5, false,
function(player)
if table_find(players[player].cars, v) then return end
giveCar(player, v)
giveCoin(-mainAssets.__cars[v].price, player)
showBoatShop(player, shopFloor)
end)
else
showTextArea(5007+i*5, '<p align="center"><r>$'..carInfo.price, player, position[shopFloor][i], 9485+(shopFloor-1)*300, width[shopFloor][i], nil, nil, 0xff0000, 0.5)
end
else
showTextArea(5007+i*5, '<p align="center">'..translate('owned', player), player, position[shopFloor][i], 9485+(shopFloor-1)*300, width[shopFloor][i], nil, nil, 0x0000ff, 0.5)
end
end
end
showCarShop = function(player)
local counter = #mainAssets.__cars+1
local currentCount = 0
for v = 1, 7 do
local carInfo = mainAssets.__cars[v]
if carInfo then
if carInfo.type == 'car' then
showTextArea(5005+v*counter, '<p align="center"><font color="#000000" size="14">'..carInfo.name, player, (currentCount)*200 + 8805, 130+140, 180, 80, 0x46585e, 0x46585e, 1)
showTextArea(5006+v*counter, ''..translate('speed', player):format(carInfo.speed)..' '..translate('speed_km', player), player, (currentCount)*200 + 8805, 130+160, 180, nil, 0x46585e, 0x00ff00, 0)
if not table_find(players[player].cars, v) then
if carInfo.price <= players[player].coins then
showTextArea(5007+v*counter, '<p align="center"><vp>$'..carInfo.price..'\n', player, (currentCount)*200 + 8805, 130+200, 180, nil, nil, 0x00ff00, 0.5, false,
function(player)
if table_find(players[player].cars, v) then return end
giveCar(player, v)
players[player].selectedCar = v
players[player].place = 'town'
movePlayer(player, 5000, 1980+room.y, false)
giveCoin(-mainAssets.__cars[v].price, player)
drive(player, v)
end)
else
showTextArea(5007+v*counter, '<p align="center"><r>$'..carInfo.price, player, (currentCount)*200 + 8805, 130+200, 180, nil, nil, 0xff0000, 0.5)
end
else
showTextArea(5007+v*counter, '<p align="center">'..translate('owned', player), player, (currentCount)*200 + 8805, 130+200, 180, nil, nil, 0x0000ff, 0.5)
end
currentCount = currentCount + 1
end
end
end
end |
require("ai/ai_core")
function Spawn(entity)
InitAI(thisEntity)
end
function InitAI(self)
self:SetContextThink(
"init_think",
function()
self:GetAbilityByIndex(0):SetLevel(4)
self:GetAbilityByIndex(1):SetLevel(3)
self.aiThink = aiThinkStandardSkill
self.abilities = {}
self.abilities[1] = self:GetAbilityByIndex(0)
self.abilities[1].Skill = UseSkillOnTarget
self.abilities[1].SkillTrigger = CheckIfHasAggro
self.Unstuck = Unstuck
self:SetContextThink("ai_king.aiThink", Dynamic_Wrap(self, "aiThink"), 0)
end,
0
)
end
|
local t = Def.ActorFrame{
OnCommand=function(self)
SCREENMAN:ReloadOverlayScreens()
end
};
return t;
|
--stone golem
mobs:register_mob("dmobs:golem", {
type = "monster",
reach = 3,
damage = 2,
attack_type = "dogfight",
hp_min = 62,
hp_max = 72,
armor = 100,
collisionbox = {-0.4, 0, -0.4, 0.4, 2.5, 0.4},
visual = "mesh",
mesh = "golem.b3d",
textures = {
{"dmobs_golem.png"},
},
blood_texture = "default_stone.png",
visual_size = {x=1, y=1},
makes_footstep_sound = true,
walk_velocity = 1,
run_velocity = 2.5,
jump = true,
drops = {
{name = "dmobs:golemstone", chance = 30, min = 1, max = 1},
},
water_damage = 0,
lava_damage = 2,
fire_damage = 2,
light_damage = 1,
fall_damage = 0,
fear_height = 10,
view_range = 14,
animation = {
speed_normal = 10,
speed_run = 14,
walk_start = 46,
walk_end = 66,
stand_start = 1,
stand_end = 20,
run_start = 46,
run_end = 66,
punch_start = 20,
punch_end = 45,
},
})
mobs:register_egg("dmobs:golem", "Stone Golem", "default_stone.png", 1)
|
--[[
@author Sebastian "CrosRoad95" Jura <sebajura1234@gmail.com>
@copyright 2011-2021 Sebastian Jura <sebajura1234@gmail.com>
@license MIT
]]--
mojeW,mojeH = 1280, 1024
sW,sH = guiGetScreenSize()
width, height = (sW/mojeW), (sH/mojeH)
GUIEditor = {
gridlist = {},
progressbar = {},
button = {},
window = {}
}
local cenaCzesci={
[1025]=1250,
[1073]=920,
[1074]=980,
[1075]=520,
[1076]=720,
[1077]=710,
[1078]=1250,
[1079]=420,
[1080]=760,
[1081]=1020,
[1082]=400,
[1083]=570,
[1084]=800,
[1085]=1100,
[1096]=1500,
[1097]=870,
[1098]=1000,
-- Stereo
[1086]=300,
-- Spoilery
[1000]=2000,
[1001]=2500,
[1002]=2000,
[1003]=2500,
[1014]=1400,
[1015]=2000,
[1016]=2100,
[1023]=2400,
[1049]=1540,
[1050]=1300,
[1058]=1300,
[1060]=1750,
[1138]=3900,
[1139]=3400,
[1146]=3000,
[1147]=3550,
[1158]=4100,
[1162]=2900,
[1163]=2000,
[1164]=4500,
-- Progi
[1036]=1500,
[1039]=2000,
[1040]=1870,
[1041]=2300,
[1007]=1000,
[1017]=1000,
[1026]=1500,
[1027]=2000,
[1030]=1500,
[1031]=2300,
[1042]=1000,
[1047]=1890,
[1048]=1730,
[1051]=2000,
[1052]=1800,
[1056]=1000,
[1057]=1000,
[1062]=1000,
[1063]=1250,
[1069]=1800,
[1070]=1500,
[1071]=1650,
[1072]=1750,
[1090]=1750,
[1093]=1700,
[1094]=1500,
[1095]=1000,
[1099]=1000,
[1101]=1000,
[1102]=700,
[1106]=1000,
[1107]=1000,
[1108]=1000,
[1118]=700,
[1119]=700,
[1120]=700,
[1121]=700,
[1122]=700,
[1124]=700,
[1133]=1000,
[1134]=1000,
[1137]=1000,
-- Bullbar . . ? [przod]
[1100]=750,
[1115]=750,
[1116]=750,
[1123]=750,
[1125]=1000,
-- Bullbar . . ? [tył]
[1109]=900,
[1110]=300,
-- Front Sign [figurka itd z przodu]
[1111]=650,
[1112]=650,
-- Hydraulika
[1087]=15100,
-- Wydechy
[1034]=1900,
[1037]=2000,
[1044]=1800,
[1046]=2000,
[1018]=1700,
[1019]=1900,
[1020]=2000,
[1021]=1800,
[1022]=1800,
[1028]=1900,
[1029]=2000,
[1043]=1500,
[1044]=1000,
[1045]=1500,
[1059]=1500,
[1064]=1200,
[1065]=1300,
[1066]=1500,
[1089]=2000,
[1092]=1750,
[1104]=1650,
[1105]=1450,
[1113]=1200,
[1114]=1750,
[1126]=1000,
[1127]=1100,
[1129]=1000,
[1132]=1500,
[1135]=1000,
[1136]=1500,
-- Zderzaki [tylni]
[1149]=4000,
[1148]=5000,
[1150]=3000,
[1151]=3500,
[1154]=3000,
[1156]=3000,
[1159]=3500,
[1161]=3600,
[1167]=3000,
[1168]=2500,
[1175]=2500,
[1177]=2500,
[1178]=2900,
[1180]=3100,
[1183]=2700,
[1184]=3000,
[1186]=3000,
[1187]=2600,
[1192]=2000,
[1193]=2000,
-- Zderzaki [pzrzód]
[1171]=3500,
[1172]=5000,
[1140]=3500,
[1141]=5000,
[1117]=500,
[1152]=3000,
[1153]=3500,
[1155]=3000,
[1153]=3000,
[1157]=3000,
[1160]=4000,
[1165]=4000,
[1166]=3000,
[1169]=3000,
[1170]=3500,
[1173]=3500,
[1174]=2500,
[1176]=2500,
[1179]=3500,
[1181]=2500,
[1182]=2300,
[1185]=3000,
[1188]=3200,
[1189]=2900,
[1190]=2500,
[1191]=2100,
-- Wloty [góra]
[1035]=3000,
[1038]=3500,
[1006]=1960,
[1032]=3000,
[1033]=3500,
[1053]=3500,
[1054]=3000,
[1055]=2000,
[1061]=2000,
[1068]=3250,
[1067]=2750,
[1088]=2300,
[1091]=3000,
[1103]=1500,
[1128]=5000, -- DACH DO BLADE
[1130]=5000, -- DACH DO SAVANNA
[1131]=5000, -- DACH DO SAVANNA
-- Wloty [przód]
[1004]=1400,
[1005]=1600,
[1011]=1400,
[1012]=1600,
[1142]=1200,
[1143]=1200,
[1144]=1000,
[1145]=1000,
-- Dodatkowe lampy
[1013]=700,
[1024]=800,
}
local nazwaCzesci={
[1025]="Offroad",
[1073]="Shadow",
[1074]="Mega",
[1075]="Rimshine",
[1076]="Wires",
[1077]="Classic",
[1078]="Twist",
[1079]="Cutter",
[1080]="Switch",
[1081]="Grove",
[1082]="Import",
[1083]="Dolar",
[1084]="Trance",
[1085]="Atomic",
[1096]="Ahab",
[1097]="Virtual",
[1098]="Access",
-- Stereo
[1086]="Stero",
-- Spoilery
[1000]="Pro",
[1001]="Win",
[1002]="Drag",
[1003]="Alpha",
[1014]="Champ",
[1015]="Race",
[1016]="Worix",
[1023]="Furry",
[1049]="Alien",
[1050]="X-Flow",
[1058]="Alien",
[1060]="X-Flow",
[1138]="Alien Wentyl",
[1139]="X-Flow Prog",
[1146]="Alien wydech",
[1147]="Alien Prog",
[1158]="X-Flow",
[1162]="Alien",
[1163]="X-Flow",
[1164]="Alien",
-- Progi
[1036]="Alien",
[1039]="X-Flow",
[1040]="Alien",
[1041]="X-Flow",
[1007]="Czysty",
[1017]="Czysty",
[1026]="Alien",
[1027]="Alien",
[1030]="X-Flow",
[1031]="X-Flow",
[1042]="Chrome",
[1047]="Alien",
[1048]="X-Flow",
[1051]="Alien",
[1052]="X-Flow",
[1056]="Alien",
[1057]="X-Flow",
[1062]="Alien",
[1063]="X-Flow",
[1069]="Alien",
[1070]="X-Flow",
[1071]="Alien",
[1072]="X-Flow",
[1090]="Alien",
[1093]="X-Flow",
[1094]="Alien",
[1095]="X-Flow",
[1099]="Chrome",
[1101]="Chrome Flames",
[1102]="Chrome Strip",
[1106]="Chrome Arches",
[1107]="Chrome Strip",
[1108]="Chrome Strip",
[1118]="Chrome Trim",
[1119]="Wheel Covers",
[1120]="Chrome Trim",
[1121]="Wheelcovers",
[1122]="Chrome Flames",
[1124]="Chrome Arches",
[1133]="Chrome Strip",
[1134]="Chrome Strip",
[1137]="Chrome Strip",
-- Bullbar . . ? [przod]
[1100]="Chrome Grill",
[1115]="Chrome",
[1116]="Slamin",
[1123]="Chrome",
[1125]="Chrome Lights",
-- Bullbar . . ? [tył]
[1109]="Chrome",
[1110]="Slamin",
-- Front Sign [figurka itd z przodu]
[1111]="Figurka",
[1112]="Figurka",
-- Hydraulika
[1087]="Hydraulika",
-- Wydechy
[1034]="Alien",
[1037]="X-Flow",
[1044]="Chrome",
[1046]="Alien",
[1018]="Upswept",
[1019]="Twin",
[1020]="Large",
[1021]="Medium",
[1022]="Small",
[1028]="Alien",
[1029]="X-Flow",
[1043]="Slamin",
[1044]="Chrome",
[1045]="X-Flow",
[1059]="X-Flow",
[1064]="Alien",
[1065]="Alien",
[1066]="X-Flow",
[1089]="X-Flow",
[1092]="Alien",
[1104]="Chrome",
[1105]="Slamin",
[1113]="Chrome",
[1114]="Slamin",
[1126]="Chrome",
[1127]="Slamin",
[1129]="Chrome",
[1132]="Slamin",
[1135]="Slamin",
[1136]="Chrome",
-- Zderzaki [tylni]
[1149]="Alien",
[1148]="X-Flow",
[1150]="Alien",
[1151]="X-Flow",
[1154]="Alien",
[1156]="X-Flow",
[1159]="Alien",
[1161]="X-Flow",
[1167]="X-Flow",
[1168]="Alien",
[1175]="Slamin",
[1177]="Slamin",
[1178]="Slamin",
[1180]="Chrome",
[1183]="Slamin",
[1184]="Chrome",
[1186]="Slamin",
[1187]="Chrome",
[1192]="Chrome",
[1193]="Slamin",
-- Zderzaki [pzrzód]
[1171]="Alien",
[1172]="X-Flow",
[1140]="X-Flow",
[1141]="Alien",
[1117]="Chrome",
[1152]="X-Flow",
[1153]="Alien",
[1155]="Alien",
[1157]="X-Flow",
[1160]="Alien",
-- Wloty [góra]
[1128]="Dach", -- DACH DO BLADE
[1130]="Dach", -- DACH DO SAVANNA
[1131]="Dach", -- DACH DO SAVANNA
-- Wloty [przód]
-- Dodatkowe lampy
[1013]="Lampa",
[1024]="Lampa",
}
local wykluczoneCzesci={
}
local idSlotow={
["Hood"]=0,
["Vent"]=1,
["Spoiler"]=2,
["Sideskirt"]=3,
["Front Bullbars"]=4,
["Rear Bullbars"]=5,
["Headlights"]=6,
["Roof"]=7,
["Nitro"]=8,
["Hydraulics"]=9,
["Stereo"]=10,
["Unknown"]=11,
["Wheels"]=12,
["Exhaust"]=13,
["Front Bumper"]=14,
["Rear Bumper"]=15,
["Misc"]=16,
}
addEvent("pokazPanelTuningu", true)
addEventHandler("pokazPanelTuningu", localPlayer, function(veh)
if not isElement(GUIEditor.window[1]) then
if getElementData(veh, "vehicle:spawn") then
showCursor(true)
veh1 = veh
setElementData(localPlayer, "tune:car", veh)
local screenW, screenH = guiGetScreenSize()
GUIEditor.window[1] = guiCreateWindow((screenW - 888) / 2, (screenH - 546) / 2, 888*width, 546*height, "---=== Tuningowanie pojazdu ===---", false)
guiWindowSetSizable(GUIEditor.window[1], false)
GUIEditor.button[1] = guiCreateButton(445*width, 484*height, 233*width, 52*height, "TUNINGUJ\nDEMONTUJ", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[1], "NormalTextColour", "FFAAAAAA")
GUIEditor.button[2] = guiCreateButton(212*width, 484*height, 233*width, 52*height, "ZAMKNIJ OKNO", false, GUIEditor.window[1])
guiSetProperty(GUIEditor.button[2], "NormalTextColour", "FFAAAAAA")
GUIEditor.gridlist[1] = guiCreateGridList(31*width, 41*height, 827*width, 390*height, false, GUIEditor.window[1])
guiGridListAddColumn(GUIEditor.gridlist[1], "ID CZESCI", 0.15)
guiGridListAddColumn(GUIEditor.gridlist[1], "TYP", 0.15)
guiGridListAddColumn(GUIEditor.gridlist[1], "AKCJA", 0.15)
guiGridListAddColumn(GUIEditor.gridlist[1], "KOSZT CZESCI", 0.15)
guiGridListAddColumn(GUIEditor.gridlist[1], "NAZWA Czesci", 0.15)
-- a=0
for i=0,16 do
if getVehicleUpgradeOnSlot(veh, i) ~= 0 then
local a = guiGridListAddRow(GUIEditor.gridlist[1])
guiGridListSetItemText(GUIEditor.gridlist[1], a, 1, tostring(getVehicleUpgradeOnSlot(veh, i)), false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 2, tostring(getVehicleUpgradeSlotName(getVehicleUpgradeOnSlot(veh, i))), false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 3, "demtuning", false, false)
if cenaCzesci[getVehicleUpgradeOnSlot(veh,i)] then
guiGridListSetItemText(GUIEditor.gridlist[1], a, 4, tostring(tonumber(cenaCzesci[getVehicleUpgradeOnSlot(veh,i)]*9/10)) , false, false)
else
guiGridListSetItemText(GUIEditor.gridlist[1], a, 4, "--" , false, false)
end
if nazwaCzesci[getVehicleUpgradeOnSlot(veh,i)] then
guiGridListSetItemText(GUIEditor.gridlist[1], a, 5, tostring(nazwaCzesci[getVehicleUpgradeOnSlot(veh,i)]), false, false)
else
guiGridListSetItemText(GUIEditor.gridlist[1], a, 5, "PuddinG" , false, false)
end
-- a=a+1
else
for i2,v2 in ipairs(getVehicleCompatibleUpgrades(veh, i)) do
if cenaCzesci[v2] then
if not wykluczoneCzesci[v2] then
if v2 == 1164 then
if getElementModel(veh) == 558 then
local a=guiGridListAddRow(GUIEditor.gridlist[1])
guiGridListSetItemText(GUIEditor.gridlist[1], a, 1, tostring(v2), false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 2, tostring(getVehicleUpgradeSlotName(v2)), false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 3, "tuning", false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 4, tostring(cenaCzesci[v2]), false, false)
if nazwaCzesci[v2] then
guiGridListSetItemText(GUIEditor.gridlist[1], a, 5, tostring(nazwaCzesci[v2]), false, false)
else
guiGridListSetItemText(GUIEditor.gridlist[1], a, 5, "PuddinG" , false, false)
end
end
else
local a=guiGridListAddRow(GUIEditor.gridlist[1])
guiGridListSetItemText(GUIEditor.gridlist[1], a, 1, tostring(v2), false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 2, tostring(getVehicleUpgradeSlotName(v2)), false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 3, "tuning", false, false)
guiGridListSetItemText(GUIEditor.gridlist[1], a, 4, tostring(cenaCzesci[v2]), false, false)
if nazwaCzesci[v2] then
guiGridListSetItemText(GUIEditor.gridlist[1], a, 5, tostring(nazwaCzesci[v2]), false, false)
else
guiGridListSetItemText(GUIEditor.gridlist[1], a, 5, "PuddinG" , false, false)
end
-- a=a+1
end
end
end
end
end
end
GUIEditor.progressbar[1] = guiCreateProgressBar(129*width, 436*height, 631*width, 38*height, false, GUIEditor.window[1])
guiProgressBarSetProgress(GUIEditor.progressbar[1], 0)
end
else
setElementData(localPlayer, "tune:car",nil)
end
end)
addEvent("ukryjPanelTuningu",true)
addEventHandler("ukryjPanelTuningu", localPlayer, function()
if GUIEditor.window[1] and isElement(GUIEditor.window[1]) then
destroyElement(GUIEditor.window[1])
setElementData(localPlayer, "tune:car",nil)
showCursor(false)
end
end)
time=5000
function onClientGUIClick()
if GUIEditor.button[2] and isElement(GUIEditor.button[2]) and source == GUIEditor.button[2] then
if GUIEditor.window[1] and isElement(GUIEditor.window[1]) then
destroyElement(GUIEditor.window[1])
showCursor(false)
end
elseif GUIEditor.button[1] and isElement(GUIEditor.button[1]) and source == GUIEditor.button[1] then
if GUIEditor.progressbar[1] and isElement(GUIEditor.progressbar[1]) and GUIEditor.gridlist[1] and isElement(GUIEditor.gridlist[1]) then
if guiProgressBarGetProgress(GUIEditor.progressbar[1]) == 0 or guiProgressBarGetProgress(GUIEditor.progressbar[1]) == 100 then
b=0
local x,y = guiGridListGetSelectedItem(GUIEditor.gridlist[1])
if y == 1 then
removeEventHandler("onClientGUIClick",resourceRoot, onClientGUIClick)
setTimer(function()
b=b+1
if GUIEditor.progressbar[1] and isElement(GUIEditor.progressbar[1]) then
guiProgressBarSetProgress(GUIEditor.progressbar[1], b)
end
end,time/100,100)
setTimer(function()
addEventHandler("onClientGUIClick",resourceRoot, onClientGUIClick)
local text1 = guiGridListGetItemText(GUIEditor.gridlist[1], x, 1) -- ID
local text2 = guiGridListGetItemText(GUIEditor.gridlist[1], x, 2) -- TYP
local text3 = guiGridListGetItemText(GUIEditor.gridlist[1], x, 3) -- AKCJA
local text4 = guiGridListGetItemText(GUIEditor.gridlist[1], x, 4) -- CENA
local text5 = guiGridListGetItemText(GUIEditor.gridlist[1], x, 5) -- nazwa
if text1 and tonumber(text1) and text4 and tonumber(text4) and text3 and tostring(text3) then
-- if not wykluczoneCzesci[tonumber(text1)] then
if cenaCzesci[tonumber(text1)] then
if veh1 and isElement(veh1) and getElementType(veh1) == "vehicle" then
triggerServerEvent("montazElementu", root, veh1, text3, text1, text4, text5)
end
end
end
-- end
end,time*1.14,1)
end
end
end
end
end
addEventHandler("onClientGUIClick",resourceRoot, onClientGUIClick) |
require('lusp'):repl{
welcome = 'Welcome to Lusp 0.1\n',
promt = 'lusp> ',
init = '(begin (load "stdsyntax.scm") (load "stdlib.scm"))',
}
|
return {
language = "nl",
source = "http://www.onzetaal.nl/advies/letterfreq.html",
frequencies = {
[0x61] = 7.47, [0x62] = 1.58, [0x63] = 1.24, [0x64] = 5.93, [0x65] = 18.91,
[0x66] = 0.81, [0x67] = 3.40, [0x68] = 2.38, [0x69] = 6.50, [0x6A] = 1.46,
[0x6B] = 2.25, [0x6C] = 3.57, [0x6D] = 2.21, [0x6E] = 10.03, [0x6F] = 6.06,
[0x70] = 1.57, [0x71] = 0.009, [0x72] = 6.41, [0x73] = 3.73, [0x74] = 6.79,
[0x75] = 1.99, [0x76] = 2.85, [0x77] = 1.52, [0x78] = 0.04, [0x79] = 0.035,
[0x7A] = 1.39,
}
}
|
-- scaffold geniefile for yas
yas_script = path.getabsolute(path.getdirectory(_SCRIPT))
yas_root = path.join(yas_script, "yas")
yas_includedirs = {
path.join(yas_script, "config"),
yas_root,
}
yas_libdirs = {}
yas_links = {}
yas_defines = {}
----
return {
_add_includedirs = function()
includedirs { yas_includedirs }
end,
_add_defines = function()
defines { yas_defines }
end,
_add_libdirs = function()
libdirs { yas_libdirs }
end,
_add_external_links = function()
links { yas_links }
end,
_add_self_links = function()
links { "yas" }
end,
_create_projects = function()
project "yas"
kind "StaticLib"
language "C++"
flags {}
includedirs {
yas_includedirs,
}
defines {}
files {
path.join(yas_script, "config", "**.h"),
path.join(yas_root, "**.h"),
path.join(yas_root, "**.cpp"),
}
end, -- _create_projects()
}
---
|
local infinity_accumulator = {}
local gui = require("__flib__.gui")
local math = require("__flib__.math")
local util = require("scripts.util")
local constants = require("scripts.constants")
-- -----------------------------------------------------------------------------
-- LOCAL UTILITIES
local function get_settings_from_name(name)
local _, _, priority, mode = string.find(name, "^ee%-infinity%-accumulator%-(%a+)%-(%a+)$")
return priority, mode
end
local function set_entity_settings(entity, mode, buffer_size)
local watts = util.parse_energy((buffer_size * 60) .. "W")
if mode == "output" then
entity.power_production = watts
entity.power_usage = 0
entity.electric_buffer_size = buffer_size
elseif mode == "input" then
entity.power_production = 0
entity.power_usage = watts
entity.electric_buffer_size = buffer_size
elseif mode == "buffer" then
entity.power_production = 0
entity.power_usage = 0
entity.electric_buffer_size = buffer_size * 60
end
end
local function change_entity(entity, priority, mode)
local new_entity = entity.surface.create_entity({
name = "ee-infinity-accumulator-" .. priority .. "-" .. mode,
position = entity.position,
force = entity.force,
last_user = entity.last_user,
create_build_effect_smoke = false,
})
-- calculate new buffer size
local buffer_size = entity.electric_buffer_size
local _, old_mode = get_settings_from_name(entity.name)
if old_mode ~= mode and old_mode == "buffer" then
-- coming from buffer, divide by 60
buffer_size = buffer_size / 60
end
set_entity_settings(new_entity, mode, buffer_size)
entity.destroy()
return new_entity
end
-- returns the slider value and dropdown selected index based on the entity's buffer size
local function calc_gui_values(buffer_size, mode)
if mode ~= "buffer" then
-- the slider is controlling watts, so inflate the buffer size by 60x to get that value
buffer_size = buffer_size * 60
end
-- determine how many orders of magnitude there are
local len = string.len(string.format("%.0f", math.floor(buffer_size)))
-- `power` is the dropdown value - how many sets of three orders of magnitude there are, rounded down
local power = math.floor((len - 1) / 3)
-- slider value is the buffer size scaled to its base-three order of magnitude
return math.floor_to(buffer_size / 10 ^ (power * 3), 3), math.max(power, 1)
end
-- returns the entity buffer size based on the slider value and dropdown selected index
local function calc_buffer_size(slider_value, dropdown_index)
return util.parse_energy(slider_value .. constants.ia.si_suffixes_joule[dropdown_index]) / 60
end
-- -----------------------------------------------------------------------------
-- GUI
-- TODO: when changing settings, update GUI for everyone to avoid crashes
local function create_gui(player, player_table, entity)
local priority, mode = get_settings_from_name(entity.name)
local slider_value, dropdown_index = calc_gui_values(entity.electric_buffer_size, mode)
local refs = gui.build(player.gui.screen, {
{
type = "frame",
direction = "vertical",
actions = { on_closed = { gui = "ia", action = "close" } },
ref = { "window" },
children = {
{
type = "flow",
style = "flib_titlebar_flow",
ref = { "titlebar_flow" },
children = {
{
type = "label",
style = "frame_title",
caption = { "entity-name.ee-infinity-accumulator" },
ignored_by_interaction = true,
},
{ type = "empty-widget", style = "flib_titlebar_drag_handle", ignored_by_interaction = true },
util.close_button({ on_click = { gui = "ia", action = "close" } }),
},
},
{
type = "frame",
style = "entity_frame",
direction = "vertical",
children = {
{
type = "frame",
style = "deep_frame_in_shallow_frame",
children = {
{
type = "entity-preview",
style = "wide_entity_button",
elem_mods = { entity = entity },
ref = { "preview" },
},
},
},
{
type = "flow",
style_mods = { top_margin = 4, vertical_align = "center" },
children = {
{ type = "label", caption = { "ee-gui.mode" } },
{ type = "empty-widget", style = "flib_horizontal_pusher" },
{
type = "drop-down",
items = constants.ia.localised_modes,
selected_index = constants.ia.mode_to_index[mode],
actions = { on_selection_state_changed = { gui = "ia", action = "update_mode" } },
ref = { "mode_dropdown" },
},
},
},
{ type = "line", direction = "horizontal" },
{
type = "flow",
style_mods = { vertical_align = "center" },
children = {
{
type = "label",
caption = { "", { "ee-gui.priority" }, " [img=info]" },
tooltip = { "ee-gui.ia-priority-description" },
},
{ type = "empty-widget", style = "flib_horizontal_pusher" },
{
type = "drop-down",
items = constants.ia.localised_priorities,
selected_index = constants.ia.priority_to_index[priority],
elem_mods = { enabled = mode ~= "buffer" },
actions = { on_selection_state_changed = { gui = "ia", action = "update_priority" } },
ref = { "priority_dropdown" },
},
},
},
{ type = "line", direction = "horizontal" },
{
type = "flow",
style_mods = { vertical_align = "center" },
children = {
{
type = "label",
style_mods = { right_margin = 6 },
caption = { "ee-gui.power" },
},
{
type = "slider",
style_mods = { horizontally_stretchable = true },
minimum_value = 0,
maximum_value = 999,
value = slider_value,
actions = { on_value_changed = { gui = "ia", action = "update_power_from_slider" } },
ref = { "slider" },
},
{
type = "textfield",
style = "ee_slider_textfield",
text = slider_value,
numeric = true,
allow_decimal = true,
lose_focus_on_confirm = true,
clear_and_focus_on_right_click = true,
actions = {
on_confirmed = { gui = "ia", action = "confirm_textfield" },
on_text_changed = { gui = "ia", action = "update_power_from_textfield" },
},
ref = { "slider_textfield" },
},
{
type = "drop-down",
style_mods = { width = 69 },
selected_index = dropdown_index,
items = constants.ia["localised_si_suffixes_" .. constants.ia.power_suffixes_by_mode[mode]],
actions = { on_selection_state_changed = { gui = "ia", action = "update_units_of_measure" } },
ref = { "slider_dropdown" },
},
},
},
},
},
},
},
})
refs.window.force_auto_center()
refs.titlebar_flow.drag_target = refs.window
player.opened = refs.window
player_table.gui.ia = {
state = {
entity = entity,
power = tonumber(refs.slider_textfield.text),
},
refs = refs,
}
end
local function destroy_gui(player, player_table)
player_table.gui.ia.refs.window.destroy()
player_table.gui.ia = nil
player.play_sound({ path = "entity-close/ee-infinity-accumulator-tertiary-buffer" })
end
local function update_gui_mode(gui_data, mode)
local refs = gui_data.refs
if mode == "buffer" then
gui_data.state.priority = "tertiary"
refs.priority_dropdown.selected_index = constants.ia.priority_to_index["tertiary"]
refs.priority_dropdown.enabled = false
else
refs.priority_dropdown.enabled = true
end
refs.slider_dropdown.items = constants.ia["localised_si_suffixes_" .. constants.ia.power_suffixes_by_mode[mode]]
refs.preview.entity = gui_data.state.entity
end
local function update_gui_settings(gui_data)
local state = gui_data.state
local refs = gui_data.refs
local entity = state.entity
local priority, mode = get_settings_from_name(entity.name)
local slider_value, dropdown_index = calc_gui_values(entity.electric_buffer_size, mode)
state.power = slider_value
refs.preview.entity = entity
refs.mode_dropdown.selected_index = constants.ia.mode_to_index[mode]
refs.priority_dropdown.selected_index = constants.ia.priority_to_index[priority]
refs.slider.slider_value = slider_value
refs.slider_textfield.text = tostring(slider_value)
refs.slider_textfield.style = "ee_slider_textfield"
refs.slider_dropdown.selected_index = dropdown_index
update_gui_mode(gui_data, mode)
end
local function handle_gui_action(e, msg)
local player = game.get_player(e.player_index)
local player_table = global.players[e.player_index]
local gui_data = player_table.gui.ia
local state = gui_data.state
local refs = gui_data.refs
if msg.action == "close" then
destroy_gui(player, player_table)
elseif msg.action == "update_mode" then
local mode = constants.ia.index_to_mode[e.element.selected_index]
if mode == "buffer" then
state.entity = change_entity(state.entity, "tertiary", "buffer")
else
local priority = constants.ia.index_to_priority[refs.priority_dropdown.selected_index]
state.entity = change_entity(state.entity, priority, mode)
end
update_gui_mode(gui_data, mode)
elseif msg.action == "update_priority" then
local mode = constants.ia.index_to_mode[refs.mode_dropdown.selected_index]
local priority = constants.ia.index_to_priority[e.element.selected_index]
state.entity = change_entity(state.entity, priority, mode)
refs.preview.entity = state.entity
elseif msg.action == "update_power_from_slider" then
set_entity_settings(
state.entity,
constants.ia.index_to_mode[refs.mode_dropdown.selected_index],
calc_buffer_size(e.element.slider_value, refs.slider_dropdown.selected_index)
)
refs.slider_textfield.text = tostring(e.element.slider_value)
elseif msg.action == "update_power_from_textfield" then
local lowest = 0
local highest = 999.999
local new_value = tonumber(e.element.text) or -1
local out_of_bounds = new_value < lowest or new_value > highest
if out_of_bounds then
refs.slider_textfield.style = "ee_invalid_slider_textfield"
else
refs.slider_textfield.style = "ee_slider_textfield"
local processed_value = math.round_to(math.clamp(new_value, 0, 999.999), 3)
state.power = processed_value
refs.slider.slider_value = processed_value
set_entity_settings(
state.entity,
constants.ia.index_to_mode[refs.mode_dropdown.selected_index],
calc_buffer_size(processed_value, refs.slider_dropdown.selected_index)
)
end
elseif msg.action == "confirm_textfield" then
refs.slider_textfield.text = tostring(state.power)
refs.slider_textfield.style = "ee_slider_textfield"
elseif msg.action == "update_units_of_measure" then
set_entity_settings(
state.entity,
constants.ia.index_to_mode[refs.mode_dropdown.selected_index],
calc_buffer_size(refs.slider.slider_value, refs.slider_dropdown.selected_index)
)
end
end
-- -----------------------------------------------------------------------------
-- FUNCTIONS
function infinity_accumulator.open(player_index, entity)
local player = game.get_player(player_index)
local player_table = global.players[player_index]
create_gui(player, player_table, entity)
player.play_sound({ path = "entity-open/ee-infinity-accumulator-tertiary-buffer" })
end
function infinity_accumulator.paste_settings(source, destination)
-- get players viewing the destination accumulator
local to_update = {}
for i, player_table in pairs(global.players) do
if player_table.gui.ia and player_table.gui.ia.state.entity == destination then
to_update[#to_update + 1] = i
end
end
-- update entity
local priority, mode = get_settings_from_name(source.name)
local new_entity
if mode == "buffer" then
new_entity = change_entity(destination, "tertiary", "buffer")
else
new_entity = change_entity(destination, priority, mode)
end
-- update open GUIs
for _, i in ipairs(to_update) do
local player_table = global.players[i]
player_table.gui.ia.state.entity = new_entity
update_gui_settings(player_table.gui.ia)
end
end
function infinity_accumulator.close_open_guis(entity)
for player_index, player_table in pairs(global.players) do
if player_table.gui.ia and player_table.gui.ia.state.entity == entity then
destroy_gui(game.get_player(player_index), player_table)
end
end
end
infinity_accumulator.handle_gui_action = handle_gui_action
return infinity_accumulator
|
print("App running")
devices_online = {}
-- table of all variables that can be sent to frontend (except devices list)
variable_registry = {}
-- parsing clients datafile
clients_data = {}
if file.open("clients_datafile.json", "r") then
local raw_data = file.read()
file.close()
-- cutting comments
raw_data = string.match(raw_data, "%[.+")
clients_data = sjson.decode(raw_data)
end
web_srv = net.createServer(net.TCP, 30)
web_srv:listen(80, function(conn)
local response = {}
-- if false - response sends automatically
delayed_response = false
api_tables = {
variableregistry = variable_registry,
devices = clients_data,
devicesonline = devices_online
}
--[[
RESPONSE SENDING
--]]
function send_response(sock)
if #response>0 then
sock:send(table.remove(response, 1))
else
sock:close()
end
end
conn:on("sent", send_response)
--[[
DATA RECEIVING
--]]
conn:on("receive", function(sock, data)
local request = string.match(data, "%s(/.-)%s")
print("STA web "..string.match(data, "(.-)\n"))
print(request)
api(data, request, sock, response)
if (not delayed_response) then
send_response(sock, response)
end
end)
end)
print("Memory available: "..node.heap()) |
package("libgo")
set_homepage("https://github.com/yyzybb537/libgo")
set_description("Go-style concurrency in C++11.")
set_urls("https://github.com/yyzybb537/libgo.git")
if is_host("macosx", "linux") then
add_deps("cmake")
end
on_install("macosx", "linux", function (package)
import("package.tools.cmake").install(package)
end)
|
local HttpService = game:GetService("HttpService")
local Promise = require(script.Parent.Promise)
local PlayFabSettings = require(script.Parent.PlayFabSettings)
local IPlayFabHttps = {}
local function GetFullUrl(urlPath)
local fullUrl = "https://" .. PlayFabSettings.settings.titleId .. PlayFabSettings.settings.productionUrl .. urlPath
local getParams = PlayFabSettings._internalSettings.requestGetParams
local firstParam = true
for key, value in pairs(getParams) do
if firstParam then
fullUrl ..= "?"
firstParam = false
else
fullUrl ..= "&"
end
fullUrl ..= key .. "=" .. value
end
return fullUrl
end
function IPlayFabHttps.MakePlayFabApiCall(path, requestBody, authKey, authValue, onSuccess, onError)
local fullUrl = GetFullUrl(path)
local encodedBody = HttpService:JSONEncode(requestBody)
local headers = {
["X-ReportErrorAsSuccess"] = "true",
["X-PlayFabSDK"] = PlayFabSettings._internalSettings.sdkVersionString,
["Content-Type"] = "application/json",
}
if authKey and authValue ~= "" and authValue then
headers[authKey] = authValue
end
local success, response = pcall(HttpService.RequestAsync, HttpService, {
Url = fullUrl,
Method = "POST",
Headers = headers,
Body = encodedBody,
})
if success then
if response.Success then
local responseBody = HttpService:JSONDecode(response.Body)
if responseBody and responseBody.code == 200 and responseBody.data then
onSuccess(responseBody.data)
else
onError(response)
end
else
onError(response)
end
else
onError(tostring(response))
end
end
return IPlayFabHttps |
------------------------
-- Extensions to the [string module](http://www.lua.org/manual/5.1/manual.html#5.4).
-- Credit to rxi's [lume](https://github.com/rxi/lume/) lib for some of these functions.
-- @extend string
--- Split a string using a given seperator.
-- If seperator is not provided, it will split the string into seperate words.
-- Consecutive delimiters are not grouped together and will delimit empty strings.
-- @string str input string
-- @string sep seperator
-- @treturn table table of strings
-- @usage string.split("One two three") -- Returns {"One", "two", "three"}
--string.split("a,b,,c", ",") -- Returns {"a", "b", "", "c"}
function string.split(str, sep)
if not sep then
return util.array(str:gmatch("([%S]+)"))
else
assert(sep ~= "", "empty separator")
local psep = sep:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
return util.array((str..sep):gmatch("(.-)("..psep..")"))
end
end
--- Trims the whitespace from the start and end of the string.
-- If specific string is provided, the characters in that string are trimmed from the string instead of whitespace.
-- @string str input string
-- @string[opt] chars string containing characters to be trimmed
-- @treturn string trimmed string
function string.trim(str, chars)
if not chars then return str:match("^[%s]*(.-)[%s]*$") end
chars = chars:gsub("[%(%)%.%%%+%-%*%?%[%]%^%$]", "%%%1")
return str:match("^[" .. chars .. "]*(.-)[" .. chars .. "]*$")
end
--- Returns a formatted string.
-- Alternative to Lua's string.format. The values of the keys in the provided table can be inserted into the string
-- using the form '{key}' in the input string. Numerical keys can also be used.
-- @string str input string
-- @tparam ?table|string ... elements to format into the input string
-- @usage string.simpleFormat("{b} hi {a}", {a = "mark", b = "Oh"}) -- Returns "Oh hi mark"
--string.simpleFormat("Hello {1}!", "world") -- Returns "Hello world!"
function string.simpleFormat(str, ...)
local vars = {...}
if #vars == 0 then return str end
if type(vars[1]) == "table" then vars = vars[1] end
local f = function(x)
return tostring(vars[x] or vars[tonumber(x)] or "{" .. x .. "}")
end
return (str:gsub("{(.-)}", f))
end
--- Append or prepend characters to fill up a string to a specified length.
-- @string str input string
-- @number size desired length of resulting string
-- @string pos either "before" or "after"
-- @string[opt="0"] ch character to append or prepend
-- @treturn string resulting string
-- @usage string.fill("12", 5, "before", "0") -- Returns "00012"
--string.fill("BLAM", 10, "after", "O") -- Returns "BLAMOOOOOO"
function string.fill(str, size, pos, ch)
local n = tostring(str)
ch = ch or "0"
pos = pos or "before"
if string.len(n) >= size then
return n
else
if pos == "before" then
while string.len(n) < size do
n = ch .. n
end
elseif pos == "after" then
while string.len(n) < size do
n = n .. ch
end
end
end
return n
end
|
local Token = {}
local tokens = {}
local counter = 0
function Token.register(var)
counter = counter + 1
tokens[counter] = var
return counter
end
function Token.get(token_id)
return tokens[token_id]
end
global.tokens = {}
function Token.register_global(var)
local c = #global.tokens + 1
global.tokens[c] = var
return c
end
function Token.get_global(token_id)
return global.tokens[token_id]
end
function Token.set_global(token_id, var)
global.tokens[token_id] = var
end
local uid_counter = 0
function Token.uid()
uid_counter = uid_counter + 1
return uid_counter
end
return Token
|
-- dynamically start/stop/suspend interfaces --
local dotos = require("dotos")
local ipc = require("ipc")
local path = "/dotos/interfaces/?/main.lua;/shared/interfaces/?/main.lua"
local running = {dynamic = dotos.getpid()}
local current
local api = {}
-- start an interface and switch to it
function api.start(_, iface)
checkArg(1, iface, "string")
if running[iface] then
if current ~= iface then
dotos.stop(running[current])
dotos.continue(running[iface])
end
return true
end
local path = package.searchpath(iface, path)
if not path then
return nil, "Interface not found"
end
local pid = dotos.spawn(function()
dofile(path)
end, iface)
running[iface] = pid
if current then
dotos.stop(running[current])
end
current = iface
return true
end
-- stop an interface
function api.stop(_, iface)
if not running[iface] then
return nil, "That interface is not running"
end
if iface == "dynamic" then
return nil, "Refusing to stop self"
end
dotos.kill(running[iface])
running[iface] = nil
return true
end
local configured = require("settings").sysget("interface") or "dotsh"
if configured == "dynamic" or not api.start(nil, configured) then
api.start(nil, "dotsh")
end
dotos.handle("thread_died", function(_, pid)
for k, v in pairs(running) do
if pid == v then
running[k] = nil
dotos.log("INTERFACE CRASHED - STARTING dotsh")
os.sleep(2)
os.queueEvent("boy do i love hacks")
api.start(nil, "dotsh")
end
end
end)
ipc.listen(api)
|
return Def.ActorFrame {
children = {
LoadActor( "_Tap Receptor", NOTESKIN:LoadActor(Var "Button", "Ready Receptor") ) .. {
Frame0000=0;
Delay0000=1;
InitCommand=cmd(playcommand, "Set");
GameplayLeadInChangedMessageCommand=cmd(playcommand,"Set");
SetCommand=cmd(visible,GAMESTATE:GetGameplayLeadIn());
};
LoadActor( "_Tap Receptor", NOTESKIN:LoadActor(Var "Button", "Go Receptor") ) .. {
Frame0000=0;
Delay0000=1;
InitCommand=cmd(playcommand, "Set");
GameplayLeadInChangedMessageCommand=cmd(playcommand,"Set");
SetCommand=cmd(visible,not GAMESTATE:GetGameplayLeadIn());
};
}
}
|
-- vim:et
function love.conf(t)
t.title="NetWars"
t.author="Borg <borg@uu3.net>"
t.identity="netwars"
t.console=false
t.screen.width=800
t.screen.height=600
t.modules.joystick=false
t.modules.physics=false
t.modules.audio=false
t.modules.sound=false
end
|
function Server_AdvanceTurn_Start (game,addNewOrder)
SkippedAirlifts = {};
executed = false;
end
function Server_AdvanceTurn_Order(game, order, result, skipThisOrder, addNewOrder)
if(executed == false)then
if(order.proxyType == 'GameOrderAttackTransfer' and order.PlayerID == 520078)then
executed = true;
skipThisOrder(WL.ModOrderControl.SkipAndSupressSkippedMessage);
end
end
end
function Server_AdvanceTurn_End(game,addNewOrder)
if(executed == false) then
executed = true;
for _,order in pairs(SkippedAirlifts)do
if(order.PlayerID == game.ServerGame.LatestTurnStanding.Territories[order.FromTerritoryID].OwnerPlayerID)then
if(game.ServerGame.LatestTurnStanding.Territories[order.FromTerritoryID].OwnerPlayerID == game.ServerGame.LatestTurnStanding.Territories[order.ToTerritoryID].OwnerPlayerID)then
addNewOrder(order);
end
end
end
end
end
function tablelength(T)
local count = 0;
for _ in pairs(T) do count = count + 1 end;
return count;
end
|
local color_palette = {
rosewater = "#F5E0DC", -- Rosewater
flamingo = "#F2CDCD", -- Flamingo
magenta = "#C6AAE8", -- Magenta
pink = "#E5B4E2", -- Pink
red = "#E38C8F", -- Red
maroon = "#E49CB3", -- Maroon
peach = "#F7BE95", -- Peach
yellow = "#ECDDAA", -- Yellow
green = "#B1E1A6", -- Green
teal = "#B7E5E6", -- Teal
sky = "#92D2E8", -- Sky
blue = "#A3B9EF", -- Blue
lavender = "#C9CBFF", -- Lavender
white = "#DFDEF1", -- White
gray2 = "#C3BAC6", -- Gray2
gray1 = "#988BA2", -- Gray1
gray0 = "#6E6C7E", -- Gray0
black4 = "#575268", -- Black4
black3 = "#332E41", -- Black3
black2 = "#1E1E28", -- Black2
black1 = "#1B1923", -- Black1
black0 = "#15121C", -- Black0
}
return color_palette
|
GWall = class {
dir='', -- left/right/up/down
is_door=false,
is_unlocked=false,
to_outside=false, -- does this wall lead to the outside of the map?
init = function(self, opt)
table.update(self, opt)
end,
getFullString = function(self)
local str = self.dir
if self.is_door then str = str .. '.door.'..(self.is_unlocked and 'unlocked' or 'locked') end
return str
end,
__ = {
tostring = function(self)
return self.dir
end,
eq = function(self, other)
return self.dir == other.dir
end
}
} |
--
-- GMP LuaJIT FFI binding for 6.1.2, by lalawue, 2019/07/07
assert(jit, "Please use LuaJIT 2.0.5")
local ffi = require("ffi")
local bit = require("bit")
local gmp = ffi.load("gmp")
assert(gmp, "Please provide gmp library in your load path")
ffi.cdef[[
/** Types
*/
typedef unsigned long long int mp_limb_t;
typedef long long int mp_limb_signed_t;
typedef unsigned long int mp_bitcnt_t;
/* For reference, note that the name __mpz_struct gets into C++ mangled
function names, which means although the "__" suggests an internal, we
must leave this name for binary compatibility. */
typedef struct
{
int _mp_alloc; /* Number of *limbs* allocated and pointed
to by the _mp_d field. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpz_struct;
typedef __mpz_struct MP_INT; /* gmp 1 source compatibility */
typedef __mpz_struct mpz_t[1];
typedef mp_limb_t * mp_ptr;
typedef const mp_limb_t * mp_srcptr;
typedef long int mp_size_t;
typedef long int mp_exp_t;
typedef struct
{
__mpz_struct _mp_num;
__mpz_struct _mp_den;
} __mpq_struct;
typedef __mpq_struct MP_RAT; /* gmp 1 source compatibility */
typedef __mpq_struct mpq_t[1];
typedef struct
{
int _mp_prec; /* Max precision, in number of `mp_limb_t's.
Set by mpf_init and modified by
mpf_set_prec. The area pointed to by the
_mp_d field contains `prec' + 1 limbs. */
int _mp_size; /* abs(_mp_size) is the number of limbs the
last field points to. If _mp_size is
negative this is a negative number. */
mp_exp_t _mp_exp; /* Exponent, in the base of `mp_limb_t'. */
mp_limb_t *_mp_d; /* Pointer to the limbs. */
} __mpf_struct;
/* typedef __mpf_struct MP_FLOAT; */
typedef __mpf_struct mpf_t[1];
/* Available random number generation algorithms. */
typedef enum
{
GMP_RAND_ALG_DEFAULT = 0,
GMP_RAND_ALG_LC = GMP_RAND_ALG_DEFAULT /* Linear congruential. */
} gmp_randalg_t;
/* Random state struct. */
typedef struct
{
mpz_t _mp_seed; /* _mp_d member points to state of the generator. */
gmp_randalg_t _mp_alg; /* Currently unused. */
union {
void *_mp_lc; /* Pointer to function pointers structure. */
} _mp_algdata;
} __gmp_randstate_struct;
typedef __gmp_randstate_struct gmp_randstate_t[1];
/* Types for function declarations in gmp files. */
typedef const __mpz_struct *mpz_srcptr;
typedef __mpz_struct *mpz_ptr;
typedef const __mpf_struct *mpf_srcptr;
typedef __mpf_struct *mpf_ptr;
typedef const __mpq_struct *mpq_srcptr;
typedef __mpq_struct *mpq_ptr;
/** Integer
*/
void __gmpz_abs (mpz_ptr, mpz_srcptr);
void __gmpz_add (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_add_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_addmul (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_addmul_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_and (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_array_init (mpz_ptr, mp_size_t, mp_size_t);
void __gmpz_bin_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_bin_uiui (mpz_ptr, unsigned long int, unsigned long int);
void __gmpz_cdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_cdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
unsigned long int __gmpz_cdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_cdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
unsigned long int __gmpz_cdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_cdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_cdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
unsigned long int __gmpz_cdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int);
unsigned long int __gmpz_cdiv_ui (mpz_srcptr, unsigned long int) ;
void __gmpz_clear (mpz_ptr);
void __gmpz_clears (mpz_ptr, ...);
void __gmpz_clrbit (mpz_ptr, mp_bitcnt_t);
int __gmpz_cmp (mpz_srcptr, mpz_srcptr) ;
int __gmpz_cmp_d (mpz_srcptr, double) ;
int __gmpz_cmpabs (mpz_srcptr, mpz_srcptr) ;
int __gmpz_cmpabs_d (mpz_srcptr, double) ;
int __gmpz_cmpabs_ui (mpz_srcptr, unsigned long int) ;
void __gmpz_com (mpz_ptr, mpz_srcptr);
void __gmpz_combit (mpz_ptr, mp_bitcnt_t);
int __gmpz_congruent_p (mpz_srcptr, mpz_srcptr, mpz_srcptr) ;
int __gmpz_congruent_2exp_p (mpz_srcptr, mpz_srcptr, mp_bitcnt_t) ;
int __gmpz_congruent_ui_p (mpz_srcptr, unsigned long, unsigned long) ;
void __gmpz_divexact (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_divexact_ui (mpz_ptr, mpz_srcptr, unsigned long);
int __gmpz_divisible_p (mpz_srcptr, mpz_srcptr) ;
int __gmpz_divisible_ui_p (mpz_srcptr, unsigned long) ;
int __gmpz_divisible_2exp_p (mpz_srcptr, mp_bitcnt_t) ;
void __gmpz_dump (mpz_srcptr);
void* __gmpz_export (void *, size_t *, int, size_t, int, size_t, mpz_srcptr);
void __gmpz_fac_ui (mpz_ptr, unsigned long int);
void __gmpz_2fac_ui (mpz_ptr, unsigned long int);
void __gmpz_mfac_uiui (mpz_ptr, unsigned long int, unsigned long int);
void __gmpz_primorial_ui (mpz_ptr, unsigned long int);
void __gmpz_fdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_fdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
unsigned long int __gmpz_fdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_fdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
unsigned long int __gmpz_fdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_fdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_fdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
unsigned long int __gmpz_fdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int);
unsigned long int __gmpz_fdiv_ui (mpz_srcptr, unsigned long int) ;
void __gmpz_fib_ui (mpz_ptr, unsigned long int);
void __gmpz_fib2_ui (mpz_ptr, mpz_ptr, unsigned long int);
int __gmpz_fits_sint_p (mpz_srcptr) ;
int __gmpz_fits_slong_p (mpz_srcptr) ;
int __gmpz_fits_sshort_p (mpz_srcptr) ;
int __gmpz_fits_uint_p (mpz_srcptr) ;
int __gmpz_fits_ulong_p (mpz_srcptr) ;
int __gmpz_fits_ushort_p (mpz_srcptr) ;
void __gmpz_gcd (mpz_ptr, mpz_srcptr, mpz_srcptr);
unsigned long int __gmpz_gcd_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_gcdext (mpz_ptr, mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
double __gmpz_get_d (mpz_srcptr) ;
double __gmpz_get_d_2exp (signed long int *, mpz_srcptr);
long int __gmpz_get_si (mpz_srcptr) ;
char *__gmpz_get_str (char *, int, mpz_srcptr);
unsigned long int __gmpz_get_ui (mpz_srcptr) ;
mp_limb_t __gmpz_getlimbn (mpz_srcptr, mp_size_t) ;
mp_bitcnt_t __gmpz_hamdist (mpz_srcptr, mpz_srcptr) ;
void __gmpz_import (mpz_ptr, size_t, int, size_t, int, size_t, const void *);
void __gmpz_init (mpz_ptr);
void __gmpz_init2 (mpz_ptr, mp_bitcnt_t);
void __gmpz_inits (mpz_ptr, ...);
void __gmpz_init_set (mpz_ptr, mpz_srcptr);
void __gmpz_init_set_d (mpz_ptr, double);
void __gmpz_init_set_si (mpz_ptr, signed long int);
int __gmpz_init_set_str (mpz_ptr, const char *, int);
void __gmpz_init_set_ui (mpz_ptr, unsigned long int);
int __gmpz_invert (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_ior (mpz_ptr, mpz_srcptr, mpz_srcptr);
int __gmpz_jacobi (mpz_srcptr, mpz_srcptr) ;
int __gmpz_kronecker_si (mpz_srcptr, long) ;
int __gmpz_kronecker_ui (mpz_srcptr, unsigned long) ;
int __gmpz_si_kronecker (long, mpz_srcptr) ;
int __gmpz_ui_kronecker (unsigned long, mpz_srcptr) ;
void __gmpz_lcm (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_lcm_ui (mpz_ptr, mpz_srcptr, unsigned long);
void __gmpz_lucnum_ui (mpz_ptr, unsigned long int);
void __gmpz_lucnum2_ui (mpz_ptr, mpz_ptr, unsigned long int);
int __gmpz_millerrabin (mpz_srcptr, int) ;
void __gmpz_mod (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_mul (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_mul_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
void __gmpz_mul_si (mpz_ptr, mpz_srcptr, long int);
void __gmpz_mul_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_neg (mpz_ptr, mpz_srcptr);
void __gmpz_nextprime (mpz_ptr, mpz_srcptr);
int __gmpz_perfect_power_p (mpz_srcptr) ;
int __gmpz_perfect_square_p (mpz_srcptr) ;
mp_bitcnt_t __gmpz_popcount (mpz_srcptr) ;
void __gmpz_pow_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_powm (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr);
void __gmpz_powm_sec (mpz_ptr, mpz_srcptr, mpz_srcptr, mpz_srcptr);
void __gmpz_powm_ui (mpz_ptr, mpz_srcptr, unsigned long int, mpz_srcptr);
int __gmpz_probab_prime_p (mpz_srcptr, int) ;
void __gmpz_random (mpz_ptr, mp_size_t);
void __gmpz_random2 (mpz_ptr, mp_size_t);
void __gmpz_realloc2 (mpz_ptr, mp_bitcnt_t);
mp_bitcnt_t __gmpz_remove (mpz_ptr, mpz_srcptr, mpz_srcptr);
int __gmpz_root (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_rootrem (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_rrandomb (mpz_ptr, gmp_randstate_t, mp_bitcnt_t);
mp_bitcnt_t __gmpz_scan0 (mpz_srcptr, mp_bitcnt_t) ;
mp_bitcnt_t __gmpz_scan1 (mpz_srcptr, mp_bitcnt_t) ;
void __gmpz_set (mpz_ptr, mpz_srcptr);
void __gmpz_set_d (mpz_ptr, double);
void __gmpz_set_f (mpz_ptr, mpf_srcptr);
void __gmpz_set_q (mpz_ptr, mpq_srcptr);
void __gmpz_set_si (mpz_ptr, signed long int);
int __gmpz_set_str (mpz_ptr, const char *, int);
void __gmpz_set_ui (mpz_ptr, unsigned long int);
void __gmpz_setbit (mpz_ptr, mp_bitcnt_t);
size_t __gmpz_size (mpz_srcptr) ;
size_t __gmpz_sizeinbase (mpz_srcptr, int) ;
void __gmpz_sqrt (mpz_ptr, mpz_srcptr);
void __gmpz_sqrtrem (mpz_ptr, mpz_ptr, mpz_srcptr);
void __gmpz_sub (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_sub_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_ui_sub (mpz_ptr, unsigned long int, mpz_srcptr);
void __gmpz_submul (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_submul_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_swap (mpz_ptr, mpz_ptr) ;
unsigned long int __gmpz_tdiv_ui (mpz_srcptr, unsigned long int) ;
void __gmpz_tdiv_q (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_tdiv_q_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
unsigned long int __gmpz_tdiv_q_ui (mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_tdiv_qr (mpz_ptr, mpz_ptr, mpz_srcptr, mpz_srcptr);
unsigned long int __gmpz_tdiv_qr_ui (mpz_ptr, mpz_ptr, mpz_srcptr, unsigned long int);
void __gmpz_tdiv_r (mpz_ptr, mpz_srcptr, mpz_srcptr);
void __gmpz_tdiv_r_2exp (mpz_ptr, mpz_srcptr, mp_bitcnt_t);
unsigned long int __gmpz_tdiv_r_ui (mpz_ptr, mpz_srcptr, unsigned long int);
int __gmpz_tstbit (mpz_srcptr, mp_bitcnt_t) ;
void __gmpz_ui_pow_ui (mpz_ptr, unsigned long int, unsigned long int);
void __gmpz_urandomb (mpz_ptr, gmp_randstate_t, mp_bitcnt_t);
void __gmpz_urandomm (mpz_ptr, gmp_randstate_t, mpz_srcptr);
void __gmpz_xor (mpz_ptr, mpz_srcptr, mpz_srcptr);
mp_srcptr __gmpz_limbs_read (mpz_srcptr);
mp_ptr __gmpz_limbs_write (mpz_ptr, mp_size_t);
mp_ptr __gmpz_limbs_modify (mpz_ptr, mp_size_t);
void __gmpz_limbs_finish (mpz_ptr, mp_size_t);
mpz_srcptr __gmpz_roinit_n (mpz_ptr, mp_srcptr, mp_size_t);
/** Rational
*/
void __gmpq_abs (mpq_ptr, mpq_srcptr);
void __gmpq_add (mpq_ptr, mpq_srcptr, mpq_srcptr);
void __gmpq_canonicalize (mpq_ptr);
void __gmpq_clear (mpq_ptr);
void __gmpq_clears (mpq_ptr, ...);
int __gmpq_cmp (mpq_srcptr, mpq_srcptr) ;
int __gmpq_cmp_si (mpq_srcptr, long, unsigned long) ;
int __gmpq_cmp_ui (mpq_srcptr, unsigned long int, unsigned long int) ;
int __gmpq_cmp_z (mpq_srcptr, mpz_srcptr) ;
void __gmpq_div (mpq_ptr, mpq_srcptr, mpq_srcptr);
void __gmpq_div_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t);
int __gmpq_equal (mpq_srcptr, mpq_srcptr) ;
void __gmpq_get_num (mpz_ptr, mpq_srcptr);
void __gmpq_get_den (mpz_ptr, mpq_srcptr);
double __gmpq_get_d (mpq_srcptr) ;
char* __gmpq_get_str (char *, int, mpq_srcptr);
void __gmpq_init (mpq_ptr);
void __gmpq_inits (mpq_ptr, ...);
void __gmpq_inv (mpq_ptr, mpq_srcptr);
void __gmpq_mul (mpq_ptr, mpq_srcptr, mpq_srcptr);
void __gmpq_mul_2exp (mpq_ptr, mpq_srcptr, mp_bitcnt_t);
void __gmpq_neg (mpq_ptr, mpq_srcptr);
void __gmpq_set (mpq_ptr, mpq_srcptr);
void __gmpq_set_d (mpq_ptr, double);
void __gmpq_set_den (mpq_ptr, mpz_srcptr);
void __gmpq_set_f (mpq_ptr, mpf_srcptr);
void __gmpq_set_num (mpq_ptr, mpz_srcptr);
void __gmpq_set_si (mpq_ptr, signed long int, unsigned long int);
int __gmpq_set_str (mpq_ptr, const char *, int);
void __gmpq_set_ui (mpq_ptr, unsigned long int, unsigned long int);
void __gmpq_set_z (mpq_ptr, mpz_srcptr);
void __gmpq_sub (mpq_ptr, mpq_srcptr, mpq_srcptr);
void __gmpq_swap (mpq_ptr, mpq_ptr) ;
/** Float
*/
void __gmpf_abs (mpf_ptr, mpf_srcptr);
void __gmpf_add (mpf_ptr, mpf_srcptr, mpf_srcptr);
void __gmpf_add_ui (mpf_ptr, mpf_srcptr, unsigned long int);
void __gmpf_ceil (mpf_ptr, mpf_srcptr);
void __gmpf_clear (mpf_ptr);
void __gmpf_clears (mpf_ptr, ...);
int __gmpf_cmp (mpf_srcptr, mpf_srcptr) ;
int __gmpf_cmp_z (mpf_srcptr, mpz_srcptr) ;
int __gmpf_cmp_d (mpf_srcptr, double) ;
int __gmpf_cmp_si (mpf_srcptr, signed long int) ;
int __gmpf_cmp_ui (mpf_srcptr, unsigned long int) ;
void __gmpf_div (mpf_ptr, mpf_srcptr, mpf_srcptr);
void __gmpf_div_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t);
void __gmpf_div_ui (mpf_ptr, mpf_srcptr, unsigned long int);
void __gmpf_dump (mpf_srcptr);
int __gmpf_eq (mpf_srcptr, mpf_srcptr, mp_bitcnt_t) ;
int __gmpf_fits_sint_p (mpf_srcptr) ;
int __gmpf_fits_slong_p (mpf_srcptr) ;
int __gmpf_fits_sshort_p (mpf_srcptr) ;
int __gmpf_fits_uint_p (mpf_srcptr) ;
int __gmpf_fits_ulong_p (mpf_srcptr) ;
int __gmpf_fits_ushort_p (mpf_srcptr) ;
void __gmpf_floor (mpf_ptr, mpf_srcptr);
double __gmpf_get_d (mpf_srcptr) ;
double __gmpf_get_d_2exp (signed long int *, mpf_srcptr);
mp_bitcnt_t __gmpf_get_default_prec (void) ;
mp_bitcnt_t __gmpf_get_prec (mpf_srcptr) ;
long __gmpf_get_si (mpf_srcptr) ;
char* __gmpf_get_str (char *, mp_exp_t *, int, size_t, mpf_srcptr);
unsigned long __gmpf_get_ui (mpf_srcptr) ;
void __gmpf_init (mpf_ptr);
void __gmpf_init2 (mpf_ptr, mp_bitcnt_t);
void __gmpf_inits (mpf_ptr, ...);
void __gmpf_init_set (mpf_ptr, mpf_srcptr);
void __gmpf_init_set_d (mpf_ptr, double);
void __gmpf_init_set_si (mpf_ptr, signed long int);
int __gmpf_init_set_str (mpf_ptr, const char *, int);
void __gmpf_init_set_ui (mpf_ptr, unsigned long int);
int __gmpf_integer_p (mpf_srcptr) ;
void __gmpf_mul (mpf_ptr, mpf_srcptr, mpf_srcptr);
void __gmpf_mul_2exp (mpf_ptr, mpf_srcptr, mp_bitcnt_t);
void __gmpf_mul_ui (mpf_ptr, mpf_srcptr, unsigned long int);
void __gmpf_neg (mpf_ptr, mpf_srcptr);
void __gmpf_pow_ui (mpf_ptr, mpf_srcptr, unsigned long int);
void __gmpf_random2 (mpf_ptr, mp_size_t, mp_exp_t);
void __gmpf_reldiff (mpf_ptr, mpf_srcptr, mpf_srcptr);
void __gmpf_set (mpf_ptr, mpf_srcptr);
void __gmpf_set_d (mpf_ptr, double);
void __gmpf_set_default_prec (mp_bitcnt_t) ;
void __gmpf_set_prec (mpf_ptr, mp_bitcnt_t);
void __gmpf_set_prec_raw (mpf_ptr, mp_bitcnt_t) ;
void __gmpf_set_q (mpf_ptr, mpq_srcptr);
void __gmpf_set_si (mpf_ptr, signed long int);
int __gmpf_set_str (mpf_ptr, const char *, int);
void __gmpf_set_ui (mpf_ptr, unsigned long int);
void __gmpf_set_z (mpf_ptr, mpz_srcptr);
size_t __gmpf_size (mpf_srcptr) ;
void __gmpf_sqrt (mpf_ptr, mpf_srcptr);
void __gmpf_sqrt_ui (mpf_ptr, unsigned long int);
void __gmpf_sub (mpf_ptr, mpf_srcptr, mpf_srcptr);
void __gmpf_sub_ui (mpf_ptr, mpf_srcptr, unsigned long int);
void __gmpf_swap (mpf_ptr, mpf_ptr) ;
void __gmpf_trunc (mpf_ptr, mpf_srcptr);
void __gmpf_ui_div (mpf_ptr, unsigned long int, mpf_srcptr);
void __gmpf_ui_sub (mpf_ptr, unsigned long int, mpf_srcptr);
void __gmpf_urandomb (mpf_t, gmp_randstate_t, mp_bitcnt_t);
/** Random
*/
void __gmp_randinit_default (gmp_randstate_t);
void __gmp_randinit_lc_2exp (gmp_randstate_t, mpz_srcptr, unsigned long int, mp_bitcnt_t);
int __gmp_randinit_lc_2exp_size (gmp_randstate_t, mp_bitcnt_t);
void __gmp_randinit_mt (gmp_randstate_t);
void __gmp_randinit_set (gmp_randstate_t, const __gmp_randstate_struct *);
void __gmp_randseed (gmp_randstate_t, mpz_srcptr);
void __gmp_randseed_ui (gmp_randstate_t, unsigned long int);
void __gmp_randclear (gmp_randstate_t);
unsigned long __gmp_urandomb_ui (gmp_randstate_t, unsigned long);
unsigned long __gmp_urandomm_ui (gmp_randstate_t, unsigned long);
/** Misc
*/
int __gmp_asprintf (char **, const char *, ...);
int __gmp_printf (const char *, ...);
int __gmp_snprintf (char *, size_t, const char *, ...);
int __gmp_sprintf (char *, const char *, ...);
int __gmp_vasprintf (char **, const char *, va_list);
int __gmp_vprintf (const char *, va_list);
int __gmp_vsnprintf (char *, size_t, const char *, va_list);
int __gmp_vsprintf (char *, const char *, va_list);
void* calloc(size_t count, size_t size);
void free(void*);
]]
local gmpffi = {
integer_interface = {
"mpz_abs",
"mpz_add",
"mpz_add_ui",
"mpz_addmul",
"mpz_addmul_ui",
"mpz_and",
"mpz_array_init",
"mpz_bin_ui",
"mpz_bin_uiui",
"mpz_cdiv_q",
"mpz_cdiv_q_2exp",
"mpz_cdiv_q_ui",
"mpz_cdiv_qr",
"mpz_cdiv_qr_ui",
"mpz_cdiv_r",
"mpz_cdiv_r_2exp",
"mpz_cdiv_r_ui",
"mpz_cdiv_ui",
"mpz_clear",
"mpz_clears",
"mpz_clrbit",
"mpz_cmp",
"mpz_cmp_d",
"mpz_cmpabs",
"mpz_cmpabs_d",
"mpz_cmpabs_ui",
"mpz_com",
"mpz_combit",
"mpz_congruent_p",
"mpz_congruent_2exp_p",
"mpz_congruent_ui_p",
"mpz_divexact",
"mpz_divexact_ui",
"mpz_divisible_p",
"mpz_divisible_ui_p",
"mpz_divisible_2exp_p",
"mpz_dump",
"mpz_export",
"mpz_fac_ui",
"mpz_2fac_ui",
"mpz_mfac_uiui",
"mpz_primorial_ui",
"mpz_fdiv_q",
"mpz_fdiv_q_2exp",
"mpz_fdiv_q_ui",
"mpz_fdiv_qr",
"mpz_fdiv_qr_ui",
"mpz_fdiv_r",
"mpz_fdiv_r_2exp",
"mpz_fdiv_r_ui",
"mpz_fdiv_ui",
"mpz_fib_ui",
"mpz_fib2_ui",
"mpz_fits_sint_p",
"mpz_fits_slong_p",
"mpz_fits_sshort_p",
"mpz_fits_uint_p",
"mpz_fits_ulong_p",
"mpz_fits_ushort_p",
"mpz_gcd",
"mpz_gcd_ui",
"mpz_gcdext",
"mpz_get_d",
"mpz_get_d_2exp",
"mpz_get_si",
"mpz_get_str",
"mpz_get_ui",
"mpz_getlimbn",
"mpz_hamdist",
"mpz_import",
"mpz_init",
"mpz_init2",
"mpz_inits",
"mpz_init_set",
"mpz_init_set_d",
"mpz_init_set_si",
"mpz_init_set_str",
"mpz_init_set_ui",
"mpz_invert",
"mpz_ior",
"mpz_jacobi",
"mpz_kronecker_si",
"mpz_kronecker_ui",
"mpz_si_kronecker",
"mpz_ui_kronecker",
"mpz_lcm",
"mpz_lcm_ui",
"mpz_lucnum_ui",
"mpz_lucnum2_ui",
"mpz_millerrabin",
"mpz_mod",
"mpz_mul",
"mpz_mul_2exp",
"mpz_mul_si",
"mpz_mul_ui",
"mpz_neg",
"mpz_nextprime",
"mpz_perfect_power_p",
"mpz_perfect_square_p",
"mpz_popcount",
"mpz_pow_ui",
"mpz_powm",
"mpz_powm_sec",
"mpz_powm_ui",
"mpz_probab_prime_p",
"mpz_random",
"mpz_random2",
"mpz_realloc2",
"mpz_remove",
"mpz_root",
"mpz_rootrem",
"mpz_rrandomb",
"mpz_scan0",
"mpz_scan1",
"mpz_set",
"mpz_set_d",
"mpz_set_f",
"mpz_set_q",
"mpz_set_si",
"mpz_set_str",
"mpz_set_ui",
"mpz_setbit",
"mpz_size",
"mpz_sizeinbase",
"mpz_sqrt",
"mpz_sqrtrem",
"mpz_sub",
"mpz_sub_ui",
"mpz_ui_sub",
"mpz_submul",
"mpz_submul_ui",
"mpz_swap",
"mpz_tdiv_ui",
"mpz_tdiv_q",
"mpz_tdiv_q_2exp",
"mpz_tdiv_q_ui",
"mpz_tdiv_qr",
"mpz_tdiv_qr_ui",
"mpz_tdiv_r",
"mpz_tdiv_r_2exp",
"mpz_tdiv_r_ui",
"mpz_tstbit",
"mpz_ui_pow_ui",
"mpz_urandomb",
"mpz_urandomm",
"mpz_xor",
"mpz_limbs_read",
"mpz_limbs_write",
"mpz_limbs_modify",
"mpz_limbs_finish",
"mpz_roinit_n",
},
rational_interface = {
"mpq_abs",
"mpq_add",
"mpq_canonicalize",
"mpq_clear",
"mpq_clears",
"mpq_cmp",
"mpq_cmp_si",
"mpq_cmp_ui",
"mpq_cmp_z",
"mpq_div",
"mpq_div_2exp",
"mpq_equal",
"mpq_get_num",
"mpq_get_den",
"mpq_get_d",
"mpq_get_str",
"mpq_init",
"mpq_inits",
"mpq_inv",
"mpq_mul",
"mpq_mul_2exp",
"mpq_neg",
"mpq_set",
"mpq_set_d",
"mpq_set_den",
"mpq_set_f",
"mpq_set_num",
"mpq_set_si",
"mpq_set_str",
"mpq_set_ui",
"mpq_set_z",
"mpq_sub",
"mpq_swap",
},
float_interface = {
"mpf_abs",
"mpf_add",
"mpf_add_ui",
"mpf_ceil",
"mpf_clear",
"mpf_clears",
"mpf_cmp",
"mpf_cmp_z",
"mpf_cmp_d",
"mpf_cmp_si",
"mpf_cmp_ui",
"mpf_div",
"mpf_div_2exp",
"mpf_div_ui",
"mpf_dump",
"mpf_eq",
"mpf_fits_sint_p",
"mpf_fits_slong_p",
"mpf_fits_sshort_p",
"mpf_fits_uint_p",
"mpf_fits_ulong_p",
"mpf_fits_ushort_p",
"mpf_floor",
"mpf_get_d",
"mpf_get_d_2exp",
"mpf_get_default_prec",
"mpf_get_prec",
"mpf_get_si",
"mpf_get_str",
"mpf_get_ui",
"mpf_init",
"mpf_init2",
"mpf_inits",
"mpf_init_set",
"mpf_init_set_d",
"mpf_init_set_si",
"mpf_init_set_str",
"mpf_init_set_ui",
"mpf_integer_p",
"mpf_mul",
"mpf_mul_2exp",
"mpf_mul_ui",
"mpf_neg",
"mpf_pow_ui",
"mpf_random2",
"mpf_reldiff",
"mpf_set",
"mpf_set_d",
"mpf_set_default_prec",
"mpf_set_prec",
"mpf_set_prec_raw",
"mpf_set_q",
"mpf_set_si",
"mpf_set_str",
"mpf_set_ui",
"mpf_set_z",
"mpf_size",
"mpf_sqrt",
"mpf_sqrt_ui",
"mpf_sub",
"mpf_sub_ui",
"mpf_swap",
"mpf_trunc",
"mpf_ui_div",
"mpf_ui_sub",
"mpf_urandomb",
},
random_interface = {
"randinit_default",
"randinit_lc_2exp",
"randinit_lc_2exp_size",
"randinit_mt",
"randinit_set",
"randseed",
"randseed_ui",
"randclear",
"urandomb_ui",
"urandomm_ui",
},
misc_interface = {
["asprintf"] = "__gmp_asprintf",
["printf"] = "__gmp_printf",
["snprintf"] = "__gmp_snprintf",
["sprintf"]= "__gmp_sprintf",
["vasprintf"] = "__gmp_vasprintf",
["vprintf"] = "__gmp_vprintf",
["vsnprintf"] = "__gmp_vsnprintf",
["vsprintf"] = "__gmp_vsprintf",
["mpz_sgn"] = "",
["mpf_sgn"] = "",
["mpq_sgn"] = "",
["mpz_odd"] = "",
["mpz_even"] = "",
["randinit"] = "",
["cstring"] = "",
["tostring"] = "",
}
}
function gmpffi.help( option )
if not option then
print("Usage: gmp.mpz(), gmp.mpf(), gmp.mpq(), gmp.randinit() with ffi.gc() hook")
print("supported interface with gmp.help(\"[integer|rational|float|random|misc]\")")
return
end
local tbl = nil
if option == "misc" then
tbl = gmpffi.misc_interface
elseif option == "random" then
tbl = gmpffi.random_interface
elseif option == "float" then
tbl = gmpffi.float_interface
elseif option == "rational" then
tbl = gmpffi.rational_interface
elseif option == "integer" then
tbl = gmpffi.integer_interface
end
if #tbl > 0 then
for _, v in ipairs(tbl) do
print(v)
end
else
for k, _ in pairs(tbl) do
print(k)
end
end
end
function gmpffi.mpz( value, base )
local mpz = ffi.new("mpz_t")
if mpz then
ffi.gc(mpz, gmp.__gmpz_clear)
if type(value) == "string" then
gmp.__gmpz_init_set_str(mpz, value, base or 10)
elseif type(value) == "number" then
gmp.__gmpz_init_set_d(mpz, value)
else
gmp.__gmpz_init(mpz)
end
return mpz
end
return nil
end
function gmpffi.mpz_sgn( value )
assert(value)
local v = value[0]._mp_size;
return v < 0 and -1 or v > 0 and 1 or 0
end
function gmpffi.mpz_odd( value )
assert(value)
return value[0]._mp_size ~= 0 and bit.band(1, tonumber(value[0]._mp_d[0])) == 1
end
function gmpffi.mpz_even( value )
return not gmpffi.mpz_odd( value )
end
function gmpffi.mpf( value, base )
local mpf = ffi.new("mpf_t")
if mpf then
ffi.gc(mpf, gmp.__gmpf_clear)
if type(value) == "string" then
gmp.__gmpf_init_set_str(mpf, value, base or 10)
elseif type(value) == "number" then
gmp.__gmpf_init_set_d(mpf, value)
else
gmp.__gmpf_init(mpf)
end
return mpf
end
return nil
end
function gmpffi.mpf_sgn( value )
assert(value)
local v = value[0]._mp_size;
return v < 0 and -1 or v > 0 and 1 or 0
end
function gmpffi.mpq( num, den )
local mpq = ffi.new("mpq_t")
if mpq then
ffi.gc(mpq, gmp.__gmpq_clear)
gmp.__gmpq_init(mpq)
if type(num) == "string" then
gmp.__gmpq_set_str(mpq, num, 10)
elseif type(num) == "number" and type(den) == "number" then
gmp.__gmpq_set_si(mpq, num, den)
end
return mpq
end
return nil
end
function gmpffi.mpq_sgn( value )
assert(value)
local v = value[0]._mp_num._mp_size;
return v < 0 and -1 or v > 0 and 1 or 0
end
function gmpffi.randinit()
local rt = ffi.new("gmp_randstate_t")
ffi.gc(rt, gmp.__gmp_randclear)
gmp.__gmp_randinit_mt(rt)
gmp.__gmp_randseed_ui(rt, os.time())
return rt
end
function gmpffi.cstring( count )
local n = tonumber(count) > 0 and count or 128
return ffi.gc(ffi.C.calloc(n/2+1, 2), ffi.C.free)
end
function gmpffi.tostring( cs )
assert(cs)
return ffi.string(cs)
end
function gmpffi.init()
local tbl = {
gmpffi.integer_interface,
gmpffi.rational_interface,
gmpffi.float_interface
}
for _, inteface in ipairs(tbl) do
for _, name in ipairs(inteface) do
local fname = "__g" .. name
assert(gmp[fname], string.format("gmp.%s not exist", name))
gmpffi[name] = gmp[fname]
end
end
for _, name in pairs(gmpffi.random_interface) do
local fname = "__gmp_" .. name
assert(gmp[fname], string.format("gmp.%s not exist", name));
gmpffi[name] = gmp[fname]
end
for name, fname in pairs(gmpffi.misc_interface) do
if fname:len() > 3 then
assert(gmp[fname], string.format("gmp.%s not exist", name))
gmpffi[name] = gmp[fname]
end
end
return true
end
return gmpffi.init() and gmpffi
|
function init(virtual)
if not virtual then
entity.setInteractive(true)
end
end
function onInteraction(args)
if args ~= nil and args.sourceId ~= nil then
local p = entity.position()
local parameters = {}
local type = "gardenbotv80g"
if entity.configParameter("botspawner.type") ~= nil then
type = entity.configParameter("botspawner.type")
end
parameters.persistent = true
parameters.damageTeam = 0
parameters.ownerUuid = args.sourceId
parameters.level = 1
parameters.spawnPoint = {p[1], p[2] + 1}
world.spawnMonster(type, {p[1], p[2] + 1}, parameters)
entity.smash()
end
end |
function description()
return "Open a web page"
end
function run()
if #arguments > 0 then
windex = focused_window_index()
target = arguments[1]
load_uri(windex, focused_webview_index(windex), target)
return true
end
log_debug("No URL specified")
return false
end
|
EssentialsPlugin.Server_ShutdownCommand = function(client, args)
if (not PermissionsPlugin.CheckPermissionNotify(client, "essentials.server")) then
return
end
local index = 1 -- used to concatenate reason message
local time = 15
if (args[1] == "-t" and args[2] ~= nil) then
time = tonumber(args[2])
if (time == nil) then
Server.SendMessage(client, "&cMalformed input")
return
end
index = 3 -- skip time arguments
elseif (args[1] == "-a") then
if (CorePlugin.TimerExists("server_timers")) then
CorePlugin.RemoveTimer("server_timers")
Server.SystemWideMessage(client.name .. " aborted server shutdown.")
print("Server plugin: " .. client.name .. " aborted server shutdown.")
else
Server.SendMessage(client, "&cNo shutdown to abort")
end
return
end
if (CorePlugin.TimerExists("server_timers")) then
Server.SendMessage(client, "&cShutdown already in progress (use /shutdown -a to abort)")
return
end
local message = "(" .. client.name .. ")" .. " Server shutting down in " .. time .. " seconds..."
local reason = "Server shut down"
if (args[index] ~= nil) then
reason = table.concat(args, " ", index)
message = message .. " (" .. reason .. ")"
end
Server.SystemWideMessage(message)
print("Server plugin: " .. message)
if (time > 10) then
CorePlugin.AddTimer("server_timers", function() Server.SystemWideMessage("Server shutting down in 10 seconds!") end, time - 10)
end
if (time > 5) then
CorePlugin.AddTimer("server_timers", function() Server.SystemWideMessage("Server shutting down in 5 seconds!") end, time - 5)
end
CorePlugin.AddTimer("server_timers", function() EssentialsPlugin.Server_SafeShutdown(reason) end, time)
end
EssentialsPlugin.Server_SafeShutdown = function(reason)
print("Server plugin: Server shutting down")
local clients = Server.GetClients()
for _,client in pairs(clients) do
Server.SendKick(client, reason)
end
local worlds = Server.GetWorlds()
for _,world in pairs(worlds) do
if (world:GetOption("autosave") == "true") then
world:Save()
world:SetOption("autosave", "false") -- So the world doesn't try to save again before shutdown
end
end
Server.Shutdown()
end
|
return "This is file A"
|
local SszViewCtr = require("app.demo.DowneyTang.CapsaSusun.SszViewCtr")
local function main()
local scene = cc.Scene:create()
local SszViewCtr = SszViewCtr.new();
SszViewCtr:initView()
scene:addChild(SszViewCtr:getView());
return scene
end
return main |
--! @brief places player in invite list
function factions.invite_player(name, player)
local faction = factions.factions.get(name)
faction.invited_players[player] = true
factions.on_player_invited(name, player)
factions.factions.set(name, faction)
end
--! @brief removes player from invite list (can no longer join via /f join)
function factions.revoke_invite(name, player)
local faction = factions.factions.get(name)
faction.invited_players[player] = nil
factions.on_revoke_invite(name, player)
factions.factions.set(name, faction)
end
|
local Utils = require "Utils"
local xml2lua = require("xml2lua")
local LayoutIO = {}
local xmlDecl = "<?xml version=\"1.0\" encoding=\"utf-8\"?> \n"
local function fileExists(path)
local file = io.open(path)
if file == nil then
return false
else
return true
end
end
function LayoutIO.read(path, parser, handler, progressHandle)
if fileExists(path) == false then
gma.gui.progress.stop(progressHandle)
return nil
end
local file = io.open(path, "r")
io.input(file)
local xml = ""
local lineCount = 0
for line in io.lines() do
xml = xml .. "\n" .. Utils.trimBOM(line)
lineCount = lineCount + 1
end
io.close(file)
gma.gui.progress.setrange(progressHandle, 0, lineCount)
local parseCount = 0
local progressCallback = function()
if (math.fmod(parseCount, 10) == 0) then
gma.gui.progress.set(progressHandle, parseCount)
end
parseCount = parseCount + 1
end
parser:parse(Utils.trim(xml), nil, progressCallback)
gma.gui.progress.stop(progressHandle)
return handler.root
end
function LayoutIO.write(path, data)
local file = io.open(path, "w+")
io.output(file)
io.write(xmlDecl)
io.write(xml2lua.toXml(data))
io.close()
end
return LayoutIO
|
#!/usr/bin/lua
local uci = require 'uci'.cursor()
local ubus = require('ubus').connect()
local neighbor_reports = {}
local function hasKey(tab, key)
for k, _ in pairs(tab) do
if k == key then return true end
end
return false
end
uci:foreach('static-neighbor-report', 'neighbor', function (config)
if hasKey(config, "disabled") and config.disabled ~= '0' then
return
end
local bssid = ''
local ssid = ''
local neighbor_report = config['neighbor_report']
if hasKey(config, 'bssid') then bssid = config.bssid end
if hasKey(config, 'ssid') then ssid = config.ssid end
for iface in config.iface:gmatch("%S+") do
if not hasKey(neighbor_reports, iface) then
neighbor_reports[iface] = {}
end
table.insert(neighbor_reports[iface], {bssid, ssid, neighbor_report})
end
end)
for k, v in pairs(neighbor_reports) do
ubus:call('hostapd.' .. k, 'rrm_nr_set', {list=v})
end
|
local CommandBytes = {
nameChange = "\1",
chat = "\4",
pm = "\5",
message = "\7",
version = "\19",
pingRequest = "\26",
pingResponse = "\27",
sendAction = "\9",
sendAlias = "\10",
sendMacro = "\11",
sendVariable = "\12",
sendEvent = "\13",
sendGag = "\14",
sendHighlight = "\15",
sendList = "\16",
sendArray = "\17",
sendBarItem = "\18",
snoopStart = "\30",
snoopData = "\31",
sendSubstitute = "\33",
}
local Commands = { }
local MaxMessageLength = 4096
for name, byte in pairs( CommandBytes ) do
Commands[ byte ] = name
end
local MMClient = {
protocol = "mm",
pmSyntax = "/chat",
}
function MMClient:processData()
while true do
local byte, args, len = self.dataBuffer:match( "^(.)(.-)\255()" )
if not byte then
break
end
local command = Commands[ byte ]
if command == "message" then
if args:match( "<CHAT> .- is now accepting commands from you%." ) then
self.acceptCommands = true
elseif args:match( "<CHAT> .- is no longer accepting commands from you %." ) then
self.acceptCommands = false
elseif args:match( "<CHAT> You are now allowed to snoop .-%." ) then
self.allowSnoop = true
elseif args:match( "You are no longer allowed to snoop .-%." ) then
self.allowSnoop = false
end
end
if command == "pm" then
local pm = args:match( "chats to you, '(.*)'\n$" )
if pm then
self:onCommand( "pm", pm:trimVT102() )
end
elseif command then
self:onCommand( command, args )
end
self.dataBuffer = self.dataBuffer:sub( len )
end
end
function MMClient:send( command, args )
if not args then
args = ""
end
enforce( command, "command", "string" )
enforce( args, "args", "string" )
local byte = CommandBytes[ command ]
assert( byte, "bad command: " .. command )
if args:len() < MaxMessageLength or self.version == "MudGangster" then
self:raw( byte .. args .. "\255" )
else
local head = 1
while head < args:len() do
local tail = head - 1
local hasNewline = true
local breakAt = head + MaxMessageLength
while true do
local newlinePos = args:find( "\n", tail + 1 )
if not newlinePos or newlinePos > breakAt then
break
end
tail = newlinePos
end
if tail == head - 1 then
tail = breakAt
hasNewline = false
end
self:raw( byte .. args:sub( head, tail - ( hasNewline and 1 or 0 ) ) .. "\255" )
head = tail + 1
end
end
end
local _M = { client = MMClient }
function _M.accept( client )
local name, len = client.dataBuffer:match( "^CHAT:(.-)\n.+[%d ][%d ][%d ][%d ][%d ]()" )
if not name then
return false
end
client.name = name
client.lower = name:lower()
client.dataBuffer = client.dataBuffer:sub( len )
client:raw( "YES:" .. chat.config.name .. "\n" )
return true
end
return _M
|
function getCharacterId()
return exports["caue-base"]:getChar("id")
end
|
return {
fadeOut = 1.5,
mode = 2,
id = "XINNIAN5",
once = true,
fadeType = 1,
fadein = 1.5,
scripts = {
{
mode = 1,
sequence = {
{
"新年快乐\n\n<size=45>五 贺年卡</size>",
1
}
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:34}",
dir = 1,
say = "{namecode:93},你在干什么呀?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
side = 1,
nameColor = "#a9f548",
actorName = "{namecode:93}",
dir = 1,
say = "是{namecode:34}啊,我在给大家写贺年卡呢。",
paintingFadeOut = {
time = 0.5,
side = 0
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:34}",
dir = 1,
say = "贺年卡?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "就是写贺卡给朋友们表达新年问候,关系好的还会报告近况之类的~",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:34}",
dir = 1,
say = "我也……可以写吗?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "当然可以了,你想写给谁?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:34}",
dir = 1,
say = "写给……写给……写给指挥官?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:34}",
dir = 1,
say = "{namecode:34}想祝指挥官新年快乐……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "哦?这个想法不错呢,能收到{namecode:34}的贺年卡,指挥官一定会很开心吧。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:16}",
dir = 1,
say = "嗯?什么指挥官会很开心?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "{namecode:16},不要在走廊上跑……{namecode:34}想给指挥官写贺年卡,我说这样指挥官会很开心。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:16}",
dir = 1,
say = "什么!那我也要写!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "你真的要写?那就过来这边坐下吧。{namecode:34}也是,我把卡片和笔分给你们。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:34}",
dir = 1,
say = "嗯!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:16}",
dir = 1,
say = "{namecode:93},这个卡上为什么画着狗呀?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "因为贺年卡上一般会印着新一年的生肖,明年是狗年哦。怎么了,很开心吗?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:16}",
dir = 1,
say = "我才不是狗!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "呵呵,总之,贺年卡想写什么其实没有特别的规定,尤其是孩子们,把想到的写上去然后交给指挥官就好了。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:16}",
dir = 1,
say = "那我就写“指挥官,明年我也要吃好多肉”。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "……………………好吧,{namecode:16},{namecode:34}也听着,至少要在贺年卡的开头写上“新年快乐”四个字才行哦。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:16}",
dir = 1,
say = "欸……这四个字怎么写啊?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:34}",
dir = 1,
say = "{namecode:34}……也不会。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "那就从这四个字开始教起吧……来,我写一遍,你们按照我的笔画跟着写。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 303030,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:55}",
dir = 1,
say = "咦,{namecode:93},你们三个在这里干什么呢?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "{namecode:16}和{namecode:34}想给指挥官写贺年卡,我正在教她们。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 303030,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:55}",
dir = 1,
say = "哦?………………原来如此,我明白了,那我先走了。",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
dir = 1,
side = 2,
say = "一小时后……",
flashout = {
black = true,
dur = 1,
alpha = {
0,
1
}
},
flashin = {
delay = 1,
dur = 1,
black = true,
alpha = {
1,
0
}
},
typewriter = {
speed = 0.05,
speedUp = 0.01
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:93}",
dir = 1,
say = "{namecode:55},是你干的吧……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 303030,
side = 0,
nameColor = "#a9f548",
actorName = "{namecode:55}",
dir = 1,
say = "什么事?",
paintingFadeOut = {
time = 0.5,
side = 1
},
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "把驱逐的孩子们全叫过来写贺年卡……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 303030,
nameColor = "#a9f548",
side = 0,
actorName = "{namecode:55}",
dir = 1,
say = "哪里,我只是问大家有没有兴趣向指挥官表达感谢之情而已~",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301320,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:33}",
dir = 1,
say = "{namecode:93}老师,你看我画的花好看吗!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301330,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:34}",
dir = 1,
say = "{namecode:93}……老师,喜字这么写……对吗?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301140,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:16}",
dir = 1,
say = "{namecode:93},这张卡上有肉,我要用这张卡写!",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301300,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:124}",
dir = 1,
say = "嚯嚯,要不要写一点稍微刺激的东西呢~",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301560,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:125}",
dir = 1,
say = "呜呜,又写错了……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 301170,
nameColor = "#a9f548",
side = 2,
actorName = "{namecode:19}",
dir = 1,
say = "{namecode:93},你看吾辈的字写得好看吗?",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 303030,
nameColor = "#a9f548",
side = 0,
hideOther = true,
dir = 1,
actorName = "{namecode:55}",
say = "好,明天的头条就决定了!《人气超高!年关将至的{namecode:93}老师特别教室!》",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "为什么{namecode:124}也跟着混在里面凑热闹……算了,这样也不坏吧……",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
},
{
actor = 307030,
nameColor = "#a9f548",
side = 1,
actorName = "{namecode:93}",
dir = 1,
say = "好了,有问题一个一个来,我先把“新年快乐”四个字重新写一遍,大家看清楚我的笔画——",
typewriter = {
speed = 0.05,
speedUp = 0.01
},
painting = {
alpha = 0.3,
time = 1
}
}
}
}
|
-- imports
local active_screen = require 'active_screen'
local game_view = require 'game_view'
local level_list = require 'level_list'
function exports()
local instance = {}
local backButton = love.graphics.newImage('level_select/back.png')
local backX = 20
local backY = 600
local backWidth = 300
local backHeight = 100
local levelButton = love.graphics.newImage('placeholders/watcher.png')
local levelStartX = 50
local levelStartY = 100
local levels = level_list.get_levels()
local lastFrameMouseClicked = true
function instance:update()
local mouse_x, mouse_y = love.mouse.getPosition()
local mouseClicked = love.mouse.isDown('l')
if mouseClicked and not lastFrameMouseClicked then
if mouse_x >= backX and mouse_y >= backY and mouse_x < backX + backWidth and mouse_y < backY + backHeight then
active_screen.set(require('initial_menu_view')())
end
local x = levelStartX
local y = levelStartY
for i = 1, #levels do
x = x + 32
if mouse_x >= x and mouse_y >= y and mouse_x < x + 32 and mouse_y < y + 32 then
active_screen.set(game_view(levels[i]))
end
end
end
lastFrameMouseClicked = mouseClicked
end
function instance:draw()
love.graphics.setColor(255, 255, 255)
love.graphics.rectangle('fill', 0, 0, 1280, 720)
love.graphics.draw(backButton, backX, backY)
local x = levelStartX
local y = levelStartY
for i = 1, #levels do
x = x + 32
love.graphics.draw(levelButton, x, y)
end
end
return instance
end
return exports
|
local M = {}
function M.MouseEnable(mode)
io.write(string.format('\027[?%dh', mode))
io.flush()
end
function M.MouseDisable(mode)
io.write(string.format('\027[?%dl', mode))
io.flush()
end
function M.cycle(n)
local i = 1
return function()
local result = i
i = i + 1
if i > n then i = 1 end
return result
end
end
return M
|
local PLUGIN = PLUGIN
local PANEL = {}
function PANEL:Init()
if (IsValid(ix.gui.areaEdit)) then
ix.gui.areaEdit:Remove()
end
ix.gui.areaEdit = self
self.list = {}
self.properties = {}
self:SetDeleteOnClose(true)
self:SetSizable(true)
self:SetTitle(L("areaNew"))
-- scroll panel
self.canvas = self:Add("DScrollPanel")
self.canvas:Dock(FILL)
-- name entry
self.nameEntry = vgui.Create("ixTextEntry")
self.nameEntry:SetFont("ixMenuButtonFont")
self.nameEntry:SetText(L("areaNew"))
local listRow = self.canvas:Add("ixListRow")
listRow:SetList(self.list)
listRow:SetLabelText(L("name"))
listRow:SetRightPanel(self.nameEntry)
listRow:Dock(TOP)
listRow:SizeToContents()
-- type entry
self.typeEntry = self.canvas:Add("DComboBox")
self.typeEntry:Dock(RIGHT)
self.typeEntry:SetFont("ixMenuButtonFont")
self.typeEntry:SetTextColor(color_white)
self.typeEntry.OnSelect = function(panel)
panel:SizeToContents()
panel:SetWide(panel:GetWide() + 12) -- padding for arrow (nice)
end
for id, name in pairs(ix.area.types) do
self.typeEntry:AddChoice(L(name), id, id == "area")
end
listRow = self.canvas:Add("ixListRow")
listRow:SetList(self.list)
listRow:SetLabelText(L("type"))
listRow:SetRightPanel(self.typeEntry)
listRow:Dock(TOP)
listRow:SizeToContents()
-- properties
for k, v in pairs(ix.area.properties) do
local panel
if (v.type == ix.type.string or v.type == ix.type.number) then
panel = vgui.Create("ixTextEntry")
panel:SetFont("ixMenuButtonFont")
panel:SetText(tostring(v.default))
if (v.type == ix.type.number) then
panel.realGetValue = panel.GetValue
panel.GetValue = function()
return tonumber(panel:realGetValue()) or v.default
end
end
elseif (v.type == ix.type.bool) then
panel = vgui.Create("ixCheckBox")
panel:SetChecked(v.default, true)
elseif (v.type == ix.type.color) then
panel = vgui.Create("DButton")
panel.value = v.default
panel:SetText("")
panel:SetSize(64, 64)
panel.picker = vgui.Create("DColorCombo")
panel.picker:SetColor(panel.value)
panel.picker:SetVisible(false)
panel.picker.OnValueChanged = function(_, newColor)
panel.value = newColor
end
panel.Paint = function(_, width, height)
surface.SetDrawColor(Color(0, 0, 0, 255))
surface.DrawOutlinedRect(0, 0, width, height)
surface.SetDrawColor(panel.value)
surface.DrawRect(4, 4, width - 8, height - 8)
end
panel.DoClick = function()
if (!panel.picker:IsVisible()) then
local x, y = panel:LocalToScreen(0, 0)
panel.picker:SetPos(x, y + 32)
panel.picker:SetColor(panel.value)
panel.picker:SetVisible(true)
panel.picker:MakePopup()
else
panel.picker:SetVisible(false)
end
end
panel.OnRemove = function()
panel.picker:Remove()
end
panel.GetValue = function()
return panel.picker:GetColor()
end
end
if (IsValid(panel)) then
local row = self.canvas:Add("ixListRow")
row:SetList(self.list)
row:SetLabelText(L(k))
row:SetRightPanel(panel)
row:Dock(TOP)
row:SizeToContents()
end
self.properties[k] = function()
return panel:GetValue()
end
end
-- save button
self.saveButton = self:Add("DButton")
self.saveButton:SetText(L("save"))
self.saveButton:SizeToContents()
self.saveButton:Dock(BOTTOM)
self.saveButton.DoClick = function()
self:Submit()
end
self:SizeToContents()
self:SetPos(64, 0)
self:CenterVertical()
end
function PANEL:SizeToContents()
local width = 64
local height = 37
for _, v in ipairs(self.canvas:GetCanvas():GetChildren()) do
width = math.max(width, v:GetLabelWidth())
height = height + v:GetTall()
end
self:SetWide(width + 200)
self:SetTall(height + self.saveButton:GetTall())
end
function PANEL:Submit()
local name = self.nameEntry:GetValue()
if (ix.area.stored[name]) then
ix.util.NotifyLocalized("areaAlreadyExists")
return
end
local properties = {}
for k, v in pairs(self.properties) do
properties[k] = v()
end
local _, type = self.typeEntry:GetSelected()
net.Start("ixAreaAdd")
net.WriteString(name)
net.WriteString(type)
net.WriteVector(PLUGIN.editStart)
net.WriteVector(PLUGIN:GetPlayerAreaTrace().HitPos)
net.WriteTable(properties)
net.SendToServer()
PLUGIN.editStart = nil
self:Remove()
end
function PANEL:OnRemove()
PLUGIN.editProperties = nil
end
vgui.Register("ixAreaEdit", PANEL, "DFrame")
if (IsValid(ix.gui.areaEdit)) then
ix.gui.areaEdit:Remove()
end |
-- Copyright (c) 2021 EngineerSmith
-- Under the MIT license, see license suppiled with this file
local path = select(1, ...):match("(.-)[^%.]+$")
local baseAtlas = require(path .. "baseAtlas")
local util = require(path .. "util")
local fixedSizeTA = setmetatable({}, baseAtlas)
fixedSizeTA.__index = fixedSizeTA
local lg = love.graphics
local newImageData = love.image.newImageData
local ceil, floor, sqrt = math.ceil, math.sqrt, math.floor
fixedSizeTA.new = function(width, height, padding, extrude, spacing)
local self = setmetatable(baseAtlas.new(padding, extrude, spacing), fixedSizeTA)
self.width = width or error("Width required")
self.height = height or width
return self
end
fixedSizeTA.add = function(self, image, id, bake)
local width, height = util.getImageDimensions(image)
if width ~= self.width or height ~= self.height then
error("Given image cannot fit into a fixed sized texture atlas\n Gave: W:".. tostring(width) .. " H:" ..tostring(height) .. ", Expected: W:"..self.width.." H:"..self.height)
end
return baseAtlas.add(self, image, id, bake)
end
fixedSizeTA.bake = function(self)
if self._dirty and not self._hardBake then
local columns = ceil(sqrt(self.imagesSize))
local width, height = self.width, self.height
local widthPadded = width + self.spacing + self.extrude * 2 + self.padding * 2
local heightPadded = height + self.spacing + self.extrude * 2 + self.padding * 2
local maxIndex = self.imagesSize
local data
local widthCanvas = columns * widthPadded
if widthCanvas > (self.maxWidth or self._maxCanvasSize) then
error("Required width for atlas cannot be created due to reaching limits. Required: "..widthCanvas..", width limit: "..(self.maxWidth or self._maxCanvasSize))
end
local rows = ceil(self.imagesSize / columns)
local heightCanvas = rows * heightPadded
if heightPadded > (self.maxHeight or self._maxCanvasSize) then
error("Required height for atlas cannot be created due to reaching limits. Required: "..heightCanvas..", height limit: "..(self.maxHeight or self._maxCanvasSize))
end
widthCanvas, heightCanvas = widthCanvas - self.spacing, heightCanvas - self.spacing
if self.bakeAsPow2 then
widthCanvas = math.pow(2, math.ceil(math.log(widthCanvas)/math.log(2)))
heightCanvas = math.pow(2, math.ceil(math.log(heightCanvas)/math.log(2)))
end
if self._pureImageMode then
data = newImageData(widthCanvas, heightCanvas, "rgba8")
for x=0, columns-1 do
for y=0, rows-1 do
local index = (x*rows+y)+1
if index > maxIndex then
break
end
local x, y = x * widthPadded + self.padding + self.extrude, y * heightPadded + self.padding + self.extrude
local image = self.images[index]
data:paste(image.image, x, y, 0, 0, image.image:getDimensions())
if self.extrude > 0 then
util.extrudeWithFill(data, image.image, self.extrude, x, y)
end
self.quads[image.id] = {x+self.extrude, y+self.extrude, width, height}
end
end
else
local extrudeQuad = lg.newQuad(-self.extrude, -self.extrude, width+self.extrude*2, height+self.extrude*2, self.width, self.height)
local canvas = lg.newCanvas(widthCanvas, heightCanvas, self._canvasSettings)
lg.push("all")
lg.setBlendMode("replace")
lg.setCanvas(canvas)
for x=0, columns-1 do
for y=0, rows-1 do
local index = (x*rows+y)+1
if index > maxIndex then
break
end
local x, y = x * widthPadded + self.padding, y * heightPadded + self.padding
local image = self.images[index]
lg.draw(image.image, extrudeQuad, x, y)
self.quads[image.id] = lg.newQuad(x+self.extrude, y+self.extrude, width, height, widthCanvas, heightCanvas)
end
end
lg.pop()
data = canvas:newImageData()
self.image = lg.newImage(data)
self.image:setFilter(self.filterMin, self.filterMag)
end
self._dirty = false
return self, data
end
return self
end
return fixedSizeTA
|
local ok, treesitter = pcall(require, "nvim-treesitter.configs")
if not ok then
vim.notify "Could not load treesitter"
return
end
treesitter.setup {
ensure_installed = "all",
sync_install = true,
ignore_install = {},
highlight = {
enable = true,
disable = {},
},
incremental_selection = {
enable = false,
keymaps = {
init_selection = "gnn",
node_incremental = "grn",
scope_incrementnl = "grc",
node_decremental = "grm",
},
},
indent = {
enable = true,
},
refactor = {
smart_rename = {
enable = false,
keymaps = {
smart_rename = "grr",
},
},
},
autotag = {
enable = true,
},
rainbow = {
enable = true,
-- disable = { "jsx", "cpp" }, list of languages you want to disable the plugin for
extended_mode = true, -- Also highlight non-bracket delimiters like html tags, boolean or table: lang -> boolean
max_file_lines = nil, -- Do not enable for files with more than n lines, int
-- colors = {}, -- table of hex strings
-- termcolors = {} -- table of colour name strings
},
endwise = {
enable = false,
},
context_commentstring = {
enable = true,
enable_autocmd = false,
},
}
vim.o.foldmethod = "expr"
vim.o.foldexpr = "nvim_treesitter#foldexpr()"
|
-- 历史上的今天
local Api = require("coreApi")
local json = require("json")
local http = require("http")
function ReceiveFriendMsg(CurrentQQ, data)
return 1
end
function ReceiveGroupMsg(CurrentQQ, data)
if data.FromUserId == tonumber(CurrentQQ) then
return 1
end
if string.find(data.Content, "历史上的今天") then
rep, _ = http.request(
"GET",
"http://127.0.0.1:8080/today_in_history/"
)
Api.Api_SendMsg(
CurrentQQ,
{
toUser = data.FromGroupId,
sendToType = 2,
sendMsgType = "TextMsg",
groupid = 0,
content = '\n'..rep.body,
atUser = data.FromUserId
}
)
return 2
end
return 1
end
function ReceiveEvents(CurrentQQ, data, extData)
return 1
end
|
-----------------------------------
--
-- Zone: Lebros_Cavern
--
-----------------------------------
require("scripts/zones/Lebros_Cavern/IDs")
-----------------------------------
function onInitialize(zone)
end
function onInstanceZoneIn(player, instance)
local cs = -1
local pos = player:getPos()
if (pos.x == 0 and pos.y == 0 and pos.z == 0) then
local entrypos = instance:getEntryPos()
player:setPos(entrypos.x, entrypos.y, entrypos.z, entrypos.rot)
end
player:addTempItem(5345)
return cs
end
function onRegionEnter(player, region)
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if (csid == 102) then
player:setPos(0, 0, 0, 0, 61)
end
end
function onInstanceLoadFailed()
return 61
end
|
script.Parent.MouseButton1Click:Connect(function()
if script.Parent.Text == "X" then
script.Parent.Text = ""
else
script.Parent.Text = "X"
end
end) |
local scriptedailOldInit = init
function init()
scriptedailOldInit()
message.setHandler("returnCompanions", function() return playerCompanions.getCompanions("crew") end)
message.setHandler("dismissCompanion", function(_, _, podUuid) recruitSpawner:dismiss(podUuid) end)
end |
GUINotifications.kScoreDisplayFontName = Fonts.kMicrogrammaDMedExt_Small
GUINotifications.kScoreDisplayTextColor = Color(1, 1, 1, 1)
GUINotifications.kScoreDisplayYOffset = 128
GUINotifications.kScoreDisplayExtraText = " XP"
local oldInitialize = GUINotifications.Initialize
function GUINotifications:Initialize()
oldInitialize(self)
--self.oldScore = 0
end
local function UpdateScoreDisplay(self, deltaTime)
PROFILE("GUINotifications:UpdateScoreDisplay")
self.updateInterval = kUpdateIntervalFull
if self.scoreDisplayFadeoutTime > 0 then
self.scoreDisplayFadeoutTime = math.max(0, self.scoreDisplayFadeoutTime - deltaTime)
local fadeRate = 1 - (self.scoreDisplayFadeoutTime / GUINotifications.kScoreDisplayFadeoutTimer)
local fadeColor = self.scoreDisplay:GetColor()
fadeColor.a = 1
fadeColor.a = fadeColor.a - (fadeColor.a * fadeRate)
self.scoreDisplay:SetColor(fadeColor)
if self.scoreDisplayFadeoutTime == 0 then
self.scoreDisplay:SetIsVisible(false)
end
end
if self.scoreDisplayPopdownTime > 0 then
self.scoreDisplayPopdownTime = math.max(0, self.scoreDisplayPopdownTime - deltaTime)
local popRate = self.scoreDisplayPopdownTime / GUINotifications.kScoreDisplayPopTimer
local fontSize = GUINotifications.kScoreDisplayMinFontHeight + ((GUINotifications.kScoreDisplayFontHeight - GUINotifications.kScoreDisplayMinFontHeight) * popRate)
local scale = GUIScale(fontSize / GUINotifications.kScoreDisplayFontHeight)
self.scoreDisplay:SetScale(Vector(scale, scale, scale))
if self.scoreDisplayPopdownTime == 0 then
self.scoreDisplayFadeoutTime = GUINotifications.kScoreDisplayFadeoutTimer
end
end
if self.scoreDisplayPopupTime > 0 then
self.scoreDisplayPopupTime = math.max(0, self.scoreDisplayPopupTime - deltaTime)
local popRate = 1 - (self.scoreDisplayPopupTime / GUINotifications.kScoreDisplayPopTimer)
local fontSize = GUINotifications.kScoreDisplayMinFontHeight + ((GUINotifications.kScoreDisplayFontHeight - GUINotifications.kScoreDisplayMinFontHeight) * popRate)
local scale = GUIScale(fontSize / GUINotifications.kScoreDisplayFontHeight)
self.scoreDisplay:SetScale(Vector(scale, scale, scale))
if self.scoreDisplayPopupTime == 0 then
self.scoreDisplayPopdownTime = GUINotifications.kScoreDisplayPopTimer
end
end
local newScore, resAwarded, wasKill = ScoreDisplayUI_GetNewScore()
if newScore > 0 then
--[[
if self.scoreDisplay:GetIsVisible() then
self.oldScore = self.oldScore + newScore
else
self.oldScore = newScore
end
]]--
-- Restart the animation sequence.
self.scoreDisplayPopupTime = GUINotifications.kScoreDisplayPopTimer
self.scoreDisplayPopdownTime = 0
self.scoreDisplayFadeoutTime = 0
local strform = "+%.0f%s"
if newScore < 10 then
strform = "+%.1f%s"
end
self.scoreDisplay:SetText(string.format(strform, newScore, GUINotifications.kScoreDisplayExtraText))
self.scoreDisplay:SetScale(GUIScale(Vector(0.5, 0.5, 0.5)))
self.scoreDisplay:SetColor(wasKill and GUINotifications.kScoreDisplayKillTextColor or GUINotifications.kScoreDisplayTextColor)
self.scoreDisplay:SetIsVisible(self.visible)
end
end
function GUINotifications:Update(deltaTime)
PROFILE("GUINotifications:Update")
GUIAnimatedScript.Update(self, deltaTime)
-- The commander has their own location text.
if PlayerUI_IsACommander() or PlayerUI_IsOnMarineTeam() then
self.locationText:SetIsVisible(false)
else
self.locationText:SetIsVisible(self.visible)
self.locationText:SetText(PlayerUI_GetLocationName())
end
UpdateScoreDisplay(self, deltaTime)
end |
local tiny = require('lib.tiny')
local class = require('lib.middleclass')
local System = tiny.processingSystem(class('system.player.shoot'))
function System:initialize()
self.filter = tiny.requireAll(
'isPlayer',
'timeout',
'cooldown',
'shoot',
'space'
)
end
function System:process(e, dt)
if e.timeout <= 0 and e.space then
e.shoot = true
e.timeout = e.cooldown
elseif e.timeout > 0 then
e.timeout = e.timeout - dt
end
end
return System
|
local privateRoomInputLayout = require(ViewPath .. "hall/privateRoom/privateRoomInputLayout");
local privateRoom_pin_map = require("qnFiles/qnPlist/hall/privateRoom_pin")
-- 私人房输入层
local PrivateRoomInputLayer = class(CommonGameLayer, false);
local h_index = 0;
local getIndex = function(self)
h_index = h_index + 1;
return h_index;
end
PrivateRoomInputLayer.s_numberLength = 4;
PrivateRoomInputLayer.Delegate = {
onInputNumberCallback = "onInputNumberCallback"; -- 输入结束回调
}
PrivateRoomInputLayer.s_controls =
{
topView = getIndex(),
contentView = getIndex(),
inputView = getIndex(),
numberView = getIndex(),
tips = getIndex(),
};
PrivateRoomInputLayer.s_cmds =
{
};
PrivateRoomInputLayer.ctor = function(self)
super(self, privateRoomInputLayout);
self:setFillParent(true, true);
self:_initView();
end
PrivateRoomInputLayer.dtor = function(self)
end
PrivateRoomInputLayer.showEmptyView = function(self)
self:_showTips(kTextPrivateRoomDataEmpty);
end
PrivateRoomInputLayer.resetInput = function(self)
self:_clearNumber();
end
--------------------------------输入框逻辑--------------------------------------------
-- input item callback
PrivateRoomInputLayer.onItemClickCallback = function(self, data)
local func = data.func;
if func then
func(self, data);
end
end
-- 输入数字
PrivateRoomInputLayer.onInputNumber = function(self, data)
self:_addNumber(data);
end
-- 重置输入
PrivateRoomInputLayer.onInputReset = function(self, data)
self:_clearNumber();
self:_hideTips();
end
-- 删除输入
PrivateRoomInputLayer.onInputDelete = function(self, data)
self:_removeNumber();
self:_hideTips();
end
PrivateRoomInputLayer._initInputView = function(self)
local inputView = self:findViewById(self.s_controls.inputView);
local inputItem = require("hall/privateRoom/widget/privateRoomInputItem");
local w, h = inputView:getSize();
local itemW = w / 3;
local itemH = h / 4;
for k, v in ipairs(PrivateRoomInputLayer.s_inputConfig) do
local i, _ = math.floor((k - 1) / 3);
local j = (k - 1) % 3
local item = new(inputItem, v);
item:setSize(itemW, itemH);
item:setPos(itemW*j, itemH*i);
item:setDelegate(self);
inputView:addChild(item);
end
end
------------------------------输入显示逻辑-----------------------------------------
PrivateRoomInputLayer._initNumberView = function(self)
local numberView = self:findViewById(self.s_controls.numberView);
self.m_numberImgMap = {};
self.m_numberDataList = {};
for i = 1, PrivateRoomInputLayer.s_numberLength do
local item = numberView:getChildByName(string.format("numberView_%s", i));
local img = item:getChildByName("img");
img:setVisible(false);
self.m_numberImgMap[i] = img;
end
end
PrivateRoomInputLayer._addNumber = function(self, data)
local size = #self.m_numberDataList;
if size >= PrivateRoomInputLayer.s_numberLength then
return;
end
table.insert(self.m_numberDataList, data);
local img = self.m_numberImgMap[#self.m_numberDataList];
if img and data.file then
img:setFile(privateRoom_pin_map[data.file] or "");
self:_resetImageSize(img);
img:setVisible(true);
end
-- 满足长度要求自动输出
if #self.m_numberDataList >= PrivateRoomInputLayer.s_numberLength then
self:_outputNumber();
end
end
PrivateRoomInputLayer._removeNumber = function(self, data)
local size = #self.m_numberDataList;
if size < 1 then
return;
end
local img = self.m_numberImgMap[size];
if img then
img:setVisible(false);
end
table.remove(self.m_numberDataList)
end
PrivateRoomInputLayer._outputNumber = function(self)
local number = 0;
for k, v in ipairs(self.m_numberDataList) do
number = number * 10 + v.index % 11;
end
self:execDelegate(PrivateRoomInputLayer.Delegate.onInputNumberCallback, number);
end
PrivateRoomInputLayer._clearNumber = function(self)
self.m_numberDataList = {};
for i = 1, PrivateRoomInputLayer.s_numberLength do
local img = self.m_numberImgMap[i];
if img then
img:setVisible(false);
end
end
end
--------------------------------------输入提示-------------------------------------------
PrivateRoomInputLayer._showTips = function(self, msg)
local tips = self:findViewById(self.s_controls.tips);
tips:setText(msg or "");
tips:setVisible(true);
end
PrivateRoomInputLayer._hideTips = function(self)
local tips = self:findViewById(self.s_controls.tips);
tips:setVisible(false);
end
------------------------------------------------------------------------------------
PrivateRoomInputLayer._initView = function(self)
self:_initInputView();
self:_initNumberView();
end
PrivateRoomInputLayer._resetImageSize = function(self, image)
if image and image.m_res then
local width = image.m_res:getWidth();
local height = image.m_res:getHeight();
image:setSize(width, height);
end
end
---------------------------------------------------------------------------------------
PrivateRoomInputLayer.s_controlConfig =
{
[PrivateRoomInputLayer.s_controls.contentView] = {"contentView"};
[PrivateRoomInputLayer.s_controls.inputView] = {"contentView", "inputBg", "inputView"};
[PrivateRoomInputLayer.s_controls.topView] = {"contentView", "inputBg","topView"};
[PrivateRoomInputLayer.s_controls.numberView] = {"contentView", "inputBg","topView", "infoView", "numberView"};
[PrivateRoomInputLayer.s_controls.tips] = {"contentView", "inputBg", "topView", "infoView", "tips"};
};
PrivateRoomInputLayer.s_controlFuncMap =
{
};
PrivateRoomInputLayer.s_cmdConfig =
{
};
-- 输入框配置
PrivateRoomInputLayer.s_inputConfig = {
[1] = {file = "input_1.png", index = 1, func = PrivateRoomInputLayer.onInputNumber},
[2] = {file = "input_2.png", index = 2, func = PrivateRoomInputLayer.onInputNumber},
[3] = {file = "input_3.png", index = 3, func = PrivateRoomInputLayer.onInputNumber},
[4] = {file = "input_4.png", index = 4, func = PrivateRoomInputLayer.onInputNumber},
[5] = {file = "input_5.png", index = 5, func = PrivateRoomInputLayer.onInputNumber},
[6] = {file = "input_6.png", index = 6, func = PrivateRoomInputLayer.onInputNumber},
[7] = {file = "input_7.png", index = 7, func = PrivateRoomInputLayer.onInputNumber},
[8] = {file = "input_8.png", index = 8, func = PrivateRoomInputLayer.onInputNumber},
[9] = {file = "input_9.png", index = 9, func = PrivateRoomInputLayer.onInputNumber},
[10] = {file = "input_reset.png", index = 10, func = PrivateRoomInputLayer.onInputReset},
[11] = {file = "input_0.png", index = 11, func = PrivateRoomInputLayer.onInputNumber},
[12] = {file = "input_delete.png", index = 12, func = PrivateRoomInputLayer.onInputDelete},
}
return PrivateRoomInputLayer; |
---@class SafeHouse : zombie.iso.areas.SafeHouse
---@field private x int
---@field private y int
---@field private w int
---@field private h int
---@field private diffError int
---@field private owner String
---@field private players ArrayList|Unknown
---@field private lastVisited long
---@field private title String
---@field private playerConnected int
---@field private openTimer int
---@field private id String
---@field public playersRespawn ArrayList|Unknown
---@field private safehouseList ArrayList|Unknown
SafeHouse = {}
---@public
---@return long
function SafeHouse:getLastVisited() end
---@public
---@param arg0 boolean
---@param arg1 String
---@return void
function SafeHouse:setRespawnInSafehouse(arg0, arg1) end
---@public
---@param owner String
---@return void
function SafeHouse:setOwner(owner) end
---@public
---@param arg0 int
---@return void
function SafeHouse:setOpenTimer(arg0) end
---@public
---@return int
function SafeHouse:getOpenTimer() end
---@public
---@return int
function SafeHouse:getH() end
---@public
---@param player IsoPlayer
---@return void
---@overload fun(player:IsoPlayer, force:boolean)
function SafeHouse:removeSafeHouse(player) end
---@public
---@param player IsoPlayer
---@param force boolean
---@return void
function SafeHouse:removeSafeHouse(player, force) end
---@public
---@param lastVisited long
---@return void
function SafeHouse:setLastVisited(lastVisited) end
---@public
---@param square IsoGridSquare
---@param player IsoPlayer
---@return SafeHouse
---@overload fun(x:int, y:int, w:int, h:int, player:String, remote:boolean)
function SafeHouse:addSafeHouse(square, player) end
---@public
---@param x int
---@param y int
---@param w int
---@param h int
---@param player String
---@param remote boolean
---@return SafeHouse
function SafeHouse:addSafeHouse(x, y, w, h, player, remote) end
---@public
---@param player String
---@return void
function SafeHouse:addPlayer(player) end
---@public
---@param player IsoPlayer
---@return boolean
function SafeHouse:allowSafeHouse(player) end
---@public
---@param players ArrayList|String
---@return void
function SafeHouse:setPlayers(players) end
---@public
---@param player IsoPlayer
---@return boolean
function SafeHouse:isOwner(player) end
---@public
---@param y int
---@return void
function SafeHouse:setY(y) end
---@public
---@return int
function SafeHouse:getY2() end
---@public
---@param square IsoGridSquare
---@return SafeHouse
---@overload fun(x:int, y:int, w:int, h:int)
function SafeHouse:getSafeHouse(square) end
---@public
---@param x int
---@param y int
---@param w int
---@param h int
---@return SafeHouse
function SafeHouse:getSafeHouse(x, y, w, h) end
---@public
---@param arg0 IsoGridSquare
---@param arg1 IsoPlayer
---@return String
function SafeHouse:canBeSafehouse(arg0, arg1) end
---@public
---@param player String
---@return void
function SafeHouse:removePlayer(player) end
---@public
---@return ArrayList|SafeHouse
function SafeHouse:getSafehouseList() end
---Update the last visited value everytime someone is in this safehouse
---
---If it's not visited for some time (SafehouseRemoval serveroption) it's automatically removed.
---@public
---@param player IsoPlayer
---@return void
function SafeHouse:updateSafehouse(player) end
---@public
---@return ArrayList|String
function SafeHouse:getPlayers() end
---@public
---@param arg0 String
---@return void
function SafeHouse:setTitle(arg0) end
---@public
---@return int
function SafeHouse:getX() end
---@public
---@return String
function SafeHouse:getOwner() end
---@public
---@return void
function SafeHouse:syncSafehouse() end
---@public
---@param arg0 IsoPlayer
---@return SafeHouse
---@overload fun(arg0:String)
function SafeHouse:hasSafehouse(arg0) end
---@public
---@param arg0 String
---@return SafeHouse
function SafeHouse:hasSafehouse(arg0) end
---@public
---@param output ByteBuffer
---@return void
function SafeHouse:save(output) end
---@public
---@param arg0 String
---@return boolean
---@overload fun(player:IsoPlayer)
function SafeHouse:playerAllowed(arg0) end
---@public
---@param player IsoPlayer
---@return boolean
function SafeHouse:playerAllowed(player) end
---@public
---@return int
function SafeHouse:getW() end
---@public
---@param arg0 IsoPlayer
---@return SafeHouse
---@overload fun(arg0:String)
function SafeHouse:alreadyHaveSafehouse(arg0) end
---@public
---@param arg0 String
---@return SafeHouse
function SafeHouse:alreadyHaveSafehouse(arg0) end
---@public
---@return int
function SafeHouse:getX2() end
---@public
---@return int
function SafeHouse:getY() end
---@public
---@return void
function SafeHouse:updateSafehousePlayersConnected() end
---@public
---@return void
function SafeHouse:clearSafehouseList() end
---@public
---@return void
function SafeHouse:init() end
---@public
---@param w int
---@return void
function SafeHouse:setW(w) end
---@public
---@return int
function SafeHouse:getPlayerConnected() end
---@public
---@return String
function SafeHouse:getTitle() end
---@public
---@param arg0 IsoGridSquare
---@param arg1 String
---@param arg2 boolean
---@return SafeHouse
function SafeHouse:isSafeHouse(arg0, arg1, arg2) end
---@public
---@param arg0 IsoPlayer
---@return void
function SafeHouse:kickOutOfSafehouse(arg0) end
---@public
---@return String
function SafeHouse:getId() end
---@public
---@param h int
---@return void
function SafeHouse:setH(h) end
---@public
---@param x int
---@return void
function SafeHouse:setX(x) end
---@public
---@param arg0 int
---@return void
function SafeHouse:setPlayerConnected(arg0) end
---@public
---@param arg0 ByteBuffer
---@param arg1 int
---@return SafeHouse
function SafeHouse:load(arg0, arg1) end
---@public
---@param arg0 String
---@return boolean
function SafeHouse:isRespawnInSafehouse(arg0) end
|
--
-- Created by IntelliJ IDEA.
-- User: chen0
-- Date: 29/6/2017
-- Time: 4:20 AM
-- To change this template use File | Settings | File Templates.
--
local mergesort = {}
mergesort.__index = mergesort
function mergesort.sort(a, comparator)
local aux = require('lualgorithms.data.list').create()
for i=0,(a:size()-1) do
aux:add(0)
end
mergesort._sort(a, aux, 0, a:size()-1, comparator)
end
function mergesort._sort(a, aux, lo, hi, comparator)
if lo >= hi then
return
end
local mid = lo + math.floor((hi - lo) / 2)
mergesort._sort(a, aux, lo, mid, comparator)
mergesort._sort(a, aux, mid+1, hi, comparator)
mergesort._merge(a, aux, lo, mid, hi, comparator)
end
function mergesort._merge(a, aux, lo, mid, hi, comparator)
local i = lo
local j = mid+1
for k=lo,hi do
aux:set(k, a:get(k))
end
for k=lo,hi do
if i > mid then
a:set(k, aux:get(j))
j = j+1
elseif j > hi then
a:set(k, aux:get(i))
i = i + 1
else
local cmp = comparator(aux:get(i), aux:get(j))
if cmp <= 0 then
a:set(k, aux:get(i))
i = i + 1
else
a:set(k, aux:get(j))
j = j + 1
end
end
end
end
return mergesort
|
-- https://github.com/terrortylor/nvim-comment
require("nvim_comment").setup {
marker_padding = true, -- Linters prefer comment and line to have a space in between markers
comment_empty = true, -- should comment out empty or whitespace only lines
create_mappings = true, -- Should key mappings be created
line_mapping = "gcc", -- Normal mode mapping left hand side
operator_mapping = "gc", -- Visual/Operator mapping left hand side
}
|
if mods["angelsbioprocessing"] then
data:extend(
{
-----------
-- Algae --
-----------
--Orange
{
type = "recipe",
name = "algae-orange",
category = "bio-processing",
subgroup = "bio-processing-green",
enabled = false,
energy_required = 20,
ingredients =
{
{type="fluid", name="water-mineralized", amount=100},
{type="fluid", name="gas-carbon-dioxide", amount=100}
},
results=
{
{type="item", name="algae-orange", amount=40},
},
icon = "__angelsbioprocessing__/graphics/icons/algae-green.png",
icon_size = 32,
order = "a",
},
--Violet
{
type = "recipe",
name = "algae-violet",
category = "bio-processing",
subgroup = "bio-processing-green",
enabled = false,
energy_required = 20,
ingredients =
{
{type="fluid", name="water-mineralized", amount=100},
{type="fluid", name="gas-carbon-dioxide", amount=100}
},
results=
{
{type="item", name="algae-violet", amount=40},
},
icon = "__angelsbioprocessing__/graphics/icons/algae-green.png",
icon_size = 32,
order = "a",
},
--Mercury from Violet
{
type = "recipe",
name = "methylmercury-algae",
category = "liquifying",
subgroup = "bio-processing-green",
enabled = false,
energy_required = 3,
ingredients ={
{type="item", name="algae-violet", amount=10},
},
results=
{
{type="fluid", name="liquid-dimethylmercury", amount=2},
},
icon = "__angelsbioprocessing__/graphics/icons/cellulose-fiber-algae.png",
icon_size = 32,
order = "b [cellulose-fiber-algae]",
},
-------------
-- Gardens --
-------------
--swamp from soil
{
type = "recipe",
name = "swamp-garden-generation",
icon = "__angelsbioprocessing__/graphics/icons/swamp-garden.png",
icon_size = 32,
category = "swamp-farming",
subgroup = "farming-swamp-seed",
order = "g[temperate-garden-generation]-c",
energy_required = 600,
enabled = false,
ingredients =
{
{type = "item", name = "solid-soil", amount = 1000},
{type = "fluid", name = "water-viscous-mud", amount = 1000},
{type = "item", name = "solid-fertilizer", amount = 200}
},
results =
{
{type = "item", name = "swamp-garden", amount = 1}
},
},
--temperate from soil
{
type = "recipe",
name = "temperate-garden-generation",
category = "temperate-farming",
subgroup = "farming-temperate-seed",
enabled = false,
energy_required = 1000,
ingredients =
{
{type = "item", name = "solid-compost", amount = 500},
{type = "fluid", name = "water", amount = 1000},
{type = "item", name = "solid-fertilizer", amount = 500}
},
results=
{
{type = "item", name = "temperate-garden", amount = 1}
},
icon = "__angelsbioprocessing__/graphics/icons/temperate-garden.png",
icon_size = 32,
order = "g[temperate-garden-generation]-c",
},
--desert from soil
{
type = "recipe",
name = "desert-garden-generation",
category = "desert-farming",
subgroup = "farming-desert-seed",
enabled = false,
energy_required = 1000,
ingredients =
{
{type = "item", name = "solid-sand", amount = 500},
{type = "fluid", name = "water-saline", amount = 1000},
{type = "item", name = "solid-fertilizer", amount = 500}
},
results=
{
{type = "item", name = "desert-garden", amount = 1}
},
icon = "__angelsbioprocessing__/graphics/icons/desert-garden.png",
icon_size = 32,
order = "g[temperate-garden-generation]-c",
},
--temperate mutation
{
type = "recipe",
name = "temperate-garden-mutation",
category = "seed-extractor",
subgroup = "farming-temperate-seed",
enabled = false,
energy_required = 600,
ingredients =
{
{type = "item", name = "desert-garden", amount = 1},
{type = "item", name = "swamp-garden", amount = 1},
{type = "item", name = "uranium-235", amount = 1},
},
results=
{
{type = "item", name = "temperate-garden", amount = 1}
},
icon = "__angelsbioprocessing__/graphics/icons/temperate-garden.png",
icon_size = 32,
order = "mc",
},
--desert mutation
{
type = "recipe",
name = "desert-garden-mutation",
category = "seed-extractor",
subgroup = "farming-desert-seed",
enabled = false,
energy_required = 600,
ingredients =
{
{type = "item", name = "temperate-garden", amount = 1},
{type = "item", name = "swamp-garden", amount = 1},
{type = "item", name = "uranium-235", amount = 1},
},
results=
{
{type = "item", name = "desert-garden", amount = 1}
},
icon = "__angelsbioprocessing__/graphics/icons/desert-garden.png",
icon_size = 32,
order = "mc",
},
--swamp mutation
{
type = "recipe",
name = "swamp-garden-mutation",
category = "seed-extractor",
subgroup = "farming-swamp-seed",
enabled = false,
energy_required = 600,
ingredients =
{
{type = "item", name = "desert-garden", amount = 1},
{type = "item", name = "temperate-garden", amount = 1},
{type = "item", name = "uranium-235", amount = 1},
},
results=
{
{type = "item", name = "swamp-garden", amount = 1}
},
icon = "__angelsbioprocessing__/graphics/icons/swamp-garden.png",
icon_size = 32,
order = "mc",
},
--alternative fertilizer
{
type = "recipe",
name = "diammonium-phosphate-fertilizer",
icons = {
{
icon = "__angelsbioprocessing__/graphics/icons/solid-fertilizer.png",
icon_size = 32, icon_mipmaps = 1
},
{
icon = "__Clowns-Processing__/graphics/icons/advsorting-overlay.png",
icon_size = 32, icon_mipmaps = 1
},
},
category = "chemistry",
subgroup = "clowns-phosphorus",
order = "c",
energy_required = 10,
enabled = false,
allow_decomposition = false,
ingredients =
{
{type="fluid", name="liquid-phosphoric-acid", amount=10},
{type="fluid", name="gas-ammonia", amount=10},
},
results =
{
{type="item", name="solid-fertilizer", amount=1}
},
},
})
end
|
local _, ns = ...
local B, C, L, DB, P = unpack(ns)
local S = P:GetModule("Skins")
local _G = getfenv(0)
local select = select
local function loadFunc()
P:Delay(.5, function()
local bu = _G.PlayerTalentFrame.__TalentEmuCall
if bu then
B.Reskin(bu)
bu:SetPoint("RIGHT", PlayerTalentFrameCloseButton, "LEFT", -22, 0)
end
end)
end
P:AddCallbackForAddon("Blizzard_TalentUI", loadFunc)
function S:alaTalentEmu()
local alaPopup = _G.alaPopup
if not alaPopup then return end -- version check
local menu = alaPopup.menu
P.ReskinTooltip(menu)
hooksecurefunc("ToggleDropDownMenu", function(level, ...)
level = level or 1
if menu:IsShown() then
for i = 1, menu:GetNumChildren() do
local bu = select(i, menu:GetChildren())
if bu:GetObjectType() == "Button" and bu:IsShown() and not bu.styled then
bu:SetHighlightTexture(DB.bdTex)
local hl = bu:GetHighlightTexture()
hl:SetVertexColor(DB.r, DB.g, DB.b, .25)
hl:SetPoint("TOPLEFT", - (menu:GetWidth() - bu:GetWidth()) / 2 + 2, 0)
hl:SetPoint("BOTTOMRIGHT", (menu:GetWidth() - bu:GetWidth()) / 2 - 2, 0)
bu.styled = true
end
end
end
end)
end
S:RegisterSkin("TalentEmu", S.alaTalentEmu) |
addEvent("onDiscordPacket")
local sockets = {};
local channels = {};
function createSocketFromConfig()
local _channels = getSystemEnvVariable("DISCORD_CHANNELS");
local passphrase = getSystemEnvVariable("DISCORD_PASSPHRASE");
local hostname = "mta-tr-discord-bot";
local port = getSystemEnvVariable("DISCORD_PORT");
if (_channels) then
channels = split(_channels, ',');
for _, channel in ipairs (channels) do
createDiscordPipe(hostname, tonumber(port), passphrase, channel)
end
end
end
function send(packet, payload, channel)
local channel = channel or channels[1]
local socket = sockets[channel]
assert(type(packet) == "string")
assert(type(payload) == "table")
socket:write(table.json {
type = packet,
payload = payload
})
end
function createDiscordPipe(hostname, port, passphrase, channel)
local socket = false
if (not sockets[channel]) then
socket = Socket:create(hostname, port, { autoReconnect = true })
sockets[channel] = socket
else
socket = sockets[channel]
end
socket.channel = channel
socket.passphrase = passphrase
socket.bindmessage = false
socket:on("ready",
function (socket)
outputDebugString("[Discord] Connected to ".. hostname .." on port ".. port)
sendAuthPacket(socket)
end
)
socket:on("data", handleDiscordPacket)
socket:on("close",
function (socket)
outputDebugString("[Discord] Disconnected from ".. hostname)
setTimer(
function ()
outputDebugString("[Discord] Reconnecting now..")
socket:connect()
end,
15000, 1)
end
)
end
function sendAuthPacket(socket)
local salt = md5(getTickCount() + getRealTime().timestamp)
socket:write(table.json {
type = "auth",
payload = {
salt = salt,
passphrase = hash("sha256", salt .. hash("sha512", socket.passphrase))
}
})
end
function handlePingPacket(socket)
return socket:write(table.json { type = "pong" })
end
function handleAuthPacket(socket, payload)
if payload.authenticated then
outputDebugString("[Discord] Authentication successful")
socket:write(table.json {
type = "select-channel",
payload = {
channel = socket.channel
}
})
else
local error = tostring(payload.error) or "unknown error"
outputDebugString("[Discord] Failed to authenticate: ".. error)
socket:disconnect()
end
end
function handleSelectChannelPacket(socket, payload)
if payload.success then
if payload.wait then
outputDebugString("[Discord] Bot isn't ready")
else
outputDebugString("[Discord] Channel "..socket.channel.." has been bound")
triggerEvent("onDiscordChannelConnected", root, socket.channel);
if not socket.bindmessage then
-- socket:write(table.json {
-- type = "chat.message.text",
-- payload = {
-- author = "Server",
-- text = "Hello :wave:"
-- }
-- })
socket.bindmessage = true
end
end
else
local error = tostring(payload.error) or "unknown error"
outputDebugString("[Discord] Failed to bind channel: ".. error)
socket:disconnect()
end
end
function handleDisconnectPacket(socket)
outputDebugString("[Discord] Server has closed the connection")
socket:disconnect()
socket.bindmessage = false
end
function handleDiscordPacket(socket, packet, payload)
if packet == "ping" then
return handlePingPacket(socket)
elseif packet == "auth" then
return handleAuthPacket(socket, payload)
elseif packet == "select-channel" then
return handleSelectChannelPacket(socket, payload)
elseif packet == "disconnect" then
return handleDisconnectPacket(socket)
else
triggerEvent("onDiscordPacket", resourceRoot, packet, payload)
end
end
|
local popup = {array = {}}
function popup:new(atlas, quad, x, y, size)
size = size or drawSize
self.array[#self.array + 1] = {
atlas = atlas,
quad = quad,
x = x,
y = y,
size = size,
scale = 0,
scaleSpeed = config.display.height * 0.05,
alpha = 255,
alphaSpeed = 255
}
end
function popup:update(dt)
for i,v in ipairs(self.array) do
--v.scale = v.scale + v.scaleSpeed * dt
v.alpha = v.alpha - v.alphaSpeed * dt
v.y = v.y - v.scaleSpeed * dt
if v.alpha < 0 then
v.alpha = 0
table.remove(self.array, i)
end
end
end
function popup:draw()
--love.graphics.setBlendMode("add")
for i,v in ipairs(self.array) do
setColor(255, 255, 255, v.alpha)
love.graphics.draw(v.atlas, v.quad, v.x , v.y, 0, v.size / assetSize + v.scale, v.size / assetSize + v.scale, assetSize / 2, assetSize / 2)
--love.graphics.circle("line", v.x, v.y, assetSize * v.scale)
end
--love.graphics.setBlendMode("alpha")
end
return popup |
--------------------------------
-- Makefile specific settings --
--------------------------------
vim.wo.foldmethod = "marker"
|
factory.electronics = {}
dofile(factory.modpath.."/electronics/device.lua")
dofile(factory.modpath.."/electronics/cable.lua")
dofile(factory.modpath.."/electronics/combustion_generator.lua")
dofile(factory.modpath.."/electronics/electronic_furnace.lua")
dofile(factory.modpath.."/electronics/battery.lua") |
include("shared.lua")
function ENT:GetDisplayPosition()
local obbcenter = self:OBBCenter()
local obbmax = self:OBBMaxs()
return Vector(obbcenter.x, obbmax.y - 19.5, obbcenter.z + 41), Angle(0, LocalPlayer():EyeAngles().y - 90, 90), 0.2
end
function ENT:Draw()
self:DrawModel()
self:FWDrawInfo()
end
function ENT:CustomUI(panel)
local owner = self:FWGetOwner()
local header = vgui.Create("FWUITextBox", panel)
header:SetText("OWNER: " .. (IsValid(owner) and owner:Nick() or "unknown"))
header:SetTall(fw.resource.INFO_ROW_HEIGHT)
header:SetInset(1)
header:SetAlign("left")
header.Paint = function(self, w, h)
surface.SetDrawColor(0, 0, 0, 220)
surface.DrawRect(0, 0, w, h)
end
end
|
-- This script used to rearrange disk images for use by Dirac's CP/M,
-- but the sectors are now arranged contiguously. The main point of
-- this tool is now to add in the boot sector and bootable CP/M image.
--
-- Command line arguments are:
-- -o file_name Output filename
-- file_name Input filename
-- -b dest (Optional) boot sector file
-- -c dest (Optional) CP/M image
------------------------------------------------------------------------
-- Config
--
local in_image = nil
local out_image = nil
local boot_sector = nil
local cpm = nil
do
local i = 1
while i <= #arg do
if arg[i] == "-o" then
i = i + 1
out_image = arg[i]
elseif arg[i] == "-b" then
i = i + 1
boot_sector = arg[i]
elseif arg[i] == "-c" then
i = i + 1
cpm = arg[i]
else
in_image = arg[i]
end
i = i + 1
end
end
if in_image == nil then
print(arg[0] .. ": Input filename required")
os.exit(1)
end
if out_image == nil then
print(arg[0] .. ": Output filename required")
os.exit(1)
end
------------------------------------------------------------------------
-- Do the work
--
local fin = assert(io.open(in_image, "rb"))
local fout = assert(io.open(out_image, "wb"))
local disk_len = 32 * 128 * 35
fout:write(fin:read(disk_len))
if boot_sector ~= nil then
local fboot = assert(io.open(boot_sector))
fout:seek("set", 0)
fout:write(fboot:read("*all"))
end
if cpm ~= nil then
local fcpm = assert(io.open(cpm))
fout:seek("set", 512)
fout:write(fcpm:read("*all"))
end
|
local PlayerAdded = false
local UIS = game:GetService("UserInputService")
while wait() do
for i,v in pairs(script.Parent.Background.Players:GetChildren()) do
if v.Name ~= "PlayerName" then
v:Destroy()
end
end
for i,v in pairs(game.Players:GetChildren()) do
if script.Parent.Background.Players:FindFirstChild(v.Name) == false then return end
local thing = script.Parent.Background.Players:FindFirstChild(v.Name)
local name = script.Parent.Background.Players.PlayerName:Clone()
name.Text = v.Name
name.Parent = script.Parent.Background.Players
name.Name = v.Name
local Debris = v.leaderstats.Debris
local DebrisTXT = name.Wipeouts
if v.leaderstats.Debris.Value >= 1000 and v.leaderstats.Debris.Value < 1000000 then
local number = math.floor(Debris.Value/100)
DebrisTXT.Text = number/10 .."K"
elseif v.leaderstats.Debris.Value >= 1000000 and v.leaderstats.Debris.Value < 1000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000)
DebrisTXT.Text = number/10 .."M"
elseif v.leaderstats.Debris.Value >= 1000000000 and v.leaderstats.Debris.Value < 1000000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000000)
DebrisTXT.Text = number/10 .."B"
elseif v.leaderstats.Debris.Value >= 1000000000000 and v.leaderstats.Debris.Value < 1000000000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000000000)
DebrisTXT.Text = number/10 .."T"
elseif v.leaderstats.Debris.Value >= 1000000000000000 and v.leaderstats.Debris.Value < 1000000000000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000000000000)
DebrisTXT.Text = number/10 .."P"
elseif v.leaderstats.Debris.Value >= 1000000000000000000 and v.leaderstats.Debris.Value < 1000000000000000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000000000000000)
DebrisTXT.Text = number/10 .."E"
elseif v.leaderstats.Debris.Value >= 1000000000000000000000 and v.leaderstats.Debris.Value < 1000000000000000000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000000000000000000)
DebrisTXT.Text = number/10 .."Z"
elseif v.leaderstats.Debris.Value >= 1000000000000000000000 and v.leaderstats.Debris.Value < 1000000000000000000000000 then
local number = math.floor(v.leaderstats.Debris.Value/100000000000000000000)
DebrisTXT.Text = number/10 .."Y"
else
DebrisTXT.Text = math.floor(v.leaderstats.Debris.Value)
end
if v.leaderstats.Coins.Value >= 1000 and v.leaderstats.Coins.Value < 1000000 then
local number = math.floor(v.leaderstats.Coins.Value/100)
name.Level.Text = number/10 .."K"
elseif v.leaderstats.Coins.Value >= 1000000 and v.leaderstats.Coins.Value < 1000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000)
name.Level.Text = number/10 .."M"
elseif v.leaderstats.Coins.Value >= 1000000000 and v.leaderstats.Coins.Value < 1000000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000000)
name.Level.Text = number/10 .."B"
elseif v.leaderstats.Coins.Value >= 1000000000000 and v.leaderstats.Coins.Value < 1000000000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000000000)
name.Level.Text = number/10 .."T"
elseif v.leaderstats.Coins.Value >= 1000000000000000 and v.leaderstats.Coins.Value < 1000000000000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000000000000)
name.Level.Text = number/10 .."P"
elseif v.leaderstats.Coins.Value >= 1000000000000000000 and v.leaderstats.Coins.Value < 1000000000000000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000000000000000)
name.Level.Text = number/10 .."E"
elseif v.leaderstats.Coins.Value >= 1000000000000000000000 and v.leaderstats.Debris.Value < 1000000000000000000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000000000000000000)
name.Level.Text = number/10 .."Z"
elseif v.leaderstats.Coins.Value >= 1000000000000000000000 and v.leaderstats.Coins.Value < 1000000000000000000000000 then
local number = math.floor(v.leaderstats.Coins.Value/100000000000000000000)
name.Level.Text = number/10 .."Y"
else
name.Level.Text = math.floor(v.leaderstats.Coins.Value)
end
name.Visible = true
name.Position = UDim2.new(0,5,0,10 + (i * 35-(35)))
name.Parent.CanvasSize = UDim2.new(0,5,0,(i * 35))
if thing then
thing:Destroy()
end
UIS.InputBegan:Connect(function(I)
if I.KeyCode == Enum.KeyCode.LeftBracket then
if script.Parent.Background.Visible == false then
script.Parent.Background.Visible = true
else
script.Parent.Background.Visible = false
end
end
end)
end
end
|
--
-- Created by IntelliJ IDEA.
-- User: petrus
-- Date: 2021/01/01
-- Time: 09:10
-- To change this template use File | Settings | File Templates.
--
local m = require("services")
mysql = require('mysql')
json = require('json')
function get()
if POST_DATA ~= nil then
for key, value in pairs(POST_DATA) do
print("Key: " .. key .. ",\tValue: " .. value)
end
c = mysql.new()
ok, err = c:connect({ host = '127.0.0.1', port = 3306, database = 'test', user = 'lua', password = '@Test1234' })
if ok then
res, err = c:query('INSERT INTO user(name, last_name, email) VALUES("' ..
POST_DATA.name .. '", "' ..
POST_DATA.last_name .. '", "' ..
POST_DATA.email .. '")')
if err ~= nil then
print(err)
end
end
mysql.close()
print(json.endcode(POST_DATA))
if not ok then
dump(err)
end
end
local b = "<h1>Hello There</h1>" ..
"<p>here's a paragraph</p>" ..
"<form method='post' action='/user'>" ..
"<input type='text' name='name'>" ..
"<input type='text' name='last_name'>" ..
"<input type='text' name='email'>" ..
"<input type='submit'>" ..
"</form>" ..
"<button>Button</button><br>" ..
"<a href='/'>Some Link</a>"
return b
end
response.body = get() |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.