content
stringlengths 5
1.05M
|
|---|
-- Copyright (c) 2018. tangzx(love.tangzx@qq.com)
--
-- Licensed under the Apache License, Version 2.0 (the "License"); you may not
-- use this file except in compliance with the License. You may obtain a copy of
-- the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
-- WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
-- License for the specific language governing permissions and limitations under
-- the License.
table = {}
---
--- Given a list where all elements are strings or numbers, returns the string
--- `list[i]..sep..list[i+1] ... sep..list[j]`. The default value for
--- `sep` is the empty string, the default for `i` is 1, and the default for
--- `j` is #list. If `i` is greater than `j`, returns the empty string.
---@overload fun(list:table):string
---@overload fun(list:table, sep:string):string
---@overload fun(list:table, sep:string, i:number):string
---@param list table
---@param sep string
---@param i number
---@param j number
---@return string
function table.concat(list, sep, i, j) end
--- Executes the given f over all elements of `table`. For each element, `f` is
--- called with the index and respective value as arguments. If `f` returns a
--- non-nil value, then the loop is broken, and this value is returned as the
--- final value of `foreach`.
--- See the `next` function for extra information about table traversals.
---
---@param table table
---@param f fun(key:any, value:any):any
function table.foreach (table, f) end
--- Executes the given `f` over the numerical indices of `table`. For each index,
--- `f` is called with the index and respective value as arguments. Indices are
--- visited in sequential order, from 1 to `n`, where `n` is the size of the `table`
--- (see 5.4). If `f` returns a non-nil value, then the loop is broken and this
--- value is returned as the result of `foreachi`.
---
---@param table table
---@param f fun(index:number, value:any):any
function table.foreachi(table, f) end
--- Returns the size of a table, when seen as a list. If the table has an n field
--- with a numeric value, this value is the size of the table. Otherwise, if there
--- was a previous call to table.setn over this table, the respective value is
--- returned. Otherwise, the size is one less the first integer index with a nil value.
---@param table table
---@return number
function table.getn(table) end
---
--- Inserts element `value` at position `pos` in `list`, shifting up the
--- elements to `list[pos]`, `list[pos+1]`, `···`, `list[#list]`. The default
--- value for `pos` is ``#list+1`, so that a call `table.insert(t,x)`` inserts
--- `x` at the end of list `t`.
---@overload fun(list:table, value:any):number
---@param list table
---@param pos number
---@param value any
---@return number
function table.insert(list, pos, value) end
---
--- Removes from `list` the element at position `pos`, returning the value of
--- the removed element. When `pos` is an integer between 1 and `#list`, it
--- shifts down the elements `list[pos+1]`, `list[pos+2]`, `···`,
--- `list[#list]` and erases element `list[#list]`; The index pos can also be 0
--- when `#list` is 0, or `#list` + 1; in those cases, the function erases
--- the element `list[pos]`.
---
--- The default value for `pos` is `#list`, so that a call `table.remove(l)`
--- removes the last element of list `l`.
---@overload fun<V>(list:table<number, V> | V[]):V
---@generic V
---@param list table<number, V>
---@param pos number
---@return V
function table.remove(list, pos) end
---
--- Sorts list elements in a given order, *in-place*, from `list[1]` to
--- `list[#list]`. If `comp` is given, then it must be a function that receives
--- two list elements and returns true when the first element must come before
--- the second in the final order (so that, after the sort, `i < j` implies not
--- `comp(list[j],list[i]))`. If `comp` is not given, then the standard Lua
--- operator `<` is used instead.
---
--- Note that the `comp` function must define a strict partial order over the
--- elements in the list; that is, it must be asymmetric and transitive.
--- Otherwise, no valid sort may be possible.
---
--- The sort algorithm is not stable: elements considered equal by the given
--- order may have their relative positions changed by the sort.
---@overload fun(list:table):number
---@generic V
---@param list table<number, V> | V[]
---@param comp fun(a:V, b:V):boolean
---@return number
function table.sort(list, comp) end
--- Updates the size of a `table`. If the `table` has a field "n" with a numerical
--- value, that value is changed to the given `n`. Otherwise, it updates an internal
--- state so that subsequent calls to `table.getn(table)` return `n`.
---
---@param table table
---@param n number
function table.setn(table, n) end
return table
|
local mock_loop = require('spec.mock_loop')
local test = require('luatest')
local DEFAULT_CSV_ITEMS = {
{insertText="dump()", label="dump() ", kind=2,},
{insertText="load()", label="load() ", kind=2,},
{insertText="iterate()", label="iterate() ", kind=2}
}
local DEFAULT_JSON_ITEMS = {
{insertText="decode()", kind=2, label="decode() "},
{insertText="encode()", kind=2, label="encode() "}
}
package.loaded['tarantool-lsp.tnt-doc.doc-manager'] = {
init = function() end,
getInternalLibrariesList = function()
return {
csv = true,
json = true
}
end
}
package.loaded['tarantool-lsp.completions.csv'] = require('test.completions.golden_files.csv')
package.loaded['tarantool-lsp.completions.json'] = require('test.completions.golden_files.json')
local function make_completion_call(before, after, position)
local resp
mock_loop(function(rpc)
local doc = {
uri = "file:///tmp/fake.lua"
}
rpc.notify("textDocument/didOpen", {
textDocument = {uri = doc.uri, text = before}
})
rpc.notify("textDocument/didChange", {
textDocument = {uri = doc.uri, text = after},
contentChanges = {}
})
rpc.request("textDocument/completion", {
textDocument = doc,
position = position
}, function(out)
resp = out
end)
end)
return resp
end
local libs_completion = test.group("libs-completion")
libs_completion.test_basic = function()
local text = "local csv = require('csv')\n"
local cmplt = make_completion_call(text, text .. "csv.", {line = 1, character = 4})
test.assert_equals(cmplt, {
isIncomplete = false,
items = DEFAULT_CSV_ITEMS,
})
end
-- The reason of the test is 'dirty scopes'. Doesn't take account of right border of the scopes.
-- In case of file extending, we have updated right borders, which we can update manually without AST data.
--[[
Case 1: Document was extended, current scopes are valid and new text righter that scope borders
Case 2: Document was extended, current scopes are valid but new text placed on the any previous scope
```lua
do
local m = require('...')
end
c|sv.
```
where | - is the right border
]]
-- libs_completion.test_closed_scope = function()
-- local text =
-- [[
-- do
-- local csv = require('csv')
-- end
-- ]]
-- local cmpltText =
-- [[
-- do
-- local csv = require('csv')
-- end
-- csv.
-- ]]
-- local cmplt = make_completion_call(text, cmpltText, {line = 4, character = 4})
-- test.assertEquals(cmplt, { isIncomplete = false, items = {} })
-- end
libs_completion.test_global_scope = function()
local text =
[[
local csv = require('csv')
]]
local cmpltText =
[[
local csv = require('csv')
local function abc()
csv.
end
]]
local cmplt = make_completion_call(text, cmpltText, {line = 3, character = 6})
test.assert_equals(cmplt, {
isIncomplete = false,
items = DEFAULT_CSV_ITEMS
})
end
libs_completion.test_local_scope = function()
local text =
[[
local function abc()
local csv = require('csv')
end
]]
local cmpltText =
[[
local function abc()
local csv = require('csv')
csv.
end
]]
local cmplt = make_completion_call(text, cmpltText, {line = 2, character = 6})
test.assert_equals(cmplt, {
isIncomplete = false,
items = DEFAULT_CSV_ITEMS
})
end
libs_completion.test_variable_shadowing = function()
local text =
[[
local lib = require('csv')
do
local lib = require('json')
end
]]
local cmpltText =
[[
local lib = require('csv')
do
local lib = require('json')
lib.
end
]]
local cmplt = make_completion_call(text, cmpltText, {line = 4, character = 6})
test.assert_equals(cmplt, {
isIncomplete = false,
items = DEFAULT_JSON_ITEMS
})
end
-- TODO: Reassignment to another variable
|
require("grid")
local grid = Grid.new()
local bestScoreFont = love.graphics.newFont("fonts/retro_font.TTF", 30)
local currentScoreFont = love.graphics.newFont("fonts/retro_font.TTF", 55)
function love.keyreleased(key)
if key == "escape" or key == "q" then
grid:saveScore()
love.event.push("quit")
end
if key == "r" or key == "q" then
grid:resetGrid()
print("Restarting game!")
end
if key == "a" then
print("Move left")
grid:moveLeft()
grid:checkGameState()
end
if key == "d" then
print("Move right")
grid:moveRight()
grid:checkGameState()
end
if key == "w" then
print("Move up")
grid:moveUp()
grid:checkGameState()
end
if key == "s" then
print("Move down")
grid:moveDown()
grid:checkGameState()
end
end
function love.update(dt)
end
function love.draw()
love.graphics.setColor({1, 1, 1, 1})
love.graphics.print("best score", bestScoreFont, 35, 615)
love.graphics.print(tostring(grid.bestScore), bestScoreFont, 400, 615)
love.graphics.print("score", currentScoreFont, 35, 675)
love.graphics.print(grid.currentScore, currentScoreFont, 370, 675)
grid:draw()
end
|
---@meta
local resty_core_base = {}
---@param ... string
function resty_core_base.allows_subsystem(...) end
---@param t table
function resty_core_base.clear_tab(t) end
---@return userdata
function resty_core_base.get_errmsg_ptr() end
---@return userdata
function resty_core_base.get_request() end
---@return userdata
function resty_core_base.get_size_ptr() end
---@param size number
---@param must_alloc boolean
---@return userdata
function resty_core_base.get_string_buf(size, must_alloc) end
---@return number
function resty_core_base.get_string_buf_size() end
---@param narr number
---@param nrec number
---@return table
function resty_core_base.new_tab(narr, nrec) end
---@param tb table
---@param key any
---@return any
function resty_core_base.ref_in_table(tb, key) end
---@param size number
function resty_core_base.set_string_buf_size(size) end
resty_core_base.FFI_OK = 0
resty_core_base.FFI_NO_REQ_CTX = -100
resty_core_base.FFI_BAD_CONTEXT = -101
resty_core_base.FFI_ERROR = -1
resty_core_base.FFI_AGAIN = -2
resty_core_base.FFI_BUSY = -3
resty_core_base.FFI_DONE = -4
resty_core_base.FFI_DECLINED = -5
resty_core_base.version = "0.1.23"
return resty_core_base
|
-- ========== THIS IS AN AUTOMATICALLY GENERATED FILE! ==========
PlaceObj('XTemplate', {
__is_kind_of = "XLabel",
group = "PreGame",
id = "MainMenuButtonText",
PlaceObj('XTemplateWindow', {
'__class', "XLabel",
'TextFont', "BuildMenuBuilding",
'TextColor', RGBA(255, 254, 171, 255),
}),
})
|
-- FIXME: Will overflow the stack.
function ackermann (m, n)
if m == 0 then
return n + 1
end
if n == 0 then
return ackermann(m - 1, 1)
end
return ackermann(m - 1, ackermann(m, n - 1))
end
print(ackermann(3, 11))
|
ICDP = {}
ICDP.version = "1.17.1";
ICDP.author = "Nebula";
ICDP.modName = "iCDPlayersSV";
ICDP.OnClientCommand = function(module, command, player, args)
if not isServer() then return end
if module ~= "iCDPlayersSV" then return end;
if command == "Say" then
player:Say(args.saythis);
end
end
Events.OnClientCommand.Add(ICDP.OnClientCommand);
|
-- Place this file into your %FARPROFILE%\Macros\scripts
-- Show all windows list from all consoles
local ConEmu = "4b675d80-1d4a-4ea9-8436-fdc23f2fc14b"
Macro
{
area="Shell QView Info Tree Search Dialog Editor Viewer";
key="F12";
flags="NoSendKeysToPlugins";
description="ConEmu: Show all windows list from all consoles";
action = function()
if Plugin.Menu(ConEmu) then
Keys("T")
end
end
}
Macro
{
area="Shell QView Info Tree Search Dialog Editor Viewer";
key="CtrlShiftF12";
flags="NoSendKeysToPlugins";
description="ConEmu: Standard Far windows list";
action = function()
Keys("F12")
end
}
|
-- bsu_init.lua by Bonyoze
-- Makes all the shit work
DIR = "bsu/"
LIB_DIR = DIR .. "base/bsu_lib/"
SV_DIR = DIR .. "server/"
SH_DIR = DIR .. "shared/"
CL_DIR = DIR .. "client/"
MODULES_DIR = DIR .. "modules/"
local lib = file.Find(LIB_DIR .. "*.lua", "LUA") -- bsu library files
local sv = file.Find(SV_DIR .. "*.lua", "LUA") -- server files
local sh = file.Find(SH_DIR .. "*.lua", "LUA") -- shared files
local cl = file.Find(CL_DIR .. "*.lua", "LUA") -- client files
BSU = BSU or {}
-- const values
BSU.DEFAULT_RANK = 101 -- Guest team index
BSU.BOT_RANK = 108 -- Bot team index
BSU.AFK_TIMEOUT = 900 -- 900 secs (15 mins)
BSU.CMD_PREFIX = "!"
-- SERVER/CLIENT SETUP
if SERVER then
MsgN("[BSU SERVER] Started up")
-- load/send library files
for _, file in ipairs(lib) do
include(LIB_DIR .. file)
AddCSLuaFile(LIB_DIR .. file)
end
-- load/send base files
include("bsu/base/database.lua")
include("bsu/base/teams.lua")
AddCSLuaFile("bsu/base/teams.lua")
include("bsu/base/player.lua")
AddCSLuaFile("bsu/base/player.lua")
-- load assets
resource.AddSingleFile("materials/bsu/scoreboard/windows.png")
resource.AddSingleFile("materials/bsu/scoreboard/mac.png")
resource.AddSingleFile("materials/bsu/stathud/stathudIcons16.png")
include("bsu/developer.lua") -- REMOVE THIS WHEN PUBLIC
AddCSLuaFile("bsu/developer.lua")
-- SERVER MODULES
for _, file in ipairs(sv) do
include(SV_DIR .. file)
end
for _, file in ipairs(sh) do
include(SH_DIR .. file)
AddCSLuaFile(SH_DIR .. file)
end
for _, file in ipairs(cl) do
AddCSLuaFile(CL_DIR .. file)
end
MsgN("[BSU SERVER] Finished loading modules")
else
MsgN("[BSU CLIENT] Started up")
-- load library files
for _, file in ipairs(lib) do
include(LIB_DIR .. file)
end
-- load base files
include("bsu/base/teams.lua")
include("bsu/base/player.lua")
include("bsu/developer.lua") -- REMOVE THIS WHEN PUBLIC
-- CLIENT MODULES
for _, file in ipairs(sh) do
include(SH_DIR .. file)
end
for _, file in ipairs(cl) do
include(CL_DIR .. file)
end
MsgN("[BSU CLIENT] Finished loading modules")
end
hook.Add("OnGamemodeLoaded", "BSU_GetTeamColorOverride", function()
GAMEMODE.GetTeamColor = BSU.GetPlayerColor
end)
|
local module = script
local packages = module.Parent
return {
Checkbox = require(packages:WaitForChild("checkbox")),
RadioButton = require(packages:WaitForChild("radiobutton")),
Switch = require(packages:WaitForChild("switch")),
TextLabel = require(packages:WaitForChild("textlabel")),
IconLabel = require(packages:WaitForChild("iconlabel")),
}
|
if not arg[1] then
print ('Error: no interfaces file specified')
return
end
if not arg[2] then
print ('Error: no source file specified')
return
end
local f = io.open (arg[1], 'r')
local defs = f:read ('*all')
f:close()
f = io.open (arg[3], 'r')
local src = f:read ('*all')
f:close()
local srcinputs = {}
for line in io.lines (arg[2]) do
line = line:gsub("^%s*(.-)%s*$", "%1")
if line:sub (1, 5) == 'input' then
local evt = line:match ("%).-$"):sub(2):gsub("^%s*(.-)%s*;$", "%1");
srcinputs[evt] = true
end
end
local HANDLER_TEMPLATE =
'code/await Emit_Input_Event (var& [] byte evt) -> none\n' ..
'throws Exception.Lua\n' ..
'do\n' ..
'{#1}' ..
'end'
local HANDLER_CHECK_TEMPLATE =
'\tif _strcmp(&&evt[0],"{#1}") == 0 then\n' ..
'\t\t{#2}\n' ..
'\t\t_emit_{#3}_event ({#4});\n' ..
'\tend\n'
local CODE_TEMPLATE =
'\tvoid emit_{#1}_event ({#2})\n' ..
'\t{\n' ..
'\t\ttceu_input_{#3} p = {{#4}};\n' ..
'\t\tceu_input (CEU_INPUT_{#3}, &p);\n' ..
'\t}'
function capitalize_first (str)
return str:lower():gsub('_.', string.upper):gsub('^.', string.upper)
end
function decl_param (type_, index)
return type_ .. ' param' .. index
end
function get_vars_from_params (params)
local toReturn = ''
local tmp = 0
for token in params:gmatch ('(.-) ') do
tmp = tmp + 1
if tmp % 2 == 0 then
toReturn = toReturn .. token
end
end
return toReturn
end
function get_emit_args_from_vars (args)
if args == '_' then
return ''
else
return args
end
end
function interfaces (T)
local gen = ''
local checks = ''
local decl_funcs = ''
for name, t in pairs (T) do
for evt, args in pairs (t.inputs) do
if srcinputs[evt] == true then
local code = CODE_TEMPLATE:gsub ('{#1}', evt:lower())
decl_funcs = decl_funcs .. '\t_emit_' .. evt:lower() .. '_event,\n'
local varcheckdecl = ''
local paramdecl = ''
for i=1, #args do
paramdecl = paramdecl .. decl_param (args[i], i) .. ', '
varcheckdecl = varcheckdecl .. 'var ' .. decl_param (args[i], i) ..
' = [[ MARS.message.args[' .. i .. '] ]];\n\t\t'
end
if paramdecl ~= '' then
paramdecl = paramdecl:sub(1, -3) .. ' '
end
local evt_args = get_vars_from_params (paramdecl)
local emit_args = paramdecl
code = code:gsub('{#2}', paramdecl)
:gsub('{#3}', evt:upper())
:gsub('{#4}', evt_args)
gen = gen .. code .. '\n\n'
local check = HANDLER_CHECK_TEMPLATE:gsub ('{#1}', evt)
:gsub ('{#2}', varcheckdecl)
:gsub ('{#3}', evt:lower())
:gsub ('{#4}', evt_args)
checks = checks .. check .. '\n'
end
end
end
if decl_funcs ~= '' then
decl_funcs = 'native/nohold\n' .. decl_funcs .. '\n;'
end
src = src:gsub ('__DECL_EMIT_FUNCTIONS__', decl_funcs)
src = src:gsub ('__EMIT_FUNCTIONS__', gen)
src = src:gsub ('__INTERFACES__', defs:gsub ('interfaces', 'MARS.interfaces = '))
src = src:gsub ('__INPUTS__', HANDLER_TEMPLATE:gsub('{#1}', checks))
if arg[3] then
f = io.open (arg[3], 'w')
f:write (src)
f:close()
end
end
local success, err = pcall(load (defs))
if success then
print ('Output generated!')
else
print ('[error:] ' .. tostring (err))
end
|
--
-- Simple Platformer Game (C)opyright Heark 2014
--
-- Require Files
require "system"
-- Main
function love.load()
k = love.keyboard
g = love.graphics
a = love.audio
love.graphics.getBackgroundColor(255, 255, 255)
-- Loading Classes
player.load()
end
player = {}
function player.load()
player.x = 5
player.y = 5
player.xvel = 0
player.yvel = 0
player.friction = 7
player.speed = 2250
player.width = 50
player.height = 50
bullets ={}
SHOT_SOUND=a.newSource("shot.mp3")
end
function player.draw()
love.graphics.setColor(100, 0, 0)
love.graphics.rectangle("fill",player.x,player.y,player.width,player.height)
love.graphics.setColor(100, 0, 0)
love.graphics.rectangle("line",player.x,player.y,player.width,player.height)
end
function UPDATE_PLAYER(dt)
if k.isDown("left") then player.x=player.x - player.speed*dt end
if k.isDown("right") then player.x=player.x + player.speed*dt end
if k.isDown("up") then player.x=player.y - player.speed*dt end
if k.isDown("down") then player.x=player.y + player.speed*dt end
local bullets_speed=400
for i=1,#bullets do
bullets[i].y=bullets[i].y-bullets_speed*dt
end
end
function DRAW_PLAYER()
player.draw()
end
function love.update(dt)
UPDATE_PLAYER(dt)
end
function love.draw()
DRAW_PLAYER()
end
|
-- By Olivier Roques
-- github.com/ojroques
-------------------- VARIABLES -----------------------------
local fn, cmd, vim = vim.fn, vim.cmd, vim
local o = vim.o
local fmt = string.format
local M = {}
-------------------- OPTIONS -------------------------------
M.options = {
theme = 'default', -- the theme in 'lua/bufbar/themes' to use
show_tabs = true, -- show tabs
show_bufname = 'current', -- show full buffer name
show_flags = true, -- show buffer flags
show_alternate = false, -- show alternate buffer
modifier = ':t', -- the buffer name modifier
separator = '|', -- the buffer separator
}
-------------------- HELPERS ----------------------------
local function set_hlgroup(text, class, level)
local hlgroup = fmt('Bufbar_%s_%s', class, level)
if fn.hlexists(hlgroup) == 0 then
return text
end
return fmt('%%#%s#%s%%*', hlgroup, text)
end
-------------------- BUFFERLINE ------------------------
local function is_excluded(bufnr)
return fn.buflisted(bufnr) == 0 or fn.getbufvar(bufnr, '&filetype') == 'qf'
end
local function get_buffers()
local buffers = {}
local current_bufnr, alternate_bufnr = fn.bufnr(), fn.bufnr('#')
local last_timestamp, last_buffer
for _, bufinfo in ipairs(fn.getbufinfo({buflisted = 1})) do
if not is_excluded(bufinfo.bufnr) then
local buffer = {
bufnr = bufinfo.bufnr,
current = bufinfo.bufnr == current_bufnr,
alternate = bufinfo.bufnr == alternate_bufnr,
modifiable = fn.getbufvar(bufinfo.bufnr, '&modifiable') == 1,
modified = fn.getbufvar(bufinfo.bufnr, '&modified') == 1,
readonly = fn.getbufvar(bufinfo.bufnr, '&readonly') == 1,
terminal = fn.getbufvar(bufinfo.bufnr, '&buftype') == 'terminal',
visible = fn.bufwinnr(bufinfo.bufnr) > 0,
}
if not last_timestamp or bufinfo.lastused > last_timestamp then
last_timestamp, last_buffer = bufinfo.lastused, buffer
end
table.insert(buffers, buffer)
end
end
if is_excluded(current_bufnr) and last_buffer then
last_buffer.current = true
end
return buffers
end
local function get_tabs()
local tabs = {}
local current_tab = fn.tabpagenr()
for _, tabinfo in ipairs(fn.gettabinfo()) do
local tab = {
tabnr = tabinfo.tabnr,
current = tabinfo.tabnr == current_tab,
}
table.insert(tabs, tab)
end
return tabs
end
local function get_flags(buffer)
local flags = {}
if buffer.readonly then
table.insert(flags, '[RO]')
end
if not buffer.modifiable then
table.insert(flags, '[-]')
end
if buffer.modified then
table.insert(flags, '[+]')
end
return table.concat(flags)
end
local function get_name(buffer)
local name, expand = '[No Name]', buffer.current
expand = expand or M.options.show_bufname == 'all'
expand = expand or M.options.show_bufname == 'visible' and buffer.visible
if expand then
local modifier = (buffer.terminal and ':t') or (M.options.modifier or ':t')
local flags = get_flags(buffer)
if fn.bufname(buffer.bufnr) ~= '' then
name = fn.fnamemodify(fn.bufname(buffer.bufnr), modifier)
end
if M.options.show_flags and flags ~= '' then
name = fmt('%d: %s %s', buffer.bufnr, name, flags)
else
name = fmt('%d: %s', buffer.bufnr, name)
end
elseif M.options.show_alternate and buffer.alternate then
name = fmt('%d (#)', buffer.bufnr)
else
name = fmt('%d', buffer.bufnr)
end
return name
end
function M.build_bufferline()
local separator = set_hlgroup(M.options.separator, 'separator', 'normal')
local spacer = set_hlgroup('%<%=', 'separator', 'normal')
local bufferline = {}
local buffers, buflist = get_buffers(), {}
for _, buffer in ipairs(buffers) do
local bufname = fmt(' %s ', get_name(buffer))
local class, level = 'listed', 'inactive'
class = buffer.modified and 'modified' or class
class = buffer.terminal and 'terminal' or class
level = buffer.current and 'active' or level
table.insert(buflist, set_hlgroup(bufname, class, level))
end
table.insert(bufferline, table.concat(buflist, separator))
table.insert(bufferline, spacer)
if M.options.show_tabs then
local tabs, tablist = get_tabs(), {}
for _, tab in ipairs(tabs) do
local tabname = fmt(' %d ', tab.tabnr)
local level = tab.current and 'active' or 'inactive'
table.insert(tablist, set_hlgroup(tabname, 'tabs', level))
end
table.insert(bufferline, set_hlgroup(' tabs: ', 'separator', 'emphasized'))
table.insert(bufferline, table.concat(tablist, separator))
end
return table.concat(bufferline)
end
-------------------- SETUP -----------------------------
local function set_theme()
if type(M.options.theme) ~= 'string' then
return
end
local theme = fmt('bufbar.themes.%s', M.options.theme)
M.options.theme = require(theme)
end
local function set_hlgroups()
for class, levels in pairs(M.options.theme) do
for level, args in pairs(levels) do
local hlgroup, arg = fmt('Bufbar_%s_%s', class, level), {}
for k, v in pairs(args) do
table.insert(arg, fmt('%s=%s', k, v))
end
arg = table.concat(arg, ' ')
cmd(fmt('autocmd VimEnter,ColorScheme * hi %s %s', hlgroup, arg))
end
end
end
local function set_bufferline()
o.showtabline = 2
o.tabline = [[%!luaeval('require("bufbar").build_bufferline()')]]
end
function M.setup(user_options)
M.options = vim.tbl_extend('force', M.options, user_options)
set_theme()
set_hlgroups()
set_bufferline()
end
------------------------------------------------------------
return M
|
local plugin = require("kong.plugins.base_plugin"):extend()
local iputils = require "resty.iputils"
local get_headers = ngx.req.get_headers
local inspect = require "inspect"
local FORBIDDEN = 403
-- cache of parsed CIDR values
local cache = {}
local plugin = {}
plugin.PRIORITY = 990
plugin.VERSION = "1.0.0"
local function to_binary_string(octets)
local bin = ""
for _, octet in ipairs(octets) do
bin = bin .. string.char(octet)
end
return bin
end
local function get_binary_ip(ip)
local parsed_ip, octets_or_err = iputils.ip2bin(ip)
-- failed to parse the IP address
if not parsed_ip and octets_or_err then
return nil, octets_or_err
end
return to_binary_string(octets_or_err)
end
local function get_request_ip(conf)
local binary_remote_addr = ngx.var.binary_remote_addr
local headers = kong.request.get_headers()
local header_value = ""
for index, header_name in pairs(conf.headers) do
if headers[header_name] then
return get_binary_ip(headers[header_name])
end
end
return binary_remote_addr
end
local function cidr_cache(cidr_tab)
local cidr_tab_len = #cidr_tab
local parsed_cidrs = kong.table.new(cidr_tab_len, 0) -- table of parsed cidrs to return
-- build a table of parsed cidr blocks based on configured
-- cidrs, either from cache or via iputils parse
-- TODO dont build a new table every time, just cache the final result
-- best way to do this will require a migration (see PR details)
for i = 1, cidr_tab_len do
local cidr = cidr_tab[i]
local parsed_cidr = cache[cidr]
if parsed_cidr then
parsed_cidrs[i] = parsed_cidr
else
-- if we dont have this cidr block cached,
-- parse it and cache the results
local lower, upper = iputils.parse_cidr(cidr)
cache[cidr] = { lower, upper }
parsed_cidrs[i] = cache[cidr]
end
end
return parsed_cidrs
end
function plugin:init_worker()
local ok, err = iputils.enable_lrucache()
if not ok then
kong.log.err("could not enable lrucache: ", err)
end
end
function plugin:access(conf)
local block = false
local binary_remote_addr = get_request_ip(conf)
if not binary_remote_addr then
return kong.response.exit(FORBIDDEN, { message = "Cannot identify the client IP address, unix domain sockets are not supported." })
end
if conf.blacklist and #conf.blacklist > 0 then
block = iputils.binip_in_cidrs(binary_remote_addr, cidr_cache(conf.blacklist))
end
if conf.whitelist and #conf.whitelist > 0 then
block = not iputils.binip_in_cidrs(binary_remote_addr, cidr_cache(conf.whitelist))
end
if block then
return kong.response.exit(FORBIDDEN, { message = "Your IP address is not allowed" })
end
end
return plugin
|
local CRYPT = require "lcrypt"
local sm3 = CRYPT.sm3
local hmac_sm3 = CRYPT.hmac_sm3
local sm2keygen = CRYPT.sm2keygen
local sm2sign = CRYPT.sm2sign
local sm2verify = CRYPT.sm2verify
local hexencode = CRYPT.hexencode
local base64encode = CRYPT.base64encode
local base64decode = CRYPT.base64decode
local sm4_cbc_encrypt = CRYPT.sm4_cbc_encrypt
local sm4_cbc_decrypt = CRYPT.sm4_cbc_decrypt
local sm4_ecb_encrypt = CRYPT.sm4_ecb_encrypt
local sm4_ecb_decrypt = CRYPT.sm4_ecb_decrypt
local sm4_ofb_encrypt = CRYPT.sm4_ofb_encrypt
local sm4_ofb_decrypt = CRYPT.sm4_ofb_decrypt
local sm4_ctr_encrypt = CRYPT.sm4_ctr_encrypt
local sm4_ctr_decrypt = CRYPT.sm4_ctr_decrypt
local SM = {}
-- 哈希
function SM.sm3(str, hex)
local hash = sm3(str)
if hash and hex then
return hexencode(hash)
end
return hash
end
-- 摘要
function SM.hmac_sm3 (key, text, hex)
local hash = hmac_sm3(key, text)
if hash and hex then
return hexencode(hash)
end
return hash
end
-- 生成SM2私钥、公钥
function SM.sm2keygen(pri_path, pub_path)
return sm2keygen(pri_path, pub_path)
end
-- SM3WithSM2签名
function SM.sm2sign(pri_path, text, b64)
local sign = sm2sign(pri_path, text)
if b64 then
sign = base64encode(sign)
end
return sign
end
-- SM3WithSM2验签
function SM.sm2verify(pub_path, text, sign, b64)
if b64 then
sign = base64decode(sign)
end
return sm2verify(pub_path, text, sign)
end
-- SM4分组加密算法之CBC
function SM.sm4_cbc_encrypt(key, text, iv, b64)
local cipher = sm4_cbc_encrypt(key, text, iv)
if b64 then
cipher = base64encode(cipher)
end
return cipher
end
-- SM4分组加密算法之CBC
function SM.sm4_cbc_decrypt(key, cipher, iv, b64)
if b64 then
cipher = base64decode(cipher)
end
return sm4_cbc_decrypt(key, cipher, iv)
end
-- SM4分组加密算法之ECB
function SM.sm4_ecb_encrypt(key, text, iv, b64)
local cipher = sm4_ecb_encrypt(key, text, iv)
if b64 then
cipher = base64encode(cipher)
end
return cipher
end
-- SM4分组解密算法之ECB
function SM.sm4_ecb_decrypt(key, cipher, iv, b64)
if b64 then
cipher = base64decode(cipher)
end
return sm4_ecb_decrypt(key, cipher, iv)
end
-- SM4分组加密算法之OFB
function SM.sm4_ofb_encrypt(key, text, iv, b64)
local cipher = sm4_ofb_encrypt(key, text, iv)
if b64 then
cipher = base64encode(cipher)
end
return cipher
end
-- SM4分组解密算法之OFB
function SM.sm4_ofb_decrypt(key, cipher, iv, b64)
if b64 then
cipher = base64decode(cipher)
end
return sm4_ofb_decrypt(key, cipher, iv)
end
-- SM4分组加密算法之CTR
function SM.sm4_ctr_encrypt(key, text, iv, b64)
local cipher = sm4_ctr_encrypt(key, text, iv)
if b64 then
cipher = base64encode(cipher)
end
return cipher
end
-- SM4分组解密算法之CTR
function SM.sm4_ctr_decrypt(key, cipher, iv, b64)
if b64 then
cipher = base64decode(cipher)
end
return sm4_ctr_decrypt(key, cipher, iv)
end
-- 初始化函数
return function (t)
for k, v in pairs(SM) do
t[k] = v
end
return SM
end
|
--------------------------------------
-------- HANDLER ---------------------
--------------------------------------
local Handler = {}
Handler.__index = Handler
-- sets the information to show if there was an error
function set_bad_request(handler)
handler.content = '404 Not Found'
handler.contentLength = 15
handler.type = 'static'
handler.contentType = 'text/html'
handler.status = 404
end
function Handler:create(type)
local handler = {}
setmetatable(handler, self)
-- The different types of files
handler.__contentTypes = {
['.html'] = 'text/html',
['.js'] = 'text/javascript',
['.css'] = 'text/css',
['.jpg'] = 'image/jpeg',
['.png'] = 'image/png',
['notfound'] = 'text/plain'
}
if type == 'data' or type == 'image' or type == 'static' then
handler.content = ''
handler.contentLength = 0
-- A bad request
else
set_bad_request(handler)
end
return handler
end
function Handler:find(file)
-- It's a data request
if file.extension == '' and file.path == '/data' then
-- Checks if there is a "Link"
if Link then
-- Checks if there is a query
if file.query then
local err
success, self.content = pcall(Link.processQuery, file.query)
if not success then
print('Error. Is the emulator running?')
self.content = ''
self.status = 404
else
self.status = 200
end
self.contentLength = string.len(self.content)
self.contentType = 'text/html'
else
set_bad_request(self)
self.content = 'Bad query format.'
self.contentLength = string.len(self.content)
end
else
set_bad_request(self)
self.content = 'No Link found. Try to start the game.'
self.contentLength = string.len(self.content)
end
-- A file request
else
local f = io.open(file.path, "rb")
-- The file was found
if f then
--for line in f:lines() do
--self.content = self.content .. line .. '\n'
--end
self.content = f:read('*a')
self.contentType = self.__contentTypes[file.extension]
self.contentLength = string.len(self.content)
self.status = 200
f:close()
-- The file was not found
else
set_bad_request(self)
end
end
end
return Handler
|
local HOME = os.getenv("HOME")
local OA_PATH = HOME .. "/app/openarena-0.8.8/openarena.x86_64"
local say
say = function(text)
if not text then
return
end
print("saying ", text)
local espeak_cmd = [[espeak --stdout -s200 -k18 -a50 -v female2 | play -t wav - \
gain 3
]]
do
local _with_0 = io.popen(espeak_cmd, "w")
_with_0:write(text)
_with_0:close()
return _with_0
end
end
local timer = {
time = os.time(),
reset = function(self)
self.time = os.time()
end,
diff = function(self)
return os.time() - self.time
end
}
local fd = io.popen(OA_PATH .. " 2>&1 ", "r")
local ignores = {
"rocket",
"gunned",
"push",
"plasmagun",
"electrocuted",
"railed",
"machinegunned",
"nailed",
"fragged",
"pummeled",
"cratered",
"captured",
"wrong place",
"blew",
"x_x",
":o"
}
while true do
local input = fd:read()
if not input then
break
end
input = input:gsub("%^.", ""):lower()
local ignore = false
for _, v in pairs(ignores) do
if input:match(v) then
ignore = true
break
end
end
if (not ignore) and input:match("guild") and (timer:diff() > 1) then
say(input:gsub("guild", ""):gsub("*", ""))
timer:reset()
end
end
|
SPResearch=
{
{
Name = "ScoutEMPAbility",
RequiredResearch = "",
RequiredSubSystems = "Research & FighterProduction",
Cost = 500,
Time = 35,
DisplayedName = "$7732",
DisplayPriority = 281,
Description = "$7734",
UpgradeType = Ability,
TargetType = Ship,
TargetName = "Vgr_Scout",
UpgradeName = "SpecialAttack",
Icon = Icon_Emp,
ShortDisplayedName = "$7314",
},
{
Name = "PlasmaBombs",
RequiredResearch = "",
RequiredSubSystems = "Research & FighterProduction",
Cost = 150,
Time = 15,
DisplayedName = "$7702",
DisplayPriority = 221,
Description = "$7703",
TargetName = "Vgr_Bomber",
Icon = Icon_Tech,
ShortDisplayedName = "$7300",
},
{
Name = "LanceBeams",
RequiredResearch = "",
RequiredSubSystems = "Research & FighterProduction",
Cost = 150,
Time = 15,
DisplayedName = "$7704",
DisplayPriority = 220,
Description = "$7705",
TargetName = "Vgr_LanceFighter",
Icon = Icon_Tech,
ShortDisplayedName = "$7301",
},
{
Name = "CorvetteLaser",
RequiredResearch = "",
RequiredSubSystems = "Research & CorvetteProduction",
Cost = 250,
Time = 20,
DisplayedName = "$7708",
DisplayPriority = 231,
Description = "$7709",
TargetName = "Vgr_LaserCorvette",
Icon = Icon_Tech,
ShortDisplayedName = "$7303",
},
{
Name = "CorvetteCommand",
RequiredResearch = "CorvetteTech",
RequiredSubSystems = "Research & CorvetteProduction",
Cost = 250,
Time = 20,
DisplayedName = "$7710",
DisplayPriority = 232,
Description = "$7711",
TargetName = "Vgr_CommandCorvette",
Icon = Icon_Tech,
ShortDisplayedName = "$7304",
},
{
Name = "CorvetteGraviticAttraction",
RequiredResearch = "",
RequiredSubSystems = "Research & CorvetteProduction",
Cost = 750,
Time = 20,
DisplayedName = "$7706",
DisplayPriority = 230,
Description = "$7707",
TargetName = "Vgr_MinelayerCorvette",
Icon = Icon_Tech,
ShortDisplayedName = "$7302",
},
{
Name = "EWfighterTech",
RequiredResearch = "",
RequiredSubSystems = "Research & FrigateProduction",
Cost = 350,
Time = 25,
DisplayedName = "$8033",
DisplayPriority = 249,
Description = "$8034",
TargetName = "vgr_EWfighter",
Icon = Icon_Tech,
ShortDisplayedName = "$8035",
},
{
Name = "FrigateAssault",
RequiredResearch = "",
RequiredSubSystems = "Research & FrigateProduction",
Cost = 350,
Time = 25,
DisplayedName = "$7714",
DisplayPriority = 250,
Description = "$7715",
TargetName = "vgr_assaultfrigate",
Icon = Icon_Tech,
ShortDisplayedName = "$7306",
},
{
Name = "FrigateInfiltrationTech",
RequiredResearch = "",
RequiredSubSystems = "Research & FrigateProduction",
Cost = 350,
Time = 25,
DisplayedName = "$7716",
DisplayPriority = 252,
Description = "$7717",
TargetName = "Vgr_InfiltratorFrigate",
Icon = Icon_Tech,
ShortDisplayedName = "$7307",
},
{
Name = "infiltratorfrigateCloak",
RequiredResearch = "FrigateInfiltrationTech",
RequiredSubSystems = "Research & FrigateProduction",
Cost = 350,
Time = 25,
DisplayedName = "$8005",
DisplayPriority = 253,
Description = "$8006",
UpgradeType = Ability,
TargetType = Ship,
TargetName = "vgr_infiltratorfrigate",
UpgradeName = "Cloak",
Icon = Icon_Cloak,
ShortDisplayedName = "$8005",
},
{
Name = "DestroyerGuns",
RequiredResearch = "",
RequiredSubSystems = "Research & CapShipProduction",
Cost = 500,
Time = 30,
DisplayedName = "$7720",
DisplayPriority = 261,
Description = "$7721",
TargetName = "Vgr_Destroyer",
Icon = Icon_Tech,
ShortDisplayedName = "$7309",
},
{
Name = "BattlecruiserIonWeapons",
RequiredResearch = "",
RequiredSubSystems = "Research & CapShipProduction",
Cost = 750,
Time = 35,
DisplayedName = "$7718",
DisplayPriority = 1,
Description = "$7719",
TargetName = "Vgr_BattleCruiser",
Icon = Icon_Tech,
ShortDisplayedName = "$7308",
},
{
Name = "HyperspaceGateTech",
RequiredResearch = "",
RequiredSubSystems = "Research",
Cost = 250,
Time = 25,
DisplayedName = "$7722",
DisplayPriority = 262,
Description = "$7723",
TargetName = "Vgr_HyperSpace_Platform",
Icon = Icon_Tech,
ShortDisplayedName = "$7310",
},
{
Name = "PlatformHeavyMissiles",
RequiredResearch = "",
RequiredSubSystems = "Research & PlatformProduction",
Cost = 300,
Time = 30,
DisplayedName = "$7712",
DisplayPriority = 240,
Description = "$7713",
TargetName = "Vgr_WeaponPlatform_missile",
Icon = Icon_Tech,
ShortDisplayedName = "$7305",
},
{
Name = "ProbeProxSensor",
RequiredResearch = "",
RequiredSubSystems = "Research",
Cost = 250,
Time = 20,
DisplayedName = "$7183",
DisplayPriority = 210,
Description = "$7184",
TargetName = "Vgr_Probe_Prox",
Icon = Icon_Tech,
ShortDisplayedName = "$7185",
},
{
Name = "ProbeSensorDisruption",
RequiredResearch = "ProbeProxSensor",
RequiredSubSystems = "Research",
Cost = 400,
Time = 30,
DisplayedName = "$7700",
DisplayPriority = 220,
Description = "$7701",
TargetName = "Vgr_Probe_ECM",
Icon = Icon_Tech,
ShortDisplayedName = "$7182",
},
{
Name = "vgrBUILDSPEEDUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research",
Cost = 500,
Time = 30,
DisplayedName = "$7831",
DisplayPriority = 45,
Description = "$7832",
UpgradeType = Modifier,
TargetType = AllShips,
UpgradeName = "BUILDSPEED",
UpgradeValue = 1.15,
TargetName = "vgr_Mothership",
Icon = Icon_Build,
ShortDisplayedName = "$7229",
},
{
Name = "vgrBUILDSPEEDUpgrade2",
RequiredResearch = "vgrBUILDSPEEDUpgrade1",
RequiredSubSystems = "Research",
Cost = 1500,
Time = 30,
DisplayedName = "$7833",
DisplayPriority = 45,
Description = "$7834",
UpgradeType = Modifier,
TargetType = AllShips,
UpgradeName = "BUILDSPEED",
TargetName = "vgr_Mothership",
UpgradeValue = 1.3,
Icon = Icon_Build,
ShortDisplayedName = "$7230",
},
{
Name = "CorvetteHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "CorvetteProduction & Research",
Cost = 900,
Time = 60,
DisplayedName = "$7759",
DisplayPriority = 200,
Description = "$7760",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Corvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7341",
},
{
Name = "CorvetteHealthUpgrade2",
RequiredResearch = "CorvetteHealthUpgrade1",
RequiredSubSystems = "CorvetteProduction & Research",
Cost = 1800,
Time = 80,
DisplayedName = "$7761",
DisplayPriority = 200,
Description = "$7762",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Corvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7342",
},
{
Name = "CorvetteSpeedUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "CorvetteProduction & Research",
Cost = 800,
Time = 60,
DisplayedName = "$7763",
DisplayPriority = 201,
Description = "$7764",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Corvette",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7341",
},
{
Name = "CorvetteSpeedUpgrade2",
RequiredResearch = "CorvetteSpeedUpgrade1",
RequiredSubSystems = "CorvetteProduction & Research",
Cost = 1600,
Time = 80,
DisplayedName = "$7765",
DisplayPriority = 201,
Description = "$7766",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Corvette",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.4,
Icon = Icon_Speed,
ShortDisplayedName = "$7342",
},
{
Name = "FrigateHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "FrigateProduction & Research",
Cost = 1600,
Time = 80,
DisplayedName = "$7767",
DisplayPriority = 306,
Description = "$7768",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7371",
},
{
Name = "FrigateHealthUpgrade2",
RequiredResearch = "FrigateHealthUpgrade1",
RequiredSubSystems = "FrigateProduction & Research",
Cost = 2600,
Time = 100,
DisplayedName = "$7769",
DisplayPriority = 306,
Description = "$7770",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7372",
},
{
Name = "FrigateSpeedUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "FrigateProduction & Research",
Cost = 1000,
Time = 70,
DisplayedName = "$7771",
DisplayPriority = 307,
Description = "$7772",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7371",
},
{
Name = "SpeedUpgrade2",
RequiredResearch = "FrigateSpeedUpgrade1",
RequiredSubSystems = "FrigateProduction & Research",
Cost = 1500,
Time = 100,
DisplayedName = "$7773",
DisplayPriority = 307,
Description = "$7774",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7372",
},
{
Name = "SuperCapHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "CapShipProduction & Research",
Cost = 4000,
Time = 60,
DisplayedName = "$7743",
DisplayPriority = 61,
Description = "$7744",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Capital",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.3,
Icon = Icon_Health,
ShortDisplayedName = "$7354",
},
{
Name = "SuperCapHealthUpgrade2",
RequiredResearch = "SuperCapHealthUpgrade1",
RequiredSubSystems = "CapShipProduction & Research",
Cost = 6000,
Time = 80,
DisplayedName = "$7745",
DisplayPriority = 61,
Description = "$7746",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Capital",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.6,
Icon = Icon_Health,
ShortDisplayedName = "$7355",
},
{
Name = "SuperCapSpeedUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "CapShipProduction & Research",
Cost = 2000,
Time = 60,
DisplayedName = "$7747",
DisplayPriority = 64,
Description = "$7748",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Capital",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.2,
Icon = Icon_Speed,
ShortDisplayedName = "$7354",
},
{
Name = "SuperCapSpeedUpgrade2",
RequiredResearch = "SuperCapSpeedUpgrade1",
RequiredSubSystems = "CapShipProduction & Research",
Cost = 3000,
Time = 80,
DisplayedName = "$7749",
DisplayPriority = 64,
Description = "$7750",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Capital",
UpgradeName = "MAXSPEED",
UpgradeValue = 1.35,
Icon = Icon_Speed,
ShortDisplayedName = "$7355",
},
{
Name = "PlatformHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "PlatformProduction & Research",
Cost = 1000,
Time = 50,
DisplayedName = "$7775",
DisplayPriority = 600,
Description = "$7776",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Platform",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.5,
Icon = Icon_Health,
ShortDisplayedName = "$7361",
},
{
Name = "PlatformHealthUpgrade2",
RequiredResearch = "PlatformHealthUpgrade1",
RequiredSubSystems = "PlatformProduction & Research",
Cost = 1600,
Time = 70,
DisplayedName = "$7777",
DisplayPriority = 600,
Description = "$7778",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Platform",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
Icon = Icon_Health,
ShortDisplayedName = "$7362",
},
{
Name = "UtilityHealthUpgrade1",
RequiredResearch = "",
RequiredSubSystems = "Research",
Cost = 1200,
Time = 50,
DisplayedName = "$7779",
DisplayPriority = 701,
Description = "$7780",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Utility",
UpgradeName = "MAXHEALTH",
UpgradeValue = 1.5,
Icon = Icon_Health,
ShortDisplayedName = "$7351",
},
{
Name = "UtilityHealthUpgrade2",
RequiredResearch = "UtilityHealthUpgrade1",
RequiredSubSystems = "Research",
Cost = 2400,
Time = 70,
DisplayedName = "$7781",
DisplayPriority = 701,
Description = "$7782",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Utility",
UpgradeName = "MAXHEALTH",
UpgradeValue = 2,
Icon = Icon_Health,
ShortDisplayedName = "$7352",
},
{
Name = "WeakVgrHeavyMissiles",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Reduces damage on Vgr Heavy Missiles (SP Game only!)",
DisplayPriority = 1205,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_HeavyMissileFrigate",
UpgradeName = "WeaponDamage",
UpgradeValue = 0.25,
},
{
Name = "HyperspaceRecoveryTimeUpgradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Hyperspace Recovery - SP GAME ONLY",
DisplayPriority = 1206,
Description = "",
UpgradeType = Modifier,
TargetType = AllShips,
UpgradeName = "HyperspaceRecoveryTime",
UpgradeValue = 0.01,
},
{
Name = "VaygrCarrierHealthRegenDowngrade",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vaygr Carrier Health Regen Rate Downgrade",
DisplayPriority = 1207,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_Carrier",
UpgradeName = "HealthRegenerationRate",
UpgradeValue = 0.1,
},
{
Name = "HyperspaceTransitionTimeUpgradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Hyperspace Transition - SP GAME ONLY",
DisplayPriority = 1206,
Description = "",
UpgradeType = Modifier,
TargetType = AllShips,
UpgradeName = "HyperspaceTime",
UpgradeValue = 0.1,
},
{
Name = "SuperCapHealthUpgradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vgr Super Cap Health Upgrade",
DisplayPriority = 1208,
Description = "Vaygr Carrier Health upgrade - SP GAME ONLY",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Capital",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3.5,
},
{
Name = "ShipyardSpeedDowngradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vaygr Shipyard Speed downgrade",
DisplayPriority = 1208,
Description = "Vaygr Shipyard Speed downgrade - SP GAME ONLY",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_ShipYard",
UpgradeName = "MAXSPEED",
UpgradeValue = 0.0001,
},
{
Name = "VaygrFrigateHealthUpgradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vgr Frigate Health Upgrade",
DisplayPriority = 1208,
Description = "Vaygr Frigate Health upgrade - SP GAME ONLY",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3,
},
{
Name = "VaygrFrigateHealthRegenDowngradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vaygr Frigate Health Regen Rate Downgrade",
DisplayPriority = 1207,
Description = "",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Frigate",
UpgradeName = "HealthRegenerationRate",
UpgradeValue = 0.1,
},
{
Name = "CorvetteHealthUpgradeSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vgr Corvette Health Upgrade",
DisplayPriority = 1208,
Description = "Vaygr Corvette Health upgrade - SP GAME ONLY",
UpgradeType = Modifier,
TargetType = Family,
TargetName = "Corvette",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3.5,
},
{
Name = "ExtraStrongVgrHeavyMissilesSPGAME",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Increases damage on Vgr Heavy Missiles (SP Game only!)",
DisplayPriority = 1205,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_HeavyMissileFrigate",
UpgradeName = "WeaponDamage",
UpgradeValue = 1.35,
},
{
Name = "VaygrCaptureHack",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Increases Capture Speed (SP Game only!)",
DisplayPriority = 1205,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_InfiltratorFrigate",
UpgradeName = "Capture",
UpgradeValue = 1.35,
},
{
Name = "VaygrReduceCaptureHack",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Increases Capture Speed (SP Game only!)",
DisplayPriority = 1205,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_InfiltratorFrigate",
UpgradeName = "Capture",
UpgradeValue = 0.75,
},
{
Name = "VaygrRadiationImmunityHack",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Makes Vaygr Immune to Radiation (SP Game only!)",
DisplayPriority = 1205,
Description = "",
UpgradeType = Modifier,
TargetType = AllShips,
UpgradeName = "NebulaSensitivity",
UpgradeValue = 0,
},
{
Name = "VaygrCarrierHealthUpgrade",
RequiredResearch = "RESEARCH HACK",
RequiredSubSystems = "",
Cost = 0,
Time = 0,
DisplayedName = "Vaygr Carrier Health Upgrade",
DisplayPriority = 1208,
Description = "",
UpgradeType = Modifier,
TargetType = Ship,
TargetName = "Vgr_Carrier",
UpgradeName = "MAXHEALTH",
UpgradeValue = 3,
},
}
local i=1
while (research[i]) do
i=i+1
end
for index,item in SPResearch do
research[i]=item
i=i+1
end
|
-- sdothum - 2016 (c) wtfpl
-- X11 Desktop
-- ═════════════════════════════════════════════════════════════════════════════
-- ....................................................................... Conky
-- see bin/functions/conky/theme
require 'cairo'
LUARINGS=tonumber(io.popen('conky color LUARINGS'):read(), 16)
default_color=tonumber(io.popen('conky color default_color'):read(), 16)
color0=tonumber(io.popen('conky color color0'):read(), 16)
color6=tonumber(io.popen('conky color color6'):read(), 16)
--------------------------------------------------------------------------------
-- clock DATA
-- HOURS
clock_h = {
{
name='time', arg='%l', max_value=12,
x=115, y=125,
graph_radius=65,
graph_thickness=3,
graph_unit_angle=30, graph_unit_thickness=30,
graph_bg_colour=LUARINGS, graph_bg_alpha=0,
graph_fg_colour=color0, graph_fg_alpha=0.66,
txt_radius=50,
txt_weight=0, txt_size=12.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.6,
graduation_radius=55,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=30,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
},
}
-- MINUTES
clock_m = {
{
name='time', arg='%M', max_value=60,
x=115, y=125,
graph_radius=69,
graph_thickness=2,
graph_unit_angle=6, graph_unit_thickness=6,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.05,
graph_fg_colour=color0, graph_fg_alpha=0.33,
txt_radius=81,
txt_weight=0, txt_size=10.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.4,
graduation_radius=59,
graduation_thickness=0, graduation_mark_thickness=2,
graduation_unit_angle=30,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
},
}
-- SECONDS
clock_s = {
{
name='time', arg='%S', max_value=60,
x=115, y=125,
graph_radius=62,
graph_thickness=2,
graph_unit_angle=6, graph_unit_thickness=2,
graph_bg_colour=LUARINGS, graph_bg_alpha=0,
graph_fg_colour=LUARINGS, graph_fg_alpha=0.22,
txt_radius=53,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.3,
graduation_radius=0,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=0,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0,
},
}
--------------------------------------------------------------------------------
-- gauge DATA
temp = {
{
name='exec', arg="sensors | grep 'Core .:' | sed -e 's/^.* [+]//' -e 's/...C *[(].*$//' | sort | tail -1", max_value=100,
x=94, y=539,
graph_radius=25,
graph_thickness=3,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=color0, graph_fg_alpha=0.66,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=17,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
-- {
-- name='exec', arg="sensors | grep 'Core .:' | sed -e 's/^.* [+]//' -e 's/...C *[(].*$//' | sort | head -1", max_value=100,
-- x=94, y=539,
-- graph_radius=25,
-- graph_thickness=3,
-- graph_start_angle=180,
-- graph_unit_angle=2.7, graph_unit_thickness=2.7,
-- graph_bg_colour=LUARINGS, graph_bg_alpha=0,
-- graph_fg_colour=color6, graph_fg_alpha=0.66,
-- hand_fg_colour=color0, hand_fg_alpha=0,
-- txt_radius=17,
-- txt_weight=0, txt_size=8.0,
-- txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
-- graduation_radius=28,
-- graduation_thickness=0, graduation_mark_thickness=1,
-- graduation_unit_angle=27,
-- graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
-- caption='',
-- caption_weight=1, caption_size=8.0,
-- caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
-- },
}
gauge = {
{
name='exec', arg='conky volume', max_value=100,
x=94, y=335,
graph_radius=29,
graph_thickness=1,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=default_color, graph_fg_alpha=0.88,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=38,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
name='mpd_percent', arg='', max_value=100,
x=94, y=335,
graph_radius=25,
graph_thickness=3,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=color0, graph_fg_alpha=0.66,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=17,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
name='cpu', arg='cpu0', max_value=100,
x=94, y=539,
graph_radius=29,
graph_thickness=1,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=default_color, graph_fg_alpha=0.88,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=38,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
name='memperc', arg='', max_value=100,
x=94, y=745,
graph_radius=29,
graph_thickness=1,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=default_color, graph_fg_alpha=0.88,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=38,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=23,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.5,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
name='fs_used_perc', arg='/tmp', max_value=100,
x=94, y=745,
graph_radius=25,
graph_thickness=3,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=color0, graph_fg_alpha=0.66,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=17,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
-- name='fs_used_perc', arg='/', max_value=100,
name='exec', arg='conky btrfs / percent', max_value=100,
x=94, y=905,
graph_radius=29,
graph_thickness=1,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=default_color, graph_fg_alpha=0.88,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=38,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
-- name='fs_used_perc', arg='/net', max_value=100,
name='exec', arg='conky btrfs /net percent', max_value=100,
x=94, y=905,
graph_radius=25,
graph_thickness=3,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=color0, graph_fg_alpha=0.66,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=17,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
name='swapperc', arg='', max_value=100,
x=94, y=905,
graph_radius=25,
graph_thickness=3,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0,
graph_fg_colour=color6, graph_fg_alpha=0.66,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=17,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
{
name='wireless_link_qual_perc', arg='wlp4s0', max_value=100,
x=94, y=1144,
graph_radius=29,
graph_thickness=1,
graph_start_angle=180,
graph_unit_angle=2.7, graph_unit_thickness=2.7,
graph_bg_colour=LUARINGS, graph_bg_alpha=0.06,
graph_fg_colour=default_color, graph_fg_alpha=0.88,
hand_fg_colour=color0, hand_fg_alpha=0,
txt_radius=38,
txt_weight=0, txt_size=8.0,
txt_fg_colour=LUARINGS, txt_fg_alpha=0.5,
graduation_radius=28,
graduation_thickness=0, graduation_mark_thickness=1,
graduation_unit_angle=27,
graduation_fg_colour=LUARINGS, graduation_fg_alpha=0.3,
caption='',
caption_weight=1, caption_size=8.0,
caption_fg_colour=LUARINGS, caption_fg_alpha=0.3,
},
}
-------------------------------------------------------------------------------
-- rgb_to_r_g_b
-- converts color in hexa to decimal
--
function rgb_to_r_g_b(colour, alpha)
return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha
end
-------------------------------------------------------------------------------
-- angle_to_position
-- convert degree to rad and rotate (0 degree is top/north)
--
function angle_to_position(start_angle, current_angle)
local pos = current_angle + start_angle
return ( ( pos * (2 * math.pi / 360) ) - (math.pi / 2) )
end
-------------------------------------------------------------------------------
-- draw_clock_ring
-- displays clock
--
function draw_clock_ring(display, data, value)
local max_value = data['max_value']
local x, y = data['x'], data['y']
local graph_radius = data['graph_radius']
local graph_thickness, graph_unit_thickness = data['graph_thickness'], data['graph_unit_thickness']
local graph_unit_angle = data['graph_unit_angle']
local graph_bg_colour, graph_bg_alpha = data['graph_bg_colour'], data['graph_bg_alpha']
local graph_fg_colour, graph_fg_alpha = data['graph_fg_colour'], data['graph_fg_alpha']
-- background ring
cairo_arc(display, x, y, graph_radius, 0, 2 * math.pi)
cairo_set_source_rgba(display, rgb_to_r_g_b(graph_bg_colour, graph_bg_alpha))
cairo_set_line_width(display, graph_thickness)
cairo_stroke(display)
-- arc of value
local val = (value % max_value)
local i = 1
while i <= val do
cairo_arc(display, x, y, graph_radius,( ((graph_unit_angle * i) - graph_unit_thickness)*(2*math.pi/360) )-(math.pi/2),((graph_unit_angle * i) * (2*math.pi/360))-(math.pi/2))
cairo_set_source_rgba(display,rgb_to_r_g_b(graph_fg_colour,graph_fg_alpha))
cairo_stroke(display)
i = i + 1
end
local angle = (graph_unit_angle * i) - graph_unit_thickness
-- graduations marks
local graduation_radius = data['graduation_radius']
local graduation_thickness, graduation_mark_thickness = data['graduation_thickness'], data['graduation_mark_thickness']
local graduation_unit_angle = data['graduation_unit_angle']
local graduation_fg_colour, graduation_fg_alpha = data['graduation_fg_colour'], data['graduation_fg_alpha']
if graduation_radius > 0 and graduation_thickness > 0 and graduation_unit_angle > 0 then
local nb_graduation = 360 / graduation_unit_angle
local i = 1
while i <= nb_graduation do
cairo_set_line_width(display, graduation_thickness)
cairo_arc(display, x, y, graduation_radius, (((graduation_unit_angle * i)-(graduation_mark_thickness/2))*(2*math.pi/360))-(math.pi/2),(((graduation_unit_angle * i)+(graduation_mark_thickness/2))*(2*math.pi/360))-(math.pi/2))
cairo_set_source_rgba(display,rgb_to_r_g_b(graduation_fg_colour,graduation_fg_alpha))
cairo_stroke(display)
cairo_set_line_width(display, graph_thickness)
i = i + 1
end
end
-- text
local txt_radius = data['txt_radius']
local txt_weight, txt_size = data['txt_weight'], data['txt_size']
local txt_fg_colour, txt_fg_alpha = data['txt_fg_colour'], data['txt_fg_alpha']
local movex = txt_radius * (math.cos((angle * 2 * math.pi / 360)-(math.pi/2)))
local movey = txt_radius * (math.sin((angle * 2 * math.pi / 360)-(math.pi/2)))
cairo_select_font_face (display, "Ubuntu", CAIRO_FONT_SLANT_NORMAL, txt_weight);
cairo_set_font_size (display, txt_size);
cairo_set_source_rgba (display, rgb_to_r_g_b(txt_fg_colour, txt_fg_alpha));
cairo_move_to (display, x + movex - (txt_size / 2), y + movey + 3);
cairo_show_text (display, value);
cairo_stroke (display);
end
-------------------------------------------------------------------------------
-- draw_gauge_ring
-- displays gauges
--
function draw_gauge_ring(display, data, value)
local max_value = data['max_value']
local x, y = data['x'], data['y']
local graph_radius = data['graph_radius']
local graph_thickness, graph_unit_thickness = data['graph_thickness'], data['graph_unit_thickness']
local graph_start_angle = data['graph_start_angle']
local graph_unit_angle = data['graph_unit_angle']
local graph_bg_colour, graph_bg_alpha = data['graph_bg_colour'], data['graph_bg_alpha']
local graph_fg_colour, graph_fg_alpha = data['graph_fg_colour'], data['graph_fg_alpha']
local hand_fg_colour, hand_fg_alpha = data['hand_fg_colour'], data['hand_fg_alpha']
local graph_end_angle = (max_value * graph_unit_angle) % 360
-- background ring
cairo_arc(display, x, y, graph_radius, angle_to_position(graph_start_angle, 0), angle_to_position(graph_start_angle, graph_end_angle))
cairo_set_source_rgba(display, rgb_to_r_g_b(graph_bg_colour, graph_bg_alpha))
cairo_set_line_width(display, graph_thickness)
cairo_stroke(display)
-- arc of value
local val = value % (max_value + 1)
local start_arc = 0
local stop_arc = 0
local i = 1
while i <= val do
start_arc = (graph_unit_angle * i) - graph_unit_thickness
stop_arc = (graph_unit_angle * i)
cairo_arc(display, x, y, graph_radius, angle_to_position(graph_start_angle, start_arc), angle_to_position(graph_start_angle, stop_arc))
cairo_set_source_rgba(display, rgb_to_r_g_b(graph_fg_colour, graph_fg_alpha))
cairo_stroke(display)
i = i + 1
end
local angle = start_arc
-- hand
start_arc = (graph_unit_angle * val) - (graph_unit_thickness * 2)
stop_arc = (graph_unit_angle * val)
cairo_arc(display, x, y, graph_radius, angle_to_position(graph_start_angle, start_arc), angle_to_position(graph_start_angle, stop_arc))
cairo_set_source_rgba(display, rgb_to_r_g_b(hand_fg_colour, hand_fg_alpha))
cairo_stroke(display)
-- graduations marks
local graduation_radius = data['graduation_radius']
local graduation_thickness, graduation_mark_thickness = data['graduation_thickness'], data['graduation_mark_thickness']
local graduation_unit_angle = data['graduation_unit_angle']
local graduation_fg_colour, graduation_fg_alpha = data['graduation_fg_colour'], data['graduation_fg_alpha']
if graduation_radius > 0 and graduation_thickness > 0 and graduation_unit_angle > 0 then
local nb_graduation = graph_end_angle / graduation_unit_angle
local i = 0
while i < nb_graduation do
cairo_set_line_width(display, graduation_thickness)
start_arc = (graduation_unit_angle * i) - (graduation_mark_thickness / 2)
stop_arc = (graduation_unit_angle * i) + (graduation_mark_thickness / 2)
cairo_arc(display, x, y, graduation_radius, angle_to_position(graph_start_angle, start_arc), angle_to_position(graph_start_angle, stop_arc))
cairo_set_source_rgba(display,rgb_to_r_g_b(graduation_fg_colour,graduation_fg_alpha))
cairo_stroke(display)
cairo_set_line_width(display, graph_thickness)
i = i + 1
end
end
-- text
local txt_radius = data['txt_radius']
local txt_weight, txt_size = data['txt_weight'], data['txt_size']
local txt_fg_colour, txt_fg_alpha = data['txt_fg_colour'], data['txt_fg_alpha']
local movex = txt_radius * math.cos(angle_to_position(graph_start_angle, angle))
local movey = txt_radius * math.sin(angle_to_position(graph_start_angle, angle))
cairo_select_font_face (display, "Ubuntu", CAIRO_FONT_SLANT_NORMAL, txt_weight)
cairo_set_font_size (display, txt_size)
cairo_set_source_rgba (display, rgb_to_r_g_b(txt_fg_colour, txt_fg_alpha))
cairo_move_to (display, x + movex - (txt_size / 2), y + movey + 3)
cairo_show_text (display, value)
cairo_stroke (display)
-- caption
local caption = data['caption']
local caption_weight, caption_size = data['caption_weight'], data['caption_size']
local caption_fg_colour, caption_fg_alpha = data['caption_fg_colour'], data['caption_fg_alpha']
local tox = graph_radius * (math.cos((graph_start_angle * 2 * math.pi / 360)-(math.pi/2)))
local toy = graph_radius * (math.sin((graph_start_angle * 2 * math.pi / 360)-(math.pi/2)))
cairo_select_font_face (display, "Ubuntu", CAIRO_FONT_SLANT_NORMAL, caption_weight);
cairo_set_font_size (display, caption_size)
cairo_set_source_rgba (display, rgb_to_r_g_b(caption_fg_colour, caption_fg_alpha))
cairo_move_to (display, x + tox + 5, y + toy + 1)
-- bad hack but not enough time !
if graph_start_angle < 105 then
cairo_move_to (display, x + tox - 30, y + toy + 1)
end
cairo_show_text (display, caption)
cairo_stroke (display)
end
-------------------------------------------------------------------------------
-- go_clock_rings
-- loads data and displays clock
--
function go_clock_rings(display)
local function load_clock_rings(display, data)
local str, value = '', 0
str = string.format('${%s %s}',data['name'], data['arg'])
str = conky_parse(str)
value = tonumber(str)
if value == nil then value = 0 end
draw_clock_ring(display, data, value)
end
for i in pairs(clock_h) do
load_clock_rings(display, clock_h[i])
end
for i in pairs(clock_m) do
load_clock_rings(display, clock_m[i])
end
for i in pairs(clock_s) do
load_clock_rings(display, clock_s[i])
end
end
-------------------------------------------------------------------------------
-- go_gauge_rings
-- loads data and displays gauges
--
function go_temp_rings(display)
local function load_temp_rings(display, data)
local value = 0
local f = assert(io.popen(data['arg'], 'r'))
local str = assert(f:read('*a'))
f:close()
value = tonumber(str)
if value == nil then value = 0 end
-- value = math.floor(tonumber(str) / 0.90 + 0.5)
draw_gauge_ring(display, data, value)
end
for i in pairs(temp) do
load_temp_rings(display, temp[i])
end
end
function go_gauge_rings(display)
local function load_gauge_rings(display, data)
local str, value = '', 0
str = string.format('${%s %s}',data['name'], data['arg'])
str = conky_parse(str)
value = tonumber(str)
if value == nil then value = 0 end
draw_gauge_ring(display, data, value)
end
for i in pairs(gauge) do
load_gauge_rings(display, gauge[i])
end
end
-------------------------------------------------------------------------------
-- MAIN
function conky_main()
if conky_window == nil then
return
end
local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, conky_window.width, conky_window.height)
local display = cairo_create(cs)
local updates = conky_parse('${updates}')
update_num = tonumber(updates)
if update_num == nil then update_num = 0 end
if update_num > 5 then
go_clock_rings(display)
go_gauge_rings(display)
go_temp_rings(display)
end
cairo_surface_destroy(cs)
cairo_destroy(display)
end
-------------------------------------------------------------------------------
-- MIN / MAX
-- max
function conky_max( list )
return math.max(unpack(list))
end
-- min
function conky_min( list )
return math.min(unpack(list))
end
-------------------------------------------------------------------------------
-- BANDWIDTH
-- remove trailing blanks
function conky_bandwidth( speed )
-- return string.gsub( conky_parse( speed ), '[iB ]', '')
return string.gsub(string.gsub( conky_parse( speed ), '[iB ]', ''), '^0$', '')
end
-------------------------------------------------------------------------------
-- SWAP
-- remove trailing blanks
function conky_swap( space )
return string.gsub( conky_parse( space ), '0B ', '')
end
-------------------------------------------------------------------------------
-- NULL
-- blank (null)
function conky_null( desc )
return string.gsub( conky_parse( desc ), '[(]null[)]', '')
end
-- vim: set ft=lua : --
|
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
local voices = {
{ text = 'Can I finally have some peace...?' },
{ text = 'Please leave me alone in my mourning.' }
}
npcHandler:addModule(VoiceModule:new(voices))
keywordHandler:addKeyword({'mourning'}, StdModule.say, {npcHandler = npcHandler, text = "All is lost. With {Winfred} dead, my love has died and I'm only an empty shell without hope or purpose."})
keywordHandler:addKeyword({'port hope'}, StdModule.say, {npcHandler = npcHandler, text = "We put all our hope in this far away colony. Sadly, we never made it there and I will never know what our life would have been like in Port Hope."})
keywordHandler:addKeyword({'druid'}, StdModule.say, {npcHandler = npcHandler, text = "I guess he was the one that put my father up to the whole thing. He spied on Winfred and me and it was certainly him that suggested my {imprisonment} in this tower."})
keywordHandler:addKeyword({'imprisonment'}, StdModule.say, {npcHandler = npcHandler, text = "This forsaken place seems as remote from the rest of the world as my heart is."})
keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, text = "Please leave me alone in my mourning."})
keywordHandler:addKeyword({'thais'}, StdModule.say, {npcHandler = npcHandler, text = "The bustling streets of Thais are all but a faint memory to me."})
keywordHandler:addKeyword({'carlin'}, StdModule.say, {npcHandler = npcHandler, text = "Carlin is a lovely and green city as far as I remember."})
keywordHandler:addKeyword({'venore'}, StdModule.say, {npcHandler = npcHandler, text = "My father wanted me to marry a wealthy Venorean. He understood so little about love and the ways of the heart."})
keywordHandler:addKeyword({'ab\'dendriel'}, StdModule.say, {npcHandler = npcHandler, text = "The city of the elves is an exotic wonder."})
keywordHandler:addKeyword({'kazordoon'}, StdModule.say, {npcHandler = npcHandler, text = "The city is like the dwarfs that built it. Stony, never-changing and hard to understand for an outsider."})
local function creatureSayCallback(cid, type, msg)
if not npcHandler:isFocused(cid) then
return false
elseif msgcontains(msg, "winfred") then
npcHandler:say({
'He was my one and only true love. He was a mere commoner and so my {father} forbid me to see him ...',
'We met anyway, we had plans to flee to {Port Hope} and to start a new life there ...',
'A {druid}, in service of my father, had spied on us. So they brought me here and locked me into this {tower}. The druid cast a spell on the plants at the entrance which kept everyone from entering the tower ...',
'I could see Winfred from the window but he could not come to me. One day he disappeared. I knew immediately that something horrible had happened to him.'
}, cid)
elseif msgcontains(msg, "father") then
npcHandler:say({
'He wasn\'t a bad man. He was only misguided by false friends who told him what society expected of him ...',
'By trying to uphold a respectable image in society, he ruined not only my life but also his own.'
}, cid)
elseif msgcontains(msg, "tower") then
npcHandler:say({
'Once, this tower has been my prison but after the death of Winfred it has become my refuge from the rest of the world. ...',
'I welcome the loneliness here because it mirrors the state of my heart.'
}, cid)
end
return true
end
npcHandler:setMessage(MESSAGE_GREET, "Hello, |PLAYERNAME|. Please leave me alone in my {mourning}.")
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
|
local awful = require("awful")
local filesystem = require("gears.filesystem")
local config_dir = filesystem.get_configuration_dir()
local function run_once_pgrep(cmd)
local findme = cmd
local firstspace = cmd:find(" ")
if firstspace then
findme = cmd:sub(0, firstspace - 1)
end
awful.spawn.easy_async_with_shell(string.format("pgrep -u $USER -x %s > /dev/null || (%s)", findme, cmd))
end
local function run_once_ps(findme, cmd)
awful.spawn.easy_async_with_shell(string.format("ps -C %s|wc -l", findme), function(stdout)
if tonumber(stdout) ~= 2 then
awful.spawn(cmd, false)
end
end)
end
local function run_once_grep(command)
awful.spawn.easy_async_with_shell(string.format("ps aux | grep '%s' | grep -v 'grep'", command), function(stdout)
if stdout == "" or stdout == nil then
awful.spawn(command, false)
end
end)
end
run_once_pgrep("picom --dbus --experimental-backend")
run_once_pgrep("mpDris2")
run_once_pgrep("ibus-daemon -x -r -R")
run_once_grep("gpaste-client start")
run_once_grep("xhost +")
|
dofile("urlcode.lua")
dofile("table_show.lua")
local url_count = 0
local tries = 0
local item_type = os.getenv('item_type')
local item_value = os.getenv('item_value')
local downloaded = {}
local addedtolist = {}
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.download_child_p = function(urlpos, parent, depth, start_url_parsed, iri, verdict, reason)
local url = urlpos["url"]["url"]
local html = urlpos["link_expect_html"]
local parenturl = parent["url"]
if downloaded[url] == true or addedtolist[url] == true then
return false
end
if item_type == "site" and (downloaded[url] ~= true and addedtolist[url] ~= true) then
if string.match(url, item_value) and not (string.match(url, "%%") or string.match(url, "%%25") or string.match(url, "%%3E") or string.match(url, ">") or string.match(url, "/login%?r=/user/login") or string.match(url, "%?[^%?]*%?")) then
return verdict
elseif html == 0 and not (string.match(url, "%%") or string.match(url, "%%25") or string.match(url, "%%3E") or string.match(url, ">") or string.match(url, "/login%?r=/user/login") or string.match(url, "%?[^%?]*%?")) then
return verdict
else
return false
end
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
local function check(newurl)
if (downloaded[newurl] ~= true and addedtolist[newurl] ~= true) then
if not (string.match(newurl, "%%") or string.match(newurl, "%%25") or string.match(newurl, "%%3E") or string.match(newurl, ">") or string.match(newurl, "/login%?r=/user/login") or string.match(newurl, "%?[^%?]*%?")) then
table.insert(urls, { url=newurl })
addedtolist[newurl] = true
end
end
end
if item_type == "site" then
if string.match(url, "%?") then
local newurl = string.match(url, "(https://[^%?]+)%?")
check(newurl)
end
if string.match(url, "https?://[^%.]+%.trovebox%.com") and not string.match(url, "%.jpg") then
html = read_file(file)
if string.match(url, "/page%-") and not string.match(url, "/user/login") then
local page = string.match(url, "/page%-([0-9]+)")
if not (string.match(html, '0 photos') or string.match(url, "/p/") or string.match(html, "HTTP 404")) then
if string.match(html, "id") then
local newurl1 = string.match(url, "(https?://[^/]+/[^/]+/page%-)[0-9]+")
local newurl2 = string.match(url, "https?://[^/]+/[^/]+/page%-[0-9]+(.+)")
local newpage = page + 1
local newurl = newurl1..newpage..newurl2
check(newurl)
end
end
end
for newurl in string.gmatch(html, '"(https?://[^"]+)"') do
if string.match(newurl, item_value) or string.match(newurl, "%.jpg") or string.match(newurl, "%.png") or string.match(url, "%.cloudfront%.com") then
check(newurl)
end
end
for newurl in string.gmatch(html, '"https?:....d1odebs29o9vbg%.[^%.]+.[a-z]+..[0-9a-zA-Z_%-]+..[0-9a-zA-Z_%-]+..[^%.]+%.[^"]+"') do
local part1 = string.match(html, '"(https?:)....d1odebs29o9vbg%.[^%.]+%.[a-z]+..[0-9a-zA-Z_%-]+..[0-9a-zA-Z_%-]+..[^%.]+%.[^"]+"')
local part2 = string.match(html, '"https?:....(d1odebs29o9vbg%.[^%.]+%.[a-z]+)..[0-9a-zA-Z_%-]+..[0-9a-zA-Z_%-]+..[^%.]+%.[^"]+"')
local part3 = string.match(html, '"https?:....d1odebs29o9vbg%.[^%.]+%.[a-z]+..([0-9a-zA-Z_%-]+)..[0-9a-zA-Z_%-]+..[^%.]+%.[^"]+"')
local part4 = string.match(html, '"https?:....d1odebs29o9vbg%.[^%.]+%.[a-z]+..[0-9a-zA-Z_%-]+..([0-9a-zA-Z_%-]+)..[^%.]+%.[^"]+"')
local part5 = string.match(html, '"https?:....d1odebs29o9vbg%.[^%.]+%.[a-z]+..[0-9a-zA-Z_%-]+..[0-9a-zA-Z_%-]+..([^%.]+%.[^"]+)"')
local newurl2 = part1.."//"..part2.."/"..part3.."/"..part4.."/"..part5
check(newurl2)
end
for newurl2 in string.gmatch(html, '"(%?[^"]+)"') do
if string.match(url, "https?://[^%?]+%?") then
local newurl1 = string.match(url, "(https?://[^%?]+)%?")
local newurl = newurl1..newurl2
check(newurl)
elseif not string.match(url, "https?://[^%?]+%?") then
local newurl1 = url
local newurl = newurl1..newurl2
check(newurl)
end
end
for newurl2 in string.gmatch(html, '"(/[^"]+)"') do
if not string.match(newurl2, "%%") and not string.match(newurl2, "%%25") then
local newurl1 = string.match(url, "(https?://[^/]+)/")
local newurl = newurl1..newurl2
check(newurl)
end
end
if string.match(url, "%.trovebox%.com/p/[0-9a-zA-Z]+") then
local photoid = string.match(url, "%.trovebox%.com/p/([0-9a-zA-Z]+)")
local newurl = "https://"..item_value..".trovebox.com/photo/"..photoid.."/download"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid
check(newurl)
check(newurl3)
for newphotoid in string.gmatch(html, '"id":"([0-9a-zA-Z]+)"') do
local newurl1 = "https://"..item_value..".trovebox.com/p/"..newphotoid
local newurl2 = "https://"..item_value..".trovebox.com/photo/"..newphotoid.."/download"
check(newurl1)
check(newurl2)
end
end
if string.match(url, "%.trovebox%.com/albums/") then
for newalbum in string.gmatch(html, '"id":"([0-9a-zA-Z]+)"') do
local newurl = "https://"..item_value..".trovebox.com/photos/album-"..newalbum.."/list"
local newurl1 = "https://"..item_value..".trovebox.com/photos/page-0/album-"..newalbum.."/list"
local newurl2 = "https://"..item_value..".trovebox.com/photos/album-"..newalbum.."/list?sortBy=dateUploaded,asc"
local newurl3 = "https://"..item_value..".trovebox.com/photos/album-"..newalbum.."/list?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/photos/album-"..newalbum.."/list?sortBy=dateTaken,asc"
local newurl5 = "https://"..item_value..".trovebox.com/photos/album-"..newalbum.."/list?sortBy=dateTaken,desc"
local newurl6 = "https://"..item_value..".trovebox.com/photos/page-0/album-"..newalbum.."/list?sortBy=dateUploaded,asc"
local newurl7 = "https://"..item_value..".trovebox.com/photos/page-0/album-"..newalbum.."/list?sortBy=dateUploaded,asc"
local newurl8 = "https://"..item_value..".trovebox.com/photos/page-0/album-"..newalbum.."/list?sortBy=dateTaken,asc"
local newurl9 = "https://"..item_value..".trovebox.com/photos/page-0/album-"..newalbum.."/list?sortBy=dateTaken,desc"
check(newurl)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
check(newurl5)
check(newurl6)
check(newurl7)
check(newurl8)
check(newurl9)
end
end
if string.match(url, "%.trovebox%.com/photos/tags%-.+") or string.match(url, "%.trovebox%.com/photos/page%-[0-9]+/tags%-.+") then
local part2 = string.match(url, "%.trovebox%.com/photos/tags%-(.+)")
if part2 then
local newurl10 = "https://"..item_value..".trovebox.com/photos/page-0/tags-"..part2
check(newurl10)
end
local tag = string.match(url, "tags%-([^/]+)")
if string.match(url, "/page%-") then
local tags1 = string.match(url, "%.trovebox%.com/photos/(page%-[0-9]+/tags.+)")
local tags = string.gsub(tags1, "/list", "")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z]+)"') do
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateUploaded,desc"
local newurl5 = "https://"..item_value..".trovebox.com/photo/"..photoid.."/download"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
check(newurl5)
end
end
if not string.match(url, "/page%-") then
local tags1 = string.match(url, "%.trovebox%.com/photos/(tags.+)")
local tags = string.gsub(tags1, "/list", "")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z]+)"') do
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..tags.."?sortBy=dateUploaded,desc"
local newurl5 = "https://"..item_value..".trovebox.com/photo/"..photoid.."/download"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
check(newurl5)
end
end
end
if string.match(url, "/photos/") then
for photoid in string.gmatch(url, '"id":"([^"]+)"') do
local newurl1 = "https://"..item_value..".trovebox.com/p/"..newphotoid
local newurl2 = "https://"..item_value..".trovebox.com/photo/"..newphotoid.."/download"
check(newurl1)
check(newurl2)
end
end
if string.match(url, "%.trovebox%.com/photos/album%-[0-9a-zA-Z]+/list") or string.match(url, "%.trovebox%.com/photos/page%-[0-9]+/album%-[0-9a-zA-Z]+/list") then
if string.match(url, "/page%-") then
local albumid1 = string.match(url, "%.trovebox%.com/photos/(page%-[0-9]+/album%-[0-9a-zA-Z]+)")
local albumid = string.gsub(albumid1, "/list", "")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z]+)"') do
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateUploaded,desc"
local newurl5 = "https://"..item_value..".trovebox.com/photo/"..photoid.."/download"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
check(newurl5)
end
elseif not string.match(url, "/page%-") then
local albumid1 = string.match(url, "%.trovebox%.com/photos/(album%-[0-9a-zA-Z]+)")
local albumid = string.gsub(albumid1, "/list", "")
for photoid in string.gmatch(html, '"id":"([0-9a-zA-Z]+)"') do
local newurl = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid
local newurl0 = "https://"..item_value..".trovebox.com/p/"..photoid
local newurl1 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateTaken,asc"
local newurl2 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateTaken,desc"
local newurl3 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateUploaded,asc"
local newurl4 = "https://"..item_value..".trovebox.com/p/"..photoid.."/"..albumid.."?sortBy=dateUploaded,desc"
local newurl5 = "https://"..item_value..".trovebox.com/photo/"..photoid.."/download"
check(newurl)
check(newurl0)
check(newurl1)
check(newurl2)
check(newurl3)
check(newurl4)
check(newurl5)
end
end
end
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
last_http_statcode = status_code
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if (status_code >= 200 and status_code <= 399) then
if string.match(url["url"], "https://") then
local newurl = string.gsub(url["url"], "https://", "http://")
downloaded[newurl] = true
else
downloaded[url["url"]] = true
end
end
if status_code == 500 then
io.stdout:write("Server returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
tries = tries + 1
if tries >= 3 then
io.stdout:write("Skip this url...\n")
io.stdout:flush()
return wget.actions.EXIT
else
return wget.actions.CONTINUE
end
elseif (status_code >= 400 and status_code ~= 404) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 5")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(500, 5000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
|
local M = {
log = {},
}
local function fprintf(level)
return function(format, ...)
if level == "DEBUG" and DEBUG then
io.stderr:write(string.format(level .. ': ' .. format .. '\n', ...))
end
end
end
M.log.error = fprintf 'ERROR'
M.log.debug = fprintf 'DEBUG'
return M
|
local M = {}
M.config = function()
O.lang.css = {
virtual_text = true,
formatter = {
exe = "prettier",
args = {},
},
lsp = {
path = DATA_PATH .. "/lspinstall/css/vscode-css/css-language-features/server/dist/node/cssServerMain.js",
},
}
end
M.format = function()
vim.cmd "let proj = FindRootDirectory()"
local root_dir = vim.api.nvim_get_var "proj"
-- use the global prettier if you didn't find the local one
local prettier_instance = root_dir .. "/node_modules/.bin/prettier"
if vim.fn.executable(prettier_instance) ~= 1 then
prettier_instance = O.lang.tsserver.formatter.exe
end
local ft = vim.bo.filetype
O.formatters.filetype[ft] = {
function()
local args = { "--stdin-filepath", vim.fn.fnameescape(vim.api.nvim_buf_get_name(0)) }
-- TODO: O.lang.[ft].formatter.args
local extend_args = O.lang.css.formatter.args
for i = 1, #extend_args do
table.insert(args, extend_args[i])
end
return {
exe = prettier_instance,
args = args,
stdin = true,
}
end,
}
require("formatter.config").set_defaults {
logging = false,
filetype = O.formatters.filetype,
}
end
M.lint = function()
-- TODO: implement linters (if applicable)
return "No linters configured!"
end
M.lsp = function()
if not require("lv-utils").check_lsp_client_active "cssls" then
local capabilities = vim.lsp.protocol.make_client_capabilities()
capabilities.textDocument.completion.completionItem.snippetSupport = true
-- npm install -g vscode-css-languageserver-bin
require("lspconfig").cssls.setup {
cmd = {
"node",
O.lang.css.lsp.path,
"--stdio",
},
on_attach = require("lsp").common_on_attach,
capabilities = capabilities,
}
end
end
M.dap = function()
-- TODO: implement dap
return "No DAP configured!"
end
return M
|
return {
env = env('APP_ENV', 'production'),
locale = 'zh',
fallback_locale = 'en',
time_zone = "+8:00", -- UTC + 8
session_lifetime = 3600 * 24 * 30, --sec, here means a month
session_refresh_time = 3600 * 24 * 7, --sec, here means a week
max_request_per_second = 3000, -- throttle flow request per second
phone_code_len = 4,
per_page = env('per_page', 10),
-- oauth
wechat = {
web = {
app_id = "xxxxxxxxxxx",
secret = "xxxxxxxxxxxxxx",
redirect_uri = "http://api.nana.local"
}
},
sendcloud = {
url = "http://www.sendcloud.net/smsapi/send",
smsUser = env('sendcloud.SMSUSER'),
smsKey = env('sendcloud.SMSKEY'),
templateId = env('sendcloud.TEMPLATEID')
}
}
|
local color_white = Color(255,255,255)
local function give_swep( ply, wepname )
if ( not IsValid( ply ) ) then
return
end
if ( wepname == nil ) then
return
end
if ( not table.HasValue( DM.Config.GreenWeapon, wepname ) ) then
if ( list.Get( 'Weapon' )[ wepname ] and not ply:Admin() ) then
ply:SendLua( 'notification.AddLegacy( "This weapon does not enter into the list of available (only for admins)", NOTIFY_ERROR, 2.5 )' )
ply:EmitSound( 'buttons/blip1.wav' )
return
end
end
ply:Give( wepname )
ply:SelectWeapon( wepname )
end
concommand.Add( 'dm_giveswep', function( ply, cmd, args )
local weapon = args[ 1 ]
give_swep( ply, weapon )
end )
local function change_model( ply, mdlname )
if ( not IsValid( ply ) ) then
return
end
if ( mdlname == nil ) then
return
end
if ( not player_manager.TranslateToPlayerModelName( mdlname ) ) then
return
end
ply:SetModel( mdlname )
end
concommand.Add( 'dm_changemdl', function( ply, cmd, args )
local model = args[ 1 ]
change_model( ply, model )
end )
local function drop_swep( ply, wepname )
if ( not IsValid( ply ) ) then
return
end
if ( wepname == nil ) then
return
end
local weapon = ply:GetWeapon( wepname )
if ( weapon == NULL ) then
return
end
ply:SelectWeapon( weapon )
ply:DoAnimationEvent( ACT_GMOD_GESTURE_ITEM_DROP )
local primAmmo = ply:GetAmmoCount( weapon:GetPrimaryAmmoType() )
local model = ( weapon:GetModel() == 'models/weapons/v_physcannon.mdl' and 'models/weapons/w_physics.mdl' ) or weapon:GetModel()
model = util.IsValidModel( model ) and model or 'models/hunter/blocks/cube025x025x025.mdl'
local ent = ents.Create( 'dm_weapon' )
ent:SetPos( ply:GetShootPos() + ply:GetAimVector() * 30 )
ent:SetModel( model )
ent:SetSkin( weapon:GetSkin() or 0 )
ent:SetWeaponClass( weapon:GetClass() )
ent:SetPlayer( ply )
ent:SetOverlayText( wepname )
ent.nodupe = true
ent.clip1 = weapon:Clip1()
ent.clip2 = weapon:Clip2()
ent.ammoadd = primAmmo
ply:RemoveAmmo( primAmmo, weapon:GetPrimaryAmmoType() )
ply:RemoveAmmo( ply:GetAmmoCount( weapon:GetSecondaryAmmoType() ), weapon:GetSecondaryAmmoType() )
ent:Spawn()
weapon:Remove()
end
concommand.Add( 'dm_dropswep', function( ply, cmd, args )
local weapon = args[ 1 ]
drop_swep( ply, weapon )
end )
local function setRank( ply, user, namerank )
if ( not ply:IsPlayer() or ply:Admin() ) then
local comp
for l, p in pairs( player.GetAll() ) do
if ( p:SteamID64() == user ) then
comp = p
end
end
if ( comp:IsPlayer() ) then
comp:SetRank( namerank )
comp:DataSave()
sendMsgAll( Color(15,170,235), comp:GetNick(), color_white, ' received the rank ', Color(80,200,140), namerank, color_white, '.' )
end
end
end
concommand.Add( 'dm_setrank', function( ply, cmd, args )
local steamid64 = args[ 1 ]
local rank = args[ 2 ]
setRank( ply, steamid64, rank )
end )
local function setNick( ply, nick )
sendMsgAll( Color(15, 170, 235), ply:GetNick(), color_white, ' changed his nickname to ', Color(90,200,140), nick, color_white, '.' )
ply:SetNick( nick )
end
concommand.Add( 'dm_setnick', function( ply, cmd, args )
local text = args[ 1 ]
if ( string.len( text ) < 3 or string.len( text ) > 20 ) then
sendMsg( ply, color_white, 'Your nick is too ', Color(255,252,96), ( string.len( text ) < 3 and 'short' ) or 'long', color_white, '.' )
return
end
setNick( ply, text )
end )
concommand.Add( 'dm_checkdata', function( ply, cmd, args )
if ( not ply:IsPlayer() ) then
return
end
local Data = {}
Data = ply:DataLoad()
ply:SetNick( Data.name )
ply:SetRank( Data.rank )
ply:SetFrags( Data.frags )
ply:SetDeaths( Data.deaths )
ply:SetModel( Data.model )
sendMsg( ply, color_white, 'Your details have been updated!' )
end )
local function setHP( ply, user, health )
if ( not ply:IsPlayer() or ply:Admin() ) then
local comp
for l, p in pairs( player.GetAll() ) do
if ( p:SteamID64() == user ) then
comp = p
end
end
if ( comp:IsPlayer() ) then
comp:SetHealth( health )
sendMsgAll( Color(202, 68, 68), '[', color_white, ply:GetNick(), Color(202, 68, 68), '] ', color_white, 'Installed ', Color(102, 95, 180), tonumber( health ) .. '%', color_white, ' health for the player ', Color(102, 95, 180), comp:GetNick(), color_white, '.' )
end
end
end
concommand.Add( 'dm_sethp', function( ply, cmd, args )
local steamid64 = args[ 1 ]
local hp = args[ 2 ]
setHP( ply, steamid64, hp )
end )
local function PM( ply, user, msg )
local comp
for l, p in pairs( player.GetAll() ) do
if ( p:SteamID64() == user ) then
comp = p
end
end
if ( comp:IsPlayer() ) then
if ( string.len( msg ) > 35 or string.len( msg ) <= 0 ) then
sendMsg( comp, Color(253,202,62), 'The message does not match the size (from 1 to 35)' )
return
end
sendMsg( comp, Color(215,125,60), '(PM) ', Color(85,130,158), ply:GetNick(), color_white, ': ' .. msg )
if ( comp == ply ) then
return
end
sendMsg( ply, Color(215,125,60), '(PM --> ', Color(85,130,158), ply:GetNick(), Color(215,125,60), ') ', color_white, msg )
end
end
concommand.Add( 'dm_pm', function( ply, cmd, args )
local steamid64 = args[ 1 ]
local msg = args[ 2 ]
PM( ply, steamid64, msg )
end )
local function setScale( ply, user, scale )
if ( not ply:IsPlayer() or ply:Admin() ) then
local comp
for l, p in pairs( player.GetAll() ) do
if ( p:SteamID64() == user ) then
comp = p
end
end
if ( comp:IsPlayer() ) then
local target_scale = comp:GetModelScale()
comp:SetModelScale( target_scale * scale, 0 )
comp:SetViewOffset( Vector( 0, 0, 64 ) * scale )
comp:SetViewOffsetDucked( Vector( 0, 0, 28 ) * scale )
sendMsgAll( Color(202,68,68), '[', color_white, ply:GetNick(), Color(202,68,68), '] ', color_white, 'Resized player ', Color(102,95,180), comp:GetNick(), color_white, ' to ', Color(102,95,180), tostring( scale ), color_white, '.' )
end
end
end
concommand.Add( 'dm_setscale', function( ply, cmd, args )
local steamid64 = args[ 1 ]
local scale = args[ 2 ]
setScale( ply, steamid64, scale )
end )
local function resetScore( ply, user )
if ( not ply:IsPlayer() or ply:Admin() ) then
local comp
for l, p in pairs( player.GetAll() ) do
if ( p:SteamID64() == user ) then
comp = p
end
end
if ( comp:IsPlayer() ) then
local Data = {}
Data = comp:DataLoad()
comp:SetFrags( 0 )
comp:SetDeaths( 0 )
comp:DataSave()
end
end
end
concommand.Add( 'dm_resetscore', function( ply, cmd, args )
local steamid64 = args[ 1 ]
resetScore( ply, steamid64 )
end )
|
local ffi = require 'ffi'
local libpath = package.searchpath('libvisinf', package.cpath)
if not libpath then return end
require 'cunn'
ffi.cdef[[
void SpatialStochasticPooling_updateOutput(THCState* state, THCudaTensor* input,
THCudaTensor* output, THCudaTensor* indices, int kW, int kH, int dW, int dH, bool train);
void SpatialStochasticPooling_updateGradInput(THCState* state, THCudaTensor* input,
THCudaTensor* gradInput, THCudaTensor* gradOutput, THCudaTensor* indices, int kW, int kH, int dW, int dH);
void SpatialInverseBilateralPooling_updateOutput(THCState* state, THCudaTensor* I, THCudaTensor* It, THCudaTensor* lambda, THCudaTensor* alpha,
THCudaTensor* output, int kW, int kH, int dW, int dH);
void SpatialInverseBilateralPooling_updateGradInput(THCState* state, THCudaTensor* I, THCudaTensor* It, THCudaTensor* lambda, THCudaTensor* alpha,
THCudaTensor* gradI, THCudaTensor* gradIt, THCudaTensor* gradOutput, int kW, int kH, int dW, int dH);
void SpatialInverseBilateralPooling_accGradParameters(THCState* state, THCudaTensor* I,THCudaTensor* It, THCudaTensor* lambda,THCudaTensor* alpha,
THCudaTensor* lambda_gradient, THCudaTensor* alpha_gradient, THCudaTensor* gradOutput, int kW, int kH, int dW, int dH);
]]
return ffi.load(libpath)
|
-- ============================= --
-- Copyright 2019 FiatAccompli --
-- ============================= --
-- Doing this with a ReplaceInGame script replacement rather than replacing InGame.lua
-- because I like to play nice and this way it's compatible with anything that
-- replaces InGame.xml (e.g. CQUI and base game expansions).
-- ===========================================================================
-- Base File
-- ===========================================================================
include("InGame");
function UIPluginsReplacementInitialize()
for _, addin in ipairs(Modding.GetUserInterfaces("InGame_Screen")) do
print("Loading InGame_Screen UI - " .. addin.ContextPath);
local id = addin.ContextPath:sub( -(string.find( string.reverse(addin.ContextPath), '/') - 1) ); -- grab id from end of path
local newContext = ContextPtr:LoadNewContext(addin.ContextPath, Controls.Screens, id, true);
end
for _, addin in ipairs(Modding.GetUserInterfaces("InGame_PartialScreen")) do
print("Loading InGame_PartialScreen UI - " .. addin.ContextPath);
local id = addin.ContextPath:sub( -(string.find( string.reverse(addin.ContextPath), '/') - 1) ); -- grab id from end of path
local newContext = ContextPtr:LoadNewContext(addin.ContextPath, Controls.PartialScreens, id, true);
end
-- Put the partial screen hooks toolbar back on top of any plugin screens.
-- And the same for the production panel so it goes on top of the partial
-- screen hooks.
Controls.PartialScreenHooks:Reparent();
Controls.ProductionPanel:Reparent();
end
UIPluginsReplacementInitialize();
|
--
-- lcd_aqm0802a.lua
--
-- how to use
--
-- lcd_setup()
-- lcd_print("ABCDEFGH01234567")
--
-- https://github.com/nodemcu/nodemcu-firmware/wiki/nodemcu_api_en#new_gpio_map
i2c_scl = 2 -- IO4
i2c_sda = 1 -- IO5
-- AQM0802A - http://akizukidenshi.com/catalog/g/gP-06669/
i2c_dev_addr = 0x3e
i2c_id = 0
i2c.setup(i2c_id, i2c_sda, i2c_scl, i2c.SLOW)
function lcd_data(c, d)
i2c.start(i2c_id)
i2c.address(i2c_id, i2c_dev_addr , i2c.TRANSMITTER)
i2c.write(i2c_id, c)
i2c.write(i2c_id, d)
i2c.stop(i2c_id)
end
function lcd_cmd(d)
lcd_data(0x00, d);
end
function lcd_char(d)
lcd_data(0x40, d);
end
function lcd_setup()
-- http://maicommon.ciao.jp/ss/Arduino_g/LCD_I2C/index.htm
lcd_cmd(0x38)
lcd_cmd(0x39)
lcd_cmd(0x14)
lcd_cmd(0x70)
lcd_cmd(0x56)
lcd_cmd(0x6c)
lcd_cmd(0x38)
lcd_cmd(0x0c)
lcd_clear()
end
function lcd_clear()
lcd_cmd(0x01)
end
function lcd_move_cursor(x, y)
if y == 0 then
lcd_cmd(0x80 + x)
elseif y == 1 then
lcd_cmd(0xc0 + x)
end
end
function lcd_print(str)
lcd_move_cursor(0, 0)
if str == nil then
lcd_clear();
return
end
if string.len(str) == 0 then
lcd_clear();
return
end
for i = 1, string.len(str) do
lcd_char(str:byte(i))
if i == 8 then
lcd_move_cursor(0, 1)
end
end
end
|
data:extend(
{
{
type = "recipe",
name = "shaft-mine",
enabled = true,
ingredients =
{
{"electric-mining-drill", 5},
{"steel-plate", 25},
{"electronic-circuit", 20},
{"stone-brick", 100},
},
result = "shaft-mine",
energy_required = 10,
},
{
type = "item",
name = "shaft-mine",
icon = "__Clowns-Extended-Minerals__/graphics/icons/shaft-mine.png",
icon_size = 32,
subgroup = "extraction-machine",
order = "a[items]-m[shaft-mine]",
place_result = "shaft-mine",
stack_size = 20,
},
{
type = "assembling-machine",
name = "shaft-mine",
fast_replaceable_group = "shaft-mine",
icon = "__Clowns-Extended-Minerals__/graphics/icons/shaft-mine.png",
icon_size = 32,
flags = {"placeable-neutral", "placeable-player", "player-creation"},
minable = {hardness = 0.8, mining_time = 1.2, result = "shaft-mine"},
max_health = 500,
corpse = "medium-remnants",
dying_explosion = "medium-explosion",
resistances =
{
{
type = "fire",
percent = 70
}
},
collision_box = {{-3.4, -3.4}, {3.4, 3.4}},
selection_box = {{-3.5, -3.5}, {3.5, 3.5}},
animation =
{
filename = "__Clowns-Extended-Minerals__/graphics/entity/shaft-mine.png",
priority = "high",
width = 288,
height = 288,
frame_count = 1,
line_length = 1,
animation_speed = 0.8,
shift = {1,-0.5}
},
crafting_categories = {"shaft-mining", "ore-sorting-t1"},
crafting_speed = 1, --* settings.startup["shaft-mine-crafting-speed"].value,
module_specification =
{
module_slots = 3
},
allowed_effects = {"consumption", "speed", "pollution"},
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
emissions = 0.1
},
energy_usage = "325kW", --1.5MW for 4
ingredient_count = 1, --?????
open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
working_sound =
{
sound =
{
{
filename = "__base__/sound/assembling-machine-t1-1.ogg",
volume = 0.8
},
{
filename = "__base__/sound/assembling-machine-t1-2.ogg",
volume = 0.8
},
},
idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 },
apparent_volume = 1.5,
}
}
}
)
|
-- minetest/dye/init.lua
-- To make recipes that will work with any dye ever made by anybody, define
-- them based on groups.
-- You can select any group of groups, based on your need for amount of colors.
-- basecolor: 9, excolor: 17, unicolor: 89
--
-- Example of one shapeless recipe using a color group:
-- Note: As this uses basecolor_*, you'd need 9 of these.
-- minetest.register_craft({
-- type = "shapeless",
-- output = '<mod>:item_yellow',
-- recipe = {'<mod>:item_no_color', 'group:basecolor_yellow'},
-- })
-- Other mods can use these for looping through available colors
local dye = {}
dye.basecolors = {"white", "grey", "black", "red", "yellow", "green", "cyan", "blue", "magenta"}
dye.excolors = {"white", "lightgrey", "grey", "darkgrey", "black", "red", "orange", "yellow", "lime", "green", "aqua", "cyan", "sky_blue", "blue", "violet", "magenta", "red_violet"}
-- Base color groups:
-- - basecolor_white
-- - basecolor_grey
-- - basecolor_black
-- - basecolor_red
-- - basecolor_yellow
-- - basecolor_green
-- - basecolor_cyan
-- - basecolor_blue
-- - basecolor_magenta
-- Extended color groups (* = equal to a base color):
-- * excolor_white
-- - excolor_lightgrey
-- * excolor_grey
-- - excolor_darkgrey
-- * excolor_black
-- * excolor_red
-- - excolor_orange
-- * excolor_yellow
-- - excolor_lime
-- * excolor_green
-- - excolor_aqua
-- * excolor_cyan
-- - excolor_sky_blue
-- * excolor_blue
-- - excolor_violet
-- * excolor_magenta
-- - excolor_red_violet
-- The whole unifieddyes palette as groups:
-- - unicolor_<excolor>
-- For the following, no white/grey/black is allowed:
-- - unicolor_medium_<excolor>
-- - unicolor_dark_<excolor>
-- - unicolor_light_<excolor>
-- - unicolor_<excolor>_s50
-- - unicolor_medium_<excolor>_s50
-- - unicolor_dark_<excolor>_s50
-- Local stuff
local dyelocal = {}
-- This collection of colors is partly a historic thing, partly something else.
dyelocal.dyes = {
{"white", "White dye", {dye=1, basecolor_white=1, excolor_white=1, unicolor_white=1}},
{"grey", "Grey dye", {dye=1, basecolor_grey=1, excolor_grey=1, unicolor_grey=1}},
{"dark_grey", "Dark grey dye", {dye=1, basecolor_grey=1, excolor_darkgrey=1, unicolor_darkgrey=1}},
{"black", "Black dye", {dye=1, basecolor_black=1, excolor_black=1, unicolor_black=1}},
{"violet", "Violet dye", {dye=1, basecolor_magenta=1, excolor_violet=1, unicolor_violet=1}},
{"blue", "Blue dye", {dye=1, basecolor_blue=1, excolor_blue=1, unicolor_blue=1}},
{"cyan", "Cyan dye", {dye=1, basecolor_cyan=1, excolor_cyan=1, unicolor_cyan=1}},
{"dark_green", "Dark green dye",{dye=1, basecolor_green=1, excolor_green=1, unicolor_dark_green=1}},
{"green", "Green dye", {dye=1, basecolor_green=1, excolor_green=1, unicolor_green=1}},
{"yellow", "Yellow dye", {dye=1, basecolor_yellow=1, excolor_yellow=1, unicolor_yellow=1}},
{"brown", "Brown dye", {dye=1, basecolor_yellow=1, excolor_orange=1, unicolor_dark_orange=1}},
{"orange", "Orange dye", {dye=1, basecolor_orange=1, excolor_orange=1, unicolor_orange=1}},
{"red", "Red dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_red=1}},
{"magenta", "Magenta dye", {dye=1, basecolor_magenta=1, excolor_red_violet=1,unicolor_red_violet=1}},
{"pink", "Pink dye", {dye=1, basecolor_red=1, excolor_red=1, unicolor_light_red=1}},
}
-- Define items
for _, row in ipairs(dyelocal.dyes) do
local name = row[1]
local description = row[2]
local groups = row[3]
local item_name = "dye:"..name
local item_image = "dye_"..name..".png"
minetest.register_craftitem(item_name, {
inventory_image = item_image,
description = description,
groups = groups
})
minetest.register_craft({
type = "shapeless",
output = item_name.." 4",
recipe = {"group:flower,color_"..name},
})
end
-- Mix recipes
-- Just mix everything to everything somehow sanely
dyelocal.mixbases = {"magenta", "red", "orange", "brown", "yellow", "green", "dark_green", "cyan", "blue", "violet", "black", "dark_grey", "grey", "white"}
dyelocal.mixes = {
-- magenta, red, orange, brown, yellow, green, dark_green, cyan, blue, violet, black, dark_grey, grey, white
white = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "violet", "grey", "grey", "white", "white"},
grey = {"pink", "pink", "orange", "orange", "yellow", "green", "green", "grey", "cyan", "pink", "dark_grey","grey", "grey"},
dark_grey={"brown","brown", "brown", "brown", "brown","dark_green","dark_green","blue","blue","violet","black", "black"},
black = {"black", "black", "black", "black", "black", "black", "black", "black", "black", "black", "black"},
violet= {"magenta","magenta","red", "brown", "red", "cyan", "brown", "blue", "violet","violet"},
blue = {"violet", "magenta","brown","brown","dark_green","cyan","cyan", "cyan", "blue"},
cyan = {"blue","brown","dark_green","dark_grey","green","cyan","dark_green","cyan"},
dark_green={"brown","brown","brown", "brown", "green", "green", "dark_green"},
green = {"brown", "yellow","yellow","dark_green","green","green"},
yellow= {"red", "orange", "yellow","orange", "yellow"},
brown = {"brown", "brown","orange", "brown"},
orange= {"red", "orange","orange"},
red = {"magenta","red"},
magenta={"magenta"},
}
for one,results in pairs(dyelocal.mixes) do
for i,result in ipairs(results) do
local another = dyelocal.mixbases[i]
minetest.register_craft({
type = "shapeless",
output = 'dye:'..result..' 2',
recipe = {'dye:'..one, 'dye:'..another},
})
end
end
-- Hide dyelocal
dyelocal = nil
-- EOF
|
local class = require "ecs.common.class"
local entity_mgr = require "ecs.src.entity_mgr"
local mt = class("entity_mgr")
function mt:on_new(name)
if mt.active == nil then
mt.active = self
end
self.name = name
self.systems = {}
self.entity_mgr = entity_mgr:new()
end
function mt:add_system(sys)
assert(sys.on_update, "has not defind 'on_update' method in system!")
self.systems[#self.systems + 1] = sys
if sys.add_to_world then
sys:add_to_world(self)
end
end
function mt:update(dt)
for i,sys in ipairs(self.systems) do
sys:on_update(dt)
end
end
return mt
|
--[[
Description
Auto4 script written in Lua for subtitle editor Aegisub.
Purpose is stated in the "script_description" variable. If you wonder why all the hassle with alignment etc., then the answer for you is this: because this way subs look more professional, as well as easier to read, at least for those accustomed to this kind of layout.
]]--
include("karaskel.lua")
script_name = "Reformat selected collisions"
script_description = "Reformats selected collisions by joining two selected subs \nand aligning them in a special way: by the left side inside bounding box, \nand their bounding box by the center of the video (script resolution)"
script_author = "8day"
script_version = "1.1.1"
script_modified = "27.12.2013"
-- GUI config.
function create_config()
return {
-- Checkboxes.
{
class = "checkbox", name = "right_to_left",
label = "Right-to-left &writing style",
x = 0, y = 0, width = 2, height = 1,
value = false
},
{
class = "checkbox", name = "differentiate_styles",
label = "&Differentiate styles",
x = 0, y = 1, width = 2, height = 1,
value = true
},
-- Text to be added to the beginning of subtitles.
{
class = "label",
x = 0, y = 2, width = 2, height = 1,
label = "&Beginning of the 1-st and 2-nd subs:"
},
{
class = "edit", name = "sub1beg",
x = 0, y = 3, width = 1, height = 1,
hint = "Text to be added to the beginning of the first subtitle", text = "— "
},
{
class = "edit", name = "sub2beg",
x = 1, y = 3, width = 1, height = 1,
hint = "Text to be added to the beginning of the second subtitle", text = "— "
},
-- Text to be added to the end of subtitles.
{
class = "label",
x = 0, y = 4, width = 2, height = 1,
label = "&End of the 1-st and 2-nd subs:"
},
{
class = "edit", name = "sub1fin",
x = 0, y = 5, width = 1, height = 1,
hint = "Text to be added to the end of the first subtitle", text = ""
},
{
class = "edit", name = "sub2fin",
x = 1, y = 5, width = 1, height = 1,
hint = "Text to be added to the end of the second subtitle", text = ""
},
}
end
-- Checks whether specified object is inside table (here -- data).
function object_is_inside(data, object)
for i = 1, #data do
if data[object] then return true end
end
return false
end
-- Searches idx of the final "Style"-descriptor line in "[V4+ Styles]".
function last_style_idx(subs)
local last_line, last_style_line
for i = 1, #subs do
last_line = i
if subs[i].class == "head" and subs[i].section == "[V4+ Styles]" then
-- Implicitly assumes that there is at least one style definition.
for j = last_line + 1, #subs do
if subs[j].class == "style" then last_style_line = j end
end
break
end
end
return last_style_line
end
-- Main abracadabra.
function process(subs, sel, config)
-- Initialize vars for the l-to-r system of writing.
local sub1beg, sub2beg, sub1fin, sub2fin
local an, margin
sub1beg, sub2beg = config.sub1beg, config.sub2beg
sub1fin, sub2fin = config.sub1fin, config.sub2fin
an = {top = {beg=7, center=8, fin=9},
mid = {beg=4, center=5, fin=6},
bot = {beg=1, center=2, fin=3}}
margin = "margin_l"
-- If chosen in GUI, reconfig settings to r-to-l system of writing.
if config.right_to_left then
-- Doesn't need reversing of characters because r-to-l users
-- will take this into account: they'll specify them in the correct order.
local temp1, temp2
temp1, temp2 = sub1beg, sub2beg
sub1beg, sub2beg = sub1fin, sub2fin
sub1fin, sub2fin = temp1, temp2
for k, v in pairs(an) do
an[k].beg, an[k].fin = an[k].fin, an[k].beg
end
margin = "margin_r"
end
-- Get the width of subs and script. Also get access to styles.
local meta, styles
local fst, snd
local fst_width, snd_width, script_width, widest_sub_width
meta, styles = karaskel.collect_head(subs, false)
fst, snd = subs[sel[1]], subs[sel[2]]
karaskel.preproc_line_text(meta, styles, fst)
karaskel.preproc_line_text(meta, styles, snd)
fst_width = aegisub.text_extents(styles[fst.style], sub1beg .. fst.text_stripped .. sub1fin)
snd_width = aegisub.text_extents(styles[snd.style], sub2beg .. snd.text_stripped .. sub2fin)
script_width = meta.res_x
-- Check whether text width is not exceeding script width.
if fst_width >= script_width or snd_width >= script_width then
aegisub.progress.title("Error")
aegisub.debug.out(string.format("Either width of selected subtitles is too big or " ..
"width of the script is too small (i.e. not set at all).\nScript width (PlayResX): %d;\n" ..
"First subtitle width: %f;\nSecond subtitle width: %f.", script_width, fst_width, snd_width))
return false
else
if fst_width > snd_width then
widest_sub_width = fst_width
else
widest_sub_width = snd_width
end
end
-- Create collision style.
-- Since joining of already joined subs is meaningless,
-- check for "style_name.collision(.collision)+" is absent.
local lines_shifting = 0
if not object_is_inside(styles, fst.style .. ".collision") then
local style
style = table.copy_deep(styles[fst.style])
style.name = style.name .. ".collision"
for k, v in pairs(an) do
for m, n in pairs(v) do
if style.align == an[k][m] then
style.align = an[k].beg
break
end
end
end
style.margin_l = 0
style.margin_r = 0
subs.insert(last_style_idx(subs) + 1, style)
-- Addition of new styles shifts subs idxs!
-- BTW, ATM "lines_shifting + 1" is somewhat stupid, but
-- later on when I'll write automated collision detection (hopefully),
-- it'll help to avoid this bug right from the beginning.
lines_shifting = lines_shifting + 1
end
-- Join subs.
if config.differentiate_styles and (fst.style ~= snd.style) then
fst.text = string.format("%s%s%s\\N{\\r%s}%s%s%s", sub1beg, fst.text, sub1fin, snd.style, sub2beg, snd.text, sub2fin)
else
fst.text = string.format("%s%s%s\\N%s%s%s", sub1beg, fst.text, sub1fin, sub2beg, snd.text, sub2fin)
end
-- Do some final job.
fst[margin] = math.floor((script_width - widest_sub_width) / 2)
fst.style = fst.style .. ".collision"
if fst.end_time < snd.end_time then fst.end_time = snd.end_time end
subs[sel[1] + lines_shifting] = fst
subs.delete(sel[2] + lines_shifting)
return true
end
-- Main.
function macro(subs, sel)
-- Check whether at least two lines were selected.
if #sel ~= 2 then
aegisub.progress.title("Error")
aegisub.debug.out(string.format("You should choose exactly two subtitles, not %d!", #sel))
return false
else
local button, config
repeat
button, config = aegisub.dialog.display(create_config(), {"&Process", "&Cancel"})
until true
if button == "&Process" then
if process(subs, sel, config) then aegisub.set_undo_point("\"" .. script_name .. "\"") end
end
end
end
aegisub.register_macro(script_name, script_description, macro)
|
modifier_boss_charger_trampling = class(ModifierBaseClass)
function modifier_boss_charger_trampling:OnCreated (keys)
self:StartIntervalThink(0.01)
end
function modifier_boss_charger_trampling:OnIntervalThink()
local charger = self:GetCaster()
local hero = self:GetParent()
if not hero or not hero.SetAbsOrigin then
return
end
if not charger:HasModifier('modifier_boss_charger_charge') and not charger:HasModifier('modifier_boss_charger_charge_tier5') then
self:StartIntervalThink(-1)
self:Destroy()
FindClearSpaceForUnit(hero, hero:GetAbsOrigin(), false)
return
end
hero:SetAbsOrigin(charger:GetAbsOrigin())
end
|
bh_untrained_wielder_of_the_dark_side = Creature:new {
objectName = "@mob/creature_names:untrained_wielder_of_the_dark_side",
randomNameType = NAME_GENERIC,
randomNameTag = true,
socialGroup = "kun",
faction = "",
level = 250,
chanceHit = 0.6,
damageMin = 545,
damageMax = 800,
baseXp = 6288,
baseHAM = 11000,
baseHAMmax = 14000,
armor = 1,
resists = {80,80,60,60,60,60,60,60,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = AIENABLED,
diet = HERBIVORE,
templates = {"object/mobile/dressed_untrained_wielder_of_the_darkside.iff"},
lootGroups = {
{
groups = {
{group = "tierone", chance = 2500000},
{group = "tiertwo", chance = 500000},
{group = "tierthree", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 1000000},
{group = "tierdiamond", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 10000000
},
{
groups = {
{group = "tierone", chance = 2500000},
{group = "tiertwo", chance = 500000},
{group = "tierthree", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 1000000},
{group = "tierdiamond", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 8000000
},
{
groups = {
{group = "junk", chance = 2500000},
{group = "tailor_components", chance = 500000},
{group = "loot_kit_parts", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "power_crystals", chance = 500000},
{group = "power_crystals", chance = 500000},
{group = "wearables_all", chance = 1000000},
{group = "weapons_all", chance = 1000000},
{group = "armor_all", chance = 1000000},
{group = "clothing_attachments", chance = 1000000},
{group = "armor_attachments", chance = 1000000}
},
lootChance = 5000000
}
},
weapons = {"mixed_force_weapons"},
conversationTemplate = "",
attacks = merge(pikemanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(bh_untrained_wielder_of_the_dark_side, "bh_untrained_wielder_of_the_dark_side")
|
local _, L = ...
local Timer, GetTime = CreateFrame('Frame'), GetTime
-- Borrowed fixes from Storyline :)
local LINE_FEED_REPLACE, LINE_BREAK_REPLACE
do local LINE_FEED, CARRIAGE_RETURN = string.char(10), string.char(13)
LINE_FEED_REPLACE = LINE_FEED .. '+'
LINE_BREAK_REPLACE = LINE_FEED .. CARRIAGE_RETURN .. LINE_FEED
end
local TEXT_TIME_DIVISOR -- set later as baseline divisor for (text length / time).
local TEXT_TIME_PADDING = 2 -- static padding, feels more natural with a pause to breathe.
local MAX_UNTIL_SPLIT = 200 -- start recursive string splitting if the text is too long.
Timer.Texts = {}
L.TextMixin = {}
local Text = L.TextMixin
----------------------------------
-- Text: manage text input
----------------------------------
function Text:SetText(text)
TEXT_TIME_DIVISOR = L('delaydivisor')
self:PreparePlayback()
self.storedText = text
if text then
local timeToFinish, strings, timers = self:CreateLineData(text)
self.numTexts = #strings
self.timeToFinish = timeToFinish
self.timeStarted = GetTime()
self:QueueTexts(strings, timers)
end
end
function Text:ReplaceLinefeed(text)
return text:gsub(LINE_FEED_REPLACE, '\n'):gsub(LINE_BREAK_REPLACE, '\n')
end
function Text:ReplaceNatural(str)
local new = str -- substitute natural breaks with newline.
:gsub('%.%s%.%s%.', '...') -- ponder special case
:gsub('%.%s+', '.\n') -- sentence
:gsub('%.%.%.\n', '...\n...') -- ponder
:gsub('%!%s+', '!\n') -- exclamation
:gsub('%?%s+', '?\n') -- question
return new, (new == str) -- return new string, and whether something changed
end
function Text:CreateLineData(text)
text = self:ReplaceLinefeed(text)
local timeToFinish, strings, timers = 0, {}, {}
for _, paragraph in ipairs({strsplit('\n', text)}) do
timeToFinish = timeToFinish + self:AddString(paragraph, strings, timers)
end
return timeToFinish, strings, timers
end
function Text:CalculateLineTime(length)
return (length / (TEXT_TIME_DIVISOR or 15) ) + TEXT_TIME_PADDING
end
function Text:AddString(str, strings, timers)
local length, timer, new, forceShow = str:len(), 0
if length > MAX_UNTIL_SPLIT then
new, forceShow = self:ReplaceNatural(str)
--[[ If the string is unchanged, this will recurse infinitely, therefore
force the long string to be shown. This safeguard is probably meaningless,
as it requires 200+ chars without any punctuation. ]]
if not forceShow then -- recursively split the altered string
for _, sentence in ipairs({strsplit('\n', new)}) do
timer = timer + self:AddString(sentence, strings, timers)
end
return timer
end
end
if ( length ~= 0 or forceShow ) then
timer = self:CalculateLineTime(length)
timers[ #strings + 1] = timer
strings[ #strings + 1 ] = str
end
return timer
end
----------------------------------
-- Text: playback
----------------------------------
function Text:QueueTexts(strings, timers)
assert(strings, 'No strings added to object '.. ( self:GetName() or '<unnamed fontString>' ) )
assert(timers, 'No timers added to object '.. ( self:GetName() or '<unnamed fontString>' ) )
self.strings = strings
self.timers = timers
Timer:AddText(self)
end
function Text:ForceNext()
if self:HasLineData() then
local _, remainingLineTime = self:RemoveLine()
self.timeToFinish = self.timeToFinish - remainingLineTime
if self:HasLine() then
self:SetToCurrentLine()
else
self:PauseTimer()
self:RepeatTexts()
self:FlagForceFinished(true)
end
if not self:HasFollowup() then
self:OnFinished()
self:FlagForceFinished(true)
end
end
end
function Text:SetToCurrentLine()
self:DisplayLine(self:GetLine())
end
function Text:SetCurrentLineTime(time)
self.currentLineTime = time or 0
end
function Text:UpdateCurrentLineTime(delta)
self.timers[1] = self.timers[1] + delta
end
function Text:RepeatTexts()
if self.storedText then
self:SetText(self.storedText)
end
end
function Text:OnFinished()
self.strings = nil
self.timers = nil
end
function Text:FlagForceFinished(state)
self.forceFinished = state
end
function Text:IsForceFinishedFlagged()
return self.forceFinished
end
function Text:PreparePlayback()
self.numTexts = nil
self:FlagForceFinished(false)
self:PauseTimer()
self:OnFinished()
self:DisplayLine()
end
function Text:ResumeTimer()
if self:HasLineData() then
Timer:AddText(self)
return true
end
end
function Text:PauseTimer()
Timer:RemoveText(self)
end
----------------------------------
-- Text: display
----------------------------------
function Text:DisplayLine(text, time)
if not self:GetFont() then
self:CheckApplicableFonts()
self:SetFontObject(self.fontObjectsToTry[1])
end
getmetatable(self).__index.SetText(self, text)
self:SetCurrentLineTime(time)
self:ApplyFontObjects()
if self.OnDisplayLineCallback then
self:OnDisplayLineCallback(text, time)
end
end
function Text:SetFontObjectsToTry(...)
self.fontObjectsToTry = { ... }
if self:GetText() then
self:ApplyFontObjects()
end
end
function Text:ApplyFontObjects()
self:CheckApplicableFonts()
for i, fontObject in ipairs(self.fontObjectsToTry) do
self:SetFontObject(fontObject)
if not self:IsTruncated() then
break
end
end
end
function Text:CheckApplicableFonts()
if not self.fontObjectsToTry or not self.fontObjectsToTry[1] then
error('No fonts applied to TextMixin, call SetFontObjectsToTry first')
end
end
----------------------------------
-- Text: state getters
----------------------------------
function Text:GetTimeRemaining()
if self.timeStarted and self.timeToFinish then
local difference = ( self.timeStarted + self.timeToFinish ) - GetTime()
return difference < 0 and 0 or difference
end
return 0
end
function Text:GetProgress()
local full = self:GetNumTexts()
local remaining = self:GetNumRemaining()
return ('%d/%d'):format(full - remaining + 1, full)
end
function Text:GetProgressPercent()
if self.timeStarted and self.timeToFinish then
local progress = ( GetTime() - self.timeStarted ) / self.timeToFinish
return ( progress > 1 ) and 1 or progress
end
return 1
end
function Text:GetCurrentProgress()
local modifiedTime = self:GetModifiedTime()
local fullTime = self:GetOriginalTime()
if modifiedTime and fullTime and fullTime > 0 then
return (1 - modifiedTime / fullTime)
end
end
function Text:IsFinished() return not self.strings end
function Text:IsSequence() return self.numTexts and self.numTexts > 1 end
function Text:IsLineFinished() return self.timers[1] <= 0 end
function Text:GetNumTexts() return self.numTexts or 0 end
function Text:GetNumRemaining() return self.strings and #self.strings or 0 end
function Text:HasLineData() return self.strings and self.timers end
function Text:HasLine() return self.strings and self.strings[1] and true end
function Text:HasFollowup() return self.strings and self.strings[2] and true end
function Text:GetModifiedTime() return self.timers and self.timers[1] end
function Text:GetOriginalTime() return self.currentLineTime or 0 end
function Text:GetLineProgress() return (self.timers and self.currentLineTime) and (self.timers[1]/self.currentLineTime) or 1 end
function Text:GetLine() return self.strings[1], self.timers[1] end
function Text:RemoveLine() return tremove(self.strings, 1), tremove(self.timers, 1) end
----------------------------------
-- Timer handle
----------------------------------
function Timer:AddText(fontString)
if fontString then
self.Texts[fontString] = true
self:SetScript('OnUpdate', self.OnUpdate)
end
end
function Timer:GetTexts() return pairs(self.Texts) end
function Timer:RemoveText(fontString)
if fontString then
self.Texts[fontString] = nil
end
end
function Timer:OnTextFinished(fontString)
if fontString then
self:RemoveText(fontString)
if fontString.OnFinishedCallback then
fontString:OnFinishedCallback()
end
end
end
function Timer:OnUpdate(elapsed)
for text in self:GetTexts() do
if text:HasLine() then
-- if there's no text displayed, display the current line.
if not text:GetText() then
text:SetToCurrentLine()
end
-- deduct elapsed time since update from current timer
text:UpdateCurrentLineTime(-elapsed)
-- timer is below/equal to zero, move on to next line
if text:IsLineFinished() then
text:RemoveLine()
-- check if there's another line waiting
if text:HasLine() then
text:SetToCurrentLine()
else
text:OnFinished()
end
end
else
self:OnTextFinished(text)
end
end
if not next(self.Texts) then
self:SetScript('OnUpdate', nil)
end
end
|
local objects =
{
--Maxime
createObject ( 14590, 2296.8999, 1706.69995, 1106.19995, 0, 0, 0 ,1 ),
createObject ( 1569, 2299.93311, 1686.09998, 1100.90002 , 0, 0, 0 ,1 ),
createObject ( 1569, 2299.93262, 1686.09961, 1103.40002 , 0, 0, 0 ,1 ),
createObject ( 1569, 2299.80005, 1685.64001, 1105.09998 , 0, 0, 0 ,1 ),
createObject ( 1569, 2295, 1677.77832, 1107.09998, 0, 0, 90 ,1),
createObject ( 1569, 2301.30005, 1676.83997, 1102.90002, 0, 0, 180 ,1),
}
local col = createColSphere(2300.720703125, 1685.6923828125, 1101.9095458984 ,20)
local function watchChanges( )
if getElementDimension( getLocalPlayer( ) ) > 0 and getElementDimension( getLocalPlayer( ) ) ~= getElementDimension( objects[1] ) and getElementInterior( getLocalPlayer( ) ) == getElementInterior( objects[1] ) then
for key, value in pairs( objects ) do
setElementDimension( value, getElementDimension( getLocalPlayer( ) ) )
end
elseif getElementDimension( getLocalPlayer( ) ) == 0 and getElementDimension( objects[1] ) ~= 65535 then
for key, value in pairs( objects ) do
setElementDimension( value, 65535 )
end
end
end
addEventHandler( "onClientColShapeHit", col,
function( element )
if element == getLocalPlayer( ) then
addEventHandler( "onClientRender", root, watchChanges )
end
end
)
addEventHandler( "onClientColShapeLeave", col,
function( element )
if element == getLocalPlayer( ) then
removeEventHandler( "onClientRender", root, watchChanges )
end
end
)
-- Put them standby for now.
for key, value in pairs( objects ) do
setElementDimension( value, 65535 )
end
for index, object in ipairs ( objects ) do
setElementDoubleSided ( object, true )
--setElementCollisionsEnabled ( object, true )
end
|
local log = require "dm.log"
local job = require "dm.job"
-- Default configuration for the source.
local defaults = {
-- Maximum number of issues to fetch.
limit = 100,
}
local source = {}
source.__index = source
function source:new()
return setmetatable({
cache = {},
}, self)
end
-- Check whether the source is available or not.
---@return boolean
function source:is_available()
return vim.bo.filetype == "gitcommit"
end
-- Return a list of characters which will trigger the source completion.
---@return string[]
function source:get_trigger_characters()
return { "#" }
end
-- Invoke completion.
function source:complete(params, callback)
params.option = vim.tbl_deep_extend("keep", params.option, defaults)
local bufnr = vim.api.nvim_get_current_buf()
if self.cache[bufnr] then
callback { items = self.cache[bufnr], isIncomplete = false }
else
job {
cmd = "gh",
args = {
"issue",
"list",
"--limit",
params.option.limit,
"--json",
"title,number,body",
},
on_exit = function(result)
local ok, parsed = pcall(vim.json.decode, result.stdout)
if not ok then
log.fmt_error("Failed to parse `gh` result: %s", parsed)
return
end
local items = {}
for _, issue in ipairs(parsed) do
issue.body = issue.body and issue.body:gsub("\r", "") or ""
table.insert(items, {
label = ("#%s"):format(issue.number),
documentation = {
kind = "markdown",
value = ("# %s\n\n%s"):format(issue.title, issue.body),
},
})
end
callback { items = items, isIncomplete = false }
self.cache[bufnr] = items
end,
}
end
end
-- Register the source with `nvim-cmp`.
require("cmp").register_source("gh_issue", source:new())
|
project "signtool"
uuid "89b3630f-5728-4902-8258-d4dbc532e185"
language "C++"
location ( "../../build/" .. mpt_projectpathname )
vpaths { ["*"] = "../../" }
mpt_projectname = "singtool"
dofile "../../build/premake/premake-defaults-EXE.lua"
dofile "../../build/premake/premake-defaults.lua"
includedirs {
"../../common",
"../../include",
"../../include/nlohmann-json/include",
"$(IntDir)/svn_version",
"../../build/svn_version",
}
files {
"../../common/*.cpp",
"../../common/*.h",
"../../misc/*.cpp",
"../../misc/*.h",
"../../installer/signtool/*.cpp",
"../../installer/signtool/*.h",
}
defines { "MODPLUG_TRACKER", "MPT_BUILD_SIGNTOOL" }
largeaddressaware ( true )
characterset "Unicode"
warnings "Extra"
links {
"portaudio",
"rtaudio",
}
filter {}
prebuildcommands { "..\\..\\build\\svn_version\\update_svn_version_vs_premake.cmd $(IntDir)" }
|
local SEARCH_PROVIDER_LAYOUT = {
{
headerTemplate = "AuctionatorStringColumnHeaderTemplate",
headerParameters = { "price" },
headerText = AUCTIONATOR_L_RESULTS_PRICE_COLUMN,
cellTemplate = "AuctionatorPriceCellTemplate",
cellParameters = { "price" },
},
{
headerTemplate = "AuctionatorStringColumnHeaderTemplate",
headerText = AUCTIONATOR_L_RESULTS_AVAILABLE_COLUMN,
headerParameters = { "quantity" },
cellTemplate = "AuctionatorStringCellTemplate",
cellParameters = { "quantity" },
},
{
headerTemplate = "AuctionatorStringColumnHeaderTemplate",
headerText = AUCTIONATOR_L_ITEM_LEVEL_COLUMN,
headerParameters = { "level" },
cellTemplate = "AuctionatorStringCellTemplate",
cellParameters = { "level" },
},
{
headerTemplate = "AuctionatorStringColumnHeaderTemplate",
headerParameters = { "owned" },
headerText = AUCTIONATOR_L_OWNED_COLUMN,
cellTemplate = "AuctionatorStringCellTemplate",
cellParameters = { "owned" },
width = 70
},
}
local SEARCH_EVENTS = {
"COMMODITY_SEARCH_RESULTS_UPDATED",
"ITEM_SEARCH_RESULTS_UPDATED",
--Used to update the search when a cancel happens
"AUCTION_CANCELED",
}
AuctionatorSearchDataProviderMixin = CreateFromMixins(DataProviderMixin)
function AuctionatorSearchDataProviderMixin:OnShow()
FrameUtil.RegisterFrameForEvents(self, SEARCH_EVENTS)
Auctionator.EventBus:Register(self, {
Auctionator.Selling.Events.SellSearchStart
})
self:Reset()
end
function AuctionatorSearchDataProviderMixin:OnHide()
FrameUtil.UnregisterFrameForEvents(self, SEARCH_EVENTS)
Auctionator.EventBus:Unregister(self, {
Auctionator.Selling.Events.SellSearchStart
})
end
function AuctionatorSearchDataProviderMixin:ReceiveEvent(eventName)
if eventName == Auctionator.Selling.Events.SellSearchStart then
self:Reset()
self.onSearchStarted()
end
end
function AuctionatorSearchDataProviderMixin:GetTableLayout()
return SEARCH_PROVIDER_LAYOUT
end
local COMPARATORS = {
price = Auctionator.Utilities.NumberComparator,
available = Auctionator.Utilities.NumberComparator,
level = Auctionator.Utilities.NumberComparator,
owned = Auctionator.Utilities.StringComparator,
}
function AuctionatorSearchDataProviderMixin:UniqueKey(entry)
return entry.auctionID
end
function AuctionatorSearchDataProviderMixin:Sort(fieldName, sortDirection)
local comparator = COMPARATORS[fieldName](sortDirection, fieldName)
table.sort(self.results, function(left, right)
return comparator(left, right)
end)
self.onUpdate(self.results)
end
function AuctionatorSearchDataProviderMixin:OnEvent(eventName, itemRef, auctionID)
if eventName == "COMMODITY_SEARCH_RESULTS_UPDATED" then
self:Reset()
self:AppendEntries(self:ProcessCommodityResults(itemRef), true)
-- Get item search results, excluding individual auction updates (which cause
-- the display to blank)
elseif eventName == "ITEM_SEARCH_RESULTS_UPDATED" and auctionID == nil then
self:Reset()
self:AppendEntries(self:ProcessItemResults(itemRef), true)
elseif eventName == "AUCTION_CANCELED" then
Auctionator.EventBus
:RegisterSource(self, "AuctionatorSearchDataProviderMixin")
:Fire(self, Auctionator.Selling.Events.RefreshSearch)
:UnregisterSource(self)
end
end
function AuctionatorSearchDataProviderMixin:ProcessCommodityResults(itemID)
local entries = {}
local anyOwnedNotLoaded = false
for index = C_AuctionHouse.GetNumCommoditySearchResults(itemID), 1, -1 do
local resultInfo = C_AuctionHouse.GetCommoditySearchResultInfo(itemID, index)
local entry = {
price = resultInfo.unitPrice,
owners = resultInfo.owners,
quantity = resultInfo.quantity,
level = "0",
auctionID = resultInfo.auctionID,
itemID = itemID,
itemType = Auctionator.Constants.ITEM_TYPES.COMMODITY,
}
if resultInfo.containsOwnerItem then
-- Test if the auction has been loaded for cancelling
if not C_AuctionHouse.CanCancelAuction(resultInfo.auctionID) then
anyOwnedNotLoaded = true
end
entry.owned = AUCTIONATOR_L_UNDERCUT_YES
else
entry.owned = GRAY_FONT_COLOR:WrapTextInColorCode(AUCTIONATOR_L_UNDERCUT_NO)
end
table.insert(entries, entry)
end
-- To cancel an owned auction it must have been loaded by QueryOwnedAuctions.
-- Rather than call it unnecessarily (which wastes a request) it is only
-- called if an auction exists that hasn't been loaded for cancelling yet.
-- If a user really really wants to avoid an extra request they can turn the
-- feature off.
if anyOwnedNotLoaded and Auctionator.Config.Get(Auctionator.Config.Options.SELLING_SHIFT_CANCEL) then
Auctionator.AH.QueryOwnedAuctions({})
end
return entries
end
function AuctionatorSearchDataProviderMixin:ProcessItemResults(itemKey)
local entries = {}
local anyOwnedNotLoaded = false
for index = C_AuctionHouse.GetNumItemSearchResults(itemKey), 1, -1 do
local resultInfo = C_AuctionHouse.GetItemSearchResultInfo(itemKey, index)
local entry = {
price = resultInfo.buyoutAmount or resultInfo.bidAmount,
level = tostring(resultInfo.itemKey.itemLevel or 0),
owners = resultInfo.owners,
quantity = resultInfo.quantity,
itemLink = resultInfo.itemLink,
auctionID = resultInfo.auctionID,
itemType = Auctionator.Constants.ITEM_TYPES.ITEM,
}
if resultInfo.containsOwnerItem then
-- Test if the auction has been loaded for cancelling
if not C_AuctionHouse.CanCancelAuction(resultInfo.auctionID) then
anyOwnedNotLoaded = true
end
entry.owned = AUCTIONATOR_L_UNDERCUT_YES
else
entry.owned = GRAY_FONT_COLOR:WrapTextInColorCode(AUCTIONATOR_L_UNDERCUT_NO)
end
table.insert(entries, entry)
end
-- See comment in ProcessCommodityResults
if anyOwnedNotLoaded and Auctionator.Config.Get(Auctionator.Config.Options.SELLING_SHIFT_CANCEL) then
Auctionator.AH.QueryOwnedAuctions({})
end
return entries
end
function AuctionatorSearchDataProviderMixin:GetRowTemplate()
return "AuctionatorSellSearchRowTemplate"
end
|
-- CONFIGURATION
-- Set to true to enable on startup
yalt.show = false
-- Key to toggle yalt.
yalt.key_toggle = "f1"
-- Set x and or y to put in specific spot. Default centers the yalt.
yalt.x = nil
yalt.y = nil
-- Set to nil for fullscreen with padding.
yalt.w = love.graphics.getWidth()*0.6
yalt.h = love.graphics.getHeight()*0.6
-- Change the screen padding, screen color/aplha and the icon.
yalt.screen_padding = 32
yalt.screen_color = {r = 46, g = 52, b = 54, a = 224} -- Tango! aluminium 6 @ 75% opacity
yalt.icon = "yalt/yalt.png" -- From Tango! Desktop Project
-- Change the font, font size and font color/aplha
yalt.font = love.graphics.newFont( "yalt/MonospaceTypewriter.ttf", 12 )
yalt.text_color = {r = 138, g = 226, b = 52, a = 255} -- Tango! Chameleon 1
-- Change the line input's prefix. Currently userless unix style.
yalt.prefix = "$ "
-- Change the blinking location character. To disable, set as ""
yalt.blinkchar = "_"
-- Change this so you can have a different welcome message. nil for none.
yalt.welcome = "YALT - Yet Another Love Terminal"
-- Time in seconds that it takes for the key repeat to turn on.
yalt.keyrepeat_delay = 0.7
yalt.cursorrepeat_delay = 2
|
--
-- vs2010_nuget.lua
-- Generate a NuGet packages.config file.
-- Copyright (c) 2016 Jason Perkins and the Premake project
--
premake.vstudio.nuget2010 = {}
local p = premake
local vstudio = p.vstudio
local nuget2010 = p.vstudio.nuget2010
local cs2005 = p.vstudio.cs2005
--
-- These functions take the package string as an argument and give you
-- information about it.
--
function nuget2010.packageName(package)
return package:gsub(":", ".")
end
function nuget2010.packageId(package)
return package:sub(0, package:find(":") - 1)
end
function nuget2010.packageVersion(package)
return package:sub(package:find(":") + 1, -1)
end
local function packageProject(wks, package)
for prj in p.workspace.eachproject(wks) do
for i = 1, #prj.nuget do
local projectPackage = prj.nuget[i]
if projectPackage == package then
return prj
end
end
end
end
function nuget2010.packageFramework(wks, package)
local prj = packageProject(wks, package)
if p.project.iscpp(prj) then
return "native"
elseif p.project.isdotnet(prj) then
local cfg = p.project.getfirstconfig(prj)
local action = premake.action.current()
local framework = cfg.dotnetframework or action.vstudio.targetFramework
return cs2005.formatNuGetFrameworkVersion(framework)
end
end
--
-- Generates the packages.config file.
--
function nuget2010.generatePackagesConfig(obj)
local wks = obj.workspace
local done = {}
local packages = {}
for prj in p.workspace.eachproject(wks) do
for i = 1, #prj.nuget do
local package = prj.nuget[i]
if not done[package] then
done[package] = true
table.insert(packages, package)
end
end
end
p.w('<?xml version="1.0" encoding="utf-8"?>')
p.push('<packages>')
for _, package in ipairs(packages) do
p.x('<package id="%s" version="%s" targetFramework="%s" />', nuget2010.packageId(package), nuget2010.packageVersion(package), nuget2010.packageFramework(wks, package))
end
p.pop('</packages>')
end
|
local ffi = require("ffi")
-- core types
ffi.cdef[[
typedef uint32_t dev_t;
]]
ffi.cdef[[
/*
* udev - library context
*
* reads the udev config and system environment
* allows custom logging
*/
struct udev;
struct udev *udev_ref(struct udev *udev);
struct udev *udev_unref(struct udev *udev);
struct udev *udev_new(void);
void udev_set_log_fn(struct udev *udev,
void (*log_fn)(struct udev *udev,
int priority, const char *file, int line, const char *fn,
const char *format, va_list args));
int udev_get_log_priority(struct udev *udev);
void udev_set_log_priority(struct udev *udev, int priority);
void *udev_get_userdata(struct udev *udev);
void udev_set_userdata(struct udev *udev, void *userdata);
]]
ffi.cdef[[
/*
* udev_list
*
* access to libudev generated lists
*/
struct udev_list_entry;
struct udev_list_entry *udev_list_entry_get_next(struct udev_list_entry *list_entry);
struct udev_list_entry *udev_list_entry_get_by_name(struct udev_list_entry *list_entry, const char *name);
const char *udev_list_entry_get_name(struct udev_list_entry *list_entry);
const char *udev_list_entry_get_value(struct udev_list_entry *list_entry);
]]
ffi.cdef[[
/*
* udev_device
*
* access to sysfs/kernel devices
*/
struct udev_device;
struct udev_device *udev_device_ref(struct udev_device *udev_device);
struct udev_device *udev_device_unref(struct udev_device *udev_device);
struct udev *udev_device_get_udev(struct udev_device *udev_device);
struct udev_device *udev_device_new_from_syspath(struct udev *udev, const char *syspath);
struct udev_device *udev_device_new_from_devnum(struct udev *udev, char type, dev_t devnum);
struct udev_device *udev_device_new_from_subsystem_sysname(struct udev *udev, const char *subsystem, const char *sysname);
struct udev_device *udev_device_new_from_device_id(struct udev *udev, char *id);
struct udev_device *udev_device_new_from_environment(struct udev *udev);
/* udev_device_get_parent_*() does not take a reference on the returned device, it is automatically unref'd with the parent */
struct udev_device *udev_device_get_parent(struct udev_device *udev_device);
struct udev_device *udev_device_get_parent_with_subsystem_devtype(struct udev_device *udev_device,
const char *subsystem, const char *devtype);
]]
ffi.cdef[[
/* retrieve device properties */
const char *udev_device_get_devpath(struct udev_device *udev_device);
const char *udev_device_get_subsystem(struct udev_device *udev_device);
const char *udev_device_get_devtype(struct udev_device *udev_device);
const char *udev_device_get_syspath(struct udev_device *udev_device);
const char *udev_device_get_sysname(struct udev_device *udev_device);
const char *udev_device_get_sysnum(struct udev_device *udev_device);
const char *udev_device_get_devnode(struct udev_device *udev_device);
int udev_device_get_is_initialized(struct udev_device *udev_device);
struct udev_list_entry *udev_device_get_devlinks_list_entry(struct udev_device *udev_device);
struct udev_list_entry *udev_device_get_properties_list_entry(struct udev_device *udev_device);
struct udev_list_entry *udev_device_get_tags_list_entry(struct udev_device *udev_device);
struct udev_list_entry *udev_device_get_sysattr_list_entry(struct udev_device *udev_device);
const char *udev_device_get_property_value(struct udev_device *udev_device, const char *key);
const char *udev_device_get_driver(struct udev_device *udev_device);
dev_t udev_device_get_devnum(struct udev_device *udev_device);
const char *udev_device_get_action(struct udev_device *udev_device);
unsigned long long int udev_device_get_seqnum(struct udev_device *udev_device);
unsigned long long int udev_device_get_usec_since_initialized(struct udev_device *udev_device);
const char *udev_device_get_sysattr_value(struct udev_device *udev_device, const char *sysattr);
int udev_device_set_sysattr_value(struct udev_device *udev_device, const char *sysattr, char *value);
int udev_device_has_tag(struct udev_device *udev_device, const char *tag);
]]
ffi.cdef[[
/*
* udev_monitor
*
* access to kernel uevents and udev events
*/
struct udev_monitor;
struct udev_monitor *udev_monitor_ref(struct udev_monitor *udev_monitor);
struct udev_monitor *udev_monitor_unref(struct udev_monitor *udev_monitor);
struct udev *udev_monitor_get_udev(struct udev_monitor *udev_monitor);
/* kernel and udev generated events over netlink */
struct udev_monitor *udev_monitor_new_from_netlink(struct udev *udev, const char *name);
/* bind socket */
int udev_monitor_enable_receiving(struct udev_monitor *udev_monitor);
int udev_monitor_set_receive_buffer_size(struct udev_monitor *udev_monitor, int size);
int udev_monitor_get_fd(struct udev_monitor *udev_monitor);
struct udev_device *udev_monitor_receive_device(struct udev_monitor *udev_monitor);
/* in-kernel socket filters to select messages that get delivered to a listener */
int udev_monitor_filter_add_match_subsystem_devtype(struct udev_monitor *udev_monitor,
const char *subsystem, const char *devtype);
int udev_monitor_filter_add_match_tag(struct udev_monitor *udev_monitor, const char *tag);
int udev_monitor_filter_update(struct udev_monitor *udev_monitor);
int udev_monitor_filter_remove(struct udev_monitor *udev_monitor);
]]
ffi.cdef[[
/*
* udev_enumerate
*
* search sysfs for specific devices and provide a sorted list
*/
struct udev_enumerate;
struct udev_enumerate *udev_enumerate_ref(struct udev_enumerate *udev_enumerate);
struct udev_enumerate *udev_enumerate_unref(struct udev_enumerate *udev_enumerate);
struct udev *udev_enumerate_get_udev(struct udev_enumerate *udev_enumerate);
struct udev_enumerate *udev_enumerate_new(struct udev *udev);
/* device properties filter */
int udev_enumerate_add_match_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem);
int udev_enumerate_add_nomatch_subsystem(struct udev_enumerate *udev_enumerate, const char *subsystem);
int udev_enumerate_add_match_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value);
int udev_enumerate_add_nomatch_sysattr(struct udev_enumerate *udev_enumerate, const char *sysattr, const char *value);
int udev_enumerate_add_match_property(struct udev_enumerate *udev_enumerate, const char *property, const char *value);
int udev_enumerate_add_match_sysname(struct udev_enumerate *udev_enumerate, const char *sysname);
int udev_enumerate_add_match_tag(struct udev_enumerate *udev_enumerate, const char *tag);
int udev_enumerate_add_match_parent(struct udev_enumerate *udev_enumerate, struct udev_device *parent);
int udev_enumerate_add_match_is_initialized(struct udev_enumerate *udev_enumerate);
int udev_enumerate_add_syspath(struct udev_enumerate *udev_enumerate, const char *syspath);
/* run enumeration with active filters */
int udev_enumerate_scan_devices(struct udev_enumerate *udev_enumerate);
int udev_enumerate_scan_subsystems(struct udev_enumerate *udev_enumerate);
/* return device list */
struct udev_list_entry *udev_enumerate_get_list_entry(struct udev_enumerate *udev_enumerate);
]]
ffi.cdef[[
/*
* udev_queue
*
* access to the currently running udev events
*/
struct udev_queue;
struct udev_queue *udev_queue_ref(struct udev_queue *udev_queue);
struct udev_queue *udev_queue_unref(struct udev_queue *udev_queue);
struct udev *udev_queue_get_udev(struct udev_queue *udev_queue);
struct udev_queue *udev_queue_new(struct udev *udev);
unsigned long long int udev_queue_get_kernel_seqnum(struct udev_queue *udev_queue);
unsigned long long int udev_queue_get_udev_seqnum(struct udev_queue *udev_queue);
int udev_queue_get_udev_is_active(struct udev_queue *udev_queue);
int udev_queue_get_queue_is_empty(struct udev_queue *udev_queue);
int udev_queue_get_seqnum_is_finished(struct udev_queue *udev_queue, unsigned long long int seqnum);
int udev_queue_get_seqnum_sequence_is_finished(struct udev_queue *udev_queue,
unsigned long long int start, unsigned long long int end);
struct udev_list_entry *udev_queue_get_queued_list_entry(struct udev_queue *udev_queue);
]]
ffi.cdef[[
/*
* udev_hwdb
*
* access to the static hardware properties database
*/
struct udev_hwdb;
struct udev_hwdb *udev_hwdb_new(struct udev *udev);
struct udev_hwdb *udev_hwdb_ref(struct udev_hwdb *hwdb);
struct udev_hwdb *udev_hwdb_unref(struct udev_hwdb *hwdb);
struct udev_list_entry *udev_hwdb_get_properties_list_entry(struct udev_hwdb *hwdb, const char *modalias, unsigned int flags);
]]
ffi.cdef[[
/*
* udev_util
*
* udev specific utilities
*/
int udev_util_encode_string(const char *str, char *str_enc, size_t len);
]]
local function safeffistring(str)
if str == nil then
return nil;
end
return ffi.string(str);
end
local Lib_udev = ffi.load("udev")
local exports = {
Lib_udev = Lib_udev;
-- library functions
udev_new = Lib_udev.udev_new;
udev_unref = Lib_udev.udev_unref;
udev_device_new_from_syspath = Lib_udev.udev_device_new_from_syspath;
udev_device_get_action = Lib_udev.udev_device_get_action;
udev_device_get_devtype = Lib_udev.udev_device_get_devtype;
udev_device_get_devnode = Lib_udev.udev_device_get_devnode;
udev_device_get_devpath = Lib_udev.udev_device_get_devpath;
udev_device_get_driver = Lib_udev.udev_device_get_driver;
udev_device_get_is_initialized = Lib_udev.udev_device_get_is_initialized;
udev_device_get_parent = Lib_udev.udev_device_get_parent;
udev_device_get_parent_with_subsystem_devtype = Lib_udev.udev_device_get_parent_with_subsystem_devtype;
udev_device_get_properties_list_entry = Lib_udev.udev_device_get_properties_list_entry;
udev_device_get_subsystem = Lib_udev.udev_device_get_subsystem;
udev_device_get_sysattr_value = Lib_udev.udev_device_get_sysattr_value;
udev_device_get_sysname = Lib_udev.udev_device_get_sysname;
udev_device_get_sysnum = Lib_udev.udev_device_get_sysnum;
udev_device_get_syspath = Lib_udev.udev_device_get_syspath;
udev_device_get_tags_list_entry = Lib_udev.udev_device_get_tags_list_entry;
udev_device_unref = Lib_udev.udev_device_unref;
udev_enumerate_new = Lib_udev.udev_enumerate_new;
udev_enumerate_add_match_subsystem = Lib_udev.udev_enumerate_add_match_subsystem;
udev_enumerate_get_list_entry = Lib_udev.udev_enumerate_get_list_entry;
udev_enumerate_scan_devices = Lib_udev.udev_enumerate_scan_devices;
udev_enumerate_scan_subsystems = Lib_udev.udev_enumerate_scan_subsystems;
udev_enumerate_unref = Lib_udev.udev_enumerate_unref;
udev_hwdb_new = Lib_udev.udev_hwdb_new;
udev_hwdb_ref = Lib_udev.udev_hwdb_ref;
udev_hwdb_unref = Lib_udev.udev_hwdb_unref;
udev_hwdb_get_properties_list_entry = Lib_udev.udev_hwdb_get_properties_list_entry;
udev_list_entry_get_name = Lib_udev.udev_list_entry_get_name;
udev_list_entry_get_next = Lib_udev.udev_list_entry_get_next;
udev_list_entry_get_value = Lib_udev.udev_list_entry_get_value;
udev_queue_new = Lib_udev.udev_queue_new;
-- local functions
safeffistring = safeffistring;
}
setmetatable(exports, {
__call = function(self, ...)
for k,v in pairs(self) do
_G[k] = v;
end
return self;
end,
})
return exports
|
require "vm_accuracy_test_common"
require "luavm.bytecode"
require "luavm.dynarec"
for test in iterateTests() do
if test:sub(-4,-1) == ".lua" then
local f,a,r = getTest(test)
print("running "..test)
local dyncode = table.concat(
dynarec.compile(bytecode.load(string.dump(f)))
,"\n")
print(dyncode)
local cr = {assert(loadstring(dyncode))(unpack(a))}
assert(match(cr,r), test.." failed")
print(test.." suceeded")
end
end
|
data:extend{
{
type = "armor",
name = "tiny-armor",
icon = "__Tiny_Start__/graphics/icons/tiny-power-armor.png",
icon_size = 32,
flags = {"goes-to-main-inventory"},
resistances =
{
{
type = "physical",
decrease = 3,
percent = 20
},
{
type = "acid",
decrease = 3,
percent = 30
},
{
type = "explosion",
decrease = 2,
percent = 20
},
{
type = "fire",
decrease = 2,
percent = 10
}
},
durability = 5000,
subgroup = "armor",
order = "a[tiny-armor]",
stack_size = 1,
equipment_grid = "tiny-equipment-grid",
inventory_size_bonus = 10
},
{
type = "equipment-grid",
name = "tiny-equipment-grid",
width = 5,
height = 4,
equipment_categories = {"armor"}
},
{
type = "generator-equipment",
name = "micro-fusion-reactor-equipment",
sprite =
{
filename = "__Tiny_Start__/graphics/equipment/tiny-fusion-reactor-equipment.png",
width = 128,
height = 128,
priority = "medium"
},
shape =
{
width = 2,
height = 2,
type = "full"
},
energy_source =
{
type = "electric",
usage_priority = "primary-output"
},
power = "150kW",
categories = {"armor"}
},
{
type = "item",
name = "micro-fusion-reactor-equipment",
icon = "__Tiny_Start__/graphics/icons/tiny-fusion-reactor-equipment.png",
icon_size = 32,
placed_as_equipment_result = "micro-fusion-reactor-equipment",
flags = {"goes-to-main-inventory"},
subgroup = "equipment",
order = "a[energy-source]-b[fusion-reactor]",
stack_size = 20
},
}
|
local a = 1 + 2 * 3 / 6
local bunch, go, here
a, bunch, go, here = another, world
func(arg1, arg2, another, arg3)
local we
here, we = function() end, yeah
local the, different
the, different = function()
return approach
end, yeah
dad()
dad(lord)
hello(one, two)();
(5 + 5)(world)
fun(a)(b)
fun(a)(b)
fun(a)(b, bad(hello))
hello(world(what(are(you(doing(here))))))
what(the)[3243](world, yeck(heck))
hairy[hands][are](gross)(okay(okay[world]))
local _ = (get[something] + 5)[years]
local i, x = 200, 300
local yeah = (1 + 5) * 3
yeah = ((1 + 5) * 3) / 2
yeah = ((1 + 5) * 3) / 2 + i % 100
local whoa = (1 + 2) * (3 + 4) * (4 + 5)
_ = function()
if something then
return 1, 2, 4
end
return print("hello")
end
_ = function()
if hello then
return "heloo", "world"
else
return no, way
end
end
_ = function()
return 1, 2, 34
end
return 5 + function()
return 4 + 2
end
return 5 + (function()
return 4
end) + 2
print(5 + function()
_ = 34
return good(nads)
end)
something('else', "ya")
something('else')
something("else")
_ = here(we)("go")[12123]
local something = {
test = 12323,
what = function()
return print("hello world")
end
}
print(something.test)
local frick = {
hello = "world"
}
local argon = {
num = 100,
world = function(self)
print(self.num)
return {
something = function()
return print("hi from something")
end
}
end,
somethin = function(self, str)
print("string is", str)
return {
world = function(a, b)
return print("sum", a + b)
end
}
end
}
something.what()
argon:world().something()
argon:somethin("200").world(1, 2)
x = -434
x = -hello(world(one(two)))
local hi = -"herfef"
x = -(function()
local _accum_0 = { }
local _len_0 = 0
for x in x do
_len_0 = _len_0 + 1
_accum_0[_len_0] = x
end
return _accum_0
end)()
if cool then
print("hello")
end
print("nutjob")
if hello then
_ = 343
end
if cool then
print("what")
else
_ = whack
end
local arg = {
...
}
x = function(...)
return dump({
...
})
end
x = not true
local y = not (5 + 5)
y = #"hello"
x = #{
#{ },
#{
1
},
#{
1,
2
}
}
_ = hello, world
something:hello(what)(a, b)
something:hello(what)
something.hello:world(a, b)
something.hello:world(1, 2, 3)(a, b)
x = 1232
x = x + 10 + 3
local j = j - "hello"
y = y * 2
y = y / 100
local m = m % 2
local hello = hello .. "world"
x = 0
local _list_0 = values
for _index_0 = 1, #_list_0 do
local v = _list_0[_index_0]
_ = ((function()
if ntype(v) == "fndef" then
x = x + 1
return x
end
end)())
end
hello = {
something = world,
["if"] = "hello",
["else"] = 3434,
["function"] = "okay",
good = 230203
}
_ = 5 + what(wack)
what(whack + 5)
_ = 5 - what(wack)
what(whack - 5)
x = hello - world - something
(function(something)
if something == nil then
do
local _with_0 = what
_with_0:cool(100)
something = _with_0
end
end
return print(something)
end)()
if something then
_ = 03589
else
_ = 3434
end
if something then
_ = yeah
elseif "ymmm" then
print("cool")
else
_ = okay
end
x = notsomething
y = ifsomething
local z = x and b
z = x(andb)
|
----------------------------------------
-- Sassilization
-- http://sassilization.com
-- By Sassafrass / Spacetech / LuaPineapple
----------------------------------------
UNIT.Name = "Ballista"
UNIT.Model = "models/mrgiggles/sassilization/ballista.mdl"
UNIT.Iron = 30
UNIT.Food = 25
UNIT.Gold = 5
UNIT.Supply = 2
UNIT.AttackDelay = 3
UNIT.AttackMoveDelay = 1
UNIT.Range = 60
UNIT.SightRange = 80
UNIT.Speed = 10 -- 21
UNIT.Require = {city = 0,workshop = 2}
UNIT.Spawnable = true
UNIT.HP = 15
UNIT.AttackDamage = 10
UNIT.OBBMins = Vector(-12, -12, -1)
UNIT.OBBMaxs = Vector(12, 12, 8)
UNIT.Size = 13
UNIT.Creed = 1
UNIT.camPos = Vector(-189.863266, -153.886780, 93.880409)
UNIT.angle = Angle(20.470, 39.718, 0.000)
UNIT.fov = 4.8
function UNIT:GetAttackSound()
return "SASS_Ballista.Fire"
end
|
#!/usr/bin/env luajit
-- The MIT License (MIT)
-- Copyright (c) 2016 Ruairidh Carmichael - ruairidhcarmichael@live.co.uk
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
if not arg or ... ~= '0' then
print('Please don\'t require moontastic! It should only be executed by your shell!')
return
end
require 'moontastic.utils.table'
local class = require 'middleclass'
local basics = require 'moontastic.segments.basics'
local sysinfo = require 'moontastic.segments.sysinfo'
local git = require 'moontastic.segments.git'
local fs = require 'moontastic.segments.filesystem'
local network = require 'moontastic.segments.network'
local sys = require 'moontastic.utils.sys'
local Prompt = class('Prompt')
function Prompt:initialize()
self.cwd = sys.get_valid_cwd()
self.first_line_left = {}
self.first_line_right = {}
self.last_line = {}
end
function Prompt:render()
self:_clean_segments()
local first_line = self:_render_first_line()
local last_line = self:_render_last_line()
return first_line .. last_line
end
function Prompt:_render_first_line()
local segments = self.first_line_left
local padding_len = self:_compute_padding_length_first_line()
if padding_len then
table.insert(segments, basics.Padding:new(padding_len))
end
table.extend(segments, self.first_line_right)
table.insert(segments, basics.NewLine:new())
segments = self:_color_dividers(segments)
local output = ''
for i, segment in ipairs(segments) do
output = output .. segment:render()
end
return output
end
function Prompt:_render_last_line()
local output = ''
for i, segment in ipairs(self.last_line) do
output = output .. segment:render()
end
return output
end
function Prompt:_clean_segments()
local function remove_inactive(segments)
local t = {}
for _, x in ipairs(segments) do
if x.active then table.insert(t, x) end
end
return t
end
local function remove_duplicated_dividers(segments)
local to_remove = {}
for i=1, #segments - 1 do
if (segments[i].class.name == basics.Divider.name) and (segments[i+1].class.name == basics.Divider.name) then
table.insert(to_remove, i)
end
end
for counter, i in ipairs(to_remove) do
table.remove(segments, i - counter + 1)
end
return segments
end
local function strip()
if self.first_line_left[1].class.super.name == basics.Divider.name then
table.remove(self.first_line_left, 1)
end
if self.first_line_right[#self.first_line_right].class.super.name == basics.Divider.name then
table.remove(self.first_line_right, #self.first_line_right)
end
end
self.first_line_left = remove_duplicated_dividers(remove_inactive(self.first_line_left))
self.first_line_right = remove_duplicated_dividers(remove_inactive(self.first_line_right))
strip()
end
function Prompt:_compute_padding_length_first_line()
local right_starts_w_divider = (self.first_line_right and self.first_line_right[1].class.name == basics.Divider.name)
local cols = sys.get_terminal_columns_n()
local text_len = (self:_get_total_segments_length(self.first_line_left) +
self:_get_total_segments_length(self.first_line_right))
if right_starts_w_divider then
text_len = text_len - basics.Divider:new():length()
end
local padding_len = cols - (text_len % cols)
if padding_len == cols then
padding_len = 0
if right_starts_w_divider then
table.remove(self.first_line_right, 1)
end
else
if right_starts_w_divider then
padding_len = padding_len - basics.Divider:new():length()
else
passing_len = 0
end
end
return padding_len
end
function Prompt:_get_total_segments_length(segments)
local t = {}
for _, x in ipairs(segments) do
table.insert(t, x:length())
end
return table.sum(t)
end
function Prompt:_color_dividers(segments)
local prev, next_
for i, segment in ipairs(segments) do
if segment.class.name == basics.Divider.name then
if i > 1 then prev = segments[i-1] else prev = nil end
if (i+1) < #segments then next_ = segments[i+1] else next_ = nil end
segment:set_colors(prev, next_)
end
end
return segments
end
local prompt = Prompt:new()
local function addLeftSegment(segment, arg)
arg = arg or nil
table.insert(prompt.first_line_left, segment:new(arg))
end
local function addRightSegment(segment, arg)
arg = arg or nil
table.insert(prompt.first_line_right, segment:new(arg))
end
local function addLastSegment(segment, arg)
arg = arg or nil
table.insert(prompt.last_line, segment:new(arg))
end
addLeftSegment(sysinfo.UserAtHost)
addLeftSegment(basics.Divider)
addLeftSegment(network.Ssh)
addLeftSegment(basics.Divider)
addLeftSegment(fs.CurrentDir, prompt.cwd)
addLeftSegment(basics.Divider)
addLeftSegment(fs.ReadOnly, prompt.cwd)
addLeftSegment(basics.Divider)
addLeftSegment(basics.ExitCode)
addLeftSegment(basics.Divider)
addRightSegment(basics.Divider)
addRightSegment(git.Git)
addRightSegment(basics.Divider)
addRightSegment(fs.Venv)
addRightSegment(basics.Divider)
addRightSegment(sysinfo.Time)
addLastSegment(basics.Root)
io.stdout:write(prompt:render())
|
local cjson = require "cjson.safe"
local helpers = require "kong.plugins.rewrite.helpers"
local mapTo = helpers.mapTo
local isempty = helpers.isempty
local log = helpers.log
local req_set_uri = ngx.req.set_uri
local req_set_uri_args = ngx.req.set_uri_args
local req_set_header = ngx.req.set_header
local req_read_body = ngx.req.read_body
local req_set_body_data = ngx.req.set_body_data
local req_clear_header = ngx.req.clear_header
local req_set_method = ngx.req.set_method
local encode_args = ngx.encode_args
local string_find = string.find
local _M = {}
local function req_set_headers(oldHeaders, newHeaders)
if not isempty(oldHeaders) then
for name, value in pairs(oldHeaders) do
log.info('Clearing old header '..name)
req_clear_header(name)
end
end
if not isempty(newHeaders) then
for name, value in pairs(newHeaders) do
log.info('Setting new header '..name, value)
req_set_header(name, value)
end
end
end
local function transform_querystrings(conf, scope)
if isempty(conf.request.querystring) then
return
end
req_set_uri_args(mapTo(scope, conf.request.querystring))
end
local function transform_headers(conf, scope)
if isempty(conf.request.headers) then
return
end
req_set_headers(scope.req.headers, mapTo(scope, conf.request.headers))
end
local function transform_body_text(conf, scope)
if isempty(conf.request.text) then
return
end
local body = mapTo(scope, conf.request.json)
req_set_body_data(body)
req_set_header('content-type', 'plain/text')
req_set_header('content-length', #body)
end
local function transform_body_json(conf, scope)
if isempty(conf.request.json) then
return
end
local json = mapTo(scope, conf.request.json)
local body = cjson.encode(json)
req_set_body_data(body)
req_set_header('content-type', 'application/json')
req_set_header('content-length', #body)
end
local function transform_method(conf, scope)
if isempty(conf.request.method) then
return
end
local newMethod = (mapTo(scope, conf.request.method) or scope.req.method):upper()
req_set_method(ngx["HTTP_"..newMethod])
if newMethod == "GET" or newMethod == "HEAD" or newMethod == "TRACE" then
if type(scope.req.payload) == 'table' then
local parameters = scope.req.payload
local querystring = scope.req.query
for name, value in pairs(parameters) do
querystring[name] = value
end
req_set_uri_args(querystring)
end
end
end
local function transform_path(conf, scope)
if isempty(conf.request.path) then
return
end
local uri = mapTo(scope, conf.request.path)
if uri then
-- if kong development kit exists use it to set the path
if kong then
kong.service.request.set_path(uri)
else
req_set_uri(uri)
end
end
end
function _M.access(conf, scope)
transform_method(conf, scope)
transform_path(conf, scope)
transform_body_text(conf, scope)
transform_body_json(conf, scope)
transform_headers(conf, scope)
transform_querystrings(conf, scope)
end
return _M
|
--[[-------------------------------------------------------------------
Custom Model Override
---------------------------------------------------------------------]]
GM.PlayerModelOverride = {
[TEAM_ZOMBIES] = {
Model("models/player/aliendrone.mdl")
}
}
--[[-------------------------------------------------------------------
Boss Entities
---------------------------------------------------------------------]]
-- Normal
GM:AddBoss("Predator", "predboss_2", "aztecboss_math_health") -- predator that shoots lasers
GM:AddBoss("Predator", "predboss_2", "aztecboss_math_health_2") -- ground stomp
-- Hard
GM:AddBoss("Predator", "mob_grudge_model_1", "mob_grudge_math")
-- Hyper
GM:AddBoss("Predator", "cboss_predator", "cboss_predatorhealth_counter")
-- Ultimate
GM:AddBoss("Predator", "mob_grudge_model_2", "fboss_math_2") -- endboss
GM:AddBoss("Predator", "mob_grudge_model_2", "fboss_math_1") -- endboss rage mode
GM:AddBoss("Alien", "fboss_ee_model", "fboss_ee_math") -- post-endboss miniboss
--[[-------------------------------------------------------------------
Map Fixes
---------------------------------------------------------------------]]
hook.Add( "PostCleanUpMap", "RemoveWaterSplashes", function()
-- Remove shitty entities that cause water splashing
for _, v in pairs( ents.FindByName("splash_*") ) do
if IsValid(v) then
v:Remove()
end
end
-- Remove dev room spawn
for _, ent in pairs( ents.FindInSphere( Vector(-2048,3072,2496), 64 ) ) do
if IsValid(ent) and ent:GetClass() == "info_player_start" then
ent:Remove()
end
end
end )
GM:IgnoreMessages({"TYPE MAT_COLORCORRECTION 1 IN CONSOLE FOR BETTER VISUALS"})
GM.DisableZombiePickups = true
|
local mock_time = require("deftest.mock.time")
local eva = require("eva.eva")
return function()
describe("Eva Timers", function()
local id = "test.id"
local data = "data string"
before(function()
eva.init("/resources/tests/eva_tests.json")
mock_time.mock()
mock_time.set(0)
end)
after(function()
mock_time.unmock()
end)
it("Should be creatable", function()
assert(eva.timers.get(id) == nil)
eva.timers.add(id, data, 100)
assert(eva.timers.get(id) ~= nil)
end)
it("Check basic timer api", function()
eva.timers.add(id, data, 50)
assert(eva.timers.get_time(id) == 50)
mock_time.elapse(10)
assert(eva.timers.get_time(id) == 40)
assert(not eva.timers.is_end(id))
mock_time.elapse(40)
assert(eva.timers.is_end(id))
assert(eva.timers.get(id) ~= nil)
eva.timers.clear(id)
assert(eva.timers.get(id) == nil)
assert(eva.timers.get_time(id) < 0)
end)
it("Should be pausable", function()
eva.timers.add(id, data, 50)
eva.timers.set_pause(id, true)
mock_time.elapse(10)
assert(eva.timers.get_time(id) == 50)
mock_time.elapse(10)
eva.timers.set_pause(id, false)
assert(eva.timers.get_time(id) == 50)
mock_time.elapse(20)
assert(eva.timers.get_time(id) == 30)
end)
end)
end
|
---@module CookS
---@copyright Lilith Games, Avatar Team
---@author Yen Yuan
local CookS, this = ModuleUtil.New('CookS', ServerBase)
---初始化函数
function CookS:Init()
this:DataInit()
end
function CookS:DataInit()
this.foodNum = #world.FoodLocation:GetChildren()
this.potFree = true
this.curFoodNum = 0
this.foodList = {}
for i = 1, this.foodNum do
this.foodList[i] = nil
end
end
function CookS:FoodOnDeskEventHandler(_foodId, _player)
if this.curFoodNum >= this.foodNum then
return
end
this.curFoodNum = this.curFoodNum + 1
this:PutFood(_foodId, _player)
NetUtil.Broadcast('SycnDeskFoodNumEvent', this.curFoodNum, this.foodNum)
end
--桌上放菜
local disEffect
function CookS:PutFood(_foodId, _player)
for i = 1, this.foodNum do
if this.foodList[i] == nil then
this.foodList[i] = {
foodId = _foodId,
cook = _player.UserId,
index = i,
cookName = _player.Name
}
-- 播放特效,摆上食物
disEffect =
world:CreateInstance(
'DisEffect',
'DisEffect',
world.FoodLocation['Location' .. i],
world.FoodLocation['Location' .. i].Position
)
wait(0.5)
world:CreateInstance(
Config.CookMenu[_foodId].Model,
'Food',
world.FoodLocation['Location' .. i],
world.FoodLocation['Location' .. i].Position
)
--需要扩大碰撞盒
world.FoodLocation['Location' .. i].OnCollisionBegin:Connect(
function(_hitObject)
if _hitObject and _hitObject.Avatar and _hitObject.Avatar.ClassName == 'PlayerAvatarInstance' then
NetUtil.Fire_C(
'SetSelectFoodEvent',
_hitObject,
_foodId,
this.foodList[i].cookName,
_player.UserId,
i
)
NetUtil.Fire_C('OpenDynamicEvent', _hitObject, 'Interact', 27)
end
end
)
world.FoodLocation['Location' .. i].OnCollisionEnd:Connect(
function(_hitObject)
if _hitObject and _hitObject.Avatar and _hitObject.Avatar.ClassName == 'PlayerAvatarInstance' then
NetUtil.Fire_C('ChangeMiniGameUIEvent', _hitObject)
end
end
)
world:CreateInstance(
'ShowEffect',
'Effect',
world.FoodLocation['Location' .. i].Food,
world.FoodLocation['Location' .. i].Food.Position + Vector3.Up * 0.15
)
wait(1)
disEffect:Destroy()
NetUtil.Fire_C('SetCurCamEvent', _player)
NetUtil.Fire_C('ChangeMiniGameUIEvent', _player)
return
end
end
end
function CookS:OnPlayerJoinEventHandler(_player)
NetUtil.Fire_C('SycnDeskFoodNumEvent', _player, this.curFoodNum, this.foodNum)
end
function CookS:FoodRewardEventHandler(_playerId, _cookId, _coin)
local rewardPlayer, cook = world:GetPlayerByUserId(_playerId), world:GetPlayerByUserId(_cookId)
if rewardPlayer and cook then
NetUtil.Fire_C('InsertInfoEvent', cook, rewardPlayer.Name .. '打赏了你' .. _coin, 2, false)
NetUtil.Fire_C('UpdateCoinEvent', cook, _coin, false, 11)
end
end
function CookS:PlayerEatFoodEventHandler(_foodLocation)
if world.FoodLocation['Location' .. _foodLocation].Food then
world.FoodLocation['Location' .. _foodLocation].Food:Destroy()
world.FoodLocation['Location' .. _foodLocation].OnCollisionBegin:Clear()
world.FoodLocation['Location' .. _foodLocation].OnCollisionEnd:Clear()
this.foodList[_foodLocation] = nil
this.curFoodNum = this.curFoodNum - 1
NetUtil.Broadcast('SycnDeskFoodNumEvent', this.curFoodNum, this.foodNum)
end
end
function CookS:DestroyAllFood()
for k, v in pairs(world.FoodLocation:GetChildren()) do
if v.Food then
v.Food:Destroy()
v.OnCollisionBegin:Clear()
v.OnCollisionEnd:Clear()
end
--向所有人发起流程,关闭详情ui
--NetUtil.Broadcast()
end
for i = 1, this.foodNum do
this.foodList[i] = nil
end
this.curFoodNum = 0
NetUtil.Broadcast('SycnDeskFoodNumEvent', this.curFoodNum, this.foodNum)
end
function CookS:SycnTimeSEventHandler(_clock)
if _clock == 6 then
this:DestroyAllFood()
end
end
return CookS
|
scm = {
logicops = {['>'] = true, ['<'] = true, ['>='] = true, ['<='] = true, ['='] = true, ['~='] = true, },
arithmops = {['+'] = true, ['-'] = true, ['*'] = true, ['/'] = true, ['//'] = true },
compile = function( t, l )
local l = l or 1
if type( t ) == 'table' then
if t[1] == 'lambda' then
return ('function(%s) return (%s) end'):format( table.concat( t[2], ',' ), scm.compile( t[3], l+1 ))
elseif t[1] == 'define' then
local result = scm.compile( t[3] )
if result == t[3] or result:sub(1,8) == 'function' then
return ('local %s=%s'):format( t[2], result )
else
return ('local __result%d__\n%s\nlocal %s=__result%d__'):format( l, result, t[2], l )
end
elseif t[1] == 'if' then
return ('%s and %s%s'):format( scm.compile( t[2], l+1 ), scm.compile( t[3] ), t[4] and (' or ' .. scm.compile( t[4], l + 1 )) or '' )
elseif scm.logicops[t[1]] then
assert( t[3] ~= nil )
local args = {}
for i = 2, #t-1 do
args[i-1] = ('(%s%s%s)'):format( scm.compile( t[i], l + 1), t[1], scm.compile( t[i+1], l + 1))
end
return table.concat( args, 'and' )
elseif scm.arithmops[t[1]] then
if t[1] == '-' and t[3] == nil then
return ('-(%s)'):format( scm.compile( t[2], l + 1 ))
else
assert( t[3] ~= nil )
local args = {}
for i = 2, #t do
args[i-1] = ('%s'):format( scm.compile( t[i], l + 1 ))
end
return '(' .. table.concat( args, t[1] ) .. ')'
end
elseif t[1] == 'set!' then
return ('%s=%s'):format( t[2], scm.compile( t[3], l + 1 ))
elseif t[1] == 'begin' then
local args = {}
for i = 2, #t-1 do
args[i-1] = ('%s'):format( scm.compile( t[i], l + 1 ))
end
return ('do\n%s\n%s=%s\nend'):format( table.concat(args,'\n'), ('__result%d__'):format(l),scm.compile( t[#t], l + 1))
elseif t[1] == 'let' then
local args = {}
for i = 1, #t[2] do
args[i] = ('local %s=%s'):format( t[2][i][1], scm.compile( t[2][i][2], l + 1 ))
end
return ('do\n%s\n%s=%s\nend'):format( table.concat( args, '\n' ), ('__result%d__'):format(l),scm.compile( t[3], l + 1))
elseif t[1] == 'quote' then
local args = {}
for i = 2, #t do
args[i] = t[i]
end
return args
elseif t[1] == 'vector' then
local args = {}
for i = 2, #t do
args[i-1] = scm.compile( t[i], l+1 )
end
return '{' .. table.concat( args, ',' ) .. '}'
else
local args = {}
for i = 2, #t do
args[i-1] = ('%s'):format( scm.compile( t[i], l + 1 ))
end
return ('%s(%s)'):format( t[1], table.concat( args, ',' ))
end
else
return t
end
end,
interpret = function( t )
if type( t ) == 'table' then
if ( t[1] ) == 'define' then
_G[t[2]] = loadstring( 'return ' .. scm.compile( t[3] ))()
else
print( loadstring( 'return ' .. scm.compile( t ))())
end
end
end,
parse = function( s )
local strings = {}
local function adds( k )
if not strings[k] then
strings[#strings+1] = k
strings[k] = '##<string'..#strings..'>##'
end
return strings[k]
end
local function gets( i )
return strings[tonumber(i)]
end
local function putv( s )
if tonumber( s ) then
return s .. ','
else
return "'" .. s .. "',"
end
end
return s:gsub('\\"', '\\' .. ('"'):byte()):gsub('".-"',adds):gsub( '%(', '{' ):gsub( '%)', '}' ):gsub( '([^ {}\t\n\r]+)', putv ):gsub( '##<string(%d)>##', gets )
end,
repl = function( )
while true do
scm.interpret( loadstring('return ' .. scm.parse( io.read()))())
end
end,
}
scm.repl()
print( scm.parse( '(define x "(let somethine())\\"and other")' ))
print( scm.parse( '(define abs (lambda (x) (if (> x 0) x (- x))))'))
print( scm.parse( '(define y "abbba")' ))
--print( scm.compile{'define','sq',{'lambda',{'x'},{'*','x','x'}}} )
--print( scm.compile{'define','abs',{'lambda',{'x'},{'if',{'>','x',0},'x',{'-', 'x'}}}} )
--print( scm.compile{'+',1,2,3,4} )
--print( scm.compile{'define', 'y', {'begin', {'define', 'x', 2}, {'-', 'x', 3}}} )
--print( scm.compile{'define', 'z', {'let',{{'x',2},{'y',{'+','x',4}}},{'*', 'x', 'y', 25}}} )
|
--[[
File: round.lua
Author: toneo
Realm: Server
Round module. Handles starting/finishing rounds.
]]--
GM.RESULT_DRAW = 0
GM.STATE_STOPPED = 0
GM.STATE_PREROUND = 1
GM.STATE_RUNNING = 2
GM.STATE_POSTROUND = 3
-- Which round we're on
GM.RoundNumber = 0
GM.RoundState = GM.STATE_STOPPED
GM.PostRoundTime = 5
GM.RedTeamNPCs = {}
GM.BlueTeamNPCs = {}
GM.RoundEndSongs = {
"cardwars/victory/bradberry-tune.mp3"
}
--[[
Name: GM:StartRound()
Desc: Starts the next round.
]]--
function GM:StartRound()
if self:IsRoundInProgress() then
error( "Attempt to start round when round was already in progress!", 2 )
end
local roundNo = self.RoundNumber + 1
self.RoundNumber = roundNo
self.RoundState = self.STATE_PREROUND
-- For each team, find all their cards
local redCards = {}
local blueCards = {}
self:GetAllDefinitions( self.RedHolders, redCards )
self:GetAllDefinitions( self.BlueHolders, blueCards )
local redSpawns = ents.FindByClass( "cw_npc_spawn_red" )
local blueSpawns = ents.FindByClass( "cw_npc_spawn_blue" )
local redNPCs = {}
local blueNPCs = {}
-- Spawn all cards
self:SpawnCards( redCards, redSpawns, redNPCs, "red" )
self:SpawnCards( blueCards, blueSpawns, blueNPCs, "blue" )
-- Make red NPCs hate blue and vice versa, whilst also not teamkilling
self:ModifyRelationships( redNPCs )
self:ModifyRelationships( blueNPCs )
self.RedTeamNPCs = redNPCs
self.BlueTeamNPCs = blueNPCs
print( "Card Wars: Round " .. roundNo .. " started" )
self.RoundState = self.STATE_RUNNING
end
--[[
Name: GM:EndRound( result )
Desc: Called the round has ended.
]]--
function GM:EndRound( result )
if not self:IsRoundInProgress() then
error( "Attempt to end round when round was not already in progress!", 2 )
end
self.RoundState = self.STATE_POSTROUND
print( "Card Wars: Round " .. self.RoundNumber .. " ended, result was ", result )
-- Tell everyone who won
local endingText = "ended in a "
local winnerText = "draw!"
local winnerColor = Color( 200, 200, 200, 255 )
if result ~= self.RESULT_DRAW then
endingText = "was won by the "
winnerText = team.GetName( result ) .. "!"
winnerColor = team.GetColor( result )
end
fancychat.Broadcast( Color( 255, 255, 255, 255 ), "Round " .. endingText, winnerColor, winnerText )
-- Pick some round end music to play
local endRoundSong = table.Random( self.RoundEndSongs )
if endRoundSong then
netsound.PlayToAll( endRoundSong )
end
timer.Simple( self.PostRoundTime, function()
print( "Post round complete, new round ready" )
-- Delete all straggler NPCs
for k, v in pairs( self.RedTeamNPCs ) do
if IsValid(v) then v:Remove() end
end
for k, v in pairs( self.BlueTeamNPCs ) do
if IsValid(v) then v:Remove() end
end
self.RedTeamNPCs = {}
self.BlueTeamNPCs = {}
self.RoundState = self.STATE_STOPPED
-- Trigger the cw_interface outputs which the map relies on
local interfaces = ents.FindByClass( "cw_interface" )
for k, v in pairs( interfaces ) do
-- Fire the appropriate red/blue win output, do this before OnRoundEnded.
if result == self.TEAM_RED then
v:TriggerOutput( "OnRedWin", v )
elseif result == self.TEAM_BLUE then
v:TriggerOutput( "OnBlueWin", v )
else
v:TriggerOutput( "OnDraw", v )
end
v:TriggerOutput( "OnRoundEnded", v )
end
end )
end
--[[
Name: GM:IsRoundInProgress()
Desc: Used to find out if the round is currently in progress.
Returns: true if the round is in STATE_RUNNING
]]--
function GM:IsRoundInProgress()
return ( self.RoundState == self.STATE_RUNNING )
end
--[[
Name: GM:OnNPCKilled( npc, attacker, inflictor )
Desc: Called when an NPC has been killed.
]]--
function GM:OnNPCKilled( npc, attacker, inflictor )
-- Try and remove the npc from red team, and if that fails, from blue.
if not table.RemoveByValue( self.RedTeamNPCs, npc ) then
table.RemoveByValue( self.BlueTeamNPCs, npc ) end
self:CheckForWin()
end
--[[
Name: GM:CheckForWin()
Desc: Checks to see if a team has won the current round.
]]--
function GM:CheckForWin()
if not self:IsRoundInProgress() then return end
-- Check how many NPCs are left in each team.
local redCount = table.Count( self.RedTeamNPCs )
local blueCount = table.Count( self.BlueTeamNPCs )
local redLose = redCount == 0
local blueLose = blueCount == 0
-- Red win if blue lost and red didn't lose.
-- Blue win if red lost and blue didn't lose.
-- Draw if both lost.
if redLose then
if blueLose then
self:EndRound( self.RESULT_DRAW )
else
self:EndRound( self.TEAM_BLUE )
end
elseif blueLose then
self:EndRound( self.TEAM_RED )
end
-- If execution reaches this point, the game must go on
end
--[[
Name: GM:SpawnCards( cards, spawnList, npcList, team )
Desc: Spawns all given cards at random entries in the given spawn list, inserting the newly-spawned
npcs into npcList.
Args: cards: A list of card definitions to spawn.
spawnList: A list of spawnpoint entities.
npcList: Any list, the spawned NPCs will be inserted into this.
team: Any string. Used to spawn NPCs in squads separated by their teams.
]]--
function GM:SpawnCards( cards, spawnList, npcList, team )
-- For each card, pick a random spawnpoint
for k, card in pairs( cards ) do
local randomSpawn = table.Random( spawnList )
local spawnedNPCs
if not randomSpawn then
print( "WARNING: Ran out of spawn points for NPCs! The game will run badly!" )
return
end
-- Spawn the NPCs at the given point
spawnedNPCs = self:SpawnCardNPC( card, randomSpawn, team )
-- Keep track of the created NPCs
for _, npc in pairs( spawnedNPCs ) do
table.insert( npcList, npc )
end
-- Don't re-use this spawn point
table.RemoveByValue( spawnList, randomSpawn )
end
end
--[[
Name: GM:ModifyRelationships( redNPCs, blueNPCs )
Desc: Makes all redNPCs hate blueNPCs and vice versa. Also makes all NPCs like players.
]]--
function GM:ModifyRelationships( npcs )
for _, v in pairs( npcList ) do
for __, v2 in pairs( npcList ) do
if v ~= v2 then
v:AddEntityRelationship( v2, D_LI, 99 )
end
end
v:AddRelationship( "player D_LI 99" )
end
end
--[[
Name: GM:GetAllDefinitions( holderList, definitionList )
Desc: Reads all cards held in the given list of holders and inserts their definitions into the given list.
]]--
function GM:GetAllDefinitions( holderList, definitionList )
for _, holder in pairs( holderList ) do
-- Discard any without a card being held
if holder:IsHoldingCard() then
local cardID = holder:GetHeldCard():GetCardID()
-- If card has a valid definition ID, add to definition list
if cardID then
local definition = self:LookupDefinition( cardID )
if definition then
table.insert( definitionList, definition )
end
end
end
end
end
--[[
Name: GM:SpawnCardNPC( cardDefinition, spawnpoint, team )
Desc: Spawns NPCs as per the given definition and at the specified spawnpoint.
In practice this is currently limited to a maximum of 9 NPCs per card (due to implementation).
Args: cardDefinition: One of the definitions from card_definitions.lua. This can be obtained from
a cw_card by calling ENT:GetCardID() and then GM:LookupDefinition().
spawnpoint: The spawnpoint entity to spawn the NPCs at and around.
team: A string which will be used for things such as squads so that NPCs from
different teams do not form part of the same squad.
]]--
function GM:SpawnCardNPC( cardDefinition, spawnpoint, team )
local ChangeModel = cardDefinition[ "ChangeModel" ]
local Count = cardDefinition[ "Count" ] or 1
local DamageSettings = cardDefinition[ "DamageSettings" ]
local Health = cardDefinition[ "Health" ]
local KeyValues = cardDefinition[ "KeyValues" ]
local SpawnClass = cardDefinition[ "SpawnClass" ]
local SpawnFlags = cardDefinition[ "SpawnFlags" ]
local SquadGroup = cardDefinition[ "SquadGroup" ]
local WeaponClass = cardDefinition[ "WeaponClass" ]
local WeaponProficiency = cardDefinition[ "WeaponProficiency" ]
local spawnCentre = spawnpoint:GetPos()
team = team or "nullteam"
-- TODO: Adjust position for multiple NPCs as otherwise things will be screwy
local spawned = {}
for i = 1, Count do
local spawnPos = self:FindSpawnNear( spawnCentre )
if not spawnPos then
print( "**** ERROR: Unable to spawn NPC " .. i .. " of " .. Count .. " (" .. tostring(SpawnClass) .. ") - This is usually a mapping error!" )
return spawned
end
local npc = ents.Create( SpawnClass )
if not IsValid( npc ) then
error( "Attempt to spawn invalid NPC class " .. tostring(SpawnClass) .. "!" )
end
-- TODO: Implement position offsets
npc:SetPos( spawnPos )
npc:SetAngles( spawnpoint:GetAngles() )
npc:SetMaxHealth( Health )
npc:SetHealth( Health )
if ChangeModel then npc:SetModel( ChangeModel ) end
if SpawnFlags then npc:SetKeyValue( "spawnflags", SpawnFlags ) end
if WeaponClass then npc:SetKeyValue( "additionalequipment", tostring(WeaponClass) ) end
-- Additional key values?
if KeyValues then
for k, v in pairs(KeyValues) do
npc:SetKeyValue( tostring(k), tostring(v) )
end
end
if SquadGroup then npc:SetKeyValue( "SquadName", "team_" .. tostring(team) .. "_" .. SquadGroup ) end
npc:SetKeyValue( "wakeradius", "25000.00" )
npc:SetKeyValue( "ignoreunseenenemies", "0" )
npc:Spawn()
npc:Activate()
npc:DropToFloor()
npc.DamageSettings = DamageSettings
-- Wait for the NPC to initialise, then tell it to wake up (makes for more interesting battles)
timer.Simple( 0.5, function()
npc:SetSchedule( SCHED_ALERT_WALK )
end )
if WeaponProficiency then npc:SetCurrentWeaponProficiency( WeaponProficiency ) end
table.insert( spawned, npc )
end
return spawned
end
--[[
Name: GM:FindSpawnNear( centrePoint )
Desc: Checks 9 possible spawn positions around the given centrepoint. This is done by performing
9 hull traces.
Returns: The first valid spawn position found around centrePoint, or nil if no position was found.
]]--
function GM:FindSpawnNear( centrePoint )
local hullSize = Vector( 20, 20, 80 )
local xsz, ysz = hullSize.x + 15, hullSize.y + 15
local points = {
centrePoint + Vector( -xsz, -ysz, 0 ),
centrePoint + Vector( -xsz, 0, 0 ),
centrePoint + Vector( -xsz, ysz, 0 ),
centrePoint + Vector( 0, -ysz, 0 ),
centrePoint,
centrePoint + Vector( 0, ysz, 0 ),
centrePoint + Vector( xsz, -ysz, 0 ),
centrePoint + Vector( xsz, 0, 0 ),
centrePoint + Vector( xsz, ysz, 0 )
}
local trace = {
mins = Vector( -hullSize.x / 2, -hullSize.x / 2, 0 ),
maxs = Vector( hullSize.x / 2, hullSize.x / 2, hullSize.z ),
filter = "prop_ragdoll"
}
for k, point in pairs( points ) do
-- Perform a trace to see if we can spawn something in here
trace.start = point + Vector(0, 0, 10)
trace.endpos = point + Vector(0, 0, 50)
local result = util.TraceHull( trace )
if not result.Hit then
return point
end
end
return nil
end
--[[
Name: GM:OnEntityCreated( ent )
Desc: Used within card wars to destroy things such as headcrabs which may spawn during the round
and may disrupt the balance of the game.
]]--
function GM:OnEntityCreated( ent )
-- A blacklist of classes which are not allowed to spawn during a round.
-- A blanked 'npc_*' ban is not used because npc_grenade_frag is a thing.
local bannedSpawns = {
"npc_headcrab",
"npc_headcrab_fast",
"npc_headcrab_black"
}
-- This needs to run even when in post-round
if self:IsRoundInProgress() or self.RoundState == self.STATE_POSTROUND then
local class = ent:GetClass()
print( "Entity ", class, " created during round" )
-- Delete if within blacklist
for _, banned in pairs( bannedSpawns ) do
if banned == class then
ent:Remove()
print( "... removed!" )
return
end
end
end
end
|
description = [[
Attemts to find valid sid for tcp modbus server.
]]
---
-- @usage
-- nmap --script modbus-enum.nse --script-args='functionId=8, aggressive=true, data="00 AA BB CC"' -p 502 <host>
--
-- @args functionId - modbus request function id. Valid function codes are 1-247
-- @args aggressive - boolean value defines find all or just first sid
-- @args data - payload data for modbus request in hex form. Example: "AA BB CC DD"
--
-- @output
-- PORT STATE SERVICE
-- 502/tcp open modbus
-- | modbus-enum:
-- | Positive response for sid = 0x64
-- | Positive error response for sid = 0x96
-- |_ Positive response for sid = 0xc8
--
-- Version 0.1
--
-- This script is a NSE port of modscan utility written by Mark Bristow.
-- MODBUS TCP protocol has no any authentication and allow to find information
-- about legal sids by bruteforse.
-- Presentation about tcp modbus protocol and modscan utility from Defcon 16
-- can be found here https://www.defcon.org/images/defcon-16/dc16-presentations/defcon-16-bristow.pdf
-- Modscan utility is hosted at google code: http://code.google.com/p/modscan/
--
---
author = "Alexander Rudakov"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"discovery", "intrusive"}
require "bin"
require "comm"
require "stdnse"
require "shortport"
portrule = shortport.portnumber(502, "tcp")
local form_rsid = function(sid, functionId, data)
local payload_len = 2
if ( #data > 0 ) then
payload_len = payload_len + #data
end
return bin.pack('CCCCC', 0x00, 0x00, 0x00, 0x00, 0x00) .. bin.pack('C', payload_len) .. bin.pack('C', sid) .. bin.pack('C', functionId) .. data
end
action = function(host, port)
local functionId = 8 -- default function code for diagnostics
local aggressive = false -- stop on first founded sid
local data = "00 00 AA BB" -- diagnostic code, just return data
if (nmap.registry.args['functionId']) then
functionId = nmap.registry.args['functionId']
end
if (nmap.registry.args['aggressive']) then
aggressive = nmap.registry.args['aggressive']
end
if (nmap.registry.args['data']) then
data = bin.pack('H', nmap.registry.args['data'])
end
local results = {}
for sid = 1, 246 do
stdnse.print_debug(3, "Sending command with sid = %d", sid)
rsid = form_rsid(sid, functionId, data)
local status, result = comm.exchange(host, port, rsid)
if ( status and #result >= 8 ) then
local ret_code = string.byte(result, 8)
if ret_code == (functionId + 0) then
table.insert(results, ("Positive response for sid = 0x%x"):format(sid))
if ( not aggressive ) then break end
elseif ret_code == (functionId + 128) then
table.insert(results, ("Positive error response for sid = 0x%x"):format(sid))
if ( not aggressive ) then break end
end
end
end
if ( #results > 0 ) then
port.state = "open"
port.version.name = "modbus"
nmap.set_port_version(host, port, "hardmatched")
end
return stdnse.format_output(true, results)
end
|
-- LYNNA CITY/VILLAGE
function lynna()
return destroy_bush_flute() or has("echoes")
end
function ambi_palace()
return (destroy_bush_flute() or has("echoes")) and
(destroy_bush() and has("mermaidsuit")) or
has("ages")
end
function ambi_palace_hard()
return ambi_palace() or
-- guard skip
(has("satchel") and has("scentseeds") and has("pegasusseeds"))
end
function rescue_nayru()
return use_seeds() and has("mysteryseeds") and
has("hook1") and (has("sword1") or punch())
end
function rescue_nayru_hard()
return use_seeds() and has("mysteryseeds") and
has("hook1") and (has("sword1") or punch())
end
function raft()
return has("rope") and has("chart") and
(destroy_bush_flute() or has("echoes"))
end
function shore()
return has("rickygloves") or has("mermaidsuit") or
(destroy_bush_flute() and (has("feather") or has("ages"))) or
has("bracelet") or
(has("currents") and (has("feather") or has("flippers") or raft()))
end
function pop_balloon()
return has("sword1") or has("boomerang")
end
-- CRESCENT ISLAND
function crescent_present()
return dimitri() or
(lynna() and has("mermaidsuit")) or
(raft() and (has("currents") or (has("shovel") and has("echoes"))))
end
function crescent_past()
return raft() or
(lynna() and has("mermaidsuit")) or
(dimitri() and has("currents"))
end
-- SYMMETRY CITY
function nuun()
return lynna() and
(has("currents") or
(has("shooter") and has("emberseeds") and
(has("bracelet") or has("flippers") or dimitri())))
end
function nuun_hard()
return lynna() and
(has("currents") or
(has("shooter") and has("emberseeds") and
(has("bracelet") or has("flippers") or dimitri() or
(has("hook1") and has("satchel") and has("scentseeds")))))
end
function patch_nut()
return has("sword1")
end
function patch_nut_hard()
return patch_nut() or
(use_seeds() and has("scentseeds")) or
has("shield1") or
has("boomerang") or
has("hook1") or
has("shovel")
end
--ROLLING RIDGE
function west_ridge_present()
return (has("feather") or has("ages")) and
((has("hook1") and has("currents")) or --From start
(lynna() and has("mermaidsuit") and has("currents") and max_jump() >= 2))
end
function west_ridge_past()
return (has("bombflower") and has("hook1") and --From start
(has("feather") or has("ages"))) or
(west_ridge_present() and (has("ages") or
(has("bracelet") and has ("echoes"))))--From present ridge
end
-- Clean this check up someday
function D5keys()
if hit_switch() and (has("cane") or has("hook1")) and --key 1, dark chest
hit_far_switch() and (has("hook1") or (has("feather") and has("cane"))) and --key 2, Any%
has("shooter") and --key 3, 3 statues
(destroy_pot() and has("cane") and has("feather") and
(has("shooter") or has("boomerang"))) and --key 4, 2 statues
has("cane") --key 5, before somaria chest
then
return true, AccessibilityLevel.Normal
elseif D5keys_hard() then
return true, AccessibilityLevel.SequenceBreak
else
return false, AccessibilityLevel.None
end
end
function D5keys_hard()
return hit_switch() and (has("cane") or has("hook1") or
(kill_hard() or push_enemy())) and --key 1, dark chest
(hit_far_switch() or has("bracelet")) and (has("hook1") or (has("feather") and has("cane"))) and --key 2, Any%
(has("shooter") or
(max_jump() >= 2 and (hit_far_switch() or (has("bracelet") and has("ring_toss"))) and
has("satchel") and (has("emberseeds") or has("scentseeds") or has("mysteryseeds")))) and --key 3, 3 statues
(destroy_pot() and has("cane") and has("feather") and
(has("shooter") or has("boomerang") or (has("sword1") and has("feather")))) and --key 4, 2 statues
has("cane") --key 5, before somaria chest
end
function ridge_base_past_east()
return lynna() and (has("feather") or has("ages")) and has("mermaidsuit") --through the sea
end
function openD6wall()
return has("cane") and has("bombs") and has("bracelet") and has("feather") and
((has("shooter") and has("emberseeds")) or
(use_seeds() and has("emberseeds") and
(kill_ranged() or has("feather") or
(has("satchel") and has("scentseeds")))))
end
function openD6wall_hard()
return has("cane") and has("bombs") and has("bracelet") and has("feather") and
((has("shooter") and has("emberseeds")) or
(use_seeds() and has("emberseeds") and
(kill_ranged_hard() or has("feather") or
(has("satchel") and has("scentseeds")))))
end
function D6keys()
return (has("fippers") or has("feather") or has("hook1")) and
(has("shooter") or has("boomerang") or max_jump() >= 2) and --cross pits room
(has("satchel") and has("scentseeds")) and--key 1, ropes
(has("shooter") or has("boomerang") or (max_jump() >= 2 and
(has("sword1") or has("hook1") or
(use_seeds() and has ("emberseeds")) or
(use_seeds() and has ("scentseeds")) or
(use_seeds() and has ("mysteryseeds"))))) and-- get to present hands room
has("bombs") and has("hook1") and has("feather") and--key 2, dice
openD6wall() and--get to vire spinner
(has("feather") or has("hook1")) --key 3, spinner
end
function D6keys_hard()
return (has("fippers") or has("feather") or has("hook1")) and
(has("shooter") or has("boomerang") or max_jump() >= 2) and --cross pits room
has("satchel") and has("scentseeds") and--key 1, ropes
(has("shooter") or has("boomerang") or (max_jump() >= 2 and
(has("sword1") or has("hook1") or has("bombs") or
(use_seeds() and has ("emberseeds")) or
(use_seeds() and has ("scentseeds")) or
(use_seeds() and has ("mysteryseeds"))))) and-- get to present hands room
has("bombs") and has("hook1") and has("feather") and--key 2, dice
openD6wall_hard() and--get to vire spinner
(has("feather") or has("hook1")) --key 3, spinner
end
-- ZORA SEAS
function drainD7()
if (has("mermaidsuit") and Tracker:ProviderCountForCode("d7sk") >= 3) or
(has("hook2") and Tracker:ProviderCountForCode("d7sk") >= 4) then
return true, AccessibilityLevel.Normal
elseif has("mermaidsuit") and Tracker:ProviderCountForCode("d7sk") >= 1 then
return true, AccessibilityLevel.SequenceBreak
else
return false, AccessibilityLevel.None
end
end
function refillD7()
return has("mermaidsuit") and drainD7() and has("hook1")
end
function floodD7()
if has("hook2") and
Tracker:ProviderCountForCode("d7sk") >= 4 then
return true, AccessibilityLevel.Normal
elseif has("hook2") and
Tracker:ProviderCountForCode("d7sk") >= 2 then
return true, AccessibilityLevel.SequenceBreak
else
return false, AccessibilityLevel.None
end
end
-- FULL CLEAR CHECKS --
function d1clear()
return use_seeds() and has("emberseeds") and
has("bracelet") and kill_ghini() and kill_pumpkinhead()
end
function d1clear_hard()
return use_seeds() and has("emberseeds") and
has("bracelet") and kill_ghini_hard() and kill_pumpkinhead_hard()
end
function d2clear()
return has("feather") and has("bombs") and
(has("bracelet") or has("cane")) and
hit_lever() and kill_normal() and
kill_beetle() and kill_swoop()
end
function d2clear_hard()
return has("feather") and has("bombs") and
(has("bracelet") or has("cane") or
(has("shield1") and has("hook1"))) and
hit_lever() and kill_hard() and
kill_beetle_hard() and kill_swoop_hard()
end
function d3clear()
return has("bombs") and has("shooter") and has("emberseeds") and
--not actually needed in all cases but if there's a key at Shadow Hag it's very much needed
(Tracker:ProviderCountForCode("d3sk") >= 4 or max_jump() >= 2) and
kill_moldorm() and kill_armos() and kill_subterror()
end
function d3clear_hard()
return has("bombs") and has("shooter") and
(has("emberseeds") or has("mysteryseeds")) and
--not actually needed in all cases but if there's a key at Shadow Hag it's very much needed
(Tracker:ProviderCountForCode("d3sk") >= 4 or has("feather")) and
kill_moldorm_hard() and kill_armos_hard() and kill_subterror_hard()
end
function d4clear()
return has("feather") and has("bracelet") and
has("hook1") and has("bombs") and has("shooter") and
(has("sword1") or has("emberseeds") or
has("scentseeds") or has("galeseeds")) and
kill_normal() and (has("sword1") or has("boomerang"))
end
function d4clear_hard()
return has("feather") and has("bracelet") and
has("hook1") and has("bombs") and
(has("shooter") and (has("emberseeds") or
has("scentseeds") or has("galeseeds")) or
(has("boomerang") and ((has("satchel") and has("scentseeds"))
or has("sword1")))) and
kill_normal() and (has("sword1") or has("boomerang"))
end
function d5clear()
return has("cane") and has("hook1") and
has("sword1") and has("feather") and has("bracelet") and
has("shooter") and has("emberseeds") and
Tracker:ProviderCountForCode("d5sk") >= 5
end
function d5clear_hard()
-- Should be the same as above, keeping it separate in case of future changes
return has("cane") and has("hook1") and
has("sword1") and has("feather") and has("bracelet") and
has("shooter") and has("emberseeds") and
Tracker:ProviderCountForCode("d5sk") >= 5
end
function d6clear_present()
return has("hook1") and has("bombs") and has("feather") and
has("d6key") and openD6wall() and has("bracelet") and
has("shooter") and has("emberseeds") and
has("satchel") and has("scentseeds") and
(has("sword1") or has("ring_expert")) and
Tracker:ProviderCountForCode("d6sk_present") >= 3
end
function d6clear_present_hard()
return has("hook1") and has("bombs") and
has("d6key") and openD6wall() and has("bracelet") and
has("shooter") and has("emberseeds") and
has("satchel") and has("scentseeds") and
Tracker:ProviderCountForCode("d6sk_present") >= 3
end
function d6clear_present_shuffle()
return has("hook1") and has("bombs") and has("feather") and
d6_past_shuffle() and openD6wall() and has("bracelet") and
has("shooter") and has("emberseeds") and
has("satchel") and has("scentseeds") and
(has("sword1") or has("ring_expert")) and
Tracker:ProviderCountForCode("d6sk_present") >= 3
end
function d6clear_present_shuffle_hard()
return has("hook1") and has("bombs") and
d6_past_shuffle_hard() and openD6wall() and has("bracelet") and
has("shooter") and has("emberseeds") and
has("satchel") and has("scentseeds") and
Tracker:ProviderCountForCode("d6sk_present") >= 3
end
function d6clear()
return has("d6keyold") and d6clear_present() and has("cane") and
has("bombs") and has("shooter") and has("emberseeds") and
has("mermaidsuit") and has("hook1") and has("feather")
end
function d6clear_hard()
return has("d6keyold") and d6clear_present_hard() and has("cane") and
has("bombs") and has("shooter") and has("emberseeds") and
has("mermaidsuit") and has("hook1") and has("feather")
end
function d6clear_shuffle()
return d6_present_shuffle() and d6clear_present_shuffle() and has("cane") and
has("bombs") and has("shooter") and has("emberseeds") and
has("mermaidsuit") and has("hook1") and has("feather")
end
function d6clear_shuffle_hard()
return d6_present_shuffle_hard() and d6clear_present_shuffle_hard() and has("cane") and
has("bombs") and has("shooter") and has("emberseeds") and
has("mermaidsuit") and has("hook1") and has("feather")
end
function d7clear()
return has("hook2") and has("cane") and
kill_underwater() and has("feather") and
Tracker:ProviderCountForCode("d7sk") >= 7
end
function d7clear_hard()
return has("hook2") and has("cane") and
kill_underwater_hard() and has("feather") and
Tracker:ProviderCountForCode("d7sk") >= 7
end
function d8clear()
return has("bombs") and has("cane") and
has("hook1") and has("shooter") and
has("emberseeds") and has("scentseeds") and
has("powerglove") and has("feather") and has("sword1")
end
function d8clear_hard()
-- Should be the same as above, keeping it separate in case of future changes
return has("bombs") and has("cane") and
has("hook1") and has("shooter") and
has("emberseeds") and has("scentseeds") and
has("powerglove") and has("feather") and has("sword1")
end
|
kBlueColor = Color(0, 0.5117, 1, 1)
kRedColor = Color(1, 0.2941, 0, 1)
|
-- scaffolding entry point for filament
return dofile("filament.lua")
|
local POTIONS = {7588, 7589}
function onUse(cid, item, fromPosition, itemEx, toPosition)
doTransformItem(item.uid, POTIONS[math.random(1, table.maxn(POTIONS))])
doSendMagicEffect(fromPosition, CONST_ME_MAGIC_RED)
return true
end
|
-- This will be called after data-updates.lua
|
if not redux then redux = {} end
if not redux.modules then redux.modules = {} end
require("prototypes.modules")
require("prototypes.recipe")
require("prototypes.item-groups")
|
--[[----------------------------------------------------------------------------
Application Name:
InspectorP_FirstSteps
Summary:
Sample application to InspectorP_FirstSteps Tutorial.
How to Run:
This sample contains several scripts which are part of the InspectorP_FirstSteps
tutorial. Each script can be run independently and is the result of the corresponding
tutorial slides.
Since the scripts are independently executable, scripts with higher prefix number
contains the same code as the previous one plus the new functionality.
To show this sample, set the wanted script as main (right-click -> "Set as main")
before running the app.
More Information:
See the tutorial "Devices - InspectorP - InspectorP_FirstSteps".
------------------------------------------------------------------------------]]
|
local utils = require("heirline.utils")
local M = {}
M.colours = {
white = "#b5bcc9",
grey_fg = "#737D87",
short_bg = "#34393D",
red = "#EF949C",
red_dark = "#B34B4B",
green = "#B0E5CA",
green_pale = "#839C8F",
nord_blue = "#9aa8cf",
yellow = "#fbdf90",
yellow_pale = "#B39E67",
purple = "#9F78E1",
statusline_bg = "#181f26",
light_bg = "#222930",
light_bg2 = "#1d242b",
mid_bg = "#2B3033",
orange = utils.get_highlight("DiagnosticWarn").fg,
folder = utils.get_highlight("NvimTreeFolderIcon").fg,
cyan = utils.get_highlight("Special").fg,
diag = {
warn = utils.get_highlight("DiagnosticWarn").fg,
error = utils.get_highlight("DiagnosticError").fg,
hint = utils.get_highlight("DiagnosticHint").fg,
info = utils.get_highlight("DiagnosticInfo").fg,
},
git = {
del = "#A3214C",
add = "#3D5213",
change = "#537196",
},
}
M.mode_mappings = {
["n"] = { "Normal", "-" },
["no"] = { "Op·Pending", "P" },
["nov"] = { "Op·Pending", "v" },
["noV"] = { "Op·Pending", "V" },
["niI"] = { "(Normal)", "I" },
["niR"] = { "(Normal)", "R" },
["niV"] = { "(Normal)", "V" },
["nt"] = { "Normal", "T" },
["v"] = { "Visual", "C" },
["V"] = { "V·Line", "L" },
[""] = { "V·Block", "B" },
["s"] = { "Select", "-" },
["S"] = { "S·Line", "L" },
[""] = { "S·Block", "B" },
["i"] = { "Insert", "-" },
["ic"] = { "Ins·Compl", "C" },
["ix"] = { "Ins·Compl", "X" },
["R"] = { "Replace", "-" },
["Rv"] = { "Replace", "V" },
["Rx"] = { "Replace", "X" },
["c"] = { "Command", "-" },
["cv"] = { "Vim·Ex", "Q" },
["ce"] = { "Ex", "-" },
["r"] = { "Prompt", "-" },
["rm"] = { "More", "-" },
["r?"] = { "Confirm", "-" },
["!"] = { "Shell", "-" },
["t"] = { "Terminal", "-" },
[""] = { "Empty", "-" },
}
M.vi_mode_colors = {
NORMAL = "green",
OP = "green",
INSERT = "red",
VISUAL = "skyblue",
LINES = "skyblue",
BLOCK = "skyblue",
REPLACE = "violet",
["V-REPLACE"] = "violet",
ENTER = "cyan",
MORE = "cyan",
SELECT = "orange",
COMMAND = "green",
SHELL = "green",
TERM = "green",
NONE = "yellow",
}
M.separators = {
vertical_bar = "┃",
vertical_bar_thin = "│",
left = "",
right = "",
block = "█",
left_filled = "",
right_filled = "",
slant_left = "",
slant_left_thin = "",
slant_right = "",
slant_right_thin = "",
slant_left_2 = "",
slant_left_2_thin = "",
slant_right_2 = "",
slant_right_2_thin = "",
left_rounded = "",
left_rounded_thin = "",
right_rounded = "",
right_rounded_thin = "",
circle = "●",
github_icon = " ﯙ ",
folder_icon = " ",
database = " ",
}
local mode_colors = {
NORMAL = "green",
OP = "green",
INSERT = "red",
VISUAL = "skyblue",
LINES = "skyblue",
BLOCK = "skyblue",
REPLACE = "violet",
["V-REPLACE"] = "violet",
ENTER = "cyan",
MORE = "cyan",
SELECT = "orange",
COMMAND = "green",
SHELL = "green",
TERM = "green",
NONE = "yellow",
}
M.mode_names = {
n = { "Normal", "-" },
no = { "Op·Pending", "P" },
nov = { "Op·Pending", "v" },
noV = { "Op·Pending", "V" },
niI = { "(Normal)", "I" },
niR = { "(Normal)", "R" },
niV = { "(Normal)", "V" },
nt = { "Normal", "T" },
v = { "Visual", "C" },
V = { "V·Line", "L" },
[""] = { "V·Block", "B" },
s = { "Select", "-" },
S = { "S·Line", "L" },
[""] = { "S·Block", "B" },
i = { "Insert", "-" },
ic = { "Ins·Compl", "C" },
ix = { "Ins·Compl", "X" },
R = { "Replace", "-" },
Rv = { "Replace", "V" },
Rx = { "Replace", "X" },
c = { "Command", "-" },
cv = { "Vim·Ex", "Q" },
ce = { "Ex", "-" },
r = { "Prompt", "-" },
rm = { "More", "-" },
["r?"] = { "Confirm", "-" },
["!"] = { "Shell", "-" },
t = { "Terminal", "-" },
[""] = { "Empty", "-" },
}
local mode_alias = {
n = "NORMAL",
no = "OP",
nov = "OP",
noV = "OP",
["no"] = "OP",
niI = "NORMAL",
niR = "NORMAL",
niV = "NORMAL",
nt = "NORMAL",
v = "VISUAL",
V = "LINES",
[""] = "BLOCK",
s = "SELECT",
S = "SELECT",
[""] = "BLOCK",
i = "INSERT",
ic = "INSERT",
ix = "INSERT",
R = "REPLACE",
Rc = "REPLACE",
Rv = "V-REPLACE",
Rx = "REPLACE",
c = "COMMAND",
cv = "COMMAND",
ce = "COMMAND",
r = "ENTER",
rm = "MORE",
["r?"] = "CONFIRM",
["!"] = "SHELL",
t = "TERM",
["null"] = "NONE",
}
---Returns the designated colour for the mode.
---@param mode string
---@return string
function M.mode_colour(mode)
return M.colours[mode_colors[mode_alias[mode]]]
end
M.force_inactive = {
filetypes = { "NvimTree", "dbui", "packer", "startify", "fugitive", "fugitiveblame" },
buftypes = { "terminal" },
bufnames = {},
}
---@return string
function M.vim_mode()
local mode = M.mode_mappings[vim.fn.mode()]
local value = ""
if vim.g.libmodalActiveModeName then
mode = { vim.g.libmodalActiveModeName, "U" }
end
if mode ~= nil then
value = mode[1]
if mode[2] ~= "-" then
value = value .. " [" .. mode[2] .. "]"
end
end
return value
end
---Return parent path for specified entry (either file or directory), nil if
-- there is none. Adapted from from galaxyline.
---@param path string
---@return string
local function parent_pathname(path)
local i = path:find("[\\/:][^\\/:]*$")
if not i then
return
end
return path:sub(1, i - 1)
end
---Returns the git directory for the current file. Adapted from from
-- galaxyline.
---@param path string
---@return string
local function get_git_dir(path)
-- Checks if provided directory contains git directory
local function has_git_dir(dir)
local git_dir = dir .. "/.git"
if vim.fn.isdirectory(git_dir) == 1 then
return git_dir
end
end
-- Get git directory from git file if present
local function has_git_file(dir)
local gitfile = io.open(dir .. "/.git")
if gitfile ~= nil then
local git_dir = gitfile:read():match("gitdir: (.*)")
gitfile:close()
return git_dir
end
end
-- Check if git directory is absolute path or a relative
local function is_path_absolute(dir)
local patterns = {
"^/", -- unix
"^%a:[/\\]", -- windows
}
for _, pattern in ipairs(patterns) do
if string.find(dir, pattern) then
return true
end
end
return false
end
-- If path nil or '.' get the absolute path to current directory
if not path or path == "." then
path = vim.fn.getcwd()
end
local git_dir
-- Check in each path for a git directory, continues until found or reached
-- root directory
while path do
-- Try to get the git directory checking if it exists or from a git file
git_dir = has_git_dir(path) or has_git_file(path)
if git_dir ~= nil then
break
end
-- Move to the parent directory, nil if there is none
path = parent_pathname(path)
end
if not git_dir then
return
end
if is_path_absolute(git_dir) then
return git_dir
end
return path .. "/" .. git_dir
end
---Returns the git root of the current file.
---@return string
function M.git_root()
local git_dir = get_git_dir(nil)
if not git_dir then
return ""
end
-- local root = git_dir:gsub("/.git/?", "")
-- sub_root is a path to a worktree if exists.
local sub_root = git_dir:match("/([^/]+)/.git/worktrees/.+$")
local repo = ""
if sub_root then
repo = " [" .. sub_root .. "]"
end
return repo
end
function M.dir_name(_, opts)
if opts.short then
return vim.fn.expand("%:h"):match("[^/\\]+$") or ""
end
return vim.fn.expand("%:h") or ""
end
local function short_filename(short)
if #vim.fn.expand("%:p") == 0 then
return "-"
end
if short then
return vim.fn.expand("%:t")
end
return vim.fn.expand("%:~")
end
local function file_readonly()
if vim.bo.filetype == "help" then
return ""
end
local icon = ""
if vim.bo.readonly == true then
return " " .. icon .. " "
end
return ""
end
function M.filename(_, opts)
local short = opts.short or false
local file = short_filename(short)
if vim.fn.empty(file) == 1 then
return ""
end
if string.len(file_readonly()) ~= 0 then
return file .. file_readonly()
end
local icon = ""
if vim.bo.modifiable and vim.bo.modified then
return file .. " " .. icon .. " "
end
return file .. " "
end
function M.search_results()
local lines = vim.api.nvim_buf_line_count(0)
if lines > 50000 then
return ""
end
local search_term = vim.fn.getreg("/")
if search_term == "" then
return ""
end
if search_term:find("@") then
return ""
end
local search_count = vim.fn.searchcount({
recompute = 1,
maxcount = -1,
})
local active = false
if vim.v.hlsearch and vim.v.hlsearch == 1 and search_count.total > 0 then
active = true
end
if not active then
return ""
end
search_term = search_term:gsub([[\<]], ""):gsub([[\>]], "")
return "/" .. search_term .. "[" .. search_count.current .. "/" .. search_count.total .. "]"
end
function M.locallist_count()
local ll = vim.fn.getloclist(vim.fn.winnr(), {
idx = 0,
size = 0,
})
local count = ll.size
local current = ll.idx
return (" %d/%d "):format(current, count)
end
function M.quickfix_count()
local qf = vim.fn.getqflist({
idx = 0,
size = 0,
})
local count = qf.size
local current = qf.idx
return (" %d/%d "):format(current, count)
end
local lsp_config = {
errors = "",
warnings = "",
info = "🛈",
hints = "!",
ok = "",
spinner_frames = { "⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷" },
component_separator = " ",
lsp_icon = " ",
}
local lsp_names = {
["null-ls"] = "Null",
["diagnostics_on_open"] = "Diagnostics",
["diagnostics_on_save"] = "Diagnostics",
bashls = "Bash",
clangd = "C++",
dockerls = "Docker",
gopls = "Go",
golangci_lint_ls = "GolangCI",
html = "HTML",
jedi_language_server = "Python",
jsonls = "JSON",
sqls = "SQL",
sumneko_lua = "Lua",
vimls = "Vim",
yamlls = "YAML",
}
function M.lsp_client_names()
local clients = {}
for _, client in pairs(vim.lsp.buf_get_clients(0)) do
local name = lsp_names[client.name] or client.name
clients[#clients + 1] = name
end
return table.concat(clients, lsp_config.component_separator), lsp_config.lsp_icon
end
function M.fold_method()
local name = ({
marker = "MKR",
manual = "MNL",
syntax = "SYN",
indent = "IND",
expr = "EXP",
})[vim.wo.foldmethod] or vim.wo.foldmethod or "N/A"
return string.format("%s[%d]", name, vim.wo.foldlevel)
end
---Turns the severity to a form vim.diagnostic.get accepts.
---@param severity string
---@return string
local function severity_lsp_to_vim(severity)
if type(severity) == "string" then
severity = vim.lsp.protocol.DiagnosticSeverity[severity]
end
return severity
end
---Returns the diagnostic count for the current buffer.
---@param severity string
---@return number
function M.get_diagnostics_count(severity)
local active_clients = vim.lsp.buf_get_clients(0)
if not active_clients then
return 0
end
severity = severity_lsp_to_vim(severity)
local opts = {
severity = severity,
}
return #vim.diagnostic.get(vim.api.nvim_get_current_buf(), opts)
end
---Returns true if there is a diagnostic with the given severity.
---@param severity string
---@return boolean
function M.diagnostics_exist(severity)
return M.get_diagnostics_count(severity) > 0
end
---Common function used by the diagnostics providers
local function diagnostics(severity)
local count = M.get_diagnostics_count(severity)
return count ~= 0 and tostring(count) or ""
end
---Returns the count of errors and a icon.
---@return string
---@return string
function M.diagnostic_errors()
return diagnostics(vim.diagnostic.severity.ERROR), " "
end
---Returns the count of warnings and a icon.
---@return string
---@return string
function M.diagnostic_warnings()
return diagnostics(vim.diagnostic.severity.WARN), " "
end
---Returns the count of hints and a icon.
---@return string
---@return string
function M.diagnostic_hints()
return diagnostics(vim.diagnostic.severity.HINT), " "
end
---Returns the count of informations and a icon.
---@return string
---@return string
function M.diagnostic_info()
return diagnostics(vim.diagnostic.severity.INFO), " "
end
local sqls_status = {
subscribed = false,
connection = nil,
database = "default",
}
function M.sqls_status()
local ok, events = pcall(require, "sqls.events")
if not ok then
return ""
end
if not sqls_status.subscribed then
events.add_subscriber("connection_choice", function(event)
local items = vim.split(event.choice, " ")
sqls_status.connection = items[3]
local _, _, name = event.choice:find("dbname=([^ ]+)")
sqls_status.database = name or "Unknown"
end)
events.add_subscriber("database_choice", function(event)
sqls_status.database = event.choice
end)
sqls_status.sqls_subscribed = true
end
if not sqls_status.connection or not sqls_status.database then
return ""
end
return sqls_status.connection .. M.separators.database .. sqls_status.database
end
return M
|
---------------------------------------------
-- Slowga
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/msg")
---------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0
end
function onPetAbility(target, pet, skill, summoner)
local duration = 180 + summoner:getMod(tpz.mod.SUMMONING)
if duration > 350 then
duration = 350
end
if target:addStatusEffect(tpz.effect.SLOW, 3000, 0, duration) then
skill:setMsg(tpz.msg.basic.SKILL_ENFEEB_IS)
else
skill:setMsg(tpz.msg.basic.SKILL_NO_EFFECT)
end
return tpz.effect.SLOW
end
|
-----------------------------------
-- Area: Xarcabard
-- Mob: Cursed Weapon
-- Note: PH for Barbaric Weapon
-----------------------------------
local ID = require("scripts/zones/Xarcabard/IDs")
require("scripts/globals/regimes")
require("scripts/globals/mobs")
-----------------------------------
function onMobDeath(mob, player, isKiller)
tpz.regime.checkRegime(player, mob, 52, 2, tpz.regime.type.FIELDS)
tpz.regime.checkRegime(player, mob, 53, 3, tpz.regime.type.FIELDS)
end
function onMobDespawn(mob)
tpz.mob.phOnDespawn(mob, ID.mob.BARBARIC_WEAPON_PH, 10, 7200) -- 2 hours
end
|
hanadak_ancient = Creature:new {
objectName = "@mob/creature_names:hanadak_ancient",
socialGroup = "hanadak",
faction = "",
level = 41,
chanceHit = 0.44,
damageMin = 345,
damageMax = 400,
baseXp = 4097,
baseHAM = 9300,
baseHAMmax = 11300,
armor = 0,
resists = {30,30,-1,200,200,200,-1,-1,-1},
meatType = "meat_carnivore",
meatAmount = 40,
hideType = "hide_bristley",
hideAmount = 40,
boneType = "bone_mammal",
boneAmount = 40,
milk = 0,
tamingChance = 0.25,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + HERD + KILLER,
optionsBitmask = AIENABLED,
diet = CARNIVORE,
templates = {"object/mobile/hanadak_hue.iff"},
hues = { 16, 17, 18, 19, 20, 21, 22, 23 },
scale = 1.15,
lootGroups = {},
weapons = {},
conversationTemplate = "",
attacks = {
{"knockdownattack",""},
{"blindattack",""}
}
}
CreatureTemplates:addCreatureTemplate(hanadak_ancient, "hanadak_ancient")
|
local Engine = require("trip.Engine")
function love.load(arg)
love.physics.setMeter(1)
love.event.pump() -- Prevent freeze in LÖVE 11.3
love.mouse.setRelativeMode(true)
local resources = {}
engine = Engine.new(resources, {})
end
function love.update(dt)
engine:update(dt)
end
function love.draw()
engine:draw()
end
function love.mousemoved(x, y, dx, dy, istouch)
engine:mousemoved(x, y, dx, dy, istouch)
end
|
local comm = require "comm"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
description = [[
Checks an IRC server for channels that are commonly used by malicious botnets.
Control the list of channel names with the <code>irc-botnet-channels.channels</code>
script argument. The default list of channels is
* loic
* Agobot
* Slackbot
* Mytob
* Rbot
* SdBot
* poebot
* IRCBot
* VanBot
* MPack
* Storm
* GTbot
* Spybot
* Phatbot
* Wargbot
* RxBot
]]
author = "David Fifield, Ange Gutek"
license = "Same as Nmap--See https://nmap.org/book/man-legal.html"
categories = {"discovery", "vuln", "safe"}
---
-- @usage
-- nmap -p 6667 --script=irc-botnet-channels <target>
-- @usage
-- nmap -p 6667 --script=irc-botnet-channels --script-args 'irc-botnet-channels.channels={chan1,chan2,chan3}' <target>
--
-- @args irc-botnet-channels.channels a list of channel names to check for.
--
-- @output
-- | irc-botnet-channels:
-- | #loic
-- |_ #RxBot
-- See RFC 2812 for protocol documentation.
-- Section 5.1 for protocol replies.
local RPL_TRYAGAIN = "263"
local RPL_LIST = "322"
local RPL_LISTEND = "323"
local DEFAULT_CHANNELS = {
"loic",
"Agobot",
"Slackbot",
"Mytob",
"Rbot",
"SdBot",
"poebot",
"IRCBot",
"VanBot",
"MPack",
"Storm",
"GTbot",
"Spybot",
"Phatbot",
"Wargbot",
"RxBot",
}
portrule = shortport.port_or_service({6666, 6667, 6697, 6679}, {"irc", "ircs"})
-- Parse an IRC message. Returns nil, errmsg in case of error. Otherwise returns
-- true, prefix, command, params. prefix may be nil. params is an array of
-- strings. The final param has the ':' stripped from the beginning.
--
-- The special return value true, nil indicates an empty message to be ignored.
--
-- See RFC 2812, section 2.3.1 for BNF of a message.
local function irc_parse_message(s)
local prefix, command, params
local _, p, t
s = string.gsub(s, "\r?\n$", "")
if string.match(s, "^ *$") then
return true, nil
end
p = 0
_, t, prefix = string.find(s, "^:([^ ]+) +", p + 1)
if t then
p = t
end
-- We do not check for any special format of the command name or
-- number.
_, p, command = string.find(s, "^([^ ]+)", p + 1)
if not p then
return nil, "Presumed message is missing a command."
end
params = {}
while p + 1 <= #s do
local param
_, p = string.find(s, "^ +", p + 1)
if not p then
return nil, "Missing a space before param."
end
-- We don't do any checks on the contents of params.
if #params == 14 then
params[#params + 1] = string.sub(s, p + 1)
break
elseif string.match(s, "^:", p + 1) then
params[#params + 1] = string.sub(s, p + 2)
break
else
_, p, param = string.find(s, "^([^ ]+)", p + 1)
if not p then
return nil, "Missing a param."
end
params[#params + 1] = param
end
end
return true, prefix, command, params
end
local function irc_compose_message(prefix, command, ...)
local parts, params
parts = {}
if prefix then
parts[#parts + 1] = prefix
end
if string.match(command, "^:") then
return nil, "Command may not begin with ':'."
end
parts[#parts + 1] = command
params = {...}
for i, param in ipairs(params) do
if not string.match(param, "^[^\0\r\n :][^\0\r\n ]*$") then
if i < #params then
return nil, "Bad format for param."
else
parts[#parts + 1] = ":" .. param
end
else
parts[#parts + 1] = param
end
end
return stdnse.strjoin(" ", parts) .. "\r\n"
end
local function random_nick()
return stdnse.generate_random_string(9, "abcdefghijklmnopqrstuvwxyz")
end
local function splitlines(s)
local lines = {}
local _, i, j
i = 1
while i <= #s do
_, j = string.find(s, "\r?\n", i)
lines[#lines + 1] = string.sub(s, i, j)
if not j then
break
end
i = j + 1
end
return lines
end
local function irc_connect(host, port, nick, user, pass)
local commands = {}
local irc = {}
local banner
-- Section 3.1.1.
if pass then
commands[#commands + 1] = irc_compose_message(nil, "PASS", pass)
end
nick = nick or random_nick()
commands[#commands + 1] = irc_compose_message(nil, "NICK", nick)
user = user or nick
commands[#commands + 1] = irc_compose_message(nil, "USER", user, "8", "*", user)
irc.sd, banner = comm.tryssl(host, port, table.concat(commands))
if not irc.sd then
return nil, "Unable to open connection."
end
irc.sd:set_timeout(60 * 1000)
-- Buffer these initial lines for irc_readline.
irc.linebuf = splitlines(banner)
irc.buf = stdnse.make_buffer(irc.sd, "\r?\n")
return irc
end
local function irc_disconnect(irc)
irc.sd:close()
end
local function irc_readline(irc)
local line
if next(irc.linebuf) then
line = table.remove(irc.linebuf, 1)
if string.match(line, "\r?\n$") then
return line
else
-- We had only half a line buffered.
return line .. irc.buf()
end
else
return irc.buf()
end
end
local function irc_read_message(irc)
local line, err
line, err = irc_readline(irc)
if not line then
return nil, err
end
return irc_parse_message(line)
end
local function irc_send_message(irc, prefix, command, ...)
local line
line = irc_compose_message(prefix, command, ...)
irc.sd:send(line)
end
-- Prefix channel names with '#' if necessary and concatenate into a
-- comma-separated list.
local function concat_channel_list(channels)
local mod = {}
for _, channel in ipairs(channels) do
if not string.match(channel, "^#") then
channel = "#" .. channel
end
mod[#mod + 1] = channel
end
return stdnse.strjoin(",", mod)
end
function action(host, port)
local irc
local search_channels
local channels
local errorparams
search_channels = stdnse.get_script_args(SCRIPT_NAME .. ".channels")
if not search_channels then
search_channels = DEFAULT_CHANNELS
elseif type(search_channels) == "string" then
search_channels = {search_channels}
end
irc = irc_connect(host, port)
irc_send_message(irc, "LIST", concat_channel_list(search_channels))
channels = {}
while true do
local status, prefix, code, params
status, prefix, code, params = irc_read_message(irc)
if not status then
-- Error message from irc_read_message.
errorparams = {prefix}
break
elseif code == "ERROR" then
errorparams = params
break
elseif code == RPL_TRYAGAIN then
errorparams = params
break
elseif code == RPL_LIST then
if #params >= 2 then
channels[#channels + 1] = params[2]
else
stdnse.debug1("Got short " .. RPL_LIST .. "response.")
end
elseif code == RPL_LISTEND then
break
end
end
irc_disconnect(irc)
if errorparams then
channels[#channels + 1] = "ERROR: " .. stdnse.strjoin(" ", errorparams)
end
return stdnse.format_output(true, channels)
end
|
Guidelime.registerGuide([[
[N20-30 Phelx's Shadowfang Keep (BFD) Guide]
[D Phelx's guide to acquiring all SFK quests. There are 3 total all are exclusive to the Horde.]
[GA Horde]
[O] Quests can be obtained from [XP16 16] with 2 requiring [XP18 18].
[O] This guide starts from Undercity.
Travel to the Apothecarium near the North-Western bridge and speak to Keeper Bel'dugur to accept [QA1013].
Run or Fly to [F The Sepulcher].
Get the Flightpath [P The Sepulcher] if you don't already have it.
Set your hearth to [S The Sepulcher].
Speak to Dalar Dawnweaver to accept [QA1014].
Speak to High Executor Hadrec to accept [QA1098].
**Now enter Shadowfang Keep.**
Complete [QC1013].
The Book for [QC1013] can be found in the room with the boss **Fenrus the Devourer** look on the shelves.
Complete [QC1014].
Hearth to [H The Sepulcher].
Turn in [QT1014][QT1098].
Fly to [F Undercity].
Turn in [QT1013].
]], "Phelx's Dungeon Quest Guide")
|
print("Loading lua file")
print("CTEST_FULL_OUTPUT")
testapp = {
initScene = function (self)
print("In initScene")
end,
preFrame = function (self)
print("In preFrame - Stopping kernel")
vrjKernel.stop()
end
}
print("App delegate defined, now creating OsgAppProxy")
app = vrjApp.OsgAppProxy()
print ("Now setting OsgAppProxy's delegate")
app:setAppDelegate(testapp)
print("Loading config files into kernel")
vrjKernel.loadConfigFile("standalone.jconf")
print("Setting kernel application")
app:setActiveApplication()
print("Starting kernel")
vrjKernel.start()
print("Waiting for kernel stop")
vrjKernel.waitForKernelStop()
|
local ts_utils = require('nvim-treesitter.ts_utils')
local tsm_utils = require('ts-manipulator.utils')
local A = {}
local valid_node_types = {
"argument_list",
"arguments",
"parameter_list",
"parameters",
}
local function table_has_val(tab, val)
for _, tabval in ipairs(tab) do
if tabval == val then
return true
end
end
return false
end
-- To get the current argument's node table
A.get_current = function()
local node = tsm_utils.get_node()
local root_node = ts_utils.get_root_for_node(node)
while true do
local parent = node:parent()
if parent:id() == root_node:id() then
error("The cursor is not above on any argument")
elseif table_has_val(valid_node_types, parent:type()) then
break
else node = parent
end
end
return node
end
-- Visually select the current argument
A.select_current = function()
local bufnr = vim.api.nvim_get_current_buf()
local argument_node = A.get_current()
ts_utils.update_selection(bufnr, argument_node)
end
-- Swap the current argument with the next one (if any)
A.swap_forward = function()
local bufnr = vim.api.nvim_get_current_buf()
local curr_node = A.get_current()
local next_node = ts_utils.get_next_node(curr_node)
if next_node == nil then
-- error("This is the last argument")
return
end
ts_utils.swap_nodes(curr_node, next_node, bufnr, true)
end
-- Swap the current argument with the previous one (if any)
A.swap_backward = function()
local bufnr = vim.api.nvim_get_current_buf()
local curr_node = A.get_current()
local prev_node = ts_utils.get_previous_node(curr_node)
if prev_node == nil then
-- error("This is the first argument")
return
end
ts_utils.swap_nodes(curr_node, prev_node, bufnr, true)
end
-- Move to the next argument (if any)
A.move_forward = function()
local curr_node = A.get_current()
local next_node = ts_utils.get_next_node(curr_node)
if next_node == nil then
-- error("This is the last argument")
return
end
ts_utils.goto_node(next_node, false, true)
end
-- Move to the previous argument (if any)
A.move_backward = function()
local curr_node = A.get_current()
local prev_node = ts_utils.get_previous_node(curr_node)
if prev_node == nil then
-- error("This is the first argument")
return
end
ts_utils.goto_node(prev_node, false, true)
end
return A
|
local Installer = {}
Installer.__index = Installer
function Installer.new()
local job_factory = require("optpack.lib.job_factory").new()
local git = require("optpack.lib.git").new(job_factory)
local tbl = { _git = git }
return setmetatable(tbl, Installer)
end
function Installer.already(directory)
return vim.fn.isdirectory(directory) ~= 0
end
function Installer.start(self, emitter, directory, url, depth)
if Installer.already(directory) then
return require("optpack.vendor.promise").resolve(false)
end
return self._git:clone(directory, url, depth):next(function()
emitter:emit(require("optpack.core.event").Event.Installed)
return true
end)
end
return Installer
|
--load the matrix and the 3D lib
local dream = require("3DreamEngine")
love.window.setTitle("Alpha Blend Example")
love.mouse.setRelativeMode(true)
--settings
local projectDir = "examples/AlphaBlending/"
--settings
dream.renderSet:setRefractions(true)
dream:setSky(love.graphics.newImage(projectDir .. "sky.hdr"), 0.25)
dream:init()
--scene
dream:loadMaterialLibrary(projectDir .. "materials")
local scene = dream:loadObject(projectDir .. "scene", {splitMaterials = true})
--light
local p = scene.positions[1]
local light = dream:newLight("point", p.x, p.y, p.z, 1.4, 1.2, 1.0, 20.0)
light:addShadow(true)
light:setSmoothing(true)
light.blacklist = {[scene.objects.chandelier_glass_None] = true, [scene.objects.chandelier_WhiteGlass] = true}
--custom position and rotation
dream.cam.rx = 0.9
dream.cam.ry = 0
dream.cam.ax = 0
dream.cam.ay = 0
dream.cam.az = 0
dream.cam.x = 0.95
dream.cam.y = 0.75
dream.cam.z = 0.95
dream.cam.fov = 65
function love.draw()
--update camera
dream.cam:reset()
dream.cam:translate(-dream.cam.x, -dream.cam.y, -dream.cam.z)
dream.cam:rotateY(dream.cam.ry)
dream.cam:rotateX(dream.cam.rx)
--light (no daylight) with two custom light sources
dream:resetLight(true)
dream:addLight(light)
dream:prepare()
dream:draw(scene)
dream:present()
love.graphics.print(table.concat({
"1 to toggle refractions .. (" .. tostring(dream.renderSet:getRefractions()) .. ")",
}, "\n"), 5, 5)
end
function love.mousemoved(_, _, x, y)
local speedH = 0.005
local speedV = 0.005
dream.cam.ry = dream.cam.ry - x * speedH
dream.cam.rx = math.max(-math.pi/2, math.min(math.pi/2, dream.cam.rx + y * speedV))
end
function love.update(dt)
local d = love.keyboard.isDown
local speed = 10*dt
dream.cam.x = dream.cam.x + dream.cam.ax * dt
dream.cam.y = dream.cam.y + dream.cam.ay * dt
dream.cam.z = dream.cam.z + dream.cam.az * dt
dream.cam.ax = dream.cam.ax * (1 - dt*3)
dream.cam.ay = dream.cam.ay * (1 - dt*3)
dream.cam.az = dream.cam.az * (1 - dt*3)
if d("w") then
dream.cam.ax = dream.cam.ax + math.cos(-dream.cam.ry-math.pi/2) * speed
dream.cam.az = dream.cam.az + math.sin(-dream.cam.ry-math.pi/2) * speed
end
if d("s") then
dream.cam.ax = dream.cam.ax + math.cos(-dream.cam.ry+math.pi-math.pi/2) * speed
dream.cam.az = dream.cam.az + math.sin(-dream.cam.ry+math.pi-math.pi/2) * speed
end
if d("a") then
dream.cam.ax = dream.cam.ax + math.cos(-dream.cam.ry-math.pi/2-math.pi/2) * speed
dream.cam.az = dream.cam.az + math.sin(-dream.cam.ry-math.pi/2-math.pi/2) * speed
end
if d("d") then
dream.cam.ax = dream.cam.ax + math.cos(-dream.cam.ry+math.pi/2-math.pi/2) * speed
dream.cam.az = dream.cam.az + math.sin(-dream.cam.ry+math.pi/2-math.pi/2) * speed
end
if d("space") then
dream.cam.ay = dream.cam.ay + speed
end
if d("lshift") then
dream.cam.ay = dream.cam.ay - speed
end
dream:update()
end
function love.keypressed(key)
if key == "1" then
dream.renderSet:setRefractions(not dream.renderSet:getRefractions())
dream:init()
end
--screenshots!
if key == "f2" then
dream:takeScreenshot()
end
--fullscreen
if key == "f11" then
love.window.setFullscreen(not love.window.getFullscreen())
dream:init()
end
end
function love.resize()
dream:init()
end
|
Timer = {
killOnFinish = true,
timeRemaining = 0,
finished = false,
callbackObject = nil,
callbackFunction = nil
}
function Timer:new(Time, CallbackObject, CallbackFunction, Persistant)
s = {}
setmetatable(s, self)
self.__index = self
General.activeState:add(s)
if Persistant ~= nil then
s.killOnFinish = not Persistant
else
s.killOnFinish = true
end
s.timeRemaining = Time
s.finished = false
s.callbackObject = CallbackObject
s.callbackFunction = CallbackFunction
return s
end
function Timer:start(Time, CallbackObject, CallbackFunction)
self.timeRemaining = Time
self.finished = false
self.callbackObject = CallbackObject
self.callbackFunction = CallbackFunction
self.exists = true
end
function Timer:restart(Time)
self.timeRemaining = Time
self.finished = false
self.exists = true
end
function Timer:stop()
self.exists = false
self.finished = true
end
function Timer:update()
if not self.finished then
self.timeRemaining = self.timeRemaining - General.elapsed
if self.timeRemaining < 0 then
--Mark finished, and stop updating
self.finished = true
self.exists = false
if self.callbackFunction ~= nil then
--Do callback function if one specified
self.callbackFunction(self.callbackObject)
end
if self.killOnFinish then
--Purpose has been fulfilled, time for Seppuku
self = nil
end
end
end
end
function Timer:draw()
--Empty draw, needed for state members
end
function Timer:destroy()
self.timeRemaining = nil
self.finished = nil
self.callbackObject = nil
self.callbackFunction = nil
self = nil
end
return Timer
|
-- The function get_name() should return a single string that is the name of the puzzle.
--
function get_name()
return "SEQUENCE PEAK DETECTOR"
end
-- The function get_description() should return an array of strings, where each string is
-- a line of description for the puzzle. The text you return from get_description() will
-- be automatically formatted and wrapped to fit inside the puzzle information box.
--
function get_description()
return { "SEQUENCES ARE ZERO-TERMINATED",
"READ A SEQUENCE FROM IN",
"WRITE THE MIN VALUE TO OUT.I",
"WRITE THE MAX VALUE TO OUT.A" }
end
-- The function get_streams() should return an array of streams. Each stream is described
-- by an array with exactly four values: a STREAM_* value, a name, a position, and an array
-- of integer values between -999 and 999 inclusive.
--
-- STREAM_INPUT: An input stream containing up to 39 numerical values.
-- STREAM_OUTPUT: An output stream containing up to 39 numerical values.
-- STREAM_IMAGE: An image output stream, containing exactly 30*18 numerical values between 0
-- and 4, representing the full set of "pixels" for the target image.
--
-- NOTE: Arrays in Lua are implemented as tables (dictionaries) with integer keys that start
-- at 1 by convention. The sample code below creates an input array of 39 random values
-- and an output array that doubles all of the input values.
--
-- NOTE: To generate random values you should use math.random(). However, you SHOULD NOT seed
-- the random number generator with a new seed value, as that is how TIS-100 ensures that
-- the first test run is consistent for all users, and thus something that allows for the
-- comparison of cycle scores.
--
-- NOTE: Position values for streams should be between 0 and 3, which correspond to the far
-- left and far right of the TIS-100 segment grid. Input streams will be automatically
-- placed on the top, while output and image streams will be placed on the bottom.
--
function get_streams()
local input = {}
local mins = {}
local maxs = {}
local n = 1
local mn = 1
while n<39 do
local howMany = math.random(1, 5);
if (n + howMany + 1 > 39) then
howMany = 39 - n - 1
end
local min = 999;
local max = -999;
for i = 0,howMany-1 do
input[n + i] = math.random(1, 999)
min = math.min(min, input[n + i])
max = math.max(max, input[n + i])
end
input[n + howMany] = 0
n = n + howMany + 1
mins[mn] = min
maxs[mn] = max
mn = mn + 1
end
return {
{ STREAM_INPUT, "IN", 1, input },
{ STREAM_OUTPUT, "OUT.I", 1, mins },
{ STREAM_OUTPUT, "OUT.A", 2, maxs },
}
end
-- The function get_layout() should return an array of exactly 12 TILE_* values, which
-- describe the layout and type of tiles found in the puzzle.
--
-- TILE_COMPUTE: A basic execution node (node type T21).
-- TILE_MEMORY: A stack memory node (node type T30).
-- TILE_DAMAGED: A damaged execution node, which acts as an obstacle.
--
function get_layout()
return {
TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE,
TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_DAMAGED,
TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE, TILE_COMPUTE,
}
end
|
local config = require "src/config"
local sha1 = require 'src/sha1'
local cjson = require "cjson"
local redis = require "resty.redis"
local session = require "src/session"
local red = redis:new()
local ok, err = red:connect(config.redis_host, config.redis_port)
if not ok then
ngx.say(config.redis_failed_connection(err))
return
end
local email, err = session.check_session(red)
if not email then
local res = { status = "fail",
msg = "Authentication required" }
if err then
ngx.log(ngx.ERR, err)
end
ngx.say(cjson.encode(res))
return
end
local hashed_email = sha1(email)
local user_key = "user://" .. hashed_email .. "/"
local bs, err = red:smembers(user_key)
if not bs then
ngx.say("failed to get keys: ", err)
return
end
local buckets_res = {}
local valueset={}
local n=0
for k,v in pairs(bs) do
n=n+1
valueset[n]=v
end
table.sort(valueset, function (a, b)
return string.lower(a) < string.lower(b)
end)
for idx, v in ipairs(valueset) do
local bucket_info = {
ukey = v,
name = string.sub(v, 6),
cd = "",
size = 0,
meta = ""
}
table.insert(buckets_res, bucket_info)
end
local res = { buckets = buckets_res }
ngx.say(cjson.encode(res))
|
local Prop = {}
Prop.Name = "Hospital"
Prop.Government = true
Prop.Doors = {
Vector( -5399.000000, -3074.000000, -13897.781250 ),
Vector( -5535.000000, -3426.000000, -13898.000000 ),
Vector( -5834.000000, -3706.000000, -13900.000000 ),
Vector( -378.000000, -5886.000000, -13838.000000 ),
Vector( -226.000000, -5658.000000, -13838.000000 ),
Vector( 638.000000, -5342.000000, -13838.000000 ),
Vector( 638.000000, -5342.000000, -13838.000000 ),
Vector( 761.906250, -5562.062500, -13836.000000 ),
Vector( 126.000000, -6330.000000, -13836.000000 ),
{ Pos = Vector( -278.000000, -6050.000000, -13835.781250 ), Locked = true },
{ Pos = Vector( -126.062500, -5442.062500, -13836.000000 ), Locked = true },
{ Pos = Vector( -126.000000 -5382.000000 -13836.000000 ), Locked = true },
}
GM.Property:Register( Prop )
|
local triangle = {
lifespan = 1.5,
auto_collision = true,
gravity = 0,
}
function triangle:init ()
self:attach('image', 'bullet')
end
function triangle:update ()
self.velocity.x = self:mirror().x * self.timer:seconds() * 10
self:move()
end
function triangle:collide (with)
self:damage_once(with, 80)
self.remove_from_battle = true
end
return triangle
|
local Plugin = script.Parent.Parent.Parent
local Constants = require(Plugin.Core.Util.Constants)
local Libs = Plugin.Libs
local Cryo = require(Libs.Cryo)
local Rodux = require(Libs.Rodux)
local Utility = require(Plugin.Core.Util.Utility)
local t = require(Libs.t)
local HttpService = game:GetService("HttpService")
local Immutable = require(Plugin.Core.Util.Immutable)
return Rodux.createReducer(
-- This will be set by brushtool directly upon loading.
nil,
{
StampObjectNew = function(state, action)
local guid = action.guid
local rbxObject = action.rbxObject
return Cryo.Dictionary.join(
state,
{
[guid] = {
rbxObject = rbxObject,
-- attempt at adding sub-seconds.
-- Objects may be added in the same second.
-- This can mess up ordering later on.
name = rbxObject.Name,
-- warning: models with 0 parts will return an invalid size.
-- make sure beforehand that all models have at least one part!
size = (function()
local min, max
if rbxObject:IsA("Model") then
min, max = Utility.GetModelAABB(rbxObject)
else
min, max = Utility.GetPartAABB(rbxObject)
end
local size =(max-min)
return Vector3.new(size.x, size.y, size.z)
end)(),
timeAdded = os.time(os.date("!*t")) + tick()%1,
stampCenterMode = "BoundingBox",
rotation = {
mode = "None",
fixed = 0,
min = 0,
max = 360
},
scale = {
mode = "None",
fixed = 1,
min = 1,
max = 2
},
wobble = {
mode = "None",
min = 0,
max = 30
},
verticalOffset = {
mode = "Auto",
fixed = 0,
min = 0,
max = 1
},
orientation = {
mode = "Normal",
custom = Vector3.new(0, 1, 0)
}
}
}
)
end,
StampObjectDelete = function(state, action)
local guid = action.guid
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.None
}
)
end,
StampObjectStampCenterModeSet = function(state, action)
local guid = action.guid
local stampCenterMode = action.stampCenterMode
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.Dictionary.join(
state[guid],
{
stampCenterMode = stampCenterMode
}
)
}
)
end,
StampObjectRotationSet = function(state, action)
local guid = action.guid
local mode = action.mode
local fixed = action.fixed
local min = action.min
local max = action.max
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.Dictionary.join(
state[guid],
{
rotation = Cryo.Dictionary.join(
state[guid].rotation,
{
mode = mode,
fixed = fixed,
min = min,
max = max
}
)
}
)
}
)
end,
StampObjectScaleSet = function(state, action)
local guid = action.guid
local mode = action.mode
local fixed = action.fixed
local min = action.min
local max = action.max
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.Dictionary.join(
state[guid],
{
scale = Cryo.Dictionary.join(
state[guid].scale,
{
mode = mode,
fixed = fixed,
min = min,
max = max
}
)
}
)
}
)
end,
StampObjectWobbleSet = function(state, action)
local guid = action.guid
local mode = action.mode
local min = action.min
local max = action.max
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.Dictionary.join(
state[guid],
{
wobble = Cryo.Dictionary.join(
state[guid].wobble,
{
mode = mode,
min = min,
max = max
}
)
}
)
}
)
end,
StampObjectVerticalOffsetSet = function(state, action)
local guid = action.guid
local mode = action.mode
local fixed = action.fixed
local min = action.min
local max = action.max
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.Dictionary.join(
state[guid],
{
verticalOffset = Cryo.Dictionary.join(
state[guid].verticalOffset,
{
mode = mode,
fixed = fixed,
min = min,
max = max
}
)
}
)
}
)
end,
StampObjectOrientationSet = function(state, action)
local guid = action.guid
local mode = action.mode
local custom = action.custom
return Cryo.Dictionary.join(
state,
{
[guid] = Cryo.Dictionary.join(
state[guid],
{
orientation = Cryo.Dictionary.join(
state[guid].orientation,
{
mode = mode,
custom = custom
}
)
}
)
}
)
end,
_CopyFromState = function(state, action)
return action.init.stampObjects
end
}
)
|
-- use {
-- "sainnhe/gruvbox-material",
-- config = function()
-- require("colorschemes.gruvbox_material")
-- end
-- }
vim.g.gruvbox_material_background = "hard"
vim.g.gruvbox_material_better_performance = 1
-- vim.g.gruvbox_material_transparent_background = 1
vim.g.gruvbox_material_foreground = "original"
vim.g.gruvbox_material_enable_bold = 1
vim.g.gruvbox_material_statusline_style = "original"
vim.cmd("colo gruvbox-material")
vim.cmd("hi ColorColumn guibg=#3c3836")
vim.cmd("hi CursorLine guibg=#3c3836")
vim.cmd("hi Todo guifg=#dfaa2e gui=bold,underline")
|
do --- table 1
local t=setmetatable({}, {__newindex=function(t,k,v)
rawset(t, k, 100-v)
end})
for i=1,100 do t[i] = i end
for i=1,100 do assert(t[i] == 100-i) end
for i=1,100 do t[i] = i end
for i=1,100 do assert(t[i] == i) end
for i=1,100 do t[i] = nil end
for i=1,100 do t[i] = i end
for i=1,100 do assert(t[i] == 100-i) end
end
do --- jit gaining href
local count = 0
local t = setmetatable({ foo = nil },
{ __newindex=function() count = count + 1 end })
for j=1,2 do
for i=1,100 do t.foo = 1 end
rawset(t, "foo", 1)
end
assert(count == 100)
end
do --- jit gaining aref
local count = 0
local t = setmetatable({ nil },
{ __newindex=function() count = count + 1 end })
for j=1,2 do
for i=1,100 do t[1] = 1 end
rawset(t, 1, 1)
end
assert(count == 100)
end
do --- resize
local grandparent = {}
grandparent.__newindex = function(s,_,_) tostring(s) end
local parent = {}
parent.__newindex = parent
parent.bar = 1
setmetatable(parent, grandparent)
local child = setmetatable({}, parent)
child.foo = _
end
do --- str
local t=setmetatable({}, {__newindex=function(t,k,v)
assert(v == "foo"..k)
rawset(t, k, "bar"..k)
end})
for i=1,100 do t[i]="foo"..i end
for i=1,100 do assert(t[i] == "bar"..i) end
for i=1,100 do t[i]="baz"..i end
for i=1,100 do assert(t[i] == "baz"..i) end
local t=setmetatable({foo=1,bar=1,baz=1},{})
t.baz=nil
t.baz=2
t.baz=nil
t.baz=2
end
|
-- BLIPS: see https://wiki.gtanet.work/index.php?title=Blips for blip id/color
local Tools = module("vrp", "lib/Tools")
-- TUNNEL CLIENT API
-- BLIP
-- create new blip, return native id
function tvRP.addBlip(x,y,z,idtype,idcolor,text)
local blip = AddBlipForCoord(x+0.001,y+0.001,z+0.001) -- solve strange gta5 madness with integer -> double
SetBlipSprite(blip, idtype)
SetBlipAsShortRange(blip, true)
SetBlipColour(blip,idcolor)
if text ~= nil then
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(text)
EndTextCommandSetBlipName(blip)
end
return blip
end
-- remove blip by native id
function tvRP.removeBlip(id)
RemoveBlip(id)
end
local named_blips = {}
-- set a named blip (same as addBlip but for a unique name, add or update)
-- return native id
function tvRP.setNamedBlip(name,x,y,z,idtype,idcolor,text)
tvRP.removeNamedBlip(name) -- remove old one
named_blips[name] = tvRP.addBlip(x,y,z,idtype,idcolor,text)
return named_blips[name]
end
-- remove a named blip
function tvRP.removeNamedBlip(name)
if named_blips[name] ~= nil then
tvRP.removeBlip(named_blips[name])
named_blips[name] = nil
end
end
-- GPS
-- set the GPS destination marker coordinates
function tvRP.setGPS(x,y)
SetNewWaypoint(x+0.0001,y+0.0001)
end
-- set route to native blip id
function tvRP.setBlipRoute(id)
SetBlipRoute(id,true)
end
-- MARKER
local markers = {}
local marker_ids = Tools.newIDGenerator()
local named_markers = {}
-- add a circular marker to the game map
-- return marker id
function tvRP.addMarker(x,y,z,sx,sy,sz,r,g,b,a,visible_distance)
local marker = {x=x,y=y,z=z,sx=sx,sy=sy,sz=sz,r=r,g=g,b=b,a=a,visible_distance=visible_distance}
-- default values
if marker.sx == nil then marker.sx = 2.0 end
if marker.sy == nil then marker.sy = 2.0 end
if marker.sz == nil then marker.sz = 0.7 end
if marker.r == nil then marker.r = 0 end
if marker.g == nil then marker.g = 155 end
if marker.b == nil then marker.b = 255 end
if marker.a == nil then marker.a = 200 end
-- fix gta5 integer -> double issue
marker.x = marker.x+0.001
marker.y = marker.y+0.001
marker.z = marker.z+0.001
marker.sx = marker.sx+0.001
marker.sy = marker.sy+0.001
marker.sz = marker.sz+0.001
if marker.visible_distance == nil then marker.visible_distance = 150 end
local id = marker_ids:gen()
markers[id] = marker
return id
end
-- remove marker
function tvRP.removeMarker(id)
if markers[id] then
markers[id] = nil
marker_ids:free(id)
end
end
-- set a named marker (same as addMarker but for a unique name, add or update)
-- return id
function tvRP.setNamedMarker(name,x,y,z,sx,sy,sz,r,g,b,a,visible_distance)
tvRP.removeNamedMarker(name) -- remove old marker
named_markers[name] = tvRP.addMarker(x,y,z,sx,sy,sz,r,g,b,a,visible_distance)
return named_markers[name]
end
function tvRP.removeNamedMarker(name)
if named_markers[name] then
tvRP.removeMarker(named_markers[name])
named_markers[name] = nil
end
end
-- markers draw loop
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
local px,py,pz = tvRP.getPosition()
for k,v in pairs(markers) do
-- check visibility
if GetDistanceBetweenCoords(v.x,v.y,v.z,px,py,pz,true) <= v.visible_distance then
DrawMarker(1,v.x,v.y,v.z,0,0,0,0,0,0,v.sx,v.sy,v.sz,v.r,v.g,v.b,v.a,0,0,0,0)
end
end
end
end)
-- AREA
local areas = {}
-- create/update a cylinder area
function tvRP.setArea(name, x, y, z, radius, height)
local area = {x = x + 0.001, y = y + 0.001, z = z + 0.001, radius = radius, height = height}
-- default values
if area.height == nil then area.height = 6 end
areas[name] = area
end
-- remove area
function tvRP.removeArea(name)
if areas[name] then
areas[name] = nil
end
end
-- areas triggers detections
Citizen.CreateThread(function()
while true do
Citizen.Wait(250)
local px,py,pz = tvRP.getPosition()
for k,v in pairs(areas) do
-- detect enter/leave
local player_in = (GetDistanceBetweenCoords(v.x,v.y,v.z,px,py,pz,true) <= v.radius and math.abs(pz-v.z) <= v.height)
if v.player_in and not player_in then -- was in: leave
vRPserver.leaveArea({k})
elseif not v.player_in and player_in then -- wasn't in: enter
vRPserver.enterArea({k})
end
v.player_in = player_in -- update area player_in
end
end
end)
-- DOOR
-- set the closest door state
-- doordef: .model or .modelhash
-- locked: boolean
-- doorswing: -1 to 1
function tvRP.setStateOfClosestDoor(doordef, locked, doorswing)
local x,y,z = tvRP.getPosition()
local hash = doordef.modelhash
if hash == nil then
hash = GetHashKey(doordef.model)
end
SetStateOfClosestDoorOfType(hash,x,y,z,locked,doorswing+0.0001)
end
function tvRP.openClosestDoor(doordef)
tvRP.setStateOfClosestDoor(doordef, false, 0)
end
function tvRP.closeClosestDoor(doordef)
tvRP.setStateOfClosestDoor(doordef, true, 0)
end
|
---@meta
local resty_core_phase={}
resty_core_phase.version = require("resty.core.base").version
return resty_core_phase
|
--[[
pbInfo - Locales/lang.Swedish.lua
v0.51
by p.b. a.k.a. novayuna
released under the Creative Commons License By-Nc-Sa: http://creativecommons.org/licenses/by-nc-sa/3.0/
thx to Forsoki for the translation!
-- commented lines need translations
]]
pbInfo.Locale["Messages"]["DESCRIPTION"] = "pbInfo shows a tooltip with several information about the mob, player or NPC you are hovering, a tooltip with information about gathering materials and it modifies the target blood bars to show a mob's real healthpoints.\n\nBy now, pbInfo includes a ThreatMeter, a QuestTracker and a ChatLog.";
pbInfo.Locale["Messages"]["LOADED"] = "Add-on Laddad";
pbInfo.Locale["Messages"]["NVT"] = "Inte till\195\165tet m\195\165l vald!";
pbInfo.Locale["Messages"]["TOGGLEtrue"] = " har lyckats blivit |cff00FF00aktiverad|r.";
pbInfo.Locale["Messages"]["TOGGLEfalse"] = " har lyckats blivit |cffFF0000inaktiverad|r.";
pbInfo.Locale["Messages"]["TOGGLEerror"] = " existerar inte i konfigurationen.";
pbInfo.Locale["Messages"]["ONLOAD"] = "Anv\195\164nd minikart knappen eller skriv /pbic f\195\182r att \195\164ndra inst\195\164llningar.";
pbInfo.Locale["Messages"]["ATTENTIONENABLE"]= "Observera: add-onen har blivit |cffFF0000disabled|r f\195\182rut. Skriv /pbic f\195\182r att aktivera den.";
pbInfo.Locale["Tooltip"]["HP"] = "Liv";
pbInfo.Locale["Tooltip"]["LVL"] = "Niv\195\165";
pbInfo.Locale["Tooltip"]["PROGRESS"] = "Framsteg";
pbInfo.Locale["Tooltip"]["TITLE"] = "Titel";
--pbInfo.Locale["Tooltip"]["GUILD"] = "Guild";
pbInfo.Locale["Tooltip"]["DISTANCE"] = "Avst\195\165nd";
pbInfo.Locale["Tooltip"]["TARGET"] = "M\195\165l";
pbInfo.Locale["Tooltip"]["MANATYPE1"] = "Mana";
pbInfo.Locale["Tooltip"]["MANATYPE2"] = "Rage";
pbInfo.Locale["Tooltip"]["MANATYPE3"] = "Focus";
pbInfo.Locale["Tooltip"]["MANATYPE4"] = "Energy";
pbInfo.Locale["Tooltip"]["MATINBAG"] = "I ryggs\195\164cken";
pbInfo.Locale["Tooltip"]["MATONBANK"] = "I banken";
pbInfo.Locale["ClockTooltip"]["CNDTIME"] = "Tid i Candara";
pbInfo.Locale["ClockTooltip"]["ONLINE"] = "Online";
pbInfo.Locale["QuestTracker"]["DAILY"] = "Dagliga Uppdrag";
pbInfo.Locale["QuestTracker"]["REWARD"] = "Bel\195\182ning";
pbInfo.Locale["QuestTracker"]["QUESTNPC"] = "Uppdrags-NPC";
pbInfo.Locale["QuestTracker"]["XP"] = "XP";
pbInfo.Locale["QuestTracker"]["TP"] = "TP";
pbInfo.Locale["QuestTracker"]["GOLD"] = "Guld";
pbInfo.Locale["QuestTracker"]["DQITEMS"] = "Dagliga uppdrags f\195\182rem\195\165l";
pbInfo.Locale["QuestTracker"]["COMPLQUESTS"]= "Avklara uppdrag";
pbInfo.Locale["QuestTracker"]["INFOTOOLTIP"]= "Klicka den v\195\164nstra mus knappen f\195\182r att aktivera/inaktivera QuestTracker.\n\nH\195\165ll in skift och then h\195\182gra mus knappen f\195\182r att flytta den.";
pbInfo.Locale["Config"]["Title"] = "pbInfo inst\195\164llningar";
pbInfo.Locale["Config"]["TabGeneral"] = "Genrell";
pbInfo.Locale["Config"]["TabTooltip"] = "Tooltip";
pbInfo.Locale["Config"]["TabTargetFrame"] = "M\195\165lf\195\182nster";
pbInfo.Locale["Config"]["TabBloodBars"] = "Blodm\195\164tare";
pbInfo.Locale["Config"]["TabThreatMeter"] = "Aggrom\195\164tare";
pbInfo.Locale["Config"]["TabQuestTracker"] = "QuestTracker";
pbInfo.Locale["Config"]["TabChatLog"] = "ChatLog";
--pbInfo.Locale["Config"]["TabCastingBar"] = "CastingBar";
--[pbInfo.Locale["Config"]"TabChatFrame"] = "ChatFrame";
pbInfo.Locale["Config"]["SettingEnable"] = "AKtivera pbInfo";
--pbInfo.Locale["Config"]["SettingThousandsSeparatorFormat"] = "ThousandsSeparator:";
--pbInfo.Locale["Config"]["SettingTimeStampFormat"] = "TimeStamp format:";
pbInfo.Locale["Config"]["SettingExtraLanguage"] = "Spr\195\165k:";
pbInfo.Locale["Config"]["SettingModifyTooltip"] = "Visa info om monster och spelare";
pbInfo.Locale["Config"]["SettingModifyHealthbar"] = "Visa riktigt hp i m\195\165l f\195\182nster";
pbInfo.Locale["Config"]["SettingHealthbarShowPercentage"] = "Beh\195\165ll procent v\195\164rde";
pbInfo.Locale["Config"]["SettingHealthColorFade"] = "Mjuk livspo\195\164ngs f\195\164rgning";
pbInfo.Locale["Config"]["SettingShowMana"] = "Visa mana, ilska, energi och fokusering";
pbInfo.Locale["Config"]["SettingShowDistance"] = "Visa L\195\164ngd";
--pbInfo.Locale["Config"]["SettingTooltipShowRace"] = "Show race";
--pbInfo.Locale["Config"]["SettingTooltipShowPlayerInfo"] = "Show a player's title (experimental)";
pbInfo.Locale["Config"]["SettingShowMouseoverTarget"] = "Visa m\195\165lets m\195\165l";
pbInfo.Locale["Config"]["SettingAllNPC"] = "Aktivera f\195\182r alla npc";
pbInfo.Locale["Config"]["SettingStickyTooltip"] = "Permanent Tooltip postition";
pbInfo.Locale["Config"]["SettingStickyAllTooltips"] = "alla Tooltips (magier, f\195\182rem\195\165l, etc.)";
pbInfo.Locale["Config"]["SettingStickyTooltipButton"] = "S\195\164tt position";
pbInfo.Locale["Config"]["SettingShowMaterialInfo"] = "Visa info om samlings material";
--pbInfo.Locale["Config"]["SettingShowMatInfoItemCountBank"] = "+ Bank items";
--pbInfo.Locale["Config"]["SettingShowMatInfoItemCountIV"] = "+ InventoryViewer Support";
pbInfo.Locale["Config"]["SettingShowMatInfoItemCount"] = "Visa f\195\182rem\195\165ls antal";
pbInfo.Locale["Config"]["SettingShowClockTooltip"] = "Visa KlockTooltip p\195\165 dagsljus ikonen";
pbInfo.Locale["Config"]["SettingHealthBarColorFade"] = "F\195\164rga livsm\195\164taren fr\195\165n gr\195\182n till r\195\182d";
pbInfo.Locale["Config"]["SettingModifyBloodBars"] = "Visa riktiga livet i blodm\195\164tare";
pbInfo.Locale["Config"]["SettingBloodBarsColorFade"] = "F\195\164rga blodm\195\164taren fr\195\165n gr\195\182n till r\195\182d";
pbInfo.Locale["Config"]["SettingBloodBarsDelay"] = "Uppdatera f\195\182rsening i sekunder:";
pbInfo.Locale["Config"]["SettingThreatMeter"] = "Aggrom\195\164tare";
--pbInfo.Locale["Config"]["SettingThreatMeterShowTitle"] = "Show title";
pbInfo.Locale["Config"]["SettingThreatMeterLock"] = "Fixa positionen";
pbInfo.Locale["Config"]["SettingThreatMeterPlayerOnTop"] = "Placera alltid spelaren \195\182verst";
--pbInfo.Locale["Config"]["SettingThreatMeterWarnTargetTargetTarget"]= 'Warn me if "TargetTargetTarget = Me"';
--pbInfo.Locale["Config"]["TooltipThreatMeterWarnTargetTargetTarget"]= "Shows a warning message if your target's target targets you\n (Tank->Mob->You).";
pbInfo.Locale["Config"]["SettingThreatMeterHideOnNoTarget"] = "G\195\182m om inga m\195\165l \195\164r fokuserade";
pbInfo.Locale["Config"]["SettingThreatMeterHideOnNoParty"] = "G\195\182m om du inte \195\164r med i en grupp";
pbInfo.Locale["Config"]["SettingThreatMeterRelativeToMaxThreat"]= "Visa aggro relativit till max. aggro";
pbInfo.Locale["Config"]["SettingThreatMeterShowRealThreat"] = "Visa riktiga aggro ist\195\164llet f\195\182r procent";
pbInfo.Locale["Config"]["SettingThreatMeterDisplayLimit"] = "% minimum aggro att visa i listan";
pbInfo.Locale["Config"]["SettingGameTooltipAlpha"] = "% Tooltip genomskinlighet";
pbInfo.Locale["Config"]["SettingThreatMeterAlpha"] = "% Aggrom\195\164tarens genomskinlighet";
pbInfo.Locale["Config"]["SettingThreatMeterDelay"] = "Uppdatera f\195\182rsening i sekunder:";
pbInfo.Locale["Config"]["SettingQuestTracker"] = "QuestTracker";
pbInfo.Locale["Config"]["SettingQuestTrackerShowTitle"] = "Visa titel";
--pbInfo.Locale["Config"]["SettingQuestTrackerSortAsc"] = "Sort ascending";
pbInfo.Locale["Config"]["SettingQuestTrackerProgressColorFade"] = "F\195\164rga framg\195\165ng mjukt";
pbInfo.Locale["Config"]["SettingQuestTrackerTooltip"] = "Visa Tooltip";
pbInfo.Locale["Config"]["SettingQuestTrackerTooltipRight"] = "Visa tooltip till h\195\182ger";
pbInfo.Locale["Config"]["SettingQuestTrackerTooltipDescription"]= "Visa uppdrags sammanfattning";
pbInfo.Locale["Config"]["SettingQuestTrackerHighlightDailies"] = "Framh\195\164v dagliga uppdrag";
pbInfo.Locale["Config"]["SettingQuestTrackerOpenQuestbook"] = "\195\150ppna Uppdragsloggen via v\195\164nster klick";
pbInfo.Locale["Config"]["SettingQuestTrackerShowDailiesCounter"]= "Visa antal dagliga uppdrag kvar (beta)";
pbInfo.Locale["Config"]["SettingQuestTrackerFontSizesTitle"] = "QuestTrackers titel storlek:";
pbInfo.Locale["Config"]["SettingQuestTrackerFontSizesQuestTitle"]= "Uppdrags namns titel storlek:";
pbInfo.Locale["Config"]["SettingQuestTrackerFontSizesQuestItems"]= "Uppdrags f\195\182rem\195\165ls text storlek:";
--pbInfo.Locale["Config"]["SettingQuestTrackerColorsDailyQuest"] = "Daily quest color";
pbInfo.Locale["Config"]["SettingChatLog"] = "ChatLog";
pbInfo.Locale["Config"]["SettingChatLogMaxLinesPerChat"] = "max antal rader att spara i chatloggen";
--pbInfo.Locale["Config"]["SettingChatFrameFilterTitles"] = "Remove chat titles ([Zone], [Party], ...)";
--pbInfo.Locale["Config"]["SettingChatFrameFilterXPTP"] = "Remove XP/TP messages";
pbInfo.Locale["Config"]["SettingTimeStamp"] = "Visa tid p\195\165 meddelanden i chaten";
pbInfo.Locale["Config"]["SettingTimeStampNotInCombatLog"] = "Visa inte i stridsloggen";
pbInfo.Locale["Config"]["SettingAutoRepairAll"] = "Reparera utrustining automatiskt n\195\164r jag \195\182ppnar en shop";
--pbInfo.Locale["Config"]["SettingCastingBarShowCastTime"] = "Show cast time";
--pbInfo.Locale["Config"]["SettingCastingBarButton"] = "Move CastingBar";
pbInfo.Locale["Config"]["TooltipBorderTitle"] = "Spel Tooltips position";
pbInfo.Locale["Config"]["TooltipBorderText"] = "Dra och sl\195\164pp";
pbInfo.Locale["Config"]["ResetButton"] = "! \195\133terst\195\164ll pbInfo !";
pbInfo.Locale["Config"]["CloseButton"] = "St\195\164ng";
pbInfo.Locale["Config"]["SaveButton"] = "Spara";
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by Administrator.
--- DateTime: 2020/8/27 0027 下午 10:15
---
local m = {};
local bx1 = require("bx_lua");
function m.getHPCounter()
return bx1.getHPCounter();
end
function m.getHPFrequency()
return bx1.getHPFrequency();
end
--- create vector3 by x, y, z . and x/y/z should be float.
function m.newVec3(x, y, z)
return bx1.newVec3(x, y, z);
end
--- mtxLookAt
--- @param mem_f: float memory userdata .
--- @param vec3_eye: vector3 for eye
--- @param vec3_at: vector3 for at
--- @param vec3_up: vector3 for at. null means default is {0, 1,0}
--- @param handness: null means default is 'Left'.
function m.mtxLookAt(mem_f, vec3_eye, vec3_at, vec3_up, handness)
return bx1.mtxLookAt(mem_f, vec3_eye, vec3_at, vec3_up, handness);
end
--- mtxProj
--- @param mem_f: float memory userdata.
--- @param _ut: float
--- @param _dt: float
--- @param _lt: float
--- @param _rt: float
--- @param _near: float
--- @param _far: float
--- @param homogeneousNdc: bool
--- @param handness: 'Left' or 'Right'. default is 'Left'
function m.mtxProj9(mem_f, _ut, _dt, _lt, _rt, _near, _far, homogeneousNdc, handness)
if(not handness) then
handness = 'Left';
end
return bx1.mtxProj(mem_f, _ut, _dt, _lt, _rt, _near, _far, homogeneousNdc, handness);
end
function m.mtxProj7(mem_f, _fovy, _aspect, _near, _far, homogeneousNdc, handness)
--float* _result, float _fovy, float _aspect, float _near, float _far, bool _homogeneousNdc, Handness::Enum _handness = Handness::Left
if(not handness) then
handness = 'Left';
end
return bx1.mtxProj(mem_f, _fovy, _aspect, _near, _far, homogeneousNdc, handness);
end
---
function m.mtxProj6(mem_f, mem_fov, _near, _far, homogeneousNdc, handness)
-- float* _result, const float _fov[4], float _near, float _far, bool _homogeneousNdc, Handness::Enum _handness = Handness::Left
if(not handness) then
handness = 'Left';
end
return bx1.mtxProj(mem_f, mem_fov, _near, _far, homogeneousNdc, handness);
end
--- mtxProj : compat mtxProj6, mtxProj7, mtxProj9
--- @param mem_f: float memory userdata.
function m.mtxProj(mem_f, ...)
return bx1.mtxProj(mem_f, ...);
end
--- mtxRotateXY
--- @param mem_f: float memory userdata.
--- @param _ax: float
--- @param _ay: float
function m.mtxRotateXY(mem_f, _ax, _ay)
return bx1.mtxRotateXY(mem_f, _ax, _ay);
end
return m;
|
Transform=class({
ctor=function(self,data)
if data~=nil then
self.position=Vector3:new(data.position[1],data.position[2],data.position[3])
self.localRotation=Quaternion:Euler(Vector3:new(data.rotation[1],data.rotation[2],data.rotation[3]))
self.scale=Vector3:new(data.scale[1],data.scale[2],data.scale[3])
else
self.position=Vector3:new(0,0,0)
self.localRotation=Quaternion:new()
self.scale=Vector3:new(1,1,1)
end
self._parent=nil
self.children={}
end,
property={
parent={
set=function(self,value)
local befor= self._parent
if befor ~=nil then
for k,v in pairs(befor.children)do
if v==self then
befor.children[k]=nil
break
end
end
end
self._parent=value
table.insert(value.children,self)
end,
get=function(self)
return self._parent
end
},
modelMat4={
get=function(self)
return Mat4x4.Compose(self.position, self.localRotation, self.scale )
end
},
Rotate=function(self,eulers,world)
local eulerRot=Quaternion:Euler(eulers)
if world~=nil and world==true then
self.rotation=self.rotation*Quaternion:Inverse(self.rotation)*eulerRot*self.rotation
else
self.localRotation=self.localRotation*eulerRot
end
end,
rotation={
get=function(self)
return self.localRotation
end,
set=function(self,value)
self.localRotation=value.normalized
end
}
},
extend=Component
})
|
-- 草莓Dâu Tây 's Type Fx Vert
-- Edit by Effector Cmy
local tr = aegisub.gettext
include("karaskel.lua")
script_name = tr"Xóa dấu pinyin"
script_description = tr"A demo macro showing how to do simple line modification in Automation 4"
script_author = "Niels Martin Hansen"
script_version = "1"
local pinyin = {"á", "ǎ", "à", "ā", "ò", "ó", "ǒ", "ō", "ì", "í", "ǐ", "ī", "ù", "ú", "ǔ", "ū", "é", "è", "ē", "ě", "ü", "ǘ", "ǜ", "ǖ", "ǚ", "Á", "Ǎ", "À", "Ā", "Ò", "Ó", "Ǒ", "Ō", "Ì", "Í", "Ǐ", "Ī", "Ù", "Ú", "Ǔ", "Ū", "É", "È", "Ē", "Ě", "Ü", "Ǘ", "Ǜ", "Ǖ", "Ǚ"}
function SETPY(text_once)
local setpy = ""
for i = 1, #pinyin do
if text_once == pinyin[i]:sub(1, 1) or text_once == pinyin[i]:sub(2, 2)
then setpy = setpy .. "1" break
else setpy = setpy .. "" end end
return setpy end
function PinyinToLatin(tex)
if tex == pinyin[1] or tex == pinyin[2] or tex == pinyin[3] or tex == pinyin[4]
then return "a"
elseif tex == pinyin[5] or tex == pinyin[6] or tex == pinyin[7] or tex == pinyin[8]
then return "o"
elseif tex == pinyin[9] or tex == pinyin[10] or tex == pinyin[11] or tex == pinyin[12]
then return "i"
elseif tex == pinyin[13] or tex == pinyin[14] or tex == pinyin[15] or tex == pinyin[16]
then return "u"
elseif tex == pinyin[17] or tex == pinyin[18] or tex == pinyin[19] or tex == pinyin[20]
then return "e"
elseif tex == pinyin[21] or tex == pinyin[22] or tex == pinyin[23] or tex == pinyin[24] or tex == pinyin[25]
then return "u"
elseif tex == pinyin[26] or tex == pinyin[27] or tex == pinyin[28] or tex == pinyin[29]
then return "A"
elseif tex == pinyin[30] or tex == pinyin[31] or tex == pinyin[32] or tex == pinyin[33]
then return "O"
elseif tex == pinyin[34] or tex == pinyin[35] or tex == pinyin[36] or tex == pinyin[37]
then return "I"
elseif tex == pinyin[38] or tex == pinyin[39] or tex == pinyin[40] or tex == pinyin[41]
then return "U"
elseif tex == pinyin[42] or tex == pinyin[43] or tex == pinyin[44] or tex == pinyin[45]
then return "E"
elseif tex == pinyin[46] or tex == pinyin[47] or tex == pinyin[48] or tex == pinyin[49] or tex == pinyin[50]
then return "U"
else return "" end
end
function StripPinyin(l)
local SPY = ""
for i = 1, string.len(l.text) do
if SETPY(l.text:sub(i, i)) == "1"
then SPY = SPY .. PinyinToLatin(l.text:sub(i, i+1))
else SPY = SPY .. l.text:sub(i, i) end end
return SPY end
function RunT(subtitles, selected_lines, active_line)
for z, i in ipairs(selected_lines) do
local l = subtitles[i]
l.text = StripPinyin(l)
subtitles[i] = l
end
aegisub.set_undo_point(script_name)
end
aegisub.register_macro(script_name, tr"Strip Pinyin tags to all selected lines", RunT)
|
--[[
* MOCK framework for Moai
* Copyright (C) 2012 Tommo Zhou(tommo.zhou@gmail.com). All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
local SingleTouch=newTrait('SingleTouch')
SingleTouch.__overwrite={'onTouch'}
function SingleTouch:onTouch(ev,id,x,y)
if ev=='press' and not self._touchId then
if self:testPress(x,y) then
self._touchId=id
return self:onPress(x,y)
end
elseif ev=='release' and self._touchId==id then
self._touchId=nil
return self:onRelease(x,y)
elseif ev=='drag' and self._touchId==id then
return self:onDrag(x,y)
end
end
function SingleTouch:flushTouch()
self._touchId=nil
end
function SingleTouch:onPress(x,y)
end
function SingleTouch:onDrag(x,y)
end
function SingleTouch:onRelease(x,y)
end
function SingleTouch:testPress(x,y)
return true
end
|
MathBase = class(BenchmarkBase, function(a, writer, printToConsole)
BenchmarkBase.init(a, writer, printToConsole)
a.iterrations = 200000000
a.ratio = 0.5
end)
function MathBase:doMath(i, li)
local rev = 1.0 / (i + 1.0)
return math.abs(i) * math.acos(rev) * math.asin(rev) * math.atan(rev) +
math.floor(li) + math.exp(rev) * math.cos(i) * math.sin(i) * math.pi + math.sqrt(i)
end
|
-----------------------------------
-- Area: Castle Oztroja
-- NPC: _47o
-- !pos -155.228 21.500 -140.000 151
-----------------------------------
function onTrigger(player,npc)
npc:openDoor(6)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
|
-- @module modutram.grid.Column
local Column = {}
function Column:new(o)
o = o or {}
local initialModule = o.initialModule
if not initialModule then
error ('Column MUST have a initialModule property')
end
o.gridX = initialModule:getGridX()
o.xPos = initialModule:getXPosInCm()
o.type = initialModule:getType()
o.topGridY = initialModule:getGridY()
o.bottomGridY = initialModule:getGridY()
o.gridModules = {
[initialModule:getGridY()] = initialModule
}
o.initialModule = nil
setmetatable(o, self)
self.__index = self
return o
end
function Column:addGridModule(gridModule)
self.gridModules[gridModule:getGridY()] = gridModule
self.topGridY = math.max(self.topGridY, gridModule:getGridY())
self.bottomGridY = math.min(self.bottomGridY, gridModule:getGridY())
end
function Column:getGridModule(gridY)
return self.gridModules[gridY]
end
function Column:hasGridModule(gridY)
return self:getGridModule(gridY) ~= nil
end
function Column:eachGridModule(callable)
for i = self.bottomGridY, self.topGridY do
if self.gridModules[i] then
callable(self.gridModules[i])
end
end
end
function Column:eachWithEmpty(callable)
for i = self.bottomGridY, self.topGridY do
callable(self.gridModules[i])
end
end
function Column:getGridLength()
return self.topGridY - self.bottomGridY + 1
end
return Column
|
-- The MIT License (MIT)
-- Copyright (c) 2015-2021 Daurnimator
-- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
-- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
--
-- uri component encode/decode (https://github.com/daurnimator/lua-http/blob/master/http/util.lua)
local M = {}
-- Encodes a character as a percent encoded string
local function char_to_pchar(c)
return string.format("%%%02X", c:byte(1,1))
end
-- replaces all characters except the following with the appropriate UTF-8 escape sequences:
-- ; , / ? : @ & = + $
-- alphabetic, decimal digits, - _ . ! ~ * ' ( )
-- #
function M.encode(str)
return (str:gsub("[^%;%,%/%?%:%@%&%=%+%$%w%-%_%.%!%~%*%'%(%)%#]", char_to_pchar))
end
-- escapes all characters except the following: alphabetic, decimal digits, - _ . ! ~ * ' ( )
function M.encode_component(str)
return (str:gsub("[^%w%-_%.%!%~%*%'%(%)]", char_to_pchar))
end
-- unescapes url encoded characters
-- excluding characters that are special in urls
local decodeURI_blacklist = {}
for char in ("#$&+,/:;=?@"):gmatch(".") do
decodeURI_blacklist[string.byte(char)] = true
end
local function decodeURI_helper(str)
local x = tonumber(str, 16)
if not decodeURI_blacklist[x] then
return string.char(x)
end
-- return nothing; gsub will not perform the replacement
end
function M.decode(str)
return (str:gsub("%%(%x%x)", decodeURI_helper))
end
-- Converts a hex string to a character
local function pchar_to_char(str)
return string.char(tonumber(str, 16))
end
function M.decode_component(str)
return (str:gsub("%%(%x%x)", pchar_to_char))
end
return M
|
--# selene: allow(almost_swapped, divide_by_zero, duplicate_keys, empty_if, global_usage, if_same_then_else, ifs_same_cond, multiple_statements, mismatched_arg_count, parenthese_conditions, roblox_incorrect_color3_new_bounds, roblox_incorrect_roact_usage, shadowing, incorrect_standard_library_use, suspicious_reverse_loop, type_check_inside_call, unbalanced_assignments, undefined_variable, unscoped_variables, unused_variable)
export type ViewmodelSettings = {
UseCharacterShirt: boolean;
LeftArmColor: Color3?;
RightArmColor: Color3?;
}
export type ViewmodelInstance = Model & {
HumanoidRootPart: Part;
Settings: ModuleScript;
FakeCamera: Part;
["Left Arm"]: Part;
["Right Arm"]: Part;
AnimationController: AnimationController?;
Humanoid: Humanoid?;
Weapon: Model;
}
export type Viewmodel = {
Animations: {[string]: AnimationTrack};
Settings: ViewmodelSettings;
Instance: Model;
Animator: Animator;
Culled: boolean;
Cull: (state: boolean) -> ();
LoadAnimation: (key: string, animation: Animation) -> (AnimationTrack);
GetAnimation: (key: string) -> (AnimationTrack?);
UnloadAnimation: (key: string) -> ();
Update: (deltaTime: number, viewmodelCFrame: CFrame) -> ();
}
local Players = game:GetService("Players")
local LocalPlayer = Players.LocalPlayer
local CULL_CFRAME = CFrame.new(0, 1e29, 0)
local Viewmodel = {}
Viewmodel.__index = Viewmodel
local function checkViewmodelInstance(viewmodelInstance: Model)
assert(viewmodelInstance:FindFirstChild("HumanoidRootPart"))
assert(viewmodelInstance:FindFirstChild("Settings"))
assert(viewmodelInstance:FindFirstChild("FakeCamera"))
assert(viewmodelInstance:FindFirstChild("Left Arm"))
assert(viewmodelInstance:FindFirstChild("Right Arm"))
assert(viewmodelInstance:FindFirstChildWhichIsA("AnimationController") or viewmodelInstance:FindFirstChildWhichIsA("Humanoid"))
assert(viewmodelInstance:FindFirstChild("Weapon"))
end
local function getAnimator(viewmodelInstance: Model): Animator
checkViewmodelInstance(viewmodelInstance)
local animatorContainer: AnimationController | Humanoid =
viewmodelInstance:FindFirstChildWhichIsA("AnimationController") or
viewmodelInstance:FindFirstChildWhichIsA("Humanoid")
local animator = animatorContainer:FindFirstChildWhichIsA("Animator") or Instance.new("Animator", animatorContainer)
return animator
end
local function cleanViewmodelInstance(viewmodelInstance: Model)
checkViewmodelInstance(viewmodelInstance)
viewmodelInstance.PrimaryPart = viewmodelInstance.HumanoidRootPart
if viewmodelInstance:FindFirstChild("AnimSaves") then
viewmodelInstance.AnimSaves:Destroy()
end
for _, obj in pairs(viewmodelInstance:GetDescendants()) do
if obj:IsA("BasePart") or obj:IsA("UnionOperation") then
obj.CanCollide = false
obj.CastShadow = false
end
end
end
local function updateArms(viewmodelInstance: Model, viewmodelSettings: ViewmodelSettings)
checkViewmodelInstance(viewmodelInstance)
local character: Model = LocalPlayer.Character
if character then
local shirt = character:FindFirstChildWhichIsA("Shirt")
local leftArm: Part = character:FindFirstChild("Left Arm")
local rightArm: Part = character:FindFirstChild("Right Arm")
local vmLeftArm: Part = viewmodelInstance:FindFirstChild("Left Arm")
local vmRightArm: Part = viewmodelInstance:FindFirstChild("Right Arm")
vmLeftArm.Color = viewmodelSettings.LeftArmColor or leftArm.Color
vmRightArm.Color = viewmodelSettings.RightArmColor or rightArm.Color
if viewmodelSettings.UseCharacterShirt then
local vmLeftArmShirt: Decal = vmLeftArm:FindFirstChild("Shirt")
local vmRightArmShirt: Decal = vmRightArm:FindFirstChild("Shirt")
if vmLeftArmShirt then
if shirt then
vmLeftArmShirt.Texture = shirt.ShirtTemplate
vmLeftArmShirt.Color3 = shirt.Color3
else
vmLeftArmShirt.Transparency = 1
end
end
if vmRightArmShirt then
if shirt then
vmRightArmShirt.Texture = shirt.ShirtTemplate
vmRightArmShirt.Color3 = shirt.Color3
else
vmRightArmShirt.Transparency = 1
end
end
end
end
end
function Viewmodel:Cull(state: boolean)
self.Culled = state
end
function Viewmodel:LoadAnimation(key: string, animation: Animation): AnimationTrack
local self: Viewmodel = self
assert(self.Animations[key] == nil, string.format("Animation key %s is already taken, unload this key first before loading a new one.", key))
assert(
typeof(animation) == "Instance" and animation:IsA("Animation"),
string.format(
"Animation argument is invalid (type %s - class %s)",
typeof(animation), (typeof(animation) == "Instance" and animation.ClassName))
)
local animationTrack = self.Animator:LoadAnimation(animation)
self.Animations[key] = animationTrack
return animationTrack
end
function Viewmodel:GetAnimation(key: string): AnimationTrack?
local self: Viewmodel = self
return self.Animations[key]
end
function Viewmodel:UnloadAnimation(key: string)
local self: Viewmodel = self
assert(self.Animations[key], string.format("%s is not a valid member of this Viewmodel's animations"))
local animationTrack: AnimationTrack = self.Animations[key]
self.Animations[key] = nil
animationTrack:Destroy()
end
function Viewmodel:Update(deltaTime: number, viewmodelCFrame: CFrame)
local self: Viewmodel = self
local scaledDeltaTime = deltaTime * 60
self.Instance:SetPrimaryPartCFrame(self.Culled and CULL_CFRAME or viewmodelCFrame)
if not self.Culled then
updateArms(self.Instance, self.Settings) -- save performance a little bit
--camera animation support
if self.Instance:FindFirstChild("FakeCamera") then
local fakeCamera = self.Instance.FakeCamera
local newCamCFrame = fakeCamera.CFrame:ToObjectSpace(self.Instance.PrimaryPart.CFrame)
if self.__oldCamCFrame then
local _, _, z = newCamCFrame:ToOrientation()
local x, y, _ = newCamCFrame:ToObjectSpace(self.__oldCamCFrame):ToEulerAnglesXYZ()
workspace.CurrentCamera.CFrame = workspace.CurrentCamera.CFrame * CFrame.Angles(x, y, -z)
end
self.__oldCamCFrame = newCamCFrame
end
end
end
function Viewmodel.new(viewmodelInstance: Model): Viewmodel
checkViewmodelInstance(viewmodelInstance)
cleanViewmodelInstance(viewmodelInstance)
local self = setmetatable({
Settings = require(viewmodelInstance.Settings);
Instance = viewmodelInstance;
Animator = getAnimator(viewmodelInstance);
Culled = false;
Animations = {};
}, Viewmodel)
return self
end
return Viewmodel
|
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
local generalLoaded = false
local PlayingAnim = false
local testPED = nil
-------------------------------------------------------------------------------------------------
-------------------------------------- AJOUTE de PNJ --------------------------------------------
-------------------------------------------------------------------------------------------------
local Poliss2 = {
-- ID: id de PNJ | nom: Nom du Blip | BlipID: Icone de Blip | VoiceName: NPC Talk Quand près de lui | Ambiance: Ambiance de Boutique | Arme: Hash of Weapon | modelHash: Modèle | X: Position x | Y: Position Y | Z: Position Z | Rubrique: Où Npc regarde
{id = 1, name = "LS Police", BlipID = 137, VoiceName = "GENERIC_HI", Ambiance = "AMMUCITY", Weapon = 0xA2719263, modelHash = "S_M_Y_Cop_01", x = -2150.01, y = 2884.41, z = 32.8104, heading = 120.665}, -- LS Police
}
-------------------------------------------------------------------------------------------------
-------------------------------- FIN d'AJOUTE de PNJ --------------------------------------------
-------------------------------------------------------------------------------------------------
-- Blip pour NPC
Citizen.CreateThread(function()
for k,v in pairs(Poliss2)do
--local blip = AddBlipForCoord(v.x, v.y, v.z)
--SetBlipSprite(blip, v.BlipID)
SetBlipScale(blip, 0.8)
SetBlipAsShortRange(blip, true)
BeginTextCommandSetBlipName("STRING")
AddTextComponentString(v.name)
EndTextCommandSetBlipName(blip)
end
end)
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
-- PNJ de Spawn
Citizen.CreateThread(function()
while true do
Citizen.Wait(0)
if (not generalLoaded) then
RequestModel(GetHashKey(Poliss2[1].modelHash))
while not HasModelLoaded(GetHashKey(Poliss2[1].modelHash)) do
Wait(1)
end
testPED = CreatePed(2, Poliss2[1].modelHash, Poliss2[1].x, Poliss2[1].y, Poliss2[1].z, Poliss2[1].heading, true, true)
SetPedRelationshipGroupHash(testPED, GetHashKey("CIVMALE"))
SetPedFleeAttributes(testPED, 0, 0)
SetAmbientVoiceName(testPED, Poliss2[1].Ambiance)
SetPedDropsWeaponsWhenDead(testPED, false)
SetPedDiesWhenInjured(testPED, false)
GiveWeaponToPed(testPED, Poliss2[1].Weapon, 2800, false, true)
generalLoaded = true
end
end
end)
-------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------
Citizen.CreateThread(function()
local debut_x = -2150.01
local debut_y = 2884.41
local debut_z = 32.8104
local fin_x = -2134.56
local fin_y = 2893.0
local fin_z = 32.8104
if generalLoaded == true then
while true do
Citizen.Wait(0)
SetPedPathsInArea(testPED, debut_x, debut_y, debut_z, fin_x, fin_y, fin_z, true)
--TaskGoToCoordAnyMeans(testPED, fin_x, fin_y, fin_z, 2.0, 0, false, 1, 2.0)
--TaskGoToEntity(testPED, GetPlayerPed(-1), -1, 1.0, 10.0, 1073741824.0, 0)
--SetPedKeepTask(testPED, true)
end
end
end)
|
MenuPool = setmetatable({}, MenuPool)
MenuPool.__index = MenuPool
function MenuPool.New()
local _MenuPool = {
Menus = {}
}
return setmetatable(_MenuPool, MenuPool)
end
function MenuPool:AddSubMenu(Menu, Text, Description, KeepPosition, KeepBanner)
if Menu() == "UIMenu" then
local Item = UIMenuItem.New(tostring(Text), Description or "")
Menu:AddItem(Item)
local SubMenu
if KeepPosition then
SubMenu = UIMenu.New(Menu.Title:Text(), Text, Menu.Position.X, Menu.Position.Y)
else
SubMenu = UIMenu.New(Menu.Title:Text(), Text)
end
if KeepBanner then
if Menu.Logo ~= nil then
SubMenu.Logo = Menu.Logo
else
SubMenu.Logo = nil
SubMenu.Banner = Menu.Banner
end
end
self:Add(SubMenu)
Menu:BindMenuToItem(SubMenu, Item)
return SubMenu
end
end
function MenuPool:Add(Menu)
if Menu() == "UIMenu" then
table.insert(self.Menus, Menu)
end
end
function MenuPool:MouseEdgeEnabled(bool)
if bool ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.Settings.MouseEdgeEnabled = tobool(bool)
end
end
end
function MenuPool:ControlDisablingEnabled(bool)
if bool ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.Settings.ControlDisablingEnabled = tobool(bool)
end
end
end
function MenuPool:ResetCursorOnOpen(bool)
if bool ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.Settings.ResetCursorOnOpen = tobool(bool)
end
end
end
function MenuPool:MultilineFormats(bool)
if bool ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.Settings.MultilineFormats = tobool(bool)
end
end
end
function MenuPool:Audio(Attribute, Setting)
if Attribute ~= nil and Setting ~= nil then
for _, Menu in pairs(self.Menus) do
if Menu.Settings.Audio[Attribute] then
Menu.Settings.Audio[Attribute] = Setting
end
end
end
end
function MenuPool:WidthOffset(offset)
if tonumber(offset) then
for _, Menu in pairs(self.Menus) do
Menu:SetMenuWidthOffset(tonumber(offset))
end
end
end
function MenuPool:CounterPreText(str)
if str ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.PageCounter.PreText = tostring(str)
end
end
end
function MenuPool:DisableInstructionalButtons(bool)
if bool ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.Settings.InstructionalButtons = tobool(bool)
end
end
end
function MenuPool:MouseControlsEnabled(bool)
if bool ~= nil then
for _, Menu in pairs(self.Menus) do
Menu.Settings.MouseControlsEnabled = tobool(bool)
end
end
end
function MenuPool:RefreshIndex()
for _, Menu in pairs(self.Menus) do
Menu:RefreshIndex()
end
end
function MenuPool:ProcessMenus()
self:ProcessControl()
self:ProcessMouse()
self:Draw()
end
function MenuPool:ProcessControl()
for _, Menu in pairs(self.Menus) do
if Menu:Visible() then
Menu:ProcessControl()
end
end
end
function MenuPool:ProcessMouse()
for _, Menu in pairs(self.Menus) do
if Menu:Visible() then
Menu:ProcessMouse()
end
end
end
function MenuPool:Draw()
for _, Menu in pairs(self.Menus) do
if Menu:Visible() then
Menu:Draw()
end
end
end
function MenuPool:IsAnyMenuOpen()
local open = false
for _, Menu in pairs(self.Menus) do
if Menu:Visible() then
open = true
break
end
end
return open
end
function MenuPool:CloseAllMenus()
for _, Menu in pairs(self.Menus) do
if Menu:Visible() then
Menu:Visible(false)
end
end
end
function MenuPool:SetBannerSprite(Sprite)
if Sprite() == "Sprite" then
for _, Menu in pairs(self.Menus) do
Menu:SetBannerSprite(Sprite)
end
end
end
function MenuPool:SetBannerRectangle(Rectangle)
if Rectangle() == "Rectangle" then
for _, Menu in pairs(self.Menus) do
Menu:SetBannerRectangle(Rectangle)
end
end
end
function MenuPool:TotalItemsPerPage(Value)
if tonumber(Value) then
for _, Menu in pairs(self.Menus) do
Menu.Pagination.Total = Value - 1
end
end
end
|
local util = require("bogster.util")
local theme = require("bogster.theme")
local M = {}
function M.colorscheme()
util.load(theme.setup())
end
return M
|
local patch_id = "OVERRIDE_AGENT_INDEX_FN"
if rawget(_G, patch_id) then
return
end
rawset(_G, patch_id, true)
print("Loaded patch:"..patch_id)
local fields_that_use_original = {
"faction_id",
}
local old_index_fn = Agent.__index
Agent.__index = function(self, k)
if rawget(self, "original_agent") then
if table.arraycontains(fields_that_use_original, k) then -- does not check retain faction, because it will break Rook's campaign
return old_index_fn(self.original_agent, k)
end
end
return old_index_fn(self, k)
end
|
eco_mapgen = {}
local MP = minetest.get_modpath("eco_mapgen")
dofile(MP .. "/info.lua")
dofile(MP .. "/mapgen.lua")
dofile(MP .. "/render_mapblock.lua")
dofile(MP .. "/count_resources.lua")
dofile(MP .. "/get_biome_data.lua")
dofile(MP .. "/restore.lua")
dofile(MP .. "/biome.lua")
dofile(MP .. "/biomes/grass.lua")
dofile(MP .. "/biomes/underground.lua")
dofile(MP .. "/biomes/water.lua")
dofile(MP .. "/biomes/snow.lua")
dofile(MP .. "/biomes/ice.lua")
dofile(MP .. "/biomes/desert.lua")
dofile(MP .. "/decorations.lua")
dofile(MP .. "/decorations/grass.lua")
|
function Writer(val)
local buff = {}
if val then
if type(val) == "table" then
buff=val
elseif type(val) == "string" then
buff={}
for i=1, #val do
buff[#buff+1]=val:sub(i,i)
end
else
buff={}
end
else
buff={}
end
local function intLenght(d)
for i=1, 7 do
local v = 2^i
local v1 = 2^(v-1)-1
if v1 < d then
return v
end
end
return 4
end
local function write(byte)
buff[#buff+1]=string.char(byte)
end
local function writeByte(val)
if type(val)~="number" then
return
end
write(val)
end
local function writeInt(val, size)
if type(val)~="number" then
return
end
for i=1, size/8 do
write(bit.band(val,255))
val=bit.brshift(val,8)
end
end
local function writeString(val)
if
type(val)~="string" then
return
end
writeInt(#val,32)
for i=1, #val do
write(val:sub(i,i):byte())
end
end
local function writeBool(val)
if type(val)~="boolean" then
return
end
write(val and 1 or 0)
end
local writeTable, writeFunc
local function writeVar(val)
if type(val) == "number" then
write(1)
writeInt(val,32)
elseif type(val) == "string" then
write(2)
writeString(val)
elseif type(val) == "boolean" then
write(3)
writeBool(val)
elseif type(val) == "table" then
write(4)
writeTable(val)
elseif type(val) == "function" then
write(5)
writeFunc(val)
end
end
writeTable = function(val)
if type(val)~="table" then
return
end
local n=0
for k, v in pairs(val) do
n=n+1
end
writeInt(n,32)
for k, v in pairs(val) do
writeVar(k)
writeVar(v)
end
end
writeFunc = function(val)
if type(val)~="function" then
return
end
writeString(string.dump(val))
end
local function getBuff()
local b = table.concat(buff,"")
buff={}
return b
end
return {getBuff=getBuff,writeByte=writeByte,writeInt=writeInt,writeString=writeString,writeBool=writeBool,writeTable=writeTable,writeFunc=writeFunc,writeVar=writeVar}
end
function Reader(val)
local buff = {}
if val then
if type(val) == "table" then
buff=val
elseif type(val) == "string" then
buff={}
for i=1, #val do
buff[#buff+1]=val:sub(i,i)
end
else
buff={}
end
else
buff={}
end
local function checkSize(n)
n=n or 1
for i=1, n do
if not buff[i] then
error("Out of limit",1)
end
end
end
local function read(n)
n = n or 1
checkSize(n)
local t = {}
for i=1, n do
t[#t+1]=buff[1]:byte()
table.remove(buff,1)
end
return t
end
local function readByte()
checkSize()
local v = buff[1]
table.remove(buff,1)
return v:byte()
end
local function readInt(size)
if size then
checkSize(size/8)
local val = 0
for i=1, size/8 do
val = bit.bor(val,bit.blshift(bit.band(buff[i]:byte(),255),(i-1)*8))
end
for i=1, size/8 do
table.remove(buff,1)
end
return val
end
end
local function readString()
local size = readInt(32)
checkSize(size)
local t = ""
for i=1, size do
t=t..buff[1]
table.remove(buff,1)
end
return t
end
local function readBool()
checkSize()
return read()[1]==1 and true or false
end
local readTable, readFunc
local function readVar()
checkSize()
local id = buff[1]:byte()
table.remove(buff,1)
if id == 0 then
return readByte()
elseif id == 1 then
return readInt(32)
elseif id == 2 then
return readString()
elseif id == 3 then
return readBool()
elseif id == 4 then
return readTable()
elseif id == 5 then
return readFunc()
end
end
readTable = function()
local size = readInt(32)
if size then
local t = {}
for i=1, size do
local key = readVar()
local val = readVar()
t[key]=val
end
return t
end
end
readFunc = function()
local dt = readString()
return loadstring(dt)
end
function getBuff()
return buff
end
return {readByte=readByte,readInt=readInt,readString=readString,readBool=readBool,readTable=readTable,readFunc=readFunc,readVar=readVar}
end
|
--************************
--name : SINGLE_AS_CM_02.lua
--ver : 0.1
--author : Kintama
--date : 2004/09/09
--lang : en
--desc : terminal mission
--npc :
--************************
--changelog:
--2004/09/09(0.1): Added description
--************************
function DIALOG()
NODE(0)
GENDERCHECK()
if (result==1) then -- Player is Man:
SAY("CityAdmin, how can I help you, sir?")
SAY("CityAdmin, do you need assistance, sir?")
SAY("Hello there. Come about the job, sir?")
SAY("Welcome to the City Administration. How can I help you, sir?")
SAY("Greetings, sir. You are required to assist your government in an urgent matter.")
ANSWER("I am just looking around. Thanks.",1)
ANSWER("What can you tell me about this place?",1)
ANSWER("Hey. What is this place?",1)
ANSWER("Oh sorry, I thought you were someone else.",1)
ANSWER("Yeah, I'm here about the contract.",2)
ANSWER("OK, I heard you required a competent trouble-shooter.",2)
ANSWER("All right, I'm here for an assignment I took on the CityAdmin terminal.",2)
else -- Player is a Woman:
SAY("CityAdmin, how can I help you, madame?")
SAY("CityAdmin, do you need assistance, ma'am?")
SAY("Hello there. Come about the job, madame?")
SAY("Welcome to the CityAdministration. How can I help you, ma'am?")
SAY("Greetings, madame. You are required to assist your government in an urgent matter.")
ANSWER("I am just looking around. Thanks.",1)
ANSWER("What can you tell me about this place?",1)
ANSWER("Nice place here. What do you do here?",1)
ANSWER("Pardon me, I thought you were someone else.",1)
ANSWER("Yes, I am here about a job.",2)
ANSWER("Hi, the CityAdmin terminal referred me to you regarding an assignment.",2)
end
NODE(1)
GENDERCHECK()
if (result==1) then
SAY("The CityAdmin wishes you a pleasant day.")
SAY("Have a good day. For the people!")
SAY("Sir, for general information about the CityAdmin please consult the terminals. We and the great Reeza wish you a good day!")
SAY("Thank you, sir. Have a nice day.")
ENDDIALOG()
else
SAY("The CityAdmin wishes you a pleasant day.")
SAY("Have a good day. For the people!")
SAY("Madame, for general information about the CityAdmin please consult the terminals. We and the great Reeza wish you a good day!")
SAY("Thank you, ma'am. Have a nice day.")
ENDDIALOG()
end
NODE(2) -- Giving Mission
SAY("Your target is an infiltrator named %NPC_NAME(1) last seen in %NPC_WORLD(1). This is an official termination with clearance from the top. Use your own discretion and then return to me for debriefing.")
SAY("Runner, this is an official termination of an infiltrator named %NPC_NAME(1). Target las seen in %NPC_WORLD(1). Shoot him, stab him, blow him away. Then return to me for debriefing.")
SAY("Runner, this is an official termination. Target, %NPC_NAME(1), located at %NPC_WORLD(1). Terminate and return here for debriefing. Dismissed.")
SETNEXTDIALOGSTATE(3)
ENDDIALOG()
NODE(3)
ISMISSIONTARGETACCOMPLISHED(0)
if (result==0) then -- Mission is not accomplished
SAY("Surveillance reports that %NPC_NAME(1), suspected infiltrator, is still alive. Kill the enemy in the name of Reeza and the people!")
SAY("Runner, you have not completed the mission. See to it.")
SAY("Runner, %NPC_NAME(1) still moves according to our last intel. Find and eliminate.")
SAY("Intel shows you have not yet completed the mission. Get it done, for the good of the people!")
ENDDIALOG()
else -- Mission was accomplished
SAY("Surveillance tells me you have completed the mission. The standard %REWARD_MONEY() credit reward has been moved to your account. The CityAdmin thanks you for doing your duty. Dismissed.")
SAY("Runner, reports show that infiltrator %NPC_NAME(1) has flatlined. The standard %REWARD_MONEY() credit reward has been moved to your acccount. For Reeza and the people!")
SAY("Runner, well done. %NPC_NAME(1) has been confirmed dead. The standard %REWARD_MONEY() credit reward has been moved to your account. Walk proudly in the knowledge that you have served Reeza well!")
ACTIVATEDIALOGTRIGGER(1)
ENDDIALOG()
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.