repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/metropolis_torso_rifle_gtm_5.meta.lua | 2 | 2805 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.43000000715255737,
amplification = 140,
light_colors = {
"89 31 168 255",
"48 42 88 255",
"61 16 123 0"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -13,
y = -12
},
rotation = 43
},
head = {
pos = {
x = -1,
y = 1
},
rotation = 54.090278625488281
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 7,
y = 21
},
rotation = -32
},
secondary_hand = {
pos = {
x = 14,
y = 13
},
rotation = 84
},
secondary_shoulder = {
pos = {
x = -10,
y = 19
},
rotation = -142
},
shoulder = {
pos = {
x = 10,
y = -15
},
rotation = -143
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
RyMarq/Zero-K | LuaRules/Gadgets/unit_vertical_swarm.lua | 15 | 3385 | function gadget:GetInfo()
return {
name = "Vertical Swarm",
desc = "Causes chickens to pop out of dense swarms.",
author = "Google Frog",
date = "15 April 2013",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--SYNCED
if (not gadgetHandler:IsSyncedCode()) then
return false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- CONFIG
local CHECK_FREQUENCY = 120 -- How often a single chicken is checked in frames
local RADIUS = 70 -- The checking radius
local NEAR_REQ = 8 -- How many units have to be in range to swarm (ALL UNITS with the same teamID)
local SNAP_HEIGHT = 40 -- How far up a chicken is placed
local HORIZONTAL_IMPULSE = 2 -- Impulse applied after snap
local VERTICAL_IMPULSE = 1.2*Game.gravity/70 -- Impulse applied after snap
local MAGIC_Y_CONSTANT = 10
local SwarmUnitDefs = {
[UnitDefNames["chicken"].id] = true,
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local checkFrames = {}
local toRemove = {}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GameFrame(n)
local frame = checkFrames[n%CHECK_FREQUENCY]
if frame then
local data = frame.data
local i = 1
while i <= frame.count do
local unitID = data[i].unitID
local teamID = data[i].teamID
if toRemove[unitID] or (not Spring.ValidUnitID(unitID)) then
data[i] = data[frame.count]
frame.count = frame.count - 1
toRemove[unitID] = nil
else
-- Do things
local x,y,z = Spring.GetUnitPosition(unitID)
local units = Spring.GetUnitsInCylinder(x,z,RADIUS,teamID)
local near = #units
if near >= NEAR_REQ then
local dir = math.random(0,2*math.pi)
Spring.AddUnitImpulse(unitID, 0,MAGIC_Y_CONSTANT,0)
Spring.MoveCtrl.Enable(unitID)
Spring.MoveCtrl.SetPosition(unitID, x, y+SNAP_HEIGHT, z)
Spring.MoveCtrl.Disable(unitID)
local xDir = math.cos(dir)
local zDir = math.sin(dir)
Spring.AddUnitImpulse(unitID, xDir*HORIZONTAL_IMPULSE,-MAGIC_Y_CONSTANT+VERTICAL_IMPULSE,zDir*HORIZONTAL_IMPULSE)
end
i = i + 1
end
end
end
end
local function addCheck(unitID, teamID)
local n = math.floor(math.random(0,CHECK_FREQUENCY-1))
if not checkFrames[n] then
checkFrames[n] = {count = 0, data = {}}
end
local frame = checkFrames[n]
frame.count = frame.count + 1
frame.data[frame.count] = {unitID = unitID, teamID = teamID}
end
function gadget:UnitCreated(unitID, unitDefID, teamID)
if SwarmUnitDefs[unitDefID] then
if toRemove[unitID] then
toRemove[unitID] = nil
else
addCheck(unitID, teamID)
end
end
end
function gadget:UnitDestroyed(unitID, unitDefID, teamID)
if SwarmUnitDefs[unitDefID] then
toRemove[unitID] = true
end
end
function gadget:Initialize()
for _, unitID in ipairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
gadget:UnitCreated(unitID, unitDefID)
end
end
| gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/modules/admin-mini/luasrc/model/cbi/mini/system.lua | 49 | 2293 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
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
$Id$
]]--
require("luci.sys")
require("luci.sys.zoneinfo")
require("luci.tools.webadmin")
m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone."))
s = m:section(TypedSection, "system", "")
s.anonymous = true
s.addremove = false
local system, model, memtotal, memcached, membuffers, memfree = luci.sys.sysinfo()
local uptime = luci.sys.uptime()
s:option(DummyValue, "_system", translate("System")).value = model
s:option(DummyValue, "_cpu", translate("Processor")).value = system
local load1, load5, load15 = luci.sys.loadavg()
s:option(DummyValue, "_la", translate("Load")).value =
string.format("%.2f, %.2f, %.2f", load1, load5, load15)
s:option(DummyValue, "_memtotal", translate("Memory")).value =
string.format("%.2f MB (%.0f%% %s, %.0f%% %s, %.0f%% %s)",
tonumber(memtotal) / 1024,
100 * memcached / memtotal,
tostring(translate("cached")),
100 * membuffers / memtotal,
tostring(translate("buffered")),
100 * memfree / memtotal,
tostring(translate("free"))
)
s:option(DummyValue, "_systime", translate("Local Time")).value =
os.date("%c")
s:option(DummyValue, "_uptime", translate("Uptime")).value =
luci.tools.webadmin.date_format(tonumber(uptime))
hn = s:option(Value, "hostname", translate("Hostname"))
function hn.write(self, section, value)
Value.write(self, section, value)
luci.sys.hostname(value)
end
tz = s:option(ListValue, "zonename", translate("Timezone"))
tz:value("UTC")
for i, zone in ipairs(luci.sys.zoneinfo.TZ) do
tz:value(zone[1])
end
function tz.write(self, section, value)
local function lookup_zone(title)
for _, zone in ipairs(luci.sys.zoneinfo.TZ) do
if zone[1] == title then return zone[2] end
end
end
AbstractValue.write(self, section, value)
self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0")
end
return m
| gpl-2.0 |
tarantool/luarocks | src/luarocks/cmd/pack.lua | 1 | 1649 |
--- Module implementing the LuaRocks "pack" command.
-- Creates a rock, packing sources or binaries.
local cmd_pack = {}
local util = require("luarocks.util")
local pack = require("luarocks.pack")
local signing = require("luarocks.signing")
local queries = require("luarocks.queries")
cmd_pack.help_summary = "Create a rock, packing sources or binaries."
cmd_pack.help_arguments = "{<rockspec>|<name> [<version>]}"
cmd_pack.help = [[
--sign Produce a signature file as well.
Argument may be a rockspec file, for creating a source rock,
or the name of an installed package, for creating a binary rock.
In the latter case, the app version may be given as a second
argument.
]]
--- Driver function for the "pack" command.
-- @param arg string: may be a rockspec file, for creating a source rock,
-- or the name of an installed package, for creating a binary rock.
-- @param version string or nil: if the name of a package is given, a
-- version may also be passed.
-- @return boolean or (nil, string): true if successful or nil followed
-- by an error message.
function cmd_pack.command(flags, arg, version)
assert(type(version) == "string" or not version)
if type(arg) ~= "string" then
return nil, "Argument missing. "..util.see_help("pack")
end
local file, err
if arg:match(".*%.rockspec") then
file, err = pack.pack_source_rock(arg)
else
local name = util.adjust_name_and_namespace(arg, flags)
local query = queries.new(name, version)
file, err = pack.pack_installed_rock(query, flags["tree"])
end
return pack.report_and_sign_local_file(file, err, flags["sign"])
end
return cmd_pack
| mit |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Commands/CommandSelect.lua | 1 | 5203 | --[[
Title: CommandSelect
Author(s): LiXizhi
Date: 2014/7/5
Desc: selection related command
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSelect.lua");
-------------------------------------------------------
]]
local SlashCommand = commonlib.gettable("MyCompany.Aries.SlashCommand.SlashCommand");
local CmdParser = commonlib.gettable("MyCompany.Aries.Game.CmdParser");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local block = commonlib.gettable("MyCompany.Aries.Game.block")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local Commands = commonlib.gettable("MyCompany.Aries.Game.Commands");
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager");
Commands["select"] = {
name="select",
quick_ref="/select [-add|clear|below|all|pivot|origin|move] x y z [(dx dy dz)]",
desc=[[select blocks in a region.
-- select all blocks in AABB region
/select x y z [(dx dy dz)]
-- select all block below the current player's feet
/select -below [radius] [height]
-- add a single block to current selection. one needs to make a selection first.
/select -add x y z
-- clear selection
/select -clear
-- select all blocks connected with current selection but not below current selection.
/select -all x y z [(dx dy dz)]
-- set pivot point, similar to origin, but also set position
/select -pivot x y z
-- origin is used in exporting
/select -origin x y z
-- move to a new position
/select -move x y z
]] ,
handler = function(cmd_name, cmd_text, cmd_params, fromEntity)
local options;
options, cmd_text = CmdParser.ParseOptions(cmd_text);
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SelectBlocksTask.lua");
local SelectBlocks = commonlib.gettable("MyCompany.Aries.Game.Tasks.SelectBlocks");
if(options.below) then
local radius, height = cmd_text:match("%s*(%d*)%s*(%d*)$");
-- remove all terrain where the player stand
radius = tonumber(radius) or 10;
height = tonumber(height) or 50;
local cx, cy, cz = ParaScene.GetPlayer():GetPosition();
local bx, by, bz = BlockEngine:block(cx,cy+0.1,cz);
local task = SelectBlocks:new({blockX = bx-radius,blockY = by-1, blockZ = bz-radius})
task:Run();
task.ExtendAABB(bx+radius, by-1-height, bz+radius);
elseif(options.clear) then
SelectBlocks.CancelSelection();
elseif(options.pivot or options.origin) then
local x, y, z;
x, y, z, cmd_text = CmdParser.ParsePos(cmd_text, fromEntity);
if(x and y and z) then
local instance = SelectBlocks.GetCurrentInstance();
if(instance) then
instance:SetPivotPoint({x,y,z});
if(not options.origin) then
instance:SetPosition({x,y,z});
end
end
end
elseif(options.move) then
local x, y, z;
x, y, z, cmd_text = CmdParser.ParsePos(cmd_text, fromEntity);
if(x and y and z) then
local instance = SelectBlocks.GetCurrentInstance();
if(instance) then
instance:SetPosition({x,y,z});
end
end
else
local x, y, z, dx, dy, dz;
x, y, z, cmd_text = CmdParser.ParsePos(cmd_text, fromEntity);
if(x) then
dx, dy, dz, cmd_text = CmdParser.ParsePosInBrackets(cmd_text);
if(options.add) then
SelectBlocks.ToggleBlockSelection(x, y, z);
else
-- new selection
local task = SelectBlocks:new({blockX = x,blockY = y, blockZ = z})
task:Run();
if(dx and dy and dz) then
task.ExtendAABB(x+dx, y+dy, z+dz, true);
else
task:RefreshImediately();
end
if(options.all) then
task.SelectAll(true);
end
end
elseif(options.all) then
-- select all blocks connected with current selection but not below current selection.
SelectBlocks.SelectAll(true);
end
end
end,
};
Commands["selectobj"] = {
name="selectobj",
quick_ref="/selectobj @category{entity_selectors}",
desc=[[select entities by parameters.
/selectobj : if no parameters, it will select all objects in current viewport.
/selectobj @e{r=5, type="Railcar"} :select all railcar entities within 5 meters from the triggering entity
/selectobj @e{r=5, type="Railcar", count=1} :select the closet one railcar within 5 meters from the triggering entity
/selectobj @e{r=5, name="abc"} :select entity whose name is abc
/selectobj @e{r=5, nontype="Player"} :select entities that is not a player within 5 meters from the triggering entity
/selectobj @p{r=5, } :select all players within 5 meters from the triggering entity
]],
handler = function(cmd_name, cmd_text, cmd_params, fromEntity)
NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/ObjectSelectPage.lua");
local ObjectSelectPage = commonlib.gettable("MyCompany.Aries.Game.GUI.ObjectSelectPage");
if(cmd_text == "") then
ObjectSelectPage.SelectByScreenRect();
else
local entities;
entities, cmd_text = CmdParser.ParseEntities(cmd_text, fromEntity);
if(entities and #entities>0) then
ObjectSelectPage.SelectEntities(entities);
end
end
end,
};
| gpl-2.0 |
jsj2008/ValyriaTear | img/sprites/map/characters/thanis_run.lua | 4 | 1980 | -- Sprite animation file descriptor
-- This file will describe the frames used to load the sprite animations
-- This files is following a special format compared to other animation scripts.
local ANIM_SOUTH = vt_map.MapMode.ANIM_SOUTH;
local ANIM_NORTH = vt_map.MapMode.ANIM_NORTH;
local ANIM_WEST = vt_map.MapMode.ANIM_WEST;
local ANIM_EAST = vt_map.MapMode.ANIM_EAST;
sprite_animation = {
-- The file to load the frames from
image_filename = "img/sprites/map/characters/thanis_run.png",
-- The number of rows and columns of images, will be used to compute
-- the images width and height, and also the frames number (row x col)
rows = 4,
columns = 6,
-- The frames duration in milliseconds
frames = {
[ANIM_SOUTH] = {
[0] = { id = 1, duration = 150 },
[1] = { id = 2, duration = 150 },
[2] = { id = 3, duration = 150 },
[3] = { id = 1, duration = 150 },
[4] = { id = 4, duration = 150 },
[5] = { id = 5, duration = 150 }
},
[ANIM_NORTH] = {
[0] = { id = 7, duration = 150 },
[1] = { id = 8, duration = 150 },
[2] = { id = 9, duration = 150 },
[3] = { id = 7, duration = 150 },
[4] = { id = 10, duration = 150 },
[5] = { id = 11, duration = 150 }
},
[ANIM_WEST] = {
[0] = { id = 13, duration = 150 },
[1] = { id = 14, duration = 150 },
[2] = { id = 15, duration = 150 },
[3] = { id = 13, duration = 150 },
[4] = { id = 16, duration = 150 },
[5] = { id = 17, duration = 150 }
},
[ANIM_EAST] = {
[0] = { id = 19, duration = 150 },
[1] = { id = 20, duration = 150 },
[2] = { id = 21, duration = 150 },
[3] = { id = 19, duration = 150 },
[4] = { id = 22, duration = 150 },
[5] = { id = 23, duration = 150 }
}
}
}
| gpl-2.0 |
groupforspeed/API-WaderTG | plugins/qrcode.lua | 18 | 1675 | local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"qrcode [text]",
'qrcode "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^[!/#][Qq]rcode "(%w+)" "(%w+)" (.+)$',
"^[!/#][Qq]rcode (.+)$"
},
run = run
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Selbina/npcs/Chutarmire.lua | 1 | 1680 | -----------------------------------
-- Area: Selbina
-- NPC: Chutarmire
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHUTARMIRE_SHOP_DIALOG);
stock = {0x12A0,5751, -- Scroll of Stone II
0x12AA,8100, -- Scroll of Water II
0x129B,11970, -- Scroll of Aero II
0x1291,16560, -- Scroll of Fire II
0x1296,21870, -- Scroll of Blizzard II
0x12A5,27900, -- Scroll of Thunder II
0x12BD,1165, -- Scroll of Stonega
0x12C7,2097, -- Scroll of Waterga
0x12B8,4147, -- Scroll of Aeroga
0x12AE,7025, -- Scroll of Firaga
0x12B3,10710, -- Scroll of Blizzaga
0x12C2,15120, -- Scroll of Thundaga
0x12DD,22680, -- Scroll of Poison II
0x12E7,12600, -- Scroll of Bio II
0x12E1,4644, -- Scroll of Poisonga
0x12FB,8100} -- Scroll of Shock Spikes
showShop(player, STATIC, stock);
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 |
amirhooo/teleim | plugins/help.lua | 1 | 1779 | local function run(msg, matches)
if is_chat_msg(msg) then
local text = [[✅Commands to lock|unlock
💭/close|open link
💭/close|open member
💭/close|open name
💭/close|open bot
💭/close|open image
💭/close|open sticker
💭/close|open file
💭/close|open audio
➕
✅Commands for control member
💭/kick @UserName
💭/ban @UserName
💭/unban @UserName
💭/kickme
➕
✅Group control
💭/rules
💭/setrules [Text]
💭/about
💭/setabout [Text]
💭/setphoto
💭/setname [Text]
💭/id
💭/id chat
💭/group settings
💭/getlink
💭/relink
💭/modlist
💭/help
➕
✅ Group Promote commands
💭/spromote @UserName
💭/sdemote @UserName
💭/promote @UserName
💭/demote @UserName
➖🔸➖🔹➖🔸➖🔹➖]]
return text
end
if is_channel_msg(msg) then
local text = [[✅Commands to lock|unlock
💭/close|open link
💭/close|open member
💭/close|open name
💭/close|open bot
💭/close|open image
💭/close|open sticker
💭/close|open file
💭/close|open audio
➕
✅Commands for control member
💭/kick @UserName
💭/ban @UserName
💭/unban @UserName
💭/kickme
➕
✅Group control
💭/rules
💭/setrules [Text]
💭/about
💭/setabout [Text]
💭/setphoto
💭/setname [Text]
💭/id
💭/id chat
💭/group settings
💭/getlink
💭/relink
💭/modlist
💭/help
➕
✅ Group Promote commands
💭/spromote @UserName
💭/sdemote @UserName
💭/promote @UserName
💭/demote @UserName
➖🔸➖🔹➖🔸➖🔹➖]]
return text
else
local text = [[aaa]]
--return text
end
end
return {
description = "Help plugin. Get info from other plugins. ",
usage = {
"/help: Show list of plugins.",
},
patterns = {
"^/(help)$",
},
run = run,
}
| gpl-3.0 |
NPLPackages/paracraft | script/kids/3DMapSystemUI/MsgProc_AutoAction.lua | 1 | 9868 | --[[
Title: Auto action timer handler
Author(s): LiXizhi
Date: 2007/10/16
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemUI/MsgProc_AutoAction.lua");
Map3DSystem.EnableAutoActionMarker(true);
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemUI/Desktop/autotips.lua");
local L = CommonCtrl.Locale("IDE");
-- disabled by default
Map3DSystem.bShowMarkers = false;
local MyTimer;
-- Auto action is a timer that periodically check the player position and its surroundings, and display some helper text and visual markers.
function Map3DSystem.EnableAutoActionMarker(bShow)
if(not bShow) then
bShow = not Map3DSystem.bShowMarkers;
end
Map3DSystem.bShowMarkers = bShow;
if(bShow) then
Map3DSystem.InitMakerAsset();
NPL.load("(gl)script/ide/timer.lua");
MyTimer = MyTimer or commonlib.Timer:new({callbackFunc = Map3DSystem.OnTimer_AutoAction});
MyTimer:Change(500, 500);
else
if(MyTimer) then
MyTimer:Change();
end
end
end
-- automatically called when script is loaded. However, if the application restarts, remember to call
function Map3DSystem.InitMakerAsset()
if(not Map3DSystem.Assets) then
Map3DSystem.Assets = {};
end
if(not Map3DSystem.Assets["CharMaker"]) then
-- TODO: move asset to locale file.
Map3DSystem.Assets["CharMaker"] = ParaAsset.LoadStaticMesh("", "model/common/marker_point/marker_point.x") --ParaAsset.LoadParaX("", L"CharMaker");
Map3DSystem.Assets["XRefScript"] = ParaAsset.LoadStaticMesh("", "model/common/building_point/building_point.x") --ParaAsset.LoadParaX("", L"XRefScript");
Map3DSystem.Assets["BCSSelectMarker"] = ParaAsset.LoadParaX("", "character/common/marker_point/marker_point3.x");
end
end
function Map3DSystem.ForceDonotHighlight()
g_force_donot_highlight = true;
end
function Map3DSystem.CancelForceDonotHighlight()
g_force_donot_highlight = false;
end
-- display some helper via mini scene graph
-- this is timer handler for timer ID 102
function Map3DSystem.OnTimer_AutoAction()
if(not ParaScene.IsSceneEnabled()) then
return
end
local nextaction;
-- find all nearby characters and display some visual clues
local CharMarkerGraph_Last = ParaScene.GetMiniSceneGraph("CharMarker");
local CharMarkerGraph = ParaScene.GetMiniSceneGraph("CharMarkerLast");
-- here is the trick: create two graphs: current and last, and move objects from last to current, and delete remaining ones in the last.
CharMarkerGraph:SetName("CharMarker");
CharMarkerGraph_Last:SetName("CharMarkerLast");
local XRefScriptGraph = ParaScene.GetMiniSceneGraph("XRefScriptMarkerLast");
local XRefScriptGraph_Last = ParaScene.GetMiniSceneGraph("XRefScriptMarker");
XRefScriptGraph:SetName("XRefScriptMarker");
XRefScriptGraph_Last:SetName("XRefScriptMarkerLast");
local player = ParaScene.GetPlayer();
local char = player:ToCharacter();
if(Map3DSystem.UI.DesktopMode.CanShowClosestCharMarker) then
if(char:IsValid())then
local nCount = player:GetNumOfPerceivedObject();
local closest = nil;
local min_dist = 100000;
for i=0,nCount-1 do
local gameobj = player:GetPerceivedObject(i);
local dist = gameobj:DistanceTo(player);
if( dist < min_dist) then
closest = gameobj;
min_dist = dist;
end
-- Shall we display something to all perceived characters?
end
if(closest~=nil) then
local fromX, fromY, fromZ = player:GetPosition();
fromY = fromY+1.0;
local toX, toY, toZ = closest:GetPosition();
if(min_dist<Map3DSystem.options.CharClickDist) then
-- highlight the closest interactable character
local donot_highlight;
local onclickscript = closest:GetAttributeObject():GetField("On_Click", "");
if(onclickscript~=nil and onclickscript~="") then
nextaction = L"press Ctrl key to talk to it!"
else
if(char:IsMounted())then
nextaction = L"press Space key to get off!"
-- if object is mounted, do not highlight
donot_highlight = true;
elseif(closest:ToCharacter():IsMounted()) then
nextaction = L"press Shift key and then Space key to get off!"
-- if closest object is mounted, do not highlight
donot_highlight = true;
elseif(closest:HasAttachmentPoint(0)==true) then
nextaction = L"press Shift key to mount on it!"
else
nextaction = L"press Shift key to switch to it!"
end
if(not closest:IsStanding()) then
-- if object is moving, do not highlight
donot_highlight = true;
end
end
-- NOTE by Andy: force to unhighlight the closest character, currently the following situations are used:
-- 1. donot highlight the closest character when movie is playing
if(g_force_donot_highlight == true) then
donot_highlight = true;
end
if(not donot_highlight) then
local obj = CharMarkerGraph_Last:GetObject(toX, toY, toZ);
if(obj:IsValid()) then
-- if there is already an highlighter in the last frame, we will reuse it in the current frame.
CharMarkerGraph_Last:RemoveObject(obj);
CharMarkerGraph:AddChild(obj);
else
obj = ParaScene.CreateMeshPhysicsObject("ClosestCharMaker", Map3DSystem.Assets["CharMaker"], 1,1,1, false, "1,0,0,0,1,0,0,0,1,0,0,0");
if(obj:IsValid()==true) then
obj:SetPosition(toX, toY, toZ);
obj:SetFacing(0);
obj:GetAttributeObject():SetField("progress", 1);
CharMarkerGraph:AddChild(obj);
end
end
end
else
-- TODO: mark the closest character, but player is not close enough to interact with it.
end
end
end
else
CharMarkerGraph:Reset();
end
if(Map3DSystem.UI.DesktopMode.CanShowNearByXrefMarker) then
-- find any XRef scripts on the nearby mesh objects
local objlist = {};
local fromX, fromY, fromZ = player:GetPosition();
local NearByRadius = 5;
local nCount = ParaScene.GetActionMeshesBySphere(objlist, fromX, fromY, fromZ, NearByRadius);
local k = 1;
local subIndex = nil;
local closestObj = nil;
local min_dist = 100000;
for k=1,nCount do
local obj = objlist[k];
local nXRefCount = obj:GetXRefScriptCount();
local i=0;
local toX, toY, toZ;
for i=0,nXRefCount-1 do
toX, toY, toZ = obj:GetXRefScriptPosition(i);
local dist = math.sqrt((fromX-toX)*(fromX-toX)+(fromY-toY)*(fromY-toY)+(fromZ-toZ)*(fromZ-toZ));
if( dist < min_dist) then
subIndex = i;
closestObj = obj;
min_dist = dist;
end
local script = obj:GetXRefScript(i);
-- only display a visual helper if the script file contains "_point" in the file name.
if(string.find(script, "model/scripts/.+_point.*") ~= nil) then
-- display some visual clues if it is an the action point
local meshobj = XRefScriptGraph_Last:GetObject(toX, toY, toZ);
if(meshobj:IsValid()) then
-- if there is already an highlighter in the last frame, we will reuse it in the current frame.
XRefScriptGraph_Last:RemoveObject(meshobj);
XRefScriptGraph:AddChild(meshobj);
else
local transform = obj:GetXRefScriptLocalMatrix(i);
if(not transform) then
transform = "1,0,0,0,1,0,0,0,1,0,0,0"
end
meshobj = ParaScene.CreateMeshPhysicsObject("XRefScriptMaker", Map3DSystem.Assets["XRefScript"], 1,1,1, false, transform);
if(meshobj:IsValid()==true) then
meshobj:SetPosition(toX, toY, toZ);
meshobj:SetFacing(0);
meshobj:GetAttributeObject():SetField("progress", 1);
XRefScriptGraph:AddChild(meshobj);
end
end
end
end
end
if(closestObj~=nil) then
if(not XRefScriptObj) then XRefScriptObj = {} end
toX, toY, toZ = closestObj:GetXRefScriptPosition(subIndex);
if(min_dist<Map3DSystem.options.XrefClickDist) then
-- TODO: when it is the nearest action point, display some specials
local script = closestObj:GetXRefScript(subIndex);
-- only display a visual helper if the script file contains "_point" in the file name.
if(string.find(script, "model/scripts/.+_point.*") ~= nil) then
local obj = CharMarkerGraph_Last:GetObject(toX, toY, toZ);
if(obj:IsValid()) then
-- if there is already an highlighter in the last frame, we will reuse it in the current frame.
CharMarkerGraph_Last:RemoveObject(obj);
CharMarkerGraph:AddChild(obj);
else
obj = ParaScene.CreateMeshPhysicsObject("ClosestCharMaker", Map3DSystem.Assets["CharMaker"], 1,1,1, false, "1,0,0,0,1,0,0,0,1,0,0,0");
if(obj:IsValid()==true) then
obj:SetPosition(toX, toY, toZ);
obj:SetFacing(0);
obj:GetAttributeObject():SetField("progress", 1);
CharMarkerGraph:AddChild(obj);
end
end
nextaction = L"mouse click on mark or press Ctrl key to change the building block!"
--local msg = {};
--msg.posX, msg.posY, msg.posZ = toX, toY, toZ;
--msg.scaleX, msg.scaleY, msg.scaleZ = closestObj:GetXRefScriptScaling(subIndex);
--msg.facing = closestObj:GetXRefScriptFacing(subIndex);
--msg.dist = min_dist;
--
---- call the script file
--NPL.call(closestObj:GetXRefScript(subIndex), msg);
elseif(string.find(script, "model/scripts/.+chair.*") ~= nil) then
-- show tips: press control key to sit on the chair
nextaction = L"press Ctrl key to sit!"
end
else
-- TODO: it is the nearest action point, but character is not close enough to trigger it
end
end
else
if(not Map3DSystem.UI.DesktopMode.CanShowClosestCharMarker) then
CharMarkerGraph:Reset();
end
XRefScriptGraph:Reset();
end
CharMarkerGraph_Last:Reset();
XRefScriptGraph_Last:Reset();
-- display tips
autotips.AddTips("nextaction", nextaction, 10);
-- refresh autotips.
autotips.Refresh();
end | gpl-2.0 |
monkoose/neovim-setup | lua/custom/term.lua | 1 | 1715 | local utils = require("custom.utils")
local statusline = require("statusline")
local default_size = math.floor((vim.o.lines * (2 / 5)))
local augroup = vim.api.nvim_create_augroup("termresize", {})
local term = {
shell = "/bin/fish",
bufnr = 0,
pos = "split",
size = default_size,
}
local function set_win_options()
local width = vim.api.nvim_win_get_width(0)
if vim.o.columns == width then
term.pos = "split"
term.size = vim.api.nvim_win_get_height(0)
else
term.pos = "vsplit"
term.size = width
end
end
local function split_btm()
vim.cmd("silent keepalt botright " .. term.size .. term.pos)
end
local function create_buf()
term.bufnr = vim.api.nvim_create_buf(false, false)
vim.api.nvim_buf_set_option(term.bufnr, "filetype", "myterm")
vim.api.nvim_create_autocmd("WinLeave", {
buffer = term.bufnr,
group = augroup,
callback = set_win_options,
})
return term.bufnr
end
local function open_term()
split_btm()
vim.api.nvim_win_set_buf(0, term.bufnr)
end
local function new_term()
create_buf()
open_term()
vim.wo.statusline = " "
vim.fn.termopen({ term.shell })
vim.b.term_title = ""
statusline.setstatusline(true)
vim.cmd.startinsert()
end
local function hide(winid)
if (winid == vim.api.nvim_get_current_win()) then
utils.jump_to_prev_win()
end
vim.api.nvim_win_hide(winid)
end
local function win_exists(winid)
return winid ~= -1
end
local function toggle_term()
if vim.fn.bufexists(term.bufnr) == 1 then
local term_winid = vim.fn.bufwinid(term.bufnr)
if win_exists(term_winid) then
hide(term_winid)
else
open_term()
end
else
new_term()
end
end
return {
toggle = toggle_term
}
| mit |
vince06fr/prosody-modules | mod_pubsub_post/mod_pubsub_post.lua | 32 | 1139 | module:depends("http");
local st = require "util.stanza";
local json = require "util.json";
local formdecode = require "net.http".formdecode;
local uuid_generate = require "util.uuid".generate;
local timestamp_generate = require "util.datetime".datetime;
local pubsub_service = module:depends("pubsub").service;
function handle_POST(event, path)
local data = event.request.body;
local item_id = "default";
local post_item = st.stanza("item", { id = item_id, xmlns = "http://jabber.org/protocol/pubsub" })
:tag("entry", { xmlns = "http://www.w3.org/2005/Atom" })
:tag("id"):text(uuid_generate()):up()
:tag("title"):text(data):up()
:tag("author")
:tag("name"):text(event.request.conn:ip()):up()
:up()
:tag("published"):text(timestamp_generate()):up();
local ok, err = pubsub_service:publish(path, true, item_id, post_item);
module:log("debug", "Handled POST: \n%s\n", tostring(event.request.body));
return ok and "Posted" or ("Error: "..err);
end
module:provides("http", {
route = {
["POST /*"] = handle_POST;
};
});
function module.load()
module:log("debug", "Loaded at %s", module:http_url());
end
| mit |
fyrchik/xlua | exercises/gigasecond/gigasecond_spec.lua | 3 | 1176 | local gigasecond = require('gigasecond')
describe('gigasecond', function()
it('test 1', function()
local actual = gigasecond.anniversary(os.time({ year = 2011, month = 3, day = 25, hour = 0, min = 0, sec = 0 }))
local expectedDate = os.date('%x', os.time({ year = 2042, month = 12, day = 1, hour = 0, min = 0, sec = 0 }))
assert.are.equals(expectedDate, actual)
end)
it('test 2', function()
local actual = gigasecond.anniversary(os.time({ year = 1977, month = 5, day = 13, hour = 0, min = 0, sec = 0 }))
local expectedDate = os.date('%x', os.time({ year = 2009, month = 1, day = 19 }))
assert.are.equals(expectedDate, actual)
end)
it('test 3', function()
local actual = gigasecond.anniversary(os.time({ year = 1959, month = 7, day = 19 }))
local expectedDate = os.date('%x', os.time({ year = 1991, month = 3, day = 27 }))
assert.are.equals(expectedDate, actual)
end)
it('test 4', function()
local actual = gigasecond.anniversary(os.time({ year = 1993, month = 8, day = 17 }))
local expectedDate = os.date('%x', os.time({ year = 2025, month = 4, day = 25 }))
assert.are.equals(expectedDate, actual)
end)
end)
| mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bastok_Markets/npcs/Olwyn.lua | 1 | 1235 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Olwyn
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,OLWYN_SHOP_DIALOG);
stock = {0x1020,4445,1, -- Ether
0x1037,736,2, -- Echo Drops
0x1010,837,2, -- Potion
0x1036,2387,3, -- Eye Drops
0x1034,290,3} -- Antidote
showNationShop(player, BASTOK, stock);
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 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/metropolis_torso_pistol_ptm_2.meta.lua | 2 | 2835 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.43000000715255737,
amplification = 140,
light_colors = {
"89 31 168 255",
"48 42 88 255",
"61 16 123 0"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -3,
y = 15
},
rotation = -87.387901306152344
},
head = {
pos = {
x = 0,
y = 0
},
rotation = -31.122470855712891
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 50,
y = -36
},
rotation = -90
},
secondary_hand = {
pos = {
x = -12,
y = -26
},
rotation = 0
},
secondary_shoulder = {
pos = {
x = 19,
y = -5
},
rotation = 93.55999755859375
},
shoulder = {
pos = {
x = -21,
y = -7
},
rotation = 87
},
strafe_facing_offset = -90
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
RyMarq/Zero-K | lups/headers/vectors.lua | 8 | 2720 | -- $Id: vectors.lua 3171 2008-11-06 09:06:29Z det $
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--
-- file: vectors.h.lua
-- brief: collection of some usefull vector functions (length, addition, skmult, vmult, ..)
-- authors: jK
-- last updated: 30 Oct. 2007
--
-- Copyright (C) 2007.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
local sqrt = math.sqrt
local min = math.min
local type = type
Vector = {}
Vector.mt = {}
function Vector.new (t)
local v = {}
setmetatable(v, Vector.mt)
for i,w in pairs(t) do v[i] = w end
return v
end
function Vector.mt.__add(a,b)
if type(a) ~= "table" or
type(b) ~= "table"
then
error("attempt to `add' a vector with a non-table value", 2)
end
local v = {}
local n = math.min(#a or 0,#b or 0)
for i=1,n do v[i] = a[i]+b[i] end
return v
end
function Vector.mt.__sub(a,b)
if type(a) ~= "table" or
type(b) ~= "table"
then
error("attempt to `sub' a vector with a non-table value", 2)
end
local v = {}
local n = math.min(#a or 0,#b or 0)
for i=1,n do v[i] = a[i]-b[i] end
return v
end
function Vector.mt.__mul(a,b)
if ((type(a) ~= "table") and (type(b) ~= "number"))or
((type(b) ~= "table") and (type(a) ~= "number"))
then
error("attempt to `mult' a vector with something else than a number", 2)
end
local u,w
if (type(a) == "table") then
u,w = a,b
else
u,w = b,a
end
local v = {}
for i=1,#u do v[i] = w*u[i] end
return v
end
function Vadd(a,b)
local v = {}
local n = min(#a or 0,#b or 0)
for i=1,n do v[i] = a[i]+b[i] end
return v
end
function Vsub(a,b)
local v = {}
local n = min(#a or 0,#b or 0)
for i=1,n do v[i] = a[i]-b[i] end
return v
end
function Vmul(a,b)
local u,w
if (type(a) == "table") then
u,w = a,b
else
u,w = b,a
end
local v = {}
for i=1,#u do v[i] = w*u[i] end
return v
end
function Vcross(a,b)
return {a[2]*b[3] - a[3]*b[2],
a[3]*b[1] - a[1]*b[3],
a[1]*b[2] - a[2]*b[1]}
end
function Vlength(a)
return sqrt(a[1]*a[1] + a[2]*a[2] + a[3]*a[3])
end
function CopyVector(write,read,n)
for i=1,n do
write[i]=read[i]
end
end
function CreateEmitMatrix3x3(x,y,z)
local xz = x*z
local xy = x*y
local yz = y*z
return {
x*x, xy-z, xz+y,
xy+z, y*y, yz-x,
xz-y, yz+x, z*z
}
end
function MultMatrix3x3(m, x,y,z)
return m[1]*x + m[2]*y + m[3]*z,
m[4]*x + m[5]*y + m[6]*z,
m[7]*x + m[8]*y + m[9]*z
end
| gpl-2.0 |
RyMarq/Zero-K | LuaRules/Configs/MetalSpots/RustyDelta_Final.lua | 8 | 2895 | return {
spots = {
{x = 9960, z = 3576, metal = 2.011},
{x = 1576, z = 1768, metal = 2.011},
{x = 9272, z = 2696, metal = 2.011},
{x = 3256, z = 1864, metal = 2.011},
{x = 1704, z = 2808, metal = 2.011},
{x = 984, z = 2696, metal = 2.011},
{x = 10136, z = 3720, metal = 2.011},
{x = 4728, z = 3832, metal = 2.011},
{x = 280, z = 1928, metal = 2.011},
{x = 9672, z = 2120, metal = 2.011},
{x = 728, z = 968, metal = 2.011},
{x = 408, z = 136, metal = 2.011},
{x = 8680, z = 1768, metal = 2.011},
{x = 216, z = 2296, metal = 2.011},
{x = 5128, z = 2040, metal = 6.0342411994934},
{x = 552, z = 1224, metal = 2.011},
{x = 6504, z = 3720, metal = 2.011},
{x = 10152, z = 392, metal = 2.011},
{x = 3112, z = 2616, metal = 2.011},
{x = 3832, z = 4040, metal = 2.011},
{x = 6424, z = 4040, metal = 2.011},
{x = 4664, z = 584, metal = 2.011},
{x = 9704, z = 1224, metal = 2.011},
{x = 5320, z = 3176, metal = 2.011},
{x = 4952, z = 3176, metal = 2.011},
{x = 872, z = 3032, metal = 2.011},
{x = 1416, z = 3960, metal = 2.011},
{x = 8840, z = 3960, metal = 2.011},
{x = 5800, z = 2600, metal = 2.011},
{x = 3016, z = 344, metal = 2.011},
{x = 5848, z = 808, metal = 2.011},
{x = 8824, z = 56, metal = 2.011},
{x = 408, z = 984, metal = 2.011},
{x = 5128, z = 312, metal = 5.9612107276917},
{x = 5608, z = 584, metal = 2.011},
{x = 9160, z = 2904, metal = 2.011},
{x = 10040, z = 2296, metal = 2.011},
{x = 5128, z = 3912, metal = 5.8271403312683},
{x = 8552, z = 2808, metal = 2.011},
{x = 6264, z = 3848, metal = 2.011},
{x = 4408, z = 808, metal = 2.011},
{x = 8488, z = 1448, metal = 4.302},
{x = 9384, z = 3032, metal = 2.011},
{x = 5960, z = 3384, metal = 2.011},
{x = 4296, z = 3384, metal = 2.011},
{x = 9896, z = 3912, metal = 2.011},
{x = 136, z = 3720, metal = 2.011},
{x = 312, z = 3576, metal = 2.011},
{x = 7144, z = 2616, metal = 2.011},
{x = 7608, z = 3464, metal = 2.011},
{x = 1432, z = 56, metal = 2.011},
{x = 2648, z = 3464, metal = 2.011},
{x = 5528, z = 3832, metal = 2.011},
{x = 9864, z = 984, metal = 2.011},
{x = 152, z = 152, metal = 2.011},
{x = 584, z = 2120, metal = 2.011},
{x = 5944, z = 1688, metal = 2.011},
{x = 3992, z = 3848, metal = 2.011},
{x = 4456, z = 2600, metal = 2.011},
{x = 9848, z = 136, metal = 2.011},
{x = 3752, z = 3720, metal = 2.011},
{x = 360, z = 3912, metal = 2.011},
{x = 9528, z = 968, metal = 2.011},
{x = 9976, z = 1928, metal = 2.011},
{x = 4328, z = 1688, metal = 2.011},
{x = 7240, z = 344, metal = 2.011},
{x = 7016, z = 1864, metal = 2.011},
{x = 1112, z = 2904, metal = 2.011},
{x = 10104, z = 152, metal = 2.011},
{x = 1768, z = 1448, metal = 4.302},
{x = 104, z = 392, metal = 2.011},
}
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/wild_melon.lua | 1 | 1131 | -----------------------------------------
-- ID: 4597
-- Item: wild_melon
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility -6
-- Intelligence 4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,0,4597);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, -6);
target:addMod(MOD_INT, 4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, -6);
target:delMod(MOD_INT, 4);
end;
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/farportal_vortex.lua | 3 | 1272 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
base_size = 64
return {
system_rotation = 0, system_rotationv = 0.5,
base = 1000,
angle = { 0, 0 }, anglev = { 0, 0 }, anglea = { 0, 0 },
life = { 100, 100 },
size = { 256, 256 }, sizev = {0, 0}, sizea = {0, 0},
r = {255, 255}, rv = {0, 0}, ra = {0, 0},
g = {255, 255}, gv = {0, 0}, ga = {0, 0},
b = {255, 255}, bv = {0, 0}, ba = {0, 0},
a = {255, 255}, av = {0, 0}, aa = {0, 0},
}, function(self)
self.ps:emit(1)
end, 1, vortex or "shockbolt/terrain/farportal-blue-vortex", true
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/Dock/DockAssetsPreloader.lua | 1 | 14422 | --[[
Title: DockAssetsPreloader
Author(s): leio
Date: 2020/10/29
Desc:
Use Lib:
-------------------------------------------------------
local DockAssetsPreloader = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Dock/DockAssetsPreloader.lua");
DockAssetsPreloader.Start();
--]]
NPL.load("(gl)script/ide/FileLoader.lua");
NPL.load("(gl)script/ide/timer.lua");
NPL.load("(gl)script/kids/3DMapSystemUI/MiniGames/SwfLoadingBarPage.lua");
local DockAssetsPreloader = NPL.export();
-- NOTE:this is generated by https://github.com/tatfook/ParacraftAssetList
-- don't change this by manuallly
local assets = {
"Texture/Aries/Creator/keepwork/explorer_32bits.png",
"Texture/Aries/Creator/keepwork/worldshare_32bits.png",
"Texture/Aries/Creator/keepwork/dock/biaoji_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_beibao_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_chuangzao_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_haoyou_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_home_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_huiyuan_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_renwu_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_shangcheng_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_tangsuo_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_xitong_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_xuexi_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_xuexiao_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn_ziyuan_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_chengzhangrenwu_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_chengzhangriji_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_dasai_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_guanwang_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_ketang_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_shizhan_32bits.png",
"Texture/Aries/Creator/keepwork/dock/btn2_yonghushequ_32bits.png",
"Texture/Aries/Creator/keepwork/dock/ditu_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/blue_v_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/crown_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/renwu_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/T_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/T_gray_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/V_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/V_gray_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/VT_32bits.png",
"Texture/Aries/Creator/keepwork/UserInfo/VT_gray_32bits.png",
"Texture/Aries/Creator/keepwork/Window/button/btn_huangse_32bits.png",
"Texture/Aries/Creator/keepwork/Window/button/btn_huise_32bits.png",
"Texture/Aries/Creator/keepwork/Window/button/btn_lvse_32bits.png",
"Texture/Aries/Creator/keepwork/Window/dakuang_32bits.png",
"Texture/Aries/Creator/keepwork/Window/dakuang2_32bits.png",
"Texture/Aries/Creator/keepwork/Window/guanbi_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_beibao_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_chuangzao_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_haoyou_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_shangcheng_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_tansuo_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_tishi_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_vip_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_xitong_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_xuexi_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_xuexiao_32bits.png",
"Texture/Aries/Creator/keepwork/Window/title/biaoti_ziyuan_32bits.png",
"Texture/Aries/Creator/keepwork/Window/tooltip/tipbj_32bits.png",
"Texture/Aries/Creator/keepwork/Window/tooltip/tipkuang_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/btn_guang_25X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/btn_shijie_84X23_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/btn_yinyue1_25X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/btn_yinyue2_25X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/dikuang_64X64_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/dikuang2_26X26_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/dikuang3_26X26_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/dikuang4_192X351_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/icon_bukexuan_24X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/icon_didian_12X15_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/icon_kexuan_24X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/icon_yiruzhu_24X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/icon_yixuan_24X24_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/1_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/10_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/2_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/3_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/4_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/5_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/6_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/7_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/8_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/number/9_15X14_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/tupiandi_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/tupiandi2_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/xuanzhong_36X36_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/xuexiao_54X49_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zhiding_43X47_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_bingxing_96X25_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_bukexuan_39X15_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_kexuan_27X15_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_quxiao_47X11_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_sanwei_96X25_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_shewei_47X11_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_yiruzhu_39X15_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_yixuan_27X15_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zi_zanwushijie_221X46_32bits.png",
"Texture/Aries/Creator/keepwork/ParaWorld/zuopkuang_266X134_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/dialog/dialog_440X93_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/dialog/guanbi_22X22_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/dialog/xiala_12X38_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/bianji_20X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/biaoti_128X64_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_add_guanzhudi_99X30_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_bianji_24X24_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_cancel_16X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_confirm_16X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_genghuan_38X39_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_gerenwangzhan_38X38_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_guanzhu_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_guanzhudi_99X30_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_jia_11X11_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_jian_10X3_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_jingru_40X40_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_ladong_20X8_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_ladongdi_10x130_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_qiehuanyou_12X21_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_qiehuanzuo_12X21_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_quxiaoguanzhu_99X30_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_shanchu_40X40_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_shuaxin_40X40_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_wenjian_40X40_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_xuanzhuanyou_40X35_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_xuanzhuanzou_40X35_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/btn_zuop_90X34_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/fengexian_1X45_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/fenshudi_76X41_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/icon_dianzan_16X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/icon_liulan_16X12_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/icon_xinxi_18X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/0_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/1_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/2_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/3_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/4_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/5_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/6_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/7_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/8_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/9_16X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/number/dian_7X7_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/renwukuang_339X529_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/shuruzhuangdi_16X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/suosi_28X31_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/tipbj_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/tipX_19X20_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/tixingzi_332X50_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/wenzidi_70X24_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_diqu_33X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_fensi_34X15_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_guangzhu_34X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_guanzhu_30X15_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_shengri_32X15_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_xuexiao_34X17_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_yiguanzhu_46X15_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_zhanghao_34X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zi_zhishidou_50X16_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zuopkuang_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/ggs/user/zuopkuang_selected_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/map/btn_E_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/map/btn_localmap_32bits.png",
"Texture/Aries/Creator/keepwork/map/btn_R_32X32_32bits.png",
"Texture/Aries/Creator/keepwork/map/btn_spawnpoint_32bits.png",
"Texture/Aries/Creator/keepwork/map/btn_worldmap_32bits.png",
"Texture/Aries/Creator/keepwork/map/maparrow_32bits.png",
"Texture/Aries/Common/ThemeTeen/circle_32bits.png"
}
DockAssetsPreloader.cur_time = 0;
DockAssetsPreloader.timeout = 30000;
DockAssetsPreloader.timer = nil;
function DockAssetsPreloader.GetLoginMode()
if(System and System.options and System.options.loginmode)then
return System.options.loginmode;
end
end
function DockAssetsPreloader.Start(callback)
local loginmode = DockAssetsPreloader.GetLoginMode();
LOG.std(nil, "info", "DockAssetsPreloader check loginmode:", loginmode);
if(loginmode == "offline")then
if(callback)then
callback();
end
return
end
if(DockAssetsPreloader.is_start)then
if(callback)then
callback();
end
return
end
DockAssetsPreloader.is_start = true
DockAssetsPreloader.cur_time = 0;
local fileLoader = CommonCtrl.FileLoader:new{
download_list = DockAssetsPreloader.GetDownloadList(),--下载文件列表
logname = "log/mc_textures_loader",--log文件地址
}
fileLoader:Start();
Map3DSystem.App.MiniGames.SwfLoadingBarPage.ShowPage({
show_background = true,
});
local timer = commonlib.Timer:new({callbackFunc = function(timer)
DockAssetsPreloader.cur_time = DockAssetsPreloader.cur_time + timer.delta;
local percent = fileLoader:GetPercent();
Map3DSystem.App.MiniGames.SwfLoadingBarPage.Update(percent);
Map3DSystem.App.MiniGames.SwfLoadingBarPage.UpdateText(L"下载贴图中,首次加载会比较慢,请耐心等待");
if(percent >= 1 or DockAssetsPreloader.cur_time > DockAssetsPreloader.timeout)then
Map3DSystem.App.MiniGames.SwfLoadingBarPage.ClosePage();
if(callback)then
callback();
end
-- kill timer
timer:Change()
return
end
end})
timer:Change(0, 100);
end
function DockAssetsPreloader.FillAssets(loader)
if(not loader)then
return
end
for k,v in ipairs(assets) do
loader:AddAssets(v);
end
end
function DockAssetsPreloader.IsIsolatedApp()
if(System.options and System.options.cmdline_world and System.options.cmdline_world~="") then
return true
end
return false;
end
function DockAssetsPreloader.GetDownloadList()
NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/CustomCharItems.lua");
local CustomCharItems = commonlib.gettable("MyCompany.Aries.Game.EntityManager.CustomCharItems")
local list = {};
table.insert(list, {filename = CustomCharItems.defaultModelFile, filesize = 1});
if(not DockAssetsPreloader.IsIsolatedApp())then
for k,v in ipairs(assets) do
table.insert(list,{
filename = v,
filesize = 1,
});
end
end
return list;
end
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/rest/v1/get/flow/alert/list.lua | 1 | 1589 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local rest_utils = require("rest_utils")
local flow_alert_store = require "flow_alert_store".new()
local auth = require "auth"
--
-- Read alerts data
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v1/get/flow/alert/list.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
local format = _GET["format"] or "json"
local no_html = (format == "txt")
if not auth.has_capability(auth.capabilities.alerts) then
rest_utils.answer(rest_utils.consts.err.not_granted)
return
end
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
interface.select(ifid)
-- Fetch the results
local alerts, recordsFiltered = flow_alert_store:select_request(nil, "*, hex(alerts_map) alerts_map")
for _, _value in ipairs(alerts or {}) do
res[#res + 1] = flow_alert_store:format_record(_value, no_html)
end
if no_html then
res = flow_alert_store:to_csv(res)
rest_utils.vanilla_payload_response(rc, res, "text/csv")
else
rest_utils.extended_answer(rc, {records = res}, {
["draw"] = tonumber(_GET["draw"]),
["recordsFiltered"] = recordsFiltered,
["recordsTotal"] = #res
}, format)
end
| gpl-3.0 |
gmagnotta/packages | net/luci-app-e2guardian/files/e2guardian-cbi.lua | 55 | 18594 | --[[
LuCI E2Guardian module
Copyright (C) 2015, Itus Networks, Inc.
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
Author: Marko Ratkaj <marko.ratkaj@sartura.hr>
Luka Perkov <luka.perkov@sartura.hr>
]]--
local fs = require "nixio.fs"
local sys = require "luci.sys"
m = Map("e2guardian", translate("E2Guardian"))
m.on_after_commit = function() luci.sys.call("/etc/init.d/e2guardian restart") end
s = m:section(TypedSection, "e2guardian")
s.anonymous = true
s.addremove = false
s:tab("tab_general", translate("General Settings"))
s:tab("tab_additional", translate("Additional Settings"))
s:tab("tab_logs", translate("Logs"))
----------------- General Settings Tab -----------------------
filterip = s:taboption("tab_general", Value, "filterip", translate("IP that E2Guardian listens"))
filterip.datatype = "ip4addr"
filterports = s:taboption("tab_general", Value, "filterports", translate("Port that E2Guardian listens"))
filterports.datatype = "portrange"
filterports.placeholder = "0-65535"
proxyip = s:taboption("tab_general", Value, "proxyip", translate("IP address of the proxy"))
proxyip.datatype = "ip4addr"
proxyip.default = "127.0.0.1"
proxyport = s:taboption("tab_general", Value, "proxyport", translate("Port of the proxy"))
proxyport.datatype = "portrange"
proxyport.placeholder = "0-65535"
languagedir = s:taboption("tab_general", Value, "languagedir", translate("Language dir"))
languagedir.datatype = "string"
languagedir.default = "/usr/share/e2guardian/languages"
language = s:taboption("tab_general", Value, "language", translate("Language to use"))
language.datatype = "string"
language.default = "ukenglish"
loglevel = s:taboption("tab_general", ListValue, "loglevel", translate("Logging Settings"))
loglevel:value("0", translate("none"))
loglevel:value("1", translate("just denied"))
loglevel:value("2", translate("all text based"))
loglevel:value("3", translate("all requests"))
loglevel.default = "2"
logexceptionhits = s:taboption("tab_general", ListValue, "logexceptionhits", translate("Log Exception Hits"))
logexceptionhits:value("0", translate("never"))
logexceptionhits:value("1", translate("log, but dont mark as exceptions"))
logexceptionhits:value("2", translate("log and mark"))
logexceptionhits.default = "2"
logfileformat = s:taboption("tab_general", ListValue, "logfileformat", translate("Log File Format"))
logfileformat:value("1", translate("DansgGuardian format, space delimited"))
logfileformat:value("2", translate("CSV-style format"))
logfileformat:value("3", translate("Squid Log File Format"))
logfileformat:value("4", translate("Tab delimited"))
logfileformat:value("5", translate("Protex format"))
logfileformat:value("6", translate("Protex format with server field blanked"))
logfileformat.default = "1"
accessdeniedaddress = s:taboption("tab_general", Value, "accessdeniedaddress", translate("Access denied address"),
translate("Server to which the cgi e2guardian reporting script was copied. Reporting levels 1 and 2 only"))
accessdeniedaddress.datatype = "string"
accessdeniedaddress.default = "http://YOURSERVER.YOURDOMAIN/cgi-bin/e2guardian.pl"
usecustombannedimage = s:taboption("tab_general", ListValue, "usecustombannedimage", translate("Banned image replacement"))
usecustombannedimage:value("on", translate("Yes"))
usecustombannedimage:value("off", translate("No"))
usecustombannedimage.default = "on"
custombannedimagefile = s:taboption("tab_general", Value, "custombannedimagefile", translate("Custom banned image file"))
custombannedimagefile.datatype = "string"
custombannedimagefile.default = "/usr/share/e2guardian/transparent1x1.gif"
usecustombannedflash = s:taboption("tab_general", ListValue, "usecustombannedflash", translate("Banned flash replacement"))
usecustombannedflash:value("on", translate("Yes"))
usecustombannedflash:value("off", translate("No"))
usecustombannedflash.default = "on"
custombannedflashfile = s:taboption("tab_general", Value, "custombannedflashfile", translate("Custom banned flash file"))
custombannedflashfile.datatype = "string"
custombannedflashfile.default = "/usr/share/e2guardian/blockedflash.swf"
filtergroups = s:taboption("tab_general", Value, "filtergroups", translate("Number of filter groups"))
filtergroups.datatype = "and(uinteger,min(1))"
filtergroups.default = "1"
filtergroupslist = s:taboption("tab_general", Value, "filtergroupslist", translate("List of filter groups"))
filtergroupslist.datatype = "string"
filtergroupslist.default = "/etc/e2guardian/lists/filtergroupslist"
bannediplist = s:taboption("tab_general", Value, "bannediplist", translate("List of banned IPs"))
bannediplist.datatype = "string"
bannediplist.default = "/etc/e2guardian/lists/bannediplist"
exceptioniplist = s:taboption("tab_general", Value, "exceptioniplist", translate("List of IP exceptions"))
exceptioniplist.datatype = "string"
exceptioniplist.default = "/etc/e2guardian/lists/exceptioniplist"
perroomblockingdirectory = s:taboption("tab_general", Value, "perroomblockingdirectory", translate("Per-Room blocking definition directory"))
perroomblockingdirectory.datatype = "string"
perroomblockingdirectory.default = "/etc/e2guardian/lists/bannedrooms/"
showweightedfound = s:taboption("tab_general", ListValue, "showweightedfound", translate("Show weighted phrases found"))
showweightedfound:value("on", translate("Yes"))
showweightedfound:value("off", translate("No"))
showweightedfound.default = "on"
weightedphrasemode = s:taboption("tab_general", ListValue, "weightedphrasemode", translate("Weighted phrase mode"))
weightedphrasemode:value("0", translate("off"))
weightedphrasemode:value("1", translate("on, normal operation"))
weightedphrasemode:value("2", translate("on, phrase found only counts once on a page"))
weightedphrasemode.default = "2"
urlcachenumber = s:taboption("tab_general", Value, "urlcachenumber", translate("Clean result caching for URLs"))
urlcachenumber.datatype = "and(uinteger,min(0))"
urlcachenumber.default = "1000"
urlcacheage = s:taboption("tab_general", Value, "urlcacheage", translate("Age before they should be ignored in seconds"))
urlcacheage.datatype = "and(uinteger,min(0))"
urlcacheage.default = "900"
scancleancache = s:taboption("tab_general", ListValue, "scancleancache", translate("Cache for content (AV) scans as 'clean'"))
scancleancache:value("on", translate("Yes"))
scancleancache:value("off", translate("No"))
scancleancache.default = "on"
phrasefiltermode = s:taboption("tab_general", ListValue, "phrasefiltermode", translate("Filtering options"))
phrasefiltermode:value("0", translate("raw"))
phrasefiltermode:value("1", translate("smart"))
phrasefiltermode:value("2", translate("both raw and smart"))
phrasefiltermode:value("3", translate("meta/title"))
phrasefiltermode.default = "2"
preservecase = s:taboption("tab_general", ListValue, "perservecase", translate("Lower caseing options"))
preservecase:value("0", translate("force lower case"))
preservecase:value("1", translate("dont change"))
preservecase:value("2", translate("scan fist in lower, then in original"))
preservecase.default = "0"
hexdecodecontent = s:taboption("tab_general", ListValue, "hexdecodecontent", translate("Hex decoding options"))
hexdecodecontent:value("on", translate("Yes"))
hexdecodecontent:value("off", translate("No"))
hexdecodecontent.default = "off"
forcequicksearch = s:taboption("tab_general", ListValue, "forcequicksearch", translate("Quick search"))
forcequicksearch:value("on", translate("Yes"))
forcequicksearch:value("off", translate("No"))
forcequicksearch.default = "off"
reverseaddresslookups= s:taboption("tab_general", ListValue, "reverseaddresslookups", translate("Reverse lookups for banned site and URLs"))
reverseaddresslookups:value("on", translate("Yes"))
reverseaddresslookups:value("off", translate("No"))
reverseaddresslookups.default = "off"
reverseclientiplookups = s:taboption("tab_general", ListValue, "reverseclientiplookups", translate("Reverse lookups for banned and exception IP lists"))
reverseclientiplookups:value("on", translate("Yes"))
reverseclientiplookups:value("off", translate("No"))
reverseclientiplookups.default = "off"
logclienthostnames = s:taboption("tab_general", ListValue, "logclienthostnames", translate("Perform reverse lookups on client IPs for successful requests"))
logclienthostnames:value("on", translate("Yes"))
logclienthostnames:value("off", translate("No"))
logclienthostnames.default = "off"
createlistcachefiles = s:taboption("tab_general", ListValue, "createlistcachefiles", translate("Build bannedsitelist and bannedurllist cache files"))
createlistcachefiles:value("on",translate("Yes"))
createlistcachefiles:value("off",translate("No"))
createlistcachefiles.default = "on"
prefercachedlists = s:taboption("tab_general", ListValue, "prefercachedlists", translate("Prefer cached list files"))
prefercachedlists:value("on", translate("Yes"))
prefercachedlists:value("off", translate("No"))
prefercachedlists.default = "off"
maxuploadsize = s:taboption("tab_general", Value, "maxuploadsize", translate("Max upload size (in Kbytes)"))
maxuploadsize:value("-1", translate("no blocking"))
maxuploadsize:value("0", translate("complete block"))
maxuploadsize.default = "-1"
maxcontentfiltersize = s:taboption("tab_general", Value, "maxcontentfiltersize", translate("Max content filter size"),
translate("The value must not be higher than max content ram cache scan size or 0 to match it"))
maxcontentfiltersize.datatype = "and(uinteger,min(0))"
maxcontentfiltersize.default = "256"
maxcontentramcachescansize = s:taboption("tab_general", Value, "maxcontentramcachescansize", translate("Max content ram cache scan size"),
translate("This is the max size of file that DG will download and cache in RAM"))
maxcontentramcachescansize.datatype = "and(uinteger,min(0))"
maxcontentramcachescansize.default = "2000"
maxcontentfilecachescansize = s:taboption("tab_general", Value, "maxcontentfilecachescansize", translate("Max content file cache scan size"))
maxcontentfilecachescansize.datatype = "and(uinteger,min(0))"
maxcontentfilecachescansize.default = "20000"
proxytimeout = s:taboption("tab_general", Value, "proxytimeout", translate("Proxy timeout (5-100)"))
proxytimeout.datatype = "range(5,100)"
proxytimeout.default = "20"
proxyexchange = s:taboption("tab_general", Value, "proxyexchange", translate("Proxy header excahnge (20-300)"))
proxyexchange.datatype = "range(20,300)"
proxyexchange.default = "20"
pcontimeout = s:taboption("tab_general", Value, "pcontimeout", translate("Pconn timeout"),
translate("How long a persistent connection will wait for other requests"))
pcontimeout.datatype = "range(5,300)"
pcontimeout.default = "55"
filecachedir = s:taboption("tab_general", Value, "filecachedir", translate("File cache directory"))
filecachedir.datatype = "string"
filecachedir.default = "/tmp"
deletedownloadedtempfiles = s:taboption("tab_general", ListValue, "deletedownloadedtempfiles", translate("Delete file cache after user completes download"))
deletedownloadedtempfiles:value("on", translate("Yes"))
deletedownloadedtempfiles:value("off", translate("No"))
deletedownloadedtempfiles.default = "on"
initialtrickledelay = s:taboption("tab_general", Value, "initialtrickledelay", translate("Initial Trickle delay"),
translate("Number of seconds a browser connection is left waiting before first being sent *something* to keep it alive"))
initialtrickledelay.datatype = "and(uinteger,min(0))"
initialtrickledelay.default = "20"
trickledelay = s:taboption("tab_general", Value, "trickledelay", translate("Trickle delay"),
translate("Number of seconds a browser connection is left waiting before being sent more *something* to keep it alive"))
trickledelay.datatype = "and(uinteger,min(0))"
trickledelay.default = "10"
downloadmanager = s:taboption("tab_general", Value, "downloadmanager", translate("Download manager"))
downloadmanager.datatype = "string"
downloadmanager.default = "/etc/e2guardian/downloadmanagers/default.conf"
contentscannertimeout = s:taboption("tab_general", Value, "contentscannertimeout", translate("Content scanner timeout"))
contentscannertimeout.datatype = "and(uinteger,min(0))"
contentscannertimeout.default = "60"
contentscanexceptions = s:taboption("tab_general", ListValue, "contentscanexceptions", translate("Content scan exceptions"))
contentscanexceptions:value("on", translate("Yes"))
contentscanexceptions:value("off", translate("No"))
contentscanexceptions.default = "off"
recheckreplacedurls = s:taboption("tab_general", ListValue, "recheckreplacedurls", translate("e-check replaced URLs"))
recheckreplacedurls:value("on", translate("Yes"))
recheckreplacedurls:value("off", translate("No"))
recheckreplacedurls.default = "off"
forwardedfor = s:taboption("tab_general", ListValue, "forwardedfor", translate("Misc setting: forwardedfor"),
translate("If on, it may help solve some problem sites that need to know the source ip."))
forwardedfor:value("on", translate("Yes"))
forwardedfor:value("off", translate("No"))
forwardedfor.default = "off"
usexforwardedfor = s:taboption("tab_general", ListValue, "usexforwardedfor", translate("Misc setting: usexforwardedfor"),
translate("This is for when you have squid between the clients and E2Guardian"))
usexforwardedfor:value("on", translate("Yes"))
usexforwardedfor:value("off", translate("No"))
usexforwardedfor.default = "off"
logconnectionhandlingerrors = s:taboption("tab_general", ListValue, "logconnectionhandlingerrors", translate("Log debug info about log()ing and accept()ing"))
logconnectionhandlingerrors:value("on", translate("Yes"))
logconnectionhandlingerrors:value("off", translate("No"))
logconnectionhandlingerrors.default = "on"
logchildprocesshandling = s:taboption("tab_general", ListValue, "logchildprocesshandling", translate("Log child process handling"))
logchildprocesshandling:value("on", translate("Yes"))
logchildprocesshandling:value("off", translate("No"))
logchildprocesshandling.default = "off"
maxchildren = s:taboption("tab_general", Value, "maxchildren", translate("Max number of processes to spawn"))
maxchildren.datatype = "and(uinteger,min(0))"
maxchildren.default = "180"
minchildren = s:taboption("tab_general", Value, "minchildren", translate("Min number of processes to spawn"))
minchildren.datatype = "and(uinteger,min(0))"
minchildren.default = "20"
minsparechildren = s:taboption("tab_general", Value, "minsparechildren", translate("Min number of processes to keep ready"))
minsparechildren.datatype = "and(uinteger,min(0))"
minsparechildren.default = "16"
preforkchildren = s:taboption("tab_general", Value, "preforkchildren", translate("Sets minimum nuber of processes when it runs out"))
preforkchildren.datatype = "and(uinteger,min(0))"
preforkchildren.default = "10"
maxsparechildren = s:taboption("tab_general", Value, "maxsparechildren", translate("Sets the maximum number of processes to have doing nothing"))
maxsparechildren.datatype = "and(uinteger,min(0))"
maxsparechildren.default = "32"
maxagechildren = s:taboption("tab_general", Value, "maxagechildren", translate("Max age of child process"))
maxagechildren.datatype = "and(uinteger,min(0))"
maxagechildren.default = "500"
maxips = s:taboption("tab_general", Value, "maxips", translate("Max number of clinets allowed to connect"))
maxips:value("0", translate("no limit"))
maxips.default = "0"
ipipcfilename = s:taboption("tab_general", Value, "ipipcfilename", translate("IP list IPC server directory and filename"))
ipipcfilename.datatype = "string"
ipipcfilename.default = "/tmp/.dguardianipc"
urlipcfilename = s:taboption("tab_general", Value, "urlipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process"))
urlipcfilename.datatype = "string"
urlipcfilename.default = "/tmp/.dguardianurlipc"
ipcfilename = s:taboption("tab_general", Value, "ipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process"))
ipcfilename.datatype = "string"
ipcfilename.default = "/tmp/.dguardianipipc"
nodeamon = s:taboption("tab_general", ListValue, "nodeamon", translate("Disable deamoning"))
nodeamon:value("on", translate("Yes"))
nodeamon:value("off", translate("No"))
nodeamon.default = "off"
nologger = s:taboption("tab_general", ListValue, "nologger", translate("Disable logger"))
nologger:value("on", translate("Yes"))
nologger:value("off", translate("No"))
nologger.default = "off"
logadblock = s:taboption("tab_general", ListValue, "logadblock", translate("Enable logging of ADs"))
logadblock:value("on", translate("Yes"))
logadblock:value("off", translate("No"))
logadblock.default = "off"
loguseragent = s:taboption("tab_general", ListValue, "loguseragent", translate("Enable logging of client user agent"))
loguseragent:value("on", translate("Yes"))
loguseragent:value("off", translate("No"))
loguseragent.default = "off"
softrestart = s:taboption("tab_general", ListValue, "softrestart", translate("Enable soft restart"))
softrestart:value("on", translate("Yes"))
softrestart:value("off", translate("No"))
softrestart.default = "off"
------------------------ Additional Settings Tab ----------------------------
e2guardian_config_file = s:taboption("tab_additional", TextValue, "_data", "")
e2guardian_config_file.wrap = "off"
e2guardian_config_file.rows = 25
e2guardian_config_file.rmempty = false
function e2guardian_config_file.cfgvalue()
local uci = require "luci.model.uci".cursor_state()
file = "/etc/e2guardian/e2guardianf1.conf"
if file then
return fs.readfile(file) or ""
else
return ""
end
end
function e2guardian_config_file.write(self, section, value)
if value then
local uci = require "luci.model.uci".cursor_state()
file = "/etc/e2guardian/e2guardianf1.conf"
fs.writefile(file, value:gsub("\r\n", "\n"))
end
end
---------------------------- Logs Tab -----------------------------
e2guardian_logfile = s:taboption("tab_logs", TextValue, "lines", "")
e2guardian_logfile.wrap = "off"
e2guardian_logfile.rows = 25
e2guardian_logfile.rmempty = true
function e2guardian_logfile.cfgvalue()
local uci = require "luci.model.uci".cursor_state()
file = "/tmp/e2guardian/access.log"
if file then
return fs.readfile(file) or ""
else
return "Can't read log file"
end
end
function e2guardian_logfile.write()
return ""
end
return m
| gpl-2.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_base/cl_init.lua | 1 | 6624 | include("shared.lua")
include("animations.lua")
SWEP.DrawAmmo = true
SWEP.DrawCrosshair = false
SWEP.ViewModelFOV = 60
SWEP.ViewModelFlip = true
SWEP.BobScale = 1.5
SWEP.SwayScale = 1.5
SWEP.Slot = 0
SWEP.IronsightsMultiplier = 0.6
SWEP.HUD3DScale = 0.01
SWEP.HUD3DBone = "base"
SWEP.HUD3DAng = Angle(180, 0, 0)
function SWEP:Deploy()
return true
end
function SWEP:TranslateFOV(fov)
return GAMEMODE.FOVLerp * fov
end
function SWEP:AdjustMouseSensitivity()
if self:GetIronsights() then return GAMEMODE.FOVLerp end
end
function SWEP:ViewModelDrawn()
self:Anim_ViewModelDrawn()
if not self.HUD3DPos or GAMEMODE.WeaponHUDMode == 1 then return end
local vm = self.Owner and self.Owner:IsValid() and self.Owner:GetViewModel()
if not IsValid(vm) then return end
local pos, ang = self:GetHUD3DPos(vm)
if pos then
self:Draw3DHUD(vm, pos, ang)
end
end
function SWEP:DrawWorldModel()
local owner = self:GetOwner()
if owner:IsValid() and owner.ShadowMan then return end
self:Anim_DrawWorldModel()
end
function SWEP:GetHUD3DPos(vm)
local bone = vm:LookupBone(self.HUD3DBone)
if not bone then return end
local m = vm:GetBoneMatrix(bone)
if not m then return end
local pos, ang = m:GetTranslation(), m:GetAngles()
if self.ViewModelFlip then
ang.r = -ang.r
end
local offset = self.HUD3DPos
local aoffset = self.HUD3DAng
pos = pos + ang:Forward() * offset.x + ang:Right() * offset.y + ang:Up() * offset.z
if aoffset.yaw ~= 0 then ang:RotateAroundAxis(ang:Up(), aoffset.yaw) end
if aoffset.pitch ~= 0 then ang:RotateAroundAxis(ang:Right(), aoffset.pitch) end
if aoffset.roll ~= 0 then ang:RotateAroundAxis(ang:Forward(), aoffset.roll) end
return pos, ang
end
local colBG = Color(16, 16, 16, 90)
local colRed = Color(220, 0, 0, 230)
local colYellow = Color(220, 220, 0, 230)
local colWhite = Color(220, 220, 220, 230)
function SWEP:Draw3DHUD(vm, pos, ang)
local wid, hei = 64, 100
local x, y = wid * -0.5, hei * -0.5
local clip = self:Clip1()
local spare = self.Owner:GetAmmoCount(self:GetPrimaryAmmoType())
local maxclip = self.Primary.ClipSize
cam.Start3D2D(pos, ang, self.HUD3DScale)
draw.RoundedBoxEx(16, x, y, wid, hei, colBG, true, false, true, false)
if maxclip > 0 then
draw.SimpleText(spare, spare >= 1000 and "ZS3D2DFontSmall" or "ZS3D2DFont", x + wid * 0.5, y + hei * 0.75, spare == 0 and colRed or spare <= maxclip and colYellow or colWhite, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText(clip, clip >= 100 and "ZS3D2DFont" or "ZS3D2DFontBig", x + wid * 0.5, y + hei * 0.3, clip == 0 and colRed or clip < maxclip / 2 and colYellow or colWhite, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
else
draw.SimpleText(clip, clip >= 100 and "ZS3D2DFont" or "ZS3D2DFontBig", x + wid * 0.5, y + hei * 0.5, clip == 0 and colRed or clip < maxclip / 2 and colYellow or colWhite, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
cam.End3D2D()
end
function SWEP:Draw2DHUD()
local screenscale = BetterScreenScale()
local wid, hei = 180 * screenscale, 64 * screenscale
local x, y = ScrW() - wid - screenscale * 128, ScrH() - hei - screenscale * 72
local clip = self:Clip1()
local spare = self.Owner:GetAmmoCount(self:GetPrimaryAmmoType())
local maxclip = self.Primary.ClipSize
draw.RoundedBox(16, x, y, wid, hei, colBG)
if maxclip > 0 then
draw.SimpleText(spare, spare >= 1000 and "ZSHUDFontSmall" or "ZSHUDFont", x + wid * 0.75, y + hei * 0.5, spare == 0 and colRed or spare <= maxclip and colYellow or colWhite, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
draw.SimpleText(clip, clip >= 100 and "ZSHUDFont" or "ZSHUDFontBig", x + wid * 0.25, y + hei * 0.5, clip == 0 and colRed or clip < maxclip / 2 and colYellow or colWhite, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
else
draw.SimpleText(clip, clip >= 100 and "ZSHUDFont" or "ZSHUDFontBig", x + wid * 0.5, y + hei * 0.5, clip == 0 and colRed or clip < maxclip / 2 and colYellow or colWhite, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
end
end
function SWEP:OnRemove()
self:Anim_OnRemove()
end
function SWEP:GetIronsightsDeltaMultiplier()
local bIron = self:GetIronsights()
local fIronTime = self.fIronTime or 0
if not bIron and fIronTime < CurTime() - 0.25 then
return 0
end
local Mul = 1
if fIronTime > CurTime() - 0.25 then
Mul = math.Clamp((CurTime() - fIronTime) * 4, 0, 1)
if not bIron then Mul = 1 - Mul end
end
return Mul
end
local ghostlerp = 0
function SWEP:GetViewModelPosition(pos, ang)
local bIron = self:GetIronsights()
if bIron ~= self.bLastIron then
self.bLastIron = bIron
self.fIronTime = CurTime()
if bIron then
self.SwayScale = 0.3
self.BobScale = 0.1
else
self.SwayScale = 2.0
self.BobScale = 1.5
end
end
local Mul = math.Clamp((CurTime() - (self.fIronTime or 0)) * 4, 0, 1)
if not bIron then Mul = 1 - Mul end
if Mul > 0 then
local Offset = self.IronSightsPos
if self.IronSightsAng then
ang = Angle(ang.p, ang.y, ang.r)
ang:RotateAroundAxis(ang:Right(), self.IronSightsAng.x * Mul)
ang:RotateAroundAxis(ang:Up(), self.IronSightsAng.y * Mul)
ang:RotateAroundAxis(ang:Forward(), self.IronSightsAng.z * Mul)
end
pos = pos + Offset.x * Mul * ang:Right() + Offset.y * Mul * ang:Forward() + Offset.z * Mul * ang:Up()
end
if self.Owner:GetBarricadeGhosting() then
ghostlerp = math.min(1, ghostlerp + FrameTime() * 4)
elseif ghostlerp > 0 then
ghostlerp = math.max(0, ghostlerp - FrameTime() * 5)
end
if ghostlerp > 0 then
pos = pos + 3.5 * ghostlerp * ang:Up()
ang:RotateAroundAxis(ang:Right(), -30 * ghostlerp)
end
return pos, ang
end
function SWEP:DrawWeaponSelection(...)
return self:BaseDrawWeaponSelection(...)
end
function SWEP:DrawHUD()
self:DrawCrosshair()
if GAMEMODE.WeaponHUDMode >= 1 then
self:Draw2DHUD()
end
end
local OverrideIronSights = {}
function SWEP:CheckCustomIronSights()
local class = self:GetClass()
if OverrideIronSights[class] then
if type(OverrideIronSights[class]) == "table" then
self.IronSightsPos = OverrideIronSights[class].Pos
self.IronSightsAng = OverrideIronSights[class].Ang
end
return
end
local filename = "ironsights/"..class..".txt"
if file.Exists(filename, "MOD") then
local pos = Vector(0, 0, 0)
local ang = Vector(0, 0, 0)
local tab = string.Explode(" ", file.Read(filename, "MOD"))
pos.x = tonumber(tab[1]) or 0
pos.y = tonumber(tab[2]) or 0
pos.z = tonumber(tab[3]) or 0
ang.x = tonumber(tab[4]) or 0
ang.y = tonumber(tab[5]) or 0
ang.z = tonumber(tab[6]) or 0
OverrideIronSights[class] = {Pos = pos, Ang = ang}
self.IronSightsPos = pos
self.IronSightsAng = ang
else
OverrideIronSights[class] = true
end
end
| gpl-3.0 |
matin-igdery/og | plugins/stats.lua | 4 | 4003 | do
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'Infernal' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /InfernalTG ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' then
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(chat_id)
else
return
end
end
if matches[2] == "InfernalTG" then -- Put everything you like :)
if not is_sudo(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[!/]([Ss]tats)$",
"^[!/]([Ss]tatslist)$",
"^[!/]([Ss]tats) (group) (%d+)",
"^[!/]([Ss]tats) (InfernalTG)",-- Put everything you like :)
"^[!/](Infernal)"-- Put everything you like :)
},
run = run
}
end
| gpl-2.0 |
joostlek/Cryonite | otouto/bindings.lua | 1 | 2245 | --[[
bindings.lua (rev. 2016/05/28)
otouto's bindings for the Telegram bot API.
https://core.telegram.org/bots/api
Copyright 2016 topkecleon. Published under the AGPLv3.
See the "Bindings" section of README.md for usage information.
]]--
local bindings = {}
local HTTPS = require('ssl.https')
local JSON = require('dkjson')
local ltn12 = require('ltn12')
local MP_ENCODE = require('multipart-post').encode
-- Build and send a request to the API.
-- Expecting self, method, and parameters, where method is a string indicating
-- the API method and parameters is a key/value table of parameters with their
-- values.
-- Returns the table response with success. Returns false and the table
-- response with failure. Returns false and false with a connection error.
-- To mimic old/normal behavior, it errs if used with an invalid method.
function bindings:request(method, parameters, file)
parameters = parameters or {}
for k,v in pairs(parameters) do
parameters[k] = tostring(v)
end
if file and next(file) ~= nil then
local file_type, file_name = next(file)
local file_file = io.open(file_name, 'r')
local file_data = {
filename = file_name,
data = file_file:read('*a')
}
file_file:close()
parameters[file_type] = file_data
end
if next(parameters) == nil then
parameters = {''}
end
local response = {}
local body, boundary = MP_ENCODE(parameters)
local success = HTTPS.request{
url = self.BASE_URL .. method,
method = 'POST',
headers = {
["Content-Type"] = "multipart/form-data; boundary=" .. boundary,
["Content-Length"] = #body,
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response)
}
local data = table.concat(response)
if not success then
print(method .. ': Connection error.')
return false, false
else
local result = JSON.decode(data)
if not result then
return false, false
elseif result.ok then
return result
else
assert(result.description ~= 'Method not found', method .. ': Method not found.')
return false, result
end
end
end
function bindings.gen(_, key)
return function(self, params, file)
return bindings.request(self, key, params, file)
end
end
setmetatable(bindings, { __index = bindings.gen })
return bindings
| agpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Mhaura/npcs/Blandine.lua | 1 | 2178 | -----------------------------------
-- Area: Mhaura
-- NPC: Blandine
-- Start Quest: The Sand Charm
-- @zone 249
-- @pos 23 -7 41
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
X = player:getXPos(); Z = player:getZPos();
TheSandCharm = player:getQuestStatus(OTHER_AREAS,THE_SAND_CHARM);
if(Z <= 29 or Z >= 38 or X <= 16 or X >= 32) then
if(player:getFameLevel(WINDURST) >= 4 and TheSandCharm == QUEST_AVAILABLE) then
player:startEvent(0x007d); -- Start quest "The Sand Charm"
elseif(player:getVar("theSandCharmVar") == 2) then
player:startEvent(0x007c); -- During quest "The Sand Charm" - 2nd dialog
elseif(TheSandCharm == QUEST_COMPLETED and player:getVar("SmallDialogByBlandine") == 1) then
player:startEvent(0x0080); -- Thanks dialog of Bladine after "The Sand Charm"
elseif(TheSandCharm == QUEST_COMPLETED) then
player:startEvent(0x0081); -- New standard dialog after "The Sand Charm"
else
player:startEvent(0x007a); -- Standard dialog
end
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 == 0x007d) then
player:addQuest(OTHER_AREAS,THE_SAND_CHARM);
player:setVar("theSandCharmVar",1);
elseif(csid == 0x007c) then
player:setVar("theSandCharmVar",3);
elseif(csid == 0x0080) then
player:setVar("SmallDialogByBlandine",0);
end
end;
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Agent/AgentWorld.lua | 1 | 6460 | --[[
Title: Agent World
Author(s): LiXizhi
Date: 2021/3/8
Desc: a simulated world in memory, in which we can add code blocks and movie block.
Entities from agent world are created into the real world, however, the agent world itself does not take any real world space.
We can load agent world from agent file (template file).
This is also base class for a virtual BlockEngine.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Agent/AgentWorld.lua");
local AgentWorld = commonlib.gettable("MyCompany.Aries.Game.Agent.AgentWorld");
local world = AgentWorld:new():Init("Mod/Agents/MacroPlatform.xml");
local world = AgentWorld:new():Init();
world:Run()
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Agent/AgentEntityCode.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Agent/AgentEntityMovieClip.lua");
local AgentEntityCode = commonlib.gettable("MyCompany.Aries.Game.EntityManager.AgentEntityCode");
local AgentEntityMovieClip = commonlib.gettable("MyCompany.Aries.Game.EntityManager.AgentEntityMovieClip");
local EntityCode = commonlib.gettable("MyCompany.Aries.Game.EntityManager.EntityCode")
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local AgentWorld = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), commonlib.gettable("MyCompany.Aries.Game.Agent.AgentWorld"));
AgentWorld:Property({"centerPos", {0,0,0}, "GetCenterPosition", "SetCenterPosition", auto=true});
function AgentWorld:ctor()
self.blocks = {};
self.codeblocks = {};
self.codeblockNames = {}; -- container of code block entity that does not have coordinates.
self:SetCenterPosition({0, 0, 0})
end
function AgentWorld:Clear()
for _, b in ipairs(self.codeblocks) do
local entityCode = b.blockEntity;
if(entityCode) then
entityCode:Stop();
end
end
for _, entity in pairs(self.codeblockNames) do
local codeblock = entity:GetCodeBlock()
if(codeblock and codeblock:IsLoaded()) then
codeblock:Stop();
end
end
self.blocks = {};
self.codeblocks = {};
self.codeblockNames = {};
end
-- @param filename: block template file name, it can be nil for empty world
function AgentWorld:Init(filename)
GameLogic:Connect("WorldUnloaded", self, self.OnWorldUnload, "UniqueConnection");
if(filename) then
self:LoadFromAgentFile(filename);
end
return self;
end
function AgentWorld:GetSparseIndex(x, y, z)
return y*900000000+x*30000+z;
end
-- convert from sparse index to block x,y,z
-- @return x,y,z
function AgentWorld:FromSparseIndex(index)
local x, y, z;
y = math.floor(index / (900000000));
index = index - y*900000000;
x = math.floor(index / (30000));
z = index - x*30000;
return x,y,z;
end
-- @param filename: agent xml or bmax or block template file.
-- @param cx, cy, cz: center position where the entities in the agent world are created into the real world. default to 0.
function AgentWorld:LoadFromAgentFile(filename, cx, cy, cz)
self:SetCenterPosition({cx or 0, cy or 0, cz or 0})
local blocks = self.blocks;
local xmlRoot = ParaXML.LuaXML_ParseFile(filename);
if(xmlRoot) then
local root_node = commonlib.XPath.selectNode(xmlRoot, "/pe:blocktemplate");
if(root_node) then
local px, py, pz = 0, 0, 0;
if(root_node.attr and root_node.attr.pivot) then
px, py, pz = root_node.attr.pivot:match("^(%d+)%D(%d+)%D(%d+)")
px, py, pz = tonumber(px), tonumber(py), tonumber(pz)
end
local node = commonlib.XPath.selectNode(root_node, "/pe:blocks");
if(node and node[1]) then
local blocks_ = NPL.LoadTableFromString(node[1]);
if(blocks_ and #blocks_>=1) then
for _, b in ipairs(blocks_) do
local blockId = b[4];
local x, y, z = px + b[1], py + b[2], pz + b[3]
blocks[self:GetSparseIndex(x, y, z)] = b;
if(blockId == block_types.names.CodeBlock) then
local entity = AgentEntityCode:new();
entity:LoadFromXMLNode(b[6])
entity:SetBlockEngine(self);
b.blockEntity = entity;
local attr = b[6] and b[6].attr;
if(attr) then
if(attr.isPowered == true or attr.isPowered == "true") then
self.codeblocks[#(self.codeblocks) + 1] = b;
end
end
elseif(blockId == block_types.names.MovieClip) then
local entity = AgentEntityMovieClip:new();
entity:LoadFromXMLNode(b[6])
b.blockEntity = entity;
end
end
end
end
end
else
LOG.std(nil, "warn", "AgentWorld", "failed to load template from file: %s", filename or "");
end
end
-- simulate a BlockEngine interface
function AgentWorld:GetBlock(x, y, z)
local blockId = self:GetBlockId(x, y, z)
if(blockId) then
return block_types.get(blockId);
end
end
function AgentWorld:GetBlockId(x, y, z)
if(x) then
local index = self:GetSparseIndex(x, y, z)
local b = self.blocks[index]
if(b) then
return b[4];
end
end
end
function AgentWorld:GetBlockData(x, y, z)
if(x) then
local index = self:GetSparseIndex(x, y, z)
local b = self.blocks[index]
if(b) then
return b[5];
end
end
end
function AgentWorld:SetBlockData(x, y, z, data)
-- dummy
end
function AgentWorld:GetBlockEntity(x, y, z)
local index = self:GetSparseIndex(x, y, z)
local b = self.blocks[index]
if(b) then
return b.blockEntity;
end
end
function AgentWorld:NotifyNeighborBlocksChange(x, y, z, blockId)
end
function AgentWorld:Reset()
self:Clear();
end
function AgentWorld:Destroy()
self:Clear()
AgentWorld._super.Destroy(self);
end
-- run all code blocks in the agent world
function AgentWorld:Run()
for _, b in ipairs(self.codeblocks) do
local entityCode = b.blockEntity;
if(entityCode) then
entityCode:SetPowered(true);
end
end
end
function AgentWorld:OnWorldUnload()
-- unload virtual entities and free memory
self:Clear()
end
--@param name: if nil, we will always create an unnamed empty code entity
function AgentWorld:CreateGetCodeEntity(name)
local entity = name and self.codeblockNames[name];
if(not entity) then
entity = AgentEntityCode:new();
entity:SetBlockEngine(self);
entity:SetAllowFastMode(true);
if(name) then
self.codeblockNames[name] = entity;
end
end
return entity;
end
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Movie/BoneController.lua | 1 | 2717 | --[[
Title: Bone controllers
Author(s): LiXizhi
Date: 2015/9/25
Desc: Bone controllers are transforms vectors into multiple bones's parameters, it is mostly used in facial expression.
Controllers in animation files(such as bmax, fbx, x) can be specified in an xml file using same model filename.
for example, if model file is test.bmax, then we will automatically look for test.bmax.xml for controller file.
---++ controller meta file format
<verbatim>
the meta file may contains other informations, so the controller section should be at xpath "mesh/controller"
<mesh>
<controllers>
<controller name="mouth">
<input type="vector2" min_value="-1" max_value="1">
<output bone="upper_lip_trans" converter="">
<converter>
output[2]=input[2]*0.02;output[3]=input[1]*0.02;
</converter>
</output>
<output bone="lower_lip_trans" converter="output[2]=input[2]*0.02"/>
</input>
</controller>
</controllers>
</mesh>
</verbatim>
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/BoneController.lua");
local BoneController = commonlib.gettable("MyCompany.Aries.Game.Movie.BoneController");
BoneController.ShowPage()
-------------------------------------------------------
]]
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local BoneController = commonlib.inherit(commonlib.gettable("System.Core.ToolBase"), commonlib.gettable("MyCompany.Aries.Game.Movie.BoneController"));
function BoneController:ctor()
end
local page;
function BoneController.OnInit()
page = document:GetPageCtrl();
end
-- @param OnClose: function(values) end
-- @param last_values: {text, ...}
function BoneController.ShowPage()
BoneController:InitSingleton();
local params = {
url = "script/apps/Aries/Creator/Game/Movie/BoneController.html",
name = "BoneController.ShowPage",
isShowTitleBar = false,
DestroyOnClose = true,
bToggleShowHide=false,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
click_through = false,
enable_esc_key = true,
bShow = true,
isTopLevel = true,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_rt",
x = -10,
y = 50,
width = 200,
height = 400,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
-- @param filename: the x, fbx, or parax file name or the meta file
function BoneController:LoadFromFile(filename)
if(filename:match("%s+$") ~= "xml") then
filename = filename..".xml";
end
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/birth/sexes.lua | 3 | 1173 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- Player sexes
newBirthDescriptor{
type = "sex",
name = "Female",
desc =
{
"You are a female of the species.",
"There is no in-game difference between the two sexes.",
},
copy = { female=true, },
}
newBirthDescriptor{
type = "sex",
name = "Male",
desc =
{
"You are a male of the species.",
"There is no in-game difference between the two sexes.",
},
copy = { male=true, },
}
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/NplBrowser/NplBrowserLoaderPage.lua | 1 | 14284 | --[[
Title: NplBrowserLoaderPage
Author(s): leio
Date: 2019.3.26
Desc:
This is a background loader to download the resources of cefclient.exe automatically.
Deployed on cdn server, the resources are download by AssetsManager which is configured by configs/nplbrowser.xml.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserLoaderPage.lua");
local NplBrowserLoaderPage = commonlib.gettable("NplBrowser.NplBrowserLoaderPage");
NplBrowserLoaderPage.CheckOnce()
NplBrowserLoaderPage.Check(callback)
------------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Login/BuildinMod.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserPlugin.lua");
NPL.load("(gl)script/ide/timer.lua");
local BuildinMod = commonlib.gettable("MyCompany.Aries.Game.MainLogin.BuildinMod");
local AssetsManager = NPL.load("AutoUpdater");
local NplBrowserPlugin = commonlib.gettable("NplBrowser.NplBrowserPlugin");
local NplBrowserLoaderPage = commonlib.gettable("NplBrowser.NplBrowserLoaderPage");
NPL.load("(gl)script/Github/GitReleaseUpdater.lua");
NplBrowserLoaderPage.cef_main_files = {
"cefclient.exe",
"NplCefPlugin.dll",
"libcef.dll",
"cef.pak",
}
NplBrowserLoaderPage.loaded = false;
NplBrowserLoaderPage.timer = nil;
NplBrowserLoaderPage.try_update_max_times = 3;
NplBrowserLoaderPage.try_times = 0;
NplBrowserLoaderPage.callback_maps = {};
local dest_folder = "cef3";
local config_file = "script/apps/Aries/Creator/Game/NplBrowser/configs/nplbrowser.xml";
local page;
-- init function. page script fresh is set to false.
function NplBrowserLoaderPage.OnInit()
page = document:GetPageCtrl();
end
function NplBrowserLoaderPage.ShowPage()
local width, height=400, 50;
System.App.Commands.Call("File.MCMLWindowFrame", {
url = "script/apps/Aries/Creator/Game/NplBrowser/NplBrowserLoaderPage.html",
name = "NplBrowserLoaderPage.ShowPage",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 10,
allowDrag = false,
isTopLevel = false,
directPosition = true,
align = "_lt",
x = 5,
y = 40,
width = width,
height = height,
cancelShowAnimation = true,
});
end
function NplBrowserLoaderPage.UpdateProgressText(text)
if(page) then
page:SetValue("progressText", text)
end
end
function NplBrowserLoaderPage.Close()
if(page) then
page:CloseWindow();
page = nil;
end
end
function NplBrowserLoaderPage.CreateOrGetAssetsManager(id,redist_root,config_file)
if(not id)then return end
local a = NplBrowserLoaderPage.asset_manager;
if(not a)then
a = AssetsManager:new();
local timer;
if(redist_root and config_file)then
a:onInit(redist_root,config_file,function(state)
if(state)then
if(state == AssetsManager.State.PREDOWNLOAD_VERSION)then
NplBrowserLoaderPage.UpdateProgressText(L"准备下载版本号");
elseif(state == AssetsManager.State.DOWNLOADING_VERSION)then
NplBrowserLoaderPage.UpdateProgressText(L"下载版本号");
elseif(state == AssetsManager.State.VERSION_CHECKED)then
NplBrowserLoaderPage.UpdateProgressText(L"检测版本号");
elseif(state == AssetsManager.State.VERSION_ERROR)then
NplBrowserLoaderPage.UpdateProgressText(L"版本号错误");
elseif(state == AssetsManager.State.PREDOWNLOAD_MANIFEST)then
NplBrowserLoaderPage.UpdateProgressText(L"准备下载文件列表");
elseif(state == AssetsManager.State.DOWNLOADING_MANIFEST)then
NplBrowserLoaderPage.UpdateProgressText(L"下载文件列表");
elseif(state == AssetsManager.State.MANIFEST_DOWNLOADED)then
NplBrowserLoaderPage.UpdateProgressText(L"下载文件列表完成");
elseif(state == AssetsManager.State.MANIFEST_ERROR)then
NplBrowserLoaderPage.UpdateProgressText(L"下载文件列表错误");
elseif(state == AssetsManager.State.PREDOWNLOAD_ASSETS)then
NplBrowserLoaderPage.UpdateProgressText(L"准备下载资源文件");
local nowTime = 0
local lastTime = 0
local interval = 100
local lastDownloadedSize = 0
timer = commonlib.Timer:new({callbackFunc = function(timer)
local p = a:getPercent();
p = math.floor(p * 100);
NplBrowserLoaderPage.ShowPercent(p);
local totalSize = a:getTotalSize()
local downloadedSize = a:getDownloadedSize()
nowTime = nowTime + interval
if downloadedSize > lastDownloadedSize then
local downloadSpeed = (downloadedSize - lastDownloadedSize) / ((nowTime - lastTime) / 1000)
lastDownloadedSize = downloadedSize
lastTime = nowTime
local tips = string.format("%.1f/%.1fMB(%.1fKB/S)", downloadedSize / 1024 / 1024, totalSize / 1024 / 1024, downloadSpeed / 1024)
NplBrowserLoaderPage.UpdateProgressText(tips)
end
end})
timer:Change(0, interval)
elseif(state == AssetsManager.State.DOWNLOADING_ASSETS)then
elseif(state == AssetsManager.State.ASSETS_DOWNLOADED)then
NplBrowserLoaderPage.UpdateProgressText(L"下载资源文件结束");
local p = a:getPercent();
p = math.floor(p * 100);
NplBrowserLoaderPage.ShowPercent(p);
if(timer)then
timer:Change();
NplBrowserLoaderPage.LastDownloadedSize = 0
end
a:apply();
elseif(state == AssetsManager.State.ASSETS_ERROR)then
NplBrowserLoaderPage.UpdateProgressText(L"下载资源文件错误");
elseif(state == AssetsManager.State.PREUPDATE)then
NplBrowserLoaderPage.UpdateProgressText(L"准备更新");
elseif(state == AssetsManager.State.UPDATING)then
NplBrowserLoaderPage.UpdateProgressText(L"更新中");
elseif(state == AssetsManager.State.UPDATED)then
if(not NplBrowserLoaderPage.MainFilesExisted(redist_root))then
NplBrowserLoaderPage.UpdateProgressText(L"更新错误");
local mytimer = commonlib.Timer:new({callbackFunc = function(timer)
NplBrowserLoaderPage.SetChecked(false);
end})
mytimer:Change(3000, nil)
else
LOG.std(nil, "debug", "AppLauncher", "更新完成")
NplBrowserLoaderPage.UpdateProgressText(L"更新完成");
NplBrowserLoaderPage.SetChecked(true);
end
elseif(state == AssetsManager.State.FAIL_TO_UPDATED)then
NplBrowserLoaderPage.UpdateProgressText(L"更新错误");
local mytimer = commonlib.Timer:new({callbackFunc = function(timer)
NplBrowserLoaderPage.SetChecked(false);
end})
mytimer:Change(3000, nil)
end
end
end, function (dest, cur, total)
NplBrowserLoaderPage.OnMovingFileCallback(dest, cur, total)
end);
end
NplBrowserLoaderPage.asset_manager = a;
end
return a;
end
function NplBrowserLoaderPage.CheckOnce()
if(not NplBrowserLoaderPage.isCheckOnce) then
NplBrowserLoaderPage.Check()
end
end
-- @param callback: function(bChecked) end, bChecked is true if successfully downloaded
-- return true if we are downloading
function NplBrowserLoaderPage.Check(callback)
local IsTouchDevice = ParaEngine.GetAppCommandLineByParam('IsTouchDevice', nil)
if (IsTouchDevice == "true") then
return;
end
if(not NplBrowserLoaderPage.isCheckOnce) then
NplBrowserLoaderPage.isCheckOnce = true;
end
if(not NplBrowserPlugin.OsSupported())then
LOG.std(nil, "info", "NplBrowserLoaderPage.OnCheck", "npl browser isn't supported on %s",System.os.GetPlatform());
return
end
if (System.os.GetPlatform() == "mac" or System.os.GetPlatform() == 'ios')then
NplBrowserLoaderPage.loaded = true;
if (type(callback) == "function") then
callback(true);
end
return not NplBrowserLoaderPage.IsLoaded();
end
if(not NplBrowserLoaderPage.MainFilesExisted(dest_folder))then
NplBrowserLoaderPage.loaded = false;
end
if(NplBrowserLoaderPage.try_times >= NplBrowserLoaderPage.try_update_max_times)then
LOG.std(nil, "warn", "NplBrowserLoaderPage.OnCheck", "try update times is full:%d/%d",NplBrowserLoaderPage.try_times,NplBrowserLoaderPage.try_update_max_times);
return
end
if(NplBrowserLoaderPage.loaded)then
if(callback)then
callback(true);
end
return
end
if(callback)then
NplBrowserLoaderPage.callback_maps[callback] = true;
end
if(NplBrowserLoaderPage.is_opened)then
return not NplBrowserLoaderPage.IsLoaded();
end
local mod = BuildinMod.GetModByName("NplBrowser") or {};
local version = mod.version;
NplBrowserLoaderPage.is_opened = true;
NplBrowserLoaderPage.buildin_version = version;
NplBrowserLoaderPage.OnCheck("browser_asset_manager",dest_folder,config_file)
return not NplBrowserLoaderPage.IsLoaded();
end
function NplBrowserLoaderPage.OnCheck(id,folder,config_file)
if(not id or not folder or not config_file)then return end
local redist_root = folder .. "/"
ParaIO.CreateDirectory(redist_root);
local a = NplBrowserLoaderPage.CreateOrGetAssetsManager(id,redist_root,config_file);
if(not a)then return end
if(NplBrowserLoaderPage.buildin_version)then
a:loadLocalVersion()
local cur_version = a:getCurVersion();
local buildin_version = NplBrowserLoaderPage.buildin_version;
local cur_version_value = AssetsManager.getVersionNumberValue(cur_version);
local buildin_version_value = AssetsManager.getVersionNumberValue(buildin_version);
if(cur_version_value >= buildin_version_value)then
NplBrowserLoaderPage.SetChecked(true);
LOG.std(nil, "info", "NplBrowserLoaderPage.OnCheck", "local version is:%s, buildin version is %s, because of %s >= %s ,remote version check skipped",cur_version,buildin_version,cur_version,buildin_version);
return
end
end
NplBrowserLoaderPage.ShowPage();
NplBrowserLoaderPage.ShowPercent(0);
NplBrowserLoaderPage.try_times = NplBrowserLoaderPage.try_times + 1;
LOG.std(nil, "warn", "NplBrowserLoaderPage.OnCheck", "try update times:%d",NplBrowserLoaderPage.try_times);
a:check(nil,function()
local cur_version = a:getCurVersion();
local latest_version = a:getLatestVersion();
if(a:isNeedUpdate())then
NplBrowserLoaderPage.UpdateProgressText(string.format(L"当前版本(%s) 最新版本(%s)",cur_version, latest_version));
local mytimer = commonlib.Timer:new({callbackFunc = function(timer)
a:download();
end})
mytimer:Change(3000, nil)
else
NplBrowserLoaderPage.SetChecked(true);
end
end);
end
function NplBrowserLoaderPage.ShowPercent()
end
function NplBrowserLoaderPage.OnMovingFileCallback(dest, cur, total)
local tips = string.format(L"更新%s (%d/%d)", dest, cur, total)
NplBrowserLoaderPage.UpdateProgressText(tips)
local percent = 100 * cur / total
NplBrowserLoaderPage.ShowPercent(percent)
end
function NplBrowserLoaderPage.SetChecked(v)
NplBrowserLoaderPage.loaded = v;
if(v)then
-- LOG.std(nil, "info", "NplBrowserLoaderPage", "NplBrowser is loaded");
-- local NplBrowserManager = NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserManager.lua");
-- NplBrowserManager:LoadAllPreShowWindows();
end
for callback,v in pairs(NplBrowserLoaderPage.callback_maps) do
callback(v)
end
NplBrowserLoaderPage.callback_maps = {};
NplBrowserLoaderPage.Close();
NplBrowserLoaderPage.is_opened = false;
NplBrowserLoaderPage.asset_manager = nil;
end
function NplBrowserLoaderPage.IsLoaded()
if (System.os.GetPlatform() == 'mac' or
-- System.os.GetPlatform() == 'android' or
System.os.GetPlatform() == 'ios' ) then
return true;
end
return NplBrowserLoaderPage.loaded;
end
-- check if main files are existed, if found anyone isn't exited, the version file will be deleted for running auto update again
function NplBrowserLoaderPage.MainFilesExisted(redist_root)
for k,name in ipairs (NplBrowserLoaderPage.cef_main_files) do
local filename = string.format("%s/%s",redist_root, name);
if(not ParaIO.DoesFileExist(filename))then
LOG.std(nil, "error", "NplBrowserLoaderPage.MainFilesExisted", "the file isn't existed:%s",filename);
local version_filename = string.format("%s/%s",redist_root, AssetsManager.defaultVersionFilename);
ParaIO.DeleteFile(version_filename);
LOG.std(nil, "warn", "NplBrowserLoaderPage.MainFilesExisted", "delete the version file for running auto update again:%s",version_filename);
return false;
end
end
return true;
end | gpl-2.0 |
pakoito/ToME---t-engine4 | game/engines/default/engine/MapEffect.lua | 3 | 1100 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Entity = require "engine.Entity"
--- Describes a trap
module(..., package.seeall, class.inherit(Entity))
_M.display_on_seen = true
_M._no_save_fields.effect_shader_tex = true
function _M:init(t, no_default)
t.alpha = t.alpha or 100
t.display = t.display or ''
Entity.init(self, t, no_default)
end
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/shertul_fortress_engine.lua | 3 | 1407 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local radius = radius or 1
dir = 90
use_shader = {type="distort", power=0.06, power_time=1000, blacken=30} alterscreen = true
base_size = 64
local life=50
return {
system_rotation = dir, system_rotationv = 0,
generator = function()
return {
trail = 0,
life = life or 32,
size = 145, sizev = 0, sizea = 0,
x = 0, xv = 0, xa = 0,
y = 0, yv = 0, ya = 0,
dir = 0, dirv = dirv, dira = 0,
vel = 0, velv = 0, vela = 0,
r = 1, rv = 0, ra = 0,
g = 1, gv = 0, ga = 0,
b = 1, bv = 0, ba = 0,
a = 1, av = 0, aa = 0,
}
end, },
function(self)
self.ps:emit(1)
end,
1, "particles_images/distort_wave_directional"
| gpl-3.0 |
hfjgjfg/PERSIANGUARD10 | plugins/groupsetting.lua | 23 | 31508 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted.')
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' then
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'rem' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
if msg.from.id ~= 0 then
chat_add_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and matches[2] then
if not is_owner(msg) then
return "Only owner can promote"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'demote' and matches[2] then
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "You can't demote yourself"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'newlink' then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'help' then
if not is_momod(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
end
return {
patterns = {
"^(add)$",
"^(rem)$",
"^(rules)$",
"^(about)$",
"^(setname) (.*)$",
"^(setphoto)$",
"^(promote) (.*)$",
"^(help)$",
"^(clean) (.*)$",
"^(demote) (.*)$",
"^(set) ([^%s]+) (.*)$",
"^(lock) (.*)$",
"^(setowner) (%d+)$",
"^(owner)$",
"^(res) (.*)$",
"^(setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^(unlock) (.*)$",
"^(setflood) (%d+)$",
"^(settings)$",
"^(modlist)$",
"^(newlink)$",
"^(link)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/objects/cloth-armors.lua | 3 | 2189 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newEntity{
define_as = "BASE_CLOTH_ARMOR",
slot = "BODY",
type = "armor", subtype="cloth",
add_name = " (#ARMOR#)",
display = "[", color=colors.SLATE, image = resolvers.image_material("robe", "cloth"),
moddable_tile = resolvers.moddable_tile("robe"),
encumber = 2,
rarity = 5,
desc = [[A cloth vestment. It offers no intrinsic protection but can be enchanted.]],
randart_able = "/data/general/objects/random-artifacts/generic.lua",
egos = "/data/general/objects/egos/robe.lua", egos_chance = { prefix=resolvers.mbonus(30, 15), suffix=resolvers.mbonus(30, 15) },
}
newEntity{ base = "BASE_CLOTH_ARMOR",
name = "linen robe", short_name = "linen",
level_range = {1, 10},
cost = 0.5,
material_level = 1,
}
newEntity{ base = "BASE_CLOTH_ARMOR",
name = "woollen robe", short_name = "woollen",
level_range = {10, 20},
cost = 1.5,
material_level = 2,
}
newEntity{ base = "BASE_CLOTH_ARMOR",
name = "cashmere robe", short_name = "cashmere",
level_range = {20, 30},
cost = 2.5,
material_level = 3,
wielder = {
combat_def = 2,
},
}
newEntity{ base = "BASE_CLOTH_ARMOR",
name = "silk robe", short_name = "silk",
level_range = {30, 40},
cost = 3.5,
material_level = 4,
wielder = {
combat_def = 3,
},
}
newEntity{ base = "BASE_CLOTH_ARMOR",
name = "elven-silk robe", short_name = "e.silk",
level_range = {40, 50},
cost = 5.5,
material_level = 5,
wielder = {
combat_def = 5,
},
}
| gpl-3.0 |
Darvame/teateatea | test.lua | 1 | 14394 | local tea = require "teateatea";
local crunning;
local tosmeta = {
__tostring = function(self)
return self[1];
end
};
local check = function(this, tothis, opt, safe)
if not (this == nil or this ~= tothis) then
return true;
end
print(crunning or "Test", "OPT::" .. (opt or ""),"FAILED");
print("1>" .. (tostring(this) or "nil") .. "<");
print("2>" .. (tostring(tothis) or "nil") .. "<");
assert(safe, 'test failed');
return false;
end
local ok_cc = 0;
local ok = function()
print("[OK] [" .. ok_cc .. "] " .. crunning);
ok_cc = ok_cc + 1;
end
local eql_tables = function(t1, t2, opt)
if not check(#t1, #t2, "table size", true) then
print "THAT TABLE::";
for i = 1, #t2 do
print(">" .. (tostring(t1[i]) or "nil") .. "<", ">" .. (tostring(t2[i]) or "nil") .. "<");
end
assert(nil);
end
for i = 1, #t1 do
check(t1[i], t2[i], opt);
end
end
local eql_kvtables = function(t1, t2, opt)
local er;
for k, v in next, t1 do
if not check(v, t2[k], opt, true) then er = true; end
end
-- and backward
for k, v in next, t2 do
if not check(v, t1[k], opt, true) then er = true; end
end
if er then
print("TABLE::");
for k, v in next, t1 do
print(k.."="..v);
end
end
assert(not er);
end
-- .pack
crunning = "pack";
do
local str = "";
for i = 1, 1000 do
str = str .. i .. ";";
end
local t = {};
for i = 1, 1000 do
t[i] = tostring(i);
end
t[#t+1] = '';
eql_tables(tea.pack(str, ";"), t);
end
ok(); -- 0
eql_tables(tea.pack("abc;i; ;;;*&;123; - ;last", ";", true), {
"abc", "i", " ", "*&", "123", " - ", "last"
}, "';'");
ok(); -- 1
eql_tables(tea.pack("abc!i! !!!*&!123! - !last", "!", true), {
"abc", "i", " ", "*&", "123", " - ", "last"
}, "'!'");
ok(); -- 2
eql_tables(tea.pack("abc!i! !!!*&!123! - !last", "!", false), {
"abc", "i", " ", "", "", "*&", "123", " - ", "last"
}, "'!'");
ok(); -- 3
eql_tables(tea.pack("abc #mysep!i #mysep! #mysep! #mysep! #mysep!*& #mysep!123 #mysep! #mysep! - #mysep!last", " #mysep!"), {
"abc", "i", " ", "", "", "*&", "123", "", " - ", "last"
}, "' #mysep!'");
ok(); -- 4
eql_tables(tea.pack("a b c o p c ! the_end", " "), {
"a", "b", "c", "o", "p", "c", "!", "the_end"
}, "*space");
ok(); -- 5
-- .pack_t
crunning = "tpack";
eql_tables(tea.pack("a b c; i; ; ; ;*&; 123; - ; last ; ", ";", nil, true), {
"a b c", "i", "", "", "", "*&", "123", "-", "last", ""
}, ";");
ok(); -- 6
eql_tables(tea.pack(setmetatable({}, { __tostring = function() return "a b c; i; ; ; ;*&; 123; - ; last ; " end }), ";", true, true), {
"a b c", "i", "*&", "123", "-", "last"
}, "; meta");
ok(); -- 7
eql_tables(tea.pack("ab c ! i; ! ! !*&! 123 ! - !last ", "!", true, true), {
"ab c", "i;", "*&", "123", "-", "last"
}, "!");
ok(); -- 8
eql_tables(tea.pack("a b c #mysep! i #mysep! #mysep! a#mysep! #mysep!*& #mysep!123 #mysep! - #mysep!last", " #mysep!", true, true), {
"a b c", "i", "a#mysep!", "*&", "123", "-", "last"
}, " #mysep!");
ok(); -- 9
eql_tables(tea.pack("a b c o p c ! the_end ", " ", true, true), {
"a", "b", "c", "o", "p", "c", "!", "the_end"
}, "*space");
ok(); -- 10
eql_tables(tea.pack("a b c o p c ! the_end", " ", nil, true), {
"a", "b", "c", "o", "p", "c", "!", "the_end"
}, "*1space");
ok(); -- 11
-- .pack_m
crunning = "mpack";
eql_tables(tea.pack("abc;i; ;?;*&;123; - ?last", ";?", true, nil, true, 1, 1, 1), {
"abc", "i", " ", "*&", "123", " - ", "last"
}, "';?'");
ok(); -- 12
eql_tables(tea.pack("abc;i; ;?;*&;123; - ?last", ";?", nil, nil, true), {
"abc", "i", " ", "", "", "*&", "123", " - ", "last"
}, "';?'");
ok(); -- 13
eql_tables(tea.pack("a b1c o4p c?! the_end?", " ?1234567890", true, nil, true), {
"a", "b", "c", "o", "p", "c", "!", "the_end"
}, "*space, dig");
ok(); -- 14
-- .pack_mt
crunning = "mtpack";
eql_tables(tea.pack("a b c; i; ; ; ;*&; 123; - ; last ; ", ";", true, true, true), {
"a b c", "i", "*&", "123", "-", "last"
}, ";");
ok(); -- 15
eql_tables(tea.pack("a b c; i; ; ; ;*&; 123; - ; last ; ", ";?", true, true, true), {
"a b c", "i", "*&", "123", "-", "last"
}, ";?");
ok(); -- 16
eql_tables(tea.pack("a b c o p c?! the_end?", " ?1234567890", true, true, true), {
"a", "b", "c", "o", "p", "c", "!", "the_end"
}, "*space, dig");
ok(); -- 17
eql_tables(tea.pack("a b c o p c ! the_end ", " ABCDEFG", true, true, true), {
"a", "b", "c", "o", "p", "c", "!", "the_end"
}, "*space");
ok(); -- 18
-- .pack_kv
crunning = "kvpack";
eql_kvtables(tea.kvpack("a=b;c=d;x= y ;empty;12345=12345", "=", ";"), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["12345"]="12345";
["empty"] = "";
}, "';'");
ok(); -- 19
eql_kvtables(tea.kvpack("a b c d x y notbroken 12345 12345", " ", " ", true), {
["a"] = "b";
["c"] = "d";
["notbroken"]="12345";
}, "only*space; same keys");
ok(); -- 20
eql_kvtables(tea.kvpack("key1=value1&key2=value2&key3=value3&key4=value4&", "=", "&"), {
["key1"] = "value1";
["key2"] = "value2";
["key3"] = "value3";
["key4"] = "value4";
}, "&qry");
ok(); -- 21
eql_kvtables(tea.kvpack("key1endsvalue1endlkey2endsvalue2endlemptyendlendlkey3endsvalue3endlkey4endsvalue4endl", "ends", "endl"), {
["key1"] = "value1";
["key2"] = "value2";
["key3"] = "value3";
["key4"] = "value4";
["empty"] = "";
}, "*almost same");
ok(); -- 22
-- .pack_tkv
crunning = "tkvpack";
eql_kvtables(tea.kvpack("a=b;c=d;x= y ;empty ; ;1234 5 =12345 ;", "=", ";", nil, true, true), {
["a"] = "b";
["c"] = "d";
["x"] = "y";
["1234 5"]="12345";
["empty"] = "";
}, "';'");
ok(); -- 23
eql_kvtables(tea.kvpack(setmetatable({}, { __tostring = function() return "a=b;c=d;x= y ;empty ; ;1234 5 =12345 ;" end }), "=", ";", nil, true, true), {
["a"] = "b";
["c"] = "d";
["x"] = "y";
["1234 5"]="12345";
["empty"] = "";
}, "';' meta");
ok(); -- 24
eql_kvtables(tea.kvpack("a b c d x y notbroken 12345 12345", " ", " ", true, true, true), {
["a"] = "b";
["c"] = "d";
["notbroken"]="12345";
}, "only*space; same keys");
ok(); -- 25
eql_kvtables(tea.kvpack("key1=value1& key2=value2&key3=value3&key4=value4&&&&&&&&&&&&&&&&", "=", "&", nil, true, true), {
["key1"] = "value1";
["key2"] = "value2";
["key3"] = "value3";
["key4"] = "value4";
}, "&qry");
ok(); -- 26
eql_kvtables(tea.kvpack("abc k2l1 123 2l yolo k2l garb", "k2l1", "2l", nil, true, true), {
["abc"] = "123";
["yolo k"] = "";
["garb"] = "";
}, "*key inside");
ok(); -- 27
-- .pack_mkv
crunning = "mkvpack";
eql_kvtables(tea.kvpack("a b c d x y notbroken 12345 12345", " !", " ?", true, nil, nil, true, true), {
["a"] = "b";
["c"] = "d";
["notbroken"]="12345";
}, "only*space; same keys");
ok(); -- 28
eql_kvtables(tea.kvpack("a=b;c=d,x= y ;empty=!empty2!!12345=12345", "=", ";,!", nil, nil, nil, true, true, 1, 1, 1, "NULL"), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["empty"] = "";
["empty2"] = "";
["12345"]="12345";
}, "';'");
ok(); -- 29
-- .pack_mtkv
crunning = "mtkvpack";
eql_kvtables(tea.kvpack("a=b;c=d,x= y ;empty! ! 1234 5 =12345 ?", "=", "!;,?", nil, true, true, true, true), {
["a"] = "b";
["c"] = "d";
["x"] = "y";
["1234 5"]="12345";
["empty"] = "";
}, "!;,?");
ok(); -- 30
eql_kvtables(tea.kvpack("a=b;c=d,x- y ;empty- !broken ! 1234 5 =12345 ?", "=-", "!;,?", nil, true, true, true, true), {
["a"] = "b";
["c"] = "d";
["x"] = "y";
["empty"] = "";
["broken"] = "";
["1234 5"]="12345";
}, "!;,?|=-");
ok(); -- 31
eql_kvtables(tea.kvpack(setmetatable({}, { __tostring = function() return "a=b;c=d;x= y ;empty ; 1234 5 =12345 ;" end }), "=", ';', nil, true, true, true, true), {
["a"] = "b";
["c"] = "d";
["x"] = "y";
["1234 5"]="12345";
["empty"] = "";
}, "';' meta");
ok(); -- 32
-- .trim
crunning = "trim";
check(tea.trim(" A o a o a 1!!! "), "A o a o a 1!!!"); ok(); -- 33
check(tea.trim(" Aoaoa1!!! ", 1, 1, 1), "Aoaoa1!!!"); ok(); -- 34
check(tea.trim(setmetatable({}, { __tostring = function() return " Aoaoa1!!! " end })), "Aoaoa1!!!"); ok(); -- 35
check(tea.trim("Aoaoa1!!! "), "Aoaoa1!!!"); ok(); -- 36
check(tea.trim(" Aoaoa1!!! "), "Aoaoa1!!!"); ok(); -- 37
check(tea.trim("Aoaoa1!! !", 1 , 1, 1), "Aoaoa1!! !"); ok(); -- 38
check(tea.trim({}, 1, 1) == nil, true); ok(); -- 39
-- .pack_mkv_value
crunning = "mkvpack_value";
eql_kvtables(tea.kvpack("a b c d x y notbroken 12345 12345", " ", " ?", true, nil, nil, nil, true), {
["a"] = "b";
["c"] = "d";
["notbroken"]="12345";
}, "only*space; same keys");
ok(); -- 40
eql_kvtables(tea.kvpack("a=EQL!b;c=EQL!d,x=EQL! y ;empty=EQL!!empty2!!empty3=12345=EQL!12345", "=EQL!", ";,=!", nil, nil, nil, nil, true), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["empty"] = "";
["empty2"] = "";
["empty3"] = "";
["12345"]="12345";
}, "';'");
ok(); -- 41
eql_kvtables(tea.kvpack("aEQLb;cEQLd,xEQL y ;emptyEQL!empty2!!empty3!12345EQL12345", "EQL", ";,!=", nil, nil, nil, nil, true), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["empty"] = "";
["empty2"] = "";
["empty3"] = "";
["12345"]="12345";
}, "';'");
ok(); -- 42
-- .pack_mkv_key
crunning = "mkvpack_key";
eql_kvtables(tea.kvpack("a b c d x y notbroken!12345 12345", " !", " ", true, nil, nil, true), {
["a"] = "b";
["c"] = "d";
["notbroken"]="12345";
}, "only*space; same keys");
ok(); -- 43
eql_kvtables(tea.kvpack("a=b=EQL+c+d=EQL+x- y =EQL+empty==EQL+empty2=EQL+=EQL+empty3=EQL+12345=12345", "=-+", "=EQL+", nil, nil, nil, true), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["empty"] = "";
["empty2"] = "";
["empty3"] = "";
["12345"]="12345";
}, "';'");
ok(); -- 44
eql_kvtables(tea.kvpack("a=bEQLc+dEQLx- y EQLempty=EQLempty2EQLEQLempty3EQL12345=12345", "=-+", "EQL", nil, nil, nil, true), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["empty"] = "";
["empty2"] = "";
["empty3"] = "";
["12345"]="12345";
}, "';'");
ok(); -- 45
crunning = "empty";
eql_kvtables(tea.pack("1=2;3=4;"), {
"1=2;3=4;"
}, "empty"); ok(); -- 46
eql_kvtables(tea.kvpack("1=2;3=4;"), {
["1=2;3=4;"] = "";
}, "emptykv"); ok(); -- 47
eql_kvtables(tea.kvpack("1=2;3=4;", nil, nil, true), {
}, "drop emptykv"); ok(); -- 48
crunning = "meta other";
eql_tables(tea.pack("1;2;3;4;", setmetatable({";"}, tosmeta)), {
'1', '2', '3', '4', '',
}, "meta sep"); ok(); -- 49
eql_kvtables(tea.kvpack("1=2;3=4;", setmetatable({"="}, tosmeta),
setmetatable({";"}, tosmeta)), {
['1'] = '2'; ['3'] = '4';
}, "meta eq sep"); ok(); -- 50
crunning = "diff trim ws";
eql_kvtables(tea.kvpack(" 1 = 2 ; 3 = 4 ;", "=", ";", nil, true), {
['1'] = ' 2 ',
['3'] = ' 4 ',
}, "tws key"); ok(); -- 51
eql_kvtables(tea.kvpack(" 1 = 2 ; 3 = 4 ;", "=", ";", nil, nil, true), {
[' 1 '] = '2',
[' 3 '] = '4',
}, "tws value"); ok(); -- 52
crunning = "pack single end";
eql_tables(tea.pack("qwerty88qwerty", "8888"), {
"qwerty88qwerty"
}, "one long");
ok(); -- 53
eql_kvtables(tea.kvpack("1=qwerty88qwerty", "=", "8888"), {
['1'] = "qwerty88qwerty"
}, "one long");
ok(); -- 54
crunning = "mask"
eql_kvtables(tea.kvpack_mask("a=EQL!b;c=EQL!d,x=EQL! y ;empty=EQL!!empty2!!empty3=12345=EQL!12345", "=EQL!", ";,=!", tea.mask.kvpack(nil, nil, nil, nil, true)), {
["a"] = "b";
["c"] = "d";
["x"] = " y ";
["empty"] = "";
["empty2"] = "";
["empty3"] = "";
["12345"]="12345";
}, "kvmask");
ok(); -- 55
eql_kvtables(tea.kvpack_mask("a=b;c=d;x= y ;empty ; ;1234 5 =12345 ;", "=", ";", tea.mask.kvpack(nil, true, true)), {
["a"] = "b";
["c"] = "d";
["x"] = "y";
["1234 5"]="12345";
["empty"] = "";
}, "kvmask");
ok(); -- 56
eql_tables(tea.pack_mask("a b c; i; ; ; ;*&; 123; - ; last ; ", ";", tea.mask.pack(nil, true)), {
"a b c", "i", "", "", "", "*&", "123", "-", "last", ""
}, "mask");
ok(); -- 57
crunning = "no empty swap";
eql_kvtables(tea.kvpack("1=2;3=4;5=6;7=;8;=9;==10;100=100", "=", ";"), {
['1'] = "2";
['3'] = "4";
['5'] = "6";
['7'] = "";
['8'] = "";
['100'] = '100';
}, "do not swap");
ok(); -- 58
eql_kvtables(tea.kvpack("1=2;3=4;5=6;7=;8;=9;==10;100=100", "=", ";", true), {
['1'] = "2";
['3'] = "4";
['5'] = "6";
['100'] = '100';
}, "do not swap, drop empty");
ok(); -- 59
crunning = "empty swap";
eql_kvtables(tea.kvpack("1=2;3=4;5=6;7=;8;=9;==10;100=100", "=", ";", false, false, false, false, false, true), {
['1'] = "2";
['3'] = "4";
['5'] = "6";
['7'] = "";
['8'] = "";
['9'] = "";
['=10'] = "";
['100'] = '100';
}, "do swap");
ok(); -- 60
eql_kvtables(tea.kvpack("1=2;3=4;5=6;7=;8;=9;==10;100=100", "=", ";", true, false, false, false, false, true), {
['1'] = "2";
['3'] = "4";
['5'] = "6";
['100'] = '100';
}, "do swap, drop empty");
ok(); -- 61
crunning = "begins";
check(tea.begins("1234", 1234), true); ok(); -- 62
check(tea.begins(nil, 1234), false); ok(); -- 63
check(tea.begins("1", 12), false); ok(); -- 64
check(tea.begins(" 1", setmetatable({" "}, tosmeta)), true); ok(); -- 65
crunning = "ends";
check(tea.ends("1234", 1234), true); ok(); -- 66
check(tea.ends(nil, 1234), false); ok(); -- 67
check(tea.ends("1", 12), false); ok(); -- 68
check(tea.ends(" 1", setmetatable({"1"}, tosmeta)), true); ok(); -- 69
crunning = "begins_multiple";
eql_tables({tea.begins_multiple("0$0", "0$0", "12", false, "0$0 1")},{
true, false, false, true
}); ok(); -- 70
crunning = "ends_multiple";
eql_tables({tea.ends_multiple("0$0", "0$0", "12", false, "1 0$0")},{
true, false, false, true
}); ok(); -- 71
crunning = "pack_mask_multiple";
do
local a, b, c, n = tea.pack_mask_multiple(tea.mask.pack(true, true), ";", "1;2;3;4", setmetatable({"1 ; 2; 3; 4 "}, tosmeta), "1;;2;;3;;4", false);
local t = {'1', '2', '3', '4'};
eql_tables(a, t);
eql_tables(b, t);
eql_tables(c, t);
eql_tables(n, {}); ok(); -- 72
end
crunning = "kvpack_mask_multiple";
do
local a, b, c, n = tea.kvpack_mask_multiple(tea.mask.kvpack(true, true, true), "=", ";",
"1=a;2=bb;3=ccc;4=dddd", setmetatable({"1 = a ; 2 = bb; 3 = ccc; 4=dddd "}, tosmeta), "1=a;;2=bb;;3=ccc;;4=dddd;;;", false);
local t = {['1'] = 'a', ['2'] = 'bb', ['3'] = 'ccc', ['4'] = 'dddd'};
eql_kvtables(a, t);
eql_kvtables(b, t);
eql_kvtables(c, t);
eql_kvtables(n, {}); ok(); -- 73
end
crunning = "kvpack_10000";
do
local c = tea.kvpack(("x=1;"):rep(1000), "=", ";");
ok(); -- 74
end
crunning = "pack_10000";
do
local c = tea.pack(("1,"):rep(1000), ",");
ok(); -- 75
end
| mit |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/flower_pink_2.meta.lua | 18 | 2002 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 80,
light_colors = {
"140 57 181 255",
"255 74 231 255",
"148 33 132 255",
"123 49 156 255",
"140 57 181 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/flower_pink_8.meta.lua | 18 | 2002 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 80,
light_colors = {
"140 57 181 255",
"255 74 231 255",
"148 33 132 255",
"123 49 156 255",
"140 57 181 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
jkassman/wesnoth | data/ai/micro_ais/cas/ca_wolves_multipacks_wander.lua | 26 | 5870 | local H = wesnoth.require "lua/helper.lua"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local MAIUV = wesnoth.require "ai/micro_ais/micro_ai_unit_variables.lua"
local LS = wesnoth.require "lua/location_set.lua"
local WMPF = wesnoth.require "ai/micro_ais/cas/ca_wolves_multipacks_functions.lua"
local ca_wolves_multipacks_wander = {}
function ca_wolves_multipacks_wander:evaluation(ai, cfg)
-- When there's nothing to attack, the wolves wander and regroup into their packs
local wolves = AH.get_units_with_moves {
side = wesnoth.current.side,
type = cfg.type or "Wolf"
}
if wolves[1] then return cfg.ca_score end
return 0
end
function ca_wolves_multipacks_wander:execution(ai, cfg)
local packs = WMPF.assign_packs(cfg)
for pack_number,pack in pairs(packs) do
-- If any of the wolves has a goal set, this is used for the entire pack
local wolves, goal = {}, {}
for _,loc in ipairs(pack) do
local wolf = wesnoth.get_unit(loc.x, loc.y)
table.insert(wolves, wolf)
-- If any of the wolves in the pack has a goal set, we use that one
local wolf_goal = MAIUV.get_mai_unit_variables(wolf, cfg.ai_id)
if wolf_goal.goal_x then
goal = { wolf_goal.goal_x, wolf_goal.goal_y }
end
end
-- If the position of any of the wolves is at the goal, delete it
for _,wolf in ipairs(wolves) do
if (wolf.x == goal[1]) and (wolf.y == goal[2]) then goal = {} end
end
-- Pack gets a new goal if none exist or on any move with 10% random chance
local rand = math.random(10)
if (not goal[1]) or (rand == 1) then
local width, height = wesnoth.get_map_size()
local locs = wesnoth.get_locations { x = '1-'..width, y = '1-'..height }
-- Need to find reachable terrain for this to be a viable goal
-- We only check whether the first wolf can get there
local unreachable = true
while unreachable do
local rand = math.random(#locs)
local next_hop = AH.next_hop(wolves[1], locs[rand][1], locs[rand][2])
if next_hop then
goal = { locs[rand][1], locs[rand][2] }
unreachable = nil
end
end
end
-- This goal is saved with every wolf of the pack
for _,wolf in ipairs(wolves) do
MAIUV.insert_mai_unit_variables(wolf, cfg.ai_id, { goal_x = goal[1], goal_y = goal[2] })
end
-- The pack wanders with only 2 considerations
-- 1. Keeping the pack together (most important)
-- Going through all combinations of all hexes for all wolves is too expensive
-- -> find hexes that can be reached by all wolves
-- 2. Getting closest to the goal
-- Number of wolves that can reach each hex,
local reach_map = LS.create()
for _,wolf in ipairs(wolves) do
local reach = wesnoth.find_reach(wolf)
for _,loc in ipairs(reach) do
reach_map:insert(loc[1], loc[2], (reach_map:get(loc[1], loc[2]) or 0) + 100)
end
end
-- Keep only those hexes that can be reached by all wolves in the pack
-- and add distance from goal for those
local max_rating, goto_hex = -9e99
reach_map:iter( function(x, y, v)
local rating = reach_map:get(x, y)
if (rating == #pack * 100) then
rating = rating - H.distance_between(x, y, goal[1], goal[2])
reach_map:insert(x,y, rating)
if rating > max_rating then
max_rating, goto_hex = rating, { x, y }
end
else
reach_map:remove(x, y)
end
end)
-- Sort wolves by MP, the one with fewest moves goes first
table.sort(wolves, function(a, b) return a.moves < b.moves end)
-- If there's no hex that all units can reach, use the 'center of gravity' between them
-- Then we move the first wolf (fewest MP) toward that hex, and the position of that wolf
-- becomes the goto coordinates for the others
if (not goto_hex) then
local cg = { 0, 0 } -- Center of gravity hex
for _,wolf in ipairs(wolves) do
cg = { cg[1] + wolf.x, cg[2] + wolf.y }
end
cg[1] = math.floor(cg[1] / #pack)
cg[2] = math.floor(cg[2] / #pack)
-- Find closest move for Wolf #1 to that position, which then becomes the goto hex
goto_hex = AH.find_best_move(wolves[1], function(x, y)
return -H.distance_between(x, y, cg[1], cg[2])
end)
-- We could move this wolf right here, but for convenience all the actual moves
-- are done together below. This should be a small extra calculation cost
end
-- Now all wolves in the pack are moved toward goto_hex, starting with the one with fewest MP
-- Distance to goal hex is taken into account as secondary criterion
for _,wolf in ipairs(wolves) do
local best_hex = AH.find_best_move(wolf, function(x, y)
local rating = - H.distance_between(x, y, goto_hex[1], goto_hex[2])
rating = rating - H.distance_between(x, y, goal[1], goal[2]) / 100.
return rating
end)
if cfg.show_pack_number then
WMPF.clear_label(wolf.x, wolf.y)
end
AH.movefull_stopunit(ai, wolf, best_hex)
if cfg.show_pack_number and wolf and wolf.valid then
WMPF.put_label(wolf.x, wolf.y, pack_number)
end
end
end
end
return ca_wolves_multipacks_wander
| gpl-2.0 |
koesie10/LuaSerializer | tests/advanced-test.lua | 1 | 17669 | -- From https://github.com/cuberite/WorldEdit/blob/master/Info.lua
-- Info.lua
-- Implements the g_PluginInfo standard plugin description
g_PluginInfo =
{
Name = "WorldEdit",
Version = 7,
DisplayVersion = "0.1.6",
Date = "2016-02-02", -- yyyy-mm-dd
SourceLocation = "https://github.com/cuberite/WorldEdit",
Description = [[This plugin allows you to easily manage the world, edit the world, navigate around or get information. It bears similarity to the Bukkit's WorldEdit plugin and aims to have the same set of commands,however, it has no affiliation to that plugin.
]],
Commands =
{
---------------------------------------------------------------------------------------------------
-- double-slash commands:
["//"] =
{
Alias = {"/,"},
Permission = "worldedit.superpickaxe",
Handler = HandleSuperPickCommand,
HelpString = " Toggle the super pickaxe pickaxe function",
Category = "Tool",
},
["//addleaves"] =
{
Permission = "worldedit.region.addleaves",
Handler = HandleAddLeavesCommand,
HelpString = " Adds leaves next to log blocks",
Category = "Region",
},
["//chunk"] =
{
Permission = "worldedit.selection.chunk",
Handler = HandleChunkCommand,
HelpString = " Select the chunk you are currently in.",
Category = "Selection",
},
["//count"] =
{
Permission = "worldedit.selection.count",
Handler = HandleCountCommand,
HelpString = " Count the number of blocks in the region.",
Category = "Selection",
},
["//contract"] =
{
Permission = "worldedit.selection.contract",
Handler = HandleExpandContractCommand,
HelpString = " Contract the selection area",
Category = "Selection",
},
["//copy"] =
{
Permission = "worldedit.clipboard.copy",
Handler = HandleCopyCommand,
HelpString = " Copy the selection to the clipboard",
Category = "Clipboard",
},
["//cut"] =
{
Permission = "worldedit.clipboard.cut",
Handler = HandleCutCommand,
HelpString = " Cut the selection to the clipboard",
Category = "Clipboard",
},
["//cyl"] =
{
Permission = "worldedit.generation.cylinder",
Handler = HandleCylCommand,
HelpString = "Generates a cylinder.",
Category = "Generation",
},
["//deselect"] =
{
Alias = {"//desel"},
Permission = "worldedit.selection.deselect",
Handler = HandleDeselectCommand,
HelpString = "Deselect the current selection",
Category = "Selection",
},
["//distr"] =
{
Permission = "worldedit.selection.distr",
Handler = HandleDistrCommand,
HelpString = " Inspect the block distribution of the current selection.",
Category = "Selection",
},
["//drain"] =
{
Permission = "worldedit.drain",
Handler = HandleDrainCommand,
HelpString = " Drains all water around you in the given radius.",
Category = "Terraforming",
},
["//ellipsoid"] =
{
Permission = "worldedit.region.ellipsoid",
Handler = HandleEllipsoidCommand,
HelpString = " Creates an ellipsoid in the selected region",
Category = "Region",
},
["//expand"] =
{
Permission = "worldedit.selection.expand",
Handler = HandleExpandContractCommand,
HelpString = " Expand the selection area",
Category = "Selection",
},
["//extinguish"] =
{
Alias = { "//ex", "//ext", "/ex", "/ext", "/extinguish", },
Permission = "worldedit.extinguish",
Handler = HandleExtinguishCommand,
HelpString = " Removes all the fires around you in the given radius.",
Category = "Terraforming",
},
["//faces"] =
{
Alias = {"//outline"},
Permission = "worldedit.region.faces",
Handler = HandleFacesCommand,
HelpString = " Build the walls, ceiling, and floor of a selection",
Category = "Region",
},
["//generate"] =
{
Alias = {"//g", "//gen"},
Permission = "worldedit.generation.shape",
Handler = HandleGenerationShapeCommand,
HelpString = " Generates a shape according to a formula",
Category = "Generation",
},
["//green"] =
{
Permission = "worldedit.green",
Handler = HandleGreenCommand,
HelpString = " Changes all the dirt to grass.",
Category = "Terraforming",
},
["//hcyl"] =
{
Permission = "worldedit.selection.cylinder",
Handler = HandleCylCommand,
HelpString = "Generates a hollow cylinder",
Category = "Generation",
},
["//hpos1"] =
{
Permission = "worldedit.selection.pos",
Handler = HandleHPosCommand,
HelpString = " Set position 1 to the position you are looking at.",
Category = "Selection",
},
["//hpos2"] =
{
Permission = "worldedit.selection.pos",
Handler = HandleHPosCommand,
HelpString = " Set position 2 to the position you are looking at.",
Category = "Selection",
},
["//hpyramid"] =
{
Permission = "worldedit.generation.pyramid",
Handler = HandlePyramidCommand,
HelpString = "Generate a hollow pyramid",
Category = "Generation",
},
["//hsphere"] =
{
Permission = "worldedit.generation.hsphere",
Handler = HandleSphereCommand,
HelpString = " Generates a hollow sphere.",
Category = "Generation",
},
["//leafdecay"] =
{
Permission = "worldedit.region.leafdecay",
Handler = HandleLeafDecayCommand,
HelpString = "Removes all the leaves in the selection that would decay",
Category = "Region",
},
["//loadsel"] =
{
Permission = "worldedit.selection.loadselection",
Handler = HandleSaveLoadSelectionCommand,
HelpString = "Loads a selection that was saved before",
Category = "Selection",
},
["//mirror"] =
{
Permission = "worldedit.region.mirror",
Handler = HandleMirrorCommand,
HelpString = "Mirrors the selection by the specified plane",
Category = "Region",
ParameterCombinations =
{
{
Params = "plane",
Help = "Mirrors the selection by the specified plane",
},
},
},
["//paste"] =
{
Permission = "worldedit.clipboard.paste",
Handler = HandlePasteCommand,
HelpString = " Pastes the clipboard's contents",
Category = "Clipboard",
},
["//pos1"] =
{
Permission = "worldedit.selection.pos",
Handler = HandlePosCommand,
HelpString = " Set position 1",
Category = "Selection",
},
["//pos2"] =
{
Permission = "worldedit.selection.pos",
Handler = HandlePosCommand,
HelpString = " Set position 2",
Category = "Selection",
},
["//pyramid"] =
{
Permission = "worldedit.generation.pyramid",
Handler = HandlePyramidCommand,
HelpString = "Generate a filled pyramid",
Category = "Generation",
},
["//redo"] =
{
Permission = "worldedit.history.redo",
Handler = HandleRedoCommand,
HelpString = " redoes the last action (from history)",
Category = "History",
},
["//replace"] =
{
Permission = "worldedit.region.replace",
Handler = HandleReplaceCommand,
HelpString = " Replace all the blocks in the selection with another",
Category = "Region",
},
["//replacenear"] =
{
Permission = "worldedit.replacenear",
Handler = HandleReplaceNearCommand,
HelpString = " Replace nearby blocks",
Category = "Terraforming",
},
["//rotate"] =
{
Permission = "worldedit.clipboard.rotate",
Handler = HandleRotateCommand,
HelpString = " Rotates the contents of the clipboard",
Category = "Clipboard",
},
["//savesel"] =
{
Permission = "worldedit.selection.saveselection",
Handler = HandleSaveLoadSelectionCommand,
HelpString = "Saves the current selection so it can be used later",
Category = "Selection",
},
["//schematic"] =
{
Permission = "", -- Multi-commands shouldn't specify a permission
Handler = nil, -- Provide a standard multi-command handler
HelpString = "", -- Don't show in help
Category = "Schematic",
Subcommands =
{
save =
{
HelpString = "Saves the current clipboard to a file with the given filename.",
Permission = "worldedit.schematic.save",
Handler = HandleSchematicSaveCommand,
Alias = "s",
Category = "Schematic",
},
load =
{
HelpString = "Loads the given schematic file.",
Permission = "worldedit.schematic.load",
Handler = HandleSchematicLoadCommand,
Alias = "l",
Category = "Schematic",
},
formats =
{
HelpString = "List available schematic formats",
Permission = "worldedit.schematic.list",
Handler = HandleSchematicFormatsCommand,
Alias = {"listformats", "f" },
Category = "Schematic",
},
list =
{
HelpString = "List available schematics",
Permission = "worldedit.schematic.list",
Handler = HandleSchematicListCommand,
Alias = { "all", "ls", },
Category = "Schematic",
},
},
},
["//set"] =
{
Permission = "worldedit.region.set",
Handler = HandleSetCommand,
HelpString = " Set all the blocks inside the selection to a block",
Category = "Region",
},
["//setbiome"] =
{
Permission = "worldedit.biome.set",
Handler = HandleSetBiomeCommand,
HelpString = " Set the biome of the region.",
Category = "Biome",
},
["//shift"] =
{
Permission = "worldedit.selection.size",
Handler = HandleShiftCommand,
HelpString = " Move the selection area",
Category = "Selection",
},
["//shrink"] =
{
Permission = "worldedit.selection.shrink",
Handler = HandleShrinkCommand,
HelpString = " shrink the current selection to exclude air-only layers of the selection",
Category = "Selection"
},
["//size"] =
{
Permission = "worldedit.selection.size",
Handler = HandleSizeCommand,
HelpString = " Get the size of the selection",
Category = "Selection",
},
["//sphere"] =
{
Permission = "worldedit.generation.sphere",
Handler = HandleSphereCommand,
HelpString = " Generates a filled sphere.",
Category = "Generation",
},
["//stack"] =
{
Permission = "worldedit.region.stack",
Handler = HandleStackCommand,
HelpString = "Repeat the contents of the selection.",
Category = "Region",
},
["//undo"] =
{
Permission = "worldedit.history.undo",
Handler = HandleUndoCommand,
HelpString = " Undoes the last action",
Category = "History",
},
["//vmirror"] =
{
Permission = "worldedit.region.vmirror",
Handler = HandleVMirrorCommand,
HelpString = "Mirrors the selection vertically",
Category = "Region",
},
["//walls"] =
{
Permission = "worldedit.region.walls",
Handler = HandleWallsCommand,
HelpString = " Build the four sides of the selection",
Category = "Region",
},
["//wand"] =
{
Permission = "worldedit.wand",
Handler = HandleWandCommand,
HelpString = " Get the wand object",
Category = "Special",
},
---------------------------------------------------------------------------------------------------
-- Single-slash commands:
["/.s"] =
{
Permission = "worldedit.scripting.execute",
Handler = HandleLastCraftScriptCommand,
HelpString = "Execute last CraftScript",
Category = "Scripting",
},
["/ascend"] =
{
Alias = "/asc",
Permission = "worldedit.navigation.ascend",
Handler = HandleAscendCommand,
HelpString = " go up a floor",
Category = "Navigation",
},
["/biomeinfo"] =
{
Permission = "worldedit.biome.info",
Handler = HandleBiomeInfoCommand,
HelpString = " Get the biome of the targeted block(s).",
Category = "Biome",
},
["/biomelist"] =
{
Permission = "worldedit.biomelist",
Handler = HandleBiomeListCommand,
HelpString = " Gets all biomes available",
Category = "Biome",
},
["/brush"] =
{
Alias = { "//brush", "/br", "//br", },
Permission = "",
Handler = nil,
HelpString = " Brush commands",
Category = "Brush",
Subcommands =
{
sphere =
{
HelpString = " Switch to the sphere brush tool.",
Permission = "worldedit.brush.sphere",
Handler = HandleSphereBrush,
Category = "Brush",
},
cylinder =
{
HelpString = " Switch to the cylinder brush tool.",
Permission = "worldedit.brush.cylinder",
Handler = HandleCylinderBrush,
Category = "Brush",
},
},
},
["/butcher"] =
{
Permission = "worldedit.butcher",
Handler = HandleButcherCommand,
HelpString = " Kills nearby mobs based on the given radius, if no radius is given it uses the default in configuration.",
Category = "Entities",
},
["/cs"] =
{
Permission = "worldedit.scripting.execute",
Handler = HandleCraftScriptCommand,
HelpString = " Execute a CraftScript",
Category = "Scripting",
},
["/descend"] =
{
Alias = "/desc",
Permission = "worldedit.navigation.descend",
Handler = HandleDescendCommand,
HelpString = "go down a floor",
Category = "Navigation",
},
["/farwand"] =
{
Permission = "worldedit.tool.farwand",
Handler = HandleFarwandCommand,
HelpString = "Use the wand from a distance",
Category = "Tool",
},
["/jumpto"] =
{
Permission = "worldedit.navigation.jumpto.command",
Handler = HandleJumpToCommand,
HelpString = " Teleport to a location",
Category = "Navigation",
},
["/mask"] =
{
Permission = "worldedit.brush.options.mask",
Handler = HandleMaskCommand,
HelpString = " Set the brush mask",
Category = "Brush",
},
["/none"] =
{
Handler = HandleNoneCommand,
HelpString = " Unbind a bound tool from your current item",
Category = "Tool",
},
["/pumpkins"] =
{
Permission = "worldedit.generation.pumpkins",
Handler = HandlePumpkinsCommand,
HelpString = " Generates pumpkins at the surface.",
Category = "Terraforming",
},
["/remove"] =
{
Alias = { "/rem", "/rement", },
Permission = "worldedit.remove",
Handler = HandleRemoveCommand,
HelpString = " Removes all entities of a type",
Category = "Entities",
},
["/removeabove"] =
{
Alias = "//removeabove",
Permission = "worldedit.removeabove",
Handler = HandleRemoveColumnCommand,
HelpString = " Remove all the blocks above you.",
Category = "Terraforming",
},
["/removebelow"] =
{
Alias = "//removebelow",
Permission = "worldedit.removebelow",
Handler = HandleRemoveColumnCommand,
HelpString = " Remove all the blocks below you.",
Category = "Terraforming",
},
["/repl"] =
{
Permission = "worldedit.tool.replacer",
Handler = HandleReplCommand,
HelpString = " Block replace tool",
Category = "Tool",
},
["/snow"] =
{
Command = "/snow",
Permission = "worldedit.snow",
Handler = HandleSnowCommand,
HelpString = " Makes it look like it has snown.",
Category = "Terraforming",
},
["/thaw"] =
{
Permission = "worldedit.thaw",
Handler = HandleThawCommand,
HelpString = " Removes all the snow around you in the given radius.",
Category = "Terraforming",
},
["/thru"] =
{
Permission = "worldedit.navigation.thru.command",
Handler = HandleThruCommand,
HelpString = " Passthrough walls",
Category = "Navigation",
},
["/toggleeditwand"] =
{
Permission = "worldedit.wand.toggle",
Handler = HandleToggleEditWandCommand,
HelpString = " Toggle functionality of the edit wand",
Category = "Special",
},
["/tree"] =
{
Permission = "worldedit.tool.tree",
Handler = HandleTreeCommand,
HelpString = " Tree generator tool",
Category = "Tool",
},
["/up"] =
{
Permission = "worldedit.navigation.up",
Handler = HandleUpCommand,
HelpString = " go upwards some distance",
Category = "Navigation",
},
["/we"] =
{
Permission = "",
Handler = nil,
HelpString = " World edit command",
Category = "Special",
Subcommands =
{
cui =
{
HelpString = "Complete CUI handshake",
Permission = "",
Handler = HandleWorldEditCuiCommand,
Category = "Special",
},
version =
{
HelpString = "Sends the plugin version to the player.",
Permission = "",
Handler = HandleWorldEditVersionCommand,
Category = "Special",
},
help =
{
HelpString = "Sends all the available commands to the player.",
Permission = "",
Handler = HandleWorldEditHelpCommand,
Category = "Special",
},
},
},
}, -- Commands
Categories =
{
Navigation =
{
Description = "Commands that helps the player moving to locations.",
},
Clipboard =
{
Description = "All the commands that have anything todo with a players clipboard.",
},
Tool =
{
Description = "Commands that activate a tool. If a tool is activated you can use it by right or left clicking with your mouse.",
},
Region =
{
Description = "Commands in this category will allow the player to edit the region he/she has selected using //pos[1/2] or using the wand item.",
},
Schematic =
{
Description = "Commands that load or save schematic's",
},
Selection =
{
Description = "Commands that give info/help setting the region you have selected.",
},
Generation =
{
Description = "Commands that generates structures.",
},
History =
{
Description = "Commands that can undo/redo past WorldEdit actions.",
},
Terraforming =
{
Description = "Commands that help you Modifying the terrain.",
},
Biome =
{
Description = "Any biome specific commands.",
},
Special =
{
Description = "Commands that don't realy fit in another category.",
},
},
AdditionalInfo =
{
{
Header = "API",
Contents = [[
]],
},
{
Header = "Config",
Contents = [[
]],
}
}, -- AdditionalInfo
}
| mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Mhaura/npcs/Vera.lua | 1 | 2852 | -----------------------------------
-- Area: Mhaura
-- NPC: Vera
-- Finishes Quest: The Old Lady
-----------------------------------
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
questStatus = player:getQuestStatus(OTHER_AREAS,THE_OLD_LADY);
if (questStatus == QUEST_ACCEPTED and trade:getItemCount() == 1) then
VeraOldLadyVar = player:getVar("VeraOldLadyVar");
if (VeraOldLadyVar == 1 and trade:hasItemQty(542,1) == true) then
player:startEvent(0x0087,541);
elseif (VeraOldLadyVar == 2 and trade:hasItemQty(541,1) == true) then
player:startEvent(0x0088,540);
elseif (VeraOldLadyVar == 3 and trade:hasItemQty(540,1) == true) then
player:startEvent(0x0089);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
questStatus = player:getQuestStatus(OTHER_AREAS, THE_OLD_LADY);
if (player:getQuestStatus(OTHER_AREAS, ELDER_MEMORIES) ~= QUEST_AVAILABLE) then
player:startEvent(0x0082);
elseif (questStatus == QUEST_COMPLETED) then
player:startEvent(0x008a);
elseif (questStatus == QUEST_ACCEPTED) then
VeraOldLadyVar = player:getVar("VeraOldLadyVar");
if (VeraOldLadyVar == 1) then
player:startEvent(0x0084,542);
elseif (VeraOldLadyVar == 2) then
player:startEvent(0x0084,541);
elseif (VeraOldLadyVar == 3) then
player:startEvent(0x0084,540);
end
else
if (player:getMainLvl() >= SUBJOB_QUEST_LEVEL) then
player:startEvent(0x0083,542);
else
player:startEvent(0x0085);
end
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 == 0x0083 and option == 40) then
player:addQuest(OTHER_AREAS, THE_OLD_LADY);
player:setVar("VeraOldLadyVar", 1);
elseif (csid == 0x0087) then
player:tradeComplete();
player:setVar("VeraOldLadyVar", 2);
elseif (csid == 0x0088) then
player:tradeComplete();
player:setVar("VeraOldLadyVar", 3);
elseif (csid == 0x0089) then
player:tradeComplete();
player:unlockJob(0);
player:setVar("VeraOldLadyVar", 0);
player:messageSpecial(SUBJOB_UNLOCKED);
player:completeQuest(OTHER_AREAS,THE_OLD_LADY);
end
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Southern_San_dOria/npcs/Home_Point.lua | 8 | 1209 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Home Point
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (HOMEPOINT_HEAL == 1) then
player:addHP(player:getMaxHP());
player:addMP(player:getMaxMP());
end
player:startEvent(0x0254);
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 == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Northern_San_dOria/npcs/Abeaule.lua | 1 | 4011 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Abeaule
-- Starts and Finishes Quest: The Trader in the Forest, The Medicine Woman
-- @zone 231
-- @pos -136 -2 56
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
theTraderInTheForest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
if(theTraderInTheForest == QUEST_ACCEPTED) then
if(trade:hasItemQty(CLUMP_OF_BATAGREENS,1) == true and trade:getItemCount() == 1) then
player:startEvent(0x020d);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
theTraderInTheForest = player:getQuestStatus(SANDORIA,THE_TRADER_IN_THE_FOREST);
medicineWoman = player:getQuestStatus(SANDORIA,THE_MEDICINE_WOMAN);
if(theTraderInTheForest == QUEST_AVAILABLE) then
if(player:getVar("theTraderInTheForestCS") == 1) then
player:startEvent(0x0250);
else
player:startEvent(0x020c);
player:setVar("theTraderInTheForestCS",1);
end
elseif(theTraderInTheForest == QUEST_ACCEPTED) then
player:startEvent(0x0251);
elseif(theTraderInTheForest == QUEST_COMPLETED and medicineWoman == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then
if(player:getVar("medicineWomanCS") == 1) then
player:startEvent(0x0267);
else
player:startEvent(0x0265);
player:setVar("medicineWomanCS",1);
end
elseif(player:hasKeyItem(COLD_MEDICINE) == true) then
player:startEvent(0x0266);
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);
-- "The Trader in the Forest" Quest
if(csid == 0x020c and option == 0 or csid == 0x0250 and option == 0) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, SUPPLIES_ORDER);
else
player:addQuest(SANDORIA,THE_TRADER_IN_THE_FOREST);
player:setVar("theTraderInTheForestCS",0);
player:addItem(SUPPLIES_ORDER);
player:messageSpecial(ITEM_OBTAINED, SUPPLIES_ORDER);
end
elseif(csid == 0x0251 and option == 1) then
if (player:getFreeSlotsCount() > 0 and player:hasItem(SUPPLIES_ORDER) == false) then
player:addItem(SUPPLIES_ORDER);
player:messageSpecial(ITEM_OBTAINED, SUPPLIES_ORDER);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, SUPPLIES_ORDER);
end
elseif(csid == 0x020d) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, ROBE);
else
player:tradeComplete();
player:setTitle(GREEN_GROCER);
player:addItem(ROBE);
player:messageSpecial(ITEM_OBTAINED, ROBE);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_TRADER_IN_THE_FOREST);
end
-- "The Medicine Woman" Quest
elseif(csid == 0x0265 and option == 0 or csid == 0x0267 and option == 0) then
player:addQuest(SANDORIA,THE_MEDICINE_WOMAN);
elseif (csid == 0x0266) then
player:setTitle(TRAVELING_MEDICINE_MAN);
player:delKeyItem(COLD_MEDICINE);
player:addGil(GIL_RATE*2100);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,THE_MEDICINE_WOMAN);
end
end; | gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/WorldKey/InvalidKeyPage.lua | 1 | 2088 | --[[
Title: InvalidKeyPage
Author(s): yangguiyi
Date: 2020/9/2
Desc:
Use Lib:
-------------------------------------------------------
local InvalidKeyPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/InvalidKeyPage.lua");
InvalidKeyPage.Show();
--]]
local WorldKeyManager = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyManager.lua")
local InvalidKeyPage = NPL.export();
local page;
local DateTool = os.date
InvalidKeyPage.Current_Item_DS = {};
local UserData = {}
local FollowList = {}
local SearchIdList = {}
function InvalidKeyPage.OnInit()
page = document:GetPageCtrl();
page.OnClose = InvalidKeyPage.CloseView
end
function InvalidKeyPage.Show(world_data)
InvalidKeyPage.world_data = world_data
local att = ParaEngine.GetAttributeObject();
local oldsize = att:GetField("ScreenResolution", {1280,720});
local params = {
url = "script/apps/Aries/Creator/Game/Tasks/WorldKey/InvalidKeyPage.html",
name = "InvalidKeyPage.Show",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
enable_esc_key = true,
zorder = 0,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_ct",
x = -400/2,
y = -180/2,
width = 400,
height = 180,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function InvalidKeyPage.Paste()
local text = ParaMisc.GetTextFromClipboard() or "";
page:SetValue("key_text", text)
end
function InvalidKeyPage.CloseView()
-- body
end
function InvalidKeyPage.WriteOff()
local key = page:GetValue("key_text")
if key == nil or key == "" then
GameLogic.AddBBS(nil, L"请输入激活码", 3000, "255 0 0")
return
end
WorldKeyManager.AddInvalidKey(key, InvalidKeyPage.world_data, function()
if page then
page:CloseWindow(0)
InvalidKeyPage.CloseView()
end
end)
end | gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/loaf_of_steel_bread.lua | 1 | 1132 | -----------------------------------------
-- ID: 4573
-- Item: loaf_of_steel_bread
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 6
-- Vitality 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,0,4573);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 6);
target:addMod(MOD_VIT, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 6);
target:delMod(MOD_VIT, 1);
end;
| gpl-3.0 |
osamaalbsraoy/osama_albsraoy1989 | plugins/en-lock-fwd.lua | 1 | 1557 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ BY OSAMA ▀▄ ▄▀
▀▄ ▄▀ BY OSAMA (@OS_AA23) ▀▄ ▄▀
▀▄ ▄▀ JUST WRITED BY OSAMA ▀▄ ▄▀
▀▄ ▄▀ broadcast : lock fwd ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀
--]]
do
local function pre_process(msg)
--Checking mute
local hash = 'mate:'..msg.to.id
if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
return "done"
end
return msg
end
local function run(msg, matches)
chat_id = msg.to.id
if is_momod(msg) and matches[1] == 'lock fwd' then
local hash = 'mate:'..msg.to.id
redis:set(hash, true)
return "It was lock fwd 🔐✋🏻"
elseif is_momod(msg) and matches[1] == 'unlock fwd' then
local hash = 'mate:'..msg.to.id
redis:del(hash)
return "It was unlock fwd 🔓👍"
end
end
return {
patterns = {
'^(lock fwd)$',
'^(unlock fwd)$'
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
wmAndym/lua-csv | lua/test.lua | 2 | 2423 | pcall(require, "strict")
local csv = require"csv"
local errors = 0
local function testhandle(handle, correct_result)
local result = {}
for r in handle:lines() do
if not r[1] then
local r2 = {}
for k, v in pairs(r) do r2[#r2+1] = k..":"..tostring(v) end
table.sort(r2)
r = r2
end
result[#result+1] = table.concat(r, ",")
end
handle:close()
result = table.concat(result, "!\n").."!"
if result ~= correct_result then
io.stderr:write(
("Error reading '%s':\nExpected output:\n%s\n\nActual output:\n%s\n\n"):
format(handle:name(), correct_result, result))
errors = errors + 1
return false
end
return true
end
local function test(filename, correct_result, parameters)
parameters = parameters or {}
for i = 1, 16 do
parameters.buffer_size = i
local f = csv.open(filename, parameters)
local fileok = testhandle(f, correct_result)
if fileok then
f = io.open(filename, "r")
local data = f:read("*a")
f:close()
f = csv.openstring(data, parameters)
testhandle(f, correct_result)
end
end
end
test("../test-data/embedded-newlines.csv", [[
embedded
newline,embedded
newline,embedded
newline!
embedded
newline,embedded
newline,embedded
newline!]])
test("../test-data/embedded-quotes.csv", [[
embedded "quotes",embedded "quotes",embedded "quotes"!
embedded "quotes",embedded "quotes",embedded "quotes"!]])
test("../test-data/header.csv", [[
alpha:ONE,bravo:two,charlie:3!
alpha:four,bravo:five,charlie:6!]], {header=true})
test("../test-data/header.csv", [[
apple:one,charlie:30!
apple:four,charlie:60!]],
{ columns = {
apple = { name = "ALPHA", transform = string.lower },
charlie = { transform = function(x) return tonumber(x) * 10 end }}})
test("../test-data/blank-line.csv", [[
this,file,ends,with,a,blank,line!]])
test("../test-data/BOM.csv", [[
apple:one,charlie:30!
apple:four,charlie:60!]],
{ columns = {
apple = { name = "ALPHA", transform = string.lower },
charlie = { transform = function(x) return tonumber(x) * 10 end }}})
test("../test-data/bars.txt", [[
there's a comma in this field, but no newline,embedded
newline,embedded
newline!
embedded
newline,embedded
newline,embedded
newline!]])
if errors == 0 then
io.stdout:write("Passed\n")
elseif errors == 1 then
io.stdout:write("1 error\n")
else
io.stdout:write(("%d errors\n"):format(errors))
end
os.exit(errors)
| mit |
gleachkr/luakit | lib/follow_selected_wm.lua | 4 | 1741 | -- Add {A,C,S,}-Return binds to follow selected link (or link in selection) - web module.
--
-- @submodule follow_selected_wm
-- @copyright 2016 Aidan Holm <aidanholm@gmail.com>
-- @copyright 2010 Chris van Dijk <quigybo@hotmail.com>
-- @copyright 2010 Mason Larobina <mason.larobina@gmail.com>
-- @copyright 2010 Paweł Zuzelski <pawelz@pld-linux.org>
-- @copyright 2009 israellevin
local ui = ipc_channel("follow_selected_wm")
-- Return selected uri or first uri in selection
local return_selected = [=[
(function(document) {
var selection = window.getSelection(),
container = document.createElement('div'),
range, elements, i = 0;
if (selection.toString() !== "") {
range = selection.getRangeAt(0);
// Check for links contained within the selection
container.appendChild(range.cloneContents());
var elements = container.getElementsByTagName('a'),
len = elements.length, i = 0, href;
for (; i < len;)
if ((href = elements[i++].href))
return href;
// Check for links which contain the selection
container = range.startContainer;
while (container !== document) {
if ((href = container.href))
return href;
container = container.parentNode;
}
}
// Check for active links
var element = document.activeElement;
return element.src || element.href;
})(document);
]=]
ui:add_signal("follow_selected", function(_, _, action, view_id)
local p = page(view_id)
local uri = p:eval_js(return_selected)
if not uri then return end
assert(type(uri) == "string")
ui:emit_signal(action, uri, view_id)
end)
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
gmagnotta/packages | net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/member.lua | 111 | 1535 | -- ------ member configuration ------ --
ds = require "luci.dispatcher"
m5 = Map("mwan3", translate("MWAN Member Configuration"))
m5:append(Template("mwan/config_css"))
mwan_member = m5:section(TypedSection, "member", translate("Members"),
translate("Members are profiles attaching a metric and weight to an MWAN interface<br />" ..
"Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" ..
"Members may not share the same name as configured interfaces, policies or rules"))
mwan_member.addremove = true
mwan_member.dynamic = false
mwan_member.sectionhead = "Member"
mwan_member.sortable = true
mwan_member.template = "cbi/tblsection"
mwan_member.extedit = ds.build_url("admin", "network", "mwan", "configuration", "member", "%s")
function mwan_member.create(self, section)
TypedSection.create(self, section)
m5.uci:save("mwan3")
luci.http.redirect(ds.build_url("admin", "network", "mwan", "configuration", "member", section))
end
interface = mwan_member:option(DummyValue, "interface", translate("Interface"))
interface.rawhtml = true
function interface.cfgvalue(self, s)
return self.map:get(s, "interface") or "—"
end
metric = mwan_member:option(DummyValue, "metric", translate("Metric"))
metric.rawhtml = true
function metric.cfgvalue(self, s)
return self.map:get(s, "metric") or "1"
end
weight = mwan_member:option(DummyValue, "weight", translate("Weight"))
weight.rawhtml = true
function weight.cfgvalue(self, s)
return self.map:get(s, "weight") or "1"
end
return m5
| gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/defuse_kit.meta.lua | 2 | 2654 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"255 0 0 255",
"0 255 255 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {
2,
3,
4,
0,
2,
2,
0,
1,
2
},
original_poly = {
{
x = -8,
y = -24
},
{
x = 9,
y = -26.5
},
{
x = 3,
y = 0
},
{
x = 9,
y = 26.5
},
{
x = -8,
y = 21
}
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
Aminrezaa/megareborn | libs/dateparser.lua | 502 | 6212 | local difftime, time, date = os.difftime, os.time, os.date
local format = string.format
local tremove, tinsert = table.remove, table.insert
local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable
local dateparser={}
--we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore.
local unix_timestamp
do
local now = time()
local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now)))
unix_timestamp = function(t, offset_sec)
local success, improper_time = pcall(time, t)
if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end
return improper_time - local_UTC_offset_sec - offset_sec
end
end
local formats = {} -- format names
local format_func = setmetatable({}, {__mode='v'}) --format functions
---register a date format parsing function
function dateparser.register_format(format_name, format_function)
if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end
local found
for i, f in ipairs(format_func) do --for ordering
if f==format_function then
found=true
break
end
end
if not found then
tinsert(format_func, format_function)
end
formats[format_name] = format_function
return true
end
---register a date format parsing function
function dateparser.unregister_format(format_name)
if type(format_name)~="string" then return nil, "format name must be a string" end
formats[format_name]=nil
end
---return the function responsible for handling format_name date strings
function dateparser.get_format_function(format_name)
return formats[format_name] or nil, ("format %s not registered"):format(format_name)
end
---try to parse date string
--@param str date string
--@param date_format optional date format name, if known
--@return unix timestamp if str can be parsed; nil, error otherwise.
function dateparser.parse(str, date_format)
local success, res, err
if date_format then
if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end
success, res = pcall(formats[date_format], str)
else
for i, func in ipairs(format_func) do
success, res = pcall(func, str)
if success and res then return res end
end
end
return success and res
end
dateparser.register_format('W3CDTF', function(rest)
local year, day_of_year, month, day, week
local hour, minute, second, second_fraction, offset_hours
local alt_rest
year, rest = rest:match("^(%d%d%d%d)%-?(.*)$")
day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$")
if day_of_year then rest=alt_rest end
month, rest = rest:match("^(%d%d)%-?(.*)$")
day, rest = rest:match("^(%d%d)(.*)$")
if #rest>0 then
rest = rest:match("^T(.*)$")
hour, rest = rest:match("^([0-2][0-9]):?(.*)$")
minute, rest = rest:match("^([0-6][0-9]):?(.*)$")
second, rest = rest:match("^([0-6][0-9])(.*)$")
second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$")
if second_fraction then
rest=alt_rest
end
if rest=="Z" then
rest=""
offset_hours=0
else
local sign, offset_h, offset_m
sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$")
local offset_m, alt_rest = rest:match("^(%d%d)(.*)$")
if offset_m then rest=alt_rest end
offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 then return nil end
end
year = tonumber(year)
local d = {
year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))),
month = tonumber(month) or 1,
day = tonumber(day) or 1,
hour = tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
local t = unix_timestamp(d, (offset_hours or 0) * 3600)
if second_fraction then
return t + tonumber("0."..second_fraction)
else
return t
end
end)
do
local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/
A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9,
K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5,
S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12,
Z = 0,
EST = -5, EDT = -4, CST = -6, CDT = -5,
MST = -7, MDT = -6, PST = -8, PDT = -7,
GMT = 0, UT = 0, UTC = 0
}
local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12}
dateparser.register_format('RFC2822', function(rest)
local year, month, day, day_of_year, week_of_year, weekday
local hour, minute, second, second_fraction, offset_hours
local alt_rest
weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$")
if weekday then rest=alt_rest end
day, rest=rest:match("^(%d%d?)%s+(.*)$")
month, rest=rest:match("^(%w%w%w)%s+(.*)$")
month = month_val[month]
year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$")
hour, rest = rest:match("^(%d%d?):(.*)$")
minute, rest = rest:match("^(%d%d?)(.*)$")
second, alt_rest = rest:match("^:(%d%d)(.*)$")
if second then rest = alt_rest end
local tz, offset_sign, offset_h, offset_m
tz, alt_rest = rest:match("^%s+(%u+)(.*)$")
if tz then
rest = alt_rest
offset_hours = tz_table[tz]
else
offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$")
offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 or not (year and day and month and hour and minute) then
return nil
end
year = tonumber(year)
local d = {
year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))),
month = month,
day = tonumber(day),
hour= tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
return unix_timestamp(d, offset_hours * 3600)
end)
end
dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough
dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF
return dateparser | gpl-3.0 |
mysql/mysql-proxy | tests/suite/base/t/ignore-resultset-mock.lua | 12 | 1519 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
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; version 2 of the
License.
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 St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
local proto = require("mysql.proto")
function connect_server()
-- emulate a server
proxy.response = {
type = proxy.MYSQLD_PACKET_RAW,
packets = {
proto.to_challenge_packet({})
}
}
return proxy.PROXY_SEND_RESULT
end
function read_query(packet)
if packet:byte() ~= proxy.COM_QUERY then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK
}
return proxy.PROXY_SEND_RESULT
end
local query = packet:sub(2)
if query == 'SELECT 1' then
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
resultset = {
fields = {
{ name = '1' },
},
rows = { { 1 } }
}
}
else
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "(resultset-mock) >" .. query .. "<"
}
end
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/http_status_code.lua | 2 | 1728 | --
-- (C) 2020 - ntop.org
--
-- This page shows the HTTP errors that a user can get
-- example: 404, 403, ...
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require("lua_utils")
local page_utils = require("page_utils")
local message = _GET["message"] or "forbidden"
local referal_url = _GET["referer"] or '/'
local error_message = _GET["error_message"] or ""
if(_GET["message"] == "not_found") then
status_code = 404
elseif(_GET["message"] == "internal_error") then
status_code = 500
else
status_code = 403 -- forbidden
end
sendHTTPContentTypeHeader('text/html', nil, nil, nil, status_code)
page_utils.print_header()
referal_url = string.sub(referal_url, string.find(referal_url, "/"), string.len(referal_url))
message = "http_status_code."..message
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
print([[
<div style="height: 80vh" class='row my-4'>
<div class='col pl-5 d-flex justify-content-center flex-column align-items-left'>
<h2 class='mb-5 w-100' style='font-size: 4rem'>
<b>]].. i18n("error_page.presence").. [[</b>
</h2>
<b>]])
print(i18n(message))
print('</b></p><p class="text-danger">'..error_message)
print([[</p>
<a class='btn-primary btn mb-3' href="]].. referal_url ..[[">
<i class='fas fa-arrow-left'></i> ]].. i18n("error_page.go_back").. [[
</a>
</div>
<div class='col p-2 text-start d-flex justify-content-center align-items-center'>
<i class="fas fa-exclamation-triangle bigger-icon"></i>
</div>
</div>
]])
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
RyMarq/Zero-K | units/factorytank.lua | 1 | 3239 | return { factorytank = {
unitname = [[factorytank]],
name = [[Tank Foundry]],
description = [[Produces Heavy Tracked Vehicles, Builds at 10 m/s]],
acceleration = 0,
brakeRate = 0,
buildCostMetal = Shared.FACTORY_COST,
builder = true,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 11,
buildingGroundDecalSizeY = 11,
buildingGroundDecalType = [[factorytank_aoplane.dds]],
buildoptions = {
[[tankcon]],
[[tankraid]],
[[tankheavyraid]],
[[tankriot]],
[[tankassault]],
[[tankheavyassault]],
[[tankarty]],
[[tankheavyarty]],
[[tankaa]],
},
buildPic = [[factorytank.png]],
canMove = true,
canPatrol = true,
category = [[SINK UNARMED]],
corpse = [[DEAD]],
collisionVolumeOffsets = [[0 0 -25]],
collisionVolumeScales = [[110 28 44]],
collisionVolumeType = [[box]],
selectionVolumeOffsets = [[0 0 10]],
selectionVolumeScales = [[120 28 120]],
selectionVolumeType = [[box]],
customParams = {
sortName = [[6]],
solid_factory = [[4]],
default_spacing = 8,
aimposoffset = [[0 15 -35]],
midposoffset = [[0 15 -10]],
modelradius = [[100]],
unstick_help = 1,
selectionscalemult = 1,
factorytab = 1,
shared_energy_gen = 1,
},
energyUse = 0,
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 8,
footprintZ = 8,
iconType = [[factank]],
idleAutoHeal = 5,
idleTime = 1800,
levelGround = false,
maxDamage = 4000,
maxSlope = 15,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
moveState = 1,
noAutoFire = false,
objectName = [[factorytank.s3o]],
script = [[factorytank.lua]],
selfDestructAs = [[LARGE_BUILDINGEX]],
showNanoSpray = false,
sightDistance = 273,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = Shared.FACTORY_BUILDPOWER,
yardMap = "oooooooo oooooooo oooooooo oooooooo yccccccy yccccccy yccccccy yccccccy",
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 8,
footprintZ = 8,
object = [[factorytank_dead.s3o]],
collisionVolumeOffsets = [[0 14 -34]],
collisionVolumeScales = [[110 28 44]],
collisionVolumeType = [[box]],
},
HEAP = {
blocking = false,
footprintX = 6,
footprintZ = 6,
object = [[debris4x4a.s3o]],
},
},
} }
| gpl-2.0 |
10iii/synbank-com | api/lua/base.lua | 2 | 1303 | local redis = require "resty.redis"
local cjson = require "cjson"
local red = redis:new()
red:set_timeout(1000) -- 1 sec
local config = ngx.shared.config;
local the_key = ''
-- or connect to a unix domain socket file listened
-- by a redis server:
-- local ok, err = red:connect("unix:/path/to/redis.sock")
local ok, err = red:connect("127.0.0.1", 6379)
if not ok then
local resp = {api = "error",desc = "failed to connect",body = err}
ngx.say(cjson.encode(resp))
return
end
ok, err = red:select(config:get('redisdb'))
if not ok then
local resp = {api = "error",desc = "failed to select db",body = err}
ngx.say(cjson.encode(resp))
return
end
if ngx.var.cur == 'usd' then
the_key = config:get('usd_involved_trade_key')
elseif ngx.var.cur == 'cny' then
the_key = config:get('cny_involved_trade_key')
else
local resp = {api = "error",desc = "illegal currency code"}
ngx.say(cjson.encode(resp))
return
end
local res, err = red:get(the_key)
if not res then
local resp = {api = "error",desc = "failed to get the key",body = err}
ngx.say(cjson.encode(resp))
return
end
if res == ngx.null then
local resp = {api = "error",desc = "the key not found"}
ngx.say(cjson.encode(resp))
return
end
local resp = {api = "base",cur = ngx.var.cur,body = cjson.decode(res)}
ngx.say(cjson.encode(resp))
| mit |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Commands/CommandMenu.lua | 1 | 15879 | --[[
Title: menu command
Author(s): LiXizhi
Date: 2014/11/14
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandMenu.lua");
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Files.lua");
local Files = commonlib.gettable("MyCompany.Aries.Game.Common.Files");
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local SlashCommand = commonlib.gettable("MyCompany.Aries.SlashCommand.SlashCommand");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local CmdParser = commonlib.gettable("MyCompany.Aries.Game.CmdParser");
local ItemClient = commonlib.gettable("MyCompany.Aries.Game.Items.ItemClient");
local UndoManager = commonlib.gettable("MyCompany.Aries.Game.UndoManager");
local GameMode = commonlib.gettable("MyCompany.Aries.Game.GameLogic.GameMode");
local Commands = commonlib.gettable("MyCompany.Aries.Game.Commands");
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager");
Commands["menu"] = {
name="menu",
quick_ref="/menu [menu_cmd_name]",
desc=[[menu commands
/menu file.settings
/menu file.openworlddir
/menu file.saveworld
/menu file.createworld
/menu file.loadworld
/menu file.worldrevision
/menu file.uploadworld
/menu file.export
/menu file.exit
/menu window.texturepack
/menu window.info
/menu window.pos
/menu online.server
/menu help.help
/menu help.help.shortcutkey
/menu help.help.tutorial.newusertutorial
/menu help.about
/menu help.npl_code_wiki
/menu help.actiontutorial
/menu help.newuserguide
/menu edit.undo
/menu edit.redo
/menu edit.bookmark.next
/menu edit.bookmark.previous
/menu edit.bookmark.add
/menu edit.bookmark.viewall
]],
handler = function(cmd_name, cmd_text, cmd_params)
-- apply filter
if (GameLogic.GetFilters():apply_filters("menu_command", false, cmd_name, cmd_text, cmd_params)) then
return;
end
local name, bIsShow;
name, cmd_text = CmdParser.ParseString(cmd_text);
if(not name) then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/DesktopMenuPage.lua");
local DesktopMenuPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.DesktopMenuPage");
DesktopMenuPage.ActivateMenu(true);
return;
end
LOG.std(nil, "debug", "menu", "menu command %s", name);
if(name:match("^file")) then
if(name == "file.settings") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/SystemSettingsPage.lua");
local SystemSettingsPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.SystemSettingsPage");
SystemSettingsPage.ShowPage()
elseif(name == "file.openworlddir") then
if(not GameLogic.IsReadOnly() or GameLogic.IsRemoteWorld()) then
Map3DSystem.App.Commands.Call("File.WinExplorer", ParaWorld.GetWorldDirectory());
else
Map3DSystem.App.Commands.Call("File.WinExplorer", ParaWorld.GetWorldDirectory():gsub("([^/\\]+)[/\\]?$",""));
end
elseif(name == "file.saveworld") then
if(System.options.mc) then
if(GameLogic.IsReadOnly()) then
GameLogic.RunCommand("/menu file.saveworldas");
else
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/SaveWorldPage.lua");
local SaveWorldPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.Areas.SaveWorldPage");
SaveWorldPage.ShowPage()
end
else
NPL.load("(gl)script/apps/Aries/Creator/Game/GameMarket/SaveWorldPage.lua");
local SaveWorldPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.SaveWorldPage");
SaveWorldPage.ShowPage()
end
elseif(name == "file.saveworldas") then
NPL.load("(gl)script/apps/Aries/Creator/WorldCommon.lua");
local WorldCommon = commonlib.gettable("MyCompany.Aries.Creator.WorldCommon")
WorldCommon.SaveWorldAs()
elseif(name == "file.createworld") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Login/CreateNewWorld.lua");
local CreateNewWorld = commonlib.gettable("MyCompany.Aries.Game.MainLogin.CreateNewWorld")
CreateNewWorld.ShowPage()
elseif(name == "file.loadworld") then
-- NPL.load("(gl)script/apps/Aries/Creator/Game/Login/InternetLoadWorld.lua");
-- local InternetLoadWorld = commonlib.gettable("MyCompany.Aries.Creator.Game.Login.InternetLoadWorld");
-- InternetLoadWorld.ShowPage(true);
GameLogic.GetFilters():apply_filters("cellar.opus.show");
elseif(name == "file.export") then
GameLogic.RunCommand("export");
elseif(name == "file.worldrevision") then
if(not GameLogic.IsReadOnly()) then
if GameLogic.world_revision then
GameLogic.world_revision:Backup();
GameLogic.world_revision:OnOpenRevisionDir();
end
else
_guihelper.MessageBox(L"世界是只读的,无需备份");
end
elseif(name == "file.openbackupfolder") then
GameLogic.world_revision:OnOpenRevisionDir();
elseif(name == "file.uploadworld") then
if(System.options.mc) then
NPL.load("(gl)script/apps/Aries/Creator/SaveWorldPage.lua");
MyCompany.Aries.Creator.SaveWorldPage.ShowSharePage()
--NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/SaveWorldPage.lua");
--MyCompany.Aries.Creator.Game.Desktop.Areas.SaveWorldPage.ShowSharePage()
else
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/EditorModeSwitchPage.lua");
EditorModeSwitchPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.EditorModeSwitchPage");
EditorModeSwitchPage.OnClickUpload();
end
elseif(name == "file.exit") then
MyCompany.Aries.Creator.Game.Desktop.OnLeaveWorld(nil, true);
end
elseif(name:match("^edit")) then
if(name == "edit.undo") then
if(GameMode:IsAllowGlobalEditorKey()) then
UndoManager.Undo();
end
elseif(name == "edit.redo") then
if(GameMode:IsAllowGlobalEditorKey()) then
UndoManager.Redo();
end
elseif(name:match("^edit%.bookmark")) then
NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/TeleportListPage.lua");
local TeleportListPage = commonlib.gettable("MyCompany.Aries.Game.GUI.TeleportListPage");
if(name == "edit.bookmark.next") then
-- teleport to next location.
TeleportListPage.GotoNextLocation();
elseif(name == "edit.bookmark.previous") then
-- teleport to previous location
TeleportListPage.GotoPreviousLocation();
elseif(name == "edit.bookmark.add") then
-- add current bookmark location
TeleportListPage.AddCurrentLocation();
elseif(name == "edit.bookmark.viewall") then
TeleportListPage.ShowPage(nil, true);
elseif(name == "edit.bookmark.clearall") then
-- clear all bookmark location
TeleportListPage.ClearAll();
end
end
elseif(name:match("^window")) then
if(name == "window.texturepack") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/TextureModPage.lua");
local TextureModPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.TextureModPage");
TextureModPage.ShowPage(true);
elseif(name == "window.template") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/GoalTracker.lua");
local GoalTracker = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.GoalTracker");
GoalTracker.OnClickCody();
elseif(name == "window.info") then
CommandManager:RunCommand("/show info");
elseif(name == "window.pos") then
NPL.load("(gl)script/apps/Aries/Creator/Game/GUI/TeleportListPage.lua");
local TeleportListPage = commonlib.gettable("MyCompany.Aries.Game.GUI.TeleportListPage");
TeleportListPage.ShowPage(nil, true);
elseif(name == "window.find") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/FindBlockTask.lua");
local FindBlockTask = commonlib.gettable("MyCompany.Aries.Game.Tasks.FindBlockTask");
local task = MyCompany.Aries.Game.Tasks.FindBlockTask:new()
task:Run();
elseif(name == "window.explore") then
GameLogic.GetFilters():apply_filters('show_offical_worlds_page')
elseif (name == "window.role") then
GameLogic.CheckSignedIn(L"此功能需要登陆后才能使用",
function(result)
if (result) then
commonlib.TimerManager.SetTimeout(function()
local page = NPL.load("Mod/GeneralGameServerMod/App/ui/page.lua");
page.ShowUserInfoPage({username = System.User.keepworkUsername});
end, 250);
end
end)
elseif(name == "window.schoolcenter") then
local SchoolCenter = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SchoolCenter/SchoolCenter.lua")
SchoolCenter.OpenPage()
elseif(name == "window.friend") then
local FriendsPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/Friend/FriendsPage.lua");
FriendsPage.Show();
elseif(name == "window.sharemod") then
local ShareBlocksPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/ShareBlocksPage.lua");
ShareBlocksPage.ShowPage()
elseif(name == "window.changeskin") then
--[[
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/SkinPage.lua");
local SkinPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.SkinPage");
SkinPage.ShowPage();
]]
elseif(name == "window.mall") then
local KeepWorkMallPage = NPL.load("(gl)script/apps/Aries/Creator/Game/KeepWork/KeepWorkMallPage.lua");
KeepWorkMallPage.Show();
elseif(name == "window.userbag") then
local UserBagPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/User/UserBagPage.lua");
UserBagPage.ShowPage();
end
elseif(name == "online.server") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/ServerPage.lua");
local ServerPage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.ServerPage");
ServerPage.ShowPage()
elseif(name == "online.teacher_panel") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Admin/TeacherPanel.lua");
local TeacherPanel = commonlib.gettable("MyCompany.Aries.Game.Network.Admin.TeacherPanel");
TeacherPanel.ShowPage()
elseif(name == "organization.teacher_panel") then
local TeacherPanel = NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Admin/ClassManager/TeacherPanel.lua");
TeacherPanel.ShowPage()
elseif(name == "organization.student_panel") then
local StudentPanel = NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Admin/ClassManager/StudentPanel.lua");
StudentPanel.ShowPage()
elseif(name:match("^help")) then
if(name:match("^help%.help")) then
-- name can be "help.help", "help.help.tutorial", "help.help.shortcutkey"
-- "help.help.tutorial.newusertutorial", "help.help.tutorial.MovieMaking",
-- "help.help.tutorial.circuit", "help.help.tutorial.programming"
local category, subfolder;
category = name:match("^help%.help%.(.+)$");
if(category) then
if(category:match("%.")) then
category, subfolder = category:match("^([^%.]+)%.(.+)")
end
end
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/HelpPage.lua");
local HelpPage = commonlib.gettable("MyCompany.Aries.Game.Tasks.HelpPage");
if HelpPage.IsOpen() then
HelpPage.ClosePage()
else
HelpPage.ShowPage(category, subfolder);
end
elseif(name == "help.userintroduction") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Login/UserIntroduction.lua");
local UserIntroduction = commonlib.gettable("MyCompany.Aries.Game.MainLogin.UserIntroduction")
UserIntroduction.ShowPage()
elseif(name == "help.actiontutorial") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Login/TeacherAgent/TeacherAgent.lua");
local TeacherAgent = commonlib.gettable("MyCompany.Aries.Creator.Game.Teacher.TeacherAgent");
TeacherAgent:SetEnabled(not TeacherAgent:IsEnabled())
elseif(name == "help.videotutorials") then
GameLogic.RunCommand("/open "..L"https://keepwork.com/official/docs/videoguide");
elseif(name == "help.learn") then
GameLogic.RunCommand("/open "..L"https://keepwork.com/official/docs/index");
elseif(name == "help.home") then
GameLogic.RunCommand("/home")
elseif(name == "help.dailycheck" or name == "help.creativespace") then
GameLogic.CheckSignedIn(L"此功能需要登陆后才能使用",
function(result)
if (result) then
if(name == "help.dailycheck") then
local RedSummerCampRecCoursePage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampRecCoursePage.lua");
RedSummerCampRecCoursePage.Show();
--local ParacraftLearningRoomDailyPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/ParacraftLearningRoom/ParacraftLearningRoomDailyPage.lua");
--ParacraftLearningRoomDailyPage.DoCheckin();
elseif(name == "help.creativespace") then
local RedSummerCampMainWorldPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampMainWorldPage.lua");
local RedSummerCampPPtPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampPPtPage.lua");
local RedSummerCampCourseScheduling = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampCourseSchedulingV2.lua")
if RedSummerCampCourseScheduling.IsOpen() then
RedSummerCampPPtPage.ClosePPtAllPage()
else
-- RedSummerCampMainWorldPage.SetOpenFromCommandMenu(true)
-- RedSummerCampMainWorldPage.Show();
RedSummerCampCourseScheduling.ShowView()
RedSummerCampPPtPage.OpenLastPPtPage(true)
end
end
end
end)
elseif(name == "help.newuserguide") then
NPL.load("(gl)script/apps/Aries/Creator/Game/Login/UserGuide.lua");
local UserGuide = commonlib.gettable("MyCompany.Aries.Game.MainLogin.UserGuide")
UserGuide.Start(true)
elseif(name == "help.ask") then
GameLogic.RunCommand("/open "..L"https://keepwork.com/official/docs/FAQ/paracraft");
elseif(name == "help.lessons") then
GameLogic.RunCommand("/open "..L"https://keepwork.com/kecheng/cs/all");
elseif(name == "help.npl_code_wiki") then
-- open the npl code wiki site in external browser.
GameLogic.CommandManager:RunCommand("/open npl://");
elseif(name == "help.about") then
-- GameLogic.RunCommand("/open "..L"http://www.paracraft.cn/home/about-us");
System.App.Commands.Call("File.MCMLWindowFrame", {
url = "script/apps/Aries/Creator/Game/Login/AboutParacraft.html",
name = "aboutparacraft",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 0,
allowDrag = false,
directPosition = true,
align = "_ct",
x = -600/2,
y = -400/2,
width = 600,
height = 400,
cancelShowAnimation = true,
});
elseif(name == "help.Credits") then
GameLogic.RunCommand("/open "..L"https://keepwork.com/official/paracraft/credits");
elseif(name == "help.ParacraftSDK") then
GameLogic.RunCommand("/open https://github.com/LiXizhi/ParaCraftSDK/wiki");
elseif(name == "help.bug") then
GameLogic.RunCommand("/open https://github.com/LiXizhi/ParaCraft/issues");
elseif(name == "help.donate") then
GameLogic.RunCommand("/open "..L"http://www.nplproject.com/paracraft-donation");
end
elseif(name == "share.panoramasharing") then
GameLogic.GetFilters():apply_filters("show_panorama");
elseif(name:match("^community")) then
local username = System.User.keepworkUsername
if(username) then
if(name == "community.myProfile") then
GameLogic.RunCommand("/open "..format("https://keepwork.com/u/%s", username));
elseif(name == "community.myProjects") then
GameLogic.RunCommand("/open "..format("https://keepwork.com/u/%s/project", username));
end
end
end
end,
};
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/CodeAPI.lua | 1 | 7618 | --[[
Title: CodeAPI
Author(s): LiXizhi
Date: 2018/5/16
Desc: sandbox API environment, see also CodeGlobals for shared API and globals.
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI.lua");
local CodeAPI = commonlib.gettable("MyCompany.Aries.Game.Code.CodeAPI");
local api = CodeAPI:new(codeBlock);
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_Events.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_MotionLooks.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_Sensing.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_Sound.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_Data.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_Control.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeAPI_Microbit.lua");
-- all public environment methods.
local s_env_methods = {
"resume",
"yield",
"checkyield",
"checkstep",
"checkstep_nplblockly",
"terminate",
"restart",
"exit",
"xpcall",
"GetEntity",
-- Data
"print",
"printStack",
"log",
"echo",
"alert",
"setActorValue",
"getActorValue",
"getActorEntityValue",
"showVariable",
"include",
"import",
"getActor",
"cmd",
"getPlayTimer",
-- operator
"string_length",
"string_char",
"string_contain",
-- Motion
"move",
"moveTo",
"moveForward",
"walk",
"walkForward",
"turn",
"turnTo",
"rotate",
"rotateTo",
"bounce",
"velocity",
"getX",
"getY",
"getZ",
"getFacing",
"getPos",
"setPos",
"setBlockPos",
"getPlayerPos",
-- Looks
"say",
"show",
"hide",
"anim",
"play",
"playAndWait",
"playLoop",
"playSpeed",
"playBone",
"stop",
"scale",
"scaleTo",
"getPlayTime",
"getScale",
"attachTo",
"focus",
"camera",
"getCamera",
"setMovie",
"isMatchMovie",
"playMatchedMovie",
"setMovieProperty",
"playMovie",
"stopMovie",
"window",
-- Events
"registerClickEvent",
"registerKeyPressedEvent",
"registerAnimationEvent",
"registerBroadcastEvent",
"registerBlockClickEvent",
"registerTickEvent",
"registerStopEvent",
"registerAgentEvent",
"broadcast",
"broadcastAndWait",
"broadcastTo",
"registerNetworkEvent",
"broadcastNetworkEvent",
"sendNetworkEvent",
-- Control
"wait",
"waitUntil",
"registerCloneEvent",
"clone",
"delete",
"run",
"runForActor",
"becomeAgent",
"setOutput",
-- Sensing
"isTouching",
"registerCollisionEvent",
"broadcastCollision",
"distanceTo",
"calculatePushOut",
"isKeyPressed",
"isMouseDown",
"getTimer",
"resetTimer",
"ask",
-- Sound
"playNote",
"playSound",
"playSoundAndWait",
"stopSound",
"playMusic",
"playText",
--------------- NplMicroRobot
"start_NplMicroRobot",
-- Motion
"createOrGetAnimationClip_NplMicroRobot",
"createAnimationClip_NplMicroRobot",
"createTimeLine_NplMicroRobot",
"playAnimationClip_NplMicroRobot",
"stopAnimationClip_NplMicroRobot",
-- Looks
"microbit_show_leds",
"microbit_show_string",
"microbit_pause",
-- Events
"registerKeyPressedEvent_NplMicroRobot",
"registerGestureEvent_NplMicroRobot",
-- Sensing
"microbit_is_pressed",
--------------- Microbit
-- Animation
"createRobotAnimation",
"addRobotAnimationChannel",
"endRobotAnimationChannel",
"addAnimationTimeValue_Rotation",
-- Motion
"playRobotAnimation",
"microbit_servo",
"microbit_sleep",
"rotateBone",
-- Looks
"microbit_display_show",
"microbit_display_scroll",
"microbit_display_clear",
}
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local CodeAPI = commonlib.gettable("MyCompany.Aries.Game.Code.CodeAPI");
local env_imp = commonlib.gettable("MyCompany.Aries.Game.Code.env_imp");
CodeAPI.__index = CodeAPI;
-- @param actor: CodeActor that this code API is controlling.
function CodeAPI:new(codeBlock)
local o = {
codeblock = codeBlock,
check_count = 0,
};
o._G = GameLogic.GetCodeGlobal():GetCurrentGlobals();
CodeAPI.InstallMethods(o);
GameLogic.GetFilters():apply_filters("CodeAPIInstallMethods",o);
setmetatable(o, GameLogic.GetCodeGlobal():GetCurrentMetaTable());
return o;
end
-- install functions to code environment
function CodeAPI.InstallMethods(o)
for _, func_name in ipairs(s_env_methods) do
local f = function(...)
return env_imp[func_name](o, ...);
end
o[func_name] = f;
end
end
-- get function by name
function CodeAPI.GetAPIFunction(func_name)
return env_imp[func_name];
end
-- yield control until all async jobs are completed
-- @param bExitOnError: if true, this function will handle error
-- @return err, msg: err is true if there is error.
function env_imp:yield(bExitOnError)
local err, msg, p3, p4;
if(self.co) then
if(self.fake_resume_res) then
err, msg = unpack(self.fake_resume_res);
self.fake_resume_res = nil;
return err, msg;
else
self.check_count = 0;
err, msg, p3, p4 = self.co:Yield();
if(err and bExitOnError) then
env_imp.exit(self);
end
end
end
return err, msg, p3, p4;
end
-- resume from where jobs are paused last.
-- @param err: if there is error, this is true, otherwise it is nil.
-- @param msg: error message in case err=true
function env_imp:resume(err, msg, p3, p4)
if(self.co) then
if(self.co:GetStatus() == "running") then
self.fake_resume_res = {err, msg, p3, p4};
return;
else
self.fake_resume_res = nil;
end
local res, err, msg = self.co:Resume(err, msg, p3, p4);
end
end
-- calling this function 100 times will automatically yield and resume until next tick (1/30 seconds)
-- we will automatically insert this function into while and for loop. One can also call this manually
-- @param count: default to 1. heavy operations can make this larger
function env_imp:checkyield(count)
self.check_count = self.check_count + (count or 1);
if(self.check_count > 100) then
if(self.codeblock:IsAutoWait() and (self.co and coroutine.running() == self.co.co)) then
env_imp.wait(self, env_imp.GetDefaultTick(self));
else
self.check_count = 0;
end
end
end
-- @param duration: wait for this seconds. default to 1.
function env_imp:checkstep(duration)
-- 图块模式直接跳过
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeBlockWindow.lua");
local CodeBlockWindow = commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlockWindow");
if (CodeBlockWindow.IsSupportNplBlockly()) then return end
local locationInfo = commonlib.debug.locationinfo(2)
if(locationInfo) then
GameLogic.GetFilters():apply_filters("OnCodeBlockLineStep", locationInfo);
end
env_imp.wait(self, 1);
end
function env_imp:checkstep_nplblockly(blockid, before, duration)
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/CodeBlockWindow.lua");
local CodeBlockWindow = commonlib.gettable("MyCompany.Aries.Game.Code.CodeBlockWindow");
local entity = CodeBlockWindow.GetCodeEntity()
if(not entity or not entity:IsStepMode()) then return end
if (not CodeBlockWindow.IsSupportNplBlockly()) then return end
if (before) then -- 代码执行前
GameLogic.GetFilters():apply_filters("OnCodeBlockNplBlocklyLineStep", blockid);
env_imp.wait(self, duration or 0.5);
else -- 代码执行后
env_imp.wait(self, duration or 0.5);
GameLogic.GetFilters():apply_filters("OnCodeBlockNplBlocklyLineStep", blockid);
end
end
-- private:
function env_imp:GetDefaultTick()
if(not self.default_tick) then
self.default_tick = self.codeBlock and self.codeBlock:GetDefaultTick() or 0.02;
end
return self.default_tick;
end
| gpl-2.0 |
ramin65/ub-ub | plugins/info.lua | 12 | 2022 | do
local function action_by_reply(extra, success, result)
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..result.from.id..']'
local msgs = '4-تعداد پیام های ارسالی : '..user_info.msgs
if result.from.username then
user_name = '@'..result.from.username
else
user_name = ''
end
local msg = result
local user_id = msg.from.id
local chat_id = msg.to.id
local user = 'user#id'..msg.from.id
local chat = 'chat#id'..msg.to.id
local data = load_data(_config.moderation.data)
if data[tostring('admins')][tostring(user_id)] then
who = 'ادمین گروه'
elseif data[tostring(msg.to.id)]['moderators'][tostring(user_id)] then
who = 'ادمین گروه'
elseif data[tostring(msg.to.id)]['set_owner'] == tostring(user_id) then
who = 'مدیر ارشد گروه'
elseif tonumber(result.from.id) == tonumber(our_id) then
who = 'سازنده گروه'
else
who = 'عضو معمولی گروه'
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
who = 'سازنده ربات'
end
end
local text = '1-نام کامل : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'2-یوزنیم : '..user_name..'\n'
..'3-ایدی : '..result.from.id..'\n'
..msgs..'\n'
..'5-نقش در گروه : '..who
send_large_msg(extra.receiver, text)
end
local function run(msg)
if msg.text == '!info' and msg.reply_id and is_momod(msg) then
get_message(msg.reply_id, action_by_reply, {receiver=get_receiver(msg)})
end
end
return {
patterns = {
'^!info$'
},
run = run
}
end
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/techniques/pugilism.lua | 2 | 11936 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
getRelentless = function(self, cd)
local cd = 1
if self:knowTalent(self.T_RELENTLESS_STRIKES) then
local t = self:getTalentFromId(self.T_RELENTLESS_STRIKES)
cd = 1 - t.getCooldownReduction(self, t)
end
return cd
end,
newTalent{
name = "Striking Stance",
type = {"technique/unarmed-other", 1},
mode = "sustained",
hide = true,
points = 1,
cooldown = 12,
tactical = { BUFF = 2 },
type_no_req = true,
no_npc_use = true, -- They dont need it since it auto switches anyway
no_unlearn_last = true,
getAttack = function(self, t) return self:getDex(25, true) end,
getDamage = function(self, t) return self:combatStatScale("dex", 5, 35) end,
getFlatReduction = function(self, t) return math.min(35, self:combatStatScale("str", 1, 30, 0.75)) end,
-- 13 Strength = 2, 20 = 5, 30 = 9, 40 = 12, 50 = 16, 55 = 17, 70 = 22, 80 = 25
activate = function(self, t)
cancelStances(self)
local ret = {
atk = self:addTemporaryValue("combat_atk", t.getAttack(self, t)),
flat = self:addTemporaryValue("flat_damage_armor", {all = t.getFlatReduction(self, t)})
}
return ret
end,
deactivate = function(self, t, p)
self:removeTemporaryValue("combat_atk", p.atk)
self:removeTemporaryValue("flat_damage_armor", p.flat)
return true
end,
info = function(self, t)
local attack = t.getAttack(self, t)
local damage = t.getDamage(self, t)
return ([[Increases your Accuracy by %d, the damage multiplier of your striking talents (Pugilism and Finishing Moves) by %d%%, and reduces all damage taken by %d.
The offensive bonuses scale with your Dexterity and the damage reduction with your Strength.]]):
format(attack, damage, t.getFlatReduction(self, t))
end,
}
newTalent{
name = "Double Strike", -- no stamina cost attack that will replace the bump attack under certain conditions
type = {"technique/pugilism", 1},
require = techs_dex_req1,
points = 5,
random_ego = "attack",
--cooldown = function(self, t) return math.ceil(3 * getRelentless(self, cd)) end,
cooldown = 3,
message = "@Source@ throws two quick punches.",
tactical = { ATTACK = { weapon = 2 } },
requires_target = true,
getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 0.5, 0.8) + getStrikingStyle(self, dam) end,
-- Learn the appropriate stance
on_learn = function(self, t)
if not self:knowTalent(self.T_STRIKING_STANCE) then
self:learnTalent(self.T_STRIKING_STANCE, true, nil, {no_unlearn=true})
end
end,
on_unlearn = function(self, t)
if not self:knowTalent(t) then
self:unlearnTalent(self.T_STRIKING_STANCE)
end
end,
action = function(self, t)
local tg = {type="hit", range=self:getTalentRange(t)}
local x, y, target = self:getTarget(tg)
if not x or not y or not target then return nil end
if core.fov.distance(self.x, self.y, x, y) > 1 then return nil end
-- force stance change
if target and not self:isTalentActive(self.T_STRIKING_STANCE) then
self:forceUseTalent(self.T_STRIKING_STANCE, {ignore_energy=true, ignore_cd = true})
end
-- breaks active grapples if the target is not grappled
local grappled
if target:isGrappled(self) then
grappled = true
else
self:breakGrapples()
end
local hit1 = false
local hit2 = false
hit1 = self:attackTarget(target, nil, t.getDamage(self, t), true)
hit2 = self:attackTarget(target, nil, t.getDamage(self, t), true)
-- build combo points
local combo = false
if self:getTalentLevel(t) >= 4 then
combo = true
end
if combo then
if hit1 then
self:buildCombo()
end
if hit2 then
self:buildCombo()
end
elseif hit1 or hit2 then
self:buildCombo()
end
return true
end,
info = function(self, t)
local damage = t.getDamage(self, t) * 100
return ([[Deliver two quick punches that deal %d%% damage each, and switch your stance to Striking Stance. If you already have Striking Stance active and Double Strike isn't on cooldown, this talent will automatically replace your normal attacks (and trigger the cooldown).
If either jab connects, you earn one combo point. At talent level 4 or greater, if both jabs connect, you'll earn two combo points.]])
:format(damage)
end,
}
newTalent{
name = "Spinning Backhand",
type = {"technique/pugilism", 2},
require = techs_dex_req2,
points = 5,
random_ego = "attack",
--cooldown = function(self, t) return math.ceil(12 * getRelentless(self, cd)) end,
cooldown = 8,
stamina = 12,
range = function(self, t) return math.ceil(2 + self:combatTalentScale(t, 2.2, 4.3)) end, -- being able to use this over rush without massive investment is much more fun
chargeBonus = function(self, t, dist) return self:combatScale(dist, 0.15, 1, 0.50, 5) end,
message = "@Source@ lashes out with a spinning backhand.",
tactical = { ATTACKAREA = { weapon = 2 }, CLOSEIN = 1 },
requires_target = true,
getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 1.0, 1.7) + getStrikingStyle(self, dam) end,
on_pre_use = function(self, t) return not self:attr("never_move") end,
action = function(self, t)
local tg = {type="bolt", range=self:getTalentRange(t)}
local x, y, target = self:getTarget(tg)
if not x or not y or not target then return nil end
if core.fov.distance(self.x, self.y, x, y) > self:getTalentRange(t) then return nil end
-- bonus damage for charging
local charge = t.chargeBonus(self, t, (core.fov.distance(self.x, self.y, x, y) - 1))
local damage = t.getDamage(self, t) + charge
-- do the rush
local block_actor = function(_, bx, by) return game.level.map:checkEntity(bx, by, Map.TERRAIN, "block_move", self) end
local l = self:lineFOV(x, y, block_actor)
local lx, ly, is_corner_blocked = l:step()
local tx, ty = self.x, self.y
while lx and ly do
if is_corner_blocked or game.level.map:checkAllEntities(lx, ly, "block_move", self) then break end
tx, ty = lx, ly
lx, ly, is_corner_blocked = l:step()
end
local ox, oy = self.x, self.y
self:move(tx, ty, true)
if config.settings.tome.smooth_move > 0 then
self:resetMoveAnim()
self:setMoveAnim(ox, oy, 8, 5)
end
local hit1 = false
local hit2 = false
local hit3 = false
-- do the backhand
if core.fov.distance(self.x, self.y, x, y) == 1 then
-- get left and right side
local dir = util.getDir(x, y, self.x, self.y)
local lx, ly = util.coordAddDir(self.x, self.y, util.dirSides(dir, self.x, self.y).left)
local rx, ry = util.coordAddDir(self.x, self.y, util.dirSides(dir, self.x, self.y).right)
local lt, rt = game.level.map(lx, ly, Map.ACTOR), game.level.map(rx, ry, Map.ACTOR)
hit1 = self:attackTarget(target, nil, damage, true)
--left hit
if lt then
hit2 = self:attackTarget(lt, nil, damage, true)
end
--right hit
if rt then
hit3 = self:attackTarget(rt, nil, damage, true)
end
end
-- remove grappls
self:breakGrapples()
-- build combo points
local combo = false
if self:getTalentLevel(t) >= 4 then
combo = true
end
if combo then
if hit1 then
self:buildCombo()
end
if hit2 then
self:buildCombo()
end
if hit3 then
self:buildCombo()
end
elseif hit1 or hit2 or hit3 then
self:buildCombo()
end
return true
end,
info = function(self, t)
local damage = t.getDamage(self, t) * 100
local charge =t.chargeBonus(self, t, t.range(self, t)-1)*100
return ([[Attack your foes in a frontal arc with a spinning backhand, doing %d%% damage. If you're not adjacent to the target, you'll step forward as you spin, gaining up to %d%% bonus damage, which increases the farther you move.
This attack will remove any grapples you're maintaining, and earn one combo point (or one combo point per attack that connects, if the talent level is 4 or greater).]])
:format(damage, charge)
end,
}
newTalent{
name = "Axe Kick",
type = {"technique/pugilism", 3},
require = techs_dex_req3,
points = 5,
stamina = 20,
random_ego = "attack",
cooldown = function(self, t)
return 20
end,
getDuration = function(self, t)
return self:combatTalentLimit(t, 5, 1, 4)
end,
message = "@Source@ raises their leg and snaps it downward in a devastating axe kick.",
tactical = { ATTACK = { weapon = 2 } },
requires_target = true,
getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 0.8, 2) + getStrikingStyle(self, dam) end, -- low damage scaling, investment gets the extra CP
action = function(self, t)
local tg = {type="hit", range=self:getTalentRange(t)}
local x, y, target = self:getTarget(tg)
if not x or not y or not target then return nil end
if core.fov.distance(self.x, self.y, x, y) > 1 then return nil end
-- breaks active grapples if the target is not grappled
if not target:isGrappled(self) then
self:breakGrapples()
end
local hit1 = false
hit1 = self:attackTarget(target, nil, t.getDamage(self, t), true)
if hit1 and target:canBe("confusion") then
target:setEffect(target.EFF_DELIRIOUS_CONCUSSION, t.getDuration(self, t), {})
end
-- build combo points
if hit1 then
self:buildCombo()
self:buildCombo()
end
return true
end,
info = function(self, t)
local damage = t.getDamage(self, t) * 100
return ([[Deliver a devastating axe kick dealing %d%% damage. If the blow connects your target is brain damaged, causing all talents to fail for %d turns and earning 2 combo points.
This effect cannot be saved against, though it can be dodged and checks confusion immunity.]])
:format(damage, t.getDuration(self, t))
end,
}
newTalent{
name = "Flurry of Fists",
type = {"technique/pugilism", 4},
require = techs_dex_req4,
points = 5,
random_ego = "attack",
cooldown = 16,
stamina = 15,
message = "@Source@ lashes out with a flurry of fists.",
tactical = { ATTACK = { weapon = 2 } },
requires_target = true,
getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 0.3, 1) + getStrikingStyle(self, dam) end,
action = function(self, t)
local tg = {type="hit", range=self:getTalentRange(t)}
local x, y, target = self:getTarget(tg)
if not x or not y or not target then return nil end
if core.fov.distance(self.x, self.y, x, y) > 1 then return nil end
-- breaks active grapples if the target is not grappled
if not target:isGrappled(self) then
self:breakGrapples()
end
local hit1 = false
local hit2 = false
local hit3 = false
hit1 = self:attackTarget(target, nil, t.getDamage(self, t), true)
hit2 = self:attackTarget(target, nil, t.getDamage(self, t), true)
hit3 = self:attackTarget(target, nil, t.getDamage(self, t), true)
--build combo points
local combo = false
if self:getTalentLevel(t) >= 4 then
combo = true
end
if combo then
if hit1 then
self:buildCombo()
end
if hit2 then
self:buildCombo()
end
if hit3 then
self:buildCombo()
end
elseif hit1 or hit2 or hit3 then
self:buildCombo()
end
return true
end,
info = function(self, t)
local damage = t.getDamage(self, t) * 100
return ([[Lashes out at the target with three quick punches that each deal %d%% damage.
Earns one combo point. If your talent level is 4 or greater, this instead earns one combo point per blow that connects.]])
:format(damage)
end,
}
| gpl-3.0 |
rubenvb/skia | tools/lua/glyph-usage.lua | 207 | 4034 | function tostr(t)
local str = ""
for k, v in next, t do
if #str > 0 then
str = str .. ", "
end
if type(k) == "number" then
str = str .. "[" .. k .. "] = "
else
str = str .. tostring(k) .. " = "
end
if type(v) == "table" then
str = str .. "{ " .. tostr(v) .. " }"
else
str = str .. tostring(v)
end
end
return str
end
local canvas -- holds the current canvas (from startcanvas())
--[[
startcanvas() is called at the start of each picture file, passing the
canvas that we will be drawing into, and the name of the file.
Following this call, there will be some number of calls to accumulate(t)
where t is a table of parameters that were passed to that draw-op.
t.verb is a string holding the name of the draw-op (e.g. "drawRect")
when a given picture is done, we call endcanvas(canvas, fileName)
]]
function sk_scrape_startcanvas(c, fileName)
canvas = c
end
--[[
Called when the current canvas is done drawing.
]]
function sk_scrape_endcanvas(c, fileName)
canvas = nil
end
--[[
Called with the parameters to each canvas.draw call, where canvas is the
current canvas as set by startcanvas()
]]
function round(x, mul)
mul = mul or 1
return math.floor(x * mul + 0.5) / mul
end
dump_glyph_array_p = false
function dump_array_as_C(array)
for k, v in next, array do
io.write(tostring(v), ", ");
end
io.write("-1,\n")
end
local strikes = {} -- [fontID_pointsize] = [] unique glyphs
function make_strike_key(paint)
return paint:getFontID() * 1000 + paint:getTextSize()
end
-- array is an array of bools (true), using glyphID as the index
-- other is just an array[1...N] of numbers (glyphIDs)
function array_union(array, other)
for k, v in next, other do
array[v] = true;
end
end
-- take a table of bools, indexed by values, and return a sorted table of values
function bools_to_values(t)
local array = {}
for k, v in next, t do
array[#array + 1] = k
end
table.sort(array)
return array
end
function array_count(array)
local n = 0
for k in next, array do
n = n + 1
end
return n
end
function sk_scrape_accumulate(t)
verb = t.verb;
if verb == "drawPosText" or verb == "drawPosTextH" then
if t.glyphs then
local key = make_strike_key(t.paint)
strikes[key] = strikes[key] or {}
array_union(strikes[key], t.glyphs)
if dump_glyph_array_p then
dump_array_as_C(t.glyphs)
end
end
end
end
--[[
lua_pictures will call this function after all of the pictures have been
"accumulated".
]]
function sk_scrape_summarize()
local totalCount = 0
local strikeCount = 0
local min, max = 0, 0
local histogram = {}
for k, v in next, strikes do
local fontID = round(k / 1000)
local size = k - fontID * 1000
local count = array_count(v)
-- io.write("fontID,", fontID, ", size,", size, ", entries,", count, "\n");
min = math.min(min, count)
max = math.max(max, count)
totalCount = totalCount + count
strikeCount = strikeCount + 1
histogram[count] = (histogram[count] or 0) + 1
end
local ave = round(totalCount / strikeCount)
io.write("\n", "unique glyphs: min = ", min, ", max = ", max, ", ave = ", ave, "\n");
for k, v in next, histogram do
io.write("glyph_count,", k, ",frequency,", v, "\n")
end
end
function test_summary()
io.write("just testing test_summary\n")
end
function summarize_unique_glyphIDs()
io.write("/* runs of unique glyph IDs, with a -1 sentinel between different runs */\n")
io.write("static const int gUniqueGlyphIDs[] = {\n");
for k, v in next, strikes do
dump_array_as_C(bools_to_values(v))
end
io.write("-1 };\n")
end
| bsd-3-clause |
tarantool/luarocks | src/luarocks/core/cfg.lua | 1 | 29230 |
--- Configuration for LuaRocks.
-- Tries to load the user's configuration file and
-- defines defaults for unset values. See the
-- <a href="http://luarocks.org/en/Config_file_format">config
-- file format documentation</a> for details.
--
-- End-users shouldn't edit this file. They can override any defaults
-- set in this file using their system-wide or user-specific configuration
-- files. Run `luarocks` with no arguments to see the locations of
-- these files in your platform.
local next, table, pairs, require, os, pcall, ipairs, package, tonumber, type, assert =
next, table, pairs, require, os, pcall, ipairs, package, tonumber, type, assert
local util = require("luarocks.core.util")
local persist = require("luarocks.core.persist")
local sysdetect = require("luarocks.core.sysdetect")
--------------------------------------------------------------------------------
local program_version = "3.1.3"
local program_series = "3.1"
local major_version = (program_version:match("([^.]%.[^.])")) or program_series
local is_windows = package.config:sub(1,1) == "\\"
-- Set order for platform overrides.
-- More general platform identifiers should be listed first,
-- more specific ones later.
local platform_order = {
-- Unixes
"unix",
"bsd",
"solaris",
"netbsd",
"openbsd",
"freebsd",
"linux",
"macosx",
"cygwin",
"msys",
"haiku",
-- Windows
"windows",
"win32",
"mingw32",
}
local function detect_sysconfdir()
local src = debug.getinfo(1, "S").source:gsub("\\", "/"):gsub("/+", "/")
if src:sub(1, 1) == "@" then
src = src:sub(2)
end
local basedir = src:match("^(.*)/luarocks/core/cfg.lua$")
if not basedir then
return
end
-- If installed in a Unix-like tree, use a Unix-like sysconfdir
local installdir = basedir:match("^(.*)/share/lua/[^/]*$")
if installdir then
if installdir == "/usr" then
return "/etc/luarocks"
end
return installdir .. "/etc/luarocks"
end
-- Otherwise, use base directory of sources
return basedir
end
local function set_confdirs(cfg, platforms, hardcoded)
local sysconfdir = os.getenv("LUAROCKS_SYSCONFDIR") or hardcoded.SYSCONFDIR
if platforms.windows then
cfg.home = os.getenv("APPDATA") or "c:"
cfg.home_tree = cfg.home.."/luarocks"
cfg.homeconfdir = cfg.home_tree
cfg.sysconfdir = sysconfdir or ((os.getenv("PROGRAMFILES") or "c:") .. "/luarocks")
else
if not sysconfdir then
sysconfdir = detect_sysconfdir()
end
cfg.home = hardcoded.HOMEDIR or os.getenv("HOME") or ""
cfg.localdir = hardcoded.LOCALDIR or cfg.home
local home_tree_subdir = hardcoded.HOME_TREE_SUBDIR or "/.luarocks"
cfg.homeconfdir = cfg.localdir .. home_tree_subdir
cfg.sysconfdir = sysconfdir or "/etc/luarocks"
cfg.home_tree = cfg.localdir .. home_tree_subdir
end
end
local load_config_file
do
-- Create global environment for the config files;
local function env_for_config_file(cfg, platforms)
local e
e = {
home = cfg.home,
lua_version = cfg.lua_version,
platforms = util.make_shallow_copy(platforms),
processor = cfg.target_cpu, -- remains for compat reasons
target_cpu = cfg.target_cpu, -- replaces `processor`
os_getenv = os.getenv,
variables = cfg.variables or {},
dump_env = function()
-- debug function, calling it from a config file will show all
-- available globals to that config file
print(util.show_table(e, "global environment"))
end,
}
return e
end
-- Merge values from config files read into the `cfg` table
local function merge_overrides(cfg, overrides)
-- remove some stuff we do not want to integrate
overrides.os_getenv = nil
overrides.dump_env = nil
-- remove tables to be copied verbatim instead of deeply merged
if overrides.rocks_trees then cfg.rocks_trees = nil end
if overrides.rocks_servers then cfg.rocks_servers = nil end
-- perform actual merge
util.deep_merge(cfg, overrides)
end
local function update_platforms(platforms, overrides)
if overrides[1] then
for k, _ in pairs(platforms) do
platforms[k] = nil
end
for _, v in ipairs(overrides) do
platforms[v] = true
end
-- set some fallback default in case the user provides an incomplete configuration.
-- LuaRocks expects a set of defaults to be available.
if not (platforms.unix or platforms.windows) then
platforms[is_windows and "windows" or "unix"] = true
end
end
end
-- Load config file and merge its contents into the `cfg` module table.
-- @return filepath of successfully loaded file or nil if it failed
load_config_file = function(cfg, platforms, filepath)
local result, err, errcode = persist.load_into_table(filepath, env_for_config_file(cfg, platforms))
if (not result) and errcode ~= "open" then
-- errcode is either "load" or "run"; bad config file, so error out
return nil, err, "config"
end
if result then
-- success in loading and running, merge contents and exit
update_platforms(platforms, result.platforms)
result.platforms = nil
merge_overrides(cfg, result)
return filepath
end
return nil -- nothing was loaded
end
end
local platform_sets = {
freebsd = { unix = true, bsd = true, freebsd = true },
openbsd = { unix = true, bsd = true, openbsd = true },
solaris = { unix = true, solaris = true },
windows = { windows = true, win32 = true },
cygwin = { unix = true, cygwin = true },
macosx = { unix = true, bsd = true, macosx = true, macos = true },
netbsd = { unix = true, bsd = true, netbsd = true },
haiku = { unix = true, haiku = true },
linux = { unix = true, linux = true },
mingw = { windows = true, win32 = true, mingw32 = true, mingw = true },
msys = { unix = true, cygwin = true, msys = true },
}
local function make_platforms(system)
-- fallback to Unix in unknown systems
return platform_sets[system] or { unix = true }
end
--------------------------------------------------------------------------------
local function make_defaults(lua_version, target_cpu, platforms, home, hardcoded)
-- Configure defaults:
local defaults = {
lua_interpreter = hardcoded.LUA_INTERPRETER or "lua",
local_by_default = hardcoded.LOCAL_BY_DEFAULT or false,
accept_unknown_fields = false,
fs_use_modules = true,
hooks_enabled = true,
deps_mode = "one",
check_certificates = false,
cache_timeout = 60,
cache_fail_timeout = 86400,
version_check_on_fail = true,
lua_modules_path = hardcoded.LUA_MODULES_LUA_SUBDIR or "/share/lua/"..lua_version,
lib_modules_path = hardcoded.LUA_MODULES_LIB_SUBDIR or "/lib/lua/"..lua_version,
rocks_subdir = hardcoded.ROCKS_SUBDIR or "/lib/luarocks/rocks-"..lua_version,
arch = "unknown",
lib_extension = "unknown",
obj_extension = "unknown",
link_lua_explicitly = false,
rocks_servers = hardcoded.ROCKS_SERVERS or {
{
"https://luarocks.org",
"https://raw.githubusercontent.com/rocks-moonscript-org/moonrocks-mirror/master/",
"http://luafr.org/moonrocks/",
"http://luarocks.logiceditor.com/rocks",
}
},
disabled_servers = {},
upload = {
server = "https://luarocks.org",
tool_version = "1.0.0",
api_version = "1",
},
lua_extension = "lua",
connection_timeout = 30, -- 0 = no timeout
variables = {
MAKE = "make",
CC = "cc",
LD = "ld",
AR = "ar",
RANLIB = "ranlib",
CVS = "cvs",
GIT = "git",
SSCM = "sscm",
SVN = "svn",
HG = "hg",
GPG = "gpg",
RSYNC = "rsync",
WGET = "wget",
SCP = "scp",
CURL = "curl",
PWD = "pwd",
MKDIR = "mkdir",
RMDIR = "rmdir",
CP = "cp",
LS = "ls",
RM = "rm",
FIND = "find",
CHMOD = "chmod",
ICACLS = "icacls",
MKTEMP = "mktemp",
ZIP = "zip",
UNZIP = "unzip -n",
GUNZIP = "gunzip",
BUNZIP2 = "bunzip2",
TAR = "tar",
MD5SUM = "md5sum",
OPENSSL = "openssl",
MD5 = "md5",
TOUCH = "touch",
CMAKE = "cmake",
SEVENZ = "7z",
RSYNCFLAGS = "--exclude=.git -Oavz",
CURLNOCERTFLAG = "",
WGETNOCERTFLAG = "",
},
external_deps_subdirs = hardcoded.EXTERNAL_DEPS_SUBDIRS or {
bin = "bin",
lib = "lib",
include = "include"
},
runtime_external_deps_subdirs = hardcoded.RUNTIME_EXTERNAL_DEPS_SUBDIRS or {
bin = "bin",
lib = "lib",
include = "include"
},
}
if platforms.windows then
defaults.arch = "win32-"..target_cpu
defaults.lib_extension = "dll"
defaults.external_lib_extension = "dll"
defaults.static_lib_extension = "lib"
defaults.obj_extension = "obj"
defaults.external_deps_dirs = { "c:/external/", "c:/windows/system32" }
defaults.makefile = "Makefile.win"
defaults.variables.MAKE = "nmake"
defaults.variables.CC = "cl"
defaults.variables.RC = "rc"
defaults.variables.LD = "link"
defaults.variables.MT = "mt"
defaults.variables.AR = "lib"
defaults.variables.LUALIB = "lua"..lua_version..".lib"
defaults.variables.CFLAGS = "/nologo /MD /O2"
defaults.variables.LIBFLAG = "/nologo /dll"
defaults.external_deps_patterns = {
bin = { "?.exe", "?.bat" },
lib = { "?.lib", "?.dll", "lib?.dll" },
include = { "?.h" }
}
defaults.runtime_external_deps_patterns = {
bin = { "?.exe", "?.bat" },
lib = { "?.dll", "lib?.dll" },
include = { "?.h" }
}
defaults.export_path_separator = ";"
defaults.wrapper_suffix = ".bat"
local localappdata = os.getenv("LOCALAPPDATA")
if not localappdata then
-- for Windows versions below Vista
localappdata = (os.getenv("USERPROFILE") or "c:/Users/All Users").."/Local Settings/Application Data"
end
defaults.local_cache = localappdata.."/LuaRocks/Cache"
defaults.web_browser = "start"
defaults.external_deps_subdirs.lib = { "", "lib", "bin" }
defaults.runtime_external_deps_subdirs.lib = { "", "lib", "bin" }
defaults.link_lua_explicitly = true
defaults.fs_use_modules = false
end
if platforms.mingw32 then
defaults.obj_extension = "o"
defaults.static_lib_extension = "a"
defaults.external_deps_dirs = { "c:/external/", "c:/mingw", "c:/windows/system32" }
defaults.cmake_generator = "MinGW Makefiles"
defaults.variables.MAKE = "mingw32-make"
defaults.variables.CC = "mingw32-gcc"
defaults.variables.RC = "windres"
defaults.variables.LD = "mingw32-gcc"
defaults.variables.AR = "ar"
defaults.variables.RANLIB = "ranlib"
defaults.variables.CFLAGS = "-O2"
defaults.variables.LIBFLAG = "-shared"
defaults.makefile = "Makefile"
defaults.external_deps_patterns = {
bin = { "?.exe", "?.bat" },
-- mingw lookup list from http://stackoverflow.com/a/15853231/1793220
-- ...should we keep ?.lib at the end? It's not in the above list.
lib = { "lib?.dll.a", "?.dll.a", "lib?.a", "cyg?.dll", "lib?.dll", "?.dll", "?.lib" },
include = { "?.h" }
}
defaults.runtime_external_deps_patterns = {
bin = { "?.exe", "?.bat" },
lib = { "cyg?.dll", "?.dll", "lib?.dll" },
include = { "?.h" }
}
end
if platforms.unix then
defaults.lib_extension = "so"
defaults.static_lib_extension = "a"
defaults.external_lib_extension = "so"
defaults.obj_extension = "o"
defaults.external_deps_dirs = { "/usr/local", "/usr", "/", hardcoded.PREFIX }
defaults.variables.CFLAGS = "-O2"
defaults.cmake_generator = "Unix Makefiles"
defaults.variables.CC = "gcc"
defaults.variables.LD = "gcc"
defaults.gcc_rpath = true
defaults.variables.LIBFLAG = "-shared"
defaults.external_deps_patterns = {
bin = { "?" },
lib = { "lib?.a", "lib?.so", "lib?.so.*" },
include = { "?.h" }
}
defaults.runtime_external_deps_patterns = {
bin = { "?" },
lib = { "lib?.so", "lib?.so.*" },
include = { "?.h" }
}
defaults.export_path_separator = ":"
defaults.wrapper_suffix = ""
defaults.local_cache = home.."/.cache/luarocks"
if not defaults.variables.CFLAGS:match("-fPIC") then
defaults.variables.CFLAGS = defaults.variables.CFLAGS.." -fPIC"
end
defaults.web_browser = "xdg-open"
end
if platforms.cygwin then
defaults.lib_extension = "so" -- can be overridden in the config file for mingw builds
defaults.arch = "cygwin-"..target_cpu
defaults.cmake_generator = "Unix Makefiles"
defaults.variables.CC = "echo -llua | xargs gcc"
defaults.variables.LD = "echo -llua | xargs gcc"
defaults.variables.LIBFLAG = "-shared"
defaults.link_lua_explicitly = true
end
if platforms.msys then
-- msys is basically cygwin made out of mingw, meaning the subsytem is unixish
-- enough, yet we can freely mix with native win32
defaults.external_deps_patterns = {
bin = { "?.exe", "?.bat", "?" },
lib = { "lib?.so", "lib?.so.*", "lib?.dll.a", "?.dll.a",
"lib?.a", "lib?.dll", "?.dll", "?.lib" },
include = { "?.h" }
}
defaults.runtime_external_deps_patterns = {
bin = { "?.exe", "?.bat" },
lib = { "lib?.so", "?.dll", "lib?.dll" },
include = { "?.h" }
}
end
if platforms.bsd then
defaults.variables.MAKE = "gmake"
end
if platforms.macosx then
defaults.variables.MAKE = "make"
defaults.external_lib_extension = "dylib"
defaults.arch = "macosx-"..target_cpu
defaults.variables.LIBFLAG = "-bundle -undefined dynamic_lookup -all_load"
local version = util.popen_read("sw_vers -productVersion")
version = tonumber(version and version:match("^[^.]+%.([^.]+)")) or 3
if version >= 10 then
version = 8
elseif version >= 5 then
version = 5
else
defaults.gcc_rpath = false
end
defaults.variables.CC = "env MACOSX_DEPLOYMENT_TARGET=10."..version.." gcc"
defaults.variables.LD = "env MACOSX_DEPLOYMENT_TARGET=10."..version.." gcc"
defaults.web_browser = "open"
end
if platforms.linux then
defaults.arch = "linux-"..target_cpu
local gcc_arch = util.popen_read("gcc -print-multiarch 2>/dev/null")
if gcc_arch and gcc_arch ~= "" then
defaults.external_deps_subdirs.lib = { "lib", "lib/" .. gcc_arch, "lib64" }
defaults.runtime_external_deps_subdirs.lib = { "lib", "lib/" .. gcc_arch, "lib64" }
else
defaults.external_deps_subdirs.lib = { "lib", "lib64" }
defaults.runtime_external_deps_subdirs.lib = { "lib", "lib64" }
end
end
if platforms.freebsd then
defaults.arch = "freebsd-"..target_cpu
defaults.gcc_rpath = false
defaults.variables.CC = "cc"
defaults.variables.LD = "cc"
end
if platforms.openbsd then
defaults.arch = "openbsd-"..target_cpu
end
if platforms.netbsd then
defaults.arch = "netbsd-"..target_cpu
end
if platforms.solaris then
defaults.arch = "solaris-"..target_cpu
--defaults.platforms = {"unix", "solaris"}
defaults.variables.MAKE = "gmake"
end
-- Expose some more values detected by LuaRocks for use by rockspec authors.
defaults.variables.LIB_EXTENSION = defaults.lib_extension
defaults.variables.OBJ_EXTENSION = defaults.obj_extension
return defaults
end
local function make_rocks_provided(lua_version, luajit_version)
local rocks_provided = {}
local rocks_provided_3_0 = {}
rocks_provided["lua"] = lua_version.."-1"
if lua_version == "5.2" or lua_version == "5.3" then
rocks_provided["bit32"] = lua_version.."-1"
end
if lua_version == "5.3" or lua_version == "5.4" then
rocks_provided["utf8"] = lua_version.."-1"
end
if luajit_version then
rocks_provided["luabitop"] = luajit_version.."-1"
rocks_provided_3_0["luajit"] = luajit_version.."-1"
end
if rawget(_G, '_TARANTOOL') then
-- Tarantool
local tarantool_version = _TARANTOOL:match("([^-]+)-")
rocks_provided["tarantool"] = tarantool_version.."-1"
rocks_provided_3_0["tarantool"] = tarantool_version.."-1"
end
-- If luarocks is launched from tt, it cannot directly access
-- the _TARANTOOL variable.
local tarantool_version = os.getenv("TT_CLI_TARANTOOL_VERSION")
if tarantool_version ~= nil then
tarantool_version = tarantool_version:match("([^-]+)-")
if tarantool_version ~= nil then
rocks_provided["tarantool"] = tarantool_version.."-1"
rocks_provided_3_0["tarantool"] = tarantool_version.."-1"
end
end
return rocks_provided, rocks_provided_3_0
end
local function use_defaults(cfg, defaults)
-- Populate some arrays with values from their 'defaults' counterparts
-- if they were not already set by user.
for _, entry in ipairs({"variables", "rocks_provided"}) do
if not cfg[entry] then
cfg[entry] = {}
end
for k,v in pairs(defaults[entry]) do
if not cfg[entry][k] then
cfg[entry][k] = v
end
end
end
util.deep_merge_under(defaults.rocks_provided_3_0, cfg.rocks_provided)
util.deep_merge_under(cfg, defaults)
-- FIXME get rid of this
if not cfg.check_certificates then
cfg.variables.CURLNOCERTFLAG = "-k"
cfg.variables.WGETNOCERTFLAG = "--no-check-certificate"
end
end
--------------------------------------------------------------------------------
local cfg = {}
--- Initializes the LuaRocks configuration for variables, paths
-- and OS detection.
-- @param detected table containing information detected about the
-- environment. All fields below are optional:
-- * lua_version (in x.y format, e.g. "5.3")
-- * luajit_version (complete, e.g. "2.1.0-beta3")
-- * lua_bindir (e.g. "/usr/local/bin")
-- * lua_incdir (e.g. "/usr/local/include/lua5.3/")
-- * lua_libdir(e.g. "/usr/local/lib")
-- * lua_dir (e.g. "/usr/local")
-- * lua_interpreter (e.g. "lua-5.3")
-- * project_dir (a string with the path of the project directory
-- when using per-project environments, as created with `luarocks init`)
-- @param warning a logging function for warnings that takes a string
-- @return true on success; nil and an error message on failure.
function cfg.init(detected, warning)
if cfg.initialized == true then
return true
end
detected = detected or {}
local hc_ok, hardcoded = pcall(require, "luarocks.core.hardcoded")
if not hc_ok then
hardcoded = {}
end
local arg = rawget(_G, 'arg')
local lua_version = detected.lua_version or hardcoded.LUA_VERSION or _VERSION:sub(5)
local luajit_version = detected.luajit_version or hardcoded.LUAJIT_VERSION or (jit and jit.version:sub(8))
local lua_interpreter = detected.lua_interpreter or hardcoded.LUA_INTERPRETER or (arg and arg[-1] and arg[-1]:gsub(".*[\\/]", "")) or (is_windows and "lua.exe" or "lua")
local lua_bindir = detected.lua_bindir or hardcoded.LUA_BINDIR or (arg and arg[-1] and arg[-1]:gsub("[\\/][^\\/]+$", ""))
local lua_incdir = detected.lua_incdir or hardcoded.LUA_INCDIR
local lua_libdir = detected.lua_libdir or hardcoded.LUA_LIBDIR
local lua_dir = detected.lua_dir or hardcoded.LUA_DIR or (lua_bindir and lua_bindir:gsub("[\\/]bin$", ""))
local project_dir = detected.project_dir
local init = cfg.init
----------------------------------------
-- Reset the cfg table.
----------------------------------------
for k, _ in pairs(cfg) do
cfg[k] = nil
end
cfg.program_version = program_version
cfg.program_series = program_series
cfg.major_version = major_version
cfg.lua_version = lua_version
cfg.luajit_version = luajit_version
cfg.lua_interpreter = lua_interpreter
cfg.variables = {
LUA_DIR = lua_dir,
LUA_BINDIR = lua_bindir,
LUA_INCDIR = lua_incdir,
LUA_LIBDIR = lua_libdir,
}
cfg.init = init
----------------------------------------
-- System detection.
----------------------------------------
-- A proper build of LuaRocks will hardcode the system
-- and proc values with hardcoded.SYSTEM and hardcoded.PROCESSOR.
-- If that is not available, we try to identify the system.
local system, processor = sysdetect.detect()
if hardcoded.SYSTEM then
system = hardcoded.SYSTEM
end
if hardcoded.PROCESSOR then
processor = hardcoded.PROCESSOR
end
if system == "windows" then
if os.getenv("VCINSTALLDIR") then
-- running from the Development Command prompt for VS 2017
system = "windows"
else
local fd = io.open("/bin/sh", "r")
if fd then
fd:close()
system = "msys"
else
system = "mingw"
end
end
end
cfg.target_cpu = processor
local platforms = make_platforms(system)
----------------------------------------
-- Platform is determined.
-- Let's load the config files.
----------------------------------------
local sys_config_file
local home_config_file
local project_config_file
do
set_confdirs(cfg, platforms, hardcoded)
local name = "config-"..cfg.lua_version..".lua"
sys_config_file = (cfg.sysconfdir .. "/" .. name):gsub("\\", "/")
home_config_file = (cfg.homeconfdir .. "/" .. name):gsub("\\", "/")
if project_dir then
project_config_file = project_dir .. "/.luarocks/" .. name
end
end
-- Load system configuration file
local sys_config_ok, err = load_config_file(cfg, platforms, sys_config_file)
if err then
return nil, err, "config"
end
-- Load user configuration file (if allowed)
local home_config_ok
local project_config_ok
if not hardcoded.FORCE_CONFIG then
local env_var = "LUAROCKS_CONFIG_" .. lua_version:gsub("%.", "_")
local env_value = os.getenv(env_var)
if not env_value then
env_var = "LUAROCKS_CONFIG"
env_value = os.getenv(env_var)
end
-- first try environment provided file, so we can explicitly warn when it is missing
if env_value then
local env_ok, err = load_config_file(cfg, platforms, env_value)
if err then
return nil, err, "config"
elseif warning and not env_ok then
warning("Warning: could not load configuration file `"..env_value.."` given in environment variable "..env_var.."\n")
end
if env_ok then
home_config_ok = true
home_config_file = env_value
end
end
-- try the alternative defaults if there was no environment specified file or it didn't work
if not home_config_ok then
home_config_ok, err = load_config_file(cfg, platforms, home_config_file)
if err then
return nil, err, "config"
end
end
-- finally, use the project-specific config file if any
if project_dir then
project_config_ok, err = load_config_file(cfg, platforms, project_config_file)
if err then
return nil, err, "config"
end
end
end
----------------------------------------
-- Config files are loaded.
-- Let's finish up the cfg table.
----------------------------------------
-- Settings detected or given via the CLI (i.e. --lua-dir) take precedence over config files:
cfg.project_dir = detected.project_dir
cfg.lua_version = detected.lua_version or cfg.lua_version
cfg.luajit_version = detected.luajit_version or cfg.luajit_version
cfg.lua_interpreter = detected.lua_interpreter or cfg.lua_interpreter
cfg.variables.LUA_BINDIR = detected.lua_bindir or cfg.variables.LUA_BINDIR or lua_bindir
cfg.variables.LUA_INCDIR = detected.lua_incdir or cfg.variables.LUA_INCDIR or lua_incdir
cfg.variables.LUA_LIBDIR = detected.lua_libdir or cfg.variables.LUA_LIBDIR or lua_libdir
cfg.variables.LUA_DIR = detected.lua_dir or cfg.variables.LUA_DIR or lua_dir
-- Build a default list of rocks trees if not given
if cfg.rocks_trees == nil then
cfg.rocks_trees = {}
if cfg.home_tree then
table.insert(cfg.rocks_trees, { name = "user", root = cfg.home_tree } )
end
if hardcoded.PREFIX and hardcoded.PREFIX ~= cfg.home_tree then
table.insert(cfg.rocks_trees, { name = "system", root = hardcoded.PREFIX } )
end
end
local defaults = make_defaults(lua_version, processor, platforms, cfg.home, hardcoded)
if platforms.windows and hardcoded.WIN_TOOLS then
local tools = { "SEVENZ", "CP", "FIND", "LS", "MD5SUM", "PWD", "RMDIR", "WGET", "MKDIR" }
for _, tool in ipairs(tools) do
defaults.variables[tool] = '"' .. hardcoded.WIN_TOOLS .. "/" .. defaults.variables[tool] .. '.exe"'
end
else
defaults.fs_use_modules = true
end
defaults.rocks_provided, defaults.rocks_provided_3_0 = make_rocks_provided(lua_version, luajit_version)
use_defaults(cfg, defaults)
cfg.variables.LUA = cfg.variables.LUA or (cfg.variables.LUA_BINDIR and (cfg.variables.LUA_BINDIR .. "/" .. cfg.lua_interpreter):gsub("//", "/"))
cfg.user_agent = "LuaRocks/"..cfg.program_version.." "..cfg.arch
cfg.config_files = {
project = project_dir and {
file = project_config_file,
found = not not project_config_ok,
},
system = {
file = sys_config_file,
found = not not sys_config_ok,
},
user = {
file = home_config_file,
found = not not home_config_ok,
},
nearest = project_config_ok
and project_config_file
or (home_config_ok
and home_config_file
or sys_config_file),
}
----------------------------------------
-- Attributes of cfg are set.
-- Let's add some methods.
----------------------------------------
do
local function make_paths_from_tree(tree)
local lua_path, lib_path, bin_path
if type(tree) == "string" then
lua_path = tree..cfg.lua_modules_path
lib_path = tree..cfg.lib_modules_path
bin_path = tree.."/bin"
else
lua_path = tree.lua_dir or tree.root..cfg.lua_modules_path
lib_path = tree.lib_dir or tree.root..cfg.lib_modules_path
bin_path = tree.bin_dir or tree.root.."/bin"
end
return lua_path, lib_path, bin_path
end
function cfg.package_paths(current)
local new_path, new_cpath, new_bin = {}, {}, {}
local function add_tree_to_paths(tree)
local lua_path, lib_path, bin_path = make_paths_from_tree(tree)
table.insert(new_path, lua_path.."/?.lua")
table.insert(new_path, lua_path.."/?/init.lua")
table.insert(new_cpath, lib_path.."/?."..cfg.lib_extension)
table.insert(new_bin, bin_path)
end
if current then
add_tree_to_paths(current)
end
for _,tree in ipairs(cfg.rocks_trees) do
add_tree_to_paths(tree)
end
return table.concat(new_path, ";"), table.concat(new_cpath, ";"), table.concat(new_bin, cfg.export_path_separator)
end
end
function cfg.init_package_paths()
local lr_path, lr_cpath, lr_bin = cfg.package_paths()
package.path = util.cleanup_path(package.path .. ";" .. lr_path, ";", lua_version)
package.cpath = util.cleanup_path(package.cpath .. ";" .. lr_cpath, ";", lua_version)
end
--- Check if platform was detected
-- @param name string: The platform name to check.
-- @return boolean: true if LuaRocks is currently running on queried platform.
function cfg.is_platform(name)
assert(type(name) == "string")
return platforms[name]
end
function cfg.each_platform()
local i = 0
return function()
local p
repeat
i = i + 1
p = platform_order[i]
until (not p) or platforms[p]
return p
end
end
function cfg.print_platforms()
local platform_keys = {}
for k,_ in pairs(platforms) do
table.insert(platform_keys, k)
end
table.sort(platform_keys)
return table.concat(platform_keys, ", ")
end
cfg.initialized = true
return true
end
return cfg
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/ice_vapour.lua | 3 | 1454 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
base_size = 32
return { generator = function()
local ad = rng.range(0, 360)
local a = math.rad(ad)
local dir = math.rad(ad + 90)
local r = rng.range(1, 20)
local dirv = math.rad(1)
return {
trail = 1,
life = 10,
size = 1, sizev = 0.5, sizea = 0,
x = r * math.cos(a), xv = -0.1, xa = 0,
y = r * math.sin(a), yv = -0.1, ya = 0,
dir = math.rad(rng.range(0, 360)), dirv = 0, dira = 0,
vel = 0.1, velv = 0, vela = 0,
r = 0, rv = 0, ra = 0,
g = rng.range(170, 210)/255, gv = 0, ga = 0,
b = rng.range(200, 255)/255, gv = 0, ga = 0,
a = rng.range(80, 130)/255, av = 0, aa = 0,
}
end, },
function(self)
self.ps:emit(4)
end,
40,
"particle_torus"
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Network/Packets/PacketBlockChange.lua | 1 | 1202 | --[[
Title: PacketBlockChange
Author(s): LiXizhi
Date: 2014/7/17
Desc:
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Packets/PacketBlockChange.lua");
local Packets = commonlib.gettable("MyCompany.Aries.Game.Network.Packets");
local packet = Packets.PacketBlockChange:new():Init();
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Network/Packets/Packet.lua");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine");
local PacketBlockChange = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Network.Packets.Packet"), commonlib.gettable("MyCompany.Aries.Game.Network.Packets.PacketBlockChange"));
function PacketBlockChange:ctor()
end
function PacketBlockChange:Init(x,y,z, id, world)
self.x = x;
self.y = y;
self.z = z;
self.blockid = BlockEngine:GetBlockId(x,y,z);
self.data = BlockEngine:GetBlockData(x,y,z);
return self;
end
-- Passes this Packet on to the NetHandler for processing.
function PacketBlockChange:ProcessPacket(net_handler)
if(net_handler.handleBlockChange) then
net_handler:handleBlockChange(self);
end
end
| gpl-2.0 |
eriche2016/nn | MultiCriterion.lua | 28 | 1216 | local MultiCriterion, parent = torch.class('nn.MultiCriterion', 'nn.Criterion')
function MultiCriterion:__init()
parent.__init(self)
self.criterions = {}
self.weights = torch.DoubleStorage()
end
function MultiCriterion:add(criterion, weight)
assert(criterion, 'no criterion provided')
weight = weight or 1
table.insert(self.criterions, criterion)
self.weights:resize(#self.criterions, true)
self.weights[#self.criterions] = weight
return self
end
function MultiCriterion:updateOutput(input, target)
self.output = 0
for i=1,#self.criterions do
self.output = self.output + self.weights[i]*self.criterions[i]:updateOutput(input, target)
end
return self.output
end
function MultiCriterion:updateGradInput(input, target)
self.gradInput = nn.utils.recursiveResizeAs(self.gradInput, input)
nn.utils.recursiveFill(self.gradInput, 0)
for i=1,#self.criterions do
nn.utils.recursiveAdd(self.gradInput, self.weights[i], self.criterions[i]:updateGradInput(input, target))
end
return self.gradInput
end
function MultiCriterion:type(type)
for i,criterion in ipairs(self.criterions) do
criterion:type(type)
end
return parent.type(self, type)
end
| bsd-3-clause |
madpilot78/ntopng | scripts/lua/rest/v1/get/host/fingerprint/data.lua | 2 | 1843 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local graph_utils = require "graph_utils"
require "flow_utils"
require "historical_utils"
local fingerprint_utils = require "fingerprint_utils"
local rest_utils = require("rest_utils")
local available_fingerprints = {
ja3 = {
stats_key = "ja3_fingerprint",
href = function(fp) return '<A class="ntopng-external-link" href="https://sslbl.abuse.ch/ja3-fingerprints/'..fp..'" target="_blank">'..fp..' <i class="fas fa-external-link-alt"></i></A>' end
},
hassh = {
stats_key = "hassh_fingerprint",
href = function(fp) return fp end
}
}
-- Parameters used for the rest answer --
local rc
local res = {}
local ifid = _GET["ifid"]
local host_info = url2hostinfo(_GET)
local fingerprint_type = _GET["fingerprint_type"]
-- #####################################################################
local stats
if isEmptyString(fingerprint_type) then
rc = rest_utils.consts.err.invalid_args
rest_utils.answer(rc)
return
end
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
if isEmptyString(host_info["host"]) then
rc = rest_utils.consts.err.invalid_args
rest_utils.answer(rc)
return
end
if(host_info["host"] ~= nil) then
stats = interface.getHostInfo(host_info["host"], host_info["vlan"])
end
stats = stats or {}
if fingerprint_type == "ja3" then
stats = stats and stats.ja3_fingerprint or {}
elseif fingerprint_type == "hassh" then
stats = stats and stats.hassh_fingerprint or {}
end
for key, value in pairs(stats) do
res[#res + 1] = value
res[#res][fingerprint_type] = key
end
rc = rest_utils.consts.success.ok
rest_utils.answer(rc, res)
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Entity/EntityCmdTextureReplacer.lua | 1 | 3991 | --[[
Title: CmdTextureReplacer Entity
Author(s): LiXizhi
Date: 2014/2/12
Desc: replace the first block with second block in bag.
try the block below this block if second inventory slot does not exist.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/EntityCmdTextureReplacer.lua");
local EntityCmdTextureReplacer = commonlib.gettable("MyCompany.Aries.Game.EntityManager.EntityCmdTextureReplacer")
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Game/Items/ItemClient.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Common/Direction.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Entity/EntityCommandBlock.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Neuron/NeuronManager.lua");
local NeuronManager = commonlib.gettable("MyCompany.Aries.Game.Neuron.NeuronManager");
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager");
local Direction = commonlib.gettable("MyCompany.Aries.Game.Common.Direction")
local ItemClient = commonlib.gettable("MyCompany.Aries.Game.Items.ItemClient");
local PhysicsWorld = commonlib.gettable("MyCompany.Aries.Game.PhysicsWorld");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local Entity = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.EntityManager.EntityCommandBlock"), commonlib.gettable("MyCompany.Aries.Game.EntityManager.EntityCmdTextureReplacer"));
-- class name
Entity.class_name = "EntityCmdTextureReplacer";
EntityManager.RegisterEntityClass(Entity.class_name, Entity);
Entity.is_persistent = true;
-- always serialize to 512*512 regional entity file
Entity.is_regional = true;
-- command line text
function Entity:ctor()
end
-- @param Entity: the half radius of the object.
function Entity:init()
if(not Entity._super.init(self)) then
return
end
-- TODO:
return self;
end
function Entity:Refresh()
end
-- replace the one item inside the inventory with the second one.
function Entity:ExecuteCommand()
Entity._super.ExecuteCommand(self);
local itemStack_from = self.inventory:GetItem(1);
if(itemStack_from) then
local block_template = block_types.get(itemStack_from.id);
if(block_template) then
local itemStack_to = self.inventory:GetItem(2);
local to_filename;
if(itemStack_to) then
to_filename = itemStack_to:GetItem():GetTexture();
else
-- try the block below this block if second inventory slot does not exist.
local x, y, z = self:GetBlockPos();
local block_to = BlockEngine:GetBlock(x,y-1,z);
if(block_to) then
to_filename = block_to:GetTexture();
end
end
block_template:ReplaceTexture(to_filename or "Texture/Transparent.png");
end
end
end
function Entity:OnNeighborChanged(x,y,z, from_block_id)
return Entity._super.OnNeighborChanged(self, x,y,z, from_block_id);
end
function Entity:LoadFromXMLNode(node)
Entity._super.LoadFromXMLNode(self, node);
self.isPowered = node.attr.isPowered == "true";
end
function Entity:SaveToXMLNode(node, bSort)
node = Entity._super.SaveToXMLNode(self, node, bSort);
if(self.isPowered) then
node.attr.isPowered = true;
end
return node;
end
-- the title text to display (can be mcml)
function Entity:GetBagTitle()
return "将场景中所有和背包中第一个方块一样的方块的贴图替换为背包中的第二个方块的材质。<div style='float:left' tooltip='如果背包中只有一个方块,那么将看下方的方块,如果下方也无,则为透明方块'>更多...</div>"
end
function Entity:HasCommand()
return false;
end
-- called every frame
function Entity:FrameMove(deltaTime)
end | gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Yhoator_Jungle/Zone.lua | 1 | 2235 | -----------------------------------
--
-- Zone: Yhoator_Jungle
--
-----------------------------------
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil;
require("scripts/zones/Yhoator_Jungle/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if (player:getQuestStatus(WINDURST, I_CAN_HEAR_A_RAINBOW) == 1 and player:hasItem(1125)) then
colors = player:getVar("ICanHearARainbow");
r = (tonumber(colors) % 2 >= 1);
o = (tonumber(colors) % 8 >= 4);
b = (tonumber(colors) % 32 >= 16);
cs = 0x0002;
if (r == false) then
player:setVar("ICanHearARainbow_Weather",4);
player:setVar("ICanHearARainbow",colors+1);
elseif (o == false) then
player:setVar("ICanHearARainbow_Weather",1);
player:setVar("ICanHearARainbow",colors+2);
elseif (b == false) then
player:setVar("ICanHearARainbow_Weather",6);
player:setVar("ICanHearARainbow",colors+16);
else
cs = -1;
end
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
if (csid == 0x0002) then
weather = player:getVar("ICanHearARainbow_Weather");
if (weather == 1) then
weather = 0;
end
if (player:getVar("ICanHearARainbow") < 127) then
player:updateEvent(0,0,weather);
else
player:updateEvent(0,0,weather,6);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
if (csid == 0x0002) then
player:setVar("ICanHearARainbow_Weather",0);
end
end;
| gpl-3.0 |
RyMarq/Zero-K | lups/ParticleClasses/ShieldJitter.lua | 8 | 5118 | -- $Id: ShieldJitter.lua 3171 2008-11-06 09:06:29Z det $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local ShieldJitter = {}
ShieldJitter.__index = ShieldJitter
local warpShader
local timerUniform,strengthUniform
local sphereList
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function ShieldJitter.GetInfo()
return {
name = "ShieldJitter",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "",
layer = 16, --// extreme simply z-ordering :x
--// gfx requirement
fbo = true,
shader = true,
distortion= true,
rtt = false,
ctt = true,
intel = 0,
}
end
ShieldJitter.Default = {
layer = 16,
pos = {0,0,0}, --// start pos
life = math.huge,
size = 600,
--precision = 26, --// bias the used polies for a sphere
strength = 0.015,
texture = 'bitmaps/GPL/Lups/grass5.png',
--texture = 'bitmaps/GPL/Lups/perlin_noise.jpg',
repeatEffect = false,
dieGameFrame = math.huge
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function ShieldJitter:BeginDrawDistortion()
gl.UseShader(warpShader)
gl.Uniform(timerUniform, Spring.GetGameSeconds()*0.1)
gl.Culling(GL.FRONT) --FIXME: check if camera is in the sphere
end
function ShieldJitter:EndDrawDistortion()
gl.UseShader(0)
gl.Texture(0,false)
gl.Culling(false)
end
function ShieldJitter:DrawDistortion()
local pos = self.pos
local size = self.size
gl.Uniform(strengthUniform, self.strength )
gl.Texture(0,self.texture)
gl.MultiTexCoord(1, pos[1], pos[2], pos[3], size)
gl.CallList(sphereList)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function ShieldJitter.Initialize()
warpShader = gl.CreateShader({
vertex = [[
uniform float timer;
uniform float strength;
varying float scale;
varying vec2 texCoord;
#define pos vec4(gl_MultiTexCoord1.xyz, 0.0)
#define size vec4(gl_MultiTexCoord1.www, 1.0)
void main()
{
gl_Position = gl_ModelViewProjectionMatrix * (gl_Vertex * size + pos);
texCoord = gl_MultiTexCoord0.st + timer;
vec3 normal = normalize(gl_NormalMatrix * gl_Normal);
vec3 nvertex = normalize(vec3(gl_ModelViewMatrix * gl_Vertex));
scale = strength*abs(dot( normal,nvertex ));
}
]],
fragment = [[
uniform sampler2D noiseMap;
varying float scale;
varying vec2 texCoord;
void main(void)
{
vec2 noiseVec;
noiseVec = texture2D(noiseMap, texCoord).yz - 0.5;
noiseVec *= scale;
gl_FragColor = vec4(noiseVec,0.0,gl_FragCoord.z);
}
]],
uniformInt = {
noiseMap = 0,
},
uniformFloat = {
timer = 0,
strength = 0.015,
}
})
local shLog = gl.GetShaderLog()
if (warpShader == nil or string.len(shLog or "") > 0) then
print(PRIO_MAJOR,"LUPS->ShieldJitter: shader error: "..shLog)
return false
end
timerUniform = gl.GetUniformLocation(warpShader, 'timer')
strengthUniform = gl.GetUniformLocation(warpShader, 'strength')
sphereList = gl.CreateList(DrawSphere,0,0,0,1,22)
end
function ShieldJitter.Finalize()
gl.DeleteShader(warpShader)
gl.DeleteList(sphereList)
gl.DeleteTexture(tex)
end
function ShieldJitter.ViewResize(viewSizeX, viewSizeY)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function ShieldJitter:Update()
end
-- used if repeatEffect=true;
function ShieldJitter:ReInitialize()
self.dieGameFrame = self.dieGameFrame + self.life
end
function ShieldJitter:CreateParticle()
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function ShieldJitter.Create(Options)
local newObject = MergeTable(Options, ShieldJitter.Default)
setmetatable(newObject,ShieldJitter) -- make handle lookup
newObject:CreateParticle()
return newObject
end
function ShieldJitter:Destroy()
gl.DeleteTexture(self.texture)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return ShieldJitter
| gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-olsr/luasrc/model/cbi/olsr/olsrd.lua | 38 | 17398 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
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
$Id$
]]--
require("luci.tools.webadmin")
local fs = require "nixio.fs"
local util = require "luci.util"
local ip = require "luci.ip"
local has_ipip = fs.glob("/etc/modules.d/[0-9]*-ipip")()
m = Map("olsrd", translate("OLSR Daemon"),
translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. "..
"As such it allows mesh routing for any network equipment. "..
"It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. "..
"Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation."))
function m.on_parse()
local has_defaults = false
m.uci:foreach("olsrd", "InterfaceDefaults",
function(s)
has_defaults = true
return false
end)
if not has_defaults then
m.uci:section("olsrd", "InterfaceDefaults")
end
end
function write_float(self, section, value)
local n = tonumber(value)
if n ~= nil then
return Value.write(self, section, "%.1f" % n)
end
end
s = m:section(TypedSection, "olsrd", translate("General settings"))
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("lquality", translate("Link Quality Settings"))
s:tab("smartgw", translate("SmartGW"), not has_ipip and translate("Warning: kmod-ipip is not installed. Without kmod-ipip SmartGateway will not work, please install it."))
s:tab("advanced", translate("Advanced Settings"))
ipv = s:taboption("general", ListValue, "IpVersion", translate("Internet protocol"),
translate("IP-version to use. If 6and4 is selected then one olsrd instance is started for each protocol."))
ipv:value("4", "IPv4")
ipv:value("6and4", "6and4")
poll = s:taboption("advanced", Value, "Pollrate", translate("Pollrate"),
translate("Polling rate for OLSR sockets in seconds. Default is 0.05."))
poll.optional = true
poll.datatype = "ufloat"
poll.placeholder = "0.05"
nicc = s:taboption("advanced", Value, "NicChgsPollInt", translate("Nic changes poll interval"),
translate("Interval to poll network interfaces for configuration changes (in seconds). Default is \"2.5\"."))
nicc.optional = true
nicc.datatype = "ufloat"
nicc.placeholder = "2.5"
tos = s:taboption("advanced", Value, "TosValue", translate("TOS value"),
translate("Type of service value for the IP header of control traffic. Default is \"16\"."))
tos.optional = true
tos.datatype = "uinteger"
tos.placeholder = "16"
fib = s:taboption("general", ListValue, "FIBMetric", translate("FIB metric"),
translate ("FIBMetric controls the metric value of the host-routes OLSRd sets. "..
"\"flat\" means that the metric value is always 2. This is the preferred value "..
"because it helps the linux kernel routing to clean up older routes. "..
"\"correct\" uses the hopcount as the metric value. "..
"\"approx\" use the hopcount as the metric value too, but does only update the hopcount if the nexthop changes too. "..
"Default is \"flat\"."))
fib:value("flat")
fib:value("correct")
fib:value("approx")
lql = s:taboption("lquality", ListValue, "LinkQualityLevel", translate("LQ level"),
translate("Link quality level switch between hopcount and cost-based (mostly ETX) routing.<br />"..
"<b>0</b> = do not use link quality<br />"..
"<b>2</b> = use link quality for MPR selection and routing<br />"..
"Default is \"2\""))
lql:value("2")
lql:value("0")
lqage = s:taboption("lquality", Value, "LinkQualityAging", translate("LQ aging"),
translate("Link quality aging factor (only for lq level 2). Tuning parameter for etx_float and etx_fpm, smaller values "..
"mean slower changes of ETX value. (allowed values are between 0.01 and 1.0)"))
lqage.optional = true
lqage:depends("LinkQualityLevel", "2")
lqa = s:taboption("lquality", ListValue, "LinkQualityAlgorithm", translate("LQ algorithm"),
translate("Link quality algorithm (only for lq level 2).<br />"..
"<b>etx_float</b>: floating point ETX with exponential aging<br />"..
"<b>etx_fpm</b> : same as etx_float, but with integer arithmetic<br />"..
"<b>etx_ff</b> : ETX freifunk, an etx variant which use all OLSR traffic (instead of only hellos) for ETX calculation<br />"..
"<b>etx_ffeth</b>: incompatible variant of etx_ff that allows ethernet links with ETX 0.1.<br />"..
"Defaults to \"etx_ff\""))
lqa.optional = true
lqa:value("etx_ff")
lqa:value("etx_fpm")
lqa:value("etx_float")
lqa:value("etx_ffeth")
lqa:depends("LinkQualityLevel", "2")
lqa.optional = true
lqfish = s:taboption("lquality", Flag, "LinkQualityFishEye", translate("LQ fisheye"),
translate("Fisheye mechanism for TCs (checked means on). Default is \"on\""))
lqfish.default = "1"
lqfish.optional = true
hyst = s:taboption("lquality", Flag, "UseHysteresis", translate("Use hysteresis"),
translate("Hysteresis for link sensing (only for hopcount metric). Hysteresis adds more robustness to the link sensing "..
"but delays neighbor registration. Defaults is \"yes\""))
hyst.default = "yes"
hyst.enabled = "yes"
hyst.disabled = "no"
hyst:depends("LinkQualityLevel", "0")
hyst.optional = true
hyst.rmempty = true
port = s:taboption("general", Value, "OlsrPort", translate("Port"),
translate("The port OLSR uses. This should usually stay at the IANA assigned port 698. It can have a value between 1 and 65535."))
port.optional = true
port.default = "698"
port.rmempty = true
mainip = s:taboption("general", Value, "MainIp", translate("Main IP"),
translate("Sets the main IP (originator ip) of the router. This IP will NEVER change during the uptime of olsrd. "..
"Default is 0.0.0.0, which triggers usage of the IP of the first interface."))
mainip.optional = true
mainip.rmempty = true
mainip.datatype = "ipaddr"
mainip.placeholder = "0.0.0.0"
sgw = s:taboption("smartgw", Flag, "SmartGateway", translate("Enable"), translate("Enable SmartGateway. If it is disabled, then " ..
"all other SmartGateway parameters are ignored. Default is \"no\"."))
sgw.default="no"
sgw.enabled="yes"
sgw.disabled="no"
sgw.rmempty = true
sgwnat = s:taboption("smartgw", Flag, "SmartGatewayAllowNAT", translate("Allow gateways with NAT"), translate("Allow the selection of an outgoing ipv4 gateway with NAT"))
sgwnat:depends("SmartGateway", "yes")
sgwnat.default="yes"
sgwnat.enabled="yes"
sgwnat.disabled="no"
sgwnat.optional = true
sgwnat.rmempty = true
sgwuplink = s:taboption("smartgw", ListValue, "SmartGatewayUplink", translate("Announce uplink"), translate("Which kind of uplink is exported to the other mesh nodes. " ..
"An uplink is detected by looking for a local HNA of 0.0.0.0/0, ::ffff:0:0/96 or 2000::/3. Default setting is \"both\"."))
sgwuplink:value("none")
sgwuplink:value("ipv4")
sgwuplink:value("ipv6")
sgwuplink:value("both")
sgwuplink:depends("SmartGateway", "yes")
sgwuplink.default="both"
sgwuplink.optional = true
sgwuplink.rmempty = true
sgwulnat = s:taboption("smartgw", Flag, "SmartGatewayUplinkNAT", translate("Uplink uses NAT"), translate("If this Node uses NAT for connections to the internet. " ..
"Default is \"yes\"."))
sgwulnat:depends("SmartGatewayUplink", "ipv4")
sgwulnat:depends("SmartGatewayUplink", "both")
sgwulnat.default="yes"
sgwulnat.enabled="yes"
sgwulnat.disabled="no"
sgwnat.optional = true
sgwnat.rmempty = true
sgwspeed = s:taboption("smartgw", Value, "SmartGatewaySpeed", translate("Speed of the uplink"), translate("Specifies the speed of "..
"the uplink in kilobits/s. First parameter is upstream, second parameter is downstream. Default is \"128 1024\"."))
sgwspeed:depends("SmartGatewayUplink", "ipv4")
sgwspeed:depends("SmartGatewayUplink", "ipv6")
sgwspeed:depends("SmartGatewayUplink", "both")
sgwspeed.optional = true
sgwspeed.rmempty = true
sgwprefix = s:taboption("smartgw", Value, "SmartGatewayPrefix", translate("IPv6-Prefix of the uplink"), translate("This can be used " ..
"to signal the external IPv6 prefix of the uplink to the clients. This might allow a client to change it's local IPv6 address to " ..
"use the IPv6 gateway without any kind of address translation. The maximum prefix length is 64 bits. " ..
"Default is \"::/0\" (no prefix)."))
sgwprefix:depends("SmartGatewayUplink", "ipv6")
sgwprefix:depends("SmartGatewayUplink", "both")
sgwprefix.optional = true
sgwprefix.rmempty = true
willingness = s:taboption("advanced", ListValue, "Willingness", translate("Willingness"),
translate("The fixed willingness to use. If not set willingness will be calculated dynamically based on battery/power status. Default is \"3\"."))
for i=0,7 do
willingness:value(i)
end
willingness.optional = true
willingness.default = "3"
natthr = s:taboption("advanced", Value, "NatThreshold", translate("NAT threshold"),
translate("If the route to the current gateway is to be changed, the ETX value of this gateway is "..
"multiplied with this value before it is compared to the new one. "..
"The parameter can be a value between 0.1 and 1.0, but should be close to 1.0 if changed.<br />"..
"<b>WARNING:</b> This parameter should not be used together with the etx_ffeth metric!<br />"..
"Defaults to \"1.0\"."))
for i=1,0.1,-0.1 do
natthr:value(i)
end
natthr:depends("LinkQualityAlgorithm", "etx_ff")
natthr:depends("LinkQualityAlgorithm", "etx_float")
natthr:depends("LinkQualityAlgorithm", "etx_fpm")
natthr.default = "1.0"
natthr.optional = true
natthr.write = write_float
i = m:section(TypedSection, "InterfaceDefaults", translate("Interfaces Defaults"))
i.anonymous = true
i.addremove = false
i:tab("general", translate("General Settings"))
i:tab("addrs", translate("IP Addresses"))
i:tab("timing", translate("Timing and Validity"))
mode = i:taboption("general", ListValue, "Mode", translate("Mode"),
translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. "..
"valid Modes are \"mesh\" and \"ether\". Default is \"mesh\"."))
mode:value("mesh")
mode:value("ether")
mode.optional = true
mode.rmempty = true
weight = i:taboption("general", Value, "Weight", translate("Weight"),
translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. "..
"Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, "..
"but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />"..
"<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. "..
"For any other value of LinkQualityLevel, the interface ETX value is used instead."))
weight.optional = true
weight.datatype = "uinteger"
weight.placeholder = "0"
lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"),
translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. "..
"It is only used when LQ-Level is greater than 0. Examples:<br />"..
"reduce LQ to 192.168.0.1 by half: 192.168.0.1 0.5<br />"..
"reduce LQ to all nodes on this interface by 20%: default 0.8"))
lqmult.optional = true
lqmult.rmempty = true
lqmult.cast = "table"
lqmult.placeholder = "default 1.0"
function lqmult.validate(self, value)
for _, v in pairs(value) do
if v ~= "" then
local val = util.split(v, " ")
local host = val[1]
local mult = val[2]
if not host or not mult then
return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.")
end
if not (host == "default" or ip.IPv4(host) or ip.IPv6(host)) then
return nil, translate("Can only be a valid IPv4 or IPv6 address or 'default'")
end
if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then
return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.")
end
if not mult:match("[0-1]%.[0-9]+") then
return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.")
end
end
end
return value
end
ip4b = i:taboption("addrs", Value, "Ip4Broadcast", translate("IPv4 broadcast"),
translate("IPv4 broadcast address for outgoing OLSR packets. One useful example would be 255.255.255.255. "..
"Default is \"0.0.0.0\", which triggers the usage of the interface broadcast IP."))
ip4b.optional = true
ip4b.datatype = "ip4addr"
ip4b.placeholder = "0.0.0.0"
ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"),
translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast."))
ip6m.optional = true
ip6m.datatype = "ip6addr"
ip6m.placeholder = "FF02::6D"
ip4s = i:taboption("addrs", Value, "IPv4Src", translate("IPv4 source"),
translate("IPv4 src address for outgoing OLSR packages. Default is \"0.0.0.0\", which triggers usage of the interface IP."))
ip4s.optional = true
ip4s.datatype = "ip4addr"
ip4s.placeholder = "0.0.0.0"
ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"),
translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. "..
"Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP."))
ip6s.optional = true
ip6s.datatype = "ip6addr"
ip6s.placeholder = "0::/0"
hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval"))
hi.optional = true
hi.datatype = "ufloat"
hi.placeholder = "5.0"
hi.write = write_float
hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time"))
hv.optional = true
hv.datatype = "ufloat"
hv.placeholder = "40.0"
hv.write = write_float
ti = i:taboption("timing", Value, "TcInterval", translate("TC interval"))
ti.optional = true
ti.datatype = "ufloat"
ti.placeholder = "2.0"
ti.write = write_float
tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time"))
tv.optional = true
tv.datatype = "ufloat"
tv.placeholder = "256.0"
tv.write = write_float
mi = i:taboption("timing", Value, "MidInterval", translate("MID interval"))
mi.optional = true
mi.datatype = "ufloat"
mi.placeholder = "18.0"
mi.write = write_float
mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time"))
mv.optional = true
mv.datatype = "ufloat"
mv.placeholder = "324.0"
mv.write = write_float
ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval"))
ai.optional = true
ai.datatype = "ufloat"
ai.placeholder = "18.0"
ai.write = write_float
av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time"))
av.optional = true
av.datatype = "ufloat"
av.placeholder = "108.0"
av.write = write_float
ifs = m:section(TypedSection, "Interface", translate("Interfaces"))
ifs.addremove = true
ifs.anonymous = true
ifs.extedit = luci.dispatcher.build_url("admin/services/olsrd/iface/%s")
ifs.template = "cbi/tblsection"
function ifs.create(...)
local sid = TypedSection.create(...)
luci.http.redirect(ifs.extedit % sid)
end
ign = ifs:option(Flag, "ignore", translate("Enable"))
ign.enabled = "0"
ign.disabled = "1"
ign.rmempty = false
function ign.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
network = ifs:option(DummyValue, "interface", translate("Network"))
network.template = "cbi/network_netinfo"
mode = ifs:option(DummyValue, "Mode", translate("Mode"))
function mode.cfgvalue(...)
return Value.cfgvalue(...) or m.uci:get_first("olsrd", "InterfaceDefaults", "Mode", "mesh")
end
hello = ifs:option(DummyValue, "_hello", translate("Hello"))
function hello.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd", section, "HelloInterval")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "HelloInterval", 5))
local v = tonumber(m.uci:get("olsrd", section, "HelloValidityTime")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "HelloValidityTime", 40))
return "%.01fs / %.01fs" %{ i, v }
end
tc = ifs:option(DummyValue, "_tc", translate("TC"))
function tc.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd", section, "TcInterval")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "TcInterval", 2))
local v = tonumber(m.uci:get("olsrd", section, "TcValidityTime")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "TcValidityTime", 256))
return "%.01fs / %.01fs" %{ i, v }
end
mid = ifs:option(DummyValue, "_mid", translate("MID"))
function mid.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd", section, "MidInterval")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "MidInterval", 18))
local v = tonumber(m.uci:get("olsrd", section, "MidValidityTime")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "MidValidityTime", 324))
return "%.01fs / %.01fs" %{ i, v }
end
hna = ifs:option(DummyValue, "_hna", translate("HNA"))
function hna.cfgvalue(self, section)
local i = tonumber(m.uci:get("olsrd", section, "HnaInterval")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "HnaInterval", 18))
local v = tonumber(m.uci:get("olsrd", section, "HnaValidityTime")) or tonumber(m.uci:get_first("olsrd", "InterfaceDefaults", "HnaValidityTime", 108))
return "%.01fs / %.01fs" %{ i, v }
end
return m
| gpl-2.0 |
NPLPackages/paracraft | script/kids/3DMapSystemUI/Desktop/DesktopWnd.lua | 1 | 26087 | --[[
Title: Desktop window for 3d map system
Author(s): WangTian,
Date: 2008/1/23
Revised:
* 2008/1/28 exposed to external apps via Desktop.icons by LiXizhi.
* 2008.3.18 login page is now from a local MCML file. by LiXizhi.
* 2008.6.17 mcml url icon is supported. LiXizhi.
Desc:
---++ Add desktop icons
One can add commands icons to Startup, Online, Offline command groups. Each commands may contain a url or UICallback function.
However, most desktop icons are advised to be mcml url only.
*example*
<verbatim>
Map3DSystem.UI.Desktop.AddDesktopItem({ButtonText="iconText", icon = "icon path", url="Some URL here"}, "Startup.Credits");
Map3DSystem.UI.Desktop.AddDesktopItem({ButtonText="iconText", icon = "icon path", url="Some URL here"}, "Online.MyProfile");
Map3DSystem.UI.Desktop.AddDesktopItem({ButtonText="iconText", icon = "icon path", url="Some URL here"}, "Offline.Tutorial");
</verbatim>
---++ Desktop Front page
goto a url page on the desktop front page. call below
<verbatim>
Map3DSystem.UI.Desktop.GotoDesktopPage(url)
</verbatim>
change the desktop images
<verbatim>
Map3DSystem.UI.Desktop.SetBackgroundImage(filename)
</verbatim>
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemUI/Desktop/DesktopWnd.lua");
Map3DSystem.UI.Desktop.Show();
-- to add desktop icon that has a showUI callback at startup
Map3DSystem.UI.Desktop.AddDesktopItem({ButtonText="iconText", icon = "icon path", OnShowUICallback}, "Startup.Credits");
-- to add desktop icon that opens an url page.
Map3DSystem.UI.Desktop.AddDesktopItem({ButtonText="iconText", icon = "icon path", url}, "Startup.Credits");
-------------------------------------------------------
]]
-- common control library
NPL.load("(gl)script/kids/3DMapSystem_Data.lua");
local L = CommonCtrl.Locale("ParaWorld");
if(not Map3DSystem.UI.Desktop) then Map3DSystem.UI.Desktop = {}; end
local Desktop = Map3DSystem.UI.Desktop;
Desktop.LoginBarMCML = "script/kids/3DMapSystemUI/Desktop/LoginPage.html"
Desktop.NewAccountUrl = "http://www.minixyz.com/cn_01/register.aspx";
-- Themes and Images
Desktop.DesktopBG = "Texture/3DMapSystem/Desktop/BG.png";--"Texture/3DMapSystem/Desktop/DesktopBG.png";
Desktop.HeaderBG = ""; --"Texture/3DMapSystem/Desktop/TopFrameBG.png: 10 200 10 0"
Desktop.ParaWorldLogo = "Texture/3DMapSystem/brand/paraworld_text_256X128.png"; -- "Texture/3DMapSystem/Desktop/Logo_cn.png; 0 0 192 192"; -- TODO: locale
--Desktop.ParaWorldLogo128 = "Texture/3DMapSystem/Desktop/Logo_cn_128.png"; -- TODO: locale
Desktop.ParaWorldSlogen = ""; -- "Texture/3DMapSystem/Desktop/ParaEngineTenet.png"
Desktop.StartupBarBG = ""; -- "Texture/3DMapSystem/Desktop/StartupBarBG.png";
Desktop.LoginBarBG = ""; -- "Texture/3DMapSystem/Desktop/LoginBarBG.png";
--Desktop.LoginButton_Norm = "Texture/3DMapSystem/Desktop/LoginButton_Norm.png: 15 15 15 15";
--Desktop.LoginButton_HL = "Texture/3DMapSystem/Desktop/LoginButton_HL.png: 15 15 15 15";
Desktop.LoginButton_Norm = "Texture/3DMapSystem/Desktop/LoginPageButton3.png: 15 15 15 16";
Desktop.LoginButton_HL = "Texture/3DMapSystem/Desktop/LoginPageButton_HL3.png: 15 15 15 16";
-- Fonts
Desktop.LoginBarFont = "System;12;norm";
--Desktop.LoginBarFontBold = "Verdana;12;bold";
Desktop.LastShowGridViewName = nil;
Desktop.LastShowGridRow = nil;
Desktop.LastShowGridColumn = nil;
Desktop.LastUrl = nil;
-- preinstalled desktop icons. other applications may add to this icon list at startup time.
Desktop.icons = {
name = "Desktop",
text = "Desktop",
Nodes={
{
-- "Startup" contains panel or command icons that are shown at startup.
name = "Startup",
text = "Startup",
-- child objects
Nodes = {},
},
{
-- "Online" contains icons that are only shown when user is signed in.
name = "Online",
text = "Online",
-- child objects
Nodes = {},
},
{
-- "Offline" contains icons that are only shown when user is signed in as offline.
name = "Offline",
text = "Offline",
-- child objects
Nodes = {},
},
}};
-- Edited LXZ 2008.1.28. Add a desk top command at given position. This function is usually called during an application's startup connection event (not UISetup)
-- @param command; type of Map3DSystem.App.Command, or a new table that contains {ButtonText="iconText", icon = "icon path", OnShowUICallback = nil or function (bShow, _parent,parentWindow) .. end}
-- @param position: this is a tree path string of folder names separated by dot. The desktop has a predefined folder structure, which is
-- "Startup.anyname": "Startup" contains panel or command icons that are shown at startup.
-- "Online.anyname": "Online" contains icons that are only shown when user is signed in.
-- "Offline.anyname", "Offline" contains icons that are only shown when user is signed in as offline.
-- @param posIndex: if position is a item in another folder, this is the index at which to add the item. if nil, it is added to end, if 1 it is the beginning.
function Desktop.AddDesktopItem(command, position, posIndex)
-- get the first occurance of first level child node whose name is name
local function GetChildByName(parent, name)
if(parent~=nil and parent.Nodes~=nil) then
local nSize = table.getn(parent.Nodes);
local i, node;
for i=1, nSize do
node = parent.Nodes[i];
if(node~=nil and name == node.name) then
return node;
end
end
end
end
-- search from the root icon node.
local node = Desktop.icons;
local nodeName;
for nodeName in string.gfind(position, "([^%.]+)") do
local subnode = GetChildByName(node, nodeName);
if(subnode == nil) then
-- command is added to the back
node.Nodes = node.Nodes or {};
node.Nodes[table.getn(node.Nodes)+1] = {
name = nodeName,
text = command.ButtonText,
-- posIndex to be converted to column in the grid
column = posIndex,
-- if icon is not provided, we will use an empty icon
icon = command.icon or "Texture/3DMapSystem/Desktop/Startup/Empty.png",
OnShowUICallback = command.OnShowUICallback,
AppCommand = command,
};
break;
else
node = subnode;
end
end
end
-- return a desktop icon index by its position. This function is mosted called before AddDesktopItem to determine where to insert a new command.
-- @param position: this is a tree path string of folder names separated by dot e.g. "Startup.anyname"
-- @return nil if not found, other the item index integer is returned. please note that the index may change when new items are added later on.
function Desktop.GetItemIndex(position)
-- TODO: get position gridcell.column for the position.
return nil;
end
-- obsoleted: no longer used
function Desktop.AddStartupBarApplication(appTable)
local ctl = CommonCtrl.GetControl("Desktop_Startup_GridView");
NPL.load("(gl)script/ide/GridView.lua");
local cell = CommonCtrl.GridCell:new{
GridView = nil,
name = appTable.name,
text = appTable.text,
icon = appTable.icon,
OnShowUICallback = appTable.OnShowUICallback,
};
ctl:InsertCell(cell, "Right");
end
-- public: set the background image: 1020*700
-- @param filename: nil or a file path
function Desktop.SetBackgroundImage(filename)
ParaUI.GetUIObject("Main_Desktop").background = filename or Desktop.DesktopBG
end
function Desktop.Show()
local _this,_parent;
NPL.load("(gl)script/ide/UIAnim/UIAnimManager.lua");
local fileName = "script/UIAnimation/DesktopStartupGridView.lua.table";
file = UIAnimManager.LoadUIAnimationFile(fileName);
_this = ParaUI.GetUIObject("Main_Desktop");
if(_this:IsValid() == false) then
-- Main_Desktop
local _desktop = ParaUI.CreateUIObject("container", "Main_Desktop", "_fi", 0, 0, 0, 0);
_desktop.background = Desktop.DesktopBG;
_desktop:AttachToRoot();
-- NOTE: change the canvas below the top frame
-- AppCanvas
local _appCanvas = ParaUI.CreateUIObject("container", "AppCanvas", "_fi", 0, 100, 0, 90);
_appCanvas.background = "";
_desktop:AddChild(_appCanvas);
-- TopFrame
-- NOTE: this container is a parent container that set to each application desktop
if(Desktop.HeaderBG~=nil and Desktop.HeaderBG~="") then
local _top = ParaUI.CreateUIObject("container", "TopFrame", "_fi", 0, 0, 0, 180);
_top.background = Desktop.HeaderBG;
_logo.enabled = false;
_desktop:AddChild(_top);
end
-- logo
if(Desktop.ParaWorldLogo~=nil and Desktop.ParaWorldLogo~="") then
local _logo = ParaUI.CreateUIObject("container", "Logo", "_lt", 10, 5, 200, 100);
_logo.background = Desktop.ParaWorldLogo;
_logo.enabled = false;
_desktop:AddChild(_logo);
end
-- slogen
if(Desktop.ParaWorldSlogen~=nil and Desktop.ParaWorldSlogen~="") then
local _tenet = ParaUI.CreateUIObject("container", "Tenet", "_rt", 0, 0, -1024, 64);
_tenet.background = Desktop.ParaWorldSlogen;
_tenet.enabled = false;
_desktop:AddChild(_tenet);
end
-- Startup
local _startupBar = ParaUI.CreateUIObject("container", "StartupBar", "_rt", -460, 10, 440, 90);
_startupBar.background = Desktop.StartupBarBG;
_desktop:AddChild(_startupBar);
Desktop.ShowStartup();
-- Login
local _login = ParaUI.CreateUIObject("container", "LoginBar", "_mb", 0, 0, 0, 90);
_login.background = Desktop.LoginBarBG;
_desktop:AddChild(_login);
end
Desktop.LastShowGridViewName = nil;
Desktop.LastShowGridRow = nil;
Desktop.LastShowGridColumn = nil;
Desktop.LastUrl = nil;
Desktop.ShowLogin();
-- show the startup panel
Desktop.ShowStartupPanel(true);
end
-- always show the first cell as the startup panel.
-- @param bForceUpdate: if true, it will rebuilt the UI for the cell at row, column even it is the same as last click.
function Desktop.ShowStartupPanel(bForceUpdate)
Desktop.OnClickGridCell("Desktop_Startup_GridView", 1, 1, true, bForceUpdate);
Desktop.LastShowGridViewName = "Desktop_Startup_GridView";
Desktop.LastShowGridRow = 1;
Desktop.LastShowGridColumn = 1;
end
-- the middle application canvas
function Desktop.GetAppCanvas()
local _desktop = ParaUI.GetUIObject("Main_Desktop");
return _desktop:GetChild("AppCanvas");
end
-- show the current app display and hide the last app display
-- if the same current and last app display, hide current
-- @param bShow: true or nil to show, false to hide,
-- @param bForceUpdate: if true, it will rebuilt the UI for the cell at row, column even it is the same as last click.
function Desktop.OnClickGridCell(gridviewName, row, column, bShow, bForceUpdate)
local ctl;
if(gridviewName == "Desktop_Startup_GridView") then
ctl = CommonCtrl.GetControl("Desktop_Startup_GridView");
elseif(gridviewName == "Desktop_Login_Online_GridView") then
ctl = CommonCtrl.GetControl("Desktop_Login_Online_GridView");
elseif(gridviewName == "Desktop_Login_Offline_GridView") then
ctl = CommonCtrl.GetControl("Desktop_Login_Offline_GridView");
end
if(ctl ~= nil) then
-- get the grid cell according to gridview name and row&column position
local gridcell = ctl:GetCellByRowAndColumn(row, column);
if(gridcell ~= nil) then
--------- DEBUG PURPOSE ---------
if(gridcell.name == "Empty") then
return;
end
---------------------------------
local lastGridviewName = Desktop.LastShowGridViewName;
local lastRow = Desktop.LastShowGridRow;
local lastColumn = Desktop.LastShowGridColumn;
local lastUrl = Desktop.LastUrl;
local url = nil;
if(gridcell.OnShowUICallback == nil and gridcell.AppCommand) then
url = gridcell.AppCommand.url
end
if(lastGridviewName == gridviewName and lastRow == row and lastColumn == column) then
-- User clicks the same node twice
if(bShow == false) then
-- hide app panel if any
if(lastUrl) then
NPL.load("(gl)script/kids/3DMapSystemApp/Login/ParaworldStartPage.lua");
Map3DSystem.App.Login.ParaworldStartPage.Show(false, Desktop.GetAppCanvas())
end
if(gridcell.OnShowUICallback ~= nil) then
gridcell.OnShowUICallback(false, Desktop.GetAppCanvas());
end
gridcell.highlight = false;
gridcell.GridView:Update();
end
else
-- User clicks a different node: show the node and hide the last.
if(lastUrl and url) then
else
-- close the last page
Desktop.OnClickGridCell(lastGridviewName, lastRow, lastColumn, false);
end
bForceUpdate = true;
end
if(bForceUpdate) then
-- show current icon
if(url) then
if(lastUrl == nil) then
-- show the url window if it is not shown before.
NPL.load("(gl)script/kids/3DMapSystemApp/Login/ParaworldStartPage.lua");
Map3DSystem.App.Login.ParaworldStartPage.Show(true, Desktop.GetAppCanvas())
end
if(url~="") then
Map3DSystem.App.Login.GotoPage(url)
end
elseif(gridcell.OnShowUICallback ~= nil) then
-- if this icon is a panel, show the panel.
gridcell.OnShowUICallback(true, Desktop.GetAppCanvas());
elseif(gridcell.AppCommand~=nil) then
-- if this is a command, call the command.
if(gridcell.AppCommand.Call~=nil) then
gridcell.AppCommand:Call();
end
end
Desktop.LastShowGridViewName = gridviewName;
Desktop.LastShowGridRow = row;
Desktop.LastShowGridColumn = column;
Desktop.LastUrl = url;
gridcell.highlight = true;
gridcell.GridView:Update();
else
if(url and lastUrl) then
Map3DSystem.App.Login.GotoPage(url)
end
end
end
end
end
function Desktop.OwnerDrawGridCellHandler(_parent, gridcell)
if(_parent == nil or gridcell == nil) then
return;
end
if(gridcell ~= nil) then
if(gridcell.highlight == true) then
local _this = ParaUI.CreateUIObject("container", gridcell.text.."_highlight", "_lt", 14, 4, 72, 72);
_this.enable = false;
-- disable the high light, the icon is of various shapes
--_this.background = "Texture/3DMapSystem/Desktop/HighLight.png";
_this.background = "";
_parent:AddChild(_this);
end
local _this = ParaUI.CreateUIObject("button", gridcell.text.."_icon", "_lt", 18, 8, 64, 64);
_this.background = gridcell.icon;
_this.onclick = string.format(";Map3DSystem.UI.Desktop.OnClickGridCell(%q, %d, %d);", gridcell.GridView.name, gridcell.row, gridcell.column);
_parent:AddChild(_this);
_this = ParaUI.CreateUIObject("button", gridcell.text.."_text", "_lt", 0, 68, 100, 24);
_this.onclick = string.format(";Map3DSystem.UI.Desktop.OnClickGridCell(%q, %d, %d);", gridcell.GridView.name, gridcell.row, gridcell.column);
_this.text = gridcell.text;
_this.background = "";
_this.font = Desktop.LoginBarFont;
if(gridcell.GridView.font_color) then
_guihelper.SetFontColor(_this, gridcell.GridView.font_color)
--_this:GetFont("text").color = "200 227 241";
end
_parent:AddChild(_this);
end
end
function Desktop.OnClickShiftLeft()
local ctl = CommonCtrl.GetControl("Desktop_Startup_GridView");
ctl:OnShiftLeftByCell();
end
function Desktop.OnClickShiftRight()
local ctl = CommonCtrl.GetControl("Desktop_Startup_GridView");
ctl:OnShiftRightByCell();
end
function Desktop.ShowStartup(bShow)
local _desktop = ParaUI.GetUIObject("Main_Desktop");
local _startupBar = _desktop:GetChild("StartupBar");
local _startup = _startupBar:GetChild("Startup");
if(_startup:IsValid() == false) then
if(bShow == false) then
return;
end
_startup = ParaUI.CreateUIObject("container", "Startup", "_fi", 0, 0, 0, 0);
_startup.background = "";
_startupBar:AddChild(_startup);
-- TODO: need animation for the startup bar
_pageleft = ParaUI.CreateUIObject("button", "PageLeft", "_lt", 0, 25, 32, 32);
_pageleft.background = "Texture/3DMapSystem/common/PageLeft.png";
_pageleft.onclick = ";Map3DSystem.UI.Desktop.OnClickShiftLeft();";
_startupBar:AddChild(_pageleft);
_pageright = ParaUI.CreateUIObject("button", "PageRight", "_rt", -27, 25, 32, 32);
_pageright.background = "Texture/3DMapSystem/common/PageRight.png";
_pageright.onclick = ";Map3DSystem.UI.Desktop.OnClickShiftRight();";
_startupBar:AddChild(_pageright);
-- show the application in IP in GridView
NPL.load("(gl)script/ide/GridView.lua");
local ctl = CommonCtrl.GetControl("Desktop_Startup_GridView");
if(ctl==nil)then
ctl = CommonCtrl.GridView:new{
name = "Desktop_Startup_GridView",
alignment = "_lt",
container_bg = "",
left = 15, top = 0,
width = 400,
height = 90,
cellWidth = 100,
cellHeight = 90,
parent = _startup,
columns = 7,
rows = 1,
DrawCellHandler = Desktop.OwnerDrawGridCellHandler,
};
-- insert all icons
local cell;
local index, node;
for index, node in ipairs(Desktop.icons.Nodes[1].Nodes) do
-- fill default
cell = CommonCtrl.GridCell:new(node);
if(node.column == nil) then
ctl:AppendCell(cell, "Right");
else
ctl:InsertCell(cell, "Right");
end
end
---- TODO: test drag: remove this block.
--do
--local i;
--for i = 1, 7 do
--cell = CommonCtrl.GridCell:new{
--GridView = nil,
--name = "Empty",
--text = "Empty",
--column = 10+i,
--row = 1,
--icon = "Texture/3DMapSystem/Desktop/Startup/Empty.png",
--OnShowUICallback = nil,
--};
--ctl:InsertCell(cell, "Right");
--end
--end
else
ctl.parent = _startup;
end
ctl:Show();
else
if(bShow == nil) then
_startup.visible = not _startup.visible;
else
_startup.visible = bShow;
end
end
end
function Desktop.ShowLogin()
local _desktop = ParaUI.GetUIObject("Main_Desktop");
local _loginBar = _desktop:GetChild("LoginBar");
local _login = _loginBar:GetChild("Login");
if(_login:IsValid() == false) then
if(bShow == false) then
return;
end
_login = ParaUI.CreateUIObject("container", "Login", "_fi", 0, 0, 0, 0);
_login.background = "";
_loginBar:AddChild(_login);
--
-- load from MCML page
--
NPL.load("(gl)script/kids/3DMapSystemApp/mcml/PageCtrl.lua");
local MyPage = Map3DSystem.mcml.PageCtrl:new({url=Desktop.LoginBarMCML});
MyPage:Create("Desktop.loginpage", _login, "_fi", 0, 0, 0, 0);
else
if(bShow == nil) then
_login.visible = not _login.visible;
else
_login.visible = bShow;
end
end
-- hide the offline and online container if valid
local _offline = _loginBar:GetChild("Offline");
local _online = _loginBar:GetChild("Online");
if(_offline:IsValid()) then
_offline.visible = false;
end
if(_online:IsValid()) then
_online.visible = false;
end
end
-- switch to login page.
function Desktop.ShowOnline()
local _desktop = ParaUI.GetUIObject("Main_Desktop");
local _loginBar = _desktop:GetChild("LoginBar");
local _online = _loginBar:GetChild("Online");
if(_online:IsValid() == false) then
if(bShow == false) then
return;
end
-- Online container
_online = ParaUI.CreateUIObject("container", "Online", "_fi", 0, 0, 0, 0);
_online.background = "Texture/3DMapSystem/Desktop/LoginPageBottom.png: 15 55 15 8";
_loginBar:AddChild(_online);
--local _this = ParaUI.CreateUIObject("button", "b", "_mt", 0, 0, 0, 3);
--_this.background = "Texture/3DMapSystem/Desktop/divider.png"
--_this.enabled = false;
--_online:AddChild(_this);
--_guihelper.SetUIColor(_this, "255 255 255");
local _welcome = ParaUI.CreateUIObject("text", "Welcome", "_lt", 20, 20, 200, 24);
local name;
local profile = Map3DSystem.App.profiles.ProfileManager.GetProfile();
if(profile) then
name = profile:getFullName() or "";
end
_welcome.text = string.format(L"欢迎 %s, 登录成功!", name or "");
--_welcome:GetFont("text").color = "200 227 241";
_welcome.font = Desktop.LoginBarFont;
_online:AddChild(_welcome);
local _back = ParaUI.CreateUIObject("button", "BackToLogin", "_lt", 20, 50, _guihelper.GetTextWidth(L"返回登陆页")+20, 33);
_back.text = L"返回登陆页";
_back.background = Desktop.LoginButton_HL;
_back:GetFont("text").color = "4 55 89";
_back.font = Desktop.LoginBarFont;
_back.onclick = ";Map3DSystem.UI.Desktop.ShowLogin();";
_online:AddChild(_back);
NPL.load("(gl)script/ide/GridView.lua");
local ctl = CommonCtrl.GetControl("Desktop_Login_Online_GridView");
if(ctl==nil)then
ctl = CommonCtrl.GridView:new{
name = "Desktop_Login_Online_GridView",
alignment = "_fi",
container_bg = "",
left = 280, top = 0,
width = 20,
height = 0,
cellWidth = 100,
cellHeight = 90,
parent = _online,
columns = 20,
rows = 1,
font_color = "#C8E3F1",
DrawCellHandler = Desktop.OwnerDrawGridCellHandler,
};
local cell;
local index, node;
for index, node in ipairs(Desktop.icons.Nodes[2].Nodes) do
-- fill default
cell = CommonCtrl.GridCell:new(node);
if(node.column == nil) then
ctl:AppendCell(cell, "Right");
else
ctl:InsertCell(cell, "Right");
end
end
else
ctl.parent = _online;
end
ctl:Show();
else
if(bShow == nil) then
_online.visible = not _online.visible;
else
_online.visible = bShow;
end
end
-- hide the offline and login container if valid
local _offline = _loginBar:GetChild("Offline");
local _login = _loginBar:GetChild("Login");
if(_offline:IsValid() == true) then
_offline.visible = false;
end
if(_login:IsValid() == true) then
_login.visible = false;
end
-- make sure that it switched to the first tab in online app.
Desktop.OnClickGridCell("Desktop_Login_Online_GridView", 1, 1, true)
end
function Desktop.ShowOffline()
local _desktop = ParaUI.GetUIObject("Main_Desktop");
local _loginBar = _desktop:GetChild("LoginBar");
local _offline = _loginBar:GetChild("Offline");
if(_offline:IsValid() == false) then
if(bShow == false) then
return;
end
-- Offline container
_offline = ParaUI.CreateUIObject("container", "Offline", "_fi", 0, 0, 0, 0);
_offline.background = "Texture/3DMapSystem/Desktop/LoginPageBottom.png: 15 55 15 8";
_loginBar:AddChild(_offline);
--local _this = ParaUI.CreateUIObject("button", "b", "_mt", 0, 0, 0, 3);
--_this.background = "Texture/3DMapSystem/Desktop/divider.png"
--_this.enabled = false;
--_offline:AddChild(_this);
--_guihelper.SetUIColor(_this, "255 255 255");
local _loginOffline = ParaUI.CreateUIObject("text", "LoginSucceed", "_lt", 20, 10, 250, 24);
_loginOffline.text = L"正在以单机模式运行!";--"Currently running in Offline Mode!";
--_loginOffline:GetFont("text").color = "200 227 241";
_loginOffline.font = Desktop.LoginBarFont;
_offline:AddChild(_loginOffline);
local _back = ParaUI.CreateUIObject("button", "BackToLogin", "_lt", 20, 40, 150, 32);
_back.text = L"返回登陆页";
_back.background = Desktop.LoginButton_HL;
_back:GetFont("text").color = "4 55 89";
_back.font = Desktop.LoginBarFont;
_back.onclick = ";Map3DSystem.UI.Desktop.ShowLogin();";
_offline:AddChild(_back);
NPL.load("(gl)script/ide/GridView.lua");
local ctl = CommonCtrl.GetControl("Desktop_Login_Offline_GridView");
if(ctl==nil)then
ctl = CommonCtrl.GridView:new{
name = "Desktop_Login_Offline_GridView",
alignment = "_fi",
container_bg = "",
left = 280, top = 0,
width = 20,
height = 0,
cellWidth = 100,
cellHeight = 90,
parent = _offline,
columns = 20,
rows = 1,
font_color = "#C8E3F1",
DrawCellHandler = Desktop.OwnerDrawGridCellHandler,
};
local cell;
local index, node;
for index, node in ipairs(Desktop.icons.Nodes[3].Nodes) do
-- fill default
cell = CommonCtrl.GridCell:new(node);
if(node.column == nil) then
ctl:AppendCell(cell, "Right");
else
ctl:InsertCell(cell, "Right");
end
end
else
ctl.parent = _offline;
end
ctl:Show();
else
if(bShow == nil) then
_offline.visible = not _offline.visible;
else
_offline.visible = bShow;
end
end
-- hide the online and login container if valid
local _online = _loginBar:GetChild("Online");
local _login = _loginBar:GetChild("Login");
if(_online:IsValid() == true) then
_online.visible = false;
end
if(_login:IsValid() == true) then
_login.visible = false;
end
-- make sure that it switched to the first tab in online app.
Desktop.OnClickGridCell("Desktop_Login_Offline_GridView", 1, 1, true)
end
-- Exit app button.
function Desktop.OnClickCallback_ExitApp()
_guihelper.MessageBox(L"你确定要退出程序么?", Desktop.OnExitApp);
end
-- quick to windows
function Desktop.OnExitApp()
ParaGlobal.ExitApp();
end
-- switch to in-game empty scene for testing. TODO: remove this.
function Desktop.LoadEmptyScene()
main_state="ingame";
end
-- switch to in-game demo scene for testing. TODO: remove this.
function Desktop.LoadDemoScene()
main_state="ingame2";
end
-- to offline mode.
function Desktop.OnLoginOfflineMode()
Desktop.ShowOffline()
end
-- click to create new account
function Desktop.OnClickNewAccount(ctrlName, values)
-- switch to startup view
Map3DSystem.App.Login.OnClickNewAccount();
end
-- Authenticate user and check client version.
function Desktop.OnClickConnect(ctrlName, values)
if(values.username == "" or values.password == "") then
paraworld.ShowMessage(L"用户名和密码不能为空, 如果你尚未注册, 请点击新建用户按钮.")
return;
end
NPL.load("(gl)script/kids/3DMapSystemApp/Login/LoginProcedure.lua");
paraworld.ShowMessage(L"正在验证用户身份, 请等待...", function()
Desktop.OnClickConnect(ctrlName, values)
end, _guihelper.MessageBoxButtons.RetryCancel)
ParaEngine.ForceRender();
--Map3DSystem.App.Login.Proc_Authentication(values, nil); -- do not switch at the moment.
Map3DSystem.App.Login.Proc_Authentication(values, Desktop.ShowOnline);
end
-- goto a url page on the desktop front page.
-- @param url: url of the page
-- @param cachePolicy: nil or a cache policy. if nil, it defaults to 1 day.
function Desktop.GotoDesktopPage(url, cachepolicy)
-- make sure that it switched to the first tab in online app.
Desktop.OnClickGridCell("Desktop_Startup_GridView", 1, 1, true)
-- go to page
Map3DSystem.App.Login.GotoPage(url, cachepolicy)
end | gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bastok_Markets/npcs/Shamarhaan.lua | 1 | 1087 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Shamarhaan
-- Type: Quest Starter
-- @zone: 235
-- @pos: -285.382 -13.021 -84.743
--
-- Auto-Script: Requires Verification. Verified standard dialog - thrydwolf 12/8/2011
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01b1);
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 |
Aminrezaa/megareborn | plugins/lock_fosh.lua | 3 | 2340 | local function pre_process(msg)
local chkfosh = redis:hget('settings:fosh',msg.chat_id_)
if not chkfosh then
redis:hset('settings:fosh',msg.chat_id_,'off')
end
end
local function run(msg, matches)
--Commands --دستورات فعال و غیرفعال کردن فحش
if matches[1]:lower() == 'unlock' then
if matches[2]:lower() == 'fosh' then
if not is_mod(msg) then return end
local fosh = redis:hget('settings:fosh',msg.chat_id_)
if fosh == 'on' then
redis:hset('settings:fosh',msg.chat_id_,'off')
return '*Fosh Hash Been* `Unlocked`'
elseif fosh == 'off' then
return '*Fosh Is Already* `Unlocked`'
end
end
end
if matches[1]:lower() == 'lock' then
if matches[2]:lower() == 'fosh' then
if not is_mod(msg) then return end
local fosh = redis:hget('settings:fosh',msg.chat_id_)
if fosh == 'off' then
redis:hset('settings:fosh',msg.chat_id_,'on')
return '*Fosh Hash Been* `Locked`'
elseif fosh == 'on' then
return '*Fosh Is Already* `Locked`'
end
end
end
--Delete words contains --حذف پیامهای فحش
if not is_mod(msg) then
local fosh = redis:hget('settings:fosh',msg.chat_id_)
if fosh == 'on' then
tdcli.deleteMessages(msg.chat_id_, {[0] = msg.id_}, dl_cb, nil)
end
end
end
return {
patterns = {
"(ک*س)$",
"کیر",
"کص",
"کــــــــــیر",
"کــــــــــــــــــــــــــــــیر",
"کـیـــــــــــــــــــــــــــــــــــــــــــــــــــر",
"ک×یر",
"ک÷یر",
"ک*ص",
"کــــــــــیرر",
"kir",
"kos",
"گوساله",
"gosale",
"gusale",
"جاکش",
"قرمساق",
"دیوس",
"دیوص",
"dayus",
"dayos",
"dayu3",
"10yus",
"10yu3",
"daus",
"dau3",
"تخمی",
"حرومزاده",
"حروم زاده",
"harumzade",
"haromzade",
"haroomzade",
"lashi",
"لاشی",
"لاشي",
"جنده",
"jende",
"tokhmi",
"madarjende",
"kharkosde",
"خارکسده",
"خوارکسده",
"خارکصده",
"خوارکصده",
"kharko3de",
"مادرجنده",
--Commands ##Don't change this##
"^[!/#]([Ll][Oo][Cc][Kk]) (.*)$",
"^[!/#]([Uu][Nn][Ll][Oo][Cc][Kk]) (.*)$",
------------End----------------
},
run = run,
pre_process = pre_process
}
--End lock_fosh.lua
| gpl-3.0 |
kamran2222/Blackeagles | bot/utils.lua | 309 | 23029 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
for v,group in pairs(_config.realm) do
if group == msg.to.id then
var = true
end
end
return var
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end | gpl-2.0 |
james2doyle/lit | libs/calculate-deps.lua | 6 | 2942 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
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 normalize = require('semver').normalize
local gte = require('semver').gte
local log = require('log').log
local queryDb = require('pkg').queryDb
local colorize = require('pretty-print').colorize
return function (db, deps, newDeps)
local addDep, processDeps
function processDeps(dependencies)
if not dependencies then return end
for alias, dep in pairs(dependencies) do
local name, version = dep:match("^([^@]+)@?(.*)$")
if #version == 0 then
version = nil
end
if type(alias) == "number" then
alias = name:match("([^/]+)$")
end
if not name:find("/") then
error("Package names must include owner/name at a minimum")
end
if version then
local ok
ok, version = pcall(normalize, version)
if not ok then
error("Invalid dependency version: " .. dep)
end
end
addDep(alias, name, version)
end
end
function addDep(alias, name, version)
local meta = deps[alias]
if meta then
if name ~= meta.name then
local message = string.format("%s %s ~= %s",
alias, meta.name, name)
log("alias conflict", message, "failure")
return
end
if version then
if not gte(meta.version, version) then
local message = string.format("%s %s ~= %s",
alias, meta.version, version)
log("version conflict", message, "failure")
return
end
end
else
local author, pname = name:match("^([^/]+)/(.*)$")
local match, hash = db.match(author, pname, version)
if not match then
error("No such "
.. (version and "version" or "package") .. ": "
.. name
.. (version and '@' .. version or ''))
end
local kind
meta, kind, hash = assert(queryDb(db, hash))
meta.db = db
meta.hash = hash
meta.kind = kind
deps[alias] = meta
end
processDeps(meta.dependencies)
end
processDeps(newDeps)
local names = {}
for k in pairs(deps) do
names[#names + 1] = k
end
table.sort(names)
for i = 1, #names do
local name = names[i]
local meta = deps[name]
log("including dependency", string.format("%s (%s)",
colorize("highlight", name), meta.path or meta.version))
end
return deps
end
| apache-2.0 |
RyMarq/Zero-K | LuaRules/Gadgets/unit_is_on_fire.lua | 2 | 7691 | -- $Id: unit_is_on_fire.lua 3309 2008-11-28 04:25:20Z google frog $
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Units on fire",
desc = "Aaagh! It burns! It burns!",
author = "quantum",
date = "Mar, 2008",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local SAVE_FILE = "Gadgets/unit_is_on_fire.lua"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (gadgetHandler:IsSyncedCode()) then
--------------------------------------------------------------------------------
-- SYNCED
--------------------------------------------------------------------------------
--// customparams values
-- setunitsonfire:
-- iff a weapon has this tag set to anything it will set units on fire.
-- burntime:
-- burntime of weapon in frames. defaults to DEFAULT_BURN_TIME*firestarter/100
-- burntimerand:
-- adds randomness to burntime. Defaults to DEFAULT_BURN_TIME_RANDOMNESS
-- Constant random distribution over domain [burntime*(1-burnTimeRand),burntime].
-- burnchance:
-- Chance of a unit to be set on fire when hit. Defaults to firestarter/1000
-- burndamage:
-- Damage per frame of burning. Defaults to DEFAULT_BURN_DAMAGE
--//SETTINGS
local DEFAULT_BURN_TIME = 450
local DEFAULT_BURN_TIME_RANDOMNESS = 0.3
local DEFAULT_BURN_DAMAGE = 0.5
local MIN_IMMERSION_FOR_EXTINGUISH = 0.8
local CHECK_INTERVAL = 6
local LOS_ACCESS = {inlos = true}
--//VARS
local gameFrame = 0
--//LOCALS
local random = math.random
local Spring = Spring
local gadget = gadget
local AreTeamsAllied = Spring.AreTeamsAllied
local AddUnitDamage = Spring.AddUnitDamage
local SetUnitRulesParam = Spring.SetUnitRulesParam
local SetUnitCloak = Spring.SetUnitCloak
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function cpv(value)
return value and tonumber(value)
end
-- NOTE: fireStarter is divided by 100 somewhere in the engine between weapon defs and here.
local flamerWeaponDefs = {}
for i = 1, #WeaponDefs do
local wcp = WeaponDefs[i].customParams or {}
if (wcp.setunitsonfire) then -- stupid tdf
--// (fireStarter-tag: 1.0->always flame trees, 2.0->always flame units/buildings too) -- citation needed
flamerWeaponDefs[i] = {
burnTime = cpv(wcp.burntime) or WeaponDefs[i].fireStarter*DEFAULT_BURN_TIME,
burnTimeRand = cpv(wcp.burntimerand) or DEFAULT_BURN_TIME_RANDOMNESS,
burnTimeBase = 1 - (cpv(wcp.burntimerand) or DEFAULT_BURN_TIME_RANDOMNESS),
burnChance = cpv(wcp.burnchance) or WeaponDefs[i].fireStarter/10,
burnDamage = cpv(wcp.burndamage) or DEFAULT_BURN_DAMAGE,
}
flamerWeaponDefs[i].maxDamage = flamerWeaponDefs[i].burnDamage*flamerWeaponDefs[i].burnTime
end
end
local unitsOnFire = {}
local inWater = {}
local inGameFrame = false
_G.unitsOnFire = unitsOnFire
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function CheckImmersion(unitID)
local pos = select(2, Spring.GetUnitBasePosition(unitID))
local height = Spring.GetUnitHeight(unitID)
if pos < -(height * MIN_IMMERSION_FOR_EXTINGUISH) then
return true
end
return false
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:UnitEnteredWater(unitID, unitDefID, unitTeam)
inWater[unitID] = true
end
function gadget:UnitLeftWater(unitID, unitDefID, unitTeam)
inWater[unitID] = nil
end
function gadget:UnitDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponID,
attackerID, attackerDefID, attackerTeam)
if (inGameFrame) then return end --ignore own AddUnitDamage calls
if (flamerWeaponDefs[weaponID]) then
local fwd = flamerWeaponDefs[weaponID]
if (UnitDefs[unitDefID].customParams.fireproof~="1") then
if (random() < fwd.burnChance) then
local burnLength = fwd.burnTime*(random()*fwd.burnTimeRand + fwd.burnTimeBase)
if (not unitsOnFire[unitID]) or unitsOnFire[unitID].damageLeft < (burnLength*fwd.burnDamage) then
unitsOnFire[unitID] = {
endFrame = gameFrame + burnLength,
damageLeft = burnLength*fwd.burnDamage,
fireDmg = fwd.burnDamage,
attackerID = attackerID,
--attackerDefID = attackerDefID,
weaponID = weaponID,
}
SetUnitRulesParam(unitID, "on_fire", 1, LOS_ACCESS)
GG.UpdateUnitAttributes(unitID)
end
end
end
end
end
function gadget:UnitDestroyed(unitID)
inWater[unitID] = nil
if (unitsOnFire[unitID]) then
unitsOnFire[unitID] = nil
end
end
function gadget:GameFrame(n)
gameFrame = n
if (n%CHECK_INTERVAL<1)and(next(unitsOnFire)) then
local burningUnits = {}
local cnt = 1
inGameFrame = true
for unitID, t in pairs(unitsOnFire) do
if (n > t.endFrame) or (inWater[unitID] and CheckImmersion(unitID)) then
SetUnitRulesParam(unitID, "on_fire", 0)
GG.UpdateUnitAttributes(unitID)
unitsOnFire[unitID] = nil
else
t.damageLeft = t.damageLeft - t.fireDmg*CHECK_INTERVAL
AddUnitDamage(unitID,t.fireDmg*CHECK_INTERVAL,0,t.attackerID, t.weaponID )
--Spring.Echo(t.attackerDefID)
burningUnits[cnt] = unitID
cnt=cnt+1
end
end
inGameFrame = false
end
end
function gadget:Initialize()
Spring.SetGameRulesParam("unitsOnFire",1)
local allUnits = Spring.GetAllUnits()
for i=1,#allUnits do
local unitID = allUnits[i]
local x,y,z = Spring.GetUnitPosition(unitID)
if y < 0 then
gadget:UnitEnteredWater(unitID)
end
end
end
function gadget:Load(zip)
if not (GG.SaveLoad and GG.SaveLoad.ReadFile) then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Failed to access save/load API")
return
end
local loadData = GG.SaveLoad.ReadFile(zip, "Units on Fire", SAVE_FILE) or {}
local currGameFrame = Spring.GetGameRulesParam("lastSaveGameFrame") or 0
unitsOnFire = {}
for oldID, entry in pairs(loadData) do
local newID = GG.SaveLoad.GetNewUnitID(oldID)
entry.endFrame = entry.endFrame - currGameFrame
entry.attackerID = GG.SaveLoad.GetNewUnitID(entry.attackerID)
unitsOnFire[newID] = entry
SetUnitRulesParam(newID, "on_fire", 1, LOS_ACCESS)
GG.UpdateUnitAttributes(newID)
end
_G.unitsOnFire = unitsOnFire
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
else
--------------------------------------------------------------------------------
-- UNSYNCED
--------------------------------------------------------------------------------
function gadget:Save(zip)
if not GG.SaveLoad then
Spring.Log(gadget:GetInfo().name, LOG.ERROR, "Failed to access save/load API")
return
end
local onFire = Spring.Utilities.MakeRealTable(SYNCED.unitsOnFire, "Units on Fire")
--local inWater = {} -- regenerate on init
GG.SaveLoad.WriteSaveData(zip, SAVE_FILE, onFire)
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
end
| gpl-2.0 |
rigeirani/sss | plugins/isX.lua | 605 | 2031 | local https = require "ssl.https"
local ltn12 = require "ltn12"
local function request(imageUrl)
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local api_key = mashape.api_key
if api_key:isempty() then
return nil, 'Configure your Mashape API Key'
end
local api = "https://sphirelabs-advanced-porn-nudity-and-adult-content-detection.p.mashape.com/v1/get/index.php?"
local parameters = "&url="..(URL.escape(imageUrl) or "")
local url = api..parameters
local respbody = {}
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "Accept: application/json"
}
print(url)
local body, code, headers, status = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return "", code end
local body = table.concat(respbody)
return body, code
end
local function parseData(data)
local jsonBody = json:decode(data)
local response = ""
print(data)
if jsonBody["Error Occured"] ~= nil then
response = response .. jsonBody["Error Occured"]
elseif jsonBody["Is Porn"] == nil or jsonBody["Reason"] == nil then
response = response .. "I don't know if that has adult content or not."
else
if jsonBody["Is Porn"] == "True" then
response = response .. "Beware!\n"
end
response = response .. jsonBody["Reason"]
end
return jsonBody["Is Porn"], response
end
local function run(msg, matches)
local data, code = request(matches[1])
if code ~= 200 then return "There was an error. "..code end
local isPorn, result = parseData(data)
return result
end
return {
description = "Does this photo contain adult content?",
usage = {
"!isx [url]",
"!isporn [url]"
},
patterns = {
"^!is[x|X] (.*)$",
"^!is[p|P]orn (.*)$"
},
run = run
} | gpl-2.0 |
pixeljetstream/luajit_gfx_sandbox | runtime/lua/socket/ftp.lua | 60 | 9243 | -----------------------------------------------------------------------------
-- FTP support for the Lua language
-- LuaSocket toolkit.
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local table = require("table")
local string = require("string")
local math = require("math")
local socket = require("socket")
local url = require("socket.url")
local tp = require("socket.tp")
local ltn12 = require("ltn12")
socket.ftp = {}
local _M = socket.ftp
-----------------------------------------------------------------------------
-- Program constants
-----------------------------------------------------------------------------
-- timeout in seconds before the program gives up on a connection
_M.TIMEOUT = 60
-- default port for ftp service
_M.PORT = 21
-- this is the default anonymous password. used when no password is
-- provided in url. should be changed to your e-mail.
_M.USER = "ftp"
_M.PASSWORD = "anonymous@anonymous.org"
-----------------------------------------------------------------------------
-- Low level FTP API
-----------------------------------------------------------------------------
local metat = { __index = {} }
function _M.open(server, port, create)
local tp = socket.try(tp.connect(server, port or _M.PORT, _M.TIMEOUT, create))
local f = base.setmetatable({ tp = tp }, metat)
-- make sure everything gets closed in an exception
f.try = socket.newtry(function() f:close() end)
return f
end
function metat.__index:portconnect()
self.try(self.server:settimeout(_M.TIMEOUT))
self.data = self.try(self.server:accept())
self.try(self.data:settimeout(_M.TIMEOUT))
end
function metat.__index:pasvconnect()
self.data = self.try(socket.tcp())
self.try(self.data:settimeout(_M.TIMEOUT))
self.try(self.data:connect(self.pasvt.ip, self.pasvt.port))
end
function metat.__index:login(user, password)
self.try(self.tp:command("user", user or _M.USER))
local code, reply = self.try(self.tp:check{"2..", 331})
if code == 331 then
self.try(self.tp:command("pass", password or _M.PASSWORD))
self.try(self.tp:check("2.."))
end
return 1
end
function metat.__index:pasv()
self.try(self.tp:command("pasv"))
local code, reply = self.try(self.tp:check("2.."))
local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)"
local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern))
self.try(a and b and c and d and p1 and p2, reply)
self.pasvt = {
ip = string.format("%d.%d.%d.%d", a, b, c, d),
port = p1*256 + p2
}
if self.server then
self.server:close()
self.server = nil
end
return self.pasvt.ip, self.pasvt.port
end
function metat.__index:port(ip, port)
self.pasvt = nil
if not ip then
ip, port = self.try(self.tp:getcontrol():getsockname())
self.server = self.try(socket.bind(ip, 0))
ip, port = self.try(self.server:getsockname())
self.try(self.server:settimeout(_M.TIMEOUT))
end
local pl = math.mod(port, 256)
local ph = (port - pl)/256
local arg = string.gsub(string.format("%s,%d,%d", ip, ph, pl), "%.", ",")
self.try(self.tp:command("port", arg))
self.try(self.tp:check("2.."))
return 1
end
function metat.__index:send(sendt)
self.try(self.pasvt or self.server, "need port or pasv first")
-- if there is a pasvt table, we already sent a PASV command
-- we just get the data connection into self.data
if self.pasvt then self:pasvconnect() end
-- get the transfer argument and command
local argument = sendt.argument or
url.unescape(string.gsub(sendt.path or "", "^[/\\]", ""))
if argument == "" then argument = nil end
local command = sendt.command or "stor"
-- send the transfer command and check the reply
self.try(self.tp:command(command, argument))
local code, reply = self.try(self.tp:check{"2..", "1.."})
-- if there is not a a pasvt table, then there is a server
-- and we already sent a PORT command
if not self.pasvt then self:portconnect() end
-- get the sink, source and step for the transfer
local step = sendt.step or ltn12.pump.step
local readt = {self.tp.c}
local checkstep = function(src, snk)
-- check status in control connection while downloading
local readyt = socket.select(readt, nil, 0)
if readyt[tp] then code = self.try(self.tp:check("2..")) end
return step(src, snk)
end
local sink = socket.sink("close-when-done", self.data)
-- transfer all data and check error
self.try(ltn12.pump.all(sendt.source, sink, checkstep))
if string.find(code, "1..") then self.try(self.tp:check("2..")) end
-- done with data connection
self.data:close()
-- find out how many bytes were sent
local sent = socket.skip(1, self.data:getstats())
self.data = nil
return sent
end
function metat.__index:receive(recvt)
self.try(self.pasvt or self.server, "need port or pasv first")
if self.pasvt then self:pasvconnect() end
local argument = recvt.argument or
url.unescape(string.gsub(recvt.path or "", "^[/\\]", ""))
if argument == "" then argument = nil end
local command = recvt.command or "retr"
self.try(self.tp:command(command, argument))
local code,reply = self.try(self.tp:check{"1..", "2.."})
if (code >= 200) and (code <= 299) then
recvt.sink(reply)
return 1
end
if not self.pasvt then self:portconnect() end
local source = socket.source("until-closed", self.data)
local step = recvt.step or ltn12.pump.step
self.try(ltn12.pump.all(source, recvt.sink, step))
if string.find(code, "1..") then self.try(self.tp:check("2..")) end
self.data:close()
self.data = nil
return 1
end
function metat.__index:cwd(dir)
self.try(self.tp:command("cwd", dir))
self.try(self.tp:check(250))
return 1
end
function metat.__index:type(type)
self.try(self.tp:command("type", type))
self.try(self.tp:check(200))
return 1
end
function metat.__index:greet()
local code = self.try(self.tp:check{"1..", "2.."})
if string.find(code, "1..") then self.try(self.tp:check("2..")) end
return 1
end
function metat.__index:quit()
self.try(self.tp:command("quit"))
self.try(self.tp:check("2.."))
return 1
end
function metat.__index:close()
if self.data then self.data:close() end
if self.server then self.server:close() end
return self.tp:close()
end
-----------------------------------------------------------------------------
-- High level FTP API
-----------------------------------------------------------------------------
local function override(t)
if t.url then
local u = url.parse(t.url)
for i,v in base.pairs(t) do
u[i] = v
end
return u
else return t end
end
local function tput(putt)
putt = override(putt)
socket.try(putt.host, "missing hostname")
local f = _M.open(putt.host, putt.port, putt.create)
f:greet()
f:login(putt.user, putt.password)
if putt.type then f:type(putt.type) end
f:pasv()
local sent = f:send(putt)
f:quit()
f:close()
return sent
end
local default = {
path = "/",
scheme = "ftp"
}
local function parse(u)
local t = socket.try(url.parse(u, default))
socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'")
socket.try(t.host, "missing hostname")
local pat = "^type=(.)$"
if t.params then
t.type = socket.skip(2, string.find(t.params, pat))
socket.try(t.type == "a" or t.type == "i",
"invalid type '" .. t.type .. "'")
end
return t
end
local function sput(u, body)
local putt = parse(u)
putt.source = ltn12.source.string(body)
return tput(putt)
end
_M.put = socket.protect(function(putt, body)
if base.type(putt) == "string" then return sput(putt, body)
else return tput(putt) end
end)
local function tget(gett)
gett = override(gett)
socket.try(gett.host, "missing hostname")
local f = _M.open(gett.host, gett.port, gett.create)
f:greet()
f:login(gett.user, gett.password)
if gett.type then f:type(gett.type) end
f:pasv()
f:receive(gett)
f:quit()
return f:close()
end
local function sget(u)
local gett = parse(u)
local t = {}
gett.sink = ltn12.sink.table(t)
tget(gett)
return table.concat(t)
end
_M.command = socket.protect(function(cmdt)
cmdt = override(cmdt)
socket.try(cmdt.host, "missing hostname")
socket.try(cmdt.command, "missing command")
local f = open(cmdt.host, cmdt.port, cmdt.create)
f:greet()
f:login(cmdt.user, cmdt.password)
f.try(f.tp:command(cmdt.command, cmdt.argument))
if cmdt.check then f.try(f.tp:check(cmdt.check)) end
f:quit()
return f:close()
end)
_M.get = socket.protect(function(gett)
if base.type(gett) == "string" then return sget(gett)
else return tget(gett) end
end)
return _M | mit |
fegimanam/teshep | plugins/ingroup.lua | 3 | 38187 | do
local function check_member(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
lock_bots = 'no',
lock_arabic = 'no',
flood = 'yes'
},
realm_field = 'no'
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Ora sei il proprietario del gruppo.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
lock_bots = 'no',
lock_arabic = 'no',
flood = 'yes'
},
realm_field = 'no'
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Gruppo indicizzato, ora sei il suo proprietario')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Gruppo rimosso dall\'indice')
end
end
end
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local settings = data[tostring(target)]['settings']
local text = "Impostazioni gruppo:\nBlocco nome: "..settings.lock_name.."\nBlocco foto: "..settings.lock_photo.."\nBlocco membri: "..settings.lock_member.."\nSensitività flood: "..NUM_MSG_MAX.."\nScudo bot: "..bots_protection
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Descrizione del gruppo impostata:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'Nessuna descrizione disponibile.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'Descrizione '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Caratteri arabi già bloccati'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Caratteri arabi bloccati'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Caratteri arabi già sbloccati'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Caratteri arabi sbloccati'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Protezione dai bot (API) già abilitata'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Protezione dai bot (API) abilitata'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Protezione dai bot (API) già disabilitata'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Protezione dai bot (API) disabilitata'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Nome già bloccato'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Nome bloccato'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Nome già sbloccato'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Nome sbloccato'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Solo il proprietario può modificare questa impostazione"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Flood già bloccato'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Flood bloccato'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Solo il proprietario può modificare questa impostazione"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Flood già sbloccato'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Flood sbloccato'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Membri già bloccati'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Membri bloccati'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Membri già sbloccati'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Membri sbloccati'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Foto già sbloccata'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Foto sbloccata'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "Solo per moderatori!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Regole impostate:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "Non sei un amministratore"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
return 'Il gruppo è già aggiunto.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "Non sei amministratore"
end
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Il gruppo non era aggiunto.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
local data = load_data(_config.moderation.data)
local target = msg.to.id
local realm_field = data[tostring(target)]['realm_field']
if realm_field == 'yes' then
return 'Questo gruppo è già un Realm'
else
data[tostring(target)]['realm_field'] = 'yes'
save_data(_config.moderation.data, data)
return 'Questo gruppo ora è un Realm'
end
end
local function realmrem(msg)
local data = load_data(_config.moderation.data)
local target = msg.to.id
local realm_field = data[tostring(target)]['realm_field']
if realm_field == 'no' then
return 'Questo gruppo non è un Realm'
else
data[tostring(target)]['realm_field'] = 'no'
save_data(_config.moderation.data, data)
return 'Questo gruppo ora non è più un Realm'
end
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'Nessuna regola disponibile.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Regole:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File scaricato in:', result)
os.rename(result, file)
print('File spostato in:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Foto salvata!', ok_cb, false)
else
print('Errore nel download: '..msg.id)
send_large_msg(receiver, 'Errore, per favore prova di nuovo!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Il gruppo non è aggiunto.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' è già moderatore.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' è stato promosso moderatore.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Il gruppo non è aggiunto.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' non è un moderatore.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' ora non è più moderatore.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha impostato ["..msg.from.id.."] come proprietario")
local text = msg.from.print_name:gsub("_", " ").." è il proprietario"
return send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'Nessun @'..member..' in questo gruppo.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = '@'..member
member_id = v.id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return 'Il gruppo non è aggiunto.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'Nessun moderatore in questo gruppo.'
end
local i = 1
local message = '\nLista dei moderatori di ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
if success == -1 then
return send_large_msg(receiver, '*Errore: nessun link creato* \nNon sono il creatore del gruppo. Solo il creatore può generare un link.')
end
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function kicknouser(cb_extra, success, result)
local chat = "chat#id"..cb_extra.chat
local user
for k,v in pairs(result.members) do
if not v.username then
user = 'user#id'..v.id
chat_del_user(chat, user, ok_cb, true)
end
end
end
--QUESTE TRE FUNZIONI (SOTTO) SERVONO A KICKARE GLI UTENTI INATTIVI
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat = "chat#id"..cb_extra.chat_id
local chat_id = cb_extra.chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'agg' then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") aggiunto")
return modadd(msg)
end
if matches[1] == 'rim' then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") rimosso")
return modrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 then
return automodadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local receiver = 'user#id'..msg.action.user.id
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return false
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Benvenuto in "' .. string.gsub(msg.to.print_name, '_', ' ') ..'", ecco le regole del gruppo:\n'..rules
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso "..msg.action.user.id)
send_large_msg(receiver, rules)
end
if matches[1] == 'chat_del_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha provato a rimuovere la foto ma ha fallito ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha provato a cambiare la foto ma ha fallito ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha provato a cambiare il nome ma ha fallito ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'nome' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Gruppo { "..msg.to.print_name.." } nome cambiato in [ "..new_name.." ] da "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'foto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Per favore inviami la nuova foto del gruppo ora'
end
if matches[1] == 'promuovi' and not matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può promuovere nuovi moderatori"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promuovi' and matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può promuovere nuovi moderatori"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'promote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha promosso @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'degrada' and not matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può degradare un moderatore"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'degrada' and matches[2] then
if not is_owner(msg) then
return "Solo il proprietario può degradare un moderatore"
end
if string.gsub(matches[2], "@", "") == msg.from.username then
return "Non puoi rinunciare alla carica di moderatore da solo"
end
local member = string.gsub(matches[2], "@", "")
local mod_cmd = 'demote'
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha degradato @".. member)
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
if matches[1] == 'listamod' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto la lista dei moderatori")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto la descrizione")
return get_description(msg, data)
end
if matches[1] == 'regole' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto le regole")
return get_rules(msg, data)
end
if matches[1] == 'setta' then
if matches[2] == 'regole' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha cambiato le regole in ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha cambiato la descrizione in ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'blocca' then
local target = msg.to.id
if matches[2] == 'nome' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato il nome ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'membri' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato i membri ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato il flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato i caratteri arabi ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bot' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha bloccato i bot ")
return lock_group_bots(msg, data, target)
end
end
if matches[1] == 'sblocca' then
local target = msg.to.id
if matches[2] == 'nome' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato il nome ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'membri' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato i membri ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'foto' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato la foto ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato il flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato la lingua araba ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bot' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha sbloccato i bot ")
return unlock_group_bots(msg, data, target)
end
end
if matches[1] == 'info' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto le impostazioni ")
return show_group_settingsmod(msg, data, target)
end
if matches[1] == 'nuovolink' then
if not is_momod(msg) then
return "Solo per moderatori!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Errore: link non creato* \nNon sono il creatore di questo gruppo, solo il creatore può generare il link.')
end
send_large_msg(receiver, "Nuovo link creato")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha revocato il link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "Solo per moderatori!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Crea un nuovo link usando /nuovolink prima!"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha richiesto il link ["..group_link.."]")
return "Link del gruppo:\n"..group_link
end
if matches[1] == 'setboss' and matches[2] then
if not is_owner(msg) then
return "Solo per il proprietario!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha impostato ["..matches[2].."] come proprietario")
local text = matches[2].." impostato come proprietario"
return text
end
if matches[1] == 'setboss' and not matches[2] then
if not is_owner(msg) then
return "Solo per il proprietario!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'boss' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "Nessun proprietario. Chiedi ad un amministratore del bot di impostare il proprietario di questo gruppo"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Il proprietario è ["..group_owner..']'
end
if matches[1] == 'setgrboss' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "Solo per amministratori!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." impostato come proprietario"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "Solo per moderatori!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Il valore deve rientrare nel range [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha impostato il flood a ["..matches[2].."]")
return 'Flood impostato a '..matches[2]
end
if matches[1] == 'spazza' then
if not is_owner(msg) then
return "Solo il proprietario può cancellare"
end
if matches[2] == 'membri' then
if not is_owner(msg) then
return "Solo il proprietario può eliminare tutti i membri"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'mod' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'Nessun moderatore in questo gruppo.'
end
--local message = '\nLista dei moderatori di ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso i moderatori")
return 'Moderatori rimossi'
end
if matches[2] == 'regole' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso le regole")
return 'Regole rimosse'
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha rimosso la descrizione")
return 'Descrizione rimossa'
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] ha usato /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'aggrealm' and is_admin(msg) then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") aggiunto ai realm")
return realmadd(msg)
end
if matches[1] == 'rimrealm' and is_admin(msg) then
print("Gruppo "..msg.to.print_name.."("..msg.to.id..") rimosso dai realm")
return realmrem(msg)
end
if matches[1] == 'isrealm' then
if is_realmM(msg) then
return 'Questo gruppo è un Realm'
else
return 'Questo gruppo non è un Realm'
end
end
if matches[1] == 'kickanouser' then
if not is_owner(msg) then
return "Solo il proprietario può usare questo comando!"
end
chat_info(receiver, kicknouser, {chat = msg.to.id})
end
if matches[1] == 'kickainattivi' then
if not is_momod(msg) then
return 'Solo un moderatore può rimuovere gli utenti inattivi'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^/(agg)$",
"^/(rim)$",
"^/(regole)$",
"^/(about)$",
"^/(nome) (.*)$",
"^/(foto)$",
"^/(promuovi) (.*)$",
"^/(promuovi)",
"^/(spazza) (.*)$",
"^/(degrada) (.*)$",
"^/(degrada)",
"^/(setta) ([^%s]+) (.*)$",
"^/(blocca) (.*)$",
"^/(setboss) (%d+)$",
"^/(setboss)",
"^/(boss)$",
"^/(res) (.*)$",
"^/(setgrboss) (%d+) (%d+)$",-- (group id) (owner id)
"^/(sblocca) (.*)$",
"^/(setflood) (%d+)$",
"^/(info)$",
"^/(listamod)$",
"^/(nuovolink)$",
"^/(link)$",
"^/(aggrealm)$",
"^/(rimrealm)$",
"^/(isrealm)$",
"^/(kickanouser)$",
"^/(kickainattivi)$",
"^/(kickainattivi) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Inner_Horutoto_Ruins/npcs/_5cs.lua | 1 | 2887 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Magical Gizmo #4 (S out of P, Q, R, S, T, U)
-- Involved In Mission: The Horutoto Ruins Experiment
-- Working ???%
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- The Magical Gizmo Number, this number will be compared to the random
-- value created by the mission The Horutoto Ruins Experiment, when you
-- reach the Gizmo Door and have the cutscene
random_value = player:getVar("windurst_mission_1_1_rv");
magical_gizmo_no = 4; -- of the 6
-- Check if we are on Windurst Mission 1-1
if(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT) then
windurst_mission_1_1 = player:getVar("windurst_mission_1_1");
if(windurst_mission_1_1 == 3) then
-- Check if we found the correct Magical Gizmo or not
if( random_value == magical_gizmo_no ) then
player:startEvent(0x36);
-- Set the progress
player:setVar("windurst_mission_1_1",4);
else
already_opened = player:getVar("windurst_mission_1_1_op4");
if(already_opened == 2) then
-- We've already examined this
player:messageSpecial(EXAMINED_RECEPTACLE);
else
-- Opened the wrong one
player:startEvent(0x37);
end
end
else
-- Nothing
end
else
-- Nothing
end
return 1;
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 we just finished the cutscene for Windurst Mission 1-1
-- The cutscene that we opened the correct Magical Gizmo
if(csid == 0x36) then
-- Give the player the key item
player:addKeyItem(CRACKED_MANA_ORBS);
player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS);
-- Delete the random value we created for the Magic Gizmo's
player:setVar("windurst_mission_1_1_rv", 0);
elseif(csid == 0x37) then
-- Opened the wrong one
player:setVar("windurst_mission_1_1_op4", 2);
-- Give the message that thsi orb is not broken
player:messageSpecial(NOT_BROKEN_ORB);
end
end;
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/settings.lua | 1 | 9697 | -----------------------------------------------
------------- GLOBAL SETTINGS -------------
-----------------------------------------------
--This is to allow server operators to further customize their servers. As more features are added to pXI, the list will surely expand.
--Anything scripted can be customized with proper script editing.
--PLEASE REQUIRE THIS SCRIPT IN ANY SCRIPTS YOU DO: ADD THIS LINE TO THE TOP!!!!
-- require("scripts/globals/settings");
--With this script added to yours, you can pull variables from it!!
--Common functions
require("scripts/globals/common");
--Always include status.lua, which defines mods
--require("scripts/globals/status");
--See chocoprice.lua to adjust chocobo stables.
--require("scripts/globals/chocoprice");
INITIAL_LEVEL_CAP = 50; --The initial level cap for new players. There seems to be a hardcap of 255.
START_GIL = 10; --Amount of gil given to newly created characters.
START_INVENTORY = 30; --Amount of EXTRA slots beyond 30 to be given to a character. Do not set above 80!
OPENING_CUTSCENE_ENABLE = 0; --Set to 1 to enable opening cutscenes, 0 to disable.
SUBJOB_QUEST_LEVEL = 18; --Minimum level to accept either subjob quest. Set to 0 to start the game with subjobs unlocked.
ADVANCED_JOB_LEVEL = 30; --Minimum level to accept advanced job quests. Set to 0 to start the game with advanced jobs.
SHOP_PRICE = 1.000; --Multiplies prices in NPC shops.
GIL_RATE = 1.000; --Multiplies gil earned from quests. Won't always display in game.
EXP_RATE = 1.000; --Multiplies exp earned from fov.
TABS_RATE = 1.000; --Multiplies tabs earned from fov.
SAN_FAME = 1.000; --Multiplies fame earned from San d'Oria quests.
BAS_FAME = 1.000; --Multiplies fame earned from Bastok quests.
WIN_FAME = 1.000; --Multiplies fame earned from Windurst quests.
NORG_FAME = 1.000; --Multiplies fame earned from Norg and Tenshodo quests.
FISHING_GUILD_POINTS = 1.000; --Multiplies guild points earned from fishermans' guild trades.
WOODWORKING_GUILD_POINTS = 1.000; --Multiplies guild points earned from carpenters' guild trades.
SMITHING_GUILD_POINTS = 1.000; --Multiplies guild points earned from blacksmiths' guild trades.
GOLDSMITHING_GUILD_POINTS = 1.000; --Multiplies guild points earned from goldsmiths' guild trades.
CLOTHCRAFT_GUILD_POINTS = 1.000; --Multiplies guild points earned from weavers' guild trades.
LEATHERCRAFT_GUILD_POINTS = 1.000; --Multiplies guild points earned from tanners' guild trades.
BONECRAFT_GUILD_POINTS = 1.000; --Multiplies guild points earned from boneworkers' guild trades.
ALCHEMY_GUILD_POINTS = 1.000; --Multiplies guild points earned from alchemists' guild trades.
COOKING_GUILD_POINTS = 1.000; --Multiplies guild points earned from culinarians' guild trades.
DISABLE_GUILD_CONTRACTS = 0; --Set to 1 to disable guild contracts, allowing players to accumulate guild points from all guilds at once.
CURE_POWER = 1.000; --Multiplies amount healed from Healing Magic, including the relevant Blue Magic.
SPELL_POWER = 1.000; --Multiplies damage dealt by Elemental and Divine Magic.
BLUE_POWER = 1.000; --Multiplies damage dealt by most Blue Magic.
DRAIN_POWER = 1.000; --Multiplies amount drained by Drain, Aspir, and relevant Blue Magic spells.
ITEM_POWER = 1.000; --Multiplies the effect of items such as Potions and Ethers.
WEAPON_SKILL_POWER = 1.000; -- Multiplies damage dealt by Weapon Skills.
WEAPON_SKILL_POINTS = 1.000; --Multiplies points earned during weapon unlocking.
HARVESTING_BREAK_CHANCE = 0.33; --% chance for the sickle to break during harvesting. Set between 0 and 1.
EXCAVATION_BREAK_CHANCE = 0.33; --% chance for the pickaxe to break during excavation. Set between 0 and 1.
LOGGING_BREAK_CHANCE = 0.33; --% chance for the hatchet to break during logging. Set between 0 and 1.
MINING_BREAK_CHANCE = 0.33; --% chance for the pickaxe to break during mining. Set between 0 and 1.
HARVESTING_RATE = 0.50; --% chance to recieve an item from haresting. Set between 0 and 1.
EXCAVATION_RATE = 0.50; --% chance to recieve an item from excavation. Set between 0 and 1.
LOGGING_RATE = 0.50; --% chance to recieve an item from logging. Set between 0 and 1.
MINING_RATE = 0.50; --% chance to recieve an item from mining. Set between 0 and 1.
-- SE implemented coffer/chest illusion time in order to prevent coffer farming. No-one in the same area can open a chest or coffer for loot (gil, gems & items)
-- till a random time between MIN_ILLSION_TIME and MAX_ILLUSION_TIME. During this time players can loot keyitem and item related to quests (AF, maps... etc.)
COFFER_MAX_ILLUSION_TIME = 3600; -- 1 hour
COFFER_MIN_ILLUSION_TIME = 1800; -- 30 minutes
CHEST_MAX_ILLUSION_TIME = 3600; -- 1 hour
CHEST_MIN_ILLUSION_TIME = 1800; -- 30 minutes
TIMELESS_HOURGLASS_COST = 500000; -- cost of the timeless hourglass for Dynamis.
RELIC_1ST_UPGRADE_WAIT_TIME = 100; -- wait time for 1st relic upgrade (stage 1 -> stage 2) in seconds. 86400s = 1 RL day.
RELIC_2ND_UPGRADE_WAIT_TIME = 100; -- wait time for 2nd relic upgrade (stage 2 -> stage 3) in seconds. 604800s = 1 RL week.
RELIC_3RD_UPGRADE_WAIT_TIME = 100; -- wait time for 3rd relic upgrade (stage 3 -> stage 4) in seconds. 295200s = 82 hours.
ALL_MAPS = 0; --Set to 1 to give starting characters all the maps.
JINX_MODE_2005 = 0; --Set to 1 to give starting characters swimsuits from 2005.
JINX_MODE_2008 = 0; --Set to 1 to give starting characters swimsuits from 2008.
SUMMERFEST = 0; --Set to 1 to give starting characters Far East dress.
CHRISTMAS = 0; --Set to 1 to give starting characters Christmas dress.
HALLOWEEN = 0; --Set to 1 to give starting characters Halloween dress.
--QUEST/MISSION SPECIFIC SETTINGS
WSNM_LEVEL = 70; -- Min Level to get WSNM Quests
WSNM_SKILL_LEVEL = 240;
AF1_QUEST_LEVEL = 40; -- Minimum level to start AF1 quest
AF2_QUEST_LEVEL = 50; -- Minimum level to start AF2 quest
AF1_FAME = 20; -- base fame for completing an AF1 quest
AF2_FAME = 40; -- base fame for completing an AF2 quest
AF3_FAME = 60; -- base fame for completing an AF3 quest
DEBUG_MODE = 1; -- Set to 1 to activate auto-warping to the next location (only supported by certain missions / quests).
QM_RESET_TIME = 300; -- Default time (in seconds) you have from killing ???-pop mission NMs to click again and get key item, until ??? resets.
--FIELDS OF VALOR SETTINGS
REGIME_WAIT = 1; --Make people wait till 00:00 game time as in retail. If it's 0, there is no wait time.
LOW_LEVEL_REGIME = 0; --Allow people to kill regime targets even if they give no exp, allowing people to farm regime targets at 75 in low level areas.
--JOB ABILITY/TRAIT SPECIFIC SETTINGS
SCAVENGE_RATE = 0.1; --The chance of obtaining an item when you use the Ranger job ability Scavenge. Do not set above 1!
STATUS_RESIST_MULTIPLIER = 10; -- Sets the strength of status resist traits.
CIRCLE_DURATION = 600; -- Sets the duration of circle effects, in seconds. Retail is 60 seconds.
CIRCLE_KILLER_EFFECT = 20; -- Intimidation percentage granted by circle effects. (made up number)
KILLER_EFFECT = 10; -- Intimidation percentage from killer job traits.
--SPELL SPECIFIC SETTINGS
MILK_OVERWRITE = 1; --Set to 1 to allow Milk and Regen to overwrite each other. Default is 1.
JUICE_OVERWRITE = 1; --Set to 1 to allow Juice and Refresh to overwrite each other. Default is 1.
DIA_OVERWRITE = 1; --Set to 1 to allow Bio to overwrite same tier Dia. Default is 1.
BIO_OVERWRITE = 0; --Set to 1 to allow Dia to overwrite same tier Bio. Default is 0.
BARELEMENT_OVERWRITE = 1; --Set to 1 to allow Barelement spells to overwrite each other (prevent stacking). Default is 1.
BARSTATUS_OVERWRITE = 1; --Set to 1 to allow Barstatus spells to overwrite each other (prevent stacking). Default is 1.
BARD_SONG_LIMIT = 1; --Maximum amount of songs from a single Bard that can be granted to a single target at once. Set between 1 and 31.
BARD_INSTRUMENT_LIMIT = 2; --Maximum amount of songs from a single Bard with an instrument that can be granted to a single target at once. Set between 2 and 32.
ENHANCING_SONG_DURATION = 120; -- duration of enhancing bard songs such as Minuets, Ballads, etc.
STONESKIN_CAP = 350; -- soft cap for hp absorbed by stoneskin
BLINK_SHADOWS = 2; -- number of shadows supplied by Blink spell
ENSPELL_DURATION = 180; -- duration of RDM en-spells
SPIKE_EFFECT_DURATION = 180; -- the duration of RDM, BLM spikes effects (not Reprisal)
ELEMENTAL_DEBUFF_DURATION = 120; -- base duration of elemental debuffs
STORM_DURATION = 180; -- duration of Scholar storm spells
KLIMAFORM_MACC = 30; -- magic accuracy added by Klimaform. 30 is just a guess.
AQUAVEIL_INTERR_RATE = 25; -- percent spell interruption rate reduction from Aquaveil (see http://www.bluegartrls.com/forum/82143-spell-interruption-down-cap-aquaveil-tests.html)
ABSORB_SPELL_AMOUNT = 8; -- how much of a stat gets absorbed by DRK absorb spells - expected to be a multiple of 8.
ABSORB_SPELL_TICK = 9; -- duration of 1 absorb spell tick
SNEAK_INVIS_DURATION_MULTIPLIER = 1; -- multiplies duration of sneak,invis,deodorize to reduce player torture. 1 = retail behavior. MUST BE INTEGER.
--CELEBRATIONS
EXPLORER_MOOGLE = 1;
EXPLORER_MOOGLE_LEVELCAP = 10;
--MISC
HOMEPOINT_HEAL = 0; --Set to 1 if you want Home Points to heal you like in single-player Final Fantasy games.
RIVERNE_PORTERS = 120; -- Time in seconds that Unstable Displacements in Cape Riverne stay open after trading a scale.
LANTERNS_STAY_LIT = 1200; -- time in seconds that lanterns in the Den of Rancor stay lit. | gpl-3.0 |
RyMarq/Zero-K | effects/janus.lua | 25 | 4668 | -- janusmuzzle
-- janusback
return {
["janusmuzzle"] = {
fire = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.6,
colormap = [[1 1 0 0.9 1 0.8 0.3 08 0 0 0 0.01]],
directional = false,
emitrot = 30,
emitrotspread = 15,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 20,
particlelifespread = 0,
particlesize = 0.5,
particlesizespread = 0.5,
particlespeed = 2,
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0.5,
sizemod = 1.0,
texture = [[orangesmoke2]],
},
},
fluffy = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.6,
colormap = [[1 1 1 1 1 1 1 1 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 15,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 60,
particlelifespread = 0,
particlesize = [[10 i-0.9]],
particlesizespread = 0,
particlespeed = [[2 i1.5]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
},
["janusback"] = {
fire = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.6,
colormap = [[1 1 0 0.9 1 0.8 0.3 08 0 0 0 0.01]],
directional = false,
emitrot = 30,
emitrotspread = 15,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 20,
particlelifespread = 0,
particlesize = 0.5,
particlesizespread = 0.5,
particlespeed = 2,
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0.5,
sizemod = 1.0,
texture = [[orangesmoke2]],
},
},
fluffy = {
air = true,
class = [[CSimpleParticleSystem]],
count = 10,
ground = true,
water = true,
properties = {
airdrag = 0.6,
colormap = [[1 1 1 1 1 1 1 1 0 0 0 0.01]],
directional = false,
emitrot = 0,
emitrotspread = 45,
emitvector = [[dir]],
gravity = [[0, 0, 0]],
numparticles = 1,
particlelife = 60,
particlelifespread = 0,
particlesize = [[10 i-0.5]],
particlesizespread = 0,
particlespeed = [[15 i-1.5]],
particlespeedspread = 2,
pos = [[0, 0, 0]],
sizegrowth = 0.2,
sizemod = 1.0,
texture = [[smokesmall]],
},
},
sparks = {
air = true,
class = [[CSimpleParticleSystem]],
count = 1,
ground = true,
water = true,
properties = {
airdrag = 0.97,
colormap = [[1 1 0 0.01 1 1 0 0.01 1 0.5 0 0.01 0 0 0 0.01]],
directional = true,
emitrot = 0,
emitrotspread = 45,
emitvector = [[dir]],
gravity = [[0, -0.2, 0]],
numparticles = 10,
particlelife = 7,
particlelifespread = 0,
particlesize = 12,
particlesizespread = 0,
particlespeed = 6,
particlespeedspread = 4,
pos = [[0, 1, 0]],
sizegrowth = 0,
sizemod = 1.0,
texture = [[plasma]],
},
},
},
}
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/quests/tutorial.lua | 3 | 1357 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
name = "Tutorial"
desc = function(self, who)
local desc = {}
desc[#desc+1] = "You must venture in the heart of the forest and kill the Lone Wolf, who randomly attacks villagers."
return table.concat(desc, "\n")
end
on_status_change = function(self, who, status, sub)
if self:isCompleted() then
who:setQuestStatus(self.id, engine.Quest.DONE)
world:gainAchievement({id="TUTORIAL_DONE",no_difficulties=true}, game.player)
end
end
on_grant = function(self)
local d = require("engine.dialogs.ShowText").new("Tutorial: Movement", "tutorial/move")
game:registerDialog(d)
end
| gpl-3.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua | 37 | 6267 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
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
$Id$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
members of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/undeads/undeads.lua | 3 | 2277 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- Undead talents
newTalentType{ type="undead/base", name = "base", generic = true, description = "Undead's innate abilities." }
newTalentType{ type="undead/ghoul", name = "ghoul", generic = true, description = "Ghoul's innate abilities." }
newTalentType{ type="undead/skeleton", name = "skeleton", generic = true, description = "Skeleton's innate abilities." }
newTalentType{ type="undead/vampire", name = "vampire", generic = true, description = "Vampire's innate abilities." }
newTalentType{ type="undead/lich", name = "lich", generic = true, description = "Liches innate abilities." }
-- Generic requires for undeads based on talent level
undeads_req1 = {
level = function(level) return 0 + (level-1) end,
}
undeads_req2 = {
level = function(level) return 4 + (level-1) end,
}
undeads_req3 = {
level = function(level) return 8 + (level-1) end,
}
undeads_req4 = {
level = function(level) return 12 + (level-1) end,
}
undeads_req5 = {
level = function(level) return 16 + (level-1) end,
}
load("/data/talents/undeads/ghoul.lua")
load("/data/talents/undeads/skeleton.lua")
-- Undeads's power: ID
newTalent{
short_name = "UNDEAD_ID",
name = "Knowledge of the Past",
type = {"undead/base", 1},
no_npc_use = true,
mode = "passive",
no_unlearn_last = true,
on_learn = function(self, t) self.auto_id = 100 end,
info = function(self)
return ([[You concentrate for a moment to recall some of your memories as a living being and look for knowledge to identify rare objects.]])
end,
}
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/rest/v2/get/datasource/datasource.lua | 1 | 4788 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/datasources/?.lua;" .. package.path
local json = require "dkjson"
local rest_utils = require "rest_utils"
local template = require "resty.template"
-- Import the classes library.
local classes = require "classes"
-- ##############################################
local datasource = classes.class()
-- ##############################################
-- This is the base REST prefix for all the available datasources
datasource.BASE_REST_PREFIX = "/lua/rest/v2/get/datasource/"
-- ##############################################
-- @brief Base class constructor
function datasource:init()
self._dataset_params = {} -- Holds per-dataset params
self._datamodel_instance = nil -- Instance of the datamodel holding data for each dataset
end
-- ##############################################
-- @brief Parses params
-- @param params_table A table with submitted params
-- @return True if parameters parsing is successful, false otherwise
function datasource:read_params(params_table)
if not params_table then
self.parsed_params = nil
return false
end
self.parsed_params = {}
for _, param in pairs(self.meta.params or {}) do
local parsed_param = params_table[param]
-- Assumes all params mandatory and not empty
-- May override this behavior in subclasses
if isEmptyString(parsed_param) then
-- Reset any possibly set param
self.parsed_params = nil
return false
end
self.parsed_params[param] = parsed_param
end
-- Ok, parsin has been successful
return true
end
-- ##############################################
-- @brief Parses params submitted along with the REST endpoint request. If parsing fails, a REST error is sent.
-- @param params_table A table with submitted params, either _POST or _GET
-- @return True if parameters parsing is successful, false otherwise
function datasource:_rest_read_params(params_table)
if not self:read_params(params_table) then
rest_utils.answer(rest_utils.consts.err.widgets_missing_datasource_params)
return false
end
return true
end
-- ##############################################
-- @brief Send datasource data via REST
function datasource:rest_send_response()
-- Make sure this is a direct REST request and not just a require() that needs this class
if not _SERVER -- Not executing a Lua script initiated from the web server (i.e., backend execution)
or not _SERVER["URI"] -- Cannot reliably determine if this is a REST request
or not _SERVER["URI"]:starts(datasource.BASE_REST_PREFIX) -- Web Lua script execution but not for this REST endpoint
then
-- Don't send any REST response
return
end
if not self:_rest_read_params(_POST) then
-- Params parsing has failed, error response already sent by the caller
return
end
self:fetch()
rest_utils.answer(
rest_utils.consts.success.ok,
self.datamodel_instance:get_data()
)
end
-- ##############################################
-- @brief Deserializes REST endpoint response into an internal datamodel
-- @param rest_response_data Response data as obtained from the REST call
function datasource:deserialize(rest_response_data)
if rest_response_data and rest_response_data.RESPONSE_CODE == 200 then
local data = json.decode(rest_response_data.CONTENT)
local when = os.time()
if data and data.rc == rest_utils.consts.success.ok.rc then
self.datamodel_instance = self.meta.datamodel:new(data.rsp.header)
for _, row in ipairs(data.rsp.rows) do
self.datamodel_instance:appendRow(when, data.rsp.header, row)
end
end
end
end
-- ##############################################
-- @brief Returns instance metadata, which depends on the current instance and parsed_params
function datasource:get_metadata()
local res = {}
-- Render a url with submitted parsed_params
if self.meta.url then
local url_func = template.compile(self.meta.url, nil, true)
local url_rendered = url_func({
params = self.parsed_params,
})
res["url"] = url_rendered
end
return res
end
-- ##############################################
-- @brief Transform data according to the specified transformation
-- @param data The data to be transformed
-- @param transformation The transformation to be applied
-- @return transformed data
function datasource:transform(transformation)
return self.datamodel_instance:transform(transformation)
end
-- ##############################################
return datasource
-- ##############################################
| gpl-3.0 |
NPLPackages/paracraft | script/kids/3DMapSystem_Misc.lua | 1 | 4820 | --[[
Title: Misc functions for 3D Map system
Author(s): WangTian
Date: 2007/8/31
Desc: 3D Map system misc functions
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystem_Misc.lua");
Map3DSystem.Misc.xxx();
------------------------------------------------------------
]]
commonlib.setfield("Map3DSystem.Misc", {})
Map3DSystem.Misc.IsExclusiveMessageBoxEnabled = false;
-------------------------------------------------
-- TODO: move to NPL.IDE: commonlib
-------------------------------------------------
-- NOTE: DON'T copy table with nested table reference. e.g. a = {}; a.ref = a;
function Map3DSystem.Misc.CopyTable( tableSource )
local copy_table = {};
local copy_k, copy_v;
for k, v in pairs(tableSource) do
if ( type( k ) == 'table' ) then
copy_k = Map3DSystem.CopyTable( k );
else
copy_k = k;
end
if ( type( v ) == 'table' ) then
copy_v = Map3DSystem.CopyTable( v );
else
copy_v = v;
end
copy_table[ copy_k ] = copy_v;
end
return copy_table;
end
-- NOTE: show a message box that wait for specific script action. e.g. web service call, file transfer
function Map3DSystem.Misc.ShowExclusiveMessageBox( message )
local _width, _height = 370,150;
local _this, _parent;
_this = ParaUI.CreateUIObject("container","Map3D_ExclusiveMessageBox", "_fi",0,0,0,0);
_this:AttachToRoot();
_this.background="";
_parent = _this;
_this = ParaUI.CreateUIObject("container","Map3D_ExclusiveMessageBox_BG", "_ct",-_width/2,-_height/2-50,_width,_height);
_parent:AddChild(_this);
_this.background="Texture/msg_box.png";
_this:SetTopLevel(true);
_parent = _this;
_this=ParaUI.CreateUIObject("text","Map3D_EscPopup_Text", "_lt",15,10,_width-30,20);
_this.text = L(message);
_this.autosize=true;
_this:DoAutoSize();
_parent:InvalidateRect();
_parent:AddChild(_this);
Map3DSystem.Misc.IsExclusiveMessageBoxEnabled = true;
end
function Map3DSystem.Misc.DestroyExclusiveMessageBox( )
if(Map3DSystem.Misc.IsExclusiveMessageBoxEnabled == true) then
ParaUI.Destroy("Map3D_ExclusiveMessageBox");
elseif(Map3DSystem.Misc.IsExclusiveMessageBoxEnabled == false) then
log("Exclusive message box already disabled.\r\n");
else
--TODO: got nil
end
end
function Map3DSystem.Misc.SaveTableToFile()
end
-- serialize to string
-- serialization will be well organized and easy to read the table structure
-- e.g. print(commonlib.serialize(o, 1))
function Map3DSystem.Misc.serialize2(o, lvl)
if type(o) == "number" then
return (tostring(o))
elseif type(o) == "nil" then
return ("nil")
elseif type(o) == "string" then
return (string.format("%q", o))
elseif type(o) == "boolean" then
if(o) then
return "true"
else
return "false"
end
elseif type(o) == "function" then
return (tostring(o))
elseif type(o) == "userdata" then
return ("userdata")
elseif type(o) == "table" then
local forwardStr = "";
for i = 0, lvl do
forwardStr = "\t"..forwardStr;
end
local str = "{\r\n"
local k,v
for k,v in pairs(o) do
nextlvl = lvl + 1;
str = str..forwardStr..("\t[")..Map3DSystem.Misc.serialize2(k, nextlvl).."] = "..Map3DSystem.Misc.serialize2(v, nextlvl)..",\r\n"
end
str = str..forwardStr.."}";
return str
else
log("-- cannot serialize a " .. type(o).."\r\n")
end
end
-- this function will record a table to a specific file.
-- different to SaveTableToFile is that this file will be well organized and easy to read the table structure
-- local t = {test=1};
-- commonlib.SaveTableToFile(t, "temp/t.txt");
function Map3DSystem.Misc.SaveTableToFile(o, filename)
local succeed;
local file = ParaIO.open(filename, "w");
if(file:IsValid()) then
file:WriteString(Map3DSystem.Misc.serialize2(o,0));
succeed = true;
end
file:close();
return succeed;
end
-- Exceptions:
--
-- local t1, t2 = {}, {};
-- t1.A = nil;
-- t2.B = nil;
-- Map3DSystem.Misc.IsEqualTable(t1, t2); <-- return true
--
function Map3DSystem.Misc.IsEqualTable(t1, t2)
if type(t1) == "number" then
return (tostring(t1) == tostring(t2))
elseif type(t1) == "nil" then
return (t1 == t2)
elseif type(t1) == "string" then
return (t1 == t2)
elseif type(t1) == "boolean" then
return (t1 == t2)
elseif type(t1) == "function" then
return (tostring(t1) == tostring(t2))
elseif type(t1) == "userdata" then
-- !!!CAUTION!!!: can't compare userdata
return true;
elseif type(t1) == "table" then
local len1 = table.getn(t1);
local len2 = table.getn(t2);
if(len1 ~= len2) then
return false;
end
local k,v
for k,v in pairs(t1) do
-- assume we don't have table for key entry
if(Map3DSystem.Misc.IsEqualTable(t1[k], t2[k]) == false) then
return false;
end
end
return true;
else
log("-- cannot serialize a " .. type(o).."\r\n")
return false;
end
end
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/admin/get_device_protocols.lua | 1 | 5515 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/pro/modules/?.lua;" .. package.path
require "lua_utils"
local presets_utils = require "presets_utils"
local json = require("dkjson")
local page_utils = require("page_utils")
sendHTTPContentTypeHeader('text/html')
if not isAdministrator() then
return
end
-- ################################################
-- Table parameters
local currentPage = _GET["currentPage"]
local perPage = _GET["perPage"]
local sortColumn = _GET["sortColumn"]
local sortOrder = _GET["sortOrder"]
local device_type = _GET["device_type"]
local policy_filter = _GET["policy_filter"]
local proto_filter = _GET["l7proto"]
local category = _GET["category"]
interface.select(ifname)
presets_utils.init()
-- ################################################
-- Sorting and Pagination
local sortPrefs = "nf_device_protocols"
if isEmptyString(sortColumn) or sortColumn == "column_" then
sortColumn = getDefaultTableSort(sortPrefs)
elseif sortColumn ~= "" then
tablePreferences("sort_"..sortPrefs, sortColumn)
end
if isEmptyString(_GET["sortColumn"]) then
sortOrder = getDefaultTableSortOrder(sortPrefs, true)
end
if _GET["sortColumn"] ~= "column_" and _GET["sortColumn"] ~= "" then
tablePreferences("sort_order_"..sortPrefs, sortOrder, true)
end
if currentPage == nil then
currentPage = 1
else
currentPage = tonumber(currentPage)
end
if perPage == nil then
perPage = 10
else
perPage = tonumber(perPage)
tablePreferences("rows_number_policies", perPage)
end
-- ################################################
local to_skip = (currentPage-1) * perPage
if sortOrder == "desc" then sOrder = rev_insensitive else sOrder = asc_insensitive end
local device_policies = presets_utils.getDevicePolicies(device_type)
local function matchesPolicyFilter(item_id)
if isEmptyString(policy_filter) then
return true
end
local policy = device_policies[tonumber(item_id)]
if policy == nil then
if policy_filter ~= presets_utils.DEFAULT_ACTION then -- != default
return false
end
elseif policy.clientActionId ~= nil and policy_filter ~= policy.clientActionId and
policy.serverActionId ~= nil and policy_filter ~= policy.serverActionId then
return false
end
return true
end
local function matchesProtoFilter(item_id)
if isEmptyString(proto_filter) then
return true
end
return proto_filter == item_id
end
local function matchesCategoryFilter(item_id)
if isEmptyString(category) then
return true
end
local cat = ntop.getnDPIProtoCategory(tonumber(item_id))
return category == cat.name
end
local items = {}
local sorter = {}
local num_items = 0
items = interface.getnDPIProtocols(nil, true)
for item_name, item_id in pairs(items) do
if not matchesProtoFilter(item_id) or not matchesPolicyFilter(item_id) or not matchesCategoryFilter(item_id) then
goto continue
end
local cat = ntop.getnDPIProtoCategory(tonumber(item_id))
items[item_name] = { name = item_name, id = item_id, conf = device_policies[tonumber(item_id)], catName = cat.name }
num_items = num_items + 1
if sortColumn == "column_" or sortColumn == "column_ndpi_application" then
sorter[item_name] = item_name
elseif sortColumn == "column_ndpi_category" then
sorter[item_name] = cat.name
end
::continue::
end
local res_formatted = {}
local cur_num = 0
for sorted_item, _ in pairsByValues(sorter, sOrder) do
cur_num = cur_num + 1
if cur_num <= to_skip then
goto continue
elseif cur_num > to_skip + perPage then
break
end
local record = {}
record["column_ndpi_application_id"] = tostring(items[sorted_item]["id"])
record["column_ndpi_application"] = tostring(items[sorted_item]["name"])
record["column_ndpi_category"] = items[sorted_item].catName
local cr = ''
local sr = ''
local conf = items[sorted_item]["conf"]
local field_id = items[sorted_item]["id"]
for _, action in ipairs(presets_utils.actions) do
local checked = ''
if ((conf == nil or conf.clientActionId == nil) and action.id == presets_utils.DEFAULT_ACTION) or
((conf ~= nil and conf.clientActionId ~= nil) and conf.clientActionId == action.id) then
checked = 'checked'
end
cr = cr..'<label class="radio-inline mx-2"><input type="radio" name="'..field_id..'_client_action" value="'..action.id..'" '..checked..'><span class="mx-1" style="font-size: 16px;">'..action.icon..'</span></label>'
checked = ''
if ((conf == nil or conf.serverActionId == nil) and action.id == presets_utils.DEFAULT_ACTION) or
((conf ~= nil and conf.serverActionId ~= nil) and conf.serverActionId == action.id) then
checked = 'checked'
end
sr = sr..'<label class="radio-inline mx-2"><input type="radio" name="'..field_id..'_server_action" value="'..action.id..'" '..checked..'><span class="mx-1" style="font-size: 16px;">'..action.icon..'</span></label>'
end
record["column_client_policy"] = cr
record["column_server_policy"] = sr
res_formatted[#res_formatted + 1] = record
::continue::
end
local result = {}
result["perPage"] = perPage
result["currentPage"] = currentPage
result["totalRows"] = num_items
result["data"] = res_formatted
result["sort"] = {{sortColumn, sortOrder}}
print(json.encode(result, nil))
| gpl-3.0 |
crazyboy11/spol | plugins/info.lua | 1 | 8124 | do
local ali_ghoghnoos = 172178919 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#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 = 'Fullname : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'Username: '..Username..'\n'
..'User ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(ali_ghoghnoos) then
text = text..'Rank : Executive Admin \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..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..'Total messages : '..user_info_msgs..'\n\n'
text = text..''
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, extra.user..'this Username is invalid.', 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 = 'Fullname : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'Username: '..Username..'\n'
..'User ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == tonumber(ali_ghoghnoos) then
text = text..'Rank : Executive Admin \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..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..'Total messages : '..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 = 'Fullname : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'Username: '..Username..'\n'
..'User ID : '..result.from.id..'\n\n'
local hash = 'rank:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == tonumber(ali_ghoghnoos) then
text = text..'Rank : Executive Admin \n\n'
elseif is_admin2(result.from.id) then
text = text..'Rank : Admin \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'Rank : Owner \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'Rank Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..''
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.id..':'..msg.to.id
redis:incr(hash)
if not is_owner(msg) then
return "only for the owners"
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 = 'Fullname : '..(msg.from.first_name or 'ندارد')..'\n'
local text = text..'Lastname : '..(msg.from.last_name or 'ندارد')..'\n'
local text = text..'Username : '..Username..'\n'
local text = text..'User ID : '..msg.from.id..'\n\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == tonumber(ali_ghoghnoos) then
text = text..'Rank : Executive Admin \n\n'
elseif is_sudo(msg) then
text = text..'Rank : Admin \n\n'
elseif is_owner(msg) then
text = text..'Rank : Owner \n\n'
elseif is_momod(msg) then
text = text..'Rank : Moderator \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..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..'Total messages : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'Groupname : '..msg.to.title..'\n'
text = text..'Group ID : '..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 = {
user = {
'!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>',
},
admin = {
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.' },
},
patterns = {
"^[/!]([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
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/rooms/nine_chambers.lua | 3 | 1033 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return {
[[#!!!#!!!#!!!#]],
[[!...#...#...!]],
[[!...........!]],
[[!...#...#...!]],
[[######.######]],
[[!...#...#...!]],
[[!...........!]],
[[!...#...#...!]],
[[######.######]],
[[!...#...#...!]],
[[!...........!]],
[[!...#...#...!]],
[[#!!!#!!!#!!!#]],
} | gpl-3.0 |
RyMarq/Zero-K | units/planeheavyfighter.lua | 1 | 4100 | return { planeheavyfighter = {
unitname = [[planeheavyfighter]],
name = [[Raptor]],
description = [[Air Superiority Fighter]],
brakerate = 0.4,
buildCostMetal = 300,
buildPic = [[planeheavyfighter.png]],
canFly = true,
canGuard = true,
canMove = true,
canPatrol = true,
canSubmerge = false,
category = [[FIXEDWING]],
collide = false,
collisionVolumeOffsets = [[0 0 5]],
collisionVolumeScales = [[30 12 50]],
collisionVolumeType = [[box]],
selectionVolumeOffsets = [[0 0 10]],
selectionVolumeScales = [[60 60 80]],
selectionVolumeType = [[cylZ]],
corpse = [[DEAD]],
crashDrag = 0.01,
cruiseAlt = 220,
customParams = {
midposoffset = [[0 3 0]],
aimposoffset = [[0 3 0]],
modelradius = [[10]],
refuelturnradius = [[120]],
combat_slowdown = 0.5,
selection_scale = 1.4,
},
explodeAs = [[GUNSHIPEX]],
fireState = 2,
floater = true,
footprintX = 2,
footprintZ = 2,
frontToSpeed = 0.1,
iconType = [[stealthfighter]],
idleAutoHeal = 5,
idleTime = 1800,
maxAcc = 0.5,
maxDamage = 1100,
maxRudder = 0.006,
maxVelocity = 7.6,
minCloakDistance = 75,
mygravity = 1,
noChaseCategory = [[TERRAFORM LAND SINK TURRET SHIP SWIM FLOAT SUB HOVER]],
objectName = [[fighter2.s3o]],
script = [[planeheavyfighter.lua]],
selfDestructAs = [[GUNSHIPEX]],
sightDistance = 750,
speedToFront = 0.5,
turnRadius = 80,
weapons = {
{
def = [[LASER]],
badTargetCategory = [[GUNSHIP]],
mainDir = [[0 0 1]],
maxAngleDif = 90,
onlyTargetCategory = [[FIXEDWING GUNSHIP]],
},
},
weaponDefs = {
LASER = {
name = [[Anti-Air Laser Battery]],
areaOfEffect = 12,
avoidFriendly = false,
beamDecay = 0.736,
beamTime = 1/30,
beamttl = 15,
canattackground = false,
canAttackGround = 0,
collideFriendly = false,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
cylinderTargeting = 1,
customParams = {
isaa = [[1]],
},
damage = {
default = 0.96,
planes = 9.6,
subs = 0.96,
},
explosionGenerator = [[custom:flash_teal7]],
fireStarter = 100,
impactOnly = true,
impulseFactor = 0,
interceptedByShieldType = 1,
laserFlareSize = 2.9,
minIntensity = 1,
range = 800,
reloadtime = 0.1,
rgbColor = [[0 1 1]],
soundStart = [[weapon/laser/rapid_laser]],
soundStartVolume = 1.9,
thickness = 1.95,
tolerance = 8192,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2200,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
collisionVolumeOffsets = [[0 0 5]],
collisionVolumeScales = [[35 15 45]],
collisionVolumeType = [[box]],
object = [[fighter2_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 2,
footprintZ = 2,
object = [[debris2x2b.s3o]],
},
},
} }
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/engines/default/engine/interface/GameTargeting.lua | 2 | 16054 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
require "engine.KeyBind"
local Dialog = require "engine.ui.Dialog"
local Map = require "engine.Map"
local Target = require "engine.Target"
--- Handles default targeting interface & display
module(..., package.seeall, class.make)
--- Initializes targeting
function _M:init()
self.target = Target.new(Map, self.player)
self.target.target.entity = self.player
self.old_tmx, self.old_tmy = 0, 0
self.target_style = "lock"
-- Allow scrolling when targetting
self.target.on_set_target = function(self, how)
if self.key ~= self.targetmode_key then return end
local dx, dy = game.level.map:moveViewSurround(self.target.x, self.target.y, 1, 1, true)
if how == "mouse" and (dx ~= 0 or dy ~= 0) then
local cx, cy = core.mouse.get()
core.mouse.set(cx - game.level.map.tile_w * dx, cy - game.level.map.tile_h * dy)
end
end
end
--- Maintain the current target each tick
-- Make sure the target still exists
function _M:targetOnTick()
if self.target.target.entity and not self.level:hasEntity(self.target.target.entity) then self.target.target.entity = false end
end
--- Display the tooltip, if any
function _M:targetDisplayTooltip(dx, dy, force, nb_keyframes)
-- Tooltip is displayed over all else
if self.level and self.level.map and self.level.map.finished then
local tmx, tmy
-- Display a tooltip if available
if self.tooltip_x then
if type(self.tooltip_x) == "table" then
self.tooltip:toScreen(self.tooltip.last_display_x, self.tooltip.last_display_y, nb_keyframes)
else
tmx, tmy = self.level.map:getMouseTile(self.tooltip_x , self.tooltip_y)
self.tooltip:displayAtMap(tmx, tmy, dx, dy, nil, force, nb_keyframes)
end
end
-- Move target around
if self.old_tmx ~= tmx or self.old_tmy ~= tmy then
self.target.target.x, self.target.target.y = tmx, tmy
end
self.old_tmx, self.old_tmy = tmx, tmy
end
end
--- Forces the tooltip to pop with the given text
function _M:tooltipDisplayAtMap(x, y, text, extra, force, nb_keyframes)
self.tooltip:displayAtMap(nil, nil, x, y, text, force, nb_keyframes)
if extra and type(extra) == "table" then
if extra.up then self.tooltip.last_display_y = self.tooltip.last_display_y - self.tooltip.h end
end
self.tooltip_x = {}
end
--- Enter/leave targeting mode
-- This is the "meat" of this interface, do not expect to understand it easily, it mixes some nasty stuff
-- This require the Game to have both a "key" field (this is the default) and a "normal_key" field<br/>
-- It will switch over to a special keyhandler and then restore the "normal_key" one
function _M:targetMode(v, msg, co, typ)
local old = self.target_mode
self.target_mode = v
if not v then
Map:setViewerFaction((self.always_target == true or self.always_target == "old") and self.player.faction or nil)
if msg then self.log(type(msg) == "string" and msg or "Tactical display disabled. Press shift+'t' to enable.") end
self.level.map.changed = true
self.targetmode_trigger_hotkey = nil
self.target:setActive(false)
if tostring(old) == "exclusive" then
local x, y, e = self.target.target.x, self.target.target.y, self.target.target.entity
local fct = function(notok)
if notok then
self.target.target.entity = nil
self.target.target.x = nil
self.target.target.y = nil
x, y, e = nil, nil, nil
end
self.key = self.normal_key
self.key:setCurrent()
if self.target_co then
local co = self.target_co
self.target_co = nil
self.target.target.x, self.target.target.y, self.target.target.entity = x, y, e
local ok, err = coroutine.resume(co, self.target.target.x, self.target.target.y, self.target.target.entity)
if not ok and err then print(debug.traceback(co)) error(err) end
end
end
if self.target_warning and self.target.target.x == self.player.x and self.target.target.y == self.player.y then
Dialog:yesnoPopup(type(self.target_warning) == "string" and self.target_warning or "Target yourself?", "Are you sure you want to target yourself?", fct, "No", "Yes", nil, true)
else
fct(false)
end
end
else
Map:setViewerFaction(self.player.faction)
if msg then self.log(type(msg) == "string" and msg or "Tactical display enabled. Press shift+'t' to disable.") end
self.level.map.changed = true
self.target:setActive(true, typ)
self.target_style = "lock"
self.target_warning = true
if type(typ) == "table" and typ.talent then
self.target_warning = typ.talent.name
elseif type(typ) == "table" and typ.__name then
self.target_warning = typ.__name
end
-- Exclusive mode means we disable the current key handler and use a specific one
-- that only allows targetting and resumes talent coroutine when done
if tostring(v) == "exclusive" then
self.target_co = co
self.key = self.targetmode_key
self.key:setCurrent()
local do_scan = true
if self.target_no_star_scan
or (
self.target.target.entity and
self.level.map.seens(self.target.target.entity.x, self.target.target.entity.y) and
self.player ~= self.target.target.entity
) then
if type(typ) == "table" and typ.first_target ~= "friend" and self.player:reactionToward(self.target.target.entity) >= 0 then
else
do_scan = false
end
end
if do_scan then
local filter = nil
if not (type(typ) == "table" and typ.no_first_target_filter) then
if type(typ) == "table" and typ.first_target and typ.first_target == "friend" then
filter = function(a) return self.player:reactionToward(a) >= 0 end
else
filter = function(a) return self.player:reactionToward(a) < 0 end
end
end
self.target:scan(5, nil, self.player.x, self.player.y, filter, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on)
end
if self.target.target.entity and self.target.target.entity.x and self.target.target.entity.y then self.target.target.x, self.target.target.y = self.target.target.entity.x, self.target.target.entity.y end
end
if self.target.target.x then
self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y)
end
end
end
function _M:targetTriggerHotkey(i)
self.targetmode_trigger_hotkey = i
end
--- This setups the default keybindings for targeting
function _M:targetSetupKey()
local accept = function() self:targetMode(false, false) self.tooltip_x, self.tooltip_y = nil, nil end
self.targetmode_key = engine.KeyBind.new()
self.targetmode_key:addCommands{ _SPACE=accept, }
if engine.interface and engine.interface.PlayerHotkeys then
engine.interface.PlayerHotkeys:bindAllHotkeys(self.targetmode_key, function(i)
if self.targetmode_trigger_hotkey == i then accept() end
end)
end
self.targetmode_key:addBinds
{
TACTICAL_DISPLAY = accept,
ACCEPT = accept,
EXIT = function()
self.target.target.entity = nil
self.target.target.x = nil
self.target.target.y = nil
self:targetMode(false, false)
self.tooltip_x, self.tooltip_y = nil, nil
end,
-- Targeting movement
RUN_LEFT = function() self.target:freemove(4) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_RIGHT = function() self.target:freemove(6) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_UP = function() self.target:freemove(8) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_DOWN = function() self.target:freemove(2) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_LEFT_DOWN = function() self.target:freemove(1) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_RIGHT_DOWN = function() self.target:freemove(3) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_LEFT_UP = function() self.target:freemove(7) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
RUN_RIGHT_UP = function() self.target:freemove(9) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_LEFT = function() if self.target_style == "lock" then self.target:scan(4, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(4, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(4) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_RIGHT = function() if self.target_style == "lock" then self.target:scan(6, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(6, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(6) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_UP = function() if self.target_style == "lock" then self.target:scan(8, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(8, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(8) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_DOWN = function() if self.target_style == "lock" then self.target:scan(2, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(2, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(2) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_LEFT_DOWN = function() if self.target_style == "lock" then self.target:scan(1, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(1, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(1) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_RIGHT_DOWN = function() if self.target_style == "lock" then self.target:scan(3, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(3, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(3) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_LEFT_UP = function() if self.target_style == "lock" then self.target:scan(7, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(7, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(7) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_RIGHT_UP = function() if self.target_style == "lock" then self.target:scan(9, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(9, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(9) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end,
MOVE_STAY = function()
if self.target_style == "immediate" then
self.target:setDirFrom(5, self.target.target.entity or self.player)
self.targetmode_key:triggerVirtual("ACCEPT")
return
end
self.target:setSpot(self.target.source_actor.x, self.target.source_actor.y, "freemove")
self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y)
end,
SCREENSHOT = function() self.normal_key:triggerVirtual("SCREENSHOT") end,
}
end
--- Handle mouse event for targeting
-- @return true if the event was handled
function _M:targetMouse(button, mx, my, xrel, yrel, event)
if not self.level then return end
-- Move tooltip
self.tooltip_x, self.tooltip_y = mx, my
local tmx, tmy = self.level.map:getMouseTile(mx, my)
self.target:setSpot(tmx, tmy, "mouse")
if self.key == self.targetmode_key then
-- Target with mouse
if button == "none" and xrel and yrel and event == "motion" then
self.target:setSpotInMotion(tmx, tmy, "mouse")
-- Accept target
elseif button == "left" and not xrel and not yrel and event == "button" then
self:targetMode(false, false)
self.tooltip_x, self.tooltip_y = nil, nil
-- Cancel target
elseif not xrel and not yrel and event == "button" then
self.target.target.entity = nil
self.target.target.x = nil
self.target.target.y = nil
self:targetMode(false, false)
self.tooltip_x, self.tooltip_y = nil, nil
end
return true
end
end
--- Player requests a target
-- This method should be called by your Player:getTarget() method, it will handle everything
-- @param typ the targeting parameters
function _M:targetGetForPlayer(typ)
if self.target.forced then return unpack(self.target.forced) end
if coroutine.running() and typ then
local msg
self.target_no_star_scan = nil
if type(typ) == "string" then msg, typ = typ, nil
elseif type(typ) == "table" then
if typ.default_target then
self.target.target.entity = typ.default_target
self.target_no_star_scan = true
end
msg = typ.msg
end
self:targetMode("exclusive", msg, coroutine.running(), typ)
if typ.immediate_keys then self.target_style = "immediate" end
if typ.nolock then self.target_style = "free" end
if typ.nowarning then self.target_warning = false end
return coroutine.yield()
end
return self.target.target.x, self.target.target.y, self.target.target.entity
end
--- Player wants to set its target
-- This method should be called by your Player:setTarget() method, it will handle everything
function _M:targetSetForPlayer(target)
self.target.target.entity = target
self.target.target.x = (type(target) == "table" and target.x) or nil
self.target.target.y = (type(target) == "table" and target.y) or nil
end
| gpl-3.0 |
RyMarq/Zero-K | LuaUI/Fonts/Skrawl_40.lua | 26 | 34023 | -- $Id: Skrawl_40.lua 3171 2008-11-06 09:06:29Z det $
local fontSpecs = {
srcFile = [[Skrawl.ttf]],
family = [[Skrawl]],
style = [[Regular]],
yStep = 45,
height = 40,
xTexSize = 512,
yTexSize = 1024,
outlineRadius = 1,
outlineWeight = 100,
}
local glyphs = {}
glyphs[32] = { --' '--
num = 32,
adv = 14,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 1, txp = 4, typ = 4,
}
glyphs[33] = { --'!'--
num = 33,
adv = 13,
oxn = -1, oyn = -1, oxp = 10, oyp = 41,
txn = 41, tyn = 1, txp = 52, typ = 43,
}
glyphs[34] = { --'"'--
num = 34,
adv = 12,
oxn = 0, oyn = 24, oxp = 11, oyp = 40,
txn = 81, tyn = 1, txp = 92, typ = 17,
}
glyphs[35] = { --'#'--
num = 35,
adv = 26,
oxn = -1, oyn = -1, oxp = 23, oyp = 35,
txn = 121, tyn = 1, txp = 145, typ = 37,
}
glyphs[36] = { --'$'--
num = 36,
adv = 21,
oxn = -1, oyn = -1, oxp = 21, oyp = 39,
txn = 161, tyn = 1, txp = 183, typ = 41,
}
glyphs[37] = { --'%'--
num = 37,
adv = 31,
oxn = -1, oyn = -1, oxp = 34, oyp = 34,
txn = 201, tyn = 1, txp = 236, typ = 36,
}
glyphs[38] = { --'&'--
num = 38,
adv = 33,
oxn = -1, oyn = -1, oxp = 25, oyp = 38,
txn = 241, tyn = 1, txp = 267, typ = 40,
}
glyphs[39] = { --'''--
num = 39,
adv = 6,
oxn = -1, oyn = 26, oxp = 7, oyp = 37,
txn = 281, tyn = 1, txp = 289, typ = 12,
}
glyphs[40] = { --'('--
num = 40,
adv = 15,
oxn = -1, oyn = -5, oxp = 12, oyp = 35,
txn = 321, tyn = 1, txp = 334, typ = 41,
}
glyphs[41] = { --')'--
num = 41,
adv = 15,
oxn = 0, oyn = -3, oxp = 13, oyp = 36,
txn = 361, tyn = 1, txp = 374, typ = 40,
}
glyphs[42] = { --'*'--
num = 42,
adv = 20,
oxn = 1, oyn = 18, oxp = 20, oyp = 37,
txn = 401, tyn = 1, txp = 420, typ = 20,
}
glyphs[43] = { --'+'--
num = 43,
adv = 20,
oxn = 1, oyn = 4, oxp = 19, oyp = 23,
txn = 441, tyn = 1, txp = 459, typ = 20,
}
glyphs[44] = { --','--
num = 44,
adv = 11,
oxn = 0, oyn = -6, oxp = 10, oyp = 9,
txn = 1, tyn = 45, txp = 11, typ = 60,
}
glyphs[45] = { --'-'--
num = 45,
adv = 13,
oxn = -1, oyn = 9, oxp = 13, oyp = 16,
txn = 41, tyn = 45, txp = 55, typ = 52,
}
glyphs[46] = { --'.'--
num = 46,
adv = 9,
oxn = -1, oyn = -2, oxp = 9, oyp = 8,
txn = 81, tyn = 45, txp = 91, typ = 55,
}
glyphs[47] = { --'/'--
num = 47,
adv = 11,
oxn = -2, oyn = -2, oxp = 15, oyp = 34,
txn = 121, tyn = 45, txp = 138, typ = 81,
}
glyphs[48] = { --'0'--
num = 48,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 31,
txn = 161, tyn = 45, txp = 182, typ = 77,
}
glyphs[49] = { --'1'--
num = 49,
adv = 8,
oxn = -1, oyn = -1, oxp = 8, oyp = 35,
txn = 201, tyn = 45, txp = 210, typ = 81,
}
glyphs[50] = { --'2'--
num = 50,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 32,
txn = 241, tyn = 45, txp = 262, typ = 78,
}
glyphs[51] = { --'3'--
num = 51,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 32,
txn = 281, tyn = 45, txp = 302, typ = 78,
}
glyphs[52] = { --'4'--
num = 52,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 32,
txn = 321, tyn = 45, txp = 343, typ = 78,
}
glyphs[53] = { --'5'--
num = 53,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 31,
txn = 361, tyn = 45, txp = 383, typ = 77,
}
glyphs[54] = { --'6'--
num = 54,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 35,
txn = 401, tyn = 45, txp = 423, typ = 81,
}
glyphs[55] = { --'7'--
num = 55,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 32,
txn = 441, tyn = 45, txp = 462, typ = 78,
}
glyphs[56] = { --'8'--
num = 56,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 33,
txn = 1, tyn = 89, txp = 22, typ = 123,
}
glyphs[57] = { --'9'--
num = 57,
adv = 20,
oxn = -1, oyn = -1, oxp = 19, oyp = 31,
txn = 41, tyn = 89, txp = 61, typ = 121,
}
glyphs[58] = { --':'--
num = 58,
adv = 11,
oxn = -1, oyn = -1, oxp = 10, oyp = 27,
txn = 81, tyn = 89, txp = 92, typ = 117,
}
glyphs[59] = { --';'--
num = 59,
adv = 11,
oxn = 0, oyn = -8, oxp = 12, oyp = 26,
txn = 121, tyn = 89, txp = 133, typ = 123,
}
glyphs[60] = { --'<'--
num = 60,
adv = 20,
oxn = -1, oyn = 4, oxp = 21, oyp = 27,
txn = 161, tyn = 89, txp = 183, typ = 112,
}
glyphs[61] = { --'='--
num = 61,
adv = 20,
oxn = 0, oyn = 6, oxp = 20, oyp = 18,
txn = 201, tyn = 89, txp = 221, typ = 101,
}
glyphs[62] = { --'>'--
num = 62,
adv = 20,
oxn = -1, oyn = 4, oxp = 20, oyp = 27,
txn = 241, tyn = 89, txp = 262, typ = 112,
}
glyphs[63] = { --'?'--
num = 63,
adv = 15,
oxn = -1, oyn = -2, oxp = 17, oyp = 38,
txn = 281, tyn = 89, txp = 299, typ = 129,
}
glyphs[64] = { --'@'--
num = 64,
adv = 39,
oxn = 0, oyn = -1, oxp = 38, oyp = 34,
txn = 321, tyn = 89, txp = 359, typ = 124,
}
glyphs[65] = { --'A'--
num = 65,
adv = 22,
oxn = -5, oyn = -1, oxp = 22, oyp = 38,
txn = 361, tyn = 89, txp = 388, typ = 128,
}
glyphs[66] = { --'B'--
num = 66,
adv = 25,
oxn = -2, oyn = -1, oxp = 27, oyp = 37,
txn = 401, tyn = 89, txp = 430, typ = 127,
}
glyphs[67] = { --'C'--
num = 67,
adv = 25,
oxn = 0, oyn = -1, oxp = 26, oyp = 35,
txn = 441, tyn = 89, txp = 467, typ = 125,
}
glyphs[68] = { --'D'--
num = 68,
adv = 23,
oxn = -1, oyn = -1, oxp = 24, oyp = 36,
txn = 1, tyn = 133, txp = 26, typ = 170,
}
glyphs[69] = { --'E'--
num = 69,
adv = 26,
oxn = -1, oyn = -2, oxp = 26, oyp = 37,
txn = 41, tyn = 133, txp = 68, typ = 172,
}
glyphs[70] = { --'F'--
num = 70,
adv = 24,
oxn = -1, oyn = -1, oxp = 23, oyp = 38,
txn = 81, tyn = 133, txp = 105, typ = 172,
}
glyphs[71] = { --'G'--
num = 71,
adv = 26,
oxn = 0, oyn = -1, oxp = 25, oyp = 38,
txn = 121, tyn = 133, txp = 146, typ = 172,
}
glyphs[72] = { --'H'--
num = 72,
adv = 24,
oxn = -4, oyn = -1, oxp = 23, oyp = 38,
txn = 161, tyn = 133, txp = 188, typ = 172,
}
glyphs[73] = { --'I'--
num = 73,
adv = 23,
oxn = -1, oyn = -1, oxp = 24, oyp = 38,
txn = 201, tyn = 133, txp = 226, typ = 172,
}
glyphs[74] = { --'J'--
num = 74,
adv = 22,
oxn = -1, oyn = -1, oxp = 22, oyp = 38,
txn = 241, tyn = 133, txp = 264, typ = 172,
}
glyphs[75] = { --'K'--
num = 75,
adv = 21,
oxn = -1, oyn = -1, oxp = 22, oyp = 38,
txn = 281, tyn = 133, txp = 304, typ = 172,
}
glyphs[76] = { --'L'--
num = 76,
adv = 25,
oxn = -1, oyn = -1, oxp = 25, oyp = 38,
txn = 321, tyn = 133, txp = 347, typ = 172,
}
glyphs[77] = { --'M'--
num = 77,
adv = 22,
oxn = -1, oyn = -1, oxp = 22, oyp = 38,
txn = 361, tyn = 133, txp = 384, typ = 172,
}
glyphs[78] = { --'N'--
num = 78,
adv = 22,
oxn = 0, oyn = -1, oxp = 23, oyp = 38,
txn = 401, tyn = 133, txp = 424, typ = 172,
}
glyphs[79] = { --'O'--
num = 79,
adv = 24,
oxn = -1, oyn = -1, oxp = 23, oyp = 35,
txn = 441, tyn = 133, txp = 465, typ = 169,
}
glyphs[80] = { --'P'--
num = 80,
adv = 24,
oxn = -1, oyn = -1, oxp = 24, oyp = 38,
txn = 1, tyn = 177, txp = 26, typ = 216,
}
glyphs[81] = { --'Q'--
num = 81,
adv = 25,
oxn = -1, oyn = -1, oxp = 25, oyp = 38,
txn = 41, tyn = 177, txp = 67, typ = 216,
}
glyphs[82] = { --'R'--
num = 82,
adv = 23,
oxn = -1, oyn = -1, oxp = 23, oyp = 38,
txn = 81, tyn = 177, txp = 105, typ = 216,
}
glyphs[83] = { --'S'--
num = 83,
adv = 23,
oxn = -1, oyn = -1, oxp = 25, oyp = 39,
txn = 121, tyn = 177, txp = 147, typ = 217,
}
glyphs[84] = { --'T'--
num = 84,
adv = 22,
oxn = -1, oyn = -1, oxp = 23, oyp = 38,
txn = 161, tyn = 177, txp = 185, typ = 216,
}
glyphs[85] = { --'U'--
num = 85,
adv = 22,
oxn = -1, oyn = -1, oxp = 22, oyp = 39,
txn = 201, tyn = 177, txp = 224, typ = 217,
}
glyphs[86] = { --'V'--
num = 86,
adv = 22,
oxn = -1, oyn = -1, oxp = 22, oyp = 37,
txn = 241, tyn = 177, txp = 264, typ = 215,
}
glyphs[87] = { --'W'--
num = 87,
adv = 24,
oxn = -1, oyn = -1, oxp = 24, oyp = 37,
txn = 281, tyn = 177, txp = 306, typ = 215,
}
glyphs[88] = { --'X'--
num = 88,
adv = 23,
oxn = -1, oyn = -1, oxp = 24, oyp = 39,
txn = 321, tyn = 177, txp = 346, typ = 217,
}
glyphs[89] = { --'Y'--
num = 89,
adv = 22,
oxn = -1, oyn = -1, oxp = 23, oyp = 38,
txn = 361, tyn = 177, txp = 385, typ = 216,
}
glyphs[90] = { --'Z'--
num = 90,
adv = 21,
oxn = -1, oyn = -1, oxp = 24, oyp = 38,
txn = 401, tyn = 177, txp = 426, typ = 216,
}
glyphs[91] = { --'['--
num = 91,
adv = 15,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 441, tyn = 177, txp = 444, typ = 180,
}
glyphs[92] = { --'\'--
num = 92,
adv = 11,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 221, txp = 4, typ = 224,
}
glyphs[93] = { --']'--
num = 93,
adv = 15,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 221, txp = 44, typ = 224,
}
glyphs[94] = { --'^'--
num = 94,
adv = 20,
oxn = -1, oyn = 16, oxp = 20, oyp = 36,
txn = 81, tyn = 221, txp = 102, typ = 241,
}
glyphs[95] = { --'_'--
num = 95,
adv = 20,
oxn = -2, oyn = -2, oxp = 24, oyp = 3,
txn = 121, tyn = 221, txp = 147, typ = 226,
}
glyphs[96] = { --'`'--
num = 96,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 161, tyn = 221, txp = 181, typ = 252,
}
glyphs[97] = { --'a'--
num = 97,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 26,
txn = 201, tyn = 221, txp = 222, typ = 248,
}
glyphs[98] = { --'b'--
num = 98,
adv = 19,
oxn = -2, oyn = -1, oxp = 20, oyp = 34,
txn = 241, tyn = 221, txp = 263, typ = 256,
}
glyphs[99] = { --'c'--
num = 99,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 27,
txn = 281, tyn = 221, txp = 303, typ = 249,
}
glyphs[100] = { --'d'--
num = 100,
adv = 20,
oxn = -1, oyn = 0, oxp = 21, oyp = 36,
txn = 321, tyn = 221, txp = 343, typ = 257,
}
glyphs[101] = { --'e'--
num = 101,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 27,
txn = 361, tyn = 221, txp = 383, typ = 249,
}
glyphs[102] = { --'f'--
num = 102,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 36,
txn = 401, tyn = 221, txp = 423, typ = 258,
}
glyphs[103] = { --'g'--
num = 103,
adv = 20,
oxn = -1, oyn = -5, oxp = 21, oyp = 27,
txn = 441, tyn = 221, txp = 463, typ = 253,
}
glyphs[104] = { --'h'--
num = 104,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 36,
txn = 1, tyn = 265, txp = 22, typ = 302,
}
glyphs[105] = { --'i'--
num = 105,
adv = 11,
oxn = -1, oyn = -1, oxp = 11, oyp = 32,
txn = 41, tyn = 265, txp = 53, typ = 298,
}
glyphs[106] = { --'j'--
num = 106,
adv = 13,
oxn = -1, oyn = -5, oxp = 14, oyp = 30,
txn = 81, tyn = 265, txp = 96, typ = 300,
}
glyphs[107] = { --'k'--
num = 107,
adv = 18,
oxn = -1, oyn = -1, oxp = 18, oyp = 31,
txn = 121, tyn = 265, txp = 140, typ = 297,
}
glyphs[108] = { --'l'--
num = 108,
adv = 10,
oxn = -1, oyn = -1, oxp = 8, oyp = 37,
txn = 161, tyn = 265, txp = 170, typ = 303,
}
glyphs[109] = { --'m'--
num = 109,
adv = 21,
oxn = -1, oyn = -1, oxp = 21, oyp = 27,
txn = 201, tyn = 265, txp = 223, typ = 293,
}
glyphs[110] = { --'n'--
num = 110,
adv = 22,
oxn = -1, oyn = -1, oxp = 22, oyp = 26,
txn = 241, tyn = 265, txp = 264, typ = 292,
}
glyphs[111] = { --'o'--
num = 111,
adv = 22,
oxn = -1, oyn = -1, oxp = 22, oyp = 26,
txn = 281, tyn = 265, txp = 304, typ = 292,
}
glyphs[112] = { --'p'--
num = 112,
adv = 20,
oxn = -1, oyn = -7, oxp = 21, oyp = 23,
txn = 321, tyn = 265, txp = 343, typ = 295,
}
glyphs[113] = { --'q'--
num = 113,
adv = 20,
oxn = -1, oyn = -5, oxp = 21, oyp = 23,
txn = 361, tyn = 265, txp = 383, typ = 293,
}
glyphs[114] = { --'r'--
num = 114,
adv = 16,
oxn = -1, oyn = -1, oxp = 16, oyp = 26,
txn = 401, tyn = 265, txp = 418, typ = 292,
}
glyphs[115] = { --'s'--
num = 115,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 27,
txn = 441, tyn = 265, txp = 462, typ = 293,
}
glyphs[116] = { --'t'--
num = 116,
adv = 19,
oxn = -1, oyn = -1, oxp = 20, oyp = 33,
txn = 1, tyn = 309, txp = 22, typ = 343,
}
glyphs[117] = { --'u'--
num = 117,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 26,
txn = 41, tyn = 309, txp = 62, typ = 336,
}
glyphs[118] = { --'v'--
num = 118,
adv = 19,
oxn = -1, oyn = -1, oxp = 20, oyp = 26,
txn = 81, tyn = 309, txp = 102, typ = 336,
}
glyphs[119] = { --'w'--
num = 119,
adv = 20,
oxn = -1, oyn = -1, oxp = 21, oyp = 27,
txn = 121, tyn = 309, txp = 143, typ = 337,
}
glyphs[120] = { --'x'--
num = 120,
adv = 20,
oxn = -1, oyn = -1, oxp = 20, oyp = 27,
txn = 161, tyn = 309, txp = 182, typ = 337,
}
glyphs[121] = { --'y'--
num = 121,
adv = 20,
oxn = -1, oyn = -7, oxp = 20, oyp = 26,
txn = 201, tyn = 309, txp = 222, typ = 342,
}
glyphs[122] = { --'z'--
num = 122,
adv = 21,
oxn = -1, oyn = -1, oxp = 21, oyp = 22,
txn = 241, tyn = 309, txp = 263, typ = 332,
}
glyphs[123] = { --'{'--
num = 123,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 309, txp = 284, typ = 312,
}
glyphs[124] = { --'|'--
num = 124,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 309, txp = 324, typ = 312,
}
glyphs[125] = { --'}'--
num = 125,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 309, txp = 364, typ = 312,
}
glyphs[126] = { --'~'--
num = 126,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 309, txp = 404, typ = 312,
}
glyphs[127] = { --''--
num = 127,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 441, tyn = 309, txp = 461, typ = 340,
}
glyphs[128] = { --''--
num = 128,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 1, tyn = 353, txp = 21, typ = 384,
}
glyphs[129] = { --''--
num = 129,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 41, tyn = 353, txp = 61, typ = 384,
}
glyphs[130] = { --''--
num = 130,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 81, tyn = 353, txp = 101, typ = 384,
}
glyphs[131] = { --''--
num = 131,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 121, tyn = 353, txp = 141, typ = 384,
}
glyphs[132] = { --''--
num = 132,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 161, tyn = 353, txp = 181, typ = 384,
}
glyphs[133] = { --'
'--
num = 133,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 201, tyn = 353, txp = 221, typ = 384,
}
glyphs[134] = { --''--
num = 134,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 241, tyn = 353, txp = 261, typ = 384,
}
glyphs[135] = { --''--
num = 135,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 281, tyn = 353, txp = 301, typ = 384,
}
glyphs[136] = { --''--
num = 136,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 321, tyn = 353, txp = 341, typ = 384,
}
glyphs[137] = { --''--
num = 137,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 361, tyn = 353, txp = 381, typ = 384,
}
glyphs[138] = { --''--
num = 138,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 401, tyn = 353, txp = 421, typ = 384,
}
glyphs[139] = { --''--
num = 139,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 441, tyn = 353, txp = 461, typ = 384,
}
glyphs[140] = { --''--
num = 140,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 1, tyn = 397, txp = 21, typ = 428,
}
glyphs[141] = { --''--
num = 141,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 41, tyn = 397, txp = 61, typ = 428,
}
glyphs[142] = { --''--
num = 142,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 81, tyn = 397, txp = 101, typ = 428,
}
glyphs[143] = { --''--
num = 143,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 121, tyn = 397, txp = 141, typ = 428,
}
glyphs[144] = { --''--
num = 144,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 161, tyn = 397, txp = 181, typ = 428,
}
glyphs[145] = { --''--
num = 145,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 201, tyn = 397, txp = 221, typ = 428,
}
glyphs[146] = { --''--
num = 146,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 241, tyn = 397, txp = 261, typ = 428,
}
glyphs[147] = { --''--
num = 147,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 281, tyn = 397, txp = 301, typ = 428,
}
glyphs[148] = { --''--
num = 148,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 321, tyn = 397, txp = 341, typ = 428,
}
glyphs[149] = { --''--
num = 149,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 361, tyn = 397, txp = 381, typ = 428,
}
glyphs[150] = { --''--
num = 150,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 401, tyn = 397, txp = 421, typ = 428,
}
glyphs[151] = { --''--
num = 151,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 441, tyn = 397, txp = 461, typ = 428,
}
glyphs[152] = { --''--
num = 152,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 1, tyn = 441, txp = 21, typ = 472,
}
glyphs[153] = { --''--
num = 153,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 41, tyn = 441, txp = 61, typ = 472,
}
glyphs[154] = { --''--
num = 154,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 81, tyn = 441, txp = 101, typ = 472,
}
glyphs[155] = { --''--
num = 155,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 121, tyn = 441, txp = 141, typ = 472,
}
glyphs[156] = { --''--
num = 156,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 161, tyn = 441, txp = 181, typ = 472,
}
glyphs[157] = { --''--
num = 157,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 201, tyn = 441, txp = 221, typ = 472,
}
glyphs[158] = { --''--
num = 158,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 241, tyn = 441, txp = 261, typ = 472,
}
glyphs[159] = { --''--
num = 159,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 281, tyn = 441, txp = 301, typ = 472,
}
glyphs[160] = { --' '--
num = 160,
adv = 14,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 441, txp = 324, typ = 444,
}
glyphs[161] = { --'¡'--
num = 161,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 441, txp = 364, typ = 444,
}
glyphs[162] = { --'¢'--
num = 162,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 441, txp = 404, typ = 444,
}
glyphs[163] = { --'£'--
num = 163,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 441, tyn = 441, txp = 461, typ = 472,
}
glyphs[164] = { --'¤'--
num = 164,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 1, tyn = 485, txp = 21, typ = 516,
}
glyphs[165] = { --'¥'--
num = 165,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 41, tyn = 485, txp = 61, typ = 516,
}
glyphs[166] = { --'¦'--
num = 166,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 81, tyn = 485, txp = 101, typ = 516,
}
glyphs[167] = { --'§'--
num = 167,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 121, tyn = 485, txp = 141, typ = 516,
}
glyphs[168] = { --'¨'--
num = 168,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 161, tyn = 485, txp = 181, typ = 516,
}
glyphs[169] = { --'©'--
num = 169,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 201, tyn = 485, txp = 221, typ = 516,
}
glyphs[170] = { --'ª'--
num = 170,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 485, txp = 244, typ = 488,
}
glyphs[171] = { --'«'--
num = 171,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 281, tyn = 485, txp = 301, typ = 516,
}
glyphs[172] = { --'¬'--
num = 172,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 321, tyn = 485, txp = 341, typ = 516,
}
glyphs[173] = { --''--
num = 173,
adv = 13,
oxn = -1, oyn = 9, oxp = 13, oyp = 16,
txn = 361, tyn = 485, txp = 375, typ = 492,
}
glyphs[174] = { --'®'--
num = 174,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 401, tyn = 485, txp = 421, typ = 516,
}
glyphs[175] = { --'¯'--
num = 175,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 441, tyn = 485, txp = 444, typ = 488,
}
glyphs[176] = { --'°'--
num = 176,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 1, tyn = 529, txp = 21, typ = 560,
}
glyphs[177] = { --'±'--
num = 177,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 529, txp = 44, typ = 532,
}
glyphs[178] = { --'²'--
num = 178,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 529, txp = 84, typ = 532,
}
glyphs[179] = { --'³'--
num = 179,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 121, tyn = 529, txp = 124, typ = 532,
}
glyphs[180] = { --'´'--
num = 180,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 161, tyn = 529, txp = 181, typ = 560,
}
glyphs[181] = { --'µ'--
num = 181,
adv = 23,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 529, txp = 204, typ = 532,
}
glyphs[182] = { --'¶'--
num = 182,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 241, tyn = 529, txp = 261, typ = 560,
}
glyphs[183] = { --'·'--
num = 183,
adv = 10,
oxn = 1, oyn = 10, oxp = 9, oyp = 18,
txn = 281, tyn = 529, txp = 289, typ = 537,
}
glyphs[184] = { --'¸'--
num = 184,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 321, tyn = 529, txp = 341, typ = 560,
}
glyphs[185] = { --'¹'--
num = 185,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 529, txp = 364, typ = 532,
}
glyphs[186] = { --'º'--
num = 186,
adv = 14,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 529, txp = 404, typ = 532,
}
glyphs[187] = { --'»'--
num = 187,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 441, tyn = 529, txp = 461, typ = 560,
}
glyphs[188] = { --'¼'--
num = 188,
adv = 33,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 573, txp = 4, typ = 576,
}
glyphs[189] = { --'½'--
num = 189,
adv = 38,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 573, txp = 44, typ = 576,
}
glyphs[190] = { --'¾'--
num = 190,
adv = 33,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 573, txp = 84, typ = 576,
}
glyphs[191] = { --'¿'--
num = 191,
adv = 15,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 121, tyn = 573, txp = 124, typ = 576,
}
glyphs[192] = { --'À'--
num = 192,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 161, tyn = 573, txp = 164, typ = 576,
}
glyphs[193] = { --'Á'--
num = 193,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 573, txp = 204, typ = 576,
}
glyphs[194] = { --'Â'--
num = 194,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 573, txp = 244, typ = 576,
}
glyphs[195] = { --'Ã'--
num = 195,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 573, txp = 284, typ = 576,
}
glyphs[196] = { --'Ä'--
num = 196,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 573, txp = 324, typ = 576,
}
glyphs[197] = { --'Å'--
num = 197,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 573, txp = 364, typ = 576,
}
glyphs[198] = { --'Æ'--
num = 198,
adv = 41,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 573, txp = 404, typ = 576,
}
glyphs[199] = { --'Ç'--
num = 199,
adv = 27,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 441, tyn = 573, txp = 444, typ = 576,
}
glyphs[200] = { --'È'--
num = 200,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 617, txp = 4, typ = 620,
}
glyphs[201] = { --'É'--
num = 201,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 617, txp = 44, typ = 620,
}
glyphs[202] = { --'Ê'--
num = 202,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 617, txp = 84, typ = 620,
}
glyphs[203] = { --'Ë'--
num = 203,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 121, tyn = 617, txp = 124, typ = 620,
}
glyphs[204] = { --'Ì'--
num = 204,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 161, tyn = 617, txp = 164, typ = 620,
}
glyphs[205] = { --'Í'--
num = 205,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 617, txp = 204, typ = 620,
}
glyphs[206] = { --'Î'--
num = 206,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 617, txp = 244, typ = 620,
}
glyphs[207] = { --'Ï'--
num = 207,
adv = 13,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 617, txp = 284, typ = 620,
}
glyphs[208] = { --'Ð'--
num = 208,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 617, txp = 324, typ = 620,
}
glyphs[209] = { --'Ñ'--
num = 209,
adv = 30,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 617, txp = 364, typ = 620,
}
glyphs[210] = { --'Ò'--
num = 210,
adv = 32,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 617, txp = 404, typ = 620,
}
glyphs[211] = { --'Ó'--
num = 211,
adv = 32,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 441, tyn = 617, txp = 444, typ = 620,
}
glyphs[212] = { --'Ô'--
num = 212,
adv = 32,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 661, txp = 4, typ = 664,
}
glyphs[213] = { --'Õ'--
num = 213,
adv = 32,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 661, txp = 44, typ = 664,
}
glyphs[214] = { --'Ö'--
num = 214,
adv = 32,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 661, txp = 84, typ = 664,
}
glyphs[215] = { --'×'--
num = 215,
adv = 20,
oxn = 2, oyn = 6, oxp = 18, oyp = 22,
txn = 121, tyn = 661, txp = 137, typ = 677,
}
glyphs[216] = { --'Ø'--
num = 216,
adv = 32,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 161, tyn = 661, txp = 164, typ = 664,
}
glyphs[217] = { --'Ù'--
num = 217,
adv = 29,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 661, txp = 204, typ = 664,
}
glyphs[218] = { --'Ú'--
num = 218,
adv = 29,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 661, txp = 244, typ = 664,
}
glyphs[219] = { --'Û'--
num = 219,
adv = 29,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 661, txp = 284, typ = 664,
}
glyphs[220] = { --'Ü'--
num = 220,
adv = 29,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 661, txp = 324, typ = 664,
}
glyphs[221] = { --'Ý'--
num = 221,
adv = 24,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 661, txp = 364, typ = 664,
}
glyphs[222] = { --'Þ'--
num = 222,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 661, txp = 404, typ = 664,
}
glyphs[223] = { --'ß'--
num = 223,
adv = 24,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 441, tyn = 661, txp = 444, typ = 664,
}
glyphs[224] = { --'à'--
num = 224,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 705, txp = 4, typ = 708,
}
glyphs[225] = { --'á'--
num = 225,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 705, txp = 44, typ = 708,
}
glyphs[226] = { --'â'--
num = 226,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 705, txp = 84, typ = 708,
}
glyphs[227] = { --'ã'--
num = 227,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 121, tyn = 705, txp = 124, typ = 708,
}
glyphs[228] = { --'ä'--
num = 228,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 161, tyn = 705, txp = 164, typ = 708,
}
glyphs[229] = { --'å'--
num = 229,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 705, txp = 204, typ = 708,
}
glyphs[230] = { --'æ'--
num = 230,
adv = 28,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 705, txp = 244, typ = 708,
}
glyphs[231] = { --'ç'--
num = 231,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 705, txp = 284, typ = 708,
}
glyphs[232] = { --'è'--
num = 232,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 705, txp = 324, typ = 708,
}
glyphs[233] = { --'é'--
num = 233,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 705, txp = 364, typ = 708,
}
glyphs[234] = { --'ê'--
num = 234,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 705, txp = 404, typ = 708,
}
glyphs[235] = { --'ë'--
num = 235,
adv = 18,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 441, tyn = 705, txp = 444, typ = 708,
}
glyphs[236] = { --'ì'--
num = 236,
adv = 10,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 749, txp = 4, typ = 752,
}
glyphs[237] = { --'í'--
num = 237,
adv = 10,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 749, txp = 44, typ = 752,
}
glyphs[238] = { --'î'--
num = 238,
adv = 10,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 749, txp = 84, typ = 752,
}
glyphs[239] = { --'ï'--
num = 239,
adv = 10,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 121, tyn = 749, txp = 124, typ = 752,
}
glyphs[240] = { --'ð'--
num = 240,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 161, tyn = 749, txp = 164, typ = 752,
}
glyphs[241] = { --'ñ'--
num = 241,
adv = 22,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 749, txp = 204, typ = 752,
}
glyphs[242] = { --'ò'--
num = 242,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 749, txp = 244, typ = 752,
}
glyphs[243] = { --'ó'--
num = 243,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 749, txp = 284, typ = 752,
}
glyphs[244] = { --'ô'--
num = 244,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 321, tyn = 749, txp = 324, typ = 752,
}
glyphs[245] = { --'õ'--
num = 245,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 361, tyn = 749, txp = 364, typ = 752,
}
glyphs[246] = { --'ö'--
num = 246,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 401, tyn = 749, txp = 404, typ = 752,
}
glyphs[247] = { --'÷'--
num = 247,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 441, tyn = 749, txp = 461, typ = 780,
}
glyphs[248] = { --'ø'--
num = 248,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 1, tyn = 793, txp = 4, typ = 796,
}
glyphs[249] = { --'ù'--
num = 249,
adv = 21,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 41, tyn = 793, txp = 44, typ = 796,
}
glyphs[250] = { --'ú'--
num = 250,
adv = 21,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 81, tyn = 793, txp = 84, typ = 796,
}
glyphs[251] = { --'û'--
num = 251,
adv = 20,
oxn = 0, oyn = -1, oxp = 20, oyp = 30,
txn = 121, tyn = 793, txp = 141, typ = 824,
}
glyphs[252] = { --'ü'--
num = 252,
adv = 21,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 161, tyn = 793, txp = 164, typ = 796,
}
glyphs[253] = { --'ý'--
num = 253,
adv = 17,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 201, tyn = 793, txp = 204, typ = 796,
}
glyphs[254] = { --'þ'--
num = 254,
adv = 20,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 241, tyn = 793, txp = 244, typ = 796,
}
glyphs[255] = { --'ÿ'--
num = 255,
adv = 17,
oxn = -1, oyn = -2, oxp = 2, oyp = 1,
txn = 281, tyn = 793, txp = 284, typ = 796,
}
fontSpecs.glyphs = glyphs
return fontSpecs
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/unlock-afflicted_cursed.lua | 3 | 1849 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return "New Class: #LIGHT_GREEN#Cursed (Afflicted)",
[[Through ignorance, greed or folly, the Cursed served some dark design and are now doomed to pay for their sins.
Their only master now is the hatred they carry for every living thing.
Drawing strength from the death of all they encounter, the Cursed become terrifying combatants.
Worse, any who approach the Cursed can be driven mad by their terrible aura.
Some of them, however, strive to redeem their faults by using their Cursed powers to battle evil.
You have "lifted" the curse of Ben Cruthdar. You can now create new characters with the #LIGHT_GREEN#Cursed class#WHITE#.
Cursed are heavy melee warriors, focusing all their hatred into their blows.
Class features:#YELLOW#
- Engulf your foes in your Gloom, weakening, confusing, stunning and damaging them
- Hunt your prey, tracking them and marking them for death
- Powerful melee combatant#WHITE#
The Cursed use hate, a resource that grows as they kill their foes and decreases while standing idle.
Most of their talents are more effective with high hate.
]]
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/spells/advanced-golemancy.lua | 3 | 6410 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local Chat = require "engine.Chat"
newTalent{
name = "Life Tap", short_name = "GOLEMANCY_LIFE_TAP",
type = {"spell/advanced-golemancy", 1},
require = {
special = { desc="Having an Alchemist Golem", fct=function(self, t) return self.alchemy_golem end},
stat = { mag=function(level) return 22 + (level-1) * 2 end },
level = function(level) return 10 + (level-1) end,
},
points = 5,
mana = 25,
cooldown = 12,
tactical = { HEAL = 2 },
is_heal = true,
getPower = function(self, t) return 70 + self:combatTalentSpellDamage(t, 15, 450) end,
action = function(self, t)
local mover, golem = getGolem(self)
if not golem then
game.logPlayer(self, "Your golem is currently inactive.")
return
end
local power = math.min(t.getPower(self, t), golem.life)
golem.life = golem.life - power -- Direct hit, bypass all checks
golem.changed = true
self:attr("allow_on_heal", 1)
self:heal(power, golem)
self:attr("allow_on_heal", -1)
if core.shader.active(4) then
self:addParticles(Particles.new("shader_shield_temp", 1, {toback=true , size_factor=1.5, y=-0.3, img="healarcane", life=25}, {type="healing", time_factor=2000, beamsCount=20, noup=2.0, beamColor1={0x8e/255, 0x2f/255, 0xbb/255, 1}, beamColor2={0xe7/255, 0x39/255, 0xde/255, 1}, circleDescendSpeed=4}))
self:addParticles(Particles.new("shader_shield_temp", 1, {toback=false, size_factor=1.5, y=-0.3, img="healarcane", life=25}, {type="healing", time_factor=2000, beamsCount=20, noup=1.0, beamColor1={0x8e/255, 0x2f/255, 0xbb/255, 1}, beamColor2={0xe7/255, 0x39/255, 0xde/255, 1}, circleDescendSpeed=4}))
end
game:playSoundNear(self, "talents/arcane")
return true
end,
info = function(self, t)
local power=t.getPower(self, t)
return ([[You tap into your golem's life energies to replenish your own. Drains %d life.]]):
format(power)
end,
}
newTalent{
name = "Gem Golem",
type = {"spell/advanced-golemancy",2},
require = spells_req_high2,
mode = "passive",
points = 5,
no_unlearn_last = true,
info = function(self, t)
return ([[Insert a pair of gems into your golem, providing it with the gem bonuses and changing its melee attack damage type. You may remove the gems and insert different ones; this does not destroy the gems you remove.
Gem level usable: %d
Gem changing is done in the golem's inventory.]]):format(self:getTalentLevelRaw(t))
end,
}
newTalent{
name = "Supercharge Golem",
type = {"spell/advanced-golemancy", 3},
require = spells_req_high3,
points = 5,
mana = 20,
cooldown = function(self, t) return math.ceil(self:combatTalentLimit(t, 0, 24, 20)) end, -- Limit to > 0
tactical = { DEFEND = 1, ATTACK=1 },
getPower = function(self, t) return (60 + self:combatTalentSpellDamage(t, 15, 450)) / 7, 7, self:combatTalentLimit(t, 100, 27, 55) end, --Limit life gain < 100%
action = function(self, t)
local regen, dur, hp = t.getPower(self, t)
-- ressurect the golem
if not game.level:hasEntity(self.alchemy_golem) or self.alchemy_golem.dead then
self.alchemy_golem.dead = nil
self.alchemy_golem.life = self.alchemy_golem.max_life / 100 * hp
-- Find space
local x, y = util.findFreeGrid(self.x, self.y, 5, true, {[Map.ACTOR]=true})
if not x then
game.logPlayer(self, "Not enough space to supercharge!")
return
end
game.zone:addEntity(game.level, self.alchemy_golem, "actor", x, y)
self.alchemy_golem:setTarget(nil)
self.alchemy_golem.ai_state.tactic_leash_anchor = self
self.alchemy_golem:removeAllEffects()
end
local mover, golem = getGolem(self)
if not golem then
game.logPlayer(self, "Your golem is currently inactive.")
return
end
golem:setEffect(golem.EFF_SUPERCHARGE_GOLEM, dur, {regen=regen})
game:playSoundNear(self, "talents/arcane")
return true
end,
info = function(self, t)
local regen, turns, life = t.getPower(self, t)
return ([[You activate a special mode of your golem, boosting its regeneration rate by %0.2f life per turn for %d turns.
If your golem was dead, it is instantly brought back to life with %d%% life.
While supercharged, your golem is enraged and deals 25%% more damage.]]):
format(regen, turns, life)
end,
}
newTalent{
name = "Runic Golem",
type = {"spell/advanced-golemancy",4},
require = spells_req_high4,
mode = "passive",
points = 5,
no_unlearn_last = true,
on_learn = function(self, t)
self.alchemy_golem.life_regen = self.alchemy_golem.life_regen + 1
self.alchemy_golem.mana_regen = self.alchemy_golem.mana_regen + 1
self.alchemy_golem.stamina_regen = self.alchemy_golem.stamina_regen + 1
local lev = self:getTalentLevelRaw(t)
if lev == 1 or lev == 3 or lev == 5 then
self.alchemy_golem.max_inscriptions = self.alchemy_golem.max_inscriptions + 1
self.alchemy_golem.inscriptions_slots_added = self.alchemy_golem.inscriptions_slots_added + 1
end
end,
on_unlearn = function(self, t)
self.alchemy_golem.life_regen = self.alchemy_golem.life_regen - 1
self.alchemy_golem.mana_regen = self.alchemy_golem.mana_regen - 1
self.alchemy_golem.stamina_regen = self.alchemy_golem.stamina_regen - 1
local lev = self:getTalentLevelRaw(t)
if lev == 0 or lev == 2 or lev == 4 then
self.alchemy_golem.max_inscriptions = self.alchemy_golem.max_inscriptions - 1
self.alchemy_golem.inscriptions_slots_added = self.alchemy_golem.inscriptions_slots_added - 1
end
end,
info = function(self, t)
return ([[Increases your golem's life, mana and stamina regeneration rates by %0.2f.
At level 1, 3 and 5, the golem also gains a new rune slot.
Even without this talent, Golems start with three rune slots.]]):
format(self:getTalentLevelRaw(t))
end,
}
| gpl-3.0 |
crazyboy11/spol | plugins/music.lua | 3 | 2458 | --[[
#
# Music Downloader
#
# @Dragon_Born
# @GPMod
#
#
]]
local function musiclink(msg, musicid)
local value = redis:hget('music:'..msg.to.id, musicid)
if not value then
return
else
value = value..'\n\n@SpheroCh'
return value
end
end
------------------ Seconds To Minutes alg ------------------
function sectomin (Sec)
if (tonumber(Sec) == nil) or (tonumber(Sec) == 0) then
return "00:00"
else
Seconds = math.floor(tonumber(Sec))
if Seconds < 1 then Seconds = 1 end
Minutes = math.floor(Seconds / 60)
Seconds = math.floor(Seconds - (Minutes * 60))
if Seconds < 10 then
Seconds = "0"..Seconds
end
if Minutes < 10 then
Minutes = "0"..Minutes
end
return Minutes..':'..Seconds
end
end
function run(msg, matches)
if string.match(msg.text, '[\216-\219][\128-\191]') then
return send_large_msg(get_receiver(msg), 'فارسی پشتیبانی نمیشود\nاز متن فینگلیش استفاده کنید. ')
end
if matches[1]:lower() == "dl" then
local value = redis:hget('music:'..msg.to.id, matches[2])
if not value then
return 'آهنگ مورد نظر پیدا نشد.'
else
value = value..'\n\n@SpheroCh'
return value
end
return
end
local url = http.request("http://api.gpmod.ir/music.search/?q="..URL.escape(matches[2]).."&count=30&sort=2")
--[[
-- Sort order:
-- 1 — by duration
-- 2 — by popularity
-- 0 — by date added
---
-- max counts = 300
]]
local jdat = json:decode(url)
local text , time , num = ''
local hash = 'music:'..msg.to.id
redis:del(hash)
if #jdat.response < 2 then return "No result found." end
for i = 2, #jdat.response do
if 900 > jdat.response[i].duration then
num = i - 1
time = sectomin(jdat.response[i].duration)
text = text..num..'- Artist: '.. jdat.response[i].artist .. ' | '..time..'\nTitle: '..jdat.response[i].title..'\n\n'
redis:hset(hash, num, 'Artist: '.. jdat.response[i].artist .. '\nTitle: '..jdat.response[i].title..' | '..time..'\n\n'.."GPMod.ir/dl.php?q="..jdat.response[i].owner_id.."_"..jdat.response[i].aid)
end
end
text = text..'برای دریافت لینک دانلود از دستور زیر استفاده کنید\n/dl <number>\n(example): /dl 1'
return text
end
return {
description = "music",
usage = {
"!music <khanande> : show musics for <khanande>",
"!dl <number> : download and show download link",
},
patterns = {
"^[/!]([Mm][Uu][Ss][Ii][Cc]) (.*)$",
"^[/!]([dD][Ll]) (.*)$"
},
run = run
}
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/rest/v2/get/user/alert/list.lua | 1 | 1466 | --
-- (C) 2021-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path
local rest_utils = require("rest_utils")
local user_alert_store = require "user_alert_store".new()
local auth = require "auth"
--
-- Read alerts data
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v2/get/user/alert/list.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local format = _GET["format"] or "json"
local no_html = (format == "txt")
if not auth.has_capability(auth.capabilities.alerts) then
rest_utils.answer(rest_utils.consts.err.not_granted)
return
end
interface.select(getSystemInterfaceId())
-- Fetch the results
local alerts, recordsFiltered = user_alert_store:select_request()
for _key,_value in ipairs(alerts or {}) do
local record = user_alert_store:format_record(_value, no_html)
res[#res + 1] = record
end -- for
if no_html then
res = user_alert_store:to_csv(res)
rest_utils.vanilla_payload_response(rc, res, "text/csv")
else
rest_utils.extended_answer(rc, {records = res}, {
["draw"] = tonumber(_GET["draw"]),
["recordsFiltered"] = recordsFiltered,
["recordsTotal"] = #res
}, format)
end
| gpl-3.0 |
eriche2016/nn | SpatialDilatedConvolution.lua | 3 | 3277 | local THNN = require 'nn.THNN'
local SpatialDilatedConvolution, parent = torch.class('nn.SpatialDilatedConvolution', 'nn.SpatialConvolution')
function SpatialDilatedConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH, dilationW, dilationH)
parent.__init(self, nInputPlane, nOutputPlane, kW, kH, dW, dH, padW, padH)
self.dilationW = dilationW or 1
self.dilationH = dilationH or 1
end
local function makeContiguous(self, input, gradOutput)
if not input:isContiguous() then
self._input = self._input or input.new()
self._input:resizeAs(input):copy(input)
input = self._input
end
if gradOutput then
if not gradOutput:isContiguous() then
self._gradOutput = self._gradOutput or gradOutput.new()
self._gradOutput:resizeAs(gradOutput):copy(gradOutput)
gradOutput = self._gradOutput
end
end
return input, gradOutput
end
function SpatialDilatedConvolution:updateOutput(input)
self.finput = self.finput or self.weight.new()
self.fgradInput = self.fgradInput or self.weight.new()
input = makeContiguous(self, input)
input.THNN.SpatialDilatedConvolution_updateOutput(
input:cdata(),
self.output:cdata(),
self.weight:cdata(),
THNN.optionalTensor(self.bias),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH,
self.dilationW, self.dilationH
)
return self.output
end
function SpatialDilatedConvolution:updateGradInput(input, gradOutput)
if self.gradInput then
input, gradOutput = makeContiguous(self, input, gradOutput)
self.fgradInput = self.fgradInput or self.weight.new()
input.THNN.SpatialDilatedConvolution_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.weight:cdata(),
self.finput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH,
self.dilationW, self.dilationH
)
return self.gradInput
end
end
function SpatialDilatedConvolution:accGradParameters(input, gradOutput, scale)
scale = scale or 1
input, gradOutput = makeContiguous(self, input, gradOutput)
self.fgradInput = self.fgradInput or self.weight.new()
input.THNN.SpatialDilatedConvolution_accGradParameters(
input:cdata(),
gradOutput:cdata(),
self.gradWeight:cdata(),
THNN.optionalTensor(self.gradBias),
self.finput:cdata(),
self.fgradInput:cdata(),
self.kW, self.kH,
self.dW, self.dH,
self.padW, self.padH,
self.dilationW, self.dilationH,
scale
)
end
function SpatialDilatedConvolution:__tostring__()
local s = string.format('%s(%d -> %d, %dx%d', torch.type(self),
self.nInputPlane, self.nOutputPlane, self.kW, self.kH)
if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then
s = s .. string.format(', %d,%d', self.dW, self.dH)
end
if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then
s = s .. ', ' .. self.padW .. ',' .. self.padH
end
s = s .. ', ' .. self.dilationW .. ',' .. self.dilationH
if self.bias then
return s .. ')'
else
return s .. ') without bias'
end
end
| bsd-3-clause |
pakoito/ToME---t-engine4 | game/modules/tome/data/maps/zones/rhaloren-camp-last.lua | 3 | 4213 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
defineTile('.', "FLOOR")
defineTile('!', "FLOOR", "NOTE4")
defineTile('#', "WALL")
defineTile('+', "DOOR")
defineTile('P', "FLOOR", nil, "INQUISITOR")
defineTile('p', "FLOOR", nil, {random_filter={max_ood=2, special=function(e) return e.faction == "rhalore" end}})
subGenerator{
x = 0, y = 0, w = 50, h = 43,
generator = "engine.generator.map.Roomer",
data = {
nb_rooms = 10,
rooms = {"random_room"},
['.'] = "FLOOR",
['#'] = "WALL",
up = "UP",
door = "DOOR",
force_tunnels = {
{"random", {26, 43}, id=-500},
},
},
define_up = true,
}
checkConnectivity({26,44}, "entrance", "boss-area", "boss-area")
return {
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[ ]],
[[#########################+########################]],
[[##....................+.....+.......p...........##]],
[[#.............p.......#p.!.p#....................#]],
[[###########+###########################+##########]],
[[#......p..............#.....#....p...............#]],
[[##.............p......+..P..+..........p........##]],
[[##################################################]]
}
| gpl-3.0 |
jsj2008/ValyriaTear | img/sprites/map/enemies/lord_idle.lua | 4 | 1150 | -- Sprite animation file descriptor
-- This file will describe the frames used to load the sprite animations
-- This files is following a special format compared to other animation scripts.
local ANIM_SOUTH = vt_map.MapMode.ANIM_SOUTH;
local ANIM_NORTH = vt_map.MapMode.ANIM_NORTH;
local ANIM_WEST = vt_map.MapMode.ANIM_WEST;
local ANIM_EAST = vt_map.MapMode.ANIM_EAST;
sprite_animation = {
-- The file to load the frames from
image_filename = "img/sprites/map/enemies/lord_spritesheet.png",
-- The number of rows and columns of images, will be used to compute
-- the images width and height, and also the frames number (row x col)
rows = 4,
columns = 6,
-- The actual frame size
frame_width = 75.0,
frame_height = 75.0,
-- The frames duration in milliseconds
frames = {
[ANIM_SOUTH] = {
[0] = { id = 0, duration = 150 }
},
[ANIM_NORTH] = {
[0] = { id = 6, duration = 150 }
},
[ANIM_EAST] = {
[0] = { id = 12, duration = 150 }
},
[ANIM_WEST] = {
[0] = { id = 18, duration = 150 }
}
}
}
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/npcs/multihued-drake.lua | 3 | 8834 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
local Talents = require("engine.interface.ActorTalents")
newEntity{
define_as = "BASE_NPC_MULTIHUED_DRAKE",
type = "dragon", subtype = "multihued",
display = "D", color=colors.PURPLE,
shader = "quad_hue", resolvers.nice_tile{shader = false},
body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 },
resolvers.drops{chance=100, nb=1, {type="money"} },
infravision = 10,
life_rating = 18,
rank = 2,
size_category = 5,
autolevel = "drake",
ai = "dumb_talented_simple", ai_state = { ai_move="move_complex", talent_in=1, },
stats = { str=20, dex=20, mag=30, con=16 },
knockback_immune = 1,
stun_immune = 0.8,
blind_immune = 0.8,
poison_immune = 0.5,
}
newEntity{ base = "BASE_NPC_MULTIHUED_DRAKE",
name = "multi-hued drake hatchling", color=colors.PURPLE, display="d",
desc = [[A drake hatchling. Not too powerful by itself, but it usually comes with its brothers and sisters.]],
level_range = {15, nil}, exp_worth = 1,
rarity = 1,
rank = 1, size_category = 2,
max_life = resolvers.rngavg(60,80),
combat_armor = 5, combat_def = 0,
on_melee_hit = {[DamageType.FIRE]=resolvers.mbonus(7, 3), [DamageType.COLD]=resolvers.mbonus(7, 3)},
combat = { dam=resolvers.levelup(resolvers.rngavg(25,70), 1, 0.6), atk=resolvers.rngavg(25,70), apr=25, dammod={str=1.1} },
resists = { [DamageType.PHYSICAL] = 20, [DamageType.FIRE] = 20, [DamageType.COLD] = 20, [DamageType.ACID] = 20, [DamageType.LIGHTNING] = 20, },
make_escort = {
{type="dragon", subtype="multihued", name="multi-hued drake hatchling", number=3, no_subescort=true},
},
resolvers.talents{
[Talents.T_ICE_CLAW]={base=1, every=10},
}
}
newEntity{ base = "BASE_NPC_MULTIHUED_DRAKE",
name = "multi-hued drake", color=colors.PURPLE, display="D",
desc = [[A mature multi-hued drake, armed with many deadly breath weapons and nasty claws.]],
level_range = {25, nil}, exp_worth = 1,
rarity = 3,
max_life = resolvers.rngavg(150,170),
combat_armor = 12, combat_def = 0,
on_melee_hit = {[DamageType.FIRE]=resolvers.mbonus(10, 5), [DamageType.COLD]=resolvers.mbonus(10, 5)},
combat = { dam=resolvers.levelup(resolvers.rngavg(25,110), 1, 1.2), atk=resolvers.rngavg(25,100), apr=25, dammod={str=1.1} },
stats_per_level = 4,
lite = 1,
resists = { [DamageType.PHYSICAL] = 30, [DamageType.FIRE] = 30, [DamageType.COLD] = 30, [DamageType.ACID] = 30, [DamageType.LIGHTNING] = 30, },
make_escort = {
{type="dragon", name="multi-hued drake hatchling", number=1},
},
resolvers.talents{
[Talents.T_ICE_CLAW]={base=3, every=6, max=6},
[Talents.T_WING_BUFFET]={base=2, every=7, max=5},
[Talents.T_FIRE_BREATH]={base=4, every=4, max=11},
[Talents.T_ICE_BREATH]={base=4, every=4, max=11},
[Talents.T_SAND_BREATH]={base=4, every=4, max=11},
[Talents.T_POISON_BREATH]={base=4, every=4, max=11},
[Talents.T_LIGHTNING_BREATH]={base=4, every=4, max=11},
[Talents.T_ACID_BREATH]={base=4, every=4, max=11},
},
}
newEntity{ base = "BASE_NPC_MULTIHUED_DRAKE", define_as = "GREATER_MULTI_HUED_WYRM",
name = "greater multi-hued wyrm", color=colors.PURPLE, display="D",
resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/dragon_multihued_greater_multi_hued_wyrm.png", display_h=2, display_y=-1}}},
desc = [[An old and powerful multi-hued drake, armed with many deadly breath weapons and nasty claws.]],
level_range = {35, nil}, exp_worth = 1,
rarity = 8,
rank = 3,
max_life = resolvers.rngavg(220,250),
combat_armor = 30, combat_def = 30,
on_melee_hit = {[DamageType.FIRE]=resolvers.mbonus(10, 5), [DamageType.COLD]=resolvers.mbonus(10, 5), [DamageType.LIGHTNING]=resolvers.mbonus(10, 5), [DamageType.ACID]=resolvers.mbonus(10, 5)},
combat = { dam=resolvers.levelup(resolvers.rngavg(25,150), 1, 2.2), atk=resolvers.rngavg(25,130), apr=25, dammod={str=1.1} },
stats_per_level = 5,
lite = 1,
stun_immune = 1,
blind_immune = 1,
resists = { [DamageType.PHYSICAL] = 40, [DamageType.FIRE] = 40, [DamageType.COLD] = 40, [DamageType.ACID] = 40, [DamageType.LIGHTNING] = 40, },
ai = "tactical",
make_escort = {
{type="dragon", name="multi-hued drake", number=1},
{type="dragon", name="multi-hued drake", number=1, no_subescort=true},
},
resolvers.talents{
[Talents.T_SILENCE]={base=3, every=6},
[Talents.T_DISARM]={base=3, every=6},
[Talents.T_ICE_CLAW]={base=3, every=6},
[Talents.T_WING_BUFFET]={base=2, every=7},
[Talents.T_FIRE_BREATH]={base=9, every=4},
[Talents.T_ICE_BREATH]={base=9, every=4},
[Talents.T_SAND_BREATH]={base=9, every=4},
[Talents.T_POISON_BREATH]={base=9, every=4},
[Talents.T_LIGHTNING_BREATH]={base=9, every=4},
[Talents.T_ACID_BREATH]={base=9, every=4},
},
ingredient_on_death = "MULTIHUED_WYRM_SCALE",
}
newEntity{ base = "BASE_NPC_MULTIHUED_DRAKE",
unique = true,
name = "Ureslak the Prismatic", color=colors.VIOLET, display="D",
resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/drake_multi_ureslak.png", display_h=2, display_y=-1}}},
desc = [[A huge multi-hued drake. It seems to shift color rapidly.]],
level_range = {35, nil}, exp_worth = 4,
rarity = 50,
rank = 3.5,
max_life = resolvers.rngavg(320,350), life_rating = 22,
combat_armor = 33, combat_def = 40,
on_melee_hit = {[DamageType.FIRE]=resolvers.mbonus(10, 5), [DamageType.COLD]=resolvers.mbonus(10, 5), [DamageType.LIGHTNING]=resolvers.mbonus(10, 5), [DamageType.ACID]=resolvers.mbonus(10, 5)},
combat = { dam=resolvers.levelup(resolvers.rngavg(25,150), 1, 2.2), atk=resolvers.rngavg(25,130), apr=32, dammod={str=1.1} },
lite = 1,
stun_immune = 1,
blind_immune = 1,
ai = "tactical",
ai_tactic = resolvers.tactic"ranged",
ai_status = {ally_compassion = 0},
make_escort = {
{type="dragon", name="greater multi-hued wyrm", number=2, no_subescort=true},
},
no_auto_resists = true,
color_switch = 2,
resists = { all=50, [DamageType.FIRE] = 100, [DamageType.COLD] = -100 },
resolvers.talents{ [Talents.T_DRACONIC_BODY] = 1, [Talents.T_FIRE_BREATH]=15, [Talents.T_FLAME]=7 },
stats = { str=20, dex=20, mag=80, con=16 },
talent_cd_reduction={[Talents.T_MANATHRUST]=4},
colors = {
{"red", {
resists = { all=50, [DamageType.FIRE] = 100, [DamageType.COLD] = -100 },
talents = { [Talents.T_DRACONIC_BODY] = 1, [Talents.T_EQUILIBRIUM_POOL]=1, [Talents.T_MANA_POOL]=1, [Talents.T_FIRE_BREATH]=15, [Talents.T_FLAME]=7 },
}},
{"white", {
resists = { all=50, [DamageType.COLD] = 100, [DamageType.FIRE] = -100 },
talents = { [Talents.T_DRACONIC_BODY] = 1, [Talents.T_EQUILIBRIUM_POOL]=1, [Talents.T_MANA_POOL]=1, [Talents.T_ICE_BREATH]=15, [Talents.T_ICE_SHARDS]=7 },
}},
{"blue", {
resists = { all=50, [DamageType.LIGHTNING] = 100, [DamageType.PHYSICAL] = -100 },
talents = { [Talents.T_DRACONIC_BODY] = 1, [Talents.T_EQUILIBRIUM_POOL]=1, [Talents.T_MANA_POOL]=1, [Talents.T_LIGHTNING_BREATH]=15, [Talents.T_SHOCK]=7 },
}},
{"green", {
resists = { all=50, [DamageType.NATURE] = 100, [DamageType.BLIGHT] = -100 },
talents = { [Talents.T_DRACONIC_BODY] = 1, [Talents.T_EQUILIBRIUM_POOL]=1, [Talents.T_MANA_POOL]=1, [Talents.T_POISON_BREATH]=15, [Talents.T_SPIT_POISON]=7 },
}},
{"dark", {
resists = { all=50, [DamageType.DARKNESS] = 100, [DamageType.LIGHT] = -100 },
talents = { [Talents.T_DRACONIC_BODY] = 1, [Talents.T_NEGATIVE_POOL]=1, [Talents.T_STARFALL]=7, [Talents.T_MOONLIGHT_RAY]=7 },
}},
{"violet", {
resists = { all=-50 },
talents = { [Talents.T_DRACONIC_BODY] = 1, [Talents.T_MANA_POOL]=1, [Talents.T_MANATHRUST]=12 },
}},
},
on_act = function(self)
self.color_switch = self.color_switch - 1
if self.color_switch <= 0 then
self.color_switch = 2
-- Reset cooldowns
local db_cd = self.talents_cd[self.T_DRACONIC_BODY]
self.talents_cd = {}
self.talents_cd[self.T_DRACONIC_BODY] = db_cd
self:incEquilibrium(-100)
self:incMana(100)
self:incNegative(100)
-- Assign talents & resists
local t = rng.table(self.colors)
self.resists = t[2].resists
self.talents = t[2].talents
self.changed = true
game.logSeen(self, "#YELLOW#%s's skin turns %s!", self.name:capitalize(), t[1])
end
end,
}
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/rest/v2/charts/time/data.lua | 2 | 1238 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local rest_utils = require("rest_utils")
local epoch_begin = tonumber(_GET["epoch_begin"])
local epoch_end = tonumber(_GET["epoch_end"])
local num_records = tonumber(_GET["totalRows"]) or 24
local rc = rest_utils.consts.success.ok
local curr = epoch_begin
-- 1 hour is 60*60=3600
local datasets = {}
local labels = {}
for i = 1, num_records, 1 do
if (curr < epoch_end) then
local key = os.date("%x", curr)
if datasets[key] == nil then
datasets[key] = 0
end
-- add an hour?
datasets[key] = datasets[key] + 1
curr = curr + 3600 -- ad an hour
else
break
end
end
local flatten = {}
local i = 1
for k, d in pairsByKeys(datasets) do
flatten[i] = d
labels[i] = k
i = i + 1
end
rest_utils.answer(rc, {
data = {
labels = labels,
datasets = {
{data = flatten, label = "Hours in a day", backgroundColor = "#f83a5dfa"}
}
},
options = {
maintainAspectRatio = false
},
redirect_url = ntop.getHttpPrefix()
})
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.