repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
lsmoura/dtb | inc/AceGUI-3.0/widgets/AceGUIWidget-MultiLineEditBox.lua | 1 | 9623 | local Type, Version = "MultiLineEditBox", 24
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local pairs = pairs
-- WoW APIs
local GetCursorInfo, GetSpellInfo, ClearCursor = GetCursorInfo, GetSpellInfo, ClearCursor
local CreateFrame, UIParent = CreateFrame, UIParent
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: ACCEPT, ChatFontNormal
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function Layout(self)
self:SetHeight(self.numlines * 14 + (self.disablebutton and 19 or 41) + self.labelHeight)
if self.labelHeight == 0 then
self.scrollBar:SetPoint("TOP", self.frame, "TOP", 0, -23)
else
self.scrollBar:SetPoint("TOP", self.label, "BOTTOM", 0, -19)
end
if self.disablebutton then
self.scrollBar:SetPoint("BOTTOM", self.frame, "BOTTOM", 0, 21)
self.scrollBG:SetPoint("BOTTOMLEFT", 0, 4)
else
self.scrollBar:SetPoint("BOTTOM", self.button, "TOP", 0, 18)
self.scrollBG:SetPoint("BOTTOMLEFT", self.button, "TOPLEFT")
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function OnClick(self) -- Button
self = self.obj
self.editBox:ClearFocus()
if not self:Fire("OnEnterPressed", self.editBox:GetText()) then
self.button:Disable()
end
end
local function OnCursorChanged(self, _, y, _, cursorHeight) -- EditBox
self, y = self.obj.scrollFrame, -y
local offset = self:GetVerticalScroll()
if y < offset then
self:SetVerticalScroll(y)
else
y = y + cursorHeight - self:GetHeight()
if y > offset then
self:SetVerticalScroll(y)
end
end
end
local function OnEditFocusLost(self) -- EditBox
self:HighlightText(0, 0)
end
local function OnEnter(self) -- EditBox / ScrollFrame
self = self.obj
if not self.entered then
self.entered = true
self:Fire("OnEnter")
end
end
local function OnLeave(self) -- EditBox / ScrollFrame
self = self.obj
if self.entered then
self.entered = nil
self:Fire("OnLeave")
end
end
local function OnMouseUp(self) -- ScrollFrame
self = self.obj.editBox
self:SetFocus()
self:SetCursorPosition(self:GetNumLetters())
end
local function OnReceiveDrag(self) -- EditBox / ScrollFrame
local type, id, info = GetCursorInfo()
if type == "spell" then
info = GetSpellInfo(id, info)
elseif type ~= "item" then
return
end
ClearCursor()
self = self.obj
local editBox = self.editBox
if not editBox:HasFocus() then
editBox:SetFocus()
editBox:SetCursorPosition(editBox:GetNumLetters())
end
editBox:Insert(info)
self.button:Enable()
end
local function OnSizeChanged(self, width, height) -- ScrollFrame
self.obj.editBox:SetWidth(width)
end
local function OnTextChanged(self, userInput) -- EditBox
if userInput then
self = self.obj
self:Fire("OnTextChanged", self.editBox:GetText())
self.button:Enable()
end
end
local function OnTextSet(self) -- EditBox
self:HighlightText(0, 0)
self:SetCursorPosition(self:GetNumLetters())
self:SetCursorPosition(0)
self.obj.button:Disable()
end
local function OnVerticalScroll(self, offset) -- ScrollFrame
local editBox = self.obj.editBox
editBox:SetHitRectInsets(0, 0, offset, editBox:GetHeight() - offset - self:GetHeight())
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self.editBox:SetText("")
self:SetDisabled(false)
self:SetWidth(200)
self:DisableButton(false)
self:SetNumLines()
self.entered = nil
self:SetMaxLetters(0)
end,
-- ["OnRelease"] = nil,
["SetDisabled"] = function(self, disabled)
local editBox = self.editBox
if disabled then
editBox:ClearFocus()
editBox:EnableMouse(false)
editBox:SetTextColor(0.5, 0.5, 0.5)
self.label:SetTextColor(0.5, 0.5, 0.5)
self.scrollFrame:EnableMouse(false)
self.button:Disable()
else
editBox:EnableMouse(true)
editBox:SetTextColor(1, 1, 1)
self.label:SetTextColor(1, 0.82, 0)
self.scrollFrame:EnableMouse(true)
end
end,
["SetLabel"] = function(self, text)
if text and text ~= "" then
self.label:SetText(text)
if self.labelHeight ~= 10 then
self.labelHeight = 10
self.label:Show()
end
elseif self.labelHeight ~= 0 then
self.labelHeight = 0
self.label:Hide()
end
Layout(self)
end,
["SetNumLines"] = function(self, value)
if not value or value < 4 then
value = 4
end
self.numlines = value
Layout(self)
end,
["SetText"] = function(self, text)
self.editBox:SetText(text)
end,
["GetText"] = function(self)
return self.editBox:GetText()
end,
["SetMaxLetters"] = function (self, num)
self.editBox:SetMaxLetters(num or 0)
end,
["DisableButton"] = function(self, disabled)
self.disablebutton = disabled
if disabled then
self.button:Hide()
else
self.button:Show()
end
Layout(self)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local backdrop = {
bgFile = [[Interface\Tooltips\UI-Tooltip-Background]],
edgeFile = [[Interface\Tooltips\UI-Tooltip-Border]], edgeSize = 16,
insets = { left = 4, right = 3, top = 4, bottom = 3 }
}
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local widgetNum = AceGUI:GetNextWidgetNum(Type)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
label:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, -4)
label:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, -4)
label:SetJustifyH("LEFT")
label:SetText(ACCEPT)
label:SetHeight(10)
local button = CreateFrame("Button", ("%s%dButton"):format(Type, widgetNum), frame, "UIPanelButtonTemplate2")
button:SetPoint("BOTTOMLEFT", 0, 4)
button:SetHeight(22)
button:SetWidth(label:GetStringWidth() + 24)
button:SetText(ACCEPT)
button:SetScript("OnClick", OnClick)
button:Disable()
local text = button:GetFontString()
text:ClearAllPoints()
text:SetPoint("TOPLEFT", button, "TOPLEFT", 5, -5)
text:SetPoint("BOTTOMRIGHT", button, "BOTTOMRIGHT", -5, 1)
text:SetJustifyV("MIDDLE")
local scrollBG = CreateFrame("Frame", nil, frame)
scrollBG:SetBackdrop(backdrop)
scrollBG:SetBackdropColor(0, 0, 0)
scrollBG:SetBackdropBorderColor(0.4, 0.4, 0.4)
local scrollFrame = CreateFrame("ScrollFrame", ("%s%dScrollFrame"):format(Type, widgetNum), frame, "UIPanelScrollFrameTemplate")
local scrollBar = _G[scrollFrame:GetName() .. "ScrollBar"]
scrollBar:ClearAllPoints()
scrollBar:SetPoint("TOP", label, "BOTTOM", 0, -19)
scrollBar:SetPoint("BOTTOM", button, "TOP", 0, 18)
scrollBar:SetPoint("RIGHT", frame, "RIGHT")
scrollBG:SetPoint("TOPRIGHT", scrollBar, "TOPLEFT", 0, 19)
scrollBG:SetPoint("BOTTOMLEFT", button, "TOPLEFT")
scrollFrame:SetPoint("TOPLEFT", scrollBG, "TOPLEFT", 5, -6)
scrollFrame:SetPoint("BOTTOMRIGHT", scrollBG, "BOTTOMRIGHT", -4, 4)
scrollFrame:SetScript("OnEnter", OnEnter)
scrollFrame:SetScript("OnLeave", OnLeave)
scrollFrame:SetScript("OnMouseUp", OnMouseUp)
scrollFrame:SetScript("OnReceiveDrag", OnReceiveDrag)
scrollFrame:SetScript("OnSizeChanged", OnSizeChanged)
scrollFrame:HookScript("OnVerticalScroll", OnVerticalScroll)
local editBox = CreateFrame("EditBox", nil, scrollFrame)
editBox:SetAllPoints()
editBox:SetFontObject(ChatFontNormal)
editBox:SetMultiLine(true)
editBox:EnableMouse(true)
editBox:SetAutoFocus(false)
editBox:SetCountInvisibleLetters(false)
editBox:SetScript("OnCursorChanged", OnCursorChanged)
editBox:SetScript("OnEditFocusLost", OnEditFocusLost)
editBox:SetScript("OnEnter", OnEnter)
editBox:SetScript("OnEscapePressed", editBox.ClearFocus)
editBox:SetScript("OnLeave", OnLeave)
editBox:SetScript("OnMouseDown", OnReceiveDrag)
editBox:SetScript("OnReceiveDrag", OnReceiveDrag)
editBox:SetScript("OnTextChanged", OnTextChanged)
editBox:SetScript("OnTextSet", OnTextSet)
scrollFrame:SetScrollChild(editBox)
local widget = {
button = button,
editBox = editBox,
frame = frame,
label = label,
labelHeight = 10,
numlines = 4,
scrollBar = scrollBar,
scrollBG = scrollBG,
scrollFrame = scrollFrame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
button.obj, editBox.obj, scrollFrame.obj = widget, widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| unlicense |
NogsIoT/Nogs-IDE | Templates/Projects/Default/color.lua | 1 | 1494 | --[[
* Color utils
*
* Copyright (C) Nogs GmbH, Andre Riesberg
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not,
* write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
local color = {}
function color.rgbToValue(r, g, b)
return math.floor(r * 255.0) * 65536 + math.floor(g * 255.0) * 256 + math.floor(b * 255.0)
end
-- h 0..1, s 0..1 v 0..1
function color.rgb(r, g ,b)
return r, g, b
end
function color.hsv(h, s, v)
local r,g,b
local i = math.floor(h * 6)
local f = h * 6 - i
local p = v * (1 - s)
local q = v * (1 - f * s)
local t = v * (1 - (1 - f) * s)
local switch = i % 6
if switch <= 0 then return v, t, p end
if switch <= 1 then return q, v, p end
if switch <= 2 then return p, v, t end
if switch <= 3 then return p, q, v end
if switch <= 4 then return t, p, v end
return v, p, q
end
return color
| gpl-2.0 |
fiskio/lstm-char-cnn | util/LookupTableOneHot.lua | 6 | 1035 | local LookupTableOneHot, parent = torch.class('nn.LookupTableOneHot', 'nn.Module')
function LookupTableOneHot:__init(input_size)
parent.__init(self)
self.eye = torch.eye(input_size)
self.output = torch.Tensor()
end
function LookupTableOneHot:updateOutput(input)
-- make sure input is a contiguous torch.LongTensor
if (not input:isContiguous()) or torch.type(input) ~= 'torch.LongTensor' then
self._indices = self._indices or torch.LongTensor()
self._indices:resize(input:size()):copy(input)
input = self._indices
end
if input:dim() == 1 then
local nIndex = input:size(1)
self.output:index(self.eye, 1, input)
elseif input:dim() == 2 then
-- batch mode
local nExample = input:size(1)
local nIndex = input:size(2)
self._inputView = self._inputView or torch.LongTensor()
self._inputView:view(input, -1)
self.output:index(self.eye, 1, self._inputView)
self.output = self.output:view(nExample, nIndex, self.eye:size(1))
end
return self.output
end | mit |
chewi/Aquaria | files/scripts/entities/vine.lua | 5 | 2527 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- SPORE SEED
v.growEmitter = 0
v.done = false
v.lifeTime = 0
function init(me)
setupEntity(me)
entity_setTexture(me, "Naija/Thorn")
--[[
entity_setWidth(me, 64)
entity_setHeight(me, 512)
]]--
entity_setEntityLayer(me, -1)
entity_initEmitter(me, v.growEmitter, "SporeSeedGrow")
entity_setCollideRadius(me, 0)
entity_setState(me, STATE_IDLE)
entity_setInternalOffset(me, 0, -128)
v.lifeTime = 5
entity_alpha(me, 0)
entity_alpha(me, 1, 0.1)
entity_scale(me, 1, 0)
entity_scale(me, 1, 1, 0.5, 0, 0, 1)
entity_clampToSurface(me)
end
function postInit(me)
entity_rotateToSurfaceNormal(me)
end
function songNote(me, note)
end
function update(me, dt)
if not v.done then
v.lifeTime = v.lifeTime - dt
if v.lifeTime < 0 then
entity_delete(me, 0.2)
v.done = true
end
local sx, sy = entity_getScale(me)
local len = 256*sy
local x1, y1 = entity_getPosition(me)
local fx, fy = entity_getNormal(me)
local x2 = x1 + fx*len
local y2 = y1 + fy*len
local ent = getFirstEntity()
while ent~=0 do
if entity_getEntityType(ent) ~= ET_NEUTRAL and ent ~= me and entity_isDamageTarget(ent, DT_AVATAR_VINE) then
local dmg = 0.5
if entity_getEntityType(ent)==ET_AVATAR and isForm(FORM_NATURE) then
dmg = 0
end
if entity_collideCircleVsLine(ent, x1,y1,x2,y2,16) then
if dmg ~= 0 then
entity_damage(ent, me, 0.5, DT_AVATAR_VINE)
end
end
end
ent = getNextEntity()
end
end
end
function hitSurface(me)
end
function enterState(me)
end
function damage(me, attacker, bone, damageType, dmg)
return false
end
function exitState(me)
end
| gpl-2.0 |
joehanchoi/hammerspoon | extensions/layout/init.lua | 7 | 10183 | --- === hs.layout ===
---
--- Window layout manager
---
--- This extension allows you to trigger window placement/sizing to a number of windows at once
local layout = {}
local geometry = require("hs.geometry")
local fnutils = require("hs.fnutils")
local screen = require("hs.screen")
local window = require("hs.window")
local application = require("hs.application")
--- hs.layout.left25
--- Constant
--- A unit rect which will make a window occupy the left 25% of a screen
layout.left25 = geometry.rect(0, 0, 0.25, 1)
--- hs.layout.left30
--- Constant
--- A unit rect which will make a window occupy the left 30% of a screen
layout.left30 = geometry.rect(0, 0, 0.3, 1)
--- hs.layout.left50
--- Constant
--- A unit rect which will make a window occupy the left 50% of a screen
layout.left50 = geometry.rect(0, 0, 0.5, 1)
--- hs.layout.left70
--- Constant
--- A unit rect which will make a window occupy the left 70% of a screen
layout.left70 = geometry.rect(0, 0, 0.7, 1)
--- hs.layout.left75
--- Constant
--- A unit rect which will make a window occupy the left 75% of a screen
layout.left75 = geometry.rect(0, 0, 0.75, 1)
--- hs.layout.right25
--- Constant
--- A unit rect which will make a window occupy the right 25% of a screen
layout.right25 = geometry.rect(0.75, 0, 0.25, 1)
--- hs.layout.right30
--- Constant
--- A unit rect which will make a window occupy the right 30% of a screen
layout.right30 = geometry.rect(0.7, 0, 0.3, 1)
--- hs.layout.right50
--- Constant
--- A unit rect which will make a window occupy the right 50% of a screen
layout.right50 = geometry.rect(0.5, 0, 0.5, 1)
--- hs.layout.right70
--- Constant
--- A unit rect which will make a window occupy the right 70% of a screen
layout.right70 = geometry.rect(0.3, 0, 0.7, 1)
--- hs.layout.right75
--- Constant
--- A unit rect which will make a window occupy the right 75% of a screen
layout.right75 = geometry.rect(0.25, 0, 0.75, 1)
--- hs.layout.maximized
--- Constant
--- A unit rect which will make a window occupy all of a screen
layout.maximized = geometry.rect(0, 0, 1, 1)
--- hs.layout.apply(table[, windowTitleComparator])
--- Function
--- Applies a layout to applications/windows
---
--- Parameters:
--- * table - A table describing your desired layout. Each element in the table should be another table describing a set of windows to match, and their desired size/position. The fields in each of these tables are:
--- * A string containing an application name, or an `hs.application` object, or nil
--- * A string containing a window title or nil
--- * A string containing a screen name, or an `hs.screen` object, or a function that accepts no parameters and returns an `hs.screen` object, or nil to select the first available screen
--- * A Unit rect (see `hs.window.moveToUnit()`)
--- * A Frame rect (see `hs.screen:frame()`)
--- * A Full-frame rect (see `hs.screen:fullFrame()`)
--- * windowTitleComparator - (optional) Function to use for window title comparison. It is called with two string arguments (below) and its return value is evaluated as a boolean. If no comparator is provided, the '==' operator is used
--- * windowTitle: The `:title()` of the window object being examined
--- * layoutWindowTitle: The window title string (second field) specified in each element of the layout table
---
--- Returns:
--- * None
---
--- Notes:
--- * If the application name argument is nil, window titles will be matched regardless of which app they belong to
--- * If the window title argument is nil, all windows of the specified application will be matched
--- * You can specify both application name and window title if you want to match only one window of a particular application
--- * If you specify neither application name or window title, no windows will be matched :)
--- * Monitor name is a string, as found in `hs.screen:name()`. You can also pass an `hs.screen` object, or a function that returns an `hs.screen` object. If you pass nil, the first screen will be selected
--- * The final three arguments use `hs.geometry.rect()` objects to describe the desired position and size of matched windows:
--- * Unit rect will be passed to `hs.window.moveToUnit()`
--- * Frame rect will be passed to `hs.window.setFrame()` (including menubar and dock)
--- * Full-frame rect will be passed to `hs.window.setFrame()` (ignoring menubar and dock)
--- * If either the x or y components of frame/full-frame rect are negative, they will be applied as offsets against the opposite edge of the screen (e.g. If x is -100 then the left edge of the window will be 100 pixels from the right edge of the screen)
--- * Only one of the rect arguments will apply to any matched windows. If you specify more than one, the first will win
--- * An example usage:
---
--- ```layout1 = {
--- {"Mail", nil, "Color LCD", hs.layout.maximized, nil, nil},
--- {"Safari", nil, "Thunderbolt Display", hs.layout.maximized, nil, nil},
--- {"iTunes", "iTunes", "Color LCD", hs.layout.maximized, nil, nil},
--- {"iTunes", "MiniPlayer", "Color LCD", nil, nil, hs.geometry.rect(0, -48, 400, 48)},
--- }```
--- * An example of a function that works well as a `windowTitleComparator` is the Lua built-in `string.match`, which uses Lua Patterns to match strings
function layout.apply(layout, windowTitleComparator)
-- Layout parameter should be a table where each row takes the form of:
-- {"App name", "Window name","Display Name"/"hs.screen object", "unitrect", "framerect", "fullframerect"},
-- First three items in each row are strings (although the display name can also be an hs.screen object, or nil)
-- Second three items are rects that specify the position of the window. The first one that is
-- not nil, wins.
-- unitrect is a rect passed to window:moveToUnit()
-- framerect is a rect passed to window:setFrame()
-- If either the x or y components of framerect are negative, they will be applied as
-- offsets from the width or height of screen:frame(), respectively
-- fullframerect is a rect passed to window:setFrame()
-- If either the x or y components of fullframerect are negative, they will be applied
-- as offsets from the width or height of screen:fullFrame(), respectively
if not windowTitleComparator then
windowTitleComparator = function(windowTitle, layoutWindowTitle)
return windowTitle == layoutWindowTitle
end
end
for n,_row in pairs(layout) do
local app = nil
local wins = nil
local display = nil
local displaypoint = nil
local unit = _row[4]
local frame = _row[5]
local fullframe = _row[6]
local windows = nil
-- Find the application's object, if wanted
if _row[1] then
if type(_row[1]) == "userdata" then
app = _row[1]
else
app = application.get(_row[1])
if not app then
print("Unable to find app: " .. _row[1])
end
end
end
-- Find the destination display, if wanted
if _row[3] then
if type(_row[3]) == "string" then
local displays = fnutils.filter(screen.allScreens(), function(aScreen) return aScreen:name() == _row[3] end)
if displays then
-- TODO: This is bogus, multiple identical monitors will be impossible to lay out
display = displays[1]
end
elseif type(_row[3]) == "function" then
display = _row[3]()
elseif fnutils.contains(screen.allScreens(), _row[3]) then
display = _row[3]
else
-- Default to the main screen if the passed-in screen isn't found; useful for
-- layouts activated using the screen watcher, meaning that screens in layouts may
-- not be in the current screen configuration.
display = screen.primaryScreen()
end
else
display = screen.primaryScreen()
end
if not display then
print("Unable to find display: ", _row[3])
else
displaypoint = geometry.point(display:frame().x, display:frame().y)
end
-- Find the matching windows, if any
if _row[2] then
if app then
wins = fnutils.filter(app:allWindows(), function(win) return windowTitleComparator(win:title(), _row[2]) end)
else
wins = fnutils.filter(window:allWindows(), function(win) return windowTitleComparator(win:title(), _row[2]) end)
end
elseif app then
wins = app:allWindows()
end
-- Apply the display/frame positions requested, if any
if not wins then
print(_row[1],_row[2])
print("No windows matched, skipping.")
else
for m,_win in pairs(wins) do
local winframe = nil
local screenrect = nil
-- Move window to destination display, if wanted
if display and displaypoint then
_win:setTopLeft(displaypoint)
end
-- Apply supplied position, if any
if unit then
_win:moveToUnit(unit)
elseif frame then
winframe = frame
screenrect = _win:screen():frame()
elseif fullframe then
winframe = fullframe
screenrect = _win:screen():fullFrame()
end
if winframe then
if winframe.x < 0 or winframe.y < 0 then
if winframe.x < 0 then
winframe.x = screenrect.w + winframe.x
end
if winframe.y < 0 then
winframe.y = screenrect.h + winframe.y
end
end
_win:setFrame(winframe)
end
end
end
end
end
return layout
| mit |
tehran980/tele_HSN | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
aqasaeed/botz | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
tkdrob/Battle-Tag | Data/Script/Lua/Classes/UTActivity.State.Bytecode.lua | 1 | 8889 |
--[[--------------------------------------------------------------------------
--
-- File: UTActivity.State.Bytecode.lua
-- Copyright (c) Ubisoft Entertainment. All rights reserved.
--
-- Project: Ubitoys.Tag
-- Date: July 27, 2010
--
------------------------------------------------------------------------------
--
-- Description: ...
--
----------------------------------------------------------------------------]]
--[[ Dependencies ----------------------------------------------------------]]
require "UTActivity.Ui.Bytecode"
--[[ Class -----------------------------------------------------------------]]
UTActivity.State.Bytecode = UTClass(UTState)
-- __ctor --------------------------------------------------------------------
function UTActivity.State.Bytecode:__ctor(activity, ...)
assert(activity)
end
-- Begin ---------------------------------------------------------------------
function UTActivity.State.Bytecode:Begin()
-- load bytecode
local path = activity.bytecodePath
local chunk, message = loadfile(path)
self.result, self.byteCode = pcall(chunk)
if (self.result) then
self.CODE_LENGTH = #self.byteCode
end
print("CODE LENGTH : " .. self.CODE_LENGTH .. " -------------------------------------------")
-- UI
UIMenuManager.stack:Push(UTActivity.Ui.Bytecode)
-- initialise command
self.command = 0x86
self.lockFlash = 0;
-- TOC for flash mem : header(4 o) number(1 o) entry(4 o) offset(2 o) size(2 o) size(2 o)
self.TOC = {0x43, 0x4f, 0x44, 0x45, 0x01, 0x44, 0x46, 0x4c, 0x54, 0x0d, 0x00,
quartz.system.bitwise.bitwiseand(self.CODE_LENGTH, 0x00ff), quartz.system.bitwise.bitwiseand(self.CODE_LENGTH, 0xff00) / 256,
quartz.system.bitwise.bitwiseand(self.CODE_LENGTH, 0x00ff), quartz.system.bitwise.bitwiseand(self.CODE_LENGTH, 0xff00) / 256}
self.flashMemory = {0x00, 0x00, 0x40, 0x00}
-- add magic number
self.byteCode[self.CODE_LENGTH + 1] = 0x22
self.byteCode[self.CODE_LENGTH + 2] = 0x04
self.byteCode[self.CODE_LENGTH + 3] = 0x19
self.byteCode[self.CODE_LENGTH + 4] = 0x86
-- initialise message
self.msgTotalSize = self.CODE_LENGTH + #self.TOC + 4
self:CreateNextMessage()
self.step = 0
self.maxStep = 2 + math.ceil((self.CODE_LENGTH + #self.TOC + 4) / 58)
-- register to proxy message received
assert(engine.libraries.usb)
assert(engine.libraries.usb.proxy)
-- decrease the timings on the device pinger,
-- so that we can detect device deconnections a little bit faster
assert(engine.libraries.usb.proxy.processes.devicePinger)
--engine.libraries.usb.proxy.processes.devicePinger:Reset(2000000, 4000000, 500000)
engine.libraries.usb.proxy.processes.devicePinger:Reset(4000000, 8000000, 500000)
-- event from proxy
engine.libraries.usb.proxy._DispatchMessage:Add(self, UTActivity.State.Bytecode.OnMessageReceived)
engine.libraries.usb.proxy._DeviceRemoved:Add(self, UTActivity.State.Bytecode.OnDeviceRemoved)
-- stop bytecode sending
self.stopSending = false
end
-- CreateNextMessage ---------------------------------------------------------
function UTActivity.State.Bytecode:CreateNextMessage()
-- init timer
self.timer = quartz.system.time.gettimemicroseconds()
-- create message
if (self.command == 0x81) then
-- erase page
self.msg = {0x04, 0xff, self.command, self.flashMemory[1], self.flashMemory[2], self.flashMemory[3], self.flashMemory[4]}
elseif (self.command == 0x82) then
-- init write sequence
self.msg = {0x06, 0xff, self.command, self.flashMemory[1], self.flashMemory[2], self.flashMemory[3], self.flashMemory[4],
quartz.system.bitwise.bitwiseand(self.msgTotalSize, 0xff00) / 256, quartz.system.bitwise.bitwiseand(self.msgTotalSize, 0x00ff)}
elseif (self.command == 0x83) then
-- info for this message : nb data, broadcast, command, offset and length
local msgSize = math.min(self.msgTotalSize - self.offset, 58)
self.msg = {msgSize + 3, 0xff, self.command, quartz.system.bitwise.bitwiseand(self.offset, 0xff00) / 256, quartz.system.bitwise.bitwiseand(self.offset, 0x00ff), msgSize}
-- write msg
for i = 1, msgSize do
if (i + self.offset <= #self.TOC) then
self.msg[i + 6] = self.TOC[i]
else
self.msg[i + 6] = self.byteCode[i + self.offset - #self.TOC]
end
end
-- next offset
self.offset = self.offset + msgSize
elseif (self.command == 0x86) then
-- lock flash
self.msg = {0x01, 0xff, self.command, self.lockFlash}
end
-- init answers
for _, player in ipairs(activity.players) do
if (player.rfGunDevice) then player.rfGunDevice.acknowledge = false
end
end
end
-- End -----------------------------------------------------------------------
function UTActivity.State.Bytecode:End()
-- reset the timings on the device pinger,
if (engine.libraries.usb.proxy) then
assert(engine.libraries.usb.proxy.processes.devicePinger)
engine.libraries.usb.proxy.processes.devicePinger:Reset()
-- unregister to proxy message received
engine.libraries.usb.proxy._DispatchMessage:Remove(self, UTActivity.State.Bytecode.OnMessageReceived)
engine.libraries.usb.proxy._DeviceRemoved:Remove(self, UTActivity.State.Bytecode.OnDeviceRemoved)
end
-- pop menu
UIMenuManager.stack:Pop()
end
-- OnDeviceRemoved -----------------------------------------------------------
function UTActivity.State.Bytecode:OnDeviceRemoved(device)
-- a device from my list has been removed : STOP right now and go back to main menu
if (not self.stopSending) then
for _, player in ipairs(activity.players) do
if (player.rfGunDevice and player.rfGunDevice == device) then
self.uiPopup = UIPopupWindow:New()
self.uiPopup.title = l"con046"
self.uiPopup.text = l"con048"
-- buttons
self.uiPopup.uiButton2 = self.uiPopup:AddComponent(UIButton:New(), "uiButton2")
self.uiPopup.uiButton2.rectangle = UIPopupWindow.buttonRectangles[2]
self.uiPopup.uiButton2.text = l "but019"
self.uiPopup.uiButton2.OnAction = function ()
UIManager.stack:Pop()
UIMenuManager.stack:Pop()
activity.matches = nil
activity:PostStateChange("playersmanagement")
self.enabled = false
end
self.stopSending = true
UIManager.stack:Push(self.uiPopup)
break
end
end
end
end
-- OnMessageReceived----------------------------------------------------------
function UTActivity.State.Bytecode:OnMessageReceived(device, addressee, command, arg)
-- test command !
if (command == self.command) then
if (device and not device.acknowledge) then
-- acknowledge answers
if (0x83 == command) then
local answerOffset = (arg[1] * 256) + arg[2]
if (answerOffset == self.offset) then
device.acknowledge = true
end
else
device.acknowledge = true
end
-- every device has answered ?
local acknowledge = true
for _, player in ipairs(activity.players) do
if (player.rfGunDevice and not player.rfGunDevice.acknowledge) then
acknowledge = false
break
end
end
if (acknowledge) then
self.step = self.step + 1
if (command == 0x81) then
self.command = 0x82
self:CreateNextMessage()
elseif (command == 0x82) then
self.command = 0x83
self.offset = 0
self:CreateNextMessage()
elseif (command == 0x83) then
if (self.offset == self.msgTotalSize) then
self.command = 0x86
self.lockFlash = 1
end
self:CreateNextMessage()
elseif (command == 0x86) then
if (0 == self.lockFlash) then
self.command = 0x81
self:CreateNextMessage()
else
-- go now
activity:PostStateChange("matchmaking")
end
end
end
end
end
end
-- Update --------------------------------------------------------------------
function UTActivity.State.Bytecode:Update()
-- send msg each 250ms
local interval = 250000
local numberOfPlayers = 0
for _, player in ipairs(activity.players) do
if (not player.rfGunDevice.timedout) then
numberOfPlayers = numberOfPlayers + 1
end
end
interval = 21000 + (numberOfPlayers*16000)
local elapsedTime = quartz.system.time.gettimemicroseconds() - self.timer
if (elapsedTime > interval) then
-- send current msg
self.timer = quartz.system.time.gettimemicroseconds()
quartz.system.usb.sendmessage(engine.libraries.usb.proxy.handle, self.msg)
end
end
| mit |
eagle14/kia14 | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
milos-korenciak/heroku-buildpack-tex | buildpack/texmf-dist/scripts/oberdiek/oberdiek.magicnum.lua | 6 | 5306 | --
-- This is file `oberdiek.magicnum.lua',
-- generated with the docstrip utility.
--
-- The original source files were:
--
-- magicnum.dtx (with options: `lua')
--
-- This is a generated file.
--
-- Project: magicnum
-- Version: 2011/04/10 v1.4
--
-- Copyright (C) 2007, 2009-2011 by
-- Heiko Oberdiek <heiko.oberdiek at googlemail.com>
--
-- This work may be distributed and/or modified under the
-- conditions of the LaTeX Project Public License, either
-- version 1.3c of this license or (at your option) any later
-- version. This version of this license is in
-- http://www.latex-project.org/lppl/lppl-1-3c.txt
-- and the latest version of this license is in
-- http://www.latex-project.org/lppl.txt
-- and version 1.3 or later is part of all distributions of
-- LaTeX version 2005/12/01 or later.
--
-- This work has the LPPL maintenance status "maintained".
--
-- This Current Maintainer of this work is Heiko Oberdiek.
--
-- The Base Interpreter refers to any `TeX-Format',
-- because some files are installed in TDS:tex/generic//.
--
-- This work consists of the main source file magicnum.dtx
-- and the derived files
-- magicnum.sty, magicnum.pdf, magicnum.ins, magicnum.drv, magicnum.txt,
-- magicnum-test1.tex, magicnum-test2.tex, magicnum-test3.tex,
-- magicnum-test4.tex, magicnum.lua, oberdiek.magicnum.lua.
--
module("oberdiek.magicnum", package.seeall)
function getversion()
tex.write("2011/04/10 v1.4")
end
local data = {
["tex.catcode"] = {
[0] = "escape",
[1] = "begingroup",
[2] = "endgroup",
[3] = "math",
[4] = "align",
[5] = "eol",
[6] = "parameter",
[7] = "superscript",
[8] = "subscript",
[9] = "ignore",
[10] = "space",
[11] = "letter",
[12] = "other",
[13] = "active",
[14] = "comment",
[15] = "invalid",
["active"] = 13,
["align"] = 4,
["begingroup"] = 1,
["comment"] = 14,
["endgroup"] = 2,
["eol"] = 5,
["escape"] = 0,
["ignore"] = 9,
["invalid"] = 15,
["letter"] = 11,
["math"] = 3,
["other"] = 12,
["parameter"] = 6,
["space"] = 10,
["subscript"] = 8,
["superscript"] = 7
},
["etex.grouptype"] = {
[0] = "bottomlevel",
[1] = "simple",
[2] = "hbox",
[3] = "adjustedhbox",
[4] = "vbox",
[5] = "align",
[6] = "noalign",
[8] = "output",
[9] = "math",
[10] = "disc",
[11] = "insert",
[12] = "vcenter",
[13] = "mathchoice",
[14] = "semisimple",
[15] = "mathshift",
[16] = "mathleft",
["adjustedhbox"] = 3,
["align"] = 5,
["bottomlevel"] = 0,
["disc"] = 10,
["hbox"] = 2,
["insert"] = 11,
["math"] = 9,
["mathchoice"] = 13,
["mathleft"] = 16,
["mathshift"] = 15,
["noalign"] = 6,
["output"] = 8,
["semisimple"] = 14,
["simple"] = 1,
["vbox"] = 4,
["vcenter"] = 12
},
["etex.iftype"] = {
[0] = "none",
[1] = "char",
[2] = "cat",
[3] = "num",
[4] = "dim",
[5] = "odd",
[6] = "vmode",
[7] = "hmode",
[8] = "mmode",
[9] = "inner",
[10] = "void",
[11] = "hbox",
[12] = "vbox",
[13] = "x",
[14] = "eof",
[15] = "true",
[16] = "false",
[17] = "case",
[18] = "defined",
[19] = "csname",
[20] = "fontchar",
["case"] = 17,
["cat"] = 2,
["char"] = 1,
["csname"] = 19,
["defined"] = 18,
["dim"] = 4,
["eof"] = 14,
["false"] = 16,
["fontchar"] = 20,
["hbox"] = 11,
["hmode"] = 7,
["inner"] = 9,
["mmode"] = 8,
["none"] = 0,
["num"] = 3,
["odd"] = 5,
["true"] = 15,
["vbox"] = 12,
["vmode"] = 6,
["void"] = 10,
["x"] = 13
},
["etex.nodetype"] = {
[-1] = "none",
[0] = "char",
[1] = "hlist",
[2] = "vlist",
[3] = "rule",
[4] = "ins",
[5] = "mark",
[6] = "adjust",
[7] = "ligature",
[8] = "disc",
[9] = "whatsit",
[10] = "math",
[11] = "glue",
[12] = "kern",
[13] = "penalty",
[14] = "unset",
[15] = "maths",
["adjust"] = 6,
["char"] = 0,
["disc"] = 8,
["glue"] = 11,
["hlist"] = 1,
["ins"] = 4,
["kern"] = 12,
["ligature"] = 7,
["mark"] = 5,
["math"] = 10,
["maths"] = 15,
["none"] = -1,
["penalty"] = 13,
["rule"] = 3,
["unset"] = 14,
["vlist"] = 2,
["whatsit"] = 9
},
["etex.interactionmode"] = {
[0] = "batch",
[1] = "nonstop",
[2] = "scroll",
[3] = "errorstop",
["batch"] = 0,
["errorstop"] = 3,
["nonstop"] = 1,
["scroll"] = 2
},
["luatex.pdfliteral.mode"] = {
[0] = "setorigin",
[1] = "page",
[2] = "direct",
["direct"] = 2,
["page"] = 1,
["setorigin"] = 0
}
}
function get(name)
local startpos, endpos, category, entry =
string.find(name, "^(%a[%a%d%.]*)%.(-?[%a%d]+)$")
if not entry then
return
end
local node = data[category]
if not node then
return
end
local num = tonumber(entry)
local value
if num then
value = node[num]
if not value then
return
end
else
value = node[entry]
if not value then
return
end
value = "" .. value
end
tex.write(value)
end
--
-- End of File `oberdiek.magicnum.lua'.
| mit |
shahabsaf1/tg | bot/bot.lua | 1 | 6691 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"9gag",
"eur",
"echo",
"btc",
"get",
"giphy",
"google",
"gps",
"help",
"id",
"images",
"img_google",
"location",
"banhammer",
"moderation",
"media",
"plugins",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"xkcd",
"youtube" },
sudo_users = {119989724},
disabled_channels = {}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
dunn/ntopng | scripts/lua/modules/flow_utils.lua | 8 | 38550 | --
-- (C) 2013-15 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "template"
-- http://www.itu.int/itudoc/itu-t/ob-lists/icc/e212_685.pdf
local mobile_country_code = {
["202"] = "Greece",
["204"] = "Netherlands (Kingdom of the)",
["206"] = "Belgium",
["208"] = "France",
["212"] = "Monaco (Principality of)",
["213"] = "Andorra (Principality of)",
["214"] = "Spain",
["216"] = "Hungary (Republic of)",
["218"] = "Bosnia and Herzegovina",
["219"] = "Croatia (Republic of)",
["220"] = "Serbia and Montenegro",
["222"] = "Italy",
["225"] = "Vatican City State",
["226"] = "Romania",
["228"] = "Switzerland (Confederation of)",
["230"] = "Czech Republic",
["231"] = "Slovak Republic",
["232"] = "Austria",
["234"] = "United Kingdom",
["235"] = "United Kingdom",
["238"] = "Denmark",
["240"] = "Sweden",
["242"] = "Norway",
["244"] = "Finland",
["246"] = "Lithuania (Republic of)",
["247"] = "Latvia (Republic of)",
["248"] = "Estonia (Republic of)",
["250"] = "Russian Federation",
["255"] = "Ukraine",
["257"] = "Belarus (Republic of)",
["259"] = "Moldova (Republic of)",
["260"] = "Poland (Republic of)",
["262"] = "Germany (Federal Republic of)",
["266"] = "Gibraltar",
["268"] = "Portugal",
["270"] = "Luxembourg",
["272"] = "Ireland",
["274"] = "Iceland",
["276"] = "Albania (Republic of)",
["278"] = "Malta",
["280"] = "Cyprus (Republic of)",
["282"] = "Georgia",
["283"] = "Armenia (Republic of)",
["284"] = "Bulgaria (Republic of)",
["286"] = "Turkey",
["288"] = "Faroe Islands",
["290"] = "Greenland (Denmark)",
["292"] = "San Marino (Republic of)",
["293"] = "Slovenia (Republic of)",
["294"] = "The Former Yugoslav Republic of Macedonia",
["295"] = "Liechtenstein (Principality of)",
["302"] = "Canada",
["308"] = "Saint Pierre and Miquelon",
["310"] = "United States of America",
["311"] = "United States of America",
["312"] = "United States of America",
["313"] = "United States of America",
["314"] = "United States of America",
["315"] = "United States of America",
["316"] = "United States of America",
["330"] = "Puerto Rico",
["332"] = "United States Virgin Islands",
["334"] = "Mexico",
["338"] = "Jamaica",
["340"] = "Martinique / Guadeloupe",
["342"] = "Barbados",
["344"] = "Antigua and Barbuda",
["346"] = "Cayman Islands",
["348"] = "British Virgin Islands",
["350"] = "Bermuda",
["352"] = "Grenada",
["354"] = "Montserrat",
["356"] = "Saint Kitts and Nevis",
["358"] = "SaintLucia",
["360"] = "Saint Vincent and the Grenadines",
["362"] = "Netherlands Antilles",
["363"] = "Aruba",
["364"] = "Bahamas (Commonwealth of the)",
["365"] = "Anguilla",
["366"] = "Dominica (Commonwealth of)",
["368"] = "Cuba",
["370"] = "Dominican Republic",
["372"] = "Haiti (Republic of)",
["374"] = "Trinidad and Tobago",
["376"] = "Turks and Caicos Islands",
["400"] = "Azerbaijani Republic",
["401"] = "Kazakhstan (Republic of)",
["402"] = "Bhutan (Kingdom of)",
["404"] = "India (Republic of)",
["410"] = "Pakistan (Islamic Republic of)",
["412"] = "Afghanistan",
["413"] = "Sri Lanka (Democratic Socialist Republic of)",
["414"] = "Myanmar (Union of)",
["415"] = "Lebanon",
["416"] = "Jordan (Hashemite Kingdom of)",
["417"] = "Syrian Arab Republic",
["418"] = "Iraq (Republic of)",
["419"] = "Kuwait (State of)",
["420"] = "Saudi Arabia (Kingdom of)",
["421"] = "Yemen (Republic of)",
["422"] = "Oman (Sultanate of)",
["424"] = "United Arab Emirates",
["425"] = "Israel (State of)",
["426"] = "Bahrain (Kingdom of)",
["427"] = "Qatar (State of)",
["428"] = "Mongolia",
["429"] = "Nepal",
["430"] = "United Arab Emirates b",
["431"] = "United Arab Emirates b",
["432"] = "Iran (Islamic Republic of)",
["434"] = "Uzbekistan (Republic of)",
["436"] = "Tajikistan (Republic of)",
["437"] = "Kyrgyz Republic",
["438"] = "Turkmenistan",
["440"] = "Japan",
["441"] = "Japan",
["450"] = "Korea (Republic of)",
["452"] = "Viet Nam (Socialist Republic of)",
["454"] = "Hongkong China",
["455"] = "Macao China",
["456"] = "Cambodia (Kingdom of)",
["457"] = "Lao People's Democratic Republic",
["460"] = "China (People's Republic of)",
["461"] = "China (People's Republic of)",
["466"] = "Taiwan",
["467"] = "Democratic People's Republic of Korea",
["470"] = "Bangladesh (People's Republic of)",
["472"] = "Maldives (Republic of)",
["502"] = "Malaysia",
["505"] = "Australia",
["510"] = "Indonesia (Republic of)",
["514"] = "Democratique Republic of Timor-Leste",
["515"] = "Philippines (Republic of the)",
["520"] = "Thailand",
["525"] = "Singapore (Republic of)",
["528"] = "Brunei Darussalam",
["530"] = "New Zealand",
["534"] = "Northern Mariana Islands (Commonwealth of the)",
["535"] = "Guam",
["536"] = "Nauru (Republic of)",
["537"] = "Papua New Guinea",
["539"] = "Tonga (Kingdom of)",
["540"] = "Solomon Islands",
["541"] = "Vanuatu (Republic of)",
["542"] = "Fiji (Republic of)",
["543"] = "Wallis and Futuna",
["544"] = "American Samoa",
["545"] = "Kiribati (Republic of)",
["546"] = "New Caledonia",
["547"] = "French Polynesia",
["548"] = "Cook Islands",
["549"] = "Samoa (Independent State of)",
["550"] = "Micronesia (Federated States of)",
["551"] = "Marshall Islands (Republic of the)",
["552"] = "Palau (Republic of)",
["602"] = "Egypt (Arab Republic of)",
["603"] = "Algeria (People's Democratic Republic of)",
["604"] = "Morocco (Kingdom of)",
["605"] = "Tunisia",
["606"] = "Libya",
["607"] = "Gambia (Republic of the)",
["608"] = "Senegal (Republic of)",
["609"] = "Mauritania (Islamic Republic of)",
["610"] = "Mali (Republic of)",
["611"] = "Guinea (Republic of)",
["612"] = "Cote d'Ivoire (Republic of)",
["613"] = "Burkina Faso",
["614"] = "Niger (Republic of the)",
["615"] = "Togolese Republic",
["616"] = "Benin (Republic of)",
["617"] = "Mauritius (Republic of)",
["618"] = "Liberia (Republic of)",
["619"] = "Sierra Leone",
["620"] = "Ghana",
["621"] = "Nigeria (Federal Republic of)",
["622"] = "Chad (Republic of)",
["623"] = "Central African Republic",
["624"] = "Cameroon (Republic of)",
["625"] = "Cape Verde (Republic of)",
["626"] = "Sao Tome and Principe (Democratic Republic of)",
["627"] = "Equatorial Guinea (Republic of)",
["628"] = "Gabonese Republic",
["629"] = "Congo (Republic of the)",
["630"] = "Democratic Republic of the Congo",
["631"] = "Angola (Republic of)",
["632"] = "Guinea-Bissau (Republic of)",
["633"] = "Seychelles (Republic of)",
["634"] = "Sudan (Republic of the)",
["635"] = "Rwandese Republic",
["636"] = "Ethiopia (Federal Democratic Republic of)",
["637"] = "Somali Democratic Republic",
["638"] = "Djibouti (Republic of)",
["639"] = "Kenya (Republic of)",
["640"] = "Tanzania (United Republic of)",
["641"] = "Uganda (Republic of)",
["642"] = "Burundi (Republic of)",
["643"] = "Mozambique (Republic of)",
["645"] = "Zambia (Republic of)",
["646"] = "Madagascar (Republic of)",
["647"] = "Reunion (French Department of)",
["648"] = "Zimbabwe (Republic of)",
["649"] = "Namibia (Republic of)",
["650"] = "Malawi",
["651"] = "Lesotho (Kingdom of)",
["652"] = "Botswana (Republic of)",
["653"] = "Swaziland (Kingdom of)",
["654"] = "Comoros (Union of the)",
["655"] = "South Africa (Republic of)",
["657"] = "Eritrea",
["702"] = "Belize",
["704"] = "Guatemala (Republic of)",
["706"] = "El Salvador (Republic of)",
["708"] = "Honduras (Republic of)",
["710"] = "Nicaragua",
["712"] = "Costa Rica",
["714"] = "Panama (Republic of)",
["716"] = "Peru",
["722"] = "Argentine Republic",
["724"] = "Brazil (Federative Republic of)",
["730"] = "Chile",
["732"] = "Colombia (Republic of)",
["734"] = "Venezuela (Bolivarian Republic of)",
["736"] = "Bolivia (Republic of)",
["738"] = "Guyana",
["740"] = "Ecuador",
["742"] = "French Guiana (French Department of)",
["744"] = "Paraguay (Republic of)",
["746"] = "Suriname (Republic of)",
["748"] = "Uruguay (Eastern Republic of)",
["412"] = "Afghanistan",
["276"] = "Albania (Republic of)",
["603"] = "Algeria (People's Democratic Republic of)",
["544"] = "American Samoa",
["213"] = "Andorra (Principality of)",
["631"] = "Angola (Republic of)",
["365"] = "Anguilla",
["344"] = "Antigua and Barbuda",
["722"] = "Argentine Republic",
["283"] = "Armenia (Republic of)",
["363"] = "Aruba",
["505"] = "Australia",
["232"] = "Austria",
["400"] = "Azerbaijani Republic",
["364"] = "Bahamas (Commonwealth of the)",
["426"] = "Bahrain (Kingdom of)",
["470"] = "Bangladesh (People's Republic of)",
["342"] = "Barbados",
["257"] = "Belarus (Republic of)",
["206"] = "Belgium",
["702"] = "Belize",
["616"] = "Benin (Republic of)",
["350"] = "Bermuda",
["402"] = "Bhutan (Kingdom of)",
["736"] = "Bolivia (Republic of)",
["218"] = "Bosnia and Herzegovina",
["652"] = "Botswana (Republic of)",
["724"] = "Brazil (Federative Republic of)",
["348"] = "British Virgin Islands",
["528"] = "Brunei Darussalam",
["284"] = "Bulgaria (Republic of)",
["613"] = "Burkina Faso",
["642"] = "Burundi (Republic of)",
["456"] = "Cambodia (Kingdom of)",
["624"] = "Cameroon (Republic of)",
["302"] = "Canada",
["625"] = "Cape Verde (Republic of)",
["346"] = "Cayman Islands",
["623"] = "Central African Republic",
["622"] = "Chad (Republic of)",
["730"] = "Chile",
["461"] = "China (People's Republic of)",
["460"] = "China (People's Republic of)",
["732"] = "Colombia (Republic of)",
["654"] = "Comoros (Union of the)",
["629"] = "Congo (Republic of the)",
["548"] = "Cook Islands",
["712"] = "Costa Rica",
["612"] = "Cote d'Ivoire (Republic of)",
["219"] = "Croatia (Republic of)",
["368"] = "Cuba",
["280"] = "Cyprus (Republic of)",
["230"] = "Czech Republic",
["467"] = "Democratic People's Republic of Korea",
["630"] = "Democratic Republic of the Congo",
["514"] = "Democratique Republic of Timor-Leste",
["238"] = "Denmark",
["638"] = "Djibouti (Republic of)",
["366"] = "Dominica (Commonwealth of)",
["370"] = "Dominican Republic",
["740"] = "Ecuador",
["602"] = "Egypt (Arab Republic of)",
["706"] = "El Salvador (Republic of)",
["627"] = "Equatorial Guinea (Republic of)",
["657"] = "Eritrea",
["248"] = "Estonia (Republic of)",
["636"] = "Ethiopia (Federal Democratic Republic of)",
["288"] = "Faroe Islands",
["542"] = "Fiji (Republic of)",
["244"] = "Finland",
["208"] = "France",
["742"] = "French Guiana (French Department of)",
["547"] = "French Polynesia",
["628"] = "Gabonese Republic",
["607"] = "Gambia (Republic of the)",
["282"] = "Georgia",
["262"] = "Germany (Federal Republic of)",
["620"] = "Ghana",
["266"] = "Gibraltar",
["202"] = "Greece",
["290"] = "Greenland (Denmark)",
["352"] = "Grenada",
["340"] = "Guadeloupe (French Department of)",
["535"] = "Guam",
["704"] = "Guatemala (Republic of)",
["611"] = "Guinea (Republic of)",
["632"] = "Guinea-Bissau (Republic of)",
["738"] = "Guyana",
["372"] = "Haiti (Republic of)",
["708"] = "Honduras (Republic of)",
["454"] = "Hongkong China",
["216"] = "Hungary (Republic of)",
["274"] = "Iceland",
["404"] = "India (Republic of)",
["510"] = "Indonesia (Republic of)",
["901"] = "International Mobile shared code c",
["432"] = "Iran (Islamic Republic of)",
["418"] = "Iraq (Republic of)",
["272"] = "Ireland",
["425"] = "Israel (State of)",
["222"] = "Italy",
["338"] = "Jamaica",
["441"] = "Japan",
["440"] = "Japan",
["416"] = "Jordan (Hashemite Kingdom of)",
["401"] = "Kazakhstan (Republic of)",
["639"] = "Kenya (Republic of)",
["545"] = "Kiribati (Republic of)",
["450"] = "Korea (Republic of)",
["419"] = "Kuwait (State of)",
["437"] = "Kyrgyz Republic",
["457"] = "Lao People's Democratic Republic",
["247"] = "Latvia (Republic of)",
["415"] = "Lebanon",
["651"] = "Lesotho (Kingdom of)",
["618"] = "Liberia (Republic of)",
["606"] = "Libya",
["295"] = "Liechtenstein (Principality of)",
["246"] = "Lithuania (Republic of)",
["270"] = "Luxembourg",
["455"] = "Macao China",
["646"] = "Madagascar (Republic of)",
["650"] = "Malawi",
["502"] = "Malaysia",
["472"] = "Maldives (Republic of)",
["610"] = "Mali (Republic of)",
["278"] = "Malta",
["551"] = "Marshall Islands (Republic of the)",
["340"] = "Martinique (French Department of)",
["609"] = "Mauritania (Islamic Republic of)",
["617"] = "Mauritius (Republic of)",
["334"] = "Mexico",
["550"] = "Micronesia (Federated States of)",
["259"] = "Moldova (Republic of)",
["212"] = "Monaco (Principality of)",
["428"] = "Mongolia",
["354"] = "Montserrat",
["604"] = "Morocco (Kingdom of)",
["643"] = "Mozambique (Republic of)",
["414"] = "Myanmar (Union of)",
["649"] = "Namibia (Republic of)",
["536"] = "Nauru (Republic of)",
["429"] = "Nepal",
["204"] = "Netherlands (Kingdom of the)",
["362"] = "Netherlands Antilles",
["546"] = "New Caledonia",
["530"] = "New Zealand",
["710"] = "Nicaragua",
["614"] = "Niger (Republic of the)",
["621"] = "Nigeria (Federal Republic of)",
["534"] = "Northern Mariana Islands (Commonwealth of the)",
["242"] = "Norway",
["422"] = "Oman (Sultanate of)",
["410"] = "Pakistan (Islamic Republic of)",
["552"] = "Palau (Republic of)",
["714"] = "Panama (Republic of)",
["537"] = "Papua New Guinea",
["744"] = "Paraguay (Republic of)",
["716"] = "Peru",
["515"] = "Philippines (Republic of the)",
["260"] = "Poland (Republic of)",
["268"] = "Portugal",
["330"] = "Puerto Rico",
["427"] = "Qatar (State of)",
["8XX"] = "Reserved a 0XX Reserved a 1XX Reserved a",
["647"] = "Reunion (French Department of) 226 Romania",
["250"] = "Russian Federation",
["635"] = "Rwandese Republic",
["356"] = "Saint Kitts and Nevis",
["358"] = "SaintLucia",
["308"] = "Saint Pierre and Miquelon",
["360"] = "Saint Vincent and the Grenadines",
["549"] = "Samoa (Independent State of)",
["292"] = "San Marino (Republic of)",
["626"] = "Sao Tome and Principe (Democratic Republic of)",
["420"] = "Saudi Arabia (Kingdom of)",
["608"] = "Senegal (Republic of)",
["220"] = "Serbia and Montenegro",
["633"] = "Seychelles (Republic of)",
["619"] = "Sierra Leone",
["525"] = "Singapore (Republic of)",
["231"] = "Slovak Republic",
["293"] = "Slovenia (Republic of)",
["540"] = "Solomon Islands",
["637"] = "Somali Democratic Republic",
["655"] = "South Africa (Republic of)",
["214"] = "Spain",
["413"] = "Sri Lanka (Democratic Socialist Republic of)",
["634"] = "Sudan (Republic of the)",
["746"] = "Suriname (Republic of)",
["653"] = "Swaziland (Kingdom of)",
["240"] = "Sweden",
["228"] = "Switzerland (Confederation of)",
["417"] = "Syrian Arab Republic",
["466"] = "Taiwan",
["436"] = "Tajikistan (Republic of)",
["640"] = "Tanzania (United Republic of)",
["520"] = "Thailand",
["294"] = "The Former Yugoslav Republic of Macedonia",
["615"] = "Togolese Republic",
["539"] = "Tonga (Kingdom of)",
["374"] = "Trinidad and Tobago",
["605"] = "Tunisia",
["286"] = "Turkey",
["438"] = "Turkmenistan",
["376"] = "Turks and Caicos Islands",
["641"] = "Uganda (Republic of)",
["255"] = "Ukraine",
["424"] = "United Arab Emirates",
["430"] = "United Arab Emirates b",
["431"] = "United Arab Emirates b",
["235"] = "United Kingdom",
["234"] = "United Kingdom",
["310"] = "United States of America",
["316"] = "United States of America",
["311"] = "United States of America",
["312"] = "United States of America",
["313"] = "United States of America",
["314"] = "United States of America",
["315"] = "United States of America",
["332"] = "United States Virgin Islands",
["748"] = "Uruguay (Eastern Republic of)",
["434"] = "Uzbekistan (Republic of)",
["541"] = "Vanuatu (Republic of)",
["225"] = "Vatican City State",
["734"] = "Venezuela (Bolivarian Republic of)",
["452"] = "Viet Nam (Socialist Republic of)",
["543"] = "Wallis and Futuna",
["421"] = "Yemen (Republic of)",
["645"] = "Zambia (Republic of)",
["648"] = "Zimbabwe (Republic of)",
}
-- #######################
function handleCustomFlowField(key, value)
if(key == 'TCP_FLAGS') then
return(formatTcpFlags(value))
elseif((key == 'INPUT_SNMP') or (key == 'OUTPUT_SNMP')) then
return(formatInterfaceId(value))
elseif((key == 'FLOW_USER_NAME') or (key == '57593')) then
elems = string.split(value, ';')
if((elems ~= nil) and (table.getn(elems) == 6)) then
r = '<table class="table table-bordered table-striped">'
imsi = elems[1]
mcc = string.sub(imsi, 1, 3)
if(mobile_country_code[mcc] ~= nil) then
mcc_name = " ["..mobile_country_code[mcc].."]"
else
mcc_name = ""
end
r = r .. "<th>IMSI (International mobile Subscriber Identity)</th><td>"..elems[1]..mcc_name
r = r .. " <A HREF=http://www.numberingplans.com/?page=analysis&sub=imsinr><i class='fa fa-info'></i></A></td></tr>"
r = r .. "<th>NSAPI</th><td>".. elems[2].."</td></tr>"
r = r .. "<th>GSM Cell LAC (Location Area Code)</th><td>".. elems[3].."</td></tr>"
r = r .. "<th>GSM Cell Identifier</th><td>".. elems[4].."</td></tr>"
r = r .. "<th>SAC (Service Area Code)</th><td>".. elems[5].."</td></tr>"
r = r .. "<th>IP Address</th><td>".. ntop.inet_ntoa(elems[6]).."</td></tr>"
r = r .. "</table>"
return(r)
else
return(value)
end
end
-- Unformatted value
return value
end
-- #######################
function formatTcpFlags(flags)
if(flags == 0) then
return("")
end
rsp = "<A HREF=http://en.wikipedia.org/wiki/Transmission_Control_Protocol>"
if(bit.band(flags, 1) == 2) then rsp = rsp .. " SYN " end
if(bit.band(flags, 16) == 16) then rsp = rsp .. " ACK " end
if(bit.band(flags, 1) == 1) then rsp = rsp .. " FIN " end
if(bit.band(flags, 4) == 4) then rsp = rsp .. " RST " end
if(bit.band(flags, 8) == 8 ) then rsp = rsp .. " PUSH " end
return(rsp .. "</A>")
end
-- #######################
function formatInterfaceId(id)
if(id == 65535) then
return("Unknown")
else
return(id)
end
end
-- #######################
local flow_fields_description = {
["IN_BYTES"] = "Incoming flow bytes (src->dst)",
["IN_PKTS"] = "Incoming flow packets (src->dst)",
["FLOWS"] = "Number of flows",
["PROTOCOL"] = "IP protocol byte",
["PROTOCOL_MAP"] = "IP protocol name",
["SRC_TOS"] = "Type of service (TOS)",
["TCP_FLAGS"] = "Cumulative of all flow TCP flags",
["L4_SRC_PORT"] = "IPv4 source port",
["L4_SRC_PORT_MAP"] = "Layer 4 source port symbolic name",
["IPV4_SRC_ADDR"] = "IPv4 source address",
["IPV4_SRC_MASK"] = "IPv4 source subnet mask (/<bits>)",
["INPUT_SNMP"] = "Input interface SNMP idx",
["L4_DST_PORT"] = "IPv4 destination port",
["L4_DST_PORT_MAP"] = "Layer 4 destination port symbolic name",
["L4_SRV_PORT"] = "Layer 4 server port",
["L4_SRV_PORT_MAP"] = "Layer 4 server port symbolic name",
["IPV4_DST_ADDR"] = "IPv4 destination address",
["IPV4_DST_MASK"] = "IPv4 dest subnet mask (/<bits>)",
["OUTPUT_SNMP"] = "Output interface SNMP idx",
["IPV4_NEXT_HOP"] = "IPv4 Next Hop",
["SRC_AS"] = "Source BGP AS",
["DST_AS"] = "Destination BGP AS",
["LAST_SWITCHED"] = "SysUptime (msec) of the last flow pkt",
["FIRST_SWITCHED"] = "SysUptime (msec) of the first flow pkt",
["OUT_BYTES"] = "Outgoing flow bytes (dst->src)",
["OUT_PKTS"] = "Outgoing flow packets (dst->src)",
["IPV6_SRC_ADDR"] = "IPv6 source address",
["IPV6_DST_ADDR"] = "IPv6 destination address",
["IPV6_SRC_MASK"] = "IPv6 source mask",
["IPV6_DST_MASK"] = "IPv6 destination mask",
["ICMP_TYPE"] = "ICMP Type * 256 + ICMP code",
["SAMPLING_INTERVAL"] = "Sampling rate",
["SAMPLING_ALGORITHM"] = "Sampling type (deterministic/random)",
["FLOW_ACTIVE_TIMEOUT"] = "Activity timeout of flow cache entries",
["FLOW_INACTIVE_TIMEOUT"] = "Inactivity timeout of flow cache entries",
["ENGINE_TYPE"] = "Flow switching engine",
["ENGINE_ID"] = "Id of the flow switching engine",
["TOTAL_BYTES_EXP"] = "Total bytes exported",
["TOTAL_PKTS_EXP"] = "Total flow packets exported",
["TOTAL_FLOWS_EXP"] = "Total number of exported flows",
["MIN_TTL"] = "Min flow TTL",
["MAX_TTL"] = "Max flow TTL",
["DST_TOS"] = "TOS/DSCP (dst->src)",
["IN_SRC_MAC"] = "Source MAC Address",
["SRC_VLAN"] = "Source VLAN",
["DST_VLAN"] = "Destination VLAN",
["IP_PROTOCOL_VERSION"] = "4=IPv4]6=IPv6]",
["DIRECTION"] = "It indicates where a sample has been taken (always 0)",
["IPV6_NEXT_HOP"] = "IPv6 next hop address",
["MPLS_LABEL_1"] = "MPLS label at position 1",
["MPLS_LABEL_2"] = "MPLS label at position 2",
["MPLS_LABEL_3"] = "MPLS label at position 3",
["MPLS_LABEL_4"] = "MPLS label at position 4",
["MPLS_LABEL_5"] = "MPLS label at position 5",
["MPLS_LABEL_6"] = "MPLS label at position 6",
["MPLS_LABEL_7"] = "MPLS label at position 7",
["MPLS_LABEL_8"] = "MPLS label at position 8",
["MPLS_LABEL_9"] = "MPLS label at position 9",
["MPLS_LABEL_10"] = "MPLS label at position 10",
["OUT_DST_MAC"] = "Destination MAC Address",
["APPLICATION_ID"] = "Cisco NBAR Application Id",
["PACKET_SECTION_OFFSET"] = "Packet section offset",
["SAMPLED_PACKET_SIZE"] = "Sampled packet size",
["SAMPLED_PACKET_ID"] = "Sampled packet id",
["EXPORTER_IPV4_ADDRESS"] = "Exporter IPv4 Address",
["EXPORTER_IPV6_ADDRESS"] = "Exporter IPv6 Address",
["FLOW_ID"] = "Serial Flow Identifier",
["FLOW_START_SEC"] = "Seconds (epoch) of the first flow packet",
["FLOW_END_SEC"] = "Seconds (epoch) of the last flow packet",
["FLOW_START_MILLISECONDS"] = "Msec (epoch) of the first flow packet",
["FLOW_END_MILLISECONDS"] = "Msec (epoch) of the last flow packet",
["BIFLOW_DIRECTION"] = "1=initiator, 2=reverseInitiator",
["OBSERVATION_POINT_TYPE"] = "Observation point type",
["OBSERVATION_POINT_ID"] = "Observation point id",
["SELECTOR_ID"] = "Selector id",
["IPFIX_SAMPLING_ALGORITHM"] = "Sampling algorithm",
["SAMPLING_SIZE"] = "Number of packets to sample",
["SAMPLING_POPULATION"] = "Sampling population",
["FRAME_LENGTH"] = "Original L2 frame length",
["PACKETS_OBSERVED"] = "Tot number of packets seen",
["PACKETS_SELECTED"] = "Number of pkts selected for sampling",
["SELECTOR_NAME"] = "Sampler name",
["APPLICATION_NAME"] = "Palo Alto App-Id",
["USER_NAME"] = "Palo Alto User-Id",
["FRAGMENTS"] = "Number of fragmented flow packets",
["CLIENT_NW_DELAY_SEC"] = "Network latency client <-> nprobe (sec)",
["CLIENT_NW_DELAY_USEC"] = "Network latency client <-> nprobe (residual usec)",
["CLIENT_NW_DELAY_MS"] = "Network latency client <-> nprobe (msec)",
["SERVER_NW_DELAY_SEC"] = "Network latency nprobe <-> server (sec)",
["SERVER_NW_DELAY_USEC"] = "Network latency nprobe <-> server (residual usec)",
["SERVER_NW_DELAY_MS"] = "Network latency nprobe <-> server (residual msec)",
["APPL_LATENCY_SEC"] = "Application latency (sec)",
["APPL_LATENCY_USEC"] = "Application latency (residual usec)",
["APPL_LATENCY_MS"] = "Application latency (msec)",
["NUM_PKTS_UP_TO_128_BYTES"] = "# packets whose size <= 128",
["NUM_PKTS_128_TO_256_BYTES"] = "# packets whose size > 128 and <= 256",
["NUM_PKTS_256_TO_512_BYTES"] = "# packets whose size > 256 and < 512",
["NUM_PKTS_512_TO_1024_BYTES"] = "# packets whose size > 512 and < 1024",
["NUM_PKTS_1024_TO_1514_BYTES"] = "# packets whose size > 1024 and <= 1514",
["NUM_PKTS_OVER_1514_BYTES"] = "# packets whose size > 1514",
["CUMULATIVE_ICMP_TYPE"] = "Cumulative OR of ICMP type packets",
["SRC_IP_COUNTRY"] = "Country where the src IP is located",
["SRC_IP_CITY"] = "City where the src IP is located",
["DST_IP_COUNTRY"] = "Country where the dst IP is located",
["DST_IP_CITY"] = "City where the dst IP is located",
["FLOW_PROTO_PORT"] = "L7 port that identifies the flow protocol or 0 if unknown",
["UPSTREAM_TUNNEL_ID"] = "Upstream tunnel identifier (e.g. GTP TEID) or 0 if unknown",
["LONGEST_FLOW_PKT"] = "Longest packet (bytes) of the flow",
["SHORTEST_FLOW_PKT"] = "Shortest packet (bytes) of the flow",
["RETRANSMITTED_IN_PKTS"] = "Number of retransmitted TCP flow packets (src->dst)",
["RETRANSMITTED_IN_BYTES"] = "Number of retransmitted TCP flow bytes (src->dst)",
["RETRANSMITTED_OUT_PKTS"] = "Number of retransmitted TCP flow packets (dst->src)",
["RETRANSMITTED_OUT_BYTES"] = "Number of retransmitted TCP flow bytes (dst->src)",
["OOORDER_IN_PKTS"] = "Number of out of order TCP flow packets (dst->src)",
["OOORDER_OUT_PKTS"] = "Number of out of order TCP flow packets (dst->src)",
["UNTUNNELED_PROTOCOL"] = "Untunneled IP protocol byte",
["UNTUNNELED_IPV4_SRC_ADDR"] = "Untunneled IPv4 source address",
["UNTUNNELED_L4_SRC_PORT"] = "Untunneled IPv4 source port",
["UNTUNNELED_IPV4_DST_ADDR"] = "Untunneled IPv4 destination address",
["UNTUNNELED_L4_DST_PORT"] = "Untunneled IPv4 destination port",
["L7_PROTO"] = "Layer 7 protocol (numeric)",
["L7_PROTO_NAME"] = "Layer 7 protocol name",
["DOWNSTREAM_TUNNEL_ID"] = "Downstream tunnel identifier (e.g. GTP TEID) or 0 if unknown",
["FLOW_USER_NAME"] = "Flow Username",
["FLOW_SERVER_NAME"] = "Flow server name",
["PLUGIN_NAME"] = "Plugin name used by this flow (if any)",
["UNTUNNELED_IPV6_SRC_ADDR"] = "Untunneled IPv6 source address",
["UNTUNNELED_IPV6_DST_ADDR"] = "Untunneled IPv6 destination address",
["NUM_PKTS_TTL_EQ_1"] = "# packets with TTL = 1",
["NUM_PKTS_TTL_2_5"] = "# packets with TTL > 1 and TTL <= 5",
["NUM_PKTS_TTL_5_32"] = "# packets with TTL > 5 and TTL <= 32",
["NUM_PKTS_TTL_32_64"] = "# packets with TTL > 32 and <= 64 ",
["NUM_PKTS_TTL_64_96"] = "# packets with TTL > 64 and <= 96",
["NUM_PKTS_TTL_96_128"] = "# packets with TTL > 96 and <= 128",
["NUM_PKTS_TTL_128_160"] = "# packets with TTL > 128 and <= 160",
["NUM_PKTS_TTL_160_192"] = "# packets with TTL > 160 and <= 192",
["NUM_PKTS_TTL_192_224"] = "# packets with TTL > 192 and <= 224",
["NUM_PKTS_TTL_224_255"] = "# packets with TTL > 224 and <= 255",
["IN_SRC_OSI_SAP"] = "OSI Source SAP (OSI Traffic Only)",
["OUT_DST_OSI_SAP"] = "OSI Destination SAP (OSI Traffic Only)",
["DURATION_IN"] = "Client to Server stream duration (msec)",
["DURATION_OUT"] = "Client to Server stream duration (msec)",
["TCP_WIN_MIN_IN"] = "Min TCP Window (src->dst)",
["TCP_WIN_MAX_IN"] = "Max TCP Window (src->dst)",
["TCP_WIN_MSS_IN"] = "TCP Max Segment Size (src->dst)",
["TCP_WIN_SCALE_IN"] = "TCP Window Scale (src->dst)",
["TCP_WIN_MIN_OUT"] = "Min TCP Window (dst->src)",
["TCP_WIN_MAX_OUT"] = "Max TCP Window (dst->src)",
["TCP_WIN_MSS_OUT"] = "TCP Max Segment Size (dst->src)",
["TCP_WIN_SCALE_OUT"] = "TCP Window Scale (dst->src)",
-- MYSQL
["MYSQL_SERVER_VERSION"] = "MySQL server version",
["MYSQL_USERNAME"] = "MySQL username",
["MYSQL_DB"] = "MySQL database in use",
["MYSQL_QUERY"] = "MySQL Query",
["MYSQL_RESPONSE"] = "MySQL server response",
["MYSQL_APPL_LATENCY_USEC"] = "MySQL request->response latecy (usec)",
["SRC_AS_PATH_1"] = "Src AS path position 1",
["SRC_AS_PATH_2"] = "Src AS path position 2",
["SRC_AS_PATH_3"] = "Src AS path position 3",
["SRC_AS_PATH_4"] = "Src AS path position 4",
["SRC_AS_PATH_5"] = "Src AS path position 5",
["SRC_AS_PATH_6"] = "Src AS path position 6",
["SRC_AS_PATH_7"] = "Src AS path position 7",
["SRC_AS_PATH_8"] = "Src AS path position 8",
["SRC_AS_PATH_9"] = "Src AS path position 9",
["SRC_AS_PATH_10"] = "Src AS path position 10",
["DST_AS_PATH_1"] = "Dest AS path position 1",
["DST_AS_PATH_2"] = "Dest AS path position 2",
["DST_AS_PATH_3"] = "Dest AS path position 3",
["DST_AS_PATH_4"] = "Dest AS path position 4",
["DST_AS_PATH_5"] = "Dest AS path position 5",
["DST_AS_PATH_6"] = "Dest AS path position 6",
["DST_AS_PATH_7"] = "Dest AS path position 7",
["DST_AS_PATH_8"] = "Dest AS path position 8",
["DST_AS_PATH_9"] = "Dest AS path position 9",
["DST_AS_PATH_10"] = "Dest AS path position 10",
-- DHCP
["DHCP_CLIENT_MAC"] = "MAC of the DHCP client",
["DHCP_CLIENT_IP"] = "DHCP assigned client IPv4 address",
["DHCP_CLIENT_NAME"] = "DHCP client name",
["DHCP_REMOTE_ID"] = "DHCP agent remote Id",
["DHCP_SUBSCRIBER_ID"] = "DHCP subscribed Id",
["DHCP_MESSAGE_TYPE"] = "DHCP message type",
-- DIAMETER
["DIAMETER_REQ_MSG_TYPE"] = "DIAMETER Request Msg Type",
["DIAMETER_RSP_MSG_TYPE"] = "DIAMETER Response Msg Type",
["DIAMETER_REQ_ORIGIN_HOST"] = "DIAMETER Origin Host Request",
["DIAMETER_RSP_ORIGIN_HOST"] = "DIAMETER Origin Host Response",
["DIAMETER_REQ_USER_NAME"] = "DIAMETER Request User Name",
["DIAMETER_RSP_RESULT_CODE"] = "DIAMETER Response Result Code",
["DIAMETER_EXP_RES_VENDOR_ID"] = "DIAMETER Response Experimental Result Vendor Id",
["DIAMETER_EXP_RES_RESULT_CODE"] = "DIAMETER Response Experimental Result Code",
-- DNS
["DNS_QUERY"] = "DNS query",
["DNS_QUERY_ID"] = "DNS query transaction Id",
["DNS_QUERY_TYPE"] = "DNS query type (e.g. 1=A, 2=NS..)",
["DNS_RET_CODE"] = "DNS return code (e.g. 0=no error)",
["DNS_NUM_ANSWERS"] = "DNS # of returned answers",
["DNS_TTL_ANSWER"] = "TTL of the first A record (if any)",
["DNS_RESPONSE"] = "DNS response(s)",
-- FTP
["FTP_LOGIN"] = "FTP client login",
["FTP_PASSWORD"] = "FTP client password",
["FTP_COMMAND"] = "FTP client command",
["FTP_COMMAND_RET_CODE"] = "FTP client command return code",
-- GTP
["GTPV0_REQ_MSG_TYPE"] = "GTPv0 Request Msg Type",
["GTPV0_RSP_MSG_TYPE"] = "GTPv0 Response Msg Type",
["GTPV0_TID"] = "GTPv0 Tunnel Identifier",
["GTPV0_APN_NAME"] = "GTPv0 APN Name",
["GTPV0_END_USER_IP"] = "GTPv0 End User IP Address",
["GTPV0_END_USER_MSISDN"] = "GTPv0 End User MSISDN",
["GTPV0_RAI_MCC"] = "GTPv0 Mobile Country Code",
["GTPV0_RAI_MNC"] = "GTPv0 Mobile Network Code",
["GTPV0_RAI_CELL_LAC"] = "GTPv0 Cell Location Area Code",
["GTPV0_RAI_CELL_RAC"] = "GTPv0 Cell Routing Area Code",
["GTPV0_RESPONSE_CAUSE"] = "GTPv0 Cause of Operation",
["GTPV1_REQ_MSG_TYPE"] = "GTPv1 Request Msg Type",
["GTPV1_RSP_MSG_TYPE"] = "GTPv1 Response Msg Type",
["GTPV1_C2S_TEID_DATA"] = "GTPv1 Client->Server TunnelId Data",
["GTPV1_C2S_TEID_CTRL"] = "GTPv1 Client->Server TunnelId Control",
["GTPV1_S2C_TEID_DATA"] = "GTPv1 Server->Client TunnelId Data",
["GTPV1_S2C_TEID_CTRL"] = "GTPv1 Server->Client TunnelId Control",
["GTPV1_END_USER_IP"] = "GTPv1 End User IP Address",
["GTPV1_END_USER_IMSI"] = "GTPv1 End User IMSI",
["GTPV1_END_USER_MSISDN"] = "GTPv1 End User MSISDN",
["GTPV1_END_USER_IMEI"] = "GTPv1 End User IMEI",
["GTPV1_APN_NAME"] = "GTPv1 APN Name",
["GTPV1_RAI_MCC"] = "GTPv1 RAI Mobile Country Code",
["GTPV1_RAI_MNC"] = "GTPv1 RAI Mobile Network Code",
["GTPV1_RAI_LAC"] = "GTPv1 RAI Location Area Code",
["GTPV1_RAI_RAC"] = "GTPv1 RAI Routing Area Code",
["GTPV1_ULI_MCC"] = "GTPv1 ULI Mobile Country Code",
["GTPV1_ULI_MNC"] = "GTPv1 ULI Mobile Network Code",
["GTPV1_ULI_CELL_LAC"] = "GTPv1 ULI Cell Location Area Code",
["GTPV1_ULI_CELL_CI"] = "GTPv1 ULI Cell CI",
["GTPV1_ULI_SAC"] = "GTPv1 ULI SAC",
["GTPV1_RESPONSE_CAUSE"] = "GTPv1 Cause of Operation",
["GTPV2_REQ_MSG_TYPE"] = "GTPv2 Request Msg Type",
["GTPV2_RSP_MSG_TYPE"] = "GTPv2 Response Msg Type",
["GTPV2_C2S_S1U_GTPU_TEID"] = "GTPv2 Client->Svr S1U GTPU TEID",
["GTPV2_C2S_S1U_GTPU_IP"] = "GTPv2 Client->Svr S1U GTPU IP",
["GTPV2_S2C_S1U_GTPU_TEID"] = "GTPv2 Srv->Client S1U GTPU TEID",
["GTPV2_S2C_S1U_GTPU_IP"] = "GTPv2 Srv->Client S1U GTPU IP",
["GTPV2_END_USER_IMSI"] = "GTPv2 End User IMSI",
["GTPV2_END_USER_MSISDN"] = "GTPv2 End User MSISDN",
["GTPV2_APN_NAME"] = "GTPv2 APN Name",
["GTPV2_ULI_MCC"] = "GTPv2 Mobile Country Code",
["GTPV2_ULI_MNC"] = "GTPv2 Mobile Network Code",
["GTPV2_ULI_CELL_TAC"] = "GTPv2 Tracking Area Code",
["GTPV2_ULI_CELL_ID"] = "GTPv2 Cell Identifier",
["GTPV2_RESPONSE_CAUSE"] = "GTPv2 Cause of Operation",
-- HTTP
["HTTP_URL"] = "HTTP URL",
["HTTP_METHOD"] = "HTTP METHOD",
["HTTP_RET_CODE"] = "HTTP return code (e.g. 200, 304...)",
["HTTP_REFERER"] = "HTTP Referer",
["HTTP_UA"] = "HTTP User Agent",
["HTTP_MIME"] = "HTTP Mime Type",
["HTTP_HOST"] = "HTTP Host Name",
["HTTP_FBOOK_CHAT"] = "HTTP Facebook Chat",
["HTTP_SITE"] = "HTTP server without host name",
-- Oracle
["ORACLE_USERNAME"] = "Oracle Username",
["ORACLE_QUERY"] = "Oracle Query",
["ORACLE_RSP_CODE"] = "Oracle Response Code",
["ORACLE_RSP_STRING"] = "Oracle Response String",
["ORACLE_QUERY_DURATION"] = "Oracle Query Duration (msec)",
-- Process
['SRC_PROC_PID'] = "Client Process PID",
['SRC_PROC_NAME'] = "Client Process Name",
['SRC_PROC_UID'] = "Client process UID",
['SRC_PROC_USER_NAME'] = "Client process User Name",
['SRC_FATHER_PROC_PID'] = "Client Father Process PID",
['SRC_FATHER_PROC_NAME'] = "Client Father Process Name",
['SRC_PROC_ACTUAL_MEMORY'] = "Client Process Used Memory (KB)",
['SRC_PROC_PEAK_MEMORY'] = "Client Process Peak Memory (KB)",
['SRC_PROC_AVERAGE_CPU_LOAD'] = "Client Process Average Process CPU Load (%)",
['SRC_PROC_NUM_PAGE_FAULTS'] = "Client Process Number of page faults",
['SRC_PROC_PCTG_IOWAIT'] = "Client process iowait time % (% * 100)",
['DST_PROC_PID'] = "Server Process PID",
['DST_PROC_UID'] = "Server process UID",
['DST_PROC_NAME'] = "Server Process Name",
['DST_PROC_USER_NAME'] = "Server process User Name",
['DST_FATHER_PROC_PID'] = "Server Father Process PID",
['DST_FATHER_PROC_NAME'] = "Server Father Process Name",
['DST_PROC_ACTUAL_MEMORY'] = "Server Process Used Memory (KB)",
['DST_PROC_PEAK_MEMORY'] = "Server Process Peak Memory (KB)",
['DST_PROC_AVERAGE_CPU_LOAD'] = "Server Process Average Process CPU Load (%)",
['DST_PROC_NUM_PAGE_FAULTS'] = "Server Process Number of page faults",
['DST_PROC_PCTG_IOWAIT'] = "Server process iowait time % (% * 100)",
-- Radius
["RADIUS_REQ_MSG_TYPE"] = "RADIUS Request Msg Type",
["RADIUS_RSP_MSG_TYPE"] = "RADIUS Response Msg Type",
["RADIUS_USER_NAME"] = "RADIUS User Name (Access Only)",
["RADIUS_CALLING_STATION_ID"] = "RADIUS Calling Station Id",
["RADIUS_CALLED_STATION_ID"] = "RADIUS Called Station Id",
["RADIUS_NAS_IP_ADDR"] = "RADIUS NAS IP Address",
["RADIUS_NAS_IDENTIFIER"] = "RADIUS NAS Identifier",
["RADIUS_USER_IMSI"] = "RADIUS User IMSI (Extension)",
["RADIUS_USER_IMEI"] = "RADIUS User MSISDN (Extension)",
["RADIUS_FRAMED_IP_ADDR"] = "RADIUS Framed IP",
["RADIUS_ACCT_SESSION_ID"] = "RADIUS Accounting Session Name",
["RADIUS_ACCT_STATUS_TYPE"] = "RADIUS Accounting Status Type",
["RADIUS_ACCT_IN_OCTETS"] = "RADIUS Accounting Input Octets",
["RADIUS_ACCT_OUT_OCTETS"] = "RADIUS Accounting Output Octets",
["RADIUS_ACCT_IN_PKTS"] = "RADIUS Accounting Input Packets",
["RADIUS_ACCT_OUT_PKTS"] = "RADIUS Accounting Output Packets",
-- VoIP
['RTP_MOS'] = "Rtp Voice Quality",
['RTP_R_FACTOR'] = "Rtp Voice Quality Metric (%)", --http://tools.ietf.org/html/rfc3611#section-4.7.5
['RTP_RTT'] = "Rtp Round Trip Time",
['RTP_IN_TRANSIT'] = "RTP Transit (value * 100) (src->dst)",
['RTP_OUT_TRANSIT'] = "RTP Transit (value * 100) (dst->src)",
['RTP_FIRST_SSRC'] = "First flow RTP Sync Source ID",
['RTP_FIRST_TS'] = "First flow RTP timestamp",
['RTP_LAST_SSRC'] = "Last flow RTP Sync Source ID",
['RTP_LAST_TS'] = "Last flow RTP timestamp",
['RTP_IN_JITTER'] = "Rtp Incoming Packet Delay Variation",
['RTP_OUT_JITTER'] = "Rtp Out Coming Packet Delay Variation",
['RTP_IN_PKT_LOST'] = "Rtp Incoming Packets Lost",
['RTP_OUT_PKT_LOST'] = "Rtp Out Coming Packets Lost",
['RTP_OUT_PAYLOAD_TYPE'] = "Rtp Out Coming Payload Type",
['RTP_IN_MAX_DELTA'] = "Max delta (ms*100) between consecutive pkts (src->dst)",
['RTP_OUT_MAX_DELTA'] = "Max delta (ms*100) between consecutive pkts (dst->src)",
['RTP_IN_PAYLOAD_TYPE'] = "Rtp Incoming Payload Type",
['RTP_SIP_CALL_ID'] = "SIP call-id corresponding to this RTP stream",
['SIP_CALL_ID'] = "SIP call-id",
['SIP_CALLING_PARTY'] = "SIP Call initiator",
['SIP_CALLED_PARTY'] = "SIP Called party",
['SIP_RTP_CODECS'] = "SIP RTP codecs",
['SIP_INVITE_TIME'] = "SIP time (epoch) of INVITE",
['SIP_TRYING_TIME'] = "SIP time (epoch) of Trying",
['SIP_RINGING_TIME'] = "SIP time (epoch) of RINGING",
['SIP_INVITE_OK_TIME'] = "SIP time (epoch) of INVITE OK",
['SIP_INVITE_FAILURE_TIME'] = "SIP time (epoch) of INVITE FAILURE",
['SIP_BYE_TIME'] = "SIP time (epoch) of BYE",
['SIP_BYE_OK_TIME'] = "SIP time (epoch) of BYE OK",
['SIP_CANCEL_TIME'] = "SIP time (epoch) of CANCEL",
['SIP_CANCEL_OK_TIME'] = "SIP time (epoch) of CANCEL OK",
['SIP_RTP_IPV4_SRC_ADDR'] = "SIP RTP stream source IP",
['SIP_RTP_L4_SRC_PORT'] = "SIP RTP stream source port",
['SIP_RTP_IPV4_DST_ADDR'] = "SIP RTP stream dest IP",
['SIP_RTP_L4_DST_PORT'] = "SIP RTP stream dest port",
['SIP_FAILURE_CODE'] = "SIP failure response code",
['SIP_RESPONSE_CODE'] = "SIP failure response code",
['SIP_REASON_CAUSE'] = "SIP Cancel/Bye/Failure reason cause",
['SIP_C_IP'] = "SIP C IP adresses",
['SIP_CALL_STATE'] = "Sip Call State",
-- S1AP
["S1AP_ENB_UE_S1AP_ID"] = "S1AP ENB Identifier",
["S1AP_MME_UE_S1AP_ID"] = "S1AP MME Identifier",
["S1AP_MSG_EMM_TYPE_MME_TO_ENB"] = "S1AP EMM Message Type from MME to ENB",
["S1AP_MSG_ESM_TYPE_MME_TO_ENB"] = "S1AP ESM Message Type from MME to ENB",
["S1AP_MSG_EMM_TYPE_ENB_TO_MME"] = "S1AP EMM Message Type from ENB to MME",
["S1AP_MSG_ESM_TYPE_ENB_TO_MME"] = "S1AP ESM Message Type from ENB to MME",
["S1AP_CAUSE_ENB_TO_MME"] = "S1AP Cause from ENB to MME",
["S1AP_DETAILED_CAUSE_ENB_TO_MME"] = "S1AP Detailed Cause from ENB to MME",
-- Mail
["SMTP_MAIL_FROM"] = "Mail sender",
["SMTP_RCPT_TO"] = "Mail recipient",
["POP_USER"] = "POP3 user login",
["IMAP_LOGIN"] = "Mail sender",
-- WHOIS
["WHOIS_DAS_DOMAIN"] = "Whois/DAS Domain name",
}
-- #######################
function getFlowKey(name)
v = rtemplate[tonumber(name)]
if(v == nil) then return(name) end
s = flow_fields_description[v]
if(s ~= nil) then
s = string.gsub(s, "<", "<")
s = string.gsub(s, ">", ">")
return(s)
else
return(name)
end
end
-- #######################
| gpl-3.0 |
aspiraboo/kappa | vc14/data/lib/core/player.lua | 14 | 2590 | local foodCondition = Condition(CONDITION_REGENERATION, CONDITIONID_DEFAULT)
function Player.feed(self, food)
local condition = self:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT)
if condition then
condition:setTicks(condition:getTicks() + (food * 1000))
else
local vocation = self:getVocation()
if not vocation then
return nil
end
foodCondition:setTicks(food * 1000)
foodCondition:setParameter(CONDITION_PARAM_HEALTHGAIN, vocation:getHealthGainAmount())
foodCondition:setParameter(CONDITION_PARAM_HEALTHTICKS, vocation:getHealthGainTicks() * 1000)
foodCondition:setParameter(CONDITION_PARAM_MANAGAIN, vocation:getManaGainAmount())
foodCondition:setParameter(CONDITION_PARAM_MANATICKS, vocation:getManaGainTicks() * 1000)
self:addCondition(foodCondition)
end
return true
end
function Player.getClosestFreePosition(self, position, extended)
if self:getAccountType() >= ACCOUNT_TYPE_GOD then
return position
end
return Creature.getClosestFreePosition(self, position, extended)
end
function Player.getDepotItems(self, depotId)
return self:getDepotChest(depotId, true):getItemHoldingCount()
end
function Player.getLossPercent(self)
local blessings = 0
local lossPercent = {
[0] = 100,
[1] = 70,
[2] = 45,
[3] = 25,
[4] = 10,
[5] = 0
}
for i = 1, 5 do
if self:hasBlessing(i) then
blessings = blessings + 1
end
end
return lossPercent[blessings]
end
function Player.isPremium(self)
return self:getPremiumDays() > 0 or configManager.getBoolean(configKeys.FREE_PREMIUM)
end
function Player.sendCancelMessage(self, message)
if type(message) == "number" then
message = Game.getReturnMessage(message)
end
return self:sendTextMessage(MESSAGE_STATUS_SMALL, message)
end
function Player.isUsingOtClient(self)
return self:getClient().os >= CLIENTOS_OTCLIENT_LINUX
end
function Player.sendExtendedOpcode(self, opcode, buffer)
if not self:isUsingOtClient() then
return false
end
local networkMessage = NetworkMessage()
networkMessage:addByte(0x32)
networkMessage:addByte(opcode)
networkMessage:addString(buffer)
networkMessage:sendToPlayer(self)
networkMessage:delete()
return true
end
APPLY_SKILL_MULTIPLIER = true
local addSkillTriesFunc = Player.addSkillTries
function Player.addSkillTries(...)
APPLY_SKILL_MULTIPLIER = false
local ret = addSkillTriesFunc(...)
APPLY_SKILL_MULTIPLIER = true
return ret
end
local addManaSpentFunc = Player.addManaSpent
function Player.addManaSpent(...)
APPLY_SKILL_MULTIPLIER = false
local ret = addManaSpentFunc(...)
APPLY_SKILL_MULTIPLIER = true
return ret
end
| gpl-2.0 |
adonaac/yaoui | yaoui/FlatTextinput.lua | 4 | 1446 | local yui_path = (...):match('(.-)[^%.]+$')
local Object = require(yui_path .. 'UI.classic.classic')
local FlatTextinput = Object:extend('FlatTextinput')
function FlatTextinput:new(yui, settings)
self.yui = yui
self.x, self.y = 0, 0
self.name = settings.name
self.size = settings.size or 20
self.font = love.graphics.newFont(self.yui.Theme.open_sans_regular, math.floor(self.size*0.7))
self.w = settings.w or 100 + 2*self.size
self.h = self.font:getHeight() + math.floor(self.size*0.7)
self.textarea = self.yui.UI.Textarea(0, 0, self.w, self.h, {
yui = self.yui,
font = self.font,
parent = self,
extensions = {self.yui.Theme.FlatTextinput},
single_line = true,
})
self.h = self.textarea.h
self.onEnter = settings.onEnter
end
function FlatTextinput:update(dt)
if self.textarea.input:pressed('enter') then
if self.onEnter then
self:onEnter(self.textarea:getText())
end
end
self.textarea.x, self.textarea.y = self.x, self.y
self.textarea.text_base_x, self.textarea.text_base_y = self.x + self.textarea.text_margin, self.y + self.textarea.text_margin
self.textarea:update(dt)
if self.textarea.hot then love.mouse.setCursor(self.yui.Theme.ibeam) end
end
function FlatTextinput:draw()
self.textarea:draw()
end
function FlatTextinput:setText(text)
self.textarea:setText(text)
end
return FlatTextinput
| mit |
resistor58/deaths-gmod-server | NPC_Control2/lua/weapons/gmod_tool/stools/npc_relations.lua | 1 | 4221 | include("shared.lua")
selected_npcs_relations = {}
TOOL.Category = "NPC Control 2"
TOOL.Name = "NPC Relations"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.ClientConVar["newdisp"] = "1"
//TOOL.ClientConVar["doface"] = "1"
TOOL.ClientConVar["priority"] = "10"
TOOL.ClientConVar["viceversa"] = "1"
if (CLIENT) then
language.Add("Tool_npc_relations_name", "NPC Relations")
language.Add("Tool_npc_relations_desc", "Make NPCs love or hate things!")
language.Add("Tool_npc_relations_0", "Left-Click to select an NPC, Right-Click to make them change their disposition")
end
function TOOL:LeftClick( trace )
if SERVER then
local dohalt = false
if (selected_npcs_relations[self:GetOwner()] == nil) then selected_npcs_relations[self:GetOwner()] = {} end
if (GetConVarNumber("npc_allow_relations") != 1 && !SinglePlayer()) then
npcc_doNotify("NPC Disposition control is disabled on this server", "NOTIFY_ERROR", self:GetOwner())
dohalt = true
end
if (!AdminCheck( self:GetOwner(), "Relations control" )) then
dohalt = true
end
if (!trace.Entity:IsValid() || !trace.Entity:IsNPC()) then dohalt = true end
if (!NPCProtectCheck( self:GetOwner(), trace.Entity )) then dohalt = true end
if (!dohalt) then
if (selected_npcs_relations[self:GetOwner()][trace.Entity] == nil) then
selected_npcs_relations[self:GetOwner()][trace.Entity] = trace.Entity
npcc_doNotify("NPC Selected", "NOTIFY_GENERIC", self:GetOwner())
else
selected_npcs_relations[self:GetOwner()][trace.Entity] = nil
npcc_doNotify("NPC Disbanded", "NOTIFY_GENERIC", self:GetOwner())
end
end
end
return true
end
function TOOL:RightClick( trace )
if SERVER then
local dohalt = false
if (selected_npcs_relations[self:GetOwner()] == nil) then selected_npcs_relations[self:GetOwner()] = {} end
if (GetConVarNumber("npc_allow_relations") != 1) then
npcc_doNotify("NPC Disposition control is disabled on this server", "NOTIFY_ERROR", self:GetOwner())
dohalt = true
end
if (!AdminCheck( self:GetOwner(), "Relations control" )) then
dohalt = true
end
if (!trace.Entity:IsValid()) then dohalt = true end
if (trace.Entity:IsPlayer() && GetConVarNumber("npc_allow_attacking_players") != 1) then
npcc_doNotify("You can't target players", "NOTIFY_ERROR", self:GetOwner())
dohalt = true
end
local viceversa = self:GetClientNumber("viceversa")
if (!dohalt) then
for k, v in pairs(selected_npcs_relations[self:GetOwner()]) do
if (v:IsValid() && v:IsNPC()) then
v:AddEntityRelationship( trace.Entity, self:GetClientNumber("newdisp"), self:GetClientNumber("priority") )
if (viceversa == 1 && trace.Entity:IsNPC()) then trace.Entity:AddEntityRelationship( v, self:GetClientNumber("newdisp"), self:GetClientNumber("priority") ) end
end
end
end
end
return true
end
function TOOL:Reload( trace )
if SERVER then
for k, v in pairs(selected_npcs_relations[self:GetOwner()]) do
v = nil
end
npcc_doNotify("All NPCs disbanded", "NOTIFY_ERROR", self:GetOwner())
end
end
function TOOL.BuildCPanel( panel )
panel:AddControl("Label", {Text = "New Disposition:"})
local data = {}
//data.Label = "New Disposition:"
data.MenuButton = 0
data.Options = {}
data.Options["Hate"] = {npc_relations_newdisp = "1"}
data.Options["Like"] = {npc_relations_newdisp = "3"}
data.Options["Fear"] = {npc_relations_newdisp = "2"}
data.Options["Neutral"] = {npc_relations_newdisp = "4"}
panel:AddControl("ComboBox", data)
//panel:AddControl("CheckBox", {Label = "Make NPC(s) face new enemy", Command = "npc_relations_doface"})
panel:AddControl("CheckBox", {Label = "Affect target aswell", Comand = "npc_relations_viceversa"})
panel:AddControl("Slider", {Label = "Priority:", min = 1, max = 200, Command = "npc_relations_priority"})
panel:AddControl("Label", {Text = "Combine Mines' dispositions will never change."})
end
| gpl-3.0 |
dunn/ntopng | scripts/lua/hosts_comparison.lua | 11 | 5679 | --
-- (C) 2014-15-15 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
require "graph_utils"
page = _GET["page"]
hosts_ip = _GET["hosts"]
-- Default values
if(page == nil) then
page = "overview"
end
active_traffic = true
active_packets = false
active_ndpi = false
show_aggregation = true
active_page = "hosts"
sendHTTPHeader('text/html; charset=iso-8859-1')
ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc")
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
if(hosts_ip == nil) then
print("<div class=\"alert alert-danger\"><img src=".. ntop.getHttpPrefix() .. "/img/warning.png> Hosts parameter is missing (internal error ?)</div>")
return
end
print [[
<nav class="navbar navbar-default" role="navigation">
<div class="navbar-collapse collapse">
<ul class="nav navbar-nav">
]]
url=ntop.getHttpPrefix().."/lua/hosts_comparison.lua?hosts="..hosts_ip
hosts_ip_tab_name = string.gsub(hosts_ip, ',', " <i class=\"fa fa-exchange fa-lg\"></i> ")
print("<li><a href=\"#\">Hosts: "..hosts_ip_tab_name.." </a></li>\n")
if((page == "overview") or (page == nil)) then
print("<li class=\"active\"><a href=\"#\"><i class=\"fa fa-home fa-lg\"></i></a></li>\n")
else
print("<li><a href=\""..url.."&page=overview\"><i class=\"fa fa-home fa-lg\"></i></a></li>")
end
if(page == "traffic") then
print("<li class=\"active\"><a href=\"#\">Traffic</a></li>\n")
else
if(active_traffic) then
print("<li><a href=\""..url.."&page=traffic\">Traffic</a></li>")
end
end
if(page == "packets") then
print("<li class=\"active\"><a href=\"#\">Packets</a></li>\n")
else
if(active_packets) then
print("<li><a href=\""..url.."&page=packets\">Packets</a></li>")
end
end
if(page == "ndpi") then
print("<li class=\"active\"><a href=\"#\">Protocols</a></li>\n")
else
if(active_ndpi) then
print("<li><a href=\""..url.."&page=ndpi\">Protocols</a></li>")
end
end
print [[
<li><a href="javascript:history.go(-1)"><i class='fa fa-reply'></i></a></li>
</ul>
</div>
</nav>
]]
-- =========================== Tab Menu =================
if (page == "overview") then
if(show_aggregation) then
print [[
<div class="btn-group">
<button class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">Aggregation <span class="caret"></span></button>
<ul class="dropdown-menu">
]]
print('<li><a href="'..url .. '&aggregation=ndpi">'.. "Application" ..'</a></li>\n')
print('<li><a href="'..url .. '&aggregation=l4proto">'.. "Proto L4" ..'</a></li>\n')
print('<li><a href="'..url .. '&aggregation=port">'.. "Port" ..'</a></li>\n')
print [[
</ul>
</div><!-- /btn-group -->
]]
print(' Refresh: <div class="btn-group">\n')
print[[
<button id="graph_refresh" class="btn btn-default btn-sm">
<i rel="tooltip" data-toggle="tooltip" data-placement="top" data-original-title="Refresh graph" class="glyphicon glyphicon-refresh"></i></button>
]]
print [[
</div>
</div>
<br/>
]]
print[[
<script>
$("#graph_refresh").click(function() {
sankey();
});
$(window).load(function()
{
// disabled graph interval
clearInterval(sankey_interval);
});
</script>
]]
end -- End if(show_aggregation)
-- =========================== Aggregation Menu =================
print("<center>")
print('<div class="row">')
print(" <div>")
dofile(dirs.installdir .. "/scripts/lua/inc/sankey.lua")
print(" </div>")
print("</div>")
print("</center><br/>")
elseif(page == "traffic") then
if(show_aggregation) then
print [[
<div class="btn-group">
<button id="aggregation_bubble_displayed" class="btn btn-default btn-sm dropdown-toggle" data-toggle="dropdown">Aggregation <span class="caret"></span></button>
<ul class="dropdown-menu" id="aggregation_bubble">
<li><a>Application</a></li>
<li><a>L4 Protocol</a></li>
<li><a>Port</a></li>
</ul>
</div><!-- /btn-group -->
]]
print(' Refresh: <div class="btn-group">\n')
print[[
<button id="graph_refresh" class="btn btn-default btn-sm">
<i rel="tooltip" data-toggle="tooltip" data-placement="top" data-original-title="Refresh graph" class="glyphicon glyphicon-refresh"></i></button>
]]
print [[
</div>
</div>
<br/>
]]
end -- End if(show_aggregation)
-- =========================== Aggregation Menu =================
print("<center>")
print("<div class=\"row-fluid\">")
print('<div id="bubble_chart"></div>')
print("</div>")
print("</center>")
print [[
<link href="/css/bubble-chart.css" rel="stylesheet">
<script src="/js/bubble-chart.js"></script>
<script>
var bubble = do_bubble_chart("bubble_chart", ']]
print (ntop.getHttpPrefix())
print [[/lua/hosts_comparison_bubble.lua', { hosts:]]
print("\""..hosts_ip.."\" }, 10); \n")
print [[
bubble.stopInterval();
</script>
]]
print [[
<script>
$("#graph_refresh").click(function() {
bubble.forceUpdate();
});
$('#aggregation_bubble li > a').click(function(e){
$('#aggregation_bubble_displayed').html(this.innerHTML+' <span class="caret"></span>');
if (this.innerHTML == "Application") {
bubble_aggregation= "ndpi"
} else if (this.innerHTML == "L4 Protocol") {
bubble_aggregation = "l4proto";
} else {
bubble_aggregation = "port";
}
//alert(this.innerHTML + "-" + bubble_aggregation);
bubble.setUrlParams({ aggregation: bubble_aggregation, hosts:]]
print("\""..hosts_ip.."\" }") print [[ );
bubble.forceUpdate();
});
</script>
]]
elseif(page == "packets") then
elseif(page == "ndpi") then
end -- End if page == ...
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
mahdib9/mahdi | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
aqasaeed/botz | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
theonlywild/erfan | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
chewi/Aquaria | game_scripts/_mods/jukebox/scripts/node_jukebox-quit.lua | 6 | 1847 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
dofile(appendUserDataPath("_mods/jukebox/scripts/jukeboxinclude.lua"))
--[[
Button layout on screen:
RAND
PREV NEXT
*EXIT*
--]]
local navmap = {
[ACTION_MENUUP] = "jukebox-random",
[ACTION_MENULEFT] = "jukebox-previous",
[ACTION_MENURIGHT] = "jukebox-next"
}
function init(me)
node_setCursorActivation(me, true)
node_setCatchActions(me, true)
end
function action(me, action, state)
if isNestedMain() then return end
return jukebox_doButtonAction(me, action, state, navmap)
end
function activate(me)
if isNestedMain() then return end
playSfx("TitleAction")
spawnParticleEffect("TitleEffect1", node_x(me), node_y(me))
watch(0.5)
local doQuit = false
if confirm("", "exit") then
doQuit = true
end
setNodeToActivate(0)
if doQuit then
fadeOutMusic(2)
toggleCursor(false)
fade(1, 2, 0, 0, 0)
watch(2)
watch(0.5)
goToTitle()
end
end
function update(me, dt)
end
| gpl-2.0 |
Fir3element/tfs11 | data/globalevents/scripts/startup.lua | 21 | 2222 | function onStartup()
db.query("TRUNCATE TABLE `players_online`")
db.asyncQuery("DELETE FROM `guild_wars` WHERE `status` = 0")
db.asyncQuery("DELETE FROM `players` WHERE `deletion` != 0 AND `deletion` < " .. os.time())
db.asyncQuery("DELETE FROM `ip_bans` WHERE `expires_at` != 0 AND `expires_at` <= " .. os.time())
db.asyncQuery("DELETE FROM `market_history` WHERE `inserted` <= " .. (os.time() - configManager.getNumber(configKeys.MARKET_OFFER_DURATION)))
-- Move expired bans to ban history
local resultId = db.storeQuery("SELECT * FROM `account_bans` WHERE `expires_at` != 0 AND `expires_at` <= " .. os.time())
if resultId ~= false then
repeat
local accountId = result.getDataInt(resultId, "account_id")
db.asyncQuery("INSERT INTO `account_ban_history` (`account_id`, `reason`, `banned_at`, `expired_at`, `banned_by`) VALUES (" .. accountId .. ", " .. db.escapeString(result.getDataString(resultId, "reason")) .. ", " .. result.getDataLong(resultId, "banned_at") .. ", " .. result.getDataLong(resultId, "expires_at") .. ", " .. result.getDataInt(resultId, "banned_by") .. ")")
db.asyncQuery("DELETE FROM `account_bans` WHERE `account_id` = " .. accountId)
until not result.next(resultId)
result.free(resultId)
end
-- Check house auctions
local resultId = db.storeQuery("SELECT `id`, `highest_bidder`, `last_bid`, (SELECT `balance` FROM `players` WHERE `players`.`id` = `highest_bidder`) AS `balance` FROM `houses` WHERE `owner` = 0 AND `bid_end` != 0 AND `bid_end` < " .. os.time())
if resultId ~= false then
repeat
local house = House(result.getDataInt(resultId, "id"))
if house ~= nil then
local highestBidder = result.getDataInt(resultId, "highest_bidder")
local balance = result.getDataLong(resultId, "balance")
local lastBid = result.getDataInt(resultId, "last_bid")
if balance >= lastBid then
db.query("UPDATE `players` SET `balance` = " .. (balance - lastBid) .. " WHERE `id` = " .. highestBidder)
house:setOwnerGuid(highestBidder)
end
db.asyncQuery("UPDATE `houses` SET `last_bid` = 0, `bid_end` = 0, `highest_bidder` = 0, `bid` = 0 WHERE `id` = " .. house:getId())
end
until not result.next(resultId)
result.free(resultId)
end
end
| gpl-2.0 |
MaddyRogier/ShuffleCards | main.lua | 1 | 3539 | --[[----------------------------------
Shuffle Deck of Cards
Designed on iPhone 6
Maddy Rogier
----------------------------------]]--
--[[----------------------------------
function - card design
----------------------------------]]--
red = {.541,0,.051}
black = {.055,.055,.055}
suitFiles = { "club.png", "diamond.png", "heart.png", "spade.png" }
suitColors = { black, red, red, black }
local function getCardSuit( card ) --card 2 character string, 1st character is suit then turned number,
local suit = string.sub(card, 1, 1) --calls first character of card, lua build in sub calls string
if suit == "C" then --starts to compare character suit
return 1
elseif suit == "D" then
return 2
elseif suit == "H" then
return 3
elseif suit == "S" then
return 4
end --/if
end --/function
local function getCardRank( card )
local rank = string.sub(card, 2) --starting at second character and ending at 2nd character string
return rank
end --/function
--[[----------------------------------
function - render
----------------------------------]]--
local function render( card )
local rankString = getCardRank( card )
local suitNumber = getCardSuit( card )
local suitColor = suitColors[ suitNumber ]
local suitFile = suitFiles[ suitNumber ]
local group = display.newGroup()
local back = display.newRoundedRect(0,0,455,700,20)
back:setFillColor(1,1,1)
back:setStrokeColor(.055,.055,.055)
back.strokeWidth = 2
local suit = display.newImage(suitFile,-150,-180)
suit:scale(.1, .1)
local rankText = display.newText(rankString,-150,-280,"verdana",72)
rankText:setFillColor(unpack(suitColor))
group:insert(back)
group:insert(suit)
group:insert(rankText)
return group
end --/function
--[[----------------------------------
function - creates/rotates cards
----------------------------------]]--
local function drawCard( index, card ) --index counter
local image = render( card )
image.x = 400+100*index
image.y = 450
image.rotation = -50+11*index
end --/function
--[[----------------------------------
array - 52 cards
----------------------------------]]--
local deckOfCards = {
"CA", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "C10", "CJ", "CQ", "CK",
"DA", "D2", "D3", "D4", "D5", "D6", "D7", "D8", "D9", "D10", "DJ", "DQ", "DK",
"HA", "H2", "H3", "H4", "H5", "H6", "H7", "H8", "H9", "H10", "HJ", "HQ", "HK",
"SA", "S2", "S3", "S4", "S5", "S6", "S7", "S8", "S9", "S10", "SJ", "SQ", "SK", }
--[[----------------------------------
function - shuffles cards randomly
----------------------------------]]--
math.randomseed( os.time() )
local function shuffleTable( t )
local randomNum = math.random
assert( t, "shuffleTable() error" )
local iterations = #t
local j
for i = iterations, 2, -1 do
j = randomNum(i)
t[i], t[j] = t[j], t[i]
end --/for
end --/function
shuffleTable( deckOfCards )
--[[----------------------------------
function - draws cards
----------------------------------]]--
local function drawCards( count, deck )
for i = 1, count do
drawCard( i, deck[ i ] )
end
end
--[[----------------------------------
function - deals out 5 cards
----------------------------------]]--
drawCards( 5, deckOfCards )
| mit |
snogglethorpe/snogray | lua-util/string.lua | 1 | 3071 | -- string.lua -- Miscellaneous string functions
--
-- Copyright (C) 2012, 2013 Miles Bader <miles@gnu.org>
--
-- This source code is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License as
-- published by the Free Software Foundation; either version 3, or (at
-- your option) any later version. See the file COPYING for more details.
--
-- Written by Miles Bader <miles@gnu.org>
--
local std_string = string -- standard Lua string module
-- module
--
local string = {}
-- Inherit from the standard Lua string module, so clients can just
-- call this module 'string'
--
setmetatable (string, {__index = std_string})
-- Return a string version of NUM, with commas added every 3rd place
-- Any fractional part is discarded.
--
function string.commify (num)
num = tostring (math.floor (num))
return string.gsub (string.reverse (string.gsub (string.reverse (num),
"...", "%0,")),
"^,", "")
end
-- Return a string version of NUM, with commas added every 3rd place,
-- and either the phrase UNIT_NAME or UNITS_NAME appended, depending
-- on whether NUM has the value 1 or not.
--
-- If UNITS_NAME is omitted, UNIT_NAME is used for both, and if
-- UNITS_NAME is true, then UNIT_NAME with an "s" appended is used for
-- values other than 1.
--
function string.commify_with_units (num, unit_name, units_name)
units_name = units_name or unit_name
if units_name == true then
units_name = unit_name.."s"
end
if num == 1 then
return "1"..unit_name
else
return string.commify (num)..units_name
end
end
-- Return a string version of NUM with its fractional part rounded to
-- PLACES decimal places (default 1), and commas added every 3rd place
-- in its integer part.
--
function string.round_and_commify (num, places)
local frac_scale = 10^(places or 1)
local scnum = math.floor (num * frac_scale + 0.5)
local ip = math.floor (scnum / frac_scale)
local fp = scnum - ip * frac_scale
ip = string.commify (ip)
if fp ~= 0 then
ip = ip.."."..tostring(fp)
end
return ip
end
-- Concatenate a series of strings and separators, omitting the
-- proceeding separator for any string which is nil.
--
function string.sep_concat (str, ...)
local i = 1
while i < select ('#', ...) do
local new = select (i + 1, ...)
if not str then
str = new
elseif new then
str = str..select (i, ...)..new
end
i = i + 2
end
return str
end
-- Return a string version of VAL padded on the left with spaces to
-- be at least LEN chars.
--
function string.left_pad (val, len)
val = tostring (val)
if #val < len then
return string.rep (" ", len - #val)..val
else
return val
end
end
-- Return a string version of VAL padded on the right with spaces to
-- be at least LEN chars.
--
function string.right_pad (val, len)
val = tostring (val)
if #val < len then
return val..string.rep (" ", len - #val)
else
return val
end
end
-- return the module
--
return string
| gpl-3.0 |
Nottinghster/OTServ_SVN-0.6.4 | src/data/actions/scripts/doors/gateofexp_closed.lua | 4 | 1446 | -- ActionIDs:
-- 1001~1999: Level doors(level is actionID-1000)
-- 2001~2008: Vocation doors(voc is ActionID-2000. 1:Sorcerer, 2:Druid, 3:Paladin, 4:Knight, 5:MS, 6:ED, 7:RP, 8:EK)
function onUse(cid, item, frompos, item2, topos)
local isLevelDoor = (item.actionid >= 1001 and item.actionid <= 1999)
local isVocationDoor = (item.actionid >= 2001 and item.actionid <= 2008)
if not(isLevelDoor or isVocationDoor) then
-- Make it a normal door
doTransformItem(item.uid, item.itemid+1)
return true
end
local canEnter = true
if(isLevelDoor and getPlayerLevel(cid) < (item.actionid-1000)) then
canEnter = false
end
if(isVocationDoor) then
local doorVoc = item.actionid-2000
if (doorVoc == 1 and not(isSorcerer(cid))) or
(doorVoc == 2 and not(isDruid(cid))) or
(doorVoc == 3 and not(isPaladin(cid))) or
(doorVoc == 4 and not(isKnight(cid))) or
(doorVoc ~= getPlayerVocation(cid)) then
canEnter = false
end
end
if(not canEnter and getPlayerAccess(cid) == 0) then
doPlayerSendTextMessage(cid, MESSAGE_INFO_DESCR, "Only the worthy may pass.")
return true
end
doTransformItem(item.uid, item.itemid+1)
local canGo = (queryTileAddThing(cid, frompos, bit.bor(2, 4)) == RETURNVALUE_NOERROR) --Veryfies if the player can go, ignoring blocking things
if not(canGo) then
return false
end
local dir = getDirectionTo(getPlayerPosition(cid), frompos)
doMoveCreature(cid, dir)
return true
end | gpl-2.0 |
resistor58/deaths-gmod-server | wire/lua/effects/thruster_ring_shrink/init.lua | 1 | 1781 |
EFFECT.Mat = Material( "effects/select_ring" )
/*---------------------------------------------------------
Initializes the effect. The data is a table of data
which was passed from the server.
---------------------------------------------------------*/
function EFFECT:Init( data )
local size = 16
self.Entity:SetCollisionBounds( Vector( -size,-size,-size ), Vector( size,size,size ) )
local Pos = data:GetOrigin() + data:GetNormal() * 2
self.Entity:SetPos( Pos )
self.Entity:SetAngles( data:GetNormal():Angle() + Angle( 0.01, 0.01, 0.01 ) )
self.Pos = data:GetOrigin()
self.Normal = data:GetNormal()
self.Speed = 2
self.Size = 16
self.Alpha = 255
end
/*---------------------------------------------------------
THINK
---------------------------------------------------------*/
function EFFECT:Think( )
local speed = FrameTime() * self.Speed
//if (self.Speed > 100) then self.Speed = self.Speed - 1000 * speed end
//self.Size = self.Size + speed * self.Speed
self.Size = self.Size - (255 - self.Alpha)*0.02
self.Alpha = self.Alpha - 250.0 * speed
self.Entity:SetPos( self.Entity:GetPos() + self.Normal * speed * 128 )
if (self.Alpha < 0 ) then return false end
if (self.Size < 0) then return false end
return true
end
/*---------------------------------------------------------
Draw the effect
---------------------------------------------------------*/
function EFFECT:Render( )
if (self.Alpha < 1 ) then return end
render.SetMaterial( self.Mat )
render.DrawQuadEasy( self.Entity:GetPos(),
self.Entity:GetAngles():Forward(),
self.Size, self.Size,
Color( math.Rand( 10, 100), math.Rand( 100, 220), math.Rand( 240, 255), self.Alpha )
)
end
| gpl-3.0 |
sharifteam/sharifbot3 | libs/XMLElement.lua | 569 | 4025 | -- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence.
-- updated for module-free world of lua 5.3 on April 2 2015
-- Not documented at all, but not interesting enough to warrant documentation anyway.
local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error
local table, string = table, string
local XMLElement={}
local mt
XMLElement.new = function(lom)
return setmetatable({lom=lom or {}}, mt)
end
local function filter(filtery_thing, lom)
filtery_thing=filtery_thing or '*'
for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do
if thing == "text()" then
if type(lom)=='string' then return true end
elseif thing == '*' then
if type(lom)=='table' then return true end
else
if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end
end
end
return nil
end
mt ={ __index = {
getAttr = function(self, attribute)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
return self.lom.attr[attribute]
end,
setAttr = function(self, attribute, value)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if value == nil then return self:removeAttr(attribute) end
self.lom.attr[attribute]=tostring(value)
return self
end,
removeAttr = function(self, attribute)
local lom = self.lom
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if not lom.attr[attribute] then return self end
for i,v in ipairs(lom.attr) do
if v == attribute then
table.remove(lom.attr, i)
break
end
end
lom.attr[attribute]=nil
end,
removeAllAttributes = function(self)
local attr = self.lom.attr
for i, v in pairs(self.lom.attr) do
attr[i]=nil
end
return self
end,
getAttributes = function(self)
local attr = {}
for i, v in ipairs(self.lom.attr) do
table.insert(attr,v)
end
return attr
end,
getXML = function(self)
local function getXML(lom)
local attr, inner = {}, {}
for i, attribute in ipairs(lom.attr) do
table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute]))
end
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getXML(v))
else
error("oh shit")
end
end
local tagcontents = table.concat(inner)
local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or ""
if #tagcontents>0 then
return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag)
else
return string.format("<%s%s />", lom.tag, attrstring)
end
end
return getXML(self.lom)
end,
getText = function(self)
local function getText(lom)
local inner = {}
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getText(v))
end
end
return table.concat(inner)
end
return getText(self.lom)
end,
getChildren = function(self, filter_thing)
local res = {}
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
table.insert(res, type(node)=='table' and XMLElement.new(node) or node)
end
end
return res
end,
getDescendants = function(self, filter_thing)
local res = {}
local function descendants(lom)
for i, child in ipairs(lom) do
if filter(filter_thing, child) then
table.insert(res, type(child)=='table' and XMLElement.new(child) or child)
if type(child)=='table' then descendants(child) end
end
end
end
descendants(self.lom)
return res
end,
getChild = function(self, filter_thing)
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
return type(node)=='table' and XMLElement.new(node) or node
end
end
end,
getTag = function(self)
return self.lom.tag
end
}}
return XMLElement | gpl-3.0 |
luakit-crowd/luakit | lib/session.lua | 6 | 2645 | ------------------------------------------------------
-- Session saving / loading functions --
-- © 2010 Mason Larobina <mason.larobina@gmail.com> --
------------------------------------------------------
local function rm(file)
luakit.spawn(string.format("rm %q", file))
end
-- Session functions
session = {
-- The file which we'll use for session info, $XDG_DATA_HOME/luakit/session
file = luakit.data_dir .. "/session",
-- Save all given windows uris to file.
save = function (wins)
local lines = {}
-- Save tabs from all the given windows
for wi, w in pairs(wins) do
local current = w.tabs:current()
for ti, tab in ipairs(w.tabs.children) do
table.insert(lines, string.format("%d\t%d\t%s\t%s", wi, ti,
tostring(current == ti), tab.uri))
end
end
if #lines > 0 then
local fh = io.open(session.file, "w")
fh:write(table.concat(lines, "\n"))
io.close(fh)
else
rm(session.file)
end
end,
-- Load window and tab state from file
load = function (delete)
if not os.exists(session.file) then return end
local ret = {}
-- Read file
local lines = {}
local fh = io.open(session.file, "r")
for line in fh:lines() do table.insert(lines, line) end
io.close(fh)
-- Delete file
if delete ~= false then rm(session.file) end
-- Parse session file
local split = lousy.util.string.split
for _, line in ipairs(lines) do
local wi, ti, current, uri = unpack(split(line, "\t"))
wi = tonumber(wi)
current = (current == "true")
if not ret[wi] then ret[wi] = {} end
table.insert(ret[wi], {uri = uri, current = current})
end
return (#ret > 0 and ret) or nil
end,
-- Spawn windows from saved session and return the last window
restore = function (delete)
wins = session.load(delete)
if not wins or #wins == 0 then return end
-- Spawn windows
local w
for _, win in ipairs(wins) do
w = nil
for _, item in ipairs(win) do
if not w then
w = window.new({item.uri})
else
w:new_tab(item.uri, item.current)
end
end
end
return w
end,
}
-- Save current window session helper
window.methods.save_session = function (w)
session.save({w,})
end
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
robertbrook/lib | underscore.lua | 22 | 9838 | -- Copyright (c) 2009 Marcus Irven
--
-- 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.
--- Underscore is a set of utility functions for dealing with
-- iterators, arrays, tables, and functions.
local Underscore = { funcs = {} }
Underscore.__index = Underscore
function Underscore.__call(_, value)
return Underscore:new(value)
end
function Underscore:new(value, chained)
return setmetatable({ _val = value, chained = chained or false }, self)
end
function Underscore.iter(list_or_iter)
if type(list_or_iter) == "function" then return list_or_iter end
return coroutine.wrap(function()
for i=1,#list_or_iter do
coroutine.yield(list_or_iter[i])
end
end)
end
function Underscore.range(start_i, end_i, step)
if end_i == nil then
end_i = start_i
start_i = 1
end
step = step or 1
local range_iter = coroutine.wrap(function()
for i=start_i, end_i, step do
coroutine.yield(i)
end
end)
return Underscore:new(range_iter)
end
--- Identity function. This function looks useless, but is used throughout Underscore as a default.
-- @name _.identity
-- @param value any object
-- @return value
-- @usage _.identity("foo")
-- => "foo"
function Underscore.identity(value)
return value
end
-- chaining
function Underscore:chain()
self.chained = true
return self
end
function Underscore:value()
return self._val
end
-- iter
function Underscore.funcs.each(list, func)
for i in Underscore.iter(list) do
func(i)
end
return list
end
function Underscore.funcs.map(list, func)
local mapped = {}
for i in Underscore.iter(list) do
mapped[#mapped+1] = func(i)
end
return mapped
end
function Underscore.funcs.reduce(list, memo, func)
for i in Underscore.iter(list) do
memo = func(memo, i)
end
return memo
end
function Underscore.funcs.detect(list, func)
for i in Underscore.iter(list) do
if func(i) then return i end
end
return nil
end
function Underscore.funcs.select(list, func)
local selected = {}
for i in Underscore.iter(list) do
if func(i) then selected[#selected+1] = i end
end
return selected
end
function Underscore.funcs.reject(list, func)
local selected = {}
for i in Underscore.iter(list) do
if not func(i) then selected[#selected+1] = i end
end
return selected
end
function Underscore.funcs.all(list, func)
func = func or Underscore.identity
-- TODO what should happen with an empty list?
for i in Underscore.iter(list) do
if not func(i) then return false end
end
return true
end
function Underscore.funcs.any(list, func)
func = func or Underscore.identity
-- TODO what should happen with an empty list?
for i in Underscore.iter(list) do
if func(i) then return true end
end
return false
end
function Underscore.funcs.include(list, value)
for i in Underscore.iter(list) do
if i == value then return true end
end
return false
end
function Underscore.funcs.invoke(list, function_name, ...)
local args = {...}
Underscore.funcs.each(list, function(i) i[function_name](i, unpack(args)) end)
return list
end
function Underscore.funcs.pluck(list, propertyName)
return Underscore.funcs.map(list, function(i) return i[propertyName] end)
end
function Underscore.funcs.min(list, func)
func = func or Underscore.identity
return Underscore.funcs.reduce(list, { item = nil, value = nil }, function(min, item)
if min.item == nil then
min.item = item
min.value = func(item)
else
local value = func(item)
if value < min.value then
min.item = item
min.value = value
end
end
return min
end).item
end
function Underscore.funcs.max(list, func)
func = func or Underscore.identity
return Underscore.funcs.reduce(list, { item = nil, value = nil }, function(max, item)
if max.item == nil then
max.item = item
max.value = func(item)
else
local value = func(item)
if value > max.value then
max.item = item
max.value = value
end
end
return max
end).item
end
function Underscore.funcs.to_array(list)
local array = {}
for i in Underscore.iter(list) do
array[#array+1] = i
end
return array
end
function Underscore.funcs.reverse(list)
local reversed = {}
for i in Underscore.iter(list) do
table.insert(reversed, 1, i)
end
return reversed
end
function Underscore.funcs.sort(iter, comparison_func)
local array = iter
if type(iter) == "function" then
array = Underscore.funcs.to_array(iter)
end
table.sort(array, comparison_func)
return array
end
-- arrays
function Underscore.funcs.first(array, n)
if n == nil then
return array[1]
else
local first = {}
n = math.min(n,#array)
for i=1,n do
first[i] = array[i]
end
return first
end
end
function Underscore.funcs.rest(array, index)
index = index or 2
local rest = {}
for i=index,#array do
rest[#rest+1] = array[i]
end
return rest
end
function Underscore.funcs.slice(array, start_index, length)
local sliced_array = {}
start_index = math.max(start_index, 1)
local end_index = math.min(start_index+length-1, #array)
for i=start_index, end_index do
sliced_array[#sliced_array+1] = array[i]
end
return sliced_array
end
function Underscore.funcs.flatten(array)
local all = {}
for ele in Underscore.iter(array) do
if type(ele) == "table" then
local flattened_element = Underscore.funcs.flatten(ele)
Underscore.funcs.each(flattened_element, function(e) all[#all+1] = e end)
else
all[#all+1] = ele
end
end
return all
end
function Underscore.funcs.push(array, item)
table.insert(array, item)
return array
end
function Underscore.funcs.pop(array)
return table.remove(array)
end
function Underscore.funcs.shift(array)
return table.remove(array, 1)
end
function Underscore.funcs.unshift(array, item)
table.insert(array, 1, item)
return array
end
function Underscore.funcs.join(array, separator)
return table.concat(array, separator)
end
-- objects
function Underscore.funcs.keys(obj)
local keys = {}
for k,v in pairs(obj) do
keys[#keys+1] = k
end
return keys
end
function Underscore.funcs.values(obj)
local values = {}
for k,v in pairs(obj) do
values[#values+1] = v
end
return values
end
function Underscore.funcs.extend(destination, source)
for k,v in pairs(source) do
destination[k] = v
end
return destination
end
function Underscore.funcs.is_empty(obj)
return next(obj) == nil
end
-- Originally based on penlight's deepcompare() -- http://luaforge.net/projects/penlight/
function Underscore.funcs.is_equal(o1, o2, ignore_mt)
local ty1 = type(o1)
local ty2 = type(o2)
if ty1 ~= ty2 then return false end
-- non-table types can be directly compared
if ty1 ~= 'table' then return o1 == o2 end
-- as well as tables which have the metamethod __eq
local mt = getmetatable(o1)
if not ignore_mt and mt and mt.__eq then return o1 == o2 end
local is_equal = Underscore.funcs.is_equal
for k1,v1 in pairs(o1) do
local v2 = o2[k1]
if v2 == nil or not is_equal(v1,v2, ignore_mt) then return false end
end
for k2,v2 in pairs(o2) do
local v1 = o1[k2]
if v1 == nil then return false end
end
return true
end
-- functions
function Underscore.funcs.compose(...)
local function call_funcs(funcs, ...)
if #funcs > 1 then
return funcs[1](call_funcs(_.rest(funcs), ...))
else
return funcs[1](...)
end
end
local funcs = {...}
return function(...)
return call_funcs(funcs, ...)
end
end
function Underscore.funcs.wrap(func, wrapper)
return function(...)
return wrapper(func, ...)
end
end
function Underscore.funcs.curry(func, argument)
return function(...)
return func(argument, ...)
end
end
function Underscore.functions()
return Underscore.keys(Underscore.funcs)
end
-- add aliases
Underscore.methods = Underscore.functions
Underscore.funcs.for_each = Underscore.funcs.each
Underscore.funcs.collect = Underscore.funcs.map
Underscore.funcs.inject = Underscore.funcs.reduce
Underscore.funcs.foldl = Underscore.funcs.reduce
Underscore.funcs.filter = Underscore.funcs.select
Underscore.funcs.every = Underscore.funcs.all
Underscore.funcs.some = Underscore.funcs.any
Underscore.funcs.head = Underscore.funcs.first
Underscore.funcs.tail = Underscore.funcs.rest
local function wrap_functions_for_oo_support()
local function value_and_chained(value_or_self)
local chained = false
if getmetatable(value_or_self) == Underscore then
chained = value_or_self.chained
value_or_self = value_or_self._val
end
return value_or_self, chained
end
local function value_or_wrap(value, chained)
if chained then value = Underscore:new(value, true) end
return value
end
for fn, func in pairs(Underscore.funcs) do
Underscore[fn] = function(obj_or_self, ...)
local obj, chained = value_and_chained(obj_or_self)
return value_or_wrap(func(obj, ...), chained)
end
end
end
wrap_functions_for_oo_support()
return Underscore:new()
| bsd-3-clause |
resistor58/deaths-gmod-server | T-Rex/lua/entities/obj_flare/init.lua | 1 | 1626 |
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
function ENT:SpawnFunction(pl, tr)
if !tr.Hit then return end
local pos = tr.HitPos +Vector(0,0,20)
local ang = tr.HitNormal:Angle() +Angle(90,0,0)
local entFlare = ents.Create("prop_physics")
entFlare:SetModel("models/props_junk/flare.mdl")
entFlare:SetKeyValue("classname", "obj_flare")
entFlare:SetPos(pos)
entFlare:SetAngles(ang)
entFlare:Spawn()
entFlare:Activate()
entFlare:SetCollisionGroup(COLLISION_GROUP_INTERACTIVE)
entFlare:NoCollide("player")
local index = entFlare:EntIndex()
local function RemoveHooks()
hook.Remove("GravGunPunt", "flarePickup" .. index); hook.Remove("GravGunOnPickedUp", "flarePickup" .. index)
end
hook.Add("GravGunOnPickedUp", "flarePickup" .. index, function(pl, ent)
if !ValidEntity(entFlare) then RemoveHooks()
elseif ValidEntity(ent) && ent == entFlare then
entFlare.tmIgnition = CurTime()
RemoveHooks()
end
end)
hook.Add("GravGunPunt", "flarePickup" .. index, function(pl, ent)
if !ValidEntity(entFlare) then RemoveHooks()
elseif ValidEntity(ent) && ent == entFlare then
entFlare.tmIgnition = CurTime()
RemoveHooks()
end
end)
entFlare:CallOnRemove("CleanUpHooks", function(entFlare)
RemoveHooks()
end)
undo.Create("Flare")
undo.AddEntity(entFlare)
undo.SetPlayer(pl)
undo.Finish()
undo.Create("SENT")
undo.AddEntity(entFlare)
undo.SetPlayer(pl)
undo.SetCustomUndoText("Undone Flare")
undo.Finish("Scripted Entity (Flare)")
cleanup.Add(pl, "sents", entFlare)
return ent
end
| gpl-3.0 |
dunn/ntopng | scripts/lua/admin/get_users.lua | 11 | 2673 | --
-- (C) 2013 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPHeader('application/json')
if(haveAdminPrivileges()) then
currentPage = _GET["currentPage"]
perPage = _GET["perPage"]
sortColumn = _GET["sortColumn"]
sortOrder = _GET["sortOrder"]
if(sortColumn == nil) then
sortColumn = "column_"
end
if(currentPage == nil) then
currentPage = 1
else
currentPage = tonumber(currentPage)
end
if(perPage == nil) then
perPage = 5
else
perPage = tonumber(perPage)
end
users_list = ntop.getUsers()
print ("{ \"currentPage\" : " .. currentPage .. ",\n \"data\" : [\n")
num = 0
total = 0
to_skip = (currentPage-1) * perPage
vals = {}
num = 0
for key, value in pairs(users_list) do
num = num + 1
postfix = string.format("0.%04u", num)
if(sortColumn == "column_full_name") then
vals[users_list[key]["full_name"]..postfix] = key
elseif(sortColumn == "column_group") then
vals[users_list[key]["group"]..postfix] = key
else -- if(sortColumn == "column_username") then
vals[key] = key
end
end
table.sort(vals)
if(sortOrder == "asc") then
funct = asc
else
funct = rev
end
num = 0
for _key, _value in pairsByKeys(vals, funct) do
key = vals[_key]
value = users_list[key]
if(to_skip > 0) then
to_skip = to_skip-1
else
if(num < perPage) then
if(num > 0) then
print ",\n"
end
print ("{")
print (" \"column_username\" : \"" .. key .. "\", ")
print (" \"column_full_name\" : \"" .. value["full_name"] .. "\", ")
print (" \"column_group\" : \"" .. value["group"] .. "\", ")
print (" \"column_edit\" : \"<a href='#password_dialog' data-toggle='modal' onclick='return(reset_pwd_dialog(\\\"".. key.."\\\"));'><span class='label label-info'>Manage</span></a> ")
if(key ~= "admin") then
print ("<a href='#delete_user_dialog' role='button' class='add-on' data-toggle='modal' id='delete_btn_" .. key .. "'><span class='label label-danger'>Delete</span></a><script> $('#delete_btn_" .. key .. "').on('mouseenter', function() { delete_user_alert.warning('Are you sure you want to delete " .. key .. "?'); $('#delete_dialog_username').val('" .. key .. "'); }); </script>")
end
print ("\"}")
num = num + 1
end
end
total = total + 1
end -- for
print ("\n], \"perPage\" : " .. perPage .. ",\n")
if(sortColumn == nil) then
sortColumn = ""
end
if(sortOrder == nil) then
sortOrder = ""
end
print ("\"sort\" : [ [ \"" .. sortColumn .. "\", \"" .. sortOrder .."\" ] ],\n")
print ("\"totalRows\" : " .. total .. " \n}")
end | gpl-3.0 |
zhaoxx063/luci | applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/splash_leases.lua | 68 | 1118 | -- Copyright 2013 Freifunk Augsburg / Michael Wendland <michael@michiwend.com>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.splash_leases", package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Splash Leases",
vlabel = "Active Clients",
y_min = "0",
number_format = "%5.1lf",
data = {
sources = {
splash_leases = { "leased", "whitelisted", "blacklisted" }
},
options = {
splash_leases__leased = { color = "00CC00", title = "Leased", overlay = false },
splash_leases__whitelisted = { color = "0000FF", title = "Whitelisted", overlay = false },
splash_leases__blacklisted = { color = "FF0000", title = "Blacklisted", overlay = false }
}
}
}
end
| apache-2.0 |
resistor58/deaths-gmod-server | wire/lua/entities/gmod_wire_eyepod/init.lua | 1 | 8994 | AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Eye Pod"
ENT.OverlayDelay = 0
function ENT:Initialize()
-- Make Physics work
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
-- set it so we don't colide
self:SetCollisionGroup( COLLISION_GROUP_WORLD )
self.CollisionGroup = COLLISION_GROUP_WORLD
-- turn off shadow
self.Entity:DrawShadow(false)
-- Set wire I/O
self.Entity.Inputs = WireLib.CreateSpecialInputs(self.Entity, { "Enable", "SetPitch", "SetYaw", "SetViewAngle" }, {"NORMAL", "NORMAL", "NORMAL", "ANGLE"})
self.Entity.Outputs = WireLib.CreateSpecialOutputs(self.Entity, { "X", "Y", "XY" }, {"NORMAL", "NORMAL", "VECTOR2"})
-- Initialize values
self.driver = nil
self.X = 0
self.Y = 0
self.enabled = 0
self.pod = nil
self.EyeAng = Angle(0,0,0)
self.Rotate90 = false
self.DefaultToZero = 1
self.ShowRateOfChange = 0
self.LastUpdateTime = CurTime()
-- clamps
self.ClampXMin = 0
self.ClampXMax = 0
self.ClampYMin = 0
self.ClampYMax = 0
self.ClampX = 0
self.ClampY = 0
local phys = self.Entity:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
end
function ENT:Setup(DefaultToZero,RateOfChange,ClampXMin,ClampXMax,ClampYMin,ClampYMax, ClampX, ClampY)
self.DefaultToZero = DefaultToZero
self.ShowRateOfChange = RateOfChange
self.ClampXMin = ClampXMin
self.ClampXMax = ClampXMax
self.ClampYMin = ClampYMin
self.ClampYMax = ClampYMax
self.ClampX = ClampX
self.ClampY = ClampY
end
function ENT:PodLink(vehicle)
if !IsValid(vehicle) or !vehicle:IsVehicle() then
if IsValid(self.pod) then
self.pod.AttachedWireEyePod = nil
end
self.pod = nil
return false
end
self.pod = vehicle
local Rotate90ModelList = {
"models/props_c17/furniturechair001a.mdl",
"models/airboat.mdl",
"models/props_c17/chair_office01a.mdl",
"models/nova/chair_office02.mdl",
"models/nova/chair_office01.mdl",
"models/props_combine/breenchair.mdl",
"models/nova/chair_wood01.mdl",
"models/nova/airboat_seat.mdl",
"models/nova/chair_plastic01.mdl",
"models/nova/jeep_seat.mdl",
"models/props_phx/carseat.mdl",
"models/props_phx/carseat2.mdl",
"models/props_phx/carseat3.mdl",
"models/buggy.mdl",
"models/vehicle.mdl"
}
self.Rotate90 = false
self.EyeAng = Angle(0,0,0)
if IsValid(self.pod) and self.pod:IsVehicle() then
if table.HasValue( Rotate90ModelList,string.lower( self.pod:GetModel() ) ) then
self.Rotate90 = true
self.EyeAng = Angle(0,90,0)
end
end
local ttable = {
AttachedWireEyePod = self.Entity
}
table.Merge(vehicle:GetTable(), ttable )
return true
end
function ENT:OnRemove()
if IsValid(self.pod) and self.pod:IsVehicle() then
self.pod:GetTable().AttachedWireEyePod = nil
end
if IsValid(self.driver) then
umsg.Start("UpdateEyePodState", self.driver)
umsg.Short(0)
umsg.Angle(self.EyeAng)
umsg.Bool(self.Rotate90)
umsg.End()
self.driver = nil
end
end
function ENT:Think()
-- Make sure the gate updates even if we don't receive any input
self:TriggerInput()
if IsValid(self.pod) then
-- if we are in a pod, set the player
if self.pod:IsVehicle() and self.pod:GetDriver():IsPlayer() then
self.driver = self.pod:GetDriver()
else -- else set X and Y to 0
if IsValid(self.driver) then
umsg.Start("UpdateEyePodState", self.driver)
umsg.Short(0)
umsg.Angle(self.EyeAng)
umsg.Bool(self.Rotate90)
umsg.End()
self.driver = nil
end
if (self.DefaultToZero == 1) then
self.X = 0
self.Y = 0
Wire_TriggerOutput(self.Entity, "X", self.X)
Wire_TriggerOutput(self.Entity, "Y", self.Y)
local XY_Vec = {self.X,self.Y}
Wire_TriggerOutput(self.Entity, "XY", XY_Vec)
end
end
else -- else set X and Y to 0
if IsValid(self.driver) then
umsg.Start("UpdateEyePodState", self.driver)
umsg.Short(0)
umsg.Angle(self.EyeAng)
umsg.Bool(self.Rotate90)
umsg.End()
self.driver = nil
end
if (self.DefaultToZero == 1) then
self.X = 0
self.Y = 0
Wire_TriggerOutput(self.Entity, "X", self.X)
Wire_TriggerOutput(self.Entity, "Y", self.Y)
local XY_Vec = {self.X,self.Y}
Wire_TriggerOutput(self.Entity, "XY", XY_Vec)
end
self.pod = nil
end
-- update the overlay with the user's name
local Txt = "Eye Pod Control"
if self.Entity.enabled == 1 and IsValid(self.driver) and self.driver:IsPlayer() then
Txt = Txt.." - In use by "..self.driver:Name()
else
Txt = Txt.." - Not Active"
end
if IsValid(self.pod) and self.pod:IsVehicle() then
Txt = Txt.."\nLinked to "..self.pod:GetModel()
else
Txt = Txt.."\nNot Linked"
end
if Txt ~= self.LastOverlay then
self.Entity:SetNetworkedBeamString("GModOverlayText", Txt)
self.LastOverlay = Txt
end
self.Entity:NextThink(CurTime() + 0.1)
return true
end
local function AngNorm(Ang)
return (Ang + 180) % 360 - 180
end
local function AngNorm90(Ang)
return (Ang + 90) % 180 - 90
end
function ENT:TriggerInput(iname, value)
-- Change variables to reflect input
if (iname == "Enable") then
if (value != 0) then
self.enabled = 1
else
self.enabled = 0
end
elseif (iname == "SetPitch") then
self.EyeAng = Angle(AngNorm90(value),self.EyeAng.y,self.EyeAng.r)
elseif (iname == "SetYaw") then
if (self.Rotate90 == true) then
self.EyeAng = Angle(AngNorm90(self.EyeAng.p),AngNorm(value+90),self.EyeAng.r)
else
self.EyeAng = Angle(AngNorm90(self.EyeAng.p),AngNorm(value),self.EyeAng.r)
end
elseif (iname == "SetViewAngle") then
if (self.Rotate90 == true) then
self.EyeAng = Angle(AngNorm90(value.p),AngNorm(value.y+90),0)
else
self.EyeAng = Angle(AngNorm90(value.p),AngNorm(value.y),0)
end
end
-- If we're not enabled, set the output to zero and exit
if (self.enabled == 0) then
if (self.DefaultToZero == 1) then
self.X = 0
self.Y = 0
Wire_TriggerOutput(self.Entity, "X", self.X)
Wire_TriggerOutput(self.Entity, "Y", self.Y)
local XY_Vec = {self.X,self.Y}
Wire_TriggerOutput(self.Entity, "XY", XY_Vec)
end
if IsValid(self.driver) and IsValid(self.pod) then
umsg.Start("UpdateEyePodState", self.driver)
umsg.Short(self.enabled)
umsg.Angle(self.EyeAng)
umsg.Bool(self.Rotate90)
umsg.End()
end
return
end
--Turn on the EyePod Control file
self.enabled = 1
if IsValid(self.driver) and IsValid(self.pod) then
umsg.Start("UpdateEyePodState", self.driver)
umsg.Short(self.enabled)
umsg.Angle(self.EyeAng)
umsg.Bool(self.Rotate90)
umsg.End()
end
end
local UpdateTimer = CurTime()
local function EyePodMouseControl(ply, movedata)
local Vehicle = nil
local EyePod = nil
--is the player in a vehicle?
if ply and ply:InVehicle() and IsValid(ply:GetVehicle()) then
Vehicle = ply:GetVehicle()
local Table = Vehicle:GetTable()
--is the vehicle linked to an EyePod?
if Table and IsValid(Table.AttachedWireEyePod) then
--get the EyePod
EyePod = Table.AttachedWireEyePod
else
return
end
else
return
end
if !IsValid(EyePod) or !IsValid(Vehicle) then return end
if (EyePod.enabled == 1) then
local cmd = ply:GetCurrentCommand()
--update the cumualative output
EyePod.X = cmd:GetMouseX()/10 + EyePod.X
EyePod.Y = -cmd:GetMouseY()/10 + EyePod.Y
--clamp the output
if EyePod.ClampX == 1 then
EyePod.X = math.Clamp(EyePod.X,EyePod.ClampXMin,EyePod.ClampXMax)
end
if EyePod.ClampY == 1 then
EyePod.Y = math.Clamp(EyePod.Y,EyePod.ClampYMin,EyePod.ClampYMax)
end
--update the outputs every 0.015 seconds
if (CurTime() > (EyePod.LastUpdateTime+0.015)) then
Wire_TriggerOutput(EyePod, "X", EyePod.X)
Wire_TriggerOutput(EyePod, "Y", EyePod.Y)
local XY_Vec = {EyePod.X,EyePod.Y}
Wire_TriggerOutput(EyePod, "XY", XY_Vec)
--reset the output so it is not cumualative if you want the rate of change
if EyePod.ShowRateOfChange == 1 then
EyePod.X = 0
EyePod.Y = 0
end
EyePod.LastUpdateTime = CurTime()
end
--reset the mouse
cmd:SetMouseX(0)
cmd:SetMouseY(0)
return
end
end
hook.Add("SetupMove", "WireEyePodMouseControl", EyePodMouseControl)
-- Advanced Duplicator Support
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if IsValid(self.pod) then
info.pod = self.pod:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
if (info.pod) then
self.pod = GetEntByID(info.pod)
if !self.pod then
self.pod = ents.GetByIndex(info.pod)
end
if self.pod then
self.Entity:PodLink(self.pod)
end
end
end | gpl-3.0 |
resistor58/deaths-gmod-server | wire/lua/entities/gmod_wire_datasocket/init.lua | 1 | 4240 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Socket"
local MODEL = Model( "models/hammy/pci_slot.mdl" )
//Time after loosing one plug to search for another
local NEW_PLUG_WAIT_TIME = 2
local PLUG_IN_SOCKET_CONSTRAINT_POWER = 5000
local PLUG_IN_ATTACH_RANGE = 3
function ENT:Initialize()
self.Entity:SetModel( MODEL )
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
self.MyPlug = nil
self.Memory = nil
self.OwnMemory = nil
self.Const = nil
self.Inputs = Wire_CreateInputs(self.Entity, { "Memory" })
self.Outputs = Wire_CreateOutputs(self.Entity, { "Memory" })
self:SetOverlayText( "Data socket" )
Wire_TriggerOutput(self.Entity, "Memory", 0)
end
function ENT:SetMemory(mement)
self.Memory = mement
Wire_TriggerOutput(self.Entity, "Memory", 1)
end
function ENT:Setup(a,ar,ag,ab,aa)
self.A = a or 0
self.AR = ar or 255
self.AG = ag or 0
self.AB = ab or 0
self.AA = aa or 255
self.Entity:SetColor(ar, ag, ab, aa)
end
function ENT:ReadCell( Address )
if (self.Memory) then
if (self.Memory.ReadCell) then
return self.Memory:ReadCell( Address )
else
return nil
end
else
return nil
end
end
function ENT:WriteCell( Address, value )
if (self.Memory) then
if (self.Memory.WriteCell) then
return self.Memory:WriteCell( Address, value )
else
return false
end
else
return false
end
end
function ENT:Think()
self.BaseClass.Think(self)
// If we were unplugged, reset the plug and socket to accept new ones.
if (self.Const) and (not self.Const:IsValid()) then
self.Const = nil
self.NoCollideConst = nil
if (self.MyPlug) and (self.MyPlug:IsValid()) then
self.MyPlug:SetSocket(nil)
self.MyPlug = nil
end
self.Memory = nil //We're now getting no signal
Wire_TriggerOutput(self.Entity, "Memory", 0)
self.Entity:NextThink( CurTime() + NEW_PLUG_WAIT_TIME ) //Give time before next grabbing a plug.
return true
end
// If we have no plug in us
if (not self.MyPlug) or (not self.MyPlug:IsValid()) then
// Find entities near us
local sockCenter = self:GetOffset( Vector(-1.75, 0, 0) )
local local_ents = ents.FindInSphere( sockCenter, PLUG_IN_ATTACH_RANGE )
for key, plug in pairs(local_ents) do
// If we find a plug, try to attach it to us
if ( plug:IsValid() && plug:GetClass() == "gmod_wire_dataplug" ) then
// If no other sockets are using it
if plug.MySocket == nil then
local plugpos = plug:GetPos()
local dist = (sockCenter-plugpos):Length()
self:AttachPlug(plug)
end
end
end
end
end
function ENT:AttachPlug( plug )
// Set references between them
plug:SetSocket(self.Entity)
self.MyPlug = plug
// Position plug
local newpos = self:GetOffset( Vector(-1.75, 0, 0) )
local socketAng = self.Entity:GetAngles()
plug:SetPos( newpos )
plug:SetAngles( socketAng )
self.NoCollideConst = constraint.NoCollide(self.Entity, plug, 0, 0)
if (not self.NoCollideConst) then
self.MyPlug = nil
plug:SetSocket(nil)
self.Memory = nil
Wire_TriggerOutput(self.Entity, "Memory", 0)
return
end
// Constrain together
self.Const = constraint.Weld( self.Entity, plug, 0, 0, PLUG_IN_SOCKET_CONSTRAINT_POWER, true )
if (not self.Const) then
self.NoCollideConst:Remove()
self.NoCollideConst = nil
self.MyPlug = nil
plug:SetSocket(nil)
self.Memory = nil
Wire_TriggerOutput(self.Entity, "Memory", 0)
return
end
// Prepare clearup incase one is removed
plug:DeleteOnRemove( self.Const )
self.Entity:DeleteOnRemove( self.Const )
self.Const:DeleteOnRemove( self.NoCollideConst )
plug:AttachedToSocket(self.Entity)
end
function ENT:OnRestore()
self.A = self.A or 0
self.AR = self.AR or 255
self.AG = self.AG or 0
self.AB = self.AB or 0
self.AA = self.AA or 255
self.BaseClass.OnRestore(self)
end
function ENT:TriggerInput(iname, value, iter)
if (iname == "Memory") then
self.OwnMemory = self.Inputs.Memory.Src
end
end
| gpl-3.0 |
resistor58/deaths-gmod-server | Explosives And Nukes/lua/effects/effect_explosion_scaleable/init.lua | 2 | 11255 |
local tMats = {}
tMats.Glow1 = Material("sprites/light_glow02")
tMats.Glow2 = Material("sprites/flare1")
for _,mat in pairs(tMats) do
mat:SetMaterialInt("$spriterendermode",9)
mat:SetMaterialInt("$ignorez",1)
mat:SetMaterialInt("$illumfactor",8)
end
local SmokeParticleUpdate = function(particle)
if particle:GetStartAlpha() == 0 and particle:GetLifeTime() >= 0.5*particle:GetDieTime() then
particle:SetStartAlpha(particle:GetEndAlpha())
particle:SetEndAlpha(0)
particle:SetNextThink(-1)
else
particle:SetNextThink(CurTime() + 0.1)
end
return particle
end
function EFFECT:Init(data)
self.Scale = data:GetScale()
self.ScaleSlow = math.sqrt(self.Scale)
self.ScaleSlowest = math.sqrt(self.ScaleSlow)
self.Normal = data:GetNormal()
self.RightAngle = self.Normal:Angle():Right():Angle()
self.Position = data:GetOrigin() - 12*self.Normal
self.Position2 = self.Position + self.Scale*64*self.Normal
local CurrentTime = CurTime()
self.Duration = 0.5*self.Scale
self.KillTime = CurrentTime + self.Duration
self.GlowAlpha = 200
self.GlowSize = 100*self.Scale
self.FlashAlpha = 100
self.FlashSize = 0
local emitter = ParticleEmitter(self.Position)
--fire ball
for i=1,math.ceil(self.Scale*12) do
local vecang = (self.Normal + VectorRand()*math.Rand(0,0.7)):GetNormalized()
local velocity = math.Rand(700,1100)*vecang*self.Scale
local particle = emitter:Add("effects/fire_cloud"..math.random(1,2), self.Position + vecang*math.Rand(0,70)*self.Scale)
particle:SetVelocity(velocity)
particle:SetGravity(VectorRand()*math.Rand(200,400) + Vector(0,0,math.Rand(500,700)))
particle:SetAirResistance(250)
particle:SetDieTime(math.Rand(0.7,1.1)*self.Scale)
particle:SetStartAlpha(math.Rand(230,250))
particle:SetStartSize(math.Rand(110,140)*self.ScaleSlow)
particle:SetEndSize(math.Rand(150,190)*self.ScaleSlow)
particle:SetRoll(math.Rand(150,180))
particle:SetRollDelta(0.6*math.random(-1,1))
particle:SetColor(255,255,255)
end
--fire puff
for i=1,math.ceil(self.Scale*25) do
local vecang = self.RightAngle
vecang:RotateAroundAxis(self.Normal,math.Rand(0,360))
vecang = vecang:Forward() + VectorRand()*0.1
local velocity = math.Rand(256,1800)*vecang
local particle = emitter:Add("effects/fire_cloud"..math.random(1,2), self.Position + vecang*16*self.Scale)
particle:SetVelocity(velocity*self.Scale)
particle:SetGravity(VectorRand()*math.Rand(200,400))
particle:SetAirResistance(300)
particle:SetDieTime(math.Rand(0.6,0.8)*self.Scale)
particle:SetStartAlpha(math.Rand(230,250))
particle:SetStartSize(math.Rand(100,130)*self.ScaleSlow)
particle:SetEndSize(math.Rand(140,180)*self.ScaleSlow)
particle:SetRoll(math.Rand(150,180))
particle:SetRollDelta(0.4*math.random(-1,1))
particle:SetColor(255,255,255)
end
--fire burst
for i=1,math.ceil(self.Scale*8) do
local vecang = (self.Normal + VectorRand()*math.Rand(0.5,1.5)):GetNormalized()
local velocity = math.Rand(1200,1400)*vecang*self.Scale
local particle = emitter:Add("effects/fire_cloud"..math.random(1,2), self.Position - vecang*32*self.Scale)
particle:SetVelocity(velocity)
particle:SetDieTime(math.Rand(0.26,0.4))
particle:SetStartAlpha(math.Rand(230,250))
particle:SetStartSize(math.Rand(30,40)*self.ScaleSlow)
particle:SetEndSize(math.Rand(40,50)*self.ScaleSlow)
particle:SetStartLength(math.Rand(370,400)*self.ScaleSlow)
particle:SetEndLength(math.Rand(40,50)*self.ScaleSlow)
particle:SetColor(255,255,255)
end
--embers
for i=1,math.ceil(self.Scale*18) do
local vecang = (self.Normal + VectorRand()*math.Rand(0.2,1.2)):GetNormalized()
local particle = emitter:Add("effects/fire_embers"..math.random(1,3), self.Position + vecang*math.random(80,240)*self.ScaleSlow)
particle:SetVelocity(VectorRand()*math.Rand(32,96))
particle:SetAirResistance(1)
particle:SetDieTime(math.Rand(2,2.4)*self.ScaleSlow)
particle:SetStartAlpha(math.Rand(250,255))
particle:SetStartSize(math.Rand(16,21)*self.ScaleSlow)
particle:SetEndSize(math.Rand(16,21)*self.ScaleSlow)
particle:SetColor(255,255,255)
end
--flying embers
for i=1,math.ceil(math.Rand(10,16)*self.ScaleSlow) do
local vecang = (self.Normal + VectorRand()*math.Rand(0,2.5)):GetNormalized()
local particle = emitter:Add("effects/fire_embers"..math.random(1,3), self.Position + vecang*64*self.Scale)
particle:SetVelocity(vecang*math.Rand(350,800)*self.ScaleSlow)
particle:SetGravity(Vector(0,0,-600))
particle:SetAirResistance(1)
particle:SetDieTime(math.Rand(1.9,2.3)*self.ScaleSlow)
particle:SetStartAlpha(255)
particle:SetEndAlpha(255)
particle:SetStartSize(math.Rand(11,15)*self.ScaleSlow)
particle:SetEndSize(0)
particle:SetRoll(math.Rand(150,170))
particle:SetRollDelta(0.7*math.random(-1,1))
particle:SetCollide(true)
particle:SetBounce(0.9)
particle:SetColor(255,180,100)
end
--dust puff
for i=1,math.ceil(self.Scale*57) do
local vecang = self.RightAngle
vecang:RotateAroundAxis(self.Normal,math.Rand(0,360))
vecang = vecang:Forward() + VectorRand()*0.1
local velocity = math.Rand(1200,2800)*vecang
local particle = emitter:Add("particle/particle_smokegrenade", self.Position - vecang*64*self.Scale - self.Normal*32)
local dietime = math.Rand(2.5,2.9)*self.Scale
particle:SetVelocity(velocity*self.Scale)
particle:SetGravity((self.Normal - 1.3e-3*velocity):GetNormalized()*200)
particle:SetAirResistance(250)
particle:SetDieTime(dietime)
particle:SetLifeTime(math.Rand(-0.12,-0.08))
particle:SetStartAlpha(0)
particle:SetEndAlpha(200)
particle:SetThinkFunction(SmokeParticleUpdate)
particle:SetNextThink(CurrentTime + 0.5*dietime)
particle:SetStartSize(math.Rand(90,110)*self.ScaleSlow)
particle:SetEndSize(math.Rand(130,150)*self.ScaleSlow)
particle:SetRoll(math.Rand(150,180))
particle:SetRollDelta(0.6*math.random(-1,1))
particle:SetColor(152,142,126)
end
--pillar of dust
for i=1,math.ceil(self.Scale*12) do
local vecang = (self.Normal + VectorRand()*math.Rand(0,0.5)):GetNormalized()
local velocity = math.Rand(-300,500)*vecang*self.Scale
local particle = emitter:Add("particle/particle_smokegrenade", self.Position + vecang*math.Rand(-50,75)*self.Scale)
local dietime = math.Rand(2.8,3.4)*self.Scale
particle:SetVelocity(velocity)
particle:SetGravity(Vector(0,0,math.Rand(50,250)))
particle:SetAirResistance(65)
particle:SetDieTime(dietime)
particle:SetLifeTime(math.Rand(-0.12,-0.08))
particle:SetStartAlpha(0)
particle:SetEndAlpha(200)
particle:SetThinkFunction(SmokeParticleUpdate)
particle:SetNextThink(CurrentTime + 0.5*dietime)
particle:SetStartSize(math.Rand(90,140)*self.ScaleSlow)
particle:SetEndSize(math.Rand(240,280)*self.ScaleSlow)
particle:SetRoll(math.Rand(150,170))
particle:SetRollDelta(0.7*math.random(-1,1))
particle:SetColor(152,142,126)
end
--dust cloud
for i=1,math.ceil(self.Scale*8) do
local vecang = (self.Normal + VectorRand()*math.Rand(0.3,0.7)):GetNormalized()
local velocity = math.Rand(150,300)*vecang*self.Scale
local particle = emitter:Add("particle/particle_smokegrenade", self.Position + vecang*math.Rand(20,80)*self.Scale)
local dietime = math.Rand(2.9,3.5)*self.Scale
particle:SetVelocity(velocity)
particle:SetGravity(Vector(0,0,math.Rand(200,240)))
particle:SetAirResistance(65)
particle:SetDieTime(dietime)
particle:SetLifeTime(math.Rand(-0.2,-0.15))
particle:SetStartAlpha(0)
particle:SetEndAlpha(200)
particle:SetThinkFunction(SmokeParticleUpdate)
particle:SetNextThink(CurrentTime + 0.5*dietime)
particle:SetStartSize(math.Rand(90,140)*self.ScaleSlow)
particle:SetEndSize(math.Rand(240,280)*self.ScaleSlow)
particle:SetRoll(math.Rand(180,200))
particle:SetRollDelta(0.85*math.random(-1,1))
particle:SetColor(152,142,126)
end
--dirt
for i=1,math.ceil(math.Rand(9,13)*self.ScaleSlow) do
local vecang = (self.Normal + VectorRand()*math.Rand(0,3)):GetNormalized()
local particle = emitter:Add("effects/fleck_cement"..math.random(1,2), self.Position + vecang*64*self.Scale)
local size = math.Rand(5,9)
particle:SetVelocity(vecang*math.Rand(600,1100)*self.ScaleSlow)
particle:SetGravity(Vector(0,0,-600))
particle:SetAirResistance(1)
particle:SetDieTime(math.Rand(2.8,3.5)*self.ScaleSlow)
particle:SetStartAlpha(math.Rand(140,170))
particle:SetEndAlpha(0)
particle:SetStartSize(size)
particle:SetEndSize(size)
particle:SetRoll(math.Rand(400,500))
particle:SetRollDelta(math.Rand(-24,24))
particle:SetCollide(true)
particle:SetBounce(0.9)
particle:SetColor(173,160,143)
end
if self.Scale > 6 then
--shock wave
for i=1,math.ceil(self.Scale*55) do
local vecang = Vector(math.Rand(-1,1),math.Rand(-1,1),0):GetNormalized()
local velocity = math.Rand(8900,9100)*vecang
local particle = emitter:Add("sprites/heatwave", self.Position - vecang*64*self.Scale - Vector(0,0,80*self.ScaleSlowest))
local dietime = 0.08*self.Scale
particle:SetVelocity(velocity)
particle:SetDieTime(dietime)
particle:SetLifeTime(0)
particle:SetStartAlpha(60)
particle:SetEndAlpha(0)
particle:SetStartSize(160*self.ScaleSlowest)
particle:SetEndSize(200*self.ScaleSlowest)
particle:SetColor(255,255,255)
end
end
emitter:Finish()
if self.Scale > 4 then
surface.PlaySound("ambient/explosions/explode_8.wav")
self.Entity:EmitSound("ambient/explosions/explode_4.wav")
elseif self.Scale > 11 then
surface.PlaySound("ambient/explosions/explode_8.wav")
self.Entity:EmitSound("ambient/explosions/explode_1.wav")
elseif self.Scale > 23 then
surface.PlaySound("ambient/explosions/exp1.wav")
surface.PlaySound("ambient/explosions/explode_4.wav")
elseif self.Scale > 35 then
surface.PlaySound("ambient/explosions/exp2.wav")
surface.PlaySound("ambient/explosions/explode_6.wav")
else
self.Entity:EmitSound("ambient/explosions/explode_4.wav")
end
end
--THINK
-- Returning false makes the entity die
function EFFECT:Think()
local TimeLeft = self.KillTime - CurTime()
local TimeScale = TimeLeft/self.Duration
local FTime = FrameTime()
if TimeLeft > 0 then
self.FlashAlpha = self.FlashAlpha - 200*FTime
self.FlashSize = self.FlashSize + 60000*FTime
self.GlowAlpha = 200*TimeScale
self.GlowSize = TimeLeft*self.Scale
return true
else
return false
end
end
-- Draw the effect
function EFFECT:Render()
--base glow
render.SetMaterial(tMats.Glow1)
render.DrawSprite(self.Position2,7000*self.GlowSize,5500*self.GlowSize,Color(255,240,220,self.GlowAlpha))
--blinding flash
if self.FlashAlpha > 0 then
render.SetMaterial(tMats.Glow2)
render.DrawSprite(self.Position2,self.FlashSize,self.FlashSize,Color(255,245,215,self.FlashAlpha))
end
end
| gpl-3.0 |
milos-korenciak/heroku-buildpack-tex | buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/lib/DepthFirstSearch.lua | 3 | 2399 | -- Copyright 2011 by Jannis Pohlmann
-- Copyright 2012 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/lib/DepthFirstSearch.lua,v 1.1 2012/11/27 17:24:26 tantau Exp $
--- The DepthFirstSearch class implements a generic depth first function. It does not
-- require that it is run on graphs, but can be used for anything where a visit function and
-- a complete function is available.
local DepthFirstSearch = {}
DepthFirstSearch.__index = DepthFirstSearch
-- Namespace
require("pgf.gd.lib").DepthFirstSearch = DepthFirstSearch
-- Imports
local Stack = require "pgf.gd.lib.Stack"
-- TT: TODO Jannis: Please document...
function DepthFirstSearch.new(init_func, visit_func, complete_func)
local dfs = {
init_func = init_func,
visit_func = visit_func,
complete_func = complete_func,
stack = Stack.new(),
discovered = {},
visited = {},
completed = {},
}
setmetatable(dfs, DepthFirstSearch)
return dfs
end
function DepthFirstSearch:run()
self:reset()
self.init_func(self)
while self.stack:getSize() > 0 do
local data = self.stack:peek()
if not self:getVisited(data) then
if self.visit_func then
self.visit_func(self, data)
end
else
if self.complete_func then
self.complete_func(self, data)
end
self:setCompleted(data, true)
self.stack:pop()
end
end
end
function DepthFirstSearch:reset()
self.discovered = {}
self.visited = {}
self.completed = {}
self.stack = Stack.new()
end
function DepthFirstSearch:setDiscovered(data, discovered)
self.discovered[data] = discovered
end
function DepthFirstSearch:getDiscovered(data)
return self.discovered[data]
end
function DepthFirstSearch:setVisited(data, visited)
self.visited[data] = visited
end
function DepthFirstSearch:getVisited(data)
return self.visited[data]
end
function DepthFirstSearch:setCompleted(data, completed)
self.completed[data] = completed
end
function DepthFirstSearch:getCompleted(data)
return self.completed[data]
end
function DepthFirstSearch:push(data)
self.stack:push(data)
end
-- Done
return DepthFirstSearch | mit |
tehran980/https-github.com-uziins-uzzbot | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
SPMATINTG/SPsur | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
hfjgjfg/ccc111 | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
tkdrob/Battle-Tag | Packages/Introduction/Data/Script/Lua/UAIntroduction.Ui.Seq_Stage5.lua | 1 | 3328 |
--[[--------------------------------------------------------------------------
--
-- File: UAIntroduction.Ui.Seq_Stage5.lua
-- Copyright (c) Ubisoft Entertainment. All rights reserved.
--
-- Project: Ubitoys.Tag
-- Date: September 21, 2010
--
------------------------------------------------------------------------------
--
-- Description: <Here are the T-Boxes>
--
----------------------------------------------------------------------------]]
--[[ Dependencies ----------------------------------------------------------]]
require "Ui/UIMenuWindow"
--[[ Class -----------------------------------------------------------------]]
UAIntroduction.Ui = UAIntroduction.Ui or {}
UAIntroduction.Ui.Seq_Stage5 = UTClass(UIMenuWindow)
-- __ctor -------------------------------------------------------------------
function UAIntroduction.Ui.Seq_Stage5:__ctor(state)
assert(activity)
assert(state)
-- window settings
self.uiWindow.title = activity.name
-- contents,
self.uiPanel = self.uiWindow:AddComponent(UIPanel:New(), "uiPanel")
self.uiPanel.rectangle = self.clientRectangle
self.uiContents = self.uiPanel:AddComponent(UITitledPanel:New(), "uiContents")
self.uiContents.rectangle = { 20, 20, 695, 435 }
self.uiContents.title = l "con014"
self.uiContents.clientRectangle = {}
for i = 1, 4 do
self.uiContents.clientRectangle[i] = self.uiWindow.rectangle[i] + self.clientRectangle[i] + self.uiContents.rectangle[i]
end
self.text = l "con015"
-- buttons,
-- uiButton5: next
self.uiButton5 = self:AddComponent(UIButton:New(), "uiButton5")
self.uiButton5.rectangle = UIMenuWindow.buttonRectangles[5]
self.uiButton5.text = l "but006"
self.uiButton5.tip = l"tip005"
self.uiButton5.OnAction = function ()
state:Next()
end
-- gm lock
self.uiButton5.enabled = false
game.gameMaster:Play("base:audio/gamemaster/dlg_gm_init_17.wav", function () self.uiButton5.enabled = true end)
end
-- Draw ---------------------------------------------------------------------
function UAIntroduction.Ui.Seq_Stage5:Draw()
UIMenuWindow.Draw(self)
-- contents,
quartz.system.drawing.pushcontext()
quartz.system.drawing.loadtranslation(unpack(self.uiContents.clientRectangle))
quartz.system.drawing.loadtranslation(0, UITitledPanel.headerSize)
-- bitmap
quartz.system.drawing.loadcolor3f(unpack(UIComponent.colors.white))
quartz.system.drawing.loadtexture("base:texture/ui/seq_roundloop_stage5left.tga")
quartz.system.drawing.drawtexture(0, 0)
--quartz.system.drawing.loadtexture("base:texture/ui/seq_roundloop_stage5right.tga")
--quartz.system.drawing.drawtexture(82 + 82, 0)
-- text
local fontJustification = quartz.system.drawing.justification.bottomleft + quartz.system.drawing.justification.wordbreak
local rectangle = { 40, 50, 675 - 40, 390 - 20 }
quartz.system.drawing.loadcolor3f(unpack(self.fontColor))
quartz.system.drawing.loadfont(UIComponent.fonts.default)
quartz.system.drawing.drawtextjustified(self.text, fontJustification, unpack(rectangle) )
quartz.system.drawing.pop()
end | mit |
dunn/ntopng | scripts/lua/pid_stats.lua | 10 | 2910 | --
-- (C) 2013-15 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPHeader('text/html; charset=iso-8859-1')
mode = _GET["mode"] --l4,l7,host
pid = tonumber(_GET["pid"])
name = _GET["name"]
host = _GET["host"]
local debug = false
if (debug) then setTraceLevel(TRACE_DEBUG) end
interface.select(ifname)
if (pid ~= nil) then
flows = interface.findPidFlows(pid)
elseif (name ~= nil) then
flows = interface.findNameFlows(name)
end
if(mode == nil) then
mode = "host"
end
if(flows == nil) then
print('[ { "label": "No flows", "value": 1 } ]') -- No flows found
else
apps = { }
tot = 0
for k,f in pairs(flows) do
process = 1
traceError(TRACE_DEBUG,TRACE_CONSOLE,"Cli:"..f["cli.ip"].." - Srv:"..f["srv.ip"])
if((host ~= nil) and ((f["cli.ip"] ~= host) and (f["srv.ip"] ~= host))) then
process = 0
end
if(mode == "l7") then
key = f["proto.ndpi"]
v = f["cli2srv.bytes"] + f["srv2cli.bytes"]
elseif(mode == "l4") then
key = f["proto.l4"]
v = f["cli2srv.bytes"] + f["srv2cli.bytes"]
elseif(mode == "host") then
if ((f["client_process"] ~= nil) and (f["client_process"]["name"] == name)) then
-- key = f["cli.source_id"].."-"..f["cli.ip"].."(client)"
key = f["cli.ip"].."(client)"
v = f["cli2srv.bytes"]
elseif ((f["server_process"] ~= nil) and (f["server_process"]["name"] == name)) then
-- key = f["srv.source_id"].."-"..f["srv.ip"].."(server)"
key = f["srv.ip"].."(server)"
v = f["srv2cli.bytes"]
end
end
if((key ~= nil) and (process == 1))then
if(apps[key] == nil) then apps[key] = 0 end
traceError(TRACE_DEBUG,TRACE_CONSOLE,"key: "..key..",value: "..apps[key])
apps[key] = apps[key] + v
tot = tot + v
end
end
-- Print up to this number of entries
max_num_entries = 10
-- Print entries whose value >= 5% of the total
threshold = (tot * 5) / 100
print "[\n"
num = 0
accumulate = 0
for key, value in pairs(apps) do
if((num ~= 0) and (value < threshold)) then
break
end
if(num > 0) then
print ",\n"
end
print("\t { \"label\": \"" .. key .."\", \"value\": ".. value .." }")
accumulate = accumulate + value
num = num + 1
if(num == max_num_entries) then
break
end
end
if((num == 0) and (top_key ~= nil)) then
print("\t { \"label\": \"" .. top_key .."\", \"value\": ".. top_value ..", \"url\": \""..ntop.getHttpPrefix().."/lua/host_details.lua?host=".. top_key .."\" }")
accumulate = accumulate + top_value
end
-- In case there is some leftover do print it as "Other"
if(accumulate < tot) then
if(num > 0) then print(",") end
print("\n\t { \"label\": \"Other\", \"value\": ".. (tot-accumulate) .." }")
end
print "\n]"
end
| gpl-3.0 |
mamadtnt/bot | plugins/sudo.lua | 359 | 1878 | function run_sh(msg)
name = get_name(msg)
text = ''
-- if config.sh_enabled == false then
-- text = '!sh command is disabled'
-- else
-- if is_sudo(msg) then
-- bash = msg.text:sub(4,-1)
-- text = run_bash(bash)
-- else
-- text = name .. ' you have no power here!'
-- end
-- end
if is_sudo(msg) then
bash = msg.text:sub(4,-1)
text = run_bash(bash)
else
text = name .. ' you have no power here!'
end
return text
end
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
function on_getting_dialogs(cb_extra,success,result)
if success then
local dialogs={}
for key,value in pairs(result) do
for chatkey, chat in pairs(value.peer) do
print(chatkey,chat)
if chatkey=="id" then
table.insert(dialogs,chat.."\n")
end
if chatkey=="print_name" then
table.insert(dialogs,chat..": ")
end
end
end
send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false)
end
end
function run(msg, matches)
if not is_sudo(msg) then
return "You aren't allowed!"
end
local receiver = get_receiver(msg)
if string.match(msg.text, '!sh') then
text = run_sh(msg)
send_msg(receiver, text, ok_cb, false)
return
end
if string.match(msg.text, '!cpu') then
text = run_bash('uname -snr') .. ' ' .. run_bash('whoami')
text = text .. '\n' .. run_bash('top -b |head -2')
send_msg(receiver, text, ok_cb, false)
return
end
if matches[1]=="Get dialogs" then
get_dialog_list(on_getting_dialogs,{get_receiver(msg)})
return
end
end
return {
description = "shows cpuinfo",
usage = "!cpu",
patterns = {"^!cpu", "^!sh","^Get dialogs$"},
run = run
}
| gpl-2.0 |
sanger-pathogens/companion | bin/tmhmm_to_gff3.lua | 4 | 4561 | #!/usr/bin/env gt
--[[
Author: Sascha Steinbiss <ss34@sanger.ac.uk>
Copyright (c) 2014 Genome Research Ltd
Permission to use, copy, modify, and distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
]]
function usage()
io.stderr:write(string.format("Usage: %s <TMHMM2 output> "
.." <GFF with polypeptide annotations>\n" ,
arg[0]))
os.exit(1)
end
if #arg < 2 then
usage()
os.exit(1)
end
package.path = gt.script_dir .. "/?.lua;" .. package.path
require("lib")
cv = gt.custom_visitor_new()
cv.tmhs = {}
function cv:visit_feature(fn)
local pp_id = nil
if fn:get_type() == "polypeptide" then
pp_id = fn:get_attribute("ID")
local tm = nil
-- search for a TMH in the TMHMM results
for seq,v in pairs(cv.tmhs) do
if string.match(pp_id, seq) then
tm = v
break
end
end
-- if we have a TMH for this feature then attach it
if tm and tm.number > 0 then
node_rng = fn:get_range()
whole_region_rng = {tonumber(tm.parts[1][2])-1, tonumber(tm.parts[#tm.parts][3])-1}
-- print(node_rng:length() - 3) -- minus stop codon
-- print((whole_region_rng[2]-whole_region_rng[1]+1) * 3)
if fn:get_strand() == '-' then
whole_region_rng = {node_rng:get_end() - (whole_region_rng[2])*3+1,
node_rng:get_end() - (whole_region_rng[1])*3}
else
whole_region_rng = {node_rng:get_start() + (whole_region_rng[1])*3,
node_rng:get_start() + (whole_region_rng[2])*3}
end
mnode = gt.feature_node_new(fn:get_seqid(), "membrane_structure",
whole_region_rng[1], whole_region_rng[2],
fn:get_strand())
mnode:set_attribute("ID", pp_id..".membrane")
mnode:set_source("TMHMM2.0")
fn:add_child(mnode)
for i,part in ipairs(tm.parts) do
ptype = nil
if part[1] == "inside" then
ptype = "cytoplasmic_polypeptide_region"
elseif part[1] == "outside" then
ptype = "non_cytoplasmic_polypeptide_region"
else
ptype = "transmembrane_helix"
end
if fn:get_strand() == '-' then
whole_region_rng = {node_rng:get_end() - (tonumber(part[3])-1)*3,
node_rng:get_end() - (tonumber(part[2])-1)*3}
else
whole_region_rng = {node_rng:get_start() + (tonumber(part[2])-1)*3,
node_rng:get_start() + (tonumber(part[3])-1)*3}
end
pt = gt.feature_node_new(fn:get_seqid(), ptype,
whole_region_rng[1], whole_region_rng[2],
fn:get_strand())
mnode:add_child(pt)
pt:set_source("TMHMM2.0")
end
end
end
return 0
end
-- extract TMH data from TMHMM output and store per protein
for l in io.lines(arg[1]) do
a,b = string.match(l, "^# (.+)%s+Number of predicted TMHs:%s+(%d+)")
if a and b then
v = split(a, ':')[1]
if not cv.tmhs[v] then
cv.tmhs[v] = {}
end
cv.tmhs[v].number = tonumber(b)
else
if string.sub(l, 1, 2) ~= "# " then
local seq, _, state, start, stop = unpack(split(l, "%s+"))
seq = split(seq, ':')[1]
if cv.tmhs[seq] and cv.tmhs[seq].number > 0 then
if cv.tmhs[seq].parts == nil then
cv.tmhs[seq].parts = {}
end
table.insert(cv.tmhs[seq].parts, {state, start, stop})
end
end
end
end
vis_stream = gt.custom_stream_new_unsorted()
vis_stream.instream = gt.gff3_in_stream_new_sorted(arg[2])
vis_stream.visitor = cv
function vis_stream:next_tree()
local node = self.instream:next_tree()
if node then
node:accept(self.visitor)
end
return node
end
out_stream = gt.gff3_out_stream_new(vis_stream)
local gn = out_stream:next_tree()
while (gn) do
gn = out_stream:next_tree()
end | isc |
mmcclimon/dotfiles | hammerspoon/resizer.lua | 1 | 1463 | -- entirely so that I don't have to quote keys everywhere else.
local screen_lookup = {
["Color LCD"] = "int", -- really, macos?
["DELL P2715Q"] = "ext",
["DELL U2719DX"] = "ext",
}
local screen_config = {
["iTerm2"] = {
ext = function (frame)
return { x = 140, y = 130, w = 925, h = 880 }
end,
int = function (frame)
return { x = 130, y = 0, w = 925, h = frame.h }
end,
},
["Slack"] = {
all = function (frame)
local left = frame.x + frame.w - 950
return { x = left, y = 0, w = 950, h = 850 }
end,
},
["Firefox"] = {
ext = function (frame)
local width = 3 * frame.w / 4;
return { x = 0, y = 0, w = width, h = frame.h }
end,
int = function (frame)
return { x = 0, y = 0, w = frame.w - 75, h = frame.h }
end,
}
};
local function resizeWindows (app_name)
for app_name, app_config in pairs(screen_config) do
local app = hs.application.find(app_name)
local screen = screen_lookup[ hs.screen.primaryScreen():name() ]
local calc_size = app_config[screen] or app_config["all"]
if app and screen and calc_size then
local windows = app:visibleWindows()
for _, window in ipairs(windows) do
local frame = window:screen():fullFrame()
local geom = calc_size(frame)
window:move(geom)
break -- one window is enough, in case of madness
end
end
end
end
resizer = {
resizeWindows = resizeWindows,
}
| mit |
bestroidd/advan | plugins/photo2sticker.lua | 18 | 1039 | local function tosticker(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/stickers/sticker.webp'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_document(get_receiver(msg), file, ok_cb, false)
redis:del("photo:sticker")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and redis:get("photo:sticker") then
if redis:get("photo:sticker") == 'waiting' then
load_photo(msg.id, tosticker, msg)
end
end
end
if matches[1] == "tosticker" then
redis:set("photo:sticker", "waiting")
return 'Please send your photo now'
end
end
return {
patterns = {
"^[!/#](tosticker)$",
"%[(photo)%]",
},
run = run,
}
-- by channel: @WaderTGTeam
| gpl-2.0 |
amilaperera/google-diff-match-patch | lua/diff_match_patch_test.lua | 264 | 39109 | --[[
* Test Harness for Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser
* Ported to Lua by Duncan Cross
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
local dmp = require 'diff_match_patch'
local DIFF_INSERT = dmp.DIFF_INSERT
local DIFF_DELETE = dmp.DIFF_DELETE
local DIFF_EQUAL = dmp.DIFF_EQUAL
-- Utility functions.
local function pretty(v)
if (type(v) == 'string') then
return string.format('%q', v):gsub('\\\n', '\\n')
elseif (type(v) == 'table') then
local str = {}
local next_i = 1
for i, v in pairs(v) do
if (i == next_i) then
next_i = next_i + 1
str[#str + 1] = pretty(v)
else
str[#str + 1] = '[' .. pretty(i) .. ']=' .. pretty(v)
end
end
return '{' .. table.concat(str, ',') .. '}'
else
return tostring(v)
end
end
function assertEquals(...)
local msg, expected, actual
if (select('#', ...) == 2) then
expected, actual = ...
msg = 'Expected: \'' .. pretty(expected)
.. '\' Actual: \'' .. pretty(actual) .. '\''
else
msg, expected, actual = ...
end
assert(expected == actual, msg)
end
function assertTrue(...)
local msg, actual
if (select('#', ...) == 1) then
actual = ...
assertEquals(true, actual)
else
msg, actual = ...
assertEquals(msg, true, actual)
end
end
function assertFalse(...)
local msg, actual
if (select('#', ...) == 1) then
actual = ...
assertEquals(flase, actual)
else
msg, actual = ...
assertEquals(msg, false, actual)
end
end
-- If expected and actual are the equivalent, pass the test.
function assertEquivalent(...)
local msg, expected, actual
expected, actual = ...
msg = 'Expected: \'' .. pretty(expected)
.. '\' Actual: \'' .. pretty(actual) .. '\''
if (_equivalent(expected, actual)) then
assertEquals(msg, pretty(expected), pretty(actual))
else
assertEquals(msg, expected, actual)
end
end
-- Are a and b the equivalent? -- Recursive.
function _equivalent(a, b)
if (a == b) then
return true
end
if (type(a) == 'table') and (type(b) == 'table') then
for k, v in pairs(a) do
if not _equivalent(v, b[k]) then
return false
end
end
for k, v in pairs(b) do
if not _equivalent(v, a[k]) then
return false
end
end
return true
end
return false
end
function diff_rebuildtexts(diffs)
-- Construct the two texts which made up the diff originally.
local text1, text2 = {}, {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op ~= DIFF_INSERT) then
text1[#text1 + 1] = data
end
if (op ~= DIFF_DELETE) then
text2[#text2 + 1] = data
end
end
return table.concat(text1), table.concat(text2)
end
-- DIFF TEST FUNCTIONS
function testDiffCommonPrefix()
-- Detect any common prefix.
-- Null case.
assertEquals(0, dmp.diff_commonPrefix('abc', 'xyz'))
-- Non-null case.
assertEquals(4, dmp.diff_commonPrefix('1234abcdef', '1234xyz'))
-- Whole case.
assertEquals(4, dmp.diff_commonPrefix('1234', '1234xyz'))
end
function testDiffCommonSuffix()
-- Detect any common suffix.
-- Null case.
assertEquals(0, dmp.diff_commonSuffix('abc', 'xyz'))
-- Non-null case.
assertEquals(4, dmp.diff_commonSuffix('abcdef1234', 'xyz1234'))
-- Whole case.
assertEquals(4, dmp.diff_commonSuffix('1234', 'xyz1234'))
end
function testDiffCommonOverlap()
-- Detect any suffix/prefix overlap.
-- Null case.
assertEquals(0, dmp.diff_commonOverlap('', 'abcd'));
-- Whole case.
assertEquals(3, dmp.diff_commonOverlap('abc', 'abcd'));
-- No overlap.
assertEquals(0, dmp.diff_commonOverlap('123456', 'abcd'));
-- Overlap.
assertEquals(3, dmp.diff_commonOverlap('123456xxx', 'xxxabcd'));
--[[
-- Unicode.
-- Some overly clever languages (C#) may treat ligatures as equal to their
-- component letters. E.g. U+FB01 == 'fi'
-- LUANOTE: No ability to handle Unicode.
assertEquals(0, dmp.diff_commonOverlap('fi', '\ufb01i'));
--]]
end
function testDiffHalfMatch()
-- Detect a halfmatch.
dmp.settings{Diff_Timeout = 1}
-- No match.
assertEquivalent({nil}, {dmp.diff_halfMatch('1234567890', 'abcdef')})
assertEquivalent({nil}, {dmp.diff_halfMatch('12345', '23')})
-- Single Match.
assertEquivalent({'12', '90', 'a', 'z', '345678'},
{dmp.diff_halfMatch('1234567890', 'a345678z')})
assertEquivalent({'a', 'z', '12', '90', '345678'},
{dmp.diff_halfMatch('a345678z', '1234567890')})
assertEquivalent({'abc', 'z', '1234', '0', '56789'},
{dmp.diff_halfMatch('abc56789z', '1234567890')})
assertEquivalent({'a', 'xyz', '1', '7890', '23456'},
{dmp.diff_halfMatch('a23456xyz', '1234567890')})
-- Multiple Matches.
assertEquivalent({'12123', '123121', 'a', 'z', '1234123451234'},
{dmp.diff_halfMatch('121231234123451234123121', 'a1234123451234z')})
assertEquivalent({'', '-=-=-=-=-=', 'x', '', 'x-=-=-=-=-=-=-='},
{dmp.diff_halfMatch('x-=-=-=-=-=-=-=-=-=-=-=-=', 'xx-=-=-=-=-=-=-=')})
assertEquivalent({'-=-=-=-=-=', '', '', 'y', '-=-=-=-=-=-=-=y'},
{dmp.diff_halfMatch('-=-=-=-=-=-=-=-=-=-=-=-=y', '-=-=-=-=-=-=-=yy')})
-- Non-optimal halfmatch.
-- Optimal diff would be -q+x=H-i+e=lloHe+Hu=llo-Hew+y not -qHillo+x=HelloHe-w+Hulloy
assertEquivalent({'qHillo', 'w', 'x', 'Hulloy', 'HelloHe'},
{dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')})
-- Optimal no halfmatch.
dmp.settings{Diff_Timeout = 0}
assertEquivalent({nill}, {dmp.diff_halfMatch('qHilloHelloHew', 'xHelloHeHulloy')})
end
function testDiffCleanupMerge()
-- Cleanup a messy diff.
-- Null case.
local diffs = {}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({}, diffs)
-- No change case.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_INSERT, 'c'}},
diffs)
-- Merge equalities.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_EQUAL, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'abc'}}, diffs)
-- Merge deletions.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_DELETE, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}}, diffs)
-- Merge insertions.
diffs = {{DIFF_INSERT, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_INSERT, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_INSERT, 'abc'}}, diffs)
-- Merge interweave.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'b'}, {DIFF_DELETE, 'c'},
{DIFF_INSERT, 'd'}, {DIFF_EQUAL, 'e'}, {DIFF_EQUAL, 'f'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'ac'}, {DIFF_INSERT, 'bd'}, {DIFF_EQUAL, 'ef'}},
diffs)
-- Prefix and suffix detection.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'}, {DIFF_DELETE, 'dc'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'd'},
{DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'c'}}, diffs)
-- Prefix and suffix detection with equalities.
diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'a'}, {DIFF_INSERT, 'abc'},
{DIFF_DELETE, 'dc'}, {DIFF_EQUAL, 'y'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'd'},
{DIFF_INSERT, 'b'}, {DIFF_EQUAL, 'cy'}}, diffs)
-- Slide edit left.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_INSERT, 'ba'}, {DIFF_EQUAL, 'c'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'ac'}}, diffs)
-- Slide edit right.
diffs = {{DIFF_EQUAL, 'c'}, {DIFF_INSERT, 'ab'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'ca'}, {DIFF_INSERT, 'ba'}}, diffs)
-- Slide edit left recursive.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'c'},
{DIFF_DELETE, 'ac'}, {DIFF_EQUAL, 'x'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'acx'}}, diffs)
-- Slide edit right recursive.
diffs = {{DIFF_EQUAL, 'x'}, {DIFF_DELETE, 'ca'}, {DIFF_EQUAL, 'c'},
{DIFF_DELETE, 'b'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupMerge(diffs)
assertEquivalent({{DIFF_EQUAL, 'xca'}, {DIFF_DELETE, 'cba'}}, diffs)
end
function testDiffCleanupSemanticLossless()
-- Slide diffs to match logical boundaries.
-- Null case.
local diffs = {}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({}, diffs)
-- Blank lines.
diffs = {{DIFF_EQUAL, 'AAA\r\n\r\nBBB'}, {DIFF_INSERT, '\r\nDDD\r\n\r\nBBB'},
{DIFF_EQUAL, '\r\nEEE'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'AAA\r\n\r\n'},
{DIFF_INSERT, 'BBB\r\nDDD\r\n\r\n'}, {DIFF_EQUAL, 'BBB\r\nEEE'}}, diffs)
-- Line boundaries.
diffs = {{DIFF_EQUAL, 'AAA\r\nBBB'}, {DIFF_INSERT, ' DDD\r\nBBB'},
{DIFF_EQUAL, ' EEE'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'AAA\r\n'}, {DIFF_INSERT, 'BBB DDD\r\n'},
{DIFF_EQUAL, 'BBB EEE'}}, diffs)
-- Word boundaries.
diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_INSERT, 'ow and the c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_INSERT, 'cow and the '},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- Alphanumeric boundaries.
diffs = {{DIFF_EQUAL, 'The-c'}, {DIFF_INSERT, 'ow-and-the-c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The-'}, {DIFF_INSERT, 'cow-and-the-'},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- Hitting the start.
diffs = {{DIFF_EQUAL, 'a'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'ax'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'aax'}}, diffs)
-- Hitting the end.
diffs = {{DIFF_EQUAL, 'xa'}, {DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'a'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'xaa'}, {DIFF_DELETE, 'a'}}, diffs)
-- Sentence boundaries.
diffs = {{DIFF_EQUAL, 'The xxx. The '}, {DIFF_INSERT, 'zzz. The '},
{DIFF_EQUAL, 'yyy.'}}
dmp.diff_cleanupSemanticLossless(diffs)
assertEquivalent({{DIFF_EQUAL, 'The xxx.'}, {DIFF_INSERT, ' The zzz.'},
{DIFF_EQUAL, ' The yyy.'}}, diffs)
end
function testDiffCleanupSemantic()
-- Cleanup semantically trivial equalities.
-- Null case.
local diffs = {}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({}, diffs)
-- No elimination #1.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'},
{DIFF_DELETE, 'e'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, 'cd'}, {DIFF_EQUAL, '12'},
{DIFF_DELETE, 'e'}}, diffs)
-- No elimination #2.
diffs = {{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'},
{DIFF_DELETE, 'wxyz'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'ABC'}, {DIFF_EQUAL, '1234'},
{DIFF_DELETE, 'wxyz'}}, diffs)
-- Simple elimination.
diffs = {{DIFF_DELETE, 'a'}, {DIFF_EQUAL, 'b'}, {DIFF_DELETE, 'c'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_INSERT, 'b'}}, diffs)
-- Backpass elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_EQUAL, 'cd'}, {DIFF_DELETE, 'e'},
{DIFF_EQUAL, 'f'}, {DIFF_INSERT, 'g'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcdef'}, {DIFF_INSERT, 'cdfg'}}, diffs)
-- Multiple eliminations.
diffs = {{DIFF_INSERT, '1'}, {DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'},
{DIFF_INSERT, '2'}, {DIFF_EQUAL, '_'}, {DIFF_INSERT, '1'},
{DIFF_EQUAL, 'A'}, {DIFF_DELETE, 'B'}, {DIFF_INSERT, '2'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'AB_AB'}, {DIFF_INSERT, '1A2_1A2'}}, diffs)
-- Word boundaries.
diffs = {{DIFF_EQUAL, 'The c'}, {DIFF_DELETE, 'ow and the c'},
{DIFF_EQUAL, 'at.'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_EQUAL, 'The '}, {DIFF_DELETE, 'cow and the '},
{DIFF_EQUAL, 'cat.'}}, diffs)
-- No overlap elimination.
diffs = {{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcxx'}, {DIFF_INSERT, 'xxdef'}}, diffs)
-- Overlap elimination.
diffs = {{DIFF_DELETE, 'abcxxx'}, {DIFF_INSERT, 'xxxdef'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abc'}, {DIFF_EQUAL, 'xxx'}, {DIFF_INSERT, 'def'}}, diffs)
-- Reverse overlap elimination.
diffs = {{DIFF_DELETE, 'xxxabc'}, {DIFF_INSERT, 'defxxx'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_INSERT, 'def'}, {DIFF_EQUAL, 'xxx'}, {DIFF_DELETE, 'abc'}}, diffs)
-- Two overlap eliminations.
diffs = {{DIFF_DELETE, 'abcd1212'}, {DIFF_INSERT, '1212efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A3'}, {DIFF_INSERT, '3BC'}}
dmp.diff_cleanupSemantic(diffs)
assertEquivalent({{DIFF_DELETE, 'abcd'}, {DIFF_EQUAL, '1212'}, {DIFF_INSERT, 'efghi'}, {DIFF_EQUAL, '----'}, {DIFF_DELETE, 'A'}, {DIFF_EQUAL, '3'}, {DIFF_INSERT, 'BC'}}, diffs)
end
function testDiffCleanupEfficiency()
-- Cleanup operationally trivial equalities.
local diffs
dmp.settings{Diff_EditCost = 4}
-- Null case.
diffs = {}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({}, diffs)
-- No elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'wxyz'},
{DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'},
{DIFF_EQUAL, 'wxyz'}, {DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}, diffs)
-- Four-edit elimination.
diffs = {{DIFF_DELETE, 'ab'}, {DIFF_INSERT, '12'}, {DIFF_EQUAL, 'xyz'},
{DIFF_DELETE, 'cd'}, {DIFF_INSERT, '34'}}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abxyzcd'},
{DIFF_INSERT, '12xyz34'}
}, diffs)
-- Three-edit elimination.
diffs = {
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'x'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '34'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'xcd'},
{DIFF_INSERT, '12x34'}
}, diffs)
-- Backpass elimination.
diffs = {
{DIFF_DELETE, 'ab'},
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'xy'},
{DIFF_INSERT, '34'},
{DIFF_EQUAL, 'z'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '56'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abxyzcd'},
{DIFF_INSERT, '12xy34z56'}
}, diffs)
-- High cost elimination.
dmp.settings{Diff_EditCost = 5}
diffs = {
{DIFF_DELETE, 'ab'},
{DIFF_INSERT, '12'},
{DIFF_EQUAL, 'wxyz'},
{DIFF_DELETE, 'cd'},
{DIFF_INSERT, '34'}
}
dmp.diff_cleanupEfficiency(diffs)
assertEquivalent({
{DIFF_DELETE, 'abwxyzcd'},
{DIFF_INSERT, '12wxyz34'}
}, diffs)
dmp.settings{Diff_EditCost = 4}
end
function testDiffPrettyHtml()
-- Pretty print.
local diffs = {
{DIFF_EQUAL, 'a\n'},
{DIFF_DELETE, '<B>b</B>'},
{DIFF_INSERT, 'c&d'}
}
assertEquals(
'<span>a¶<br></span>'
.. '<del style="background:#ffe6e6;"><B>b</B>'
.. '</del><ins style="background:#e6ffe6;">c&d</ins>',
dmp.diff_prettyHtml(diffs)
)
end
function testDiffText()
-- Compute the source and destination texts.
local diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, ' lazy'}
}
assertEquals('jumps over the lazy', dmp.diff_text1(diffs))
assertEquals('jumped over a lazy', dmp.diff_text2(diffs))
end
function testDiffDelta()
-- Convert a diff into delta string.
local diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, ' lazy'},
{DIFF_INSERT, 'old dog'}
}
local text1 = dmp.diff_text1(diffs)
assertEquals('jumps over the lazy', text1)
local delta = dmp.diff_toDelta(diffs)
assertEquals('=4\t-1\t+ed\t=6\t-3\t+a\t=5\t+old dog', delta)
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta))
-- Generates error (19 ~= 20).
success, result = pcall(dmp.diff_fromDelta, text1 .. 'x', delta)
assertEquals(false, success)
-- Generates error (19 ~= 18).
success, result = pcall(dmp.diff_fromDelta, string.sub(text1, 2), delta)
assertEquals(false, success)
-- Generates error (%c3%xy invalid Unicode).
success, result = pcall(dmp.patch_fromDelta, '', '+%c3%xy')
assertEquals(false, success)
--[[
-- Test deltas with special characters.
-- LUANOTE: No ability to handle Unicode.
diffs = {{DIFF_EQUAL, '\u0680 \000 \t %'}, {DIFF_DELETE, '\u0681 \x01 \n ^'}, {DIFF_INSERT, '\u0682 \x02 \\ |'}}
text1 = dmp.diff_text1(diffs)
assertEquals('\u0680 \x00 \t %\u0681 \x01 \n ^', text1)
delta = dmp.diff_toDelta(diffs)
assertEquals('=7\t-7\t+%DA%82 %02 %5C %7C', delta)
--]]
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta(text1, delta))
-- Verify pool of unchanged characters.
diffs = {
{DIFF_INSERT, 'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # '}
}
local text2 = dmp.diff_text2(diffs)
assertEquals(
'A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ',
text2
)
delta = dmp.diff_toDelta(diffs)
assertEquals(
'+A-Z a-z 0-9 - _ . ! ~ * \' ( ) ; / ? = @ & = + $ , # ',
delta
)
-- Convert delta string into a diff.
assertEquivalent(diffs, dmp.diff_fromDelta('', delta))
end
function testDiffXIndex()
-- Translate a location in text1 to text2.
-- Translation on equality.
assertEquals(6, dmp.diff_xIndex({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, '1234'},
{DIFF_EQUAL, 'xyz'}
}, 3))
-- Translation on deletion.
assertEquals(2, dmp.diff_xIndex({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '1234'},
{DIFF_EQUAL, 'xyz'}
}, 4))
end
function testDiffLevenshtein()
-- Levenshtein with trailing equality.
assertEquals(4, dmp.diff_levenshtein({
{DIFF_DELETE, 'abc'},
{DIFF_INSERT, '1234'},
{DIFF_EQUAL, 'xyz'}
}))
-- Levenshtein with leading equality.
assertEquals(4, dmp.diff_levenshtein({
{DIFF_EQUAL, 'xyz'},
{DIFF_DELETE, 'abc'},
{DIFF_INSERT, '1234'}
}))
-- Levenshtein with middle equality.
assertEquals(7, dmp.diff_levenshtein({
{DIFF_DELETE, 'abc'},
{DIFF_EQUAL, 'xyz'},
{DIFF_INSERT, '1234'}
}))
end
function testDiffBisect()
-- Normal.
local a = 'cat'
local b = 'map'
-- Since the resulting diff hasn't been normalized, it would be ok if
-- the insertion and deletion pairs are swapped.
-- If the order changes, tweak this test as required.
assertEquivalent({
{DIFF_DELETE, 'c'},
{DIFF_INSERT, 'm'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, 't'},
{DIFF_INSERT, 'p'}
}, dmp.diff_bisect(a, b, 2 ^ 31))
-- Timeout.
assertEquivalent({
{DIFF_DELETE, 'cat'},
{DIFF_INSERT, 'map'}
}, dmp.diff_bisect(a, b, 0))
end
function testDiffMain()
-- Perform a trivial diff.
local a,b
-- Null case.
assertEquivalent({}, dmp.diff_main('', '', false))
-- Equality.
assertEquivalent({
{DIFF_EQUAL, 'abc'}
}, dmp.diff_main('abc', 'abc', false))
-- Simple insertion.
assertEquivalent({
{DIFF_EQUAL, 'ab'},
{DIFF_INSERT, '123'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('abc', 'ab123c', false))
-- Simple deletion.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '123'},
{DIFF_EQUAL, 'bc'}
}, dmp.diff_main('a123bc', 'abc', false))
-- Two insertions.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_INSERT, '123'},
{DIFF_EQUAL, 'b'},
{DIFF_INSERT, '456'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('abc', 'a123b456c', false))
-- Two deletions.
assertEquivalent({
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '123'},
{DIFF_EQUAL, 'b'},
{DIFF_DELETE, '456'},
{DIFF_EQUAL, 'c'}
}, dmp.diff_main('a123b456c', 'abc', false))
-- Perform a real diff.
-- Switch off the timeout.
dmp.settings{ Diff_Timeout=0 }
-- Simple cases.
assertEquivalent({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, 'b'}
}, dmp.diff_main('a', 'b', false))
assertEquivalent({
{DIFF_DELETE, 'Apple'},
{DIFF_INSERT, 'Banana'},
{DIFF_EQUAL, 's are a'},
{DIFF_INSERT, 'lso'},
{DIFF_EQUAL, ' fruit.'}
}, dmp.diff_main('Apples are a fruit.', 'Bananas are also fruit.', false))
--[[
-- LUANOTE: No ability to handle Unicode.
assertEquivalent({
{DIFF_DELETE, 'a'},
{DIFF_INSERT, '\u0680'},
{DIFF_EQUAL, 'x'},
{DIFF_DELETE, '\t'},
{DIFF_INSERT, '\0'}
}, dmp.diff_main('ax\t', '\u0680x\0', false))
]]--
-- Overlaps.
assertEquivalent({
{DIFF_DELETE, '1'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, 'y'},
{DIFF_EQUAL, 'b'},
{DIFF_DELETE, '2'},
{DIFF_INSERT, 'xab'}
}, dmp.diff_main('1ayb2', 'abxab', false))
assertEquivalent({
{DIFF_INSERT, 'xaxcx'},
{DIFF_EQUAL, 'abc'},
{DIFF_DELETE, 'y'}
}, dmp.diff_main('abcy', 'xaxcxabc', false))
assertEquivalent({
{DIFF_DELETE, 'ABCD'},
{DIFF_EQUAL, 'a'},
{DIFF_DELETE, '='},
{DIFF_INSERT, '-'},
{DIFF_EQUAL, 'bcd'},
{DIFF_DELETE, '='},
{DIFF_INSERT, '-'},
{DIFF_EQUAL, 'efghijklmnopqrs'},
{DIFF_DELETE, 'EFGHIJKLMNOefg'}
}, dmp.diff_main('ABCDa=bcd=efghijklmnopqrsEFGHIJKLMNOefg',
'a-bcd-efghijklmnopqrs', false))
-- Large equality.
assertEquivalent({
{DIFF_INSERT, ' '},
{DIFF_EQUAL, 'a'},
{DIFF_INSERT, 'nd'},
{DIFF_EQUAL, ' [[Pennsylvania]]'},
{DIFF_DELETE, ' and [[New'}
}, dmp.diff_main('a [[Pennsylvania]] and [[New',
' and [[Pennsylvania]]', false))
-- Timeout.
dmp.settings{Diff_Timeout = 0.1} -- 100ms
-- Increase the text lengths by 1024 times to ensure a timeout.
a = string.rep([[
`Twas brillig, and the slithy toves
Did gyre and gimble in the wabe:
All mimsy were the borogoves,
And the mome raths outgrabe.
]], 1024)
b = string.rep([[
I am the very model of a modern major general,
I've information vegetable, animal, and mineral,
I know the kings of England, and I quote the fights historical,
From Marathon to Waterloo, in order categorical.
]], 1024)
local startTime = os.clock()
dmp.diff_main(a, b)
local endTime = os.clock()
-- Test that we took at least the timeout period.
assertTrue(0.1 <= endTime - startTime)
-- Test that we didn't take forever (be forgiving).
-- Theoretically this test could fail very occasionally if the
-- OS task swaps or locks up for a second at the wrong moment.
assertTrue(0.1 * 2 > endTime - startTime)
dmp.settings{Diff_Timeout = 0}
-- Test the linemode speedup.
-- Must be long to pass the 100 char cutoff.
-- Simple line-mode.
a = string.rep('1234567890\n', 13)
b = string.rep('abcdefghij\n', 13)
assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true))
-- Single line-mode.
a = string.rep('1234567890', 13)
b = string.rep('abcdefghij', 13)
assertEquivalent(dmp.diff_main(a, b, false), dmp.diff_main(a, b, true))
-- Overlap line-mode.
a = string.rep('1234567890\n', 13)
b = [[
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
1234567890
1234567890
1234567890
abcdefghij
]]
local texts_linemode = diff_rebuildtexts(dmp.diff_main(a, b, true))
local texts_textmode = diff_rebuildtexts(dmp.diff_main(a, b, false))
assertEquivalent(texts_textmode, texts_linemode)
-- Test null inputs.
success, result = pcall(dmp.diff_main, nil, nil)
assertEquals(false, success)
end
-- MATCH TEST FUNCTIONS
function testMatchAlphabet()
-- Initialise the bitmasks for Bitap.
-- Unique.
assertEquivalent({a=4, b=2, c=1}, dmp.match_alphabet('abc'))
-- Duplicates.
assertEquivalent({a=37, b=18, c=8}, dmp.match_alphabet('abcaba'))
end
function testMatchBitap()
-- Bitap algorithm.
dmp.settings{Match_Distance=100, Match_Threshold=0.5}
-- Exact matches.
assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 6))
assertEquals(6, dmp.match_bitap('abcdefghijk', 'fgh', 1))
-- Fuzzy matches.
assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxhi', 1))
assertEquals(3, dmp.match_bitap('abcdefghijk', 'cdefxyhijk', 6))
assertEquals(-1, dmp.match_bitap('abcdefghijk', 'bxy', 2))
-- Overflow.
assertEquals(3, dmp.match_bitap('123456789xx0', '3456789x0', 3))
-- Threshold test.
dmp.settings{Match_Threshold = 0.4}
assertEquals(5, dmp.match_bitap('abcdefghijk', 'efxyhi', 2))
dmp.settings{Match_Threshold = 0.3}
assertEquals(-1, dmp.match_bitap('abcdefghijk', 'efxyhi', 2))
dmp.settings{Match_Threshold = 0.0}
assertEquals(2, dmp.match_bitap('abcdefghijk', 'bcdef', 2))
dmp.settings{Match_Threshold = 0.5}
-- Multiple select.
assertEquals(1, dmp.match_bitap('abcdexyzabcde', 'abccde', 4))
assertEquals(9, dmp.match_bitap('abcdexyzabcde', 'abccde', 6))
-- Distance test.
dmp.settings{Match_Distance = 10} -- Strict location.
assertEquals(-1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25))
assertEquals(1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdxxefg', 2))
dmp.settings{Match_Distance = 1000} -- Loose location.
assertEquals(1,
dmp.match_bitap('abcdefghijklmnopqrstuvwxyz', 'abcdefg', 25))
end
function testMatchMain()
-- Full match.
-- Shortcut matches.
assertEquals(1, dmp.match_main('abcdef', 'abcdef', 1000))
assertEquals(-1, dmp.match_main('', 'abcdef', 2))
assertEquals(4, dmp.match_main('abcdef', '', 4))
assertEquals(4, dmp.match_main('abcdef', 'de', 4))
-- Beyond end match.
assertEquals(4, dmp.match_main("abcdef", "defy", 5))
-- Oversized pattern.
assertEquals(1, dmp.match_main("abcdef", "abcdefy", 1))
-- Complex match.
assertEquals(5, dmp.match_main(
'I am the very model of a modern major general.',
' that berry ',
6
))
-- Test null inputs.
success, result = pcall(dmp.match_main, nil, nil, 0)
assertEquals(false, success)
end
-- PATCH TEST FUNCTIONS
function testPatchObj()
-- Patch Object.
local p = dmp.new_patch_obj()
p.start1 = 21
p.start2 = 22
p.length1 = 18
p.length2 = 17
p.diffs = {
{DIFF_EQUAL, 'jump'},
{DIFF_DELETE, 's'},
{DIFF_INSERT, 'ed'},
{DIFF_EQUAL, ' over '},
{DIFF_DELETE, 'the'},
{DIFF_INSERT, 'a'},
{DIFF_EQUAL, '\nlaz'}
}
local strp = tostring(p)
assertEquals(
'@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n',
strp
)
end
function testPatchFromText()
local strp
strp = ''
assertEquivalent({}, dmp.patch_fromText(strp))
strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n %0Alaz\n'
assertEquals(strp, tostring(dmp.patch_fromText(strp)[1]))
assertEquals(
'@@ -1 +1 @@\n-a\n+b\n',
tostring(dmp.patch_fromText('@@ -1 +1 @@\n-a\n+b\n')[1])
)
assertEquals(
'@@ -1,3 +0,0 @@\n-abc\n',
tostring(dmp.patch_fromText('@@ -1,3 +0,0 @@\n-abc\n')[1])
)
assertEquals(
'@@ -0,0 +1,3 @@\n+abc\n',
tostring(dmp.patch_fromText('@@ -0,0 +1,3 @@\n+abc\n')[1])
)
-- Generates error.
success, result = pcall(dmp.patch_fromText, 'Bad\nPatch\n')
assertEquals(false, success)
end
function testPatchToText()
local strp, p
strp = '@@ -21,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'
p = dmp.patch_fromText(strp)
assertEquals(strp, dmp.patch_toText(p))
strp = '@@ -1,9 +1,9 @@\n-f\n+F\n oo+fooba\n'
.. '@@ -7,9 +7,9 @@\n obar\n-,\n+.\n tes\n'
p = dmp.patch_fromText(strp)
assertEquals(strp, dmp.patch_toText(p))
end
function testPatchAddContext()
local p
dmp.settings{Patch_Margin = 4}
p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps over the lazy dog.')
assertEquals(
'@@ -17,12 +17,18 @@\n fox \n-jump\n+somersault\n s ov\n',
tostring(p)
)
-- Same, but not enough trailing context.
p = dmp.patch_fromText('@@ -21,4 +21,10 @@\n-jump\n+somersault\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps.')
assertEquals(
'@@ -17,10 +17,16 @@\n fox \n-jump\n+somersault\n s.\n',
tostring(p)
)
-- Same, but not enough leading context.
p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps.')
assertEquals('@@ -1,7 +1,8 @@\n Th\n-e\n+at\n qui\n', tostring(p))
-- Same, but with ambiguity.
p = dmp.patch_fromText('@@ -3 +3,2 @@\n-e\n+at\n')[1]
dmp.patch_addContext(p, 'The quick brown fox jumps. The quick brown fox crashes.')
assertEquals('@@ -1,27 +1,28 @@\n Th\n-e\n+at\n quick brown fox jumps. \n', tostring(p))
end
function testPatchMake()
-- Null case.
local patches = dmp.patch_make('', '')
assertEquals('', dmp.patch_toText(patches))
local text1 = 'The quick brown fox jumps over the lazy dog.'
local text2 = 'That quick brown fox jumped over a lazy dog.'
-- Text2+Text1 inputs.
local expectedPatch = '@@ -1,8 +1,7 @@\n Th\n-at\n+e\n qui\n'
.. '@@ -21,17 +21,18 @@\n jump\n-ed\n+s\n over \n-a\n+the\n laz\n'
-- The second patch must be "-21,17 +21,18",
-- not "-22,17 +21,18" due to rolling context.
patches = dmp.patch_make(text2, text1)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Text2 inputs.
expectedPatch = '@@ -1,11 +1,12 @@\n Th\n-e\n+at\n quick b\n'
.. '@@ -22,18 +22,17 @@\n jump\n-s\n+ed\n over \n-the\n+a\n laz\n'
patches = dmp.patch_make(text1, text2)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Diff input.
local diffs = dmp.diff_main(text1, text2, false)
patches = dmp.patch_make(diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Diff inputs.
patches = dmp.patch_make(text1, diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Text1+Text2+Diff inputs (deprecated).
patches = dmp.patch_make(text1, text2, diffs)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Character encoding.
patches = dmp.patch_make('`1234567890-=[]\\;\',./', '~!@#$%^&*()_+{}|="<>?')
assertEquals('@@ -1,21 +1,21 @@\n'
.. '-%601234567890-=%5B%5D%5C;\',./\n'
.. '+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n', dmp.patch_toText(patches))
-- Character decoding.
diffs = {
{DIFF_DELETE, '`1234567890-=[]\\;\',./'},
{DIFF_INSERT, '~!@#$%^&*()_+{}|="<>?'}
}
assertEquivalent(diffs, dmp.patch_fromText(
'@@ -1,21 +1,21 @@'
.. '\n-%601234567890-=%5B%5D%5C;\',./'
.. '\n+~!@#$%25%5E&*()_+%7B%7D%7C=%22%3C%3E?\n'
)[1].diffs)
-- Long string with repeats.
text1 = string.rep('abcdef', 100)
text2 = text1 .. '123'
expectedPatch = '@@ -573,28 +573,31 @@\n'
.. ' cdefabcdefabcdefabcdefabcdef\n+123\n'
patches = dmp.patch_make(text1, text2)
assertEquals(expectedPatch, dmp.patch_toText(patches))
-- Test null inputs.
success, result = pcall(dmp.patch_make, nil, nil)
assertEquals(false, success)
end
function testPatchSplitMax()
-- Assumes that dmp.Match_MaxBits is 32.
local patches = dmp.patch_make('abcdefghijklmnopqrstuvwxyz01234567890',
'XabXcdXefXghXijXklXmnXopXqrXstXuvXwxXyzX01X23X45X67X89X0')
dmp.patch_splitMax(patches)
assertEquals('@@ -1,32 +1,46 @@\n+X\n ab\n+X\n cd\n+X\n ef\n+X\n gh\n+X\n ij\n+X\n kl\n+X\n mn\n+X\n op\n+X\n qr\n+X\n st\n+X\n uv\n+X\n wx\n+X\n yz\n+X\n 012345\n@@ -25,13 +39,18 @@\n zX01\n+X\n 23\n+X\n 45\n+X\n 67\n+X\n 89\n+X\n 0\n', dmp.patch_toText(patches))
patches = dmp.patch_make('abcdef1234567890123456789012345678901234567890123456789012345678901234567890uvwxyz', 'abcdefuvwxyz')
local oldToText = dmp.patch_toText(patches)
dmp.patch_splitMax(patches)
assertEquals(oldToText, dmp.patch_toText(patches))
patches = dmp.patch_make('1234567890123456789012345678901234567890123456789012345678901234567890', 'abc')
dmp.patch_splitMax(patches)
assertEquals('@@ -1,32 +1,4 @@\n-1234567890123456789012345678\n 9012\n@@ -29,32 +1,4 @@\n-9012345678901234567890123456\n 7890\n@@ -57,14 +1,3 @@\n-78901234567890\n+abc\n', dmp.patch_toText(patches))
patches = dmp.patch_make('abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1 abcdefghij , h = 0 , t = 1', 'abcdefghij , h = 1 , t = 1 abcdefghij , h = 1 , t = 1 abcdefghij , h = 0 , t = 1')
dmp.patch_splitMax(patches)
assertEquals('@@ -2,32 +2,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n@@ -29,32 +29,32 @@\n bcdefghij , h = \n-0\n+1\n , t = 1 abcdef\n', dmp.patch_toText(patches))
end
function testPatchAddPadding()
-- Both edges full.
local patches = dmp.patch_make('', 'test')
assertEquals('@@ -0,0 +1,4 @@\n+test\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -1,8 +1,12 @@\n %01%02%03%04\n+test\n %01%02%03%04\n', dmp.patch_toText(patches))
-- Both edges partial.
patches = dmp.patch_make('XY', 'XtestY')
assertEquals('@@ -1,2 +1,6 @@\n X\n+test\n Y\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -2,8 +2,12 @@\n %02%03%04X\n+test\n Y%01%02%03\n', dmp.patch_toText(patches))
-- Both edges none.
patches = dmp.patch_make('XXXXYYYY', 'XXXXtestYYYY')
assertEquals('@@ -1,8 +1,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches))
dmp.patch_addPadding(patches)
assertEquals('@@ -5,8 +5,12 @@\n XXXX\n+test\n YYYY\n', dmp.patch_toText(patches))
end
function testPatchApply()
local patches
dmp.settings{Match_Distance = 1000}
dmp.settings{Match_Threshold = 0.5}
dmp.settings{Patch_DeleteThreshold = 0.5}
-- Null case.
patches = dmp.patch_make('', '')
assertEquivalent({'Hello world.', {}},
{dmp.patch_apply(patches, 'Hello world.')})
-- Exact match.
patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.',
'That quick brown fox jumped over a lazy dog.')
assertEquivalent(
{'That quick brown fox jumped over a lazy dog.', {true, true}},
{dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')})
-- Partial match.
assertEquivalent(
{'That quick red rabbit jumped over a tired tiger.', {true, true}},
{dmp.patch_apply(patches, 'The quick red rabbit jumps over the tired tiger.')})
-- Failed match.
assertEquivalent(
{'I am the very model of a modern major general.', {false, false}},
{dmp.patch_apply(patches, 'I am the very model of a modern major general.')})
-- Big delete, small change.
patches = dmp.patch_make(
'x1234567890123456789012345678901234567890123456789012345678901234567890y',
'xabcy')
assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(patches,
'x123456789012345678901234567890-----++++++++++-----'
.. '123456789012345678901234567890y')})
-- Big delete, big change 1.
patches = dmp.patch_make('x1234567890123456789012345678901234567890123456789'
.. '012345678901234567890y', 'xabcy')
assertEquivalent({'xabc12345678901234567890'
.. '---------------++++++++++---------------'
.. '12345678901234567890y', {false, true}},
{dmp.patch_apply(patches, 'x12345678901234567890'
.. '---------------++++++++++---------------'
.. '12345678901234567890y'
)})
-- Big delete, big change 2.
dmp.settings{Patch_DeleteThreshold = 0.6}
patches = dmp.patch_make(
'x1234567890123456789012345678901234567890123456789'
.. '012345678901234567890y',
'xabcy'
)
assertEquivalent({'xabcy', {true, true}}, {dmp.patch_apply(
patches,
'x12345678901234567890---------------++++++++++---------------'
.. '12345678901234567890y'
)}
)
dmp.settings{Patch_DeleteThreshold = 0.5}
-- Compensate for failed patch.
dmp.settings{Match_Threshold = 0, Match_Distance = 0}
patches = dmp.patch_make(
'abcdefghijklmnopqrstuvwxyz--------------------1234567890',
'abcXXXXXXXXXXdefghijklmnopqrstuvwxyz--------------------'
.. '1234567YYYYYYYYYY890'
)
assertEquivalent({
'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567YYYYYYYYYY890',
{false, true}
}, {dmp.patch_apply(
patches,
'ABCDEFGHIJKLMNOPQRSTUVWXYZ--------------------1234567890'
)})
dmp.settings{Match_Threshold = 0.5}
dmp.settings{Match_Distance = 1000}
-- No side effects.
patches = dmp.patch_make('', 'test')
local patchstr = dmp.patch_toText(patches)
dmp.patch_apply(patches, '')
assertEquals(patchstr, dmp.patch_toText(patches))
-- No side effects with major delete.
patches = dmp.patch_make('The quick brown fox jumps over the lazy dog.',
'Woof')
patchstr = dmp.patch_toText(patches)
dmp.patch_apply(patches, 'The quick brown fox jumps over the lazy dog.')
assertEquals(patchstr, dmp.patch_toText(patches))
-- Edge exact match.
patches = dmp.patch_make('', 'test')
assertEquivalent({'test', {true}}, {dmp.patch_apply(patches, '')})
-- Near edge exact match.
patches = dmp.patch_make('XY', 'XtestY')
assertEquivalent({'XtestY', {true}}, {dmp.patch_apply(patches, 'XY')})
-- Edge partial match.
patches = dmp.patch_make('y', 'y123')
assertEquivalent({'x123', {true}}, {dmp.patch_apply(patches, 'x')})
end
function runTests()
local passed = 0
local failed = 0
for name, func in pairs(_G) do
if (type(func) == 'function') and tostring(name):match("^test") then
local success, message = pcall(func)
if success then
print(name .. ' Ok.')
passed = passed + 1
else
print('** ' .. name .. ' FAILED: ' .. tostring(message))
failed = failed + 1
end
end
end
print('Tests passed: ' .. passed)
print('Tests failed: ' .. failed)
if failed ~= 0 then
os.exit(1)
end
end
runTests()
| apache-2.0 |
robertbrook/lib | pl/MultiMap.lua | 36 | 1458 | --- MultiMap, a Map which has multiple values per key.
--
-- Dependencies: `pl.utils`, `pl.class`, `pl.tablex`, `pl.List`
-- @classmod pl.MultiMap
local classes = require 'pl.class'
local tablex = require 'pl.tablex'
local utils = require 'pl.utils'
local List = require 'pl.List'
local index_by,tsort,concat = tablex.index_by,table.sort,table.concat
local append,extend,slice = List.append,List.extend,List.slice
local append = table.insert
local class = require 'pl.class'
local Map = require 'pl.Map'
-- MultiMap is a standard MT
local MultiMap = utils.stdmt.MultiMap
class(Map,nil,MultiMap)
MultiMap._name = 'MultiMap'
function MultiMap:_init (t)
if not t then return end
self:update(t)
end
--- update a MultiMap using a table.
-- @param t either a Multimap or a map-like table.
-- @return the map
function MultiMap:update (t)
utils.assert_arg(1,t,'table')
if Map:class_of(t) then
for k,v in pairs(t) do
self[k] = List()
self[k]:append(v)
end
else
for k,v in pairs(t) do
self[k] = List(v)
end
end
end
--- add a new value to a key. Setting a nil value removes the key.
-- @param key the key
-- @param val the value
-- @return the map
function MultiMap:set (key,val)
if val == nil then
self[key] = nil
else
if not self[key] then
self[key] = List()
end
self[key]:append(val)
end
end
return MultiMap
| bsd-3-clause |
LuaDist2/util | util/warnself.lua | 4 | 2084 |
-- This module will check all function calls.
-- An error will be reported, when obj.method() call is used
-- instead of obj:method().
--
-- The checking makes things 2-times slower.
-- You can skip importing of this module when finished with development.
-- For example, import this module only when log level is set to debug.
-- Some functions have their first arg named "self",
-- even when not being proper methods.
-- We ignore these.
local IGNORED_FUNC = {
Storage__printformat=true,
Tensor__printMatrix=true,
Tensor__printTensor=true,
}
local function _getParent(obj)
local mt = getmetatable(obj)
if not mt or not mt.__index then
return nil
end
local parent = mt.__index
if type(parent) ~= "table" then
-- We don't know what keys to try with the mt.__index(obj, k) func.
-- As a fallback, we try to find the method on the metatable.
parent = mt
end
return parent
end
local function _findKeyByVal(obj, val)
for field, fieldVal in pairs(obj) do
if fieldVal == val then
return field
end
end
local parent = _getParent(obj)
if not parent then
return nil
end
return _findKeyByVal(parent, val)
end
-- Checks that var "self" refers to an object
-- with the called method.
local function onCallCheckSelf()
local var1Name, obj = debug.getlocal(2, 1)
if var1Name ~= "self" then
return
end
local lookup = obj
if type(obj) == "userdata" then
lookup = _getParent(obj)
end
if type(lookup) == "table" then
local func = debug.getinfo(2, "f").func
local field = _findKeyByVal(lookup, func)
if field then
-- OK. Found the method on the used object.
return
end
end
local info = debug.getinfo(2, "n")
if IGNORED_FUNC[info.name] then
return
end
local msg = string.format("wrong self for %s()", tostring(info.name))
error(msg, 3)
end
assert(debug.gethook() == nil, "another hook is active")
debug.sethook(onCallCheckSelf, "c")
| bsd-3-clause |
resistor58/deaths-gmod-server | wire/lua/entities/gmod_wire_data_transferer/init.lua | 1 | 4803 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "Data Transferer"
function ENT:Initialize()
self.Entity:PhysicsInit( SOLID_VPHYSICS )
self.Entity:SetMoveType( MOVETYPE_VPHYSICS )
self.Entity:SetSolid( SOLID_VPHYSICS )
self.Inputs = Wire_CreateInputs(self.Entity, {"Send","A","B","C","D","E","F","G","H"})
self.Outputs = Wire_CreateOutputs(self.Entity, {"A","B","C","D","E","F","G","H"})
self.Sending = false
self.Activated = false
self.ActivateTime = 0
self.DefaultZero = true
self.IgnoreZero = false
self.Values = {};
self.Values["A"] = 0
self.Values["B"] = 0
self.Values["C"] = 0
self.Values["D"] = 0
self.Values["E"] = 0
self.Values["F"] = 0
self.Values["G"] = 0
self.Values["H"] = 0
self:SetBeamRange(25000)
self:ShowOutput()
end
function ENT:Setup(Range,DefaultZero,IgnoreZero)
self.IgnoreZero = IgnoreZero
self.DefaultZero = DefaultZero
self:SetBeamRange(Range)
end
function ENT:OnRemove()
Wire_Remove(self.Entity)
end
function ENT:TriggerInput(iname, value)
if(iname == "Send")then
if(value > 0)then
self.Sending = true
else
self.Sending = false
end
else
self.Values[iname] = value
end
end
function ENT:Think()
if(self.Activated == false && self.DefaultZero)then
Wire_TriggerOutput(self.Entity,"A",0)
Wire_TriggerOutput(self.Entity,"B",0)
Wire_TriggerOutput(self.Entity,"C",0)
Wire_TriggerOutput(self.Entity,"D",0)
Wire_TriggerOutput(self.Entity,"E",0)
Wire_TriggerOutput(self.Entity,"F",0)
Wire_TriggerOutput(self.Entity,"G",0)
Wire_TriggerOutput(self.Entity,"H",0)
else
if(CurTime() > self.ActivateTime + 0.5)then
self.Activated = false
end
end
local vStart = self.Entity:GetPos()
local vForward = self.Entity:GetUp()
local trace = {}
trace.start = vStart
trace.endpos = vStart + (vForward * self:GetBeamRange())
trace.filter = { self.Entity }
local trace = util.TraceLine( trace )
local ent = trace.Entity
if not (ent && ent:IsValid() &&
(trace.Entity:GetClass() == "gmod_wire_data_transferer" ||
trace.Entity:GetClass() == "gmod_wire_data_satellitedish" ||
trace.Entity:GetClass() == "gmod_wire_data_store" ))then
if(Color(self.Entity:GetColor()) != Color(255,255,255,255))then
self.Entity:SetColor(255, 255, 255, 255)
end
return false
end
if(Color(self.Entity:GetColor()) != Color(0,255,0,255))then
self.Entity:SetColor(0, 255, 0, 255)
end
if(trace.Entity:GetClass() == "gmod_wire_data_transferer")then
ent:RecieveValue("A",self.Values.A)
ent:RecieveValue("B",self.Values.B)
ent:RecieveValue("C",self.Values.C)
ent:RecieveValue("D",self.Values.D)
ent:RecieveValue("E",self.Values.E)
ent:RecieveValue("F",self.Values.F)
ent:RecieveValue("G",self.Values.G)
ent:RecieveValue("H",self.Values.H)
elseif(trace.Entity:GetClass() == "gmod_wire_data_satellitedish")then
if(ent.Transmitter && ent.Transmitter:IsValid())then
ent.Transmitter:RecieveValue("A",self.Values.A)
ent.Transmitter:RecieveValue("B",self.Values.B)
ent.Transmitter:RecieveValue("C",self.Values.C)
ent.Transmitter:RecieveValue("D",self.Values.D)
ent.Transmitter:RecieveValue("E",self.Values.E)
ent.Transmitter:RecieveValue("F",self.Values.F)
ent.Transmitter:RecieveValue("G",self.Values.G)
ent.Transmitter:RecieveValue("H",self.Values.H)
else
self.Entity:SetColor(255, 0, 0, 255)
end
elseif(trace.Entity:GetClass() == "gmod_wire_data_store")then
Wire_TriggerOutput(self.Entity,"A",ent.Values.A)
Wire_TriggerOutput(self.Entity,"B",ent.Values.B)
Wire_TriggerOutput(self.Entity,"C",ent.Values.C)
Wire_TriggerOutput(self.Entity,"D",ent.Values.D)
Wire_TriggerOutput(self.Entity,"E",ent.Values.E)
Wire_TriggerOutput(self.Entity,"F",ent.Values.F)
Wire_TriggerOutput(self.Entity,"G",ent.Values.G)
Wire_TriggerOutput(self.Entity,"H",ent.Values.H)
if(self.Sending)then
ent.Values.A = self.Entity.Inputs["A"].Value
ent.Values.B = self.Entity.Inputs["B"].Value
ent.Values.C = self.Entity.Inputs["C"].Value
ent.Values.D = self.Entity.Inputs["D"].Value
ent.Values.E = self.Entity.Inputs["E"].Value
ent.Values.F = self.Entity.Inputs["F"].Value
ent.Values.G = self.Entity.Inputs["G"].Value
ent.Values.H = self.Entity.Inputs["H"].Value
end
end
self.Entity:NextThink(CurTime()+0.125)
end
function ENT:ShowOutput()
self:SetOverlayText( "Data Transferer" )
end
function ENT:OnRestore()
Wire_Restored(self.Entity)
end
function ENT:RecieveValue(output,value)
self.Activated = true
self.ActivateTime = CurTime()
if value ~= 0 or not self.IgnoreZero then
Wire_TriggerOutput(self.Entity,output,value)
end
end
| gpl-3.0 |
milos-korenciak/heroku-buildpack-tex | buildpack/texmf-dist/tex/generic/pgf/graphdrawing/lua/pgf/gd/tools/make_gd_wrap.lua | 3 | 4929 | -- Copyright 2012 by Till Tantau
--
-- This file may be distributed an/or modified
--
-- 1. under the LaTeX Project Public License and/or
-- 2. under the GNU Public License
--
-- See the file doc/generic/pgf/licenses/LICENSE for more information
-- @release $Header: /cvsroot/pgf/pgf/generic/pgf/graphdrawing/lua/pgf/gd/tools/make_gd_wrap.lua,v 1.2 2013/01/01 17:10:09 tantau Exp $
---
-- This program generates a C wrap file around graph drawing
-- algorithms. The idea is that when you have a graph drawing
-- algorithm implemented in C and wish to invoke it from Lua, you need
-- a wrapper that manages the translation between Lua and C. This
-- program is intended to make it (reasonably) easy to produce such a
-- wraper.
-- Sufficient number of arguments?
if #arg < 4 or arg[1] == "-h" or arg[1] == "-?" or arg[1] == "--help" then
print([["
Usage: make_gd_wrap library1 library2 ... libraryn template library_name target_c_file
This program will read all of the graph drawing library files using
Lua's require. Then, it will iterate over all declared algorithm keys
(declared using declare { algorithm_written_in_c = ... }) and will
produce the code for library for the required target C files based on
the template.
"]])
os.exit()
end
-- Imports
local InterfaceToDisplay = require "pgf.gd.interface.InterfaceToDisplay"
local InterfaceCore = require "pgf.gd.interface.InterfaceCore"
-- Ok, setup:
InterfaceToDisplay.bind(require "pgf.gd.bindings.Binding")
-- Now, read all libraries:
for i=1,#arg-3 do
require(arg[i])
end
-- Now, read the template:
local file = io.open(arg[#arg-2])
local template = file:read("*a")
file:close()
-- Let us grab the declaration:
local functions_dec = (template:match("%$functions(%b{})") or ""):match("^{(.*)}$")
local functions_reg_dec = (template:match("%$functions_registry(%b{})") or ""):match("^{(.*)}$")
local factories_dec = (template:match("%$factories(%b{})") or ""):match("^{(.*)}$")
local factories_reg_dec = (template:match("%$factories_registry(%b{})") or ""):match("^{(.*)}$")
-- Now, handle all keys with a algorithm_written_in_c field
local keys = InterfaceCore.keys
local filename = arg[#arg]
local target = arg[#arg-1]
local includes = {}
local functions = {}
local functions_registry = {}
local factories = {}
local factories_reg = {}
for _,k in ipairs(keys) do
if k.algorithm_written_in_c and k.code then
local library, fun_name = k.algorithm_written_in_c:match("(.*)%.(.*)")
if target == library then
-- First, gather the includes:
if type(k.includes) == "string" then
if not includes[k.includes] then
includes[#includes + 1] = k.includes
includes[k.includes] = true
end
elseif type(k.includes) == "table" then
for _,i in ipairs(k.includes) do
if not includes[i] then
includes[#includes + 1] = i
includes[i] = true
end
end
end
-- Second, create a code block:
functions[#functions+1] = functions_dec:gsub("%$([%w_]-)%b{}",
{
function_name = fun_name,
function_body = k.code
})
-- Third, create functions_registry entry
functions_registry[#functions_registry + 1] = functions_reg_dec:gsub("%$([%w_]-)%b{}",
{
function_name = fun_name,
function_body = k.code
})
end
end
if k.module_class then
-- First, gather the includes:
if type(k.includes) == "string" then
if not includes[k.includes] then
includes[#includes + 1] = k.includes
includes[k.includes] = true
end
elseif type(k.includes) == "table" then
for _,i in ipairs(k.includes) do
if not includes[i] then
includes[#includes + 1] = i
includes[i] = true
end
end
end
-- Second, create a code block:
factories[#factories+1] = factories_dec:gsub(
"%$([%w_]-)%b{}",
{
factory_class = k.module_class,
factory_code = k.code,
factory_base = k.module_base,
factory_name = k.module_class .. '_factory'
})
-- Third, create factories_registry entry
factories_reg[#factories_reg + 1] = factories_reg_dec:gsub(
"%$([%w_]-)%b{}",
{
factory_class = k.module_class,
factory_code = k.code,
factory_base = k.module_base,
factory_name = k.module_class .. '_factory'
})
end
end
local file = io.open(filename, "w")
if not file then
print ("failed to open file " .. filename)
os.exit(-1)
end
file:write ((template:gsub(
"%$([%w_]-)%b{}",
{
factories = table.concat(factories, "\n\n"),
factories_registry = table.concat(factories_reg, "\n"),
functions = table.concat(functions, "\n\n"),
functions_registry = table.concat(functions_registry, "\n"),
includes = table.concat(includes, "\n"),
library_c_name = target:gsub("%.", "_"),
library_name = target
})))
file:close()
| mit |
zhaoxx063/luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/fstab.lua | 39 | 5639 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "nixio.util"
local tp = require "luci.template.parser"
local block = io.popen("block info", "r")
local ln, dev, devices = nil, nil, {}
repeat
ln = block:read("*l")
dev = ln and ln:match("^/dev/(.-):")
if dev then
local e, s, key, val = { }
for key, val in ln:gmatch([[(%w+)="(.-)"]]) do
e[key:lower()] = val
devices[val] = e
end
s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev)))
e.dev = "/dev/%s" % dev
e.size = s and math.floor(s / 2048)
devices[e.dev] = e
end
until not ln
block:close()
m = Map("fstab", translate("Mount Points"))
local mounts = luci.sys.mounts()
v = m:section(Table, mounts, translate("Mounted file systems"))
fs = v:option(DummyValue, "fs", translate("Filesystem"))
mp = v:option(DummyValue, "mountpoint", translate("Mount Point"))
avail = v:option(DummyValue, "avail", translate("Available"))
function avail.cfgvalue(self, section)
return luci.tools.webadmin.byte_format(
( tonumber(mounts[section].available) or 0 ) * 1024
) .. " / " .. luci.tools.webadmin.byte_format(
( tonumber(mounts[section].blocks) or 0 ) * 1024
)
end
used = v:option(DummyValue, "used", translate("Used"))
function used.cfgvalue(self, section)
return ( mounts[section].percent or "0%" ) .. " (" ..
luci.tools.webadmin.byte_format(
( tonumber(mounts[section].used) or 0 ) * 1024
) .. ")"
end
mount = m:section(TypedSection, "mount", translate("Mount Points"), translate("Mount Points define at which point a memory device will be attached to the filesystem"))
mount.anonymous = true
mount.addremove = true
mount.template = "cbi/tblsection"
mount.extedit = luci.dispatcher.build_url("admin/system/fstab/mount/%s")
mount.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(mount.extedit % sid)
return
end
end
mount:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = mount:option(DummyValue, "device", translate("Device"))
dev.rawhtml = true
dev.cfgvalue = function(self, section)
local v, e
v = m.uci:get("fstab", section, "uuid")
e = v and devices[v:lower()]
if v and e and e.size then
return "UUID: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size }
elseif v and e then
return "UUID: %s (%s)" %{ tp.pcdata(v), e.dev }
elseif v then
return "UUID: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
v = m.uci:get("fstab", section, "label")
e = v and devices[v]
if v and e and e.size then
return "Label: %s (%s, %d MB)" %{ tp.pcdata(v), e.dev, e.size }
elseif v and e then
return "Label: %s (%s)" %{ tp.pcdata(v), e.dev }
elseif v then
return "Label: %s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
v = Value.cfgvalue(self, section) or "?"
e = v and devices[v]
if v and e and e.size then
return "%s (%d MB)" %{ tp.pcdata(v), e.size }
elseif v and e then
return tp.pcdata(v)
elseif v then
return "%s (<em>%s</em>)" %{ tp.pcdata(v), translate("not present") }
end
end
mp = mount:option(DummyValue, "target", translate("Mount Point"))
mp.cfgvalue = function(self, section)
if m.uci:get("fstab", section, "is_rootfs") == "1" then
return "/overlay"
else
return Value.cfgvalue(self, section) or "?"
end
end
fs = mount:option(DummyValue, "fstype", translate("Filesystem"))
fs.cfgvalue = function(self, section)
local v, e
v = m.uci:get("fstab", section, "uuid")
v = v and v:lower() or m.uci:get("fstab", section, "label")
v = v or m.uci:get("fstab", section, "device")
e = v and devices[v]
return e and e.type or m.uci:get("fstab", section, "fstype") or "?"
end
op = mount:option(DummyValue, "options", translate("Options"))
op.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) or "defaults"
end
rf = mount:option(DummyValue, "is_rootfs", translate("Root"))
rf.cfgvalue = function(self, section)
local target = m.uci:get("fstab", section, "target")
if target == "/" then
return translate("yes")
elseif target == "/overlay" then
return translate("overlay")
else
return translate("no")
end
end
ck = mount:option(DummyValue, "enabled_fsck", translate("Check"))
ck.cfgvalue = function(self, section)
return Value.cfgvalue(self, section) == "1"
and translate("yes") or translate("no")
end
swap = m:section(TypedSection, "swap", "SWAP", translate("If your physical memory is insufficient unused data can be temporarily swapped to a swap-device resulting in a higher amount of usable <abbr title=\"Random Access Memory\">RAM</abbr>. Be aware that swapping data is a very slow process as the swap-device cannot be accessed with the high datarates of the <abbr title=\"Random Access Memory\">RAM</abbr>."))
swap.anonymous = true
swap.addremove = true
swap.template = "cbi/tblsection"
swap.extedit = luci.dispatcher.build_url("admin/system/fstab/swap/%s")
swap.create = function(...)
local sid = TypedSection.create(...)
if sid then
luci.http.redirect(swap.extedit % sid)
return
end
end
swap:option(Flag, "enabled", translate("Enabled")).rmempty = false
dev = swap:option(DummyValue, "device", translate("Device"))
dev.cfgvalue = function(self, section)
local v
v = m.uci:get("fstab", section, "uuid")
if v then return "UUID: %s" % v end
v = m.uci:get("fstab", section, "label")
if v then return "Label: %s" % v end
v = Value.cfgvalue(self, section) or "?"
e = v and devices[v]
if v and e and e.size then
return "%s (%s MB)" % {v, e.size}
else
return v
end
end
return m
| apache-2.0 |
tempbottle/luvit.io | libs/render-template.lua | 4 | 3542 | local pathJoin = require('luvi').path.join
local templateDir = pathJoin(module.dir, "../templates")
local fs = require('coro-fs').chroot(templateDir)
local uv = require('uv')
local renderMarkdown = require('markdown')
local digest = require('openssl').digest.digest
local cache = {}
-- When a file changes, invalidate it's cached value so it will be recompiled
-- the next time it's requested.
uv.new_fs_event():start(templateDir, {}, function (err, filename)
assert(not err, err)
local base = filename:match("^(.*).html$")
if not base then return end
cache[base] = nil
end)
local function stringify(data)
if data:match("^[\32-\126\n]*$") then
return "'" .. data:gsub("\n", "\\n"):gsub("'", "\\'") .. "'"
end
local open = "[["
local close = "]]"
local a = 0
while data:find(open, 1, true) or data:find(close, 1, true) do
a = a + 1
open = "[" .. string.rep("=", a) .. "["
close = "]" .. string.rep("=", a) .. "]"
end
return open .. "\n" .. data .. close
end
local function compile(data, name)
local parts = {
"local _P = {}",
"local function print(t) _P[#_P+1]=t end",
}
local last = #data
local getText, getPrint, getCode
function getText(first)
local a, b, pre, eq, post = data:find("([ \t]*)<%?(=?)( *)", first)
local mode
if a then
if #eq > 0 then
mode = getPrint
a = a + #pre
else
mode = getCode
b = b - #post
end
else
a = last + 1
end
local part = data:sub(first, a - 1)
if #part > 0 then
parts[#parts + 1] = "print" .. stringify(part)
end
if mode then return mode(b + 1) end
end
function getPrint(first)
local a, b = data:find("%?>", first)
local mode
if a then
mode = getText
else
a = last + 1
end
local part = data:sub(first, a - 1)
if #part > 0 then
parts[#parts + 1] = "print(var(" .. part .. "," .. stringify(part) .. "))"
end
if mode then return mode(b + 1) end
end
function getCode(first)
local a, b = data:find("%?>\n?", first)
local mode
if a then
mode = getText
else
a = last + 1
end
local part = data:sub(first, a - 1)
if #part > 0 then
parts[#parts + 1] = part
end
if mode then return mode(b + 1) end
end
getText(1)
parts[#parts + 1] = "return table.concat(_P)"
local code = table.concat(parts, "\n")
local fn, err = loadstring(code, "compiled template: " .. name)
if fn then return fn end
error(err .. "\n" .. code)
end
local function load(name)
local template = cache[name]
if not template then
local source = assert(fs.readFile(name .. ".html"))
template = compile(source, name)
cache[name] = template
end
return template
end
local metatable
local function partial(name, data, source)
name = name or "unknown"
local template = source and compile(source, name) or load(name)
data.self = data
setfenv(template, setmetatable(data, metatable))
return template()
end
local function var(value, name)
return value == nil and "{" .. name .. "}" or tostring(value)
end
local function md5(string)
return digest("md5", string)
end
metatable = {
__index = {
os = os,
md5 = md5,
markdown = renderMarkdown,
tostring = tostring,
var = var,
partial = partial,
table = table,
string = string
}
}
return function (res, name, data)
data.body = partial(name, data)
res.body = partial("layout", data)
res.code = 200
res.headers["Content-Type"] = "text/html"
end
| apache-2.0 |
resistor58/deaths-gmod-server | Mad Cows Weapons/lua/entities/ent_mad_c4/shared.lua | 1 | 1361 | ENT.Type = "anim"
ENT.PrintName = "Explosive C4"
ENT.Author = "Worshipper"
ENT.Contact = "Josephcadieux@hotmail.com"
ENT.Purpose = ""
ENT.Instructions = ""
/*---------------------------------------------------------
Name: ENT:SetupDataTables()
Desc: Setup the data tables.
---------------------------------------------------------*/
function ENT:SetupDataTables()
self:DTVar("Int", 0, "Timer")
end
/*---------------------------------------------------------
Name: ENT:Initialize()
---------------------------------------------------------*/
function ENT:Initialize()
self.C4CountDown = self:GetDTInt(0)
self:CountDown()
self.Entity:EmitSound("C4.Plant")
end
/*---------------------------------------------------------
Name: ENT:CountDown()
---------------------------------------------------------*/
function ENT:CountDown()
if self.C4CountDown > 1 then
self.Entity:EmitSound("C4.PlantSound")
self.C4CountDown = self.C4CountDown - 1
timer.Create(self.Entity, 1, 0, function()
self:CountDown()
end)
else
self.C4CountDown = 0
timer.Destroy("CountDown")
end
end
/*---------------------------------------------------------
Name: ENT:OnRemove()
---------------------------------------------------------*/
function ENT:OnRemove()
timer.Destroy(self.Entity)
end | gpl-3.0 |
jdavis7257/contrib | ingress/controllers/nginx/lua/error_page.lua | 45 | 1661 | http = require "resty.http"
def_backend = "upstream-default-backend"
local concat = table.concat
local upstream = require "ngx.upstream"
local get_servers = upstream.get_servers
local get_upstreams = upstream.get_upstreams
local random = math.random
local us = get_upstreams()
function openURL(status)
local httpc = http.new()
local random_backend = get_destination()
local res, err = httpc:request_uri(random_backend, {
path = "/",
method = "GET",
headers = {
["X-Code"] = status or "404",
["X-Format"] = ngx.var.httpAccept or "html",
}
})
if not res then
ngx.log(ngx.ERR, err)
ngx.exit(500)
end
if ngx.var.http_cookie then
ngx.header["Cookie"] = ngx.var.http_cookie
end
ngx.status = tonumber(status)
ngx.say(res.body)
end
function get_destination()
for _, u in ipairs(us) do
if u == def_backend then
local srvs, err = get_servers(u)
local us_table = {}
if not srvs then
return "http://127.0.0.1:8181"
else
for _, srv in ipairs(srvs) do
us_table[srv["name"]] = srv["weight"]
end
end
local destination = random_weight(us_table)
return "http://"..destination
end
end
end
function random_weight(tbl)
local total = 0
for k, v in pairs(tbl) do
total = total + v
end
local offset = random(0, total - 1)
for k1, v1 in pairs(tbl) do
if offset < v1 then
return k1
end
offset = offset - v1
end
end
| apache-2.0 |
chewi/Aquaria | files/scripts/entities/plasmawormbg.lua | 6 | 7647 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- ================================================================================================
-- P L A S M A W O R M B G
-- ================================================================================================
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
v.dir = 0
v.switchDirDelay = 0
v.wiggleTime = 0
v.wiggleDir = 1
v.interestTimer = 0
v.colorRevertTimer = 0
v.collisionSegs = 64
v.avoidLerp = 0
v.avoidDir = 1
v.interest = false
v.glow = nil
v.segs = 64
v.glowSegInt = 4
v.glowSegs = v.segs/v.glowSegInt
local function setNormalGlow()
for i=1,v.glowSegs do
quad_color(v.glow[i], 0.6, 0.6, 0.9)
quad_color(v.glow[i], 1, 1, 1, 2, -1, 1, 1)
end
end
-- initializes the entity
function init(me)
v.glow = {}
-- oldhealth : 40
setupBasicEntity(
me,
"plasmaworm/tentacles-bg", -- texture
9, -- health
1, -- manaballamount
1, -- exp
1, -- money
0, -- collideRadius (only used if hit entities is on)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
3000, -- updateCull -1: disabled, default: 4000
1
)
entity_setEntityLayer(me, -3)
entity_setDropChance(me, 50)
v.lungeDelay = 1.0 -- prevent the nautilus from attacking right away
entity_initHair(me, v.segs, 16, 64, "plasmaworm/body-bg")
--[[
entity_initSegments(
25, -- num segments
2, -- minDist
12, -- maxDist
"wurm-body", -- body tex
"wurm-tail", -- tail tex
128, -- width
128, -- height
0.01, -- taper
0 -- reverse segment direction
)
]]--
if chance(50) then
v.dir = 0
else
v.dir = 1
end
if chance(50) then
v.interest = true
end
v.switchDirDelay = math.random(800)/100.0
v.naija = getNaija()
entity_addVel(me, math.random(1000)-500, math.random(1000)-500)
entity_setDeathParticleEffect(me, "Explode")
entity_setDamageTarget(me, DT_ENEMY_TRAP, false)
--entity_fv(me)
entity_setSegs(me, 8, 2, 0.1, 0.9, 0, -0.03, 8, 0)
for i=1,v.glowSegs do
v.glow[i] = createQuad("Naija/LightFormGlow", 13)
quad_scale(v.glow[i], 3, 3)
quad_scale(v.glow[i], 4, 4, 0.5, -1, 1, 1)
quad_alpha(v.glow[i], 0.4)
end
setNormalGlow()
entity_scale(me, 0.6, 0.6)
entity_setDamageTarget(me, DT_AVATAR_LIZAP, false)
entity_setEntityType(me, ET_NEUTRAL)
end
v.spin = 0
-- the entity's main update function
function update(me, dt)
entity_rotateToVel(me)
if v.colorRevertTimer > 0 then
v.colorRevertTimer = v.colorRevertTimer - dt
if v.colorRevertTimer < 0 then
entity_setColor(me, 1, 1, 1, 3)
setNormalGlow()
end
end
v.spin = v.spin - dt
if v.spin > 5 then
-- do something cool!
msg("SPUN!")
v.spin = 0
end
-- in idle state only
if entity_getState(me)==STATE_IDLE then
-- count down the v.lungeDelay timer to 0
if v.lungeDelay > 0 then v.lungeDelay = v.lungeDelay - dt if v.lungeDelay < 0 then v.lungeDelay = 0 end end
-- if we don't have a target, find one
if not entity_hasTarget(me) then
entity_findTarget(me, 1000)
else
v.wiggleTime = v.wiggleTime + (dt*200)*v.wiggleDir
if v.wiggleTime > 1000 then
v.wiggleDir = -1
elseif v.wiggleTime < 0 then
v.wiggleDir = 1
end
v.interestTimer = v.interestTimer - dt
if v.interestTimer < 0 then
if v.interest then
v.interest = false
else
v.interest = true
entity_addVel(me, math.random(1000)-500, math.random(1000)-500)
end
v.interestTimer = math.random(400.0)/100.0 + 2.0
end
if v.interest then
if entity_isNearObstruction(getNaija(), 8) then
v.interest = false
else
if entity_isTargetInRange(me, 1600) then
if entity_isTargetInRange(me, 100) then
entity_moveTowardsTarget(me, dt, -500) -- if we're too close, move away
elseif not entity_isTargetInRange(me, 300) then
entity_moveTowardsTarget(me, dt, 1000) -- move in if we're too far away
end
entity_moveAroundTarget(me, dt, 1000+v.wiggleTime, v.dir)
end
end
else
--if entity_isTargetInRange(me, 1600) then
--entity_moveTowardsTarget(me, dt, -100) -- if we're too close, move away
--end
end
--[[
v.switchDirDelay = v.switchDirDelay - dt
if v.switchDirDelay < 0 then
v.switchDirDelay = math.random(800)/100.0
if v.dir == 0 then
v.dir = 1
else
v.dir = 0
end
end
]]--
--[[
-- 40% of the time when we're in range and not delaying, launch an attack
if entity_isTargetInRange(me, 300) then
if math.random(100) < 40 and v.lungeDelay == 0 then
entity_setState(me, STATE_ATTACKPREP, 0.5)
end
end
]]--
v.avoidLerp = v.avoidLerp + dt*v.avoidDir
if v.avoidLerp >= 1 or v.avoidLerp <= 0 then
v.avoidLerp = 0
if v.avoidDir == -1 then
v.avoidDir = 1
else
v.avoidDir = -1
end
end
-- avoid other things nearby
entity_doEntityAvoidance(me, dt, 32, 0.1)
-- entity_doSpellAvoidance(dt, 200, 1.5);
entity_doCollisionAvoidance(me, dt, 10, 0.1)
entity_doCollisionAvoidance(me, dt, 6, 1.0)
end
end
entity_updateMovement(me, dt)
entity_setHairHeadPosition(me, entity_x(me), entity_y(me))
entity_updateHair(me, dt)
for i=0,v.glowSegs-1 do
local x, y = entity_getHairPosition(me, i*v.glowSegInt)
--debugLog(string.format("hair(%d, %d)", x, y))
quad_setPosition(v.glow[i+1], x, y)
end
--entity_handleShotCollisionsHair(me, v.collisionSegs)
--entity_handleShotCollisions(me)
--if entity_collideHairVsCircle(me, v.naija, v.collisionSegs, 0.5) then
--entity_touchAvatarDamage(me, 0, 0, 500)
--end
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
entity_setMaxSpeed(me, 400)
elseif entity_isState(me, STATE_DEAD) then
for i=1,v.glowSegs do
quad_delete(v.glow[i], 0.5)
end
end
end
function exitState(me)
end
function hitSurface(me)
end
function damage(me, attacker, bone, damageType, dmg)
entity_setMaxSpeed(me, 600)
return true
end
v.lastNote = 0
function songNote(me, note)
if getForm()~=FORM_NORMAL then
return
end
if note ~= v.lastNote then
v.spin = v.spin + 0.1
end
v.lastNote = note
v.interest = true
local r,g,b = getNoteColor(note)
entity_setColor(me, r,g,b,1)
v.colorRevertTimer = 10
r = r * 0.5 + 0.5
g = g * 0.5 + 0.5
b = b * 0.5 + 0.5
for i=1,v.glowSegs do
quad_color(v.glow[i], r, g, b)
quad_color(v.glow[i], 1, 1, 1, 2, -1, 1, 1)
end
--entity_setColor(me, 1,1,1,10)
end
| gpl-2.0 |
resistor58/deaths-gmod-server | wire/lua/weapons/gmod_tool/stools/wire_las_reciever.lua | 1 | 4477 | TOOL.Category = "Wire - Detection"
TOOL.Name = "Laser Pointer Receiver"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if ( CLIENT ) then
language.Add( "Tool_wire_las_reciever_name", "Laser Receiver Tool (Wire)" )
language.Add( "Tool_wire_las_reciever_desc", "Spawns a constant laser receiver prop for use with the wire system." )
language.Add( "Tool_wire_las_reciever_0", "Primary: Create/Update Laser Receiver" )
language.Add( "WireILaserRecieverTool_ilas_reciever", "Laser Receiver:" )
language.Add( "sboxlimit_wire_las_recievers", "You've hit laser receivers limit!" )
language.Add( "undone_wireigniter", "Undone Wire Laser Receiver" )
end
if (SERVER) then
CreateConVar('sbox_maxwire_las_receivers', 20)
end
TOOL.ClientConVar[ "model" ] = "models/jaanus/wiretool/wiretool_range.mdl"
cleanup.Register( "wire_las_receivers" )
function TOOL:LeftClick( trace )
if (!trace.HitPos) then return false end
if (trace.Entity:IsPlayer()) then return false end
if ( CLIENT ) then return true end
local ply = self:GetOwner()
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_las_reciever" && trace.Entity.pl == ply ) then
return true
end
if ( !self:GetSWEP():CheckLimit( "wire_las_receivers" ) ) then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local wire_las_reciever = MakeWireLaserReciever( ply, trace.HitPos, Ang, self:GetModel() )
local min = wire_las_reciever:OBBMins()
wire_las_reciever:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(wire_las_reciever, trace.Entity, trace.PhysicsBone, true)
undo.Create("Wire Laser Receiver")
undo.AddEntity( wire_las_reciever )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_las_receivers", wire_las_reciever )
return true
end
if (SERVER) then
function MakeWireLaserReciever( pl, Pos, Ang, model )
if ( !pl:CheckLimit( "wire_las_receivers" ) ) then return false end
local wire_las_reciever = ents.Create( "gmod_wire_las_reciever" )
if (!wire_las_reciever:IsValid()) then return false end
wire_las_reciever:SetAngles( Ang )
wire_las_reciever:SetPos( Pos )
wire_las_reciever:SetModel( Model(model or "models/jaanus/wiretool/wiretool_range.mdl") )
wire_las_reciever:Spawn()
wire_las_reciever:SetPlayer( pl )
wire_las_reciever.pl = pl
pl:AddCount( "wire_las_receivers", wire_las_reciever )
return wire_las_reciever
end
duplicator.RegisterEntityClass("gmod_wire_las_reciever", MakeWireLaserReciever, "Pos", "Ang", "Model")
end
function TOOL:UpdateGhostWireLaserReciever( ent, player )
if ( !ent || !ent:IsValid() ) then return end
local tr = utilx.GetPlayerTrace( player, player:GetCursorAimVector() )
local trace = util.TraceLine( tr )
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_las_reciever" ) then
ent:SetNoDraw( true )
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
ent:SetAngles( Ang )
ent:SetNoDraw( false )
end
function TOOL:Think()
local model = self:GetModel()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != model ) then
self:MakeGhostEntity( Model(model), Vector(0,0,0), Angle(0,0,0) )
end
self:UpdateGhostWireLaserReciever( self.GhostEntity, self:GetOwner() )
end
function TOOL:GetModel()
local model = "models/jaanus/wiretool/wiretool_range.mdl"
local modelcheck = self:GetClientInfo( "model" )
if (util.IsValidModel(modelcheck) and util.IsValidProp(modelcheck)) then
model = modelcheck
end
return model
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool_wire_las_reciever_name", Description = "#Tool_wire_las_reciever_desc" })
panel:AddControl("ComboBox", {
Label = "#Presets",
MenuButton = "1",
Folder = "wire_las_reciever",
Options = {
Default = {
wire_las_reciever_las_reciever = "0",
wire_las_reciever_model = "models/jaanus/wiretool/wiretool_range.mdl"
}
},
CVars = {
[0] = "wire_las_reciever_las_reciever ",
[1] = "wire_las_reciever_model"
}
})
WireDermaExts.ModelSelect(panel, "wire_las_reciever_model", list.Get( "Wire_Misc_Tools_Models" ), 1)
end
| gpl-3.0 |
Aico/mudlet | src/mudlet-lua/lua/DB.lua | 10 | 49950 | ----------------------------------------------------------------------------------
--- Mudlet DB
----------------------------------------------------------------------------------
-- TODO will be already loaded in LuaGlobal
-----------------------------------------------------------------------------
-- General-purpose useful tools that were needed during development:
-----------------------------------------------------------------------------
if package.loaded["rex_pcre"] then rex = require"rex_pcre" end
-- TODO those funciton are already definde elsewhere
-- Tests if a table is empty: this is useful in situations where you find
-- yourself wanting to do 'if my_table == {}' and such.
function table.is_empty(tbl)
return next(tbl) == nil
end
function string.starts(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.ends(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
-- TODO move to StringUtils?
-----------------------------------------------------------------------------
-- Some Date / Time parsing functions.
-----------------------------------------------------------------------------
datetime = {
_directives = {
["%b"] = "(?P<abbrev_month_name>jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)",
["%B"] = "(?P<month_name>january|febuary|march|april|may|june|july|august|september|october|november|december)",
["%d"] = "(?P<day_of_month>\\d{2})",
["%H"] = "(?P<hour_24>\\d{2})",
["%I"] = "(?P<hour_12>\\d{2})",
["%m"] = "(?P<month>\\d{2})",
["%M"] = "(?P<minute>\\d{2})",
["%p"] = "(?P<ampm>am|pm)",
["%S"] = "(?P<second>\\d{2})",
["%y"] = "(?P<year_half>\\d{2})",
["%Y"] = "(?P<year_full>\\d{4})"
},
_pattern_cache = {},
_month_names = {
["january"] = 1,
["febuary"] = 2,
["march"] = 3,
["april"] = 4,
["may"] = 5,
["june"] = 6,
["july"] = 7,
["august"] = 8,
["september"] = 9,
["october"] = 10,
["november"] = 11,
["december"] = 12
},
_abbrev_month_names = {
["jan"] = 1,
["feb"] = 2,
["mar"] = 3,
["apr"] = 4,
["may"] = 5,
["jun"] = 6,
["jul"]= 7,
["aug"]= 8,
["sep"] = 9,
["oct"] = 10,
["nov"] = 11,
["dec"] = 12
}
}
-- NOT LUADOC
-- The rex.match function does not return named patterns even if you use named capture
-- groups, but the r:tfind does -- but this only operates on compiled patterns. So,
-- we are caching the conversion of 'simple format' date patterns into a regex, and
-- then compiling them.
function datetime:_get_pattern(format)
if not datetime._pattern_cache[format] then
local fmt = rex.gsub(format, "(%[A-Za-z])",
function(m)
return datetime._directives[m] or m
end
)
datetime._pattern_cache[format] = rex.new(fmt, rex.flags().CASELESS)
end
return datetime._pattern_cache[format]
end
--- Parses the specified source string, according to the format if given, to return a representation of
--- the date/time. The default format if not specified is: "^%Y-%m-%d %H:%M:%S$" <br/><br/>
---
--- If as_epoch is provided and true, the return value will be a Unix epoch -- the number
--- of seconds since 1970. This is a useful format for exchanging date/times with other systems. If as_epoch
--- is false, then a Lua time table will be returned. Details of the time tables are provided
--- in the http://www.lua.org/pil/22.1.html. <br/><br/>
---
--- Supported Format Codes
--- </pre>
--- %b Abbreviated Month Name
--- %B Full Month Name
--- %d Day of Month
--- %H Hour (24-hour format)
--- %I Hour (12-hour format, requires %p as well)
--- %p AM or PM
--- %m 2-digit month (01-12)
--- %M 2-digit minutes (00-59)
--- %S 2-digit seconds (00-59)
--- %y 2-digit year (00-99), will automatically prepend 20 so 10 becomes 2010 and not 1910.
--- %Y 4-digit year.
--- </pre>
function datetime:parse(source, format, as_epoch)
if not format then
format = "^%Y-%m-%d %H:%M:%S$"
end
local fmt = datetime:_get_pattern(format)
local m = {fmt:tfind(source)}
if m then
m = m[3]
dt = {}
if m.year_half then
dt.year = tonumber("20"..m.year_half)
elseif m.year_full then
dt.year = tonumber(m.year_full)
end
if m.month then
dt.month = tonumber(m.month)
elseif m.month_name then
dt.month = datetime._month_names[m.month_name:lower()]
elseif m.abbrev_month_name then
dt.month = datetime._abbrev_month_names[m.abbrev_month_name:lower()]
end
dt.day = m.day_of_month
if m.hour_12 then
assert(m.ampm, "You must use %p (AM|PM) with %I (12-hour time)")
if m.ampm == "PM" then
dt.hour = 12 + tonumber(m.hour_12)
else
dt.hour = tonumber(m.hour_12)
end
else
dt.hour = tonumber(m.hour_24)
end
dt.min = tonumber(m.minute)
dt.sec = tonumber(m.second)
dt.isdst = false
if as_epoch then
return os.time(dt)
else
return dt
end
else
return nil
end
end
-----------------------------------------------------------------------------
-- The database wrapper library
-----------------------------------------------------------------------------
if package.loaded["luasql.sqlite3"] then require "luasql.sqlite3" end
db = {}
db.__autocommit = {}
db.__schema = {}
db.__conn = {}
db.debug_sql = false
-- NOT LUADOC
-- Converts the type of a lua object to the equivalent type in SQL
function db:_sql_type(value)
local t = type(value)
if t == "number" then
return "REAL"
elseif t == "nil" then
return "NULL"
elseif t == "table" and value._timestamp ~= nil then
return "INTEGER"
else
return "TEXT"
end
end
-- NOT LUADOC
-- Converts a data value in Lua to its SQL equivalent; notably it will also escape single-quotes to
-- prevent inadvertant SQL injection.
function db:_sql_convert(value)
local t = db:_sql_type(value)
if value == nil then
return "NULL"
elseif t == "TEXT" then
return '"'..value:gsub("'", "''")..'"'
elseif t == "NULL" then
return "NULL"
elseif t == "INTEGER" then
-- With db.Timestamp's, a value of false should be interpreted as nil.
if value._timestamp == false then
return "NULL"
end
return tostring(value._timestamp)
else
return tostring(value)
end
end
-- NOT LUADOC
-- Given a sheet name and the details of an index, this function will return a unique index name to
-- add to the database. The purpose of this is to create unique index names as indexes are tested
-- for existance on each call of db:create and not only on creation. That way new indexes can be
-- added after initial creation.
function db:_index_name(tbl_name, params)
local t = type(params)
if t == "string" then
return "idx_" .. tbl_name .. "_c_" .. params
elseif assert(t == "table", "Indexes must be either a string or a table.") then
local parts = {"idx", tbl_name, "c"}
for _, v in pairs(params) do
parts[#parts+1] = v
end
return table.concat(parts, "_")
end
end
-- NOT LUADOC
-- This function returns true if all of the columns referenced in index_columns also exist within
-- the sheet_columns table array. The purpose of this is to raise an error if someone tries to index
-- a column which doesn't currently exist in the schema.
function db:_index_valid(sheet_columns, index_columns)
if type(index_columns) == "string" then
if sheet_columns[index_columns] ~= nil then
return true
else
return false
end
else
for _, v in ipairs(index_columns) do
if sheet_columns[v] == nil then
echo("\n--> Bad index "..v)
return false
end
end
end
return true
end
-- NOT LUADOC
-- The column_spec is either a string or an indexed table. This function returns either "column" or
-- "column1", "column2" for use in the column specification of INSERT.
function db:_sql_columns(value)
local colstr = ''
local t = type(value)
if t == "table" then
col_chunks = {}
for _, v in ipairs(value) do
col_chunks[#col_chunks+1] = '"'..v:lower()..'"'
end
colstr = table.concat(col_chunks, ',')
elseif assert(t == "string",
"Must specify either a table array or string for index, not "..type(value)) then
colstr = '"'..value:lower()..'"'
end
return colstr
end
-- NOT LUADOC
-- This serves as a very similar function to db:_sql_columns, quoting column names properly but for
-- uses outside of INSERTs.
function db:_sql_fields(values)
local sql_fields = {}
for k, v in pairs(values) do
sql_fields[#sql_fields+1] = '"'..k..'"'
end
return "("..table.concat(sql_fields, ",")..")"
end
-- NOT LUADOC
-- This quotes values to be passed into an INSERT or UPDATE operation in a SQL list. Meaning, it turns
-- {x="this", y="that", z=1} into ('this', 'that', 1).
-- It is intelligent with data-types; strings are automatically quoted (with internal single quotes
-- escaped), nil turned into NULL, timestamps converted to integers, and such.
function db:_sql_values(values)
local sql_values = {}
for k, v in pairs(values) do
local t = type(v)
local s = ""
if t == "string" then
s = "'"..v:gsub("'", "''").."'"
elseif t == "nil" then
s = "NULL"
elseif t == "table" and t._timestamp ~= nil then
if not t._timestamp then
return "NULL"
else
s = tostring(t._timestamp)
end
else
s = tostring(v)
end
sql_values[#sql_values+1] = s
end
return "("..table.concat(sql_values, ",")..")"
end
--- <b><u>TODO</u></b> db:safe_name(name)
-- On a filesystem level, names are restricted to being alphanumeric only. So, "my_database" becomes
-- "mydatabase", and "../../../../etc/passwd" becomes "etcpasswd". This prevents any possible
-- security issues with database names.
function db:safe_name(name)
name = name:gsub("[^%ad]", "")
name = name:lower()
return name
end
--- Creates and/or modifies an existing database. This function is safe to define at a top-level of a Mudlet
--- script: in fact it is reccommended you run this function at a top-level without any kind of guards.
--- If the named database does not exist it will create it. If the database does exist then it will add
--- any columns or indexes which didn't exist before to that database. If the database already has all the
--- specified columns and indexes, it will do nothing. <br/><br/>
---
--- The database will be called Database_<sanitized database name>.db and will be stored in the
--- Mudlet configuration directory. <br/><br/>
---
--- Database 'tables' are called 'sheets' consistently throughout this documentation, to avoid confusion
--- with Lua tables. <br/><br/>
---
--- The schema table must be a Lua table array containing table dictionaries that define the structure and
--- layout of each sheet. <br/><br/>
---
--- For sheets with unique indexes, you may specify a _violations key to indicate how the db layer handle
--- cases where the unique index is violated. The options you may use are:
--- <pre>
--- FAIL - the default. A hard error is thrown, cancelling the script.
--- IGNORE - The command that would add a record that violates uniqueness just fails silently.
--- REPLACE - The old record which matched the unique index is dropped, and the new one is added to replace it.
--- </pre>
---
--- @usage Example bellow will create a database with two sheets; the first is kills and is used to track every successful kill,
--- with both where and when the kill happened. It has one index, a compound index tracking the combination of name and area.
--- The second sheet has two indexes, but one is unique: it isn't possible to add two items to the enemies sheet with the same name.
--- <pre>
--- local mydb = db:create("combat_log",
--- {
--- kills = {
--- name = "",
--- area = "",
--- killed = db:Timestamp("CURRENT_TIMESTAMP"),
--- _index = {{"name", "area"}}
--- },
--- enemies = {
--- name = "",
--- city = "",
--- reason = "",
--- enemied = db:Timestamp("CURRENT_TIMESTAMP"),
--- _index = { "city" },
--- _unique = { "name" },
--- _violations = "IGNORE"
--- }
--- }
--- )
--- </pre>
--- Note that you have to use double {{ }} if you have composite index/unique constrain.
function db:create(db_name, sheets)
if not db.__env then
db.__env = luasql.sqlite3()
end
db_name = db:safe_name(db_name)
if not db.__conn[db_name] then
db.__conn[db_name] = db.__env:connect(getMudletHomeDir() .. "/Database_" .. db_name .. ".db")
db.__conn[db_name]:setautocommit(false)
db.__autocommit[db_name] = true
end
db.__schema[db_name] = {}
-- We need to separate the actual column configuration from the meta-configuration of the desired
-- sheet. {sheet={"column"}} verses {sheet={"column"}, _index={"column"}}. In the former we are
-- creating a database with a single field; in the latter we are also adding an index on that
-- field. The db package reserves any key that begins with an underscore to be special and syntax
-- for its own use.
for s_name, sht in pairs(sheets) do
options = {}
if sht[1] ~= nil then
t = {}
for k, v in pairs(sht) do
t[v] = nil
end
sht = t
else
for k, v in pairs(sht) do
if string.starts(k, "_") then
options[k] = v
sht[k] = nil
end
end
end
if not options._violations then
options._violations = "FAIL"
end
db.__schema[db_name][s_name] = {columns=sht, options=options}
db:_migrate(db_name, s_name)
end
return db:get_database(db_name)
end
-- NOT LUADOC
-- The migrate function is meant to upgrade an existing database live, to maintain a consistant
-- and correct set of sheets and fields, along with their indexes. It should be safe to run
-- at any time, and must not cause any data loss. It simply adds to what is there: in perticular
-- it is not capable of removing indexes, columns, or sheets after they have been defined.
function db:_migrate(db_name, s_name)
local conn = db.__conn[db_name]
local schema = db.__schema[db_name][s_name]
local current_columns = {}
-- The PRAGMA table_info command is a query which returns all of the columns currently
-- defined in the specified table. The purpose of this section is to see if any new columns
-- have been added.
local cur = conn:execute("PRAGMA table_info('"..s_name.."')")
if cur ~= 0 then
local row = cur:fetch({}, "a")
while row do
current_columns[row.name:lower()] = row.type
row = cur:fetch({}, "a")
end
cur:close()
end
-- The SQL definition of a column is:
-- "column_name" column_type NULL
-- The db module does not presently support columns that are required. Everything is optional,
-- everything may be NULL / nil.
-- If you specify a column's type, you also specify its default value.
local sql_column = ', "%s" %s NULL'
local sql_column_default = sql_column..' DEFAULT %s'
if table.is_empty(current_columns) then
-- At this point, we know that the specified table does not exist in the database and so we
-- should create it.
-- Every sheet has an implicit _row_id column. It is not presently (and likely never will be)
-- supported to define the primary key of any sheet.
local sql_chunks = {"CREATE TABLE ", s_name, '("_row_id" INTEGER PRIMARY KEY AUTOINCREMENT'}
-- We iterate over every defined column, and add a line which creates it.
for key, value in pairs(schema.columns) do
local sql = ""
if value == nil then
sql = sql_column:format(key:lower(), db:_sql_type(value))
else
sql = sql_column_default:format(key:lower(), db:_sql_type(value), db:_sql_convert(value))
end
sql_chunks[#sql_chunks+1] = sql
end
sql_chunks[#sql_chunks+1] = ")"
local sql = table.concat(sql_chunks, "")
db:echo_sql(sql)
conn:execute(sql)
else
-- At this point we know that the sheet already exists, but we are concerned if the current
-- definition includes columns which may be added.
local sql_chunks = {}
local sql_add = 'ALTER TABLE %s ADD COLUMN "%s" %s NULL DEFAULT %s'
for k, v in pairs(schema.columns) do
k = k:lower()
t = db:_sql_type(v)
v = db:_sql_convert(v)
-- Here we test it a given column exists in the sheet already, and if not, we add that
-- column.
if not current_columns[k] then
local sql = sql_add:format(s_name, k, t, v)
conn:execute(sql)
db:echo_sql(sql)
end
end
end
-- On every invocation of db:create we run the code that creates indexes, as that code will
-- do nothing if the specific indexes already exist. This is enforced by the db:_index_name
-- function creating a unique index.
--
-- Note that in no situation will an existing index be deleted.
db:_migrate_indexes(conn, s_name, schema, current_columns)
db:echo_sql("COMMIT")
conn:commit()
conn:execute("VACUUM")
end
-- NOT LUADOC
-- Creates any indexes which do not yet exist in the given database.
function db:_migrate_indexes(conn, s_name, schema, current_columns)
local sql_create_index = "CREATE %s IF NOT EXISTS %s ON %s (%s);"
local opt = {_unique = "UNIQUE INDEX", _index = "INDEX"} -- , _check = "CHECK"}
for option_type, options in pairs(schema.options) do
if option_type == "_unique" or option_type == "_index" then
for _, value in pairs(options) do
-- If an index references a column which does not presently exist within the schema
-- this will fail.
if db:_index_valid(current_columns, value) then
--assert(db:_index_valid(current_columns, value),
-- "In sheet "..s_name.." an index field is specified that does not exist.")
sql = sql_create_index:format(
opt[option_type], db:_index_name(s_name, value), s_name, db:_sql_columns(value)
)
db:echo_sql(sql)
conn:execute(sql)
end
end
end
end
end
--- Adds one or more new rows to the specified sheet. If any of these rows would violate a UNIQUE index,
--- a lua error will be thrown and execution will cancel. As such it is advisable that if you use a UNIQUE
--- index, you test those values before you attempt to insert a new row. <br/><br/>
---
--- Each table is a series of key-value pairs to set the values of the sheet, but if any keys do not exist
--- then they will be set to nil or the default value. As you can see, all fields are optional.
---
--- @usage Adding one record.
--- <pre>
--- db:add(mydb.enemies, {name="Bob Smith", city="San Francisco"})
--- </pre>
--- @usage Adding multiple records.
--- <pre>
--- db:add(mydb.enemies,
--- {name="John Smith", city="San Francisco"},
--- {name="Jane Smith", city="San Francisco"},
--- {name="Richard Clark"}
--- )
--- </pre>
function db:add(sheet, ...)
local db_name = sheet._db_name
local s_name = sheet._sht_name
assert(s_name, "First argument to db:add must be a proper Sheet object.")
local conn = db.__conn[db_name]
local sql_insert = "INSERT OR %s INTO %s %s VALUES %s"
for _, t in ipairs({...}) do
if t._row_id then
-- You are not permitted to change a _row_id
t._row_id = nil
end
local sql = sql_insert:format(db.__schema[db_name][s_name].options._violations, s_name, db:_sql_fields(t), db:_sql_values(t))
db:echo_sql(sql)
assert(conn:execute(sql), "Failed to add item: this is probably a violation of a UNIQUE index or other constraint.")
end
if db.__autocommit[db_name] then
conn:commit()
end
end
--- Execute SQL select query against database. This only useful for some very specific cases. <br/>
--- Use db:fetch if possible instead - this function should not be normally used!
---
--- @release post Mudlet 1.1.1 (<b><u>TODO update before release</u></b>)
---
--- @usage Following will select all distinct area from my kills DB.
--- <pre>
--- db:fetch_sql(mydb.kills, "SELECT distinct area FROM kills")
--- </pre>
---
--- @see db:fetch
function db:fetch_sql(sheet, sql)
local db_name = sheet._db_name
local conn = db.__conn[db_name]
db:echo_sql(sql)
local cur = conn:execute(sql)
if cur ~= 0 then
local results = {}
local row = cur:fetch({}, "a")
while row do
results[#results+1] = db:_coerce_sheet(sheet, row)
row = cur:fetch({}, "a")
end
cur:close()
return results
else
return nil
end
end
--- Returns a table array containing a table for each matching row in the specified sheet. All arguments
--- but sheet are optional. If query is nil, the entire contents of the sheet will be returned. <br/><br/>
---
--- Query is a string which should be built by calling the various db: expression functions, such as db:eq,
--- db:AND, and such. You may pass a SQL WHERE clause here if you wish, but doing so is very dangerous.
--- If you don't know SQL well, its best to build the expression.<br/><br/>
---
--- Query may also be a table array of such expressions, if so they will be AND'd together implicitly.<br/><br/>
---
--- The results that are returned are not in any guaranteed order, though they are usually the same order
--- as the records were inserted. If you want to rely on the order in any way, you must pass a value to the
--- order_by field. This must be a table array listing the columns you want to sort by.
--- It can be { "column1" }, or { "column1", "column2" } <br/><br/>
---
--- The results are returned in ascending (smallest to largest) order; to reverse this pass true into the final field.
---
--- @usage The first will fetch all of your enemies, sorted first by the city they reside in and then by their name.
--- <pre>
--- db:fetch(mydb.enemies, nil, {"city", "name"})
--- </pre>
--- @usage The second will fetch only the enemies which are in San Francisco.
--- <pre>
--- db:fetch(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))
--- </pre>
--- @usage The third will fetch all the things you've killed in Undervault which have Drow in their name.
--- <pre>
--- db:fetch(mydb.kills,
--- {
--- db:eq(mydb.kills.area, "Undervault"),
--- db:like(mydb.kills.name, "%Drow%")
--- }
--- )
--- </pre>
---
--- @see db:fetch_sql
function db:fetch(sheet, query, order_by, descending)
local s_name = sheet._sht_name
local sql = "SELECT * FROM "..s_name
if query then
if type(query) == "table" then
sql = sql.." WHERE "..db:AND(unpack(query))
else
sql = sql.." WHERE "..query
end
end
if order_by then
local o = {}
for _, v in ipairs(order_by) do
assert(v.name, "You must pass field instances (as obtained from yourdb.yoursheet.yourfield) to sort.")
o[#o+1] = v.name
end
sql = sql.." ORDER BY "..db:_sql_columns(o)
if descending then
sql = sql.." DESC"
end
end
return db:fetch_sql(sheet, sql)
end
--- Returns the result of calling the specified aggregate function on the field and its sheet. <br/><br/>
---
--- The supported aggregate functions are:
--- <pre>
--- COUNT - Returns the total number of records that are in the sheet or match the query.
--- AVG - Returns the average of all the numbers in the specified field.
--- MAX - Returns the highest number in the specified field.
--- MIN - Returns the lowest number in the specified field.
--- TOTAL - Returns the value of adding all the contents of the specified field.
--- </pre>
---
--- @param query optional
---
--- @usage Example:
--- <pre>
--- local mydb = db:get_database("my database")
--- echo(db:aggregate(mydb.enemies.name, "count"))
--- </pre>
function db:aggregate(field, fn, query)
local db_name = field.database
local s_name = field.sheet
local conn = db.__conn[db_name]
assert(type(field) == "table", "Field must be a field reference.")
assert(field.name, "Field must be a real field reference.")
local sql_chunks = {"SELECT", fn, "(", field.name, ")", "AS", fn, "FROM", s_name}
if query then
if type(query) == "table" then
sql_chunks[#sql_chunks+1] = db:AND(unpack(query))
else
sql_chunks[#sql_chunks+1] = query
end
end
if order_by then
local o = {}
for _, v in ipairs(order_by) do
assert(v.name, "You must pass field instances (as obtained from yourdb.yoursheet.yourfield) to sort.")
o[#o+1] = v.name
end
sql_chunks[#sql_chunks+1] = "ORDER BY"
sql_chunks[#sql_chunks+1] = db:_sql_columns(o)
if descending then
sql_chunks[#sql_chunks+1] = "DESC"
end
end
local sql = table.concat(sql_chunks, " ")
db:echo_sql(sql)
local cur = conn:execute(sql)
if cur ~= 0 then
local row = cur:fetch({}, "a")
local count = row[fn]
cur:close()
return count
else
return 0
end
end
--- Deletes rows from the specified sheet. The argument for query tries to be intelligent: <br/>
--- * if it is a simple number, it deletes a specific row by _row_id <br/>
--- * if it is a table that contains a _row_id (e.g., a table returned by db:get) it deletes just that record. <br/>
--- * Otherwise, it deletes every record which matches the query pattern which is specified as with db:get. <br/>
--- * If the query is simply true, then it will truncate the entire contents of the sheet. <br/>
---
--- @usage When passed an actual result table that was obtained from db:fetch, it will delete the record for that table.
--- <pre>
--- enemies = db:fetch(mydb.enemies)
--- db:delete(mydb.enemies, enemies[1])
--- </pre>
--- @usage When passed a number, will delete the record for that _row_id. This example shows getting the row id from a table.
--- <pre>
--- enemies = db:fetch(mydb.enemies)
--- db:delete(mydb.enemies, enemies[1]._row_id)
--- </pre>
--- @usage As above, but this example just passes in the row id directly.
--- <pre>
--- db:delete(mydb.enemies, 5)
--- </pre>
--- @usage Here, we will delete anything which matches the same kind of query as db:fetch uses - namely,
--- anyone who is in the city of San Francisco.
--- <pre>
--- db:delete(mydb.enemies, db:eq(mydb.enemies.city, "San Francisco"))
--- </pre>
--- @usage And finally, we will delete the entire contents of the enemies table.
--- <pre>
--- db:delete(mydb.enemies, true)
--- </pre>
function db:delete(sheet, query)
local db_name = sheet._db_name
local s_name = sheet._sht_name
local conn = db.__conn[db_name]
assert(query, "must pass a query argument to db:delete()")
if type(query) == "number" then
query = "_row_id = "..tostring(query)
elseif type(query) == "table" then
assert(query._row_id, "Passed a non-result table to db:delete, need a _row_id field to continue.")
query = "_row_id = "..tostring(query._row_id)
end
local sql = "DELETE FROM "..s_name
if query ~= true then
sql = sql.." WHERE "..query
end
db:echo_sql(sql)
assert(conn:execute(sql))
if db.__autocommit[db_name] then
conn:commit()
end
end
--- Merges the specified table array into the sheet, modifying any existing rows and adding any that don't exist.
---
--- This function is a convenience utility that allows you to quickly modify a sheet, changing
--- existing rows and add new ones as appropriate. It ONLY works on sheets which have a unique
--- index, and only when that unique index is only on a single field. For more complex situations
--- you'll have to do the logic yourself.
---
--- The table array may contain tables that were either returned previously by db:fetch, or new tables
--- that you've constructed with the correct fields, or any mix of both. Each table must have a value
--- for the unique key that has been set on this sheet.
---
--- @usage For example, consider this database:
--- <pre>
--- local mydb = db:create("peopledb",
--- {
--- friends = {
--- name = "",
--- race = "",
--- level = 0,
--- city = "",
--- _index = { "city" },
--- _unique = { "name" }
--- }
--- }
--- )
--- </pre>
---
--- Here you have a database with one sheet, which contains your friends, their race, level,
--- and what city they live in. Let's say you want to fetch everyone who lives in San Francisco, you could do:
--- <pre>
--- local results = db:fetch(mydb.friends, db:eq(mydb.friends.city, "San Francisco"))
--- </pre>
---
--- The tables in results are static, any changes to them are not saved back to the database.
--- But after a major radioactive cataclysm rendered everyone in San Francisco a mutant,
--- you could make changes to the tables as so:
--- <pre>
--- for _, friend in ipairs(results) do
--- friend.race = "Mutant"
--- end
--- </pre>
---
--- If you are also now aware of a new arrival in San Francisco, you could add them to that existing table array:
--- <pre>
--- results[#results+1] = {name="Bobette", race="Mutant", city="San Francisco"}
--- </pre>
---
--- And commit all of these changes back to the database at once with:
--- <pre>
--- db:merge_unique(mydb.friends, results)
--- </pre>
---
--- The db:merge_unique function will change the 'city' values for all the people who we previously fetched, but then add a new record as well.
function db:merge_unique(sheet, tables)
local db_name = sheet._db_name
local s_name = sheet._sht_name
local unique_options = db.__schema[db_name][s_name].options._unique
assert(unique_options, "db:merge_unique only works on a sheet with a unique index.")
assert(#unique_options == 1, "db:merge_unique only works on a sheet with a single unique index.")
local unique_index = unique_options[1]
local unique_key = ""
if type(unique_index) == "table" then
assert(#unique_index == 1, "db:merge_unique currently only supports sheets with a single unique index with a single column.")
unique_key = unique_index[1]
else
unique_key = unique_index
end
db:echo_sql(":: Unique index = "..unique_key)
local conn = db.__conn[db_name]
local mydb = db:get_database(db_name)
mydb:_begin()
for _, tbl in ipairs(tables) do
assert(tbl[unique_key], "attempting to db:merge_unique with a table that does not have the unique key.")
local results = db:fetch(sheet, db:eq(sheet[unique_key], tbl[unique_key]))
if results and results[1] then
local t = results[1]
for k, v in pairs(tbl) do
t[k] = v
end
db:update(sheet, t)
else
db:add(sheet, tbl)
end
end
mydb:_commit()
mydb:_end()
end
--- This function updates a row in the specified sheet, but only accepts a row which has been previously
--- obtained by db:fetch. Its primary purpose is that if you do a db:fetch, then change the value of a field
--- or tow, you can save back that table.
---
--- @usage This obtains a database reference, and queries the friends sheet for someone named Bob. As this
--- returns a table array containing only one item, it assigns that one item to the local variable named bob.
--- We then change the notes on Bob, and pass it into db:update() to save the changes back.
--- <pre>
--- local mydb = db:get_database("my database")
--- local bob = db:fetch(mydb.friends, db:eq(mydb.friends.name, "Bob"))[1]
--- bob.notes = "He's a really awesome guy."
--- db:update(mydb.friends, bob)
--- </pre>
function db:update(sheet, tbl)
assert(tbl._row_id, "Can only update a table with a _row_id")
assert(not table.is_empty(tbl), "An empty table was passed to db:update")
local db_name = sheet._db_name
local s_name = sheet._sht_name
local conn = db.__conn[db_name]
local sql_chunks = {"UPDATE OR", db.__schema[db_name][s_name].options._violations, s_name, "SET"}
local set_chunks = {}
local set_block = [["%s" = %s]]
for k, v in pairs(db.__schema[db_name][s_name]['columns']) do
if tbl[k] then
local field = sheet[k]
set_chunks[#set_chunks+1] = set_block:format(k, db:_coerce(field, tbl[k]))
end
end
sql_chunks[#sql_chunks+1] = table.concat(set_chunks, ",")
sql_chunks[#sql_chunks+1] = "WHERE _row_id = "..tbl._row_id
local sql = table.concat(sql_chunks, " ")
db:echo_sql(sql)
assert(conn:execute(sql))
if db.__autocommit[db_name] then
conn:commit()
end
end
--- The db:set function allows you to set a certain field to a certain value across an entire sheet.
--- Meaning, you can change all of the last_read fields in the sheet to a certain value, or possibly only
--- the last_read fields which are in a certain city. The query argument can be any value which is appropriate
--- for db:fetch, even nil which will change the value for the specified column for EVERY row in the sheet.
---
--- For example, consider a situation in which you are tracking how many times you find a certain
--- type of egg during Easter. You start by setting up your database and adding an Eggs sheet, and
--- then adding a record for each type of egg.
--- <pre>
--- local mydb = db:create("egg database", {eggs = {color = "", last_found = db.Timestamp(false), found = 0}})
--- db:add(mydb.eggs,
--- {color = "Red"},
--- {color = "Blue"},
--- {color = "Green"},
--- {color = "Yellow"},
--- {color = "Black"}
--- )
--- </pre>
---
--- Now, you have three columns. One is a string, one a timestamp (that ends up as nil in the database),
--- and one is a number. <br/><br/>
---
--- You can then set up a trigger to capture from the mud the string, "You pick up a (.*) egg!", and you
--- end up arranging to store the value of that expression in a variable called "myegg". <br/><br/>
---
--- To increment how many we found, we will do this:
--- <pre>
--- myegg = "Red" -- We will pretend a trigger set this.
--- db:set(mydb.eggs.found, db:exp("found + 1"), db:eq(mydb.eggs.color, myegg))
--- db:set(mydb.eggs.last_found, db.Timestamp("CURRENT_TIMESTAMP"), db:eq(mydb.eggs.color, myegg))
--- </pre>
---
--- This will go out and set two fields in the Red egg sheet; the first is the found field, which will
--- increment the value of that field (using the special db:exp function). The second will update the
--- last_found field with the current time. <br/><br/>
---
--- Once this contest is over, you may wish to reset this data but keep the database around.
--- To do that, you may use a more broad use of db:set as such:
--- <pre>
--- db:set(mydb.eggs.found, 0)
--- db:set(mydb.eggs.last_found, nil)
--- </pre>
function db:set(field, value, query)
local db_name = sheet._db_name
local s_name = sheet._sht_name
local conn = db.__conn[db_name]
local sql_update = [[UPDATE OR %s %s SET "%s" = %s]]
if query then
sql_update = sql_update .. [[ WHERE %s]]
end
local sql = sql_update:format(db.__schema[db_name][s_name].options._violations, s_name, field.name, db:_coerce(field, value), query)
db:echo_sql(sql)
assert(conn:execute(sql))
if db.__autocommit[db_name] then
conn:commit()
end
end
--- This is a debugging function, which echos any SQL commands if db.debug_sql is true.
--- You should not call this function directly from Mudlet.
---
--- @usage Set following lua variable to enable SQL echos.
--- <pre>
--- db.debug_sql=true
--- </pre>
function db:echo_sql(sql)
if db.debug_sql then
echo("\n"..sql.."\n")
end
end
-- NOT LUADOC
-- After a table so retrieved from the database, this function coerces values to
-- their proper types. Specifically, numbers and datetimes become the proper
-- types.
function db:_coerce_sheet(sheet, tbl)
if tbl then
tbl._row_id = tonumber(tbl._row_id)
for k, v in pairs(tbl) do
if k ~= "_row_id" then
local field = sheet[k]
if field.type == "number" then
tbl[k] = tonumber(tbl[k]) or tbl[k]
elseif field.type == "datetime" then
tbl[k] = db:Timestamp(datetime:parse(tbl[k], nil, true))
end
end
end
return tbl
end
end
-- NOT LUADOC
-- The function converts a Lua value into its SQL representation, depending on the
-- type of the specified field. Strings will be single-quoted (and single-quotes
-- within will be properly escaped), numbers will be rendered properly, and such.
function db:_coerce(field, value)
if field.type == "number" then
return tonumber(value) or "'"..value.."'"
elseif field.type == "datetime" then
if value._timestamp == false then
return "NULL"
else
return tonumber(value._timestamp) or "'"..value.."'"
end
else
return "'"..tostring(value):gsub("'", "''").."'"
end
end
--- Returns a database expression to test if the field in the sheet is equal to the value.
---
--- @see db:fetch
function db:eq(field, value, case_insensitive)
if case_insensitive then
local v = db:_coerce(field, value):lower()
return "lower("..field.name..") == "..v
else
local v = db:_coerce(field, value)
return field.name.." == "..v
end
end
--- Returns a database expression to test if the field in the sheet is NOT equal to the value.
---
--- @see db:fetch
function db:not_eq(field, value, case_insensitive)
if case_insensitive then
local v = db:_coerce(field, value):lower()
return "lower("..field.name..") != "..v
else
local v = db:_coerce(field, value)
return field.name.." != "..v
end
end
--- Returns a database expression to test if the field in the sheet is less than the value.
---
--- @see db:fetch
function db:lt(field, value)
local v = db:_coerce(field, value)
return field.name.." < "..v
end
--- Returns a database expression to test if the field in the sheet is less than or equal to the value.
---
--- @see db:fetch
function db:lte(field, value)
local v = db:_coerce(field, value)
return field.name.." <= "..v
end
--- Returns a database expression to test if the field in the sheet is greater than to the value.
---
--- @see db:fetch
function db:gt(field, value)
local v = db:_coerce(field, value)
return field.name.." > "..v
end
--- Returns a database expression to test if the field in the sheet is greater than or equal to the value.
---
--- @see db:fetch
function db:gte(field, value)
local v = db:_coerce(field, value)
return field.name.." >= "..v
end
--- Returns a database expression to test if the field in the sheet is nil.
---
--- @see db:fetch
function db:is_nil(field)
return field.name.." IS NULL"
end
--- Returns a database expression to test if the field in the sheet is not nil.
---
--- @see db:fetch
function db:is_not_nil(field)
return field.name.." IS NOT NULL"
end
--- Returns a database expression to test if the field in the sheet matches the specified pattern. <br/><br/>
---
--- LIKE patterns are not case-sensitive, and allow two wild cards. The first is an underscore which matches
--- any single one character. The second is a percent symbol which matches zero or more of any character.
--- <pre>
--- LIKE with "_" is therefore the same as the "." regular expression.
--- LIKE with "%" is therefore the same as ".*" regular expression.
--- </pre>
---
--- @see db:not_like
--- @see db:fetch
function db:like(field, value)
local v = db:_coerce(field, value)
return field.name.." LIKE "..v
end
--- Returns a database expression to test if the field in the sheet does not match the specified pattern.
---
--- LIKE patterns are not case-sensitive, and allow two wild cards. The first is an underscore which matches
--- any single one character. The second is a percent symbol which matches zero or more of any character.
--- <pre>
--- LIKE with "_" is therefore the same as the "." regular expression.
--- LIKE with "%" is therefore the same as ".*" regular expression.
--- </pre>
---
--- @see db:like
--- @see db:fetch
function db:not_like(field, value)
local v = db:_coerce(field, value)
return field.name.." NOT LIKE "..v
end
--- Returns a database expression to test if the field in the sheet is a value between lower_bound and upper_bound.
--- This only really makes sense for numbers and Timestamps.
---
--- @see db:not_between
--- @see db:fetch
function db:between(field, left_bound, right_bound)
local x = db:_coerce(field, left_bound)
local y = db:_coerce(field, right_bound)
return field.name.." BETWEEN "..x.." AND "..y
end
--- Returns a database expression to test if the field in the sheet is NOT a value between lower_bound and upper_bound.
--- This only really makes sense for numbers and Timestamps.
---
--- @see db:between
--- @see db:fetch
function db:not_between(field, left_bound, right_bound)
local x = db:_coerce(field, left_bound)
local y = db:_coerce(field, right_bound)
return field.name.." NOT BETWEEN "..x.." AND "..y
end
--- Returns a database expression to test if the field in the sheet is one of the values in the table array. <br/><br/>
---
--- First, note the trailing underscore carefully! It is required.
---
--- @usage The following example illustrates the use of <b>in_</b>:
--- This will obtain all of your kills which happened in the Undervault, Hell or Purgatory. Every db:in_ expression
--- can be written as a db:OR, but that quite often gets very complex.
--- <pre>
--- local mydb = db:get_database("my database")
--- local areas = {"Undervault", "Hell", "Purgatory"}
--- db:fetch(mydb.kills, db:in_(mydb.kills.area, areas))
--- </pre>
---
--- @see db:fetch
function db:in_(field, tbl)
local parts = {}
for _, v in ipairs(tbl) do
parts[#parts+1] = db:_coerce(field, v)
end
return field.name.." IN ("..table.concat(parts, ",")..")"
end
--- Returns a database expression to test if the field in the sheet is not one of the values in the table array.
---
--- @see db:in_
--- @see db:fetch
function db:not_in(field, tbl)
local parts = {}
for _, v in ipairs(tbl) do
parts[#parts+1] = db:_coerce(field, v)
end
return field.name.." NOT IN ("..table.concat(parts, ",")..")"
end
--- Returns the string as-is to the database. <br/><br/>
---
--- Use this function with caution, but it is very useful in some circumstances. One of the most
--- common of such is incrementing an existing field in a db:set() operation, as so:
--- <pre>
--- db:set(mydb.enemies, db:exp("kills + 1"), db:eq(mydb.enemies.name, "Ixokai"))
--- </pre>
---
--- This will increment the value of the kills field for the row identified by the name Ixokai. <br/><br/>
---
--- But there are other uses, as the underlining database layer provides many functions you can call
--- to do certain things. If you want to get a list of all your enemies who have a name longer then
--- 10 characters, you may do:
--- <pre>
--- db:fetch(mydb.enemies, db:exp("length(name) > 10"))
--- </pre>
---
--- Again, take special care with this, as you are doing SQL syntax directly and the library can't
--- help you get things right.
---
--- @see db:fetch
function db:exp(text)
return text
end
--- Returns a compound database expression that combines all of the simple expressions passed into it.
--- These expressions should be generated with other db: functions such as db:eq, db:like, db:lt and the like. <br/><br/>
---
--- This compound expression will only find items in the sheet if all sub-expressions match.
---
--- @see db:fetch
function db:AND(...)
local parts = {}
for _, expression in ipairs({...}) do
parts[#parts+1] = "("..expression..")"
end
return "("..table.concat(parts, " AND ")..")"
end
--- Returns a compound database expression that combines both of the simple expressions passed into it.
--- These expressions should be generated with other db: functions such as db:eq, db:like, db:lt and the like. <br/><br/>
---
--- This compound expression will find any item that matches either the first or the second sub-expression.
---
--- @see db:fetch
function db:OR(left, right)
if not string.starts(left, "(") then
left = "("..left..")"
end
if not string.starts(right, "(") then
right = "("..right..")"
end
return left.." OR "..right
end
--- <b><u>TODO</u></b>
function db:close()
for _, c in pairs(db.__conn) do
c:close()
end
db.__env:close()
end
-- Timestamp support
db.__Timestamp = {}
db.__TimestampMT = {
__index = db.__Timestamp
}
function db.__Timestamp:as_string(format)
if not format then
format = "%m-%d-%Y %H:%M:%S"
end
return os.date(format, self._timestamp)
end
function db.__Timestamp:as_table()
return os.date("*t", self._timestamp)
end
function db.__Timestamp:as_number()
return self._timestamp
end
--- <b><u>TODO</u></b>
function db:Timestamp(ts, fmt)
local dt = {}
if type(ts) == "table" then
dt._timestamp = os.time(ts)
elseif type(ts) == "number" then
dt._timestamp = ts
elseif type(ts) == "string" and
assert(ts == "CURRENT_TIMESTAMP", "The only strings supported by db.DateTime:new is CURRENT_TIMESTAMP") then
dt._timestamp = "CURRENT_TIMESTAMP"
elseif ts == nil then
dt._timestamp = false
else
assert(nil, "Invalid value passed to db.Timestamp()")
end
return setmetatable(dt, db.__TimestampMT)
end
-- function db.Timestamp:new(ts, fmt)
-- local dt = {}
-- if type(ts) == "table" then
-- dt._timestamp = os.time(ts)
-- elseif type(ts) == "number" then
-- dt._timestamp = ts
-- elseif assert(ts == "CURRENT_TIMESTAMP", "The only strings supported by db.DateTime:new is CURRENT_TIMESTAMP") then
-- dt._timestamp = "CURRENT_TIMESTAMP"
-- end
-- return setmetatable(dt, db.__TimestampMT)
-- end
db.Field = {}
db.__FieldMT = {
__index = db.Field
}
db.Sheet = {}
db.__SheetMT = {
__index = function(t, k)
local v = rawget(db.Sheet, k)
if v then
return v
end
local db_name = rawget(t, "_db_name")
local sht_name = rawget(t, "_sht_name")
local f_name = k:lower()
local errormsg = "Attempt to access field %s in sheet %s in database %s that does not exist."
local field = db.__schema[db_name][sht_name]['columns'][f_name]
if assert(field, errormsg:format(k, sht_name, db_name)) then
type_ = type(field)
if type_ == "table" and field._timestamp then
type_ = "datetime"
end
rt = setmetatable({database=db_name, sheet=sht_name, type=type_, name=f_name}, db.__FieldMT)
rawset(t,k,rt)
return rt
end
end
}
db.Database = {}
db.__DatabaseMT = {
__index = function(t, k)
local v = rawget(t, k)
if v then
return v
end
local v = rawget(db.Database, k)
if v then
return v
end
local db_name = rawget(t, "_db_name")
if assert(db.__schema[db_name][k:lower()], "Attempt to access sheet '"..k:lower().."'in db '"..db_name.."' that does not exist.") then
rt = setmetatable({_db_name = db_name, _sht_name = k:lower()}, db.__SheetMT)
rawset(t,k,rt)
return rt
end
end
}
function db.Database:_begin()
db.__autocommit[self._db_name] = false
end
function db.Database:_commit()
local conn = db.__conn[self._db_name]
conn:commit()
end
function db.Database:_rollback()
local conn = db.__conn[self._db_name]
conn:rollback()
end
function db.Database:_end()
db.__autocommit[self._db_name] = true
end
function db.Database._drop(s_name)
local conn = db.__conn[self._db_name]
local schema = db.__schema[self._db_name]
if schema.options._index then
for _, value in schema.options._index do
conn:execute("DROP INDEX IF EXISTS " .. db:_index_name(s_name, value))
end
end
if schema.options._unique then
for _, value in schema.options._unique do
conn:execute("DROP INDEX IF EXISTS " .. db:_index_name(s_name, value))
end
end
conn:execute("DROP TABLE IF EXISTS "..s_name)
conn:commit()
end
--- Returns a reference of an already existing database. This instance can be used to get references
--- to the sheets (and from there, fields) that are defined within the database. You use these
--- references to construct queries. <br/><br/>
---
--- These references do not contain any actual data, they only point to parts of the database structure.
---
--- @usage If a database has a sheet named enemies, you can obtain a reference to that sheet by simply doing:
--- <pre>
--- local mydb = db:get_database("my database")
--- local enemies_ref = mydb.enemies
--- local name_ref = mydb.enemies.name
--- </pre>
function db:get_database(db_name)
db_name = db:safe_name(db_name)
assert(db.__schema[db_name], "Attempt to access database that does not exist.")
db_inst = {_db_name = db_name}
return setmetatable(db_inst, db.__DatabaseMT)
end
| gpl-2.0 |
DeinFreund/Zero-K | scripts/turrettorp.lua | 16 | 2934 | include "constants.lua"
local base = piece 'base'
local arm1 = piece 'arm1'
local arm2 = piece 'arm2'
local turret = piece 'turret'
local firepoint = piece 'firepoint'
local waterFire = false
local smokePiece = {base}
-- Signal definitions
local SIG_AIM = 2
local function Bob(rot)
while true do
Turn(base, x_axis, math.rad(rot + math.random(-5,5)), math.rad(math.random(1,2)))
Turn(base, z_axis, math.rad(math.random(-5,5)), math.rad(math.random(1,2)))
Move(base, y_axis, 48 + math.rad(math.random(0,2)), math.rad(math.random(1,2)))
Sleep(2000)
Turn(base, x_axis, math.rad(rot + math.random(-5,5)), math.rad(math.random(1,2)))
Turn(base, z_axis, math.rad(math.random(-5,5)), math.rad(math.random(1,2)))
Move(base, y_axis, 48 + math.rad(math.random(-2,0)), math.rad(math.random(1,2)))
Sleep(1000)
end
end
function script.Create()
--while select(5, Spring.GetUnitHealth(unitID)) < 1 do
-- Sleep(400)
--end
local x,_,z = Spring.GetUnitBasePosition(unitID)
local y = Spring.GetGroundHeight(x,z)
if y > 0 then
Turn(arm1, z_axis, math.rad(-70), math.rad(80))
Turn(arm2, z_axis, math.rad(70), math.rad(80))
Move(base, y_axis, 20, 25)
elseif y > -19 then
StartThread(Bob, 0)
else
waterFire = true
StartThread(Bob, 180)
Turn(base, x_axis, math.rad(180))
Move(base, y_axis, 48)
Turn(arm1, x_axis, math.rad(180))
Turn(arm2, x_axis, math.rad(180))
--Turn(turret, x_axis, math.rad(0))
end
StartThread(SmokeUnit, smokePiece)
end
function script.AimWeapon1(heading, pitch)
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
if waterFire then
Turn(turret, y_axis, -heading + math.pi, math.rad(120))
else
Turn(turret, y_axis, heading, math.rad(120))
end
WaitForTurn(turret, y_axis)
return true
end
function script.FireWeapon(num)
local px, py, pz = Spring.GetUnitPosition(unitID)
if waterFire then
Spring.PlaySoundFile("sounds/weapon/torpedo.wav", 10, px, py, pz)
else
Spring.PlaySoundFile("sounds/weapon/torp_land.wav", 10, px, py, pz)
end
end
function script.AimFromWeapon(num)
return base
end
function script.QueryWeapon(num)
return firepoint
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity <= .25 then
Explode(base, sfxNone)
Explode(firepoint, sfxNone)
Explode(arm1, sfxNone)
Explode(turret, sfxNone)
return 1
elseif severity <= .50 then
Explode(base, sfxNone)
Explode(firepoint, sfxFall)
Explode(arm2, sfxShatter)
Explode(turret, sfxFall)
return 1
elseif severity <= .99 then
Explode(base, sfxNone)
Explode(firepoint, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(arm1, sfxShatter)
Explode(turret, sfxFall + sfxSmoke + sfxFire + sfxExplode)
return 2
else
Explode(base, sfxNone)
Explode(firepoint, sfxFall + sfxSmoke + sfxFire + sfxExplode)
Explode(arm2, sfxShatter + sfxExplode)
Explode(turret, sfxFall + sfxSmoke + sfxFire + sfxExplode)
return 2
end
end
| gpl-2.0 |
DeinFreund/Zero-K | effects/nuke_600.lua | 24 | 15878 | -- nuke_600_landcloud_pillar
-- nuke_600_landcloud_topcap
-- nuke_600_seacloud_cap
-- nuke_600_landcloud
-- nuke_600_seacloud_topcap
-- nuke_600_landcloud_ring
-- nuke_600_seacloud
-- nuke_600_landcloud_cap
-- nuke_600
-- nuke_600_seacloud_ring
-- nuke_600_seacloud_pillar
return {
["nuke_600_landcloud_pillar"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0.5 1 1 0.75 0.5 0.75 0.25 0.25 0.25 0.5 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 1,
particlelife = 240,
particlelifespread = 40,
particlesize = 4,
particlesizespread = 4,
particlespeed = 1,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 64,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
["nuke_600_landcloud_topcap"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0 1 1 1 1 0.75 0.25 0.25 0.25 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 4,
particlelife = 240,
particlelifespread = 40,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 64,
sizemod = 0.75,
texture = [[fireball]],
},
},
},
["nuke_600_seacloud_cap"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 4,
particlelife = 30,
particlelifespread = 20,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 64,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
["nuke_600_landcloud"] = {
usedefaultexplosions = false,
cap = {
air = true,
class = [[CExpGenSpawner]],
count = 96,
ground = true,
water = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_LANDCLOUD_CAP]],
pos = [[0, i8, 0]],
},
},
pillar = {
air = true,
class = [[CExpGenSpawner]],
count = 128,
ground = true,
water = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_LANDCLOUD_PILLAR]],
pos = [[0, i8, 0]],
},
},
ring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
properties = {
delay = 64,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_LANDCLOUD_RING]],
pos = [[0, 512, 0]],
},
},
topcap = {
air = true,
class = [[CExpGenSpawner]],
count = 32,
ground = true,
water = true,
properties = {
delay = [[96 i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_LANDCLOUD_TOPCAP]],
pos = [[0, 768 i8, 0]],
},
},
},
["nuke_600_seacloud_topcap"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 4,
particlelife = 240,
particlelifespread = 40,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 64,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
["nuke_600_landcloud_ring"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0.75 1 1 0.75 0.5 1 0.75 0.75 0.75 1 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 128,
particlelife = 240,
particlelifespread = 40,
particlesize = 4,
particlesizespread = 4,
particlespeed = 16,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 32,
sizemod = 0.5,
texture = [[smokesmall]],
},
},
},
["nuke_600_seacloud"] = {
usedefaultexplosions = false,
cap = {
air = true,
class = [[CExpGenSpawner]],
count = 96,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_SEACLOUD_CAP]],
pos = [[0, i8, 0]],
},
},
pillar = {
air = true,
class = [[CExpGenSpawner]],
count = 128,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_SEACLOUD_PILLAR]],
pos = [[0, i8, 0]],
},
},
ring = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
delay = 64,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_SEACLOUD_RING]],
pos = [[0, 512, 0]],
},
},
topcap = {
air = true,
class = [[CExpGenSpawner]],
count = 32,
ground = true,
water = true,
underwater = true,
properties = {
delay = [[96 i1]],
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_SEACLOUD_TOPCAP]],
pos = [[0, 768 i8, 0]],
},
},
},
["nuke_600_landcloud_cap"] = {
land = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 1 1 0 1 1 1 1 0.75 0.25 0.25 0.25 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 4,
particlelife = 30,
particlelifespread = 20,
particlesize = 4,
particlesizespread = 4,
particlespeed = 4,
particlespeedspread = 4,
pos = [[0, 0, 0]],
sizegrowth = 64,
sizemod = 0.75,
texture = [[fireball]],
},
},
},
["nuke_600"] = {
usedefaultexplosions = false,
groundflash = {
alwaysvisible = true,
circlealpha = 1,
circlegrowth = 10,
flashalpha = 0.5,
flashsize = 1200,
ttl = 60,
color = {
[1] = 1,
[2] = 0.5,
[3] = 0,
},
},
landcloud = {
air = true,
class = [[CExpGenSpawner]],
count = 1,
ground = true,
properties = {
delay = 30,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_LANDCLOUD]],
pos = [[0, 0, 0]],
},
},
landdirt = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
properties = {
airdrag = 0.95,
alwaysvisible = true,
colormap = [[0 0 0 0 0.5 0.4 0.3 1 0.6 0.4 0.2 0.75 0.5 0.4 0.3 0.5 0 0 0 0]],
directional = false,
emitrot = 85,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.025, 0]],
numparticles = 64,
particlelife = 120,
particlelifespread = 20,
particlesize = 4,
particlesizespread = 4,
particlespeed = 2,
particlespeedspread = 12,
pos = [[0, 0, 0]],
sizegrowth = 32,
sizemod = 0.75,
texture = [[dirt]],
},
},
pikes = {
air = true,
class = [[explspike]],
count = 32,
ground = true,
water = true,
properties = {
alpha = 1,
alphadecay = 0.006,
alwaysvisible = true,
color = [[1,0.5,0.1]],
dir = [[-8 r16, -8 r16, -8 r16]],
length = 1,
lengthgrowth = 1,
width = 64,
},
},
seacloud = {
class = [[CExpGenSpawner]],
count = 1,
water = true,
underwater = true,
properties = {
delay = 30,
dir = [[dir]],
explosiongenerator = [[custom:NUKE_600_SEACLOUD]],
pos = [[0, 0, 0]],
},
},
sphere = {
air = true,
class = [[CSpherePartSpawner]],
count = 1,
ground = true,
water = true,
properties = {
alpha = 0.5,
alwaysvisible = true,
color = [[1,1,0.5]],
expansionspeed = 15,
ttl = 80,
},
},
watermist = {
class = [[CSimpleParticleSystem]],
count = 1,
water = true,
underwater = true,
properties = {
airdrag = 0.99,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, -0.05, 0]],
numparticles = 64,
particlelife = 80,
particlelifespread = 20,
particlesize = 7,
particlesizespread = 4,
particlespeed = 8,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 2,
sizemod = 1,
texture = [[smokesmall]],
},
},
},
["nuke_600_seacloud_ring"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 90,
emitrotspread = 5,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 128,
particlelife = 240,
particlelifespread = 40,
particlesize = 4,
particlesizespread = 4,
particlespeed = 16,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 32,
sizemod = 0.5,
texture = [[smokesmall]],
},
},
},
["nuke_600_seacloud_pillar"] = {
cloud = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
underwater = true,
properties = {
airdrag = 0.97,
alwaysvisible = true,
colormap = [[0 0 0 0 0.8 0.8 1 1 0.8 0.8 1 0.75 0.8 0.8 1 0.5 0 0 0 0]],
directional = false,
emitrot = 0,
emitrotspread = 90,
emitvector = [[0, 1, 0]],
gravity = [[0, 0.05, 0]],
numparticles = 1,
particlelife = 240,
particlelifespread = 40,
particlesize = 4,
particlesizespread = 4,
particlespeed = 1,
particlespeedspread = 1,
pos = [[0, 0, 0]],
sizegrowth = 64,
sizemod = 0.75,
texture = [[smokesmall]],
},
},
},
}
| gpl-2.0 |
AresTao/darkstar | scripts/globals/spells/bluemagic/smite_of_rage.lua | 28 | 1707 | -----------------------------------------
-- Spell: Smite of Rage
-- Damage varies with TP
-- Spell cost: 28 MP
-- Monster Type: Arcana
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 3
-- Stat Bonus: AGI+3
-- Level: 34
-- Casting Time: 0.5 seconds
-- Recast Time: 13 seconds
-- Skillchain Element(s): Wind (can open Scission or Gravitation; can close Detonation)
-- Combos: Undead Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_DAMAGE;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_DETONATION;
params.numhits = 1;
params.multiplier = 1.5;
params.tp150 = 2.25;
params.tp300 = 2.5;
params.azuretp = 2.53125;
params.duppercap = 35;
params.str_wsc = 0.2;
params.dex_wsc = 0.2;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
AresTao/darkstar | scripts/globals/spells/bluemagic/power_attack.lua | 28 | 1761 | -----------------------------------------
-- Spell: Power Attack
-- Deals critical damage. Chance of critical hit varies with TP
-- Spell cost: 5 MP
-- Monster Type: Vermin
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 1
-- Stat Bonus: MND+1
-- Level: 4
-- Casting Time: 0.5 seconds
-- Recast Time: 7.25 seconds
-- Skillchain property: Reverberation (Can open Impaction or Induration)
-- Combos: Plantoid Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_CRITICAL;
params.dmgtype = DMGTYPE_BLUNT;
params.scattr = SC_REVERBERATION;
params.numhits = 1;
params.multiplier = 1.125;
params.tp150 = 0.5;
params.tp300 = 0.7;
params.azuretp = 0.8;
params.duppercap = 11; -- guesstimated crit %s for TP
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.3;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
antoniova/nes | output/luaScripts/BugsBunnyBirthdayBlowout.lua | 9 | 5535 | --Bugs Bunny Birthday Blowout
--Written by XKeeper
--Creates Lag and Sprite counters as well as Camera position
-- ************************************************************************************
-- ************************************************************************************
-- ************************************************************************************
function box(x1,y1,x2,y2,color)
if (x1 >= 0 and x1 <= 255 and x2 >= 0 and x2 <= 255 and y1 >= 0 and y1 <= 244 and y2 >= 0 and y2 <= 244) then
gui.drawbox(x1,y1,x2,y2,color);
end;
end;
-- ************************************************************************************
-- ************************************************************************************
-- ************************************************************************************
function filledbox(x1,y1,x2,y2,color)
for i = 0, math.abs(y1 - y2) do
line(x1,y1 + i,x2,y1 + i,color);
end;
end;
-- ************************************************************************************
-- ************************************************************************************
-- ************************************************************************************
function lifebar(x, y, sx, sy, a1, a2, oncolor, offcolor, noborder)
-- this function will have the effect of drawing an HP bar
-- keep in mind xs and ys are 2px larger to account for borders
x1 = x;
x2 = x + sx + 4;
y1 = y;
y2 = y + sy + 4;
w = math.floor(a1 / math.max(1, a1, a2) * sx);
if not a2 then w = 0 end;
if (noborder) then
box(x1 + 1, y1 + 1, x2 - 1, y2 - 1, "#000000");
else
box(x1 + 1, y1 + 1, x2 - 1, y2 - 1, "#ffffff");
box(x1 , y1 , x2 , y2 , "#000000");
end;
if (w < sx) then
filledbox(x1 + w + 2, y1 + 2, x2 - 2, y2 - 2, offcolor);
end;
if (w > 0) then
filledbox(x1 + 2, y1 + 2, x1 + 2 + w, y2 - 2, oncolor);
end;
end;
-- ************************************************************************************
-- ************************************************************************************
-- ************************************************************************************
function line(x1,y1,x2,y2,color)
if (x1 >= 0 and x1 <= 255 and x2 >= 0 and x2 <= 255 and y1 >= 0 and y1 <= 244 and y2 >= 0 and y2 <= 244) then
local success = pcall(function() gui.drawline(x1,y1,x2,y2,color) end);
if not success then
text(60, 224, "ERROR: ".. x1 ..",".. y1 .." ".. x2 ..",".. y2);
end;
end;
end;
function text(x,y,str)
if (x >= 0 and x <= 255 and y >= 0 and y <= 240) then
gui.text(x,y,str);
end;
end;
function pixel(x,y,color)
if (x >= 0 and x <= 255 and y >= 0 and y <= 240) then
gui.drawpixel(x,y,color);
end;
end;
function drawpos(cx, cy, ex, ey, n)
sx = ex - cx;
sy = ey - cy;
num = "";
if n then
num = string.format("%02X", n);
end;
if sx >= 0 and sx <= 255 and sy >= 0 and sy <= 244 then
line(sx, sy, sx + 16, sy + 0, "#ff0000");
line(sx, sy, sx + 0, sy + 16, "#ff0000");
text(sx, sy, num);
elseif sx < 0 and sy >= 0 and sy <= 244 then
line(0, sy, 16, sy, "#ff0000");
text(4, sy, num);
elseif sx > 255 and sy >= 0 and sy <= 244 then
line(239, sy, 255, sy, "#ff0000");
text(243, sy, num);
elseif sy < 0 and sx >= 0 and sx <= 256 then
line(sx, 8, sx, 24, "#ff0000");
text(sx, 8, num);
elseif sy > 244 and sx >= 0 and sx <= 256 then
line(sx, 212, sx, 244, "#ff0000");
text(sx, 216, num);
end;
end;
lagdetectorold = 0;
timer = 0;
lagframes = 0;
lastlag = 0;
while (true) do
timer = timer + 1;
lagdetector = memory.readbyte(0x00f5);
-- if lagdetector == lagdetectorold then
if AND(lagdetector, 0x20) == 0x20 then
-- if lagdetector == 0x0C then
lagframes = lagframes + 1;
else
if lagframes ~= 0 then
lastlag = lagframes;
end;
lagframes = 0;
lagdetectorold = lagdetector;
end;
memory.writebyte(0x00f5, OR(lagdetector, 0x20));
playerx = memory.readbyte(0x0432) + memory.readbyte(0x0433) * 0x100;
playery = memory.readbyte(0x0435) + memory.readbyte(0x0436) * 0x100;
screenx = memory.readbyte(0x0456) + memory.readbyte(0x0457) * 0x100;
screeny = memory.readbyte(0x0458) + memory.readbyte(0x0459) * 0x100;
text( 8, 8, string.format("%04X, %04X", playerx, playery));
text( 8, 16, string.format("%04X, %04X", screenx, screeny));
drawpos(screenx, screeny, playerx, playery);
tmp = 0;
for i = 0, 0xb do
offset = 0x7680 + i * 0x20;
enemyt = memory.readbyte(offset);
enemyx = memory.readbyte(offset + 2) + memory.readbyte(offset + 3) * 0x100;
enemyy = memory.readbyte(offset + 4) + memory.readbyte(offset + 5) * 0x100;
if enemyt ~= 0xff then
-- text(160, 8 + 8 * tmp, string.format("%02X: %02X <%04X, %04X>", i, enemyt, enemyx, enemyy));
drawpos(screenx, screeny, enemyx, enemyy, i);
tmp = tmp + 1;
end
end;
text(142, 192, string.format("%02d lag frames", lastlag));
text(142, 216, string.format("%02d active sprites", tmp));
-- box(2, 208, 2 + 8 * lastlag, 210, "#ff4444");
-- box(2, 209, 2 + 8 * lastlag, 211, "#ff4444");
-- box(2, 212, 2 + 8 * tmp, 213, "#4444ff");
-- box(2, 214, 2 + 8 * tmp, 215, "#4444ff");
lifebar(144, 200, 100, 4, lastlag, 8, "#ffcc22", "#000000");
lifebar(144, 208, 100, 4, tmp, 12, "#4488ff", "#000000");
FCEU.frameadvance();
end;
| gpl-2.0 |
DeinFreund/Zero-K | LuaRules/Gadgets/cmd_remove_wait.lua | 7 | 1499 | if not gadgetHandler:IsSyncedCode() then
return
end
function gadget:GetInfo()
return {
name = "Remove Wait",
desc = "Removes wait from structures which have no need for the command.",
author = "GoogleFrog",
date = "3 April 2015",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true,
}
end
local spRemoveUnitCmdDesc = Spring.RemoveUnitCmdDesc
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local CMD_WAIT = CMD.WAIT
local removeCommands = {
CMD.WAIT,
CMD.STOP,
CMD.REPEAT,
}
local waitRemoveDefs = {}
for unitDefID = 1, #UnitDefs do
local ud = UnitDefs[unitDefID]
if ud.customParams and ud.customParams.removewait then
waitRemoveDefs[unitDefID] = true
end
end
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_WAIT] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return waitRemoveDefs
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if (cmdID == CMD_WAIT and waitRemoveDefs[unitDefID]) then
return false
end
return true
end
function gadget:UnitCreated(unitID, unitDefID)
if waitRemoveDefs[unitDefID] then
for i = 1, #removeCommands do
local cmdDesc = spFindUnitCmdDesc(unitID, removeCommands[i])
if cmdDesc then
spRemoveUnitCmdDesc(unitID, cmdDesc)
end
end
end
end
function gadget:Initialize()
-- load active units
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
gadget:UnitCreated(unitID, unitDefID)
end
end | gpl-2.0 |
AresTao/darkstar | scripts/globals/items/heat_rod.lua | 41 | 1097 | -----------------------------------------
-- ID: 17071
-- Item: Heat Rod
-- Additional Effect: Lightning Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(5,20);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHTNING, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHTNING,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHTNING);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHTNING,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHTNING_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Eastern_Altepa_Desert/mobs/Cactrot_Rapido.lua | 16 | 12212 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NM: Cactrot Rapido
-----------------------------------
require("scripts/globals/titles");
local path = {
-45.214237, 0.059482, -204.244873,
-46.114422, 0.104212, -203.765884,
-47.013275, 0.149004, -203.285812,
-47.911877, 0.193759, -202.805313,
-58.443733, 0.767810, -197.319977,
-61.495697, 0.477824, -195.851227,
-64.869675, 0.109868, -194.287720,
-75.073441, 0.254733, -189.665695,
-81.320366, 0.495319, -186.993607,
-91.067123, 0.288822, -183.020676,
-97.377228, -0.392546, -180.579071,
-99.247047, -0.895448, -179.936798,
-100.800270, -1.393698, -179.434647,
-102.352448, -1.900111, -178.961166,
-103.899933, -2.504567, -178.528854,
-105.126732, -3.031813, -178.190872,
-106.367256, -3.527977, -177.907257,
-107.613914, -4.023795, -177.639709,
-108.867058, -4.500517, -177.388947,
-110.153046, -4.924853, -177.183960,
-111.440956, -5.322861, -177.007553,
-112.735832, -5.956526, -176.851334,
-114.710777, -5.139105, -176.495575,
-116.667969, -4.440962, -176.081223,
-117.885887, -3.910276, -175.532532,
-119.009041, -3.591512, -174.816345,
-120.015816, -3.243386, -173.936310,
-120.987274, -2.875988, -173.018311,
-121.980667, -2.569070, -172.122421,
-122.732048, -2.157357, -171.448853,
-125.173172, -0.957143, -169.194305,
-125.936897, -0.534065, -168.118042,
-126.509903, -0.232718, -167.291153,
-127.278130, 0.155391, -166.201279,
-128.056259, 0.507568, -165.116730,
-128.636505, 0.869508, -164.300949,
-136.568512, 3.083321, -153.014694,
-136.977478, 3.211246, -152.089355,
-137.378784, 3.349919, -151.163742,
-137.792618, 3.493883, -150.238480,
-138.222778, 3.588699, -149.317413,
-139.789780, 4.143739, -145.951996,
-140.113312, 4.375872, -144.993851,
-140.287079, 4.543484, -143.998215,
-140.466980, 4.650395, -142.999802,
-140.650879, 4.757523, -142.002258,
-140.834824, 4.864695, -141.004730,
-141.029587, 4.938367, -140.006378,
-141.407669, 5.135919, -138.010376,
-141.643478, 5.328803, -136.341202,
-141.718018, 5.393569, -135.328995,
-141.813690, 5.423491, -134.313965,
-141.928970, 5.490732, -132.961258,
-142.095245, 5.603091, -130.931778,
-142.253555, 5.573742, -129.240341,
-142.852249, 5.496122, -123.503990,
-143.283661, 5.484383, -119.451439,
-143.331360, 5.500263, -118.093521,
-143.367279, 5.357600, -117.080986,
-143.595398, 4.682551, -114.444756,
-143.761444, 4.288168, -113.153831,
-143.944153, 3.851855, -111.863541,
-144.114670, 3.081480, -110.600967,
-144.374863, 2.389771, -109.383690,
-144.561234, 1.352810, -107.876305,
-144.406784, 0.635471, -106.733185,
-144.221008, -0.194526, -105.556168,
-143.877808, -0.956815, -104.450096,
-143.333038, -1.686279, -103.367638,
-142.964157, -2.185963, -102.417923,
-142.580856, -1.692963, -101.476410,
-142.176361, -1.494776, -100.551079,
-141.584686, -1.078624, -99.351585,
-141.150131, -0.753439, -98.444046,
-140.304092, -0.076350, -96.605209,
-138.948074, 0.686977, -93.901413,
-138.008743, 1.152010, -92.116440,
-136.429688, 1.963583, -89.143188,
-134.031357, 2.365622, -84.672249,
-133.287766, 2.253940, -83.149849,
-131.816559, 1.901823, -80.109253,
-129.684540, 1.223290, -75.525696,
-126.872261, 0.516513, -69.392265,
-124.933060, 0.570506, -65.425987,
-122.093231, 0.971921, -59.642326,
-121.642838, 0.935626, -58.728325,
-109.254097, -0.174285, -33.826805,
-107.579643, -0.704243, -30.530849,
-104.290489, -2.292845, -24.004328,
-103.340012, -2.798456, -22.273823,
-101.417862, -3.851769, -18.828547,
-97.400208, -5.963912, -11.658532,
-96.157463, -6.415525, -9.279702,
-94.492889, -7.087772, -6.000663,
-87.445793, -8.721937, 8.182076,
-82.627701, -10.710227, 17.341963,
-78.738350, -12.969520, 24.556398,
-77.843742, -12.820852, 24.081251,
-76.622406, -12.841505, 24.162075,
-75.760681, -13.003385, 24.680101,
-74.814415, -13.116152, 25.040958,
-73.821739, -13.185088, 25.261553,
-72.808220, -13.145959, 25.357367,
-71.794624, -13.038998, 25.335396,
-70.787224, -12.916903, 25.232685,
-69.777863, -12.797923, 25.146303,
-68.767639, -12.701465, 25.068045,
-67.753258, -12.639880, 24.988928,
-66.398720, -12.608677, 24.871193,
-63.693352, -12.663887, 24.614614,
-61.332371, -12.802485, 24.348162,
-50.877781, -13.008631, 23.174417,
-49.525688, -12.897259, 23.080366,
-44.121357, -12.405771, 22.702574,
-41.750877, -12.331022, 22.526335,
-31.591017, -12.228968, 21.767466,
-30.574598, -12.240875, 21.682938,
-28.892553, -12.373736, 21.497755,
-26.193161, -12.326892, 21.279018,
-25.180489, -12.211316, 21.241808,
-23.829905, -12.058004, 21.196482,
-18.073771, -11.557770, 20.988880,
-15.020272, -11.416804, 20.876867,
-10.272671, -11.514080, 20.625463,
-5.530938, -11.567481, 20.363932,
-2.144115, -11.611256, 20.183678,
1.250314, -11.545613, 20.013973,
4.980156, -11.624237, 19.813007,
6.658255, -11.886693, 19.655684,
7.651558, -12.083179, 19.533247,
8.947555, -12.524771, 19.332045,
10.214692, -12.953741, 19.087330,
11.502657, -13.320731, 18.860584,
12.780280, -13.754982, 18.569122,
14.030073, -14.196076, 18.227663,
15.295671, -14.636890, 17.897783,
16.523689, -15.021481, 17.490923,
18.113350, -15.462179, 17.026085,
19.330448, -16.081728, 16.884964,
20.436007, -16.775909, 16.924559,
21.711395, -17.273441, 16.566978,
23.008286, -17.863113, 16.240875,
25.600761, -16.349407, 15.708939,
27.885015, -14.547360, 15.286979,
29.175026, -13.795184, 15.093222,
31.474035, -12.003471, 14.741585,
32.733868, -11.282872, 14.418842,
34.007584, -10.686451, 14.024928,
35.271973, -10.187914, 13.686438,
36.557934, -9.658462, 13.328313,
38.519291, -9.480738, 12.813184,
42.436985, -9.212695, 11.718233,
43.381554, -9.141721, 11.339855,
44.327057, -9.046030, 10.973053,
45.586422, -8.833047, 10.505932,
53.230701, -8.530454, 7.711083,
55.138641, -8.453061, 6.993709,
59.573353, -7.617370, 5.394830,
69.459343, -7.685488, 1.939287,
72.022415, -7.802935, 1.038878,
72.933075, -7.848290, 0.582272,
73.840149, -7.893467, 0.117998,
74.749786, -7.938770, -0.341271,
75.661224, -7.972084, -0.797652,
76.574295, -7.968478, -1.252196,
83.864113, -7.963341, -4.913532,
85.353340, -7.848778, -5.726798,
92.465195, -7.863905, -9.688751,
93.283051, -7.853431, -10.298190,
94.106422, -7.894407, -10.898237,
94.932503, -7.953709, -11.493578,
95.759720, -8.025735, -12.087400,
102.684669, -8.555371, -16.980604,
103.452599, -8.716061, -17.633831,
104.192497, -8.917103, -18.314260,
105.165489, -9.238935, -19.207094,
106.146698, -9.576337, -20.094185,
107.875641, -10.310707, -21.564810,
110.510101, -11.774194, -23.772697,
112.850891, -11.348615, -25.616978,
113.918427, -10.971118, -26.418327,
114.921410, -10.609308, -27.303473,
115.544731, -10.389357, -28.099230,
116.108887, -10.155023, -28.928883,
116.677101, -9.907154, -29.764107,
117.259628, -9.660060, -30.577936,
117.841934, -9.415455, -31.403658,
118.628448, -9.101988, -32.489857,
119.226006, -8.906536, -33.291828,
121.370842, -8.177029, -36.269379,
121.892303, -8.089925, -37.141682,
122.419975, -8.003403, -38.010284,
123.126312, -8.000000, -39.172443,
124.321335, -7.985068, -41.228336,
124.715233, -7.965429, -42.168995,
125.117836, -7.945378, -43.105942,
125.524841, -7.925108, -44.041027,
125.932388, -7.857445, -44.973671,
126.477409, -7.837416, -46.216499,
128.163406, -7.896171, -50.290894,
128.435196, -7.838074, -51.272820,
128.713623, -7.837389, -52.253597,
129.000900, -7.732649, -53.228714,
129.289841, -7.648998, -54.203396,
129.763367, -7.580074, -56.180931,
129.849594, -7.588713, -57.197235,
129.947464, -7.598557, -58.212494,
130.050140, -7.608885, -59.227268,
130.154587, -7.632762, -60.241852,
130.148819, -7.683857, -61.259670,
129.995834, -7.740675, -62.266739,
129.800461, -7.810890, -63.265373,
129.614334, -7.882718, -64.265656,
129.431046, -7.955023, -65.266464,
129.248032, -8.027370, -66.267303,
128.941101, -8.148669, -67.934982,
128.592590, -8.226739, -69.244926,
128.169174, -8.255370, -70.171631,
127.624290, -8.259485, -71.033081,
127.052391, -8.258126, -71.877647,
126.489380, -8.258752, -72.728165,
125.929886, -8.260109, -73.581032,
125.371674, -8.261738, -74.434708,
124.246277, -8.290220, -76.135551,
123.706482, -8.174309, -76.993515,
122.960106, -8.099961, -78.127975,
121.970772, -8.000000, -79.504745,
121.232613, -8.000000, -80.207413,
120.399490, -8.000000, -80.794556,
119.492821, -8.000000, -81.260330,
118.549973, -8.000000, -81.649460,
117.614258, -8.000000, -82.055428,
116.680702, -8.000000, -82.466354,
115.746910, -8.000000, -82.876801,
114.813171, -7.956547, -83.285782,
113.566681, -7.910290, -83.827690,
111.362625, -7.895653, -84.719353,
110.370857, -7.837558, -84.951813,
109.379196, -7.779317, -85.183273,
108.389091, -7.722087, -85.421638,
107.398117, -7.713781, -85.657982,
106.404572, -7.742430, -85.887161,
100.443123, -7.914205, -87.261345,
78.931618, -9.066314, -92.160812,
78.006859, -9.174266, -92.574493,
77.191170, -9.243567, -93.175354,
76.518112, -9.365136, -93.929840,
75.956619, -9.517926, -94.767433,
75.396698, -9.684797, -95.603516,
74.836777, -9.851719, -96.439613,
74.276855, -10.018639, -97.275703,
73.716927, -10.185554, -98.111778,
73.157005, -10.352473, -98.947868,
72.037186, -10.691887, -100.619995,
65.185234, -12.325055, -110.974182,
64.502304, -12.210523, -112.137856,
63.758068, -12.309777, -113.272629,
60.121979, -12.452700, -119.008751,
57.324074, -12.271764, -123.665543,
54.016415, -11.951966, -129.203384,
51.480064, -12.026159, -133.225754,
50.535629, -12.216867, -134.627289,
49.575897, -12.556334, -136.002838,
48.761570, -12.911916, -137.027985,
47.980934, -13.217538, -138.086014,
45.906788, -14.359197, -140.978027,
45.197201, -13.630539, -142.093567,
44.498314, -12.896272, -143.199234,
43.958618, -12.095625, -144.064774,
42.670326, -11.275743, -146.004883,
36.821983, -8.478559, -154.982544,
33.769165, -7.889951, -159.845291,
28.914276, -7.639688, -167.631866,
22.451923, -4.734315, -177.783630,
20.719790, -3.657952, -180.643219,
20.171061, -3.421347, -181.483154,
19.586971, -3.203986, -182.310669,
18.478239, -2.926458, -182.771957,
17.234682, -2.637700, -182.976196,
16.290546, -2.427790, -183.316666,
15.309304, -2.271078, -183.548950,
14.327208, -2.134478, -183.788116,
13.344822, -1.998021, -184.026215,
12.361718, -1.863053, -184.263077,
8.079593, -1.926340, -185.327988,
2.468133, -1.674941, -186.621872,
0.478332, -1.519862, -187.029205,
-5.183570, -1.168827, -188.135437,
-10.524970, -0.787942, -189.075882,
-11.111217, -0.629007, -189.894958,
-12.298127, -0.580679, -190.385666,
-13.245046, -0.599274, -190.750412,
-14.188004, -0.496885, -191.123428,
-15.131532, -0.387342, -191.495163,
-16.076939, -0.359143, -191.862503,
-18.904144, 0.286367, -192.923462,
-19.298399, 0.512927, -193.844086,
-20.236032, 0.637131, -194.226257,
-21.165127, 0.763740, -194.627731,
-22.089966, 0.795228, -195.051437,
-23.013824, 0.792700, -195.483749,
-23.938154, 0.790050, -195.915085,
-25.589787, 0.636639, -196.951553,
-26.508005, 0.544279, -197.385910,
-27.422697, 0.452274, -197.827805,
-28.337297, 0.380589, -198.272293,
-29.254520, 0.334919, -198.716125,
-31.397188, 0.228204, -199.746597,
-36.625172, 0.000000, -202.187897,
-37.873020, 0.000000, -202.493210,
-39.119324, 0.000000, -203.037552,
-40.370975, 0.000000, -203.569611
};
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
onMobRoam(mob);
end;
function onPath(mob)
pathfind.patrol(mob, path, PATHFLAG_RUN);
end;
function onMobRoam(mob)
-- move to start position if not moving
if (mob:isFollowingPath() == false) then
mob:pathThrough(pathfind.first(path), PATHFLAG_RUN);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
killer:addTitle(CACTROT_DESACELERADOR);
-- Set Cactrot Rapido's spawnpoint and respawn time (24-72 hours)
UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random((86400),(259200)));
end; | gpl-3.0 |
AresTao/darkstar | scripts/globals/mobskills/Fiery_Breath.lua | 13 | 1293 | ---------------------------------------------
-- Fiery Breath
--
-- Description: Deals Fire damage to enemies within a fan-shaped area.
-- Type: Breath
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes: Used only by Tiamat, Smok and Ildebrann
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/utils");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then
return 1;
elseif (target:isBehind(mob, 48) == true) then
return 1;
elseif (mob:AnimationSub() == 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_FIRE, 1400);
local angle = mob:getAngle(target);
angle = mob:getRotPos() - angle;
dmgmod = dmgmod * ((128-math.abs(angle))/128);
utils.clamp(dmgmod, 50, 1600);
local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
AresTao/darkstar | scripts/globals/spells/cure_vi.lua | 18 | 3534 | -----------------------------------------
-- Spell: Cure VI
-- Restores target's HP.
-- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local divisor = 0;
local constant = 0;
local basepower = 0;
local power = 0;
local basecure = 0;
local final = 0;
local minCure = 600;
power = getCurePower(caster);
if (power < 210) then
divisor = 1.5;
constant = 600;
basepower = 90;
elseif (power < 300) then
divisor = 0.9;
constant = 680;
basepower = 210;
elseif (power < 400) then
divisor = 10/7;
constant = 780;
basepower = 300;
elseif (power < 500) then
divisor = 2.5;
constant = 850;
basepower = 400;
elseif (power < 700) then
divisor = 5/3;
constant = 890;
basepower = 500;
else
divisor = 999999;
constant = 1010;
basepower = 0;
end
if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then
basecure = getBaseCure(power,divisor,constant,basepower);
final = getCureFinal(caster,spell,basecure,minCure,false);
if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then
local solaceStoneskin = 0;
local equippedBody = caster:getEquipID(SLOT_BODY);
if (equippedBody == 11186) then
solaceStoneskin = math.floor(final * 0.30);
elseif (equippedBody == 11086) then
solaceStoneskin = math.floor(final * 0.35);
else
solaceStoneskin = math.floor(final * 0.25);
end
target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25);
end;
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
--Applying server mods....
final = final * CURE_POWER;
local diff = (target:getMaxHP() - target:getHP());
if (final > diff) then
final = diff;
end
target:restoreHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
else
if (target:isUndead()) then
spell:setMsg(2);
local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5;
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0);
dmg = dmg*resist;
dmg = addBonuses(caster,spell,target,dmg);
dmg = adjustForTarget(target,dmg,spell:getElement());
dmg = finalMagicAdjustments(caster,target,spell,dmg);
final = dmg;
target:delHP(final);
target:updateEnmityFromDamage(caster,final);
elseif (caster:getObjType() == TYPE_PC) then
spell:setMsg(75);
else
-- e.g. monsters healing themselves.
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant);
else
basecure = getBaseCure(power,divisor,constant,basepower);
end
final = getCureFinal(caster,spell,basecure,minCure,false);
local diff = (target:getMaxHP() - target:getHP());
if (final > diff) then
final = diff;
end
target:addHP(final);
end
end
return final;
end; | gpl-3.0 |
DeinFreund/Zero-K | scripts/cloakskirm.lua | 1 | 4212 | include "constants.lua"
local hips = piece 'hips'
local chest = piece 'chest'
local gun = piece 'gun'
local muzzle = piece 'muzzle'
local exhaust = piece 'exhaust'
local turner = piece 'turner'
local aimpoint = piece 'aimpoint'
local gunemit = piece 'gunemit'
local thigh = {piece 'lthigh', piece 'rthigh'}
local shin = {piece 'lshin', piece 'rshin'}
local foot = {piece 'lfoot', piece 'rfoot'}
local knee = {piece 'lknee', piece 'rknee'}
local heel = {piece 'lheel', piece 'rheel'}
local smokePiece = {chest, exhaust, muzzle}
local RELOAD_PENALTY = tonumber(UnitDefs[unitDefID].customParams.reload_move_penalty)
local SIG_Aim = 1
local SIG_Walk = 2
local function Walk()
for i = 1, 2 do
Turn (thigh[i], y_axis, 0, math.rad(135))
Turn (thigh[i], z_axis, 0, math.rad(135))
Turn (foot[i], z_axis, 0, math.rad(135))
end
Signal(SIG_Walk)
SetSignalMask(SIG_Walk)
local side = 1
local speedMult = 1
while true do
speedMult = (Spring.GetUnitRulesParam(unitID, "totalMoveSpeedChange") or 1)
Turn (shin[side], x_axis, math.rad(85), speedMult*math.rad(260))
Turn (thigh[side], x_axis, math.rad(-100), speedMult*math.rad(135))
Turn (thigh[3-side], x_axis, math.rad(30), speedMult*math.rad(135))
WaitForMove (hips, y_axis)
Move (hips, y_axis, 3, speedMult*9)
WaitForMove (hips, y_axis)
Turn (shin[side], x_axis, math.rad(10), speedMult*math.rad(315))
Move (hips, y_axis, 0, speedMult*9)
side = 3 - side
end
end
local function StopWalk()
Signal(SIG_Walk)
for i = 1, 2 do
Turn (foot[i], x_axis, 0, math.rad(400))
Turn (thigh[i], x_axis, 0, math.rad(225))
Turn (shin[i], x_axis, 0, math.rad(225))
Turn (thigh[i], y_axis, math.rad(60 - i*40), math.rad(135))
Turn (thigh[i], z_axis, math.rad(6*i - 9), math.rad(135))
Turn (foot[i], z_axis, math.rad(9 - 6*i), math.rad(135))
end
end
function script.StartMoving()
StartThread(Walk)
end
function script.StopMoving()
StartThread(StopWalk)
end
function script.Create()
StartThread(SmokeUnit, smokePiece)
Turn (chest, y_axis, math.rad(-20))
end
local function ReloadPenaltyAndAnimation()
aimBlocked = true
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", RELOAD_PENALTY)
GG.UpdateUnitAttributes(unitID)
Sleep(200)
Turn (gun, x_axis, 1, math.rad(120))
Turn (turner, y_axis, 0, math.rad(200))
Sleep(2300) -- 3.5 second reload so no point checking earlier.
while true do
local state = Spring.GetUnitWeaponState(unitID, 1, "reloadState")
local gameFrame = Spring.GetGameFrame()
if state - 32 < gameFrame then
aimBlocked = false
Sleep(500)
Turn (gun, x_axis, 0, math.rad(100))
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1)
GG.UpdateUnitAttributes(unitID)
return
end
Sleep(340)
end
end
function script.AimFromWeapon(num)
return gunemit
end
function script.QueryWeapon(num)
return gunemit
end
local function RestoreAfterDelay()
SetSignalMask(SIG_Aim)
Sleep (2000)
Turn (turner, y_axis, 0, math.rad(40))
Turn (gun, x_axis, math.rad(20), math.rad(40))
end
function script.AimWeapon(num, heading, pitch)
Signal(SIG_Aim)
SetSignalMask(SIG_Aim)
if aimBlocked then
return false
end
Turn (hips, x_axis, 0)
Turn (chest, x_axis, 0)
Turn (gun, x_axis, -pitch, math.rad(100))
Turn (turner, y_axis, heading + math.rad(5), math.rad(200))
WaitForTurn (turner, y_axis)
WaitForTurn (gun, x_axis)
StartThread(RestoreAfterDelay)
return true
end
function script.FireWeapon(num)
EmitSfx (exhaust, 1024)
StartThread(ReloadPenaltyAndAnimation)
end
function script.BlockShot(num, targetID)
if Spring.ValidUnitID(targetID) then
local distMult = (Spring.GetUnitSeparation(unitID, targetID) or 0)/450
return GG.OverkillPrevention_CheckBlock(unitID, targetID, 180.1, 75 * distMult, false, false, true)
end
return false
end
local explodables = {hips, thigh[2], foot[1], shin[2], knee[1], heel[2]}
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
for i = 1, #explodables do
if math.random() < severity then
Explode (explodables[i], sfxFall + sfxSmoke + sfxFire)
end
end
if (severity < 0.5) then
return 1
else
Explode (chest, sfxShatter)
Explode (gun, sfxShatter)
return 2
end
end
| gpl-2.0 |
ruohoruotsi/Wavelet-Tree-Synth | nnet/Variational-LSTM-Autoencoder-master/util/Maskh.lua | 1 | 1044 | local Maskh, parent = torch.class('nn.Maskh', 'nn.Module')
function Maskh:__init()
parent.__init(self)
self.gradInput = {}
end
function Maskh:updateOutput(input)
local prev, current, mask = unpack(input)
assert(prev:size(1) == mask:size(1))
local mask_ = mask:clone()
mask_ = mask_:view(mask_:size(1),-1):expandAs(prev)
self.output = torch.cmul(prev, -mask_+1) + torch.cmul(current, mask_)
return self.output
end
function Maskh:updateGradInput(input, gradOutput)
local prev, current, mask = unpack(input)
assert(prev:size(1) == mask:size(1))
local mask_ = mask:clone()
mask_ = mask_:view(mask_:size(1),-1):expandAs(prev)
self.gradInput[1] = self.gradInput[1] or prev.new()
self.gradInput[1]:resizeAs(prev)
self.gradInput[2] = self.gradInput[2] or current.new()
self.gradInput[2]:resizeAs(current)
self.gradInput[1]:copy(torch.cmul(gradOutput, -mask_+1))
self.gradInput[2]:copy(torch.cmul(gradOutput, mask_))
self.gradInput[3] = torch.zeros(mask:size())
return self.gradInput
end
| gpl-2.0 |
DeinFreund/Zero-K | LuaUI/Widgets/chili_new/controls/image.lua | 9 | 3306 | --//=============================================================================
--- Image module
--- Image fields.
-- Inherits from Control.
-- @see button.Button
-- @table Image
-- @tparam {r,g,b,a} color color, (default {1,1,1,1})
-- @string[opt=nil] file path
-- @bool[opt=true] keepAspect aspect should be kept
-- @tparam {func1,func2} OnClick function listeners to be invoked on click (default {})
Image = Button:Inherit{
classname= "image",
defaultWidth = 64,
defaultHeight = 64,
padding = {0,0,0,0},
color = {1,1,1,1},
color2 = nil,
file = nil,
file2 = nil,
flip = true;
flip2 = true;
keepAspect = true;
useRTT = false;
OnClick = {},
}
local this = Image
local inherited = this.inherited
--//=============================================================================
local function _DrawTextureAspect(x,y,w,h ,tw,th, flipy)
local twa = w/tw
local tha = h/th
local aspect = 1
if (twa < tha) then
aspect = twa
y = y + h*0.5 - th*aspect*0.5
h = th*aspect
else
aspect = tha
x = x + w*0.5 - tw*aspect*0.5
w = tw*aspect
end
local right = math.ceil(x+w)
local bottom = math.ceil(y+h)
x = math.ceil(x)
y = math.ceil(y)
gl.TexRect(x,y,right,bottom,false,flipy)
end
function Image:DrawControl()
if (not (self.file or self.file2)) then return end
if (self.keepAspect) then
if (self.file2) then
gl.Color(self.color2 or self.color)
TextureHandler.LoadTexture(0,self.file2,self)
local texInfo = gl.TextureInfo(self.file2) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(0,0,self.width,self.height, tw,th, self.flip2)
end
if (self.file) then
gl.Color(self.color)
TextureHandler.LoadTexture(0,self.file,self)
local texInfo = gl.TextureInfo(self.file) or {xsize=1, ysize=1}
local tw,th = texInfo.xsize, texInfo.ysize
_DrawTextureAspect(0,0,self.width,self.height, tw,th, self.flip)
end
else
if (self.file2) then
gl.Color(self.color2 or self.color)
TextureHandler.LoadTexture(0,self.file2,self)
gl.TexRect(0,0,self.width,self.height,false,self.flip2)
end
if (self.file) then
gl.Color(self.color)
TextureHandler.LoadTexture(0,self.file,self)
gl.TexRect(0,0,self.width,self.height,false,self.flip)
end
end
gl.Texture(0,false)
end
--//=============================================================================
function Image:IsActive()
local onclick = self.OnClick
if (onclick and onclick[1]) then
return true
end
end
function Image:HitTest()
--FIXME check if there are any eventhandlers linked (OnClick,OnMouseUp,...)
return self:IsActive() and self
end
function Image:MouseDown(...)
--// we don't use `this` here because it would call the eventhandler of the button class,
--// which always returns true, but we just want to do so if a calllistener handled the event
return Control.MouseDown(self, ...) or self:IsActive() and self
end
function Image:MouseUp(...)
return Control.MouseUp(self, ...) or self:IsActive() and self
end
function Image:MouseClick(...)
return Control.MouseClick(self, ...) or self:IsActive() and self
end
--//=============================================================================
| gpl-2.0 |
superzazu/quadLOVE | lib/middleclass.lua | 63 | 6117 | local middleclass = {
_VERSION = 'middleclass v3.0.1',
_DESCRIPTION = 'Object Orientation for Lua',
_URL = 'https://github.com/kikito/middleclass',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2011 Enrique García Cota
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 function _setClassDictionariesMetatables(aClass)
local dict = aClass.__instanceDict
dict.__index = dict
local super = aClass.super
if super then
local superStatic = super.static
setmetatable(dict, super.__instanceDict)
setmetatable(aClass.static, { __index = function(_,k) return dict[k] or superStatic[k] end })
else
setmetatable(aClass.static, { __index = function(_,k) return dict[k] end })
end
end
local function _setClassMetatable(aClass)
setmetatable(aClass, {
__tostring = function() return "class " .. aClass.name end,
__index = aClass.static,
__newindex = aClass.__instanceDict,
__call = function(self, ...) return self:new(...) end
})
end
local function _createClass(name, super)
local aClass = { name = name, super = super, static = {}, __mixins = {}, __instanceDict={} }
aClass.subclasses = setmetatable({}, {__mode = "k"})
_setClassDictionariesMetatables(aClass)
_setClassMetatable(aClass)
return aClass
end
local function _createLookupMetamethod(aClass, name)
return function(...)
local method = aClass.super[name]
assert( type(method)=='function', tostring(aClass) .. " doesn't implement metamethod '" .. name .. "'" )
return method(...)
end
end
local function _setClassMetamethods(aClass)
for _,m in ipairs(aClass.__metamethods) do
aClass[m]= _createLookupMetamethod(aClass, m)
end
end
local function _setDefaultInitializeMethod(aClass, super)
aClass.initialize = function(instance, ...)
return super.initialize(instance, ...)
end
end
local function _includeMixin(aClass, mixin)
assert(type(mixin)=='table', "mixin must be a table")
for name,method in pairs(mixin) do
if name ~= "included" and name ~= "static" then aClass[name] = method end
end
if mixin.static then
for name,method in pairs(mixin.static) do
aClass.static[name] = method
end
end
if type(mixin.included)=="function" then mixin:included(aClass) end
aClass.__mixins[mixin] = true
end
local Object = _createClass("Object", nil)
Object.static.__metamethods = { '__add', '__call', '__concat', '__div', '__ipairs', '__le',
'__len', '__lt', '__mod', '__mul', '__pairs', '__pow', '__sub',
'__tostring', '__unm'}
function Object.static:allocate()
assert(type(self) == 'table', "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'")
return setmetatable({ class = self }, self.__instanceDict)
end
function Object.static:new(...)
local instance = self:allocate()
instance:initialize(...)
return instance
end
function Object.static:subclass(name)
assert(type(self) == 'table', "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'")
assert(type(name) == "string", "You must provide a name(string) for your class")
local subclass = _createClass(name, self)
_setClassMetamethods(subclass)
_setDefaultInitializeMethod(subclass, self)
self.subclasses[subclass] = true
self:subclassed(subclass)
return subclass
end
function Object.static:subclassed(other) end
function Object.static:isSubclassOf(other)
return type(other) == 'table' and
type(self) == 'table' and
type(self.super) == 'table' and
( self.super == other or
type(self.super.isSubclassOf) == 'function' and
self.super:isSubclassOf(other)
)
end
function Object.static:include( ... )
assert(type(self) == 'table', "Make sure you that you are using 'Class:include' instead of 'Class.include'")
for _,mixin in ipairs({...}) do _includeMixin(self, mixin) end
return self
end
function Object.static:includes(mixin)
return type(mixin) == 'table' and
type(self) == 'table' and
type(self.__mixins) == 'table' and
( self.__mixins[mixin] or
type(self.super) == 'table' and
type(self.super.includes) == 'function' and
self.super:includes(mixin)
)
end
function Object:initialize() end
function Object:__tostring() return "instance of " .. tostring(self.class) end
function Object:isInstanceOf(aClass)
return type(self) == 'table' and
type(self.class) == 'table' and
type(aClass) == 'table' and
( aClass == self.class or
type(aClass.isSubclassOf) == 'function' and
self.class:isSubclassOf(aClass)
)
end
function middleclass.class(name, super, ...)
super = super or Object
return super:subclass(name, ...)
end
middleclass.Object = Object
setmetatable(middleclass, { __call = function(_, ...) return middleclass.class(...) end })
return middleclass
| mit |
DeinFreund/Zero-K | LuaUI/Widgets/unit_smart_nanos.lua | 5 | 18535 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--
-- file: unit_smart_nanos.lua
-- brief: Enables auto reclaim & repair for idle turrets
-- author: Owen Martindell
--
-- Copyright (C) 2008.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Smart Nanos",
desc = "Enables auto reclaim & repair for idle turrets v1.5",
author = "TheFatController",
date = "22 April, 2008",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local GetUnitDefID = Spring.GetUnitDefID
local GetAllUnits = Spring.GetAllUnits
local GetMyTeamID = Spring.GetMyTeamID
local GetUnitNearestEnemy = Spring.GetUnitNearestEnemy
local GiveOrderToUnit = Spring.GiveOrderToUnit
local GetUnitHealth = Spring.GetUnitHealth
local GetUnitsInCylinder = Spring.GetUnitsInCylinder
local GetUnitPosition = Spring.GetUnitPosition
local GetCommandQueue = Spring.GetCommandQueue
local GetFeatureDefID = Spring.GetFeatureDefID
local GetFeatureResources = Spring.GetFeatureResources
local AreTeamsAllied = Spring.AreTeamsAllied
local GetFeaturePosition = Spring.GetFeaturePosition
local GetGameSeconds = Spring.GetGameSeconds
local GetSelectedUnits = Spring.GetSelectedUnits
local GetUnitTeam = Spring.GetUnitTeam
local GetTeamResources = Spring.GetTeamResources
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local UPDATE = 0.5 -- Response time for commands
local NANO_GROUPS = 8 -- Groups to split nanoturrets into
local UPDATE_TICK = 2.5 -- Seconds to check if last order is still the best
local noReclaimList = {}
noReclaimList["Dragon's Teeth"] = 0
noReclaimList["Shark's Teeth"] = 0
noReclaimList["Fortification Wall"] = 0
noReclaimList["Spike"] = 0
noReclaimList["Commander Wreckage"] = 25
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local timeCounter = 0
local order_counter = 0
local pointer = NANO_GROUPS
local nano_pointer = NANO_GROUPS
local stalling = false
local goodEnergy = false
local goodMetal = false
local teamUnits = {}
local buildUnits = {}
local nanoTurrets = {}
local allyUnits = {}
local orderQueue = {}
if (Game.modShortName == "BA") then local BA = true end
local myTeamID
local EMPTY_TABLE = {}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
myTeamID = GetMyTeamID()
if (Spring.GetSpectatingState() or Spring.IsReplay()) and (not Spring.IsCheatingEnabled()) then
Spring.Echo("Smart Nanos widget disabled for spectators")
widgetHandler:RemoveWidget()
end
for _,unitID in ipairs(GetAllUnits()) do
local unitTeam = GetUnitTeam(unitID)
if (unitTeam == myTeamID) or AreTeamsAllied(unitTeam, myTeamID) then
local unitDefID = GetUnitDefID(unitID)
local _, _, _, _, buildProgress = GetUnitHealth(unitID)
if (buildProgress < 1) then
widget:UnitCreated(unitID, unitDefID, unitTeam)
else
widget:UnitFinished(unitID, unitDefID, unitTeam)
end
end
end
UPDATE = (UPDATE / NANO_GROUPS)
end
function widget:UnitCreated(unitID, unitDefID, unitTeam)
if (unitTeam ~= myTeamID) then return end
buildUnits[unitID] = true
end
function widget:UnitFinished(unitID, unitDefID, unitTeam)
if UnitDefs[unitDefID].customParams.commtype then myTeamID = GetMyTeamID() end
if (unitTeam == myTeamID) then
buildUnits[unitID] = nil
teamUnits[unitID] = {}
teamUnits[unitID].unitDefID = unitDefID
teamUnits[unitID].damaged = false
if (UnitDefs[unitDefID].isBuilder and not UnitDefs[unitDefID].canMove) then
nanoTurrets[unitID] = {}
nanoTurrets[unitID].unitDefID = unitDefID
nanoTurrets[unitID].buildDistance = UnitDefs[nanoTurrets[unitID].unitDefID].buildDistance
nanoTurrets[unitID].buildDistanceSqr = (UnitDefs[nanoTurrets[unitID].unitDefID].buildDistance *
UnitDefs[nanoTurrets[unitID].unitDefID].buildDistance)
nanoTurrets[unitID].damaged = false
local posX,_,posZ = GetUnitPosition(unitID)
nanoTurrets[unitID].posX = posX
nanoTurrets[unitID].posZ = posZ
nanoTurrets[unitID].timeCounter = GetGameSeconds()
nanoTurrets[unitID].auto = false
nanoTurrets[unitID].pointer = nano_pointer
if (nano_pointer < NANO_GROUPS) then
nano_pointer = nano_pointer + 1
else
nano_pointer = 1
end
teamUnits[unitID] = nil
end
elseif AreTeamsAllied(unitTeam, myTeamID) then
allyUnits[unitID] = {}
allyUnits[unitID].unitDefID = unitDefID
allyUnits[unitID].damaged = false
end
end
function widget:CommandNotify(id, params, options)
--[[
local CMD_UPGRADEMEX = math.huge
if BA and (id == 31244) then
if (#params == 1) then
local unitDefID = GetUnitDefID(params[1])
if (unitDefID ~= nil) and (UnitDefs[unitDefID].customParams.ismex) then
CMD_UPGRADEMEX = 31244
end
end
end
]]--
local selUnits = GetSelectedUnits()
for _,unitID in ipairs(selUnits) do
if nanoTurrets[unitID] then
nanoTurrets[unitID].auto = false
orderQueue[unitID] = nil
end
end
--if (id == CMD.RECLAIM) or (id == CMD_UPGRADEMEX) then
if (id == CMD.RECLAIM) then
targetUnit = params[1]
teamUnits[targetUnit] = nil
for unitID,unitDefs in pairs(nanoTurrets) do
local cQueue = GetCommandQueue(unitID, 1)
if (#cQueue > 0) then
if (cQueue[1].id == CMD.REPAIR) and (cQueue[1].params[1] == targetUnit) then
if options.shift then
GiveOrderToUnit(unitID,CMD.STOP, EMPTY_TABLE, 0)
else
GiveOrderToUnit(unitID,CMD.RECLAIM,{targetUnit}, 0)
end
end
end
end
end
if (id == CMD.REPAIR) then
targetUnit = params[1]
if (not teamUnits[targetUnit]) and (not allyUnits[targetUnit]) and (not nanoTurrets[targetUnit])
and (not buildUnits[targetUnit]) and (GetUnitTeam(targetUnit) == myTeamID) then
widget:UnitFinished(targetUnit, GetUnitDefID(targetUnit), myTeamID)
end
for unitID,unitDefs in pairs(nanoTurrets) do
local cQueue = GetCommandQueue(unitID, 1)
if (#cQueue > 0) then
if (cQueue[1].id == CMD.RECLAIM) and (cQueue[1].params[1] == targetUnit) then
GiveOrderToUnit(unitID,CMD.REPAIR,{targetUnit}, 0)
end
end
end
end
end
local function getDistance(x1,z1,x2,z2)
local dx,dz = x1-x2,z1-z2
return (dx*dx)+(dz*dz)
end
local function processOrderQueue()
local newQueue = {}
for unitID,orders in pairs(orderQueue) do
if nanoTurrets[unitID] and nanoTurrets[unitID].auto then
local key = table.concat(orders,"-")
local map = newQueue[key]
if not map then
map = {}
newQueue[key] = map
end
map[unitID] = orders
else
orderQueue[unitID] = nil
end
end
for _,unitMap in pairs(newQueue) do
local anyID = next(unitMap)
local type, id, params = unitMap[anyID][1], unitMap[anyID][2], unitMap[anyID][3]
if (type == 1) then
Spring.GiveOrderToUnitMap(unitMap, CMD.INSERT, {0, id, CMD.OPT_SHIFT, params}, CMD.OPT_ALT)
else
Spring.GiveOrderToUnitMap(unitMap, id, {params}, CMD.OPT_SHIFT)
end
end
orderQueue = {}
end
function widget:Update(deltaTime)
if (next(nanoTurrets) == nil) then return false end
if (timeCounter > UPDATE) then
timeCounter = 0
if (GetMyTeamID() ~= myTeamID) then
Spring.Echo("Smart Nanos widget disabled for team change")
widgetHandler:RemoveWidget()
return false
end
local eCur, eMax = GetTeamResources(myTeamID, "energy")
local mCur, mMax, _, mInc = GetTeamResources(myTeamID, "metal")
local ePercent = (eCur / eMax)
if (ePercent < 0.3) and (eCur < 500) then
stalling = true
goodEnergy = false
elseif (ePercent > 0.5) or (eCur >= 500) then
stalling = false
if (ePercent > 0.9) and ((eMax - eCur) < 250) then
goodEnergy = true
else
goodEnergy = false
end
end
if ((mMax - mCur) < mInc) then goodMetal = true else goodMetal = false end
if next(orderQueue) then
if (order_counter == NANO_GROUPS) then
processOrderQueue()
order_counter = 1
else
order_counter = order_counter + 1
end
end
if (pointer == NANO_GROUPS) then
for unitID,_ in pairs(teamUnits) do
local curH, maxH = GetUnitHealth(unitID)
if curH and maxH then
teamUnits[unitID].rHealth = curH
if (curH < maxH) then
teamUnits[unitID].damaged = true
else
teamUnits[unitID].damaged = false
end
else
teamUnits[unitID] = nil
end
end
for unitID,_ in pairs(allyUnits) do
local curH, maxH = GetUnitHealth(unitID)
if curH and maxH then
allyUnits[unitID].rHealth = curH
if (curH < maxH) then
allyUnits[unitID].damaged = true
else
allyUnits[unitID].damaged = false
end
else
allyUnits[unitID] = nil
end
end
pointer = 1
else
pointer = (pointer + 1)
end
for unitID,unitDefs in pairs(nanoTurrets) do
if (unitDefs.pointer == pointer) then
local curH, maxH = GetUnitHealth(unitID)
if (curH < maxH) then
nanoTurrets[unitID].damaged = true
else
nanoTurrets[unitID].damaged = false
end
local cQueue = GetCommandQueue(unitID, 1)
local cQueueCount = GetCommandQueue(unitID, 0)
local commandMe = false
local prevCommand = nil
local prevUnit = nil
if (cQueueCount == 0) then
commandMe = true
nanoTurrets[unitID].auto = false
else
if (cQueue[1].id == CMD.PATROL) and (cQueueCount <= 4) then
commandMe = true
nanoTurrets[unitID].auto = false
end
if nanoTurrets[unitID].auto then
if (cQueue[1].id == CMD.RECLAIM) then
prevCommand = CMD.RECLAIM
prevUnit = cQueue[1].params[1]
if prevUnit < Game.maxUnits then
local targetDefID = GetUnitDefID(prevUnit)
if (targetDefID ~= nil) and UnitDefs[targetDefID].canMove then
local uX, _, uZ = GetUnitPosition(prevUnit)
if (getDistance(unitDefs.posX, unitDefs.posZ, uX, uZ) > unitDefs.buildDistanceSqr) then
commandMe = true
end
end
end
end
if (cQueue[1].id == CMD.REPAIR) then
prevCommand = CMD.REPAIR
prevUnit = cQueue[1].params[1]
local targetDefID = GetUnitDefID(prevUnit)
if (targetDefID ~= nil) and UnitDefs[targetDefID].canMove then
local uX, _, uZ = GetUnitPosition(prevUnit)
if (getDistance(unitDefs.posX, unitDefs.posZ, uX, uZ) > unitDefs.buildDistanceSqr) then
commandMe = true
end
end
end
if ((unitDefs.timeCounter + UPDATE_TICK) < GetGameSeconds()) then
commandMe = true
end
end
end
if (commandMe) then
unitDefs.timeCounter = GetGameSeconds()
local ordered = false
local nearUnits = GetUnitsInCylinder(unitDefs.posX,unitDefs.posZ,unitDefs.buildDistance)
local nearFeatures = Spring.GetFeaturesInRectangle(unitDefs.posX - (unitDefs.buildDistance+75), unitDefs.posZ - (unitDefs.buildDistance+75),
unitDefs.posX + (unitDefs.buildDistance+75), unitDefs.posZ + (unitDefs.buildDistance+75))
if (nearUnits ~= nil) and (nearFeatures ~= nil) then
for _,nearUnitID in pairs(nearUnits) do
if nanoTurrets[nearUnitID] and nanoTurrets[nearUnitID].damaged and (unitID ~= nearUnitID) then
if (prevCommand ~= CMD.REPAIR) or (prevUnit ~= bestUnit) then
orderQueue[unitID] = {1, CMD.REPAIR, nearUnitID}
end
ordered = true
break
end
end
if (not ordered) then
local bestUnit = nil
local bestStat = math.huge
local nextUnit = nil
for _,nearUnitID in pairs(nearUnits) do
if (teamUnits[nearUnitID] and teamUnits[nearUnitID].damaged) then
if (nextUnit == nil) then nextUnit = nearUnitID end
if (#UnitDefs[GetUnitDefID(nearUnitID)].weapons > 0) then
if (teamUnits[nearUnitID].rHealth < bestStat) then
bestUnit = nearUnitID
bestStat = teamUnits[nearUnitID].rHealth
end
end
end
end
--[[
local nearEnemyID = GetUnitNearestEnemy(unitID,unitDefs.buildDistance)
if nearEnemyID and (not bestUnit) then
if (prevCommand ~= CMD.RECLAIM) or (prevUnit ~= nearEnemyID) then
orderQueue[unitID] = {1, CMD.RECLAIM, nearEnemyID}
end
ordered = true
end
]]--
if (bestUnit ~= nil) and (not ordered) then
if (prevCommand ~= CMD.REPAIR) or (prevUnit ~= bestUnit) then
orderQueue[unitID] = {1, CMD.REPAIR, bestUnit}
end
ordered = true
elseif (nextUnit ~= nil) and (not ordered) then
if (prevCommand ~= CMD.REPAIR) or (prevUnit ~= nextUnit) then
orderQueue[unitID] = {1, CMD.REPAIR, nextUnit}
end
ordered = true
end
end
if (not ordered) or ((not goodEnergy) and (not goodMetal)) then
local bestFeature = nil
local metal = false
for _,featureID in ipairs(nearFeatures) do
local fX, _, fZ = GetFeaturePosition(featureID)
local fd = GetFeatureDefID(featureID)
local radiusSqr = (FeatureDefs[fd].radius * FeatureDefs[fd].radius)
if (getDistance(unitDefs.posX, unitDefs.posZ, fX, fZ) < (unitDefs.buildDistanceSqr + radiusSqr)) then
if (FeatureDefs[fd].reclaimable) and (not noReclaimList[FeatureDefs[fd].tooltip]) then
local fm,_,fe = GetFeatureResources(featureID)
if (fm > 0) and (fe > 0) then
bestFeature = featureID
metal = true
elseif (fm > 0) and (not stalling) and (not goodMetal) then
bestFeature = featureID
metal = true
elseif (fe > 0) and (not goodEnergy) and (not metal) then
bestFeature = featureID
end
end
end
end
if not metal then
local bestUnit = nil
local bestStat = math.huge
for _,nearUnitID in pairs(nearUnits) do
if (allyUnits[nearUnitID] and allyUnits[nearUnitID].damaged) then
if (#UnitDefs[GetUnitDefID(nearUnitID)].weapons > 0) then
if (allyUnits[nearUnitID].rHealth < bestStat) then
bestUnit = nearUnitID
bestStat = allyUnits[nearUnitID].rHealth
end
end
end
end
if (bestUnit ~= nil) then
if (prevCommand ~= CMD.REPAIR) or (prevUnit ~= bestUnit) then
orderQueue[unitID] = {1, CMD.REPAIR, bestUnit}
end
ordered = true
end
end
if bestFeature and (not ordered) then
if (prevCommand ~= CMD.RECLAIM) or (prevUnit ~= (bestFeature + Game.maxUnits)) then
orderQueue[unitID] = {1, CMD.RECLAIM, (bestFeature + Game.maxUnits)}
end
ordered = true
end
end
end
if (nanoTurrets[unitID].auto) and (not ordered) and (cQueueCount > 0) and
((cQueue[1].id == CMD.REPAIR) or (cQueue[1].id == CMD.RECLAIM)) then
orderQueue[unitID] = {0, cQueue[1].id, cQueue[1].params[1]}
elseif ordered then
nanoTurrets[unitID].auto = true
end
end
end
end
else
timeCounter = timeCounter + deltaTime
end
end
function widget:UnitGiven(unitID, unitDefID, unitTeam)
widget:UnitFinished(unitID, unitDefID, unitTeam)
end
function widget:UnitDestroyed(unitID, unitDefID, unitTeam)
buildUnits[unitID] = nil
nanoTurrets[unitID] = nil
teamUnits[unitID] = nil
allyUnits[unitID] = nil
orderQueue[unitID] = nil
end
function widget:UnitTaken(unitID, unitDefID, unitTeam)
buildUnits[unitID] = nil
nanoTurrets[unitID] = nil
teamUnits[unitID] = nil
allyUnits[unitID] = nil
orderQueue[unitID] = nil
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
| gpl-2.0 |
AresTao/darkstar | scripts/zones/The_Shrine_of_RuAvitau/mobs/Seiryu.lua | 27 | 1101 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: Seiryu (Pet version)
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
end;
-----------------------------------
-- onMonsterMagicPrepare
-----------------------------------
function onMonsterMagicPrepare(mob,target)
-- For some reason, this returns false even when Hundred Fists is active, so... yeah.
-- Core does this:
-- m_PMob->StatusEffectContainer->AddStatusEffect(new CStatusEffect(EFFECT_HUNDRED_FISTS,0,1,0,45));
if (mob:hasStatusEffect(EFFECT_HUNDRED_FISTS,0) == false) then
local rnd = math.random();
if (rnd < 0.5) then
return 186; -- aeroga 3
elseif (rnd < 0.7) then
return 157; -- aero 4
elseif (rnd < 0.9) then
return 208; -- tornado
else
return 237; -- choke
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Kazham/npcs/Thali_Mhobrum.lua | 15 | 1696 | -----------------------------------
-- Area: Kazham
-- NPC: Thali Mhobrum
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
local path = {
55.816410, -11.000000, -43.992680,
54.761787, -11.000000, -44.046181,
51.805824, -11.000000, -44.200321,
52.922001, -11.000000, -44.186420,
51.890709, -11.000000, -44.224312,
47.689358, -11.000000, -44.374969,
52.826096, -11.000000, -44.191029,
47.709465, -11.000000, -44.374393,
52.782181, -11.000000, -44.192482,
47.469643, -11.000000, -44.383091
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00A3); -- scent from Blue Rafflesias
npc:wait(-1);
else
player:startEvent(0x00BE);
npc:wait(-1);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
npc:wait(0);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Miah_Riyuh.lua | 50 | 5024 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Miah Riyuh
-- @pos 5.323 -2 37.462 94
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Allegiance = player:getCampaignAllegiance();
-- 0 = none, 1 = San d'Oria Iron Rams, 2 = Bastok Fighting Fourth, 3 = Windurst Cobras
local TheFightingFourth = player:getQuestStatus(CRYSTAL_WAR,THE_FIGHTING_FOURTH);
local SnakeOnThePlains = player:getQuestStatus(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
local SteamedRams = player:getQuestStatus(CRYSTAL_WAR,STEAMED_RAMS);
local GreenLetter = player:hasKeyItem(GREEN_RECOMMENDATION_LETTER);
if (SteamedRams == QUEST_ACCEPTED or TheFightingFourth == QUEST_ACCEPTED) then
player:startEvent(122);
elseif (SnakeOnThePlains == QUEST_AVAILABLE and GreenLetter == true) then
player:startEvent(103);
elseif (SnakeOnThePlains == QUEST_AVAILABLE and player:getVar("GREEN_R_LETTER_USED") == 1) then
player:startEvent(105);
elseif (SnakeOnThePlains == QUEST_ACCEPTED and player:isMaskFull(player:getVar("SEALED_DOORS"),3) == true) then
player:startEvent(106);
elseif (SnakeOnThePlains == QUEST_ACCEPTED and player:hasKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY)) then
local PuttyUsed = 0;
if (player:getMaskBit(player:getVar("SEALED_DOORS"),0)) then
PuttyUsed = PuttyUsed +1;
end
if (player:getMaskBit(player:getVar("SEALED_DOORS"),1)) then
PuttyUsed = PuttyUsed +1;
end
if (player:getMaskBit(player:getVar("SEALED_DOORS"),2)) then
PuttyUsed = PuttyUsed +1;
end
player:startEvent(104, 0, 0, 0, 0, 0, 0, 0, PuttyUsed);
elseif (SnakeOnThePlains == QUEST_COMPLETED and Allegiance == 3) then
player:startEvent(107);
else
player:startEvent(121);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 103 and option == 0) then
player:addQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:addKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:setVar("GREEN_R_LETTER_USED",1);
player:delKeyItem(GREEN_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, ZONPAZIPPAS_ALLPURPOSE_PUTTY);
elseif (csid == 103 and option == 1) then
player:setVar("GREEN_R_LETTER_USED",1);
player:delKeyItem(GREEN_RECOMMENDATION_LETTER);
elseif (csid == 104 and option == 1) then
player:delQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:delKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:setVar("SEALED_DOORS", 0);
elseif (csid == 105 and option == 0) then
player:addQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:addKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY);
player:setVar("GREEN_R_LETTER_USED",1);
player:delKeyItem(GREEN_RECOMMENDATION_LETTER);
player:messageSpecial(KEYITEM_OBTAINED, ZONPAZIPPAS_ALLPURPOSE_PUTTY);
elseif (csid == 106 and option == 0) then
-- Is first join, so add Sprinter's Shoes and bronze medal
if (player:getVar("Campaign_Nation") == 0) then
if (player:getFreeSlotsCount() >= 1) then
player:setCampaignAllegiance(3);
player:setVar("GREEN_R_LETTER_USED",0);
player:addTitle(COBRA_UNIT_MERCENARY);
player:addKeyItem(BRONZE_RIBBON_OF_SERVICE);
player:addItem(15754);
player:completeQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:setVar("SEALED_DOORS", 0);
player:messageSpecial(KEYITEM_OBTAINED, BRONZE_RIBBON_OF_SERVICE);
player:messageSpecial(ITEM_OBTAINED, 15754);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 15754);
end
else
player:setCampaignAllegiance(3);
player:setVar("GREEN_R_LETTER_USED",0);
player:addTitle(COBRA_UNIT_MERCENARY);
player:completeQuest(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS);
player:setVar("SEALED_DOORS", 0);
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Port_Bastok/npcs/Gudav.lua | 17 | 1931 | -----------------------------------
-- Area: Port Bastok
-- NPC: Gudav
-- Starts Quests: A Foreman's Best Friend
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(13096,1) and trade:getItemCount() == 1) then
if (player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND) == QUEST_ACCEPTED) then
player:tradeComplete();
player:startEvent(0x0070);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getMainLvl() >= 7 and player:getQuestStatus(BASTOK,A_FOREMAN_S_BEST_FRIEND) == QUEST_AVAILABLE) then
player:startEvent(0x006e);
else
player:startEvent(0x001f);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x006e) then
player:addQuest(BASTOK,A_FOREMAN_S_BEST_FRIEND);
elseif (csid == 0x0070) then
if (player:hasKeyItem(MAP_OF_THE_GUSGEN_MINES) == false) then
player:addKeyItem(MAP_OF_THE_GUSGEN_MINES);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_GUSGEN_MINES);
end
player:addFame(BASTOK,BAS_FAME*60);
player:completeQuest(BASTOK,A_FOREMAN_S_BEST_FRIEND);
end
end; | gpl-3.0 |
soroushwilson/soroush | plugins/info.lua | 3 | 9283 | --[[
Add phone by : @WaderTGTeam tnx to : @WaderTGTeam
]]
do
local sudo = 136888679 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'channel' then
hash = 'rank:variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('channel#id'..msg.to.id, 'مقام کاربر ('..name..') به '..value..' تغییر داده شد ', ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = 'ندارد'
end
local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'یوزر: '..Username..'\n'
..'ایدی کاربری : '..result.id..'\n\n'
..'شماره : +'..result.phone..'\n'
local hash = 'rank:variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(sudo) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_admin2(result.id) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
text = text..''
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, extra.user..' نام کاربری مورد نظر یافت نشد.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = 'ندارد'
end
local text = 'نام کامل : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'یوزر: '..Username..'\n'
..'ایدی کاربری : '..result.id..'\n\n'
..'شماره : +'..result.phone..'\n'
local hash = 'rank:variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(sudo) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_admin2(result.id) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
text = text..''
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'ایدی شخص مورد نظر در سیستم ثبت نشده است.\nاز دستور زیر استفاده کنید\n/info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = '----'
end
local text = 'نام : '..(result.from.first_name or '')..'\nفامیل :'..(result.from.last_name or '----')..'\n'
..'یوزرنیم : '..Username..'\n'
..'ایدی : '..result.from.peer_id..'\n\n'
..'شماره : +'..result.phone..'\n'
local hash = 'مقام:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.peer_id == tonumber(sudo) then
text = text..'مقام : مدیر کل ربات Executive Admin \n\n'
elseif is_admin2(result.from.peer_id) then
text = text..'مقام : ادمین Admin \n\n'
elseif is_owner2(result.from.peer_id, result.to.peer_id) then
text = text..'مقام : مدیر کل گروه Owner \n\n'
elseif is_momod2(result.from.peer_id, result.to.peer_id) then
text = text..'مقام : مدیر گروه Moderator \n\n'
else
text = text..'مقام : کاربر Member \n\n'
end
else
text = text..'مقام : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.peer_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.peer_id..':'..result.to.peer_id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
text = text..'@anti_spam_group'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' then
local hash = 'usecommands:'..msg.from.peer_id..':'..msg.to.peer_id
redis:incr(hash)
if not is_sudo(msg) then
return "تنها برای صاحب ربات مجاز است"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'info' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = 'ندارد'
end
local text = 'نام : '..(msg.from.first_name or 'ندارد')..'\n'
local text = text..'فامیل : '..(msg.from.last_name or 'ندارد')..'\n'
local text = text..'یوزر : '..Username..'\n'
local text = text..'ایدی کاربری : '..msg.from.id..'\n\n'
local text = text..'شماره : +'..msg.from.phone..'\n'
local hash = 'rank:variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(sudo) then
text = text..'مقام : مدیر کل ربات (Executive Admin) \n\n'
elseif is_sudo(msg) then
text = text..'مقام : ادمین ربات (Admin) \n\n'
elseif is_owner(msg) then
text = text..'مقام : مدیر کل گروه (Owner) \n\n'
elseif is_momod(msg) then
text = text..'مقام : مدیر گروه (Moderator) \n\n'
else
text = text..'مقام : کاربر (Member) \n\n'
end
else
text = text..'مقام : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'تعداد پیام های فرستاده شده : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'نام گروه : '..msg.to.title..'\n'
text = text..'ایدی گروه : '..msg.to.id
end
text = text..''
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == 'info' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^([Ii][Nn][Ff][Oo])$",
"^[/!#]([Ii][Nn][Ff][Oo])$",
"^([Ii][Nn][Ff][Oo]) (.*)$",
"^[/!#]([Ii][Nn][Ff][Oo]) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
},
run = run
}
end
--[[
Add phone by : @WaderTGTeam tnx to : @WaderTGTeam
]]
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Bastok_Markets/npcs/Visala.lua | 19 | 1168 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Visala
-- Guild Merchant NPC: Goldsmithing Guild
-- @pos -202.000 -7.814 -56.823 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(5272,8,23,4)) then
player:showText(npc, VISALA_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Rabao/TextIDs.lua | 7 | 2028 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6393; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6397; -- Obtained: <item>
GIL_OBTAINED = 6398; -- Obtained <number> gil
KEYITEM_OBTAINED = 6400; -- Obtained key item: <keyitem>
NOT_HAVE_ENOUGH_GIL = 6402; -- You do not have enough gil.
HOMEPOINT_SET = 2; -- Home point set!
FISHING_MESSAGE_OFFSET = 6641; -- You can't fish here.
-- Other Texts
PAKHI_DELIVERY_DIALOG = 10004; -- When your pack is fit to burrrst, send your non-essential items to your delivery box and bam, prrroblem solved!
SPIRIT_DELIVERY_DIALOG = 10005; -- We can deliver goods to your residence or to the residences of your friends
-- Quest Dialog
GARUDA_UNLOCKED = 10089; -- You are now able to summon
NOMAD_MOOGLE_DIALOG = 10157; -- I'm a traveling moogle, kupo. I help adventurers in the Outlands access items they have stored in a Mog House elsewhere, kupo.
-- Shop Texts
SHINY_TEETH_SHOP_DIALOG = 10009; -- Well met, adventurer. If you're looking for a weapon to carve through those desert beasts, you've come to the right place.
BRAVEWOLF_SHOP_DIALOG = 10010; -- For rainy days and windy days, or for days when someone tries to thrust a spear in your guts, having a good set of armor can set your mind at ease.
BRAVEOX_SHOP_DIALOG = 10011; -- These days, you can get weapons and armor cheap at the auction houses. But magic is expensive no matter where you go.
SCAMPLIX_SHOP_DIALOG = 10012; -- No problem, Scamplix not bad guy. Scamplix is good guy, sells stuff to adventurers. Scamplix got lots of good stuff for you.
GENEROIT_SHOP_DIALOG = 10275; -- Ho there! I am called Generoit. I have everything here for the chocobo enthusiast, and other rare items galore.
-- conquest Base
CONQUEST_BASE = 6482; -- Tallying conquest results...
-- Porter Moogle
RETRIEVE_DIALOG_ID = 10731; -- You retrieve a <item> from the porter moogle's care.
| gpl-3.0 |
Jmainguy/docker_images | prosody/prosody/lib/luarocks/rocks/luasocket/3.0rc1-1/test/urltest.lua | 30 | 17349 | local socket = require("socket")
socket.url = require("socket.url")
dofile("testsupport.lua")
local check_build_url = function(parsed)
local built = socket.url.build(parsed)
if built ~= parsed.url then
print("built is different from expected")
print(built)
print(expected)
os.exit()
end
end
local check_protect = function(parsed, path, unsafe)
local built = socket.url.build_path(parsed, unsafe)
if built ~= path then
print(built, path)
print("path composition failed.")
os.exit()
end
end
local check_invert = function(url)
local parsed = socket.url.parse(url)
parsed.path = socket.url.build_path(socket.url.parse_path(parsed.path))
local rebuilt = socket.url.build(parsed)
if rebuilt ~= url then
print(url, rebuilt)
print("original and rebuilt are different")
os.exit()
end
end
local check_parse_path = function(path, expect)
local parsed = socket.url.parse_path(path)
for i = 1, math.max(#parsed, #expect) do
if parsed[i] ~= expect[i] then
print(path)
os.exit()
end
end
if expect.is_directory ~= parsed.is_directory then
print(path)
print("is_directory mismatch")
os.exit()
end
if expect.is_absolute ~= parsed.is_absolute then
print(path)
print("is_absolute mismatch")
os.exit()
end
local built = socket.url.build_path(expect)
if built ~= path then
print(built, path)
print("path composition failed.")
os.exit()
end
end
local check_absolute_url = function(base, relative, absolute)
local res = socket.url.absolute(base, relative)
if res ~= absolute then
io.write("absolute: In test for '", relative, "' expected '",
absolute, "' but got '", res, "'\n")
os.exit()
end
end
local check_parse_url = function(gaba)
local url = gaba.url
gaba.url = nil
local parsed = socket.url.parse(url)
for i, v in pairs(gaba) do
if v ~= parsed[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '",
v, "' but got '", tostring(parsed[i]), "'\n")
for i,v in pairs(parsed) do print(i,v) end
os.exit()
end
end
for i, v in pairs(parsed) do
if v ~= gaba[i] then
io.write("parse: In test for '", url, "' expected ", i, " = '",
tostring(gaba[i]), "' but got '", v, "'\n")
for i,v in pairs(parsed) do print(i,v) end
os.exit()
end
end
end
print("testing URL parsing")
check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@host:port",
host = "host",
port = "port",
userinfo = "user:password",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment",
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params?query#",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = ""
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params?#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path;params#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path;?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/path?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port/;params?query#fragment",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://userinfo@host:port",
scheme = "scheme",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
}
check_parse_url{
url = "//userinfo@host:port/path;params?query#fragment",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "//userinfo@host:port/path",
authority = "userinfo@host:port",
host = "host",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
}
check_parse_url{
url = "//userinfo@host/path",
authority = "userinfo@host",
host = "host",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
}
check_parse_url{
url = "//user:password@host/path",
authority = "user:password@host",
host = "host",
userinfo = "user:password",
password = "password",
user = "user",
path = "/path",
}
check_parse_url{
url = "//user:@host/path",
authority = "user:@host",
host = "host",
userinfo = "user:",
password = "",
user = "user",
path = "/path",
}
check_parse_url{
url = "//user@host:port/path",
authority = "user@host:port",
host = "host",
userinfo = "user",
user = "user",
port = "port",
path = "/path",
}
check_parse_url{
url = "//host:port/path",
authority = "host:port",
port = "port",
host = "host",
path = "/path",
}
check_parse_url{
url = "//host/path",
authority = "host",
host = "host",
path = "/path",
}
check_parse_url{
url = "//host",
authority = "host",
host = "host",
}
check_parse_url{
url = "/path",
path = "/path",
}
check_parse_url{
url = "path",
path = "path",
}
-- IPv6 tests
check_parse_url{
url = "http://[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80/index.html",
scheme = "http",
host = "FEDC:BA98:7654:3210:FEDC:BA98:7654:3210",
authority = "[FEDC:BA98:7654:3210:FEDC:BA98:7654:3210]:80",
port = "80",
path = "/index.html"
}
check_parse_url{
url = "http://[1080:0:0:0:8:800:200C:417A]/index.html",
scheme = "http",
host = "1080:0:0:0:8:800:200C:417A",
authority = "[1080:0:0:0:8:800:200C:417A]",
path = "/index.html"
}
check_parse_url{
url = "http://[3ffe:2a00:100:7031::1]",
scheme = "http",
host = "3ffe:2a00:100:7031::1",
authority = "[3ffe:2a00:100:7031::1]",
}
check_parse_url{
url = "http://[1080::8:800:200C:417A]/foo",
scheme = "http",
host = "1080::8:800:200C:417A",
authority = "[1080::8:800:200C:417A]",
path = "/foo"
}
check_parse_url{
url = "http://[::192.9.5.5]/ipng",
scheme = "http",
host = "::192.9.5.5",
authority = "[::192.9.5.5]",
path = "/ipng"
}
check_parse_url{
url = "http://[::FFFF:129.144.52.38]:80/index.html",
scheme = "http",
host = "::FFFF:129.144.52.38",
port = "80",
authority = "[::FFFF:129.144.52.38]:80",
path = "/index.html"
}
check_parse_url{
url = "http://[2010:836B:4179::836B:4179]",
scheme = "http",
host = "2010:836B:4179::836B:4179",
authority = "[2010:836B:4179::836B:4179]",
}
check_parse_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
authority = "userinfo@[::FFFF:129.144.52.38]:port",
host = "::FFFF:129.144.52.38",
port = "port",
userinfo = "userinfo",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_parse_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@[::192.9.5.5]:port",
host = "::192.9.5.5",
port = "port",
userinfo = "user:password",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
print("testing URL building")
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url{
url = "//userinfo@[::FFFF:129.144.52.38]:port/path;params?query#fragment",
host = "::FFFF:129.144.52.38",
port = "port",
user = "userinfo",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url{
url = "scheme://user:password@[::192.9.5.5]:port/path;params?query#fragment",
scheme = "scheme",
host = "::192.9.5.5",
port = "port",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host/path;params?query#fragment",
scheme = "scheme",
host = "host",
user = "user",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user@host/path;params?query#fragment",
scheme = "scheme",
host = "host",
user = "user",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path;params?query#fragment",
scheme = "scheme",
host = "host",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path;params#fragment",
scheme = "scheme",
host = "host",
path = "/path",
params = "params",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path#fragment",
scheme = "scheme",
host = "host",
path = "/path",
fragment = "fragment"
}
check_build_url {
url = "scheme://host/path",
scheme = "scheme",
host = "host",
path = "/path",
}
check_build_url {
url = "//host/path",
host = "host",
path = "/path",
}
check_build_url {
url = "/path",
path = "/path",
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
userinfo = "not used",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
user = "user",
userinfo = "not used",
authority = "not used",
password = "password",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
host = "host",
port = "port",
userinfo = "user:password",
authority = "not used",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
check_build_url {
url = "scheme://user:password@host:port/path;params?query#fragment",
scheme = "scheme",
authority = "user:password@host:port",
path = "/path",
params = "params",
query = "query",
fragment = "fragment"
}
-- standard RFC tests
print("testing absolute resolution")
check_absolute_url("http://a/b/c/d;p?q#f", "g:h", "g:h")
check_absolute_url("http://a/b/c/d;p?q#f", "g", "http://a/b/c/g")
check_absolute_url("http://a/b/c/d;p?q#f", "./g", "http://a/b/c/g")
check_absolute_url("http://a/b/c/d;p?q#f", "g/", "http://a/b/c/g/")
check_absolute_url("http://a/b/c/d;p?q#f", "/g", "http://a/g")
check_absolute_url("http://a/b/c/d;p?q#f", "//g", "http://g")
check_absolute_url("http://a/b/c/d;p?q#f", "?y", "http://a/b/c/d;p?y")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y", "http://a/b/c/g?y")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y/./x", "http://a/b/c/g?y/./x")
check_absolute_url("http://a/b/c/d;p?q#f", "#s", "http://a/b/c/d;p?q#s")
check_absolute_url("http://a/b/c/d;p?q#f", "g#s", "http://a/b/c/g#s")
check_absolute_url("http://a/b/c/d;p?q#f", "g#s/./x", "http://a/b/c/g#s/./x")
check_absolute_url("http://a/b/c/d;p?q#f", "g?y#s", "http://a/b/c/g?y#s")
check_absolute_url("http://a/b/c/d;p?q#f", ";x", "http://a/b/c/d;x")
check_absolute_url("http://a/b/c/d;p?q#f", "g;x", "http://a/b/c/g;x")
check_absolute_url("http://a/b/c/d;p?q#f", "g;x?y#s", "http://a/b/c/g;x?y#s")
check_absolute_url("http://a/b/c/d;p?q#f", ".", "http://a/b/c/")
check_absolute_url("http://a/b/c/d;p?q#f", "./", "http://a/b/c/")
check_absolute_url("http://a/b/c/d;p?q#f", "..", "http://a/b/")
check_absolute_url("http://a/b/c/d;p?q#f", "../", "http://a/b/")
check_absolute_url("http://a/b/c/d;p?q#f", "../g", "http://a/b/g")
check_absolute_url("http://a/b/c/d;p?q#f", "../..", "http://a/")
check_absolute_url("http://a/b/c/d;p?q#f", "../../", "http://a/")
check_absolute_url("http://a/b/c/d;p?q#f", "../../g", "http://a/g")
check_absolute_url("http://a/b/c/d;p?q#f", "", "http://a/b/c/d;p?q#f")
check_absolute_url("http://a/b/c/d;p?q#f", "/./g", "http://a/./g")
check_absolute_url("http://a/b/c/d;p?q#f", "/../g", "http://a/../g")
check_absolute_url("http://a/b/c/d;p?q#f", "g.", "http://a/b/c/g.")
check_absolute_url("http://a/b/c/d;p?q#f", ".g", "http://a/b/c/.g")
check_absolute_url("http://a/b/c/d;p?q#f", "g..", "http://a/b/c/g..")
check_absolute_url("http://a/b/c/d;p?q#f", "..g", "http://a/b/c/..g")
check_absolute_url("http://a/b/c/d;p?q#f", "./../g", "http://a/b/g")
check_absolute_url("http://a/b/c/d;p?q#f", "./g/.", "http://a/b/c/g/")
check_absolute_url("http://a/b/c/d;p?q#f", "g/./h", "http://a/b/c/g/h")
check_absolute_url("http://a/b/c/d;p?q#f", "g/../h", "http://a/b/c/h")
-- extra tests
check_absolute_url("//a/b/c/d;p?q#f", "d/e/f", "//a/b/c/d/e/f")
check_absolute_url("/a/b/c/d;p?q#f", "d/e/f", "/a/b/c/d/e/f")
check_absolute_url("a/b/c/d", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("a/b/c/d/../", "d/e/f", "a/b/c/d/e/f")
check_absolute_url("http://velox.telemar.com.br", "/dashboard/index.html",
"http://velox.telemar.com.br/dashboard/index.html")
print("testing path parsing and composition")
check_parse_path("/eu/tu/ele", { "eu", "tu", "ele"; is_absolute = 1 })
check_parse_path("/eu/", { "eu"; is_absolute = 1, is_directory = 1 })
check_parse_path("eu/tu/ele/nos/vos/eles/",
{ "eu", "tu", "ele", "nos", "vos", "eles"; is_directory = 1})
check_parse_path("/", { is_absolute = 1, is_directory = 1})
check_parse_path("", { })
check_parse_path("eu%01/%02tu/e%03l%04e/nos/vos%05/e%12les/",
{ "eu\1", "\2tu", "e\3l\4e", "nos", "vos\5", "e\18les"; is_directory = 1})
check_parse_path("eu/tu", { "eu", "tu" })
print("testing path protection")
check_protect({ "eu", "-_.!~*'():@&=+$,", "tu" }, "eu/-_.!~*'():@&=+$,/tu")
check_protect({ "eu ", "~diego" }, "eu%20/~diego")
check_protect({ "/eu>", "<diego?" }, "%2feu%3e/%3cdiego%3f")
check_protect({ "\\eu]", "[diego`" }, "%5ceu%5d/%5bdiego%60")
check_protect({ "{eu}", "|diego\127" }, "%7beu%7d/%7cdiego%7f")
check_protect({ "eu ", "~diego" }, "eu /~diego", 1)
check_protect({ "/eu>", "<diego?" }, "/eu>/<diego?", 1)
check_protect({ "\\eu]", "[diego`" }, "\\eu]/[diego`", 1)
check_protect({ "{eu}", "|diego\127" }, "{eu}/|diego\127", 1)
print("testing inversion")
check_invert("http:")
check_invert("a/b/c/d.html")
check_invert("//net_loc")
check_invert("http:a/b/d/c.html")
check_invert("//net_loc/a/b/d/c.html")
check_invert("http://net_loc/a/b/d/c.html")
check_invert("//who:isit@net_loc")
check_invert("http://he:man@boo.bar/a/b/c/i.html;type=moo?this=that#mark")
check_invert("/b/c/d#fragment")
check_invert("/b/c/d;param#fragment")
check_invert("/b/c/d;param?query#fragment")
check_invert("/b/c/d?query")
check_invert("/b/c/d;param?query")
check_invert("http://he:man@[::192.168.1.1]/a/b/c/i.html;type=moo?this=that#mark")
print("the library passed all tests")
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Lower_Jeuno/npcs/Harnek.lua | 17 | 2370 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Harnek
-- Starts and Finishes Quest: The Tenshodo Showdown (finish)
-- @zone 245
-- @pos 44 0 -19
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(LETTER_FROM_THE_TENSHODO)) then
player:startEvent(0x2725,0,LETTER_FROM_THE_TENSHODO); -- During Quest "The Tenshodo Showdown"
elseif (player:hasKeyItem(SIGNED_ENVELOPE)) then
player:startEvent(0x2726); -- Finish Quest "The Tenshodo Showdown"
else
player:startEvent(0x00d9); -- Standard dialog
end
end;
-- 0x000c 0x000d 0x0009 0x000a 0x0014 0x00d9 0x009f 0x2725 0x2726
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x2725) then
player:setVar("theTenshodoShowdownCS",2);
player:delKeyItem(LETTER_FROM_THE_TENSHODO);
player:addKeyItem(TENSHODO_ENVELOPE);
player:messageSpecial(KEYITEM_OBTAINED,TENSHODO_ENVELOPE);
elseif (csid == 0x2726) then
if (player:getFreeSlotsCount() == 0 or player:hasItem(16764)) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16764); -- Marauder's Knife
else
player:delKeyItem(SIGNED_ENVELOPE);
player:addItem(16764);
player:messageSpecial(ITEM_OBTAINED, 16764); -- Marauder's Knife
player:setVar("theTenshodoShowdownCS",0);
player:addFame(WINDURST,WIN_FAME*30);
player:completeQuest(WINDURST,THE_TENSHODO_SHOWDOWN);
end
end
end; | gpl-3.0 |
Guard13007/LightWorld-Editor | src/lib/light_world/body.lua | 1 | 23696 | local _PACKAGE = (...):match("^(.+)[%./][^%./]+") or ""
local normal_map = require(_PACKAGE..'/normal_map')
local util = require(_PACKAGE..'/util')
local anim8 = require(_PACKAGE..'/anim8')
local vector = require(_PACKAGE..'/vector')
local body = {}
body.__index = body
body.glowShader = love.graphics.newShader(_PACKAGE.."/shaders/glow.glsl")
body.materialShader = love.graphics.newShader(_PACKAGE.."/shaders/material.glsl")
local function new(id, type, ...)
local args = {...}
local obj = setmetatable({}, body)
obj.id = id
obj.type = type
obj.shine = true
obj.red = 1.0
obj.green = 1.0
obj.blue = 1.0
obj.alpha = 1.0
obj.glowRed = 255
obj.glowGreen = 255
obj.glowBlue = 255
obj.glowStrength = 0.0
obj.tileX = 0
obj.tileY = 0
obj.zheight = 1
obj.rotation = 0
obj.scalex = 1
obj.scaley = 1
obj.castsNoShadow = false
obj.visible = true
obj.is_on_screen = true
if obj.type == "circle" then
obj.x = args[1] or 0
obj.y = args[2] or 0
circle_canvas = love.graphics.newCanvas(args[3]*2, args[3]*2)
util.drawto(circle_canvas, 0, 0, 1, function()
love.graphics.circle('fill', args[3], args[3], args[3])
end)
obj.img = love.graphics.newImage(circle_canvas:getImageData())
obj.imgWidth = obj.img:getWidth()
obj.imgHeight = obj.img:getHeight()
obj.ix = obj.imgWidth * 0.5
obj.iy = obj.imgHeight * 0.5
obj:generateNormalMapFlat("top")
obj:setShadowType('circle', args[3], args[4], args[5])
elseif obj.type == "rectangle" then
local x = args[1] or 0
local y = args[2] or 0
local width = args[3] or 64
local height = args[4] or 64
local ox = args[5] or width * 0.5
local oy = args[6] or height * 0.5
obj:setPoints(
x - ox, y - oy,
x - ox + width, y - oy,
x - ox + width, y - oy + height,
x - ox, y - oy + height
)
elseif obj.type == "polygon" then
obj:setPoints(...)
elseif obj.type == "image" then
obj.img = args[1]
obj.x = args[2] or 0
obj.y = args[3] or 0
if obj.img then
obj.imgWidth = obj.img:getWidth()
obj.imgHeight = obj.img:getHeight()
obj.ix = obj.imgWidth * 0.5
obj.iy = obj.imgHeight * 0.5
end
obj:generateNormalMapFlat("top")
obj:setShadowType('rectangle', args[4] or obj.imgWidth, args[5] or obj.imgHeight, args[6], args[7])
obj.reflective = true
elseif obj.type == "animation" then
obj.img = args[1]
obj.x = args[2] or 0
obj.y = args[3] or 0
obj.animations = {}
obj.castsNoShadow = true
obj:generateNormalMapFlat("top")
obj.reflective = true
elseif obj.type == "refraction" then
obj.x = args[2] or 0
obj.y = args[3] or 0
obj:setNormalMap(args[1], args[4], args[5])
obj.width = args[4] or obj.normalWidth
obj.height = args[5] or obj.normalHeight
obj.ox = obj.width * 0.5
obj.oy = obj.height * 0.5
obj.refraction = true
elseif obj.type == "reflection" then
obj.x = args[2] or 0
obj.y = args[3] or 0
obj:setNormalMap(args[1], args[4], args[5])
obj.width = args[4] or obj.normalWidth
obj.height = args[5] or obj.normalHeight
obj.ox = obj.width * 0.5
obj.oy = obj.height * 0.5
obj.reflection = true
end
obj:commit_changes()
return obj
end
-- refresh
function body:refresh()
if self.shadowType == 'polygon' and self:has_changed() then
self.data = {unpack(self.unit_data)}
local center = vector(self.x, self.y)
for i = 1, #self.data, 2 do
local point = vector(self.data[i], self.data[i+1])
point = point:rotate(self.rotation)
point = point:scale(self.scalex, self.scaley)
self.data[i], self.data[i+1] = (point + center):unpack()
end
self:commit_changes()
end
end
function body:has_changed()
return self:position_changed() or
self:rotation_changed() or
self:scale_changed()
end
function body:position_changed()
return self.old_x ~= self.x or
self.old_y ~= self.y
end
function body:rotation_changed()
return self.old_rotation ~= self.rotation
end
function body:scale_changed()
return self.old_scalex ~= self.scalex or
self.old_scaley ~= self.scaley
end
function body:commit_changes()
self.old_x, self.old_y = self.x, self.y
self.old_rotation = self.rotation
self.old_scalex, self.old_scaley = self.scalex, self.scaley
end
function body:newGrid(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border)
return anim8.newGrid(
frameWidth, frameHeight,
imageWidth or self.img:getWidth(), imageHeight or self.img:getHeight(),
left, top, border
)
end
-- frameWidth, frameHeight, imageWidth, imageHeight, left, top, border
function body:addAnimation(name, frames, durations, onLoop)
self.animations[name] = anim8.newAnimation(frames, durations, onLoop)
if not self.current_animation_name then
self:setAnimation(name)
end
end
function body:setAnimation(name)
self.current_animation_name = name
self.animation = self.animations[self.current_animation_name]
local frame = self.animation.frames[self.animation.position]
_,_,self.width, self.height = frame:getViewport()
end
function body:gotoFrame(frame) self.animation:gotoFrame(frame) end
function body:pause() self.animation:pause() end
function body:resume() self.animation:resume() end
function body:flipH() self.animation:flipH() end
function body:flipV() self.animation:flipV() end
function body:pauseAtEnd() self.animation:pauseAtEnd() end
function body:pauseAtStart() self.animation:pauseAtStart() end
function body:update(dt)
self:refresh()
if self.type == "animation" and self.animation then
local frame = self.animation.frames[self.animation.position]
_,_,self.width, self.height = frame:getViewport()
self.imgWidth, self.imgHeight = self.width, self.height
self.normalWidth, self.normalHeight = self.width, self.height
self.ix, self.iy = self.imgWidth * 0.5,self.imgHeight * 0.5
self.nx, self.ny = self.ix, self.iy
self.animation:update(dt)
end
end
function body:rotate(angle)
self:setRotation(self.rotation + angle)
end
function body:setRotation(angle)
self.rotation = angle
end
function body:scale(sx, sy)
self.scalex = self.scalex + sx
self.scaley = self.scaley + (sy or sx)
end
function body:setScale(sx, sy)
self.scalex = sx
self.scaley = sy or sx
end
-- set position
function body:setPosition(x, y)
if x ~= self.x or y ~= self.y then
self.x = x
self.y = y
end
end
-- move position
function body:move(x, y)
if x then
self.x = self.x + x
end
if y then
self.y = self.y + y
end
end
-- get x position
function body:getPosition()
return self.x, self.y
end
-- get width
function body:getWidth()
return self.width
end
-- get height
function body:getHeight()
return self.height
end
-- get image width
function body:getImageWidth()
return self.imgWidth
end
-- get image height
function body:getImageHeight()
return self.imgHeight
end
-- set offset
function body:setOffset(ox, oy)
if ox ~= self.ox or oy ~= self.oy then
self.ox = ox
self.oy = oy
end
end
-- set offset
function body:setImageOffset(ix, iy)
if ix ~= self.ix or iy ~= self.iy then
self.ix = ix
self.iy = iy
end
end
-- set offset
function body:setNormalOffset(nx, ny)
if nx ~= self.nx or ny ~= self.ny then
self.nx = nx
self.ny = ny
end
end
-- set glow color
function body:setGlowColor(red, green, blue)
self.glowRed = red
self.glowGreen = green
self.glowBlue = blue
end
-- set glow alpha
function body:setGlowStrength(strength)
self.glowStrength = strength
end
function body:setVisible(visible)
self.visible = visible
end
-- get radius
function body:getRadius()
return self.radius * self.scalex
end
-- set radius
function body:setRadius(radius)
if radius ~= self.radius then
self.radius = radius
end
end
-- set polygon data
function body:setPoints(...)
self.unit_data = {...}
--calculate l,r,t,b
self.x, self.y, self.width, self.height = self.unit_data[1], self.unit_data[2], 0, 0
for i = 1, #self.unit_data, 2 do
local px, py = self.unit_data[i], self.unit_data[i+1]
if px < self.x then self.x = px end
if py < self.y then self.y = py end
if px > self.width then self.width = px end
if py > self.height then self.height = py end
end
-- normalize width and height
self.width = self.width - self.x
self.height = self.height - self.y
for i = 1, #self.unit_data, 2 do
self.unit_data[i], self.unit_data[i+1] = self.unit_data[i] - self.x, self.unit_data[i+1] - self.y
end
self.x = self.x + (self.width * 0.5)
self.y = self.y + (self.height * 0.5)
local poly_canvas = love.graphics.newCanvas(self.width, self.height)
util.drawto(poly_canvas, 0, 0, 1, function()
love.graphics.polygon('fill', self.unit_data)
end)
--normalize points to be around the center x y
for i = 1, #self.unit_data, 2 do
self.unit_data[i], self.unit_data[i+1] = self.unit_data[i] - self.width * 0.5, self.unit_data[i+1] - self.height * 0.5
end
if not self.img then
self.img = love.graphics.newImage(poly_canvas:getImageData())
self.imgWidth = self.img:getWidth()
self.imgHeight = self.img:getHeight()
self.ix = self.imgWidth * 0.5
self.iy = self.imgHeight * 0.5
self:generateNormalMapFlat("top")
end
--wrapping with polygon normals causes edges to show
--also we do not need wrapping for this default normal map
self.normal:setWrap("clamp", "clamp")
self.shadowType = "polygon"
self:refresh()
end
-- get polygon data
function body:getPoints()
return unpack(self.data)
end
-- set shadow on/off
function body:setShadow(b)
self.castsNoShadow = not b
end
-- set shine on/off
function body:setShine(b)
self.shine = b
end
-- set glass color
function body:setColor(red, green, blue)
self.red = red
self.green = green
self.blue = blue
end
-- set glass alpha
function body:setAlpha(alpha)
self.alpha = alpha
end
-- set reflection on/off
function body:setReflection(reflection)
self.reflection = reflection
end
-- set refraction on/off
function body:setRefraction(refraction)
self.refraction = refraction
end
-- set reflective on other objects on/off
function body:setReflective(reflective)
self.reflective = reflective
end
-- set refractive on other objects on/off
function body:setRefractive(refractive)
self.refractive = refractive
end
-- set image
function body:setImage(img)
if img then
self.img = img
self.imgWidth = self.img:getWidth()
self.imgHeight = self.img:getHeight()
self.ix = self.imgWidth * 0.5
self.iy = self.imgHeight * 0.5
end
end
-- set normal
function body:setNormalMap(normal, width, height, nx, ny)
if normal then
self.normal = normal
self.normal:setWrap("repeat", "repeat")
self.normalWidth = width or self.normal:getWidth()
self.normalHeight = height or self.normal:getHeight()
self.nx = nx or self.normalWidth * 0.5
self.ny = ny or self.normalHeight * 0.5
self.normalVert = {
{0.0, 0.0, 0.0, 0.0},
{self.normalWidth, 0.0, self.normalWidth / self.normal:getWidth(), 0.0},
{self.normalWidth, self.normalHeight, self.normalWidth / self.normal:getWidth(), self.normalHeight / self.normal:getHeight()},
{0.0, self.normalHeight, 0.0, self.normalHeight / self.normal:getHeight()}
}
self.normalMesh = love.graphics.newMesh(self.normalVert, self.normal, "fan")
else
self.normalMesh = nil
end
end
-- set height map
function body:setHeightMap(heightMap, strength)
self:setNormalMap(normal_map.fromHeightMap(heightMap, strength))
end
-- generate flat normal map
function body:generateNormalMapFlat(mode)
self:setNormalMap(normal_map.generateFlat(self.img, mode))
end
-- generate faded normal map
function body:generateNormalMapGradient(horizontalGradient, verticalGradient)
self:setNormalMap(normal_map.generateGradient(self.img, horizontalGradient, verticalGradient))
end
-- generate normal map
function body:generateNormalMap(strength)
self:setNormalMap(normal_map.fromHeightMap(self.img, strength))
end
-- set material
function body:setMaterial(material)
if material then
self.material = material
end
end
-- set normal
function body:setGlowMap(glow)
self.glow = glow
self.glowStrength = 1.0
end
-- set tile offset
function body:setNormalTileOffset(tx, ty)
self.tileX = tx / self.normalWidth
self.tileY = ty / self.normalHeight
self.normalVert = {
{0.0, 0.0, self.tileX, self.tileY},
{self.normalWidth, 0.0, self.tileX + 1.0, self.tileY},
{self.normalWidth, self.normalHeight, self.tileX + 1.0, self.tileY + 1.0},
{0.0, self.normalHeight, self.tileX, self.tileY + 1.0}
}
end
-- get type
function body:getType()
return self.type
end
-- get type
function body:setShadowType(type, ...)
self.shadowType = type
local args = {...}
if self.shadowType == "circle" then
self.radius = args[1] or 16
self.ox = args[2] or 0
self.oy = args[3] or 0
elseif self.shadowType == "rectangle" then
self.shadowType = "polygon"
local width = args[1] or 64
local height = args[2] or 64
self.ox = args[3] or width * 0.5
self.oy = args[4] or height * 0.5
self:setPoints(
self.x - self.ox, self.y - self.oy,
self.x - self.ox + width, self.y - self.oy,
self.x - self.ox + width, self.y - self.oy + height,
self.x - self.ox, self.y - self.oy + height
)
elseif self.shadowType == "polygon" then
self:setPoints(args)
elseif self.shadowType == "image" then
if self.img then
self.width = self.imgWidth
self.height = self.imgHeight
self.shadowVert = {
{0.0, 0.0, 0.0, 0.0},
{self.width, 0.0, 1.0, 0.0},
{self.width, self.height, 1.0, 1.0},
{0.0, self.height, 0.0, 1.0}
}
if not self.shadowMesh then
self.shadowMesh = love.graphics.newMesh(self.shadowVert, self.img, "fan")
self.shadowMesh:setVertexColors(true)
end
else
self.width = 64
self.height = 64
end
self.shadowX = args[1] or 0
self.shadowY = args[2] or 0
self.fadeStrength = args[3] or 0.0
end
end
function body:isVisible()
return self.visible and self.is_on_screen
end
function body:inLightRange(light)
local l, t, w = light.x - light.range, light.y - light.range, light.range*2
return self:inRange(l,t,w,w,1)
end
function body:inRange(l, t, w, h, s)
local radius
if self.type == 'circle' then
radius = self.radius * self.scalex
else
local sw = (self.width * self.scalex)
local sh = (self.height * self.scaley)
radius = (sw > sh and sw or sh)
end
local bx, by, bw, bh = self.x - radius, self.y - radius, radius * 2, radius * 2
return self.visible and (bx+bw) > (l/s) and bx < (l+w)/s and (by+bh) > (t/s) and by < (t+h)/s
end
function body:drawAnimation()
self.animation:draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
end
function body:drawNormal()
if not self.refraction and not self.reflection and self.normalMesh then
love.graphics.setColor(255, 255, 255)
if self.type == 'animation' then
self.animation:draw(self.normal, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
else
love.graphics.draw(self.normalMesh, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
end
end
end
function body:drawGlow()
love.graphics.setColor(self.glowRed * self.glowStrength, self.glowGreen * self.glowStrength, self.glowBlue * self.glowStrength)
if self.type == "circle" then
love.graphics.circle("fill", self.x, self.y, self.radius * self.scalex)
elseif self.type == "polygon" then
love.graphics.polygon("fill", unpack(self.data))
elseif (self.type == "image" or self.type == "animation") and self.img then
if self.glow then
love.graphics.setShader(self.glowShader)
self.glowShader:send("glowImage", self.glow)
self.glowShader:send("glowTime", love.timer.getTime() * 0.5)
love.graphics.setColor(255, 255, 255)
else
love.graphics.setColor(0, 0, 0)
end
if self.type == "animation" then
self.animation:draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
else
love.graphics.draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
end
love.graphics.setShader()
end
end
function body:drawRefraction()
if self.refraction and self.normal then
love.graphics.setColor(255, 255, 255)
if self.tileX == 0.0 and self.tileY == 0.0 then
love.graphics.draw(self.normal, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
else
self.normalMesh:setVertices(self.normalVert)
love.graphics.draw(self.normalMesh, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
end
end
love.graphics.setColor(0, 0, 0)
if not self.refractive then
if self.type == "circle" then
love.graphics.circle("fill", self.x, self.y, self.radius * self.scalex)
elseif self.type == "polygon" then
love.graphics.polygon("fill", unpack(self.data))
elseif self.type == "image" and self.img then
love.graphics.draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
elseif self.type == 'animation' then
self.animation:draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
end
end
end
function body:drawReflection()
if self.reflection and self.normal then
love.graphics.setColor(255, 0, 0)
self.normalMesh:setVertices(self.normalVert)
love.graphics.draw(self.normalMesh, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
end
if self.reflective and self.img then
love.graphics.setColor(0, 255, 0)
if self.type == 'animation' then
self.animation:draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
else
love.graphics.draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
end
elseif not self.reflection and self.img then
love.graphics.setColor(0, 0, 0)
if self.type == 'animation' then
self.animation:draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
else
love.graphics.draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
end
end
end
function body:drawMaterial()
if self.material and self.normal then
love.graphics.setShader(self.materialShader)
love.graphics.setColor(255, 255, 255)
self.materialShader:send("material", self.material)
if self.type == 'animation' then
self.animation:draw(self.normal, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
else
love.graphics.draw(self.normal, self.x, self.y, self.rotation, self.scalex, self.scaley, self.nx, self.ny)
end
love.graphics.setShader()
end
end
function body:drawStencil()
if not self.refraction and not self.reflection and not self.castsNoShadow then
love.graphics.draw(self.img, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ix, self.iy)
end
end
function body:drawShadow(light)
if self.castsNoShadow or (self.zheight - light.z) > 0 then
return
end
love.graphics.setColor(self.red, self.green, self.blue, self.alpha)
if self.shadowType == "polygon" then
self:drawPolyShadow(light)
elseif self.shadowType == "circle" then
self:drawCircleShadow(light)
elseif self.shadowType == "image" and self.img then
self:drawImageShadow(light)
end
end
--using shadow point calculations from this article
--http://web.cs.wpi.edu/~matt/courses/cs563/talks/shadow/shadow.html
function body:drawPolyShadow(light)
local lightPosition = vector(light.x, light.y)
local lh = lightPosition * self.zheight
local height_diff = (self.zheight - light.z)
if height_diff == 0 then -- prevent inf
height_diff = -0.001
end
for i = 1, #self.data, 2 do
local vertex = vector(self.data[i], self.data[i + 1])
local nextVertex = vector(self.data[(i + 2) % #self.data], self.data[(i + 2) % #self.data + 1])
local startToEnd = nextVertex - vertex
if vector(startToEnd.y, -startToEnd.x) * (vertex - lightPosition) > 0 then
local point1 = (lh - (vertex * light.z))/height_diff
local point2 = (lh - (nextVertex * light.z))/height_diff
love.graphics.polygon("fill",
vertex.x, vertex.y, point1.x, point1.y,
point2.x, point2.y, nextVertex.x, nextVertex.y)
end
end
end
--using shadow point calculations from this article
--http://web.cs.wpi.edu/~matt/courses/cs563/talks/shadow/shadow.html
function body:drawCircleShadow(light)
local selfPos = vector(self.x - self.ox, self.y - self.oy)
local lightPosition = vector(light.x, light.y)
local lh = lightPosition * self.zheight
local height_diff = (self.zheight - light.z)
local radius = self.radius * self.scalex
if height_diff == 0 then -- prevent inf
height_diff = -0.001
end
local angle = math.atan2(light.x - selfPos.x, selfPos.y - light.y) + math.pi / 2
local point1 = vector(selfPos.x + math.sin(angle) * radius,
selfPos.y - math.cos(angle) * radius)
local point2 = vector(selfPos.x - math.sin(angle) * radius,
selfPos.y + math.cos(angle) * radius)
local point3 = (lh - (point1 * light.z))/height_diff
local point4 = (lh - (point2 * light.z))/height_diff
local shadow_radius = point3:dist(point4)/2
local circleCenter = (point3 + point4)/2
if lightPosition:dist(selfPos) <= radius then
love.graphics.circle("fill", circleCenter.x, circleCenter.y, shadow_radius)
else
love.graphics.polygon("fill", point1.x, point1.y,
point2.x, point2.y,
point4.x, point4.y,
point3.x, point3.y)
if lightPosition:dist(circleCenter) < light.range then -- dont draw circle if way off screen
local angle1 = math.atan2(point3.y - circleCenter.y, point3.x - circleCenter.x)
local angle2 = math.atan2(point4.y - circleCenter.y, point4.x - circleCenter.x)
if angle1 < angle2 then
love.graphics.arc("fill", circleCenter.x, circleCenter.y, shadow_radius, angle1, angle2)
else
love.graphics.arc("fill", circleCenter.x, circleCenter.y, shadow_radius, angle1 - math.pi, angle2 - math.pi)
end
end
end
end
function body:drawImageShadow(light)
local height_diff = (light.z - self.zheight)
if height_diff <= 0.1 then -- prevent shadows from leaving thier person like peter pan.
height_diff = 0.1
end
local length = 1.0 / height_diff
local shadowRotation = math.atan2((self.x) - light.x, (self.y + self.oy) - light.y)
local shadowStartY = self.imgHeight + (math.cos(shadowRotation) + 1.0) * self.shadowY
local shadowX = math.sin(shadowRotation) * self.imgHeight * length
local shadowY = (length * math.cos(shadowRotation) + 1.0) * shadowStartY
self.shadowMesh:setVertices({
{shadowX, shadowY, 0, 0, self.red, self.green, self.blue, self.alpha},
{shadowX + self.imgWidth, shadowY, 1, 0, self.red, self.green, self.blue, self.alpha},
{self.imgWidth, shadowStartY, 1, 1, self.red, self.green, self.blue, self.alpha},
{0, shadowStartY, 0, 1, self.red, self.green, self.blue, self.alpha}
})
love.graphics.draw(self.shadowMesh, self.x, self.y, self.rotation, self.scalex, self.scaley, self.ox, self.oy)
end
return setmetatable({new = new}, {__call = function(_, ...) return new(...) end})
| mit |
Almightree/GuildInviteTool | Libs/AceGUI-3.0/widgets/AceGUIContainer-TreeGroup.lua | 9 | 19868 | --[[-----------------------------------------------------------------------------
TreeGroup Container
Container that uses a tree control to switch between groups.
-------------------------------------------------------------------------------]]
local Type, Version = "TreeGroup", 38
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local next, pairs, ipairs, assert, type = next, pairs, ipairs, assert, type
local math_min, math_max, floor = math.min, math.max, floor
local select, tremove, unpack, tconcat = select, table.remove, unpack, table.concat
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameTooltip, FONT_COLOR_CODE_CLOSE
-- Recycling functions
local new, del
do
local pool = setmetatable({},{__mode='k'})
function new()
local t = next(pool)
if t then
pool[t] = nil
return t
else
return {}
end
end
function del(t)
for k in pairs(t) do
t[k] = nil
end
pool[t] = true
end
end
local DEFAULT_TREE_WIDTH = 175
local DEFAULT_TREE_SIZABLE = true
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function GetButtonUniqueValue(line)
local parent = line.parent
if parent and parent.value then
return GetButtonUniqueValue(parent).."\001"..line.value
else
return line.value
end
end
local function UpdateButton(button, treeline, selected, canExpand, isExpanded)
local self = button.obj
local toggle = button.toggle
local frame = self.frame
local text = treeline.text or ""
local icon = treeline.icon
local iconCoords = treeline.iconCoords
local level = treeline.level
local value = treeline.value
local uniquevalue = treeline.uniquevalue
local disabled = treeline.disabled
button.treeline = treeline
button.value = value
button.uniquevalue = uniquevalue
if selected then
button:LockHighlight()
button.selected = true
else
button:UnlockHighlight()
button.selected = false
end
local normalTexture = button:GetNormalTexture()
local line = button.line
button.level = level
if ( level == 1 ) then
button:SetNormalFontObject("GameFontNormal")
button:SetHighlightFontObject("GameFontHighlight")
button.text:SetPoint("LEFT", (icon and 16 or 0) + 8, 2)
else
button:SetNormalFontObject("GameFontHighlightSmall")
button:SetHighlightFontObject("GameFontHighlightSmall")
button.text:SetPoint("LEFT", (icon and 16 or 0) + 8 * level, 2)
end
if disabled then
button:EnableMouse(false)
button.text:SetText("|cff808080"..text..FONT_COLOR_CODE_CLOSE)
else
button.text:SetText(text)
button:EnableMouse(true)
end
if icon then
button.icon:SetTexture(icon)
button.icon:SetPoint("LEFT", 8 * level, (level == 1) and 0 or 1)
else
button.icon:SetTexture(nil)
end
if iconCoords then
button.icon:SetTexCoord(unpack(iconCoords))
else
button.icon:SetTexCoord(0, 1, 0, 1)
end
if canExpand then
if not isExpanded then
toggle:SetNormalTexture("Interface\\Buttons\\UI-PlusButton-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-PlusButton-DOWN")
else
toggle:SetNormalTexture("Interface\\Buttons\\UI-MinusButton-UP")
toggle:SetPushedTexture("Interface\\Buttons\\UI-MinusButton-DOWN")
end
toggle:Show()
else
toggle:Hide()
end
end
local function ShouldDisplayLevel(tree)
local result = false
for k, v in ipairs(tree) do
if v.children == nil and v.visible ~= false then
result = true
elseif v.children then
result = result or ShouldDisplayLevel(v.children)
end
if result then return result end
end
return false
end
local function addLine(self, v, tree, level, parent)
local line = new()
line.value = v.value
line.text = v.text
line.icon = v.icon
line.iconCoords = v.iconCoords
line.disabled = v.disabled
line.tree = tree
line.level = level
line.parent = parent
line.visible = v.visible
line.uniquevalue = GetButtonUniqueValue(line)
if v.children then
line.hasChildren = true
else
line.hasChildren = nil
end
self.lines[#self.lines+1] = line
return line
end
--fire an update after one frame to catch the treeframes height
local function FirstFrameUpdate(frame)
local self = frame.obj
frame:SetScript("OnUpdate", nil)
self:RefreshTree()
end
local function BuildUniqueValue(...)
local n = select('#', ...)
if n == 1 then
return ...
else
return (...).."\001"..BuildUniqueValue(select(2,...))
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Expand_OnClick(frame)
local button = frame.button
local self = button.obj
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function Button_OnClick(frame)
local self = frame.obj
self:Fire("OnClick", frame.uniquevalue, frame.selected)
if not frame.selected then
self:SetSelected(frame.uniquevalue)
frame.selected = true
frame:LockHighlight()
self:RefreshTree()
end
AceGUI:ClearFocus()
end
local function Button_OnDoubleClick(button)
local self = button.obj
local status = self.status or self.localstatus
local status = (self.status or self.localstatus).groups
status[button.uniquevalue] = not status[button.uniquevalue]
self:RefreshTree()
end
local function Button_OnEnter(frame)
local self = frame.obj
self:Fire("OnButtonEnter", frame.uniquevalue, frame)
if self.enabletooltips then
GameTooltip:SetOwner(frame, "ANCHOR_NONE")
GameTooltip:SetPoint("LEFT",frame,"RIGHT")
GameTooltip:SetText(frame.text:GetText() or "", 1, .82, 0, true)
GameTooltip:Show()
end
end
local function Button_OnLeave(frame)
local self = frame.obj
self:Fire("OnButtonLeave", frame.uniquevalue, frame)
if self.enabletooltips then
GameTooltip:Hide()
end
end
local function OnScrollValueChanged(frame, value)
if frame.obj.noupdate then return end
local self = frame.obj
local status = self.status or self.localstatus
status.scrollvalue = floor(value + 0.5)
self:RefreshTree()
AceGUI:ClearFocus()
end
local function Tree_OnSizeChanged(frame)
frame.obj:RefreshTree()
end
local function Tree_OnMouseWheel(frame, delta)
local self = frame.obj
if self.showscroll then
local scrollbar = self.scrollbar
local min, max = scrollbar:GetMinMaxValues()
local value = scrollbar:GetValue()
local newvalue = math_min(max,math_max(min,value - delta))
if value ~= newvalue then
scrollbar:SetValue(newvalue)
end
end
end
local function Dragger_OnLeave(frame)
frame:SetBackdropColor(1, 1, 1, 0)
end
local function Dragger_OnEnter(frame)
frame:SetBackdropColor(1, 1, 1, 0.8)
end
local function Dragger_OnMouseDown(frame)
local treeframe = frame:GetParent()
treeframe:StartSizing("RIGHT")
end
local function Dragger_OnMouseUp(frame)
local treeframe = frame:GetParent()
local self = treeframe.obj
local frame = treeframe:GetParent()
treeframe:StopMovingOrSizing()
--treeframe:SetScript("OnUpdate", nil)
treeframe:SetUserPlaced(false)
--Without this :GetHeight will get stuck on the current height, causing the tree contents to not resize
treeframe:SetHeight(0)
treeframe:SetPoint("TOPLEFT", frame, "TOPLEFT",0,0)
treeframe:SetPoint("BOTTOMLEFT", frame, "BOTTOMLEFT",0,0)
local status = self.status or self.localstatus
status.treewidth = treeframe:GetWidth()
treeframe.obj:Fire("OnTreeResize",treeframe:GetWidth())
-- recalculate the content width
treeframe.obj:OnWidthSet(status.fullwidth)
-- update the layout of the content
treeframe.obj:DoLayout()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetTreeWidth(DEFAULT_TREE_WIDTH, DEFAULT_TREE_SIZABLE)
self:EnableButtonTooltips(true)
end,
["OnRelease"] = function(self)
self.status = nil
for k, v in pairs(self.localstatus) do
if k == "groups" then
for k2 in pairs(v) do
v[k2] = nil
end
else
self.localstatus[k] = nil
end
end
self.localstatus.scrollvalue = 0
self.localstatus.treewidth = DEFAULT_TREE_WIDTH
self.localstatus.treesizable = DEFAULT_TREE_SIZABLE
end,
["EnableButtonTooltips"] = function(self, enable)
self.enabletooltips = enable
end,
["CreateButton"] = function(self)
local num = AceGUI:GetNextWidgetNum("TreeGroupButton")
local button = CreateFrame("Button", ("AceGUI30TreeButton%d"):format(num), self.treeframe, "OptionsListButtonTemplate")
button.obj = self
local icon = button:CreateTexture(nil, "OVERLAY")
icon:SetWidth(14)
icon:SetHeight(14)
button.icon = icon
button:SetScript("OnClick",Button_OnClick)
button:SetScript("OnDoubleClick", Button_OnDoubleClick)
button:SetScript("OnEnter",Button_OnEnter)
button:SetScript("OnLeave",Button_OnLeave)
button.toggle.button = button
button.toggle:SetScript("OnClick",Expand_OnClick)
button.text:SetHeight(14) -- Prevents text wrapping
return button
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
if not status.groups then
status.groups = {}
end
if not status.scrollvalue then
status.scrollvalue = 0
end
if not status.treewidth then
status.treewidth = DEFAULT_TREE_WIDTH
end
if status.treesizable == nil then
status.treesizable = DEFAULT_TREE_SIZABLE
end
self:SetTreeWidth(status.treewidth,status.treesizable)
self:RefreshTree()
end,
--sets the tree to be displayed
["SetTree"] = function(self, tree, filter)
self.filter = filter
if tree then
assert(type(tree) == "table")
end
self.tree = tree
self:RefreshTree()
end,
["BuildLevel"] = function(self, tree, level, parent)
local groups = (self.status or self.localstatus).groups
local hasChildren = self.hasChildren
for i, v in ipairs(tree) do
if v.children then
if not self.filter or ShouldDisplayLevel(v.children) then
local line = addLine(self, v, tree, level, parent)
if groups[line.uniquevalue] then
self:BuildLevel(v.children, level+1, line)
end
end
elseif v.visible ~= false or not self.filter then
addLine(self, v, tree, level, parent)
end
end
end,
["RefreshTree"] = function(self,scrollToSelection)
local buttons = self.buttons
local lines = self.lines
for i, v in ipairs(buttons) do
v:Hide()
end
while lines[1] do
local t = tremove(lines)
for k in pairs(t) do
t[k] = nil
end
del(t)
end
if not self.tree then return end
--Build the list of visible entries from the tree and status tables
local status = self.status or self.localstatus
local groupstatus = status.groups
local tree = self.tree
local treeframe = self.treeframe
status.scrollToSelection = status.scrollToSelection or scrollToSelection -- needs to be cached in case the control hasn't been drawn yet (code bails out below)
self:BuildLevel(tree, 1)
local numlines = #lines
local maxlines = (floor(((self.treeframe:GetHeight()or 0) - 20 ) / 18))
if maxlines <= 0 then return end
local first, last
scrollToSelection = status.scrollToSelection
status.scrollToSelection = nil
if numlines <= maxlines then
--the whole tree fits in the frame
status.scrollvalue = 0
self:ShowScroll(false)
first, last = 1, numlines
else
self:ShowScroll(true)
--scrolling will be needed
self.noupdate = true
self.scrollbar:SetMinMaxValues(0, numlines - maxlines)
--check if we are scrolled down too far
if numlines - status.scrollvalue < maxlines then
status.scrollvalue = numlines - maxlines
end
self.noupdate = nil
first, last = status.scrollvalue+1, status.scrollvalue + maxlines
--show selection?
if scrollToSelection and status.selected then
local show
for i,line in ipairs(lines) do -- find the line number
if line.uniquevalue==status.selected then
show=i
end
end
if not show then
-- selection was deleted or something?
elseif show>=first and show<=last then
-- all good
else
-- scrolling needed!
if show<first then
status.scrollvalue = show-1
else
status.scrollvalue = show-maxlines
end
first, last = status.scrollvalue+1, status.scrollvalue + maxlines
end
end
if self.scrollbar:GetValue() ~= status.scrollvalue then
self.scrollbar:SetValue(status.scrollvalue)
end
end
local buttonnum = 1
for i = first, last do
local line = lines[i]
local button = buttons[buttonnum]
if not button then
button = self:CreateButton()
buttons[buttonnum] = button
button:SetParent(treeframe)
button:SetFrameLevel(treeframe:GetFrameLevel()+1)
button:ClearAllPoints()
if buttonnum == 1 then
if self.showscroll then
button:SetPoint("TOPRIGHT", -22, -10)
button:SetPoint("TOPLEFT", 0, -10)
else
button:SetPoint("TOPRIGHT", 0, -10)
button:SetPoint("TOPLEFT", 0, -10)
end
else
button:SetPoint("TOPRIGHT", buttons[buttonnum-1], "BOTTOMRIGHT",0,0)
button:SetPoint("TOPLEFT", buttons[buttonnum-1], "BOTTOMLEFT",0,0)
end
end
UpdateButton(button, line, status.selected == line.uniquevalue, line.hasChildren, groupstatus[line.uniquevalue] )
button:Show()
buttonnum = buttonnum + 1
end
end,
["SetSelected"] = function(self, value)
local status = self.status or self.localstatus
if status.selected ~= value then
status.selected = value
self:Fire("OnGroupSelected", value)
end
end,
["Select"] = function(self, uniquevalue, ...)
self.filter = false
local status = self.status or self.localstatus
local groups = status.groups
local path = {...}
for i = 1, #path do
groups[tconcat(path, "\001", 1, i)] = true
end
status.selected = uniquevalue
self:RefreshTree(true)
self:Fire("OnGroupSelected", uniquevalue)
end,
["SelectByPath"] = function(self, ...)
self:Select(BuildUniqueValue(...), ...)
end,
["SelectByValue"] = function(self, uniquevalue)
self:Select(uniquevalue, ("\001"):split(uniquevalue))
end,
["ShowScroll"] = function(self, show)
self.showscroll = show
if show then
self.scrollbar:Show()
if self.buttons[1] then
self.buttons[1]:SetPoint("TOPRIGHT", self.treeframe,"TOPRIGHT",-22,-10)
end
else
self.scrollbar:Hide()
if self.buttons[1] then
self.buttons[1]:SetPoint("TOPRIGHT", self.treeframe,"TOPRIGHT",0,-10)
end
end
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local treeframe = self.treeframe
local status = self.status or self.localstatus
status.fullwidth = width
local contentwidth = width - status.treewidth - 20
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
local maxtreewidth = math_min(400, width - 50)
if maxtreewidth > 100 and status.treewidth > maxtreewidth then
self:SetTreeWidth(maxtreewidth, status.treesizable)
end
treeframe:SetMaxResize(maxtreewidth, 1600)
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - 20
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["SetTreeWidth"] = function(self, treewidth, resizable)
if not resizable then
if type(treewidth) == 'number' then
resizable = false
elseif type(treewidth) == 'boolean' then
resizable = treewidth
treewidth = DEFAULT_TREE_WIDTH
else
resizable = false
treewidth = DEFAULT_TREE_WIDTH
end
end
self.treeframe:SetWidth(treewidth)
self.dragger:EnableMouse(resizable)
local status = self.status or self.localstatus
status.treewidth = treewidth
status.treesizable = resizable
-- recalculate the content width
if status.fullwidth then
self:OnWidthSet(status.fullwidth)
end
end,
["GetTreeWidth"] = function(self)
local status = self.status or self.localstatus
return status.treewidth or DEFAULT_TREE_WIDTH
end,
["LayoutFinished"] = function(self, width, height)
if self.noAutoHeight then return end
self:SetHeight((height or 0) + 20)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local DraggerBackdrop = {
bgFile = "Interface\\Tooltips\\UI-Tooltip-Background",
edgeFile = nil,
tile = true, tileSize = 16, edgeSize = 0,
insets = { left = 3, right = 3, top = 7, bottom = 7 }
}
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame", nil, UIParent)
local treeframe = CreateFrame("Frame", nil, frame)
treeframe:SetPoint("TOPLEFT")
treeframe:SetPoint("BOTTOMLEFT")
treeframe:SetWidth(DEFAULT_TREE_WIDTH)
treeframe:EnableMouseWheel(true)
treeframe:SetBackdrop(PaneBackdrop)
treeframe:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
treeframe:SetBackdropBorderColor(0.4, 0.4, 0.4)
treeframe:SetResizable(true)
treeframe:SetMinResize(100, 1)
treeframe:SetMaxResize(400, 1600)
treeframe:SetScript("OnUpdate", FirstFrameUpdate)
treeframe:SetScript("OnSizeChanged", Tree_OnSizeChanged)
treeframe:SetScript("OnMouseWheel", Tree_OnMouseWheel)
local dragger = CreateFrame("Frame", nil, treeframe)
dragger:SetWidth(8)
dragger:SetPoint("TOP", treeframe, "TOPRIGHT")
dragger:SetPoint("BOTTOM", treeframe, "BOTTOMRIGHT")
dragger:SetBackdrop(DraggerBackdrop)
dragger:SetBackdropColor(1, 1, 1, 0)
dragger:SetScript("OnEnter", Dragger_OnEnter)
dragger:SetScript("OnLeave", Dragger_OnLeave)
dragger:SetScript("OnMouseDown", Dragger_OnMouseDown)
dragger:SetScript("OnMouseUp", Dragger_OnMouseUp)
local scrollbar = CreateFrame("Slider", ("AceConfigDialogTreeGroup%dScrollBar"):format(num), treeframe, "UIPanelScrollBarTemplate")
scrollbar:SetScript("OnValueChanged", nil)
scrollbar:SetPoint("TOPRIGHT", -10, -26)
scrollbar:SetPoint("BOTTOMRIGHT", -10, 26)
scrollbar:SetMinMaxValues(0,0)
scrollbar:SetValueStep(1)
scrollbar:SetValue(0)
scrollbar:SetWidth(16)
scrollbar:SetScript("OnValueChanged", OnScrollValueChanged)
local scrollbg = scrollbar:CreateTexture(nil, "BACKGROUND")
scrollbg:SetAllPoints(scrollbar)
scrollbg:SetTexture(0,0,0,0.4)
local border = CreateFrame("Frame",nil,frame)
border:SetPoint("TOPLEFT", treeframe, "TOPRIGHT")
border:SetPoint("BOTTOMRIGHT")
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1, 0.1, 0.1, 0.5)
border:SetBackdropBorderColor(0.4, 0.4, 0.4)
--Container Support
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -10)
content:SetPoint("BOTTOMRIGHT", -10, 10)
local widget = {
frame = frame,
lines = {},
levels = {},
buttons = {},
hasChildren = {},
localstatus = { groups = {}, scrollvalue = 0 },
filter = false,
treeframe = treeframe,
dragger = dragger,
scrollbar = scrollbar,
border = border,
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
treeframe.obj, dragger.obj, scrollbar.obj = widget, widget, widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-2.0 |
WaywardEclipse/Isolation | gamemode/server/admin/commands.lua | 2 | 10384 | local name = "[Admin] - ";
commands = {};
table.insert(commands, {2, 0, "noclip",
function (ply, args, msg)
if ply:GetMoveType() == MOVETYPE_WALK then
ply:SetMoveType(MOVETYPE_NOCLIP);
else
ply:SetMoveType(MOVETYPE_WALK);
end
end});
table.insert(commands, {1, 1, "givemoney",
function (ply, args, msg)
ply:SetNWInt("Cash", ply:GetNWInt("Cash") + tonumber(args[1]));
ply:SaveData()
end});
table.insert(commands, {2, 2, "kick",
function (ply, args, msg)
playerToKick = getPlayerByName(args[1]);
if IsValid(playerToKick) then
if playerToKick ~= ply then
reason = string.sub(msg, 7 + string.len(args[1]));
if getRankByNum(playerToKick) > 2 then
playerToKick:Kick("Kicked - (Reason) " .. reason);
PrintMessage(HUD_PRINTTALK, name..playerToKick:Name().." Was Kicked by "..ply:Name());
elseif getRankByNum(playerToKick) > 1 then
playerToKick:Kick("Kicked - (Reason) "..reason);
PrintMessage(HUD_PRINTTALK, name..playerToKick:Name().." Was Kicked By "..ply:Name());
else
ply:PrintMessage(HUD_PRINTTALK, name.."Cannot Kick People With Your Rank Or Higher");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end});
table.insert(commands, {3, 1, "resetstats",
function (ply, args, msg)
if args[1] == "me" then
ply:SetDefaults()
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Deleted Their Player Data");
else
if getRankByNum(ply) == 1 then
playerToDeleteData = getPlayerByName(args[1]);
if IsValid(playerToDeleteData) then
if playerToDeleteData ~= ply then
ply:SetDefaults()
PrintMessage(HUD_PRINTTALK, name..playerToDeleteData:Name().."'s Data Has Been Deleted By "..ply:Name());
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end
end});
table.insert(commands, {1, 2, "setrank",
function (ply, args, msg)
playerToSetRank = getPlayerByName(args[1]);
if IsValid(playerToSetRank) then
if playerToSetRank ~= ply then
playerToSetRank:SetUserGroup(args[2]);
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Set "..playerToSetRank:Name().."'s Rank To "..args[2]);
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end})
table.insert(commands, {3, 1, "kill",
function (ply, args, msg)
if args[1] == "me" then
ply:Kill()
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Killed Themself");
else
if getRankByNum(ply) <= 2 then
playerToKill = getPlayerByName(args[1]);
if IsValid(playerToKill) then
if playerToKill ~= ply then
if getRankByNum(playerToKill) > 2 then
playerToKill:Kill();
PrintMessage(HUD_PRINTTALK, name..playerToKill:Name().." Was Slayed By "..ply:Name());
elseif getRankByNum(playerToKill) > 1 then
playerToKill:Kill();
PrintMessage(HUD_PRINTTALK, name..playerToKill:Name().." Was Slayed By "..ply:Name());
else
ply:PrintMessage(HUD_PRINTTALK, name.."Cannot Kill People With Your Rank Or Higher");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end
end});
table.insert(commands, {2, 1, "freeze",
function (ply, args, msg)
if args[1] == "me" then
if playerToFreeze:IsFrozen() then
playerToFreeze:Freeze(false);
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Unfroze Themself");
else
playerToFreeze:Freeze(true);
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Froze Themself");
end
else
playerToFreeze = getPlayerByName(args[1]);
if playerToFreeze ~= NULL then
if playerToFreeze ~= ply then
if getRankByNum(playerToFreeze) > 2 then
if playerToFreeze:IsFrozen() then
playerToFreeze:Freeze(false);
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Was Unfrozen By "..ply:Name());
else
playerToFreeze:Freeze(true);
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Was Frozen By "..ply:Name());
end
elseif getRankByNum(playerToFreeze) > 1 then
if playerToFreeze:IsFrozen() then
playerToFreeze:Freeze(false);
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Was Unfrozen By "..ply:Name());
else
playerToFreeze:Freeze(true);
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Was Frozen By "..ply:Name());
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Cannot Freeze People With Your Rank Or Higher");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end});
table.insert(commands, {3, 1, "god",
function (ply, args, msg)
if args[1] == "me" then
ply:GodEnable();
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Has Godded Themself");
else
playerToFreeze = getPlayerByName(args[1]);
if playerToFreeze ~= NULL then
if playerToFreeze ~= ply then
if getRankByNum(playerToFreeze) > 2 then
playerToFreeze:GodEnable();
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Has Been Godded By "..ply:Name());
elseif getRankByNum(playerToFreeze) > 1 then
playerToFreeze:GodEnable();
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Has Been Godded By "..ply:Name());
else
ply:PrintMessage(HUD_PRINTTALK, name.."Cannot God People With Your Rank Or Higher");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end});
table.insert(commands, {2, 1, "ungod",
function (ply, args, msg)
if args[1] == "me" then
ply:GodDisable();
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Has Ungodded Themself");
else
playerToFreeze = getPlayerByName(args[1]);
if playerToFreeze ~= NULL then
if playerToFreeze ~= ply then
if getRankByNum(playerToFreeze) > 2 then
playerToFreeze:GodDisable();
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Has Been Ungodded By "..ply:Name());
elseif getRankByNum(playerToFreeze) > 1 then
playerToFreeze:GodDisable();
PrintMessage(HUD_PRINTTALK, name..playerToFreeze:Name().." Has Been Ungodded By "..ply:Name());
else
ply:PrintMessage(HUD_PRINTTALK, name.."Cannot UnGod People With Your Rank Or Higher");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end});
table.insert(commands, {2, 1, "goto",
function (ply, args, msg)
playerToGoTo = getPlayerByName(args[1]);
if IsValid(playerToGoTo) then
if playerToGoTo ~= ply then
ply:SetMoveType(MOVETYPE_NOCLIP);
ply:SetPos(playerToGoTo:GetPos());
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Has Teleported To "..playerToGoTo:Name());
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end});
table.insert(commands, {2, 2, "teleport",
function (ply, args, msg)
if args[1] == "me" then
ply:GodDisable();
PrintMessage(HUD_PRINTTALK, name..ply:Name().." Has Ungodded Themself");
else
playerToTeleport = getPlayerByName(args[1]);
playerToTeleportTo = getPlayerByName(args[2]);
if IsValid(playerToTeleport) and IsValid(playerToTeleportTo) then
if playerToTeleport ~= ply then
if getRankByNum(playerToTeleport) > 2 then
playerToTeleport:SetPos(playerToTeleportTo:GetPos());
PrintMessage(HUD_PRINTTALK, name..playerToTeleport:Name().." Has Been Teleport To "..playerToTeleportTo:Name());
elseif getRankByNum(playerToTeleport) > 1 then
playerToTeleport:SetPos(playerToTeleportTo:GetPos());
PrintMessage(HUD_PRINTTALK, name..playerToTeleport:Name().." Has Been Teleport To "..playerToTeleportTo:Name().." By Owner");
else
ply:PrintMessage(HUD_PRINTTALK, name.."Cannot Teleport People With Your Rank Or Higher");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end});
table.insert(commands, {1, 2, "give",
function (ply, args, msg)
if args[1] == "me" then
ply:Give(args[2])
PrintMessage(HUD_PRINTTALK, name..ply:Name().." gave themself a " .. args[2]);
else
if getRankByNum(ply) <= 2 then
playerToGive = getPlayerByName(args[1]);
if IsValid(playerToGive) then
if playerToGive ~= ply then
if getRankByNum(playerToGive) > 2 then
playerToGive:Give(args[2]);
PrintMessage(HUD_PRINTTALK, name..playerToGive:Name().." was given a " .. args[2] .. " by "..ply:Name());
elseif getRankByNum(playerToGive) > 1 then
playerToGive:Give(args[2]);
PrintMessage(HUD_PRINTTALK, name..playerToGive:Name().." was given a " .. args[2] .. " by "..ply:Name());
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't give weapon to player of your rank or higher.");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end
end});
table.insert(commands, {1, 2, "giveammo",
function (ply, args, msg)
if args[1] == "me" then
ply:GiveAmmo(args[2], ply:GetActiveWeapon():GetPrimaryAmmoType())
PrintMessage(HUD_PRINTTALK, name..ply:Name().." gave themself " .. args[2] .. " ammo.");
else
if getRankByNum(ply) <= 2 then
playerToGive = getPlayerByName(args[1]);
if IsValid(playerToGive) then
if playerToGive ~= ply then
if getRankByNum(playerToGive) > 2 then
playerToGive:GiveAmmo(args[2], playerToGive:GetActiveWeapon():GetPrimaryAmmoType());
PrintMessage(HUD_PRINTTALK, name..playerToGive:Name().." was given " .. args[2] .. " ammo by "..ply:Name());
elseif getRankByNum(playerToGive) > 1 then
playerToGive:GiveAmmo(args[2], playerToGive:GetActiveWeapon():GetPrimaryAmmoType());
PrintMessage(HUD_PRINTTALK, name..playerToGive:Name().." was given " .. args[2] .. " ammo by "..ply:Name());
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't give ammo to player of your rank or higher.");
end
end
else
ply:PrintMessage(HUD_PRINTTALK, name.."Couldn't Find That Player");
end
end
end
end});
table.insert(commands, {3, 1, "me",
function (ply, args, msg)
for _,v in pairs(player.GetAll()) do
PrintToChat("*" .. ply:Nick() .. " " .. args[1], Color(63, 232, 181))
end
end});
function getCommands()
return commands;
end | mit |
AresTao/darkstar | scripts/globals/weaponskills/blast_shot.lua | 30 | 1320 | -----------------------------------
-- Blast Shot
-- Marksmanship weapon skill
-- Skill Level: 200
-- Delivers a melee-distance ranged attack. params.accuracy varies with TP.
-- Aligned with the Snow Gorget & Light Gorget.
-- Aligned with the Snow Belt & Light Belt.
-- Element: None
-- Modifiers: AGI:30%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 2; params.ftp200 = 2; params.ftp300 = 2;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.agi_wsc = 0.7;
end
local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
NeoRaider/luci | applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/iwinfo.lua | 37 | 1612 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.iwinfo", package.seeall)
function rrdargs( graph, plugin, plugin_instance )
--
-- signal/noise diagram
--
local snr = {
title = "%H: Signal and noise on %pi",
vlabel = "dBm",
number_format = "%5.1lf dBm",
data = {
types = { "signal_noise", "signal_power" },
options = {
signal_power = {
title = "Signal",
overlay = true,
color = "0000ff"
},
signal_noise = {
title = "Noise",
overlay = true,
color = "ff0000"
}
}
}
}
--
-- signal quality diagram
--
local quality = {
title = "%H: Signal quality on %pi",
vlabel = "Quality",
number_format = "%3.0lf",
data = {
types = { "signal_quality" },
options = {
signal_quality = {
title = "Quality",
noarea = true,
color = "0000ff"
}
}
}
}
--
-- phy rate diagram
--
local bitrate = {
title = "%H: Average phy rate on %pi",
vlabel = "MBit/s",
number_format = "%5.1lf%sBit/s",
data = {
types = { "bitrate" },
options = {
bitrate = {
title = "Rate",
color = "00ff00"
}
}
}
}
--
-- associated stations
--
local stations = {
title = "%H: Associated stations on %pi",
vlabel = "Stations",
y_min = "0",
alt_autoscale_max = true,
number_format = "%3.0lf",
data = {
types = { "stations" },
options = {
stations = {
title = "Stations",
color = "0000ff"
}
}
}
}
return { snr, quality, bitrate, stations }
end
| apache-2.0 |
AresTao/darkstar | scripts/zones/Den_of_Rancor/npcs/Treasure_Coffer.lua | 17 | 3342 | -----------------------------------
-- Area: Den of Rancor
-- NPC: Treasure Coffer
-- @zone 160
-- @pos
-----------------------------------
package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Den_of_Rancor/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1050,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1050,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local zone = player:getZoneID();
if (player:hasKeyItem(MAP_OF_THE_DEN_OF_RANCOR) == false) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addKeyItem(MAP_OF_THE_DEN_OF_RANCOR);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_DEN_OF_RANCOR); -- Map of the Den of Rancor (KI)
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = cofferLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1050);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Port_Windurst/npcs/Machu-Kuchu.lua | 34 | 1123 | -----------------------------------
-- Area: Port Windurst
-- Machu-Kuchu
-- Warps players to Windurst Walls
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x152);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (option == 1) then
player:setPos(65.534,-7.5,-49.935,59,239); -- Retail packet capped
end
end;
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Mhaura/npcs/Orlando.lua | 15 | 3535 | -----------------------------------
-- Area: Mhaura
-- NPC: Orlando
-- Type: Standard NPC
-- @pos -37.268 -9 58.047 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES);
local itemID = trade:getItem();
local itemList =
{
{564, 200}, -- Fingernail Sack
{565, 250}, -- Teeth Sack
{566, 200}, -- Goblin Cup
{568, 120}, -- Goblin Die
{656, 600}, -- Beastcoin
{748, 900}, -- Gold Beastcoin
{749, 800}, -- Mythril Beastcoin
{750, 750}, -- Silver Beastcoin
{898, 120}, -- Chicken Bone
{900, 100}, -- Fish Bone
{16995, 150}, -- Rotten Meat
};
for x, item in pairs(itemList) do
if (QuestStatus == QUEST_ACCEPTED) or (player:getLocalVar("OrlandoRepeat") == 1) then
if (item[1] == itemID) then
if (trade:hasItemQty(itemID, 8) and trade:getItemCount() == 8) then
-- Correct amount, valid item.
player:setVar("ANTIQUE_PAYOUT", (GIL_RATE*item[2]));
player:startEvent(0x0066, GIL_RATE*item[2], itemID);
elseif (trade:getItemCount() < 8) then
-- Wrong amount, but valid item.
player:startEvent(0x0068);
end
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES);
if (player:getFameLevel(WINDURST) >= 2) then
if (player:hasKeyItem(CHOCOBO_LICENSE)) then
if (QuestStatus ~= QUEST_AVAILABLE) then
player:startEvent(0x0067);
elseif (QuestStatus == QUEST_AVAILABLE) then
player:startEvent(0x0065);
end
else
player:startEvent(0x0064);
end
else
player:startEvent(0x006A);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES);
local payout = player:getVar("ANTIQUE_PAYOUT");
if (csid == 0x0065) then
player:addQuest(OTHER_AREAS, ORLANDO_S_ANTIQUES);
elseif (csid == 0x0066) then
player:tradeComplete();
player:addFame(WINDURST,WIN_FAME*10);
player:addGil(payout);
player:messageSpecial(GIL_OBTAINED,payout);
player:completeQuest(OTHER_AREAS, ORLANDO_S_ANTIQUES);
player:setVar("ANTIQUE_PAYOUT", 0);
player:setLocalVar("OrlandoRepeat", 0);
elseif (csid == 0x0067) then
if (QuestStatus == QUEST_COMPLETED) then
player:setLocalVar("OrlandoRepeat", 1);
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Yasmina.lua | 36 | 1058 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Yasmina
-- Type: Chocobo Renter
-- @zone: 94
-- @pos -34.972 -5.815 221.845
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0006, 10, 10);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
NREL/api-umbrella | src/api-umbrella/cli/health.lua | 1 | 3105 | local http = require "resty.http"
local json_decode = require("cjson").decode
local read_config = require "api-umbrella.cli.read_config"
local unistd = require "posix.unistd"
local function health(options, config)
local status = "red"
local exit_code = 1
local url = "http://127.0.0.1:" .. config["http_port"] .. "/api-umbrella/v1/health"
if options["wait_for_status"] then
url = url .. "?wait_for_status=" .. options["wait_for_status"] .. "&wait_timeout=" .. options["wait_timeout"]
end
local httpc = http.new()
local res, http_err = httpc:request_uri(url)
if not res then
return status, exit_code, http_err
elseif res.headers["Content-Type"] ~= "application/json" then
local err = "nginx error"
return status, exit_code, err
else
local data = json_decode(res.body)
if data["status"] then
status = data["status"]
if res.status == 200 and status ~= "red" then
exit_code = 0
end
else
local err = "nginx error"
return status, exit_code, err
end
end
return status, exit_code
end
return function(options)
local config = read_config()
-- Perform a health check using the API health endpoint.
--
-- By default, perform the health check and return the status immediately.
--
-- If the --wait-for-status option is given, then the CLI app will wait until
-- that status (or better) is met (or until timeout).
local status, exit_code, health_err, _
if not options["wait_for_status"] then
status, exit_code, _ = health(options, config)
else
-- Validate the wait_for_status param.
local wait_for_status = options["wait_for_status"]
if wait_for_status ~= "green" and wait_for_status ~= "yellow" and wait_for_status ~= "red" then
print("Error: invalid --wait-for-status argument (" .. (tostring(wait_for_status) or "") .. ")")
os.exit(1)
end
-- Validate the wait_timeout param (defaults to 50 seconds).
local wait_timeout = tonumber(options["wait_timeout"] or 50)
if not wait_timeout then
print("Error: invalid --wait-timeout argument (" .. (tostring(wait_timeout) or "") .. ")")
os.exit(1)
end
-- Most of the wait-for-status functionality is implemented within the API
-- endpoint (will will wait until the expected status is achieved).
-- However, we will also loop in the CLI app until this status is achieved
-- to handle connection errors if nginx hasn't yet bound to the expected
-- port.
local timeout_at = os.time() + wait_timeout
while true do
status, exit_code, health_err = health(options, config)
-- If a low-level connection error wasn't returned, then we assume the
-- API endpoint was hit and it already waited the proper amount of time,
-- so we should immediately return whatever status the API returned.
if not health_err then
break
end
-- Bail if we've exceeded the timeout waiting.
if os.time() > timeout_at then
break
end
unistd.sleep(1)
end
end
print(status or "red")
os.exit(exit_code or 1)
end
| mit |
DeinFreund/Zero-K | LuaRules/Configs/StartBoxes/Gods Of War 2 Remake V2.lua | 17 | 1126 | return {
[0] = {
nameLong = "South-West",
nameShort = "W",
startpoints = {
{824,6344},
},
boxes = {
{
{0,5519},
{1649,5519},
{1649,7168},
{0,7168},
},
},
},
[1] = {
nameLong = "North-East",
nameShort = "NE",
startpoints = {
{6344,824},
},
boxes = {
{
{5519,0},
{7168,0},
{7168,1649},
{5519,1649},
},
},
},
[2] = {
nameLong = "West",
nameShort = "W",
startpoints = {
{824,2975},
},
boxes = {
{
{0,2150},
{1649,2150},
{1649,3799},
{0,3799},
},
},
},
[3] = {
nameLong = "East",
nameShort = "E",
startpoints = {
{6344,4050},
},
boxes = {
{
{5519,3226},
{7168,3226},
{7168,4874},
{5519,4874},
},
},
},
[4] = {
nameLong = "North",
nameShort = "N",
startpoints = {
{2975,824},
},
boxes = {
{
{2150,0},
{3799,0},
{3799,1649},
{2150,1649},
},
},
},
[5] = {
nameLong = "South",
nameShort = "S",
startpoints = {
{4050,6344},
},
boxes = {
{
{3226,5519},
{4874,5519},
{4874,7168},
{3226,7168},
},
},
},
}
| gpl-2.0 |
prosody-modules/import | mod_tcpproxy/mod_tcpproxy.lua | 31 | 3923 | local st = require "util.stanza";
local xmlns_ibb = "http://jabber.org/protocol/ibb";
local xmlns_tcp = "http://prosody.im/protocol/tcpproxy";
local host_attr, port_attr = xmlns_tcp.."\1host", xmlns_tcp.."\1port";
local base64 = require "util.encodings".base64;
local b64, unb64 = base64.encode, base64.decode;
local host = module.host;
local open_connections = {};
local function new_session(jid, sid, conn)
if not open_connections[jid] then
open_connections[jid] = {};
end
open_connections[jid][sid] = conn;
end
local function close_session(jid, sid)
if open_connections[jid] then
open_connections[jid][sid] = nil;
if next(open_connections[jid]) == nil then
open_connections[jid] = nil;
end
return true;
end
end
function proxy_component(origin, stanza)
local ibb_tag = stanza.tags[1];
if (not (stanza.name == "iq" and stanza.attr.type == "set")
and stanza.name ~= "message")
or
(not (ibb_tag)
or ibb_tag.attr.xmlns ~= xmlns_ibb) then
if stanza.attr.type ~= "error" then
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
end
return;
end
if ibb_tag.name == "open" then
-- Starting a new stream
local to_host, to_port = ibb_tag.attr[host_attr], ibb_tag.attr[port_attr];
local jid, sid = stanza.attr.from, ibb_tag.attr.sid;
if not (to_host and to_port) then
return origin.send(st.error_reply(stanza, "modify", "bad-request", "No host/port specified"));
elseif not sid or sid == "" then
return origin.send(st.error_reply(stanza, "modify", "bad-request", "No sid specified"));
elseif ibb_tag.attr.stanza ~= "message" then
return origin.send(st.error_reply(stanza, "modify", "bad-request", "Only 'message' stanza transport is supported"));
end
local conn, err = socket.tcp();
if not conn then
return origin.send(st.error_reply(stanza, "wait", "resource-constraint", err));
end
conn:settimeout(0);
local success, err = conn:connect(to_host, to_port);
if not success and err ~= "timeout" then
return origin.send(st.error_reply(stanza, "wait", "remote-server-not-found", err));
end
local listener,seq = {}, 0;
function listener.onconnect(conn)
origin.send(st.reply(stanza));
end
function listener.onincoming(conn, data)
origin.send(st.message({to=jid,from=host})
:tag("data", {xmlns=xmlns_ibb,seq=seq,sid=sid})
:text(b64(data)));
seq = seq + 1;
end
function listener.ondisconnect(conn, err)
origin.send(st.message({to=jid,from=host})
:tag("close", {xmlns=xmlns_ibb,sid=sid}));
close_session(jid, sid);
end
conn = server.wrapclient(conn, to_host, to_port, listener, "*a" );
new_session(jid, sid, conn);
elseif ibb_tag.name == "data" then
local conn = open_connections[stanza.attr.from][ibb_tag.attr.sid];
if conn then
local data = unb64(ibb_tag:get_text());
if data then
conn:write(data);
else
return origin.send(
st.error_reply(stanza, "modify", "bad-request", "Invalid data (base64?)")
);
end
else
return origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
end
elseif ibb_tag.name == "close" then
if close_session(stanza.attr.from, ibb_tag.attr.sid) then
origin.send(st.reply(stanza));
else
return origin.send(st.error_reply(stanza, "cancel", "item-not-found"));
end
end
end
local function stanza_handler(event)
proxy_component(event.origin, event.stanza);
return true;
end
module:hook("iq/bare", stanza_handler, -1);
module:hook("message/bare", stanza_handler, -1);
module:hook("presence/bare", stanza_handler, -1);
module:hook("iq/full", stanza_handler, -1);
module:hook("message/full", stanza_handler, -1);
module:hook("presence/full", stanza_handler, -1);
module:hook("iq/host", stanza_handler, -1);
module:hook("message/host", stanza_handler, -1);
module:hook("presence/host", stanza_handler, -1);
require "core.componentmanager".register_component(host, function() end); -- COMPAT Prosody 0.7
| mit |
mamaddeveloper/Testmamo | plugins/helprealm.lua | 1 | 1248 | do
function run(msg, matches)
return 'These commands only works in bots private \n Hammer \n /owners group_id [kick|ban|unban] user_id \n /owners 1234567 kick 1234567 \n \n cleaning \n /owners group_id clean [modlist|rules|about] \n /owners 1234567 clean modlist \n \n setting flood sensitivity \n /owners group_id setflood value \n /owners 1234567 setflood 17 \n \n lock groups member|name \n /owners group_id lock [member|name] \n /owners 1234567 lock member \n \n unlock groups member|name \n /owner group_id unlock [member|name] \n /owners 1234567 unlock name \n \n Group link \n /owners group_id get link \n /owners 1234567 get link \n /owners group_id new link \n /owners 1234567 new link \n \n change name|rules|name \n /changename [group_id] [name] \n /changename 123456789 SaTaN \n /changrules [group_id] [rules] \n /changrules 123456789 rules ! \n /changeabout [group_id] [about] \n /changeabout 123456789 about! \n \n Group log \n /loggroup [group_id] \n /loggroup 123456789 \n \n Join \n /join [group_id] \n THis command will add user in [group_id] \n \n You Can Use: "!" , "/" , "$" , "&". \n Creator: @WilSoN_DeVeLoPeR'
end
return {
patterns = {
"^[/!%&$#@]([Rr]ealm)$",
"^([Rr]ealm)$"
},
run = run
}
end
| gpl-2.0 |
AresTao/darkstar | scripts/zones/Windurst_Woods/npcs/Abby_Jalunshi.lua | 38 | 1042 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Abby Jalunshi
-- Type: Moghouse Renter
-- @zone: 241
-- @pos -101.895 -5 36.172
--
-- Auto-Script: Requires Verification (Verfied By Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x031e);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
tysonliddell/OpenRA | mods/d2k/maps/shellmap/d2k-shellmap.lua | 3 | 6564 | --[[
Copyright 2007-2020 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AttackGroupSize = {8}
AttackDelay = { DateTime.Seconds(2), DateTime.Seconds(4) }
IdlingUnits =
{
Atreides = { },
Harkonnen = { },
Ordos = { },
Corrino = { }
}
HoldProduction =
{
Atreides = false,
Harkonnen = false,
Ordos = false,
Corrino = false
}
IsAttacking =
{
Atreides = false,
Harkonnen = false,
Ordos = false,
Corrino = false
}
AtreidesInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper", "grenadier", "grenadier" }
AtreidesVehicleTypes = { "trike", "trike", "quad" }
AtreidesTankTypes = { "combat_tank_a", "combat_tank_a", "combat_tank_a", "siege_tank" }
AtreidesStarportTypes = { "trike.starport", "quad.starport", "siege_tank.starport", "missile_tank.starport", "combat_tank_a.starport" }
HarkonnenInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper", "mpsardaukar" }
HarkonnenVehicleTypes = { "trike", "quad", "quad" }
HarkonnenTankTypes = { "combat_tank_h", "combat_tank_h", "combat_tank_h", "siege_tank" }
HarkonnenStarportTypes = { "trike.starport", "quad.starport", "siege_tank.starport", "missile_tank.starport", "combat_tank_h.starport" }
OrdosInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" }
OrdosVehicleTypes = { "raider", "raider", "quad", "stealth_raider" }
OrdosTankTypes = { "combat_tank_o", "combat_tank_o", "combat_tank_o", "siege_tank" }
OrdosStarportTypes = { "trike.starport", "quad.starport", "siege_tank.starport", "missile_tank.starport", "combat_tank_o.starport" }
CorrinoInfantryTypes = { "light_inf", "trooper", "sardaukar", "sardaukar", "sardaukar", "sardaukar" }
CorrinoVehicleTypes = { "trike", "quad", "quad" }
CorrinoTankTypes = { "combat_tank_h", "combat_tank_h", "combat_tank_h", "siege_tank" }
CorrinoStarportTypes = { "trike.starport", "quad.starport", "siege_tank.starport", "missile_tank.starport", "combat_tank_h.starport" }
Upgrades = { "upgrade.barracks", "upgrade.light", "upgrade.conyard", "upgrade.heavy", "upgrade.hightech" }
Harvester = { "harvester" }
AtrCarryHarvWaypoints = { atr_harvcarry_2.Location, atr_harvcarry_1.Location }
HarCarryHarvWaypoints = { har_harvcarry_2.Location, har_harvcarry_1.Location }
OrdCarryHarvWaypoints = { ord_harvcarry_2.Location, ord_harvcarry_1.Location }
CorCarryHarvWaypoints = { cor_harvcarry_2.Location, cor_harvcarry_1.Location }
SmgCarryHarvWaypoints = { smg_harvcarry_2.Location, smg_harvcarry_1.Location }
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end
Produce = function(house, units)
if HoldProduction[house.Name] then
Trigger.AfterDelay(DateTime.Minutes(1), function() Produce(house, units) end)
return
end
local delay = Utils.RandomInteger(AttackDelay[1], AttackDelay[2])
local toBuild = { Utils.Random(units) }
house.Build(toBuild, function(unit)
local unitCount = 1
if IdlingUnits[house.Name] then
unitCount = 1 + #IdlingUnits[house.Name]
end
IdlingUnits[house.Name][unitCount] = unit[1]
Trigger.AfterDelay(delay, function() Produce(house, units) end)
if unitCount >= (AttackGroupSize[1] * 2) then
SendAttack(house)
end
end)
end
SetupAttackGroup = function(house)
local units = { }
for i = 0, AttackGroupSize[1], 1 do
if #IdlingUnits[house.Name] == 0 then
return units
end
local number = Utils.RandomInteger(1, #IdlingUnits[house.Name])
if IdlingUnits[house.Name][number] and not IdlingUnits[house.Name][number].IsDead then
units[i] = IdlingUnits[house.Name][number]
table.remove(IdlingUnits[house.Name], number)
end
end
return units
end
SendAttack = function(house)
if IsAttacking[house.Name] then
return
end
IsAttacking[house.Name] = true
HoldProduction[house.Name] = true
local units = SetupAttackGroup(house)
Utils.Do(units, function(unit)
IdleHunt(unit)
end)
Trigger.OnAllRemovedFromWorld(units, function()
IsAttacking[house.Name] = false
HoldProduction[house.Name] = false
end)
end
SendNewHarv = function(house, waypoint, count)
local harvs = house.GetActorsByType("harvester")
if #harvs < count then
local harvesters = Reinforcements.ReinforceWithTransport(house, "carryall.reinforce", Harvester, waypoint, { waypoint[1] })[2]
Utils.Do(harvesters, function(harvester)
Trigger.OnAddedToWorld(harvester, function()
InitializeHarvester(harvester)
SendNewHarv(house, waypoint, count)
end)
end)
end
end
InitializeHarvester = function(harvester)
harvester.FindResources()
end
ticks = 0
speed = 5
Tick = function()
ticks = ticks + 1
local t = (ticks + 45) % (360 * speed) * (math.pi / 180) / speed;
Camera.Position = viewportOrigin + WVec.New(19200 * math.sin(t), 28800 * math.cos(t), 0)
end
WorldLoaded = function()
atreides = Player.GetPlayer("Atreides")
harkonnen = Player.GetPlayer("Harkonnen")
ordos = Player.GetPlayer("Ordos")
corrino = Player.GetPlayer("Corrino")
smugglers = Player.GetPlayer("Smugglers")
viewportOrigin = Camera.Position
Utils.Do(Utils.Take(4, Upgrades), function(upgrade)
atr_cyard.Produce(upgrade)
har_cyard.Produce(upgrade)
ord_cyard.Produce(upgrade)
cor_cyard.Produce(upgrade)
end)
atr_cyard.Produce(Upgrades[5])
Trigger.AfterDelay(DateTime.Seconds(45), function()
SendNewHarv(atreides, AtrCarryHarvWaypoints, 3)
SendNewHarv(harkonnen, HarCarryHarvWaypoints, 3)
SendNewHarv(ordos, OrdCarryHarvWaypoints, 3)
SendNewHarv(corrino, CorCarryHarvWaypoints, 3)
SendNewHarv(smugglers, SmgCarryHarvWaypoints, 1)
end)
Trigger.AfterDelay(DateTime.Seconds(1), function()
Produce(atreides, AtreidesInfantryTypes)
Produce(atreides, AtreidesVehicleTypes)
Produce(atreides, AtreidesTankTypes)
Produce(atreides, AtreidesStarportTypes)
Produce(harkonnen, HarkonnenInfantryTypes)
Produce(harkonnen, HarkonnenVehicleTypes)
Produce(harkonnen, HarkonnenTankTypes)
Produce(harkonnen, HarkonnenStarportTypes)
Produce(ordos, OrdosInfantryTypes)
Produce(ordos, OrdosVehicleTypes)
Produce(ordos, OrdosTankTypes)
Produce(ordos, OrdosStarportTypes)
Produce(corrino, CorrinoInfantryTypes)
Produce(corrino, CorrinoVehicleTypes)
Produce(corrino, CorrinoTankTypes)
Produce(corrino, CorrinoStarportTypes)
end)
end
| gpl-3.0 |
AresTao/darkstar | scripts/zones/Den_of_Rancor/npcs/HomePoint#2.lua | 19 | 1194 | -----------------------------------
-- Area: Den_of_Rancor
-- NPC: HomePoint#2
-- @pos 182 34 -62 160
-----------------------------------
package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Den_of_Rancor/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 93);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
AresTao/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Gamygyn.lua | 16 | 1259 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Marquis Gamygyn
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if (mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 8192;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if (Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330183); -- 177
SpawnMob(17330184); -- 178
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if (Animate_Trigger == 32767) then
killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
omidas77/speedbot | plugins/clash.lua | 2 | 3559 | --[[
#
# @GPMod
# @dragon_born
#
]]
local apikey =
'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiIsImtpZCI6IjI4YTMxOGY3LTAwMDAtYTFlYi03ZmExLTJjNzQzM2M2Y2NhNSJ9.eyJpc3MiOiJzdXBlcmNlbGwiLCJhdWQiOiJzdXBlcmNlbGw6Z2FtZWFwaSIsImp0aSI6Ijg4OTE3MTc1LTQ0NmItNGMzZC05NzYwLWU0Njk2MDc5NzViMiIsImlhdCI6MTQ3NzY2ODc3MSwic3ViIjoiZGV2ZWxvcGVyLzlkNjRlZDE5LTk0NjAtZWNmYS00Mzg1LTllYTMzYzI4ZWU3ZiIsInNjb3BlcyI6WyJjbGFzaCJdLCJsaW1pdHMiOlt7InRpZXIiOiJkZXZlbG9wZXIvc2lsdmVyIiwidHlwZSI6InRocm90dGxpbmcifSx7ImNpZHJzIjpbIjg1LjEwLjI1MC4yMTYiXSwidHlwZSI6ImNsaWVudCJ9XX0.YPp0nlSiJfypCvhnyVlFM33juaQo0-tfWK9e4U8deJZviEUAxze4SbGNRK3fwTBOIaufyqnC62Ny6IJKHFD-dg'
local function run(msg, matches)
if matches[1]:lower() == 'clan' or matches[1]:lower() == 'clash' or matches[1]:lower() == 'clantag' or matches[1]:lower() == 'tag' then
local clantag = matches[2]
if string.match(matches[2], '^#.+$') then
clantag = string.gsub(matches[2], '#', '')
end
clantag = string.upper(clantag)
local curl = 'curl -X GET --header "Accept: application/json" --header "authorization: Bearer '..apikey..'" "https://api.clashofclans.com/v1/clans/%23'..clantag..'"'
cmd = io.popen(curl)
local result = cmd:read('*all')
local jdat = json:decode(result)
if jdat.reason then
if jdat.reason == 'accessDenied' then return 'ÈÑÇí ËÈÊ API Key ÎæÏ Èå ÓÇíÊ ÒíÑ ÈÑæíÏ\ndeveloper.clashofclans.com' end
return '#Error\n'..jdat.reason
end
local text = 'Clan Tag: '.. jdat.tag
text = text..'\nClan Name: '.. jdat.name
text = text..'\nDescription: '.. jdat.description
text = text..'\nType: '.. jdat.type
text = text..'\nWar Frequency: '.. jdat.warFrequency
text = text..'\nClan Level: '.. jdat.clanLevel
text = text..'\nWar Wins: '.. jdat.warWins
text = text..'\nClan Points: '.. jdat.clanPoints
text = text..'\nRequired Trophies: '.. jdat.requiredTrophies
text = text..'\nMembers: '.. jdat.members
text = text..'\n\n@AlphaPlusTM'
cmd:close()
return text
end
if matches[1]:lower() == 'members' or matches[1]:lower() == 'clashmembers' or matches[1]:lower() == 'clanmembers' then
local members = matches[2]
if string.match(matches[2], '^#.+$') then
members = string.gsub(matches[2], '#', '')
end
members = string.upper(members)
local curl = 'curl -X GET --header "Accept: application/json" --header "authorization: Bearer '..apikey..'" "https://api.clashofclans.com/v1/clans/%23'..members..'/members"'
cmd = io.popen(curl)
local result = cmd:read('*all')
local jdat = json:decode(result)
if jdat.reason then
if jdat.reason == 'accessDenied' then return 'ÈÑÇí ËÈÊ API Key ÎæÏ Èå ÓÇíÊ ÒíÑ ÈÑæíÏ\ndeveloper.clashofclans.com' end
return '#Error\n'..jdat.reason
end
local leader = ""
local coleader = ""
local items = jdat.items
leader = 'Clan Moderators: \n'
for i = 1, #items do
if items[i].role == "leader" then
leader = leader.."\nLeader: "..items[i].name.."\nLevel: "..items[i].expLevel
end
if items[i].role == "coLeader" then
coleader = coleader.."\nCo-Leader: "..items[i].name.."\nLevel: "..items[i].expLevel
end
end
text = leader.."\n"..coleader.."\n\nClan Members:"
for i = 1, #items do
text = text..'\n'..i..'- '..items[i].name..'\nlevel: '..items[i].expLevel.."\n"
end
text = text.."\n\n@AlphaPlusTM"
cmd:close()
return text
end
end
return {
patterns = {
"^[/!](clash) (.*)$",
"^[/!](clan) (.*)$",
"^[/!](clantag) (.*)$",
"^[/!](tag) (.*)$",
"^[/!](clashmembers) (.*)$",
"^[/!](clanmembers) (.*)$",
"^[/!](members) (.*)$",
},
run = run
} | gpl-2.0 |
AresTao/darkstar | scripts/zones/Maze_of_Shakhrami/npcs/_5ia.lua | 19 | 2623 | -----------------------------------
-- Area: Maze of Shakhrami
-- NPC: Strange Apparatus
-- @pos: 375 20 -259 198
-----------------------------------
package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil;
require("scripts/zones/Maze_of_Shakhrami/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0037, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0035, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0035) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0037) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
DeinFreund/Zero-K | LuaUI/Widgets/chili/Handlers/texturehandler.lua | 25 | 3354 | --//=============================================================================
--//
TextureHandler = {}
--//=============================================================================
--//TWEAKING
local timeLimit = 0.2/15 --//time per second / desiredFPS
--//=============================================================================
--// SpeedUp
local next = next
local spGetTimer = Spring.GetTimer
local spDiffTimers = Spring.DiffTimers
local glActiveTexture = gl.ActiveTexture
local glCallList = gl.CallList
local weakMetaTable = {__mode="k"}
--//=============================================================================
--// local
local loaded = {}
local requested = {}
local placeholderFilename = theme.skin.icons.imageplaceholder
local placeholderDL = gl.CreateList(gl.Texture,CHILI_DIRNAME .. "skins/default/empty.png")
--local placeholderDL = gl.CreateList(gl.Texture,placeholderFilename)
local function AddRequest(filename,obj)
local req = requested
if (req[filename]) then
local t = req[filename]
t[obj] = true
else
req[filename] = setmetatable({[obj]=true}, weakMetaTable)
end
end
--//=============================================================================
--// Destroy
TextureHandler._scream = Script.CreateScream()
TextureHandler._scream.func = function()
requested = {}
for filename,tex in pairs(loaded) do
gl.DeleteList(tex.dl)
gl.DeleteTexture(filename)
end
loaded = {}
end
--//=============================================================================
--//
function TextureHandler.LoadTexture(arg1,arg2,arg3)
local activeTexID,filename,obj
if (type(arg1)=='number') then
activeTexID = arg1
filename = arg2
obj = arg3
else
activeTexID = 0
filename = arg1
obj = arg2
end
local tex = loaded[filename]
if (not tex) then
AddRequest(filename,obj)
glActiveTexture(activeTexID,glCallList,placeholderDL)
else
glActiveTexture(activeTexID,glCallList,tex.dl)
end
end
function TextureHandler.DeleteTexture(filename)
local tex = loaded[filename]
if (tex) then
tex.references = tex.references - 1
if (tex.references==0) then
gl.DeleteList(tex.dl)
gl.DeleteTexture(filename)
loaded[filename] = nil
end
end
end
--//=============================================================================
--//
local usedTime = 0
local lastCall = spGetTimer()
function TextureHandler.Update()
if (usedTime>0) then
thisCall = spGetTimer()
usedTime = usedTime - spDiffTimers(thisCall,lastCall)
lastCall = thisCall
if (usedTime<0) then usedTime = 0 end
end
if (not next(requested)) then return end
local timerStart = spGetTimer()
while (usedTime < timeLimit) do
local filename,objs = next(requested)
if (not filename) then return end
gl.Texture(filename)
gl.Texture(false)
local texture = {}
texture.dl = gl.CreateList(gl.Texture,filename)
texture.references = #objs
loaded[filename] = texture
for obj in pairs(objs) do
obj:Invalidate()
end
requested[filename] = nil
local timerEnd = spGetTimer()
usedTime = usedTime + spDiffTimers(timerEnd,timerStart)
timerStart = timerEnd
end
lastCall = spGetTimer()
end
--//=============================================================================
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.