repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
FishFilletsNG/fillets-data | script/floppy/demo_dialogs_ru.lua | 1 | 2678 | -- FIXME.asm
dialogId("dlg-x-poster1", "font_orange", "THE GREATEST EARTHQUAKE SINCE 1990")
dialogStr("")
dialogId("dlg-x-poster2", "font_orange", "when Dragon’s Lair was issued, Rules for beginners, version 1.0.")
dialogStr("когда Dragon's Lair был опубликован, Правила для начинающих, версия 1.0")
dialogId("dlg-x-poster3", "font_orange", "DRAGON’S LAIR PLUS")
dialogStr("DRAGON'S LAIR PLUS")
dialogId("dlg-x-poster4", "font_orange", "The world of role-playing games will soon change forever.")
dialogStr("Мир ролевых игр в скором времени изменился навсегда.")
dialogId("dlg-x-poster5", "font_orange", "Dragon’s Lair Plus is not only a new version.")
dialogStr("Dragon's Lair Plus это не только новая версия.")
dialogId("dlg-x-poster6", "font_orange", "It’s a new game.")
dialogStr("Это новая игра.")
dialogId("dlg-x-poster7", "font_orange", "Plenty of new possibilities. New occupations. New system of character creation, where, instead of your lives, your skills grow. New elegant mechanism of playing.")
dialogStr("Множество новых возможностей. Новые профессии. Новая система создания персонажа, где, вместо вашей жизни, растет ваше мастерство. Новый элегантный механизм игры.")
dialogId("dlg-x-poster8", "font_orange", "A game for 21. century.")
dialogStr("Это игра для 21 века.")
dialogId("dlg-x-poster9", "font_orange", "GAMES HAVE CHANGED")
dialogStr("ИГРА ИЗМЕНИЛАСЬ")
dialogId("dlg-x-poster10", "font_poster", "This is what we get from the computer after inserting the waterproof diskette that was found during our investigation of secret criminal organisation.")
dialogStr("Это то, что мы получаем от компьютера после установки промокшей дискеты, что было обнаружено в ходе нашего расследования тайной криминалистической организацией.")
dialogId("dlg-x-poster11", "font_poster", "We are shocked. Do not let journalists know it.")
dialogStr("Мы шокированы. Ни один журналист не знал это.")
dialogId("dlg-x-poster12", "font_poster", "You must prevent the panic.")
dialogStr("Мы должны предотвратить панику.")
dialogId("dlg-x-poster13", "font_poster", "And subscribe two copies for us.")
dialogStr("И записывать по две копии.")
| gpl-2.0 |
zielmicha/freeciv-mirror | dependencies/tolua-5.1/src/bin/lua/module.lua | 5 | 1440 | -- tolua: module class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Module class
-- Represents module.
-- The following fields are stored:
-- {i} = list of objects in the module.
classModule = {
classtype = 'module'
}
classModule.__index = classModule
setmetatable(classModule,classContainer)
-- register module
function classModule:register ()
push(self)
output(' tolua_module(tolua_S,"'..self.name..'",',self:hasvar(),');')
output(' tolua_beginmodule(tolua_S,"'..self.name..'");')
local i=1
while self[i] do
self[i]:register()
i = i+1
end
output(' tolua_endmodule(tolua_S);')
pop()
end
-- Print method
function classModule:print (ident,close)
print(ident.."Module{")
print(ident.." name = '"..self.name.."';")
local i=1
while self[i] do
self[i]:print(ident.." ",",")
i = i+1
end
print(ident.."}"..close)
end
-- Internal constructor
function _Module (t)
setmetatable(t,classModule)
append(t)
return t
end
-- Constructor
-- Expects two string representing the module name and body.
function Module (n,b)
local t = _Module(_Container{name=n})
push(t)
t:parse(strsub(b,2,strlen(b)-1)) -- eliminate braces
pop()
return t
end
| gpl-2.0 |
AnySDK/Sample_Lua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ActionInterval.lua | 10 | 1441 |
--------------------------------
-- @module ActionInterval
-- @extend FiniteTimeAction
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ActionInterval] getAmplitudeRate
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#ActionInterval] setAmplitudeRate
-- @param self
-- @param #float amp
--------------------------------
-- how many seconds had elapsed since the actions started to run.
-- @function [parent=#ActionInterval] getElapsed
-- @param self
-- @return float#float ret (return value: float)
--------------------------------
--
-- @function [parent=#ActionInterval] startWithTarget
-- @param self
-- @param #cc.Node target
--------------------------------
--
-- @function [parent=#ActionInterval] step
-- @param self
-- @param #float dt
--------------------------------
--
-- @function [parent=#ActionInterval] clone
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
--
-- @function [parent=#ActionInterval] reverse
-- @param self
-- @return ActionInterval#ActionInterval ret (return value: cc.ActionInterval)
--------------------------------
--
-- @function [parent=#ActionInterval] isDone
-- @param self
-- @return bool#bool ret (return value: bool)
return nil
| mit |
unigent/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-diag-devinfo/luasrc/controller/luci_diag/devinfo_common.lua | 76 | 5638 | --[[
Luci diag - Diagnostics controller module
(c) 2009 Daniel Dickinson
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
]]--
module("luci.controller.luci_diag.devinfo_common", package.seeall)
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.cbi")
require("luci.model.uci")
local translate = luci.i18n.translate
local DummyValue = luci.cbi.DummyValue
local SimpleSection = luci.cbi.SimpleSection
function index()
return -- no-op
end
function run_processes(outnets, cmdfunc)
i = next(outnets, nil)
while (i) do
outnets[i]["output"] = luci.sys.exec(cmdfunc(outnets, i))
i = next(outnets, i)
end
end
function parse_output(devmap, outnets, haslink, type, mini, debug)
local curnet = next(outnets, nil)
while (curnet) do
local output = outnets[curnet]["output"]
local subnet = outnets[curnet]["subnet"]
local ports = outnets[curnet]["ports"]
local interface = outnets[curnet]["interface"]
local netdevs = {}
devlines = luci.util.split(output)
if not devlines then
devlines = {}
table.insert(devlines, output)
end
local j = nil
j = next(devlines, j)
local found_a_device = false
while (j) do
if devlines[j] and ( devlines[j] ~= "" ) then
found_a_device = true
local devtable
local row = {}
devtable = luci.util.split(devlines[j], ' | ')
row["ip"] = devtable[1]
if (not mini) then
row["mac"] = devtable[2]
end
if ( devtable[4] == 'unknown' ) then
row["vendor"] = devtable[3]
else
row["vendor"] = devtable[4]
end
row["type"] = devtable[5]
if (not mini) then
row["model"] = devtable[6]
end
if (haslink) then
row["config_page"] = devtable[7]
end
if (debug) then
row["raw"] = devlines[j]
end
table.insert(netdevs, row)
end
j = next(devlines, j)
end
if not found_a_device then
local row = {}
row["ip"] = curnet
if (not mini) then
row["mac"] = ""
end
if (type == "smap") then
row["vendor"] = luci.i18n.translate("No SIP devices")
else
row["vendor"] = luci.i18n.translate("No devices detected")
end
row["type"] = luci.i18n.translate("check other networks")
if (not mini) then
row["model"] = ""
end
if (haslink) then
row["config_page"] = ""
end
if (debug) then
row["raw"] = output
end
table.insert(netdevs, row)
end
local s
if (type == "smap") then
if (mini) then
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet)
else
local interfacestring = ""
if ( interface ~= "" ) then
interfacestring = ", " .. interface
end
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("SIP devices discovered for") .. " " .. curnet .. " (" .. subnet .. ":" .. ports .. interfacestring .. ")")
end
s.template = "diag/smapsection"
else
if (mini) then
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet)
else
local interfacestring = ""
if ( interface ~= "" ) then
interfacestring = ", " .. interface
end
s = devmap:section(luci.cbi.Table, netdevs, luci.i18n.translate("Devices discovered for") .. " " .. curnet .. " (" .. subnet .. interfacestring .. ")")
end
end
s:option(DummyValue, "ip", translate("IP Address"))
if (not mini) then
s:option(DummyValue, "mac", translate("MAC Address"))
end
s:option(DummyValue, "vendor", translate("Vendor"))
s:option(DummyValue, "type", translate("Device Type"))
if (not mini) then
s:option(DummyValue, "model", translate("Model"))
end
if (haslink) then
s:option(DummyValue, "config_page", translate("Link to Device"))
end
if (debug) then
s:option(DummyValue, "raw", translate("Raw"))
end
curnet = next(outnets, curnet)
end
end
function get_network_device(interface)
local state = luci.model.uci.cursor_state()
state:load("network")
local dev
return state:get("network", interface, "ifname")
end
function cbi_add_networks(field)
uci.cursor():foreach("network", "interface",
function (section)
if section[".name"] ~= "loopback" then
field:value(section[".name"])
end
end
)
field.titleref = luci.dispatcher.build_url("admin", "network", "network")
end
function config_devinfo_scan(map, scannet)
local o
o = scannet:option(luci.cbi.Flag, "enable", translate("Enable"))
o.optional = false
o.rmempty = false
o = scannet:option(luci.cbi.Value, "interface", translate("Interface"))
o.optional = false
luci.controller.luci_diag.devinfo_common.cbi_add_networks(o)
local scansubnet
scansubnet = scannet:option(luci.cbi.Value, "subnet", translate("Subnet"))
scansubnet.optional = false
o = scannet:option(luci.cbi.Value, "timeout", translate("Timeout"), translate("Time to wait for responses in seconds (default 10)"))
o.optional = true
o = scannet:option(luci.cbi.Value, "repeat_count", translate("Repeat Count"), translate("Number of times to send requests (default 1)"))
o.optional = true
o = scannet:option(luci.cbi.Value, "sleepreq", translate("Sleep Between Requests"), translate("Milliseconds to sleep between requests (default 100)"))
o.optional = true
end
| gpl-2.0 |
FishFilletsNG/fillets-data | script/cave/dialogs_ru.lua | 1 | 4206 | dialogId("jes-m-netopyr", "font_small", "That bat must be terribly strong.")
dialogStr("Эта летучая мышь, должно быть, ужасно сильная.")
dialogId("jes-v-tojo", "font_big", "Well, yes.")
dialogStr("Пожалуй, да.")
dialogId("jes-m-tvor", "font_small", "That red creature is a little bit strange.")
dialogStr("Это красное существо немного странное.")
dialogId("jes-v-nestezuj", "font_big", "That may be true, but I think we are going to need it.")
dialogStr("Может и так, но, я думаю, оно нам понадобится.")
dialogId("jes-v-uzke", "font_big", "It’s too narrow for me. You have to do it on your own down there.")
dialogStr("Тут слишком узко для меня. Ты должна справиться самостоятельно там внизу.")
dialogId("jes-m-ryba", "font_small", "That white fish is a terrible obstacle.")
dialogStr("Эта белая рыба является страшной помехой.")
dialogId("jes-v-kamen", "font_big", "Fish? I thought it was only a stone.")
dialogStr("Рыба? Я думал, что это просто камень.")
dialogId("jes-v-gral", "font_big", "I think that we should be looking for the Grail somewhere else...")
dialogStr("Я думаю, что мы должны поискать Грааль где-нибудь ещё...")
dialogId("jes-m-deprese", "font_small", "Don’t be depressive. We will solve this in no time.")
dialogStr("Не будь таким депрессивным. Мы решим эту проблему в ближайшее время.")
dialogId("jes-v-nevim", "font_big", "I am not so sure.")
dialogStr("Я не так уж уверен в этом.")
dialogId("jes-m-takvidis", "font_small", "See? You are here.")
dialogStr("Вот видишь? Ты здесь.")
dialogId("jes-m-potvora0", "font_small", "What kind of color-shifting monster is this?")
dialogStr("Что это за монстр здесь, постоянно меняющий свой цвет?")
dialogId("jes-m-potvora1", "font_small", "This is an abomination.")
dialogStr("Это отвратительно.")
dialogId("jes-m-potvora2", "font_small", "This is an offense of Nature.")
dialogStr("Это ошибка природы.")
dialogId("jes-v-potvora0", "font_big", "It is called the Flashy hammerhead.")
dialogStr("Это Ослепительная Рыба-молот.")
dialogId("jes-v-potvora1", "font_big", "It is called the Glossy repulsor.")
dialogStr("Это Глянцевая Мерзость.")
dialogId("jes-v-potvora2", "font_big", "It is called the Politician fish.")
dialogStr("Это Рыба-политик.")
dialogId("jes-m-netopyr0", "font_small", "This bat is kind of strange.")
dialogStr("Какая странная разновидность летучих мышей.")
dialogId("jes-v-netopyr0", "font_big", "This is very phlegmatic bat.")
dialogStr("Эта летучая мышь очень флегматичная.")
dialogId("jes-m-netopyr1", "font_small", "This is a stuffed bat.")
dialogStr("Это откормленная летучая мышь.")
dialogId("jes-v-netopyr1", "font_big", "It’s a sculpture of bat.")
dialogStr("Это скульптура летучий мыши.")
dialogId("jes-m-netopyr2", "font_small", "It’s a stalagmite shaped as a bat.")
dialogStr("Это сталагмит, похожий на летучую мышь.")
dialogId("jes-v-netopyr2", "font_big", "It’s a plain stalagmite.")
dialogStr("Это обычный сталагмит.")
dialogId("jes-m-netopyr3", "font_small", "It’s just an ordinary piece of rock.")
dialogStr("Это обычный кусок горной породы.")
dialogId("jes-v-nechut0", "font_big", "I think you are going to need that ‘monster’.")
dialogStr("Я думаю, нам пригодится это „чудовище“.")
dialogId("jes-v-nechut1", "font_big", "I think you will have to overcome your dislike of that ‘abomination’.")
dialogStr("Я думаю, тебе придётся побороть свою неприязнь к „отвратному“.")
| gpl-2.0 |
gedadsbranch/Darkstar-Mission | scripts/globals/mobskills/Impale.lua | 6 | 1213 | ---------------------------------------------
-- Impale
--
-- Description: Deals damage to a single target. Additional effect: Paralysis
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes:
---------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local isNM = mob:isMobType(MOBTYPE_NOTORIOUS);
local numhits = 1;
local accmod = 1;
local dmgmod = 2.3;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local shadows = info.hitslanded;
if(isNM) then
shadows = MOBPARAM_IGNORE_SHADOWS;
end
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,shadows);
local typeEffect = EFFECT_PARALYSIS;
local power = 20;
if(isNM) then
typeEffect = EFFECT_POISON;
end
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, power, 0, 120);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
hooksta4/darkstar | scripts/globals/items/marron_glace.lua | 35 | 1337 | -----------------------------------------
-- ID: 4502
-- Item: Marron Glace
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Magic % 13
-- Magic Cap 85
-- Magic Regen While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4502);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_MPP, 13);
target:addMod(MOD_FOOD_MP_CAP, 85);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_MPP, 13);
target:delMod(MOD_FOOD_MP_CAP, 85);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
skwerlman/ccsquish | debug/minichunkspy.lua | 3 | 7418 | -- Minichunkspy: Disassemble and reassemble chunks.
-- Copyright M Joonas Pihlaja 2009
-- MIT license
--
-- minichunkspy = require"minichunkspy"
--
-- chunk = string.dump(loadfile"blabla.lua")
-- disassembled_chunk = minichunkspy.disassemble(chunk)
-- chunk = minichunkspy.assemble(disassembled_chunk)
-- assert(minichunkspy.validate(<function or chunk>))
--
-- Tested on little-endian 32 bit platforms. Modify
-- the Size_t type to be a 64 bit integer to make it work
-- for 64 bit systems, and set BIG_ENDIAN = true for
-- big-endian systems.
local string, table, math = string, table, math
local ipairs, setmetatable, type, assert = ipairs, setmetatable, type, assert
local _ = __END_OF_GLOBALS__
local string_char, string_byte, string_sub = string.char, string.byte, string.sub
local table_concat = table.concat
local math_abs, math_ldexp, math_frexp = math.abs, math.ldexp, math.frexp
local Inf = math.huge
local Nan = Inf - Inf
local BIG_ENDIAN = false --twiddle this for your platform.
local function construct (class, ...)
return class.new(class, ...)
end
local mt_memo = {}
local Field = construct{
new =
function (class, self)
local self = self or {}
local mt = mt_memo[class] or {
__index = class,
__call = construct
}
mt_memo[class] = mt
return setmetatable(self, mt)
end,
}
local None = Field{
unpack = function (self, bytes, ix) return nil, ix end,
pack = function (self, val) return "" end
}
local char_memo = {}
local function char(n)
local field = char_memo[n] or Field{
unpack = function (self, bytes, ix)
return string_sub(bytes, ix, ix+n-1), ix+n
end,
pack = function (self, val) return string_sub(val, 1, n) end
}
char_memo[n] = field
return field
end
local uint8 = Field{
unpack = function (self, bytes, ix)
return string_byte(bytes, ix, ix), ix+1
end,
pack = function (self, val) return string_char(val) end
}
local uint32 = Field{
unpack =
function (self, bytes, ix)
local a,b,c,d = string_byte(bytes, ix, ix+3)
if BIG_ENDIAN then a,b,c,d = d,c,b,a end
return a + b*256 + c*256^2 + d*256^3, ix+4
end,
pack =
function (self, val)
assert(type(val) == "number",
"unexpected value type to pack as an uint32")
local a,b,c,d
d = val % 2^32
a = d % 256; d = (d - a) / 256
b = d % 256; d = (d - b) / 256
c = d % 256; d = (d - c) / 256
if BIG_ENDIAN then a,b,c,d = d,c,b,a end
return string_char(a,b,c,d)
end
}
local int32 = uint32{
unpack = function (self, bytes, ix)
local val, ix = uint32:unpack(bytes, ix)
return val < 2^32 and val or (val - 2^31), ix
end
}
local Byte = uint8
local Size_t = uint32
local Integer = int32
-- Opaque types:
local Number = char(8)
local Insn = char(4)
local Struct = Field{
unpack =
function (self, bytes, ix)
local val = {}
local i,j = 1,1
while self[i] do
local field = self[i]
local key = field.name
if not key then key, j = j, j+1 end
--print("unpacking struct field", key, " at index ", ix)
val[key], ix = field:unpack(bytes, ix)
i = i+1
end
return val, ix
end,
pack =
function (self, val)
local data = {}
local i,j = 1,1
while self[i] do
local field = self[i]
local key = field.name
if not key then key, j = j, j+1 end
data[i] = field:pack(val[key])
i = i+1
end
return table_concat(data)
end
}
local List = Field{
unpack =
function (self, bytes, ix)
local len, ix = Integer:unpack(bytes, ix)
local vals = {}
local field = self.type
for i=1,len do
--print("unpacking list field", i, " at index ", ix)
vals[i], ix = field:unpack(bytes, ix)
end
return vals, ix
end,
pack =
function (self, vals)
local len = #vals
local data = { Integer:pack(len) }
local field = self.type
for i=1,len do
data[#data+1] = field:pack(vals[i])
end
return table_concat(data)
end
}
local Boolean = Field{
unpack =
function (self, bytes, ix)
local val, ix = Integer:unpack(bytes, ix)
assert(val == 0 or val == 1,
"unpacked an unexpected value "..val.." for a Boolean")
return val == 1, ix
end,
pack =
function (self, val)
assert(type(val) == "boolean",
"unexpected value type to pack as a Boolean")
return Integer:pack(val and 1 or 0)
end
}
local String = Field{
unpack =
function (self, bytes, ix)
local len, ix = Integer:unpack(bytes, ix)
local val = nil
if len > 0 then
-- len includes trailing nul byte; ignore it
local string_len = len - 1
val = bytes:sub(ix, ix+string_len-1)
end
return val, ix + len
end,
pack =
function (self, val)
assert(type(val) == "nil" or type(val) == "string",
"unexpected value type to pack as a String")
if val == nil then
return Integer:pack(0)
end
return Integer:pack(#val+1) .. val .. "\000"
end
}
local ChunkHeader = Struct{
char(4){name = "signature"},
Byte{name = "version"},
Byte{name = "format"},
Byte{name = "endianness"},
Byte{name = "sizeof_int"},
Byte{name = "sizeof_size_t"},
Byte{name = "sizeof_insn"},
Byte{name = "sizeof_Number"},
Byte{name = "integral_flag"},
}
local ConstantTypes = {
[0] = None,
[1] = Boolean,
[3] = Number,
[4] = String,
}
local Constant = Field{
unpack =
function (self, bytes, ix)
local t, ix = Byte:unpack(bytes, ix)
local field = ConstantTypes[t]
assert(field, "unknown constant type "..t.." to unpack")
local v, ix = field:unpack(bytes, ix)
return {
type = t,
value = v
}, ix
end,
pack =
function (self, val)
local t, v = val.type, val.value
return Byte:pack(t) .. ConstantTypes[t]:pack(v)
end
}
local Local = Struct{
String{name = "name"},
Integer{name = "startpc"},
Integer{name = "endpc"}
}
local Function = Struct{
String{name = "name"},
Integer{name = "line"},
Integer{name = "last_line"},
Byte{name = "num_upvalues"},
Byte{name = "num_parameters"},
Byte{name = "is_vararg"},
Byte{name = "max_stack_size"},
List{name = "insns", type = Insn},
List{name = "constants", type = Constant},
List{name = "prototypes", type = nil}, --patch type below
List{name = "source_lines", type = Integer},
List{name = "locals", type = Local},
List{name = "upvalues", type = String},
}
assert(Function[10].name == "prototypes",
"missed the function prototype list")
Function[10].type = Function
local Chunk = Struct{
ChunkHeader{name = "header"},
Function{name = "body"}
}
local function validate(chunk)
if type(chunk) == "function" then
return validate(string.dump(chunk))
end
local f = Chunk:unpack(chunk, 1)
local chunk2 = Chunk:pack(f)
if chunk == chunk2 then return true end
local i
local len = math.min(#chunk, #chunk2)
for i=1,len do
local a = chunk:sub(i,i)
local b = chunk:sub(i,i)
if a ~= b then
return false, ("chunk roundtripping failed: "..
"first byte difference at index %d"):format(i)
end
end
return false, ("chunk round tripping failed: "..
"original length %d vs. %d"):format(#chunk, #chunk2)
end
return {
disassemble = function (chunk) return Chunk:unpack(chunk, 1) end,
assemble = function (disassembled) return Chunk:pack(disassembled) end,
validate = validate
}
| mit |
gedadsbranch/Darkstar-Mission | scripts/zones/Windurst_Woods/npcs/Cayu_Pensharhumi.lua | 38 | 1416 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Cayu Pensharhumi
-- Type: Standard NPC
-- @pos 39.437 -0.91 -40.808 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,2) == false) then
player:startEvent(0x02dd);
else
player:startEvent(0x0103);
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 == 0x02dd) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",2,true);
end
end;
| gpl-3.0 |
Moodstocks/nn | Padding.lua | 32 | 1429 | local Padding, parent = torch.class('nn.Padding', 'nn.Module')
-- pad can be positive (right) negative (left)
function Padding:__init(dim, pad, nInputDim, value)
self.dim = dim
self.pad = pad
self.nInputDim = nInputDim
self.value = value or 0
self.outputSize = torch.LongStorage()
parent.__init(self)
end
function Padding:updateOutput(input)
self.outputSize:resize(input:dim())
self.outputSize:copy(input:size())
local dim = self.dim
if self.nInputDim and input:dim() ~= self.nInputDim then
dim = dim + 1
end
self.outputSize[dim] = self.outputSize[dim] + math.abs(self.pad)
self.output:resize(self.outputSize)
self.output:fill(self.value)
local outputWindow
if self.pad > 0 then
outputWindow = self.output:narrow(dim, 1, input:size(dim))
else
outputWindow = self.output:narrow(dim, 1 - self.pad, input:size(dim))
end
outputWindow:copy(input)
return self.output
end
function Padding:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input)
local dim = self.dim
if self.nInputDim and input:dim() ~= self.nInputDim then
dim = dim + 1
end
local gradOutputWindow
if self.pad > 0 then
gradOutputWindow = gradOutput:narrow(dim, 1, input:size(dim))
else
gradOutputWindow = gradOutput:narrow(dim, 1 - self.pad, input:size(dim))
end
self.gradInput:copy(gradOutputWindow)
return self.gradInput
end
| bsd-3-clause |
syhunt/community | src/SyHybrid/dynamic/dynamic.lua | 1 | 15447 | SyhuntDynamic = {}
SyhuntDynamic.waitlogin = false
function dynamictargetchanged(t)
--if app.ask_yn('Do you wish to scan logged URL: '..t.url..'?') == true then
if SyhuntDynamic.waitlogin == true then
SyhuntDynamic.waitlogin = false
browser.options.showbottombar = false
SyhuntDynamic:SetURLCookie(t)
app.bringtofront()
SyhuntDynamic:NewScanDialog()
end
end
function SyhuntDynamic:AddCommands()
console.addcmd('appscan',"SyhuntDynamic:ScanThisSite('appscan')",'Scans the current site')
console.addcmd('spider',"SyhuntDynamic:ScanThisSite('spider')",'Spiders the current site')
end
function SyhuntDynamic:AddClipmon()
clipmon = symini.clipmon:new()
clipmon.ontargetchanged = dynamictargetchanged
end
function SyhuntDynamic:ManualLogin()
if SyHybridUser:IsOptionAvailable(true) == true then
self.waitlogin = true
local html = clipmon:getloginhelp()
browser.loadpagex({name='manual login help',html=html})
end
end
function SyhuntDynamic:CaptureCookie(onlogscript)
if tab:hasloadedurl(true) then
local onlogscript = onlogscript or ''
tab:runluaonlog('done','SyhuntDynamic:SetURLCookieFromSandcat() '..onlogscript)
tab:runjs([[console.log('ck='+btoa(document.cookie)+',ua='+btoa(navigator.userAgent));console.log('done');]],tab.url,0)
end
end
function SyhuntDynamic:SetURLCookieFromSandcat()
local sl = ctk.string.list:new()
sl.commatext = tab.lastjslogmsg
local t = {}
t.url = tab.url
t.cookie = ctk.base64.decode(sl:getvalue('ck'))
t.useragent = ctk.base64.decode(sl:getvalue('ua'))
self:SetURLCookie(t)
sl:release()
end
function SyhuntDynamic:SetURLCookie(t)
prefs.set('syhunt.dynamic.options.target.url', t.url)
if t.useragent ~= '' then
prefs.set('syhunt.dynamic.emulation.useragent', t.useragent)
prefs.set('syhunt.dynamic.emulation.forceuseragent', true)
end
-- Saves to site preferences
--app.showmessage(t.cookie)
--app.showmessage(t.url)
symini.prefs_set('dynamic.lists.cookies', t.cookie, t.url)
symini.prefs_set('dynamic.crawling.autofollowinstarturl', false, t.url)
tab.status = 'Page session details saved.'
end
function SyhuntDynamic:SaveCapturedURLs()
local destfile = app.savefile('Syhunt URL list (*.lst)|*.lst','lst','')
if destfile ~= '' then
local sl = ctk.string.list:new()
sl.text = tab.urllist
sl:savetofile(destfile)
sl:release()
end
end
function SyhuntDynamic:CaptureURLsEnd()
if tab:hasloadedurl(true) then
tab.captureurls = true
app.showmessage('URL Logger enabled.')
end
end
function SyhuntDynamic:CaptureURLs()
browser.setactivepage('browser')
local url = app.showinputdialog('Start URL:', '', 'Start URL')
tab.loadend = 'SyhuntDynamic:CaptureURLsEnd()'
if url ~= '' then
tab:gotourl(url)
end
end
function SyhuntDynamic:ClearResults()
if self:IsScanInProgress(true) == false then
local ui = self.ui
ui.url.value = ''
tab:results_clear()
tab:tree_clear()
tab:userdata_set('session','')
tab:userdata_set('taskid','')
tab:runsrccmd('showmsgs',false)
tab.toolbar:eval('MarkReset();')
tab.status = ''
tab.icon = 'url(SyHybrid.scx#images\\16\\dynamic.png)'
tab.title = 'New Tab'
self:LoadProgressPanel()
end
end
function SyhuntDynamic:EditPreferences(html)
html = html or SyHybrid:getfile('dynamic/prefs/prefs.html')
local slp = ctk.string.loop:new()
local ds = symini.dynamic:new()
ds:start()
slp:load(ds.options)
while slp:parsing() do
prefs.regdefault(slp.current,ds:prefs_getdefault(slp.current))
end
html = ctk.string.replace(html,'%dynamic_checks%',SyHybrid:GetOptionsHTML(ds.options_checks))
html = ctk.string.replace(html,'%dynamic_injection_checks%',SyHybrid:GetOptionsHTML(ds.options_checksinj))
local t = {}
t.html = html
t.id = 'syhuntdynamic'
t.options = ds.options
t.options_disabled = ds.options_locked
local res = Sandcat.Preferences:EditCustom(t)
ds:release()
slp:release()
return res
end
function SyhuntDynamic:EditNetworkPreferences()
local html = SyHybrid:getfile('dynamic/prefs_net/prefs.html')
self:EditPreferences(html)
end
function SyhuntDynamic:EditSitePreferences(url)
url = url or tab.url
local res = false
if ctk.string.beginswith(string.lower(url),'http') then
local jsonfile = prefs.getsiteprefsfilename(url)
local slp = ctk.string.loop:new()
local hs = symini.hybrid:new()
hs:start()
slp:load(hs.options)
while slp:parsing() do
prefs.regdefault(slp.current,hs:prefs_getdefault(slp.current))
end
local t = {}
t.html = SyHybrid:getfile('dynamic/prefs_site/prefs.html')
t.id = 'syhuntsiteprefs'
t.options = hs.options
t.jsonfile = jsonfile
res = Sandcat.Preferences:EditCustomFile(t)
--app.showmessage(tostring(res))
hs:release()
slp:release()
else
app.showmessage('No site loaded.')
end
return res
end
function SyhuntDynamic:GenerateReport()
local sesname = tab:userdata_get('session','')
if sesname ~= '' then
ReportMaker:loadtab(sesname)
else
app.showmessage('No session loaded.')
end
end
function SyhuntDynamic:IsScanInProgress(warn)
warn = warn or false
local tid = tab:userdata_get('taskid','')
if tid ~= '' then
if browser.gettaskinfo(tid).enabled == false then
return false
else
if warn == true then
app.showmessage('A scan is in progress.')
end
return true
end
else
return false
end
end
function SyhuntDynamic:Load()
local mainexe = app.dir..'SyMini.dll'
local mainico = app.dir..'\\Packs\\Icons\\SyDynamic.ico'
self:NewTab()
app.seticonfromfile(mainico)
browser.info.fullname = 'Syhunt Dynamic'
browser.info.name = 'Dynamic'
browser.info.exefilename = mainexe
browser.info.abouturl = 'http://www.syhunt.com/en/?n=Products.SyhuntDynamic'
browser.pagebar:eval('Tabs.RemoveAll()')
browser.pagebar:eval([[$("#tabstrip").insert("<include src='SyHybrid.scx#dynamic/pagebar.html'/>",1);]])
browser.pagebar:eval('SandcatUIX.Update();Tabs.Select("results");')
PageMenu.newtabscript = 'SyhuntDynamic:NewTab(false)'
end
function SyhuntDynamic:EditVulnDetails(filename)
if VulnInfo == nil then
SyHybrid:dofile('hybrid/vulninfo.lua')
end
VulnInfo:editvulnfile(filename)
end
function SyhuntDynamic:LoadVulnDetails(filename)
if VulnInfo == nil then
SyHybrid:dofile('hybrid/vulninfo.lua')
end
VulnInfo:loadvulnfile(filename)
end
function SyhuntDynamic:LoadURLDetails(url)
browser.setactivepage('response')
local ses = symini.session:new()
local req = {}
ses.name = tab:userdata_get('session')
req = ses:getrequestdetails(url,'snapshot.first')
ses:release()
tab:response_load(req)
if req.isseccheck == true then
if ctk.url.crack(req.url).path ~= '' then
self:LoadVulnDetails(req.vulnfilename)
end
end
end
function SyhuntDynamic:LoadTree(dir)
tab.showtree = true
tab.tree_loaditemfunc = 'SyhuntDynamic:LoadURLDetails'
tab:tree_clear()
local opt = {}
opt.dir = dir..'\\'
opt.recurse = true
opt.makebold = true
--opt.affscripts = affscripts
--tab:tree_loaddir(opt)
end
function SyhuntDynamic:GetTargetListHTML()
local histfile = browser.info.configdir..'Targets Dynamic'..'.sclist'
local html = ''
if ctk.file.exists(histfile) == true then
local slp = ctk.string.loop:new()
slp:loadfromfile(histfile)
while slp:parsing() do
local url = ctk.string.after(slp.current, 'url="')
url = ctk.string.before(url,'"')
html = html..'<li class="urlsetter" targeturl="'..url..'">'..url..'</li>'
end
slp:release()
end
return html
end
function SyhuntDynamic:NewScan(runinbg)
local canscan = true
if runinbg == false then
if self:IsScanInProgress(true) == true then
canscan = false
end
end
if canscan == true then
prefs.set('syhunt.dynamic.options.target.editsiteprefs',false)
local html = SyHybrid:getfile('dynamic/prefs_scan/prefs.html')
html = ctk.string.replace(html,'%dynamic_targets%',SyhuntDynamic:GetTargetListHTML())
local ok = self:EditPreferences(html)
if ok == true then
local targeturl = prefs.get('syhunt.dynamic.options.target.url','')
local huntmethod = prefs.get('syhunt.dynamic.options.huntmethod','appscan')
local editsiteprefs = prefs.get('syhunt.dynamic.options.target.editsiteprefs',false)
if targeturl ~= '' then
local targeturl_original = self:NormalizeTargetURLEx(targeturl, false)
local autofollow = symini.prefs_get('dynamic.crawling.autofollowinstarturl', true, targeturl_original)
targeturl = self:NormalizeTargetURLEx(targeturl, autofollow, false)
prefs.set('syhunt.dynamic.options.target.url',targeturl)
if editsiteprefs == true then
ok = self:EditSitePreferences(targeturl)
end
if ok == true then
self:ScanSite(runinbg,targeturl,huntmethod)
end
end
end
end
end
function SyhuntDynamic:NewScanDialog()
local tab = self:NewTab()
if tab ~= '' then
self:NewScan(false)
end
end
function SyhuntDynamic:NewTab()
local cr = {}
cr.dblclickfunc = 'SyhuntDynamic:EditVulnDetails'
cr.columns = SyHybrid:getfile('dynamic/vulncols.lst')
local j = {}
if browser.info.initmode == 'syhuntdynamic' then
j.icon = '@ICON_EMPTY'
else
j.icon = 'url(SyHybrid.scx#images\\16\\dynamic.png)'
end
j.title = 'New Tab'
j.toolbar = 'SyHybrid.scx#dynamic\\toolbar\\toolbar.html'
j.table = 'SyhuntDynamic.ui'
j.activepage = 'results'
j.showpagestrip = true
local newtab = browser.newtabx(j)
if newtab ~= '' then
self:LoadTree('')
tab:results_customize(cr)
self:LoadProgressPanel()
browser.setactivepage(j.activepage)
app.update()
end
return newtab
end
function SyhuntDynamic:LoadProgressPanel()
local defstats = [[
s=code.stats-links,v=1
]]
local logos = ''
local html = SyHybrid:getfile('dynamic/progress.html')
logos = logos..SyHybridUser:GetEditionLogo()
html = ctk.string.replace(html, '<!--logoplus-->',logos)
tab:results_loadx(html)
tab:results_updatehtml(defstats)
end
function SyhuntDynamic:NormalizeTargetURLEx(url, autofollow, askfollow)
askfollow = askfollow or false
url = self:NormalizeTargetURL(url)
local redir = symini.checkurlredir(url)
if redir.result == true and redir.ondomain == false then
if autofollow == true then
url = redir.url
else
if askfollow == true then
if app.ask_yn('Follow redirect (recommended) to ['..redir.url..']?') == true then
url = redir.url
end
end
end
end
return url
end
function SyhuntDynamic:NormalizeTargetURL(url)
local addproto = true
if ctk.string.beginswith(string.lower(url),'http:') then
addproto = false
elseif ctk.string.beginswith(string.lower(url),'https:') then
addproto = false
end
if addproto then
url = 'http://'..url
end
return url
end
function SyhuntDynamic:PauseScan()
local tid = tab:userdata_get('taskid','')
if tid ~= '' then
browser.suspendtask(tid)
end
end
function SyhuntDynamic:ScanSite(runinbg,url,method)
method = method or 'spider'
if url ~= '' then
prefs.save()
tab.captureurls = false
local script = SyHybrid:getfile('dynamic/scantask.lua')
local menu = SyHybrid:getfile('dynamic/scantaskmenu.html')
local j = ctk.json.object:new()
local tid = 0
local stat = symini.checkinst()
j.sessionname = symini.getsessionname()
j.huntmethod = method
j.monitor = tab.handle
j.urllist = tab.urllist
j.starturl = url
j.runinbg = runinbg
menu = ctk.string.replace(menu,'%s',j.sessionname)
if stat.result == true then
tid = tab:runtask(script,tostring(j),menu)
else
app.showmessage(stat.resultstr)
end
if runinbg == false then
-- Updates the tab user interface
self:LoadTree('')
tab:userdata_set('session',j.sessionname)
tab:userdata_set('taskid',tid)
tab.title = ctk.url.crack(url).host
self.ui.url.value = url
browser.setactivepage('results')
end
j:release()
end
end
-- Starts a scan against the loaded web page
function SyhuntDynamic:ScanThisSite_Std(method)
if tab:hasloadedurl(true) then
if SyHybridUser:IsMethodAvailable(method, true) then
prefs.set('syhunt.dynamic.options.target.url', tab.url)
prefs.set('syhunt.dynamic.options.huntmethod', method)
self:NewScanDialog()
--self:ScanSite(true,tab.url,method)
end
end
end
-- Starts a scan against the loaded web page and its cookie data
function SyhuntDynamic:ScanThisSite(method)
self:CaptureCookie('SyhuntDynamic:ScanThisSite_Std("'..method..'")')
end
function SyhuntDynamic:StopScan()
local tid = tab:userdata_get('taskid','')
local sesname = tab:userdata_get('session','')
if tid ~= '' then
browser.stoptask(tid,'User requested')
tab.icon = '@ICON_STOP'
tab.toolbar:eval('MarkAsStopped()')
SessionManager:setsessionstatus(sesname, 'Canceled')
end
end
function SyhuntDynamic:AddToTargetList()
local d = {}
d.title = 'Add Dynamic Target'
d.name_caption = 'Name (eg: MySite)'
d.value_caption = 'URL'
local r = Sandcat.Preferences:EditNameValue(d)
if r.res == true then
local item = {}
item.name = r.name
item.url = self:NormalizeTargetURLEx(r.value, true)
item.repeaturlallow = false
item.repeaturlwarn = true
HistView:AddURLLogItem(item, 'Targets Dynamic')
self:ViewTargetList(false)
end
end
function SyhuntDynamic:ClearIncrementalData(tag)
local d = symini.getincdetails(tag)
if ctk.file.exists(d.filename) == true then
ctk.file.delete(d.filename)
app.showmessage('Incremental cache cleared for this item.')
else
app.showalert('No incremental cache found for this item!')
end
end
function SyhuntDynamic:DoTargetListAction(action, itemid)
local item = HistView:GetURLLogItem(itemid, 'Targets Dynamic')
if item ~= nil then
if action == 'scan' then
prefs.set('syhunt.dynamic.options.target.url', item.url)
self:NewScanDialog()
end
if action == 'manuallogin' then
SyhuntDynamic:ManualLogin(item.url)
end
if action == 'clearinc' then
SyhuntDynamic:ClearIncrementalData(item.url)
end
if action == 'editprefs' then
local ok = self:EditSitePreferences(item.url)
if ok == true then
self:ViewTargetList(false)
end
end
end
end
function SyhuntDynamic:ViewTargetList(newtab)
local t = {}
t.newtab = newtab
t.toolbar = 'SyHybrid.scx#dynamic/histview_tbtargets.html'
t.histname = 'Targets Dynamic'
t.tabicon = 'url(SyHybrid.scx#images\\16\\dynamic_bookmarks.png);'
t.readsiteprefs = true
t.style = [[
]]
t.menu = [[
<li onclick="SyhuntDynamic:DoTargetListAction('scan','%i')">Scan Site...</li>
<li onclick="SyhuntDynamic:DoTargetListAction('editprefs','%i')">Edit Site Preferences...</li>
<li onclick="SyhuntDynamic:DoTargetListAction('manuallogin','%i')">Manual Login (External)...</li>
<hr/>
<li onclick="SyhuntDynamic:DoTargetListAction('clearinc','%i')">Clear Incremental Cache</li>
<hr/>
<li onclick="HistView:DeleteURLLogItem('%i','Targets Dynamic')">Delete</li>
]]
HistView = HistView or Sandcat:require('histview')
HistView:ViewURLLogFile(t)
end
function SyhuntDynamic:ViewVulnerabilities()
local sesname = tab:userdata_get('session','')
if sesname ~= '' then
SessionManager:show_sessiondetails(sesname)
else
app.showmessage('No session loaded.')
end
end | bsd-3-clause |
gedadsbranch/Darkstar-Mission | scripts/zones/Bibiki_Bay/npcs/Fheli_Lapatzuo.lua | 12 | 4792 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Fheli Lapatzuo
-- Type: Manaclipper
-- @pos 488.793 -4.003 709.473 4
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
require("scripts/zones/Bibiki_Bay/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local schedule = 0;
local vHour = VanadielHour();
local vMin = VanadielMinute();
if( vHour == 0 and vMin <= 10) then -- Schedule
--Do nothing. -- 0: A - 0:10 - Dhalmel Rock
elseif( vHour == 0 and vMin <= 50) then -- 1: D - 0:50 - Dhalmel Rock
schedule = 1; -- 2: A - 4:50 - Purgonorgo Isle
elseif( vHour <= 3) then -- 3: D - 5:30 - Purgonorgo Isle
schedule = 2; -- 4: A - 12:10 - Maliyakaleya Reef
elseif( vHour == 4 and vMin <= 50) then -- 5: D - 12:50 - Maliyakaleya Reef
schedule = 2; -- 6: A - 16:50 - Purgonorgo Isle
elseif( vHour <= 4) then -- 7: D - 17:30 - Purgonorgo Isle
schedule = 3;
elseif( vHour == 5 and vMin <= 30) then
schedule = 3;
elseif( vHour <= 11) then
schedule = 4;
elseif( vHour == 12 and vMin <= 10) then
schedule = 4;
elseif( vHour == 12 and vMin <= 50) then
schedule = 5;
elseif( vHour <= 15) then
schedule = 6;
elseif( vHour == 16 and vMin <= 50) then
schedule = 6;
elseif( vHour <= 16) then
schedule = 7;
elseif( vHour == 17 and vMin <= 30) then
schedule = 7;
end
local arrive = 0;
local depart = 0;
local seconds = 0;
local description = 0; -- Dhamel Rock Tour: 0, Maliyakaleya Reef: 1, Purgonorgo Isle: 2, Sunset Docks: 3
if( schedule == 0) then -- Arrival, bound for Dhamel Rock
arrive = 1;
if( vHour == 17) then vHour = 7;
elseif( vHour == 18) then vHour = 6;
elseif( vHour == 19) then vHour = 5;
elseif( vHour == 20) then vHour = 4;
elseif( vHour == 21) then vHour = 3;
elseif( vHour == 22) then vHour = 2;
elseif( vHour == 23) then vHour = 1;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 10));
elseif( schedule == 1) then -- Departure to Dhalmel Rock
depart = 1;
seconds = math.floor(2.4 * (50 - vMin));
elseif( schedule == 2) then -- Arrival, bound for Purgonorgo Isle
arrive = 1;
description = 2; -- Purgonorgo Isle
if( vHour == 0) then vHour = 4;
elseif( vHour == 1) then vHour = 3;
elseif( vHour == 2) then vHour = 2;
elseif( vHour == 3) then vHour = 1;
elseif( vHour == 4) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 50));
elseif( schedule == 3) then -- Departure to Purgonorgo Isle
depart = 1;
description = 2; -- Purgonorgo Isle
if( vHour == 4) then vHour = 1;
elseif( vHour == 5) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 30));
elseif( schedule == 4) then -- Arrival, bound for Maliyakaleya Reef
arrive = 1;
description = 1; -- Maliyakaleya Reef
if( vHour == 5) then vHour = 7;
elseif( vHour == 6) then vHour = 6;
elseif( vHour == 7) then vHour = 5;
elseif( vHour == 8) then vHour = 4;
elseif( vHour == 9) then vHour = 3;
elseif( vHour == 10) then vHour = 2;
elseif( vHour == 11) then vHour = 1;
elseif( vHour == 12) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 10));
elseif( schedule == 5) then -- Departure to Maliyakaleya Reef
depart = 1;
description = 1; -- Maliyakaleya Reef
seconds = math.floor(2.4 * (50 - vMin));
elseif( schedule == 6) then -- Arrival, bound for Purgonorgo Isle
arrive = 1;
description = 2; -- Purgonorgo Isle
if( vHour == 12) then vHour = 4;
elseif( vHour == 13) then vHour = 3;
elseif( vHour == 14) then vHour = 2;
elseif( vHour == 15) then vHour = 1;
elseif( vHour == 16) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 50));
elseif( schedule == 7) then -- Departure to Purgonorgo Isle
depart = 1;
description = 2; -- Purgonorgo Isle
if( vHour == 16) then vHour = 1;
elseif( vHour == 17) then vHour = 0;
end
seconds = math.floor(2.4 * (vHour * 60 - vMin + 30));
end
player:startEvent( 0x0012, seconds, depart, arrive, description, 0, 0, 0, 0);
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 |
hooksta4/darkstar | scripts/globals/abilities/dark_maneuver.lua | 54 | 1332 | -----------------------------------
-- Ability: Dark Maneuver
-- Enhances the effect of dark attachments. Must have animator equipped.
-- Obtained: Puppetmaster level 1
-- Recast Time: 10 seconds (shared with all maneuvers)
-- Duration: 1 minute
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and
not player:hasStatusEffect(EFFECT_OVERLOAD)) then
return 0,0;
else
return 71,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local burden = 10;
if (target:getMP() < target:getPet():getMP()) then
burden = 15;
end
local overload = target:addBurden(ELE_DARK-1, burden);
if (overload ~= 0) then
target:removeAllManeuvers();
target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload);
else
if (target:getActiveManeuvers() == 3) then
target:removeOldestManeuver();
end
target:addStatusEffect(EFFECT_DARK_MANEUVER, 0, 0, 60);
end
return EFFECT_DARK_MANEUVER;
end; | gpl-3.0 |
dermoumi/m2n | extlibs/src/LuaJIT/src/jit/bc.lua | 1 | 5316 | ------------------
-- LuaJIT bytecode listing module.
--
-- Copyright (C) 2005-2014 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
------------------
--
-- This module lists the bytecode of a Lua function. If it's loaded by -jbc
-- it hooks into the parser and lists all functions of a chunk as they
-- are parsed.
--
-- Example usage:
--
-- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)'
-- luajit -jbc=- foo.lua
-- luajit -jbc=foo.list foo.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_LISTFILE. The file is overwritten every time the module
-- is started.
--
-- This module can also be used programmatically:
--
-- local bc = require("jit.bc")
--
-- local function foo() print("hello") end
--
-- bc.dump(foo) --> -- BYTECODE -- [...]
-- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello"
--
-- local out = {
-- -- Do something with each line:
-- write = function(t, ...) io.write(...) end,
-- close = function(t) end,
-- flush = function(t) end,
-- }
-- bc.dump(foo, out)
--
--------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20003, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local bit = require("bit")
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, band, shr = string.byte, bit.band, bit.rshift
local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck
local funcuvname = jutil.funcuvname
local bcnames = vmdef.bcnames
local stdout, stderr = io.stdout, io.stderr
--------------------
local function ctlsub(c)
if c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
elseif c == "\t" then return "\\t"
else return format("\\%03d", byte(c))
end
end
-- Return one bytecode line.
local function bcline(func, pc, prefix)
local ins, m = funcbc(func, pc)
if not ins then return end
local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128)
local a = band(shr(ins, 8), 0xff)
local oidx = 6*band(ins, 0xff)
local op = sub(bcnames, oidx+1, oidx+6)
local s = format("%04d %s %-6s %3s ",
pc, prefix or " ", op, ma == 0 and "" or a)
local d = shr(ins, 16)
if mc == 13*128 then -- BCMjump
return format("%s=> %04d\n", s, pc+d-0x7fff)
end
if mb ~= 0 then
d = band(d, 0xff)
elseif mc == 0 then
return s.."\n"
end
local kc
if mc == 10*128 then -- BCMstr
kc = funck(func, -d-1)
kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub))
elseif mc == 9*128 then -- BCMnum
kc = funck(func, d)
if op == "TSETM " then kc = kc - 2^52 end
elseif mc == 12*128 then -- BCMfunc
local fi = funcinfo(funck(func, -d-1))
if fi.ffid then
kc = vmdef.ffnames[fi.ffid]
else
kc = fi.loc
end
elseif mc == 5*128 then -- BCMuv
kc = funcuvname(func, d)
end
if ma == 5 then -- BCMuv
local ka = funcuvname(func, a)
if kc then kc = ka.." ; "..kc else kc = ka end
end
if mb ~= 0 then
local b = shr(ins, 24)
if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end
return format("%s%3d %3d\n", s, b, d)
end
if kc then return format("%s%3d ; %s\n", s, d, kc) end
if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits
return format("%s%3d\n", s, d)
end
-- Collect branch targets of a function.
local function bctargets(func)
local target = {}
for pc=1,1000000000 do
local ins, m = funcbc(func, pc)
if not ins then break end
if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end
end
return target
end
-- Dump bytecode instructions of a function.
local function bcdump(func, out, all)
if not out then out = stdout end
local fi = funcinfo(func)
if all and fi.children then
for n=-1,-1000000000,-1 do
local k = funck(func, n)
if not k then break end
if type(k) == "proto" then bcdump(k, out, true) end
end
end
out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined))
local target = bctargets(func)
for pc=1,1000000000 do
local s = bcline(func, pc, target[pc] and "=>")
if not s then break end
out:write(s)
end
out:write("\n")
out:flush()
end
--------------------
-- Active flag and output file handle.
local active, out
-- List handler.
local function h_list(func)
return bcdump(func, out)
end
-- Detach list handler.
local function bclistoff()
if active then
active = false
jit.attach(h_list)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach list handler.
local function bcliston(outfile)
if active then bclistoff() end
if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(h_list, "bc")
active = true
end
-- Public module functions.
module(...)
line = bcline
dump = bcdump
targets = bctargets
on = bcliston
off = bclistoff
start = bcliston -- For -j command line option.
| unlicense |
gedadsbranch/Darkstar-Mission | scripts/zones/North_Gustaberg/npcs/qm1.lua | 34 | 3485 | -----------------------------------
-- Area: North Gustaberg
-- NPC: qm1 (???)
-- Involved in Quest "The Siren's Tear"
-- @pos 309.600, 2.600, 324.000 106 | DB start position
-- @pos 290.000, 0.600, 332.100 106 | alternative start position
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/zones/North_Gustaberg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x000a);
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);
local npc = player:getEventTarget();
if (csid == 0x000a and option == 0) then
local mainweapon = player:getEquipID(SLOT_MAIN);
local subweapon = player:getEquipID(SLOT_SUB);
if (mainweapon == 0 and subweapon == 0) then
local freeslots = player:getFreeSlotsCount();
local alreadyHasItem = player:hasItem(576);
local SirensTear = player:getQuestStatus(BASTOK,THE_SIREN_S_TEAR);
local SirensTearProgress = player:getVar("SirensTear");
if (SirensTear == QUEST_COMPLETED and SirensTearProgress < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,576);
else
if (freeslots == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,576);
elseif (alreadyHasItem) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED_TWICE,576);
player:addItem(576);
else
player:addItem(576);
player:messageSpecial(ITEM_OBTAINED,576);
resetSirenTear(npc);
end
end
else
player:messageSpecial(SHINING_OBJECT_SLIPS_AWAY);
moveSirenTear(npc);
end
end
end;
-----------------------------------
-- Additional Functions
-----------------------------------
function moveSirenTear(npc)
-- determining starting point of the journey using the 3rd decimal place
npcPos = math.floor(math.floor(npc:getXPos())*1000000 + math.floor(npc:getYPos())*1000 + npc:getZPos());
disp = (npc:getYPos()*100 - math.floor(npc:getYPos()*100+0.5))*10;
dispf = disp*0.001;
switch (npcPos) : caseof {
[309002324] = function (x) npc:setPos(296,3+dispf,220,0); end,
[296003220] = function (x) npc:setPos(349.48,3.3+dispf,208,0); end,
[349003208] = function (x) npc:setPos(332.1,6+dispf,150.1); end,
[332006150] = function (x) if (disp == 0) then npc:setPos(290,0.601,332.1); else npc:setPos(309.6,2.6,324); end end,
[290000332] = function (x) npc:setPos(296,3+dispf,220,0); end,
default = function (x) end }
end;
function resetSirenTear(npc)
npcPos = math.floor(math.floor(npc:getXPos())*1000000 + math.floor(npc:getYPos())*1000 + npc:getZPos());
disp = (npc:getYPos()*100 - math.floor(npc:getYPos()*100+0.5))*10;
if (npcPos == 290000332 or disp == 1) then
npc:setPos(309.6,2.6,324);
else
npc:setPos(290,0.601,332.1);
end
end; | gpl-3.0 |
hooksta4/darkstar | scripts/zones/zones/Qufim_Island/npcs/Trodden_Snow.lua | 19 | 4780 | -----------------------------------
-- Area: Qufim Island
-- NPC: Trodden Snow
-- Mission: ASA - THAT_WHICH_CURDLES_BLOOD
-- Mission: ASA - SUGAR_COATED_DIRECTIVE
-- @zone 126
-- @pos -19 -17 104
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Qufim_Island/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Enfeebling Kit
if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD) then
local item = 0;
local asaStatus = player:getVar("ASA_Status");
-- TODO: Other Enfeebling Kits
if (asaStatus == 0) then
item = 2779;
else
printf("Error: Unknown ASA Status Encountered <%u>", asaStatus);
end
if (trade:getItemCount() == 1 and trade:hasItemQty(item,1)) then
player:tradeComplete();
player:startEvent(0x002c);
end
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
--ASA 4 CS: Triggers With At Least 3 Counterseals.
if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE) then
local completedSeals = 0;
if (player:hasKeyItem(AMBER_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(AZURE_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(CERULEAN_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(EMERALD_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(SCARLET_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (player:hasKeyItem(VIOLET_COUNTERSEAL)) then
completedSeals = completedSeals + 1;
end;
if (completedSeals >= 3) then
player:setVar("ASA_Status", completedSeals);
player:startEvent(0x002d);
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==0x002c) then
player:addKeyItem(DOMINAS_SCARLET_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_SCARLET_SEAL);
player:addKeyItem(DOMINAS_CERULEAN_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_CERULEAN_SEAL);
player:addKeyItem(DOMINAS_EMERALD_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_EMERALD_SEAL);
player:addKeyItem(DOMINAS_AMBER_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AMBER_SEAL);
player:addKeyItem(DOMINAS_VIOLET_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_VIOLET_SEAL);
player:addKeyItem(DOMINAS_AZURE_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AZURE_SEAL);
player:completeMission(ASA,THAT_WHICH_CURDLES_BLOOD);
player:addMission(ASA,SUGAR_COATED_DIRECTIVE);
player:setVar("ASA_Status",0);
player:setVar("ASA4_Amber","0");
player:setVar("ASA4_Azure","0");
player:setVar("ASA4_Cerulean","0");
player:setVar("ASA4_Emerald","0");
player:setVar("ASA4_Scarlet","0");
player:setVar("ASA4_Violet","0");
elseif (csid==0x002d) then
local completedSeals = player:getVar("ASA_Status");
-- Calculate Reward
if (completedSeals == 3) then
player:addGil(GIL_RATE*3000);
elseif (completedSeals == 4) then
player:addGil(GIL_RATE*10000);
elseif (completedSeals == 5) then
player:addGil(GIL_RATE*30000);
elseif (completedSeals == 6) then
player:addGil(GIL_RATE*50000);
end
-- Clean Up Remaining Key Items
player:delKeyItem(DOMINAS_SCARLET_SEAL);
player:delKeyItem(DOMINAS_CERULEAN_SEAL);
player:delKeyItem(DOMINAS_EMERALD_SEAL);
player:delKeyItem(DOMINAS_AMBER_SEAL);
player:delKeyItem(DOMINAS_VIOLET_SEAL);
player:delKeyItem(DOMINAS_AZURE_SEAL);
player:delKeyItem(SCARLET_COUNTERSEAL);
player:delKeyItem(CERULEAN_COUNTERSEAL);
player:delKeyItem(EMERALD_COUNTERSEAL);
player:delKeyItem(AMBER_COUNTERSEAL);
player:delKeyItem(VIOLET_COUNTERSEAL);
player:delKeyItem(AZURE_COUNTERSEAL);
-- Advance Mission
player:completeMission(ASA,SUGAR_COATED_DIRECTIVE);
player:addMission(ASA,ENEMY_OF_THE_EMPIRE_I);
player:setVar("ASA_Status",0);
end
end; | gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Kazham/npcs/Kobhi_Sarhigamya.lua | 34 | 1061 | ----------------------------------
-- Area: Kazham
-- NPC: Kobhi Sarhigamya
-- Type: Item Deliverer
-- @zone: 250
-- @pos -115.29 -11 -22.609
--
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
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 |
gedadsbranch/Darkstar-Mission | scripts/zones/Lower_Jeuno/npcs/Navisse.lua | 34 | 4871 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Navisse
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
require("scripts/globals/pathfind");
local path = {
-- -59.562683, 6.000051, -90.890404,
-58.791367, 6.000050, -91.663391,
-58.021465, 6.000049, -92.432144,
-58.729881, 6.000051, -91.577568,
-60.351879, 6.000053, -89.835815,
-61.099354, 6.000054, -89.034248,
-61.841427, 5.999946, -88.238564,
-62.769325, 5.999948, -87.244301,
-61.750378, 5.999948, -87.684868,
-60.796600, 5.999947, -88.208214,
-55.475166, 5.999943, -91.271210,
-56.590668, 5.999943, -91.245201,
-57.651192, 6.000052, -91.002350,
-64.134392, 6.000052, -89.460915,
-63.261021, 6.000051, -90.107605,
-62.330879, 6.000051, -90.679604,
-61.395359, 6.000050, -91.235107,
-56.591644, 6.000047, -94.066406,
-57.208908, 6.000048, -93.245895,
-57.934330, 6.000049, -92.435081,
-59.788624, 6.000052, -90.439583,
-61.832211, 5.999946, -88.248795,
-62.574249, 5.999948, -87.453148,
-61.832058, 5.999946, -88.248627,
-61.089920, 6.000054, -89.044273,
-60.348049, 6.000053, -89.840111,
-59.043877, 6.000051, -91.238251,
-58.301846, 6.000050, -92.033958,
-57.467026, 6.000048, -92.929070,
-56.536987, 6.000047, -93.926826,
-57.528469, 6.000047, -93.482582,
-58.476944, 6.000048, -92.949654,
-59.416409, 6.000049, -92.400879,
-64.235306, 6.000051, -89.563835,
-64.000816, 6.000054, -88.482338,
-63.516331, 5.999947, -87.539917,
-62.444843, 5.999948, -87.352570,
-61.468765, 5.999947, -87.831436,
-60.520329, 5.999947, -88.364532,
-55.100037, 5.999943, -91.488144,
-56.063160, 5.999944, -90.932312,
-62.719467, 5.999948, -87.093468,
-62.064899, 5.999947, -87.960884,
-61.338562, 5.999946, -88.770836,
-59.579746, 6.000052, -90.663826,
-58.177391, 6.000050, -92.167343,
-57.435341, 6.000048, -92.963005,
-56.734436, 6.000047, -93.714989,
-57.492855, 6.000049, -92.901787,
-58.251190, 6.000050, -92.088486,
-59.364170, 6.000051, -90.894829,
-61.039413, 6.000054, -89.098907,
-61.784184, 5.999946, -88.300293,
-62.804745, 5.999948, -87.206451,
-60.463631, 6.000053, -89.715942,
-59.721657, 6.000052, -90.511711,
-58.974190, 6.000051, -91.313248,
-58.232239, 6.000050, -92.109024,
-56.840717, 6.000047, -93.600716,
-57.914623, 6.000048, -93.276276,
-58.855755, 6.000048, -92.730408,
-64.140175, 6.000051, -89.619812,
-63.025597, 6.000052, -89.751106,
-61.954758, 6.000052, -89.984474,
-60.887684, 6.000052, -90.234573,
-55.190853, 5.999943, -91.590721,
-55.368877, 6.000050, -92.667923,
-55.841885, 6.000048, -93.664970,
-56.916370, 6.000048, -93.400879,
-57.705578, 6.000049, -92.652748,
-58.456089, 6.000050, -91.865067,
-60.405739, 6.000053, -89.778008,
-61.147854, 6.000054, -88.982376,
-61.889904, 5.999946, -88.186691,
-62.637497, 5.999948, -87.385239,
-63.643429, 6.000055, -87.880524,
-64.248825, 6.000053, -88.784004,
-63.455921, 6.000052, -89.526733,
-62.418514, 6.000052, -89.852493,
-61.363335, 6.000052, -90.117607,
-55.142048, 5.999943, -91.602325,
-55.358624, 6.000050, -92.679016,
-55.842934, 6.000048, -93.675148,
-56.919590, 6.000048, -93.408241,
-57.710354, 6.000049, -92.649918,
-58.459896, 6.000050, -91.861336,
-60.409424, 6.000053, -89.774185,
-61.151508, 6.000054, -88.978500,
-62.848709, 5.999948, -87.159264,
-61.829231, 5.999948, -87.629791,
-60.951675, 5.999947, -88.117493,
-55.395309, 5.999943, -91.317513,
-56.522537, 5.999943, -91.263893,
-57.586517, 6.000052, -91.018196,
-64.081299, 6.000052, -89.473526,
-63.209583, 6.000051, -90.135269,
-62.270042, 6.000050, -90.714821,
-61.334797, 6.000050, -91.270729,
-56.586208, 6.000047, -94.069595,
-64.130554, 6.000051, -89.625450,
-56.496498, 6.000047, -94.122322,
-57.173595, 6.000048, -93.271568,
-57.904095, 6.000049, -92.465279,
-59.571453, 6.000052, -90.672951,
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0099);
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
npc:wait(0);
end;
| gpl-3.0 |
hooksta4/darkstar | scripts/zones/zones/Labyrinth_of_Onzozo/Zone.lua | 2 | 1836 | -----------------------------------
--
-- Zone: Labyrinth_of_Onzozo (213)
--
-----------------------------------
package.loaded["scripts/zones/Labyrinth_of_Onzozo/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Labyrinth_of_Onzozo/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17649898,17649899,17649900};
SetGroundsTome(tomes);
-- Mysticmaker Profblix
SetRespawnTime(17649693, 900, 10800);
UpdateTreasureSpawnPoint(17649896);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-58.808,-21.364,-286.654,190);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
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 |
legonia/mr.robot | plugins/banhammer.lua | 214 | 11956 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
local bots_protection = "Yes"
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = ''
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if member_id == our_id then return false end
if get_cmd == 'kick' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
return unbanall_user(member_id, chat_id)
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
local receiver = get_receiver(msg)
if matches[1]:lower() == 'kickme' then-- /kickme
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return nil
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'ban'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
return
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unban'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'kick'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'banall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unbanall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
hooksta4/darkstar | scripts/zones/Lower_Jeuno/npcs/Tuh_Almobankha.lua | 2 | 3751 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Tuh Almobankha
-- Title Change NPC
-- @pos -14 0 -61 245
-----------------------------------
require("scripts/globals/titles");
local title2 = { BROWN_MAGE_GUINEA_PIG , BROWN_MAGIC_BYPRODUCT , RESEARCHER_OF_CLASSICS , TORCHBEARER , FORTUNETELLER_IN_TRAINING ,
CHOCOBO_TRAINER , CLOCK_TOWER_PRESERVATIONIST , LIFE_SAVER , CARD_COLLECTOR , TWOS_COMPANY , TRADER_OF_ANTIQUITIES , GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN ,
TENSHODO_MEMBER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title3 = { ACTIVIST_FOR_KINDNESS , ENVOY_TO_THE_NORTH , EXORCIST_IN_TRAINING , FOOLS_ERRAND_RUNNER , STREET_SWEEPER ,
MERCY_ERRAND_RUNNER , BELIEVER_OF_ALTANA , TRADER_OF_MYSTERIES , WANDERING_MINSTREL , ANIMAL_TRAINER , HAVE_WINGS_WILL_FLY ,
ROD_RETRIEVER , DESTINED_FELLOW , TROUPE_BRILIOTH_DANCER , PROMISING_DANCER , STARDUST_DANCER ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title4 = { TIMEKEEPER , BRINGER_OF_BLISS , PROFESSIONAL_LOAFER , TRADER_OF_RENOWN , HORIZON_BREAKER , SUMMIT_BREAKER ,
BROWN_BELT , DUCAL_DUPE , CHOCOBO_LOVE_GURU , PICKUP_ARTIST , WORTHY_OF_TRUST , A_FRIEND_INDEED , CHOCOROOKIE , CRYSTAL_STAKES_CUPHOLDER ,
WINNING_OWNER , VICTORIOUS_OWNER , TRIUMPHANT_OWNER , HIGH_ROLLER , FORTUNES_FAVORITE , CHOCOCHAMPION ,
0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title5 = { PARAGON_OF_BEASTMASTER_EXCELLENCE , PARAGON_OF_BARD_EXCELLENCE , SKY_BREAKER , BLACK_BELT , GREEDALOX , CLOUD_BREAKER ,
STAR_BREAKER , ULTIMATE_CHAMPION_OF_THE_WORLD , DYNAMISJEUNO_INTERLOPER , DYNAMISBEAUCEDINE_INTERLOPER , DYNAMISXARCABARD_INTERLOPER ,
DYNAMISQUFIM_INTERLOPER , CONQUEROR_OF_FATE , SUPERHERO , SUPERHEROINE , ELEGANT_DANCER , DAZZLING_DANCE_DIVA , GRIMOIRE_BEARER ,
FELLOW_FORTIFIER , BUSHIN_ASPIRANT , BUSHIN_RYU_INHERITOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title6 = { GRAND_GREEDALOX , SILENCER_OF_THE_ECHO , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x271E,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil());
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==0x271E) then
if (option > 0 and option <29) then
if (player:delGil(400)) then
player:setTitle( title2[option] )
end
elseif (option > 256 and option <285) then
if (player:delGil(500)) then
player:setTitle( title3[option - 256] )
end
elseif (option > 512 and option < 541) then
if (player:delGil(600)) then
player:setTitle( title4[option - 512] )
end
elseif (option > 768 and option <797) then
if (player:delGil(700)) then
player:setTitle( title5[option - 768] )
end
elseif (option > 1024 and option < 1053) then
if (player:delGil(800)) then
player:setTitle( title6[option - 1024] )
end
end
end
end; | gpl-3.0 |
hooksta4/darkstar | scripts/zones/zones/Selbina/npcs/Nomad_Moogle.lua | 4 | 1055 | -----------------------------------
--
-- Nomad Moogle
--
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,NOMAD_MOOGLE_DIALOG);
player:sendMenu(1);
end;
-----------------------------------
-- onEventUpdate Action
-----------------------------------
function onEventUpdate(player,csid,option)
--print("onEventUpdate");
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("onEventFinish");
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Castle_Zvahl_Baileys/npcs/Treasure_Chest.lua | 12 | 3200 | -----------------------------------
-- Area: Castle Zvahl Baileys
-- NPC: Treasure Chest
-- @zone 161
-----------------------------------
package.loaded["scripts/zones/Castle_Zvahl_Baileys/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Castle_Zvahl_Baileys/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1048,1); -- Treasure Key
-- trade:hasItemQty(1115,1); -- Skeleton Key
-- trade:hasItemQty(1023,1); -- Living Key
-- trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if((trade:hasItemQty(1048,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: keyitem -----------
if(player:getQuestStatus(BASTOK,A_TEST_OF_TRUE_LOVE) == QUEST_ACCEPTED and player:hasKeyItem(UN_MOMENT) == false) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if(pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if(success ~= -2) then
player:tradeComplete();
if(math.random() <= success) then -- 0 or 1
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if(questItemNeeded == 1) then
player:setVar("ATestOfTrueLoveProgress",player:getVar("ATestOfTrueLoveProgress")+1);
player:addKeyItem(UN_MOMENT);
player:messageSpecial(KEYITEM_OBTAINED,UN_MOMENT); -- Un moment for A Test Of True Love quest
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if(loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1048);
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 |
hooksta4/darkstar | scripts/globals/spells/slow.lua | 18 | 1498 | -----------------------------------------
-- Spell: Slow
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-- Slow's potency is calculated with the formula (150 + dMND*2)/1024, and caps at 300/1024 (~29.3%).
-- And MND of 75 is neccessary to reach the hardcap of Slow.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND));
--Power.
local power = 150 + dMND * 2;
if (power > 300) then
power = 300;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
power = power * 2;
end
--Duration, including resistance.
local duration = 120 * applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_SLOW);
if (duration >= 60) then --Do it!
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
if (target:addStatusEffect(EFFECT_SLOW,power,0,duration, 0, 1)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
return EFFECT_SLOW;
end; | gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/globals/items/chunk_of_homemade_cheese.lua | 35 | 1208 | -----------------------------------------
-- ID: 5225
-- Item: chunk_of_homemade_cheese
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 10
-- Defense 40
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5225);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_DEF, 40);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_DEF, 40);
end;
| gpl-3.0 |
lohool/OLA | Ola/wax/stdlib/helpers/cache.lua | 1 | 2065 | wax.cache = {}
setmetatable(wax.cache, wax.cache)
-- Returns contents of cache keys
-- key: string # value for cache
-- maxAge: number (optional) # max age of file in seconds
function wax.cache.get(key, maxAge)
local path = wax.cache.pathFor(key)
if not wax.filesystem.isFile(path) then return nil end
if maxAge then
local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
if fileAge > maxAge then
return nil
end
end
local success, result = pcall(function()
return NSKeyedUnarchiver:unarchiveObjectWithFile(path)
end)
if not success then -- Bad cache
puts("Error: Couldn't read cache with key %s", key)
wax.cache.clear(key)
return nil
else
return result
end
end
-- Creates a cache for the key with contents
-- key: string # value for the cache
-- contents: object # whatever is NSKeyedArchive compatible
function wax.cache.set(key, contents)
local path = wax.cache.pathFor(key)
if not contents then -- delete the value from the cache
wax.cache.clear(key)
else
local success = NSKeyedArchiver:archiveRootObject_toFile(contents, path)
if not success then puts("Couldn't archive cache '%s' to '%s'", key, path) end
end
end
function wax.cache.age(key)
local path = wax.cache.pathFor(key)
-- If there is no file, just send them back a really big age. Cleaner than
-- dealing with nils
if not wax.filesystem.isFile(path) then return wax.time.days(1000) end
local fileAge = os.time() - wax.filesystem.attributes(path).modifiedAt
return fileAge
end
-- Removes specific keys from cache
function wax.cache.clear(...)
for i, key in ipairs({...}) do
local path = wax.cache.pathFor(key)
wax.filesystem.delete(path)
end
end
-- Removes entire cache dir
function wax.cache.clearAll()
wax.filesystem.delete(NSCacheDirectory)
wax.filesystem.createDir(NSCacheDirectory)
end
function wax.cache.pathFor(key)
return NSCacheDirectory .. "/" .. wax.base64.encode(key)
end | mit |
snabbco/snabb | lib/pflua/src/pf/regalloc.lua | 4 | 16429 | -- Implements register allocation for pflua's native backend
--
-- Follows the algorithm described in:
-- "Linear scan register allocation"
-- Poletto and Sarkar
-- https://dl.acm.org/citation.cfm?id=330250
--
-- The result of register allocation is a table that describes
-- the register allocated for the given virtual registers, e.g.:
--
-- { v1 = 1, -- %rcx
-- v2 = 2, -- %rdx
-- r3 = 0, -- %rax
-- len = 6, -- %rsi
-- callee_saves = {},
-- spills = { v3 = 0, v4 = 1 },
-- spill_registers = { 3, 4 }
-- }
--
-- The callee_saves field lists the callee-save registers that are
-- used in the allocation. This lets the code generation pass easily
-- generate any push/pops that are needed.
--
-- Register numbers are based on DynASM's Rq() register mapping.
--
-- The following registers are reserved and not allocated:
-- * %rdi to store the packet pointer argument
--
-- The allocator should first prioritize using caller-save registers
-- * %rax, %rcx, %rdx, %r8-%r11
--
-- before using callee-save registers
-- * %rbx, %r12-%r15
--
-- The spills and spill_registers fields are used for spilling registers
-- to memory if that becomes necessary. When the first register is spilled,
-- two additional registers are spilled (and put into spill_registers) so
-- that they can be used to move data from/to memory and registers.
--
-- The spills field keeps track of the stack slots (numbered from 0)
-- that are used for spilled registers. Variables should only be mapped
-- in one of the main allocation table or in the spills table.
module(...,package.seeall)
local utils = require('pf.utils')
local verbose = os.getenv("PF_VERBOSE");
-- returns the registers that a given instruction reads
local function reads_from(instr)
local itype = instr[1]
local function maybe_reg(reg)
if type(reg) == "number" then
return nil
else
return reg
end
end
if itype == "mov" or itype == "mov64" then
return { maybe_reg(instr[3]) }
elseif itype == "ntohs" or itype == "ntohl" or itype == "uint32" then
return { instr[2] }
elseif itype == "cjmp" or itype == "jmp" or itype == "ret-true" or
itype == "ret-false" or itype == "nop" or itype == "label" then
return {}
else
-- instructions don't have immediates in the first arg
return { instr[2], maybe_reg(instr[3]) }
end
end
-- Update the ends of intervals based on variable occurrences in
-- the "control" ast
local function find_live_in_control(label, control, intervals)
-- the head of an ast is always an operation name, so skip
for i = 2, #control do
local ast_type = type(control[i])
if ast_type == "string" then
for _, interval in ipairs(intervals) do
if control[i] == interval.name then
interval.finish = label
end
end
elseif ast_type == "table" then
find_live_in_control(label, control[i], intervals)
end
end
end
-- The lack of loops and unique register names for each load
-- in the instruction IR makes finding live intervals easy.
--
-- A live interval is a table
-- { name = String, start = number, finish = number }
--
-- The start and finish fields are indices into the instruction
-- array
--
local function live_intervals(instrs)
local len = { name = "len", start = 1, finish = 1 }
local order = { len }
local intervals = { len = len }
for idx, instr in ipairs(instrs) do
local itype = instr[1]
-- movs and loads are the only instructions that result in
-- new live intervals
if itype == "load" or itype == "mov" or itype == "mov64" then
local name = instr[2]
local interval = { name = name,
start = idx,
finish = idx }
intervals[name] = interval
table.insert(order, interval)
end
for _, reg in ipairs(reads_from(instr)) do
intervals[reg].finish = idx
end
end
-- we need the resulting allocations to be ordered by starting
-- point, so we emit the ordered sequence rather than the map
return order
end
-- Check if a register is free in the freelist
local function is_free(seq, reg)
for _, val in ipairs(seq) do
if val == reg then
return true
end
end
return false
end
-- Remove the given register from the freelist
local function remove_free(freelist, reg)
for idx, reg2 in ipairs(freelist) do
if reg2 == reg then
table.remove(freelist, idx)
return
end
end
end
-- Insert an interval sorted by increasing finish
local function insert_active(active, interval)
local finish = interval.finish
for idx, interval2 in ipairs(active) do
if interval2.finish > finish then
table.insert(active, idx, interval)
return
end
end
table.insert(active, interval)
end
-- Optimize movs from a register to the same one
local function delete_useless_movs(ir, alloc)
for idx, instr in ipairs(ir) do
if instr[1] == "mov" then
if alloc[instr[2]] == alloc[instr[3]] then
-- It's faster just to convert these to
-- nops than to re-number the table
ir[idx] = { "nop" }
end
end
end
end
-- All available registers, tied to unix x64 ABI
x86_regs = {
caller_regs = {11, 10, 9, 8, 6, 2, 1, 0},
callee_regs = {15, 14, 13, 12, 3},
len = 6 -- %rsi
}
-- Do register allocation with the given IR
-- Returns a register allocation and potentially mutates
-- the ir for optimizations
function allocate(ir, regs)
regs = regs or x86_regs
local intervals = live_intervals(ir)
local active = {}
local next_spill = 0
-- caller-save registers, use these first
local free_caller = utils.dup(regs.caller_regs)
-- callee-save registers, if we have to
local free_callee = utils.dup(regs.callee_regs)
local allocation = { len = regs.len,
callee_saves = {},
spills = {} }
remove_free(free_caller, allocation.len)
local function expire_old(interval)
local to_expire = {}
for idx, active_interval in ipairs(active) do
if active_interval.finish > interval.start then
break
else
local name = active_interval.name
local reg = allocation[name]
table.insert(to_expire, idx)
-- figure out which free list this register is supposed to be on
if is_free(regs.caller_regs, reg) then
table.insert(free_caller, reg)
elseif is_free(regs.callee_regs, reg) then
table.insert(free_callee, reg)
else
error("unknown register")
end
end
end
for i=1, #to_expire do
table.remove(active, to_expire[#to_expire - i + 1])
end
end
local function spill_at(interval)
-- when there's a first spill, pick two additional variables
-- to spill to the stack and reserve their registers for accessing
-- spilled variables via movs
if next_spill == 0 then
local i1, i2 = active[#active], active[#active-1]
local reg1 = allocation[i1.name]
local reg2 = allocation[i2.name]
table.remove(active); table.remove(active)
allocation[i1.name] = nil
allocation[i2.name] = nil
allocation.spills[i1.name] = 0
allocation.spills[i2.name] = 1
allocation.spill_registers = { reg1, reg2 }
next_spill = next_spill + 2
end
local to_spill = active[#active]
if to_spill.finish > interval.finish then
allocation[interval.name] = allocation[to_spill.name]
allocation[to_spill.name] = nil
allocation.spills[to_spill.name] = next_spill
table.remove(active)
insert_active(active, interval)
else
allocation.spills[interval.name] = next_spill
end
next_spill = next_spill + 1
end
for _, interval in pairs(intervals) do
local name = interval.name
expire_old(interval)
-- because we prefill some registers, check first if
-- we need to allocate for this interval
if not allocation[name] then
if #free_caller == 0 and #free_callee == 0 then
spill_at(interval)
-- newly freed registers are put at the end, so allocating from
-- the end will tend to produce better results since we want to
-- try eliminate movs with the same destination/source register
elseif #free_caller ~= 0 then
allocation[name] = free_caller[#free_caller]
table.remove(free_caller)
insert_active(active, interval)
else
local idx = #free_callee
allocation[name] = free_callee[idx]
allocation.callee_saves[free_callee[idx]] = true
table.remove(free_callee)
insert_active(active, interval)
end
else
insert_active(active, interval)
end
end
delete_useless_movs(ir, allocation)
if verbose then
utils.pp({ "register_allocation", allocation })
end
return allocation
end
function selftest()
local function test(instrs, expected)
utils.assert_equals(expected, live_intervals(instrs))
end
-- part of `tcp`, see pf.selection
local example_1 =
{ { "label", 0 },
{ "cmp", "len", 34 },
{ "cjmp", "<", 4 },
{ "label", 3 },
{ "load", "v1", 12, 2 },
{ "cmp", "v1", 8 },
{ "cjmp", "!=", 6 },
{ "label", 5 },
{ "load", "r1", 23, 1 },
{ "cmp", "r1", 6 },
{ "cjmp", "=", "true-label" },
{ "ret-false" },
{ "label", 6 },
{ "cmp", "len", 54 },
{ "cjmp", "<", 8 },
{ "label", 7 },
{ "cmp", "v1", 56710 },
{ "cjmp", "!=", 10 },
{ "label", 9 },
{ "load", "v2", 20, 1 },
{ "cmp", "v2", 6 },
{ "cjmp", "!=", 12 } }
local example_2 =
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "mov", "r3", "r1" },
{ "mul", "r3", "r2" },
{ "cmp", "r3", 1 },
{ "cjmp", "!=", 4 },
{ "cmp", "len", 1 } }
-- this example isn't from real code, but tests what happens when
-- there is higher register pressure
local example_3 =
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "load", "r3", 15, 2 },
{ "load", "r4", 16, 2 },
{ "load", "r5", 17, 2 },
{ "load", "r6", 18, 2 },
{ "load", "r7", 19, 2 },
{ "load", "r8", 20, 2 },
{ "load", "r9", 21, 2 },
{ "cmp", "r1", 1 },
{ "cmp", "r2", 1 },
{ "cmp", "r3", 1 },
{ "cmp", "r4", 1 },
{ "cmp", "r5", 1 },
{ "cmp", "r6", 1 },
{ "cmp", "r7", 1 },
{ "cmp", "r8", 1 },
{ "cmp", "r9", 1 } }
-- test that tries to make movs use same dst/src
local example_4 =
{ { "label", 1 },
{ "load", "v1", 12, 2 },
{ "cmp", "v1", 1 },
{ "load", "r1", 12, 2 },
{ "mov", "r2", "r1" },
{ "cmp", "r2", 1 },
{ "cmp", "len", 1 } }
-- full `tcp` example from more recent instruction selection
local example_5 =
{ { "label", 0 },
{ "cmp", "len", 34 },
{ "cjmp", "<", 4 },
{ "label", 3 },
{ "load", "r1", 12, 2 },
{ "mov", "v1", "r1" },
{ "cmp", "v1", 8 },
{ "cjmp", "!=", 6 },
{ "label", 5 },
{ "load", "r2", 23, 1 },
{ "cmp", "r2", 6 },
{ "cjmp", "=", "true-label" },
{ "ret-false" },
{ "label", 6 },
{ "cmp", "len", 54 },
{ "cjmp", "<", 8 },
{ "label", 7 },
{ "cmp", "v1", 56710 },
{ "cjmp", "!=", 10 },
{ "label", 9 },
{ "load", "r3", 20, 1 },
{ "mov", "v2", "r3" },
{ "cmp", "v2", 6 },
{ "cjmp", "!=", 12 },
{ "label", 11 },
{ "ret-true" },
{ "label", 12 },
{ "cmp", "len", 55 },
{ "cjmp", "<", 14 },
{ "label", 13 },
{ "cmp", "v2", 44 },
{ "cjmp", "!=", 16 },
{ "label", 15 },
{ "load", "r4", 54, 1 },
{ "cmp", "r4", 6 },
{ "cjmp", "=", "true-label" },
{ "ret-false" },
{ "label", 16 },
{ "ret-false" },
{ "label", 14 },
{ "ret-false" },
{ "label", 10 },
{ "ret-false" },
{ "label", 8 },
{ "ret-false" },
{ "label", 4 },
{ "ret-false" } }
-- test that variables in load offsets are properly accounted for
local example_6 =
{ { "label", 0 },
{ "mov", "r1", 5 },
{ "load", "v2", 12, 2 },
{ "load", "v1", "r1", 2 },
{ "cmp", "v1", 1 },
{ "cmp", "v2", 2 } }
-- another test with high register pressure, should be high enough
-- to require spilling
local example_7 =
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "load", "r3", 15, 2 },
{ "load", "r4", 16, 2 },
{ "load", "r5", 17, 2 },
{ "load", "r6", 18, 2 },
{ "load", "r7", 19, 2 },
{ "load", "r8", 20, 2 },
{ "load", "r9", 21, 2 },
{ "load", "r10", 22, 2 },
{ "load", "r11", 23, 2 },
{ "load", "r12", 24, 2 },
{ "load", "r13", 25, 2 },
{ "load", "r14", 26, 2 },
{ "cmp", "r1", 1 },
{ "cmp", "r2", 1 },
{ "cmp", "r3", 1 },
{ "cmp", "r4", 1 },
{ "cmp", "r5", 1 },
{ "cmp", "r6", 1 },
{ "cmp", "r7", 1 },
{ "cmp", "r8", 1 },
{ "cmp", "r9", 1 },
{ "cmp", "r10", 1 },
{ "cmp", "r11", 1 },
{ "cmp", "r12", 1 },
{ "cmp", "r13", 1 },
{ "cmp", "r14", 1 } }
test(example_1,
{ { name = "len", start = 1, finish = 14 },
{ name = "v1", start = 5, finish = 17 },
{ name = "r1", start = 9, finish = 10 },
{ name = "v2", start = 20, finish = 21 } })
test(example_2,
{ { name = "len", start = 1, finish = 8 },
{ name = "r1", start = 2, finish = 4 },
{ name = "r2", start = 3, finish = 5 },
{ name = "r3", start = 4, finish = 6 } })
test(example_5,
{ { name = "len", start = 1, finish = 28 },
{ name = "r1", start = 5, finish = 6 },
{ name = "v1", start = 6, finish = 18 },
{ name = "r2", start = 10, finish = 11 },
{ name = "r3", start = 21, finish = 22 },
{ name = "v2", start = 22, finish = 31 },
{ name = "r4", start = 34, finish = 35 } })
test(example_6,
{ { name = "len", start = 1, finish = 1 },
{ name = "r1", start = 2, finish = 4 },
{ name = "v2", start = 3, finish = 6 },
{ name = "v1", start = 4, finish = 5 } })
local function test(instrs, expected)
utils.assert_equals(expected, allocate(instrs))
end
test(example_1,
{ v1 = 0, r1 = 1, len = 6, v2 = 0,
callee_saves = {}, spills = {} })
-- mutates example_2
test(example_2,
{ r1 = 0, r2 = 1, r3 = 0, len = 6,
callee_saves = {}, spills = {} })
utils.assert_equals(example_2,
{ { "label", 1 },
{ "load", "r1", 12, 2 },
{ "load", "r2", 14, 2 },
{ "nop" },
{ "mul", "r3", "r2" },
{ "cmp", "r3", 1 },
{ "cjmp", "!=", 4 },
{ "cmp", "len", 1 } })
test(example_3,
{ r1 = 6, r2 = 0, r3 = 1, r4 = 2, r5 = 8, r6 = 9,
r7 = 10, r8 = 11, r9 = 3, len = 6,
callee_saves = utils.set(3), spills = {} })
test(example_4,
{ v1 = 0, r1 = 0, len = 6, r2 = 0, callee_saves = {},
spills = {} })
test(example_5,
{ len = 6, r1 = 0, v1 = 0, r2 = 1, r3 = 0,
v2 = 0, r4 = 0, callee_saves = {},
spills = {} })
test(example_7,
{ r1 = 6, r2 = 0, r3 = 1, r4 = 2, r5 = 8, r6 = 9,
r7 = 10, r8 = 11, r9 = 3, r10 = 12, r11 = 13,
spills = { r12 = 1, r13 = 0, r14 = 2 },
len = 6, callee_saves = utils.set(3, 12, 13, 14, 15),
spill_registers = { 15, 14 } })
end
| apache-2.0 |
AnySDK/Sample_Lua | src/AdTracking.lua | 1 | 2268 | require "ClassBase"
local adtracking_plugin = nil
AdTracking = class()
function AdTracking:ctor()
adtracking_plugin = AgentManager:getInstance():getAdTrackingPlugin()
end
function AdTracking:onRegister()
if adtracking_plugin ~= nil then
adtracking_plugin:onRegister("userid")
end
end
function AdTracking:onLogin()
if adtracking_plugin ~= nil then
local paramMap = {
User_Id = "123456",
Role_Id = "test",
Role_Name = "test"
}
adtracking_plugin:onLogin(paramMap)
end
end
function AdTracking:onPay()
if adtracking_plugin ~= nil then
local date = os.date("%Y-%m-%d %H:%M:%S");
local paramMap = {
User_Id = "123456",
Order_Id = tostring(date),
Currency_Amount = "5",
Currency_Type ="CNY",
Payment_Type = "test",
Payment_Time = tostring(date)
};
adtracking_plugin:onPay(paramMap)
end
end
function AdTracking:trackEvent()
if adtracking_plugin ~= nil then
adtracking_plugin:trackEvent("event_1")
adtracking_plugin:trackEvent("event_2")
adtracking_plugin:trackEvent("onCustEvent1")
adtracking_plugin:trackEvent("onCustEvent2")
end
end
function AdTracking:onCreateRole()
if adtracking_plugin ~= nil and adtracking_plugin:isFunctionSupported("onCreateRole") then
local paramMap = {
User_Id = "123456",
Role_Id = "test",
Role_Name = "test"
}
adtracking_plugin:trackEvent("onCreateRole", paramMap)
end
end
function AdTracking:onLevelUp()
if adtracking_plugin ~= nil and adtracking_plugin:isFunctionSupported("onLevelUp") then
local paramMap = {
User_Id = "123456",
Role_Id = "test",
Role_Name = "test",
Level = "10"
}
adtracking_plugin:trackEvent("onLevelUp", paramMap)
end
end
function AdTracking:onStartToPay()
if adtracking_plugin ~= nil and adtracking_plugin:isFunctionSupported("onStartToPay") then
local date=os.date("%Y-%m-%d %H:%M:%S");
local paramMap = {
User_Id = "123456",
Order_Id = tostring(date),
Currency_Amount = "5",
Currency_Type ="CNY",
Payment_Type = "test",
Payment_Time = tostring(date)
};
adtracking_plugin:trackEvent("onStartToPay", paramMap)
end
end | mit |
hooksta4/darkstar | scripts/zones/zones/Sacrarium/npcs/Large_Keyhole.lua | 2 | 1419 | -----------------------------------
-- Area: Sacrarium
-- NPC: Large Keyhole
-- Notes: Used to open R. Gate
-- @pos 100.231 -1.414 51.700 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local LargeKeyholeID = npc:getID();
local DoorID = GetNPCByID(LargeKeyholeID):getID() - 2;
if (player:hasKeyItem(TEMPLE_KNIGHT_KEY)) then
GetNPCByID(DoorID):openDoor(15);
else
player:messageSpecial(LARGE_KEYHOLE);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local Timemax=GetServerVariable("SACRARIUM_Coral_Key_trade")+10;
local CurentTime=os.time();
local LargeKeyholeID = npc:getID();
local DoorID = GetNPCByID(LargeKeyholeID):getID() - 2;
if (trade:hasItemQty(1658,1) and trade:getItemCount() == 1) then
if (CurentTime < Timemax) then
GetNPCByID(DoorID):openDoor(15);
SetServerVariable("SACRARIUM_Coral_Key_trade",0);
end
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Kazham/npcs/HomePoint#1.lua | 12 | 1238 | -----------------------------------
-- Area: Kazham
-- NPC: HomePoint#1
-- @pos 77.654 -13.000 -94.457 250
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Kazham/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 39);
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 == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
prosody-modules/import2 | mod_incidents_handling/incidents_handling/incidents_handling.lib.lua | 32 | 16333 | -- This contains the auxiliary functions for the Incidents Handling module.
-- (C) 2012-2013, Marco Cirillo (LW.Org)
local pairs, ipairs, os_date, string, table, tonumber = pairs, ipairs, os.date, string, table, tonumber
local dataforms_new = require "util.dataforms".new
local st = require "util.stanza"
local xmlns_inc = "urn:xmpp:incident:2"
local xmlns_iodef = "urn:ietf:params:xml:ns:iodef-1.0"
local my_host = nil
-- // Util and Functions //
local function ft_str()
local d = os_date("%FT%T%z"):gsub("^(.*)(%+%d+)", function(dt, z)
if z == "+0000" then return dt.."Z" else return dt..z end
end)
return d
end
local function get_incident_layout(i_type)
local layout = {
title = (i_type == "report" and "Incident report form") or (i_type == "request" and "Request for assistance with incident form"),
instructions = "Started/Ended Time, Contacts, Sources and Targets of the attack are mandatory. See RFC 5070 for further format instructions.",
{ name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/commands" },
{ name = "name", type = "hidden", value = my_host },
{ name = "entity", type ="text-single", label = "Remote entity to query" },
{ name = "started", type = "text-single", label = "Incident Start Time" },
{ name = "ended", type = "text-single", label = "Incident Ended Time" },
{ name = "reported", type = "hidden", value = ft_str() },
{ name = "description", type = "text-single", label = "Description",
desc = "Description syntax is: <lang (in xml:lang format)> <short description>" },
{ name = "contacts", type = "text-multi", label = "Contacts",
desc = "Contacts entries format is: <address> <type> <role> - separated by new lines" },
{ name = "related", type = "text-multi", label = "Related Incidents",
desc = "Related incidents entries format is: <CSIRT's FQDN> <Incident ID> - separated by new lines" },
{ name = "impact", type = "text-single", label = "Impact Assessment",
desc = "Impact assessment format is: <severity> <completion> <type>" },
{ name = "sources", type = "text-multi", label = "Attack Sources",
desc = "Attack sources format is: <address> <category> <count> <count-type>" },
{ name = "targets", type = "text-multi", label = "Attack Targets",
desc = "Attack target format is: <address> <category> <noderole>" }
}
if i_type == "request" then
table.insert(layout, {
name = "expectation",
type = "list-single",
label = "Expected action from remote entity",
value = {
{ value = "nothing", label = "No action" },
{ value = "contact-sender", label = "Contact us, regarding the incident" },
{ value = "investigate", label = "Investigate the entities listed into the incident" },
{ value = "block-host", label = "Block the involved accounts" },
{ value = "other", label = "Other action, filling the description field is required" }
}})
table.insert(layout, { name = "description", type = "text-single", label = "Description" })
end
return dataforms_new(layout)
end
local function render_list(incidents)
local layout = {
title = "Stored Incidents List",
instructions = "You can select and view incident reports here, if a followup/response is possible it'll be noted in the step after selection.",
{ name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/commands" },
{
name = "ids",
type = "list-single",
label = "Stored Incidents",
value = {}
}
}
-- Render stored incidents list
for id in pairs(incidents) do
table.insert(layout[2].value, { value = id, label = id })
end
return dataforms_new(layout)
end
local function insert_fixed(t, item) table.insert(t, { type = "fixed", value = item }) end
local function render_single(incident)
local layout = {
title = string.format("Incident ID: %s - Friendly Name: %s", incident.data.id.text, incident.data.id.name),
instructions = incident.data.desc.text,
{ name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/commands" }
}
insert_fixed(layout, "Start Time: "..incident.data.start_time)
insert_fixed(layout, "End Time: "..incident.data.end_time)
insert_fixed(layout, "Report Time: "..incident.data.report_time)
insert_fixed(layout, "Contacts --")
for _, contact in ipairs(incident.data.contacts) do
insert_fixed(layout, string.format("Role: %s Type: %s", contact.role, contact.type))
if contact.jid then insert_fixed(layout, "--> JID: "..contact.jid..(contact.xmlns and ", XMLNS: "..contact.xmlns or "")) end
if contact.email then insert_fixed(layout, "--> E-Mail: "..contact.email) end
if contact.telephone then insert_fixed(layout, "--> Telephone: "..contact.telephone) end
if contact.postaladdr then insert_fixed(layout, "--> Postal Address: "..contact.postaladdr) end
end
insert_fixed(layout, "Related Activity --")
for _, related in ipairs(incident.data.related) do
insert_fixed(layout, string.format("Name: %s ID: %s", related.name, related.text))
end
insert_fixed(layout, "Assessment --")
insert_fixed(layout, string.format("Language: %s Severity: %s Completion: %s Type: %s",
incident.data.assessment.lang, incident.data.assessment.severity, incident.data.assessment.completion, incident.data.assessment.type))
insert_fixed(layout, "Sources --")
for _, source in ipairs(incident.data.event_data.sources) do
insert_fixed(layout, string.format("Address: %s Counter: %s", source.address.text, source.counter.value))
end
insert_fixed(layout, "Targets --")
for _, target in ipairs(incident.data.event_data.targets) do
insert_fixed(layout, string.format("For NodeRole: %s", (target.noderole.cat == "ext-category" and target.noderole.ext) or targets.noderole.cat))
for _, address in ipairs(target.addresses) do
insert_fixed(layout, string.format("---> Address: %s Type: %s", address.text, (address.cat == "ext-category" and address.ext) or address.cat))
end
end
if incident.data.expectation then
insert_fixed(layout, "Expected Action: "..incident.data.expectation.action)
if incident.data.expectation.desc then
insert_fixed(layout, "Expected Action Description: "..incident.data.expectation.desc)
end
end
if incident.type == "request" and incident.status == "open" then
table.insert(layout, { name = "response-datetime", type = "hidden", value = ft_str() })
table.insert(layout, { name = "response", type = "text-single", label = "Respond to the request" })
end
return dataforms_new(layout)
end
local function get_type(var, typ)
if typ == "counter" then
local count_type, count_ext = var, nil
if count_type ~= "byte" or count_type ~= "packet" or count_type ~= "flow" or count_type ~= "session" or
count_type ~= "alert" or count_type ~= "message" or count_type ~= "event" or count_type ~= "host" or
count_type ~= "site" or count_type ~= "organization" then
count_ext = count_type
count_type = "ext-type"
end
return count_type, count_ext
elseif typ == "category" then
local cat, cat_ext = var, nil
if cat ~= "asn" or cat ~= "atm" or cat ~= "e-mail" or cat ~= "ipv4-addr" or
cat ~= "ipv4-net" or cat ~= "ipv4-net-mask" or cat ~= "ipv6-addr" or cat ~= "ipv6-net" or
cat ~= "ipv6-net-mask" or cat ~= "mac" then
cat_ext = cat
cat = "ext-category"
end
return cat, cat_ext
elseif type == "noderole" then
local noderole_ext = nil
if cat ~= "client" or cat ~= "server-internal" or cat ~= "server-public" or cat ~= "www" or
cat ~= "mail" or cat ~= "messaging" or cat ~= "streaming" or cat ~= "voice" or
cat ~= "file" or cat ~= "ftp" or cat ~= "p2p" or cat ~= "name" or
cat ~= "directory" or cat ~= "credential" or cat ~= "print" or cat ~= "application" or
cat ~= "database" or cat ~= "infra" or cat ~= "log" then
noderole_ext = true
end
return noderole_ext
end
end
local function do_tag_mapping(tag, object)
if tag.name == "IncidentID" then
object.id = { text = tag:get_text(), name = tag.attr.name }
elseif tag.name == "StartTime" then
object.start_time = tag:get_text()
elseif tag.name == "EndTime" then
object.end_time = tag:get_text()
elseif tag.name == "ReportTime" then
object.report_time = tag:get_text()
elseif tag.name == "Description" then
object.desc = { text = tag:get_text(), lang = tag.attr["xml:lang"] }
elseif tag.name == "Contact" then
local jid = tag:get_child("AdditionalData").tags[1]
local email = tag:get_child("Email")
local telephone = tag:get_child("Telephone")
local postaladdr = tag:get_child("PostalAddress")
if not object.contacts then
object.contacts = {}
object.contacts[1] = {
role = tag.attr.role,
ext_role = (tag.attr["ext-role"] and true) or nil,
type = tag.attr.type,
ext_type = (tag.attr["ext-type"] and true) or nil,
xmlns = jid.attr.xmlns,
jid = jid:get_text(),
email = email,
telephone = telephone,
postaladdr = postaladdr
}
else
object.contacts[#object.contacts + 1] = {
role = tag.attr.role,
ext_role = (tag.attr["ext-role"] and true) or nil,
type = tag.attr.type,
ext_type = (tag.attr["ext-type"] and true) or nil,
xmlns = jid.attr.xmlns,
jid = jid:get_text(),
email = email,
telephone = telephone,
postaladdr = postaladdr
}
end
elseif tag.name == "RelatedActivity" then
object.related = {}
for _, t in ipairs(tag.tags) do
if tag.name == "IncidentID" then
object.related[#object.related + 1] = { text = t:get_text(), name = tag.attr.name }
end
end
elseif tag.name == "Assessment" then
local impact = tag:get_child("Impact")
object.assessment = { lang = impact.attr.lang, severity = impact.attr.severity, completion = impact.attr.completion, type = impact.attr.type }
elseif tag.name == "EventData" then
local source = tag:get_child("Flow").tags[1]
local target = tag:get_child("Flow").tags[2]
local expectation = tag:get_child("Flow").tags[3]
object.event_data = { sources = {}, targets = {} }
for _, t in ipairs(source.tags) do
local addr = t:get_child("Address")
local cntr = t:get_child("Counter")
object.event_data.sources[#object.event_data.sources + 1] = {
address = { cat = addr.attr.category, ext = addr.attr["ext-category"], text = addr:get_text() },
counter = { type = cntr.attr.type, ext_type = cntr.attr["ext-type"], value = cntr:get_text() }
}
end
for _, entry in ipairs(target.tags) do
local noderole = { cat = entry:get_child("NodeRole").attr.category, ext = entry:get_child("NodeRole").attr["ext-category"] }
local current = #object.event_data.targets + 1
object.event_data.targets[current] = { addresses = {}, noderole = noderole }
for _, tag in ipairs(entry.tags) do
object.event_data.targets[current].addresses[#object.event_data.targets[current].addresses + 1] = { text = tag:get_text(), cat = tag.attr.category, ext = tag.attr["ext-category"] }
end
end
if expectation then
object.event_data.expectation = {
action = expectation.attr.action,
desc = expectation:get_child("Description") and expectation:get_child("Description"):get_text()
}
end
elseif tag.name == "History" then
object.history = {}
for _, t in ipairs(tag.tags) do
object.history[#object.history + 1] = {
action = t.attr.action,
date = t:get_child("DateTime"):get_text(),
desc = t:get_chilld("Description"):get_text()
}
end
end
end
local function stanza_parser(stanza)
local object = {}
if stanza:get_child("report", xmlns_inc) then
local report = st.clone(stanza):get_child("report", xmlns_inc):get_child("Incident", xmlns_iodef)
for _, tag in ipairs(report.tags) do do_tag_mapping(tag, object) end
elseif stanza:get_child("request", xmlns_inc) then
local request = st.clone(stanza):get_child("request", xmlns_inc):get_child("Incident", xmlns_iodef)
for _, tag in ipairs(request.tags) do do_tag_mapping(tag, object) end
elseif stanza:get_child("response", xmlns_inc) then
local response = st.clone(stanza):get_child("response", xmlns_inc):get_child("Incident", xmlns_iodef)
for _, tag in ipairs(response.tags) do do_tag_mapping(tag, object) end
end
return object
end
local function stanza_construct(id)
if not id then return nil
else
local object = incidents[id].data
local s_type = incidents[id].type
local stanza = st.iq():tag(s_type or "report", { xmlns = xmlns_inc })
stanza:tag("Incident", { xmlns = xmlns_iodef, purpose = incidents[id].purpose })
:tag("IncidentID", { name = object.id.name }):text(object.id.text):up()
:tag("StartTime"):text(object.start_time):up()
:tag("EndTime"):text(object.end_time):up()
:tag("ReportTime"):text(object.report_time):up()
:tag("Description", { ["xml:lang"] = object.desc.lang }):text(object.desc.text):up():up();
local incident = stanza:get_child(s_type, xmlns_inc):get_child("Incident", xmlns_iodef)
for _, contact in ipairs(object.contacts) do
incident:tag("Contact", { role = (contact.ext_role and "ext-role") or contact.role,
["ext-role"] = (contact.ext_role and contact.role) or nil,
type = (contact.ext_type and "ext-type") or contact.type,
["ext-type"] = (contact.ext_type and contact.type) or nil })
:tag("Email"):text(contact.email):up()
:tag("Telephone"):text(contact.telephone):up()
:tag("PostalAddress"):text(contact.postaladdr):up()
:tag("AdditionalData")
:tag("jid", { xmlns = contact.xmlns }):text(contact.jid):up():up():up()
end
incident:tag("RelatedActivity"):up();
for _, related in ipairs(object.related) do
incident:get_child("RelatedActivity")
:tag("IncidentID", { name = related.name }):text(related.text):up();
end
incident:tag("Assessment")
:tag("Impact", {
lang = object.assessment.lang,
severity = object.assessment.severity,
completion = object.assessment.completion,
type = object.assessment.type
}):up():up();
incident:tag("EventData")
:tag("Flow")
:tag("System", { category = "source" }):up()
:tag("System", { category = "target" }):up():up():up();
local e_data = incident:get_child("EventData")
local sources = e_data:get_child("Flow").tags[1]
local targets = e_data:get_child("Flow").tags[2]
for _, source in ipairs(object.event_data.sources) do
sources:tag("Node")
:tag("Address", { category = source.address.cat, ["ext-category"] = source.address.ext })
:text(source.address.text):up()
:tag("Counter", { type = source.counter.type, ["ext-type"] = source.counter.ext_type })
:text(source.counter.value):up():up();
end
for _, target in ipairs(object.event_data.targets) do
targets:tag("Node"):up() ; local node = targets.tags[#targets.tags]
for _, address in ipairs(target.addresses) do
node:tag("Address", { category = address.cat, ["ext-category"] = address.ext }):text(address.text):up();
end
node:tag("NodeRole", { category = target.noderole.cat, ["ext-category"] = target.noderole.ext }):up();
end
if object.event_data.expectation then
e_data:tag("Expectation", { action = object.event_data.expectation.action }):up();
if object.event_data.expectation.desc then
local expectation = e_data:get_child("Expectation")
expectation:tag("Description"):text(object.event_data.expectation.desc):up();
end
end
if object.history then
local history = incident:tag("History"):up();
for _, item in ipairs(object.history) do
history:tag("HistoryItem", { action = item.action })
:tag("DateTime"):text(item.date):up()
:tag("Description"):text(item.desc):up():up();
end
end
-- Sanitize contact empty tags
for _, tag in ipairs(incident) do
if tag.name == "Contact" then
for i, check in ipairs(tag) do
if (check.name == "Email" or check.name == "PostalAddress" or check.name == "Telephone") and
not check:get_text() then
table.remove(tag, i)
end
end
end
end
if s_type == "request" then stanza.attr.type = "get"
elseif s_type == "response" then stanza.attr.type = "set"
else stanza.attr.type = "set" end
return stanza
end
end
_M = {} -- wraps methods into the library.
_M.ft_str = ft_str
_M.get_incident_layout = get_incident_layout
_M.render_list = render_list
_M.render_single = render_single
_M.get_type = get_type
_M.stanza_parser = stanza_parser
_M.stanza_construct = stanza_construct
_M.set_my_host = function(host) my_host = host end
return _M
| mit |
hooksta4/darkstar | scripts/zones/zones/The_Colosseum/npcs/Cooking.lua | 2 | 4295 | -----------------------------------
-- Area: The Colosseum
-- NPC: Cooking
-- Guild Merchant NPC: Woodworking Guild
-- @pos 0 0 0 0 zone 71
-----------------------------------
package.loaded["scripts/zones/The_Colosseum/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/The_Colosseum/TextIDs");
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local balance = player:getCurrency("guild_cooking");
player:PrintToPlayer("All the Cooking materials you need for your adventure!");
player:PrintToPlayer("Trade me a single Terra Crystal to receive Synth Support.");
player:PrintToPlayer("You have "..balance.." of GP points!");
stock = {0x11DA,1, --Bird Egg
0x1128,1, --Saruta Orange
0x111A,1, --Selbina Milk
0x3A8,1, --Rock Salt
0x5F2,1, --Dried Marjoram
0x263,1, --Rye Flour
0x274,1, --Cinnamon
0x273,1, --Maple Sugar
0x110B,1, --Faerie Apple
0x110A,1, --Lizard Egg
0x110F,1, --Batagreens
0x114F,1, --San d'Orian Grapes
0x262,1, --San d'Orian Flour
0x1125,1, --San d'Orian Carrot
0x09A0,1, --Carbon Dioxide
0x1647,1, --Uleguerand Milk
0x1112,1, --Honey
0x1174,1, --Pamamas
0x026B,1, --Popoto
0x0612,1, --Turmeric
0x1123,1, --Wild Onion
0x027F,1, --Ronfaure Chestnut
0x110D,1, --Rolanberry
0x0457,1, --Gelatin
0x0272,1, --Black Pepper
0x1109,1, --Nebimonite
0x1184,1, --Shall Shell
0x1107,1, --Dhalmel Meat
0x02C0,1, --Bamboo Stick
0x1162,1, --Coral Fungus
0x05F4,1, --Fresh Mugwort
0x0264,1, --Kazham Peppers
0x0613,1, --Coriander
0x1126,1, --Mithran Tomato
0x05C3,1, --Curry Powder
0x0279,1, --Olive Oil
0x026C,1, --Tarutaru Rice
0x05BF,1, --Sticky Rice
0x142C,1, --Ground Wasabi
0x1612,1 --Nopales
}
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(4241,1))
then
player:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,480);
else
if (player:getVar('[GUILD]currentGuild') ~= 9 ) then
player:PrintToPlayer( "You are not eligible to earn GP for this guild!");
--end
--if (daily_points <=10000)
--then
--player:setVar("[Guild]daily_points", os.date("%j")); -- %M for next minute, %j for next day
--player:setVar("Wait1DayForYomiOkuri",VanadielDayOfTheYear());
else
if (trade:hasItemQty(4489,1)) --vegetable gruel
then
player:addCurrency("guild_cooking", 300);
player:PrintToPlayer( "You have gained 300 GP !");
--daily_points, +300;
player:tradeComplete();
elseif
(trade:hasItemQty(4534,1)) --vegetable gruel +1
then
player:addCurrency("guild_cooking", 400);
player:PrintToPlayer( "You have gained 400 GP !");
player:tradeComplete();
elseif
(trade:hasItemQty(4413,1))--apple pie
then
player:addCurrency("guild_cooking", 500);
player:PrintToPlayer( "You have gained 500 GP !");
player:tradeComplete();
elseif
(trade:hasItemQty(4320,1))-- apple pie +1
then
player:addCurrency("guild_cooking", 600);
player:PrintToPlayer( "You have gained 600 GP !");
player:tradeComplete();
elseif
(trade:hasItemQty(4603,1))-- chamomile tea
then
player:addCurrency("guild_cooking", 700);
player:PrintToPlayer( "You have gained 700 GP !");
player:tradeComplete();
elseif
(trade:hasItemQty(4286,1)) -- healing tea
then
player:addCurrency("guild_cooking", 800);
--player:messageSpecial(GP_OBTAINED, option);
player:PrintToPlayer( "You have gained 800 GP !");
player:tradeComplete();
end
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);
end;
| gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/globals/weaponskills/tachi_rana.lua | 12 | 4581 | -----------------------------------
-- Tachi Rana
-- Great Katana weapon skill
-- Skill Level: N/A
-- Delivers a three-fold attack. params.accuracy varies with TP. Aftermath effect varies with TP. See Kogarasumaru.
-- In order to obtain Tachi: Rana, the Unlocking a Myth (Samurai) quest must be completed.
-- Will stack with Sneak Attack (first hit only).
-- Aligned with the Shadow Gorget, Soil Gorget & Snow Gorget.
-- Aligned with the Shadow Belt, Soil Belt & Snow Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.5;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if((player:getEquipID(SLOT_MAIN) == 19002) and (player:getMainJob() == JOB_SAM)) then
if(damage > 0) then
-- AFTERMATH LV1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1);
-- AFTERMATH LV3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
dermoumi/m2n | bin/assets/scripts/audio/flangerfilter.lua | 1 | 1817 | --[[
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org>
--]]
local AudioFilter = require 'audio._filter'
local AudioFlangerFilter = AudioFilter:subclass('audio.flangerfilter')
local ffi = require 'ffi'
local C = ffi.C
function AudioFlangerFilter:initialize()
local handle = C.nxAudioFilterFlangerCreate()
self._cdata = ffi.gc(handle, C.nxAudioFilterRelease)
end
function AudioFlangerFilter:setParams(delay, freq)
if self._cdata ~= nil then
C.nxAudioFilterFlangerSetParams(self._cdata, delay, freq)
end
return self
end
return AudioFlangerFilter | unlicense |
FishFilletsNG/fillets-data | script/captain/dialogs_sv.lua | 1 | 2088 |
dialogId("vl-m-hara", "font_small", "There is a lot of garbage here!")
dialogStr("Här är det mycket skräp!")
dialogId("vl-v-kaj1", "font_big", "This was surely a captain’s cabin.")
dialogStr("Det här var tydligen kaptens hytt.")
dialogId("vl-v-kaj2", "font_big", "What would you expect after so many years?")
dialogStr("Vad hade du väntat dig efter så många år?")
dialogId("vl-m-hak", "font_small", "Do you think that Silver had this hook in place of his hand?")
dialogStr("Tror du att kapten Silver använde den här kroken som sin hand?")
dialogId("vl-v-lodni", "font_big", "This is a ship hook. It’s used to pull up boats...")
dialogStr("Det här en båtshake. Den används för att dra upp båtar...")
dialogId("vl-x-site", "font_brown", "... and nets!")
dialogStr("... och nät!")
dialogId("vl-m-oko", "font_small", "It’s a strange looking eye.")
dialogStr("Det är ett konstigt öga.")
dialogId("vl-v-silha", "font_big", "This eye squints kind of sneakily.")
dialogStr("Ögat kikar i smyg.")
dialogId("vl-leb-kecy0", "font_lightgrey", "Haven’t you seen my eye somewhere?")
dialogStr("Har du sett mitt öga här omkring?")
dialogId("vl-leb-kecy1", "font_lightgrey", "This scarf is very important. The human skull with an empty eye socket looks really disgusting, you know.")
dialogStr("Scarfen är mycket viktig. Skallen med en tom ögonhåla ser riktigt otäckt ut.")
dialogId("vl-leb-kecy2", "font_lightgrey", "After that unfortunate accident with a teaspoon I have a completely different viewpoint of the world.")
dialogStr("Efter den oturliga olyckan med en tesked så har jag en helt ny syn på tillvaron.")
dialogId("vl-leb-kecy3", "font_lightgrey", "Why am I here, after all? As if they can’t put some chest here... or a chamber pot.")
dialogStr("Varför är jag här, egentligen? Som om de skulle ställa en kista här... eller en potta.")
dialogId("vl-leb-kecy4", "font_lightgrey", "Do you appreciate my facial expressions? Not bad for a skeleton, is it?")
dialogStr("Gillar du mina grimaser? Inte dåligt för ett skelett, va?")
| gpl-2.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Aht_Urhgan_Whitegate/npcs/Tafeesa.lua | 34 | 1032 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tafeesa
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x028F);
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 |
henu/Urho3D | bin/Data/LuaScripts/38_SceneAndUILoad.lua | 26 | 5306 | -- Scene & UI load example.
-- This sample demonstrates:
-- - Loading a scene from a file and showing it
-- - Loading a UI layout from a file and showing it
-- - Subscribing to the UI layout's events
require "LuaScripts/Utilities/Sample"
function Start()
-- Execute the common startup for samples
SampleStart()
-- Create the scene content
CreateScene()
-- Create the UI content
CreateUI()
-- Setup the viewport for displaying the scene
SetupViewport()
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_RELATIVE)
-- Subscribe to global events for camera movement
SubscribeToEvents()
end
function CreateScene()
scene_ = Scene()
-- Load scene content prepared in the editor (XML format). GetFile() returns an open file from the resource system
-- which scene.LoadXML() will read
local file = cache:GetFile("Scenes/SceneLoadExample.xml")
scene_:LoadXML(file)
-- In Lua the file returned by GetFile() needs to be deleted manually
file:delete()
-- Create the camera (not included in the scene file)
cameraNode = scene_:CreateChild("Camera")
cameraNode:CreateComponent("Camera")
-- Set an initial position for the camera scene node above the plane
cameraNode.position = Vector3(0.0, 2.0, -10.0)
end
function CreateUI()
-- Set up global UI style into the root UI element
local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
ui.root.defaultStyle = style
-- Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
-- control the camera, and when visible, it will interact with the UI
local cursor = ui.root:CreateChild("Cursor")
cursor:SetStyleAuto()
ui.cursor = cursor
-- Set starting position of the cursor at the rendering window center
cursor:SetPosition(graphics.width / 2, graphics.height / 2)
-- Load UI content prepared in the editor and add to the UI hierarchy
local layoutRoot = ui:LoadLayout(cache:GetResource("XMLFile", "UI/UILoadExample.xml"))
ui.root:AddChild(layoutRoot)
-- Subscribe to button actions (toggle scene lights when pressed then released)
local button = layoutRoot:GetChild("ToggleLight1", true)
if button ~= nil then
SubscribeToEvent(button, "Released", "ToggleLight1")
end
button = layoutRoot:GetChild("ToggleLight2", true)
if button ~= nil then
SubscribeToEvent(button, "Released", "ToggleLight2")
end
end
function ToggleLight1()
local lightNode = scene_:GetChild("Light1", true)
if lightNode ~= nil then
lightNode.enabled = not lightNode.enabled
end
end
function ToggleLight2()
local lightNode = scene_:GetChild("Light2", true)
if lightNode ~= nil then
lightNode.enabled = not lightNode.enabled
end
end
function SetupViewport()
-- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen
local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera"))
renderer:SetViewport(0, viewport)
end
function SubscribeToEvents()
-- Subscribe HandleUpdate() function for camera motion
SubscribeToEvent("Update", "HandleUpdate")
end
function HandleUpdate(eventType, eventData)
-- Take the frame time step, which is stored as a float
local timeStep = eventData["TimeStep"]:GetFloat()
-- Move the camera, scale movement with time step
MoveCamera(timeStep)
end
function MoveCamera(timeStep)
input.mouseVisible = input.mouseMode ~= MM_RELATIVE
mouseDown = input:GetMouseButtonDown(MOUSEB_RIGHT)
-- Override the MM_RELATIVE mouse grabbed settings, to allow interaction with UI
input.mouseGrabbed = mouseDown
-- Right mouse button controls mouse cursor visibility: hide when pressed
ui.cursor.visible = not mouseDown
-- Do not move if the UI has a focused element
if ui.focusElement ~= nil then
return
end
-- Movement speed as world units per second
local MOVE_SPEED = 20.0
-- Mouse sensitivity as degrees per pixel
local MOUSE_SENSITIVITY = 0.1
-- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
-- Only move the camera when the cursor is hidden
if not ui.cursor.visible then
local mouseMove = input.mouseMove
yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x
pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y
pitch = Clamp(pitch, -90.0, 90.0)
-- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode.rotation = Quaternion(pitch, yaw, 0.0)
end
-- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if input:GetKeyDown(KEY_W) then
cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_S) then
cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_A) then
cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
if input:GetKeyDown(KEY_D) then
cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep)
end
end
| mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/forceThrow1.lua | 2 | 2552 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser 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
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
ForceThrow1Command = {
name = "forcethrow1",
damage = 200, -- NOT CORRECT, Need data.
speed = 4.0,
forceCost = 28,
accuracySkillMod = "forcethrow_accuracy";
stateEffects = {
StateEffect(
STUN_EFFECT,
{},
{ "jedi_state_defense" },
{},
65,
0,
10
)
},
animationCRC = hashCode("force_throw_1_particle_level_1_light"),
combatSpam = "forcethrow1",
poolsToDamage = RANDOM_ATTRIBUTE,
attackType = FORCEATTACK,
range = 32
}
AddCommand(ForceThrow1Command)
| agpl-3.0 |
MobinRanjbar/hue | tools/wrk-scripts/lib/equal-5bb8dbf.lua | 22 | 1818 | -- The MIT License (MIT)
--
-- Copyright (c) 2014, Cyril David <cyx@cyx.is>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local function equal(x, y)
local t1, t2 = type(x), type(y)
-- Shortcircuit if types not equal.
if t1 ~= t2 then return false end
-- For primitive types, direct comparison works.
if t1 ~= 'table' and t2 ~= 'table' then return x == y end
-- Since we have two tables, make sure both have the same
-- length so we can avoid looping over different length arrays.
if #x ~= #y then return false end
-- Case 1: check over all keys of x
for k,v in pairs(x) do
if not equal(v, y[k]) then return false end
end
-- Case 2: check over `y` this time.
for k,v in pairs(y) do
if not equal(v, x[k]) then return false end
end
return true
end
return equal
| apache-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/requestCraftingSession.lua | 4 | 2159 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser 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
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
RequestCraftingSessionCommand = {
name = "requestcraftingsession",
}
AddCommand(RequestCraftingSessionCommand)
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/lair/npc_theater/global_imperial_colonel_camp_imperial_medium_theater.lua | 2 | 1043 | global_imperial_colonel_camp_imperial_medium_theater = Lair:new {
mobiles = {
{"imperial_colonel",1},
{"imperial_major",1},
{"imperial_first_lieutenant",2},
{"imperial_sergeant",3}
},
spawnLimit = 12,
buildingsVeryEasy = {"object/building/poi/lok_imperial_medium4.iff","object/building/poi/lok_imperial_medium5.iff"},
buildingsEasy = {"object/building/poi/lok_imperial_medium4.iff","object/building/poi/lok_imperial_medium5.iff"},
buildingsMedium = {"object/building/poi/lok_imperial_medium4.iff","object/building/poi/lok_imperial_medium5.iff"},
buildingsHard = {"object/building/poi/lok_imperial_medium4.iff","object/building/poi/lok_imperial_medium5.iff"},
buildingsVeryHard = {"object/building/poi/lok_imperial_medium4.iff","object/building/poi/lok_imperial_medium5.iff"},
missionBuilding = "object/tangible/lair/base/objective_banner_imperial.iff",
mobType = "npc",
buildingType = "theater"
}
addLairTemplate("global_imperial_colonel_camp_imperial_medium_theater", global_imperial_colonel_camp_imperial_medium_theater)
| agpl-3.0 |
jchuang1977/my_packages | net/luci-app-ocserv/files/usr/lib/lua/luci/model/cbi/ocserv/user-config.lua | 30 | 4979 | --[[
LuCI - Lua Configuration Interface
Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
local niulib = require "luci.niulib"
]]--
local fs = require "nixio.fs"
local has_ipv6 = fs.access("/proc/net/ipv6_route")
m = Map("ocserv", translate("OpenConnect VPN"))
s = m:section(TypedSection, "ocserv", "OpenConnect")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("ca", translate("CA certificate"))
s:tab("template", translate("Edit Template"))
local e = s:taboption("general", Flag, "enable", translate("Enable server"))
e.rmempty = false
e.default = "1"
function m.on_commit(map)
luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1")
end
function e.write(self, section, value)
if value == "0" then
luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1")
else
luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1")
end
Flag.write(self, section, value)
end
local o
o = s:taboption("general", ListValue, "auth", translate("User Authentication"),
translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius)."))
o.rmempty = false
o.default = "plain"
o:value("plain")
o:value("PAM")
o = s:taboption("general", Value, "zone", translate("Firewall Zone"),
translate("The firewall zone that the VPN clients will be set to"))
o.nocreate = true
o.default = "lan"
o.template = "cbi/firewall_zonelist"
s:taboption("general", Value, "port", translate("Port"),
translate("The same UDP and TCP ports will be used"))
s:taboption("general", Value, "max_clients", translate("Max clients"))
s:taboption("general", Value, "max_same", translate("Max same clients"))
s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)"))
local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"),
translate("The assigned IPs will be selected deterministically"))
pip.default = "1"
local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"),
translate("Enable UDP channel support; this must be enabled unless you know what you are doing"))
udp.default = "1"
local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"),
translate("Enable support for CISCO AnyConnect clients"))
cisco.default = "1"
ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address"))
ipaddr.default = "192.168.100.1"
nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm.default = "255.255.255.0"
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
if has_ipv6 then
ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix"))
end
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the ocserv configuration."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value)
end
ca = s:taboption("ca", Value, "_ca",
translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients."))
ca.template = "cbi/tvalue"
ca.rows = 20
function ca.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ca.pem")
end
--[[DNS]]--
s = m:section(TypedSection, "dns", translate("DNS servers"),
translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
--[[Routes]]--
s = m:section(TypedSection, "routes", translate("Routing table"),
translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)"))
o.default = "255.255.255.0"
o:value("255.255.255.0")
o:value("255.255.0.0")
o:value("255.0.0.0")
return m
| gpl-2.0 |
jchuang1977/my_packages | net/luci-app-ocserv/files/usr/lib/lua/luci/model/cbi/ocserv/main.lua | 30 | 4979 | --[[
LuCI - Lua Configuration Interface
Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
local niulib = require "luci.niulib"
]]--
local fs = require "nixio.fs"
local has_ipv6 = fs.access("/proc/net/ipv6_route")
m = Map("ocserv", translate("OpenConnect VPN"))
s = m:section(TypedSection, "ocserv", "OpenConnect")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("ca", translate("CA certificate"))
s:tab("template", translate("Edit Template"))
local e = s:taboption("general", Flag, "enable", translate("Enable server"))
e.rmempty = false
e.default = "1"
function m.on_commit(map)
luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1")
end
function e.write(self, section, value)
if value == "0" then
luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1")
else
luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1")
end
Flag.write(self, section, value)
end
local o
o = s:taboption("general", ListValue, "auth", translate("User Authentication"),
translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius)."))
o.rmempty = false
o.default = "plain"
o:value("plain")
o:value("PAM")
o = s:taboption("general", Value, "zone", translate("Firewall Zone"),
translate("The firewall zone that the VPN clients will be set to"))
o.nocreate = true
o.default = "lan"
o.template = "cbi/firewall_zonelist"
s:taboption("general", Value, "port", translate("Port"),
translate("The same UDP and TCP ports will be used"))
s:taboption("general", Value, "max_clients", translate("Max clients"))
s:taboption("general", Value, "max_same", translate("Max same clients"))
s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)"))
local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"),
translate("The assigned IPs will be selected deterministically"))
pip.default = "1"
local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"),
translate("Enable UDP channel support; this must be enabled unless you know what you are doing"))
udp.default = "1"
local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"),
translate("Enable support for CISCO AnyConnect clients"))
cisco.default = "1"
ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address"))
ipaddr.default = "192.168.100.1"
nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"))
nm.default = "255.255.255.0"
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
if has_ipv6 then
ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix"))
end
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the ocserv configuration."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value)
end
ca = s:taboption("ca", Value, "_ca",
translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients."))
ca.template = "cbi/tvalue"
ca.rows = 20
function ca.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ca.pem")
end
--[[DNS]]--
s = m:section(TypedSection, "dns", translate("DNS servers"),
translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
--[[Routes]]--
s = m:section(TypedSection, "routes", translate("Routing table"),
translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)"))
o.default = "255.255.255.0"
o:value("255.255.255.0")
o:value("255.255.0.0")
o:value("255.0.0.0")
return m
| gpl-2.0 |
bellinat0r/Epiar | Resources/Scripts/fleet.lua | 2 | 8686 | -- Fleet class to guide AI behavior (e.g. imitate leader's travel route, accept orders as a group,
-- don't attack fellow escorts, etc.). The idea is that this should eventually be a cleaner way
-- of controlling AIs than tampering directly with AIData from outside.
--
-- Note: This is distinct from the Alliances in that Alliances are story-based, while Fleets are
-- simply practical tools to control how AIs behave. A mission with Alliance-independent AIs might
-- still want to put them in a Fleet.
--
-- Last updated: Dec 12, 2010
--
-- Current status: Partially working
--
-- To-do:
-- - Make ai.lua pull values from Fleets rather than having them pushed into AIData
-- - Do garbage collection for stale fleets
-- - Make IDs get more promptly de-listed upon destruction, and watch out for consequences of sprite ID re-use
-- - More
Fleet = { }
--
-- constructor
--
function Fleet.create(_name)
local self = {
name = _name,
members = { },
leader = -1,
state = nil,
add = Fleet.add,
remove = Fleet.remove,
size = Fleet.size,
hasBoth = Fleet.hasBoth,
target = Fleet.target,
hunt = Fleet.hunt,
gateTravel = Fleet.gateTravel,
formation = Fleet.formation,
hold = Fleet.hold,
checkSprite = Fleet.checkSprite,
isLeader = Fleet.isLeader,
getLeader = Fleet.getLeader,
getLeaderRoute = Fleet.getLeaderRoute,
fleetmateProx = Fleet.fleetmateProx
}
Fleets.list[_name] = self
return self
end
--
-- instance functions
--
function Fleet.add(self, id, leader)
if id == nil then return end
-- keep track of which ships are in this fleet
self.members[id] = true
-- but also which fleet the new ship is a member of (for simplicity, only allow one fleet per ship)
Fleets.shipFleet[id] = self.name
-- each fleet may optionally have a leader, which is treated differently
if leader then self.leader = id end
return self
end
function Fleet.remove(self, id)
self.members[id] = nil
Fleets.shipFleet[id] = nil
return self
end
function Fleet.size(self)
local size = 0
for k,v in pairs(self.members) do size = size + 1 end
return size
end
function Fleet.hasBoth(self, first, second)
return ( self.members[first] ~= nil and self.members[second] ~= nil )
end
function Fleet.target(self, t)
for n,id in pairs(self.members) do
local sprite = self:checkSprite(id)
if sprite ~= nil and AIData[id] ~= nil then
AIData[id].target = t
end
end
return self
end
function Fleet.hunt(self, t)
-- if it doesn't have a GetHull function, it's not a valid target
if Epiar.getSprite(t).GetHull == nil then return false end
local permitted = false
for id,yes in pairs(self.members) do
local sprite = self:checkSprite(id)
if sprite ~= nil and AIData[id] ~= nil and Fleets:fleetmates(id, t) == false then
setHuntHostile(id, t)
AIData[id].nextState = "Hunting"
permitted = true
end
end
self.state = "Hunting"
return permitted
end
function Fleet.gateTravel(self, dest, route)
for id,yes in pairs(self.members) do
local sprite = self:checkSprite(id)
if sprite ~= nil and AIData[id] ~= nil then
AIData[id].destinationName = dest
if self:isLeader(id) or self:getLeader() == -1 or route == nil then
AIData[id].nextState = "ComputingRoute"
elseif route ~= nil then
AIData[id].Autopilot = APInit("AI", id)
AIData[id].Autopilot.GateRoute = copy_table(route)
AIData[id].nextState = "GateTravelling"
else
AIData[id].accompany = self:getLeader()
-- "Waiting" is a lot like "Accompanying" except that it will automatically transition into "GateTravelling"
AIData[id].nextState = "Waiting"
end
end
end
return self
end
function Fleet.formation(self)
for id,yes in pairs(self.members) do
local sprite = self:checkSprite(id)
if sprite ~= nil and AIData[id] ~= nil then
AIData[id].hostile = nil
AIData[id].target = -1
AIData[id].destination = -1
AIData[id].destinationName = nil
AIData[id].Autopilot = nil
AIData[id].nextState = "default"
end
end
self.state = "Accompanying"
end
function Fleet.hold(self)
for id,yes in pairs(self.members) do
local sprite = self:checkSprite(id)
if sprite ~= nil and AIData[id] ~= nil then
AIData[id].hostile = nil
AIData[id].target = -1
AIData[id].destination = -1
AIData[id].destinationName = nil
AIData[id].Autopilot = nil
AIData[id].nextState = "HoldingPosition"
end
end
self.state = "HoldingPosition"
end
function Fleet.checkSprite(self, id)
local sprite = Epiar.getSprite(id)
if sprite == nil then
self:remove(id)
end
return sprite
end
function Fleet.isLeader(self, id)
return (self.leader == id)
end
function Fleet.getLeader(self, id)
return self.leader
end
function Fleet.getLeaderRoute(self)
if self:getLeader() == PLAYER:GetID() and Autopilot.spcr == nil then
return Autopilot.GateRoute
elseif AIData[self:getLeader()].Autopilot.spcr == nil then
return AIData[self:getLeader()].Autopilot.GateRoute
else
return nil
end
end
function Fleet.fleetmateProx(self, id)
local cur_ship = Epiar.getSprite(id)
local myX, myY = cur_ship:GetPosition()
local min_dist = nil
for fm_id,yes in pairs(self.members) do
if fm_id ~= id then
local sprite = Epiar.getSprite(fm_id)
if sprite == nil then
self:remove(fm_id)
else
local fmX, fmY = sprite:GetPosition()
local dist = distfrom( myX, myY, fmX, fmY )
if min_dist == nil or dist < min_dist then
min_dist = dist
end
end
end
end
return min_dist
end
--
-- manager functions
--
Fleets = {
list = { },
shipFleet = { },
-- usage: if( Fleets:fleetmates( id1, id2 ) ) then ... end
fleetmates = function(self, first, second)
for name, fleet in pairs(self.list) do
if fleet:hasBoth(first, second) then return true end
end
return false
end,
getShipFleet = function(self, s)
return Fleets:get(self.shipFleet[s])
end,
-- Fleets:join( first, second )
-- If first is already a member of a fleet, add second to that one;
-- Otherwise, create one, make first the leader, then add second to that one.
-- Fleets:join( single )
-- If single is already a member of a fleet, do nothing;
-- Otherwise, create one and make single the leader.
join = function(self, first, second)
local f = Fleets:getShipFleet(first)
--print (second .. " is joining " .. first .. "'s fleet")
--f PLAYER ~= nil and PLAYER:GetID() == first then
-- f = Fleets:createOrGet("player's fleet")
-- f:add(PLAYER:GetID(), true)
--end
if f == nil then
f = Fleet.create( first .. " fleet " .. os.time() )
f:add(first, true)
end
if second ~= nil then
setAccompany(second, first)
f:add(second)
end
return f
end,
unjoin = function(self, first, second)
local f = Fleets:getShipFleet(first)
if Fleets:getShipFleet(first) ~= nil then
setAccompany(second, -1)
f:remove(second)
end
return f
end,
get = function(self, f)
return self.list[f]
end,
-- Don't use this function unless you want to refer to an individual fleet by a specific name.
createOrGet = function(self, name)
local f = self:get(name)
if f == nil then
return Fleet.create(name)
else
return f
end
end,
cleanup = function(self)
-- remove any empty fleets
end
}
--
-- player functions
--
-- this function is currently for testing purposes only
function givePlayerEscort()
local X, Y
if HUD.getTarget() < 0 then
X, Y = PLAYER:GetPosition()
else
X, Y = Epiar.getSprite( HUD.getTarget() ):GetPosition()
end
local esc1 = Ship.new("escort 1",X - 150, Y, "Fleet Guard", "Ion Engines","Escort","Independent")
--local esc2 = Ship.new("escort 2",X + 150, Y, "Fleet Guard", "Ion Engines","Escort","Independent")
Fleets:join(PLAYER:GetID(), esc1:GetID())
--Fleets:join(PLAYER:GetID(), esc2:GetID())
PLAYER:AddHiredEscort(esc1:GetModelName(), 0, esc1:GetID())
end
function playerFleetHunt()
local f = Fleets:getShipFleet( PLAYER:GetID() )
if f ~= nil and f:size() > 0 then
HUD.newAlert(
f:hunt( HUD.getTarget() ) and
"Escorts pursuing designated target." or
"That is not an acceptable target!"
)
else
HUD.newAlert("You have no escorts.")
end
end
function playerFleetFormation()
local f = Fleets:getShipFleet( PLAYER:GetID() )
if f ~= nil and f:size() > 0 then
HUD.newAlert("Escorts returning to formation.")
f:formation()
else
HUD.newAlert("You have no escorts.")
end
end
function playerFleetHold()
local f = Fleets:getShipFleet( PLAYER:GetID() )
if f ~= nil and f:size() > 0 then
HUD.newAlert("Escorts holding position.")
f:hold()
else
HUD.newAlert("You have no escorts.")
end
end
--
-- utility functions
--
function copy_table(a)
local b = { }
for k,v in pairs(a) do
b[k] = v
end
return b
end
| gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/loot/items/geonosian_lab/rifle_tenloss_dxr6_disruptor.lua | 3 | 1052 | --Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
rifle_tenloss_dxr6_disruptor = {
minimumLevel = 0,
maximumLevel = -1,
customObjectName = "",
directObjectTemplate = "object/weapon/ranged/rifle/rifle_tenloss_dxr6_disruptor_loot.iff",
craftingValues = {
{"mindamage",40,150,0},
{"maxdamage",80,320,0},
{"attackspeed",9.4,6.7,1},
{"woundchance",4.8,12.3,0},
{"hitpoints",750,750,0},
{"attackhealthcost",21,12,0},
{"attackactioncost",32,19,0},
{"attackmindcost",77,42,0},
{"roundsused",30,65,0},
{"zerorangemod",-80,-40,0},
{"maxrangemod",10,30,0},
{"midrange",54,54,0},
{"midrangemod",45,70,0},
},
customizationStringNames = {},
customizationValues = {},
-- randomDotChance: The chance of this weapon object dropping with a random dot on it. Higher number means less chance. Set to 0 to always have a random dot.
randomDotChance = 1000,
junkDealerTypeNeeded = JUNKWEAPONS,
junkMinValue = 20,
junkMaxValue = 60
}
addLootItemTemplate("rifle_tenloss_dxr6_disruptor", rifle_tenloss_dxr6_disruptor)
| agpl-3.0 |
szagoruyko/nn | SpatialContrastiveNormalization.lua | 63 | 1444 | local SpatialContrastiveNormalization, parent = torch.class('nn.SpatialContrastiveNormalization','nn.Module')
function SpatialContrastiveNormalization:__init(nInputPlane, kernel, threshold, thresval)
parent.__init(self)
-- get args
self.nInputPlane = nInputPlane or 1
self.kernel = kernel or torch.Tensor(9,9):fill(1)
self.threshold = threshold or 1e-4
self.thresval = thresval or threshold or 1e-4
local kdim = self.kernel:nDimension()
-- check args
if kdim ~= 2 and kdim ~= 1 then
error('<SpatialContrastiveNormalization> averaging kernel must be 2D or 1D')
end
if (self.kernel:size(1) % 2) == 0 or (kdim == 2 and (self.kernel:size(2) % 2) == 0) then
error('<SpatialContrastiveNormalization> averaging kernel must have ODD dimensions')
end
-- instantiate sub+div normalization
self.normalizer = nn.Sequential()
self.normalizer:add(nn.SpatialSubtractiveNormalization(self.nInputPlane, self.kernel))
self.normalizer:add(nn.SpatialDivisiveNormalization(self.nInputPlane, self.kernel,
self.threshold, self.thresval))
end
function SpatialContrastiveNormalization:updateOutput(input)
self.output = self.normalizer:forward(input)
return self.output
end
function SpatialContrastiveNormalization:updateGradInput(input, gradOutput)
self.gradInput = self.normalizer:backward(input, gradOutput)
return self.gradInput
end
| bsd-3-clause |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/loot/groups/wearables/wearables_scarce.lua | 4 | 6202 | wearables_scarce = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "apron_chef_s01", weight = 120481}, -- Chef's Apron
{itemTemplate = "belt_s03", weight = 120481}, -- Cartridge Belt
{itemTemplate = "belt_s05", weight = 120481}, -- Grenadier's Belt
{itemTemplate = "belt_s13", weight = 120481}, -- Dignified Belt
{itemTemplate = "belt_s17", weight = 120481}, -- Fancy Belt
{itemTemplate = "belt_s20", weight = 120481}, -- Simplified Belt
{itemTemplate = "bikini_leggings_s01", weight = 120481}, -- Sheer Leggings
{itemTemplate = "bikini_s01", weight = 120481}, -- Revealing Bikini
{itemTemplate = "bikini_s02", weight = 120481}, -- Metal Bikini
{itemTemplate = "bikini_s03", weight = 120481}, -- Low-Cut Top
{itemTemplate = "bikini_s04", weight = 120481}, -- Revealing Top
{itemTemplate = "bodysuit_s01", weight = 120481}, -- Heavy Flightsuit
{itemTemplate = "bodysuit_s06", weight = 120481}, -- Revealing Fleshwrap
{itemTemplate = "bodysuit_s08", weight = 120481}, -- Transport Flightsuit
{itemTemplate = "bodysuit_s12", weight = 120481}, -- Trader's Flightsuit
{itemTemplate = "bodysuit_s13", weight = 120481}, -- Reinforced Jumpsuit
{itemTemplate = "bodysuit_s14", weight = 120481}, -- Fighter Flightsuit
{itemTemplate = "bodysuit_s15", weight = 120481}, -- Tactical Skinsuit
{itemTemplate = "bodysuit_s16", weight = 120481}, -- Infiltration Suit
{itemTemplate = "dress_s14", weight = 120491}, -- Exquisite Gown
{itemTemplate = "dress_s15", weight = 120491}, -- Grand Healer's Robe
{itemTemplate = "dress_s33", weight = 120481}, -- Patterned Slip Dress
{itemTemplate = "dress_s34", weight = 120491}, -- Luxurious Gown
{itemTemplate = "dress_s35", weight = 120491}, -- Grand Ball Gown
{itemTemplate = "gloves_s10", weight = 120481}, -- Heavy Gloves
{itemTemplate = "gloves_s13", weight = 120481}, -- Long Uniform Gloves
{itemTemplate = "hat_twilek_s01", weight = 120481}, -- Twi'lek Bone Crest
{itemTemplate = "hat_twilek_s02", weight = 120481}, -- Twi'lek Lekku Wrap
{itemTemplate = "hat_twilek_s03", weight = 120481}, -- Twi'lek Noble's Crest
{itemTemplate = "hat_twilek_s04", weight = 120481}, -- Lekku Ys'rak
{itemTemplate = "hat_twilek_s05", weight = 120481}, -- Grand Twi'lek Headpiece
{itemTemplate = "apron_chef_jacket_s01_ith", weight = 120481}, -- Ithorian Apron
{itemTemplate = "ith_bodysuit_s01", weight = 120481}, -- Ithorian Comfort-Flex
{itemTemplate = "ith_bodysuit_s02", weight = 120481}, -- Ithorian Technical Suit
{itemTemplate = "ith_bodysuit_s03", weight = 120481}, -- Ithorian Tight Fit Jumpsuit
{itemTemplate = "ith_bodysuit_s05", weight = 120481}, -- Ithorian Nath-Nath Ball Outfit
{itemTemplate = "ith_bodysuit_s06", weight = 120481}, -- Ithorian Leather Gear
{itemTemplate = "ith_hat_s04", weight = 120481}, -- Ithorian Ceremonial Garb
{itemTemplate = "ith_jacket_s11", weight = 120481}, -- Ithorian Officer's Jacket
{itemTemplate = "ith_jacket_s15", weight = 120481}, -- Ithorian Fade Pattern Jacket
{itemTemplate = "ith_necklace_s02", weight = 120481}, -- Ithorian Stately Necklace
{itemTemplate = "ith_necklace_s04", weight = 120481}, -- Ithorian Gemstone Crest
{itemTemplate = "ith_necklace_s05", weight = 120481}, -- Ithorian Immense Gemstone Necklace
{itemTemplate = "ith_pants_s14", weight = 120481}, -- Ithorian Khakis
{itemTemplate = "ith_pants_s19", weight = 120481}, -- Ithorian Heavy Pantaloon
{itemTemplate = "ith_pants_s20", weight = 120481}, -- Ithorian Plated Pantaloon
{itemTemplate = "ith_pants_s21", weight = 120481}, -- Strange Ithorian Pants
{itemTemplate = "ith_robe_s02", weight = 120481}, -- Ithorian Priest's Robe
{itemTemplate = "ith_robe_s03", weight = 120481}, -- Ithorian Merchant's Robe
{itemTemplate = "ith_shirt_s09", weight = 120481}, -- Ithorian Fade Dyed Shirt
{itemTemplate = "ith_shirt_s10", weight = 120481}, -- Ithorian Mystic Shirt
{itemTemplate = "jacket_s03", weight = 120481}, -- Long Formal Jacket
{itemTemplate = "jacket_s18", weight = 120481}, -- Reinforced Pullover
{itemTemplate = "jacket_s22", weight = 120481}, -- Dress Robe
{itemTemplate = "jacket_s24", weight = 120481}, -- Sleeveless Jacket
{itemTemplate = "jacket_s25", weight = 120491}, -- Dress Uniform Jacket
{itemTemplate = "jacket_s36", weight = 120491}, -- Pilot's Jacket
{itemTemplate = "necklace_s02", weight = 120481}, -- Stately Necklace
{itemTemplate = "necklace_s04", weight = 120481}, -- Gemstone Crest
{itemTemplate = "necklace_s05", weight = 120481}, -- Immense Gemstone Necklace
{itemTemplate = "pants_s02", weight = 120481}, -- Winged Hawtpants
{itemTemplate = "pants_s13", weight = 120481}, -- Comfortable Slacks
{itemTemplate = "pants_s15", weight = 120481}, -- Dress Slacks
{itemTemplate = "pants_s18", weight = 120481}, -- Short Skirt
{itemTemplate = "pants_s21", weight = 120481}, -- Paramilitary Camos
{itemTemplate = "pants_s22", weight = 120481}, -- Infiltrator Leggings
{itemTemplate = "pants_s24", weight = 120481}, -- Pantaloons
{itemTemplate = "pants_s32", weight = 120481}, -- Short Wrap
{itemTemplate = "robe_s01", weight = 120481}, -- Robe of Honor
{itemTemplate = "robe_s12", weight = 120491}, -- Grand Mayoral Robe
{itemTemplate = "robe_s27", weight = 120488}, -- Gunman's Duster
{itemTemplate = "shirt_s11", weight = 120481}, -- Wooly Shirt
{itemTemplate = "shirt_s24", weight = 120481}, -- Sports Wrap
{itemTemplate = "shirt_s30", weight = 120481}, -- Leather Trim Shirt
{itemTemplate = "skirt_s03", weight = 120481}, -- Extremely Revealing Skirt
{itemTemplate = "skirt_s11", weight = 120481}, -- Noble Skirt
{itemTemplate = "skirt_s12", weight = 120481}, -- Refined Skirt
{itemTemplate = "skirt_s13", weight = 120481}, -- Thin Pleated Skirt
{itemTemplate = "vest_s01", weight = 120481}, -- Belted Vest
{itemTemplate = "vest_s02", weight = 120481}, -- Crested Vest
{itemTemplate = "vest_s03", weight = 120481}, -- Short Vest
{itemTemplate = "vest_s11", weight = 120481}, -- Long Vest
{itemTemplate = "wke_shirt_s04", weight = 120481}, -- Crested Battle Padding
}
}
addLootGroupTemplate("wearables_scarce", wearables_scarce)
| agpl-3.0 |
henu/Urho3D | bin/Data/LuaScripts/47_Typography.lua | 11 | 6615 | -- Text rendering example.
-- Displays text at various sizes, with checkboxes to change the rendering parameters.
require "LuaScripts/Utilities/Sample"
-- Tag used to find all Text elements
local TEXT_TAG = "Typography_text_tag"
-- Top-level container for this sample's UI
local uielement = nil
function Start()
-- Execute the common startup for samples
SampleStart()
-- Enable OS cursor
input.mouseVisible = true
-- Load XML file containing default UI style sheet
local style = cache:GetResource("XMLFile", "UI/DefaultStyle.xml")
-- Set the loaded style as default style
ui.root.defaultStyle = style
-- Create a UIElement to hold all our content
-- (Don't modify the root directly, as the base Sample class uses it)
uielement = UIElement:new()
uielement:SetAlignment(HA_CENTER, VA_CENTER)
uielement:SetLayout(LM_VERTICAL, 10, IntRect(20, 40, 20, 40))
ui.root:AddChild(uielement)
-- Add some sample text
CreateText()
-- Add a checkbox to toggle the background color.
CreateCheckbox("White background", "HandleWhiteBackground")
:SetChecked(false)
-- Add a checkbox to toggle SRGB output conversion (if available).
-- This will give more correct text output for FreeType fonts, as the FreeType rasterizer
-- outputs linear coverage values rather than SRGB values. However, this feature isn't
-- available on all platforms.
CreateCheckbox("Graphics::SetSRGB", "HandleSRGB")
:SetChecked(graphics:GetSRGB())
-- Add a checkbox for the global ForceAutoHint setting. This affects character spacing.
CreateCheckbox("UI::SetForceAutoHint", "HandleForceAutoHint")
:SetChecked(ui:GetForceAutoHint())
-- Add a drop-down menu to control the font hinting level.
local levels = {
"FONT_HINT_LEVEL_NONE",
"FONT_HINT_LEVEL_LIGHT",
"FONT_HINT_LEVEL_NORMAL"
}
CreateMenu("UI::SetFontHintLevel", levels, "HandleFontHintLevel")
:SetSelection(ui:GetFontHintLevel())
-- Add a drop-down menu to control the subpixel threshold.
local thresholds = {
"0",
"3",
"6",
"9",
"12",
"15",
"18",
"21"
}
CreateMenu("UI::SetFontSubpixelThreshold", thresholds, "HandleFontSubpixel")
:SetSelection(ui:GetFontSubpixelThreshold() / 3)
-- Add a drop-down menu to control oversampling.
local limits = {
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8"
}
CreateMenu("UI::SetFontOversampling", limits, "HandleFontOversampling")
:SetSelection(ui:GetFontOversampling() - 1)
-- Set the mouse mode to use in the sample
SampleInitMouseMode(MM_FREE)
end
function CreateText()
local container = UIElement:new()
container:SetAlignment(HA_LEFT, VA_TOP)
container:SetLayout(LM_VERTICAL)
uielement:AddChild(container)
local font = cache:GetResource("Font", "Fonts/BlueHighway.ttf")
for size = 1, 18, 0.5 do
local text = Text:new()
text.text = "The quick brown fox jumps over the lazy dog (" .. size .. "pt)"
text:SetFont(font, size)
text:AddTag(TEXT_TAG)
container:AddChild(text)
end
end
function CreateCheckbox(label, handler)
local container = UIElement:new()
container:SetAlignment(HA_LEFT, VA_TOP)
container:SetLayout(LM_HORIZONTAL, 8)
uielement:AddChild(container)
local box = CheckBox:new()
container:AddChild(box)
box:SetStyleAuto()
local text = Text:new()
container:AddChild(text)
text.text = label
text:SetStyleAuto()
text:AddTag(TEXT_TAG)
SubscribeToEvent(box, "Toggled", handler)
return box
end
function CreateMenu(label, items, handler)
local container = UIElement:new()
container:SetAlignment(HA_LEFT, VA_TOP)
container:SetLayout(LM_HORIZONTAL, 8)
uielement:AddChild(container)
local text = Text:new()
container:AddChild(text)
text.text = label
text:SetStyleAuto()
text:AddTag(TEXT_TAG)
local list = DropDownList:new()
container:AddChild(list)
list:SetStyleAuto()
for i, item in ipairs(items) do
local t = Text:new()
list:AddItem(t)
t.text = item
t:SetStyleAuto()
t:SetMinWidth(t:GetRowWidth(0) + 10)
t:AddTag(TEXT_TAG)
end
text:SetMaxWidth(text:GetRowWidth(0))
SubscribeToEvent(list, "ItemSelected", handler)
return list
end
function HandleWhiteBackground(eventType, eventData)
local box = eventData["Element"]:GetPtr("CheckBox")
local checked = box:IsChecked()
local fg = checked and Color.BLACK or Color.WHITE
local bg = checked and Color.WHITE or Color.BLACK
renderer.defaultZone.fogColor = bg
local elements = uielement:GetChildrenWithTag(TEXT_TAG, true)
for i, element in ipairs(elements) do
element.color = fg
end
end
function HandleForceAutoHint(eventType, eventData)
local box = eventData["Element"]:GetPtr("CheckBox")
local checked = box:IsChecked()
ui:SetForceAutoHint(checked)
end
function HandleSRGB(eventType, eventData)
local box = eventData["Element"]:GetPtr("CheckBox")
local checked = box:IsChecked()
if graphics:GetSRGBWriteSupport() then
graphics:SetSRGB(checked)
else
log:Write(LOG_WARNING, "graphics:GetSRGBWriteSupport returned false")
end
end
function HandleFontHintLevel(eventType, eventData)
local list = eventData["Element"]:GetPtr("DropDownList")
local i = list:GetSelection()
ui:SetFontHintLevel(i)
end
function HandleFontSubpixel(eventType, eventData)
local list = eventData["Element"]:GetPtr("DropDownList")
local i = list:GetSelection()
ui:SetFontSubpixelThreshold(i * 3)
end
function HandleFontOversampling(eventType, eventData)
local list = eventData["Element"]:GetPtr("DropDownList")
local i = list:GetSelection()
ui:SetFontOversampling(i + 1)
end
-- Create XML patch instructions for screen joystick layout specific to this sample app
function GetScreenJoystickPatchString()
return
"<patch>" ..
" <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" ..
" <attribute name=\"Is Visible\" value=\"false\" />" ..
" </add>" ..
"</patch>"
end
| mit |
ozhanf/ozhan | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
helling34/skynet | lualib/snax/gateserver.lua | 5 | 3250 | local skynet = require "skynet"
local netpack = require "netpack"
local socketdriver = require "socketdriver"
local gateserver = {}
local socket -- listen socket
local queue -- message queue
local maxclient -- max client
local client_number = 0
local CMD = setmetatable({}, { __gc = function() netpack.clear(queue) end })
local nodelay = false
local connection = {}
function gateserver.openclient(fd)
if connection[fd] then
socketdriver.start(fd)
end
end
function gateserver.closeclient(fd)
local c = connection[fd]
if c then
connection[fd] = false
socketdriver.close(fd)
end
end
function gateserver.start(handler)
assert(handler.message)
assert(handler.connect)
function CMD.open( source, conf )
assert(not socket)
local address = conf.address or "0.0.0.0"
local port = assert(conf.port)
maxclient = conf.maxclient or 1024
nodelay = conf.nodelay
skynet.error(string.format("Listen on %s:%d", address, port))
socket = socketdriver.listen(address, port)
socketdriver.start(socket)
if handler.open then
return handler.open(source, conf)
end
end
function CMD.close()
assert(socket)
socketdriver.close(socket)
socket = nil
end
local MSG = {}
local function dispatch_msg(fd, msg, sz)
if connection[fd] then
handler.message(fd, msg, sz)
else
skynet.error(string.format("Drop message from fd (%d) : %s", fd, netpack.tostring(msg,sz)))
end
end
MSG.data = dispatch_msg
local function dispatch_queue()
local fd, msg, sz = netpack.pop(queue)
if fd then
-- may dispatch even the handler.message blocked
-- If the handler.message never block, the queue should be empty, so only fork once and then exit.
skynet.fork(dispatch_queue)
dispatch_msg(fd, msg, sz)
for fd, msg, sz in netpack.pop, queue do
dispatch_msg(fd, msg, sz)
end
end
end
MSG.more = dispatch_queue
function MSG.open(fd, msg)
if client_number >= maxclient then
socketdriver.close(fd)
return
end
if nodelay then
socketdriver.nodelay(fd)
end
connection[fd] = true
client_number = client_number + 1
handler.connect(fd, msg)
end
local function close_fd(fd)
local c = connection[fd]
if c ~= nil then
connection[fd] = nil
client_number = client_number - 1
end
end
function MSG.close(fd)
if fd ~= socket then
if handler.disconnect then
handler.disconnect(fd)
end
close_fd(fd)
end
end
function MSG.error(fd, msg)
if fd == socket then
socketdriver.close(fd)
skynet.error(msg)
else
if handler.error then
handler.error(fd, msg)
end
close_fd(fd)
end
end
function MSG.warning(fd, size)
if handler.warning then
handler.warning(fd, size)
end
end
skynet.register_protocol {
name = "socket",
id = skynet.PTYPE_SOCKET, -- PTYPE_SOCKET = 6
unpack = function ( msg, sz )
return netpack.filter( queue, msg, sz)
end,
dispatch = function (_, _, q, type, ...)
queue = q
if type then
MSG[type](...)
end
end
}
skynet.start(function()
skynet.dispatch("lua", function (_, address, cmd, ...)
local f = CMD[cmd]
if f then
skynet.ret(skynet.pack(f(address, ...)))
else
skynet.ret(skynet.pack(handler.command(cmd, address, ...)))
end
end)
end)
end
return gateserver
| mit |
tfagit/telegram-bot | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
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 = {
"!qr [text]",
'!qr "[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 = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
xztraz/domoticz | dzVents/runtime/device-adapters/Adapters.lua | 2 | 4207 | local genericAdapter = require('generic_device')
local deviceAdapters = {
'airquality_device',
'alert_device',
'ampere_1_phase_device',
'ampere_3_phase_device',
'barometer_device',
'counter_device',
'custom_sensor_device',
'distance_device',
'electric_usage_device',
'evohome_device',
'gas_device',
'group_device',
'humidity_device',
'kwh_device',
'leafwetness_device',
'logitech_media_server_device',
'lux_device',
'onkyo_device',
'opentherm_gateway_device',
'p1_smartmeter_device',
'percentage_device',
'pressure_device',
'rain_device',
'rgbw_device',
'scaleweight_device',
'scene_device',
'security_device',
'solar_radiation_device',
'soilmoisture_device',
'soundlevel_device',
'switch_device',
'thermostat_setpoint_device',
'temperature_device',
'temperature_barometer_device',
'temperature_humidity_device',
'temperature_humidity_barometer_device',
'text_device',
'uv_device',
'visibility_device',
'voltage_device',
'waterflow_device',
'wind_device',
'zone_heating_device',
'zwave_thermostat_mode_device',
'kodi_device'
}
local utils = require('Utils')
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
local function DeviceAdapters(dummyLogger)
local self = {}
self.name = 'Adapter manager'
function self.getDeviceAdapters(device)
-- find a matching adapters
local adapters = {}
for i, adapterName in pairs(deviceAdapters) do
-- do a safe call and catch possible errors
ok, adapter = pcall(require, adapterName)
if (not ok) then
utils.log(adapter, utils.LOG_ERROR)
else
if (adapter.baseType == device.baseType) then
local matches = adapter.matches(device, self)
if (matches) then
table.insert(adapters, adapter)
end
end
end
end
return adapters
end
self.genericAdapter = genericAdapter
self.deviceAdapters = deviceAdapters
function self.parseFormatted (sValue, radixSeparator)
local splitted = string.split(sValue, ' ')
local sV = splitted[1]
local unit = splitted[2]
-- normalize radix to .
if (sV ~= nil) then
sV = string.gsub(sV, '%' .. radixSeparator, '.')
end
local value = sV ~= nil and tonumber(sV) or 0
return {
['value'] = value,
['unit'] = unit ~= nil and unit or ''
}
end
function self.getDummyMethod(device, name)
if (dummyLogger ~= nil) then
dummyLogger(device, name)
end
return function()
utils.log('Method ' ..
name ..
' is not available for device "' ..
device.name ..
'" (deviceType=' .. device.deviceType .. ', deviceSubType=' .. device.deviceSubType .. '). ' ..
'If you believe this is not correct, please report.',
utils.LOG_ERROR)
end
end
function self.addDummyMethod(device, name)
if (device[name] == nil) then
device[name] = self.getDummyMethod(device, name)
end
end
function self.round(num, numDecimalPlaces)
if (num == nil) then
--print(debug.traceback())
num = 0
end
local mult = 10 ^ (numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
self.states = {
on = { b = true, inv = 'Off' },
open = { b = true, inv = 'Off' },
['group on'] = { b = true },
panic = { b = true, inv = 'Off' },
normal = { b = true, inv = 'Alarm' },
alarm = { b = true, inv = 'Normal' },
chime = { b = true },
video = { b = true },
audio = { b = true },
photo = { b = true },
playing = { b = true, inv = 'Pause' },
motion = { b = true },
off = { b = false, inv = 'On' },
closed = { b = false, inv = 'On' },
unlocked = { b = false, inv = 'On' },
locked = { b = true, inv = 'Off' },
['group off'] = { b = false },
['panic end'] = { b = false },
['no motion'] = { b = false, inv = 'Off' },
stop = { b = false, inv = 'Open' },
stopped = { b = false },
paused = { b = false, inv = 'Play' },
['all on'] = { b = true, inv = 'All Off' },
['all off'] = { b = false, inv = 'All On' },
['nightmode'] = { b = true, inv = 'Off' },
['set to white'] = { b = true, inv = 'Off' },
['set kelvin level'] = { b = true, inv = 'Off' },
}
return self
end
return DeviceAdapters
| gpl-3.0 |
garoose/eecs494.p2 | dev/premake/premake/src/actions/make/make_csharp.lua | 18 | 8352 | --
-- make_csharp.lua
-- Generate a C# project makefile.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
--
-- Given a .resx resource file, builds the path to corresponding .resource
-- file, matching the behavior and naming of Visual Studio.
--
local function getresourcefilename(cfg, fname)
if path.getextension(fname) == ".resx" then
local name = cfg.buildtarget.basename .. "."
local dir = path.getdirectory(fname)
if dir ~= "." then
name = name .. path.translate(dir, ".") .. "."
end
return "$(OBJDIR)/" .. _MAKE.esc(name .. path.getbasename(fname)) .. ".resources"
else
return fname
end
end
--
-- Main function
--
function premake.make_csharp(prj)
local csc = premake.dotnet
-- Do some processing up front: build a list of configuration-dependent libraries.
-- Libraries that are built to a location other than $(TARGETDIR) will need to
-- be copied so they can be found at runtime.
local cfglibs = { }
local cfgpairs = { }
local anycfg
for cfg in premake.eachconfig(prj) do
anycfg = cfg
cfglibs[cfg] = premake.getlinks(cfg, "siblings", "fullpath")
cfgpairs[cfg] = { }
for _, fname in ipairs(cfglibs[cfg]) do
if path.getdirectory(fname) ~= cfg.buildtarget.directory then
cfgpairs[cfg]["$(TARGETDIR)/" .. _MAKE.esc(path.getname(fname))] = _MAKE.esc(fname)
end
end
end
-- sort the files into categories, based on their build action
local sources = {}
local embedded = { }
local copypairs = { }
for fcfg in premake.project.eachfile(prj) do
local action = csc.getbuildaction(fcfg)
if action == "Compile" then
table.insert(sources, fcfg.name)
elseif action == "EmbeddedResource" then
table.insert(embedded, fcfg.name)
elseif action == "Content" then
copypairs["$(TARGETDIR)/" .. _MAKE.esc(path.getname(fcfg.name))] = _MAKE.esc(fcfg.name)
elseif path.getname(fcfg.name):lower() == "app.config" then
copypairs["$(TARGET).config"] = _MAKE.esc(fcfg.name)
end
end
-- Any assemblies that are on the library search paths should be copied
-- to $(TARGETDIR) so they can be found at runtime
local paths = table.translate(prj.libdirs, function(v) return path.join(prj.basedir, v) end)
paths = table.join({prj.basedir}, paths)
for _, libname in ipairs(premake.getlinks(prj, "system", "fullpath")) do
local libdir = os.pathsearch(libname..".dll", unpack(paths))
if (libdir) then
local target = "$(TARGETDIR)/" .. _MAKE.esc(path.getname(libname))
local source = path.getrelative(prj.basedir, path.join(libdir, libname))..".dll"
copypairs[target] = _MAKE.esc(source)
end
end
-- end of preprocessing --
-- set up the environment
_p('# %s project makefile autogenerated by Premake', premake.action.current().shortname)
_p('')
_p('ifndef config')
_p(' config=%s', _MAKE.esc(prj.configurations[1]:lower()))
_p('endif')
_p('')
_p('ifndef verbose')
_p(' SILENT = @')
_p('endif')
_p('')
_p('ifndef CSC')
_p(' CSC=%s', csc.getcompilervar(prj))
_p('endif')
_p('')
_p('ifndef RESGEN')
_p(' RESGEN=resgen')
_p('endif')
_p('')
-- Platforms aren't support for .NET projects, but I need the ability to match
-- the buildcfg:platform identifiers with a block of settings. So enumerate the
-- pairs the same way I do for C/C++ projects, but always use the generic settings
local platforms = premake.filterplatforms(prj.solution, premake[_OPTIONS.cc].platforms)
table.insert(platforms, 1, "")
-- write the configuration blocks
for cfg in premake.eachconfig(prj) do
premake.gmake_cs_config(cfg, csc, cfglibs)
end
-- set project level values
_p('# To maintain compatibility with VS.NET, these values must be set at the project level')
_p('TARGET := $(TARGETDIR)/%s', _MAKE.esc(prj.buildtarget.name))
_p('FLAGS += /t:%s %s', csc.getkind(prj):lower(), table.implode(_MAKE.esc(prj.libdirs), "/lib:", "", " "))
_p('REFERENCES += %s', table.implode(_MAKE.esc(premake.getlinks(prj, "system", "basename")), "/r:", ".dll", " "))
_p('')
-- list source files
_p('SOURCES := \\')
for _, fname in ipairs(sources) do
_p('\t%s \\', _MAKE.esc(path.translate(fname)))
end
_p('')
_p('EMBEDFILES := \\')
for _, fname in ipairs(embedded) do
_p('\t%s \\', getresourcefilename(prj, fname))
end
_p('')
_p('COPYFILES += \\')
for target, source in pairs(cfgpairs[anycfg]) do
_p('\t%s \\', target)
end
for target, source in pairs(copypairs) do
_p('\t%s \\', target)
end
_p('')
-- identify the shell type
_p('SHELLTYPE := msdos')
_p('ifeq (,$(ComSpec)$(COMSPEC))')
_p(' SHELLTYPE := posix')
_p('endif')
_p('ifeq (/bin,$(findstring /bin,$(SHELL)))')
_p(' SHELLTYPE := posix')
_p('endif')
_p('')
-- main build rule(s)
_p('.PHONY: clean prebuild prelink')
_p('')
_p('all: $(TARGETDIR) $(OBJDIR) prebuild $(EMBEDFILES) $(COPYFILES) prelink $(TARGET)')
_p('')
_p('$(TARGET): $(SOURCES) $(EMBEDFILES) $(DEPENDS)')
_p('\t$(SILENT) $(CSC) /nologo /out:$@ $(FLAGS) $(REFERENCES) $(SOURCES) $(patsubst %%,/resource:%%,$(EMBEDFILES))')
_p('\t$(POSTBUILDCMDS)')
_p('')
-- Create destination directories. Can't use $@ for this because it loses the
-- escaping, causing issues with spaces and parenthesis
_p('$(TARGETDIR):')
premake.make_mkdirrule("$(TARGETDIR)")
_p('$(OBJDIR):')
premake.make_mkdirrule("$(OBJDIR)")
-- clean target
_p('clean:')
_p('\t@echo Cleaning %s', prj.name)
_p('ifeq (posix,$(SHELLTYPE))')
_p('\t$(SILENT) rm -f $(TARGETDIR)/%s.* $(COPYFILES)', prj.buildtarget.basename)
_p('\t$(SILENT) rm -rf $(OBJDIR)')
_p('else')
_p('\t$(SILENT) if exist $(subst /,\\\\,$(TARGETDIR)/%s.*) del $(subst /,\\\\,$(TARGETDIR)/%s.*)', prj.buildtarget.basename, prj.buildtarget.basename)
for target, source in pairs(cfgpairs[anycfg]) do
_p('\t$(SILENT) if exist $(subst /,\\\\,%s) del $(subst /,\\\\,%s)', target, target)
end
for target, source in pairs(copypairs) do
_p('\t$(SILENT) if exist $(subst /,\\\\,%s) del $(subst /,\\\\,%s)', target, target)
end
_p('\t$(SILENT) if exist $(subst /,\\\\,$(OBJDIR)) rmdir /s /q $(subst /,\\\\,$(OBJDIR))')
_p('endif')
_p('')
-- custom build step targets
_p('prebuild:')
_p('\t$(PREBUILDCMDS)')
_p('')
_p('prelink:')
_p('\t$(PRELINKCMDS)')
_p('')
-- per-file rules
_p('# Per-configuration copied file rules')
for cfg in premake.eachconfig(prj) do
_p('ifneq (,$(findstring %s,$(config)))', _MAKE.esc(cfg.name:lower()))
for target, source in pairs(cfgpairs[cfg]) do
premake.make_copyrule(source, target)
end
_p('endif')
_p('')
end
_p('# Copied file rules')
for target, source in pairs(copypairs) do
premake.make_copyrule(source, target)
end
_p('# Embedded file rules')
for _, fname in ipairs(embedded) do
if path.getextension(fname) == ".resx" then
_p('%s: %s', getresourcefilename(prj, fname), _MAKE.esc(fname))
_p('\t$(SILENT) $(RESGEN) $^ $@')
end
_p('')
end
end
--
-- Write a block of configuration settings.
--
function premake.gmake_cs_config(cfg, csc, cfglibs)
_p('ifneq (,$(findstring %s,$(config)))', _MAKE.esc(cfg.name:lower()))
_p(' TARGETDIR := %s', _MAKE.esc(cfg.buildtarget.directory))
_p(' OBJDIR := %s', _MAKE.esc(cfg.objectsdir))
_p(' DEPENDS := %s', table.concat(_MAKE.esc(premake.getlinks(cfg, "dependencies", "fullpath")), " "))
_p(' REFERENCES := %s', table.implode(_MAKE.esc(cfglibs[cfg]), "/r:", "", " "))
_p(' FLAGS += %s %s', table.implode(cfg.defines, "/d:", "", " "), table.concat(table.join(csc.getflags(cfg), cfg.buildoptions), " "))
_p(' define PREBUILDCMDS')
if #cfg.prebuildcommands > 0 then
_p('\t@echo Running pre-build commands')
_p('\t%s', table.implode(cfg.prebuildcommands, "", "", "\n\t"))
end
_p(' endef')
_p(' define PRELINKCMDS')
if #cfg.prelinkcommands > 0 then
_p('\t@echo Running pre-link commands')
_p('\t%s', table.implode(cfg.prelinkcommands, "", "", "\n\t"))
end
_p(' endef')
_p(' define POSTBUILDCMDS')
if #cfg.postbuildcommands > 0 then
_p('\t@echo Running post-build commands')
_p('\t%s', table.implode(cfg.postbuildcommands, "", "", "\n\t"))
end
_p(' endef')
_p('endif')
_p('')
end
| mit |
MikeMcShaffry/gamecode3 | Dev/Source/3rdParty/LuaPlus/Src/Modules/socket/src/socket.lua | 146 | 4061 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket.core")
module("socket")
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function connect(address, port, laddress, lport)
local sock, err = socket.tcp()
if not sock then return nil, err end
if laddress then
local res, err = sock:bind(laddress, lport, -1)
if not res then return nil, err end
end
local res, err = sock:connect(address, port)
if not res then return nil, err end
return sock
end
function bind(host, port, backlog)
local sock, err = socket.tcp()
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
local res, err = sock:bind(host, port)
if not res then return nil, err end
res, err = sock:listen(backlog)
if not res then return nil, err end
return sock
end
try = newtry()
function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
sourcet = {}
sinkt = {}
BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
sink = choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
source = choose(sourcet)
| lgpl-2.1 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/saber2hHit1.lua | 2 | 2377 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser 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
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
Saber2hHit1Command = {
name = "saber2hhit1",
damageMultiplier = 1.25,
speedMultiplier = 1.25,
forceCostMultiplier = 1.0,
animationCRC = hashCode("combo_2c_light"),
combatSpam = "saber2hhit1",
poolsToDamage = RANDOM_ATTRIBUTE,
weaponType = TWOHANDJEDIWEAPON,
range = -1
}
AddCommand(Saber2hHit1Command)
| agpl-3.0 |
thiolliere/ultimate-warfare | src/weapon1.lua | 1 | 2154 | weapon[1]={}
weapon[1].impulse=200
weapon[1].recul=weapon[1].impulse
weapon[1].bulletnumber=0
weapon[1].bulletnumbermax=10
weapon[1].reloadingmagazinetime=70
weapon[1].reloadingbullettime=10
weapon[1].density=0.7
weapon[1].width=0.5*meter
weapon[1].height=0.3*meter
weapon[1].magazine=5
weapon[1].bullet={}
weapon[1].shoot = function ( x,y,orientation)
local i=weapon[1].bulletnumber
weapon[1].bullet[i]={}
weapon[1].bullet[i].body=love.physics.newBody( world, x, y, "dynamic")
weapon[1].bullet[i].shape=love.physics.newRectangleShape(weapon[1].width,weapon[1].height)
weapon[1].bullet[i].fixture=love.physics.newFixture(weapon[1].bullet[i].body,weapon[1].bullet[i].shape,weapon[1].density)
weapon[1].bullet[i].fixture:setUserData("bullet")
weapon[1].bullet[i].fixture:setCategory(3)
weapon[1].bullet[i].body:setBullet(true)
weapon[1].bullet[i].draw=function()
if weapon[1].bullet[i].body:isActive() then
love.graphics.setColor(10,10,10)
love.graphics.polygon("fill",weapon[1].bullet[i].body:getWorldPoints(weapon[1].bullet[i].shape:getPoints()))
end
end
weapon[1].bullet[i].body:applyLinearImpulse(orientation*weapon[1].impulse,0)
weapon[1].bulletnumber=weapon[1].bulletnumber+1%32
end
weapon[1].trigger = nil
weapon[1].trigger = function(character)
local o = character.orientation
local angle = character.body:getAngle()
local x=character.body:getX()
local y=character.body:getY()
if character.charge then
character.body:applyLinearImpulse(-weapon[1].recul*o,0,x+math.sin(angle),y-math.cos(angle)) -- à changer avec la position de l'arme ou pas
weapon[1].shoot(x+o*character.height*1.5,y,o)
character.magazine=character.magazine-1
character.charge=false
character.reloading=0
end
end
weapon[1].update=nil
weapon[1].update=function(character)
if not character.charge then
character.reloading=character.reloading+1
if character.magazine==0 then
if character.reloading>weapon[1].reloadingmagazinetime then
character.charge=true
character.magazine=weapon[1].magazine
end
else
if character.reloading>weapon[1].reloadingbullettime then
character.charge=true
end
end
end
end
| mit |
LomoX-Offical/nginx-openresty-windows | src/lua-resty-core-0.1.12/lib/resty/core/regex.lua | 1 | 24048 | -- Copyright (C) Yichun Zhang (agentzh)
local ffi = require 'ffi'
local base = require "resty.core.base"
local bit = require "bit"
require "resty.core.time" -- for ngx.now used by resty.lrucache
local lrucache = require "resty.lrucache"
local lrucache_get = lrucache.get
local lrucache_set = lrucache.set
local ffi_string = ffi.string
local ffi_gc = ffi.gc
local ffi_copy = ffi.copy
local ffi_cast = ffi.cast
local C = ffi.C
local bor = bit.bor
local band = bit.band
local lshift = bit.lshift
local sub = string.sub
local fmt = string.format
local byte = string.byte
local ngx = ngx
local type = type
local tostring = tostring
local error = error
local get_string_buf = base.get_string_buf
local get_string_buf_size = base.get_string_buf_size
local new_tab = base.new_tab
if not ngx.re then
ngx.re = {}
end
local MAX_ERR_MSG_LEN = 128
local FLAG_COMPILE_ONCE = 0x01
local FLAG_DFA = 0x02
local FLAG_JIT = 0x04
local FLAG_DUPNAMES = 0x08
local FLAG_NO_UTF8_CHECK = 0x10
local PCRE_CASELESS = 0x0000001
local PCRE_MULTILINE = 0x0000002
local PCRE_DOTALL = 0x0000004
local PCRE_EXTENDED = 0x0000008
local PCRE_ANCHORED = 0x0000010
local PCRE_UTF8 = 0x0000800
local PCRE_DUPNAMES = 0x0080000
local PCRE_JAVASCRIPT_COMPAT = 0x2000000
local PCRE_ERROR_NOMATCH = -1
local regex_match_cache
local regex_sub_func_cache = new_tab(0, 4)
local regex_sub_str_cache = new_tab(0, 4)
local max_regex_cache_size
local regex_cache_size = 0
local script_engine
ffi.cdef[[
typedef struct {
ngx_str_t value;
void *lengths;
void *values;
} ngx_http_lua_complex_value_t;
typedef struct {
void *pool;
unsigned char *name_table;
int name_count;
int name_entry_size;
int ncaptures;
int *captures;
void *regex;
void *regex_sd;
ngx_http_lua_complex_value_t *replace;
const char *pattern;
} ngx_http_lua_regex_t;
ngx_http_lua_regex_t *
ngx_http_lua_ffi_compile_regex(const unsigned char *pat,
size_t pat_len, int flags,
int pcre_opts, unsigned char *errstr,
size_t errstr_size);
int ngx_http_lua_ffi_exec_regex(ngx_http_lua_regex_t *re, int flags,
const unsigned char *s, size_t len, int pos);
void ngx_http_lua_ffi_destroy_regex(ngx_http_lua_regex_t *re);
int ngx_http_lua_ffi_compile_replace_template(ngx_http_lua_regex_t *re,
const unsigned char
*replace_data,
size_t replace_len);
struct ngx_http_lua_script_engine_s;
typedef struct ngx_http_lua_script_engine_s *ngx_http_lua_script_engine_t;
ngx_http_lua_script_engine_t *ngx_http_lua_ffi_create_script_engine(void);
void ngx_http_lua_ffi_init_script_engine(ngx_http_lua_script_engine_t *e,
const unsigned char *subj,
ngx_http_lua_regex_t *compiled,
int count);
void ngx_http_lua_ffi_destroy_script_engine(
ngx_http_lua_script_engine_t *e);
size_t ngx_http_lua_ffi_script_eval_len(ngx_http_lua_script_engine_t *e,
ngx_http_lua_complex_value_t *cv);
size_t ngx_http_lua_ffi_script_eval_data(ngx_http_lua_script_engine_t *e,
ngx_http_lua_complex_value_t *cv,
unsigned char *dst);
uint32_t ngx_http_lua_ffi_max_regex_cache_size(void);
]]
local c_str_type = ffi.typeof("const char *")
local cached_re_opts = new_tab(0, 4)
local _M = {
version = base.version
}
local buf_grow_ratio = 2
function _M.set_buf_grow_ratio(ratio)
buf_grow_ratio = ratio
end
local function get_max_regex_cache_size()
if max_regex_cache_size then
return max_regex_cache_size
end
max_regex_cache_size = C.ngx_http_lua_ffi_max_regex_cache_size()
return max_regex_cache_size
end
local regex_cache_is_empty = true
function _M.is_regex_cache_empty()
return regex_cache_is_empty
end
local function lrucache_set_wrapper(...)
regex_cache_is_empty = false
lrucache_set(...)
end
local function parse_regex_opts(opts)
local t = cached_re_opts[opts]
if t then
return t[1], t[2]
end
local flags = 0
local pcre_opts = 0
local len = #opts
for i = 1, len do
local opt = byte(opts, i)
if opt == byte("o") then
flags = bor(flags, FLAG_COMPILE_ONCE)
elseif opt == byte("j") then
flags = bor(flags, FLAG_JIT)
elseif opt == byte("i") then
pcre_opts = bor(pcre_opts, PCRE_CASELESS)
elseif opt == byte("s") then
pcre_opts = bor(pcre_opts, PCRE_DOTALL)
elseif opt == byte("m") then
pcre_opts = bor(pcre_opts, PCRE_MULTILINE)
elseif opt == byte("u") then
pcre_opts = bor(pcre_opts, PCRE_UTF8)
elseif opt == byte("U") then
pcre_opts = bor(pcre_opts, PCRE_UTF8)
flags = bor(flags, FLAG_NO_UTF8_CHECK)
elseif opt == byte("x") then
pcre_opts = bor(pcre_opts, PCRE_EXTENDED)
elseif opt == byte("d") then
flags = bor(flags, FLAG_DFA)
elseif opt == byte("a") then
pcre_opts = bor(pcre_opts, PCRE_ANCHORED)
elseif opt == byte("D") then
pcre_opts = bor(pcre_opts, PCRE_DUPNAMES)
flags = bor(flags, FLAG_DUPNAMES)
elseif opt == byte("J") then
pcre_opts = bor(pcre_opts, PCRE_JAVASCRIPT_COMPAT)
else
return error(fmt('unknown flag "%s" (flags "%s")',
sub(opts, i, i), opts))
end
end
cached_re_opts[opts] = {flags, pcre_opts}
return flags, pcre_opts
end
local function collect_named_captures(compiled, flags, res)
local name_count = compiled.name_count
local name_table = compiled.name_table
local entry_size = compiled.name_entry_size
local ind = 0
local dup_names = (band(flags, FLAG_DUPNAMES) ~= 0)
for i = 1, name_count do
local n = bor(lshift(name_table[ind], 8), name_table[ind + 1])
-- ngx.say("n = ", n)
local name = ffi_string(name_table + ind + 2)
local cap = res[n]
if dup_names then
-- unmatched captures (false) are not collected
if cap then
local old = res[name]
if old then
old[#old + 1] = cap
else
res[name] = {cap}
end
end
else
res[name] = cap
end
ind = ind + entry_size
end
end
local function collect_captures(compiled, rc, subj, flags, res)
local cap = compiled.captures
local ncap = compiled.ncaptures
local name_count = compiled.name_count
if not res then
res = new_tab(ncap, name_count)
end
local i = 0
local n = 0
while i <= ncap do
if i > rc then
res[i] = false
else
local from = cap[n]
if from >= 0 then
local to = cap[n + 1]
res[i] = sub(subj, from + 1, to)
else
res[i] = false
end
end
i = i + 1
n = n + 2
end
if name_count > 0 then
collect_named_captures(compiled, flags, res)
end
return res
end
_M.collect_captures = collect_captures
local function destroy_compiled_regex(compiled)
C.ngx_http_lua_ffi_destroy_regex(ffi_gc(compiled, nil))
end
_M.destroy_compiled_regex = destroy_compiled_regex
local function re_match_compile(regex, opts)
local flags = 0
local pcre_opts = 0
if opts then
flags, pcre_opts = parse_regex_opts(opts)
else
opts = ""
end
local compiled, key
local compile_once = (band(flags, FLAG_COMPILE_ONCE) == 1)
-- FIXME: better put this in the outer scope when fixing the ngx.re API's
-- compatibility in the init_by_lua* context.
if not regex_match_cache then
local sz = get_max_regex_cache_size()
if sz <= 0 then
compile_once = false
else
regex_match_cache = lrucache.new(sz)
end
end
if compile_once then
key = regex .. '\0' .. opts
compiled = lrucache_get(regex_match_cache, key)
end
-- compile the regex
if compiled == nil then
-- print("compiled regex not found, compiling regex...")
local errbuf = get_string_buf(MAX_ERR_MSG_LEN)
compiled = C.ngx_http_lua_ffi_compile_regex(regex, #regex,
flags, pcre_opts,
errbuf, MAX_ERR_MSG_LEN)
if compiled == nil then
return nil, ffi_string(errbuf)
end
ffi_gc(compiled, C.ngx_http_lua_ffi_destroy_regex)
-- print("ncaptures: ", compiled.ncaptures)
if compile_once then
-- print("inserting compiled regex into cache")
lrucache_set_wrapper(regex_match_cache, key, compiled)
end
end
return compiled, compile_once, flags
end
_M.re_match_compile = re_match_compile
local function re_match_helper(subj, regex, opts, ctx, want_caps, res, nth)
-- we need to cast this to strings to avoid exceptions when they are
-- something else.
subj = tostring(subj)
local compiled, compile_once, flags = re_match_compile(regex, opts)
if compiled == nil then
-- compiled_once holds the error string
if not want_caps then
return nil, nil, compile_once
end
return nil, compile_once
end
-- exec the compiled regex
local rc
do
local pos
if ctx then
pos = ctx.pos
if not pos or pos <= 0 then
pos = 0
else
pos = pos - 1
end
else
pos = 0
end
rc = C.ngx_http_lua_ffi_exec_regex(compiled, flags, subj, #subj, pos)
end
if rc == PCRE_ERROR_NOMATCH then
if not compile_once then
destroy_compiled_regex(compiled)
end
return nil
end
if rc < 0 then
if not compile_once then
destroy_compiled_regex(compiled)
end
if not want_caps then
return nil, nil, "pcre_exec() failed: " .. rc
end
return nil, "pcre_exec() failed: " .. rc
end
if rc == 0 then
if band(flags, FLAG_DFA) == 0 then
if not want_caps then
return nil, nil, "capture size too small"
end
return nil, "capture size too small"
end
rc = 1
end
-- print("cap 0: ", compiled.captures[0])
-- print("cap 1: ", compiled.captures[1])
if ctx then
ctx.pos = compiled.captures[1] + 1
end
if not want_caps then
if not nth or nth < 0 then
nth = 0
end
if nth > compiled.ncaptures then
return nil, nil, "nth out of bound"
end
if nth >= rc then
return nil, nil
end
local from = compiled.captures[nth * 2] + 1
local to = compiled.captures[nth * 2 + 1]
if from < 0 or to < 0 then
return nil, nil
end
return from, to
end
res = collect_captures(compiled, rc, subj, flags, res)
if not compile_once then
destroy_compiled_regex(compiled)
end
return res
end
function ngx.re.match(subj, regex, opts, ctx, res)
return re_match_helper(subj, regex, opts, ctx, true, res)
end
function ngx.re.find(subj, regex, opts, ctx, nth)
return re_match_helper(subj, regex, opts, ctx, false, nil, nth)
end
local function new_script_engine(subj, compiled, count)
if not script_engine then
script_engine = C.ngx_http_lua_ffi_create_script_engine()
if script_engine == nil then
return nil
end
ffi_gc(script_engine, C.ngx_http_lua_ffi_destroy_script_engine)
end
C.ngx_http_lua_ffi_init_script_engine(script_engine, subj, compiled,
count)
return script_engine
end
local function check_buf_size(buf, buf_size, pos, len, new_len, must_alloc)
if new_len > buf_size then
buf_size = buf_size * buf_grow_ratio
if buf_size < new_len then
buf_size = new_len
end
local new_buf = get_string_buf(buf_size, must_alloc)
ffi_copy(new_buf, buf, len)
buf = new_buf
pos = buf + len
end
return buf, buf_size, pos, new_len
end
_M.check_buf_size = check_buf_size
local function re_sub_compile(regex, opts, replace, func)
local flags = 0
local pcre_opts = 0
if opts then
flags, pcre_opts = parse_regex_opts(opts)
else
opts = ""
end
local compiled
local compile_once = (band(flags, FLAG_COMPILE_ONCE) == 1)
if compile_once then
if func then
local subcache = regex_sub_func_cache[opts]
if subcache then
-- print("cache hit!")
compiled = subcache[regex]
end
else
local subcache = regex_sub_str_cache[opts]
if subcache then
local subsubcache = subcache[regex]
if subsubcache then
-- print("cache hit!")
compiled = subsubcache[replace]
end
end
end
end
-- compile the regex
if compiled == nil then
-- print("compiled regex not found, compiling regex...")
local errbuf = get_string_buf(MAX_ERR_MSG_LEN)
compiled = C.ngx_http_lua_ffi_compile_regex(regex, #regex, flags,
pcre_opts, errbuf,
MAX_ERR_MSG_LEN)
if compiled == nil then
return nil, ffi_string(errbuf)
end
ffi_gc(compiled, C.ngx_http_lua_ffi_destroy_regex)
if func == nil then
local rc =
C.ngx_http_lua_ffi_compile_replace_template(compiled,
replace, #replace)
if rc ~= 0 then
if not compile_once then
destroy_compiled_regex(compiled)
end
return nil, "failed to compile the replacement template"
end
end
-- print("ncaptures: ", compiled.ncaptures)
if compile_once then
if regex_cache_size < get_max_regex_cache_size() then
-- print("inserting compiled regex into cache")
if func then
local subcache = regex_sub_func_cache[opts]
if not subcache then
regex_sub_func_cache[opts] = {[regex] = compiled}
else
subcache[regex] = compiled
end
else
local subcache = regex_sub_str_cache[opts]
if not subcache then
regex_sub_str_cache[opts] =
{[regex] = {[replace] = compiled}}
else
local subsubcache = subcache[regex]
if not subsubcache then
subcache[regex] = {[replace] = compiled}
else
subsubcache[replace] = compiled
end
end
end
regex_cache_size = regex_cache_size + 1
else
compile_once = false
end
end
end
return compiled, compile_once, flags
end
_M.re_sub_compile = re_sub_compile
local function re_sub_func_helper(subj, regex, replace, opts, global)
local compiled, compile_once, flags =
re_sub_compile(regex, opts, nil, replace)
if not compiled then
-- error string is in compile_once
return nil, nil, compile_once
end
-- exec the compiled regex
subj = tostring(subj)
local subj_len = #subj
local count = 0
local pos = 0
local cp_pos = 0
local dst_buf_size = get_string_buf_size()
-- Note: we have to always allocate the string buffer because
-- the user might call whatever resty.core's API functions recursively
-- in the user callback function.
local dst_buf = get_string_buf(dst_buf_size, true)
local dst_pos = dst_buf
local dst_len = 0
while true do
local rc = C.ngx_http_lua_ffi_exec_regex(compiled, flags, subj,
subj_len, pos)
if rc == PCRE_ERROR_NOMATCH then
break
end
if rc < 0 then
if not compile_once then
destroy_compiled_regex(compiled)
end
return nil, nil, "pcre_exec() failed: " .. rc
end
if rc == 0 then
if band(flags, FLAG_DFA) == 0 then
if not compile_once then
destroy_compiled_regex(compiled)
end
return nil, nil, "capture size too small"
end
rc = 1
end
count = count + 1
local prefix_len = compiled.captures[0] - cp_pos
local res = collect_captures(compiled, rc, subj, flags)
local piece = tostring(replace(res))
local piece_len = #piece
local new_dst_len = dst_len + prefix_len + piece_len
dst_buf, dst_buf_size, dst_pos, dst_len =
check_buf_size(dst_buf, dst_buf_size, dst_pos, dst_len,
new_dst_len, true)
if prefix_len > 0 then
ffi_copy(dst_pos, ffi_cast(c_str_type, subj) + cp_pos,
prefix_len)
dst_pos = dst_pos + prefix_len
end
if piece_len > 0 then
ffi_copy(dst_pos, piece, piece_len)
dst_pos = dst_pos + piece_len
end
cp_pos = compiled.captures[1]
pos = cp_pos
if pos == compiled.captures[0] then
pos = pos + 1
if pos > subj_len then
break
end
end
if not global then
break
end
end
if not compile_once then
destroy_compiled_regex(compiled)
end
if count > 0 then
if pos < subj_len then
local suffix_len = subj_len - cp_pos
local new_dst_len = dst_len + suffix_len
local _
dst_buf, _, dst_pos, dst_len =
check_buf_size(dst_buf, dst_buf_size, dst_pos, dst_len,
new_dst_len, true)
ffi_copy(dst_pos, ffi_cast(c_str_type, subj) + cp_pos,
suffix_len)
end
return ffi_string(dst_buf, dst_len), count
end
return subj, 0
end
local function re_sub_str_helper(subj, regex, replace, opts, global)
local compiled, compile_once, flags =
re_sub_compile(regex, opts, replace, nil)
if not compiled then
-- error string is in compile_once
return nil, nil, compile_once
end
-- exec the compiled regex
subj = tostring(subj)
local subj_len = #subj
local count = 0
local pos = 0
local cp_pos = 0
local dst_buf_size = get_string_buf_size()
local dst_buf = get_string_buf(dst_buf_size)
local dst_pos = dst_buf
local dst_len = 0
while true do
local rc = C.ngx_http_lua_ffi_exec_regex(compiled, flags, subj,
subj_len, pos)
if rc == PCRE_ERROR_NOMATCH then
break
end
if rc < 0 then
if not compile_once then
destroy_compiled_regex(compiled)
end
return nil, nil, "pcre_exec() failed: " .. rc
end
if rc == 0 then
if band(flags, FLAG_DFA) == 0 then
if not compile_once then
destroy_compiled_regex(compiled)
end
return nil, nil, "capture size too small"
end
rc = 1
end
count = count + 1
local prefix_len = compiled.captures[0] - cp_pos
local cv = compiled.replace
if cv.lengths ~= nil then
local e = new_script_engine(subj, compiled, rc)
if e == nil then
return nil, nil, "failed to create script engine"
end
local bit_len = C.ngx_http_lua_ffi_script_eval_len(e, cv)
local new_dst_len = dst_len + prefix_len + bit_len
dst_buf, dst_buf_size, dst_pos, dst_len =
check_buf_size(dst_buf, dst_buf_size, dst_pos, dst_len,
new_dst_len)
if prefix_len > 0 then
ffi_copy(dst_pos, ffi_cast(c_str_type, subj) + cp_pos,
prefix_len)
dst_pos = dst_pos + prefix_len
end
if bit_len > 0 then
C.ngx_http_lua_ffi_script_eval_data(e, cv, dst_pos)
dst_pos = dst_pos + bit_len
end
else
local bit_len = cv.value.len
dst_buf, dst_buf_size, dst_pos, dst_len =
check_buf_size(dst_buf, dst_buf_size, dst_pos, dst_len,
dst_len + prefix_len + bit_len)
if prefix_len > 0 then
ffi_copy(dst_pos, ffi_cast(c_str_type, subj) + cp_pos,
prefix_len)
dst_pos = dst_pos + prefix_len
end
if bit_len > 0 then
ffi_copy(dst_pos, cv.value.data, bit_len)
dst_pos = dst_pos + bit_len
end
end
cp_pos = compiled.captures[1]
pos = cp_pos
if pos == compiled.captures[0] then
pos = pos + 1
if pos > subj_len then
break
end
end
if not global then
break
end
end
if not compile_once then
destroy_compiled_regex(compiled)
end
if count > 0 then
if pos < subj_len then
local suffix_len = subj_len - cp_pos
local new_dst_len = dst_len + suffix_len
local _
dst_buf, _, dst_pos, dst_len =
check_buf_size(dst_buf, dst_buf_size, dst_pos, dst_len,
new_dst_len)
ffi_copy(dst_pos, ffi_cast(c_str_type, subj) + cp_pos,
suffix_len)
end
return ffi_string(dst_buf, dst_len), count
end
return subj, 0
end
local function re_sub_helper(subj, regex, replace, opts, global)
local repl_type = type(replace)
if repl_type == "function" then
return re_sub_func_helper(subj, regex, replace, opts, global)
end
if repl_type ~= "string" then
replace = tostring(replace)
end
return re_sub_str_helper(subj, regex, replace, opts, global)
end
function ngx.re.sub(subj, regex, replace, opts)
return re_sub_helper(subj, regex, replace, opts, false)
end
function ngx.re.gsub(subj, regex, replace, opts)
return re_sub_helper(subj, regex, replace, opts, true)
end
return _M
| bsd-2-clause |
LeMagnesium/minetest-minetestforfun-server | mods/mesecons/mesecons_delayer/init.lua | 13 | 5674 | -- Function that get the input/output rules of the delayer
local delayer_get_output_rules = function(node)
local rules = {{x = 0, y = 0, z = 1}}
for i = 0, node.param2 do
rules = mesecon.rotate_rules_left(rules)
end
return rules
end
local delayer_get_input_rules = function(node)
local rules = {{x = 0, y = 0, z = -1}}
for i = 0, node.param2 do
rules = mesecon.rotate_rules_left(rules)
end
return rules
end
-- Functions that are called after the delay time
local delayer_activate = function(pos, node)
local def = minetest.registered_nodes[node.name]
local time = def.delayer_time
minetest.swap_node(pos, {name = def.delayer_onstate, param2=node.param2})
mesecon.queue:add_action(pos, "receptor_on", {delayer_get_output_rules(node)}, time, nil)
end
local delayer_deactivate = function(pos, node)
local def = minetest.registered_nodes[node.name]
local time = def.delayer_time
minetest.swap_node(pos, {name = def.delayer_offstate, param2=node.param2})
mesecon.queue:add_action(pos, "receptor_off", {delayer_get_output_rules(node)}, time, nil)
end
-- Register the 2 (states) x 4 (delay times) delayers
for i = 1, 4 do
local groups = {}
if i == 1 then
groups = {bendy=2,snappy=1,dig_immediate=2}
else
groups = {bendy=2,snappy=1,dig_immediate=2, not_in_creative_inventory=1}
end
local delaytime
if i == 1 then delaytime = 0.1
elseif i == 2 then delaytime = 0.3
elseif i == 3 then delaytime = 0.5
elseif i == 4 then delaytime = 1.0 end
boxes = {{ -6/16, -8/16, -6/16, 6/16, -7/16, 6/16 }, -- the main slab
{ -2/16, -7/16, -4/16, 2/16, -26/64, -3/16 }, -- the jeweled "on" indicator
{ -3/16, -7/16, -3/16, 3/16, -26/64, -2/16 },
{ -4/16, -7/16, -2/16, 4/16, -26/64, 2/16 },
{ -3/16, -7/16, 2/16, 3/16, -26/64, 3/16 },
{ -2/16, -7/16, 3/16, 2/16, -26/64, 4/16 },
{ -6/16, -7/16, -6/16, -4/16, -27/64, -4/16 }, -- the timer indicator
{ -8/16, -8/16, -1/16, -6/16, -7/16, 1/16 }, -- the two wire stubs
{ 6/16, -8/16, -1/16, 8/16, -7/16, 1/16 }}
minetest.register_node("mesecons_delayer:delayer_off_"..tostring(i), {
description = "Delayer",
drawtype = "nodebox",
tiles = {
"mesecons_delayer_off_"..tostring(i)..".png",
"mesecons_delayer_bottom.png",
"mesecons_delayer_ends_off.png",
"mesecons_delayer_ends_off.png",
"mesecons_delayer_sides_off.png",
"mesecons_delayer_sides_off.png"
},
inventory_image = "mesecons_delayer_off_1.png",
wield_image = "mesecons_delayer_off_1.png",
walkable = true,
selection_box = {
type = "fixed",
fixed = { -8/16, -8/16, -8/16, 8/16, -6/16, 8/16 },
},
node_box = {
type = "fixed",
fixed = boxes
},
groups = groups,
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
is_ground_content = true,
drop = 'mesecons_delayer:delayer_off_1',
on_punch = function (pos, node)
if node.name=="mesecons_delayer:delayer_off_1" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_off_2", param2=node.param2})
elseif node.name=="mesecons_delayer:delayer_off_2" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_off_3", param2=node.param2})
elseif node.name=="mesecons_delayer:delayer_off_3" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_off_4", param2=node.param2})
elseif node.name=="mesecons_delayer:delayer_off_4" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_off_1", param2=node.param2})
end
end,
delayer_time = delaytime,
delayer_onstate = "mesecons_delayer:delayer_on_"..tostring(i),
sounds = default.node_sound_stone_defaults(),
mesecons = {
receptor =
{
state = mesecon.state.off,
rules = delayer_get_output_rules
},
effector =
{
rules = delayer_get_input_rules,
action_on = delayer_activate
}
}
})
minetest.register_node("mesecons_delayer:delayer_on_"..tostring(i), {
description = "You hacker you",
drawtype = "nodebox",
tiles = {
"mesecons_delayer_on_"..tostring(i)..".png",
"mesecons_delayer_bottom.png",
"mesecons_delayer_ends_on.png",
"mesecons_delayer_ends_on.png",
"mesecons_delayer_sides_on.png",
"mesecons_delayer_sides_on.png"
},
walkable = true,
selection_box = {
type = "fixed",
fixed = { -8/16, -8/16, -8/16, 8/16, -6/16, 8/16 },
},
node_box = {
type = "fixed",
fixed = boxes
},
groups = {bendy = 2, snappy = 1, dig_immediate = 2, not_in_creative_inventory = 1},
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
is_ground_content = true,
drop = 'mesecons_delayer:delayer_off_1',
on_punch = function (pos, node)
if node.name=="mesecons_delayer:delayer_on_1" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_on_2", param2=node.param2})
elseif node.name=="mesecons_delayer:delayer_on_2" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_on_3", param2=node.param2})
elseif node.name=="mesecons_delayer:delayer_on_3" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_on_4", param2=node.param2})
elseif node.name=="mesecons_delayer:delayer_on_4" then
minetest.swap_node(pos, {name = "mesecons_delayer:delayer_on_1", param2=node.param2})
end
end,
delayer_time = delaytime,
delayer_offstate = "mesecons_delayer:delayer_off_"..tostring(i),
mesecons = {
receptor =
{
state = mesecon.state.on,
rules = delayer_get_output_rules
},
effector =
{
rules = delayer_get_input_rules,
action_off = delayer_deactivate
}
}
})
end
minetest.register_craft({
output = "mesecons_delayer:delayer_off_1",
recipe = {
{"mesecons_torch:mesecon_torch_on", "group:mesecon_conductor_craftable", "mesecons_torch:mesecon_torch_on"},
{"default:cobble","default:cobble", "default:cobble"},
}
})
| unlicense |
warriorhero/black-wolf | plugins/banhammer.lua | 214 | 11956 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
local bots_protection = "Yes"
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = ''
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if member_id == our_id then return false end
if get_cmd == 'kick' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) then
return send_large_msg(receiver, "you can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
return unbanall_user(member_id, chat_id)
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
local receiver = get_receiver(msg)
if matches[1]:lower() == 'kickme' then-- /kickme
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return nil
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'ban'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
return
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unban'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if msg.to.type == 'chat' then
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'kick'
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'banall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local member = string.gsub(matches[2], '@', '')
local get_cmd = 'unbanall'
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/saber2hBodyHit2.lua | 2 | 2393 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser 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
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
Saber2hBodyHit2Command = {
name = "saber2hbodyhit2",
damageMultiplier = 1.25,
speedMultiplier = 1,5,
forceCostMultiplier = 1.25,
animationCRC = hashCode("combo_3d_light"),
combatSpam = "saber2hbodyhit2",
poolsToDamage = HEALTH_ATTRIBUTE,
weaponType = TWOHANDJEDIWEAPON,
range = -1
}
AddCommand(Saber2hBodyHit2Command)
| agpl-3.0 |
MonkeyZZZZ/platform_external_skia | tools/lua/scrape_dashing.lua | 160 | 2495 | 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 total_found = {} -- accumulate() stores its data in here
local total_total = {}
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
function increment(table, key)
table[key] = (table[key] or 0) + 1
end
local drawPointsTable = {}
local drawPointsTable_direction = {}
function sk_scrape_accumulate(t)
increment(total_total, t.verb)
local p = t.paint
if p then
local pe = p:getPathEffect();
if pe then
increment(total_found, t.verb)
end
end
if "drawPoints" == t.verb then
local points = t.points
increment(drawPointsTable, #points)
if 2 == #points then
if points[1].y == points[2].y then
increment(drawPointsTable_direction, "hori")
elseif points[1].x == points[2].x then
increment(drawPointsTable_direction, "vert")
else
increment(drawPointsTable_direction, "other")
end
end
end
end
--[[
lua_pictures will call this function after all of the pictures have been
"accumulated".
]]
function sk_scrape_summarize()
for k, v in next, total_found do
io.write(k, " = ", v, "/", total_total[k], "\n")
end
print("histogram of point-counts for all drawPoints calls")
print(tostr(drawPointsTable))
print(tostr(drawPointsTable_direction))
end
| bsd-3-clause |
garoose/eecs494.p2 | dev/premake/premake/tests/base/test_path.lua | 52 | 6597 | --
-- tests/base/test_path.lua
-- Automated test suite for the action list.
-- Copyright (c) 2008-2010 Jason Perkins and the Premake project
--
T.path = { }
local suite = T.path
--
-- path.getabsolute() tests
--
function suite.getabsolute_ReturnsCorrectPath_OnMissingSubdir()
local expected = path.translate(os.getcwd(), "/") .. "/a/b/c"
test.isequal(expected, path.getabsolute("a/b/c"))
end
function suite.getabsolute_RemovesDotDots_OnWindowsAbsolute()
test.isequal("c:/ProjectB/bin", path.getabsolute("c:/ProjectA/../ProjectB/bin"))
end
function suite.getabsolute_RemovesDotDots_OnPosixAbsolute()
test.isequal("/ProjectB/bin", path.getabsolute("/ProjectA/../ProjectB/bin"))
end
function suite.getabsolute_OnTrailingSlash()
local expected = path.translate(os.getcwd(), "/") .. "/a/b/c"
test.isequal(expected, path.getabsolute("a/b/c/"))
end
function suite.getabsolute_OnLeadingEnvVar()
test.isequal("$(HOME)/user", path.getabsolute("$(HOME)/user"))
end
function suite.getabsolute_OnMultipleEnvVar()
test.isequal("$(HOME)/$(USER)", path.getabsolute("$(HOME)/$(USER)"))
end
function suite.getabsolute_OnTrailingEnvVar()
local expected = path.translate(os.getcwd(), "/") .. "/home/$(USER)"
test.isequal(expected, path.getabsolute("home/$(USER)"))
end
--
-- path.getbasename() tests
--
function suite.getbasename_ReturnsCorrectName_OnDirAndExtension()
test.isequal("filename", path.getbasename("folder/filename.ext"))
end
--
-- path.getdirectory() tests
--
function suite.getdirectory_ReturnsEmptyString_OnNoDirectory()
test.isequal(".", path.getdirectory("filename.ext"))
end
function suite.getdirectory_ReturnsDirectory_OnSingleLevelPath()
test.isequal("dir0", path.getdirectory("dir0/filename.ext"))
end
function suite.getdirectory_ReturnsDirectory_OnMultiLeveLPath()
test.isequal("dir0/dir1/dir2", path.getdirectory("dir0/dir1/dir2/filename.ext"))
end
function suite.getdirectory_ReturnsRootPath_OnRootPathOnly()
test.isequal("/", path.getdirectory("/filename.ext"))
end
--
-- path.getdrive() tests
--
function suite.getdrive_ReturnsNil_OnNotWindows()
test.isnil(path.getdrive("/hello"))
end
function suite.getdrive_ReturnsLetter_OnWindowsAbsolute()
test.isequal("x", path.getdrive("x:/hello"))
end
--
-- path.getextension() tests
--
function suite.getextension_ReturnsEmptyString_OnNoExtension()
test.isequal("", path.getextension("filename"))
end
function suite.getextension_ReturnsExtension()
test.isequal(".txt", path.getextension("filename.txt"))
end
function suite.getextension_OnMultipleDots()
test.isequal(".txt", path.getextension("filename.mod.txt"))
end
function suite.getextension_OnLeadingNumeric()
test.isequal(".7z", path.getextension("filename.7z"))
end
function suite.getextension_OnUnderscore()
test.isequal(".a_c", path.getextension("filename.a_c"))
end
function suite.getextension_OnHyphen()
test.isequal(".a-c", path.getextension("filename.a-c"))
end
--
-- path.getrelative() tests
--
function suite.getrelative_ReturnsDot_OnMatchingPaths()
test.isequal(".", path.getrelative("/a/b/c", "/a/b/c"))
end
function suite.getrelative_ReturnsDoubleDot_OnChildToParent()
test.isequal("..", path.getrelative("/a/b/c", "/a/b"))
end
function suite.getrelative_ReturnsDoubleDot_OnSiblingToSibling()
test.isequal("../d", path.getrelative("/a/b/c", "/a/b/d"))
end
function suite.getrelative_ReturnsChildPath_OnParentToChild()
test.isequal("d", path.getrelative("/a/b/c", "/a/b/c/d"))
end
function suite.getrelative_ReturnsChildPath_OnWindowsAbsolute()
test.isequal("obj/debug", path.getrelative("C:/Code/Premake4", "C:/Code/Premake4/obj/debug"))
end
function suite.getrelative_ReturnsAbsPath_OnDifferentDriveLetters()
test.isequal("D:/Files", path.getrelative("C:/Code/Premake4", "D:/Files"))
end
function suite.getrelative_ReturnsAbsPath_OnDollarMacro()
test.isequal("$(SDK_HOME)/include", path.getrelative("C:/Code/Premake4", "$(SDK_HOME)/include"))
end
function suite.getrelative_ReturnsAbsPath_OnRootedPath()
test.isequal("/opt/include", path.getrelative("/home/me/src/project", "/opt/include"))
end
--
-- path.isabsolute() tests
--
function suite.isabsolute_ReturnsTrue_OnAbsolutePosixPath()
test.istrue(path.isabsolute("/a/b/c"))
end
function suite.isabsolute_ReturnsTrue_OnAbsoluteWindowsPathWithDrive()
test.istrue(path.isabsolute("C:/a/b/c"))
end
function suite.isabsolute_ReturnsFalse_OnRelativePath()
test.isfalse(path.isabsolute("a/b/c"))
end
function suite.isabsolute_ReturnsTrue_OnDollarSign()
test.istrue(path.isabsolute("$(SDK_HOME)/include"))
end
--
-- path.join() tests
--
function suite.join_OnValidParts()
test.isequal("p1/p2", path.join("p1", "p2"))
end
function suite.join_OnAbsoluteUnixPath()
test.isequal("/p2", path.join("p1", "/p2"))
end
function suite.join_OnAbsoluteWindowsPath()
test.isequal("C:/p2", path.join("p1", "C:/p2"))
end
function suite.join_OnCurrentDirectory()
test.isequal("p2", path.join(".", "p2"))
end
function suite.join_OnNilSecondPart()
test.isequal("p1", path.join("p1", nil))
end
function suite.join_onMoreThanTwoParts()
test.isequal("p1/p2/p3", path.join("p1", "p2", "p3"))
end
function suite.join_removesExtraInternalSlashes()
test.isequal("p1/p2", path.join("p1/", "p2"))
end
function suite.join_removesTrailingSlash()
test.isequal("p1/p2", path.join("p1", "p2/"))
end
function suite.join_ignoresNilParts()
test.isequal("p2", path.join(nil, "p2", nil))
end
function suite.join_ignoresEmptyParts()
test.isequal("p2", path.join("", "p2", ""))
end
--
-- path.rebase() tests
--
function suite.rebase_WithEndingSlashOnPath()
local cwd = os.getcwd()
test.isequal("src", path.rebase("../src/", cwd, path.getdirectory(cwd)))
end
--
-- path.translate() tests
--
function suite.translate_ReturnsTranslatedPath_OnValidPath()
test.isequal("dir/dir/file", path.translate("dir\\dir\\file", "/"))
end
function suite.translate_ReturnsCorrectSeparator_OnMixedPath()
local actual = path.translate("dir\\dir/file")
if (os.is("windows")) then
test.isequal("dir\\dir\\file", actual)
else
test.isequal("dir/dir/file", actual)
end
end
--
-- path.wildcards tests
--
function suite.wildcards_MatchesTrailingStar()
local p = path.wildcards("**/xcode/*")
test.isequal(".*/xcode/[^/]*", p)
end
function suite.wildcards_MatchPlusSign()
local patt = path.wildcards("file+name.*")
local name = "file+name.c"
test.isequal(name, name:match(patt))
end
| mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/healActionWoundSelf1.lua | 3 | 2153 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser 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
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
HealActionWoundSelf1Command = {
name = "healactionwoundself1",
}
AddCommand(HealActionWoundSelf1Command)
| agpl-3.0 |
LeMagnesium/minetest-minetestforfun-server | mods/pipeworks/init.lua | 8 | 3709 | -- Pipeworks mod by Vanessa Ezekowitz - 2013-07-13
--
-- This mod supplies various steel pipes and plastic pneumatic tubes
-- and devices that they can connect to.
--
-- License: WTFPL
--
pipeworks = {}
local DEBUG = false
pipeworks.worldpath = minetest.get_worldpath()
pipeworks.modpath = minetest.get_modpath("pipeworks")
dofile(pipeworks.modpath.."/default_settings.txt")
-- Read the external config file if it exists.
local worldsettingspath = pipeworks.worldpath.."/pipeworks_settings.txt"
local worldsettingsfile = io.open(worldsettingspath, "r")
if worldsettingsfile then
worldsettingsfile:close()
dofile(worldsettingspath)
end
-- Random variables
pipeworks.expect_infinite_stacks = true
if minetest.get_modpath("unified_inventory") or not minetest.setting_getbool("creative_mode") then
pipeworks.expect_infinite_stacks = false
end
pipeworks.meseadjlist={{x=0,y=0,z=1},{x=0,y=0,z=-1},{x=0,y=1,z=0},{x=0,y=-1,z=0},{x=1,y=0,z=0},{x=-1,y=0,z=0}}
pipeworks.rules_all = {{x=0, y=0, z=1},{x=0, y=0, z=-1},{x=1, y=0, z=0},{x=-1, y=0, z=0},
{x=0, y=1, z=1},{x=0, y=1, z=-1},{x=1, y=1, z=0},{x=-1, y=1, z=0},
{x=0, y=-1, z=1},{x=0, y=-1, z=-1},{x=1, y=-1, z=0},{x=-1, y=-1, z=0},
{x=0, y=1, z=0}, {x=0, y=-1, z=0}}
pipeworks.mesecons_rules={{x=0,y=0,z=1},{x=0,y=0,z=-1},{x=1,y=0,z=0},{x=-1,y=0,z=0},{x=0,y=1,z=0},{x=0,y=-1,z=0}}
pipeworks.liquid_texture = "default_water.png"
-- Helper functions
function pipeworks.fix_image_names(table, replacement)
local outtable={}
for i in ipairs(table) do
outtable[i]=string.gsub(table[i], "_XXXXX", replacement)
end
return outtable
end
function pipeworks.add_node_box(t, b)
if not t or not b then return end
for i in ipairs(b)
do table.insert(t, b[i])
end
end
function pipeworks.may_configure(pos, player)
local name = player:get_player_name()
local meta = minetest.get_meta(pos)
local owner = meta:get_string("owner")
if owner ~= "" then -- wielders and filters
return owner == name
end
return not minetest.is_protected(pos, name)
end
function pipeworks.replace_name(tbl,tr,name)
local ntbl={}
for key,i in pairs(tbl) do
if type(i)=="string" then
ntbl[key]=string.gsub(i,tr,name)
elseif type(i)=="table" then
ntbl[key]=pipeworks.replace_name(i,tr,name)
else
ntbl[key]=i
end
end
return ntbl
end
-------------------------------------------
-- Load the various other parts of the mod
dofile(pipeworks.modpath.."/common.lua")
dofile(pipeworks.modpath.."/models.lua")
dofile(pipeworks.modpath.."/autoplace_pipes.lua")
dofile(pipeworks.modpath.."/autoplace_tubes.lua")
dofile(pipeworks.modpath.."/luaentity.lua")
dofile(pipeworks.modpath.."/item_transport.lua")
dofile(pipeworks.modpath.."/flowing_logic.lua")
dofile(pipeworks.modpath.."/crafts.lua")
dofile(pipeworks.modpath.."/tube_registration.lua")
dofile(pipeworks.modpath.."/routing_tubes.lua")
dofile(pipeworks.modpath.."/sorting_tubes.lua")
dofile(pipeworks.modpath.."/vacuum_tubes.lua")
dofile(pipeworks.modpath.."/signal_tubes.lua")
dofile(pipeworks.modpath.."/decorative_tubes.lua")
dofile(pipeworks.modpath.."/filter-injector.lua")
dofile(pipeworks.modpath.."/trashcan.lua")
dofile(pipeworks.modpath.."/wielder.lua")
if pipeworks.enable_pipes then dofile(pipeworks.modpath.."/pipes.lua") end
if pipeworks.enable_teleport_tube then dofile(pipeworks.modpath.."/teleport_tube.lua") end
if pipeworks.enable_pipe_devices then dofile(pipeworks.modpath.."/devices.lua") end
if pipeworks.enable_redefines then dofile(pipeworks.modpath.."/compat.lua") end
if pipeworks.enable_autocrafter then dofile(pipeworks.modpath.."/autocrafter.lua") end
minetest.register_alias("pipeworks:pipe", "pipeworks:pipe_110000_empty")
minetest.log("Pipeworks loaded!")
| unlicense |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/dathomir/nightsister_outcast.lua | 2 | 1489 | nightsister_outcast = Creature:new {
objectName = "@mob/creature_names:nightsister_outcast",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "nightsister",
faction = "nightsister",
level = 81,
chanceHit = 0.75,
damageMin = 555,
damageMax = 820,
baseXp = 7761,
baseHAM = 12000,
baseHAMmax = 15000,
armor = 1,
resists = {30,30,30,100,100,100,100,100,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_dathomir_nightsister_outcast.iff"},
lootGroups = {
{
groups = {
{group = "crystals_good", chance = 500000},
{group = "color_crystals", chance = 500000},
{group = "nightsister_common", chance = 2000000},
{group = "armor_attachments", chance = 250000},
{group = "clothing_attachments", chance = 250000},
{group = "melee_weapons", chance = 2500000},
{group = "rifles", chance = 1000000},
{group = "pistols", chance = 1000000},
{group = "carbines", chance = 1000000},
{group = "wearables_common", chance = 500000},
{group = "wearables_uncommon", chance = 500000}
}
}
},
weapons = {"mixed_force_weapons"},
conversationTemplate = "",
attacks = merge(pikemanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(nightsister_outcast, "nightsister_outcast")
| agpl-3.0 |
StephenZhuang/qdkpv2 | QDKP_V2/QDKP2_Config/Libs/AceGUI-3.0/widgets/AceGUIWidget-Label.lua | 9 | 4607 | --[[-----------------------------------------------------------------------------
Label Widget
Displays text and optionally an icon.
-------------------------------------------------------------------------------]]
local Type, Version = "Label", 23
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local max, select, pairs = math.max, select, pairs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateImageAnchor(self)
if self.resizing then return end
local frame = self.frame
local width = frame.width or frame:GetWidth() or 0
local image = self.image
local label = self.label
local height
label:ClearAllPoints()
image:ClearAllPoints()
if self.imageshown then
local imagewidth = image:GetWidth()
if (width - imagewidth) < 200 or (label:GetText() or "") == "" then
-- image goes on top centered when less than 200 width for the text, or if there is no text
image:SetPoint("TOP")
label:SetPoint("TOP", image, "BOTTOM")
label:SetPoint("LEFT")
label:SetWidth(width)
height = image:GetHeight() + label:GetHeight()
else
-- image on the left
image:SetPoint("TOPLEFT")
if image:GetHeight() > label:GetHeight() then
label:SetPoint("LEFT", image, "RIGHT", 4, 0)
else
label:SetPoint("TOPLEFT", image, "TOPRIGHT", 4, 0)
end
label:SetWidth(width - imagewidth - 4)
height = max(image:GetHeight(), label:GetHeight())
end
else
-- no image shown
label:SetPoint("TOPLEFT")
label:SetWidth(width)
height = label:GetHeight()
end
self.resizing = true
frame:SetHeight(height)
frame.height = height
self.resizing = nil
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
-- set the flag to stop constant size updates
self.resizing = true
-- height is set dynamically by the text and image size
self:SetWidth(200)
self:SetText()
self:SetImage(nil)
self:SetImageSize(16, 16)
self:SetColor()
self:SetFontObject()
-- reset the flag
self.resizing = nil
-- run the update explicitly
UpdateImageAnchor(self)
end,
-- ["OnRelease"] = nil,
["OnWidthSet"] = function(self, width)
UpdateImageAnchor(self)
end,
["SetText"] = function(self, text)
self.label:SetText(text)
UpdateImageAnchor(self)
end,
["SetColor"] = function(self, r, g, b)
if not (r and g and b) then
r, g, b = 1, 1, 1
end
self.label:SetVertexColor(r, g, b)
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
self.imageshown = true
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
else
self.imageshown = nil
end
UpdateImageAnchor(self)
end,
["SetFont"] = function(self, font, height, flags)
self.label:SetFont(font, height, flags)
end,
["SetFontObject"] = function(self, font)
self:SetFont((font or GameFontHighlightSmall):GetFont())
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
UpdateImageAnchor(self)
end,
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlightSmall")
label:SetJustifyH("LEFT")
label:SetJustifyV("TOP")
local image = frame:CreateTexture(nil, "BACKGROUND")
-- create widget
local widget = {
label = label,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/faction/imperial/imperial_inquisitor.lua | 2 | 1461 | imperial_inquisitor = Creature:new {
objectName = "@mob/creature_names:imperial_inquisitor",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "imperial",
faction = "imperial",
level = 120,
chanceHit = 4.000000,
damageMin = 745,
damageMax = 1200,
baseXp = 11296,
baseHAM = 44000,
baseHAMmax = 54000,
armor = 0,
resists = {50,50,50,0,50,0,50,50,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_imperial_inquisitor_human_male_01.iff"},
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 100000},
{group = "junk", chance = 6650000},
{group = "rifles", chance = 550000},
{group = "pistols", chance = 550000},
{group = "melee_weapons", chance = 550000},
{group = "carbines", chance = 550000},
{group = "clothing_attachments", chance = 25000},
{group = "armor_attachments", chance = 25000},
{group = "wearables_all", chance = 1000000}
}
}
},
weapons = {"imperial_weapons_heavy"},
conversationTemplate = "",
reactionStf = "@npc_reaction/military",
personalityStf = "@hireling/hireling_military",
attacks = merge(riflemanmaster,carbineermaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(imperial_inquisitor, "imperial_inquisitor")
| agpl-3.0 |
iranddos/maxtor | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(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 set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins 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 set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins 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
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins 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_name(msg, data, target)
if not is_admin(msg) then
return "For admins 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
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins 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_member(msg, data, target)
if not is_admin(msg) then
return "For admins 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
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins 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 lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
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_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
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
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
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
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..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 == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
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
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_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
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
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.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
aqasaeed/bot | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(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 set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins 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 set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins 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
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins 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_name(msg, data, target)
if not is_admin(msg) then
return "For admins 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
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins 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_member(msg, data, target)
if not is_admin(msg) then
return "For admins 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
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins 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 lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
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_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
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
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
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
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..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 == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
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
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_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
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
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.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
aqasaeed/farzad | plugins/inrealm.lua | 850 | 25085 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(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 set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins 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 set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins 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
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins 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_name(msg, data, target)
if not is_admin(msg) then
return "For admins 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
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins 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_member(msg, data, target)
if not is_admin(msg) then
return "For admins 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
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins 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 lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
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_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
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
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
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
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..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 == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
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
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_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
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
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.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](createrealm) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^[!/](help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Inquiryel/HPW_Rewrite-SBS | lua/effects/EffectHpwRewriteSparks.lua | 2 | 2567 | AddCSLuaFile()
function EFFECT:Init(data)
self.Hide = HpwRewrite.CVars.HideSparks:GetBool()
if self.Hide then return end
local ply = data:GetEntity()
local col = data:GetStart()
local dieTime = data:GetScale()
self.OldPos = vector_origin
self.Vel = vector_origin
self.Color = Color(col.x, col.y, col.z)
self.DieTime = CurTime() + dieTime
self.Wait = 0
if not IsValid(ply) then return end
self.Player = ply
self.ViewModel = ply:GetViewModel()
local vm = self.ViewModel
if not IsValid(vm) or ply:ShouldDrawLocalPlayer() then vm = HpwRewrite:GetWand(ply) end
if not IsValid(vm) then return end
self.Wand = vm
local vec = Vector(100, 100, 100)
local pos = vm:GetPos()
self:SetRenderBoundsWS(pos - vec, pos + vec)
end
function EFFECT:Think()
if self.Hide then return false end
if CurTime() > self.DieTime then
if self.Emitter then self.Emitter:Finish() end
return false
end
return true
end
function EFFECT:Render()
if self.Hide then return end
if CurTime() > self.Wait then
if IsValid(self.Wand) and IsValid(self.Player) then
local obj = self.Wand:LookupBone("spritemagic")
if obj then
local m = self.Wand:GetBoneMatrix(obj)
if m then
local pos = m:GetTranslation()
if self.Wand == self.ViewModel then pos = pos - self.Player:EyeAngles():Forward() * 10 end
self.Pos = pos
local vec = self.Pos - self.OldPos
self.OldPos = self.Pos
self.Vel = (vec * (vec:Length() ^ 2) * 0.075) + VectorRand() * 10
if not self.Emitter then
self.Emitter = ParticleEmitter(self.Pos)
return
end
local dieTime = math.Rand(0.2, 0.4)
local vel = self.Vel
local grav = self.Vel --Vector(0, 0, -20)
local resist = math.random(15, 40)
local p = self.Emitter:Add("hpwrewrite/sprites/magicsprite", self.Pos)
p:SetBounce(0.8)
p:SetCollide(true)
p:SetStartSize(3)
p:SetEndSize(0)
p:SetStartAlpha(255)
p:SetEndAlpha(0)
p:SetDieTime(dieTime)
p:SetVelocity(vel)
p:SetGravity(grav)
p:SetAirResistance(resist)
local col = self.Color
p:SetColor(col.r, col.g, col.b)
local p = self.Emitter:Add("hpwrewrite/sprites/magicsprite", self.Pos)
p:SetBounce(0.8)
p:SetCollide(true)
p:SetStartSize(1)
p:SetEndSize(0)
p:SetStartAlpha(255)
p:SetEndAlpha(0)
p:SetDieTime(dieTime)
p:SetVelocity(vel)
p:SetGravity(grav)
p:SetAirResistance(resist)
p:SetColor(255, 255, 255)
end
end
end
self.Wait = CurTime() + math.Rand(0.001, 0.015)
end
end | mit |
SharpWoW/BodyguardHealth | options.lua | 1 | 25793 | --[[
Copyright (c) 2014 by Adam Hellberg.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]
local NAME, T = ...
local bgframe = T.BodyguardFrame
local interfacePanel
local framePanel
local options = {
name = "Bodyguard Health",
type = "group",
args = {
options = {
name = "Interface options",
desc = "Opens the GUI interface for configuring",
type = "execute",
guiHidden = true,
func = function()
T.Options:Open()
end
},
general = {
order = 1,
name = "General options",
type = "group",
args = {
enabled = {
order = 1,
name = "Enabled",
desc = "When AddOn is disabled, the frame will be hidden from view",
type = "toggle",
get = function(info) return T.DB.profile.Enabled end,
set = function(info, val)
if val then
T:Enable()
else
T:Disable()
end
end
},
debug = {
order = 2,
name = "Debug mode",
desc = "With debug mode enabled, more diagnostic messages will be printed to chat",
type = "toggle",
get = function(info) return T.DB.profile.Debug end,
set = function(info, val) T.DB.profile.Debug = val end
},
lock = {
order = 3,
name = "Lock frame",
desc = "Locks frame to prevent movement and enable click-through",
type = "toggle",
get = function(info) return bgframe:IsLocked() end,
set = function(info, val) if val then bgframe:Lock() else bgframe:Unlock() end end
},
reset = {
order = 4,
name = "Reset frame",
desc = "Resets frame position and size",
type = "execute",
func = function() bgframe:ResetSettings() end
},
enablewarn = {
order = 5,
name = "Enable health warnings",
desc = "Enables the playing of sound and display of a raid warning when bodyguard is low on health",
type = "toggle",
get = function(info) return T.DB.profile.EnableWarn end,
set = function(info, val) T.DB.profile.EnableWarn = val end
},
show = {
order = 6,
name = "Show frame",
desc = "Forces the frame to show",
type = "execute",
func = function() bgframe:Show(true) end
},
hide = {
order = 7,
name = "Hide frame",
desc = "Forces the frame to hide",
type = "execute",
func = function() bgframe:Hide() end
},
gossipclose = {
order = 8,
name = "Auto-close gossip",
desc = "With this enabled, the bodyguard gossip window will automatically close when opened unless the configured modifier key is held",
type = "toggle",
get = function(info) return T.DB.profile.CloseGossip end,
set = function(info, val) T.DB.profile.CloseGossip = val end
},
gossipclosemodifier = {
order = 9,
name = "Gossip close override modifier",
desc = "When auto-close gossip is enabled, holding this modifier key down will prevent it from closing automatically",
type = "select",
values = {
control = "Control",
shift = "Shift",
alt = "Alt"
},
get = function(info) return T.DB.profile.CloseGossipModifier end,
set = function(info, val) T.DB.profile.CloseGossipModifier = val end
}
}
},
frame = {
order = 2,
type = "group",
name = "Frame settings",
desc = "Settings for the health frame",
args = {
header1 = { name = "General options", type = "header", order = 1 },
point = {
order = 2,
name = "Anchor point",
desc = "The anchor point for the frame",
type = "select",
style = "dropdown",
values = {TOP = "TOP", TOPLEFT = "TOPLEFT", TOPRIGHT = "TOPRIGHT",
BOTTOM = "BOTTOM", BOTTOMLEFT = "BOTTOMLEFT", BOTTOMRIGHT = "BOTTOMRIGHT",
CENTER = "CENTER", LEFT = "LEFT", RIGHT = "RIGHT"},
get = function(info) return T.DB.profile.FrameSettings.Point end,
set = function(info, val)
T.DB.profile.FrameSettings.Point = val
bgframe:UpdateSettings()
end
},
relpoint = {
order = 3,
name = "Relative point",
desc = "The point which the frame will anchor relative to",
type = "select",
style = "dropdown",
values = {TOP = "TOP", TOPLEFT = "TOPLEFT", TOPRIGHT = "TOPRIGHT",
BOTTOM = "BOTTOM", BOTTOMLEFT = "BOTTOMLEFT", BOTTOMRIGHT = "BOTTOMRIGHT",
CENTER = "CENTER", LEFT = "LEFT", RIGHT = "RIGHT", NIL = "None"},
get = function(info) return T.DB.profile.FrameSettings.RelPoint or "NIL" end,
set = function(info, val)
if val == "NIL" then
T.DB.profile.FrameSettings.RelPoint = nil
else
T.DB.profile.FrameSettings.RelPoint = val
end
bgframe:UpdateSettings()
end
},
width = {
order = 5,
name = "Width",
desc = "Width of the health frame (values below 200 not recommended)",
type = "range",
min = 1,
max = 1000,
step = 1,
bigStep = 10,
get = function(info) return T.DB.profile.FrameSettings.Width end,
set = function(info, val)
T.DB.profile.FrameSettings.Width = val
bgframe:UpdateSettings()
end
},
height = {
order = 6,
name = "Height",
desc = "Height of the health frame (values below 40 not recommended)",
type = "range",
min = 1,
max = 1000,
step = 1,
bigStep = 10,
get = function(info) return T.DB.profile.FrameSettings.Height end,
set = function(info, val)
T.DB.profile.FrameSettings.Height = val
bgframe:UpdateSettings()
end
},
scale = {
order = 7,
name = "Scale",
desc = "Frame scale",
type = "range",
min = 0.01,
max = 10,
step = 0.01,
bigStep = 0.1,
get = function(info) return T.DB.profile.FrameSettings.Scale end,
set = function(info, val)
T.DB.profile.FrameSettings.Scale = val
bgframe:UpdateSettings()
end
},
x = {
order = 8,
name = "X offset",
desc = "Amount of UI units to offset the frame horizontally",
type = "range",
min = -1000,
max = 1000,
step = 1,
bigStep = 10,
get = function(info) return T.DB.profile.FrameSettings.Offset.X end,
set = function(info, val)
T.DB.profile.FrameSettings.Offset.X = val
bgframe:UpdateSettings()
end
},
y = {
order = 9,
name = "Y offset",
desc = "Amount of UI units to offset the frame vertically",
type = "range",
min = -1000,
max = 1000,
step = 1,
bigStep = 10,
get = function(info) return T.DB.profile.FrameSettings.Offset.Y end,
set = function(info, val)
T.DB.profile.FrameSettings.Offset.Y = val
bgframe:UpdateSettings()
end
},
header2 = { name = "Background and Border", type = "header", order = 10 },
tile = {
order = 13,
name = "Tile background",
desc = "Tile the background texture",
type = "toggle",
get = function(info) return T.DB.profile.FrameSettings.Backdrop.Tile end,
set = function(info, val)
T.DB.profile.FrameSettings.Backdrop.Tile = val
bgframe:UpdateSettings()
end
},
color = {
order = 14,
name = "Background color",
desc = "The color of the frame background",
type = "color",
hasAlpha = true,
get = function(info)
local color = T.DB.profile.FrameSettings.Backdrop.Color
return color.R, color.G, color.B, color.A
end,
set = function(info, r, g, b, a)
local color = T.DB.profile.FrameSettings.Backdrop.Color
color.R = r
color.G = g
color.B = b
color.A = a
bgframe:UpdateSettings()
end
},
borderColor = {
order = 15,
name = "Border color",
desc = "The color of the frame border",
type = "color",
hasAlpha = true,
get = function(info)
local color = T.DB.profile.FrameSettings.Backdrop.BorderColor
return color.R, color.G, color.B, color.A
end,
set = function(info, r, g, b, a)
local color = T.DB.profile.FrameSettings.Backdrop.BorderColor
color.R = r
color.G = g
color.B = b
color.A = a
bgframe:UpdateSettings()
end
},
borderSize = {
order = 16,
name = "Border size",
desc = "The size of the frame border",
type = "range",
min = 0,
max = 128,
step = 1,
get = function(info) return T.DB.profile.FrameSettings.Backdrop.BorderSize end,
set = function(info, val)
T.DB.profile.FrameSettings.Backdrop.BorderSize = val
bgframe:UpdateSettings()
end
},
tileSize = {
order = 17,
name = "Tile size",
type = "range",
min = 0,
max = 128,
step = 1,
get = function(info) return T.DB.profile.FrameSettings.Backdrop.TileSize end,
set = function(info, val)
T.DB.profile.FrameSettings.Backdrop.TileSize = val
bgframe:UpdateSettings()
end
},
inset = {
order = 18,
name = "Inset",
type = "range",
min = -64,
max = 64,
step = 0.1,
bigStep = 0.5,
-- We return just left, as currently we sync all of them
get = function(info) return T.DB.profile.FrameSettings.Backdrop.Insets.Left end,
set = function(info, val)
T.DB.profile.FrameSettings.Backdrop.Insets.Left = val
T.DB.profile.FrameSettings.Backdrop.Insets.Right = val
T.DB.profile.FrameSettings.Backdrop.Insets.Top = val
T.DB.profile.FrameSettings.Backdrop.Insets.Bottom = val
bgframe:UpdateSettings()
end
},
header3 = { order = 19, name = "Healthbar", type = "header" },
bartextflags = {
order = 21,
name = "Bar text outline",
type = "select",
style = "dropdown",
values = {
NONE = "None",
OUTLINE = "Outline",
THICKOUTLINE = "Thick outline",
["OUTLINE, MONOCHROME"] = "Monochrome outline",
["THICKOUTLINE, MONOCHROME"] = "Monochrome thick outline"
},
get = function(info) return T.DB.profile.FrameSettings.FontFlags or "NONE" end,
set = function(info, val)
T.DB.profile.FrameSettings.FontFlags = val
bgframe:UpdateSettings()
end
},
bartextsize = {
order = 22,
name = "Bar text size",
type = "range",
min = 1,
max = 128,
step = 1,
get = function(info) return T.DB.profile.FrameSettings.FontSize end,
set = function(info, val)
T.DB.profile.FrameSettings.FontSize = val
bgframe:UpdateSettings()
end
},
bartextcolor = {
order = 23,
name = "Bar text color",
type = "color",
hasAlpha = true,
get = function(info)
local color = T.DB.profile.FrameSettings.FontColor
return color.R, color.G, color.B, color.A
end,
set = function(info, r, g, b, a)
local color = T.DB.profile.FrameSettings.FontColor
color.R = r
color.G = g
color.B = b
color.A = a
bgframe:UpdateSettings()
end
},
barhealthcolored = {
order = 24,
name = "Color based on health",
desc = "Colors the health bar based on bodyguard health (red at 0%, green at 100%).",
type = "toggle",
get = function(info) return T.DB.profile.FrameSettings.HealthBasedColor end,
set = function(info, val)
T.DB.profile.FrameSettings.HealthBasedColor = val
bgframe:UpdateHealthBar()
end
},
barcustomcolor = {
order = 25,
name = "Custom health bar color",
desc = "Configures a static color to use for the health bar, only used if health based coloring is disabled.",
type = "color",
hasAlpha = false,
get = function(info)
local color = T.DB.profile.FrameSettings.CustomColor
return color.R, color.G, color.B
end,
set = function(info, r, g, b)
local color = T.DB.profile.FrameSettings.CustomColor
color.R = r
color.G = g
color.B = b
bgframe:UpdateHealthBar()
end
},
bartextstyle = {
order = 26,
name = "Health text style",
desc = "Configures how the health text should be displayed on the bar.",
type = "select",
style = "dropdown",
values = {
NONE = "None (empty)",
PERCENTAGE = "100%",
SHORT = "18.3k",
LONG = "18,300",
MIXED = "18.3k (100%)"
},
get = function(info) return T.DB.profile.FrameSettings.HealthTextStyle end,
set = function(info, value)
T.DB.profile.FrameSettings.HealthTextStyle = value
bgframe:UpdateSettings()
bgframe:UpdateHealthBar()
end
},
header4 = { order = 27, name = "Other options", type = "header" },
menuenabled = {
order = 28,
name = "Click-through",
desc = "When frame is click-through, the menu and targeting capabilities are disabled.",
type = "toggle",
get = function(info) return T.DB.profile.FrameSettings.ClickThrough end,
set = function(info, val)
T.DB.profile.FrameSettings.ClickThrough = val
bgframe:SetMenu(not val)
end
},
opacity = {
order = 29,
name = "Opacity",
desc = "Set the opacity of the frame (100 is fully visible).",
type = "range",
min = 0,
max = 100,
step = 1,
get = function(info) return T.DB.profile.FrameSettings.Opacity end,
set = function(info, val)
T.DB.profile.FrameSettings.Opacity = val
bgframe:UpdateSettings()
end
},
usecombatopacity = {
order = 30,
name = "Use combat opacity",
desc = "Use a different opacity setting while in combat.",
type = "toggle",
get = function(info) return T.DB.profile.FrameSettings.UseCombatOpacity end,
set = function(info, val)
T.DB.profile.FrameSettings.UseCombatOpacity = val
end
},
combatopacity = {
order = 31,
name = "In-Combat Opacity",
desc = "Set the opacity of the frame while in combat (100 is fully visible).",
type = "range",
min = 0,
max = 100,
step = 1,
disabled = function() return not T.DB.profile.FrameSettings.UseCombatOpacity end,
get = function(info) return T.DB.profile.FrameSettings.CombatOpacity end,
set = function(info, val)
T.DB.profile.FrameSettings.CombatOpacity = val
end
}
}
}
}
}
T.Options = {}
function T.Options:Initialize()
local media = T.LSM
if media then
options.args.general.args.warnsound = {
order = 5,
name = "Health warning sound",
desc = "Sound to play when bodyguard health is dangerously low",
type = "select",
values = function(info)
return media:HashTable(media.MediaType.SOUND)
end,
dialogControl = "LSM30_Sound",
get = function(info) return T.DB.profile.WarnSound end,
set = function(info, val) T.DB.profile.WarnSound = val end
}
options.args.frame.args.texture = {
order = 4,
name = "Health bar texture",
desc = "Select the texture to use for the health bar",
type = "select",
values = function(info)
return media:HashTable(media.MediaType.STATUSBAR)
end,
dialogControl = "LSM30_Statusbar",
get = function(info) return T.DB.profile.FrameSettings.Texture end,
set = function(info, val)
T.DB.profile.FrameSettings.Texture = val
bgframe:UpdateSettings()
end
}
options.args.frame.args.background = {
order = 11,
name = "Frame background",
desc = "Select the texture to use for the frame background",
type = "select",
values = function(info)
return media:HashTable(media.MediaType.BACKGROUND)
end,
dialogControl = "LSM30_Background",
get = function(info) return T.DB.profile.FrameSettings.Backdrop.Background end,
set = function(info, val)
T.DB.profile.FrameSettings.Backdrop.Background = val
bgframe:UpdateSettings()
end
}
options.args.frame.args.border = {
order = 12,
name = "Frame border",
desc = "Select the border texture to use for the frame",
type = "select",
values = function(info)
return media:HashTable(media.MediaType.BORDER)
end,
dialogControl = "LSM30_Border",
get = function(info) return T.DB.profile.FrameSettings.Backdrop.Border end,
set = function(info, val)
T.DB.profile.FrameSettings.Backdrop.Border = val
bgframe:UpdateSettings()
end
}
options.args.frame.args.barfont = {
order = 20,
name = "Bar font",
desc = "Set the font to use for displaying the health percentage",
type = "select",
values = function(info)
return media:HashTable(media.MediaType.FONT)
end,
dialogControl = "LSM30_Font",
get = function(info) return T.DB.profile.FrameSettings.Font end,
set = function(info, val)
T.DB.profile.FrameSettings.Font = val
bgframe:UpdateSettings()
end
}
end
options.args.profile = LibStub("AceDBOptions-3.0"):GetOptionsTable(T.DB)
LibStub("AceConfig-3.0"):RegisterOptionsTable(NAME, options, {"bodyguardhealth", "bgh"})
local acd = LibStub("AceConfigDialog-3.0")
interfacePanel = acd:AddToBlizOptions(NAME, "Bodyguard Health", nil, "general")
framePanel = acd:AddToBlizOptions(NAME, "Frame settings", "Bodyguard Health", "frame")
acd:AddToBlizOptions(NAME, "Profile", "Bodyguard Health", "profile")
end
function T.Options:Open()
if not interfacePanel then return end
InterfaceOptionsFrame_OpenToCategory(framePanel)
InterfaceOptionsFrame_OpenToCategory(interfacePanel)
end
| mit |
keplerproject/copas | tests/tcptimeout.lua | 1 | 4457 | -- Tests Copas socket timeouts
--
-- Run the test file, it should exit successfully without hanging.
-- make sure we are pointing to the local copas first
package.path = string.format("../src/?.lua;%s", package.path)
local platform = "unix"
if package.config:sub(1,1) == "\\" then
platform = "windows"
elseif io.popen("uname", "r"):read("*a"):find("Darwin") then
platform = "mac"
end
print("Testing platform: " .. platform)
local copas = require("copas")
local socket = require("socket")
-- hack; no way to kill copas.loop from thread
local function error(err)
print(debug.traceback(err, 2))
os.exit(-1)
end
local function assert(truthy, err)
if not truthy then
print(debug.traceback(err, 2))
os.exit(-1)
end
end
-- tcp echo server for testing against, returns `ip, port` to connect to
-- send `quit\n` to cause server to disconnect client
-- stops listen server after first connection
local function singleuseechoserver()
local server = socket.bind("127.0.0.1", 0) -- "localhost" fails because of IPv6 error
local ip, port = server:getsockname()
local function echoHandler(skt)
-- remove server after first connection
copas.removeserver(server)
skt = copas.wrap(skt)
while true do
local data = skt:receive()
if not data or data == "quit" then
break
end
skt:send(data..'\n')
end
end
copas.addserver(server, echoHandler)
return ip, port
end
local tests = {}
function tests.just_exit()
copas.loop()
end
function tests.connect_and_exit()
local ip, port = singleuseechoserver()
copas.addthread(function()
local client = socket.connect(ip, port)
client = copas.wrap(client)
client:close()
end)
copas.loop()
end
if platform == "mac" then
-- this test fails on a Mac, looks like the 'listen(0)' isn't being honoured
print("\nSkipping test on Mac!\n")
else
function tests.connect_timeout_copas()
local server = socket.tcp()
server:bind("localhost", 0)
server:listen(0) -- zero backlog, single connection will block further connections
-- note: not servicing connections
local ip, port = server:getsockname()
copas.addthread(function()
-- fill server's implicit connection backlog
socket.connect(ip,port)
local client = socket.tcp()
client = copas.wrap(client)
client:settimeout(0.01)
local status, err = client:connect(ip, port)
assert(status == nil, "connect somehow succeeded")
assert(err == "timeout", "connect failed with non-timeout error: "..tostring(err))
client:close()
end)
copas.loop()
end
function tests.connect_timeout_socket()
local server = socket.tcp()
server:bind("localhost", 0)
server:listen(0) -- zero backlog, single connection will block further connections
-- note: not servicing connections
local ip, port = server:getsockname()
copas.addthread(function()
copas.useSocketTimeoutErrors(true)
-- fill server's implicit connection backlog
socket.connect(ip,port)
local client = socket.tcp()
client = copas.wrap(client)
client:settimeout(0.01)
local status, err = client:connect(ip, port)
assert(status == nil, "connect somehow succeeded")
-- we test for a different error message becasue we expect socket errors, not copas ones
assert(err == "Operation already in progress", "connect failed with non-timeout error: "..tostring(err))
client:close()
end)
copas.loop()
end
end
function tests.receive_timeout()
local ip, port = singleuseechoserver()
copas.addthread(function()
local client = socket.tcp()
client = copas.wrap(client)
client:settimeout(0.01)
local status, err = client:connect(ip, port)
assert(status, "failed to connect: "..tostring(err))
client:send("foo\n")
local data, err = client:receive()
assert(data, "failed to recieve: "..tostring(err))
assert(data == "foo", "recieved wrong echo: "..tostring(data))
local data, err = client:receive()
assert(data == nil, "somehow recieved echo without sending")
assert(err == "timeout", "failed with non-timeout error: "..tostring(err))
client:close()
end)
copas.loop()
end
-- test "framework"
for name, test in pairs(tests) do
print("testing: "..tostring(name))
local status, err = pcall(test)
if not status then
error(err)
end
end
print("[✓] all tests completed successuly")
| mit |
amirhoseinkarimi2233/uzzbot | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
githabbot/Quick-V2.7 | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
DeepeshC/pubnub | lua-corona/example-chat/main.lua | 2 | 2512 | --
-- INIT CHAT:
-- This initializes the pubnub networking layer.
--
require "pubnub"
chat = pubnub.new({
publish_key = "demo",
subscribe_key = "demo",
secret_key = nil,
ssl = nil,
origin = "pubsub.pubnub.com"
})
--
-- CHAT CHANNEL DEFINED HERE
--
CHAT_CHANNEL = 'PubNub-Chat-Channel'
--
-- TEXT OUT - Quick Print
--
local textoutline = 1
local function textout( text )
if textoutline > 22 then textoutline = 1 end
if textoutline == 1 then
local background = display.newRect(
0, 0,
display.contentWidth,
display.contentHeight
)
background:setFillColor(254,254,254)
end
local myText = display.newText(
text:gsub("^%s*(.-)%s*$", "%1"),
0, 0, nil,
display.contentWidth/20
)
myText:setTextColor( 200, 200, 180 )
myText.x = math.floor(display.contentWidth/2)
myText.y = (display.contentWidth/19) * textoutline + 45
textoutline = textoutline + 1
print(text)
end
--
-- STARTING WELCOME MESSAGE FOR THIS EXAMPLE
--
textout("...")
textout(" ")
--
-- HIDE STATUS BAR
--
display.setStatusBar( display.HiddenStatusBar )
--
-- CREATE CHATBOX TEXT INPUT FIELD
--
chatbox = native.newTextField( 10, 10, display.contentWidth - 20, 36, function(event)
-- Only send when the user is ready.
if not (event.phase == "ended" or event.phase == "submitted") then
return
end
-- Don't send Empyt Message
if chatbox.text == '' then return end
send_a_message(tostring(chatbox.text))
chatbox.text = ''
native.setKeyboardFocus(nil)
end )
--
-- A FUNCTION THAT WILL OPEN NETWORK A CONNECTION TO PUBNUB
--
function connect()
chat:subscribe({
channel = CHAT_CHANNEL,
connect = function()
textout('Connected!')
end,
callback = function(message)
textout(message.msgtext)
end,
errorback = function()
textout("Oh no!!! Dropped 3G Conection!")
end
})
end
--
-- A FUNCTION THAT WILL CLOSE NETWORK A CONNECTION TO PUBNUB
--
function disconnect()
chat:unsubscribe({
channel = CHAT_CHANNEL
})
textout('Disconnected!')
end
--
-- A FUNCTION THAT WILL SEND A MESSAGE
--
function send_a_message(text)
chat:publish({
channel = CHAT_CHANNEL,
message = { msgtext = text },
callback = function(info)
end
})
end
--
-- OPEN NETWORK CONNECTION VIA PUBNUB
--
connect()
| mit |
bluegr/scummvm | devtools/create_ultima/files/ultima6/scripts/common/common.lua | 18 | 9350 | --note nuvie direction values aren't the same as the original it uses the following scheme
--701
--6 2
--543
DIR_NORTH = 0
DIR_EAST = 1
DIR_SOUTH = 2
DIR_WEST = 3
DIR_NORTHEAST = 4
DIR_SOUTHEAST = 5
DIR_SOUTHWEST = 6
DIR_NORTHWEST = 7
DIR_NONE = 8
UI_STYLE_ORIG = 0
UI_STYLE_NEW = 1
UI_STYLE_ORIG_PLUS_CUTOFF_MAP = 2
UI_STYLE_ORIG_PLUS_FULL_MAP = 3
STACK_OBJECT_QTY = true
movement_offset_x_tbl = {0, 1, 1, 1, 0, -1, -1, -1}
movement_offset_y_tbl = {-1, -1, 0, 1, 1, 1, 0, -1 }
if not setfenv then -- Lua 5.2
-- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
-- this assumes f is a function
local function findenv(f)
local level = 1
repeat
local name, value = debug.getupvalue(f, level)
if name == '_ENV' then return level, value end
level = level + 1
until name == nil
return nil
end
getfenv = function (f) return(select(2, findenv(f)) or _G) end
setfenv = function (f, t)
local level = findenv(f)
if level then debug.setupvalue(f, level, t) end
return f
end
end
function get_target()
local loc = coroutine.yield("target")
return loc
end
function get_direction(prompt)
if prompt ~= nil then
print(prompt)
end
local dir = coroutine.yield("dir")
return dir
end
function really_get_direction(prompt)
if prompt ~= nil then
print(prompt)
end
local dir = coroutine.yield("need_dir")
return dir
end
function direction_string(dir)
if dir ~= nil then
if dir == DIR_NORTH then return "north" end
if dir == DIR_NORTHEAST then return "northeast" end
if dir == DIR_EAST then return "east" end
if dir == DIR_SOUTHEAST then return "southeast" end
if dir == DIR_SOUTH then return "south" end
if dir == DIR_SOUTHWEST then return "southwest" end
if dir == DIR_WEST then return "west" end
if dir == DIR_NORTHWEST then return "northwest" end
end
return "unknown"
end
local dir_rev_tbl =
{
[DIR_NORTH] = DIR_SOUTH,
[DIR_NORTHEAST] = DIR_SOUTHWEST,
[DIR_EAST] = DIR_WEST,
[DIR_SOUTHEAST] = DIR_NORTHWEST,
[DIR_SOUTH] = DIR_NORTH,
[DIR_SOUTHWEST] = DIR_NORTHEAST,
[DIR_WEST] = DIR_EAST,
[DIR_NORTHWEST] = DIR_SOUTHEAST
}
function direction_reverse(dir) return dir_rev_tbl[dir] end
local g_dir_offset_tbl =
{
[DIR_NORTH] = {["x"]=0, ["y"]=-1},
[DIR_NORTHEAST] = {["x"]=1, ["y"]=-1},
[DIR_EAST] = {["x"]=1, ["y"]=0},
[DIR_SOUTHEAST] = {["x"]=1, ["y"]=1},
[DIR_SOUTH] = {["x"]=0, ["y"]=1},
[DIR_SOUTHWEST] = {["x"]=-1, ["y"]=1},
[DIR_WEST] = {["x"]=-1, ["y"]=0},
[DIR_NORTHWEST] = {["x"]=-1, ["y"]=-1},
[DIR_NONE] = {["x"]=0, ["y"]=0}
}
function direction_get_loc(dir, from_x, from_y)
return g_dir_offset_tbl[dir].x + from_x, g_dir_offset_tbl[dir].y + from_y
end
function abs(val)
if val < 0 then
return -val
end
return val
end
--collect Yes/No input from user and return true if Yes selected. false otherwise.
function input_should_proceed()
local input = input_select("yn", true)
print("\n")
if input == nil or input == "N" or input == "n" then
return false
end
return true
end
function play_midgame_sequence(seq_num)
local ui_style = game_get_ui_style()
canvas_show()
canvas_hide_all_sprites()
canvas_set_opacity(0xff);
canvas_set_update_interval(25)
canvas_rotate_game_palette(true)
local bg = sprite_new(nil, 8, 16, true)
local avatar = sprite_new(nil, 8, 16, false)
local text_sprite
--local text_sprite_bg
if ui_style == UI_STYLE_ORIG then
canvas_set_solid_bg(false)
else
--[[
text_sprite_bg = sprite_new(nil, 8, 160, true)
text_sprite_bg.text_align = 2
text_sprite_bg.text_color = 14
--]]
text_sprite = sprite_new(nil, 8, 160, true)
text_sprite.text_align = 2
text_sprite.text_color = 15
bg.x = 80
bg.y = 12
avatar.x = 80
avatar.y = 12
end
local midgame_data = midgame_load("midgame"..string.format("%x", seq_num)..".lzc")
local i = 0
local data = midgame_data[i]
while data ~= nil do
bg.image = data.images[0]
if data.images[1] ~= nil then
local gender = player_get_gender()
avatar.image = data.images[1+gender]
avatar.visible = true
else
avatar.visible = false
end
local j = 0
local text = data.text[j]
while text ~= nil do
if text ~= "*END*" then
if ui_style == UI_STYLE_ORIG then
clear_scroll()
print(text)
else
text_sprite.text = text
--text_sprite_bg.text = text
end
local input = nil
while input == nil do
canvas_update()
input = input_poll()
if input ~= nil then
break
end
end
end
j = j + 1
text = data.text[j]
end
i = i + 1
data = midgame_data[i]
end
if ui_style == UI_STYLE_ORIG then
clear_scroll()
end
canvas_set_solid_bg(true)
canvas_rotate_game_palette(false)
canvas_hide()
end
function get_wrapped_dist(pt1, pt2)
local diff
if pt2 >= pt1 then
diff = pt2 - pt1
else
diff = pt1 - pt2
end
if diff > 512 then
diff = 1024 - diff
end
return diff
end
function get_anim_index_for_tile(tile_number)
local total_anims = anim_get_number_of_entries()
for i=0,total_anims-1 do
if anim_get_tile(i) == tile_number then
return i
end
end
return nil
end
function altcode_242_set_actor_talk_flag()
print("NPC: ")
local input = input_select(nil, true)
local actor_num = tonumber(input, 16)
local actor = Actor.get(actor_num)
print("\n"..actor.name.."\n")
print("flags: \n") --FIXME print talk flags
print("\nBit: ")
local bit = input_select_integer(nil, true)
local value = Actor.get_talk_flag(actor, bit)
local value_str = "off"
if value == true then
value_str = "on"
end
print(" is "..value_str..".\n")
print("New value? ")
value = input_select_integer(nil, true)
value_str = "off"
if value == 1 or value == "o" then
value_str = "on"
Actor.set_talk_flag(actor, bit)
else
Actor.clear_talk_flag(actor, bit)
end
print("\n"..value_str.."\n")
end
function altcode_250_create_object()
print("Create Item:\nType:0x")
local input = input_select(nil, true)
local obj_n = tonumber(input, 16)
local obj = Obj.new(obj_n)
local tmp_obj = Obj.new(obj_n+1)
if tmp_obj ~= nil and tmp_obj.tile_num - obj.tile_num > 1 then
print("\nFrame:0x")
input = input_select(nil, true)
obj.frame_n = tonumber(input, 16)
end
print("\nQual:0x")
input = input_select(nil, true)
obj.quality = tonumber(input, 16)
if obj.stackable or create_object_needs_quan(obj_n) then
print("\nQuan:0x")
input = input_select(nil, true)
obj.qty = tonumber(input, 16)
end
Obj.moveToInv(obj, Actor.get(1).actor_num)
print("\n")
end
function altcode_913_export_tmx_map_files()
print("\nExport maps to savedir? ")
if not input_should_proceed() then
return
end
print("saving.\n")
script_wait(1)
if map_export_tmx_files() == true then
print("done.\n\n")
else
print("error!!\n\n")
end
end
function altcode_914_export_tileset()
print("Exporting tileset to \"data/images/tiles/"..config_get_game_type().."/custom_tiles.bmp\" in the savegame directory.\n")
if not tileset_export() then
print("file already exists. Overwrite? ")
if not input_should_proceed() then
return
end
tileset_export(true)
end
print("done.\n\n")
end
function altcode_999_find_objs_on_map()
print("Find Object\nObj_n: ")
local input = input_select(nil, true)
local obj_n = tonumber(input, 10)
if obj_n == nil then
print("Nothing.\n")
return
end
print("\nFrame: ")
input = input_select(nil, true)
local frame_n = tonumber(input, 10)
print("\nQuality: ")
input = input_select(nil, true)
local quality = tonumber(input, 10)
print("\nz: ")
input = input_select(nil, true)
local z = tonumber(input, 10)
if z == nil then
z = 0
end
print("\n")
for obj in find_obj(z, obj_n, frame_n, quality) do
print(string.format("OBJ: (%x,%x,%x)\n", obj.x, obj.y, obj.z))
party_move(obj.x, obj.y, obj.z)
print("continue? ")
input = input_select("yn", false)
print("\n")
if input == "N" or input == "n" then
return
end
end
end
local altcode_tbl = {
[242]=altcode_242_set_actor_talk_flag,
[250]=altcode_250_create_object,
[913]=altcode_913_export_tmx_map_files,
[914]=altcode_914_export_tileset,
[999]=altcode_999_find_objs_on_map,
}
function handle_alt_code(altcode)
local func = altcode_tbl[altcode]
if func ~= nil then
func()
end
end
function get_actor_or_obj_from_loc(location)
local target = map_get_actor(location)
if target == nil then
target = map_get_obj(location)
end
return target
end
--load other common functions
local lua_file = nil
lua_file = nuvie_load("common/lang.lua");
lua_file();
lang_init("game")
lua_file = nuvie_load("common/actor.lua"); lua_file();
| gpl-3.0 |
NYRDS/pixel-dungeon-remix | RemixedDungeon/src/main/assets/scripts/lib/mob.lua | 1 | 3076 | --
-- User: mike
-- Date: 23.11.2017
-- Time: 21:00
-- This file is part of Remixed Pixel Dungeon.
--
local RPD = require "scripts/lib/commonClasses"
local quest = require"scripts/lib/quest"
local serpent = require "scripts/lib/serpent"
local mob = {}
local knownMobs = {}
setmetatable(knownMobs, { __mode = 'vk' })
mob.__index = mob
mob.init = function(desc)
local ret = {}
for k,v in pairs(desc) do
ret[k] = v
end
setmetatable(ret, mob)
ret.data = {}
return ret
end
local onDieCallbacks = {}
mob.installOnDieCallback = function(callback)
onDieCallbacks[callback] = true
end
mob.saveData = function (self, _)
return serpent.dump(self.data or {})
end
mob.loadData = function (self, _, str)
local _,data = serpent.load(str)
self.data = data or {}
end
mob.storeData = function(self, data)
knownMobs[self].data = data or {}
end
mob.restoreData = function(self)
return knownMobs[self].data or {}
end
mob.onDie = function(self,mob,cause)
quest.mobDied(mob, cause)
for k, _ in pairs(onDieCallbacks) do
k(mob,cause)
end
return not not (self.die and self.die(mob, cause))
end
mob.onInteract = function(self,mob,chr)
if not self.interact then
return false
end
self.interact(mob, chr)
return true
end
mob.onMove = function(self,mob,cell)
return not not (self.move and self.move(mob, cell))
end
mob.onAct = function(self,mob)
return not not (self.act and self.act(mob))
end
mob.onDamage = function(self,mob,dmg,src)
return not not (self.damage and self.damage(mob, dmg, src))
end
mob.onSpawn = function(self,mob,level)
return not not (self.spawn and self.spawn(mob,level))
end
mob.onDefenceProc = function(self,mob, enemy, damage)
if not self.defenceProc then
return damage
end
return self.defenceProc(mob, enemy, damage)
end
mob.onAttackProc = function(self,mob, enemy, damage)
if not self.attackProc then
return damage
end
return self.attackProc(mob, enemy, damage)
end
mob.onZapProc = function(self,mob, enemy, damage)
if not self.zapProc then
return damage
end
return self.zapProc(mob, enemy, damage)
end
mob.fillStats = function(self,mob)
knownMobs[mob] = self
return not not (self.stats and self.stats(mob))
end
mob.onSelectCell = function(self, mob)
return not not (self.selectCell and self.selectCell(mob))
end
mob.actionsList = function(self, mob, hero)
if not self.actions then
return {}
end
return self.actions(mob, hero)
end
mob.executeAction = function(self, mob, hero, action)
if not self.execute then
return
end
return self.execute(mob, hero, action)
end
mob.priceSell = function(self, mob, item, defaultPrice)
if not self.priceForSell then
return defaultPrice
end
return self.priceForSell(mob, item)
end
mob.priceBuy = function(self, mob, item, defaultPrice)
if not self.priceForBuy then
return defaultPrice
end
return self.priceForBuy(mob, item)
end
return mob
| gpl-3.0 |
adixcompany/ad2 | plugins/ingroup.lua | 371 | 44212 | do
-- Check Member
local function check_member_autorealm(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(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)] = {
group_type = 'Realm',
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 realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(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)] = {
group_type = 'Group',
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)] = {
group_type = 'Group',
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_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(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
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
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
--End Check Member
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 leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
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 set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
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 is_group(msg) 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 realmadd(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 is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
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 is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(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 is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{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 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, '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 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.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_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
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][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)
--vardump(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
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
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_id = cb_extra.chat_id
local chat = "chat#id"..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
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
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
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
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] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(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_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.."] 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 not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(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
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(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] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) 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' and matches[2] 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] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_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")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
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] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(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
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
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 = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| agpl-3.0 |
keplerproject/copas | tests/largetransfer.lua | 1 | 3226 | -- tests large transmissions, sending and receiving
-- uses `receive` and `receivePartial`
-- Does send the same string twice simultaneously
--
-- Test should;
-- * show timer output, once per second, and actual time should be 1 second increments
-- * both transmissions should take appr. equal time, then they we're nicely cooperative
local copas = require 'copas'
local socket = require 'socket'
local body = ("A"):rep(1024*1024*50) -- 50 mb string
local start = socket.gettime()
local done = 0
local sparams, cparams
local function runtest()
local s1 = socket.bind('*', 49500)
copas.addserver(s1, copas.handler(function(skt)
--skt:settimeout(0) -- don't set, uses `receive` method
local res, err, part = skt:receive('*a')
res = res or part
if res ~= body then print("Received doesn't match send") end
print("Reading... 49500... Done!", socket.gettime()-start, err, #res)
if copas.removeserver then copas.removeserver(s1) end
end, sparams))
local s2 = socket.bind('*', 49501)
copas.addserver(s2, copas.handler(function(skt)
skt:settimeout(0) -- set, uses the `receivePartial` method
local res, err, part = skt:receive('*a')
res = res or part
if res ~= body then print("Received doesn't match send") end
print("Reading... 49501... Done!", socket.gettime()-start, err, #res)
if copas.removeserver then copas.removeserver(s2) end
end, sparams))
copas.addthread(function()
copas.sleep(0)
local skt = socket.tcp()
skt = copas.wrap(skt, cparams)
skt:connect("localhost", 49500)
local _, err = skt:send(body)
print("Writing... 49500... Done!", socket.gettime()-start, err, #body)
skt = nil -- luacheck: ignore
collectgarbage()
collectgarbage()
done = done + 1
end)
copas.addthread(function()
copas.sleep(0)
local skt = socket.tcp()
skt = copas.wrap(skt, cparams)
skt:connect("localhost", 49501)
local _, err = skt:send(body)
print("Writing... 49501... Done!", socket.gettime()-start, err, #body)
skt = nil -- luacheck: ignore
collectgarbage()
collectgarbage()
done = done + 1
end)
copas.addthread(function()
copas.sleep(0)
local i = 1
while done ~= 2 do
copas.sleep(1)
print(i, "seconds:", socket.gettime()-start)
i = i + 1
if i > 60 then
print"timeout"
os.exit(1)
end
end
end)
print("starting loop")
copas.loop()
print("Loop done")
end
runtest() -- run test using regular connection (s/cparams == nil)
-- set ssl parameters and do it again
sparams = {
mode = "server",
protocol = "tlsv1",
key = "tests/certs/serverAkey.pem",
certificate = "tests/certs/serverA.pem",
cafile = "tests/certs/rootA.pem",
verify = {"peer", "fail_if_no_peer_cert"},
options = {"all", "no_sslv2"},
}
cparams = {
mode = "client",
protocol = "tlsv1",
key = "tests/certs/clientAkey.pem",
certificate = "tests/certs/clientA.pem",
cafile = "tests/certs/rootA.pem",
verify = {"peer", "fail_if_no_peer_cert"},
options = {"all", "no_sslv2"},
}
done = 0
start = socket.gettime()
runtest()
| mit |
nobe4/dotfiles | nvim/lua/nobe4/mappings.lua | 1 | 4362 | local options = { noremap = true, silent = false }
local map = vim.keymap.set
-- Space is the Leader key
map("", "<Space>" , "<Nop>", options)
vim.g.mapleader = " "
vim.g.maplocalleader = " "
map("n", "zf", "zM100zozz", options) -- Fold to current level
-- Move vertically
map("n", "j", "gj", options)
map("n", "k", "gk", options)
map("v", "j", "gj", options)
map("v", "k", "gk", options)
map("n", "gp", "'[v']", options) -- Select last pasted zone
map("v", "@", ":norm@", options) -- Replay mapping over visual
map("n", "<Leader>d", [[0/\[.\]<CR>:nohlsearch<CR><right>s]], options)
map("n", "<Leader>w", ":noautocmd w<CR>", options) -- Save file without autocmd
map("n", "<Leader>q", ":quit!", options)
map("n", "<Leader>x", ":xit", options)
map("n", "<Leader>m", ":make", options)
map("n", "<Leader>R", ":nnoremap <lt>Leader>r :", options) -- Prepare a quick command: http://vi.stackexchange.com/a/3136/1821
map("n", "<Leader>r", ":<UP>", options) -- repeat last command
map("n", "<Leader>o", ":call system('open ' . expand('<cWORD>'))<CR>", options) -- open WORD under cursor
map("n", "gf", ":e <cfile><CR>", options) -- open file under cursor
map("n", "<Leader>b", ":b#<CR>", options) -- show buffer list
map("n", "<Leader>l", ":ls<CR>:buffer<Space>", options) -- show buffers and wait for a selection
map("n", "<Leader><Leader>", ":<C-U>nohlsearch<C-R>=has('diff')?'<Bar>diffupdate':''<CR><CR>", options) -- clear highlight
map("n", '"p', [[:reg <bar> exec 'normal!"'.input('>').'p'<CR>]], options) -- show registers value before pasting
map("c", "<C-A>", "<Home>", options) -- Go to the start of the command line
-- Add edition breakpoint on different keypress
map("i", "<CR>", "<C-G>u<CR>", options)
map("i", "<C-U>", "<C-G>u<C-U>", options)
map("i", "<C-W>", "<C-G>u<C-W>", options)
map("c", "<C-F>", "<C-R>=expand('%:p:h')<CR>/", options) -- Insert path to current file
map("n", "<Leader>e", ":edit <C-R>=expand('%:p:h')<CR>/", options) -- Prepare to edit a file in the same folder as the current one
map("n", "<Leader>z", ":execute 'tabnew +' . line('.') .' %'<CR>", options) -- Zoom in current buffer
map("t", "<Esc>", [[<C-\><C-n>]], options) -- Escape in terminal
-- /!\ Not working
-- map("n", "<Leader>yp", function()
-- vim.o.paste = true
-- vim.api.nvim_paste(vim.fn.getreg('"'))
-- vim.o.paste = false
-- end, options)
-- Fugitive
map("n", "<Leader>gs", ":tabnew +Git status<CR>", options)
map("n", "<Leader>gp", ":Git push -uq", options)
map("n", "<Leader>gl", ":Git pull", options)
map("n", "<Leader>gb", ":GBrowse<CR>", options)
map("v", "<Leader>gb", ":GBrowse<CR>", options)
-- Fzf
map("n", "<Leader>f", function() require('telescope.builtin').find_files() end, options)
map("n", "<Leader>t", function() require('telescope.builtin').tags() end, options)
map("n", [[\]], function() require('telescope.builtin').live_grep() end, options)
-- VimCorrect
map("n", "Z=", ":Correct<CR>", options)
-- EasyAlign
map("x", "ga", "<Plug>(EasyAlign)", options)
map("n", "ga", "<Plug>(EasyAlign)", options)
map("n", "<Leader>ut", ":UndotreeToggle<CR>", options)
map("n", "<Leader>uf", ":UndotreeFocus<CR>", options)
-- Notational
-- TODO: find a way to search for the filename as well
map("n", "<Leader>n", function()
require('telescope.builtin').live_grep({
cwd = "~/Documents/docs",
glob_pattern = { '*.md', '*.txt' },
})
end, options)
-- unimpaired-like
-- Inspired by https://git.io/vHtuc
local function map_next(map_key, cmd)
map("n", "]" .. map_key, ":" .. cmd .. "next<CR>", options)
map("n", "[" .. map_key, ":" .. cmd .. "previous<CR>", options)
map("n", "]" .. map_key:upper(), ":" .. cmd .. "last<CR>", options)
map("n", "[" .. map_key:upper(), ":" .. cmd .. "first<CR>", options)
end
map_next('q','c') -- jump between items in the (q)uickfix list
map_next('t','t') -- jump between matching (t)ags
map_next('l','l') -- jump between lines in the (l)ocation list
-- LuaSnip
local ls = require("luasnip")
map({ "i", "s" }, "<C-K>", function()
if ls.expand_or_jumpable() then
ls.expand_or_jump()
else
print("NOP")
end
end, { silent = true })
map({ "i", "s" }, "<C-J>", function()
if ls.jumpable(-1) then
ls.jump(-1)
end
end, { silent = true })
map({ "i", "s" }, "<C-L>", function()
if ls.choice_active() then
ls.change_choice(1)
end
end)
| mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/loot/groups/junk.lua | 1 | 1945 | --Automatically generated by SWGEmu Spawn Tool v0.12 loot editor.
junk = {
description = "",
minimumLevel = 0,
maximumLevel = 0,
lootItems = {
{itemTemplate = "broken_binoculars_s1", weight = 300000},
{itemTemplate = "broken_binoculars_s2", weight = 300000},
{itemTemplate = "broken_decryptor", weight = 300000},
{itemTemplate = "broken_viewscreen_grey", weight = 300000},
{itemTemplate = "broken_viewscreen_tan", weight = 300000},
{itemTemplate = "camera", weight = 300000},
{itemTemplate = "cargo_pocket", weight = 300000},
{itemTemplate = "corsec_id_badge", weight = 300000},
{itemTemplate = "damaged_datapad", weight = 300000},
{itemTemplate = "decorative_bowl", weight = 300000},
{itemTemplate = "decorative_shisa", weight = 300000},
{itemTemplate = "dermal_analyzer", weight = 300000},
{itemTemplate = "dud_firework_grey", weight = 300000},
{itemTemplate = "dud_firework_red", weight = 300000},
{itemTemplate = "empty_cage", weight = 300000},
{itemTemplate = "expensive_basket", weight = 300000},
{itemTemplate = "expired_ticket", weight = 300000},
{itemTemplate = "hyperdrive_part", weight = 300000},
{itemTemplate = "ledger", weight = 300000},
{itemTemplate = "locked_briefcase", weight = 300000},
{itemTemplate = "locked_container", weight = 300000},
{itemTemplate = "loudspeaker", weight = 300000},
{itemTemplate = "palm_frond", weight = 300000},
{itemTemplate = "photographic_image", weight = 300000},
{itemTemplate = "recorded_image_1", weight = 300000},
{itemTemplate = "recording_rod", weight = 300000},
{itemTemplate = "satchel", weight = 300000},
{itemTemplate = "slave_collar", weight = 300000},
{itemTemplate = "used_ticket", weight = 300000},
{itemTemplate = "worklight", weight = 300000},
{groupTemplate = "coa_encoded_disk_fragments", weight = 80000},
{groupTemplate = "data_storage_unit_parts", weight = 920000},
}
}
addLootGroupTemplate("junk", junk)
| agpl-3.0 |
LeMagnesium/minetest-minetestforfun-server | mods/homedecor_modpack/homedecor/foyer.lua | 12 | 1879 | local S = homedecor.gettext
homedecor.register("coatrack_wallmount", {
tiles = { homedecor.plain_wood },
inventory_image = "homedecor_coatrack_wallmount_inv.png",
description = "Coatrack (wallmounted)",
groups = {snappy=3},
sounds = default.node_sound_wood_defaults(),
node_box = {
type = "fixed",
fixed = {
{-0.375, 0, 0.4375, 0.375, 0.14, 0.5}, -- NodeBox1
{-0.3025, 0.0475, 0.375, -0.26, 0.09, 0.4375}, -- NodeBox2
{0.26, 0.0475, 0.375, 0.3025, 0.09, 0.4375}, -- NodeBox3
{0.0725, 0.0475, 0.375, 0.115, 0.09, 0.4375}, -- NodeBox4
{-0.115, 0.0475, 0.375, -0.0725, 0.09, 0.4375}, -- NodeBox5
{0.24, 0.025, 0.352697, 0.3225, 0.115, 0.375}, -- NodeBox6
{-0.3225, 0.025, 0.352697, -0.24, 0.115, 0.375}, -- NodeBox7
{-0.135, 0.025, 0.352697, -0.0525, 0.115, 0.375}, -- NodeBox8
{0.0525, 0.025, 0.352697, 0.135, 0.115, 0.375}, -- NodeBox9
}
},
})
homedecor.register("coat_tree", {
mesh = "homedecor_coatrack.obj",
tiles = {
homedecor.plain_wood,
"homedecor_generic_wood_old.png"
},
inventory_image = "homedecor_coatrack_inv.png",
description = "Coat tree",
groups = {snappy=3},
sounds = default.node_sound_wood_defaults(),
expand = { top="placeholder" },
walkable = false,
selection_box = {
type = "fixed",
fixed = { -0.4, -0.5, -0.4, 0.4, 1.5, 0.4 }
},
on_rotate = screwdriver.rotate_simple
})
for _, color in pairs({ "green", "brown", "grey" }) do
homedecor.register("welcome_mat_"..color, {
description = "Welcome Mat ("..color..")",
tiles = {
"homedecor_welcome_mat_"..color..".png",
"homedecor_welcome_mat_bottom.png",
"homedecor_welcome_mat_"..color..".png",
},
groups = {crumbly=3},
sounds = default.node_sound_dirt_defaults({
footstep = {name="default_grass_footstep", gain=0.25},
}),
node_box = {
type = "fixed",
fixed = { -0.5, -0.5, -0.375, 0.5, -0.46875, 0.375 }
}
})
end
| unlicense |
sbouchex/domoticz | dzVents/runtime/integration-tests/stage1.lua | 6 | 44267 | local log
local dz
local err = function(msg)
log(msg, dz.LOG_ERROR)
end
local tstMsg = function(msg, res)
print('Stage: 1, ' .. msg .. ': ' .. tostring(res and 'OK' or 'FAILED'))
end
local expectEql = function (attr, test, marker)
if (attr ~= test) then
local msg = tostring(attr) .. '~=' .. tostring(test)
if (marker ~= nil) then
msg = msg .. ' (' .. tostring(marker) ..')'
end
err(msg)
print(debug.traceback())
return false
end
return true
end
local checkAttributes = function(dev, attributes)
local res = true
for attr, value in pairs(attributes) do
res = res and expectEql(dev[attr], value, attr)
end
return res
end
local testAirQuality = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 2,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["quality"] = 'Excellent',
["co2"] = 0,
["deviceSubType"] = "Voltcraft CO-20";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Air Quality";
})
dev.updateAirQuality(1600).silent()
tstMsg('Test air quality device', res)
return res
end
local testSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 1,
["name"] = name,
["maxDimLevel"] = 100,
["baseType"] = dz.BASETYPE_DEVICE,
["state"] = "Off",
["deviceSubType"] = "Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Light/Switch";
["description"] = 'desc vdSwitch';
})
dev.switchOn().afterSec(1)
tstMsg('Test switch device', res)
return res
end
local testQuietOnSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["name"] = name,
["maxDimLevel"] = 100,
["baseType"] = dz.BASETYPE_DEVICE,
["state"] = "Off",
["deviceSubType"] = "Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Light/Switch";
})
dev.quietOn().afterSec(3)
tstMsg('Test quietOn switch device', res)
return res
end
local testRenameSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["name"] = name,
["state"] = "Off",
["deviceSubType"] = "Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["deviceType"] = "Light/Switch";
})
dev.switchOn().afterSec(2)
tstMsg('Test Rename switch device', res)
return res
end
local testProtectSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["name"] = name,
["state"] = "Off",
["deviceSubType"] = "Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["deviceType"] = "Light/Switch";
})
dev.switchOn().afterSec(3)
tstMsg('Test Protect switch device', res)
return res
end
local testWildcardsSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["name"] = name,
["maxDimLevel"] = 100,
["baseType"] = dz.BASETYPE_DEVICE,
["state"] = "On",
["deviceSubType"] = "Switch";
["switchType"] = "Dimmer",
["switchTypeValue"] = 7,
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Light/Switch";
})
dev. dimTo(1).afterSec(4)
tstMsg('Test Wildcard switch device', res)
return res
end
local testQuietOffSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["name"] = name,
["maxDimLevel"] = 100,
["baseType"] = dz.BASETYPE_DEVICE,
["state"] = "Off",
["deviceSubType"] = "Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Light/Switch";
})
dev.switchOff()
dev.quietOff()
tstMsg('Test quietOff switch device', res)
return res
end
local testDimmer = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 43,
["name"] = name,
["maxDimLevel"] = 100,
["baseType"] = dz.BASETYPE_DEVICE,
['level'] = 34,
["lastLevel"] = 34, -- this script is NOT triggered by the dimmer so lastLevel is the current level
["state"] = "On",
["deviceSubType"] = "Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["switchType"] = "Dimmer",
["switchTypeValue"] = 7,
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Light/Switch";
["description"] = "desc vdSwitchDimmer"
})
dev.dimTo(75).afterSec(1)
tstMsg('Test dimmer', res)
return res
end
local testAlert = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 3,
["name"] = name,
["state"] = "No Alert!",
["baseType"] = dz.BASETYPE_DEVICE,
["color"] = 0,
["deviceSubType"] = "Alert";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "General";
})
dev.updateAlertSensor(dz.ALERTLEVEL_RED, 'Hey I am red')
tstMsg('Test alert sensor device', res)
return res
end
local testAmpere3 = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 4,
['current1'] = 0,
['current2'] = 0,
['current3'] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["name"] = name,
["deviceSubType"] = "CM113, Electrisave";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "Current";
})
dev.updateCurrent(123, 456, 789)
tstMsg('Test ampere 3 device', res)
return res
end
local testAmpere1 = function(name)
local dev = dz.devices(name)
local res = true
res = res and expectEql(0, dev.current)
res = res and checkAttributes(dev, {
["id"] = 5,
["name"] = name,
["state"] = "0.0",
["deviceSubType"] = "Current";
["baseType"] = dz.BASETYPE_DEVICE,
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "General";
})
dev.updateCurrent(123)
tstMsg('Test ampere 1 device', res)
return res
end
local testBarometer = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 6,
["name"] = name,
["forecastString"] = "Stable";
["forecast"] = 0;
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Barometer";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
["deviceType"] = "General";
})
dev.updateBarometer(1234, dz.BARO_THUNDERSTORM)
tstMsg('Test barometer device', res)
return res
end
local testCounter = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 7,
["name"] = name,
["counterToday"] = 0;
["valueUnits"] = "";
["baseType"] = dz.BASETYPE_DEVICE,
["valueQuantity"] = "";
["counter"] = 0.000;
["deviceSubType"] = "RFXMeter counter";
["deviceType"] = "RFXMeter";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateCounter(1234)
tstMsg('Test counter device', res)
return res
end
local testCounterIncremental = function(name)
local dev = dz.devices(name)
local res = true
local res2 = true
res = res and checkAttributes(dev, {
["id"] = 8,
["name"] = name,
["counterToday"] = 0;
["baseType"] = dz.BASETYPE_DEVICE,
["valueUnits"] = "";
["valueQuantity"] = "";
["counter"] = 0.000;
["deviceSubType"] = "Counter Incremental";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateCounter(1234)
tstMsg('Test method updateCounter for counter incremental device', res)
dev.incrementCounter(10).afterSec(10)
tstMsg('Test method incrementCounter for counter incremental device', res2)
return res and res2
end
local testCustomSensor = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 9,
["name"] = name,
["sensorUnit"] = "axis";
["sensorType"] = 1;
["baseType"] = dz.BASETYPE_DEVICE,
["state"] = "0.0";
["deviceSubType"] = "Custom Sensor";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateCustomSensor(1234)
tstMsg('Test custom sensor device', res)
return res
end
local testDistance = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 10,
["name"] = name,
["state"] = '123.4',
["baseType"] = dz.BASETYPE_DEVICE,
["distance"] = 123.4,
["deviceSubType"] = "Distance";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateDistance(42.44)
tstMsg('Test distance device', res)
return res
end
local testElectricInstanceCounter = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 11,
["name"] = name,
['WhTotal'] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
['WhActual'] = 0,
['counterToday'] = 0,
['usage'] = 0.0,
["deviceSubType"] = "kWh";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateElectricity(10, 20)
tstMsg('Test electric instance counter device', res)
return res
end
local testGas = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 12,
["name"] = name,
['counterToday'] = 0,
['counter'] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Gas";
["deviceType"] = "P1 Smart Meter";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateGas(6000) -- this won't have a direct effect
tstMsg('Test gas device', res)
return res
end
local testHumidity = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 13,
["name"] = name,
["humidityStatus"] = "Comfortable";
["humidity"] = 50;
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "LaCrosse TX3";
["deviceType"] = "Humidity";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateHumidity(88, dz.HUM_WET)
tstMsg('Test humidity device', res)
return res
end
local testLeafWetness = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 14,
["name"] = name,
['wetness'] = 2,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Leaf Wetness";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateWetness(55)
tstMsg('Test leaf wetness device', res)
return res
end
local testLux = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 15,
["name"] = name,
['lux'] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Lux";
["deviceType"] = "Lux";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateLux(355)
tstMsg('Test lux device', res)
return res
end
local testP1SmartMeter = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 16,
["name"] = name,
["WhActual"] = 0,
['usage1'] = 0,
['usage2'] = 0,
['return1'] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
['return2'] = 0,
['usage'] = 0,
['usageDelivered'] = 0,
['counterDeliveredToday'] = 0,
['counterToday'] = 0,
["deviceSubType"] = "Energy";
["deviceType"] = "P1 Smart Meter";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateP1(10, 20, 100, 200, 666, 777)
tstMsg('Test p1 smart meter device', res)
return res
end
local testPercentage = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 17,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
['percentage'] = 0,
["deviceSubType"] = "Percentage";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updatePercentage(99.99)
tstMsg('Test percentage device', res)
return res
end
local testPressureBar = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 18,
["name"] = name,
["pressure"] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Pressure";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updatePressure(88)
tstMsg('Test pressure device', res)
return res
end
local testRain = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 20,
["name"] = name,
["rain"] = 0,
["rainRate"] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "TFA";
["deviceType"] = "Rain";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateRain(3000, 6660)
tstMsg('Test rain device', res)
return res
end
local testRGB = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 22,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["maxDimLevel"] = 100,
["state"] = "On",
["deviceSubType"] = "RGB";
["deviceType"] = "Color Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.dimTo(15)
tstMsg('Test rgb device', res)
return res
end
local testRGBW = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 23,
["name"] = name,
["maxDimLevel"] = 100,
["state"] = "On",
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "RGBW";
["deviceType"] = "Color Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.setRGB(15, 30, 60)
dev.dimTo(15).afterSec(5)
tstMsg('Test RGBW device', res)
return res
end
local testScaleWeight = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 24,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
['weight'] = 0,
["deviceSubType"] = "BWR102";
["deviceType"] = "Weight";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateWeight(33.5)
tstMsg('Test scale weight device', res)
return res
end
local testSelectorSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 25,
["name"] = name,
['levelName'] = 'Off',
["baseType"] = dz.BASETYPE_DEVICE,
['level'] = 0,
["state"] = 'Off',
["deviceSubType"] = "Selector Switch";
["deviceType"] = "Light/Switch";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
res = res and ( dz.logObject(dev, nil, 'device' ) == nil )
res = res and expectEql('Off', dev.levelNames[1])
res = res and expectEql('Level1', dev.levelNames[2])
res = res and expectEql('Level2', dev.levelNames[3])
res = res and expectEql('Level3', dev.levelNames[4])
dev.switchSelector(30) -- level3
dev.switchSelector('Level3').checkFirst().afterSec(2) -- Will be checked in stage 2 with a script
dev.switchSelector('Level3').checkFirst().afterSec(4)
dev.switchSelector('Level3').checkFirst().afterSec(6)
tstMsg('Test selector switch device', res)
return res
end
local testSoilMoisture = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 27,
["name"] = name,
["moisture"] = 3,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Soil Moisture";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateSoilMoisture(34)
tstMsg('Test soil moisture device', res)
return res
end
local testSolarRadiation = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 28,
["name"] = name,
["radiation"] = 1,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Solar Radiation";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateRadiation(34)
tstMsg('Test solar radiation device', res)
return res
end
local testSoundLevel = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 29,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["level"] = 65,
["deviceSubType"] = "Sound Level";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateSoundLevel(120)
tstMsg('Test sound level device', res)
return res
end
local testTemperature = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 30,
["baseType"] = dz.BASETYPE_DEVICE,
["name"] = name,
["temperature"] = 0,
["deviceSubType"] = "LaCrosse TX3";
["deviceType"] = "Temp";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateTemperature(120)
tstMsg('Test temperature device', res)
return res
end
local testBackup = function()
local res = true
dz.openURL(dz.settings['Domoticz url'] .. '/backupdatabase.php')
tstMsg('Test Backup', res)
return res
end
local testEmit = function()
local res = true
dz.openURL(dz.settings['Domoticz url'] .."/json.htm?type=command%26param=customevent%26event=myEvents2%26data=someencodedstring" )
local myEventTable = { a ='a', b = '2'}
dz.emitEvent('myEvents3').afterSec(2)
dz.emitEvent('myEvents4','myEventString').afterSec(4)
dz.emitEvent('myEvents5',myEventTable).afterSec(6)
tstMsg('Test Emits', res)
return res
end
local testExecuteShellCommand = function()
local res = true
dz.executeShellCommand(
{
command = 'timeout 2 ping 8.8.8.8',
callback = 'test executeShellCommand'
}).afterSec(1)
tstMsg('Test executeShellCommand', res)
return res
end
local testAPITemperature = function(name)
local dev = dz.devices(name)
local res = true
dz.openURL(dz.settings['Domoticz url'] .. '/json.htm?type=command%26param=udevice%26idx=' .. tonumber(dev.id) .. '%26nvalue=0%26svalue=' .. tostring(42))
tstMsg('Test API temperature device', res)
return res
end
local testTempHum = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 31,
["name"] = name,
["temperature"] = 0,
["humidity"] = 50,
["baseType"] = dz.BASETYPE_DEVICE,
["humidityStatus"] = "Comfortable";
["deviceSubType"] = "THGN122/123/132, THGR122/228/238/268";
--["deviceType"] = 'Temp + Humidity';
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateTempHum(34, 88, dz.HUM_WET)
tstMsg('Test temperature+humidity device', res)
return res
end
local testTempHumBaro = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 32,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["temperature"] = 0,
["barometer"] = 1010,
["forecastString"] = "Sunny";
["forecast"] = 1;
["deviceSubType"] = "THB1 - BTHR918, BTHGN129";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateTempHumBaro(34, 88, dz.HUM_WET, 1033, dz.BARO_PARTLYCLOUDY)
tstMsg('Test temperature+humidity+barometer device', res)
return res
end
local testTempBaro = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 44,
["name"] = name,
["temperature"] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["barometer"] = 1038,
["forecastString"] = "Stable";
["forecast"] = 0;
["deviceSubType"] = "BMP085 I2C";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateTempBaro(34, 1033, dz.BARO_CLOUDY)
tstMsg('Test temperature+barometer device', res)
return res
end
local testText = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 33,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["text"] = 'Hello World',
["deviceSubType"] = "Text";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateText("Oh my Darwin, what a lot of tests!").afterSec(3)
dev.updateText("This change should not happen").afterSec(10) -- is cancelled in vdCancelledRepeatSwitch
tstMsg('Test text device', res)
return res
end
local testThermostatSetpoint = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 34,
["name"] = name,
["setPoint"] = 20.5,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "SetPoint";
["deviceType"] = "Thermostat";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateSetPoint(11)
dev.updateSetPoint(22).afterSec(2)
dev.updateSetPoint(33).afterSec(200)
tstMsg('Test thermostat device', res)
return res
end
local testUsageElectric = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 35,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["WhActual"] = 0,
["deviceSubType"] = "Electric";
["deviceType"] = "Usage";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateEnergy(1922)
tstMsg('Test usage electric device', res)
return res
end
local testUV = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 36,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["uv"] = 0,
["deviceSubType"] = "UVN128,UV138";
["deviceType"] = "UV";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateUV(12.33)
tstMsg('Test uv device', res)
return res
end
local testVisibility = function(name)
local dev = dz.devices(name)
local res = true
res = res and expectEql(103, math.floor(dev.visibility * 10))
res = res and checkAttributes(dev, {
["id"] = 37,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Visibility";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateVisibility(1)
tstMsg('Test visibility device', res)
return res
end
local testVoltage = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 38,
["name"] = name,
["voltage"] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Voltage";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateVoltage(220)
tstMsg('Test voltage device', res)
return res
end
local testWaterflow = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = 39,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["flow"] = 0,
["deviceSubType"] = "Waterflow";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateWaterflow(15)
tstMsg('Test waterflow device', res)
return res
end
local testWind = function(name, id, subType)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = id,
["name"] = name,
["gust"] = 0,
["temperature"] = 0,
["baseType"] = dz.BASETYPE_DEVICE,
["speed"] = 0,
["direction"] = 0,
['directionString'] = "N",
['chill'] = 0,
["deviceSubType"] = subType,
["deviceType"] = "Wind";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.updateWind(120, 'SW', 55, 66, 77, 88)
tstMsg('Test wind device', res)
return res
end
local testScene = function(name)
local scene = dz.scenes(name)
local res = true
res = res and checkAttributes(scene, {
["id"] = 1,
["name"] = name,
['state'] = 'Off',
["baseType"] = dz.BASETYPE_SCENE,
})
names = scene.devices().reduce(function(acc, device)
return acc .. device.name
end, '')
res = res and expectEql('sceneSwitch1', names, 'Scene iterators')
scene.switchOn()
tstMsg('Test scene', res)
return res
end
local testGroup = function(name)
local group = dz.groups(name)
local res = true
res = res and checkAttributes(group, {
["id"] = 2,
["name"] = name,
['state'] = 'Off',
['baseType'] = dz.BASETYPE_GROUP
})
group.switchOn()
tstMsg('Test group', res)
return res
end
local testVariableInt = function(name)
local var = dz.variables(name)
local res = true
res = res and checkAttributes(var, {
["id"] = 1,
["name"] = name,
["baseType"] = dz.BASETYPE_VARIABLE,
['value'] = 42
})
var.set(43)
tstMsg('Test variable: int', res)
return res
end
local testVariableFloat = function(name)
local var = dz.variables(name)
local res = true
res = res and checkAttributes(var, {
["id"] = 2,
["name"] = name,
["baseType"] = dz.BASETYPE_VARIABLE,
['value'] = 42.11
})
var.set(43)
tstMsg('Test variable: float', res)
return res
end
local testVariableString = function(name)
local var = dz.variables(name)
local res = true
res = res and checkAttributes(var, {
["id"] = 3,
["name"] = name,
["baseType"] = dz.BASETYPE_VARIABLE,
['value'] = 'Somestring'
})
var.set('Zork is a dork').withinSec(3)
local varCancelled = dz.variables('varCancelled')
varCancelled.set(2).afterSec(5) -- this one will be cancelled in varString.lua!
tstMsg('Test variable: string', res)
return res
end
local testVariableDate = function(name)
local var = dz.variables(name)
local res = true
res = res and checkAttributes(var, {
["id"] = 4,
["baseType"] = dz.BASETYPE_VARIABLE,
["name"] = name
})
res = res and expectEql(var.date.month, 12)
res = res and expectEql(var.date.day, 31)
res = res and expectEql(var.date.year, 2017)
var.set('20/11/2016');
tstMsg('Test variable: date', res)
return res
end
local testVariableTime = function(name)
local var = dz.variables(name)
local res = true
res = res and checkAttributes(var, {
["id"] = 5,
["baseType"] = dz.BASETYPE_VARIABLE,
["name"] = name,
})
res = res and expectEql(var.time.hour, 23)
res = res and expectEql(var.time.min, 59)
var.set('09:54');
tstMsg('Test variable: time', res)
return res
end
local testSilentSwitch = function(name)
local dev = dz.devices(name)
local res = true
dev.switchOn().silent()
tstMsg('Test silent switch device', res)
return res
end
local testSilentVar = function(name)
local var = dz.variables(name)
local res = true
var.set(1).silent();
tstMsg('Test silent variable', res)
return res
end
local testSilentScene = function(name)
local scene = dz.scenes(name)
local res = true
scene.switchOn().silent()
tstMsg('Test silent scene', res)
return res
end
local testSilentGroup = function(name)
local group = dz.groups(name)
local res = true
group.switchOn().silent()
tstMsg('Test silent group', res)
return res
end
local testSnapshot = function()
local res = true
res = res and dz.snapshot()
tstMsg('Test camera snaphot with defaults',res)
res = res and dz.snapshot(1,"stage1 snapshot").afterSec(4)
tstMsg('Test camera snaphot with id',res)
res = res and dz.snapshot("camera1","stage1 snapshot").afterSec(4)
tstMsg('Test camera snaphot with name',res)
res = res and dz.snapshot("camera1;camera1","stage1 snapshot").afterSec(5)
tstMsg('Test camera snaphot with names',res)
res = res and dz.snapshot("1;1","stage1 snapshot").afterSec(5)
tstMsg('Test camera snaphot with IDs',res)
res = res and dz.snapshot({"camera1","camera1"},"stage1 snapshot")
tstMsg('Test camera snaphot with names',res)
res = res and dz.snapshot({1,1},"stage1 snapshot").afterSec(5)
tstMsg('Test camera snaphot with IDs in table',res)
return res
end
local testManagedCounter = function(name)
local dev = dz.devices(name)
local res = true
res = dev.updateCounter(1234).afterSec(2)
tstMsg('Test managed counter',res)
return res
end
local testSetIconSwitch = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = id,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
})
dev.setIcon(10)
dev.dimTo(20).afterSec(1)
tstMsg('Test setIcon device', res)
return res
end
local testSetValueSensor = function(name)
local dev = dz.devices(name)
local res = true
res = res and checkAttributes(dev, {
["id"] = id,
["name"] = name,
["baseType"] = dz.BASETYPE_DEVICE,
["deviceSubType"] = "Custom Sensor";
["deviceType"] = "General";
["hardwareType"] = "Dummy (Does nothing, use for virtual switches only)";
["hardwareName"] = "dummy";
["hardwareTypeValue"] = 15;
["hardwareId"] = 2;
["batteryLevel"] = nil; -- 255 == nil
["changed"] = false;
["timedOut"] = false;
})
dev.setValues(nil, 12, 34, 45)
tstMsg('Test setValues device', res)
return res
end
local storeLastUpdates = function()
dz.globalData.stage1Time = dz.time.raw
end
local testLastUpdates = function()
local Time = require('Time')
local results = true
local now = dz.time.secondsSinceMidnight
results = dz.devices().reduce(function(acc, device)
if (device.name ~= 'endResult' and device.name ~= 'stage1Trigger' and device.name ~= 'stage2Trigger') then
local devTime = device.lastUpdate.secondsSinceMidnight
local delta = now - device.lastUpdate.secondsSinceMidnight
-- print('now:' .. now .. ' device: ' .. device.lastUpdate.secondsSinceMidnight .. ' delta: ' .. delta)
-- test if lastUpdate for the device is close to domoticz time
local ok = (devTime <= now and delta < 15)
acc = acc and ok
if (expectEql(true, ok, device.name .. ' lastUpdate is not correctly set') == false) then
print('now:' .. now .. ' device: ' .. device.lastUpdate.secondsSinceMidnight .. ' delta: ' .. delta)
end
end
return acc
end, results)
tstMsg('Test lastUpdates', results)
return results
end
local testSecurity = function()
local res = true
res = res and expectEql(dz.security, dz.SECURITY_DISARMED)
tstMsg('Test Security panel', res)
res = res and dz.devices('secPanel').armAway()
tstMsg('Test set security panel to armAway', res)
return res
end
local testLocation = function()
local res = true
res = res and expectEql(tonumber(dz.settings.location.latitude), 52.27887)
res = res and expectEql(tonumber(dz.settings.location.longitude), 5.665849)
res = res and expectEql(dz.settings.location.name, "Domoticz")
tstMsg('Test location in settings', res)
return res
end
local testVersion = function()
local res = true
res = res and type(dz.settings.domoticzVersion) == "string"
tstMsg('Test domoticz Version in settings (' .. dz.settings.domoticzVersion ..')' , res)
local utils = require('Utils')
res = res and expectEql(dz.settings.dzVentsVersion,utils.DZVERSION)
tstMsg('Test dzVents version in settings (' .. dz.settings.dzVentsVersion ..')' , res)
return res
end
local testRepeatSwitch = function(name)
local res = true
local dev = dz.devices(name)
dz.globalData.repeatSwitch.reset()
dz.globalData.repeatSwitch.add({ state = 'Start', delta = 0 })
dev.switchOn().afterSec(8).forSec(2).repeatAfterSec(5, 1) -- 17s total
tstMsg('Start test repeat switch device', res)
return res
end
local testCancelledRepeatSwitch = function(name)
local res = true
local dev = dz.devices(name)
dev.switchOn().afterSec(8).forSec(1).repeatAfterSec(1, 5)
tstMsg('Start test cancelled repeat switch device', res)
return res
end
local testCancelledScene = function(name)
local res = true
local sc = dz.scenes(name)
sc.switchOn().afterSec(5).forSec(1).repeatAfterSec(1, 5)
tstMsg('Start test cancelled repeat scene', res)
return res
end
local testHTTPSwitch = function(name)
local res = true
local dev = dz.devices(name)
dev.switchOn()
tstMsg('Start test http trigger switch device', res)
return res
end
local testDocumentationSwitch = function(name)
local res = true
local dev = dz.devices(name)
dev.switchOn()
tstMsg('Start test documentation switch device', res)
return res
end
local testDescriptionSwitchDevice = function(name)
local res = true
local dev = dz.devices(name)
dev.switchOn()
tstMsg('Start test description trigger switch device', res)
return res
end
local testDescriptionSwitchGroup = function(name)
local res = true
local group = dz.groups(name)
group.switchOn()
tstMsg('Start test description group', res)
return res
end
local testDescriptionSwitchScene = function(name)
local res = true
local scene = dz.scenes(name)
scene.switchOn()
tstMsg('Start test description scene', res)
return res
end
local testIFTTT = function(event)
local res = true
res = res and dz.triggerIFTTT(event)
res = res and dz.triggerIFTTT(event).afterSec(3)
return res
end
return {
active = true,
on = {
devices = {'stage1Trigger' }
},
execute = function(domoticz, trigger)
local res = true
dz = domoticz
log = dz.log
log('Starting stage 1')
res = res and testAirQuality('vdAirQuality')
res = res and testSwitch('vdSwitch')
res = res and testAlert('vdAlert')
res = res and testAmpere3('vdAmpere3')
res = res and testAmpere1('vdAmpere1')
res = res and testBackup()
res = res and testEmit()
res = res and testExecuteShellCommand()
res = res and testDimmer('vdSwitchDimmer')
res = res and testBarometer('vdBarometer')
res = res and testCounter('vdCounter')
res = res and testCounterIncremental('vdCounterIncremental')
res = res and testCustomSensor('vdCustomSensor')
res = res and testDistance('vdDistance')
res = res and testElectricInstanceCounter('vdElectricInstanceCounter')
res = res and testGas('vdGas')
res = res and testHumidity('vdHumidity')
res = res and testIFTTT('myEvent')
res = res and testLeafWetness('vdLeafWetness')
res = res and testLux('vdLux')
res = res and testP1SmartMeter('vdP1SmartMeterElectric')
res = res and testPercentage('vdPercentage')
res = res and testPressureBar('vdPressureBar')
res = res and testQuietOnSwitch('vdQuietOnSwitch')
res = res and testQuietOffSwitch('vdQuietOffSwitch')
res = res and testWildcardsSwitch('vdWildcardsSwitch')
res = res and testRain('vdRain')
res = res and testProtectSwitch('vdProtectSwitch')
res = res and testRenameSwitch('vdRenameSwitch')
res = res and testRGB('vdRGBSwitch')
res = res and testRGBW('vdRGBWSwitch')
res = res and testScaleWeight('vdScaleWeight')
res = res and testSelectorSwitch('vdSelectorSwitch')
res = res and testSetIconSwitch('vdSetIconSwitch')
res = res and testSetValueSensor('vdSetValueSensor')
res = res and testSoilMoisture('vdSoilMoisture')
res = res and testSolarRadiation('vdSolarRadiation')
res = res and testSoundLevel('vdSoundLevel')
res = res and testTemperature('vdTemperature')
res = res and testTempHum('vdTempHum')
res = res and testTempHumBaro('vdTempHumBaro')
res = res and testTempBaro('vdTempBaro')
res = res and testText('vdText')
res = res and testThermostatSetpoint("vdThermostatSetpoint")
res = res and testUsageElectric("vdUsageElectric")
res = res and testUV("vdUV")
res = res and testVisibility("vdVisibility")
res = res and testVoltage("vdVoltage")
res = res and testWaterflow("vdWaterflow")
res = res and testWind('vdWind', 41, "WTGR800")
res = res and testWind('vdWindTempChill', 42, "TFA")
res = res and testScene('scScene')
res = res and testGroup('gpGroup')
res = res and testVariableInt('varInteger')
res = res and testVariableFloat('varFloat')
res = res and testVariableString('varString')
res = res and testVariableDate('varDate')
res = res and testVariableTime('varTime')
res = res and testLastUpdates()
res = res and testSecurity()
res = res and testSilentSwitch('vdSilentSwitch')
res = res and testSilentScene('scSilentScene')
res = res and testSilentGroup('gpSilentGroup')
res = res and testSilentVar('varSilent')
res = res and testAPITemperature('vdAPITemperature');
res = res and testRepeatSwitch('vdRepeatSwitch');
res = res and testCancelledRepeatSwitch('vdCancelledRepeatSwitch');
res = res and testCancelledScene('scCancelledScene');
res = res and testLocation();
res = res and testVersion();
res = res and testHTTPSwitch('vdHTTPSwitch');
res = res and testDocumentationSwitch('vdDocumentationSwitch');
res = res and testDescriptionSwitchGroup('gpDescriptionGroup');
res = res and testDescriptionSwitchDevice('vdDescriptionSwitch');
res = res and testDescriptionSwitchScene('scDescriptionScene');
res = res and testDescriptionSwitchGroup('gpDescriptionGroup');
res = res and testSnapshot();
res = res and testManagedCounter('vdManagedCounter');
storeLastUpdates()
log('Finishing stage 1')
if (not res) then
log('Results stage 1: FAILED!!!!', dz.LOG_ERROR)
else
log('Results stage 1: SUCCEEDED')
dz.devices('stage2Trigger').switchOn().afterSec(20) -- 20 seconds because of repeatAfter tests
end
end
}
| gpl-3.0 |
sbouchex/domoticz | dzVents/runtime/dzVents.lua | 6 | 2455 | local TESTMODE = false
globalvariables['testmode'] = false
-- globalvariables['dzVents_log_level'] = 4 --debug
if (_G.TESTMODE) then
TESTMODE = false
globalvariables['testmode'] = false
end
local scriptPath = globalvariables['script_path'] -- should be ${szUserDataFolder}/scripts/dzVents/
local runtimePath = globalvariables['runtime_path'] -- should be ${szStartupFolder}/dzVents/runtime/
_G.scriptsFolderPath = scriptPath .. 'scripts' -- global
_G.generatedScriptsFolderPath = scriptPath .. 'generated_scripts' -- global
_G.dataFolderPath = scriptPath .. 'data' -- global
package.path =
scriptPath .. '?.lua;' ..
runtimePath .. '?.lua;' ..
runtimePath .. 'device-adapters/?.lua;' ..
scriptPath .. 'dzVents/?.lua;' ..
scriptPath .. 'scripts/?.lua;' ..
scriptPath .. '../lua/?.lua;' ..
scriptPath .. 'scripts/modules/?.lua;' ..
scriptPath .. '?.lua;' ..
scriptPath .. 'generated_scripts/?.lua;' ..
scriptPath .. 'data/?.lua;' ..
scriptPath .. 'modules/?.lua;' ..
package.path
local EventHelpers = require('EventHelpers')
local helpers = EventHelpers()
local utils = require('Utils')
if (tonumber(globalvariables['dzVents_log_level']) == utils.LOG_DEBUG or TESTMODE) then
print('Debug: Dumping domoticz data to ' .. scriptPath .. 'domoticzData.lua')
local persistence = require('persistence')
persistence.store(scriptPath .. 'domoticzData.lua', domoticzData)
--persistence.store(scriptPath .. 'globalvariables.lua', globalvariables)
--persistence.store(scriptPath .. 'timeofday.lua', timeofday)
local events, length = helpers.getEventSummary()
if (length > 0) then
print('Debug: dzVents version: '.. globalvariables.dzVents_version)
print('Debug: Event triggers:')
for i, event in pairs(events) do
print('Debug: ' .. event)
end
end
if (globalvariables['isTimeEvent']) then
print('Debug: Event triggers:')
print('Debug: - Timer')
end
end
commandArray = {}
local isTimeEvent = globalvariables['isTimeEvent']
if (isTimeEvent) then
commandArray = helpers.dispatchTimerEventsToScripts()
end
helpers.dispatchDeviceEventsToScripts()
helpers.dispatchVariableEventsToScripts()
helpers.dispatchSecurityEventsToScripts()
helpers.dispatchSceneGroupEventsToScripts()
helpers.dispatchHTTPResponseEventsToScripts()
helpers.dispatchShellCommandResponseEventsToScripts()
helpers.dispatchSystemEventsToScripts()
helpers.dispatchCustomEventsToScripts()
commandArray = helpers.domoticz.commandArray
return commandArray
| gpl-3.0 |
NYRDS/pixel-dungeon-remix | RemixedDungeon/src/main/assets/scripts/spells/HideInGrass.lua | 1 | 1147 | ---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by mike.
--- DateTime: 1/26/21 10:02 PM
---
local RPD = require "scripts/lib/commonClasses"
local spell = require "scripts/lib/spell"
return spell.init{
desc = function ()
return {
image = 2,
imageFile = "spellsIcons/naturegift.png",
name = "HideInGrassSpell_Name",
info = "HideInGrassSpell_Info",
magicAffinity = "Elf",
targetingType = "self",
level = 2,
spellCost = 5,
cooldown = 10,
castTime = 0.1
}
end,
cast = function(self, spell, caster)
local duration = caster:skillLevel() * 5
local terrain = caster:level().map[caster:getPos()+1]
if terrain == RPD.Terrain.GRASS or terrain == RPD.Terrain.HIGH_GRASS then
RPD.topEffect(caster:getPos(),"hide_in_grass")
RPD.affectBuff(caster,"Cloak", duration)
return true
end
RPD.glogn("HideInGrassSpell_NeedGrassToHide")
return false
end}
| gpl-3.0 |
arvindr21/esp8266-devkit | Espressif/examples/nodemcu-firmware/lua_modules/bmp085/bmp085.lua | 69 | 5037 | --------------------------------------------------------------------------------
-- BMP085 I2C module for NODEMCU
-- NODEMCU TEAM
-- LICENCE: http://opensource.org/licenses/MIT
-- Christee <Christee@nodemcu.com>
--------------------------------------------------------------------------------
local moduleName = ...
local M = {}
_G[moduleName] = M
--default value for i2c communication
local id=0
--default oversampling setting
local oss = 0
--CO: calibration coefficients table.
local CO = {}
-- read reg for 1 byte
local function read_reg(dev_addr, reg_addr)
i2c.start(id)
i2c.address(id, dev_addr ,i2c.TRANSMITTER)
i2c.write(id,reg_addr)
i2c.stop(id)
i2c.start(id)
i2c.address(id, dev_addr,i2c.RECEIVER)
local c=i2c.read(id,1)
i2c.stop(id)
return c
end
--write reg for 1 byte
local function write_reg(dev_addr, reg_addr, reg_val)
i2c.start(id)
i2c.address(id, dev_addr, i2c.TRANSMITTER)
i2c.write(id, reg_addr)
i2c.write(id, reg_val)
i2c.stop(id)
end
--get signed or unsigned 16
--parameters:
--reg_addr: start address of short
--signed: if true, return signed16
local function getShort(reg_addr, signed)
local tH = string.byte(read_reg(0x77, reg_addr))
local tL = string.byte(read_reg(0x77, (reg_addr + 1)))
local temp = tH*256 + tL
if (temp > 32767) and (signed == true) then
temp = temp - 65536
end
return temp
end
-- initialize i2c
--parameters:
--d: sda
--l: scl
function M.init(d, l)
if (d ~= nil) and (l ~= nil) and (d >= 0) and (d <= 11) and (l >= 0) and ( l <= 11) and (d ~= l) then
sda = d
scl = l
else
print("iic config failed!") return nil
end
print("init done")
i2c.setup(id, sda, scl, i2c.SLOW)
--get calibration coefficients.
CO.AC1 = getShort(0xAA, true)
CO.AC2 = getShort(0xAC, true)
CO.AC3 = getShort(0xAE, true)
CO.AC4 = getShort(0xB0)
CO.AC5 = getShort(0xB2)
CO.AC6 = getShort(0xB4)
CO.B1 = getShort(0xB6, true)
CO.B2 = getShort(0xB8, true)
CO.MB = getShort(0xBA, true)
CO.MC = getShort(0xBC, true)
CO.MD = getShort(0xBE, true)
end
--get temperature from bmp085
--parameters:
--num_10x: bool value, if true, return number of 0.1 centi-degree
-- default value is false, which return a string , eg: 16.7
function M.getUT(num_10x)
write_reg(0x77, 0xF4, 0x2E);
tmr.delay(10000);
local temp = getShort(0xF6)
local X1 = (temp - CO.AC6) * CO.AC5 / 32768
local X2 = CO.MC * 2048/(X1 + CO.MD)
local r = (X2 + X1 + 8)/16
if(num_10x == true) then
return r
else
return ((r/10).."."..(r%10))
end
end
--get raw data of pressure from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getUP_raw(oss)
local os = 0
if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then
os = oss
end
local ov = os * 64
write_reg(0x77, 0xF4, (0x34 + ov));
tmr.delay(30000);
--delay 30ms, according to bmp085 document, wait time are:
-- 4.5ms 7.5ms 13.5ms 25.5ms respectively according to oss 0,1,2,3
local MSB = string.byte(read_reg(0x77, 0xF6))
local LSB = string.byte(read_reg(0x77, 0xF7))
local XLSB = string.byte(read_reg(0x77, 0xF8))
local up_raw = (MSB*65536 + LSB *256 + XLSB)/2^(8 - os)
return up_raw
end
--get calibrated data of pressure from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getUP(oss)
local os = 0
if ((oss == 0) or (oss == 1) or (oss == 2) or (oss == 3)) and (oss ~= nil) then
os = oss
end
local raw = M.getUP_raw(os)
local B5 = M.getUT(true) * 16 - 8;
local B6 = B5 - 4000
local X1 = CO.B2 * (B6 * B6 /4096)/2048
local X2 = CO.AC2 * B6 / 2048
local X3 = X1 + X2
local B3 = ((CO.AC1*4 + X3)*2^os + 2)/4
X1 = CO.AC3 * B6 /8192
X2 = (CO.B1 * (B6 * B6 / 4096))/65536
X3 = (X1 + X2 + 2)/4
local B4 = CO.AC4 * (X3 + 32768) / 32768
local B7 = (raw -B3) * (50000/2^os)
local p = B7/B4 * 2
X1 = (p/256)^2
X1 = (X1 *3038)/65536
X2 = (-7357 *p)/65536
p = p +(X1 + X2 + 3791)/16
return p
end
--get estimated data of altitude from bmp085
--parameters:
--oss: over sampling setting, which is 0,1,2,3. Default value is 0
function M.getAL(oss)
--Altitudi can be calculated by pressure refer to sea level pressure, which is 101325
--pressure changes 100pa corresponds to 8.43m at sea level
return (M.getUP(oss) - 101325)*843/10000
end
return M | gpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/endor/beguiling_donkuwah_scout.lua | 2 | 1037 | beguiling_donkuwah_scout = Creature:new {
objectName = "@mob/creature_names:beguiling_donkuwah_scout",
randomNameType = NAME_GENERIC_TAG,
socialGroup = "donkuwah_tribe",
faction = "donkuwah_tribe",
level = 18,
chanceHit = 0.32,
damageMin = 180,
damageMax = 190,
baseXp = 1426,
baseHAM = 4100,
baseHAMmax = 5000,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + KILLER + STALKER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {
"object/mobile/dulok_male.iff",
"object/mobile/dulok_female.iff"},
lootGroups = {
{
groups = {
{group = "donkuwah_common", chance = 10000000}
},
lootChance = 1360000
}
},
weapons = {"donkuwah_weapons"},
conversationTemplate = "",
attacks = brawlermaster
}
CreatureTemplates:addCreatureTemplate(beguiling_donkuwah_scout, "beguiling_donkuwah_scout")
| agpl-3.0 |
braydondavis/Nerd-Gaming-Public | resources/[no_ng_tag]/realdriveby/exports_client.lua | 2 | 2410 | local validDrivebyWeapons = { [22]=true,[23]=true,[24]=true,[25]=true,
[26]=true,[27]=true,[28]=true,[29]=true,[32]=true,[30]=true,[31]=true,
[32]=true,[33]=true,[38]=true }
function setDriverDrivebyAbility ( ... )
local newTable = {...}
for key,weaponID in ipairs(newTable) do
if not validDrivebyWeapons[weaponID] then
table.remove ( newTable, key )
end
end
settings.driver = newTable
lastSlot = 0
return true
end
function setPassengerDrivebyAbility ( ... )
local newTable = {...}
for key,weaponID in ipairs(newTable) do
if not validDrivebyWeapons[weaponID] then
table.remove ( newTable, key )
end
end
settings.passenger = newTable
lastSlot = 0
return true
end
function getDriverDrivebyAbility()
return settings.driver
end
function getPassengerDrivebyAbility()
return settings.passenger
end
function setWeaponShotDelay ( weaponID, delay )
if not validDrivebyWeapons[weaponID] then
outputDebugString ("setWeaponShotDelay: 'weaponID' specified is not a valid driveby weapon",0,255,255,0)
return false
end
local delay = tonumber(delay)
if not delay then
outputDebugString ("setWeaponShotDelay: Bad 'delay' specified.",0,255,255,0)
return false
end
settings.shotdelay[tostring(weaponID)] = delay
return true
end
function getWeaponShotDelay(weaponID)
if not validDrivebyWeapons[weaponID] then
outputDebugString ("getWeaponShotDelay: 'weaponID' specified is not a valid driveby weapon",0,255,255,0)
return false
end
return settings.shotdelay[tostring(weaponID)] or 0
end
function setDrivebySteeringAbility ( vehicles, bikes )
if ( vehicles ) == nil then
outputDebugString ("setDrivebySteeringAbility: No valid arguments were passed.",0,255,255,0)
return false
end
settings.steerCars = vehicles
settings.steerBikes = bikes or true
end
function getDrivebySteeringAbility ( dbType )
if dbType == "car" then
return settings.steerCars
elseif dbType == "bike" then
return settings.steerBikes
else
outputDebugString ("getDrivebySteeringAbility: Bad driveby type specified. Should be 'car' or 'bike'.",0,255,255,0)
return false
end
end
function setDrivebyAutoEquip ( enabled )
if type(enabled) ~= "boolean" then
outputDebugString ("setDrivebyAutoEquip: Bad argument, should be a boolean.",0,255,255,0)
return false
end
settings.autoEquip = enabled
return true
end
function getDrivebyAutoEquip ()
return settings.autoEquip
end
| mit |
excessive/obtuse-tanuki | libs/quickie/group.lua | 15 | 4523 | --[[
Copyright (c) 2012 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local stack = {n = 0}
local default = {
pos = {0,0},
grow = {0,0},
spacing = 2,
size = {100, 30},
upper_left = {0,0},
lower_right = {0,0},
}
local current = default
local Grow = {
none = { 0, 0},
up = { 0, -1},
down = { 0, 1},
left = {-1, 0},
right = { 1, 0}
}
-- {grow = grow, spacing = spacing, size = size, pos = pos}
local function push(info)
local grow = info.grow or "none"
local spacing = info.spacing or default.spacing
local size = {
info.size and info.size[1] or current.size[1],
info.size and info.size[2] or current.size[2]
}
local pos = {current.pos[1], current.pos[2]}
if info.pos then
pos[1] = pos[1] + (info.pos[1] or 0)
pos[2] = pos[2] + (info.pos[2] or 0)
end
assert(size, "Size neither specified nor derivable from parent group.")
assert(pos, "Position neither specified nor derivable from parent group.")
grow = assert(Grow[grow], "Invalid grow: " .. tostring(grow))
current = {
pos = pos,
grow = grow,
size = size,
spacing = spacing,
upper_left = { math.huge, math.huge},
lower_right = {-math.huge, -math.huge},
}
stack.n = stack.n + 1
stack[stack.n] = current
end
local function advance(pos, size)
current.upper_left[1] = math.min(current.upper_left[1], pos[1])
current.upper_left[2] = math.min(current.upper_left[2], pos[2])
current.lower_right[1] = math.max(current.lower_right[1], pos[1] + size[1])
current.lower_right[2] = math.max(current.lower_right[2], pos[2] + size[2])
if current.grow[1] ~= 0 then
current.pos[1] = pos[1] + current.grow[1] * (size[1] + current.spacing)
end
if current.grow[2] ~= 0 then
current.pos[2] = pos[2] + current.grow[2] * (size[2] + current.spacing)
end
return pos, size
end
local function getRect(pos, size)
pos = {pos and pos[1] or 0, pos and pos[2] or 0}
size = {size and size[1] or current.size[1], size and size[2] or current.size[2]}
-- growing left/up: update current position to account for differnt size
if current.grow[1] < 0 and current.size[1] ~= size[1] then
current.pos[1] = current.pos[1] + (current.size[1] - size[1])
end
if current.grow[2] < 0 and current.size[2] ~= size[2] then
current.pos[2] = current.pos[2] - (current.size[2] - size[2])
end
pos[1] = pos[1] + current.pos[1]
pos[2] = pos[2] + current.pos[2]
return advance(pos, size)
end
local function pop()
assert(stack.n > 0, "Group stack is empty.")
stack.n = stack.n - 1
local child = current
current = stack[stack.n] or default
local size = {
child.lower_right[1] - math.max(child.upper_left[1], current.pos[1]),
child.lower_right[2] - math.max(child.upper_left[2], current.pos[2])
}
advance(current.pos, size)
end
local function beginFrame()
current = default
stack.n = 0
end
local function endFrame()
-- future use?
end
return setmetatable({
push = push,
pop = pop,
getRect = getRect,
advance = advance,
beginFrame = beginFrame,
endFrame = endFrame,
default = default,
}, {
__index = function(_,k)
return ({size = current.size, pos = current.pos})[k]
end,
__call = function(_, info)
assert(type(info) == 'table' and type(info[1]) == 'function')
push(info)
info[1]()
pop()
end,
})
| mit |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/dungeon/corellian_corvette/rebel/novatrooper_commander.lua | 2 | 1525 | novatrooper_commander = Creature:new {
objectName = "@mob/creature_names:stormtrooper_novatrooper_commander",
randomNameType = NAME_STORMTROOPER_TAG,
socialGroup = "imperial",
faction = "imperial",
level = 182,
chanceHit = 13,
damageMin = 1045,
damageMax = 1800,
baseXp = 17274,
baseHAM = 126000,
baseHAMmax = 154000,
armor = 0,
resists = {65,65,80,30,0,0,30,45,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_stormtrooper_commander_black_gold.iff"},
lootGroups = {
{
groups = {
{group = "color_crystals", chance = 100000},
{group = "junk", chance = 6200000},
{group = "rifles", chance = 550000},
{group = "pistols", chance = 550000},
{group = "melee_weapons", chance = 550000},
{group = "carbines", chance = 550000},
{group = "clothing_attachments", chance = 25000},
{group = "armor_attachments", chance = 25000},
{group = "imperial_officer_common", chance = 450000},
{group = "wearables_rare", chance = 1000000}
}
}
},
weapons = {"stormtrooper_weapons"},
conversationTemplate = "",
reactionStf = "@npc_reaction/stormtrooper",
attacks = merge(riflemanmaster,carbineermaster,marksmanmaster,brawlermaster)
}
CreatureTemplates:addCreatureTemplate(novatrooper_commander, "novatrooper_commander")
| agpl-3.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/dathomir/grovo.lua | 2 | 1116 | grovo = Creature:new {
objectName = "@monster_name:grovo",
socialGroup = "nightsister",
faction = "nightsister",
level = 75,
chanceHit = 0.7,
damageMin = 520,
damageMax = 750,
baseXp = 7207,
baseHAM = 12000,
baseHAMmax = 15000,
armor = 1,
resists = {25,160,25,200,200,200,25,25,-1},
meatType = "meat_carnivore",
meatAmount = 1000,
hideType = "hide_leathery",
hideAmount = 1000,
boneType = "bone_mammal",
boneAmount = 950,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE + ENEMY,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = CARNIVORE,
templates = {"object/mobile/nsister_rancor_grovo.iff"},
scale = 1.25,
lootGroups = {
{
groups = {
{group = "rancor_common", chance = 4000000},
{group = "armor_all", chance = 2000000},
{group = "weapons_all", chance = 2500000},
{group = "wearables_all", chance = 1500000}
},
lootChance = 2500000
}
},
weapons = {},
conversationTemplate = "",
attacks = {
{"creatureareableeding",""},
{"creatureareacombo",""}
}
}
CreatureTemplates:addCreatureTemplate(grovo, "grovo")
| agpl-3.0 |
TheLazar42/Reign-of-Darkness | builtin/misc.lua | 1 | 3146 | -- Minetest: builtin/misc.lua
--
-- Misc. API functions
--
minetest.timers_to_add = {}
minetest.timers = {}
minetest.register_globalstep(function(dtime)
for _, timer in ipairs(minetest.timers_to_add) do
table.insert(minetest.timers, timer)
end
minetest.timers_to_add = {}
for index, timer in ipairs(minetest.timers) do
timer.time = timer.time - dtime
if timer.time <= 0 then
timer.func(unpack(timer.args or {}))
table.remove(minetest.timers,index)
end
end
end)
function minetest.after(time, func, ...)
table.insert(minetest.timers_to_add, {time=time, func=func, args={...}})
end
function minetest.check_player_privs(name, privs)
local player_privs = minetest.get_player_privs(name)
local missing_privileges = {}
for priv, val in pairs(privs) do
if val then
if not player_privs[priv] then
table.insert(missing_privileges, priv)
end
end
end
if #missing_privileges > 0 then
return false, missing_privileges
end
return true, ""
end
local player_list = {}
minetest.register_on_joinplayer(function(player)
player_list[player:get_player_name()] = player
end)
minetest.register_on_leaveplayer(function(player)
player_list[player:get_player_name()] = nil
end)
function minetest.get_connected_players()
local temp_table = {}
for index, value in pairs(player_list) do
if value:is_player_connected() then
table.insert(temp_table, value)
end
end
return temp_table
end
function minetest.hash_node_position(pos)
return (pos.z+32768)*65536*65536 + (pos.y+32768)*65536 + pos.x+32768
end
function minetest.get_position_from_hash(hash)
local pos = {}
pos.x = (hash%65536) - 32768
hash = math.floor(hash/65536)
pos.y = (hash%65536) - 32768
hash = math.floor(hash/65536)
pos.z = (hash%65536) - 32768
return pos
end
function minetest.get_item_group(name, group)
if not minetest.registered_items[name] or not
minetest.registered_items[name].groups[group] then
return 0
end
return minetest.registered_items[name].groups[group]
end
function minetest.get_node_group(name, group)
return minetest.get_item_group(name, group)
end
function minetest.string_to_pos(value)
local p = {}
p.x, p.y, p.z = string.match(value, "^([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+)$")
if p.x and p.y and p.z then
p.x = tonumber(p.x)
p.y = tonumber(p.y)
p.z = tonumber(p.z)
return p
end
local p = {}
p.x, p.y, p.z = string.match(value, "^%( *([%d.-]+)[, ] *([%d.-]+)[, ] *([%d.-]+) *%)$")
if p.x and p.y and p.z then
p.x = tonumber(p.x)
p.y = tonumber(p.y)
p.z = tonumber(p.z)
return p
end
return nil
end
assert(minetest.string_to_pos("10.0, 5, -2").x == 10)
assert(minetest.string_to_pos("( 10.0, 5, -2)").z == -2)
assert(minetest.string_to_pos("asd, 5, -2)") == nil)
function minetest.setting_get_pos(name)
local value = minetest.setting_get(name)
if not value then
return nil
end
return minetest.string_to_pos(value)
end
-- To be overriden by protection mods
function minetest.is_protected(pos, name)
return false
end
function minetest.record_protection_violation(pos, name)
for _, func in pairs(minetest.registered_on_protection_violation) do
func(pos, name)
end
end
| lgpl-2.1 |
alinofel/zooz11 | plugins/hello.lua | 2 | 2461 | -- Made By @MAXDEVD
-- Made By @Omar_Real
do
local function run(msg,matches)
if matches[1] == "chat_add_user" then
local text = 'نورت😍💋مح'..'\n'..'\n'
..'المعلومات 📋 الخاصة بك 🔷'..'\n'
..'📌 اسمك : '..msg.action.user.print_name..'\n'
..'📌 معرفك : @'..(msg.action.user.username or "لا يوجد")..'\n'
..'💭 الايدي : '..msg.action.user.id..'\n'
..'📱رقم الهاتف : '..(msg.action.user.phone or "لا يوجد")..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'📌 اسم المجموعة : '..msg.to.title..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'✝ ضافك : '..msg.from.print_name..'\n'
..'✝ معرفة : @'..(msg.from.username or "لا يوجد")..'\n'
..' ايدية 🆔 : '..msg.from.id..'\n'
..'📱 رقم هاتفةة : '..(msg.from.phone or "لا يوجد")..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'📅 التاريخ : '..os.date('!%A, %B %d, %Y*\n', timestamp)
..'🕚 الوقت : '..os.date(' %T*', os.time())..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'🕵 مطور البوت : @ali_nofel'..'\n'
return reply_msg(msg.id, text, ok_cb, false)
end
if matches[1] == "chat_add_user_link" then
local text = 'نورت😍💋مح'..'\n'..'\n' ..'المعلومات 📋 الخاصة بك 🔷'..'\n'
..'📌 اسمك : '..msg.action.user.print_name..'\n'
..'📌 معرفك : @'..(msg.action.user.username or "لا يوجد")..'\n'
..'💭 الايدي : '..msg.action.user.id..'\n'
..'📱رقم الهاتف : '..(msg.action.user.phone or "لا يوجد")..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'📌 اسم المجموعة : '..msg.to.title..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'✝ ضافك : '..msg.from.print_name..'\n'
..'✝ معرفة : @'..(msg.from.username or "لا يوجد")..'\n'
..' ايديه 🆔 : '..msg.from.id..'\n'
..'📱 رقم : '..(msg.from.phone or "لا يوجد")..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'📅 التاريخ : '..os.date('!%A, %B %d, %Y*\n', timestamp)
..'🕚 الوقت : '..os.date(' %T*', os.time())..'\n'
..'➖➖➖➖➖ـ'..'\n'
..'🕵 مطور البوت : @ali_nofel'..'\n'
return reply_msg(msg.id, text, ok_cb, false)
end
end
return {
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
},
run = run
}
end
| gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/mobile/conversations.lua | 1 | 7274 | includeFile("conversation.lua")
-- ** THEMEPARKS **
-- Tutorial
includeFile("conversations/themepark/tutorial/imperial_officer_1_conv.lua")
includeFile("conversations/themepark/tutorial/imperial_officer_2_conv.lua")
includeFile("conversations/themepark/tutorial/imperial_officer_3_conv.lua")
includeFile("conversations/themepark/tutorial/imperial_officer_4_conv.lua")
includeFile("conversations/themepark/tutorial/imperial_officer_5_conv.lua")
includeFile("conversations/themepark/tutorial/imperial_officer_6_conv.lua")
includeFile("conversations/themepark/tutorial/commoner_conv.lua")
includeFile("conversations/themepark/tutorial/stormtrooper_filler_conv.lua")
includeFile("conversations/themepark/tutorial/panic_npc_1_conv.lua")
includeFile("conversations/themepark/tutorial/protocol_droid_3po_silver_conv.lua")
-- Nym Themepark
includeFile("conversations/themepark/nym/berema_conv.lua")
includeFile("conversations/themepark/nym/choster_conv.lua")
includeFile("conversations/themepark/nym/jinkins_conv.lua")
includeFile("conversations/themepark/nym/lok_hacker_conv.lua")
includeFile("conversations/themepark/nym/nym_conv.lua")
includeFile("conversations/themepark/nym/sergeant_moore_conv.lua")
includeFile("conversations/themepark/nym/kole_conv.lua")
-- Bestine Museum
includeFile("conversations/events/bestine_museum/bestine_artist01_conv.lua")
includeFile("conversations/events/bestine_museum/bestine_artist02_conv.lua")
includeFile("conversations/events/bestine_museum/bestine_artist03_conv.lua")
includeFile("conversations/events/bestine_museum/bestine_artist04_conv.lua")
includeFile("conversations/events/bestine_museum/bestine_artist05_conv.lua")
includeFile("conversations/events/bestine_museum/bestine_artist06_conv.lua")
includeFile("conversations/events/bestine_museum/museum_curator_conv.lua")
--Life Day
includeFile("conversations/events/life_day/life_day_anarra_conv.lua")
includeFile("conversations/events/life_day/life_day_kkatamk_conv.lua")
includeFile("conversations/events/life_day/life_day_oraalarri_conv.lua")
includeFile("conversations/events/life_day/life_day_radrrl_conv.lua")
includeFile("conversations/events/life_day/life_day_tebeurra_conv.lua")
-- Hero of Tat
includeFile("conversations/tasks/hero_of_tatooine/hermit_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_bounty_hunter_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_farmer_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_intellect_liar_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_intercom_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_mother_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_pirate_leader_conv.lua")
includeFile("conversations/tasks/hero_of_tatooine/hero_of_tat_ranchers_wife_conv.lua")
-- Events
includeFile("conversations/events/event_promoter_conv.lua")
-- Epic Quests
includeFile("conversations/themepark/epic_quests/goru_conv.lua")
-- Themepark Logic Convos
includeFile("conversations/themepark/logic/mission_giver_conv.lua")
includeFile("conversations/themepark/logic/mission_target_conv.lua")
-- ** DUNGEONS **
-- Corellian Corvette
includeFile("conversations/dungeon/corellian_corvette/bronell_conv.lua")
includeFile("conversations/dungeon/corellian_corvette/ds_297_conv.lua")
includeFile("conversations/dungeon/corellian_corvette/klaatu_conv.lua")
includeFile("conversations/dungeon/corellian_corvette/lt_lance_conv.lua")
-- Death Watch Bunker
includeFile("conversations/dungeon/death_watch_bunker/boba_fett_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/commander_dkrn_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/death_watch_rescue_scientist_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/foreman_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/haldo_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/lutin_nightstalker_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/mand_bunker_technician_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/medical_droid_conv.lua")
includeFile("conversations/dungeon/death_watch_bunker/workshop_droid_conv.lua")
-- Warren
includeFile("conversations/dungeon/warren/oevitt_piboi_conv.lua")
includeFile("conversations/dungeon/warren/mirla_conv.lua")
includeFile("conversations/dungeon/warren/dirk_maggin_conv.lua")
includeFile("conversations/dungeon/warren/captain_heff_conv.lua")
includeFile("conversations/dungeon/warren/manx_try_conv.lua")
-- Geonosian Lab
includeFile("conversations/dungeon/geonosian_lab/biogenic_assistant_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_construction_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_crazyguy_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_engineer_tech_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_scientist_generic_01_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_scientist_generic_02_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_scientist_generic_03_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_scientist_geonosian_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_scientist_human_convo.lua")
includeFile("conversations/dungeon/geonosian_lab/biogenic_security_tech_convo.lua")
-- ** OTHER **
includeFile("conversations/trainer/trainers_conv.lua")
includeFile("conversations/trainer/trainer_fs_conv.lua")
-- Missions
includeFile("conversations/mission/deliver_npc.lua")
includeFile("conversations/mission/informant_npc.lua")
-- Recruiters
includeFile("conversations/recruiter/rebel_recruiter_conv.lua")
includeFile("conversations/recruiter/imperial_recruiter_conv.lua")
-- Tasks
includeFile("conversations/tasks/herald_conv.lua")
includeFile("conversations/tasks/ris_armor_quest_conv.lua")
includeFile("conversations/tasks/librarian_conv.lua")
includeFile("conversations/tasks/theater_manager_conv.lua")
-- Village
includeFile("conversations/village/old_man_conv.lua")
includeFile("conversations/village/paemos_conv.lua")
includeFile("conversations/village/elder_conv.lua")
-- Race Tracks
includeFile("conversations/racetracks/agrilatswampconversation.lua")
includeFile("conversations/racetracks/kerenconversation.lua")
includeFile("conversations/racetracks/mosespaconversation.lua")
includeFile("conversations/racetracks/narmleconversation.lua")
includeFile("conversations/racetracks/lokconversation.lua")
includeFile("conversations/racetracks/nashalconversation.lua")
-- Space
includeFile("conversations/space/chassis_dealer_conv.lua")
-- Record Keepers
includeFile("conversations/record_keepers/planet_record_keeper_dantoonie_conv.lua")
includeFile("conversations/record_keepers/planet_record_keeper_tatoonie_conv.lua")
includeFile("conversations/record_keepers/record_keeper_imperial_conv.lua")
includeFile("conversations/record_keepers/record_keeper_jabba_conv.lua")
includeFile("conversations/record_keepers/record_keeper_rebel_conv.lua")
-- Personality Conversations
includeFile("conversations/pet/pets_conv.lua")
--kaas
--includeFile("conversations/kaas/kaas_imp_intro.lua")
| agpl-3.0 |
fegimanam/tele | plugins/inpm.lua | 1114 | 3008 | do
local function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function chat_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of Groups:\n*Use /join (ID) to join*\n\n '
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairsByKeys(settings) do
if m == 'set_name' then
name = n
end
end
message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n '
end
local file = io.open("./groups/lists/listed_groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function run(msg, matches)
if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then
local data = load_data(_config.moderation.data)
if matches[1] == 'join' and data[tostring(matches[2])] then
if is_banned(msg.from.id, matches[2]) then
return 'You are banned.'
end
if is_gbanned(msg.from.id) then
return 'You are globally banned.'
end
if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then
return 'Group is private.'
end
local chat_id = "chat#id"..matches[2]
local user_id = "user#id"..msg.from.id
chat_add_user(chat_id, user_id, ok_cb, false)
local group_name = data[tostring(matches[2])]['settings']['set_name']
return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")"
elseif matches[1] == 'join' and not data[tostring(matches[2])] then
return "Chat not found."
end
if matches[1] == 'chats'then
if is_admin(msg) and msg.to.type == 'chat' then
return chat_list(msg)
elseif msg.to.type ~= 'chat' then
return chat_list(msg)
end
end
if matches[1] == 'chatlist'then
if is_admin(msg) and msg.to.type == 'chat' then
send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
elseif msg.to.type ~= 'chat' then
send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false)
end
end
end
end
return {
patterns = {
"^[/!](chats)$",
"^[/!](chatlist)$",
"^[/!](join) (.*)$",
"^[/!](kickme) (.*)$",
"^!!tgservice (chat_add_user)$"
},
run = run,
}
end
| gpl-2.0 |
Chilastra-Reborn/Chilastra-source-code | bin/scripts/commands/planetwarp.lua | 4 | 2123 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 2 of the License,
--or (at your option) any later version.
--This program is distributed in the hope that it will be useful,
--but WITHOUT ANY WARRANTY; without even the implied warranty of
--MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--See the GNU Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser 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
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
PlanetwarpCommand = {
name = "planetwarp",
}
AddCommand(PlanetwarpCommand)
| agpl-3.0 |
Blizzard/premake-core | modules/self-test/test_helpers.lua | 15 | 1665 | ---
-- test_helpers.lua
--
-- Helper functions for setting up workspaces and projects, etc.
--
-- Author Jason Perkins
-- Copyright (c) 2008-2016 Jason Perkins and the Premake project.
---
local p = premake
local m = p.modules.self_test
function m.createWorkspace()
local wks = workspace("MyWorkspace")
configurations { "Debug", "Release" }
local prj = m.createProject(wks)
return wks, prj
end
-- Eventually we'll want to deprecate this one and move everyone
-- over to createWorkspace() instead (4 Sep 2015).
function m.createsolution()
local wks = workspace("MySolution")
configurations { "Debug", "Release" }
local prj = m.createproject(wks)
return wks, prj
end
function m.createProject(wks)
local n = #wks.projects + 1
if n == 1 then n = "" end
local prj = project ("MyProject" .. n)
language "C++"
kind "ConsoleApp"
return prj
end
function m.createGroup(wks)
local prj = group ("MyGroup" .. (#wks.groups + 1))
return prj
end
function m.getWorkspace(wks)
p.oven.bake()
return p.global.getWorkspace(wks.name)
end
function m.getRule(name)
p.oven.bake()
return p.global.getRule(name)
end
function m.getProject(wks, i)
wks = m.getWorkspace(wks)
return p.workspace.getproject(wks, i or 1)
end
function m.getConfig(prj, buildcfg, platform)
local wks = m.getWorkspace(prj.workspace)
prj = p.workspace.getproject(wks, prj.name)
return p.project.getconfig(prj, buildcfg, platform)
end
m.print = print
p.alias(m, "createProject", "createproject")
p.alias(m, "getConfig", "getconfig")
p.alias(m, "getProject", "getproject")
p.alias(m, "getWorkspace", "getsolution")
| bsd-3-clause |
kidaa/Algorithm-Implementations | Hamming_Weight/Lua/Yonaba/numberlua.lua | 115 | 13399 | --[[
LUA MODULE
bit.numberlua - Bitwise operations implemented in pure Lua as numbers,
with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces.
SYNOPSIS
local bit = require 'bit.numberlua'
print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff
-- Interface providing strong Lua 5.2 'bit32' compatibility
local bit32 = require 'bit.numberlua'.bit32
assert(bit32.band(-1) == 0xffffffff)
-- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility
local bit = require 'bit.numberlua'.bit
assert(bit.tobit(0xffffffff) == -1)
DESCRIPTION
This library implements bitwise operations entirely in Lua.
This module is typically intended if for some reasons you don't want
to or cannot install a popular C based bit library like BitOp 'bit' [1]
(which comes pre-installed with LuaJIT) or 'bit32' (which comes
pre-installed with Lua 5.2) but want a similar interface.
This modules represents bit arrays as non-negative Lua numbers. [1]
It can represent 32-bit bit arrays when Lua is compiled
with lua_Number as double-precision IEEE 754 floating point.
The module is nearly the most efficient it can be but may be a few times
slower than the C based bit libraries and is orders or magnitude
slower than LuaJIT bit operations, which compile to native code. Therefore,
this library is inferior in performane to the other modules.
The `xor` function in this module is based partly on Roberto Ierusalimschy's
post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html .
The included BIT.bit32 and BIT.bit sublibraries aims to provide 100%
compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library.
This compatbility is at the cost of some efficiency since inputted
numbers are normalized and more general forms (e.g. multi-argument
bitwise operators) are supported.
STATUS
WARNING: Not all corner cases have been tested and documented.
Some attempt was made to make these similar to the Lua 5.2 [2]
and LuaJit BitOp [3] libraries, but this is not fully tested and there
are currently some differences. Addressing these differences may
be improved in the future but it is not yet fully determined how to
resolve these differences.
The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua)
http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp
test suite (bittest.lua). However, these have not been tested on
platforms with Lua compiled with 32-bit integer numbers.
API
BIT.tobit(x) --> z
Similar to function in BitOp.
BIT.tohex(x, n)
Similar to function in BitOp.
BIT.band(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bxor(x, y) --> z
Similar to function in Lua 5.2 and BitOp but requires two arguments.
BIT.bnot(x) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.rshift(x, disp) --> z
Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift),
BIT.extract(x, field [, width]) --> z
Similar to function in Lua 5.2.
BIT.replace(x, v, field, width) --> z
Similar to function in Lua 5.2.
BIT.bswap(x) --> z
Similar to function in Lua 5.2.
BIT.rrotate(x, disp) --> z
BIT.ror(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.lrotate(x, disp) --> z
BIT.rol(x, disp) --> z
Similar to function in Lua 5.2 and BitOp.
BIT.arshift
Similar to function in Lua 5.2 and BitOp.
BIT.btest
Similar to function in Lua 5.2 with requires two arguments.
BIT.bit32
This table contains functions that aim to provide 100% compatibility
with the Lua 5.2 "bit32" library.
bit32.arshift (x, disp) --> z
bit32.band (...) --> z
bit32.bnot (x) --> z
bit32.bor (...) --> z
bit32.btest (...) --> true | false
bit32.bxor (...) --> z
bit32.extract (x, field [, width]) --> z
bit32.replace (x, v, field [, width]) --> z
bit32.lrotate (x, disp) --> z
bit32.lshift (x, disp) --> z
bit32.rrotate (x, disp) --> z
bit32.rshift (x, disp) --> z
BIT.bit
This table contains functions that aim to provide 100% compatibility
with the LuaBitOp "bit" library (from LuaJIT).
bit.tobit(x) --> y
bit.tohex(x [,n]) --> y
bit.bnot(x) --> y
bit.bor(x1 [,x2...]) --> y
bit.band(x1 [,x2...]) --> y
bit.bxor(x1 [,x2...]) --> y
bit.lshift(x, n) --> y
bit.rshift(x, n) --> y
bit.arshift(x, n) --> y
bit.rol(x, n) --> y
bit.ror(x, n) --> y
bit.bswap(x) --> y
DEPENDENCIES
None (other than Lua 5.1 or 5.2).
DOWNLOAD/INSTALLATION
If using LuaRocks:
luarocks install lua-bit-numberlua
Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>.
Alternately, if using git:
git clone git://github.com/davidm/lua-bit-numberlua.git
cd lua-bit-numberlua
Optionally unpack:
./util.mk
or unpack and install in LuaRocks:
./util.mk install
REFERENCES
[1] http://lua-users.org/wiki/FloatingPoint
[2] http://www.lua.org/manual/5.2/
[3] http://bitop.luajit.org/
LICENSE
(c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT).
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
(end license)
--]]
local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'}
local floor = math.floor
local MOD = 2^32
local MODM = MOD-1
local function memoize(f)
local mt = {}
local t = setmetatable({}, mt)
function mt:__index(k)
local v = f(k); t[k] = v
return v
end
return t
end
local function make_bitop_uncached(t, m)
local function bitop(a, b)
local res,p = 0,1
while a ~= 0 and b ~= 0 do
local am, bm = a%m, b%m
res = res + t[am][bm]*p
a = (a - am) / m
b = (b - bm) / m
p = p*m
end
res = res + (a+b)*p
return res
end
return bitop
end
local function make_bitop(t)
local op1 = make_bitop_uncached(t,2^1)
local op2 = memoize(function(a)
return memoize(function(b)
return op1(a, b)
end)
end)
return make_bitop_uncached(op2, 2^(t.n or 1))
end
-- ok? probably not if running on a 32-bit int Lua number type platform
function M.tobit(x)
return x % 2^32
end
M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4}
local bxor = M.bxor
function M.bnot(a) return MODM - a end
local bnot = M.bnot
function M.band(a,b) return ((a+b) - bxor(a,b))/2 end
local band = M.band
function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end
local bor = M.bor
local lshift, rshift -- forward declare
function M.rshift(a,disp) -- Lua5.2 insipred
if disp < 0 then return lshift(a,-disp) end
return floor(a % 2^32 / 2^disp)
end
rshift = M.rshift
function M.lshift(a,disp) -- Lua5.2 inspired
if disp < 0 then return rshift(a,-disp) end
return (a * 2^disp) % 2^32
end
lshift = M.lshift
function M.tohex(x, n) -- BitOp style
n = n or 8
local up
if n <= 0 then
if n == 0 then return '' end
up = true
n = - n
end
x = band(x, 16^n-1)
return ('%0'..n..(up and 'X' or 'x')):format(x)
end
local tohex = M.tohex
function M.extract(n, field, width) -- Lua5.2 inspired
width = width or 1
return band(rshift(n, field), 2^width-1)
end
local extract = M.extract
function M.replace(n, v, field, width) -- Lua5.2 inspired
width = width or 1
local mask1 = 2^width-1
v = band(v, mask1) -- required by spec?
local mask = bnot(lshift(mask1, field))
return band(n, mask) + lshift(v, field)
end
local replace = M.replace
function M.bswap(x) -- BitOp style
local a = band(x, 0xff); x = rshift(x, 8)
local b = band(x, 0xff); x = rshift(x, 8)
local c = band(x, 0xff); x = rshift(x, 8)
local d = band(x, 0xff)
return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d
end
local bswap = M.bswap
function M.rrotate(x, disp) -- Lua5.2 inspired
disp = disp % 32
local low = band(x, 2^disp-1)
return rshift(x, disp) + lshift(low, 32-disp)
end
local rrotate = M.rrotate
function M.lrotate(x, disp) -- Lua5.2 inspired
return rrotate(x, -disp)
end
local lrotate = M.lrotate
M.rol = M.lrotate -- LuaOp inspired
M.ror = M.rrotate -- LuaOp insipred
function M.arshift(x, disp) -- Lua5.2 inspired
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
local arshift = M.arshift
function M.btest(x, y) -- Lua5.2 inspired
return band(x, y) ~= 0
end
--
-- Start Lua 5.2 "bit32" compat section.
--
M.bit32 = {} -- Lua 5.2 'bit32' compatibility
local function bit32_bnot(x)
return (-1 - x) % MOD
end
M.bit32.bnot = bit32_bnot
local function bit32_bxor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = bxor(a, b)
if c then
z = bit32_bxor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bxor = bit32_bxor
local function bit32_band(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = ((a+b) - bxor(a,b)) / 2
if c then
z = bit32_band(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return MODM
end
end
M.bit32.band = bit32_band
local function bit32_bor(a, b, c, ...)
local z
if b then
a = a % MOD
b = b % MOD
z = MODM - band(MODM - a, MODM - b)
if c then
z = bit32_bor(z, c, ...)
end
return z
elseif a then
return a % MOD
else
return 0
end
end
M.bit32.bor = bit32_bor
function M.bit32.btest(...)
return bit32_band(...) ~= 0
end
function M.bit32.lrotate(x, disp)
return lrotate(x % MOD, disp)
end
function M.bit32.rrotate(x, disp)
return rrotate(x % MOD, disp)
end
function M.bit32.lshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return lshift(x % MOD, disp)
end
function M.bit32.rshift(x,disp)
if disp > 31 or disp < -31 then return 0 end
return rshift(x % MOD, disp)
end
function M.bit32.arshift(x,disp)
x = x % MOD
if disp >= 0 then
if disp > 31 then
return (x >= 0x80000000) and MODM or 0
else
local z = rshift(x, disp)
if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end
return z
end
else
return lshift(x, -disp)
end
end
function M.bit32.extract(x, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
return extract(x, field, ...)
end
function M.bit32.replace(x, v, field, ...)
local width = ... or 1
if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end
x = x % MOD
v = v % MOD
return replace(x, v, field, ...)
end
--
-- Start LuaBitOp "bit" compat section.
--
M.bit = {} -- LuaBitOp "bit" compatibility
function M.bit.tobit(x)
x = x % MOD
if x >= 0x80000000 then x = x - MOD end
return x
end
local bit_tobit = M.bit.tobit
function M.bit.tohex(x, ...)
return tohex(x % MOD, ...)
end
function M.bit.bnot(x)
return bit_tobit(bnot(x % MOD))
end
local function bit_bor(a, b, c, ...)
if c then
return bit_bor(bit_bor(a, b), c, ...)
elseif b then
return bit_tobit(bor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bor = bit_bor
local function bit_band(a, b, c, ...)
if c then
return bit_band(bit_band(a, b), c, ...)
elseif b then
return bit_tobit(band(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.band = bit_band
local function bit_bxor(a, b, c, ...)
if c then
return bit_bxor(bit_bxor(a, b), c, ...)
elseif b then
return bit_tobit(bxor(a % MOD, b % MOD))
else
return bit_tobit(a)
end
end
M.bit.bxor = bit_bxor
function M.bit.lshift(x, n)
return bit_tobit(lshift(x % MOD, n % 32))
end
function M.bit.rshift(x, n)
return bit_tobit(rshift(x % MOD, n % 32))
end
function M.bit.arshift(x, n)
return bit_tobit(arshift(x % MOD, n % 32))
end
function M.bit.rol(x, n)
return bit_tobit(lrotate(x % MOD, n % 32))
end
function M.bit.ror(x, n)
return bit_tobit(rrotate(x % MOD, n % 32))
end
function M.bit.bswap(x)
return bit_tobit(bswap(x % MOD))
end
return M
| mit |
braydondavis/Nerd-Gaming-Public | resources/[no_ng_tag]/admin/server/admin_serverjoiner.lua | 7 | 3211 | --
--
-- admin_serverjoiner.lua
--
-- Delays triggerClientEvent until the client is ready.
-- Based on _triggequeue.lua from amx.
-- Should be high up in meta.xml.
--
---------------------------------------------------------------------------
--
-- Variables
--
---------------------------------------------------------------------------
local _triggerClientEvent = triggerClientEvent
local playerData = {} -- { player = { loaded = bool, pending = {...} } }
---------------------------------------------------------------------------
--
-- Events
--
---------------------------------------------------------------------------
addEventHandler('onResourceStart', resourceRoot,
function()
for i,player in ipairs(getElementsByType('player')) do
playerData[player] = { loaded = false, pending = {} }
end
end
)
addEventHandler('onPlayerJoin', root,
function()
playerData[source] = { loaded = false, pending = {} }
end
)
addEventHandler('onPlayerQuit', root,
function()
playerData[source] = nil
end
)
-- New player loaded
addEvent('onResourceLoadedAtClient_internal', true)
addEventHandler('onResourceLoadedAtClient_internal', resourceRoot,
function(player)
if checkClient( false, player, 'onResourceLoadedAtClient_internal' ) then return end
if playerData[player] then
playerData[player].loaded = true
-- Do queued events
for i,event in ipairs(playerData[player].pending) do
_triggerClientEvent(player, event.name, event.source, unpack(event.args))
end
playerData[player].pending = nil
end
end
)
---------------------------------------------------------------------------
--
-- Functions
--
---------------------------------------------------------------------------
local function addToQueue(player, name, source, args)
for i,a in pairs(args) do
if type(a) == 'table' then
args[i] = table.deepcopy(a)
end
end
table.insert(playerData[player].pending, { name = name, source = source, args = args })
end
function triggerClientEvent( triggerFor, name, theElement, ... )
local args = { ... }
if type(triggerFor) == 'string' then
table.insert(args, 1, theElement)
theElement = name
name = triggerFor
triggerFor = nil
end
triggerFor = triggerFor or root
if triggerFor == root then
-- trigger for everyone
for player,data in pairs(playerData) do
if data.loaded then
_triggerClientEvent(player, name, theElement, unpack(args))
else
addToQueue(player, name, theElement, args)
end
end
elseif playerData[triggerFor] then
-- trigger for single player
if playerData[triggerFor].loaded then
_triggerClientEvent(triggerFor, name, theElement, unpack(args))
else
addToQueue(triggerFor, name, theElement, args)
end
end
end
---------------------------------------------------------------------------
--
-- Util
--
---------------------------------------------------------------------------
function table.deepcopy(t)
local known = {}
local function _deepcopy(t)
local result = {}
for k,v in pairs(t) do
if type(v) == 'table' then
if not known[v] then
known[v] = _deepcopy(v)
end
result[k] = known[v]
else
result[k] = v
end
end
return result
end
return _deepcopy(t)
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.