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 |
|---|---|---|---|---|---|
medoo313m/bmo-bot2 | plugins/banhammer.lua | 1 | 12546 |
local function pre_process(msg)
local data = load_data(_config.moderation.data)
-- 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 print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
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 and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis
print('User is banned!')
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) >= 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) >= 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
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' or msg.to.type == 'channel' then
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 print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
local chat_id = extra.chat_id
local chat_type = extra.chat_type
if chat_type == "chat" then
receiver = 'chat#id'..chat_id
else
receiver = 'channel#id'..chat_id
end
if success == 0 then
return send_large_msg(receiver, "Cannot find user by that username!")
end
local member_id = result.peer_id
local user_id = member_id
local member = result.username
local from_id = extra.from_id
local get_cmd = extra.get_cmd
if get_cmd == "kick" then
if member_id == from_id then
send_large_msg(receiver, "You can't kick yourself")
return
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't kick mods/owner/admins")
return
end
kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
send_large_msg(receiver, "You can't ban mods/owner/admins")
return
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
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')
banall_user(member_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally unbanned')
unbanall_user(member_id)
end
end
local function run(msg, matches)
local support_id = msg.from.id
if matches[1]:lower() == 'id' and msg.to.type == "chat" or msg.to.type == "user" 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 print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' and msg.to.type == "chat" then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin1(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_admin1(msg) then
msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
local receiver = get_receiver(msg)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(matches[2], msg.to.id)
send_large_msg(receiver, 'User ['..matches[2]..'] banned')
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin1(msg) then
msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
elseif string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if not is_admin1(msg) and not is_support(support_id) then
return
end
if matches[1]:lower() == 'banall' and is_admin1(msg) then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin1(msg) then
banall = get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] globally unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id,
chat_type = msg.to.type
}
local username = string.gsub(matches[2], '@', '')
resolve_username(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[#]([Bb]anall) (.*)$",
"^[#]([Bb]anall)$",
"^[#]([Bb]anlist) (.*)$",
"^[#]([Bb]anlist)$",
"^[#]([Gg]banlist)$",
"^[#]([Kk]ickme)",
"^[#]([Kk]ick)$",
"^[#]([Bb]an)$",
"^[#]([Bb]an) (.*)$",
"^[#]([Uu]nban) (.*)$",
"^[#]([Uu]nbanall) (.*)$",
"^[#]([Uu]nbanall)$",
"^[#]([Kk]ick) (.*)$",
"^[#]([Uu]nban)$",
"^[#]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
shingenko/darkstar | scripts/zones/Uleguerand_Range/npcs/HomePoint#1.lua | 19 | 1189 | -----------------------------------
-- Area: Uleguerand_Range
-- NPC: HomePoint#1
-- @pos
-----------------------------------
package.loaded["scripts/zones/Uleguerand_Range/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Uleguerand_Range/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 76);
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 |
shingenko/darkstar | scripts/zones/RoMaeve/Zone.lua | 16 | 2428 | -----------------------------------
--
-- Zone: RoMaeve (122)
--
-----------------------------------
package.loaded["scripts/zones/RoMaeve/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/RoMaeve/TextIDs");
require("scripts/globals/zone");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17277227,17277228};
SetFieldManual(manuals);
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;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-0.008,-33.595,123.478,62);
end
if (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then
cs = 0x0003; -- doll telling "you're in the right area"
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onGameDay
-----------------------------------
function onGameDay()
-- Moongates
local Moongate_Offset = 17277195; -- _3e0 in npc_list
local direction = VanadielMoonDirection();
local phase = VanadielMoonPhase();
if (((direction == 2 and phase >= 90) or (direction == 1 and phase >= 95)) and GetNPCByID(Moongate_Offset):getWeather() == 0) then
GetNPCByID(Moongate_Offset):openDoor(432);
GetNPCByID(Moongate_Offset+1):openDoor(432);
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 |
yuin/silkylog | themes/default/theme.lua | 1 | 1197 | config {
extra_files = {
{src = "css/*", dst = "statics/css/", template = false},
{src = "js/*", dst = "statics/js/", template = false},
{src = "img/*", dst = "statics/img/", template = false}
}
}
about_this_site = [[
<div>
<p><i class="icon-male"></i> Author: Your Name</p>
<p>Your profile</p>
</div>
]]
find_me_on = [[
<ul class="icons-ul">
<li style="margin-bottom: 0.5em;"><i class="icon-li icon-large icon-github"></i><a href="https://github.com/example">GitHub</a></li>
</ul>
]]
function seealso(art, tags)
local buf = {"<ul><h3>See Also</h3>"}
local seen = {}
seen[art.permlink_path] = 1
local i = 0
for j, tag in ipairs(art.tags or {}) do
for k, article in ipairs(tags[tag] or {}) do
if seen[article.permlink_path] == nil then
table.insert(buf, string.format("<li><a href=\"%s\">%s</a></li>", article.permlink_path, silkylog.htmlescape(article.title)))
seen[article.permlink_path] = 1
i = i + 1
if i > 4 then
break
end
end
end
if i > 4 then
break
end
end
table.insert(buf, "</ul>")
if i == 0 then
return ""
end
return table.concat(buf, "\n")
end
| mit |
rosejn/lua-fn | fn/init.lua | 2 | 6175 | require('util')
-- Short-hand operator functions for use in map, filter, reduce...
fn = {
mod = math.mod;
pow = math.pow;
add = function(n,m) return n + m end;
sub = function(n,m) return n - m end;
mul = function(n,m) return n * m end;
div = function(n,m) return n / m end;
gt = function(n,m) return m > n end;
lt = function(n,m) return m < n end;
eq = function(n,m) return n == m end;
le = function(n,m) return n <= m end;
ge = function(n,m) return n >= m end;
ne = function(n,m) return n ~= m end;
}
function fn.inc(v)
return v + 1
end
function fn.dec(v)
return v - 1
end
function fn.id(v)
return v
end
function fn.const(x)
return function() return x end
end
------------------------------------------------------------
-- Treating tables as sequences
-----------------------------------------------------------
-- Returns the size of a table
function fn.count(tbl)
return #tbl
end
-- Predicate test if a table is empty
function fn.is_empty(tbl)
return #tbl == 0
end
-- Append an element onto the end of a table
function fn.append(tbl, val)
table.insert(tbl, val)
return tbl
end
-- Returns the first element of a table
function fn.first(tbl)
return tbl[1]
end
-- Returns the second element of a table
function fn.second(tbl)
return tbl[2]
end
-- Get the last element of a table
function fn.last(tbl)
return tbl[#tbl]
end
-- Returns a new table with everything but the first element of a table,
-- or nil if the table is empty.
function fn.rest(tbl)
if fn.is_empty(tbl) then
return nil
else
local new_array = {}
for i = 2, #tbl do
table.insert(new_array, tbl[i])
end
return new_array
end
end
-- Returns a new table containing the first n elements of tbl
function fn.take(n, tbl)
local new_tbl = {}
for i=1, n do
fn.append(new_tbl, tbl[i])
end
return new_tbl
end
-- Returns a new table without the first n elements of tbl
function fn.drop(n, tbl)
local new_tbl = {}
for i=n+1, #tbl do
fn.append(new_tbl, tbl[i])
end
return new_tbl
end
------------------------------------------------------------
-- Making use of functions
-----------------------------------------------------------
-- is(checker_function, expected_value)
-- @brief
-- check function generator. return the function to return boolean,
-- if the condition was expected then true, else false. Helpful
-- for filtering and other functions that take a predicate.
-- @example
-- local is_table = fn.is(type, "table")
-- local is_even = fn.is(fn.partial(math.mod, 2), 1)
-- local is_odd = fn.is(fn.partial(math.mod, 2), 0)
function fn.is(check, expected)
return function (...)
if (check(unpack(...)) == expected) then
return true
else
return false
end
end
end
-- comp(f,g)
-- Returns a function that is the composition of functions f and g: f(g(...))
-- e.g: printf = comp(io.write, string.format)
-- -> function(...) return io.write(string.format(unpack(arg))) end
function fn.comp(f,g)
return function (...)
return f(g(...))
end
end
-- partial(f, args)
-- Returns a new function, which will call f with args and any additional
-- arguments passed to the new function.
function fn.partial(f, ...)
local pargs = {...}
return function(...)
local args = {}
for _,v in ipairs(pargs) do
fn.append(args, v)
end
for _,v in ipairs({...}) do
fn.append(args, v)
end
return f(unpack(args))
end
end
-- thread(value, f, ...)
function fn.thread(val, ...)
local functions = {...}
for _, fun in ipairs(functions) do
val = fun(val)
end
return val
end
--[[
apply(f, args..., tbl)
Call function f, passing args as the arguments, with the values in tbl appended to
the argument list.
e.g.
function compute(m, x, b)
return m * x + b
end
-- apply a list of args to a function
fn.apply(compute, {2, 3, 4})
-- prepend some args to the list that is applied
fn.apply(compute, 2, {3, 4})
fn.apply(compute, 2, 3, {4})
]]
function fn.apply(f, ...)
local pargs = {}
local args = {...}
if #args > 1 then
for i=1, (#args - 1) do
fn.append(pargs, args[i])
end
end
local full_args = util.concat(pargs, args[#args])
return f(unpack(full_args))
end
-- map(function, table)
-- e.g: map(double, {1,2,3}) -> {2,4,6}
function fn.map(func, tbl)
local newtbl = {}
for i,v in pairs(tbl) do
newtbl[i] = func(v)
end
return newtbl
end
-- filter(function, table)
-- e.g: filter(is_even, {1,2,3,4}) -> {2,4}
function fn.filter(func, tbl)
local newtbl= {}
for i,v in ipairs(tbl) do
if func(v) then
fn.append(newtbl, v)
end
end
return newtbl
end
-- reduce(function, init_val, table)
-- e.g:
-- reduce(fn.mul, 1, {1,2,3,4,5}) -> 120
-- reduce(fn.add, 0, {1,2,3,4}) -> 10
function fn.reduce(func, val, tbl)
for _,v in pairs(tbl) do
val = func(val, v)
end
return val
end
-- Returns a map with keys mapped to corresponding vals.
-- e.g.
-- zipmap({1,2,3}, {'a', 'b', 'c'}) -- => {1 = 'a', 2 = 'b', 3 = 'c'}
function fn.zipmap(keys, vals)
local m = {}
for i, key in ipairs(keys) do
m[key] = vals[i]
end
return m
end
-- zip(table, table)
-- e.g.
-- zip({1,2,3}, {'a', 'b', 'c'}) -> {{1,'a'}, {2,'b'}, {3,'c'}}
-- zip({1,2,3}, {'a', 'b', 'c', 'd'}) -> {{1,'a'}, {2,'b'}, {3,'c'}}
function fn.zip(tbl_a, tbl_b)
local len = math.min(#tbl_a, #tbl_b)
local newtbl = {}
for i = 1,len do
table.insert(newtbl, {tbl_a[i], tbl_b[i]})
end
return newtbl
end
-- zip_with(function, table, table)
-- e.g.:
-- zip_with(fn.add, {1,2,3}, {1,2,3}) -> {2,4,6}
-- zip_with(fn.add, {1,2,3}, {1,2,3,4}) -> {2,4,6}
function fn.zip_with(func, tbl_a, tbl_b)
return fn.map(function(x) return func(unpack(x)) end, fn.zip(tbl_a, tbl_b))
end
| bsd-3-clause |
mrvigeo/salib2 | plugins/banhammer.lua | 7 | 11698 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "تو نمیتونی خودتو کیک کنی")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "من نمیتونم ادمینو کاریش کنم")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "نمیتونم ادمینو کاریش کنم")
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..'] از همه گروه ها بن شد')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] از بن همه گروه ها خارج شد')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "من نمیتونم ادمینو کاریش کنم"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "تو نمیتونی خودتو بن کنی"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'کاربر '..user_id..' آنبن شد'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "نمیتونم ادمینو کاریش کنم"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "تو نمیتونی خودتو کیک کنی"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'کاربر ['..user_id..' ] سوپر بن شد'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'کاربر ['..user_id..' ] از لیست سوپر بن ها حذف شد'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^(banall) (.*)$",
"^(banall)$",
"^([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 |
coronalabs/framework-widget | unitTestListing.lua | 1 | 6859 |
-- Abstract: Widget test listing
-- Code is MIT licensed; see https://www.coronalabs.com/links/code/license
---------------------------------------------------------------------------------------
local widget = require( "widget" )
local composer = require( "composer" )
local scene = composer.newScene()
local USE_IOS_THEME = false
local USE_IOS7_THEME = false
local USE_ANDROID_THEME = false
local USE_ANDROID_HOLO_LIGHT_THEME = false
local USE_ANDROID_HOLO_DARK_THEME = false
local isGraphicsV1 = ( 1 == display.getDefault( "graphicsCompatibility" ) )
local topGrayColor = { 0.92, 0.92, 0.92, 1 }
local separatorColor = { 0.77, 0.77, 0.77, 1 }
local headerTextColor = { 0, 0, 0, 1 }
if isGraphicsV1 then
widget._convertColorToV1( topGrayColor )
widget._convertColorToV1( separatorColor )
widget._convertColorToV1( headerTextColor )
end
function scene:create( event )
local group = self.view
-- Set theme
if USE_ANDROID_THEME then
widget.setTheme( "widget_theme_android" )
end
if USE_IOS_THEME then
widget.setTheme( "widget_theme_ios" )
end
if USE_IOS7_THEME then
widget.setTheme( "widget_theme_ios7" )
end
if USE_ANDROID_HOLO_LIGHT_THEME then
widget.setTheme( "widget_theme_android_holo_light" )
end
if USE_ANDROID_HOLO_DARK_THEME then
widget.setTheme( "widget_theme_android_holo_dark" )
end
local xAnchor, yAnchor
if not isGraphicsV1 then
xAnchor = display.contentCenterX
yAnchor = display.contentCenterY
else
xAnchor = 0
yAnchor = 0
end
local background = display.newRect( xAnchor, yAnchor, display.contentWidth, display.contentHeight )
if USE_IOS_THEME then
if isGraphicsV1 then background:setFillColor( 197, 204, 212, 255 )
else background:setFillColor( 197/255, 204/255, 212/255, 1 ) end
widget.USE_IOS_THEME = true
elseif USE_ANDROID_HOLO_LIGHT_THEME then
if isGraphicsV1 then background:setFillColor( 255, 255, 255, 255 )
else background:setFillColor( 1, 1, 1, 1 ) end
widget.USE_ANDROID_HOLO_LIGHT_THEME = true
elseif USE_ANDROID_HOLO_DARK_THEME then
if isGraphicsV1 then background:setFillColor( 34, 34, 34, 255 )
else background:setFillColor( 34/255, 34/255, 34/255, 1 ) end
widget.USE_ANDROID_HOLO_DARK_THEME = true
headerTextColor = { 0.5 }
else
if isGraphicsV1 then background:setFillColor( 255, 255, 255, 255 )
else background:setFillColor( 1, 1, 1, 1 ) end
end
group:insert( background )
-- create some skinning variables
local fontUsed = native.systemFont
local headerTextSize = 20
local separatorColor = { unpack( separatorColor ) }
local title = display.newText( group, "Select a unit test to view", 0, 0, fontUsed, headerTextSize )
title:setFillColor( unpack( headerTextColor ) )
title.x, title.y = display.contentCenterX, 20
group:insert( title )
if USE_IOS7_THEME then
local separator = display.newRect( group, display.contentCenterX, title.contentHeight + title.y, display.contentWidth, 0.5 )
separator:setFillColor( unpack ( separatorColor ) )
end
--Go to selected unit test
local function gotoSelection( event )
local phase = event.phase
if "ended" == phase then
local targetScene = event.target.id
composer.gotoScene( targetScene )
end
return true
end
local buttonX = 160
-- spinner unit test
local spinnerButton = widget.newButton
{
id = "spinner",
x = buttonX,
y = 75,
label = "Spinner",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( spinnerButton )
-- switch unit test
local switchButton = widget.newButton
{
id = "switch",
x = buttonX,
y = spinnerButton.y + 36,
label = "Switch",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( switchButton )
-- Stepper unit test
local stepperButton = widget.newButton
{
id = "stepper",
x = buttonX,
y = switchButton.y + 36,
label = "Stepper",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( stepperButton )
-- Search field unit test
--[[
local searchFieldButton = widget.newButton
{
id = "searchField",
x = buttonX,
y = stepperButton.y + 36,
label = "Search Field",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( searchFieldButton )
--]]
-- progressView unit test
local progressViewButton = widget.newButton
{
id = "progressView",
x = buttonX,
y = stepperButton.y + 36,
label = "ProgressView",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( progressViewButton )
-- segmentedControl unit test
local segmentedControlButton = widget.newButton
{
id = "segmentedControl",
x = buttonX,
y = progressViewButton.y + 36,
label = "SegmentedControl",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( segmentedControlButton )
-- button unit test
local buttonButton = widget.newButton
{
id = "button",
x = buttonX,
y = segmentedControlButton.y + 36,
label = "Button",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( buttonButton )
-- tabBar unit test
local tabBarButton = widget.newButton
{
id = "tabBar",
x = buttonX,
y = buttonButton.y + 36,
label = "TabBar",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( tabBarButton )
-- slider unit test
local sliderButton = widget.newButton
{
id = "slider",
x = buttonX,
y = tabBarButton.y + 36,
label = "Slider",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( sliderButton )
-- picker unit test
local pickerButton = widget.newButton
{
id = "picker",
x = buttonX,
y = sliderButton.y + 36,
label = "PickerWheel",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( pickerButton )
-- tableView unit test
local tableViewButton = widget.newButton
{
id = "tableView",
x = buttonX,
y = pickerButton.y + 36,
label = "TableView",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( tableViewButton )
-- scrollView unit test
local scrollViewButton = widget.newButton
{
id = "scrollView",
x = buttonX,
y = tableViewButton.y + 36,
label = "ScrollView",
width = 200, height = 34,
emboss = false,
onEvent = gotoSelection
}
group:insert( scrollViewButton )
end
function scene:hide( event )
if ( "did" == event.phase ) then
composer.removeHidden( false )
end
end
scene:addEventListener( "create", scene )
scene:addEventListener( "hide", scene )
return scene
| mit |
luadch/luadch | scripts/cmd_slots.lua | 1 | 2191 | --[[
cmd_slots.lua by pulsar
usage: [+!#]slots
v0.1:
- this script shows all users with free slots
]]--
--------------
--[SETTINGS]--
--------------
local scriptname = "cmd_slots"
local scriptversion = "0.1"
local cmd = "slots"
local minlevel = cfg.get "cmd_slots_minlevel"
----------
--[CODE]--
----------
--// table lookups
local utf_match = utf.match
local utf_format = utf.format
local hub_getbot = hub.getbot()
local hub_getusers = hub.getusers
local hub_import = hub.import
local hub_debug = hub.debug
--// imports
local help, ucmd, hubcmd
--// msgs
local scriptlang = cfg.get( "language" )
local lang, err = cfg.loadlanguage( scriptlang, scriptname ); lang = lang or {}; err = err and hub.debug( err )
local help_title = lang.help_title or "Slots"
local help_usage = lang.help_usage or "[+!#]slots"
local help_desc = lang.help_desc or "shows users with free slots"
local ucmd_menu = lang.ucmd_menu or { "User", "Free Slots" }
local msg_out = lang.msg_out or [[
=== FREE SLOTS ====================
%s
==================== FREE SLOTS ===
]]
local onbmsg = function( user )
local tbl = {}
for sid, user in pairs( hub_getusers() ) do
if not user:isbot() then
local nick = user:nick()
local slots = user:slots()
if slots > 0 then
tbl[ #tbl + 1 ] = " " .. nick .. " | " .. slots .. "\n"
end
end
end
tbl = table.concat( tbl )
local msg = utf_format( msg_out, tbl )
user:reply( msg, hub_getbot )
return PROCESSED
end
hub.setlistener( "onStart", { },
function( )
help = hub_import( "cmd_help" )
ucmd = hub_import( "etc_usercommands" )
hubcmd = hub_import( "etc_hubcommands" )
if help then help.reg( help_title, help_usage, help_desc, minlevel ) end
if ucmd then ucmd.add( ucmd_menu, cmd, {}, { "CT1" }, minlevel ) end
assert( hubcmd )
assert( hubcmd.add( cmd, onbmsg ) )
return nil
end
)
hub_debug( "** Loaded " .. scriptname .. " " .. scriptversion .. " **" ) | gpl-3.0 |
mohammadtofani/seedmn | plugins/banhammer.lua | 34 | 11497 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^([Bb]anall) (.*)$",
"^([Bb]anall)$",
"^([Bb]anlist) (.*)$",
"^([Bb]anlist)$",
"^([Gg]banlist)$",
"^([Bb]an) (.*)$",
"^([Kk]ick)$",
"^([Uu]nban) (.*)$",
"^([Uu]nbanall) (.*)$",
"^([Uu]nbanall)$",
"^([Kk]ick) (.*)$",
"^([Kk]ickme)$",
"^([Bb]an)$",
"^([Uu]nban)$",
"^([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
RuiChen1113/luci | modules/luci-base/luasrc/tools/webadmin.lua | 59 | 2301 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008-2015 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.tools.webadmin", package.seeall)
local util = require "luci.util"
local uci = require "luci.model.uci"
local ip = require "luci.ip"
function byte_format(byte)
local suff = {"B", "KB", "MB", "GB", "TB"}
for i=1, 5 do
if byte > 1024 and i < 5 then
byte = byte / 1024
else
return string.format("%.2f %s", byte, suff[i])
end
end
end
function date_format(secs)
local suff = {"min", "h", "d"}
local mins = 0
local hour = 0
local days = 0
secs = math.floor(secs)
if secs > 60 then
mins = math.floor(secs / 60)
secs = secs % 60
end
if mins > 60 then
hour = math.floor(mins / 60)
mins = mins % 60
end
if hour > 24 then
days = math.floor(hour / 24)
hour = hour % 24
end
if days > 0 then
return string.format("%.0fd %02.0fh %02.0fmin %02.0fs", days, hour, mins, secs)
else
return string.format("%02.0fh %02.0fmin %02.0fs", hour, mins, secs)
end
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 cbi_add_knownips(field)
local _, n
for _, n in ipairs(ip.neighbors({ family = 4 })) do
if n.dest then
field:value(n.dest:string())
end
end
end
function firewall_find_zone(name)
local find
luci.model.uci.cursor():foreach("firewall", "zone",
function (section)
if section.name == name then
find = section[".name"]
end
end
)
return find
end
function iface_get_network(iface)
local link = ip.link(tostring(iface))
if link.master then
iface = link.master
end
local cur = uci.cursor()
local dump = util.ubus("network.interface", "dump", { })
if dump then
local _, net
for _, net in ipairs(dump.interface) do
if net.l3_device == iface or net.device == iface then
-- cross check with uci to filter out @name style aliases
local uciname = cur:get("network", net.interface, "ifname")
if not uciname or uciname:sub(1, 1) ~= "@" then
return net.interface
end
end
end
end
end
| apache-2.0 |
zhukunqian/slua-1 | build/luajit-2.1.0/src/jit/dis_x86.lua | 61 | 29376 | ----------------------------------------------------------------------------
-- LuaJIT x86/x64 disassembler module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
-- This is a helper module used by the LuaJIT machine code dumper module.
--
-- Sending small code snippets to an external disassembler and mixing the
-- output with our own stuff was too fragile. So I had to bite the bullet
-- and write yet another x86 disassembler. Oh well ...
--
-- The output format is very similar to what ndisasm generates. But it has
-- been developed independently by looking at the opcode tables from the
-- Intel and AMD manuals. The supported instruction set is quite extensive
-- and reflects what a current generation Intel or AMD CPU implements in
-- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3,
-- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM)
-- instructions.
--
-- Notes:
-- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported.
-- * No attempt at optimization has been made -- it's fast enough for my needs.
-- * The public API may change when more architectures are added.
------------------------------------------------------------------------------
local type = type
local sub, byte, format = string.sub, string.byte, string.format
local match, gmatch, gsub = string.match, string.gmatch, string.gsub
local lower, rep = string.lower, string.rep
local bit = require("bit")
local tohex = bit.tohex
-- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on.
local map_opc1_32 = {
--0x
[0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es",
"orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*",
--1x
"adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss",
"sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds",
--2x
"andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa",
"subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das",
--3x
"xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa",
"cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas",
--4x
"incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR",
"decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR",
--5x
"pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR",
"popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR",
--6x
"sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr",
"fs:seg","gs:seg","o16:","a16",
"pushUi","imulVrmi","pushBs","imulVrms",
"insb","insVS","outsb","outsVS",
--7x
"joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj",
"jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj",
--8x
"arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms",
"testBmr","testVmr","xchgBrm","xchgVrm",
"movBmr","movVmr","movBrm","movVrm",
"movVmg","leaVrm","movWgm","popUm",
--9x
"nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR",
"xchgVaR","xchgVaR","xchgVaR","xchgVaR",
"sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait",
"sz*pushfw,pushf","sz*popfw,popf","sahf","lahf",
--Ax
"movBao","movVao","movBoa","movVoa",
"movsb","movsVS","cmpsb","cmpsVS",
"testBai","testVai","stosb","stosVS",
"lodsb","lodsVS","scasb","scasVS",
--Bx
"movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi",
"movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI",
--Cx
"shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi",
"enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS",
--Dx
"shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb",
"fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7",
--Ex
"loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj",
"inBau","inVau","outBua","outVua",
"callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda",
--Fx
"lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm",
"clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm",
}
assert(#map_opc1_32 == 255)
-- Map for 1st opcode byte in 64 bit mode (overrides only).
local map_opc1_64 = setmetatable({
[0x06]=false, [0x07]=false, [0x0e]=false,
[0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false,
[0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false,
[0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:",
[0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb",
[0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb",
[0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb",
[0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb",
[0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false,
[0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false,
}, { __index = map_opc1_32 })
-- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you.
-- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2
local map_opc2 = {
--0x
[0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret",
"invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu",
--1x
"movupsXrm|movssXrm|movupdXrm|movsdXrm",
"movupsXmr|movssXmr|movupdXmr|movsdXmr",
"movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm",
"movlpsXmr||movlpdXmr",
"unpcklpsXrm||unpcklpdXrm",
"unpckhpsXrm||unpckhpdXrm",
"movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm",
"movhpsXmr||movhpdXmr",
"$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm",
"hintnopVm","hintnopVm","hintnopVm","hintnopVm",
--2x
"movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil,
"movapsXrm||movapdXrm",
"movapsXmr||movapdXmr",
"cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt",
"movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr",
"cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm",
"cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm",
"ucomissXrm||ucomisdXrm",
"comissXrm||comisdXrm",
--3x
"wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec",
"opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil,
--4x
"cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm",
"cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm",
"cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm",
"cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm",
--5x
"movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm",
"rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm",
"andpsXrm||andpdXrm","andnpsXrm||andnpdXrm",
"orpsXrm||orpdXrm","xorpsXrm||xorpdXrm",
"addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm",
"cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm",
"cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm",
"subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm",
"divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm",
--6x
"punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm",
"pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm",
"punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm",
"||punpcklqdqXrm","||punpckhqdqXrm",
"movPrVSm","movqMrm|movdquXrm|movdqaXrm",
--7x
"pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu",
"pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu",
"pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|",
"vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$",
nil,nil,
"||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm",
"movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr",
--8x
"joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj",
"jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj",
--9x
"setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm",
"setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm",
--Ax
"push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil,
"push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm",
--Bx
"cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr",
"$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt",
"|popcntVrm","ud2Dp","bt!Vmu","btcVmr",
"bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt",
--Cx
"xaddBmr","xaddVmr",
"cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|",
"pinsrwPrWmu","pextrwDrPmu",
"shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp",
"bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR",
--Dx
"||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm",
"paddqPrm","pmullwPrm",
"|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm",
"psubusbPrm","psubuswPrm","pminubPrm","pandPrm",
"paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm",
--Ex
"pavgbPrm","psrawPrm","psradPrm","pavgwPrm",
"pmulhuwPrm","pmulhwPrm",
"|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr",
"psubsbPrm","psubswPrm","pminswPrm","porPrm",
"paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm",
--Fx
"|||lddquXrm","psllwPrm","pslldPrm","psllqPrm",
"pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$",
"psubbPrm","psubwPrm","psubdPrm","psubqPrm",
"paddbPrm","paddwPrm","padddPrm","ud",
}
assert(map_opc2[255] == "ud")
-- Map for three-byte opcodes. Can't wait for their next invention.
local map_opc3 = {
["38"] = { -- [66] 0f 38 xx
--0x
[0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm",
"pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm",
"psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm",
nil,nil,nil,nil,
--1x
"||pblendvbXrma",nil,nil,nil,
"||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm",
nil,nil,nil,nil,
"pabsbPrm","pabswPrm","pabsdPrm",nil,
--2x
"||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm",
"||pmovsxwqXrm","||pmovsxdqXrm",nil,nil,
"||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm",
nil,nil,nil,nil,
--3x
"||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm",
"||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm",
"||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm",
"||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm",
--4x
"||pmulddXrm","||phminposuwXrm",
--Fx
[0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt",
},
["3a"] = { -- [66] 0f 3a xx
--0x
[0x00]=nil,nil,nil,nil,nil,nil,nil,nil,
"||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu",
"||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu",
--1x
nil,nil,nil,nil,
"||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru",
nil,nil,nil,nil,nil,nil,nil,nil,
--2x
"||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil,
--4x
[0x40] = "||dppsXrmu",
[0x41] = "||dppdXrmu",
[0x42] = "||mpsadbwXrmu",
--6x
[0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu",
[0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu",
},
}
-- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands).
local map_opcvm = {
[0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff",
[0xc8]="monitor",[0xc9]="mwait",
[0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave",
[0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga",
[0xf8]="swapgs",[0xf9]="rdtscp",
}
-- Map for FP opcodes. And you thought stack machines are simple?
local map_opcfp = {
-- D8-DF 00-BF: opcodes with a memory operand.
-- D8
[0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm",
"fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm",
-- DA
"fiaddDm","fimulDm","ficomDm","ficompDm",
"fisubDm","fisubrDm","fidivDm","fidivrDm",
-- DB
"fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp",
-- DC
"faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm",
-- DD
"fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm",
-- DE
"fiaddWm","fimulWm","ficomWm","ficompWm",
"fisubWm","fisubrWm","fidivWm","fidivrWm",
-- DF
"fildWm","fisttpWm","fistWm","fistpWm",
"fbld twordFmp","fildQm","fbstp twordFmp","fistpQm",
-- xx C0-FF: opcodes with a pseudo-register operand.
-- D8
"faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf",
-- D9
"fldFf","fxchFf",{"fnop"},nil,
{"fchs","fabs",nil,nil,"ftst","fxam"},
{"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"},
{"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"},
{"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"},
-- DA
"fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil,
-- DB
"fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf",
{nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil,
-- DC
"fadd toFf","fmul toFf",nil,nil,
"fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf",
-- DD
"ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil,
-- DE
"faddpFf","fmulpFf",nil,{nil,"fcompp"},
"fsubrpFf","fsubpFf","fdivrpFf","fdivpFf",
-- DF
nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil,
}
assert(map_opcfp[126] == "fcomipFf")
-- Map for opcode groups. The subkey is sp from the ModRM byte.
local map_opcgroup = {
arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" },
shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" },
testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" },
testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" },
incb = { "inc", "dec" },
incd = { "inc", "dec", "callUmp", "$call farDmp",
"jmpUmp", "$jmp farDmp", "pushUm" },
sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" },
sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt",
"smsw", nil, "lmsw", "vm*$invlpg" },
bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" },
cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil,
nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" },
pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" },
pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" },
pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" },
pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" },
fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr",
nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" },
prefetch = { "prefetch", "prefetchw" },
prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" },
}
------------------------------------------------------------------------------
-- Maps for register names.
local map_regs = {
B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil",
"r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" },
W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di",
"r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" },
D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi",
"r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" },
Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" },
M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
"mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext!
X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
"xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" },
}
local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" }
-- Maps for size names.
local map_sz2n = {
B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16,
}
local map_sz2prefix = {
B = "byte", W = "word", D = "dword",
Q = "qword",
M = "qword", X = "xword",
F = "dword", G = "qword", -- No need for sizes/register names for these two.
}
------------------------------------------------------------------------------
-- Output a nicely formatted line with an opcode and operands.
local function putop(ctx, text, operands)
local code, pos, hex = ctx.code, ctx.pos, ""
local hmax = ctx.hexdump
if hmax > 0 then
for i=ctx.start,pos-1 do
hex = hex..format("%02X", byte(code, i, i))
end
if #hex > hmax then hex = sub(hex, 1, hmax)..". "
else hex = hex..rep(" ", hmax-#hex+2) end
end
if operands then text = text.." "..operands end
if ctx.o16 then text = "o16 "..text; ctx.o16 = false end
if ctx.a32 then text = "a32 "..text; ctx.a32 = false end
if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end
if ctx.rex then
local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "")..
(ctx.rexx and "x" or "")..(ctx.rexb and "b" or "")
if t ~= "" then text = "rex."..t.." "..text end
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false
end
if ctx.seg then
local text2, n = gsub(text, "%[", "["..ctx.seg..":")
if n == 0 then text = ctx.seg.." "..text else text = text2 end
ctx.seg = false
end
if ctx.lock then text = "lock "..text; ctx.lock = false end
local imm = ctx.imm
if imm then
local sym = ctx.symtab[imm]
if sym then text = text.."\t->"..sym end
end
ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text))
ctx.mrm = false
ctx.start = pos
ctx.imm = nil
end
-- Clear all prefix flags.
local function clearprefixes(ctx)
ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false
ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false
ctx.rex = false; ctx.a32 = false
end
-- Fallback for incomplete opcodes at the end.
local function incomplete(ctx)
ctx.pos = ctx.stop+1
clearprefixes(ctx)
return putop(ctx, "(incomplete)")
end
-- Fallback for unknown opcodes.
local function unknown(ctx)
clearprefixes(ctx)
return putop(ctx, "(unknown)")
end
-- Return an immediate of the specified size.
local function getimm(ctx, pos, n)
if pos+n-1 > ctx.stop then return incomplete(ctx) end
local code = ctx.code
if n == 1 then
local b1 = byte(code, pos, pos)
return b1
elseif n == 2 then
local b1, b2 = byte(code, pos, pos+1)
return b1+b2*256
else
local b1, b2, b3, b4 = byte(code, pos, pos+3)
local imm = b1+b2*256+b3*65536+b4*16777216
ctx.imm = imm
return imm
end
end
-- Process pattern string and generate the operands.
local function putpat(ctx, name, pat)
local operands, regs, sz, mode, sp, rm, sc, rx, sdisp
local code, pos, stop = ctx.code, ctx.pos, ctx.stop
-- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz
for p in gmatch(pat, ".") do
local x = nil
if p == "V" or p == "U" then
if ctx.rexw then sz = "Q"; ctx.rexw = false
elseif ctx.o16 then sz = "W"; ctx.o16 = false
elseif p == "U" and ctx.x64 then sz = "Q"
else sz = "D" end
regs = map_regs[sz]
elseif p == "T" then
if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end
regs = map_regs[sz]
elseif p == "B" then
sz = "B"
regs = ctx.rex and map_regs.B64 or map_regs.B
elseif match(p, "[WDQMXFG]") then
sz = p
regs = map_regs[sz]
elseif p == "P" then
sz = ctx.o16 and "X" or "M"; ctx.o16 = false
regs = map_regs[sz]
elseif p == "S" then
name = name..lower(sz)
elseif p == "s" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = imm <= 127 and format("+0x%02x", imm)
or format("-0x%02x", 256-imm)
pos = pos+1
elseif p == "u" then
local imm = getimm(ctx, pos, 1); if not imm then return end
x = format("0x%02x", imm)
pos = pos+1
elseif p == "w" then
local imm = getimm(ctx, pos, 2); if not imm then return end
x = format("0x%x", imm)
pos = pos+2
elseif p == "o" then -- [offset]
if ctx.x64 then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("[0x%08x%08x]", imm2, imm1)
pos = pos+8
else
local imm = getimm(ctx, pos, 4); if not imm then return end
x = format("[0x%08x]", imm)
pos = pos+4
end
elseif p == "i" or p == "I" then
local n = map_sz2n[sz]
if n == 8 and ctx.x64 and p == "I" then
local imm1 = getimm(ctx, pos, 4); if not imm1 then return end
local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end
x = format("0x%08x%08x", imm2, imm1)
else
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then
imm = (0xffffffff+1)-imm
x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm)
else
x = format(imm > 65535 and "0x%08x" or "0x%x", imm)
end
end
pos = pos+n
elseif p == "j" then
local n = map_sz2n[sz]
if n == 8 then n = 4 end
local imm = getimm(ctx, pos, n); if not imm then return end
if sz == "B" and imm > 127 then imm = imm-256
elseif imm > 2147483647 then imm = imm-4294967296 end
pos = pos+n
imm = imm + pos + ctx.addr
if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end
ctx.imm = imm
if sz == "W" then
x = format("word 0x%04x", imm%65536)
elseif ctx.x64 then
local lo = imm % 0x1000000
x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo)
else
x = "0x"..tohex(imm)
end
elseif p == "R" then
local r = byte(code, pos-1, pos-1)%8
if ctx.rexb then r = r + 8; ctx.rexb = false end
x = regs[r+1]
elseif p == "a" then x = regs[1]
elseif p == "c" then x = "cl"
elseif p == "d" then x = "dx"
elseif p == "1" then x = "1"
else
if not mode then
mode = ctx.mrm
if not mode then
if pos > stop then return incomplete(ctx) end
mode = byte(code, pos, pos)
pos = pos+1
end
rm = mode%8; mode = (mode-rm)/8
sp = mode%8; mode = (mode-sp)/8
sdisp = ""
if mode < 3 then
if rm == 4 then
if pos > stop then return incomplete(ctx) end
sc = byte(code, pos, pos)
pos = pos+1
rm = sc%8; sc = (sc-rm)/8
rx = sc%8; sc = (sc-rx)/8
if ctx.rexx then rx = rx + 8; ctx.rexx = false end
if rx == 4 then rx = nil end
end
if mode > 0 or rm == 5 then
local dsz = mode
if dsz ~= 1 then dsz = 4 end
local disp = getimm(ctx, pos, dsz); if not disp then return end
if mode == 0 then rm = nil end
if rm or rx or (not sc and ctx.x64 and not ctx.a32) then
if dsz == 1 and disp > 127 then
sdisp = format("-0x%x", 256-disp)
elseif disp >= 0 and disp <= 0x7fffffff then
sdisp = format("+0x%x", disp)
else
sdisp = format("-0x%x", (0xffffffff+1)-disp)
end
else
sdisp = format(ctx.x64 and not ctx.a32 and
not (disp >= 0 and disp <= 0x7fffffff)
and "0xffffffff%08x" or "0x%08x", disp)
end
pos = pos+dsz
end
end
if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end
if ctx.rexr then sp = sp + 8; ctx.rexr = false end
end
if p == "m" then
if mode == 3 then x = regs[rm+1]
else
local aregs = ctx.a32 and map_regs.D or ctx.aregs
local srm, srx = "", ""
if rm then srm = aregs[rm+1]
elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end
ctx.a32 = false
if rx then
if rm then srm = srm.."+" end
srx = aregs[rx+1]
if sc > 0 then srx = srx.."*"..(2^sc) end
end
x = format("[%s%s%s]", srm, srx, sdisp)
end
if mode < 3 and
(not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck.
x = map_sz2prefix[sz].." "..x
end
elseif p == "r" then x = regs[sp+1]
elseif p == "g" then x = map_segregs[sp+1]
elseif p == "p" then -- Suppress prefix.
elseif p == "f" then x = "st"..rm
elseif p == "x" then
if sp == 0 and ctx.lock and not ctx.x64 then
x = "CR8"; ctx.lock = false
else
x = "CR"..sp
end
elseif p == "y" then x = "DR"..sp
elseif p == "z" then x = "TR"..sp
elseif p == "t" then
else
error("bad pattern `"..pat.."'")
end
end
if x then operands = operands and operands..", "..x or x end
end
ctx.pos = pos
return putop(ctx, name, operands)
end
-- Forward declaration.
local map_act
-- Fetch and cache MRM byte.
local function getmrm(ctx)
local mrm = ctx.mrm
if not mrm then
local pos = ctx.pos
if pos > ctx.stop then return nil end
mrm = byte(ctx.code, pos, pos)
ctx.pos = pos+1
ctx.mrm = mrm
end
return mrm
end
-- Dispatch to handler depending on pattern.
local function dispatch(ctx, opat, patgrp)
if not opat then return unknown(ctx) end
if match(opat, "%|") then -- MMX/SSE variants depending on prefix.
local p
if ctx.rep then
p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)"
ctx.rep = false
elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false
else p = "^[^%|]*" end
opat = match(opat, p)
if not opat then return unknown(ctx) end
-- ctx.rep = false; ctx.o16 = false
--XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi]
--XXX remove in branches?
end
if match(opat, "%$") then -- reg$mem variants.
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)")
if opat == "" then return unknown(ctx) end
end
if opat == "" then return unknown(ctx) end
local name, pat = match(opat, "^([a-z0-9 ]*)(.*)")
if pat == "" and patgrp then pat = patgrp end
return map_act[sub(pat, 1, 1)](ctx, name, pat)
end
-- Get a pattern from an opcode map and dispatch to handler.
local function dispatchmap(ctx, opcmap)
local pos = ctx.pos
local opat = opcmap[byte(ctx.code, pos, pos)]
pos = pos + 1
ctx.pos = pos
return dispatch(ctx, opat)
end
-- Map for action codes. The key is the first char after the name.
map_act = {
-- Simple opcodes without operands.
[""] = function(ctx, name, pat)
return putop(ctx, name)
end,
-- Operand size chars fall right through.
B = putpat, W = putpat, D = putpat, Q = putpat,
V = putpat, U = putpat, T = putpat,
M = putpat, X = putpat, P = putpat,
F = putpat, G = putpat,
-- Collect prefixes.
[":"] = function(ctx, name, pat)
ctx[pat == ":" and name or sub(pat, 2)] = name
if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes.
end,
-- Chain to special handler specified by name.
["*"] = function(ctx, name, pat)
return map_act[name](ctx, name, sub(pat, 2))
end,
-- Use named subtable for opcode group.
["!"] = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2))
end,
-- o16,o32[,o64] variants.
sz = function(ctx, name, pat)
if ctx.o16 then ctx.o16 = false
else
pat = match(pat, ",(.*)")
if ctx.rexw then
local p = match(pat, ",(.*)")
if p then pat = p; ctx.rexw = false end
end
end
pat = match(pat, "^[^,]*")
return dispatch(ctx, pat)
end,
-- Two-byte opcode dispatch.
opc2 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc2)
end,
-- Three-byte opcode dispatch.
opc3 = function(ctx, name, pat)
return dispatchmap(ctx, map_opc3[pat])
end,
-- VMX/SVM dispatch.
vm = function(ctx, name, pat)
return dispatch(ctx, map_opcvm[ctx.mrm])
end,
-- Floating point opcode dispatch.
fp = function(ctx, name, pat)
local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end
local rm = mrm%8
local idx = pat*8 + ((mrm-rm)/8)%8
if mrm >= 192 then idx = idx + 64 end
local opat = map_opcfp[idx]
if type(opat) == "table" then opat = opat[rm+1] end
return dispatch(ctx, opat)
end,
-- REX prefix.
rex = function(ctx, name, pat)
if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed.
for p in gmatch(pat, ".") do ctx["rex"..p] = true end
ctx.rex = true
end,
-- Special case for nop with REX prefix.
nop = function(ctx, name, pat)
return dispatch(ctx, ctx.rex and pat or "nop")
end,
}
------------------------------------------------------------------------------
-- Disassemble a block of code.
local function disass_block(ctx, ofs, len)
if not ofs then ofs = 0 end
local stop = len and ofs+len or #ctx.code
ofs = ofs + 1
ctx.start = ofs
ctx.pos = ofs
ctx.stop = stop
ctx.imm = nil
ctx.mrm = false
clearprefixes(ctx)
while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end
if ctx.pos ~= ctx.start then incomplete(ctx) end
end
-- Extended API: create a disassembler context. Then call ctx:disass(ofs, len).
local function create(code, addr, out)
local ctx = {}
ctx.code = code
ctx.addr = (addr or 0) - 1
ctx.out = out or io.write
ctx.symtab = {}
ctx.disass = disass_block
ctx.hexdump = 16
ctx.x64 = false
ctx.map1 = map_opc1_32
ctx.aregs = map_regs.D
return ctx
end
local function create64(code, addr, out)
local ctx = create(code, addr, out)
ctx.x64 = true
ctx.map1 = map_opc1_64
ctx.aregs = map_regs.Q
return ctx
end
-- Simple API: disassemble code (a string) at address and output via out.
local function disass(code, addr, out)
create(code, addr, out):disass()
end
local function disass64(code, addr, out)
create64(code, addr, out):disass()
end
-- Return register name for RID.
local function regname(r)
if r < 8 then return map_regs.D[r+1] end
return map_regs.X[r-7]
end
local function regname64(r)
if r < 16 then return map_regs.Q[r+1] end
return map_regs.X[r-15]
end
-- Public module functions.
return {
create = create,
create64 = create64,
disass = disass,
disass64 = disass64,
regname = regname,
regname64 = regname64
}
| mit |
Lautitia/newfies-dialer | lua/libs/uuid4.lua | 12 | 3046 | --[[
The MIT License (MIT)
Copyright (c) 2012 Toby Jennings
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 M = {}
-----
math.randomseed( os.time() )
math.random()
-----
local function num2bs(num)
local _mod = math.fmod or math.mod
local _floor = math.floor
--
local result = ""
if(num == 0) then return "0" end
while(num > 0) do
result = _mod(num,2) .. result
num = _floor(num*0.5)
end
return result
end
--
local function bs2num(num)
local _sub = string.sub
local index, result = 0, 0
if(num == "0") then return 0; end
for p=#num,1,-1 do
local this_val = _sub( num, p,p )
if this_val == "1" then
result = result + ( 2^index )
end
index=index+1
end
return result
end
--
local function padbits(num,bits)
if #num == bits then return num end
if #num > bits then print("too many bits") end
local pad = bits - #num
for i=1,pad do
num = "0" .. num
end
return num
end
--
local function getUUID()
local _rnd = math.random
local _fmt = string.format
--
_rnd()
--
local time_low_a = _rnd(0, 65535)
local time_low_b = _rnd(0, 65535)
--
local time_mid = _rnd(0, 65535)
--
local time_hi = _rnd(0, 4095 )
time_hi = padbits( num2bs(time_hi), 12 )
local time_hi_and_version = bs2num( "0100" .. time_hi )
--
local clock_seq_hi_res = _rnd(0,63)
clock_seq_hi_res = padbits( num2bs(clock_seq_hi_res), 6 )
clock_seq_hi_res = "10" .. clock_seq_hi_res
--
local clock_seq_low = _rnd(0,255)
clock_seq_low = padbits( num2bs(clock_seq_low), 8 )
--
local clock_seq = bs2num(clock_seq_hi_res .. clock_seq_low)
--
local node = {}
for i=1,6 do
node[i] = _rnd(0,255)
end
--
local guid = ""
guid = guid .. padbits(_fmt("%X",time_low_a), 4)
guid = guid .. padbits(_fmt("%X",time_low_b), 4) .. "-"
guid = guid .. padbits(_fmt("%X",time_mid), 4) .. "-"
guid = guid .. padbits(_fmt("%X",time_hi_and_version), 4) .. "-"
guid = guid .. padbits(_fmt("%X",clock_seq), 4) .. "-"
--
for i=1,6 do
guid = guid .. padbits(_fmt("%X",node[i]), 2)
end
--
return guid
end
--
M.getUUID = getUUID
return M | mpl-2.0 |
cogwerkz/DiabolicUI | locale/locale-esES.lua | 2 | 1325 | local _, Engine = ...
local L = Engine:NewLocale("esES")
if not L then return end
-- actionbar module
---------------------------------------------------------------------
-- keybinds
L["Alt"] = "A"
L["Ctrl"] = "C"
L["Shift"] = "S"
L["NumPad"] = "N"
L["Backspace"] = "BS"
L["Button1"] = "B1"
L["Button2"] = "B2"
L["Button3"] = "B3"
L["Button4"] = "B4"
L["Button5"] = "B5"
L["Button6"] = "B6"
L["Button7"] = "B7"
L["Button8"] = "B8"
L["Button9"] = "B9"
L["Button10"] = "B10"
L["Button11"] = "B11"
L["Button12"] = "B12"
L["Button13"] = "B13"
L["Button14"] = "B14"
L["Button15"] = "B15"
L["Button16"] = "B16"
L["Button17"] = "B17"
L["Button18"] = "B18"
L["Button19"] = "B19"
L["Button20"] = "B20"
L["Button21"] = "B21"
L["Button22"] = "B22"
L["Button23"] = "B23"
L["Button24"] = "B24"
L["Button25"] = "B25"
L["Button26"] = "B26"
L["Button27"] = "B27"
L["Button28"] = "B28"
L["Button29"] = "B29"
L["Button30"] = "B30"
L["Button31"] = "B31"
L["Capslock"] = "Cp"
L["Clear"] = "Cl"
L["Delete"] = "Del"
L["End"] = "Fin"
L["Home"] = "Ini"
L["Insert"] = "Ins"
L["Mouse Wheel Down"] = "AW"
L["Mouse Wheel Up"] = "RW"
L["Num Lock"] = "NL"
L["Page Down"] = "AP"
L["Page Up"] = "RP"
L["Scroll Lock"] = "SL"
L["Spacebar"] = "Sp"
L["Tab"] = "Tb"
L["Down Arrow"] = "Ar"
L["Left Arrow"] = "Ab"
L["Right Arrow"] = "Iz"
L["Up Arrow"] = "De"
| mit |
Noneatme/mta-lostresources | [gameplay]/megakills/server/CMegaKills.lua | 1 | 6229 | -- #######################################
-- ## Project: MTA Mega Kills ##
-- ## For MTA: San Andreas ##
-- ## Name: MegaKills.lua ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
MegaKills = {};
MegaKills.__index = MegaKills;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///// Returns: Object //////
-- ///////////////////////////////
function MegaKills:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// PlayerKill //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MegaKills:PlayerKill(ammo, killer)
if(killer) and (getElementType(killer) == "player") then
local player = source;
-- Reset player stats, player killed
self.playerKillCount[player] = 0;
self.playerTempCount[player] = 0;
-- Set killer stats
if not(self.playerKillCount[killer]) then
self.playerKillCount[killer] = 0;
self.playerTempCount[killer] = 0;
self.playerTickCount[killer] = getTickCount();
self.playerMegaKill[killer] = "-";
end
self.playerKillCount[killer] = self.playerKillCount[killer]+1;
self.playerTempCount[killer] = self.playerTempCount[killer]+1;
if(getTickCount()-self.playerTickCount[killer] > 5000) then
self.playerTempCount[killer] = 0;
end
self.playerTickCount[killer] = getTickCount();
self:UpdatePlayerTitle(killer, source);
end
end
-- ///////////////////////////////
-- ///// UpdatePlayerTitle //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MegaKills:UpdatePlayerTitle(player, victim)
local temp_kills = self.playerTempCount[player];
local rampage_kills = #getElementsByType("player")-1;
local kills = self.playerKillCount[player];
local old_megakill = self.playerMegaKill[player];
-- FIRSTBLOOD --
if(self.firstBloodDone == false) then
self:AnnounceFirstBlood(player, victim);
self.firstBloodDone = true;
end
-- SERIEN --
local old_megakill = self.playerMegaKill[player];
if(temp_kills == 2) then
self.playerMegaKill[player] = "DOUBLE_KILL";
elseif(temp_kills == 3) then
self.playerMegaKill[player] = "TRIPPLE_KILL";
end
-- Mega kills erst ab 5 spieler, da man diese boni schon bekommen wuerde
-- Wenn man die Haelfter der Spieler killt
-- Und bei 2-3 spielern ist das nicht viel.
if(rampage_kills >= 5) then
if(temp_kills >= rampage_kills/2) then
self.playerMegaKill[player] = "MEGA_KILL";
elseif(temp_kills == rampage_kills-1) then
self.playerMegaKill[player] = "ULTRA_KILL";
elseif(temp_kills >= rampage_kills) then
self.playerMegaKill[player] = "RAMPAGE";
end
end
-- KILLS --
local old_killstreak = self.playerKillStreak[player];
if(self.playerMegaKill[player] ~= "-") then
if(kills == 3) then
self.playerKillStreak[player] = "KILLING_SPREE";
elseif(kills == 4) then
self.playerKillStreak[player] = "DOMINATING";
elseif(kills == 6) then
self.playerKillStreak[player] = "UNSTOPPABLE";
elseif(kills == 7) then
self.playerKillStreak[player] = "WICKED_SICK";
elseif(kills == 8) then
self.playerKillStreak[player] = "MONSTER_KILL";
elseif(kills == 9) then
self.playerKillStreak[player] = "GODLIKE";
elseif(kills > 9) then
self.playerKillStreak[player] = "HOLY_SHIT";
end
end
-- kill streak
local kill_streak
local mega_kill
if(self.playerKillStreak[player] ~= old_killstreak) then
kill_streak = true;
outputChatBox("Player: "..getPlayerName(player).." is on a "..self.playerKillStreak[player].." kill streak!", getRootElement(), 0, 255, 255)
end
if(kills > 5) then
self.playerOwnage[player] = true;
else
self.playerOwnage[player] = false;
end
-- ANNOUNCE
if(old_megakill == self.playerMegaKill[player]) then
-- Do Nothing
else
mega_kill = true;
outputChatBox("Player: "..getPlayerName(player).." has a "..self.playerMegaKill[player].."!", getRootElement(), 0, 255, 255)
end
triggerClientEvent(getRootElement(), "onPlayerKillingSpree", getRootElement(), player, mega_kill, self.playerMegaKill[player], kill_streak, self.playerKillStreak[player]);
end
-- ///////////////////////////////
-- ///// AnnounceFirstBlood //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MegaKills:AnnounceFirstBlood(player)
-- FIRST BLOOD!
triggerClientEvent(getRootElement(), "onPlayerFirstBlood", getRootElement(), player);
end
-- ///////////////////////////////
-- ///// ResetVars() //////
-- ///// Returns: void //////
-- ///// Resets first blood and player variables //////
-- ///////////////////////////////
function MegaKills:ResetVars()
this.firstBloodDone = false;
-- Instanzen
self.playerKillCount = {}; -- All in count for killing sprees
self.playerTempCount = {}; -- Temp count for mega kills
self.playerMegaKill = {}; -- Player mega kill
self.playerKillStreak = {}; -- Player kill streak
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MegaKills:Constructor(...)
outputChatBox("[MegaKills] Geladen!", getRootElement(), 255, 255, 0)
-- Instanzen
self.playerKillCount = {}; -- All in count for killing sprees
self.playerTempCount = {}; -- Temp count for mega kills
self.playerTickCount = {}; -- Player Tick Count
self.playerMegaKill = {}; -- Player mega kill
self.playerKillStreak = {}; -- Player kill streak
self.playerOwnage = {}; -- Player Ownage? (5+ kills in a row)
self.firstBloodDone = false; -- First Blood
-- Funktionen
self.playerKillFunc = function(...) self:PlayerKill(...) end;
self.resetKillStreak = function(player) self:ResetKillSteak(player) end;
-- Events
--addEventHandler("onPedWasted", getRootElement(), self.playerKillFunc);
addEventHandler("onPlayerWasted", getRootElement(), self.playerKillFunc);
outputDebugString("[CALLING] MegaKills: Constructor");
end
-- EVENT HANDLER --
| gpl-2.0 |
LuaDist2/luaposix | specs/spec_helper.lua | 1 | 3666 | local unpack = table.unpack or unpack
if os.getenv "installcheck" == nil then
-- Unless we're running inside `make installcheck`, add the dev-tree
-- directories to the module search paths.
local std = require "specl.std"
local top_srcdir = os.getenv "top_srcdir" or "."
local top_builddir = os.getenv "top_builddir" or "."
package.path = std.package.normalize (
top_builddir .. "/lib/?.lua",
top_srcdir .. "/lib/?.lua",
top_builddir .. "/lib/?/init.lua",
top_srcdir .. "/lib/?/init.lua",
package.path)
package.cpath = std.package.normalize (
top_builddir .. "/ext/posix/.libs/?.so",
top_srcdir .. "/ext/posix/.libs/?.so",
top_builddir .. "/ext/posix/_libs/?.dll",
top_srcdir .. "/ext/posix/_libs/?.dll",
package.cpath)
end
local bit = require "bit32"
band, bnot, bor = bit.band, bit.bnot, bit.bor
badargs = require "specl.badargs"
hell = require "specl.shell"
posix = require "posix"
-- Allow user override of LUA binary used by hell.spawn, falling
-- back to environment PATH search for "lua" if nothing else works.
local LUA = os.getenv "LUA" or "lua"
-- Easily check for std.object.type compatibility.
function prototype (o)
return (getmetatable (o) or {})._type or io.type (o) or type (o)
end
local function mkscript (code)
local f = os.tmpname ()
local h = io.open (f, "w")
h:write (code)
h:close ()
return f
end
--- Run some Lua code with the given arguments and input.
-- @string code valid Lua code
-- @tparam[opt={}] string|table arg single argument, or table of
-- arguments for the script invocation
-- @string[opt] stdin standard input contents for the script process
-- @treturn specl.shell.Process|nil status of resulting process if
-- execution was successful, otherwise nil
function luaproc (code, arg, stdin)
local f = mkscript (code)
if type (arg) ~= "table" then arg = {arg} end
local cmd = {LUA, f, unpack (arg)}
-- inject env and stdin keys separately to avoid truncating `...` in
-- cmd constructor
cmd.stdin = stdin
cmd.env = {
LUA = LUA,
LUA_CPATH = package.cpath,
LUA_PATH = package.path,
LUA_INIT = "",
LUA_INIT_5_2 = "",
LUA_INIT_5_3 = "",
PATH = os.getenv "PATH"
}
local proc = hell.spawn (cmd)
os.remove (f)
return proc
end
-- Use a consistent template for all temporary files.
TMPDIR = posix.getenv ("TMPDIR") or "/tmp"
template = TMPDIR .. "/luaposix-test-XXXXXX"
-- Allow comparison against the error message of a function call result.
function Emsg (_, msg) return msg or "" end
-- Collect stdout from a shell command, and strip surrounding whitespace.
function cmd_output (cmd)
return hell.spawn (cmd).output:gsub ("^%s+", ""):gsub ("%s+$", "")
end
local st = require "posix.sys.stat"
local stat, S_ISDIR = st.lstat, st.S_ISDIR
-- Recursively remove a temporary directory.
function rmtmp (dir)
for f in posix.files (dir) do
if f ~= "." and f ~= ".." then
local path = dir .. "/" .. f
if S_ISDIR (stat (path).st_mode) ~= 0 then
rmtmp (path)
else
os.remove (path)
end
end
end
os.remove (dir)
end
-- Create an empty file at PATH.
function touch (path) io.open (path, "w+"):close () end
-- Format a bad argument type error.
local function typeerrors (fname, i, want, field, got)
return {
badargs.format ("?", i, want, field, got), -- LuaJIT
badargs.format (fname, i, want, field, got), -- PUC-Rio
}
end
function init (M, fname)
return M[fname], function (...) return typeerrors (fname, ...) end
end
pack = table.pack or function(...)
return {n=select("#", ...), ...}
end
| mit |
liuxuezhan/skynet | lualib/skynet/sharemap.lua | 30 | 1503 | local stm = require "skynet.stm"
local sprotoloader = require "sprotoloader"
local sproto = require "sproto"
local setmetatable = setmetatable
local sharemap = {}
function sharemap.register(protofile)
-- use global slot 0 for type define
sprotoloader.register(protofile, 0)
end
local sprotoobj
local function loadsp()
if sprotoobj == nil then
sprotoobj = sprotoloader.load(0)
end
return sprotoobj
end
function sharemap:commit()
self.__obj(sprotoobj:encode(self.__typename, self.__data))
end
function sharemap:copy()
return stm.copy(self.__obj)
end
function sharemap.writer(typename, obj)
local sp = loadsp()
obj = obj or {}
local stmobj = stm.new(sp:encode(typename,obj))
local ret = {
__typename = typename,
__obj = stmobj,
__data = obj,
commit = sharemap.commit,
copy = sharemap.copy,
}
return setmetatable(ret, { __index = obj, __newindex = obj })
end
local function decode(msg, sz, self)
local data = self.__data
for k in pairs(data) do
data[k] = nil
end
return sprotoobj:decode(self.__typename, msg, sz, data)
end
function sharemap:update()
return self.__obj(decode, self)
end
function sharemap.reader(typename, stmcpy)
local sp = loadsp()
local stmobj = stm.newcopy(stmcpy)
local _, data = stmobj(function(msg, sz)
return sp:decode(typename, msg, sz)
end)
local obj = {
__typename = typename,
__obj = stmobj,
__data = data,
update = sharemap.update,
}
return setmetatable(obj, { __index = data, __newindex = error })
end
return sharemap
| mit |
mms92/wire | lua/entities/gmod_wire_addressbus.lua | 9 | 2451 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Address Bus"
ENT.WireDebugName = "AddressBus"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetUseType(SIMPLE_USE)
self.Outputs = Wire_CreateOutputs(self, {"Memory"})
self.Inputs = Wire_CreateInputs(self,{"Memory1","Memory2","Memory3","Memory4"})
self.DataRate = 0
self.DataBytes = 0
self.Memory = {}
self.MemStart = {}
self.MemEnd = {}
for i = 1,4 do
self.Memory[i] = nil
self.MemStart[i] = 0
self.MemEnd[i] = 0
end
self:SetOverlayText("Data rate: 0 bps")
end
function ENT:Setup(Mem1st, Mem2st, Mem3st, Mem4st, Mem1sz, Mem2sz, Mem3sz, Mem4sz)
local starts = {Mem1st,Mem2st,Mem3st,Mem4st}
local sizes = {Mem1sz,Mem2sz,Mem3sz,Mem4sz}
for i = 1,4 do
starts[i] = tonumber(starts[i]) or 0
sizes[i] = tonumber(sizes[i]) or 0
self.MemStart[i] = starts[i]
self.MemEnd[i] = starts[i] + sizes[i] - 1
self["Mem"..i.."st"] = starts[i]
self["Mem"..i.."sz"] = sizes[i]
end
end
function ENT:Think()
self.BaseClass.Think(self)
self.DataRate = self.DataBytes
self.DataBytes = 0
Wire_TriggerOutput(self, "Memory", self.DataRate)
self:SetOverlayText("Data rate: "..math.floor(self.DataRate*2).." bps")
self:NextThink(CurTime()+0.5)
return true
end
function ENT:ReadCell(Address)
for i = 1,4 do
if (Address >= self.MemStart[i]) and (Address <= self.MemEnd[i]) then
if self.Memory[i] then
if self.Memory[i].ReadCell then
self.DataBytes = self.DataBytes + 1
local val = self.Memory[i]:ReadCell(Address - self.MemStart[i])
return val or 0
end
else
return 0
end
end
end
return nil
end
function ENT:WriteCell(Address, value)
local res = false
for i = 1,4 do
if (Address >= self.MemStart[i]) and (Address <= self.MemEnd[i]) then
if self.Memory[i] then
if self.Memory[i].WriteCell then
self.Memory[i]:WriteCell(Address - self.MemStart[i], value)
end
end
self.DataBytes = self.DataBytes + 1
res = true
end
end
return res
end
function ENT:TriggerInput(iname, value)
for i = 1,4 do
if iname == "Memory"..i then
self.Memory[i] = self.Inputs["Memory"..i].Src
end
end
end
duplicator.RegisterEntityClass("gmod_wire_addressbus", WireLib.MakeWireEnt, "Data", "Mem1st", "Mem2st", "Mem3st", "Mem4st", "Mem1sz", "Mem2sz", "Mem3sz", "Mem4sz")
| apache-2.0 |
tomasguisasola/luaexpat | src/lxp/totable.lua | 1 | 2800 | -- See Copyright Notice in license.html
-- Based on Luiz Henrique de Figueiredo's lxml:
-- http://www.tecgraf.puc-rio.br/~lhf/ftp/lua/#lxml
local lxp = require "lxp"
local table = require"table"
local tinsert, tremove = table.insert, table.remove
local assert, pairs, tostring, type = assert, pairs, tostring, type
-- auxiliary functions -------------------------------------------------------
local function starttag (p, tag, attr)
local stack = p:getcallbacks().stack
local newelement = {[0] = tag}
for i = 1, #attr do
local attrname = attr[i]
local attrvalue = attr[attrname]
newelement[attrname] = attrvalue
end
tinsert(stack, newelement)
end
local function endtag (p, tag)
local stack = p:getcallbacks().stack
local element = tremove(stack)
assert(element[0] == tag, "Error while closing element: table[0] should be `"..tostring(tag).."' but is `"..tostring(element[0]).."'")
local level = #stack
tinsert(stack[level], element)
end
local function text (p, txt)
local stack = p:getcallbacks().stack
local element = stack[#stack]
local n = #element
if type(element[n]) == "string" and n > 0 then
element[n] = element[n] .. txt
else
tinsert(element, txt)
end
end
-- main function -------------------------------------------------------------
local function parse (o)
local c = {
StartElement = starttag,
EndElement = endtag,
CharacterData = text,
_nonstrict = true,
stack = {{}},
}
local p = lxp.new(c)
if type(o) == "string" then
local status, err, line, col, pos = p:parse(o)
if not status then return nil, err, line, col, pos end
else
for l in pairs(o) do
local status, err, line, col, pos = p:parse(l)
if not status then return nil, err, line, col, pos end
end
end
local status, err, line, col, pos = p:parse() -- close document
if not status then return nil, err, line, col, pos end
p:close()
return c.stack[1][1]
end
-- utility functions ---------------------------------------------------------
local function compact (t) -- remove empty entries
local n = 0
for i = 1, #t do
local v = t[i]
if v then
n = n+1
if n ~= i then
t[n] = v
t[i] = nil
end
else
t[i] = nil
end
end
end
local function clean (t) -- remove empty strings
for i = 1, #t do
local v = t[i]
local tv = type(v)
if tv == "table" then
clean (v)
elseif tv == "string" and v:match"^%s*$" then
t[i] = false
end
end
compact (t)
end
local function torecord (t) -- move 1-value subtables to table entries
for i = 1, #t do
local v = t[i]
if type(v) == "table" then
if #v == 1 and type(v[1]) == "string" and t[v[0]] == nil then
t[v[0]] = v[1]
t[i] = false
else
torecord (v)
end
end
end
compact (t)
end
return {
clean = clean,
compact = compact,
parse = parse,
torecord = torecord,
}
| mit |
sk89q/PlayX | src/PlayX/lua/playx/client/vgui/PlayXBrowser.lua | 2 | 2578 | -- PlayX
-- Copyright (c) 2009, 2010 sk89q <http://www.sk89q.com>
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- $Id$
local PANEL = {}
function PANEL:Init()
self.Chrome = vgui.Create("DHTMLControls", self);
self.Chrome:Dock(TOP)
self.Chrome.HomeURL = "http://navigator.playx.sk89q.com/"
end
function PANEL:OpeningVideo(provider, uri)
end
function PANEL:Open(provider, uri)
MsgN("PlayXBrowser: Requested to open <" .. provider .. "> / <" .. uri .. ">")
PlayX.RequestOpenMedia(provider, uri, 0, false, GetConVar("playx_use_jw"):GetBool(),
GetConVar("playx_ignore_length"):GetBool())
self:OpeningVideo(provider, uri)
end
function PANEL:Paint()
if not self.Started then
self.Started = true
self.HTML = vgui.Create("HTML", self)
self.HTML:Dock(FILL)
self.Chrome:SetHTML(self.HTML)
local oldOpenURL = self.HTML.OpeningURL
self.HTML.OpeningURL = function(_, url, target, postdata)
local activity, value = url:match("^playx://([^/]+)/(.*)$")
if activity and value then
value = playxlib.URLUnescape(value)
if activity == "open" then
self:Open("", value)
elseif activity == "open-provider" then
local provider, uri = value:match("^([^/]+)/(.*)$")
self:Open(provider, uri)
end
return true
end
local value = url:match("youtube.*v=([^&]+)")
if value then
self:Open("", "http://www.youtube.com/watch?v=" .. value)
return true
end
oldOpenURL(_, url, target, postdata)
end
self.HTML:OpenURL(self.Chrome.HomeURL);
self:InvalidateLayout()
end
end
vgui.Register("PlayXBrowser", PANEL, "Panel")
| lgpl-3.0 |
liuxuezhan/skynet | test/testbson.lua | 29 | 1541 | local bson = require "bson"
local sub = bson.encode_order( "hello", 1, "world", 2 )
do
-- check decode encode_order
local d = bson.decode(sub)
assert(d.hello == 1 )
assert(d.world == 2 )
end
local function tbl_next(...)
print("--- next.a", ...)
local k, v = next(...)
print("--- next.b", k, v)
return k, v
end
local function tbl_pairs(obj)
return tbl_next, obj.__data, nil
end
local obj_a = {
__data = {
["1"] = 2,
["3"] = 4,
["5"] = 6,
}
}
setmetatable(
obj_a,
{
__index = obj_a.__data,
__pairs = tbl_pairs,
}
)
local obj_b = {
__data = {
["7"] = 8,
["9"] = 10,
["11"] = obj_a,
}
}
setmetatable(
obj_b,
{
__index = obj_b.__data,
__pairs = tbl_pairs,
}
)
local metaarray = setmetatable({ n = 5 }, {
__len = function(self) return self.n end,
__index = function(self, idx) return tostring(idx) end,
})
b = bson.encode {
a = 1,
b = true,
c = bson.null,
d = { 1,2,3,4 },
e = bson.binary "hello",
f = bson.regex ("*","i"),
g = bson.regex "hello",
h = bson.date (os.time()),
i = bson.timestamp(os.time()),
j = bson.objectid(),
k = { a = false, b = true },
l = {},
m = bson.minkey,
n = bson.maxkey,
o = sub,
p = 2^32-1,
q = obj_b,
r = metaarray,
}
print "\n[before replace]"
t = b:decode()
for k, v in pairs(t) do
print(k,type(v))
end
for k,v in ipairs(t.r) do
print(k,v)
end
b:makeindex()
b.a = 2
b.b = false
b.h = bson.date(os.time())
b.i = bson.timestamp(os.time())
b.j = bson.objectid()
print "\n[after replace]"
t = b:decode()
print("o.hello", bson.type(t.o.hello))
| mit |
AbolDalton/king | plugins/anti_spam.lua | 191 | 5291 | --An empty table for solving multiple kicking problem(thanks to @topkecleon )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is on or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
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'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked")
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked")
end
end
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
AbolDalton/king | plugins/abohava.lua | 2 | 4795 | local function temps(K)
local F = (K*1.8)-459.67
local C = K-273.15
return F,C
end
local function run(msg, matches)
local res = http.request("http://api.openweathermap.org/data/2.5/weather?q="..URL.escape(matches[2]).."&appid=269ed82391822cc692c9afd59f4aabba")
local jtab = JSON.decode(res)
if jtab.name then
if jtab.weather[1].main == "Thunderstorm" then
status = "طوفاني"
elseif jtab.weather[1].main == "Drizzle" then
status = "نمنم باران"
elseif jtab.weather[1].main == "Rain" then
status = "باراني"
elseif jtab.weather[1].main == "Snow" then
status = "برفي"
elseif jtab.weather[1].main == "Atmosphere" then
status = "مه - غباز آلود"
elseif jtab.weather[1].main == "Clear" then
status = "صاف"
elseif jtab.weather[1].main == "Clouds" then
status = "ابري"
elseif jtab.weather[1].main == "Extreme" then
status = "-------"
elseif jtab.weather[1].main == "Additional" then
status = "-------"
else
status = "-------"
end
local F1,C1 = temps(jtab.main.temp)
local F2,C2 = temps(jtab.main.temp_min)
local F3,C3 = temps(jtab.main.temp_max)
send_document(get_receiver(msg), "weather/"..jtab.weather[1].icon..".webp", ok_cb, false)
if jtab.rain then
rain = jtab.rain["3h"].." ميليمتر"
else
rain = "-----"
end
if jtab.snow then
snow = jtab.snow["3h"].." ميليمتر"
else
snow = "-----"
end
today = "هم اکنون دماي هوا در "..jtab.name.."\n"
.." "..C1.."° درجه سانتيگراد (سلسيوس)\n"
.." "..F1.."° فارنهايت\n"
.." "..jtab.main.temp.."° کلوين\n"
.."بوده و هوا "..status.." ميباشد\n\n"
.."حداقل دماي امروز: C"..C2.."° \n"
.."حداکثر دماي امروز: C"..C3.."° \n"
.."رطوبت هوا: "..jtab.main.humidity.."% درصد\n"
.."مقدار ابر آسمان: "..jtab.clouds.all.."% درصد\n"
.."سرعت باد: "..(jtab.wind.speed or "------").."m/s متر بر ثانيه\n"
.."جهت باد: "..(jtab.wind.deg or "------").."° درجه\n"
.."فشار هوا: "..(jtab.main.pressure/1000).." بار (اتمسفر)\n"
.."بارندگي 3ساعت اخير: "..rain.."\n"
.."بارش برف 3ساعت اخير: "..snow.."\n\n"
after = ""
local res = http.request("http://api.openweathermap.org/data/2.5/forecast?q="..URL.escape(matches[2]).."&appid=269ed82391822cc692c9afd59f4aabba")
local jtab = JSON.decode(res)
for i=1,5 do
local F1,C1 = temps(jtab.list[i].main.temp_min)
local F2,C2 = temps(jtab.list[i].main.temp_max)
if jtab.list[i].weather[1].main == "Thunderstorm" then
status = "طوفاني"
elseif jtab.list[i].weather[1].main == "Drizzle" then
status = "نمنم باران"
elseif jtab.list[i].weather[1].main == "Rain" then
status = "باراني"
elseif jtab.list[i].weather[1].main == "Snow" then
status = "برفي"
elseif jtab.list[i].weather[1].main == "Atmosphere" then
status = "مه - غباز آلود"
elseif jtab.list[i].weather[1].main == "Clear" then
status = "صاف"
elseif jtab.list[i].weather[1].main == "Clouds" then
status = "ابري"
elseif jtab.list[i].weather[1].main == "Extreme" then
status = "-------"
elseif jtab.list[i].weather[1].main == "Additional" then
status = "-------"
else
status = "-------"
end
local file = io.open("./file/weatherIcon/"..jtab.list[i].weather[1].icon..".char")
if file then
local file = io.open("./file/weatherIcon/"..jtab.list[i].weather[1].icon..".char", "r")
icon = file:read("*all")
else
icon = ""
end
if i == 1 then
day = "فردا هوا "
elseif i == 2 then
day = "پس فردا هوا "
elseif i == 3 then
day = "3روز بعد هوا "
elseif i == 4 then
day = "4روز بعد هوا "
elseif i == 5 then
day = "5روز بعد هوا "
end
after = after.."- "..day..status.." ميباشد. "..icon.."\n🔺C"..C2.."° \n🔻C"..C1.."° \n"
end
return today.."وضعيت آب و هوا در سه روز آينده:\n"..after.."\n\n@Tele_Mega"
else
return "مکان وارد شده صحيح نيست"
end
end
return {
description = "Weather Status",
usagehtm = '<tr><td align="center">weather شهر</td><td align="right">اين پلاگين به شما اين امکان را ميدهد که به کاملترين شکل ممکن از وضعيت آب و هواي شهر مورد نظر آگاه شويد همپنين اطلاعات آب و هواي پنجج روز آينده نيز اراه ميشود. دقت کنيد نام شهر را لاتين وارد کنيد</td></tr>',
usage = {"weather (city) : وضعيت آب و هوا"},
patterns = {"^[!/]([Ww]eather) (.*)$"},
run = run,
}
| gpl-2.0 |
Noneatme/mta-lostresources | [gamemodes]/Multistunt/main/stunts/server/airport/cars.lua | 1 | 12296 | local liftcar = {}
local car = {} -- einfach so rumstehende
liftcar[1] = createVehicle(451, -1394.716796875, -257.779296875, 25.14368057251, 359.53308105469, 359.99450683594, 50.707397460938) -- Turismo
liftcar[2] = createVehicle(451, -1396.5302734375, -259.9296875, 25.142911911011, 359.53857421875, 0, 49.493408203125) -- Turismo
liftcar[3] = createVehicle(451, -1398.607421875, -262.45703125, 25.144889831543, 359.53308105469, 359.99450683594, 51.13037109375) -- Turismo
liftcar[4] = createVehicle(411, -1400.52734375, -264.9892578125, 25.164575576782, 0, 0, 48.5595703125) -- Infernus
liftcar[5] = createVehicle(411, -1402.6787109375, -267.6474609375, 25.164573669434, 0, 0, 48.158569335938) -- Infernus
liftcar[6] = createVehicle(411, -1404.724609375, -270.05078125, 25.164653778076, 0, 0, 49.202270507813) -- Infernus
liftcar[7] = createVehicle(411, -1406.951171875, -272.5888671875, 25.165079116821, 0, 0, 52.943115234375) -- Infernus
liftcar[8] = createVehicle(480, -1408.955078125, -275.0537109375, 25.209121704102, 359.736328125, 359.99450683594, 47.565307617188) -- Comet
liftcar[9] = createVehicle(480, -1411.0634765625, -277.357421875, 25.209945678711, 359.736328125, 0, 48.619995117188) -- Comet
liftcar[10] = createVehicle(480, -1413.3857421875, -280.0986328125, 25.209503173828, 359.736328125, 0, 49.647216796875) -- Comet
liftcar[11] = createVehicle(480, -1415.3701171875, -282.5673828125, 25.211093902588, 359.74182128906, 0, 53.256225585938) -- Comet
liftcar[12] = createVehicle(480, -1417.8212890625, -285.427734375, 25.211019515991, 359.74182128906, 0, 49.257202148438) -- Comet
car[1] = createVehicle(411, -1404.5380859375, -235.1767578125, 13.875508308411, 0, 0, 328.65051269531) -- Infernus
car[2] = createVehicle(411, -1401.173828125, -237.779296875, 13.875513076782, 0, 0, 322.90466308594) -- Infernus
car[3] = createVehicle(411, -1397.26953125, -241.189453125, 13.8755235672, 0, 0, 326.59606933594) -- Infernus
car[4] = createVehicle(411, -1391.080078125, -245.78125, 13.871929168701, 0.032958984375, 0.06591796875, 324.77233886719) -- Infernus
car[5] = createVehicle(451, -1382.7666015625, -251.50390625, 13.850735664368, 359.53308105469, 359.99450683594, 310.869140625) -- Turismo
car[6] = createVehicle(451, -1379.85546875, -255.2734375, 13.850296020508, 359.53308105469, 0, 320.30090332031) -- Turismo
car[7] = createVehicle(451, -1375.0009765625, -259.3369140625, 13.850509643555, 359.52758789063, 0.032958984375, 316.68640136719) -- Turismo
car[8] = createVehicle(451, -1372.6953125, -262.0517578125, 13.852767944336, 359.50561523438, 359.96154785156, 307.44140625) -- Turismo
car[9] = createVehicle(451, -1369.2998046875, -265.7587890625, 13.855900764465, 359.52758789063, 359.9560546875, 317.52685546875) -- Turismo
car[10] = createVehicle(522, -1340.9697265625, -211.03125, 13.720824241638, 358.99475097656, 359.99450683594, 177.25341796875) -- NRG-500
car[11] = createVehicle(522, -1339.365234375, -211.1865234375, 13.722512245178, 359.23645019531, 359.99450683594, 166.45935058594) -- NRG-500
car[12] = createVehicle(522, -1337.9482421875, -211.52734375, 13.72275352478, 359.02221679688, 0.0054931640625, 164.44885253906) -- NRG-500
car[13] = createVehicle(522, -1336.8818359375, -211.982421875, 13.724202156067, 358.84094238281, 359.99450683594, 155.64331054688) -- NRG-500
car[14] = createVehicle(522, -1335.419921875, -212.0322265625, 13.721248626709, 0.087890625, 359.97253417969, 161.77917480469) -- NRG-500
car[15] = createVehicle(522, -1334.1650390625, -212.3134765625, 13.724352836609, 359.02770996094, 359.99450683594, 163.50952148438) -- NRG-500
car[16] = createVehicle(522, -1328.7333984375, -134.0859375, 13.722295761108, 359.89013671875, 0, 95.707397460938) -- NRG-500
car[17] = createVehicle(522, -1314.3369140625, -135.6015625, 13.702938079834, 357.85217285156, 359.96154785156, 267.61596679688) -- NRG-500
car[18] = createVehicle(522, -1315.0556640625, -125.228515625, 13.713015556335, 358.30810546875, 359.99450683594, 94.50439453125) -- NRG-500
car[19] = createVehicle(522, -1327.8662109375, -126.23828125, 13.741177558899, 358.85192871094, 0, 94.50439453125) -- NRG-500
car[20] = createVehicle(480, -1357.28515625, -158.5849609375, 13.92249584198, 359.74182128906, 0.010986328125, 331.962890625) -- Comet
car[21] = createVehicle(480, -1360.833984375, -151.7216796875, 13.921065330505, 359.73083496094, 0, 297.82287597656) -- Comet
car[22] = createVehicle(480, -1363.2001953125, -148.3916015625, 13.919672966003, 359.73083496094, 359.99450683594, 303.33251953125) -- Comet
car[23] = createVehicle(480, -1364.634765625, -145.728515625, 13.922396659851, 359.74182128906, 359.98901367188, 302.33825683594) -- Comet
car[24] = createVehicle(480, -1366.140625, -143.140625, 13.923365592957, 359.75830078125, 0.010986328125, 299.82788085938) -- Comet
car[25] = createVehicle(480, -1367.583984375, -140.7685546875, 13.921555519104, 359.71984863281, 0, 300.26184082031) -- Comet
car[26] = createVehicle(480, -1369.0361328125, -138.2548828125, 13.920283317566, 359.73083496094, 359.9560546875, 300.44311523438) -- Comet
car[27] = createVehicle(480, -1370.3701171875, -135.4931640625, 13.921028137207, 359.736328125, 0, 298.44360351563) -- Comet
car[28] = createVehicle(480, -1371.9912109375, -132.9296875, 13.922368049622, 359.74182128906, 359.99450683594, 300.7177734375) -- Comet
car[29] = createVehicle(480, -1371.9912109375, -132.9296875, 13.922368049622, 359.74182128906, 0, 300.7177734375) -- Comet
car[30] = createVehicle(541, -1373.798828125, -129.8212890625, 13.773409843445, 359.5166015625, 359.97253417969, 296.52648925781) -- Bullet
car[31] = createVehicle(541, -1374.75, -127.296875, 13.773162841797, 359.50012207031, 359.97253417969, 297.421875) -- Bullet
car[32] = createVehicle(541, -1382.9482421875, -116.9482421875, 13.773177146912, 359.51110839844, 0.0054931640625, 32.025146484375) -- Bullet
car[33] = createVehicle(541, -1387.357421875, -109.46875, 13.773262023926, 359.51110839844, 0, 30.003662109375) -- Bullet
car[34] = createVehicle(541, -1335.8876953125, -24.685546875, 13.773493766785, 359.50561523438, 359.94506835938, 75.833129882813) -- Bullet
car[35] = createVehicle(541, -1324.7158203125, -45.9462890625, 13.773273468018, 359.5166015625, 0.0164794921875, 199.51171875) -- Bullet
car[36] = createVehicle(541, -1321.1142578125, -52.7939453125, 13.773312568665, 359.50561523438, 0, 207.05383300781) -- Bullet
car[37] = createVehicle(444, -1213.6259765625, -123.216796875, 14.517558097839, 0.0604248046875, 359.99450683594, 130.02319335938) -- Monster 1v
car[38] = createVehicle(444, -1221.2041015625, -129.3017578125, 14.519762992859, 0, 0, 128.97399902344) -- Monster 1
car[39] = createVehicle(444, -1210.9326171875, -127.7119140625, 14.515151023865, 0.0054931640625, 359.76928710938, 154.82482910156) -- Monster 1
car[40] = createVehicle(444, -1218.3974609375, -134.787109375, 14.519737243652, 359.96154785156, 0, 134.12658691406) -- Monster 1
car[41] = createVehicle(556, -1207.7412109375, -134.048828125, 14.520263671875, 0.0439453125, 359.97802734375, 154.5556640625) -- Monster 2
car[42] = createVehicle(556, -1201.419921875, -136.7412109375, 14.521766662598, 359.98352050781, 0.0054931640625, 123.29956054688) -- Monster 2
car[43] = createVehicle(556, -1198.4404296875, -142.5341796875, 14.51934337616, 0, 0, 113.71398925781) -- Monster 2
car[44] = createVehicle(556, -1201.875, -150.38671875, 14.522372245789, 0.054931640625, 0.054931640625, 53.827514648438) -- Monster 2
car[45] = createVehicle(539, -1212.4169921875, -140.88671875, 13.516910552979, 359.62097167969, 359.17053222656, 147.26623535156) -- Vortex
car[46] = createVehicle(539, -1209.8603515625, -146.783203125, 13.507345199585, 0.120849609375, 0.120849609375, 154.87426757813) -- Vortex
car[47] = createVehicle(468, -1317.4169921875, -199.7294921875, 13.815145492554, 359.81872558594, 359.99450683594, 78.46435546875) -- Sanchez
car[48] = createVehicle(468, -1325.2041015625, -198.2080078125, 13.814884185791, 0.0274658203125, 359.98901367188, 81.029663085938) -- Sanchez
car[49] = createVehicle(468, -1332.765625, -197.208984375, 13.815965652466, 359.21447753906, 359.99450683594, 82.496337890625) -- Sanchez
car[50] = createVehicle(468, -1336.29296875, -211.4404296875, 13.815237045288, 0.340576171875, 359.96704101563, 258.18969726563) -- Sanchez
car[51] = createVehicle(468, -1340.97265625, -210.06640625, 13.816826820374, 0.6976318359375, 0.010986328125, 259.85961914063) -- Sanchez
car[52] = createVehicle(468, -1322.2548828125, -214.841796875, 13.816783905029, 0.4998779296875, 359.99450683594, 250.42236328125) -- Sanchez
car[53] = createVehicle(468, -1317.3330078125, -216.5908203125, 13.814199447632, 0.4010009765625, 359.99450683594, 250.42236328125) -- Sanchez
car[54] = createVehicle(468, -1310.66796875, -216.7822265625, 13.816697120667, 359.28588867188, 359.99450683594, 337.95043945313) -- Sanchez
car[55] = createVehicle(468, -1372.2197265625, -190.1416015625, 13.815312385559, 359.87365722656, 0.0439453125, 242.17712402344) -- Sanchez
car[56] = createVehicle(468, -1372.1923828125, -188.65234375, 13.815075874329, 359.80224609375, 0, 245.41809082031) -- Sanchez
car[57] = createVehicle(468, -1371.7568359375, -187.7451171875, 13.817624092102, 359.85168457031, 359.98901367188, 242.40234375) -- Sanchez
car[58] = createVehicle(468, -1371.0458984375, -186.7333984375, 13.817604064941, 359.89013671875, 359.96154785156, 245.00610351563) -- Sanchez
car[59] = createVehicle(468, -1370.5869140625, -185.734375, 13.817420005798, 0.0164794921875, 359.9560546875, 239.3701171875) -- Sanchez
car[60] = createVehicle(522, -1376.302734375, -197.564453125, 13.717838287354, 358.98376464844, 359.99450683594, 240.63354492188) -- NRG-500
car[61] = createVehicle(522, -1375.685546875, -196.4736328125, 13.715802192688, 359.27490234375, 0.0054931640625, 240.99609375) -- NRG-500
car[62] = createVehicle(522, -1375.025390625, -195.640625, 13.714548110962, 359.03869628906, 359.97802734375, 247.90649414063) -- NRG-500
car[63] = createVehicle(522, -1374.1728515625, -195.2353515625, 13.720200538635, 359.48364257813, 359.98901367188, 238.32092285156) -- NRG-500
car[64] = createVehicle(522, -1374.2783203125, -193.99609375, 13.728161811829, 359.27490234375, 0, 234.67895507813) -- NRG-500
car[65] = createVehicle(522, -1319.5107421875, -279.419921875, 13.716691017151, 359.51110839844, 0.0164794921875, 12.3486328125) -- NRG-500
car[66] = createVehicle(522, -1318.5595703125, -282.8623046875, 13.720718383789, 0.0494384765625, 359.98352050781, 20.555419921875) -- NRG-500
car[67] = createVehicle(522, -1326.9326171875, -283.9287109375, 13.717542648315, 359.04968261719, 359.99450683594, 48.790283203125) -- NRG-500
car[68] = createVehicle(522, -1323.724609375, -286.5458984375, 13.716648101807, 359.35729980469, 359.97253417969, 49.476928710938) -- NRG-500
car[69] = createVehicle(582, -1338.86328125, -308.0888671875, 14.210793495178, 359.58251953125, 0, 289.33044433594) -- Newsvan
car[70] = createVehicle(582, -1328.5029296875, -304.875, 14.201406478882, 359.44519042969, 0.0714111328125, 289.52270507813) -- Newsvan
car[71] = createVehicle(582, -1318.060546875, -301.0693359375, 14.205302238464, 359.37377929688, 359.86267089844, 290.02258300781) -- Newsvan
car[72] = createVehicle(409, -1323.58984375, -298.921875, 13.947038650513, 359.97802734375, 359.89562988281, 290.9619140625) -- Stretch7
for v = 1, #car, 1 do
setVehicleColor(car[v], math.random(50, 250), math.random(50, 250), math.random(20, 60), 0, 0, 0)
setElementData(car[v], "mv.typ", "Freecar")
setElementData(car[v], "mv.besitzer", "-")
setElementData(car[v], "mv.stuntcar", "airportsf")
toggleVehicleRespawn ( car[v], true )
setVehicleRespawnDelay ( car[v], 5000 )
setVehicleIdleRespawnDelay ( car[v], IdleCarRespawn*1000*60 )
giveVehicleBetterEngine(car[v])
giveVehiclePanzerung(car[v])
end
for v = 1, #liftcar, 1 do
setVehicleColor(liftcar[v], 0, 255, math.random(20, 60), 0, 0, 0)
setElementData(liftcar[v], "mv.typ", "Freecar")
setElementData(liftcar[v], "mv.besitzer", "-")
setElementData(liftcar[v], "mv.stuntcar", "airportsf")
toggleVehicleRespawn ( liftcar[v], true )
setVehicleRespawnDelay ( liftcar[v], 5000 )
setVehicleIdleRespawnDelay ( liftcar[v], IdleCarRespawn*1000*60 )
giveVehicleBetterEngine(liftcar[v])
giveVehiclePanzerung(liftcar[v])
end | gpl-2.0 |
zaully/cr0w13y_rp | crgunshops/server/server_gunshops.lua | 1 | 1975 | carriedWeapons = {}
armory = {}
function TableSize(map)
local count = 0
if map ~= nil then
for _ in pairs(map) do
count = count + 1
end
end
return count
end
local function SavePlayerWeaponInventory(identifier, carried)
local jsonString = '{}'
if TableSize(carried) > 0 then
jsonString = json.encode(carried)
end
debugp(jsonString)
MySQL.Async.execute("update users set cr_carried_weapons=@carried WHERE identifier = @identifier", {
['@carried'] = jsonString,
['@identifier'] = identifier}, function (result)
end)
end
local function StreamWeaponPrices(src)
TriggerClientEvent('cr:receiveWeaponPrices', src, kWeaponPrices)
end
function UpdatePlayerCarriedWeapons(identifier, carried)
for k in pairs(carriedWeapons[identifier]) do
carriedWeapons[identifier][k] = nil
end
for k, v in pairs(carried) do
carriedWeapons[identifier][k] = v
end
SavePlayerWeaponInventory(identifier, carried)
end
AddEventHandler('ws:giveweapons', function(src)
TriggerClientEvent('cr:removeAllWeapons', src)
local identifier = getPlayerIDFromSource(src)
if carriedWeapons[identifier] then
for k, v in pairs(carriedWeapons[identifier]) do
carriedWeapons[identifier][k] = v
TriggerClientEvent('cr:giveAmmo', src, k, v)
end
end
end)
AddEventHandler('cr:playerSignedIn', function(identifier, record, src)
TriggerClientEvent('cr:removeAllWeapons', src)
carriedWeapons[identifier] = {}
if (record.cr_carried_weapons) then
local carried = json.decode(record.cr_carried_weapons)
if carried then
for k, v in pairs(carried) do
carriedWeapons[identifier][k] = v
TriggerClientEvent('cr:giveAmmo', src, k, v)
end
end
end
StreamWeaponPrices(src)
end)
AddEventHandler('cr:playerLoggedOff', function(identifier)
SavePlayerWeaponInventory(identifier, carriedWeapons[identifier])
carriedWeapons[identifier] = {}
end) | mit |
FliPPeh/Gibbous | scheme/builtins/typeconv.lua | 1 | 2727 | local m = {}
local util = require "scheme.util"
local types = require "scheme.types"
local expect = util.expect
local expect_argc = util.expect_argc
local number_new = types.number.new
local char_new = types.char.new
local str_new = types.str.new
local list_new = types.list.new
local bool_new = types.boolean.new
--[[
-- Type stuff
--]]
local function is_type(typ)
return function(self, env, args)
expect_argc(self, 1, #args)
return bool_new(args[1].type == typ)
end
end
for i, t in ipairs{
"symbol",
"pair",
"list",
"number",
"string",
"boolean",
"char",
"procedure",
"port",
"eof-object",
"error"} do
m[t .. "?"] = is_type(t)
end
-- Special functions for input and output ports
m["input-port?"] = function(self, env, args)
expect_argc(self, 1, #args)
return bool_new(args[1].type == "port" and args[1].mode == "r")
end
m["output-port?"] = function(self, env, args)
expect_argc(self, 1, #args)
return bool_new(args[1].type == "port" and args[1].mode == "w")
end
m["type"] = function(self, env, args)
expect_argc(self, 1, #args)
return str_new(args[1].type)
end
m["symbol->string"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "symbol")
return str_new(args[1]:getval())
end
m["string->symbol"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "string")
return env:intern(args[1]:getval())
end
m["list->string"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "list")
local buf = ""
for i, c in ipairs(args[1]:getval()) do
expect(c, "char")
buf = buf .. c:getval()
end
return str_new(buf)
end
m["string->list"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "string")
local ls = {}
for i = 1, #args[1]:getval() do
table.insert(ls, char_new(args[1]:getval():sub(i, i)))
end
return list_new(ls)
end
m["number->string"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "number")
return str_new(tonumber(args[1]:getval()))
end
m["string->number"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "string")
return number_new(tostring(args[1]:getval()))
end
m["char->integer"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "char")
return number_new(args[1]:getval():byte(1))
end
m["integer->char"] = function(self, env, args)
expect_argc(self, 1, #args)
expect(args[1], "number")
return char_new(string.char(args[1]:getval()))
end
return m
| bsd-2-clause |
Team-CC-Corp/JVML-JIT | CCLib/src/java/lang/native/Method.lua | 2 | 4207 | natives["java.lang.reflect.Method"] = natives["java.lang.reflect.Method"] or {}
natives["java.lang.reflect.Method"]["invoke(Ljava/lang/Object;[Ljava/lang/Object;)Ljava/lang/Object;"] = function(this, target, args)
local methodName = toLString(getObjectField(this, "name"))
local class
if target then
class = target[1]
else
local declaringClass = getObjectField(this, "declaringClass")
local className = toLString(getObjectField(declaringClass, "name"))
class = classByName(className)
end
local mt = assert(findMethod(class, methodName), "Couldn't find method: " .. methodName .. " in class: " .. class.name)
-- Check static
assert((target == nil) == (bit.band(mt.acc, METHOD_ACC.STATIC) > 0), "Mismatch in target or static invocation")
local newArgs = {target} -- if target is nil, this array is empty so no work needed there
for i=1, #mt.desc-1 do -- last is return value
local newArg
local v = mt.desc[i]
if v.array_depth == 0 and not v.type:find("^L") then
-- primitive. Time to unbox!
newArg = getObjectField(args[5][i], "value") -- sidestep the need to check each type for the typeValue() call
else
newArg = args[5][i]
end
table.insert(newArgs, newArg)
end
local ret = mt[1](unpack(newArgs))
local retType = mt.desc[#mt.desc]
if retType.array_depth == 0 and not retType.type:find("^L") and retType.type ~= "V" then
-- return type is primitive. Need to box the primitive to return Object
ret = wrapPrimitive(ret, retType.type)
end
return ret
end
natives["java.lang.reflect.Method"]["getAnnotation(Ljava/lang/Class;)Ljava/lang/annotation/Annotation;"] = function(this, annot)
local declaringClass = getObjectField(this, "declaringClass")
local thisClassName = toLString(getObjectField(declaringClass, "name"))
local thisClass = classByName(thisClassName)
local methodName = toLString(getObjectField(this, "name"))
local mt = assert(findMethod(thisClass, methodName), "Couldn't find method: " .. methodName)
local annotClassName = toLString(getObjectField(annot, "name"))
return findMethodAnnotation(mt, classByName(annotClassName))
end
natives["java.lang.reflect.Method"]["getParameterTypes()[Ljava/lang/Class;"] = function(this)
local methodName = toLString(getObjectField(this, "name"))
local declaringClass = getObjectField(this, "declaringClass")
local className = toLString(getObjectField(declaringClass, "name"))
local class = classByName(className)
local mt = assert(findMethod(class, methodName), "Couldn't find method: " .. methodName)
local arr = newArray(getArrayClass("[java.lang.Class;"), #mt.desc - 1)
for i=1, #mt.desc-1 do -- last is return value, first is target
local class
local type = mt.desc[i].type
if type:find("^L") then
class = getJClass(type:gsub("^L", ""):gsub(";$", ""):gsub("/", "."))
elseif type:find("^[") then
class = getJClass(type:gsub("/", "."))
elseif type:find("^B") then
class = getJClass("byte")
elseif type:find("^C") then
class = getJClass("char")
elseif type:find("^D") then
class = getJClass("double")
elseif type:find("^F") then
class = getJClass("float")
elseif type:find("^I") then
class = getJClass("int")
elseif type:find("^J") then
class = getJClass("long")
elseif type:find("^S") then
class = getJClass("short")
elseif type:find("^Z") then
class = getJClass("boolean")
end
arr[5][i] = class
end
return arr
end
natives["java.lang.reflect.Method"]["getParameterCount()I"] = function(this)
local methodName = toLString(getObjectField(this, "name"))
local declaringClass = getObjectField(this, "declaringClass")
local className = toLString(getObjectField(declaringClass, "name"))
local class = classByName(className)
local mt = assert(findMethod(class, methodName), "Couldn't find method: " .. methodName)
return #mt.desc - 1
end | mit |
AbolDalton/king | plugins/op.lua | 1 | 1674 | local function run(msg, matches)
if is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['operator'] then
lock_operator = data[tostring(msg.to.id)]['settings']['operator']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_operator == "yes" then
delete_msg(msg.id, ok_cb, true)
end
end
return {
patterns = {
"شارژ(.*)",
"ایرانسل(.*)",
"irancell(.*)",
"ir-mci(.*)",
"RighTel(.*)",
"همراه اول(.*)",
"رایتل(.*)",
"تالیا.(.*)",
'بسته.(.*)",
"اینترنت.(.*)",
},
run = run
}
local function run(msg, matches)
if is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['operator'] then
lock_operator = data[tostring(msg.to.id)]['settings']['operator']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_operator == "yes" then
delete_msg(msg.id, ok_cb, true)
end
end
return {
patterns = {
"شارژ(.*)",
"ایرانسل(.*)",
"irancell(.*)",
"ir-mci(.*)",
"RighTel(.*)",
"همراه اول(.*)",
"رایتل(.*)",
"تالیا.(.*)",
"بسته.(.*)",
"اینترنت.(.*)",
},
run = run
}
| gpl-2.0 |
Ettercap/ettercap | src/lua/share/third-party/stdlib/mkrockspecs.lua | 12 | 1359 | -- Generate rockspecs from a prototype with variants
require "std"
if select ("#", ...) < 2 then
io.stderr:write "Usage: mkrockspecs PACKAGE VERSION\n"
os.exit ()
end
package_name = select (1, ...)
version = select (2, ...)
function format (x, indent)
indent = indent or ""
if type (x) == "table" then
local s = "{\n"
for i, v in pairs (x) do
if type (i) ~= "number" then
s = s..indent..i.." = "..format (v, indent.." ")..",\n"
end
end
for i, v in ipairs (x) do
s = s..indent..format (v, indent.." ")..",\n"
end
return s..indent:sub (1, -3).."}"
elseif type (x) == "string" then
return string.format ("%q", x)
else
return tostring (x)
end
end
for f, spec in pairs (loadfile ("rockspecs.lua") ()) do
if f ~= "default" then
local specfile = package_name.."-"..(f ~= "" and f:lower ().."-" or "")..version.."-2.rockspec"
h = io.open (specfile, "w")
assert (h)
flavour = f -- a global, visible in loadfile
local specs = loadfile ("rockspecs.lua") () -- reload to get current flavour interpolated
local spec = tree.merge (tree.new (specs.default), tree.new (specs[f]))
local s = ""
for i, v in pairs (spec) do
s = s..i.." = "..format (v, " ").."\n"
end
h:write (s)
h:close ()
os.execute ("luarocks lint " .. specfile)
end
end
| gpl-2.0 |
luadch/luadch | lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| gpl-3.0 |
reesun/redis-2.8 | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
Justinon/LorePlay | unused/LoreChat/LoreChat.lua | 1 | 4775 | local LoreChat = LorePlay
LoreChat.tabName = "|c8c7037LoreChat"
local tabs = {}
--[[ CREATE A FUNCTION FOR SETTINGS ON WHETHER TO ENABLE OR DISABLE ZONE IN LORECHAT TAB ]] --
function LoreChat.UpdateChannelTypesForTab(containerNumber, tabIndex)
-- Recycling English Zone as the Roleplay/LoreChat tab since not popular
tabs[tabIndex].isEnZoneChecked
= IsChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_ZONE_ENGLISH)
tabs[tabIndex].isZoneChecked
= IsChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_ZONE)
tabs[tabIndex].isSayChecked
= IsChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_SAY)
tabs[tabIndex].isTellChecked
= IsChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_WHISPER_INCOMING)
tabs[tabIndex].isYellChecked
= IsChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_YELL)
tabs[tabIndex].isNPCChecked
= IsChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_MONSTER_SAY)
end
function LoreChat.UpdateTabInfo(containerNumber)
local numContainerTabs = GetNumChatContainerTabs(containerNumber)
for tabIndex = 1, numContainerTabs, 1 do
tabs[tabIndex] = {}
tabs[tabIndex].name, tabs[tabIndex].isLocked,
tabs[tabIndex].isInteractable, tabs[tabIndex].isCombatLog,
tabs[tabIndex].areTimestampsEnabled = GetChatContainerTabInfo(1, tabIndex)
LoreChat.UpdateChannelTypesForTab(containerNumber, tabIndex)
end
end
function LoreChat.DoesLoreChatTabExist(containerNumber)
local numContainerTabs = GetNumChatContainerTabs(containerNumber)
-- Basic checks that should be good enough to not conflict with other's addons
for tabIndex = 1, numContainerTabs, 1 do
if (tabs[tabIndex].name == LoreChat.tabName) then
return true
end
end
return false
end
function LoreChat.AddChatChannelSwitch(desiredCommandAlias, existingCommand)
CHAT_SYSTEM.switchLookup[desiredCommandAlias] = CHAT_SYSTEM.switchLookup[existingCommand]
end
--[[ Zone OFF by default, EnZone ON be default]]
function LoreChat.SetLoreChatTabSettings(containerNumber)
local numContainerTabs = GetNumChatContainerTabs(containerNumber)
for tabIndex = 1, numContainerTabs, 1 do
local loreTab = tabs[tabIndex]
if loreTab.name == LoreChat.tabName then
if not loreTab.isEnZoneChecked then
SetChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_ZONE_ENGLISH, true)
end
if loreTab.isZoneChecked then
SetChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_ZONE, false)
end
if not loreTab.isSayChecked then
SetChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_SAY, true)
end
if not loreTab.isTellChecked then
SetChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_WHISPER_INCOMING, true)
end
if not loreTab.isYellChecked then
SetChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_YELL, true)
end
if not loreTab.isNPCChecked then
SetChatContainerTabCategoryEnabled(containerNumber, tabIndex, CHAT_CATEGORY_MONSTER_SAY, true)
end
break
end
end
end
-- Function to enforce certain features for the LoreChat tab, such as EnZone and Say channels being checked
function LoreChat.ConfigureLoreChat(containerNumber)
LoreChat.SetLoreChatTabSettings(containerNumber)
local channelInfo = ZO_ChatSystem_GetChannelInfo()
channelInfo[CHAT_CHANNEL_ZONE_LANGUAGE_1].name = "Roleplay"
--ResetChatCategoryColorToDefault(CHAT_CATEGORY_CODE)
SetChatCategoryColor(CHAT_CATEGORY_ZONE_ENGLISH, .55, .44, .21)
LoreChat.AddChatChannelSwitch("/rp", "/enzone")
LoreChat.AddChatChannelSwitch("/roleplay", "/enzone")
LoreChat.AddChatChannelSwitch("/lorechat", "/enzone")
LoreChat.AddChatChannelSwitch("/loreplay", "/enzone")
end
function LoreChat.ShiftChatTabs(containerNumber)
local numContainerTabs = GetNumChatContainerTabs(containerNumber)
local nextTab
for currTab = (numContainerTabs-1), 1, -1 do
nextTab = (currTab + 1)
-- "Transfer" exchanges tabs, therefore bubbling LoreChat to the front
TransferChatContainerTab(containerNumber, currTab, containerNumber, nextTab)
end
LoreChat.UpdateTabInfo(containerNumber)
end
function LoreChat.CreateLoreChatTab(containerNumber)
AddChatContainerTab(containerNumber, LoreChat.tabName, false)
LoreChat.ShiftChatTabs(containerNumber)
LoreChat.ConfigureLoreChat(containerNumber)
end
function LoreChat.InitializeChat()
-- Passing in 1 to just update the primary chat container for our purposes
LoreChat.UpdateTabInfo(1)
if (not LoreChat.DoesLoreChatTabExist(1)) then
LoreChat.CreateLoreChatTab(1)
elseif(LoreChat.DoesLoreChatTabExist(1)) then
LoreChat.ConfigureLoreChat(1)
end
end
LorePlay = LoreChat | artistic-2.0 |
uzlonewolf/proxmark3 | client/scripts/tnp3dump.lua | 6 | 7183 | local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local lib14a = require('read14a')
local utils = require('utils')
local md5 = require('md5')
local dumplib = require('html_dumplib')
local toys = require('default_toys')
example =[[
script run tnp3dump
script run tnp3dump -n
script run tnp3dump -p
script run tnp3dump -k aabbccddeeff
script run tnp3dump -k aabbccddeeff -n
script run tnp3dump -o myfile
script run tnp3dump -n -o myfile
script run tnp3dump -p -o myfile
script run tnp3dump -k aabbccddeeff -n -o myfile
]]
author = "Iceman"
usage = "script run tnp3dump -k <key> -n -p -o <filename>"
desc =[[
This script will try to dump the contents of a Mifare TNP3xxx card.
It will need a valid KeyA in order to find the other keys and decode the card.
Arguments:
-h : this help
-k <key> : Sector 0 Key A.
-n : Use the nested cmd to find all keys
-p : Use the precalc to find all keys
-o : filename for the saved dumps
]]
local RANDOM = '20436F707972696768742028432920323031302041637469766973696F6E2E20416C6C205269676874732052657365727665642E20'
local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
local DEBUG = false -- the debug flag
local numBlocks = 64
local numSectors = 16
---
-- A debug printout-function
function dbg(args)
if not DEBUG then
return
end
if type(args) == "table" then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print("###", args)
end
end
---
-- This is only meant to be used when errors occur
function oops(err)
print("ERROR: ",err)
end
---
-- Usage help
function help()
print(desc)
print("Example usage")
print(example)
end
--
-- Exit message
function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
local function readdumpkeys(infile)
t = infile:read("*all")
len = string.len(t)
local len,hex = bin.unpack(("H%d"):format(len),t)
return hex
end
local function waitCmd()
local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT)
if response then
local count,cmd,arg0 = bin.unpack('LL',response)
if(arg0==1) then
local count,arg1,arg2,data = bin.unpack('LLH511',response,count)
return data:sub(1,32)
else
return nil, "Couldn't read block.."
end
end
return nil, "No response from device"
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
local keyA
local cmd
local err
local useNested = false
local usePreCalc = false
local cmdReadBlockString = 'hf mf rdbl %d A %s'
local input = "dumpkeys.bin"
local outputTemplate = os.date("toydump_%Y-%m-%d_%H%M%S");
-- Arguments for the script
for o, a in getopt.getopt(args, 'hk:npo:') do
if o == "h" then return help() end
if o == "k" then keyA = a end
if o == "n" then useNested = true end
if o == "p" then usePreCalc = true end
if o == "o" then outputTemplate = a end
end
-- validate input args.
keyA = keyA or '4b0b20107ccb'
if #(keyA) ~= 12 then
return oops( string.format('Wrong length of write key (was %d) expected 12', #keyA))
end
-- Turn off Debug
local cmdSetDbgOff = "hf mf dbg 0"
core.console( cmdSetDbgOff)
result, err = lib14a.read14443a(false, true)
if not result then
return oops(err)
end
core.clearCommandBuffer()
-- Show tag info
print((' Found tag %s'):format(result.name))
dbg(('Using keyA : %s'):format(keyA))
--Trying to find the other keys
if useNested then
core.console( ('hf mf nested 1 0 A %s d'):format(keyA) )
end
core.clearCommandBuffer()
local akeys = ''
if usePreCalc then
local pre = require('precalc')
akeys = pre.GetAll(result.uid)
else
print('Loading dumpkeys.bin')
local hex, err = utils.ReadDumpFile(input)
if not hex then
return oops(err)
end
akeys = hex:sub(0,12*16)
end
-- Read block 0
cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = 0,arg2 = 0,arg3 = 0, data = keyA}
err = core.SendCommand(cmd:getBytes())
if err then return oops(err) end
local block0, err = waitCmd()
if err then return oops(err) end
-- Read block 1
cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = 1,arg2 = 0,arg3 = 0, data = keyA}
err = core.SendCommand(cmd:getBytes())
if err then return oops(err) end
local block1, err = waitCmd()
if err then return oops(err) end
local tmpHash = block0..block1..'%02x'..RANDOM
local key
local pos = 0
local blockNo
local blocks = {}
print('Reading card data')
core.clearCommandBuffer()
-- main loop
io.write('Reading blocks > ')
for blockNo = 0, numBlocks-1, 1 do
if core.ukbhit() then
print("aborted by user")
break
end
pos = (math.floor( blockNo / 4 ) * 12)+1
key = akeys:sub(pos, pos + 11 )
cmd = Command:new{cmd = cmds.CMD_MIFARE_READBL, arg1 = blockNo ,arg2 = 0,arg3 = 0, data = key}
local err = core.SendCommand(cmd:getBytes())
if err then return oops(err) end
local blockdata, err = waitCmd()
if err then return oops(err) end
if blockNo%4 ~= 3 then
if blockNo < 8 then
-- Block 0-7 not encrypted
blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata)
else
-- blocks with zero not encrypted.
if string.find(blockdata, '^0+$') then
blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,blockdata)
else
local baseStr = utils.ConvertHexToAscii(tmpHash:format(blockNo))
local key = md5.sumhexa(baseStr)
local aestest = core.aes128_decrypt(key, blockdata)
local hex = utils.ConvertAsciiToBytes(aestest)
hex = utils.ConvertBytesToHex(hex)
blocks[blockNo+1] = ('%02d :: %s'):format(blockNo,hex)
io.write(blockNo..',')
end
end
else
-- Sectorblocks, not encrypted
blocks[blockNo+1] = ('%02d :: %s%s'):format(blockNo,key,blockdata:sub(13,32))
end
end
io.write('\n')
core.clearCommandBuffer()
-- Print results
local bindata = {}
local emldata = ''
for _,s in pairs(blocks) do
local slice = s:sub(8,#s)
local str = utils.ConvertBytesToAscii(
utils.ConvertHexToBytes(slice)
)
emldata = emldata..slice..'\n'
for c in (str):gmatch('.') do
bindata[#bindata+1] = c
end
end
print( string.rep('--',20) )
local uid = block0:sub(1,8)
local toytype = block1:sub(1,4)
local cardidLsw = block1:sub(9,16)
local cardidMsw = block1:sub(16,24)
local cardid = block1:sub(9,24)
local subtype = block1:sub(25,28)
-- Write dump to files
if not DEBUG then
local foo = dumplib.SaveAsBinary(bindata, outputTemplate..'-'..uid..'.bin')
print(("Wrote a BIN dump to: %s"):format(foo))
local bar = dumplib.SaveAsText(emldata, outputTemplate..'-'..uid..'.eml')
print(("Wrote a EML dump to: %s"):format(bar))
end
print( string.rep('--',20) )
-- Show info
local item = toys.Find(toytype, subtype)
if item then
print((' ITEM TYPE : %s - %s (%s)'):format(item[6],item[5], item[4]) )
else
print((' ITEM TYPE : 0x%s 0x%s'):format(toytype, subtype))
end
print( (' UID : 0x%s'):format(uid) )
print( (' CARDID : 0x%s'):format(cardid ) )
print( string.rep('--',20) )
core.clearCommandBuffer()
end
main(args) | gpl-2.0 |
nkcfan/Dotfiles | .config/nvim/lua/treesitter_config.lua | 1 | 5326 | local define_modules = require("nvim-treesitter").define_modules
local query = require("nvim-treesitter.query")
local foldmethod_backups = {}
local foldexpr_backups = {}
-- folding module
-- ref: https://github.com/nvim-treesitter/nvim-treesitter/issues/475#issuecomment-748532035
define_modules(
{
folding = {
enable = true,
attach = function(bufnr)
-- Fold settings are actually window based...
foldmethod_backups[bufnr] = vim.wo.foldmethod
foldexpr_backups[bufnr] = vim.wo.foldexpr
vim.wo.foldmethod = "expr"
vim.wo.foldexpr = "nvim_treesitter#foldexpr()"
end,
detach = function(bufnr)
vim.wo.foldmethod = foldmethod_backups[bufnr]
vim.wo.foldexpr = foldexpr_backups[bufnr]
foldmethod_backups[bufnr] = nil
foldexpr_backups[bufnr] = nil
end,
is_supported = query.has_folds
}
}
)
require "nvim-treesitter.configs".setup {
ensure_installed = { "ocaml_interface", "fortran", "python", "c_sharp",
"gomod", "json5", "gowork", "todotxt", "graphql", "typescript", "ruby",
"perl", "supercollider", "fish", "slint", "php", "haskell", "java",
"hjson", "kotlin", "tlaplus", "regex", "julia", "llvm", "toml", "css",
"scss", "prisma", "pug", "rasi", "vue", "foam", "norg", "jsonc", "gleam",
"cpp", "elm", "javascript", "yaml", "eex", "yang", "heex", "lalrpop",
"ninja", "vala", "tsx", "nix", "hcl", "cooklang", "glimmer", "solidity",
"verilog", "rst", "latex", "json", "vim", "teal", "elvish", "markdown",
"ql", "astro", "hack", "go", "wgsl", "pascal", "make", "http", "scheme",
"hocon", "pioasm", "help", "lua", "cmake", "jsdoc", "zig", "ocaml", "rego",
"sparql", "beancount", "r", "gdscript", "clojure", "svelte", "devicetree",
"commonlisp", "turtle", "query", "comment", "cuda", "phpdoc", "d",
"fennel", "dart", "scala", "glsl", "html", "dockerfile", "bash", "c",
"dot", "erlang", "elixir", "rust", "surface", "fusion", "bibtex",
"ocamllex", "ledger" }, -- one of "all" or a list of languages
folding,
context_commentstring = {
enable = true
},
highlight = {
enable = true, -- false will disable the whole extension
disable = {}, -- list of language that will be disabled
-- Setting this to true will run `:h syntax` and tree-sitter at the same time.
-- Set this to `true` if you depend on 'syntax' being enabled (like for indentation).
-- Using this option may slow down your editor, and you may see some duplicate highlights.
-- Instead of true it can also be a list of languages
additional_vim_regex_highlighting = true,
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = "vii",
scope_incremental = "ii",
node_incremental = "<CR>",
node_decremental = "<S-CR>"
}
},
refactor = {
highlight_definitions = {enable = true},
highlight_current_scope = {enable = false}
},
textobjects = {
select = {
enable = true,
keymaps = {
-- You can use the capture groups defined in textobjects.scm
["ab"] = "@block.outer",
["ib"] = "@block.inner",
["af"] = "@function.outer",
["if"] = "@function.inner",
["ac"] = "@class.outer",
["ic"] = "@class.inner",
["aa"] = "@parameter.outer",
["ia"] = "@parameter.inner",
["cc"] = "@comment.outer",
["ss"] = "@statement.outer",
-- Or you can define your own textobjects like this
-- ["iF"] = {
-- python = "(function_definition) @function",
-- cpp = "(function_definition) @function",
-- c = "(function_definition) @function",
-- java = "(method_declaration) @function"
-- }
}
},
swap = {
enable = true,
swap_next = {
["<LocalLeader><LocalLeader>a"] = "@parameter.inner",
["<LocalLeader><LocalLeader>s"] = "@statement.outer"
},
swap_previous = {
["<LocalLeader><LocalLeader>A"] = "@parameter.inner",
["<LocalLeader><LocalLeader>S"] = "@statement.outer"
}
},
move = {
enable = true,
goto_next_start = {
["]m"] = "@function.outer",
["]]"] = "@class.outer",
},
goto_next_end = {
["]M"] = "@function.outer",
["]["] = "@class.outer",
},
goto_previous_start = {
["[m"] = "@function.outer",
["[["] = "@class.outer",
},
goto_previous_end = {
["[M"] = "@function.outer",
["[]"] = "@class.outer",
},
},
}
}
vim.api.nvim_set_keymap('n', '<LocalLeader>th', '<cmd>TSBufToggle highlight<CR>', {})
| mit |
nikai3d/codecombat-scripts | desert/bookkeeper.lua | 1 | 2049 | function bestCoin(xs)
local r, maxR = nil, 0
for i = 1, #xs do
local v = xs[i].value/self:distanceTo(xs[i])
if v > maxR then
r, maxR = xs[i], v
end
end
return r
end
local phase, count = 0, 0
local nx, ny = 59, 33
loop
-- Fight enemies for 15 seconds.
-- Keep count whenever an enemy is defeated.
if phase == 0 then
local e = self:findNearest(self:findEnemies())
if self:now() > 15 then
phase = 1
elseif e then
while e.health > 0 do
self:attack(e)
end
count = count + 1
else
self:move({x=nx, y=ny})
end
-- Tell Naria how many enemies you defeated.
elseif phase == 1 then
self:moveXY(nx, ny)
self:say(count)
phase, count = 2, self.gold
-- Collect coins until the clock reaches 30 seconds.
elseif phase == 2 then
local c = bestCoin(self:findItems())
if self:now() > 30 then
phase = 3
elseif c then
self:move(c.pos)
else
self:move({x=nx, y=ny})
end
-- Tell Naria how much gold you collected.
elseif phase == 3 then
self:moveXY(nx, ny)
self:say(self.gold - count)
phase, count = 4, 0
-- Fight enemies until the clock reaches 45 seconds.
-- Remember to reset the count of defeated enemies!
elseif phase == 4 then
local e = self:findNearest(self:findEnemies())
if self:now() > 45 then
phase = 5
elseif e then
while e.health > 0 do
self:attack(e)
end
count = count + 1
else
self:move({x=nx, y=ny})
end
-- Tell Naria how many enemies you defeated.
elseif phase == 5 then
self:moveXY(nx, ny)
self:say(count)
phase, count = 6, 0
else
local c = bestCoin(self:findItems())
if c then
self:move(c.pos)
else
self:move({x=nx, y=ny})
end
end
end
| mit |
LuaDist2/kong-cassandra | spec/type_fixtures.lua | 8 | 3178 | local cassandra = require "cassandra"
return {
{name='ascii', value='string'},
{name='ascii', insert_value=cassandra.null, read_value=nil},
{name='bigint', insert_value=cassandra.bigint(42000000000), read_value=42000000000},
{name='bigint', insert_value=cassandra.bigint(-42000000000), read_value=-42000000000},
{name='bigint', insert_value=cassandra.bigint(-42), read_value=-42},
{name='blob', value="\005\042"},
{name='blob', value=string.rep("blob", 10000)},
{name='boolean', value=true},
{name='boolean', value=false},
-- counters are not here because they are used with UPDATE instead of INSERT
-- todo: decimal,
{name='double', insert_value=cassandra.double(1.0000000000000004), read_test=function(value) return math.abs(value - 1.0000000000000004) < 0.000000000000001 end},
{name='double', insert_value=cassandra.double(-1.0000000000000004), read_value=-1.0000000000000004},
{name='double', insert_value=cassandra.double(0), read_test=function(value) return math.abs(value - 0) < 0.000000000000001 end},
{name='double', insert_value=cassandra.double(314151), read_test=function(value) return math.abs(value - 314151) < 0.000000000000001 end},
{name='float', insert_value=3.14151, read_test=function(value) return math.abs(value - 3.14151) < 0.0000001 end},
{name='float', insert_value=cassandra.float(3.14151), read_test=function(value) return math.abs(value - 3.14151) < 0.0000001 end},
{name='float', insert_value=cassandra.float(0), read_test=function(value) return math.abs(value - 0) < 0.0000001 end},
{name='float', insert_value=-3.14151, read_test=function(value) return math.abs(value + 3.14151) < 0.0000001 end},
{name='float', insert_value=cassandra.float(314151), read_test=function(value) return math.abs(value - 314151) < 0.0000001 end},
{name='int', value=4200},
{name='int', value=-42},
{name='text', value='string'},
{name='timestamp', insert_value=cassandra.timestamp(1405356926), read_value=1405356926},
{name='uuid', insert_value=cassandra.uuid("1144bada-852c-11e3-89fb-e0b9a54a6d11"), read_value="1144bada-852c-11e3-89fb-e0b9a54a6d11"},
{name='varchar', value='string'},
{name='blob', value=string.rep("string", 10000)},
{name='varint', value=4200},
{name='varint', value=-42},
{name='timeuuid', insert_value=cassandra.uuid("1144bada-852c-11e3-89fb-e0b9a54a6d11"), read_value="1144bada-852c-11e3-89fb-e0b9a54a6d11"},
{name='inet', insert_value=cassandra.inet("127.0.0.1"), read_value="127.0.0.1"},
{name='inet', insert_value=cassandra.inet("2001:0db8:85a3:0042:1000:8a2e:0370:7334"), read_value="2001:0db8:85a3:0042:1000:8a2e:0370:7334"},
{name='list<text>', insert_value=cassandra.list({'abc', 'def'}), read_value={'abc', 'def'}},
{name='list<int>', insert_value=cassandra.list({4, 2, 7}), read_value={4, 2, 7}},
{name='map<text,text>', insert_value=cassandra.map({k1='v1', k2='v2'}), read_value={k1='v1', k2='v2'}},
{name='map<text,int>', insert_value=cassandra.map({k1=3, k2=4}), read_value={k1=3, k2=4}},
{name='map<text,text>', insert_value=cassandra.map({}), read_value=nil},
{name='set<text>', insert_value=cassandra.set({'abc', 'def'}), read_value={'abc', 'def'}}
}
| mit |
hksonngan/Polycode | Examples/Lua/Game_Demos/Pong/Scripts/Main.lua | 10 | 4305 | ------------------------------------------------
-- Polycode Pong example by Ivan Safrin, 2013
------------------------------------------------
-- create a new Screen and set its height to 480
scene = PhysicsScene2D(1.0, 30)
scene:getDefaultCamera():setOrthoSize(0.0, 4.0)
-- load the playing field from the entity file and add it to the scene
field = SceneEntityInstance(scene, "Resources/field.entity")
scene:addChild(field)
-- get a handle to the player paddles and ball in the scene file and begin tracking collision
ball = field:getEntityById("ball", true)
scene:trackCollisionChild(ball, PhysicsScene2DEntity.ENTITY_RECT)
p1 = field:getEntityById("p1", true)
scene:trackCollisionChild(p1, PhysicsScene2DEntity.ENTITY_RECT)
p2 = field:getEntityById("p2", true)
scene:trackCollisionChild(p2, PhysicsScene2DEntity.ENTITY_RECT)
topWall = field:getEntityById("topWall", true)
scene:trackCollisionChild(topWall, PhysicsScene2DEntity.ENTITY_RECT)
bottomWall = field:getEntityById("bottomWall", true)
scene:trackCollisionChild(bottomWall, PhysicsScene2DEntity.ENTITY_RECT)
--load sounds
hitSound = Sound("Resources/hit.wav")
scoreSound = Sound("Resources/score.wav")
ballSpeed = 4.0
ballDirection = Vector2(1.0, 0.0)
-- initialize scores and get references to the player score labels on the field
p1scoreLabel = cast(field:getEntityById("p1ScoreLabel", true), SceneLabel)
p2scoreLabel = cast(field:getEntityById("p2ScoreLabel", true), SceneLabel)
p1Score = 0
p2Score = 0
function onCollision(t, event)
-- we need to cast the event to PhysicsScreenEvent because this is a PhysicsScreen event
physicsEvent = cast(event, PhysicsScene2DEvent)
-- check if the colliding entity is the ball
if physicsEvent.entity1 == ball then
-- if colliding with player 1 or player 2 paddle
if physicsEvent.entity2 == p1 or physicsEvent.entity2 == p2 then
-- reverse the horizontal direction
ballDirection.x = ballDirection.x * -1
-- adjust the vertical direction based on where on the paddle it hit
ballDirection.y = (ball:getPosition().y - physicsEvent:getSecondEntity():getPosition().y)/1.0
if ballDirection.y > 1.0 then ballDirection.y = 1.0 end
if ballDirection.y < -1.0 then ballDirection.y = -1.0 end
else
-- if collliding with the walls, simply reverse the vertical direction
ballDirection.y = ballDirection.y * -1
end
-- play the hit sound
hitSound:Play()
end
end
-- add a collision listener to the Physics Screen
-- onCollision will now be called every time there is a collion between
-- entities that we are tracking
scene:addEventListener(nil, onCollision, PhysicsScene2DEvent.EVENT_NEW_SHAPE_COLLISION)
-- Update is called automatically every frame
function Update(elapsed)
-- check player 1 input
if Services.Input:getKeyState(KEY_a) == true then
p1:setPositionY( p1:getPosition().y + (3.0 * elapsed))
elseif Services.Input:getKeyState(KEY_z) == true then
p1:setPositionY( p1:getPosition().y - (3.0 * elapsed))
end
-- check player 2 input
if Services.Input:getKeyState(KEY_UP) == true then
p2:setPositionY( p2:getPosition().y + (3.0 * elapsed))
elseif Services.Input:getKeyState(KEY_DOWN) == true then
p2:setPositionY( p2:getPosition().y - (3.0 * elapsed))
end
-- limit the paddle positions so they don't go offscreen
if p1:getPosition().y < -1.3 then p1:setPositionY(-1.3) end
if p1:getPosition().y > 1.3 then p1:setPositionY(1.3) end
if p2:getPosition().y < -1.3 then p2:setPositionY(-1.3) end
if p2:getPosition().y > 1.3 then p2:setPositionY(1.3) end
-- update the ball position
ball:setPositionX(ball:getPosition().x + (ballDirection.x * ballSpeed * elapsed))
ball:setPositionY( ball:getPosition().y + (ballDirection.y * ballSpeed * elapsed))
-- check if the ball beyond player 1's paddle and increment player 2's score
if ball:getPosition().x < -3 then
ball:setPosition(0.0, 0.0)
ballDirection.x = 1.0
ballDirection.y = 0.0
scoreSound:Play()
p2Score = p2Score + 1
p2scoreLabel:setText(""..p2Score)
end
-- check if the ball beyond player 2's paddle and increment player 1's score
if ball:getPosition().x > 3 then
ball:setPosition(0.0, 0.0)
ball:setPositionY(0)
ballDirection.x = -1.0
ballDirection.y = 0.0
scoreSound:Play()
p1Score = p1Score + 1
p1scoreLabel:setText(""..p1Score)
end
end | mit |
mms92/wire | lua/entities/gmod_wire_egp_hud/init.lua | 9 | 2380 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include('shared.lua')
AddCSLuaFile("HUDDraw.lua")
include("HUDDraw.lua")
ENT.WireDebugName = "E2 Graphics Processor HUD"
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.RenderTable = {}
self:SetUseType(SIMPLE_USE)
self.Inputs = WireLib.CreateInputs( self, { "0 to 512" } )
WireLib.CreateWirelinkOutput( nil, self, {true} )
self.xScale = { 0, 512 }
self.yScale = { 0, 512 }
self.Scaling = false
self.TopLeft = false
end
function ENT:TriggerInput( name, value )
if (name == "0 to 512") then
self:SetNWBool( "Resolution", value != 0 )
end
end
function ENT:Use( ply )
umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( self ) umsg.End()
end
function ENT:SetEGPOwner( ply )
self.ply = ply
self.plyID = ply:UniqueID()
end
function ENT:GetEGPOwner()
if (!self.ply or !self.ply:IsValid()) then
local ply = player.GetByUniqueID( self.plyID )
if (ply) then self.ply = ply end
return ply
else
return self.ply
end
return false
end
function ENT:UpdateTransmitState() return TRANSMIT_ALWAYS end
function ENT:LinkEnt( ent )
if IsValid( ent ) and ent:IsVehicle() then
if self.LinkedVehicles and self.LinkedVehicles[ent] then
return false
end
EGP:LinkHUDToVehicle( self, ent )
ent:CallOnRemove( "EGP HUD unlink on remove", function( ent )
EGP:UnlinkHUDFromVehicle( self, ent )
end)
return true
else
return false, tostring(ent) .. " is invalid or is not a vehicle"
end
end
function ENT:OnRemove()
if self.Marks then
for i=1,#self.Marks do
self.Marks[i]:RemoveCallOnRemove( "EGP HUD unlink on remove" )
end
end
EGP:UnlinkHUDFromVehicle( self )
end
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
local vehicles = self.LinkedVehicles
if vehicles then
local _vehicles = {}
for k,v in pairs( vehicles ) do
_vehicles[#_vehicles+1] = k:EntIndex()
end
info.egp_hud_vehicles = _vehicles
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
local vehicles = info.egp_hud_vehicles
if vehicles then
for i=1,#vehicles do
local vehicle = GetEntByID( vehicles[i] )
if IsValid( vehicle ) then
self:LinkEnt( vehicle )
end
end
end
end
| apache-2.0 |
luadch/luadch | scripts/etc_keyprint.lua | 1 | 2989 | --[[
etc_keyprint.lua by blastbeat
- this script tries to compute the keyprint of the hub cert (if availabe), and saves it in cfg.tbl
- using the script, the hub admin does not need to manually fiddle around with this shit anymore
]]--
local scriptname = "etc_keyprint"
local scriptversion = "0.01"
local hash_table = { } -- this table stores the correspondence between keyprint type and cert.digest method
hash_table[ "/?kp=SHA256/" ] = "sha256" -- atm we only care for sha256
-- note: we should NOT use the onStart listener here, to ensure that the other scripts get the right keyprint settings. otherwise you need to restart the hub twice, to get the settings working
local luasec = require "ssl" -- we need the modules luasec..
local basexx = require "basexx" -- ..and basexx..
if luasec and basexx then
local x509 = require "ssl.x509" -- ..and x509 stuff
local ssl_params = cfg.get( "ssl_params" ) -- this should give us at least a default ssl param table, hardcoded in luadch
local cert_path = ssl_params.certificate -- we need the cert location
if not cert_path then
return -- ssl params are invalid which really should not happen; cancel operation
end
local fd = io.open( tostring( cert_path ), "r" )
if fd then -- check, whether file can be opened..
local cert_str = fd:read "*all" -- ..and read content
if not cert_str then
fd:close( ) -- we are done because..
return -- ..something is wrong with the file; cancel operation..
end
local cert = x509.load( cert_str ) -- create a luasec cert object
if not cert then
fd:close( ) -- we are done because..
return -- ..file did not contain a valid cert; cancel operation..
end
local keyprint_type = cfg.get "keyprint_type"
local method
if keyprint_type and hash_table[ keyprint_type ] then
method = hash_table[ keyprint_type ]
else
fd:close( ) -- we are done because..
return -- ..if this happends, either cfg.get failed, which means that the default settings are wrecked, or somebody needs to complete the hash table
end
local digest = cert:digest( method )
if not digest then
fd:close( ) -- we are done because..
return -- ..the method provided in the hash table was fucked up; cancel operation
end
local keyprint = basexx.to_base32( basexx.from_hex( digest ) ):gsub( "=", "" ) -- calculate keyprint; this should not fail, but how knows; let's trust basexx
cfg.set( "keyprint_hash", keyprint, true )
cfg.set( "use_keyprint", true, true ) -- activate keyprint usage, but do not save it into cfg.tbl
fd:close( ) -- we are done.
end
end
hub.debug( "** Loaded " .. scriptname .. " " .. scriptversion .. " **" ) | gpl-3.0 |
puustina/openjam | src/splash.lua | 1 | 1369 | local splash = {
love = love.graphics.newImage("assets/love-logo.png"),
piskel = love.graphics.newImage("assets/logo_transparent_small_compact.png"),
gimp = love.graphics.newImage("assets/wilber-big.png")
}
local menu = require "src.menu"
function splash:init()
self.timer = Timer.new()
self.timer:add(3, function() Venus.switch(menu) end)
end
function splash:keypressed(key, scancode, isRepeat)
if Game.paused then return end
self.timer:clear()
Venus.switch(menu)
end
function splash:update(dt)
if Game.paused then return end
self.timer:update(dt)
end
function splash:draw()
preDraw()
love.graphics.setBackgroundColor(170, 170, 170)
love.graphics.setColor(255, 255, 255)
local s = math.min(Game.original.w/self.love:getWidth(), Game.original.h/self.love:getHeight())
love.graphics.draw(self.love, Game.original.w/2, Game.original.h/2 - 70, 0, s, s, self.love:getWidth()/2, self.love:getHeight()/2)
love.graphics.draw(self.piskel, 40, Game.original.h/2 + s * (self.love:getHeight()/2) - 40)
love.graphics.draw(self.gimp, 250, Game.original.h/2 + s * (self.love:getHeight()/2) - 70, 0, 0.4, 0.4)
love.graphics.setFont(Game.font14)
local t = "SFX: Bfxr + Bosca Ceoil, Music: Incompetech"
love.graphics.setColor(50, 50, 50)
love.graphics.print(t, Game.original.w/2 - Game.font14:getWidth(t)/2, Game.original.h - 20)
postDraw()
end
return splash
| gpl-3.0 |
mpreisler/ember | src/components/ogre/widgets/Compass.lua | 2 | 5040 | Compass = {}
function Compass:Refresh_Clicked(args)
self.helper:refresh()
self.helper:getMap():render()
return true
end
function Compass:ZoomIn_Clicked(args)
local newResolution = self.helper:getMap():getResolution() - 0.2
--prevent the user from zooming in to much (at which point only one pixel from the head of the avatar will be seen
if newResolution > 0.2 then
self.helper:getMap():setResolution(newResolution)
self.helper:getMap():render()
self.helper:refresh()
end
return true
end
function Compass:ZoomOut_Clicked(args)
local newResolution = self.helper:getMap():getResolution() + 0.2
--we'll use the arbitrary resolution of 5 as the max
if newResolution < 5 then
self.helper:getMap():setResolution(self.helper:getMap():getResolution() + 0.2)
self.helper:getMap():render()
self.helper:refresh()
end
return true
end
function Compass:repositionAtAvatar()
local pos = emberOgre:getWorld():getAvatar():getClientSideAvatarPosition()
self.helper:reposition(pos.x(), -pos.y())
end
function Compass:framestarted(frameEvent)
if self.updateFrameCountDown > 0 then
self.updateFrameCountDown = self.updateFrameCountDown - 1
if self.updateFrameCountDown == 0 then
--if we haven't created any anchor yet, it means that the whole compass is uninitialized and needs to be shown, else we can just rerender the map
if self.anchor == nil then
self:initialize()
else
self.helper:getMap():render()
self.helper:refresh()
end
self.updateFrameCountDown = -1
end
end
end
function Compass:TerrainPageGeometryUpdated(page)
--wait six frames until we rerender the map. This is a hack because apparently the event this listens for doesn't actually guarantee that the page will be rendered next frame. We need to add another event which is emitted when a page actually is rendered the first time.
self.updateFrameCountDown = 6
end
function Compass:initialize()
self.anchor = Ember.OgreView.Gui.CompassCameraAnchor:new(self.helper, emberOgre:getWorld():getMainCamera():getCamera())
if self.widget ~= nil then
self.widget:show()
end
end
function Compass:CreatedAvatarEntity(avatarEntity)
connect(self.connectors, self.widget.EventFrameStarted, self.framestarted, self)
end
function Compass:shutdown()
disconnectAll(self.connectors)
guiManager:destroyWidget(self.widget)
deleteSafe(self.helper)
deleteSafe(self.helperImpl)
deleteSafe(self.anchor)
end
function Compass:buildWidget(terrainManager)
self.helperImpl = Ember.OgreView.Gui.RenderedCompassImpl:new()
self.helper = Ember.OgreView.Gui.Compass:new(self.helperImpl, terrainManager:getScene():getSceneManager(), terrainManager:getAdapter())
self.map = self.helper:getMap()
self:buildCEGUIWidget()
--don't show the compass here, instead wait until we've gotten some terrain (by listening
connect(self.connectors, emberOgre.EventCreatedAvatarEntity, self.CreatedAvatarEntity, self)
connect(self.connectors, terrainManager.EventTerrainPageGeometryUpdated, self.TerrainPageGeometryUpdated, self)
end
-- Call this method to build the cegui widget.
function Compass:buildCEGUIWidget()
self.widget = guiManager:createWidget()
self.widget:loadMainSheet("Compass.layout", "Compass/")
self.widget:setIsActiveWindowOpaque(false)
self.renderImage = self.widget:getWindow("RenderImage")
self.pointerImage = self.widget:getWindow("Pointer")
local assetManager = Ember.OgreView.Gui.AssetsManager:new_local()
--set up the main background image
if self.helperImpl:getTexture():isNull() == false then
local texturePair = assetManager:createTextureImage(self.helperImpl:getTexture(), "CompassMap")
if texturePair:hasData() then
self.renderImage:setProperty("Image", CEGUI.PropertyHelper:imageToString(texturePair:getTextureImage()))
end
end
if self.helperImpl:getPointerTexture():isNull() == false then
--also set up the pointer image
local texturePair = assetManager:createTextureImage(self.helperImpl:getPointerTexture(), "CompassPointer")
if texturePair:hasData() then
self.pointerImage:setProperty("Image", CEGUI.PropertyHelper:imageToString(texturePair:getTextureImage()))
end
end
self.widget:getWindow("ZoomOut"):subscribeEvent("Clicked", self.ZoomOut_Clicked, self)
self.widget:getWindow("ZoomIn"):subscribeEvent("Clicked", self.ZoomIn_Clicked, self)
self.widget:hide()
end
connect(connectors, emberOgre.EventTerrainManagerCreated, function(terrainManager)
compass = {
connectors={},
map = nil,
widget = nil,
renderImage = nil,
helper = nil,
previousPosX = 0,
previousPosY = 0,
updateFrameCountDown = -1, --this is used for triggering delayed render updates. If it's more than zero, it's decreased each frame until it's zero, and a render is then carried out. If it's below zero nothing is done.
zoomInButton = nil,
anchor = nil
}
setmetatable(compass, {__index = Compass})
compass:buildWidget(terrainManager)
connect(compass.connectors, emberOgre.EventTerrainManagerBeingDestroyed, function()
compass:shutdown()
compass = nil
end)
end)
| gpl-3.0 |
keneanung/mudlet | src/mudlet-lua/lua/geyser/GeyserColor.lua | 19 | 6003 | --------------------------------------
-- --
-- The Geyser Layout Manager by guy --
-- --
--------------------------------------
Geyser.Color = {}
--- Converts color to 3 hex values as a string, no alpha, css style
-- @return The color formatted as a hex string, as accepted by html/css
function Geyser.Color.hex (r,g,b)
return string.format("#%02x%02x%02x", Geyser.Color.parse(r, g, b))
end
--- Converts color to 4 hex values as a string, with alpha, css style
-- @return The color formatted as a hex string, as accepted by html/css
function Geyser.Color.hexa (r,g,b,a)
return string.format("#%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a))
end
--- Converts color to 3 hex values as a string, no alpha, hecho style
-- @return The color formatted as a hex string, as accepted by hecho
function Geyser.Color.hhex (r,g,b)
return string.format("|c%02x%02x%02x", Geyser.Color.parse(r, g, b))
end
--- Converts color to 4 hex values as a string, with alpha, hecho style
-- @return The color formatted as a hex string, as accepted by hecho
function Geyser.Color.hhexa (r,g,b,a)
return string.format("|c%02x%02x%02x%02x", Geyser.Color.parse(r, g, b, a))
end
--- Converts color to 3 decimal values as a string, no alpha, decho style
-- @return The color formatted as a decho() style string
function Geyser.Color.hdec (r,g,b)
return string.format("<%d,%d,%d>", Geyser.Color.parse(r, g, b))
end
--- Converts color to 4 decimal values as a string, with alpha, decho style
-- @return The color formatted as a decho() style string
function Geyser.Color.hdeca (r,g,b,a)
return string.format("<%d,%d,%d,%d>", Geyser.Color.parse(r, g, b, a))
end
--- Returns 4 color components from (nearly any) acceptable format. Colors can be
-- specified in two ways. First: as a single word in english ("purple") or
-- hex ("#AA00FF", "|cAA00FF", or "0xAA00FF") or decimal ("<190,0,255>"). If
-- the hex or decimal representations contain a fourth element then alpha is
-- set too - otherwise alpha can't be set this way. Second: by passing in
-- distinct components as unsigned integers (e.g. 23 or 0xA7). When using the
-- second way, at least three values must be passed. If only three are
-- passed, then alpha is 255. Third: by passing in a table that has explicit
-- values for some, all or none of the keys r,g,b, and a.
-- @param red Either a valid string representation or the red component.
-- @param green The green component.
-- @param blue The blue component.
-- @param alpha The alpha component.
function Geyser.Color.parse(red, green, blue, alpha)
local r,g,b,a = 0,0,0,255
-- have to have something to set, else can't do anything!
if not red then
print("No color supplied.\n")
return
end
-- function to return next number
local next_num = nil
local base = 10
-- assigns all the colors, used after we figure out how the color is
-- represented as a string
local assign_colors = function ()
r = tonumber(next_num(), base)
g = tonumber(next_num(), base)
b = tonumber(next_num(), base)
local has_a = next_num()
if has_a then
a = tonumber(has_a, base)
end
end
-- Check if we were passed a string or table that needs to be parsed, i.e.,
-- there is only a valid red value, and other params are nil.
if not green or not blue then
if type(red) == "table" then
-- Here just copy over the appropriate values with sensible defaults
r = red.r or 127
g = red.g or 127
b = red.b or 127
a = red.a or 255
return r,g,b,a
elseif type(red) == "string" then
-- first case is a hex string, where first char is '#'
if string.find(red, "^#") then
local pure_hex = string.sub(red, 2) -- strip format char
next_num = string.gmatch(pure_hex, "%w%w")
base = 16
-- second case is a hex string, where first chars are '|c' or '0x'
elseif string.find(red, "^[|0][cx]") then
local pure_hex = string.sub(red, 3) -- strip format chars
next_num = string.gmatch(pure_hex, "%w%w")
base = 16
-- third case is a decimal string, of the format "<dd,dd,dd>"
elseif string.find(red, "^<") then
next_num = string.gmatch(red, "%d+")
-- fourth case is a named string
elseif color_table[red] then
local i = 0
local n = #color_table[red]
next_num = function () -- create a simple iterator
i = i + 1
if i <= n then return color_table[red][i]
else return nil end
end
else
-- finally, no matches, do nothing
return
end
end
else
-- Otherwise we weren't passed a complete string, but instead discrete
-- components as either decimal or hex
-- Yes, this is a little silly to do this way, but it fits with the
-- rest of the parsing going on...
local i = 0
next_num = function ()
i = i + 1
if i == 1 then return red
elseif i == 2 then return green
elseif i == 3 then return blue
elseif i == 4 then return alpha
else return nil
end
end
end
assign_colors()
return r,g,b,a
end
--- Applies colors to a window drawing from defaults and overridden values.
-- @param cons The window to apply colors to
function Geyser.Color.applyColors(cons)
cons:setFgColor(cons.fgColor)
cons:setBgColor(cons.bgColor)
cons:setColor(cons.color)
end
| gpl-2.0 |
Tele-Fox/best | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
xsrc/prosody | files/mod_carbons.lua | 2 | 5155 | -- XEP-0280: Message Carbons implementation for Prosody
-- Copyright (C) 2011 Kim Alvefur
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
local xmlns_carbons = "urn:xmpp:carbons:2";
local xmlns_carbons_old = "urn:xmpp:carbons:1";
local xmlns_carbons_really_old = "urn:xmpp:carbons:0";
local xmlns_forward = "urn:xmpp:forward:0";
local full_sessions, bare_sessions = full_sessions, bare_sessions;
local function toggle_carbons(event)
local origin, stanza = event.origin, event.stanza;
local state = stanza.tags[1].attr.mode or stanza.tags[1].name;
module:log("debug", "%s %sd carbons", origin.full_jid, state);
origin.want_carbons = state == "enable" and stanza.tags[1].attr.xmlns;
return origin.send(st.reply(stanza));
end
module:hook("iq-set/self/"..xmlns_carbons..":disable", toggle_carbons);
module:hook("iq-set/self/"..xmlns_carbons..":enable", toggle_carbons);
-- COMPAT
module:hook("iq-set/self/"..xmlns_carbons_old..":disable", toggle_carbons);
module:hook("iq-set/self/"..xmlns_carbons_old..":enable", toggle_carbons);
module:hook("iq-set/self/"..xmlns_carbons_really_old..":carbons", toggle_carbons);
local function message_handler(event, c2s)
local origin, stanza = event.origin, event.stanza;
local orig_type = stanza.attr.type;
local orig_from = stanza.attr.from;
local orig_to = stanza.attr.to;
if not (orig_type == nil
or orig_type == "normal"
or orig_type == "chat") then
return -- No carbons for messages of type error or headline
end
-- Stanza sent by a local client
local bare_jid = jid_bare(orig_from);
local target_session = origin;
local top_priority = false;
local user_sessions = bare_sessions[bare_jid];
-- Stanza about to be delivered to a local client
if not c2s then
bare_jid = jid_bare(orig_to);
target_session = full_sessions[orig_to];
user_sessions = bare_sessions[bare_jid];
if not target_session and user_sessions then
-- The top resources will already receive this message per normal routing rules,
-- so we are going to skip them in order to avoid sending duplicated messages.
local top_resources = user_sessions.top_resources;
top_priority = top_resources and top_resources[1].priority
end
end
if not user_sessions then
module:log("debug", "Skip carbons for offline user");
return -- No use in sending carbons to an offline user
end
if stanza:get_child("private", xmlns_carbons) then
stanza:maptags(function(tag)
if not ( tag.attr.xmlns == xmlns_carbons and tag.name == "private" ) then
return tag;
end
end);
module:log("debug", "Message tagged private, ignoring");
return
elseif stanza:get_child("no-copy", "urn:xmpp:hints") then
module:log("debug", "Message has no-copy hint, ignoring");
return
elseif stanza:get_child("x", "http://jabber.org/protocol/muc#user") then
module:log("debug", "MUC PM, ignoring");
return
end
-- Create the carbon copy and wrap it as per the Stanza Forwarding XEP
local copy = st.clone(stanza);
copy.attr.xmlns = "jabber:client";
local carbon = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons })
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_old = st.message{ from = bare_jid, type = orig_type, }
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_old }):up()
:tag("forwarded", { xmlns = xmlns_forward })
:add_child(copy):reset();
-- COMPAT
local carbon_really_old = st.clone(stanza)
:tag(c2s and "sent" or "received", { xmlns = xmlns_carbons_really_old }):up()
user_sessions = user_sessions and user_sessions.sessions;
for _, session in pairs(user_sessions) do
-- Carbons are sent to resources that have enabled it
if session.want_carbons
-- but not the resource that sent the message, or the one that it's directed to
and session ~= target_session
-- and isn't among the top resources that would receive the message per standard routing rules
and (c2s or session.priority ~= top_priority)
-- don't send v0 carbons (or copies) for c2s
and (not c2s or session.want_carbons ~= xmlns_carbons_really_old) then
carbon.attr.to = session.full_jid;
module:log("debug", "Sending carbon to %s", session.full_jid);
local carbon = session.want_carbons == xmlns_carbons_old and carbon_old -- COMPAT
or session.want_carbons == xmlns_carbons_really_old and carbon_really_old -- COMPAT
or carbon;
session.send(carbon);
end
end
end
local function c2s_message_handler(event)
return message_handler(event, true)
end
-- Stanzas sent by local clients
module:hook("pre-message/host", c2s_message_handler, 1);
module:hook("pre-message/bare", c2s_message_handler, 1);
module:hook("pre-message/full", c2s_message_handler, 1);
-- Stanzas to local clients
module:hook("message/bare", message_handler, 1);
module:hook("message/full", message_handler, 1);
module:add_feature(xmlns_carbons);
module:add_feature(xmlns_carbons_old);
if module:get_option_boolean("carbons_v0") then
module:add_feature(xmlns_carbons_really_old);
end
| gpl-3.0 |
MRAHS/SBSS-Pro | plugins/welcome.lua | 190 | 3526 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Bye '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
Habbie/hammerspoon | extensions/redshift/init.lua | 2 | 20346 | --- === hs.redshift ===
---
--- Inverts and/or lowers the color temperature of the screen(s) on a schedule, for a more pleasant experience at night
---
--- Usage:
--- ```
--- -- make a windowfilterDisable for redshift: VLC, Photos and screensaver/login window will disable color adjustment and inversion
--- local wfRedshift=hs.window.filter.new({VLC={focused=true},Photos={focused=true},loginwindow={visible=true,allowRoles='*'}},'wf-redshift')
--- -- start redshift: 2800K + inverted from 21 to 7, very long transition duration (19->23 and 5->9)
--- hs.redshift.start(2800,'21:00','7:00','4h',true,wfRedshift)
--- -- allow manual control of inverted colors
--- hs.hotkey.bind(HYPER,'f1','Invert',hs.redshift.toggleInvert)
--- ```
---
--- Note:
--- * As of macOS 10.12.4, Apple provides "Night Shift", which implements a simple red-shift effect, as part of the OS. It seems unlikely that `hs.redshift` will see significant future development.
local screen=require'hs.screen'
local timer=require'hs.timer'
local windowfilter=require'hs.window.filter'
local settings=require'hs.settings'
local log=require'hs.logger'.new('redshift')
local redshift={setLogLevel=log.setLogLevel} -- module
local type,ipairs,pairs,next,floor,abs,min,max,sformat=type,ipairs,pairs,next,math.floor,math.abs,math.min,math.max,string.format
local SETTING_INVERTED_OVERRIDE='hs.redshift.inverted.override'
local SETTING_DISABLED_OVERRIDE='hs.redshift.disabled.override'
--local BLACKPOINT = {red=0.00000001,green=0.00000001,blue=0.00000001}
local BLACKPOINT = {red=0,green=0,blue=0}
--local COLORRAMP
local running,nightStart,nightEnd,dayStart,dayEnd,nightTemp,dayTemp
local tmr,tmrNext,applyGamma,screenWatcher
local invertRequests,invertCallbacks,invertAtNight,invertUser,prevInvert={},{}
local disableRequests,disableUser={}
local wfDisable,modulewfDisable
local function round(v) return floor(0.5+v) end
local function lerprgb(p,a,b) return {red=a[1]*(1-p)+b[1]*p,green=a[2]*(1-p)+b[2]*p,blue=a[3]*(1-p)+b[3]*p} end
local function ilerp(v,s,e,a,b)
if s>e then
if v<e then v=v+86400 end
e=e+86400
end
local p=(v-s)/(e-s)
return a*(1-p)+b*p
end
local function getGamma(temp)
local R,lb,ub=redshift.COLORRAMP
for k,_ in pairs(R) do
if k<=temp then lb=max(lb or 0,k) else ub=min(ub or 10000,k) end
end
if lb==nil or ub==nil then local t=R[ub or lb] return {red=t[1],green=t[2],blue=t[3]} end
local p=(temp-lb)/(ub-lb)
return lerprgb(p,R[lb],R[ub])
-- local idx=floor(temp/100)-9
-- local p=(temp%100)/100
-- return lerprgb(p,COLORRAMP[idx],COLORRAMP[idx+1])
end
local function between(v,s,e)
if s<=e then return v>=s and v<=e else return v>=s or v<=e end
end
local function isInverted()
if not running then return false end
if invertUser~=nil then return invertUser and 'user'
else return next(invertRequests) or false end
end
local function isDisabled()
if not running then return true end
if disableUser~=nil then return disableUser and 'user'
else return next(disableRequests) or false end
end
-- core fn
applyGamma=function()
if tmrNext then tmrNext:stop() tmrNext=nil end
local now=timer.localTime()
local temp,timeNext,invertReq
if isDisabled() then temp=6500 timeNext=now-1 log.i('disabled')
elseif between(now,nightStart,nightEnd) then temp=ilerp(now,nightStart,nightEnd,dayTemp,nightTemp) --dusk
elseif between(now,dayStart,dayEnd) then temp=ilerp(now,dayStart,dayEnd,nightTemp,dayTemp) --dawn
elseif between(now,dayEnd,nightStart) then temp=dayTemp timeNext=nightStart log.i('daytime')--day
elseif between(now,nightEnd,dayStart) then invertReq=invertAtNight temp=nightTemp timeNext=dayStart log.i('nighttime')--night
else error('wtf') end
redshift.requestInvert('redshift-night',invertReq)
local invert=isInverted()
local gamma=getGamma(temp)
log.df('set color temperature %dK (gamma %d,%d,%d)%s',floor(temp),round(gamma.red*100),
round(gamma.green*100),round(gamma.blue*100),invert and (' - inverted by '..invert) or '')
for _,scr in ipairs(screen.allScreens()) do
scr:setGamma(invert and BLACKPOINT or gamma,invert and gamma or BLACKPOINT)
end
if invert~=prevInvert then
log.i('inverted status changed',next(invertCallbacks) and '- notifying callbacks' or '')
for _,fn in pairs(invertCallbacks) do fn(invert) end
prevInvert=invert
end
if timeNext then
tmrNext=timer.doAt(timeNext,applyGamma)
else
tmr:start()
end
end
--- hs.redshift.invertSubscribe([id,]fn)
--- Function
--- Subscribes a callback to be notified when the color inversion status changes
---
--- You can use this to dynamically adjust the UI colors in your modules or configuration, if appropriate.
---
--- Parameters:
--- * id - (optional) a string identifying the requester (usually the module name); if omitted, `fn`
--- itself will be the identifier; this identifier must be passed to `hs.redshift.invertUnsubscribe()`
--- * fn - a function that will be called whenever color inversion status changes; it must accept a
--- single parameter, a string or false as per the return value of `hs.redshift.isInverted()`
---
--- Returns:
--- * None
function redshift.invertSubscribe(key,fn)
if type(key)=='function' then fn=key end
if type(key)~='string' and type(key)~='function' then error('invalid key',2) end
if type(fn)~='function' then error('invalid callback',2) end
invertCallbacks[key]=fn
log.i('add invert callback',key)
return running and fn(isInverted())
end
--- hs.redshift.invertUnsubscribe(id)
--- Function
--- Unsubscribes a previously subscribed color inversion change callback
---
--- Parameters:
--- * id - a string identifying the requester or the callback function itself, depending on how you
--- called `hs.redshift.invertSubscribe()`
---
--- Returns:
--- * None
function redshift.invertUnsubscribe(key)
if not invertCallbacks[key] then return end
log.i('remove invert callback',key)
invertCallbacks[key]=nil
end
--- hs.redshift.isInverted() -> string or false
--- Function
--- Checks if the colors are currently inverted
---
--- Parameters:
--- * None
---
--- Returns:
--- * false if the colors are not currently inverted; otherwise, a string indicating the reason, one of:
--- * "user" for the user override (see `hs.redshift.toggleInvert()`)
--- * "redshift-night" if `hs.redshift.start()` was called with `invertAtNight` set to true,
--- and it's currently night time
--- * the ID string (usually the module name) provided to `hs.redshift.requestInvert()`, if another module requested color inversion
redshift.isInverted=isInverted
redshift.isDisabled=isDisabled
--- hs.redshift.requestInvert(id,v)
--- Function
--- Sets or clears a request for color inversion
---
--- Parameters:
--- * id - a string identifying the requester (usually the module name)
--- * v - a boolean indicating whether to invert the colors (if true) or clear any previous requests (if false or nil)
---
--- Returns:
--- * None
---
--- Notes:
--- * you can use this function e.g. to automatically invert colors if the ambient light sensor reading drops below
--- a certain threshold (`hs.brightness.DDCauto()` can optionally do exactly that)
--- * if the user's configuration doesn't explicitly start the redshift module, calling this will have no effect
local function request(t,k,v)
if type(k)~='string' then error('key must be a string',3) end
if v==false then v=nil end
if t[k]~=v then t[k]=v return true end
end
function redshift.requestInvert(key,v)
if request(invertRequests,key,v) then
log.f('invert request from %s %s',key,v and '' or 'canceled')
return running and applyGamma()
end
end
function redshift.requestDisable(key,v)
if request(disableRequests,key,v) then
log.f('disable color adjustment request from %s %s',key,v and '' or 'canceled')
return running and applyGamma()
end
end
--- hs.redshift.toggleInvert([v])
--- Function
--- Sets or clears the user override for color inversion.
---
--- This function should be bound to a hotkey, e.g.:
--- `hs.hotkey.bind('ctrl-cmd','=','Invert',hs.redshift.toggleInvert)`
---
--- Parameters:
--- * v - (optional) a boolean; if true, the override will invert the colors no matter what; if false,
--- the override will disable color inversion no matter what; if omitted or nil, it will toggle the
--- override, i.e. clear it if it's currently enforced, or set it to the opposite of the current
--- color inversion status otherwise.
---
--- Returns:
--- * None
function redshift.toggleInvert(v)
if not running then return end
if v==nil and invertUser==nil then v=not isInverted() end
if v~=nil and type(v)~='boolean' then error ('v must be a boolean or nil',2) end
log.f('invert user override%s',v==true and ': inverted' or (v==false and ': not inverted' or ' cancelled'))
if v==nil then settings.clear(SETTING_INVERTED_OVERRIDE)
else settings.set(SETTING_INVERTED_OVERRIDE,v) end
invertUser=v
return applyGamma()
end
--- hs.redshift.toggle([v])
--- Function
--- Sets or clears the user override for color temperature adjustment.
---
--- This function should be bound to a hotkey, e.g.:
--- `hs.hotkey.bind('ctrl-cmd','-','Redshift',hs.redshift.toggle)`
---
--- Parameters:
--- * v - (optional) a boolean; if true, the override will enable color temperature adjustment on
--- the given schedule; if false, the override will disable color temperature adjustment;
--- if omitted or nil, it will toggle the override, i.e. clear it if it's currently enforced, or
--- set it to the opposite of the current color temperature adjustment status otherwise.
---
--- Returns:
--- * None
function redshift.toggle(v)
if not running then return end
if v==nil then
if disableUser==nil then v=not isDisabled() end
elseif type(v)~='boolean' then error ('v must be a boolean or nil',2)
else v=not v end
log.f('color adjustment user override%s',v==true and ': disabled' or (v==false and ': enabled' or ' cancelled'))
if v==nil then settings.clear(SETTING_DISABLED_OVERRIDE)
else settings.set(SETTING_DISABLED_OVERRIDE,v) end
disableUser=v
return applyGamma()
end
--- hs.redshift.stop()
--- Function
--- Stops the module and disables color adjustment and color inversion
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function redshift.stop()
if not running then return end
log.i('stopped')
tmr:stop()
screen.restoreGamma()
if wfDisable then
if modulewfDisable then modulewfDisable:delete() modulewfDisable=nil
else wfDisable:unsubscribe(redshift.wfsubs) end
wfDisable=nil
end
if tmrNext then tmrNext:stop() tmrNext=nil end
screenWatcher:stop() screenWatcher=nil
running=nil
end
local function gc(t) return t.stop()end
local function stime(time)
return sformat('%02d:%02d:%02d',floor(time/3600),floor(time/60)%60,floor(time%60))
end
tmr=timer.delayed.new(10,applyGamma)
--- hs.redshift.start(colorTemp,nightStart,nightEnd[,transition[,invertAtNight[,windowfilterDisable[,dayColorTemp]]]])
--- Function
--- Sets the schedule and (re)starts the module
---
--- Parameters:
--- * colorTemp - a number indicating the desired color temperature (Kelvin) during the night cycle;
--- the recommended range is between 3600K and 1400K; lower values (minimum 1000K) result in a more pronounced adjustment
--- * nightStart - a string in the format "HH:MM" (24-hour clock) or number of seconds after midnight
--- (see `hs.timer.seconds()`) indicating when the night cycle should start
--- * nightEnd - a string in the format "HH:MM" (24-hour clock) or number of seconds after midnight
--- (see `hs.timer.seconds()`) indicating when the night cycle should end
--- * transition - (optional) a string or number of seconds (see `hs.timer.seconds()`) indicating the duration of
--- the transition to the night color temperature and back; if omitted, defaults to 1 hour
--- * invertAtNight - (optional) a boolean indicating whether the colors should be inverted (in addition to
--- the color temperature shift) during the night; if omitted, defaults to false
--- * windowfilterDisable - (optional) an `hs.window.filter` instance that will disable color adjustment
--- (and color inversion) whenever any window is allowed; alternatively, you can just provide a list of application
--- names (typically media apps and/or apps for color-sensitive work) and a windowfilter will be created
--- for you that disables color adjustment whenever one of these apps is focused
--- * dayColorTemp - (optional) a number indicating the desired color temperature (in Kelvin) during the day cycle;
--- you can use this to maintain some degree of "redshift" during the day as well, or, if desired, you can
--- specify a value higher than 6500K (up to 10000K) for more bluish colors, although that's not recommended;
--- if omitted, defaults to 6500K, which disables color adjustment and restores your screens' original color profiles
---
--- Returns:
--- * None
function redshift.start(nTemp,nStart,nEnd,dur,invert,wf,dTemp)
if not dTemp then dTemp=6500 end
if nTemp<1000 or nTemp>10000 or dTemp<1000 or dTemp>10000 then error('invalid color temperature',2) end
nStart,nEnd=timer.seconds(nStart),timer.seconds(nEnd)
dur=timer.seconds(dur or 3600)
if dur>14400 then error('max transition time is 4h',2) end
if abs(nStart-nEnd)<dur or abs(nStart-nEnd+86400)<dur
or abs(nStart-nEnd-86400)<dur then error('nightTime too close to dayTime',2) end
nightTemp,dayTemp=floor(nTemp),floor(dTemp)
redshift.stop()
invertAtNight=invert
nightStart,nightEnd=(nStart-dur/2)%86400,(nStart+dur/2)%86400
dayStart,dayEnd=(nEnd-dur/2)%86400,(nEnd+dur/2)%86400
log.f('started: %dK @ %s -> %dK @ %s,%s %dK @ %s -> %dK @ %s',
dayTemp,stime(nightStart),nightTemp,stime(nightEnd),invert and ' inverted,' or '',nightTemp,stime(dayStart),dayTemp,stime(dayEnd))
running=true
tmr:setDelay(max(1,dur/200))
screenWatcher=screen.watcher.new(function()tmr:start(5)end):start()
invertUser=settings.get(SETTING_INVERTED_OVERRIDE)
disableUser=settings.get(SETTING_DISABLED_OVERRIDE)
applyGamma()
if wf~=nil then
if windowfilter.iswf(wf) then wfDisable=wf
else
wfDisable=windowfilter.new(wf,'wf-redshift',log.getLogLevel())
modulewfDisable=wfDisable
if type(wf=='table') then
local isAppList=true
for k,v in pairs(wf) do
if type(k)~='number' or type(v)~='string' then isAppList=false break end
end
if isAppList then wfDisable:setOverrideFilter{focused=true} end
end
end
redshift.wfsubs={
[windowfilter.hasWindow]=function()redshift.requestDisable('wf-redshift',true)end,
[windowfilter.hasNoWindows]=function()redshift.requestDisable('wf-redshift')end,
}
wfDisable:subscribe(redshift.wfsubs,true)
end
end
--- hs.redshift.COLORRAMP
--- Variable
--- A table holding the gamma values for given color temperatures; each key must be a color temperature number in K (useful values are between
--- 1400 and 6500), and each value must be a list of 3 gamma numbers between 0 and 1 for red, green and blue respectively.
--- The table must have at least two entries (a lower and upper bound); the actual gamma values used for a given color temperature
--- are linearly interpolated between the two closest entries; linear interpolation isn't particularly precise for this use case,
--- so you should provide as many values as possible.
---
--- Notes:
--- * `hs.inspect(hs.redshift.COLORRAMP)` from the console will show you how the table is built
--- * the default ramp has entries from 1000K to 10000K every 100K
redshift.COLORRAMP={ -- from https://github.com/jonls/redshift/blob/master/src/colorramp.c
[1000]={1.00000000, 0.18172716, 0.00000000}, -- 1000K
[1100]={1.00000000, 0.25503671, 0.00000000}, -- 1100K
[1200]={1.00000000, 0.30942099, 0.00000000}, -- 1200K
[1300]={1.00000000, 0.35357379, 0.00000000}, -- ...
[1400]={1.00000000, 0.39091524, 0.00000000},
[1500]={1.00000000, 0.42322816, 0.00000000},
[1600]={1.00000000, 0.45159884, 0.00000000},
[1700]={1.00000000, 0.47675916, 0.00000000},
[1800]={1.00000000, 0.49923747, 0.00000000},
[1900]={1.00000000, 0.51943421, 0.00000000},
[2000]={1.00000000, 0.54360078, 0.08679949},
[2100]={1.00000000, 0.56618736, 0.14065513},
[2200]={1.00000000, 0.58734976, 0.18362641},
[2300]={1.00000000, 0.60724493, 0.22137978},
[2400]={1.00000000, 0.62600248, 0.25591950},
[2500]={1.00000000, 0.64373109, 0.28819679},
[2600]={1.00000000, 0.66052319, 0.31873863},
[2700]={1.00000000, 0.67645822, 0.34786758},
[2800]={1.00000000, 0.69160518, 0.37579588},
[2900]={1.00000000, 0.70602449, 0.40267128},
[3000]={1.00000000, 0.71976951, 0.42860152},
[3100]={1.00000000, 0.73288760, 0.45366838},
[3200]={1.00000000, 0.74542112, 0.47793608},
[3300]={1.00000000, 0.75740814, 0.50145662},
[3400]={1.00000000, 0.76888303, 0.52427322},
[3500]={1.00000000, 0.77987699, 0.54642268},
[3600]={1.00000000, 0.79041843, 0.56793692},
[3700]={1.00000000, 0.80053332, 0.58884417},
[3800]={1.00000000, 0.81024551, 0.60916971},
[3900]={1.00000000, 0.81957693, 0.62893653},
[4000]={1.00000000, 0.82854786, 0.64816570},
[4100]={1.00000000, 0.83717703, 0.66687674},
[4200]={1.00000000, 0.84548188, 0.68508786},
[4300]={1.00000000, 0.85347859, 0.70281616},
[4400]={1.00000000, 0.86118227, 0.72007777},
[4500]={1.00000000, 0.86860704, 0.73688797},
[4600]={1.00000000, 0.87576611, 0.75326132},
[4700]={1.00000000, 0.88267187, 0.76921169},
[4800]={1.00000000, 0.88933596, 0.78475236},
[4900]={1.00000000, 0.89576933, 0.79989606},
[5000]={1.00000000, 0.90198230, 0.81465502},
[5100]={1.00000000, 0.90963069, 0.82838210},
[5200]={1.00000000, 0.91710889, 0.84190889},
[5300]={1.00000000, 0.92441842, 0.85523742},
[5400]={1.00000000, 0.93156127, 0.86836903},
[5500]={1.00000000, 0.93853986, 0.88130458},
[5600]={1.00000000, 0.94535695, 0.89404470},
[5700]={1.00000000, 0.95201559, 0.90658983},
[5800]={1.00000000, 0.95851906, 0.91894041},
[5900]={1.00000000, 0.96487079, 0.93109690},
[6000]={1.00000000, 0.97107439, 0.94305985},
[6100]={1.00000000, 0.97713351, 0.95482993},
[6200]={1.00000000, 0.98305189, 0.96640795},
[6300]={1.00000000, 0.98883326, 0.97779486},
[6400]={1.00000000, 0.99448139, 0.98899179},
[6500]={1.00000000, 1.00000000, 1.00000000}, -- 6500K
-- [6500]={0.99999997, 0.99999997, 0.99999997}, --6500K
[6600]={0.98947904, 0.99348723, 1.00000000},
[6700]={0.97940448, 0.98722715, 1.00000000},
[6800]={0.96975025, 0.98120637, 1.00000000},
[6900]={0.96049223, 0.97541240, 1.00000000},
[7000]={0.95160805, 0.96983355, 1.00000000},
[7100]={0.94303638, 0.96443333, 1.00000000},
[7200]={0.93480451, 0.95923080, 1.00000000},
[7300]={0.92689056, 0.95421394, 1.00000000},
[7400]={0.91927697, 0.94937330, 1.00000000},
[7500]={0.91194747, 0.94470005, 1.00000000},
[7600]={0.90488690, 0.94018594, 1.00000000},
[7700]={0.89808115, 0.93582323, 1.00000000},
[7800]={0.89151710, 0.93160469, 1.00000000},
[7900]={0.88518247, 0.92752354, 1.00000000},
[8000]={0.87906581, 0.92357340, 1.00000000},
[8100]={0.87315640, 0.91974827, 1.00000000},
[8200]={0.86744421, 0.91604254, 1.00000000},
[8300]={0.86191983, 0.91245088, 1.00000000},
[8400]={0.85657444, 0.90896831, 1.00000000},
[8500]={0.85139976, 0.90559011, 1.00000000},
[8600]={0.84638799, 0.90231183, 1.00000000},
[8700]={0.84153180, 0.89912926, 1.00000000},
[8800]={0.83682430, 0.89603843, 1.00000000},
[8900]={0.83225897, 0.89303558, 1.00000000},
[9000]={0.82782969, 0.89011714, 1.00000000},
[9100]={0.82353066, 0.88727974, 1.00000000},
[9200]={0.81935641, 0.88452017, 1.00000000},
[9300]={0.81530175, 0.88183541, 1.00000000},
[9400]={0.81136180, 0.87922257, 1.00000000},
[9500]={0.80753191, 0.87667891, 1.00000000},
[9600]={0.80380769, 0.87420182, 1.00000000},
[9700]={0.80018497, 0.87178882, 1.00000000},
[9800]={0.79665980, 0.86943756, 1.00000000},
[9900]={0.79322843, 0.86714579, 1.00000000},
[10000]={0.78988728, 0.86491137, 1.00000000}, -- 10000K
}
return setmetatable(redshift,{__gc=gc})
| mit |
keneanung/mudlet | src/mudlet-lua/lua/TableUtils.lua | 12 | 8643 | ----------------------------------------------------------------------------------
--- Mudlet Table Utils
----------------------------------------------------------------------------------
--- Tests if a table is empty: this is useful in situations where you find
--- yourself wanting to do 'if my_table == {}' and such.
---
--- @usage Testing if the table is empty.
--- <pre>
--- myTable = {}
--- if table.is_empty(myTable) then
--- echo("myTable is empty")
--- end
--- </pre>
function table.is_empty(tbl)
for k, v in pairs(tbl) do
return false
end
return true
end
--- Lua debug function that prints the content of a Lua table on the screen, split up in keys and values.
--- Useful if you want to see what the capture groups contain i. e. the Lua table "matches".
---
--- @see display
function printTable( map )
echo("-------------------------------------------------------\n");
for k, v in pairs( map ) do
echo( "key=" .. k .. " value=" .. v .. "\n" )
end
echo("-------------------------------------------------------\n");
end
-- NOT LUADOC
-- This is supporting function for printTable().
function __printTable( k, v )
insertText ("\nkey = " .. tostring (k) .. " value = " .. tostring( v ) )
end
--- Lua debug function that prints the content of a Lua table on the screen. <br/>
--- There are currently 3 functions with similar behaviour.
---
--- @see display
--- @see printTable
function listPrint( map )
echo("-------------------------------------------------------\n");
for k,v in ipairs( map ) do
echo( k .. ". ) "..v .. "\n" );
end
echo("-------------------------------------------------------\n");
end
--- <b><u>TODO</u></b> listAdd( list, what )
function listAdd( list, what )
table.insert( list, what );
end
--- <b><u>TODO</u></b> listRemove( list, what )
function listRemove( list, what )
for k,v in ipairs( list ) do
if v == what then
table.remove( list, k )
end
end
end
--- Gets the actual size of non-index based tables. <br/><br/>
---
--- For index based tables you can get the size with the # operator: <br/>
--- This is the standard Lua way of getting the size of index tables i.e. ipairs() type of tables with
--- numerical indices. To get the size of tables that use user defined keys instead of automatic indices
--- (pairs() type) you need to use the function table.size() referenced above.
--- <pre>
--- myTableSize = # myTable
--- </pre>
function table.size(t)
if not t then
return 0
end
local i = 0
for k, v in pairs(t) do
i = i + 1
end
return i
end
--- Determines if a table contains a value as a key or as a value (recursive).
function table.contains(t, value)
for k, v in pairs(t) do
if v == value then
return true
elseif k == value then
return true
elseif type(v) == "table" then
if table.contains(v, value) then return true end
end
end
return false
end
--- Table Union.
---
--- @return Returns a table that is the union of the provided tables. This is a union of key/value
--- pairs. If two or more tables contain different values associated with the same key,
--- that key in the returned table will contain a subtable containing all relevant values.
--- See table.n_union() for a union of values. Note that the resulting table may not be
--- reliably traversable with ipairs() due to the fact that it preserves keys. If there
--- is a gap in numerical indices, ipairs() will cease traversal.
---
--- @usage Example:
--- <pre>
--- tableA = {
--- [1] = 123,
--- [2] = 456,
--- ["test"] = "test",
--- }
---
--- tableB = {
--- [1] = 23,
--- [3] = 7,
--- ["test2"] = function() return true end,
--- }
---
--- tableC = {
--- [5] = "c",
--- }
---
--- table.union(tableA, tableB, tableC) will return:
--- {
--- [1] = {
--- 123,
--- 23,
--- },
--- [2] = 456,
--- [3] = 7,
--- [5] = "c",
--- ["test"] = "test",
--- ["test2"] = function() return true end,
--- }
--- </pre>
function table.union(...)
local sets = {...}
local union = {}
for _, set in ipairs(sets) do
for key, val in pairs(set) do
if union[key] and union[key] ~= val then
if type(union[key]) == 'table' then
table.insert(union[key], val)
else
union[key] = { union[key], val }
end
else
union[key] = val
end
end
end
return union
end
--- Table Union.
---
--- @return Returns a numerically indexed table that is the union of the provided tables. This is
--- a union of unique values. The order and keys of the input tables are not preserved.
function table.n_union(...)
local sets = {...}
local union = {}
local union_keys = {}
for _, set in ipairs(sets) do
for key, val in pairs(set) do
if not union_keys[val] then
union_keys[val] = true
table.insert(union, val)
end
end
end
return union
end
--- Table Intersection.
---
--- @return Returns a table that is the intersection of the provided tables. This is an
--- intersection of key/value pairs. See table.n_intersection() for an intersection of values.
--- Note that the resulting table may not be reliably traversable with ipairs() due to
--- the fact that it preserves keys. If there is a gap in numerical indices, ipairs() will
--- cease traversal.
---
--- @usage Example:
--- <pre>
--- tableA = {
--- [1] = 123,
--- [2] = 456,
--- [4] = { 1, 2 },
--- [5] = "c",
--- ["test"] = "test",
--- }
---
--- tableB = {
--- [1] = 123,
--- [2] = 4,
--- [3] = 7,
--- [4] = { 1, 2 },
--- ["test"] = function() return true end,
--- }
---
--- tableC = {
--- [1] = 123,
--- [4] = { 1, 2 },
--- [5] = "c",
--- }
---
--- table.intersection(tableA, tableB, tableC) will return:
--- {
--- [1] = 123,
--- [4] = { 1, 2 },
--- }
--- </pre>
function table.intersection(...)
sets = {...}
if #sets < 2 then return false end
local intersection = {}
local function intersect(set1, set2)
local result = {}
for key, val in pairs(set1) do
if set2[key] then
if _comp(val, set2[key]) then result[key] = val end
end
end
return result
end
intersection = intersect(sets[1], sets[2])
for i, _ in ipairs(sets) do
if i > 2 then
intersection = intersect(intersection, sets[i])
end
end
return intersection
end
--- Table Intersection.
---
--- @return Returns a numerically indexed table that is the intersection of the provided tables.
--- This is an intersection of unique values. The order and keys of the input tables are
--- not preserved.
function table.n_intersection(...)
sets = {...}
if #sets < 2 then return false end
local intersection = {}
local function intersect(set1, set2)
local intersection_keys = {}
local result = {}
for _, val1 in pairs(set1) do
for _, val2 in pairs(set2) do
if _comp(val1, val2) and not intersection_keys[val1] then
table.insert(result, val1)
intersection_keys[val1] = true
end
end
end
return result
end
intersection = intersect(sets[1], sets[2])
for i, _ in ipairs(sets) do
if i > 2 then
intersection = intersect(intersection, sets[i])
end
end
return intersection
end
--- Table Complement.
---
--- @return Returns a table that is the relative complement of the first table with respect to
--- the second table. Returns a complement of key/value pairs.
function table.complement(set1, set2)
if not set1 and set2 then return false end
if type(set1) ~= 'table' or type(set2) ~= 'table' then return false end
local complement = {}
for key, val in pairs(set1) do
if not _comp(set2[key], val) then
complement[key] = val
end
end
return complement
end
--- Table Complement.
---
--- @return Returns a table that is the relative complement of the first table with respect to
--- the second table. Returns a complement of values.
function table.n_complement(set1, set2)
if not set1 and set2 then return false end
local complement = {}
for _, val1 in pairs(set1) do
local insert = true
for _, val2 in pairs(set2) do
if _comp(val1, val2) then
insert = false
end
end
if insert then table.insert(complement, val1) end
end
return complement
end
--- <b><u>TODO</u></b> table:update(t1, t2)
function table:update(t1, t2)
for k,v in pairs(t2) do
if type(v) == "table" then
t1[k] = self.update(t1[k] or {}, v)
else
t1[k] = v
end
end
return t1
end
---Returns the index of the value in a table
function table.index_of(table, element)
for index, value in ipairs(table) do
if value == element then
return index
end
end
return nil
end
| gpl-2.0 |
yuin/silkylog | config.lua | 1 | 2810 | silkylog = require("silkylog")
config {
debug = false,
site_url = "http://example.com/",
editor = {"vim"},
numthreads = 8,
timezone = "JST +09:00",
theme = "default",
pagination1 = 3,
pagination2 = 50,
trim_html = true,
params = {
author = "Your name",
site_name = "Your site",
site_description = "Your site description",
google_analytics_id = "",
disqus_short_name = "",
},
top_url_path = "",
article_url_path = [[articles/{{ .PostedAt.Year | printf "%04d" }}/{{ .PostedAt.Month | printf "%02d" }}/{{ .PostedAt.Day | printf "%02d" }}/{{ .Slug }}.html]],
article_title = [[{{ .App.Config.Params.SiteName }} :: {{ .Article.Title }}]],
index_url_path = [[{{if (eq .Page 0)}}index.html{{else}}page/{{ .Page }}/index.html{{end}}]],
index_title = [[{{.App.Config.Params.SiteName}}]],
tag_url_path = [[articles/tag/{{ .Tag }}/{{if (ne .Page 0)}}page/{{ .Page }}/{{end}}index.html]],
tag_title = [[{{.App.Config.Params.SiteName}} :: tag :: {{.Tag}}]],
annual_url_path = [[articles/{{ .Year | printf "%04d" }}/{{if (ne .Page 0)}}page/{{ .Page }}/{{end}}index.html]],
annual_title = [[{{.App.Config.Params.SiteName}} :: annual archive :: {{.Year}}]],
monthly_url_path = [[articles/{{ .Year | printf "%04d" }}/{{ .Month | printf "%02d" }}/{{if (ne .Page 0)}}page/{{ .Page }}/{{end}}index.html]],
monthly_title = [[{{.App.Config.Params.SiteName}} :: monthly archive :: {{.Year}}.{{.Month}}]],
include_url_path = [[include/{{ .Name }}]],
feed_url_path = [[{{ .Name }}]],
file_url_path = [[{{ .Path }}]],
content_dir = "src",
output_dir = "public_html",
theme_dir = "themes",
extra_files = {
{src = "favicon.ico", dst = "", template = false},
{src = "404.html", dst = "", template = false},
{src = "CNAME", dst = "", template = false},
{src = "profile.html", dst = "", template = true}
},
clean = {
"articles",
"page",
},
markup_processors = {
[".md"] = {
name = "blackfriday",
htmlopts = {
"HTML_USE_XHTML",
"HTML_USE_SMARTYPANTS",
"HTML_SMARTYPANTS_FRACTIONS",
"HTML_SMARTYPANTS_LATEX_DASHES"
},
exts = {
"EXTENSION_NO_INTRA_EMPHASIS",
"EXTENSION_TABLES",
"EXTENSION_FENCED_CODE",
"EXTENSION_AUTOLINK",
"EXTENSION_STRIKETHROUGH",
"EXTENSION_SPACE_HEADERS",
"EXTENSION_HEADER_IDS"
}
},
[".rst"] = function(text)
local html = assert(silkylog.runprocessor([[python]],[[rst2html.py]], text))
return html
end
}
}
| mit |
mms92/wire | lua/entities/gmod_wire_egp/lib/egplib/umsgsystem.lua | 18 | 1133 | --------------------------------------------------------
-- Custom umsg System
--------------------------------------------------------
local EGP = EGP
local CurSender
local LastErrorTime = 0
--[[ Transmit Sizes:
Angle = 12
Bool = 1
Char = 1
Entity = 2
Float = 4
Long = 4
Short = 2
String = string length
Vector = 12
VectorNormal = 12
]]
EGP.umsg = {}
function EGP.umsg.Start( name, sender )
if CurSender then
if (LastErrorTime + 1 < CurTime()) then
ErrorNoHalt("[EGP] Umsg error. It seems another umsg is already sending, but it occured over 1 second ago. Ending umsg.")
EGP.umsg.End()
else
ErrorNoHalt("[EGP] Umsg error. Another umsg is already sending!")
if (LastErrorTime + 2 < CurTime()) then
LastErrorTime = CurTime()
end
return false
end
end
CurSender = sender
net.Start( name )
return true
end
function EGP.umsg.End()
if CurSender then
if not EGP.IntervalCheck[CurSender] then EGP.IntervalCheck[CurSender] = { bytes = 0, time = 0 } end
EGP.IntervalCheck[CurSender].bytes = EGP.IntervalCheck[CurSender].bytes + net.BytesWritten()
end
net.Broadcast()
CurSender = nil
end
| apache-2.0 |
AlexarJING/space-war | lib/loveframes/objects/internal/scrollable/scrollbody.lua | 17 | 6652 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- get the current require path
local path = string.sub(..., 1, string.len(...) - string.len(".objects.internal.scrollable.scrollbody"))
local loveframes = require(path .. ".libraries.common")
-- scrollbar class
local newobject = loveframes.NewObject("scrollbody", "loveframes_object_scrollbody", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize(parent, bartype)
self.type = "scrollbody"
self.bartype = bartype
self.parent = parent
self.x = 0
self.y = 0
self.internal = true
self.internals = {}
if self.bartype == "vertical" then
self.width = 16
self.height = self.parent.height
self.staticx = self.parent.width - self.width
self.staticy = 0
elseif self.bartype == "horizontal" then
self.width = self.parent.width
self.height = 16
self.staticx = 0
self.staticy = self.parent.height - self.height
end
table.insert(self.internals, loveframes.objects["scrollarea"]:new(self, bartype))
local bar = self.internals[1].internals[1]
if self.bartype == "vertical" then
local upbutton = loveframes.objects["scrollbutton"]:new("up")
upbutton.staticx = 0 + self.width - upbutton.width
upbutton.staticy = 0
upbutton.parent = self
upbutton.Update = function(object, dt)
upbutton.staticx = 0 + self.width - upbutton.width
upbutton.staticy = 0
if object.down and object.hover then
local dtscrolling = self.parent.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
bar:Scroll(-self.parent.buttonscrollamount * dt)
else
bar:Scroll(-self.parent.buttonscrollamount)
end
end
end
local downbutton = loveframes.objects["scrollbutton"]:new("down")
downbutton.parent = self
downbutton.staticx = 0 + self.width - downbutton.width
downbutton.staticy = 0 + self.height - downbutton.height
downbutton.Update = function(object, dt)
downbutton.staticx = 0 + self.width - downbutton.width
downbutton.staticy = 0 + self.height - downbutton.height
downbutton.x = downbutton.parent.x + downbutton.staticx
downbutton.y = downbutton.parent.y + downbutton.staticy
if object.down and object.hover then
local dtscrolling = self.parent.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
bar:Scroll(self.parent.buttonscrollamount * dt)
else
bar:Scroll(self.parent.buttonscrollamount)
end
end
end
table.insert(self.internals, upbutton)
table.insert(self.internals, downbutton)
elseif self.bartype == "horizontal" then
local leftbutton = loveframes.objects["scrollbutton"]:new("left")
leftbutton.parent = self
leftbutton.staticx = 0
leftbutton.staticy = 0
leftbutton.Update = function(object, dt)
leftbutton.staticx = 0
leftbutton.staticy = 0
if object.down and object.hover then
local dtscrolling = self.parent.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
bar:Scroll(-self.parent.buttonscrollamount * dt)
else
bar:Scroll(-self.parent.buttonscrollamount)
end
end
end
local rightbutton = loveframes.objects["scrollbutton"]:new("right")
rightbutton.parent = self
rightbutton.staticx = 0 + self.width - rightbutton.width
rightbutton.staticy = 0
rightbutton.Update = function(object, dt)
rightbutton.staticx = 0 + self.width - rightbutton.width
rightbutton.staticy = 0
rightbutton.x = rightbutton.parent.x + rightbutton.staticx
rightbutton.y = rightbutton.parent.y + rightbutton.staticy
if object.down and object.hover then
local dtscrolling = self.parent.dtscrolling
if dtscrolling then
local dt = love.timer.getDelta()
bar:Scroll(self.parent.buttonscrollamount * dt)
else
bar:Scroll(self.parent.buttonscrollamount)
end
end
end
table.insert(self.internals, leftbutton)
table.insert(self.internals, rightbutton)
end
local parentstate = parent.state
self:SetState(parentstate)
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
self:CheckHover()
local parent = self.parent
local base = loveframes.base
local update = self.Update
local internals = self.internals
-- move to parent if there is a parent
if parent ~= base then
self.x = parent.x + self.staticx
self.y = parent.y + self.staticy
end
-- resize to parent
if parent ~= base then
if self.bartype == "vertical" then
self.height = self.parent.height
self.staticx = self.parent.width - self.width
if parent.hbar then self.height = self.height - parent:GetHorizontalScrollBody().height end
elseif self.bartype == "horizontal" then
self.width = self.parent.width
self.staticy = self.parent.height - self.height
if parent.vbar then self.width = self.width - parent:GetVerticalScrollBody().width end
end
end
for k, v in ipairs(internals) do
v:update(dt)
end
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local visible = self.visible
if not visible then
return
end
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawScrollBody or skins[defaultskin].DrawScrollBody
local draw = self.Draw
local drawcount = loveframes.drawcount
local internals = self.internals
-- set the object's draw order
self:SetDrawOrder()
if draw then
draw(self)
else
drawfunc(self)
end
for k, v in ipairs(internals) do
v:draw()
end
end
--[[---------------------------------------------------------
- func: GetScrollBar()
- desc: gets the object's scroll bar
--]]---------------------------------------------------------
function newobject:GetScrollBar()
return self.internals[1].internals[1]
end
| apache-2.0 |
vipteam1/VIPTEAM | plugins/dletemsg.lua | 1 | 1535 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( #dletemsg ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
local function history(extra, suc, result)
for i=1, #result do
delete_msg(result[i].id, ok_cb, false)
end
if tonumber(extra.con) == #result then
send_msg(extra.chatid, '⛔️ "'..#result..'" The msgs is cleaned !', ok_cb, false)
else
send_msg(extra.chatid, '⛔️ The msgs is cleaned !', ok_cb, false)
end
end
local function run(msg, matches)
if matches[1] == 'حذف' and is_owner(msg) then
if msg.to.type == 'channel' then
if tonumber(matches[2]) > 1000000 or tonumber(matches[2]) < 1 then
return "only from num 1 to 1000000 !!"
end
get_history(msg.to.peer_id, matches[2] + 1 , history , {chatid = msg.to.peer_id, con = matches[2]})
else
return "4 owner only"
end
else
return
end
end
return {
patterns = {
'^(حذف) (%d*)$'
},
run = run
} | gpl-2.0 |
thenumbernine/hydro-cl-lua | tests/running two solvers at once/run.lua | 1 | 5233 | #!/usr/bin/env luajit
require 'ext'
local ffi = require 'ffi'
local unistd = require 'ffi.c.unistd'
require 'ffi.c.stdlib'
local dirp = unistd.getcwd(nil, 0)
local dir = ffi.string(dirp)
ffi.C.free(dirp)
unistd.chdir'../..'
-- honestly what's App used for anyways, beyond the gui?
-- the cl.env ... can I build a solver without app, but just with a cl.env?
local App = class(require 'hydro.app')
function App:setup()
local args = {
app = self,
dim = 1,
integrator = 'forward Euler',
fluxLimiter = 'superbee',
coord = 'cartesian',
mins = {-1, -1, -1},
maxs = {1, 1, 1},
gridSize = {256, 256, 256},
boundary = {
xmin='freeflow',
xmax='freeflow',
ymin='freeflow',
ymax='freeflow',
zmin='freeflow',
zmax='freeflow',
},
initState = 'Sod',
--initState = 'self-gravitation test 1',
}
-- [=[ two-solver testing ...
-- running two solvers at once causes errors
local app = self
local cl = require 'hydro.solver.roe'
args.eqn = 'euler'
--args.eqn = 'maxwell'
--args.eqn = 'mhd'
self.solvers:insert(cl(args))
self.solvers:insert(cl(args))
local s1, s2 = self.solvers:unpack()
local numReals = s1.numCells * s1.eqn.numStates
local ptr1 = ffi.new('real[?]', numReals)
local ptr2 = ffi.new('real[?]', numReals)
local function compare(buf1, buf2)
app.cmds:enqueueReadBuffer{buffer=buf1, block=true, size=ffi.sizeof(app.real) * numReals, ptr=ptr1}
app.cmds:enqueueReadBuffer{buffer=buf2, block=true, size=ffi.sizeof(app.real) * numReals, ptr=ptr2}
local diff
for i=0,numReals-1 do
if ptr1[i] ~= ptr2[i] then
diff = i
break
end
end
if diff then
for i=0,numReals-1 do
io.write(('%7d '):format(i))
for j,v in ipairs{ptr1, ptr2} do
io.write(({' ','/'})[j])
local vi = v[i]
local s = vi and ('%.8e'):format(v[i]) or 'nil'
local ip = ffi.cast('int*', v+i)
s = s .. '(' .. (ip and (('%08x'):format(ip[1]):sub(-8) .. ('%08x'):format(ip[0]):sub(-8)) or 'nil') .. ')'
io.write(s)
end
local col = 1
if i%col==col-1 then print() end
end
print()
local ch = diff % s1.eqn.numStates
local x = math.floor(diff / tonumber(s1.eqn.numStates * s1.gridSize.x)) % tonumber(s1.gridSize.y)
local y = math.floor(diff / tonumber(s1.eqn.numStates * s1.gridSize.x * s1.gridSize.y))
print('index '..diff
..' coord '..x..', '..y..' ch '..ch
..' differs:',ptr1[diff], ptr2[diff])
s1:save's1'
s2:save's2'
error'here'
end
end
--for _,s in ipairs(self.solvers) do s.useFixedDT = true s.fixedDT = .025 end
--s2.integrator = s1.integrator
--function s2:update() self.t = self.t + .1 end
--function s2:boundary() end
--function s2:calcDT() return s1.fixedDT end
-- [==[ messing with step to find the problem
function s2:step(dt)
--[[ fails
s1.integrator:integrate(dt, function(derivBufObj)
self:calcDeriv(derivBufObj, dt)
end)
--]]
--[[ seems to work fine, but we're not adding to UBuf
self:calcDeriv(s1.integrator.derivBufObj, dt)
--]]
--[[ works as well .. but doesn't add to s2's UBuf
self:calcDeriv(self.integrator.derivBufObj, dt)
--]]
-- [[ fails with inline forward euler
-- calcDeriv runs fine on its own
-- everything except calcDeriv runs on its own
-- but as soon as the two are put together, it dies
app.cmds:enqueueFillBuffer{buffer=self.integrator.derivBufObj.obj, size=self.numCells * self.eqn.numStates * ffi.sizeof(app.real)}
-- this produces crap in s2
-- if it's not added into s2's UBuf then we're safe
-- if it isn't called and zero is added to s2's UBuf then we're safe
self:calcDeriv(self.integrator.derivBufObj, dt)
-- why does derivBufObj differ?
-- something is corrupting every numStates data ... like something is writing out of bounds ...
--compare(s1.integrator.derivBufObj.obj, s2.integrator.derivBufObj.obj)
self.multAddKernelObj(
self.UBuf,
s1.UBuf,
-- using self.integrator.derivBufObj.obj fails
-- but using s1.integrator.derivBufObj.obj works ... worked ....
s1.integrator.derivBufObj.obj,
ffi.new('real[1]', dt))
--]]
--[[ fails with the other solver's forward-euler and multAddKernel
app.cmds:finish()
app.cmds:enqueueFillBuffer{buffer=s1.integrator.derivBufObj.obj, size=self.numCells * self.eqn.numStates * ffi.sizeof(app.real)}
self:calcDeriv(s1.integrator.derivBufObj, dt)
s1.multAddKernelObj(self.UBuf, self.UBuf, s1.integrator.derivBufObj.obj, ffi.new('real[1]', dt))
app.cmds:finish()
--]]
--[[ just adding s1's deriv to s2? works fine
s1.multAddKernelObj(self.UBuf, self.UBuf, s1.integrator.derivBufObj.obj, ffi.new('real[1]', dt))
s1.multAddKernelObj.obj:setArgs(s1.UBuf, s1.UBuf, s1.integrator.derivBufObj.obj, ffi.new('real[1]', dt))
--]]
-- so the code in common is when calcDeriv is called by the 2nd solver ...
-- ... regardless of what buffer it is written to
end
--]==]
--[==[ comparing buffers. tends to die on the boundaries even if it is working (why is that?)
function s2:update()
s1.update(self)
-- ...annd even when using s1's derivBufObj, this dies once the wave hits a boundary
-- complains about negative'd values (with mirror boundary conditions)
compare(s1.UBuf, s2.UBuf)
end
--]==]
--]=]
end
App():run()
| mit |
Tele-Sped/Tele-Sped | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| agpl-3.0 |
fidlej/optim | adagrad.lua | 10 | 1621 | --[[ ADAGRAD implementation for SGD
ARGS:
- `opfunc` : a function that takes a single input (X), the point of
evaluation, and returns f(X) and df/dX
- `x` : the initial point
- `state` : a table describing the state of the optimizer; after each
call the state is modified
- `state.learningRate` : learning rate
- `state.paramVariance` : vector of temporal variances of parameters
RETURN:
- `x` : the new x vector
- `f(x)` : the function, evaluated before the update
]]
function optim.adagrad(opfunc, x, config, state)
-- (0) get/update state
if config == nil and state == nil then
print('no state table, ADAGRAD initializing')
end
local config = config or {}
local state = state or config
local lr = config.learningRate or 1e-3
local lrd = config.learningRateDecay or 0
state.evalCounter = state.evalCounter or 0
local nevals = state.evalCounter
-- (1) evaluate f(x) and df/dx
local fx,dfdx = opfunc(x)
-- (3) learning rate decay (annealing)
local clr = lr / (1 + nevals*lrd)
-- (4) parameter update with single or individual learning rates
if not state.paramVariance then
state.paramVariance = torch.Tensor():typeAs(x):resizeAs(dfdx):zero()
state.paramStd = torch.Tensor():typeAs(x):resizeAs(dfdx)
end
state.paramVariance:addcmul(1,dfdx,dfdx)
state.paramStd:resizeAs(state.paramVariance):copy(state.paramVariance):sqrt()
x:addcdiv(-clr, dfdx,state.paramStd:add(1e-10))
-- (5) update evaluation counter
state.evalCounter = state.evalCounter + 1
-- return x*, f(x) before optimization
return x,{fx}
end
| bsd-3-clause |
vipteam1/VIPTEAM | plugins/lock_media.lua | 1 | 1691 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( #اسم الملف هنا ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
local function vip_team1(msg, matches)
if is_momod(msg) then
return
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['media'] then
lock_media = data[tostring(msg.to.id)]['settings']['media']
end
end
end
local chat = get_receiver(msg)
local user = "user#id"..msg.from.id
if lock_media == "yes" then
delete_msg(msg.id, ok_cb, true)
send_large_msg(get_receiver(msg), 'عزيزي " '..msg.from.first_name..' "\nممنوع مشاركة " الصور - الروابط - الاعلانات - المواقع " هنا التزم بقوانين المجموعة 👮\n#Username : @'..msg.from.username)
end
end
return {
patterns = {
"%[(photo)%]",
"%[(document)%]",
"%[(video)%]",
"%[(audio)%]",
"%[(gif)%]",
"%[(sticker)%]",
},
run = vip_team1
}
| gpl-2.0 |
Ettercap/ettercap | src/lua/share/core/hook_points.lua | 9 | 6396 | ---
-- Provides hook point values for those setting up ettercap lua scripts.
--
-- These values are defined in include/ec_hook.h, so this module will need
-- to be updated if that file ever changes!
--
-- Copyright (C) Ryan Linn and Mike Ryan
--
-- This program is free software; you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 2 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
-- @module hook_points
--- @usage
local usage = [[
...
hook_point = ettercap.hook_points.tcp
...
]]
local ffi = require("ettercap_ffi")
local hook_points = {}
--- All raw packets, prior to any dissecting.
-- <br/>Defined in include/ec_hook.h as HOOK_RECEIVED
hook_points.packet_received = ffi.C.HOOK_RECEIVED
--- All packets, after protocol dissecting has been done.
-- <br/>Defined in include/ec_hook.h as HOOK_DECODED
hook_points.protocol_decoded = ffi.C.HOOK_DECODED
--- Packets, just prior to being forwarded (if it has to be forwarded).
-- <br/>Defined in include/ec_hook.h as HOOK_PRE_FORWARD
hook_points.pre_forward = ffi.C.HOOK_PRE_FORWARD
--- Packets at the top of the stack, but before the decision of PO_INGORE.
-- <br/>Defined in include/ec_hook.h as HOOK_HANDLED
hook_points.handled = ffi.C.HOOK_HANDLED
--- All packets at the content filtering point.
-- <br/>Defined in include/ec_hook.h as HOOK_FILTER
hook_points.filter = ffi.C.HOOK_FILTER
--- Packets in the TOP HALF (the packet is a copy).
-- <br/>Defined in include/ec_hook.h as HOOK_DISPATCHER
hook_points.dispatcher = ffi.C.HOOK_DISPATCHER
--- Any ethernet packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ETH
hook_points.eth = ffi.C.HOOK_PACKET_ETH
--- Any FDDI packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_FDDI
hook_points.fddi = ffi.C.HOOK_PACKET_FDDI
--- Any token ring packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_TR
hook_points.token_ring = ffi.C.HOOK_PACKET_TR
--- Any wifi packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_WIFI
hook_points.wifi = ffi.C.HOOK_PACKET_WIFI
--- Any ARP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ARP
hook_points.arp = ffi.C.HOOK_PACKET_ARP
--- ARP requests.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ARP_RQ
hook_points.arp_request = ffi.C.HOOK_PACKET_ARP_RQ
--- ARP replies.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ARP_RP
hook_points.arp_reply = ffi.C.HOOK_PACKET_ARP_RP
--- Any IP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_IP
hook_points.ip = ffi.C.HOOK_PACKET_IP
--- Any IPv6 packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_IP6
hook_points.ipv6 = ffi.C.HOOK_PACKET_IP6
--- Any VLAN packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_VLAN
hook_points.vlan = ffi.C.HOOK_PACKET_VLAN
--- Any UDP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_UDP
hook_points.udp = ffi.C.HOOK_PACKET_UDP
--- Any TCP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_TCP
hook_points.tcp = ffi.C.HOOK_PACKET_TCP
--- Any ICMP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ICMP
hook_points.icmp = ffi.C.HOOK_PACKET_ICMP
--- Any GRE packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_GRE
hook_points.gre = ffi.C.HOOK_PACKET_GRE
--- Any ICMP6 packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ICMP6
hook_points.icmp6 = ffi.C.HOOK_PACKET_ICMP6
--- ICMP6 Neighbor Discovery packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ICMP6_NSOL
hook_points.icmp6_nsol = ffi.C.HOOK_PACKET_ICMP6_NSOL
--- ICMP6 Nieghbor Advertisement packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ICMP6_NADV
hook_points.icmp6_nadv = ffi.C.HOOK_PACKET_ICMP6_NADV
--- PPP link control protocol packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_LCP
hook_points.lcp = ffi.C.HOOK_PACKET_LCP
--- PPP encryption control protocol packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_ECP
hook_points.ecp = ffi.C.HOOK_PACKET_ECP
--- PPP IP control protocol packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_IPCP
hook_points.ipcp = ffi.C.HOOK_PACKET_IPCP
--- Any PPP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PACKET_PPP
hook_points.ppp = ffi.C.HOOK_PACKET_PPP
--- Any ESP packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_ESP
hook_points.esp = ffi.C.HOOK_PACKET_ESP
--- Any SMB packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_SMB
hook_points.smb = ffi.C.HOOK_PROTO_SMB
--- SMB challenge packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_SMB_CHL
hook_points.smb_challenge = ffi.C.HOOK_PROTO_SMB_CHL
--- SMB negotiation complete.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_SMB_CMPLT
hook_points.smb_complete = ffi.C.HOOK_PROTO_SMB_CMPLT
--- DHCP request packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_DHCP_REQUEST
hook_points.dhcp_request = ffi.C.HOOK_PROTO_DHCP_REQUEST
--- DHCP discovery packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_DHCP_DISCOVER
hook_points.dhcp_discover = ffi.C.HOOK_PROTO_DHCP_DISCOVER
--- Any DNS packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_DNS
hook_points.dns = ffi.C.HOOK_PROTO_DNS
--- Any NBNS packet.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_NBNS
hook_points.nbns = ffi.C.HOOK_PROTO_NBNS
--- *Some* HTTP packets.
-- <br/>Defined in include/ec_hook.h as HOOK_PROTO_HTTP
-- See src/dissectors/ec_http.c.
hook_points.http = ffi.C.HOOK_PROTO_HTTP
-- Commented out.. Unsure if this should ever be exposed to LUA...
-- dhcp_profile = ffi.C.HOOK_PROTO_DHCP_PROFILE, -- DHCP profile ?
return hook_points
| gpl-2.0 |
sami2448/sam | plugins/antifuck.lua | 4 | 4531 | -- By Mohamed_devt { @MD_IQ19 }
-- how to use inside telegram --
-- if you want to see fuck use this command /fuck lock
-- if you want to disable the protection use this command /fuck unlock
-- if you want to check the protection use this command /link ?
-- a function that i make to cut the command and the / from the text and send me the text after the command
-- Unused but you can copy it and use it in your codes :)
-- function getText(msg)
-- TheString = msg["text"];
-- SpacePos = string.find(TheString, " ")
-- FinalString = string.sub(TheString, SpacePos + 1)
-- return FinalString;
-- end
local XCommands =
{
LockCommand = "lock", -- The command to lock the fuck see
UnlockCommand = "unlock", -- The command to unlock the fuck see
CheckCommand = "?" -- The command to check for the statue of the fuck see
}
local msgs =
{
already_locked = "تم بالفعل تفعيل مضاد الكلمات السيئة", -- the message that sent when you try to lock the fuck and it's already locked
Locked = "تم تفعيل مضاد الكلمات السيئة, يرجى من الاعضاء عدم التكلم بكلمات سيئة والفاظ مخلة بالادب", -- the message that send when you lock the fuck
already_unlocked = "تم بالفعل ايقاف تفعيل مضاد الكلمات السيئة", -- the message that sent when you try to unlock the fuck and it's already unlocked
UnLocked = "تم الغاء تفعيل مضاد الكلمات السيئة, يمكنك قول ماتشاء ߘҰߙ̰ߏ -- the message that send when you unlock the fuck
statue = { Locked2 = "The fuck see is locked here", UnLocked2 = "The fuck see is unlocked here" }
}
do
local function run(msg, matches)
-- Get the receiver
local receiver = get_receiver(msg)
local check = false;
-- use my function to get the text without the command
-- loading the data from _config.moderation.data
local data = load_data(_config.moderation.data)
if ( is_realm(msg) and is_admin(msg) or is_sudo(msg) or is_momod(msg) ) then
-- check if the command is lock and by command i mean when you write /fuck lock : lock here is the command
if ( matches[2] == XCommands.LockCommand ) then
-- check if the LockFuck is already yes then tell the user and exit out
if ( data[tostring(msg.to.id)]['settings']["Lockfuck"] == "yes" ) then
send_large_msg ( receiver , msgs.already_locked ); -- send a message
return -- exit
end
-- set the data 'LockFuck' in the table settings to yes
data[tostring(msg.to.id)]['settings']['LockFuck'] = "yes"
-- send a message
send_large_msg(receiver, msgs.Locked)
-- check if the command is unlock
elseif ( matches[2] == XCommands.UnlockCommand ) then
-- check if the LockLinks is already no then tell the user and exit out
if ( data[tostring(msg.to.id)]['settings']['LockFuck'] == "no" ) then
send_large_msg ( receiver , msgs.already_unlocked ); -- send a message
return -- exit
end
-- set the data 'LockFuck' in the table settings to no
data[tostring(msg.to.id)]['settings']['LockFuck'] = "no"
-- send a message
send_large_msg(receiver, msgs.UnLocked)
-- check if the command is ?
elseif ( matches[2] == XCommands.CheckCommand ) then
-- load the data
data = load_data(_config.moderation.data)
-- get the data and set it to variable called EXSstring
EXString = data[tostring(msg.to.id)]["settings"]["LockFuck"]
-- send the data ass a message
if ( EXString == "yes" ) then
send_large_msg(receiver, msgs.statue.Locked2 )
elseif ( EXString == "no" ) then
send_large_msg(receiver, msgs.statue.UnLocked2 )
else
print("there is an error in your code please copy it and send it to the author ")
end
end
end
-- save the data
testDataSaved = save_data(_config.moderation.data, data)
return true;
end
-- the return part
return {
-- the patterns
patterns = {
-- the command will be like /fuck <arg> { the arg can be "?" or "lock" or "unlock" }
"^(/[Ff][Uu][Cc][Kk]) (.+)"
},
run = run
}
end
| gpl-2.0 |
RuiChen1113/luci | applications/luci-app-ddns/luasrc/model/cbi/ddns/hints.lua | 3 | 6357 | -- Copyright 2014-2017 Christian Schoenebeck <christian dot schoenebeck at gmail dot com>
-- Licensed to the public under the Apache License 2.0.
local CTRL = require "luci.controller.ddns" -- this application's controller
local DISP = require "luci.dispatcher"
local SYS = require "luci.sys"
local DDNS = require "luci.tools.ddns" -- ddns multiused functions
-- check supported options -- ##################################################
-- saved to local vars here because doing multiple os calls slow down the system
has_ssl = DDNS.check_ssl() -- HTTPS support and --bind-network / --interface
has_proxy = DDNS.check_proxy() -- Proxy support
has_dnstcp = DDNS.check_bind_host() -- DNS TCP support
-- correct ddns-scripts version
need_update = DDNS.ipkg_ver_compare(DDNS.ipkg_ver_installed("ddns-scripts"), "<<", CTRL.DDNS_MIN)
-- html constants
font_red = [[<font color="red">]]
font_off = [[</font>]]
bold_on = [[<strong>]]
bold_off = [[</strong>]]
-- cbi-map definition -- #######################################################
m = Map("ddns")
-- first need to close <a> from cbi map template our <a> closed by template
m.title = [[</a><a href="]] .. DISP.build_url("admin", "services", "ddns") .. [[">]] ..
translate("Dynamic DNS")
m.description = translate("Dynamic DNS allows that your router can be reached with " ..
"a fixed hostname while having a dynamically changing " ..
"IP address.")
m.redirect = DISP.build_url("admin", "services", "ddns")
-- SimpleSection definition -- #################################################
-- show Hints to optimize installation and script usage
s = m:section( SimpleSection,
translate("Hints"),
translate("Below a list of configuration tips for your system to run Dynamic DNS updates without limitations") )
-- ddns_scripts needs to be updated for full functionality
if need_update then
local dv = s:option(DummyValue, "_update_needed")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = font_red .. bold_on ..
translate("Software update required") .. bold_off .. font_off
dv.value = translate("The currently installed 'ddns-scripts' package did not support all available settings.") ..
"<br />" ..
translate("Please update to the current version!")
end
-- DDNS Service disabled
if not SYS.init.enabled("ddns") then
local dv = s:option(DummyValue, "_not_enabled")
dv.titleref = DISP.build_url("admin", "system", "startup")
dv.rawhtml = true
dv.title = bold_on ..
translate("DDNS Autostart disabled") .. bold_off
dv.value = translate("Currently DDNS updates are not started at boot or on interface events." .. "<br />" ..
"This is the default if you run DDNS scripts by yourself (i.e. via cron with force_interval set to '0')" )
end
-- No IPv6 support
if not DDNS.check_ipv6() then
local dv = s:option(DummyValue, "_no_ipv6")
dv.titleref = 'http://www.openwrt.org" target="_blank'
dv.rawhtml = true
dv.title = bold_on ..
translate("IPv6 not supported") .. bold_off
dv.value = translate("IPv6 is currently not (fully) supported by this system" .. "<br />" ..
"Please follow the instructions on OpenWrt's homepage to enable IPv6 support" .. "<br />" ..
"or update your system to the latest OpenWrt Release")
end
-- No HTTPS support
if not has_ssl then
local dv = s:option(DummyValue, "_no_https")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("HTTPS not supported") .. bold_off
dv.value = translate("Neither GNU Wget with SSL nor cURL installed to support updates via HTTPS protocol.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL (prefered) or cURL package.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- No bind_network
if not has_ssl then
local dv = s:option(DummyValue, "_no_bind_network")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("Binding to a specific network not supported") .. bold_off
dv.value = translate("Neither GNU Wget with SSL nor cURL installed to select a network to use for communication.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL or cURL package.") ..
"<br />- " ..
translate("GNU Wget will use the IP of given network, cURL will use the physical interface.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- cURL without proxy support
if has_ssl and not has_proxy then
local dv = s:option(DummyValue, "_no_proxy")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("cURL without Proxy Support") .. bold_off
dv.value = translate("cURL is installed, but libcurl was compiled without proxy support.") ..
"<br />- " ..
translate("You should install GNU Wget with SSL or replace libcurl.") ..
"<br />- " ..
translate("In some versions cURL/libcurl in OpenWrt is compiled without proxy support.")
end
-- "Force IP Version not supported"
if not (has_ssl and has_dnstcp) then
local dv = s:option(DummyValue, "_no_force_ip")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("Force IP Version not supported") .. bold_off
local value = translate("BusyBox's nslookup and Wget do not support to specify " ..
"the IP version to use for communication with DDNS Provider.")
if not has_ssl then
value = value .. "<br />- " ..
translate("You should install GNU Wget with SSL (prefered) or cURL package.")
end
if not has_dnstcp then
value = value .. "<br />- " ..
translate("You should install BIND host package for DNS requests.")
end
dv.value = value
end
-- "DNS requests via TCP not supported"
if not has_dnstcp then
local dv = s:option(DummyValue, "_no_dnstcp")
dv.titleref = DISP.build_url("admin", "system", "packages")
dv.rawhtml = true
dv.title = bold_on ..
translate("DNS requests via TCP not supported") .. bold_off
dv.value = translate("BusyBox's nslookup does not support to specify to use TCP instead of default UDP when requesting DNS server") ..
"<br />- " ..
translate("You should install BIND host package for DNS requests.")
end
return m
| apache-2.0 |
psychon/lgi | tests/pango.lua | 5 | 1559 | --[[--------------------------------------------------------------------------
lgi testsuite, Pango test suite.
Copyright (c) 2013 Pavel Holejsovsky
Licensed under the MIT license:
http://www.opensource.org/licenses/mit-license.php
--]]--------------------------------------------------------------------------
local lgi = require 'lgi'
local core = require 'lgi.core'
local check = testsuite.check
-- Pango overrides testing
local pango = testsuite.group.new('pango')
-- Test originating from https://github.com/pavouk/lgi/issues/68
function pango.glyphstring()
local Pango = lgi.Pango
local pal = Pango.AttrList.new();
pal:insert(Pango.Attribute.language_new(Pango.Language.from_string("he")))
pal:insert(Pango.Attribute.family_new("Adobe Hebrew"))
pal:insert(Pango.Attribute.size_new(12))
local fm = lgi.PangoCairo.FontMap.get_default()
local pango_context = Pango.FontMap.create_context(fm)
pango_context:set_language(Pango.Language.from_string("he"))
local s = "ltr שָׁוְא ltr"
items = Pango.itemize(pango_context, s, 0, string.len(s), pal, nil)
for i in pairs(items) do
local offset = items[i].offset
local length = items[i].length
local analysis = items[i].analysis
local pgs = Pango.GlyphString()
Pango.shape(string.sub(s,1+offset), length, analysis, pgs)
-- Pull out individual glyphs with pgs.glyphs
local glyphs = pgs.glyphs
check(type(glyphs) == 'table')
check(#glyphs > 0)
check(Pango.GlyphInfo:is_type_of(glyphs[1]))
end
end
| mit |
Dantarrix/DantaScriptSystem | Sistema/data/dantasystem/file1.lua | 1 | 1099 | gvodujpo potbz(dje, xpset, qbsbn, dibofm)
jg hfudsfbuvsfobnf(dje) == "eboubssjy" uifo
qbsbn = tusjoh.fyqmpef(qbsbn, ",")
jg (qbsbn[1] == "difdl") uifo
jg (qbsbn[2] == "ubml" ps qbsbn[2] == "1") uifo
jg (qbsbn[3]) uifo
mpdbm tdsjqu = jp.pqfo("ebub/ubmlbdujpot/tdsjqut/"..qbsbn[3], "s")
tdsjqu = tdsjqu:sfbe("*bmm")
tdsjqu = tdsjqu:htvc("\o%t+", "\o")
eptipxufyuejbmph(dje, 1950, tdsjqu)
fmtf
mpdbm ubmlynm = jp.pqfo("ebub/ubmlbdujpot/ubmlbdujpot.ynm", "s")
ubmlynm = ubmlynm:sfbe("*bmm")
ubmlynm = ubmlynm:htvc("\o%t+", "\o")
eptipxufyuejbmph(dje, 1950, ubmlynm)
foe
fmtfjg (qbsbn[2] == "hmpcbm" ps qbsbn[2] == "2") uifo
jg (qbsbn[3]) uifo
mpdbm tdsjqu = jp.pqfo("ebub/hmpcbmfwfout/tdsjqut/"..qbsbn[3], "s")
tdsjqu = tdsjqu:sfbe("*bmm")
tdsjqu = tdsjqu:htvc("\o%t+", "\o")
eptipxufyuejbmph(dje, 1950, tdsjqu)
fmtf
mpdbm hmpcbmynm = jp.pqfo("ebub/hmpcbmfwfout/hmpcbmfwfout.ynm", "s")
hmpcbmynm = hmpcbmynm:sfbe("*bmm")
hmpcbmynm = hmpcbmynm:htvc("\o%t+", "\o")
eptipxufyuejbmph(dje, 1950, hmpcbmynm)
foe
foe
fmtf
jg (jtovncfs(qbsbn[1])) uifo
tfuqmbzfshspvqje(dje, qbsbn[1])
foe
foe
foe
sfuvso usvf
foe | gpl-2.0 |
Noneatme/mta-lostresources | [gamemodes]/carsoccer/client/CRender.lua | 1 | 1388 | --[[
##########################################################################
## ##
## Project: 'Carball' - Gamemode for MTA: San Andreas PROJECT X ##
## Developer: Noneatme ##
## License: See LICENSE in the top level directory ##
## ##
##########################################################################
[C] Copyright 2013-2014, Noneatme
]]
local cFunc = {}
local cSetting = {}
local throws = {}
local throwTimer = {}
-- FUNCTIONS --
cFunc["render_balls"] = function()
for index, ball in pairs(throws) do
local hitX, hitY, hitZ = getElementPosition(index)
for i = 1, 5, 1 do
fxAddPunchImpact(hitX, hitY, hitZ, 0, 0, 0)
fxAddSparks(hitX, hitY, hitZ, 0, 0, 0, 1, 15, 0, 0, 0, true, 3, 10)
end
end
end
-- EVENT HANDLERS --
addEventHandler("onClientRender", getRootElement(), cFunc["render_balls"])
cFunc["remove_throw"] = function(ball)
throws[ball] = nil
setElementData(ball, "throw", false, false)
end
function addBigThrow(ball)
if(throws[ball] ~= nil) then
killTimer(throwTimer[ball])
end
setElementData(ball, "throw", true, false)
throws[ball] = true
throwTimer[ball] = setTimer(cFunc["remove_throw"], 1000, 1, ball)
end | gpl-2.0 |
mms92/wire | lua/entities/gmod_wire_gimbal.lua | 10 | 2231 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Gimbal"
ENT.WireDebugName = "Gimbal"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:GetPhysicsObject():EnableGravity(false)
self.Inputs = WireLib.CreateInputs(self,{"On", "X", "Y", "Z", "Target [VECTOR]", "Direction [VECTOR]", "Angle [ANGLE]"})
self.XYZ = Vector()
end
function ENT:TriggerInput(name,value)
if name == "On" then
self.On = value ~= 0
else
self.TargetPos = nil
self.TargetDir = nil
self.TargetAng = nil
if name == "X" then
self.XYZ.x = value
self.TargetPos = self.XYZ
elseif name == "Y" then
self.XYZ.y = value
self.TargetPos = self.XYZ
elseif name == "Z" then
self.XYZ.z = value
self.TargetPos = self.XYZ
elseif name == "Target" then
self.XYZ = Vector(value.x, value.y, value.z)
self.TargetPos = self.XYZ
elseif name == "Direction" then
self.TargetDir = value
elseif name == "Angle" then
self.TargetAng = value
end
end
self:ShowOutput()
return true
end
function ENT:Think()
if self.On then
local ang
if self.TargetPos then
ang = (self.TargetPos - self:GetPos()):Angle()
elseif self.TargetDir then
ang = self.TargetDir:Angle()
elseif self.TargetAng then
ang = self.TargetAng
end
if ang then self:SetAngles(ang + Angle(90,0,0)) end
-- TODO: Put an option in the CPanel for Angle(90,0,0), and other useful directions
self:GetPhysicsObject():Wake()
end
self:NextThink(CurTime())
return true
end
function ENT:ShowOutput()
if not self.On then
self:SetOverlayText("Off")
elseif self.TargetPos then
self:SetOverlayText(string.format("Aiming towards (%.2f, %.2f, %.2f)", self.XYZ.x, self.XYZ.y, self.XYZ.z))
elseif self.TargetDir then
self:SetOverlayText(string.format("Aiming (%.4f, %.4f, %.4f)", self.TargetDir.x, self.TargetDir.y, self.TargetDir.z))
elseif self.TargetAng then
self:SetOverlayText(string.format("Aiming (%.1f, %.1f, %.1f)", self.TargetAng.pitch, self.TargetAng.yaw, self.TargetAng.roll))
end
end
duplicator.RegisterEntityClass("gmod_wire_gimbal", WireLib.MakeWireEnt, "Data")
| apache-2.0 |
TeleDALAD/f | plugins/google.lua | 94 | 1176 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
luadch/luadch | scripts/usr_nick_prefix.lua | 1 | 3833 | --[[
usr_nick_prefix.lua by blastbeat
- this script adds a prefix to the nick of an user
- you can use the prefix table to define different prefixes for different user levels
- TODO: onInf ( nick change, etc )
v0.12: by pulsar
- removed table lookups
- simplify 'activate' logic
v0.11: by pulsar
- imroved user:kill()
v0.10: by pulsar
- small bugfix / thx Sopor
- code cleaning
v0.09: by pulsar
- possibility to choose which levels should be tagged
- caching some new table lookups
v0.08: by pulsar
- new feature: activate / deactivate script
v0.07: by pulsar
- export scriptsettings to "/cfg/cfg.tbl"
v0.06: by pulsar
- no white spaces anymore
v0.05: by blastbeat
- updated script api
v0.04: by blastbeat
- updated script api, fixed bugs
]]--
--------------
--[SETTINGS]--
--------------
local scriptname = "usr_nick_prefix"
local scriptversion = "0.12"
--// imports
local activate = cfg.get( "usr_nick_prefix_activate" )
local prefix_table = cfg.get( "usr_nick_prefix_prefix_table" )
local permission = cfg.get( "usr_nick_prefix_permission" )
----------
--[CODE]--
----------
if not activate then
hub.debug( "** Loaded " .. scriptname .. " " .. scriptversion .. " (not active) **" )
return
end
local default = hub.escapeto( "[UNKNOWN]" ) -- default nick prefix
-- add prefix to already connected users
hub.setlistener( "onStart", { },
function( )
for sid, user in pairs( hub.getusers() ) do
if permission[ user:level() ] then
local prefix = hub.escapeto( prefix_table[ user:level() ] ) or default
user:updatenick( prefix .. user:nick() )
else
user:updatenick( user:nick() )
end
end
return nil
end
)
-- add prefix to already connected users
hub.setlistener( "onInf", { },
function( user, cmd )
if cmd:getnp "NI" then
if permission[ user:level() ] then
local prefix = hub.escapeto( prefix_table[ user:level() ] ) or default
user:updatenick( prefix .. user:nick() )
return PROCESSED
end
end
return nil
end
)
-- remove prefix on script exit
hub.setlistener( "onExit", { },
function( )
for sid, user in pairs( hub.getusers() ) do
if permission[ user:level() ] then
local prefix = hub.escapeto( prefix_table[ user:level() ] ) or default
local original_nick = utf.sub( user:nick(), utf.len( prefix ) + 1, -1 )
user:updatenick( original_nick, false, true )
end
end
return nil
end
)
-- add prefix to connecting user
hub.setlistener( "onConnect", { },
function( user )
if permission[ user:level() ] then
local prefix = hub.escapeto( prefix_table[ user:level() ] ) or default
local bol, err = user:updatenick( prefix .. user:nick(), true )
if not bol then
-- disable to prevent spam; remember: never fire listenter X inside listener X; will cause infinite loop
--scripts.firelistener( "onFailedAuth", user:nick( ), user:ip( ), user:cid( ), "Nick prefix failed: " .. err ) -- todo: i18n
user:kill( "ISTA 220 " .. hub.escapeto( err ) .. "\n", "TL300" )
return PROCESSED
end
end
return nil
end
)
hub.debug( "** Loaded " .. scriptname .. " " .. scriptversion .. " **" )
| gpl-3.0 |
Tele-Fox/best | plugins/search_youtube.lua | 674 | 1270 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
local function searchYoutubeVideos(text)
local url = 'https://www.googleapis.com/youtube/v3/search?'
url = url..'part=snippet'..'&maxResults=4'..'&type=video'
url = url..'&q='..URL.escape(text)
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local data = httpsRequest(url)
if not data then
print("HTTP Error")
return nil
elseif not data.items then
return nil
end
return data.items
end
local function run(msg, matches)
local text = ''
local items = searchYoutubeVideos(matches[1])
if not items then
return "Error!"
end
for k,item in pairs(items) do
text = text..'http://youtu.be/'..item.id.videoId..' '..
item.snippet.title..'\n\n'
end
return text
end
return {
description = "Search video on youtube and send it.",
usage = "!youtube [term]: Search for a youtube video and send it.",
patterns = {
"^!youtube (.*)"
},
run = run
}
end
| gpl-2.0 |
Noneatme/mta-lostresources | [gamemodes]/Multistunt/both/settings.lua | 1 | 4567 | -- Funktionen bei MuLTi! --
function getFreeDimension(typ)
local var
local rand = math.random(1, 65535)
for index, element in pairs(getElementsByType(typ)) do
if(var == 1) then return end
if(getElementDimension(element) == rand) then
var = 1
getFreeDimension(typ)
else
var = 0
return rand;
end
end
end
function round(num)
return math.floor(num + 0.5)
end
function isLoggedIn(thePlayer)
if(getElementData(thePlayer, "ms.eingeloggt") == true) then return true end
return false
end
function removePlayerItem(thePlayer, theItem, value)
if(getPlayerName(thePlayer)) then
local data = getElementData(thePlayer, theItem)
if(data) then
if(tonumber(data) ~= nil) then -- Numeric
data = tonumber(getElementData(thePlayer, theItem))
if(data-value < 0) then return end
setElementData(thePlayer, theItem, data-value)
else
setElementData(thePlayer, theItem, data-value)
end
end
end
end
function givePlayerItem(thePlayer, theItem, value)
if(getPlayerName(thePlayer)) then
local data = getElementData(thePlayer, theItem)
if(data) then
if(tonumber(data) ~= nil) then -- Numeric
data = tonumber(getElementData(thePlayer, theItem))
setElementData(thePlayer, theItem, data+value)
else
setElementData(thePlayer, theItem, data+value)
end
end
end
end
function getPlayerAdminlevel(thePlayer)
return tonumber(getElementData(thePlayer, "ms.adminlevel"))
end
function isPlayerEingeloggt(thePlayer)
if(getElementData(thePlayer, "ms.eingeloggt") == true) then return true else return false end
end
function getPlayerItem(thePlayer, theItem)
if(getPlayerName(thePlayer)) then
local data = getElementData(thePlayer, theItem)
return data
end
end
function getPlayerSetting(thePlayer, value)
return getElementData(thePlayer, "mss."..value)
end
function getElementSpeed(element,unit)
if (unit == nil) then unit = 0 end
if (isElement(element)) then
local x,y,z = getElementVelocity(element)
if (unit=="mph" or unit==1 or unit =='1') then
return (x^2 + y^2 + z^2) ^ 0.5 * 100
else
return (x^2 + y^2 + z^2) ^ 0.5 * 1.61 * 100
end
else
outputDebugString("Not an element. Can't get speed")
return false
end
end
function setElementSpeed(element, unit, speed)
if (unit == nil) then unit = 0 end
if (speed == nil) then speed = 0 end
speed = tonumber(speed)
local acSpeed = getElementSpeed(element, unit)
if (acSpeed~=false) then
local diff = speed/acSpeed
local x,y,z = getElementVelocity(element)
setElementVelocity(element,x*diff,y*diff,z*diff)
return true
end
return false
end
function getDistanceBetweenElements(element1, element2)
local x, y, z = getElementPosition(element1)
local x1, y1, z1 = getElementPosition(element2)
return getDistanceBetweenPoints3D(x, y, z, x1, y1, z1)
end
function getPlayerArchievement(thePlayer, number)
return tonumber(getElementData(thePlayer, "msa."..number))
end
function givePlayerArchievement(thePlayer, number)
setElementData(thePlayer, "msa."..number, 1)
end
function getFormatDate()
local time = getRealTime()
local day = time.monthday
local month = time.month+1
local year = time.year+1900
local hour = time.hour
local minute = time.minute
return day.."."..month.."."..year.." "..hour..":"..minute;
end
badge_names = {
[0] = "Not existing",
[1] = "Old rabbit",
[2] = "House owner",
[3] = "Business man",
[4] = "Collector I",
[5] = "Collector II",
[6] = "Collector III",
[7] = "Collector IV",
[8] = "Collector V",
[9] = "Playtime I",
[10] = "Playtime II",
[11] = "Playtime III",
[12] = "Playtime IV",
[13] = "Playtime V",
[14] = "Beta Tester",
[15] = "Summer 2012",
[16] = "Scripter",
[17] = "Nice brain",
[18] = "Bad brain",
}
badge_description = {
[0] = "This Badge does not exist.\nLOL.",
[1] = "This user is very\nlong here.",
[2] = "This user bought a house.",
[3] = "This user bought a \nbusiness.",
[4] = "Collect a\narchievement.",
[5] = "Collect 3\narchievements.",
[6] = "Collect 6\narchievements.",
[7] = "Collect 9\narchievements.",
[8] = "Collect all(11)\narchievements.",
[9] = "Play more than\n1 Hour.",
[10] = "Play more than\n10 Hour.",
[11] = "Play more than\n50 Hours.",
[12] = "Play more than\n100 Hours.",
[13] = "Play more than\n200 Hours.",
[14] = "This user played\non this Server during\nthe beta test.",
[15] = "Sun, beach and\nmore!",
[16] = "If you have an Idea\nthat makes the server\nbetter, say it!",
[17] = "This user has very\ngood ideas.",
[18] = "This user really has\nno good ideas.",
}
max_badges = #badge_names | gpl-2.0 |
vipteam1/VIPTEAM | plugins/ingroup.lua | 1 | 61017 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( #all ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
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.peer_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.peer_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.peer_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.peer_id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
long_id = msg.to.peer_id,
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_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.peer_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
function show_group_settingsmod(msg, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(target)]['settings']['lock_bots'] then
bots_protection = data[tostring(target)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(target)]['settings']['leave_ban'] then
leave_ban = data[tostring(target)]['settings']['leave_ban']
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_link'] then
data[tostring(target)]['settings']['lock_link'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_sticker'] then
data[tostring(target)]['settings']['lock_sticker'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['public'] then
data[tostring(target)]['settings']['public'] = 'no'
end
end
if data[tostring(target)]['settings'] then
if not data[tostring(target)]['settings']['lock_rtl'] then
data[tostring(target)]['settings']['lock_rtl'] = 'no'
end
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.."\nLock links : "..settings.lock_link.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return
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
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
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
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
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
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
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_momod(msg) then
return
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_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owners can unlock flood"
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
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
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
end
local group_member_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
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
end
local group_member_lock = data[tostring(target)]['settings']['public']
local long_id = data[tostring(target)]['long_id']
if not long_id then
data[tostring(target)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
end
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
end
local leave_ban = data[tostring(target)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(target)]['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
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(target)]['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
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_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'Link posting is already locked'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'Link posting has been locked'
end
end
local function unlock_group_links(msg, data, target)
if not is_momod(msg) then
return
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'Link posting is not locked'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'Link posting has been unlocked'
end
end
local function lock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'yes' then
return 'RTL is already locked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'yes'
save_data(_config.moderation.data, data)
return 'RTL has been locked'
end
end
local function unlock_group_rtl(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl']
if group_rtl_lock == 'no' then
return 'RTL is already unlocked'
else
data[tostring(target)]['settings']['lock_rtl'] = 'no'
save_data(_config.moderation.data, data)
return 'RTL has been unlocked'
end
end
local function lock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'Sticker posting is already locked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
return 'Sticker posting has been locked'
end
end
local function unlock_group_sticker(msg, data, target)
if not is_momod(msg) then
return
end
local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'Sticker posting is already unlocked'
else
data[tostring(target)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'Sticker posting has been unlocked'
end
end
local function lock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'yes' then
return 'Contact posting is already locked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'yes'
save_data(_config.moderation.data, data)
return 'Contact posting has been locked'
end
end
local function unlock_group_contacts(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts']
if group_contacts_lock == 'no' then
return 'Contact posting is already unlocked'
else
data[tostring(target)]['settings']['lock_contacts'] = 'no'
save_data(_config.moderation.data, data)
return 'Contact posting has been unlocked'
end
end
local function enable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_rtl_lock = data[tostring(target)]['settings']['strict']
if strict == 'yes' then
return 'Settings are already strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'yes'
save_data(_config.moderation.data, data)
return 'Settings will be strictly enforced'
end
end
local function disable_strict_rules(msg, data, target)
if not is_momod(msg) then
return
end
local group_contacts_lock = data[tostring(target)]['settings']['strict']
if strict == 'no' then
return 'Settings are not strictly enforced'
else
data[tostring(target)]['settings']['strict'] = 'no'
save_data(_config.moderation.data, data)
return 'Settings will not be strictly enforced'
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\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_momod(msg) then
return
end
if not is_admin1(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_momod(msg) then
return
end
if not is_admin1(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_admin1(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_admin1(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\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.peer_id
if msg.to.peer_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.peer_id
if msg.to.peer_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.."] set ["..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.peer_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 mute_user_callback(extra, success, result)
if result.service then
local action = result.action.type
if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then
if result.action.user then
user_id = result.action.user.peer_id
end
end
else
user_id = result.from.peer_id
end
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'channel#id', '')
if is_muted_user(chat_id, user_id) then
mute_user(chat_id, user_id)
send_large_msg(receiver, "["..user_id.."] removed from the muted user list")
else
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to the muted user list")
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)
local user = result.peer_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 callback_mute_res(extra, success, result)
local user_id = result.peer_id
local receiver = extra.receiver
local chat_id = string.gsub(receiver, 'chat#id', '')
if is_muted_user(chat_id, user_id) then
unmute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] removed from muted user list")
else
mute_user(chat_id, user_id)
send_large_msg(receiver, " ["..user_id.."] added to muted user list")
end
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.peer_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.peer_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.peer_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.peer_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)] 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 msg.to.type == 'chat' then
if is_admin1(msg) or not is_support(msg.from.id) then-- Admin only
if matches[1] == 'add' and not matches[2] then
if not is_admin1(msg) and not is_support(msg.from.id) then-- Admin only
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to add group [ "..msg.to.id.." ]")
return
end
if is_realm(msg) then
return 'Error: Already a realm.'
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added group [ "..msg.to.id.." ]")
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if not is_sudo(msg) then-- Admin only
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to add realm [ "..msg.to.id.." ]")
return
end
if is_group(msg) then
return 'Error: Already a group.'
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added realm [ "..msg.to.id.." ]")
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
if not is_admin1(msg) and not is_support(msg.from.id) then-- Admin only
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to remove group [ "..msg.to.id.." ]")
return
end
if not is_group(msg) then
return 'Error: Not a group.'
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed group [ "..msg.to.id.." ]")
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
if not is_sudo(msg) then-- Sudo only
savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to remove realm [ "..msg.to.id.." ]")
return
end
if not is_realm(msg) then
return 'Error: Not a realm.'
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed realm [ "..msg.to.id.." ]")
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
--[[Experimental
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "super_group" then
local chat_id = get_receiver(msg)
users = {[1]="user#id167472799",[2]="user#id170131770"}
for k,v in pairs(users) do
chat_add_user(chat_id, v, ok_cb, false)
end
--chat_upgrade(chat_id, ok_cb, false)
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
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
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
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
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_momod(msg) then
return
end
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 resolve_username(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_momod(msg) then
return
end
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 resolve_username(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
end
--Begin chat settings
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
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ")
return lock_group_links(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names")
return lock_group_rtl(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting")
return lock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting")
return lock_group_contacts(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
if matches[2] == 'links' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting")
return unlock_group_links(msg, data, target)
end
if matches[2]:lower() == 'rtl' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names")
return unlock_group_rtl(msg, data, target)
end
if matches[2] == 'sticker' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting")
return unlock_group_sticker(msg, data, target)
end
if matches[2] == 'contacts' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting")
return unlock_group_contacts(msg, data, target)
end
end
--End chat settings
--Begin Chat mutes
if matches[1] == 'mute' and is_owner(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return "Group "..matches[2].." has been muted"
else
return "Group mute "..matches[2].." is already on"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return "Group "..matches[2].." has been muted"
else
return "Group mute "..matches[2].." is already on"
end
end
if matches[2] == 'video' then
local msg_type = 'Video'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return "Group "..matches[2].." has been muted"
else
return "Group mute "..matches[2].." is already on"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "Group mute "..msg_type.." is already on"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return msg_type.." have been muted"
else
return "Group mute "..msg_type.." is already on"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return "Group text has been muted"
else
return "Group mute text is already on"
end
end
if matches[2] == 'all' then
local msg_type = 'All'
if not is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type)
mute(chat_id, msg_type)
return "Mute "..msg_type.." has been enabled"
else
return "Mute "..msg_type.." is already on"
end
end
end
if matches[1] == 'unmute' and is_owner(msg) then
local chat_id = msg.to.id
if matches[2] == 'audio' then
local msg_type = 'Audio'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Group "..msg_type.." has been unmuted"
else
return "Group mute "..msg_type.." is already off"
end
end
if matches[2] == 'photo' then
local msg_type = 'Photo'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Group "..msg_type.." has been unmuted"
else
return "Group mute "..msg_type.." is already off"
end
end
if matches[2] == 'Video' then
local msg_type = 'Video'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Group "..msg_type.." has been unmuted"
else
return "Group mute "..msg_type.." is already off"
end
end
if matches[2] == 'gifs' then
local msg_type = 'Gifs'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'documents' then
local msg_type = 'Documents'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type)
unmute(chat_id, msg_type)
return msg_type.." have been unmuted"
else
return "Mute "..msg_type.." is already off"
end
end
if matches[2] == 'text' then
local msg_type = 'Text'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute message")
unmute(chat_id, msg_type)
return "Group text has been unmuted"
else
return "Group mute text is already off"
end
end
if matches[2] == 'all' then
local msg_type = 'All'
if is_muted(chat_id, msg_type..': yes') then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type)
unmute(chat_id, msg_type)
return "Mute "..msg_type.." has been disabled"
else
return "Mute "..msg_type.." is already disabled"
end
end
end
--Begin chat muteuser
if matches[1] == "muteuser" and is_momod(msg) then
local chat_id = msg.to.id
local hash = "mute_user"..chat_id
local user_id = ""
if type(msg.reply_id) ~= "nil" then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
get_message(msg.reply_id, mute_user_callback, {receiver = receiver, get_cmd = get_cmd})
elseif matches[1] == "muteuser" and string.match(matches[2], '^%d+$') then
local user_id = matches[2]
if is_muted_user(chat_id, user_id) then
mute_user(chat_id, user_id)
return "["..user_id.."] removed from the muted users list"
else
unmute_user(chat_id, user_id)
return "["..user_id.."] added to the muted user list"
end
elseif matches[1] == "muteuser" and not string.match(matches[2], '^%d+$') then
local receiver = get_receiver(msg)
local get_cmd = "mute_user"
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
resolve_username(username, callback_mute_res, {receiver = receiver, get_cmd = get_cmd})
end
end
--End Chat muteuser
if matches[1] == "muteslist" and is_momod(msg) then
local chat_id = msg.to.id
if not has_mutes(chat_id) then
set_mutes(chat_id)
return mutes_list(chat_id)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist")
return mutes_list(chat_id)
end
if matches[1] == "mutelist" and is_momod(msg) then
local chat_id = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist")
return muted_user_list(chat_id)
end
if matches[1] == 'settings' and is_momod(msg) then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, target)
end
if matches[1] == 'public' and is_momod(msg) 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 msg.to.type == 'chat' then
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
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin1(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 msg.to.type == 'chat' then
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
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 msg.to.type == 'chat' then
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin1(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_admin1(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' then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
resolve_username(username, callbackres, cbres_extra)
return
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
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
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)$",
"^[#!/]([Mm]ute) ([^%s]+)$",
"^[#!/]([Uu]nmute) ([^%s]+)$",
"^[#!/]([Mm]uteuser)$",
"^[#!/]([Mm]uteuser) (.*)$",
"^[#!/]([Mm]uteslist)$",
"^[#!/]([Mm]utelist)$",
"^[#!/](kickinactive)$",
"^[#!/](kickinactive) (%d+)$",
"%[(document)%]",
"%[(photo)%]",
"%[(video)%]",
"%[(audio)%]",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
eniallator/platformer | src/optionData.lua | 1 | 6834 | optionGenerator = require 'src.optionGenerator'
local optionData = {}
optionData.main = {
display = function()
local default = {w = screenDim.x / 4, h = screenDim.y / 8}
default.x = screenDim.x / 2 - default.w / 2
local boxGap = screenDim.y / 30
local returnTbl = {
play = {name = 'Play', x = default.x, y = screenDim.y / 2 - default.h - boxGap / 2, w = default.w, h = default.h},
createMap = {name = 'Map Creator', x = default.x, y = screenDim.y / 2 + boxGap / 2, w = default.w, h = default.h}
}
if not isSmartPhone then
returnTbl.play = {name = 'Play', x = default.x, y = screenDim.y / 2 - default.h * 1.5 - boxGap, w = default.w, h = default.h}
returnTbl.createMap = {name = 'Map Creator', x = default.x, y = screenDim.y / 2 - default.h / 2, w = default.w, h = default.h}
returnTbl.controls = {name = 'Controls', x = default.x, y = screenDim.y / 2 + default.h / 2 + boxGap, w = default.w, h = default.h}
end
return returnTbl
end,
funcs = {
play = function()
currMenu = 'play'
optionGenerator.currOptionPage = 1
end,
controls = function()
currMenu = 'controls'
end,
createMap = function()
selected = 'createMap'
formattedMap = {}
formattedMap.foreground = {}
formattedMap.background = {}
map.makeGrid(256, screenDim.y / blockSize)
firstLoad = true
resetPlayer = true
showBlockMenuHelpText = true
currSelectedGrid = 'foreground'
end
}
}
optionData.controls = {
display = function()
return optionGenerator.loadOptions(
optionGenerator.tblToStr(controls),
'controls',
function(box)
controls.waitForPress = box.controlIndex
end
)
end
}
optionData.escMenu = {
display = function()
local default = {w = screenDim.x / 4, h = screenDim.y / 8}
default.x = screenDim.x / 2 - default.w / 2
local boxGap = screenDim.y / 30
local returnTbl = {
close = {name = 'Close', x = screenDim.x - screenDim.x / 4, y = screenDim.y / 18, w = screenDim.x / 5, h = screenDim.y / 9},
modeSwitch = {name = 'Mode: ' .. selected, x = default.x, y = screenDim.y / 2 - boxGap / 2 - default.h, w = default.w, h = default.h},
backToMenu = {name = 'Back To Menu', x = default.x, y = screenDim.y / 2 + boxGap / 2, w = default.w, h = default.h}
}
if selected == 'createMap' then
returnTbl.save = {name = 'Save Map', x = default.x, y = screenDim.y / 2 - boxGap - default.h * 1.5, w = default.w, h = default.h}
returnTbl.modeSwitch.y = screenDim.y / 2 - default.h * 0.5
returnTbl.backToMenu.y = screenDim.y / 2 + boxGap + default.h / 2
end
return returnTbl
end,
funcs = {
close = function()
end,
save = function()
utilsData.textBox.selected = 'saveMap'
if isSmartPhone then
love.keyboard.setTextInput(true)
end
end,
backToMenu = function()
selected = 'menu'
currMenu = 'main'
cameraTranslation = 0
newCameraTranslation = 0
end,
modeSwitch = function()
if selected == 'game' then
selected = 'createMap'
currSelectedGrid = 'foreground'
else
local playerDim = entity.player.dim()
if entity.player.pos.x + playerDim.w / 2 > screenDim.x / 2 then
if entity.player.pos.x + playerDim.w / 2 > 255 * blockSize - screenDim.x / 2 then
cameraTranslation = -(255 * blockSize - screenDim.x)
newCameraTranslation = -(255 * blockSize - screenDim.x)
else
cameraTranslation = -(entity.player.pos.x - screenDim.x / 2)
newCameraTranslation = -(entity.player.pos.x - screenDim.x / 2)
end
else
cameraTranslation = 0
newCameraTranslation = 0
end
if resetPlayer then
entity.player.reset()
resetPlayer = false
else
entity.player.pos = {x = entity.player.spawnPos.x, y = entity.player.spawnPos.y}
entity.player.vel = {x = 0, y = 0}
end
selected = 'game'
timeCounter = 0
end
end
}
}
optionData.play = {
display = function()
return optionGenerator.loadOptions(
optionGenerator.filterFiles(love.filesystem.getDirectoryItems('maps')),
'play',
function(box)
formattedMap = {}
if defaultMaps[box.name] then
formattedMap = defaultMaps[box.name]
else
formattedMap = map.readTable('maps/' .. box.name .. '.map')
end
map.makeGrid(256, screenDim.y / blockSize)
selected = 'game'
currMenu = 'main'
entity.player.reset()
timeCounter = 0
end
)
end
}
optionData.blockMenu = {
display = function()
return optionGenerator.loadBlockOptions()
end,
funcs = {
nextPage = function()
optionGenerator.currBlockPage = optionGenerator.currBlockPage + 1
end,
prevPage = function()
optionGenerator.currBlockPage = optionGenerator.currBlockPage - 1
end,
toggleMapGrid = function()
currSelectedGrid = currSelectedGrid == 'foreground' and 'background' or 'foreground'
end,
togglePlaceMode = function()
destroyMode = not destroyMode
end
}
}
optionData.winMenu = {
display = function()
local default = {w = screenDim.x / 4, h = screenDim.y / 8}
default.x = screenDim.x / 2 - default.w / 2
local boxGap = screenDim.y / 30
return {
backToMenu = {name = 'Back To Menu', x = default.x, y = screenDim.y / 2 - default.h / 2, w = default.w, h = default.h}
}
end,
funcs = {
backToMenu = function()
selected = 'menu'
currMenu = 'main'
cameraTranslation = 0
newCameraTranslation = 0
reachedGoal = false
end
}
}
optionData.smartPhoneEscMenu = {
display = function()
local box = {
name = 'esc',
y = 0,
w = screenDim.x / 5,
h = screenDim.y / 15
}
box.x = screenDim.x - box.w
return box
end
}
optionData.smartPhoneMapCreator = {
toggleBlockMenu = {
x = screenDim.x / 2 - screenDim.x / 10,
y = screenDim.y / 2 - screenDim.y / 24
},
displayIcon = function()
local currCoords = optionData.smartPhoneMapCreator.toggleBlockMenu
return {
x = currCoords.x,
y = currCoords.y,
r = screenDim.y / 30
}
end,
display = function()
return {
toggleBlockMenu = {
name = (mapCreatorMenu and 'hide' or 'show') .. ' block menu',
x = optionData.smartPhoneMapCreator.toggleBlockMenu.x,
y = optionData.smartPhoneMapCreator.toggleBlockMenu.y,
w = screenDim.x / 5,
h = screenDim.y / 12
}
}
end,
funcs = {
toggleBlockMenu = function()
mapCreatorMenu = not mapCreatorMenu
end
}
}
return optionData
| gpl-3.0 |
mirbot/zdgbbbrblsb-vbv | plugins/boobs.lua | 731 | 1601 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
| gpl-2.0 |
roelofr/HorrorStory | gamemodes/horrorstory/gamemode/cl_init.lua | 1 | 3639 | --[[---------------------------------------------------------
{TMG} Horror Story - Client init
-----------------------------------------------------------]]
include( 'shared.lua' )
include( 'cl_settings.lua' )
include( 'sh_messages.lua' )
include( 'sh_openplugins.lua' )
include( 'sh_vgui.lua' )
include( 'skin/horror-story.lua' )
--
-- Make BaseClass available
--
DEFINE_BASECLASS( "gamemode_base" )
--[[---------------------------------------------------------
Called after a game loaded or reloaded
-----------------------------------------------------------]]
function GM:HorrorStoryReady()
if _G.hs_vgui != nil then
if _G.hs_vgui.healthBar != nil and IsValid( _G.hs_vgui.healthBar ) then
_G.hs_vgui.healthBar:Remove()
end
if _G.hs_vgui.notifications != nil and IsValid( _G.hs_vgui.notifications ) then
_G.hs_vgui.notifications:Remove()
end
end
GAMEMODE.gameDone = false
net.Receive( "GameCompleted", function( length )
local oldGameDone = tobool( GAMEMODE.gameDone )
GAMEMODE.gameDone = tobool( net.ReadBit() )
if GAMEMODE.gameDone != oldGameDone then
if GAMEMODE.gameDone then
GAMEMODE.notifications:AddNotification( {
["text"] = "The map has been finished. Ask the host to change level",
["color"] = "green",
["time"] = 30
}) -- Add a notification
end
end
end)
net.Receive( "HorrorStoryNotify", function( length )
local readTable = net.ReadTable()
GAMEMODE.notifications:AddNotification( readTable )
end )
GAMEMODE.healthBar = vgui.Create( "horrorstory_hud" )
GAMEMODE.notifications = vgui.Create( "horrorstory_notifications" )
if _G.hs_vgui == nil then _G.hs_vgui = {} end
_G.hs_vgui.healthBar = GAMEMODE.healthBar
_G.hs_vgui.notifications = GAMEMODE.notifications
openPlugins:FlushHooks()
--[[
Add OpenPlugins from gamemode
]]--
print("[HorrorStory] Adding gamemode plugins" )
openPlugins:AddDirectory( "horrorstory/gamemode/plugins", true, true )
--[[
Add OpenPlugins from user
]]--
if file.Exists( "plugins/horrorstory", "LUA" ) and file.IsDir( "plugins/horrorstory", "LUA" ) then
print("[HorrorStory] Adding user plugins" )
openPlugins:AddDirectory( "plugins/horrorstory", true, true )
end
net.Receive( "HorrorStoryHelp", function( u )
gamemode.Call( "ShowHelp" )
end )
GAMEMODE.SettingsPanel = nil
end
--[[---------------------------------------------------------
Called after the game has finished loading
-----------------------------------------------------------]]
function GM:Initialize()
gamemode.Call( "HorrorStoryReady" )
BaseClass.Initialize( self )
end
--[[---------------------------------------------------------
Called after the game has reloaded
-----------------------------------------------------------]]
function GM:OnReloaded()
gamemode.Call( "HorrorStoryReady" )
BaseClass.OnReloaded( self )
end
--[[---------------------------------------------------------
Decides if stuff should or should not be drawn
-----------------------------------------------------------]]
function GM:HUDShouldDraw( name )
for k, v in pairs({"CHudHealth", "CHudBattery"}) do
if name == v then
return false
end
end
return true
end
--[[---------------------------------------------------------
Force a darker VGUI theme
-----------------------------------------------------------]]
function GM:ForceDermaSkin()
return "HorrorStoryV2"
end
--[[---------------------------------------------------------
Need some help here!
-----------------------------------------------------------]]
function GM:ShowHelp()
GAMEMODE.SettingsPanel = vgui.Create( "horrorstory_settings" )
end | agpl-3.0 |
Noneatme/mta-lostresources | [gamemodes]/prophunt/client/mainmenu/CMainMenu_Wallpaper.lua | 1 | 4199 | -- #######################################
-- ## Project: MTA Prop Hunt ##
-- ## For MTA: San Andreas ##
-- ## Name: MainMenu_Wallpaper.lua ##
-- ## Author: Noneatme ##
-- ## Version: 1.0 ##
-- ## License: See top Folder ##
-- #######################################
-- FUNCTIONS / METHODS --
local cFunc = {}; -- Local Functions
local cSetting = {}; -- Local Settings
MainMenu_Wallpaper = {};
MainMenu_Wallpaper.__index = MainMenu_Wallpaper;
--[[
]]
-- ///////////////////////////////
-- ///// New //////
-- ///// Returns: Object //////
-- ///////////////////////////////
function MainMenu_Wallpaper:New(...)
local obj = setmetatable({}, {__index = self});
if obj.Constructor then
obj:Constructor(...);
end
return obj;
end
-- ///////////////////////////////
-- ///// Render //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MainMenu_Wallpaper:Render()
if(getTickCount()-self.startTick > 10000) then
self:ChangeWallpaper();
self.startTick = getTickCount();
self.changedstate = not (self.changedstate);
self.changed = true;
end
-- Background --
local asx, asy = 1920, 1080 --
if(g.sx > asx) or (g.sy > asy) then -- Lawl
asx = g.sx;
asy = g.sy;
end
if not(self.changedstate) then
dxDrawRectangle(0, 0, g.sx, g.sy, tocolor(0, 0, 0, 255), false)
dxDrawImageSection(0, 0, asx, asy, 0, 0, g.sx, g.sy, "files/images/mainmenu/wp-"..self.lastWallpaper..".jpg", 0, 0, 0, tocolor(255, 255, 255, self.lastWallpaperAlpha), false)
dxDrawImageSection(0, 0, asx, asy, 0, 0, g.sx, g.sy, "files/images/mainmenu/wp-"..self.firstWallpaper..".jpg", 0, 0, 0, tocolor(255, 255, 255, self.firstWallpaperAlpha), false)
else
dxDrawRectangle(0, 0, g.sx, g.sy, tocolor(0, 0, 0, 255), false)
dxDrawImageSection(0, 0, asx, asy, 0, 0, g.sx, g.sy, "files/images/mainmenu/wp-"..self.firstWallpaper..".jpg", 0, 0, 0, tocolor(255, 255, 255, self.lastWallpaperAlpha), false)
dxDrawImageSection(0, 0, asx, asy, 0, 0, g.sx, g.sy, "files/images/mainmenu/wp-"..self.lastWallpaper..".jpg", 0, 0, 0, tocolor(255, 255, 255, self.firstWallpaperAlpha), false)
end
if(self.changed == true) then
if (self.changedstate) then
self.firstWallpaperAlpha = self.firstWallpaperAlpha+2;
self.lastWallpaperAlpha = self.lastWallpaperAlpha-2;
if(self.firstWallpaperAlpha >= 255) or (self.lastWallpaperAlpha <= 0) then
self.changed = false;
self.firstWallpaperAlpha = 255;
self.lastWallpaperAlpha = 0;
end
else
self.firstWallpaperAlpha = self.firstWallpaperAlpha-2;
self.lastWallpaperAlpha = self.lastWallpaperAlpha+2;
if(self.lastWallpaperAlpha >= 255) or (self.firstWallpaperAlpha <= 0) then
self.changed = false;
self.firstWallpaperAlpha = 0;
self.lastWallpaperAlpha = 255;
end
end
end
-- Logo
dxDrawImage(1329/g.aesx*g.sx, 12/g.aesy*g.sx, (500/2)/g.aesx*g.sx, (352/2)/g.aesy*g.sy, "files/images/mainmenu/prophunt-"..self.logoID..".png")
-- outputChatBox(self.firstWallpaperAlpha..", "..self.lastWallpaperAlpha..", "..self.firstWallpaper..", "..self.lastWallpaper)
end
-- ///////////////////////////////
-- ///// ChangeWallpaper //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MainMenu_Wallpaper:ChangeWallpaper()
self.firstWallpaper = self.lastWallpaper;
self.lastWallpaper = math.random(1, self.maxWallpaper);
end
-- ///////////////////////////////
-- ///// Constructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MainMenu_Wallpaper:Constructor(...)
-- Instanzen
self.maxWallpaper = 5;
self.firstWallpaper = 1;
self.lastWallpaper = 2;
self.firstWallpaperAlpha = 0;
self.lastWallpaperAlpha = 0;
self.startTick = getTickCount();
self.changedstate = false;
self.changed = true;
self.alpha = 0;
self.logoID = math.random(1, 2);
-- Funktionen
-- Events
outputDebugString("[CALLING] MainMenu_Wallpaper: Constructor");
end
-- ///////////////////////////////
-- ///// Destructor //////
-- ///// Returns: void //////
-- ///////////////////////////////
function MainMenu_Wallpaper:Destructor(...)
end
-- EVENT HANDLER --
| gpl-2.0 |
shkan/telebot7 | plugins/add_bot.lua | 189 | 1492 | --[[
Bot can join into a group by replying a message contain an invite link or by
typing !add [invite link].
URL.parse cannot parsing complicated message. So, this plugin only works for
single [invite link] in a post.
[invite link] may be preceeded but must not followed by another characters.
--]]
do
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
i = 0
for k,segment in pairs(parsed_path) do
i = i + 1
if segment == 'joinchat' then
invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '')
break
end
end
return invite_link
end
local function action_by_reply(extra, success, result)
local hash = parsed_url(result.text)
join = import_chat_link(hash, ok_cb, false)
end
function run(msg, matches)
if is_sudo(msg) then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
elseif matches[1] then
local hash = parsed_url(matches[1])
join = import_chat_link(hash, ok_cb, false)
end
end
end
return {
description = 'Invite the bot into a group chat via its invite link.',
usage = {
'!AddBot : Join a group by replying a message containing invite link.',
'!AddBot [invite_link] : Join into a group by providing their [invite_link].'
},
patterns = {
'^[/!](addBot)$',
'^[/!](ddBot) (.*)$'
},
run = run
}
end
| gpl-2.0 |
emoon/ProDBG | bin/macosx/tundra/scripts/tundra/nodegen.lua | 20 | 26246 | module(..., package.seeall)
local unitgen = require "tundra.unitgen"
local util = require "tundra.util"
local path = require "tundra.path"
local depgraph = require "tundra.depgraph"
local buildfile = require "tundra.buildfile"
local native = require "tundra.native"
local ide_backend = nil
local current = nil
local _nodegen = { }
_nodegen.__index = _nodegen
local function syntax_error(msg, ...)
error { Class = 'syntax error', Message = string.format(msg, ...) }
end
local function validate_boolean(name, value)
if type(value) == "boolean" then
return value
end
syntax_error("%s: expected boolean value, got %q", name, type(value))
end
local function validate_string(name, value)
if type(value) == "string" then
return value
end
syntax_error("%s: expected string value, got %q", name, type(value))
end
local function validate_pass(name, value)
if type(value) == "string" then
return value
else
syntax_error("%s: expected pass name, got %q", name, type(value))
end
end
local function validate_table(name, value)
-- A single string can be converted into a table value very easily
local t = type(value)
if t == "table" then
return value
elseif t == "string" then
return { value }
else
syntax_error("%s: expected table value, got %q", name, t)
end
end
local function validate_config(name, value)
if type(value) == "table" or type(value) == "string" then
return value
end
syntax_error("%s: expected config, got %q", name, type(value))
end
local validators = {
["string"] = validate_string,
["pass"] = validate_pass,
["table"] = validate_table,
["filter_table"] = validate_table,
["source_list"] = validate_table,
["boolean"] = validate_boolean,
["config"] = validate_config,
}
function _nodegen:validate()
local decl = self.Decl
for name, detail in pairs(assert(self.Blueprint)) do
local val = decl[name]
if not val then
if detail.Required then
syntax_error("%s: missing argument: '%s'", self.Keyword, name)
end
-- ok, optional value
else
local validator = validators[detail.Type]
decl[name] = validator(name, val)
end
end
for name, detail in pairs(decl) do
if not self.Blueprint[name] then
syntax_error("%s: unsupported argument: '%s'", self.Keyword, name)
end
end
end
function _nodegen:customize_env(env, raw_data)
-- available for subclasses
end
function _nodegen:configure_env(env, deps)
local build_id = env:get('BUILD_ID')
local propagate_blocks = {}
local decl = self.Decl
for _, dep_obj in util.nil_ipairs(deps) do
local data = dep_obj.Decl.Propagate
if data then
propagate_blocks[#propagate_blocks + 1] = data
end
end
local function push_bindings(env_key, data)
if data then
for _, item in util.nil_ipairs(flatten_list(build_id, data)) do
env:append(env_key, item)
end
end
end
local function replace_bindings(env_key, data)
if data then
local first = true
for _, item in util.nil_ipairs(flatten_list(build_id, data)) do
if first then
env:replace(env_key, item)
first = false
else
env:append(env_key, item)
end
end
end
end
-- Push Libs, Defines and so in into the environment of this unit.
-- These are named for convenience but are aliases for syntax niceness.
for decl_key, env_key in util.nil_pairs(self.DeclToEnvMappings) do
-- First pick settings from our own unit.
push_bindings(env_key, decl[decl_key])
for _, data in ipairs(propagate_blocks) do
push_bindings(env_key, data[decl_key])
end
end
-- Push Env blocks as is
for k, v in util.nil_pairs(decl.Env) do
push_bindings(k, v)
end
for k, v in util.nil_pairs(decl.ReplaceEnv) do
replace_bindings(k, v)
end
for _, block in util.nil_ipairs(propagate_blocks) do
for k, v in util.nil_pairs(block.Env) do
push_bindings(k, v)
end
for k, v in util.nil_pairs(block.ReplaceEnv) do
replace_bindings(k, v)
end
end
end
local function resolve_sources(env, items, accum, base_dir)
local ignored_exts = util.make_lookup_table(env:get_list("IGNORED_AUTOEXTS", {}))
for _, item in util.nil_ipairs(items) do
local type_name = type(item)
assert(type_name ~= "function")
if type_name == "userdata" then
accum[#accum + 1] = item
elseif type_name == "table" then
if depgraph.is_node(item) then
accum[#accum + 1] = item
elseif getmetatable(item) then
accum[#accum + 1] = item:get_dag(env)
else
resolve_sources(env, item, accum, item.SourceDir or base_dir)
end
else
assert(type_name == "string")
local ext = path.get_extension(item)
if not ignored_exts[ext] then
if not base_dir or path.is_absolute(item) then
accum[#accum + 1] = item
else
local p = path.join(base_dir, item)
accum[#accum + 1] = p
end
end
end
end
return accum
end
-- Analyze source list, returning list of input files and list of dependencies.
--
-- This is so you can pass a mix of actions producing files and regular
-- filenames as inputs to the next step in the chain and the output files of
-- such nodes will be used automatically.
--
-- list - list of source files and nodes that produce source files
-- suffixes - acceptable source suffixes to pick up from nodes in source list
local function analyze_sources(env, pass, list, suffixes)
if not list then
return nil
end
list = util.flatten(list)
local deps = {}
local function implicit_make(source_file)
local t = type(source_file)
if t == "table" then
return source_file
end
assert(t == "string")
local make = env:get_implicit_make_fn(source_file)
if make then
return make(env, pass, source_file)
else
return nil
end
end
local function transform(output, fn)
if type(fn) ~= "string" then
error(util.tostring(fn) .. " is not a string", 2)
end
local t = implicit_make(fn)
if t then
deps[#deps + 1] = t
t:insert_output_files(output, suffixes)
else
output[#output + 1] = fn
end
end
local files = {}
for _, src in ipairs(list) do
if depgraph.is_node(src) then
deps[#deps + 1] = src
src:insert_output_files(files, suffixes)
elseif type(src) == "table" then
error("non-DAG node in source list at this point")
else
files[#files + 1] = src
end
end
while true do
local result = {}
local old_dep_count = #deps
for _, src in ipairs(files) do
transform(result, src)
end
files = result
if #deps == old_dep_count then
--print("scan", util.tostring(list), util.tostring(suffixes), util.tostring(result))
return result, deps
end
end
end
local function x_identity(self, name, info, value, env, out_deps)
return value
end
local function x_source_list(self, name, info, value, env, out_deps)
local build_id = env:get('BUILD_ID')
local source_files
if build_id then
source_files = filter_structure(build_id, value)
else
source_files = value
end
local sources = resolve_sources(env, source_files, {}, self.Decl.SourceDir)
local source_exts = env:get_list(info.ExtensionKey)
local inputs, ideps = analyze_sources(env, resolve_pass(self.Decl.Pass), sources, source_exts)
if ideps then
util.append_table(out_deps, ideps)
end
return inputs
end
local function x_filter_table(self, name, info, value, env, out_deps)
local build_id = env:get('BUILD_ID')
return flatten_list(build_id, value)
end
local function find_named_node(name_or_dag)
if type(name_or_dag) == "table" then
return name_or_dag:get_dag(current.default_env)
elseif type(name_or_dag) == "string" then
local generator = current.units[name_or_dag]
if not generator then
errorf("unknown node specified: %q", tostring(name_or_dag))
end
return generator:get_dag(current.default_env)
else
errorf("illegal node specified: %q", tostring(name_or_dag))
end
end
-- Special resolver for dependencies in a nested (config-filtered) list.
local function resolve_dependencies(decl, raw_deps, env)
if not raw_deps then
return {}
end
local build_id = env:get('BUILD_ID')
local deps = flatten_list(build_id, raw_deps)
return util.map_in_place(deps, function (i)
if type(i) == "string" then
local n = current.units[i]
if not n then
errorf("%s: Unknown 'Depends' target %q", decl.Name, i)
end
return n
elseif type(i) == "table" and getmetatable(i) and i.Decl then
return i
else
errorf("bad 'Depends' value of type %q", type(i))
end
end)
end
local function x_pass(self, name, info, value, env, out_deps)
return resolve_pass(value)
end
local decl_transformers = {
-- the x_identity data types have already been checked at script time through validate_xxx
["string"] = x_identity,
["table"] = x_identity,
["config"] = x_identity,
["boolean"] = x_identity,
["pass"] = x_pass,
["source_list"] = x_source_list,
["filter_table"] = x_filter_table,
}
-- Create input data for the generator's DAG creation function based on the
-- blueprint passed in when the generator was registered. This is done here
-- centrally rather than in all the different node generators to reduce code
-- duplication and keep the generators miminal. If you need to do something
-- special, you can override create_input_data() in your subclass.
function _nodegen:create_input_data(env)
local decl = self.Decl
local data = {}
local deps = {}
for name, detail in pairs(assert(self.Blueprint)) do
local val = decl[name]
if val then
local xform = decl_transformers[detail.Type]
data[name] = xform(self, name, detail, val, env, deps)
end
end
return data, deps
end
function get_pass(self, name)
if not name then
return nil
end
end
local pattern_cache = {}
local function get_cached_pattern(p)
local v = pattern_cache[p]
if not v then
local comp = '[%w_]+'
local sub_pattern = p:gsub('*', '[%%w_]+')
local platform, tool, variant, subvariant = unitgen.match_build_id(sub_pattern, comp)
v = string.format('^%s%%-%s%%-%s%%-%s$', platform, tool, variant, subvariant)
pattern_cache[p] = v
end
return v
end
local function config_matches(pattern, build_id)
local ptype = type(pattern)
if ptype == "nil" then
return true
elseif ptype == "string" then
local fpattern = get_cached_pattern(pattern)
return build_id:match(fpattern)
elseif ptype == "table" then
for _, pattern_item in ipairs(pattern) do
if config_matches(pattern_item, build_id) then
return true
end
end
return false
else
error("bad 'Config' pattern type: " .. ptype)
end
end
local function make_unit_env(unit)
-- Select an environment for this unit based on its SubConfig tag
-- to support cross compilation.
local env
local subconfig = unit.Decl.SubConfig or current.default_subconfig
if subconfig and current.base_envs then
env = current.base_envs[subconfig]
if Options.VeryVerbose then
if env then
printf("%s: using subconfig %s (%s)", unit.Decl.Name, subconfig, env:get('BUILD_ID'))
else
if current.default_subconfig then
errorf("%s: couldn't find a subconfig env", unit.Decl.Name)
else
printf("%s: no subconfig %s found; using default env", unit.Decl.Name, subconfig)
end
end
end
end
if not env then
env = current.default_env
end
return env:clone()
end
local anon_count = 1
function _nodegen:get_dag(parent_env)
local build_id = parent_env:get('BUILD_ID')
local dag = self.DagCache[build_id]
if not dag then
if build_id:len() > 0 and not config_matches(self.Decl.Config, build_id) then
-- Unit has been filtered out via Config attribute.
-- Create a fresh dummy node for it.
local name
if not self.Decl.Name then
name = string.format("Dummy node %d", anon_count)
else
name = string.format("Dummy node %d for %s", anon_count, self.Decl.Name)
end
anon_count = anon_count + 1
dag = depgraph.make_node {
Env = parent_env,
Pass = resolve_pass(self.Decl.Pass),
Label = name,
}
else
local unit_env = make_unit_env(self)
if self.Decl.Name then
unit_env:set('UNIT_PREFIX', '__' .. self.Decl.Name)
end
local function do_it()
-- Before accessing the unit's dependencies, resolve them via filtering.
local deps = resolve_dependencies(self.Decl, self.Decl.Depends, unit_env)
self:configure_env(unit_env, deps)
self:customize_env(unit_env, self.Decl, deps)
local input_data, input_deps = self:create_input_data(unit_env, parent_env)
-- Copy over dependencies which have been pre-resolved
input_data.Depends = deps
for _, dep in util.nil_ipairs(deps) do
input_deps[#input_deps + 1] = dep:get_dag(parent_env)
end
dag = self:create_dag(unit_env, input_data, input_deps, parent_env)
if not dag then
error("create_dag didn't generate a result node")
end
end
local success, result = xpcall(do_it, debug.traceback)
if not success then
croak("Error while generating DAG for unit %s:\n%s", self.Decl.Name or "UNNAMED", util.tostring(result))
end
end
self.DagCache[build_id] = dag
end
return dag
end
local _generator = {
Evaluators = {},
}
_generator.__index = _generator
local function new_generator(s)
s = s or {}
s.units = {}
return setmetatable(s, _generator)
end
local function create_unit_map(state, raw_nodes)
-- Build name=>decl mapping
for _, unit in ipairs(raw_nodes) do
assert(unit.Decl)
local name = unit.Decl.Name
if name and type(name) == "string" then
if state.units[name] then
errorf("duplicate unit name: %s", name)
end
state.units[name] = unit
end
end
end
function _generate_dag(args)
local envs = assert(args.Envs)
local raw_nodes = assert(args.Declarations)
local state = new_generator {
base_envs = envs,
root_env = envs["__default"], -- the outmost config's env in a cross-compilation scenario
config = assert(args.Config),
variant = assert(args.Variant),
passes = assert(args.Passes),
}
current = state
create_unit_map(state, raw_nodes)
local subconfigs = state.config.SubConfigs
-- Pick a default environment which is used for
-- 1. Nodes without a SubConfig declaration
-- 2. Nodes with a missing SubConfig declaration
-- 3. All nodes if there are no SubConfigs set for the current config
if subconfigs then
state.default_subconfig = assert(state.config.DefaultSubConfig)
state.default_env = assert(envs[state.default_subconfig], "unknown DefaultSubConfig specified")
else
state.default_env = assert(envs["__default"])
end
local always_lut = util.make_lookup_table(args.AlwaysNodes)
local default_lut = util.make_lookup_table(args.DefaultNodes)
local always_nodes = util.map(args.AlwaysNodes, find_named_node)
local default_nodes = util.map(args.DefaultNodes, find_named_node)
local named_nodes = {}
for name, _ in pairs(state.units) do
named_nodes[name] = find_named_node(name)
end
current = nil
return { always_nodes, default_nodes, named_nodes }
end
function generate_dag(args)
local success, result = xpcall(function () return _generate_dag(args) end, buildfile.syntax_error_catcher)
if success then
return result[1], result[2], result[3]
else
croak("%s", result)
end
end
function resolve_pass(name)
assert(current)
if name then
local p = current.passes[name]
if not p then
syntax_error("%q is not a valid pass name", name)
end
return p
else
return nil
end
end
function get_target(data, suffix, prefix)
local target = data.Target
if not target then
assert(data.Name)
target = "$(OBJECTDIR)/" .. (prefix or "") .. data.Name .. (suffix or "")
end
return target
end
function get_evaluator(name)
return _generator.Evaluators[name]
end
function is_evaluator(name)
if _generator.Evaluators[name] then return true else return false end
end
local common_blueprint = {
Propagate = {
Help = "Declarations to propagate to dependent units",
Type = "filter_table",
},
Depends = {
Help = "Dependencies for this node",
Type = "table", -- handled specially
},
Env = {
Help = "Data to append to the environment for the unit",
Type = "filter_table",
},
ReplaceEnv = {
Help = "Data to replace in the environment for the unit",
Type = "filter_table",
},
Pass = {
Help = "Specify build pass",
Type = "pass",
},
SourceDir = {
Help = "Specify base directory for source files",
Type = "string",
},
Config = {
Help = "Specify configuration this unit will build in",
Type = "config",
},
SubConfig = {
Help = "Specify sub-configuration this unit will build in",
Type = "config",
},
__DagNodes = {
Help = "Internal node to keep track of DAG nodes generated so far",
Type = "table",
}
}
function create_eval_subclass(meta_tbl, base)
base = base or _nodegen
setmetatable(meta_tbl, base)
meta_tbl.__index = meta_tbl
return meta_tbl
end
function add_evaluator(name, meta_tbl, blueprint)
assert(type(name) == "string")
assert(type(meta_tbl) == "table")
assert(type(blueprint) == "table")
-- Set up this metatable as a subclass of _nodegen unless it is already
-- configured.
if not getmetatable(meta_tbl) then
setmetatable(meta_tbl, _nodegen)
meta_tbl.__index = meta_tbl
end
-- Install common blueprint items.
for name, val in pairs(common_blueprint) do
if not blueprint[name] then
blueprint[name] = val
end
end
-- Expand environment shortcuts into options.
for decl_key, env_key in util.nil_pairs(meta_tbl.DeclToEnvMappings) do
blueprint[decl_key] = {
Type = "filter_table",
Help = "Shortcut for environment key " .. env_key,
}
end
for name, val in pairs(blueprint) do
local type_ = assert(val.Type)
if not validators[type_] then
errorf("unsupported blueprint type %q", type_)
end
if val.Type == "source_list" and not val.ExtensionKey then
errorf("%s: source_list must provide ExtensionKey", name)
end
end
-- Record blueprint for use when validating user constructs.
meta_tbl.Keyword = name
meta_tbl.Blueprint = blueprint
-- Store this evaluator under the keyword that will trigger it.
_generator.Evaluators[name] = meta_tbl
end
-- Called when processing build scripts, keywords is something previously
-- registered as an evaluator here.
function evaluate(eval_keyword, data)
local meta_tbl = assert(_generator.Evaluators[eval_keyword])
-- Give the evaluator change to fix up the data before we validate it.
data = meta_tbl:preprocess_data(data)
local object = setmetatable({
DagCache = {}, -- maps BUILD_ID -> dag node
Decl = data
}, meta_tbl)
-- Expose the dag cache to the raw input data so the IDE generator can find it later
data.__DagNodes = object.DagCache
object.__index = object
-- Validate data according to Blueprint settings
object:validate()
return object
end
-- Given a list of strings or nested lists, flatten the structure to a single
-- list of strings while applying configuration filters. Configuration filters
-- match against the current build identifier like this:
--
-- { "a", "b", { "nixfile1", "nixfile2"; Config = "unix-*-*" }, "bar", { "debugfile"; Config = "*-*-debug" }, }
--
-- If 'exclusive' is set, then:
-- If 'build_id' is set, only values _with_ a 'Config' filter are included.
-- If 'build_id' is nil, only values _without_ a 'Config' filter are included.
function flatten_list(build_id, list, exclusive)
if not list then return nil end
local filter_defined = build_id ~= nil
-- Helper function to apply filtering recursively and append results to an
-- accumulator table.
local function iter(node, accum, filtered)
local node_type = type(node)
if node_type == "table" and not getmetatable(node) then
if node.Config then filtered = true end
if not filter_defined or config_matches(node.Config, build_id) then
for _, item in ipairs(node) do
iter(item, accum, filtered)
end
end
elseif not exclusive or (filtered == filter_defined) then
accum[#accum + 1] = node
end
end
local results = {}
iter(list, results, false)
return results
end
-- Conceptually similar to flatten_list(), but retains table structure.
-- Use to keep source tables as they are passed in, to retain nested SourceDir attributes.
local empty_leaf = {} -- constant
function filter_structure(build_id, data, exclusive)
if type(data) == "table" then
if getmetatable(data) then
return data -- it's already a DAG node; use as-is
end
local filtered = data.Config and true or false
if not data.Config or config_matches(data.Config, build_id) then
local result = {}
for k, item in pairs(data) do
if type(k) == "number" then
-- Filter array elements.
result[#result + 1] = filter_structure(build_id, item, filtered)
elseif k ~= "Config" then
-- Copy key-value data through.
result[k] = item
end
end
return result
else
return empty_leaf
end
else
return data
end
end
-- Processes an "Env" table. For each value, the corresponding variable in
-- 'env' is appended to if its "Config" filter matches 'build_id'. If
-- 'build_id' is nil, filtered values are skipped.
function append_filtered_env_vars(env, values_to_append, build_id, exclusive)
for key, val in util.pairs(values_to_append) do
if type(val) == "table" then
local list = flatten_list(build_id, val, exclusive)
for _, subvalue in ipairs(list) do
env:append(key, subvalue)
end
elseif not (exclusive and build_id) then
env:append(key, val)
end
end
end
-- Like append_filtered_env_vars(), but replaces existing variables instead
-- of appending to them.
function replace_filtered_env_vars(env, values_to_replace, build_id, exclusive)
for key, val in util.pairs(values_to_replace) do
if type(val) == "table" then
local list = flatten_list(build_id, val, exclusive)
if #list > 0 then
env:replace(key, list)
end
elseif not (exclusive and build_id) then
env:replace(key, val)
end
end
end
function generate_ide_files(config_tuples, default_names, raw_nodes, env, hints, ide_script)
local state = new_generator { default_env = env }
assert(state.default_env)
create_unit_map(state, raw_nodes)
local backend_fn = assert(ide_backend)
backend_fn(state, config_tuples, raw_nodes, env, default_names, hints, ide_script)
end
function set_ide_backend(backend_fn)
ide_backend = backend_fn
end
-- Expose the DefRule helper which is used to register builder syntax in a
-- simplified way.
function _G.DefRule(ruledef)
local name = assert(ruledef.Name, "Missing Name string in DefRule")
local setup_fn = assert(ruledef.Setup, "Missing Setup function in DefRule " .. name)
local cmd = assert(ruledef.Command, "Missing Command string in DefRule " .. name)
local blueprint = assert(ruledef.Blueprint, "Missing Blueprint in DefRule " .. name)
local mt = create_eval_subclass {}
local annot = ruledef.Annotation
if not annot then
annot = name .. " $(<)"
end
local preproc = ruledef.Preprocess
local function verify_table(v, tag)
if not v then
errorf("No %s returned from DefRule %s", tag, name)
end
if type(v) ~= "table" then
errorf("%s returned from DefRule %s is not a table", tag, name)
end
end
local function make_node(input_files, output_files, env, data, deps, scanner, action)
return depgraph.make_node {
Env = env,
Label = annot,
Action = action,
Pass = data.Pass or resolve_pass(ruledef.Pass),
InputFiles = input_files,
OutputFiles = output_files,
ImplicitInputs = ruledef.ImplicitInputs,
Scanner = scanner,
Dependencies = deps,
}
end
if ruledef.ConfigInvariant then
local cache = {}
function mt:create_dag(env, data, deps)
local setup_data = setup_fn(env, data)
local input_files = setup_data.InputFiles
local output_files = setup_data.OutputFiles
verify_table(input_files, "InputFiles")
verify_table(output_files, "OutputFiles")
local mashup = { }
for _, input in util.nil_ipairs(input_files) do
mashup[#mashup + 1] = input
end
mashup[#mashup + 1] = "@@"
for _, output in util.nil_ipairs(output_files) do
mashup[#mashup + 1] = output
end
mashup[#mashup + 1] = "@@"
for _, implicit_input in util.nil_ipairs(setup_data.ImplicitInputs) do
mashup[#mashup + 1] = implicit_input
end
local key = native.digest_guid(table.concat(mashup, ';'))
local key = util.tostring(key)
if cache[key] then
return cache[key]
else
local node = make_node(input_files, output_files, env, data, deps, setup_data.Scanner, setup_data.Command or cmd)
cache[key] = node
return node
end
end
else
function mt:create_dag(env, data, deps)
local setup_data = setup_fn(env, data)
verify_table(setup_data.InputFiles, "InputFiles")
verify_table(setup_data.OutputFiles, "OutputFiles")
return make_node(setup_data.InputFiles, setup_data.OutputFiles, env, data, deps, setup_data.Scanner, setup_data.Command or cmd)
end
end
if preproc then
function mt:preprocess_data(raw_data)
return preproc(raw_data)
end
end
add_evaluator(name, mt, blueprint)
end
function _nodegen:preprocess_data(data)
return data
end
| mit |
RuiChen1113/luci | libs/luci-lib-nixio/axTLS/www/lua/download.lua | 180 | 1550 | #!/usr/local/bin/lua
require"luasocket"
function receive (connection)
connection:settimeout(0)
local s, status = connection:receive (2^10)
if status == "timeout" then
coroutine.yield (connection)
end
return s, status
end
function download (host, file, outfile)
--local f = assert (io.open (outfile, "w"))
local c = assert (socket.connect (host, 80))
c:send ("GET "..file.." HTTP/1.0\r\n\r\n")
while true do
local s, status = receive (c)
--f:write (s)
if status == "closed" then
break
end
end
c:close()
--f:close()
end
local threads = {}
function get (host, file, outfile)
print (string.format ("Downloading %s from %s to %s", file, host, outfile))
local co = coroutine.create (function ()
return download (host, file, outfile)
end)
table.insert (threads, co)
end
function dispatcher ()
while true do
local n = table.getn (threads)
if n == 0 then
break
end
local connections = {}
for i = 1, n do
local status, res = coroutine.resume (threads[i])
if not res then
table.remove (threads, i)
break
else
table.insert (connections, res)
end
end
if table.getn (connections) == n then
socket.select (connections)
end
end
end
local url = arg[1]
if not url then
print (string.format ("usage: %s url [times]", arg[0]))
os.exit()
end
local times = arg[2] or 5
url = string.gsub (url, "^http.?://", "")
local _, _, host, file = string.find (url, "^([^/]+)(/.*)")
local _, _, fn = string.find (file, "([^/]+)$")
for i = 1, times do
get (host, file, fn..i)
end
dispatcher ()
| apache-2.0 |
wsy495/sipml5 | asterisk/etc/extensions.lua | 317 | 5827 |
CONSOLE = "Console/dsp" -- Console interface for demo
--CONSOLE = "DAHDI/1"
--CONSOLE = "Phone/phone0"
IAXINFO = "guest" -- IAXtel username/password
--IAXINFO = "myuser:mypass"
TRUNK = "DAHDI/G2"
TRUNKMSD = 1
-- TRUNK = "IAX2/user:pass@provider"
--
-- Extensions are expected to be defined in a global table named 'extensions'.
-- The 'extensions' table should have a group of tables in it, each
-- representing a context. Extensions are defined in each context. See below
-- for examples.
--
-- Extension names may be numbers, letters, or combinations thereof. If
-- an extension name is prefixed by a '_' character, it is interpreted as
-- a pattern rather than a literal. In patterns, some characters have
-- special meanings:
--
-- X - any digit from 0-9
-- Z - any digit from 1-9
-- N - any digit from 2-9
-- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9)
-- . - wildcard, matches anything remaining (e.g. _9011. matches
-- anything starting with 9011 excluding 9011 itself)
-- ! - wildcard, causes the matching process to complete as soon as
-- it can unambiguously determine that no other matches are possible
--
-- For example the extension _NXXXXXX would match normal 7 digit
-- dialings, while _1NXXNXXXXXX would represent an area code plus phone
-- number preceded by a one.
--
-- If your extension has special characters in it such as '.' and '!' you must
-- explicitly make it a string in the tabale definition:
--
-- ["_special."] = function;
-- ["_special!"] = function;
--
-- There are no priorities. All extensions to asterisk appear to have a single
-- priority as if they consist of a single priority.
--
-- Each context is defined as a table in the extensions table. The
-- context names should be strings.
--
-- One context may be included in another context using the 'includes'
-- extension. This extension should be set to a table containing a list
-- of context names. Do not put references to tables in the includes
-- table.
--
-- include = {"a", "b", "c"};
--
-- Channel variables can be accessed thorugh the global 'channel' table.
--
-- v = channel.var_name
-- v = channel["var_name"]
-- v.value
-- v:get()
--
-- channel.var_name = "value"
-- channel["var_name"] = "value"
-- v:set("value")
--
-- channel.func_name(1,2,3):set("value")
-- value = channel.func_name(1,2,3):get()
--
-- channel["func_name(1,2,3)"]:set("value")
-- channel["func_name(1,2,3)"] = "value"
-- value = channel["func_name(1,2,3)"]:get()
--
-- Note the use of the ':' operator to access the get() and set()
-- methods.
--
-- Also notice the absence of the following constructs from the examples above:
-- channel.func_name(1,2,3) = "value" -- this will NOT work
-- value = channel.func_name(1,2,3) -- this will NOT work as expected
--
--
-- Dialplan applications can be accessed through the global 'app' table.
--
-- app.Dial("DAHDI/1")
-- app.dial("DAHDI/1")
--
-- More examples can be found below.
--
-- An autoservice is automatically run while lua code is executing. The
-- autoservice can be stopped and restarted using the autoservice_stop() and
-- autoservice_start() functions. The autservice should be running before
-- starting long running operations. The autoservice will automatically be
-- stopped before executing applications and dialplan functions and will be
-- restarted afterwards. The autoservice_status() function can be used to
-- check the current status of the autoservice and will return true if an
-- autoservice is currently running.
--
function outgoing_local(c, e)
app.dial("DAHDI/1/" .. e, "", "")
end
function demo_instruct()
app.background("demo-instruct")
app.waitexten()
end
function demo_congrats()
app.background("demo-congrats")
demo_instruct()
end
-- Answer the chanel and play the demo sound files
function demo_start(context, exten)
app.wait(1)
app.answer()
channel.TIMEOUT("digit"):set(5)
channel.TIMEOUT("response"):set(10)
-- app.set("TIMEOUT(digit)=5")
-- app.set("TIMEOUT(response)=10")
demo_congrats(context, exten)
end
function demo_hangup()
app.playback("demo-thanks")
app.hangup()
end
extensions = {
demo = {
s = demo_start;
["2"] = function()
app.background("demo-moreinfo")
demo_instruct()
end;
["3"] = function ()
channel.LANGUAGE():set("fr") -- set the language to french
demo_congrats()
end;
["1000"] = function()
app.goto("demo", "s", 1)
end;
["1234"] = function()
app.playback("transfer", "skip")
-- do a dial here
end;
["1235"] = function()
app.voicemail("1234", "u")
end;
["1236"] = function()
app.dial("Console/dsp")
app.voicemail(1234, "b")
end;
["#"] = demo_hangup;
t = demo_hangup;
i = function()
app.playback("invalid")
demo_instruct()
end;
["500"] = function()
app.playback("demo-abouttotry")
app.dial("IAX2/guest@misery.digium.com/s@default")
app.playback("demo-nogo")
demo_instruct()
end;
["600"] = function()
app.playback("demo-echotest")
app.echo()
app.playback("demo-echodone")
demo_instruct()
end;
["8500"] = function()
app.voicemailmain()
demo_instruct()
end;
};
default = {
-- by default, do the demo
include = {"demo"};
};
public = {
-- ATTENTION: If your Asterisk is connected to the internet and you do
-- not have allowguest=no in sip.conf, everybody out there may use your
-- public context without authentication. In that case you want to
-- double check which services you offer to the world.
--
include = {"demo"};
};
["local"] = {
["_NXXXXXX"] = outgoing_local;
};
}
hints = {
demo = {
[1000] = "SIP/1000";
[1001] = "SIP/1001";
};
default = {
["1234"] = "SIP/1234";
};
}
| bsd-3-clause |
jgibbon/sipml5 | asterisk/etc/extensions.lua | 317 | 5827 |
CONSOLE = "Console/dsp" -- Console interface for demo
--CONSOLE = "DAHDI/1"
--CONSOLE = "Phone/phone0"
IAXINFO = "guest" -- IAXtel username/password
--IAXINFO = "myuser:mypass"
TRUNK = "DAHDI/G2"
TRUNKMSD = 1
-- TRUNK = "IAX2/user:pass@provider"
--
-- Extensions are expected to be defined in a global table named 'extensions'.
-- The 'extensions' table should have a group of tables in it, each
-- representing a context. Extensions are defined in each context. See below
-- for examples.
--
-- Extension names may be numbers, letters, or combinations thereof. If
-- an extension name is prefixed by a '_' character, it is interpreted as
-- a pattern rather than a literal. In patterns, some characters have
-- special meanings:
--
-- X - any digit from 0-9
-- Z - any digit from 1-9
-- N - any digit from 2-9
-- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9)
-- . - wildcard, matches anything remaining (e.g. _9011. matches
-- anything starting with 9011 excluding 9011 itself)
-- ! - wildcard, causes the matching process to complete as soon as
-- it can unambiguously determine that no other matches are possible
--
-- For example the extension _NXXXXXX would match normal 7 digit
-- dialings, while _1NXXNXXXXXX would represent an area code plus phone
-- number preceded by a one.
--
-- If your extension has special characters in it such as '.' and '!' you must
-- explicitly make it a string in the tabale definition:
--
-- ["_special."] = function;
-- ["_special!"] = function;
--
-- There are no priorities. All extensions to asterisk appear to have a single
-- priority as if they consist of a single priority.
--
-- Each context is defined as a table in the extensions table. The
-- context names should be strings.
--
-- One context may be included in another context using the 'includes'
-- extension. This extension should be set to a table containing a list
-- of context names. Do not put references to tables in the includes
-- table.
--
-- include = {"a", "b", "c"};
--
-- Channel variables can be accessed thorugh the global 'channel' table.
--
-- v = channel.var_name
-- v = channel["var_name"]
-- v.value
-- v:get()
--
-- channel.var_name = "value"
-- channel["var_name"] = "value"
-- v:set("value")
--
-- channel.func_name(1,2,3):set("value")
-- value = channel.func_name(1,2,3):get()
--
-- channel["func_name(1,2,3)"]:set("value")
-- channel["func_name(1,2,3)"] = "value"
-- value = channel["func_name(1,2,3)"]:get()
--
-- Note the use of the ':' operator to access the get() and set()
-- methods.
--
-- Also notice the absence of the following constructs from the examples above:
-- channel.func_name(1,2,3) = "value" -- this will NOT work
-- value = channel.func_name(1,2,3) -- this will NOT work as expected
--
--
-- Dialplan applications can be accessed through the global 'app' table.
--
-- app.Dial("DAHDI/1")
-- app.dial("DAHDI/1")
--
-- More examples can be found below.
--
-- An autoservice is automatically run while lua code is executing. The
-- autoservice can be stopped and restarted using the autoservice_stop() and
-- autoservice_start() functions. The autservice should be running before
-- starting long running operations. The autoservice will automatically be
-- stopped before executing applications and dialplan functions and will be
-- restarted afterwards. The autoservice_status() function can be used to
-- check the current status of the autoservice and will return true if an
-- autoservice is currently running.
--
function outgoing_local(c, e)
app.dial("DAHDI/1/" .. e, "", "")
end
function demo_instruct()
app.background("demo-instruct")
app.waitexten()
end
function demo_congrats()
app.background("demo-congrats")
demo_instruct()
end
-- Answer the chanel and play the demo sound files
function demo_start(context, exten)
app.wait(1)
app.answer()
channel.TIMEOUT("digit"):set(5)
channel.TIMEOUT("response"):set(10)
-- app.set("TIMEOUT(digit)=5")
-- app.set("TIMEOUT(response)=10")
demo_congrats(context, exten)
end
function demo_hangup()
app.playback("demo-thanks")
app.hangup()
end
extensions = {
demo = {
s = demo_start;
["2"] = function()
app.background("demo-moreinfo")
demo_instruct()
end;
["3"] = function ()
channel.LANGUAGE():set("fr") -- set the language to french
demo_congrats()
end;
["1000"] = function()
app.goto("demo", "s", 1)
end;
["1234"] = function()
app.playback("transfer", "skip")
-- do a dial here
end;
["1235"] = function()
app.voicemail("1234", "u")
end;
["1236"] = function()
app.dial("Console/dsp")
app.voicemail(1234, "b")
end;
["#"] = demo_hangup;
t = demo_hangup;
i = function()
app.playback("invalid")
demo_instruct()
end;
["500"] = function()
app.playback("demo-abouttotry")
app.dial("IAX2/guest@misery.digium.com/s@default")
app.playback("demo-nogo")
demo_instruct()
end;
["600"] = function()
app.playback("demo-echotest")
app.echo()
app.playback("demo-echodone")
demo_instruct()
end;
["8500"] = function()
app.voicemailmain()
demo_instruct()
end;
};
default = {
-- by default, do the demo
include = {"demo"};
};
public = {
-- ATTENTION: If your Asterisk is connected to the internet and you do
-- not have allowguest=no in sip.conf, everybody out there may use your
-- public context without authentication. In that case you want to
-- double check which services you offer to the world.
--
include = {"demo"};
};
["local"] = {
["_NXXXXXX"] = outgoing_local;
};
}
hints = {
demo = {
[1000] = "SIP/1000";
[1001] = "SIP/1001";
};
default = {
["1234"] = "SIP/1234";
};
}
| bsd-3-clause |
Teraku/Skill-Overhaul | SkillOverhaul/lua/units/sentrygunbrain.lua | 1 | 1494 | --Thanks to LazyOzzy from UnknownCheats for the code.
--Sentries no longer target shields.
local _select_focus_attention_original = SentryGunBrain._select_focus_attention
local _upd_fire_original = SentryGunBrain._upd_fire
function SentryGunBrain:_select_focus_attention(...)
local is_criminal = self._unit:movement():team().id == "criminal1"
local all_targets = self._detected_attention_objects
if is_criminal then
local valid_targets = {}
local obstructed_targets = {}
all_targets = {}
for key, data in pairs(self._detected_attention_objects) do
all_targets[key] = data
if self._unit:weapon():check_lof(data.unit, data.handler:get_attention_m_pos()) then
valid_targets[key] = data
else
obstructed_targets[key] = data
end
end
if next(valid_targets) ~= nil then
self._fire_at_will = true
self._detected_attention_objects = valid_targets
else
self._fire_at_will = false
self._detected_attention_objects = obstructed_targets
end
end
_select_focus_attention_original(self, ...)
self._detected_attention_objects = all_targets
end
function SentryGunBrain:_upd_fire(...)
if self._fire_at_will or self._fire_at_will == nil then
_upd_fire_original(self, ...)
elseif self._firing then
self._unit:weapon():stop_autofire()
self._firing = false
end
end | gpl-2.0 |
dan9550/OpenRA | mods/cnc/maps/nod06b/nod06b.lua | 12 | 6915 | NodUnitsVehicle1 = { 'bggy', 'bggy', 'bike', 'bike', 'bike' }
NodUnitsVehicle2 = { 'ltnk', 'ltnk', 'ltnk' }
NodUnitsGunner = { 'e1', 'e1', 'e1', 'e1', 'e1', 'e1' }
NodUnitsRocket = { 'e3', 'e3', 'e3', 'e3', 'e3', 'e3' }
Gdi1Units = { 'e1', 'e1', 'e2', 'e2', 'e2' }
HuntCellTriggerActivator = { CPos.New(61,34), CPos.New(60,34), CPos.New(59,34), CPos.New(58,34), CPos.New(57,34), CPos.New(56,34), CPos.New(55,34), CPos.New(61,33), CPos.New(60,33), CPos.New(59,33), CPos.New(58,33), CPos.New(57,33), CPos.New(56,33) }
DzneCellTriggerActivator = { CPos.New(50,30), CPos.New(49,30), CPos.New(48,30), CPos.New(47,30), CPos.New(46,30), CPos.New(45,30), CPos.New(50,29), CPos.New(49,29), CPos.New(48,29), CPos.New(47,29), CPos.New(46,29), CPos.New(45,29), CPos.New(50,28), CPos.New(49,28), CPos.New(48,28), CPos.New(47,28), CPos.New(46,28), CPos.New(45,28), CPos.New(50,27), CPos.New(49,27), CPos.New(46,27), CPos.New(45,27), CPos.New(50,26), CPos.New(49,26), CPos.New(48,26), CPos.New(47,26), CPos.New(46,26), CPos.New(45,26), CPos.New(50,25), CPos.New(49,25), CPos.New(48,25), CPos.New(47,25), CPos.New(46,25), CPos.New(45,25) }
Win1CellTriggerActivator = { CPos.New(47,27) }
Win2CellTriggerActivator = { CPos.New(57,57), CPos.New(56,57), CPos.New(55,57), CPos.New(57,56), CPos.New(56,56), CPos.New(55,56), CPos.New(57,55), CPos.New(56,55), CPos.New(55,55), CPos.New(57,54), CPos.New(56,54), CPos.New(55,54), CPos.New(57,53), CPos.New(56,53), CPos.New(55,53), CPos.New(57,52), CPos.New(56,52), CPos.New(55,52) }
ChnCellTriggerActivator = { CPos.New(61,52), CPos.New(60,52), CPos.New(59,52), CPos.New(58,52), CPos.New(61,51), CPos.New(60,51), CPos.New(59,51), CPos.New(58,51), CPos.New(61,50), CPos.New(60,50), CPos.New(59,50), CPos.New(58,50) }
Chn1ActorTriggerActivator = { Chn1Actor1, Chn1Actor2 }
Chn2ActorTriggerActivator = { Chn2Actor1 }
Atk1ActorTriggerActivator = { Atk1Actor1, Atk1Actor2 }
Atk2ActorTriggerActivator = { Atk2Actor1, Atk2Actor2 }
Chn1Waypoints = { ChnEntry.Location, waypoint0.Location }
Chn2Waypoints = { ChnEntry.Location, waypoint0.Location }
Gdi5Waypoint = { waypoint1, waypoint2, waypoint3, waypoint4, waypoint5, waypoint6, waypoint7 }
HuntTriggerFunction = function()
local list = GDI.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
Win1TriggerFunction = function()
NodObjective2 = Nod.AddPrimaryObjective("Move to the evacuation point.")
Nod.MarkCompletedObjective(NodObjective1)
end
Chn1TriggerFunction = function()
if not Chn1Switch then
local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Gdi1Units, Chn1Waypoints, { ChnEntry.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
Chn1Switch = true
end
end
Atk1TriggerFunction = function()
if not Atk1Switch then
for type, count in pairs({ ['e2'] = 2, ['jeep'] = 1, ['e1'] = 2}) do
MyActors = Utils.Take(count, GDI.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
IdleHunt(actor)
end)
end
Atk1Switch = true
end
end
Atk2TriggerFunction = function()
if not Atk2Switch then
for type, count in pairs({ ['e2'] = 2, ['e1'] = 2}) do
MyActors = Utils.Take(count, GDI.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
MoveAndHunt(actor, Gdi5Waypoint)
end)
end
Atk2Switch = true
end
end
Chn2TriggerFunction = function()
if not Chn2Switch then
local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Gdi1Units, Chn2Waypoints, { ChnEntry.Location })[2]
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
Chn2Switch = true
end
end
MoveAndHunt = function(unit, waypoints)
if unit ~= nil then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
end
InsertNodUnits = function()
Media.PlaySpeechNotification(Nod, "Reinforce")
Camera.Position = UnitsRallyVehicle2.CenterPosition
Reinforcements.Reinforce(Nod, NodUnitsVehicle1, { UnitsEntryVehicle.Location, UnitsRallyVehicle1.Location }, 10)
Reinforcements.Reinforce(Nod, NodUnitsVehicle2, { UnitsEntryVehicle.Location, UnitsRallyVehicle2.Location }, 15)
Reinforcements.Reinforce(Nod, NodUnitsGunner, { UnitsEntryGunner.Location, UnitsRallyGunner.Location }, 15)
Reinforcements.Reinforce(Nod, NodUnitsRocket, { UnitsEntryRocket.Location, UnitsRallyRocket.Location }, 25)
end
WorldLoaded = function()
GDI = Player.GetPlayer("GDI")
Nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(Nod, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(Nod, function()
Media.PlaySpeechNotification(Nod, "Win")
end)
Trigger.OnPlayerLost(Nod, function()
Media.PlaySpeechNotification(Nod, "Lose")
end)
NodObjective1 = Nod.AddPrimaryObjective("Steal the GDI nuclear detonator.")
GDIObjective = GDI.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.")
InsertNodUnits()
Trigger.OnEnteredFootprint(HuntCellTriggerActivator, function(a, id)
if a.Owner == Nod then
HuntTriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id)
if a.Owner == Nod then
Actor.Create('flare', true, { Owner = Nod, Location = waypoint17.Location })
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id)
if a.Owner == Nod then
Win1TriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id)
if a.Owner == Nod and NodObjective2 then
Nod.MarkCompletedObjective(NodObjective2)
Trigger.RemoveFootprintTrigger(id)
end
end)
OnAnyDamaged(Chn1ActorTriggerActivator, Chn1TriggerFunction)
OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction)
OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction)
OnAnyDamaged(Chn2ActorTriggerActivator, Chn2TriggerFunction)
Trigger.OnEnteredFootprint(ChnCellTriggerActivator, function(a, id)
if a.Owner == Nod then
Media.PlaySpeechNotification(Nod, "Reinforce")
Reinforcements.ReinforceWithTransport(Nod, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil)
Trigger.RemoveFootprintTrigger(id)
end
end)
end
Tick = function()
if Nod.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
GDI.MarkCompletedObjective(GDIObjective)
end
end
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
| gpl-3.0 |
bocaaust/SoundView | Libs/RuntimeResources.bundle/socket.lua | 6 | 4446 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket")
local _M = socket
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function _M.connect4(address, port, laddress, lport)
return socket.connect(address, port, laddress, lport, "inet")
end
function _M.connect6(address, port, laddress, lport)
return socket.connect(address, port, laddress, lport, "inet6")
end
function _M.bind(host, port, backlog)
if host == "*" then host = "0.0.0.0" end
local addrinfo, err = socket.dns.getaddrinfo(host);
if not addrinfo then return nil, err end
local sock, res
err = "no info on address"
for i, alt in base.ipairs(addrinfo) do
if alt.family == "inet" then
sock, err = socket.tcp()
else
sock, err = socket.tcp6()
end
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
res, err = sock:bind(alt.addr, port)
if not res then
sock:close()
else
res, err = sock:listen(backlog)
if not res then
sock:close()
else
return sock
end
end
end
return nil, err
end
_M.try = _M.newtry()
function _M.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
local sourcet, sinkt = {}, {}
_M.sourcet = sourcet
_M.sinkt = sinkt
_M.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"]
_M.sink = _M.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"]
_M.source = _M.choose(sourcet)
return _M
| apache-2.0 |
mahdib9/mb | plugins/bot_manager.lua | 89 | 6427 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'عکس پروفایل ربات تغییر کرد', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'عکس رباتو بفرست بیاد'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "پیام شما از طریق پیوی ربات ارسال شد"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "شما نمیتوانید ادمین را بلاک کنید"
end
block_user("user#id"..matches[2],ok_cb,false)
return "یوزر مورد نظر از ربات بلاک شد"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "یوزر انبلاک شد"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
patterns = {
"^[!/](pm) (%d+) (.*)$",
"^[!/](import) (.*)$",
"^[!/](unblock) (%d+)$",
"^[!/](block) (%d+)$",
"^[!/](markread) (on)$",
"^[!/](markread) (off)$",
"^[!/](setbotphoto)$",
"%[(photo)%]",
"^[!/](contactlist)$",
"^[!/](dialoglist)$",
"^[!/](delcontact) (%d+)$",
"^[!/](whois) (%d+)$"
},
run = run,
}
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
Habbie/hammerspoon | extensions/uielement/init.lua | 2 | 6427 | --- === hs.uielement ===
---
--- A generalized framework for working with OSX UI elements
local uielement = require("hs.uielement.internal")
uielement.watcher = require("hs.uielement.watcher")
local fnutils = require "hs.fnutils"
local appWatcher = require "hs.application.watcher"
local USERDATA_TAG = "hs.uielement"
local objectMT = hs.getObjectMetatable(USERDATA_TAG)
local watcherMT = hs.getObjectMetatable("hs.uielement.watcher")
--- hs.uielement:isApplication() -> bool
--- Method
--- Returns whether the UI element represents an application.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A boolean, true if the UI element is an application
function objectMT.isApplication(self)
return self:role() == "AXApplication"
end
--- === hs.uielement.watcher ===
---
--- Watch for events on certain UI elements (including windows and applications)
---
--- You can watch the following events:
--- ### Application-level events
--- See hs.application.watcher for more events you can watch.
--- * hs.uielement.watcher.applicationActivated: The current application switched to this one.
--- * hs.uielement.watcher.applicationDeactivated: The current application is no longer this one.
--- * hs.uielement.watcher.applicationHidden: The application was hidden.
--- * hs.uielement.watcher.applicationShown: The application was shown.
---
--- #### Focus change events
--- These events are watched on the application level, but send the relevant child element to the handler.
--- * hs.uielement.watcher.mainWindowChanged: The main window of the application was changed.
--- * hs.uielement.watcher.focusedWindowChanged: The focused window of the application was changed. Note that the application may not be activated itself.
--- * hs.uielement.watcher.focusedElementChanged: The focused UI element of the application was changed.
---
--- ### Window-level events
--- * hs.uielement.watcher.windowCreated: A window was created. You should watch for this event on the application, or the parent window.
--- * hs.uielement.watcher.windowMoved: The window was moved.
--- * hs.uielement.watcher.windowResized: The window was resized.
--- * hs.uielement.watcher.windowMinimized: The window was minimized.
--- * hs.uielement.watcher.windowUnminimized: The window was unminimized.
---
--- ### Element-level events
--- These work on all UI elements, including windows.
--- * hs.uielement.watcher.elementDestroyed: The element was destroyed.
--- * hs.uielement.watcher.titleChanged: The element's title was changed.
uielement.watcher.applicationActivated = "AXApplicationActivated"
uielement.watcher.applicationDeactivated = "AXApplicationDeactivated"
uielement.watcher.applicationHidden = "AXApplicationHidden"
uielement.watcher.applicationShown = "AXApplicationShown"
uielement.watcher.mainWindowChanged = "AXMainWindowChanged"
uielement.watcher.focusedWindowChanged = "AXFocusedWindowChanged"
uielement.watcher.focusedElementChanged = "AXFocusedUIElementChanged"
uielement.watcher.windowCreated = "AXWindowCreated"
uielement.watcher.windowMoved = "AXWindowMoved"
uielement.watcher.windowResized = "AXWindowResized"
uielement.watcher.windowMinimized = "AXWindowMiniaturized"
uielement.watcher.windowUnminimized = "AXWindowDeminiaturized"
uielement.watcher.elementDestroyed = "AXUIElementDestroyed"
uielement.watcher.titleChanged = "AXTitleChanged"
-- Keep track of apps, to automatically stop watchers on apps AND their elements when apps quit.
local appWatchers = {}
local function appCallback(_, event, app)
if app and (appWatchers[app:pid()] and event == application.watcher.terminated) then
fnutils.each(appWatchers[app:pid()], function(watcher) watcher:_stop() end)
appWatchers[app:pid()] = nil
end
end
local globalAppWatcher = appWatcher.new(appCallback)
globalAppWatcher:start()
-- Keep track of all other UI elements to automatically stop their watchers.
local function handleEvent(callback, element, event, watcher, userData)
if event == watcher.elementDestroyed then
-- element is newly created from a dead UI element and may not have critical fields like pid and id.
-- Use the existing watcher element instead.
if element == watcher:element() then
element = watcher:element()
end
-- Pass along event if wanted.
if watcher:watchDestroyed() then
callback(element, event, watcher, userData)
end
-- Stop watcher.
if element == watcher:element() then
watcher:stop() -- also removes from appWatchers
end
else
callback(element, event, watcher, userData)
end
end
--- hs.uielement.watcher:start(events) -> hs.uielement.watcher
--- Method
--- Tells the watcher to start watching for the given list of events.
---
--- Parameters:
--- * An array of events to be watched for.
---
--- Returns:
--- * hs.uielement.watcher
---
--- Notes:
--- * See hs.uielement.watcher for a list of events. You may also specify arbitrary event names as strings.
--- * Does nothing if the watcher has already been started. To start with different events, stop it first.
function watcherMT.start(self, events)
-- Track all watchers in appWatchers.
local pid = self:pid()
if not appWatchers[pid] then appWatchers[pid] = {} end
table.insert(appWatchers[pid], self)
-- For normal elements, listen for elementDestroyed events.
if not self:element():isApplication() then
if fnutils.contains(events, self.elementDestroyed) then
self:watchDestroyed(true)
else
self:watchDestroyed(false)
events = fnutils.copy(events)
table.insert(events, self.elementDestroyed)
end
end
-- Actually start the watcher.
return self:_start(events)
end
--- hs.uielement.watcher:stop() -> hs.uielement.watcher
--- Method
--- Tells the watcher to stop listening for events.
---
--- Parameters:
--- * None
---
--- Returns:
--- * hs.uielement.watcher
---
--- Notes:
--- * This is automatically called if the element is destroyed.
function watcherMT.stop(self)
-- Remove self from appWatchers.
local pid = self:pid()
if appWatchers[pid] then
local idx = fnutils.indexOf(appWatchers[pid], self)
if idx then
table.remove(appWatchers[pid], idx)
end
end
return self:_stop()
end
return uielement
| mit |
Habbie/hammerspoon | extensions/window/init.lua | 1 | 45475 | --- === hs.window ===
---
--- Inspect/manipulate windows
---
--- Notes:
--- * See `hs.screen` and `hs.geometry` for more information on how Hammerspoon uses window/screen frames and coordinates
local application = require "hs.application"
local window = require("hs.window.internal")
local geometry = require "hs.geometry"
local gtype=geometry.type
local screen = require "hs.screen"
local timer = require "hs.timer"
require "hs.image" -- make sure we know about HSImage userdata type
local pairs,ipairs,next,min,max,abs,cos,type = pairs,ipairs,next,math.min,math.max,math.abs,math.cos,type
local tinsert,tremove,tsort,tunpack,tpack = table.insert,table.remove,table.sort,table.unpack,table.pack
local USERDATA_TAG = "hs.window"
local objectMT = hs.getObjectMetatable(USERDATA_TAG)
--- hs.window.animationDuration (number)
--- Variable
--- The default duration for animations, in seconds. Initial value is 0.2; set to 0 to disable animations.
---
--- Usage:
--- ```
--- hs.window.animationDuration = 0 -- disable animations
--- hs.window.animationDuration = 3 -- if you have time on your hands
--- ```
window.animationDuration = 0.2
--- hs.window.desktop() -> hs.window object
--- Function
--- Returns the desktop "window"
---
--- Parameters:
--- * None
---
--- Returns:
--- * An `hs.window` object representing the desktop, or nil if Finder is not running
---
--- Notes:
--- * The desktop belongs to Finder.app: when Finder is the active application, you can focus the desktop by cycling
--- through windows via cmd-`
--- * The desktop window has no id, a role of `AXScrollArea` and no subrole
--- * The desktop is filtered out from `hs.window.allWindows()` (and downstream uses)
function window.desktop()
local finder = application.get('com.apple.finder')
if not finder then return nil end
for _,w in ipairs(finder:allWindows()) do if w:role()=='AXScrollArea' then return w end end
end
--- hs.window.allWindows() -> list of hs.window objects
--- Function
--- Returns all windows
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list of `hs.window` objects representing all open windows
---
--- Notes:
--- * `visibleWindows()`, `orderedWindows()`, `get()`, `find()`, and several more functions and methods in this and other
--- modules make use of this function, so it is important to understand its limitations
--- * This function queries all applications for their windows every time it is invoked; if you need to call it a lot and
--- performance is not acceptable consider using the `hs.window.filter` module
--- * This function can only return windows in the current Mission Control Space; if you need to address windows across
--- different Spaces you can use the `hs.window.filter` module
--- - if `Displays have separate Spaces` is *on* (in System Preferences>Mission Control) the current Space is defined
--- as the union of all currently visible Spaces
--- - minimized windows and hidden windows (i.e. belonging to hidden apps, e.g. via cmd-h) are always considered
--- to be in the current Space
--- * This function filters out the desktop "window"; use `hs.window.desktop()` to address it. (Note however that
--- `hs.application.get'Finder':allWindows()` *will* include the desktop in the returned list)
--- * Beside the limitations discussed above, this function will return *all* windows as reported by OSX, including some
--- "windows" that one wouldn't expect: for example, every Google Chrome (actual) window has a companion window for its
--- status bar; therefore you might get unexpected results - in the Chrome example, calling `hs.window.focusWindowSouth()`
--- from a Chrome window would end up "focusing" its status bar, and therefore the proper window itself, seemingly resulting
--- in a no-op. In order to avoid such surprises you can use the `hs.window.filter` module, and more specifically
--- the default windowfilter (`hs.window.filter.default`) which filters out known cases of not-actual-windows
--- * Some windows will not be reported by OSX - e.g. things that are on different Spaces, or things that are Full Screen
local SKIP_APPS={
['com.apple.WebKit.WebContent']=true,['com.apple.qtserver']=true,['com.google.Chrome.helper']=true,
['org.pqrs.Karabiner-AXNotifier']=true,['com.adobe.PDApp.AAMUpdatesNotifier']=true,
['com.adobe.csi.CS5.5ServiceManager']=true,['com.mcafee.McAfeeReporter']=true}
-- so apparently OSX enforces a 6s limit on apps to respond to AX queries;
-- Karabiner's AXNotifier and Adobe Update Notifier fail in that fashion
function window.allWindows()
local r={}
for _,app in ipairs(application.runningApplications()) do
if app:kind()>=0 then
local bid=app:bundleID() or 'N/A' --just for safety; universalaccessd has no bundleid (but it's kind()==-1 anyway)
if bid=='com.apple.finder' then --exclude the desktop "window"
-- check the role explicitly, instead of relying on absent :id() - sometimes minimized windows have no :id() (El Cap Notes.app)
for _,w in ipairs(app:allWindows()) do if w:role()=='AXWindow' then r[#r+1]=w end end
elseif not SKIP_APPS[bid] then
for _,w in ipairs(app:allWindows()) do
r[#r+1]=w
end
end
end
end
return r
end
function window._timed_allWindows()
local r={}
for _,app in ipairs(application.runningApplications()) do
local starttime=timer.secondsSinceEpoch()
local _,bid=app:allWindows(),app:bundleID() or 'N/A'
r[bid]=(r[bid] or 0) + timer.secondsSinceEpoch()-starttime
end
for app,time in pairs(r) do
if time>0.05 then print(string.format('took %.2fs for %s',time,app)) end
end
-- print('known exclusions:') print(hs.inspect(SKIP_APPS))
return r
end
--- hs.window.visibleWindows() -> list of hs.window objects
--- Function
--- Gets all visible windows
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list containing `hs.window` objects representing all windows that are visible as per `hs.window:isVisible()`
function window.visibleWindows()
local r={}
for _,app in ipairs(application.runningApplications()) do
if app:kind()>0 and not app:isHidden() then for _,w in ipairs(app:visibleWindows()) do r[#r+1]=w end end -- speedup by excluding hidden apps
end
return r
end
--- hs.window.invisibleWindows() -> list of hs.window objects
--- Function
--- Gets all invisible windows
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list containing `hs.window` objects representing all windows that are not visible as per `hs.window:isVisible()`
function window.invisibleWindows()
local r = {}
for _, win in ipairs(window.allWindows()) do
if not win:isVisible() then r[#r + 1] = win end
end
return r
end
--- hs.window.minimizedWindows() -> list of hs.window objects
--- Function
--- Gets all minimized windows
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list containing `hs.window` objects representing all windows that are minimized as per `hs.window:isMinimized()`
function window.minimizedWindows()
local r = {}
for _, win in ipairs(window.allWindows()) do
if win:isMinimized() then r[#r + 1] = win end
end
return r
end
--- hs.window.orderedWindows() -> list of hs.window objects
--- Function
--- Returns all visible windows, ordered from front to back
---
--- Parameters:
--- * None
---
--- Returns:
--- * A list of `hs.window` objects representing all visible windows, ordered from front to back
function window.orderedWindows()
local r,winset,ids = {},{},window._orderedwinids()
for _,w in ipairs(window.visibleWindows()) do winset[w:id()or -1]=w end
for _,id in ipairs(ids) do r[#r+1]=winset[id] end -- no inner loop with a set, seems about 5% faster (iterating with prepoluated tables it's 50x faster)
return r
end
--- hs.window.get(hint) -> hs.window object
--- Constructor
--- Gets a specific window
---
--- Parameters:
--- * hint - search criterion for the desired window; it can be:
--- - an id number as per `hs.window:id()`
--- - a window title string as per `hs.window:title()`
---
--- Returns:
--- * the first hs.window object that matches the supplied search criterion, or `nil` if not found
---
--- Notes:
--- * see also `hs.window.find` and `hs.application:getWindow()`
function window.get(hint)
return tpack(window.find(hint,true),nil)[1] -- just to be sure, discard extra results
end
window.windowForID=window.get
--- hs.window.find(hint) -> hs.window object(s)
--- Constructor
--- Finds windows
---
--- Parameters:
--- * hint - search criterion for the desired window(s); it can be:
--- - an id number as per `hs.window:id()`
--- - a string pattern that matches (via `string.find`) the window title as per `hs.window:title()` (for convenience, the matching will be done on lowercased strings)
---
--- Returns:
--- * one or more hs.window objects that match the supplied search criterion, or `nil` if none found
---
--- Notes:
--- * for convenience you can call this as `hs.window(hint)`
--- * see also `hs.window.get`
--- * for more sophisticated use cases and/or for better performance if you call this a lot, consider using `hs.window.filter`
---
--- Usage:
--- ```
--- -- by id
--- hs.window(8812):title() --> Hammerspoon Console
--- -- by title
--- hs.window'bash':application():name() --> Terminal
--- ```
function window.find(hint,exact,wins)
if hint==nil then return end
local typ,r=type(hint),{}
wins=wins or window.allWindows()
if typ=='number' then for _,w in ipairs(wins) do if w:id()==hint then return w end end return
elseif typ~='string' then error('hint must be a number or string',2) end
if exact then for _,w in ipairs(wins) do if w:title()==hint then r[#r+1]=w end end
else hint=hint:lower() for _,w in ipairs(wins) do local wtitle=w:title() if wtitle and wtitle:lower():find(hint) then r[#r+1]=w end end end
if #r>0 then return tunpack(r) end
end
--- hs.window:isVisible() -> boolean
--- Method
--- Determines if a window is visible (i.e. not hidden and not minimized)
---
--- Parameters:
--- * None
---
--- Returns:
--- * `true` if the window is visible, otherwise `false`
---
--- Notes:
--- * This does not mean the user can see the window - it may be obscured by other windows, or it may be off the edge of the screen
function objectMT.isVisible(self)
if not self:application() then return false end
return not self:application():isHidden() and not self:isMinimized()
end
local animations, animTimer = {}
local DISTANT_FUTURE=315360000 -- 10 years (roughly)
--[[ local function quad(x,s,len)
local l=max(0,min(2,(x-s)*2/len))
if l<1 then return l*l/2
else l=2-l return 1-(l*l/2) end
end --]]
local function quadOut(x,s,len)
local l=1-max(0,min(1,(x-s)/len))
return 1-l*l
end
local function animate()
local time = timer.secondsSinceEpoch()
for id,anim in pairs(animations) do
local r = quadOut(time,anim.time,anim.duration)
local f = {}
if r>=1 then
f=anim.endFrame
animations[id] = nil
else
for _,k in pairs{'x','y','w','h'} do
f[k] = anim.startFrame[k] + (anim.endFrame[k]-anim.startFrame[k])*r
end
end
anim.window:_setFrame(f)
end
if not next(animations) then animTimer:setNextTrigger(DISTANT_FUTURE) end
end
animTimer = timer.new(0.017,animate)
animTimer:start() --keep this split
local function getAnimationFrame(win)
local id = win:id()
if animations[id] then return animations[id].endFrame end
end
local function stopAnimation(win,snap,id)
if not id then id = win:id() end
local anim = animations[id]
if not anim then return end
animations[id] = nil
if not next(animations) then animTimer:setNextTrigger(DISTANT_FUTURE) end
if snap then win:_setFrame(anim.endFrame) end
end
function objectMT._frame(self) -- get actual window frame right now
return geometry(self:_topLeft(),self:_size())
end
function objectMT._setFrame(self, f) -- set window frame instantly
self:_setSize(f) self:_setTopLeft(f) return self:_setSize(f)
end
local function setFrameAnimated(self,id,f,duration)
local frame = self:_frame()
if not animations[id] then animations[id] = {window=self} end
local anim = animations[id]
anim.time=timer.secondsSinceEpoch() anim.duration=duration
anim.startFrame=frame anim.endFrame=f
animTimer:setNextTrigger(0.01)
return self
end
local function setFrameWithWorkarounds(self,f,duration)
local originalFrame=geometry(self:_frame())
local safeBounds=self:screen():frame()
if duration>0 then -- if no animation, skip checking for possible trouble
if not originalFrame:inside(safeBounds) then duration=0 -- window straddling screens or partially offscreen
else
local testSize=geometry.size(originalFrame.w-1,originalFrame.h-1)
self:_setSize(testSize)
-- find out if it's a terminal, or a window already shrunk to minimum, or a window on a 'sticky' edge
local newSize=self:_size()
if originalFrame.size==newSize -- terminal or minimum size
or (testSize~=newSize and (abs(f.x2-originalFrame.x2)<100 or abs(f.y2-originalFrame.y2)<100)) then --sticky edge, and not going far enough
duration=0 end -- don't animate troublesome windows
end
end
local safeFrame=geometry.new(originalFrame.xy,f.size) --apply the desired size
safeBounds:move(30,30) -- offset
safeBounds.w=safeBounds.w-60 safeBounds.h=safeBounds.h-60 -- and shrink
self:_setFrame(safeFrame:fit(safeBounds)) -- put it within a 'safe' area in the current screen, and insta-resize
local actualSize=geometry(self:_size()) -- get the *actual* size the window resized to
if actualSize.area>f.area then f.size=actualSize end -- if it's bigger apply it
if duration==0 then
self:_setSize(f.size) -- apply the final size while the window is still in the safe area
self:_setTopLeft(f)
return self:_setSize(f.size)
end
self:_setFrame(originalFrame) -- restore the original frame and start the animation
return setFrameAnimated(self,self:id(),f,duration)
end
local function setFrame(self,f,duration,workarounds)
if duration==nil then duration = window.animationDuration end
if type(duration)~='number' then duration=0 end
f=geometry(f):floor()
if gtype(f)~='rect' then error('invalid rect: '..f.string,3) end
local id=self:id()
if id then stopAnimation(self,false,id) else duration=0 end
if workarounds then return setFrameWithWorkarounds(self,f,duration)
elseif duration<=0 then return self:_setFrame(f)
else return setFrameAnimated(self,id,f,duration) end
end
--- hs.window:setFrame(rect[, duration]) -> hs.window object
--- Method
--- Sets the frame of the window in absolute coordinates
---
--- Parameters:
--- * rect - An hs.geometry rect, or constructor argument, describing the frame to be applied to the window
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
function objectMT.setFrame(self, f, duration) return setFrame(self,f,duration,window.setFrameCorrectness) end
--- hs.window:setFrameWithWorkarounds(rect[, duration]) -> hs.window object
--- Method
--- Sets the frame of the window in absolute coordinates, using the additional workarounds described in `hs.window.setFrameCorrectness`
---
--- Parameters:
--- * rect - An hs.geometry rect, or constructor argument, describing the frame to be applied to the window
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
function objectMT.setFrameWithWorkarounds(self, f, duration) return setFrame(self,f,duration,true) end
--- hs.window.setFrameCorrectness
--- Variable
--- Using `hs.window:setFrame()` in some cases does not work as expected: namely, the bottom (or Dock) edge, and edges between screens, might
--- exhibit some "stickiness"; consequently, trying to make a window abutting one of those edges just *slightly* smaller could
--- result in no change at all (you can verify this by trying to resize such a window with the mouse: at first it won't budge,
--- and, as you drag further away, suddenly snap to the new size); and similarly in some cases windows along screen edges
--- might erroneously end up partially on the adjacent screen after a move/resize. Additionally some windows (no matter
--- their placement on screen) only allow being resized at "discrete" steps of several screen points; the typical example
--- is Terminal windows, which only resize to whole rows and columns. Both these OSX issues can cause incorrect behavior
--- when using `:setFrame()` directly or in downstream uses, such as `hs.window:move()` and the `hs.grid` and `hs.window.layout` modules.
---
--- Setting this variable to `true` will make `:setFrame()` perform additional checks and workarounds for these potential
--- issues. However, as a side effect the window might appear to jump around briefly before setting toward its destination
--- frame, and, in some cases, the move/resize animation (if requested) might be skipped entirely - these tradeoffs are
--- necessary to ensure the desired result.
---
--- The default value is `false`, in order to avoid the possibly annoying or distracting window wiggling; set to `true` if you see
--- incorrect results in `:setFrame()` or downstream modules and don't mind the the wiggling.
window.setFrameCorrectness = false
--- hs.window:setFrameInScreenBounds([rect][, duration]) -> hs.window object
--- Method
--- Sets the frame of the window in absolute coordinates, possibly adjusted to ensure it is fully inside the screen
---
--- Parameters:
--- * rect - An hs.geometry rect, or constructor argument, describing the frame to be applied to the window; if omitted,
--- the current window frame will be used
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
function objectMT.setFrameInScreenBounds(self, f, duration)
if type(f)=='number' then duration=f f=nil end
f = f and geometry(f):floor() or self:frame()
return self:setFrame(f:fit(screen.find(f):frame()),duration)
end
window.ensureIsInScreenBounds=window.setFrameInScreenBounds --backward compatible
--- hs.window:frame() -> hs.geometry rect
--- Method
--- Gets the frame of the window in absolute coordinates
---
--- Parameters:
--- * None
---
--- Returns:
--- * An hs.geometry rect containing the co-ordinates of the top left corner of the window and its width and height
function objectMT.frame(self) return getAnimationFrame(self) or self:_frame() end
-- wrapping these Lua-side for dealing with animations cache
function objectMT.size(self)
local f=getAnimationFrame(self)
return f and f.size or geometry(self:_size())
end
function objectMT.topLeft(self)
local f=getAnimationFrame(self)
return f and f.xy or geometry(self:_topLeft())
end
function objectMT.setSize(self, ...)
stopAnimation(self,true)
return self:_setSize(geometry.size(...))
end
function objectMT.setTopLeft(self, ...)
stopAnimation(self,true)
return self:_setTopLeft(geometry.point(...))
end
function objectMT.minimize(self)
stopAnimation(self,true)
return self:_minimize()
end
function objectMT.unminimize(self)
stopAnimation(self,true)
return self:_unminimize()
end
function objectMT.toggleZoom(self)
stopAnimation(self,true)
return self:_toggleZoom()
end
function objectMT.setFullScreen(self, v)
stopAnimation(self,true)
return self:_setFullScreen(v)
end
function objectMT.close(self)
stopAnimation(self,true)
return self:_close()
end
--- hs.window:otherWindowsSameScreen() -> list of hs.window objects
--- Method
--- Gets other windows on the same screen
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table of `hs.window` objects representing the visible windows other than this one that are on the same screen
function objectMT.otherWindowsSameScreen(self)
local r=window.visibleWindows() for i=#r,1,-1 do if r[i]==self or r[i]:screen()~=self:screen() then tremove(r,i) end end
return r
end
--- hs.window:otherWindowsAllScreens() -> list of hs.window objects
--- Method
--- Gets every window except this one
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table containing `hs.window` objects representing all visible windows other than this one
function objectMT.otherWindowsAllScreens(self)
local r=window.visibleWindows() for i=#r,1,-1 do if r[i]==self then tremove(r,i) break end end
return r
end
local desktopFocusWorkaroundTimer --workaround for the desktop taking over
--- hs.window:focus() -> hs.window object
--- Method
--- Focuses the window
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `hs.window` object
function objectMT.focus(self)
local app=self:application()
if app then
self:becomeMain()
app:_bringtofront()
if app:bundleID()=='com.apple.finder' then --workaround for the desktop taking over
-- it may look like this should ideally go inside :becomeMain(), but the problem is actually
-- triggered by :_bringtofront(), so the workaround belongs here
if desktopFocusWorkaroundTimer then desktopFocusWorkaroundTimer:stop() end
desktopFocusWorkaroundTimer=timer.doAfter(0.3,function()
-- 0.3s comes from https://github.com/Hammerspoon/hammerspoon/issues/581
-- it'd be slightly less ugly to use a "space change completed" callback (as per issue above) rather than
-- a crude timer, althought that route is a lot more complicated
self:becomeMain()
desktopFocusWorkaroundTimer=nil --cleanup the timer
end)
self:becomeMain() --ensure space change actually takes place when necessary
end
end
return self
end
--- hs.window:sendToBack() -> hs.window object
--- Method
--- Sends the window to the back
---
--- This method works by focusing all overlapping windows behind this one, front to back.
--- If called on the focused window, this method will switch focus to the topmost window under this one; otherwise, the
--- currently focused window will regain focus after this window has been sent to the back.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `hs.window` object
---
--- Notes:
--- * Due to the way this method works and OSX limitations, calling this method when you have a lot of randomly overlapping
--- (as opposed to neatly tiled) windows might be visually jarring, and take a fair amount of time to complete.
--- So if you don't use orderly layouts, or if you have a lot of windows in general, you're probably better off using
--- `hs.application:hide()` (or simply `cmd-h`)
local WINDOW_ROLES={AXStandardWindow=true,AXDialog=true,AXSystemDialog=true}
function objectMT.sendToBack(self)
local id,frame=self:id(),self:frame()
local fw=window.focusedWindow()
local wins=window.orderedWindows()
for z=#wins,1,-1 do local w=wins[z] if id==w:id() or not WINDOW_ROLES[w:subrole()] then tremove(wins,z) end end
local toRaise,topz,didwork={}
repeat
for z=#wins,1,-1 do
didwork=nil
local wf=wins[z]:frame()
if frame:intersect(wf).area>0 then
topz=z
if not toRaise[z] then
didwork=true
toRaise[z]=true
frame=frame:union(wf) break
end
end
end
until not didwork
if topz then
for z=#wins,1,-1 do if toRaise[z] then wins[z]:focus() timer.usleep(80000) end end
wins[topz]:focus()
if fw and fw:id()~=id then fw:focus() end
end
return self
end
--- hs.window:maximize([duration]) -> hs.window object
--- Method
--- Maximizes the window
---
--- Parameters:
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
---
--- Notes:
--- * The window will be resized as large as possible, without obscuring the dock/menu
function objectMT.maximize(self, duration)
return self:setFrame(self:screen():frame(), duration)
end
--- hs.window:toggleFullScreen() -> hs.window object
--- Method
--- Toggles the fullscreen state of the window
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `hs.window` object
---
--- Notes:
--- * Not all windows support being full-screened
function objectMT.toggleFullScreen(self)
self:setFullScreen(not self:isFullScreen())
return self
end
-- aliases
objectMT.toggleFullscreen=objectMT.toggleFullScreen
objectMT.isFullscreen=objectMT.isFullScreen
objectMT.setFullscreen=objectMT.setFullScreen
--- hs.window:screen() -> hs.screen object
--- Method
--- Gets the screen which the window is on
---
--- Parameters:
--- * None
---
--- Returns:
--- * An `hs.screen` object representing the screen which most contains the window (by area)
function objectMT.screen(self)
return screen.find(self:frame())--findScreenForFrame(self:frame())
end
local function isFullyBehind(f1,w2)
local f2=geometry(w2:frame())
return f1:intersect(f2).area>=f2.area*0.95
end
local function windowsInDirection(fromWindow, numRotations, candidateWindows, frontmost, strict)
-- assume looking to east
-- use the score distance/cos(A/2), where A is the angle by which it
-- differs from the straight line in the direction you're looking
-- for. (may have to manually prevent division by zero.)
local fromFrame=geometry(fromWindow:frame())
local winset,fromz,fromid={},99999,fromWindow:id() or -1
for z,w in ipairs(candidateWindows or window.orderedWindows()) do
if fromid==(w:id() or -2) then fromz=z --workaround the fact that userdata keep changing
elseif not candidateWindows or w:isVisible() then winset[w]=z end --make a set, avoid inner loop (if using .orderedWindows skip the visible check as it's done upstream)
end
if frontmost then for w,z in pairs(winset) do if z>fromz and isFullyBehind(fromFrame,w) then winset[w]=nil end end end
local p1,wins=fromFrame.center,{}
for win,z in pairs(winset) do
local frame=geometry(win:frame())
local delta = p1:vector(frame.center:rotateCCW(p1,numRotations))
if delta.x > (strict and abs(delta.y) or 0) then
wins[#wins+1]={win=win,score=delta.length/cos(delta:angle()/2)+z,z=z,frame=frame}
end
end
tsort(wins,function(a,b)return a.score<b.score end)
if frontmost then
local i=1
while i<=#wins do
for j=i+1,#wins do
if wins[j].z<wins[i].z then
local r=wins[i].frame:intersect(wins[j].frame)
if r.w>5 and r.h>5 then --TODO var for threshold
--this window is further away, but it occludes the closest
local swap=wins[i] wins[i]=wins[j] wins[j]=swap
i=i-1 break
end
end
end
i=i+1
end
end
for i=1,#wins do wins[i]=wins[i].win end
return wins
end
--TODO zorder direct manipulation (e.g. sendtoback)
local function focus_first_valid_window(ordered_wins)
for _,win in ipairs(ordered_wins) do if win:focus() then return true end end
return false
end
--- hs.window:windowsToEast([candidateWindows[, frontmost[, strict]]]) -> list of hs.window objects
--- Method
--- Gets all windows to the east of this window
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows to the east are candidates.
--- * frontmost - (optional) boolean, if true unoccluded windows will be placed before occluded ones in the result list
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the eastward axis
---
--- Returns:
--- * A list of `hs.window` objects representing all windows positioned east (i.e. right) of the window, in ascending order of distance
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows every time this method is called; this can be slow, and some undesired "windows" could be included (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in `hs.window.filter` instead
--- hs.window:windowsToWest([candidateWindows[, frontmost[, strict]]]) -> list of hs.window objects
--- Method
--- Gets all windows to the west of this window
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows to the west are candidates.
--- * frontmost - (optional) boolean, if true unoccluded windows will be placed before occluded ones in the result list
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the westward axis
---
--- Returns:
--- * A list of `hs.window` objects representing all windows positioned west (i.e. left) of the window, in ascending order of distance
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows every time this method is called; this can be slow, and some undesired "windows" could be included (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in `hs.window.filter` instead
--- hs.window:windowsToNorth([candidateWindows[, frontmost[, strict]]]) -> list of hs.window objects
--- Method
--- Gets all windows to the north of this window
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows to the north are candidates.
--- * frontmost - (optional) boolean, if true unoccluded windows will be placed before occluded ones in the result list
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the northward axis
---
--- Returns:
--- * A list of `hs.window` objects representing all windows positioned north (i.e. up) of the window, in ascending order of distance
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows every time this method is called; this can be slow, and some undesired "windows" could be included (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in `hs.window.filter` instead
--- hs.window:windowsToSouth([candidateWindows[, frontmost[, strict]]]) -> list of hs.window objects
--- Method
--- Gets all windows to the south of this window
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows to the south are candidates.
--- * frontmost - (optional) boolean, if true unoccluded windows will be placed before occluded ones in the result list
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the southward axis
---
--- Returns:
--- * A list of `hs.window` objects representing all windows positioned south (i.e. down) of the window, in ascending order of distance
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows every time this method is called; this can be slow, and some undesired "windows" could be included (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in `hs.window.filter` instead
--- hs.window.frontmostWindow() -> hs.window object
--- Constructor
--- Returns the focused window or, if no window has focus, the frontmost one
---
--- Parameters:
--- * None
---
--- Returns:
--- * An `hs.window` object representing the frontmost window, or `nil` if there are no visible windows
function window.frontmostWindow()
local w=window.focusedWindow()
if w then return w end
for _,ww in ipairs(window.orderedWindows()) do
local app=ww:application()
if (app and app:title()~='Hammerspoon') or ww:subrole()~='AXUnknown' then return ww end
end
end
for n,dir in pairs{['0']='East','North','West','South'}do
objectMT['windowsTo'..dir]=function(self,...)
self=self or window.frontmostWindow()
return self and windowsInDirection(self,n,...)
end
objectMT['focusWindow'..dir]=function(self,wins,...)
self=self or window.frontmostWindow()
if not self then return end
if wins==true then -- legacy sameApp parameter
wins=self:application():visibleWindows()
end
return self and focus_first_valid_window(objectMT['windowsTo'..dir](self,wins,...))
end
objectMT['moveOneScreen'..dir]=function(self,...) local s=self:screen() return self:moveToScreen(s['to'..dir](s),...) end
end
--- hs.window:focusWindowEast([candidateWindows[, frontmost[, strict]]]) -> boolean
--- Method
--- Focuses the nearest possible window to the east (i.e. right)
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows
--- to the east are candidates.
--- * frontmost - (optional) boolean, if true focuses the nearest window that isn't occluded by any other window
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the
--- eastward axis
---
--- Returns:
--- * `true` if a window was found and focused, `false` otherwise; `nil` if the search couldn't take place
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows
--- every time this method is called; this can be slow, and some undesired "windows" could be included
--- (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in
--- `hs.window.filter` instead
--- hs.window:focusWindowWest([candidateWindows[, frontmost[, strict]]]) -> boolean
--- Method
--- Focuses the nearest possible window to the west (i.e. left)
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows
--- to the east are candidates.
--- * frontmost - (optional) boolean, if true focuses the nearest window that isn't occluded by any other window
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the
--- eastward axis
---
--- Returns:
--- * `true` if a window was found and focused, `false` otherwise; `nil` if the search couldn't take place
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows
--- every time this method is called; this can be slow, and some undesired "windows" could be included
--- (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in
--- `hs.window.filter` instead
--- hs.window:focusWindowNorth([candidateWindows[, frontmost[, strict]]]) -> boolean
--- Method
--- Focuses the nearest possible window to the north (i.e. up)
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows
--- to the east are candidates.
--- * frontmost - (optional) boolean, if true focuses the nearest window that isn't occluded by any other window
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the
--- eastward axis
---
--- Returns:
--- * `true` if a window was found and focused, `false` otherwise; `nil` if the search couldn't take place
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows
--- every time this method is called; this can be slow, and some undesired "windows" could be included
--- (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in
--- `hs.window.filter` instead
--- hs.window:focusWindowSouth([candidateWindows[, frontmost[, strict]]]) -> boolean
--- Method
--- Focuses the nearest possible window to the south (i.e. down)
---
--- Parameters:
--- * candidateWindows - (optional) a list of candidate windows to consider; if nil, all visible windows
--- to the east are candidates.
--- * frontmost - (optional) boolean, if true focuses the nearest window that isn't occluded by any other window
--- * strict - (optional) boolean, if true only consider windows at an angle between 45° and -45° on the
--- eastward axis
---
--- Returns:
--- * `true` if a window was found and focused, `false` otherwise; `nil` if the search couldn't take place
---
--- Notes:
--- * If you don't pass `candidateWindows`, Hammerspoon will query for the list of all visible windows
--- every time this method is called; this can be slow, and some undesired "windows" could be included
--- (see the notes for `hs.window.allWindows()`); consider using the equivalent methods in
--- `hs.window.filter` instead
--- hs.window:centerOnScreen([screen][, ensureInScreenBounds][, duration]) --> hs.window object
--- Method
--- Centers the window on a screen
---
--- Parameters:
--- * screen - (optional) An `hs.screen` object or argument for `hs.screen.find`; if nil, use the screen the window is currently on
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
function objectMT.centerOnScreen(self, toScreen,inBounds,duration)
if type(toScreen)=='boolean' then duration=inBounds inBounds=toScreen toScreen=nil
elseif type(toScreen)=='number' then duration=toScreen inBounds=nil toScreen=nil end
if type(inBounds)=='number' then duration=inBounds inBounds=nil end
toScreen=screen.find(toScreen) or self:screen()
local sf,wf=toScreen:fullFrame(),self:frame()
local frame=geometry(toScreen:localToAbsolute((geometry(sf.w,sf.h)-geometry(wf.w,wf.h))*0.5),wf.size)
if inBounds then return self:setFrameInScreenBounds(frame,duration)
else return self:setFrame(frame,duration) end
end
--- hs.window:moveToUnit(unitrect[, duration]) -> hs.window object
--- Method
--- Moves and resizes the window to occupy a given fraction of the screen
---
--- Parameters:
--- * unitrect - An `hs.geometry` unit rect, or constructor argument to create one
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
---
--- Notes:
--- * An example, which would make a window fill the top-left quarter of the screen: `win:moveToUnit'[0,0,50,50]'`
function objectMT.moveToUnit(self, unit, duration)
return self:setFrame(self:screen():fromUnitRect(unit),duration)
end
--- hs.window:moveToScreen(screen[, noResize, ensureInScreenBounds][, duration]) -> hs.window object
--- Method
--- Moves the window to a given screen, retaining its relative position and size
---
--- Parameters:
--- * screen - An `hs.screen` object, or an argument for `hs.screen.find()`, representing the screen to move the window to
--- * noResize - (optional) if `true`, maintain the window's absolute size
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
function objectMT.moveToScreen(self, toScreen,noResize,inBounds,duration)
if not toScreen then return end
local theScreen=screen.find(toScreen)
if not theScreen then print('window:moveToScreen(): screen not found: '..toScreen) return self end
if type(noResize)=='number' then duration=noResize noResize=nil inBounds=nil end
local frame=theScreen:fromUnitRect(self:screen():toUnitRect(self:frame()))
if noResize then frame.size=self:size() end
-- local frame=theScreen:localToAbsolute(self:screen():absoluteToLocal(self:frame()))
if inBounds then return self:setFrameInScreenBounds(frame,duration)
else return self:setFrame(frame,duration) end
-- else return self:setFrame(theScreen:fromUnitRect(self:screen():toUnitRect(self:frame())),duration) end
end
--- hs.window:move(rect[, screen][, ensureInScreenBounds][, duration]) --> hs.window object
--- Method
--- Moves the window
---
--- Parameters:
--- * rect - It can be:
--- - an `hs.geometry` point, or argument to construct one; will move the screen by this delta, keeping its size constant; `screen` is ignored
--- - an `hs.geometry` rect, or argument to construct one; will set the window frame to this rect, in absolute coordinates; `screen` is ignored
--- - an `hs.geometry` unit rect, or argument to construct one; will set the window frame to this rect relative to the desired screen;
--- if `screen` is nil, use the screen the window is currently on
--- * screen - (optional) An `hs.screen` object or argument for `hs.screen.find`; only valid if `rect` is a unit rect
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
function objectMT.move(self, rect,toScreen,inBounds,duration)
if type(toScreen)=='boolean' then duration=inBounds inBounds=toScreen toScreen=nil
elseif type(toScreen)=='number' then duration=toScreen inBounds=nil toScreen=nil end
if type(inBounds)=='number' then duration=inBounds inBounds=nil end
rect=geometry(rect)
local rtype,frame=rect:type()
if rtype=='point' then frame=geometry(self:frame()):move(rect)
if type(toScreen)=='number' then inBounds=nil duration=toScreen end
elseif rtype=='rect' then frame=rect
if type(toScreen)=='number' then inBounds=nil duration=toScreen end
elseif rtype=='unitrect' then
local theScreen
if toScreen then
theScreen=screen.find(toScreen)
if not theScreen then print('window:move(): screen not found: '..toScreen) return self end
else theScreen=self:screen() end
frame=rect:fromUnitRect(theScreen:frame())
else error('rect must be a point, rect, or unit rect',2) end
if inBounds then return self:setFrameInScreenBounds(frame,duration)
else return self:setFrame(frame,duration) end
end
--- hs.window:moveOneScreenEast([noResize, ensureInScreenBounds][, duration]) -> hs.window object
--- Method
--- Moves the window one screen east (i.e. right)
---
--- Parameters:
--- * noResize - (optional) if `true`, maintain the window's absolute size
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
--- hs.window:moveOneScreenWest([noResize, ensureInScreenBounds][, duration]) -> hs.window object
--- Method
--- Moves the window one screen west (i.e. left)
---
--- Parameters:
--- * noResize - (optional) if `true`, maintain the window's absolute size
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
--- hs.window:moveOneScreenNorth([noResize, ensureInScreenBounds][, duration]) -> hs.window object
--- Method
--- Moves the window one screen north (i.e. up)
---
---
--- Parameters:
--- * noResize - (optional) if `true`, maintain the window's absolute size
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
--- hs.window:moveOneScreenSouth([noResize, ensureInScreenBounds][, duration]) -> hs.window object
--- Method
--- Moves the window one screen south (i.e. down)
---
---
--- Parameters:
--- * noResize - (optional) if `true`, maintain the window's absolute size
--- * ensureInScreenBounds - (optional) if `true`, use `setFrameInScreenBounds()` to ensure the resulting window frame is fully contained within
--- the window's screen
--- * duration - (optional) The number of seconds to animate the transition. Defaults to the value of `hs.window.animationDuration`
---
--- Returns:
--- * The `hs.window` object
do
local submodules={filter=true,layout=true,tiling=true,switcher=true,highlight=true}
local function loadSubModule(k)
print("-- Loading extensions: window."..k)
window[k]=require('hs.window.'..k)
return window[k]
end
local mt=getmetatable(window)
--inject "lazy loading" for submodules
mt.__index=function(_,k)
if submodules[k] then
return loadSubModule(k)
else
return nil -- if it's already in the module, __index is never called
end
end
-- whoever gets it first (window vs application)
if not mt.__call then mt.__call=function(t,...) return t.find(...) end end
end
return window
| mit |
RuiChen1113/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua | 73 | 1191 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("luci_statistics",
translate("Unixsock Plugin Configuration"),
translate(
"The unixsock plugin creates a unix socket which can be used " ..
"to read collected data from a running collectd instance."
))
-- collectd_unixsock config section
s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" )
-- collectd_unixsock.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_unixsock.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile" )
socketfile.default = "/var/run/collect-query.socket"
socketfile:depends( "enable", 1 )
-- collectd_unixsock.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup" )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_unixsock.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms" )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
return m
| apache-2.0 |
Silencer2K/wow-mount-farm-helper | AltCraftFrame.lua | 1 | 3235 | local addonName, addon = ...
local L = LibStub('AceLocale-3.0'):GetLocale(addonName)
local LIST_SCROLL_ITEM_HEIGHT = 60
local frame = AltCraftMFHTabFrame
function frame:OnInitialize()
self.Title:SetText("Mount Farm Helper")
self.RestoreButton:SetText(L.btn_restore_all)
self.ListScroll:OnInitialize()
end
function frame:OnShow()
local parent = self:GetParent()
parent.TopLeft:SetTexture('Interface\\Addons\\AltCraft\\assets\\frame\\tl')
parent.Top:SetTexture('Interface\\Addons\\AltCraft\\assets\\frame\\t')
parent.TopRight:SetTexture('Interface\\Addons\\AltCraft\\assets\\frame\\tr')
parent.BottomLeft:SetTexture('Interface\\Addons\\AltCraft\\assets\\frame\\bl')
parent.Portrait:SetTexture('Interface\\ICONS\\ABILITY_MOUNT_GOLDENGRYPHON')
self:Update()
end
function frame:OnSelectItem(button)
if self.selectedItem and self.selectedItem == button.data.itemId then
self.selectedItem = nil
else
self.selectedItem = button.data.itemId
end
self:Update()
end
function frame:OnDeleteClick()
end
function frame:OnRestoreClick()
end
function frame:Update(what)
if what then
return
end
self.ListScroll:Update()
end
function frame.ListScroll:OnInitialize()
self.scrollBar.doNotHide = 1
HybridScrollFrame_OnLoad(self)
self.update = function() self:Update() end
HybridScrollFrame_CreateButtons(self, 'AltCraftMFHButtonTemplate', 0, 0)
self:Update()
end
function frame.ListScroll:OnUpdate()
local button
for button in table.s2k_values(self.buttons) do
if button:IsMouseOver() then
button.Highlight:Show()
if GameTooltip:IsOwned(button.Icon) then
GameTooltip:SetOwner(button.Icon, "ANCHOR_RIGHT")
GameTooltip:SetItemByID(button.data.itemId)
end
elseif self:GetParent().selectedItem == button.data.itemId then
button.Highlight:Show()
else
button.Highlight:Hide()
end
end
end
function frame.ListScroll:Update()
local list = addon:BuildAltCraftList()
local numRows = #list
HybridScrollFrame_Update(self, numRows * LIST_SCROLL_ITEM_HEIGHT, self:GetHeight())
local scrollOffset = HybridScrollFrame_GetOffset(self)
local i
for i = 1, #self.buttons do
local button = self.buttons[i]
local item = list[i + scrollOffset]
if scrollOffset + i <= numRows then
button.data = item
button:Show()
button.Icon.Texture:SetTexture(item.icon)
button.Item:SetText(item.link:gsub('[%[%]]', ''))
if item.sources[1].comment then
button.Zone:SetText(string.format('%s (%s)', item.sources[1].zone, item.sources[1].comment))
else
button.Zone:SetText(item.sources[1].zone)
end
local numSources = table.s2k_len(item.sources)
if numSources > 1 then
button.Source:SetText(string.format("%s (+%d)", item.sources[1].source, numSources - 1))
else
button.Source:SetText(item.sources[1].source)
end
else
button:Hide()
end
end
end
| mit |
sigma-random/PrefSDK | formats/bitmap/definition.lua | 1 | 4256 | local pref = require("pref")
local BitmapBPP = require("formats.bitmap.bpp")
local DataType = pref.datatype
local BitmapFormat = pref.format.create("Bitmap Image", "Imaging", "Dax", "1.1")
function BitmapFormat:validate(validator)
local validbpp = {1, 4, 8, 16, 24, 32}
validator:checkAscii(0, "BM") -- Bitmap's Signature
validator:checkType(14, 40, DataType.UInt32_LE) -- BitmapInfoHeader.biSize
validator:checkType(26, 0x00000001, DataType.UInt16_LE) -- BitmapInfoHseader.biPlanes
for _, bpp in pairs(validbpp) do
if validator:checkType(28, bpp, DataType.UInt16_LE, false) == true then -- BitmapInfoHeader.biBitCount
return
end
end
validator:error("Invalid BPP")
end
function BitmapFormat:parse(formattree)
local bitmapfileheader = formattree:addStructure("BitmapFileHeader")
bitmapfileheader:addField(DataType.UInt16_LE, "bfType")
bitmapfileheader:addField(DataType.UInt32_LE, "bfSize")
bitmapfileheader:addField(DataType.UInt16_LE, "bfReserved1")
bitmapfileheader:addField(DataType.UInt16_LE, "bfReserved2")
bitmapfileheader:addField(DataType.UInt32_LE, "bfOffBits")
local bitmapinfoheader = formattree:addStructure("BitmapInfoHeader")
bitmapinfoheader:addField(DataType.UInt32_LE, "biSize")
bitmapinfoheader:addField(DataType.Int32_LE, "biWidth"):dynamicInfo(BitmapFormat.displaySize)
bitmapinfoheader:addField(DataType.Int32_LE, "biHeight"):dynamicInfo(BitmapFormat.displaySize)
bitmapinfoheader:addField(DataType.UInt16_LE, "biPlanes")
bitmapinfoheader:addField(DataType.UInt16_LE, "biBitCount"):dynamicInfo(BitmapFormat.displayBpp)
bitmapinfoheader:addField(DataType.UInt32_LE, "biCompression")
bitmapinfoheader:addField(DataType.UInt32_LE, "biSizeImage")
bitmapinfoheader:addField(DataType.Int32_LE, "biXPelsPerMeter")
bitmapinfoheader:addField(DataType.Int32_LE, "biYPelsPerMeter")
bitmapinfoheader:addField(DataType.UInt32_LE, "biClrUsed")
bitmapinfoheader:addField(DataType.UInt32_LE, "biClrImportant")
local bitcount = bitmapinfoheader.biBitCount.value
if bitcount < 24 then
self:parseColorTable(formattree, bitmapinfoheader, bitcount)
end
formattree:addStructure("BitmapBits"):dynamicParser(bitmapinfoheader.biSizeImage.value > 0, BitmapFormat.parseBits)
end
function BitmapFormat:view(formattree)
if formattree.BitmapInfoHeader.biBitCount.value >= 24 then -- No Color Table
return nil
end
return pref.format.loadview("formats/bitmap/ui/ColorTable.qml", formattree)
end
function BitmapFormat:parseColorTable(formattree, bitmapinfoheader, bitcount)
local clrused = bitmapinfoheader.biClrUsed.value
local colortable = formattree:addStructure("ColorTable")
local tablesize = (clrused and clrused or bit.lshift(1, bitcount))
for i = 1, tablesize do
local colorentry = colortable:addStructure(string.format("Color_%d", i - 1)):dynamicInfo(BitmapFormat.displayColorHex)
colorentry:addField(DataType.UInt8, "Blue")
colorentry:addField(DataType.UInt8, "Green")
colorentry:addField(DataType.UInt8, "Red")
colorentry:addField(DataType.UInt8, "Reserved")
end
end
function BitmapFormat.parseBits(bitmapbits, formattree)
local w = formattree.BitmapInfoHeader.biWidth.value
local h = formattree.BitmapInfoHeader.biHeight.value
local bpp = formattree.BitmapInfoHeader.biBitCount.value
local rowsize = (((bpp * w) + 31) / 32) * 4
local line = 0
if h < 0 then
h = math.abs(h)
end
while line < h do
bitmapbits:addField(DataType.UInt8, string.format("ScanLine_%d", line), rowsize)
line = line + 1
end
end
function BitmapFormat.displaySize(sizefield, formattree)
if sizefield.value < 0 then
return string.format("%dpx (Reversed)", math.abs(sizefield.value))
end
return string.format("%dpx", sizefield.value)
end
function BitmapFormat.displayBpp(bitcountfield, formattree)
local bpp = BitmapBPP[bitcountfield.value]
if bpp == nil then
return "Invalid BPP"
end
return bpp
end
function BitmapFormat.displayColorHex(colorentry, formattree)
return string.format("#%02X%02X%02X%02X", colorentry.Reserved.value, colorentry.Red.value, colorentry.Green.value, colorentry.Blue.value)
end
return BitmapFormat | gpl-3.0 |
nikai3d/codecombat-scripts | mountain/zoo-keeper.lua | 1 | 1134 | local points = {}
points[1] = {x=33, y=42}
points[2] = {x=47, y=42}
points[3] = {x=33, y=26}
points[4] = {x=47, y=26}
function distance2(a, b)
local x, y = a.pos.x - b.pos.x, a.pos.y - b.pos.y
return x*x + y*y
end
function findClosest(t)
local d, dmin = nil, 4e4
for i = 1, #es do
local dis = distance2(es[i], t)
if dis < dmin then
d, dmin = es[i], dis
end
end
return d
end
while self.gold < 4 * self:costOf("soldier") do
local i = self:findNearest(self:findItems())
self:move(i.pos)
end
for i = 1, 4 do
self:summon("soldier")
end
loop
es = self:findEnemies()
local friends = self:findFriends()
for j = 1, #friends do
local point = points[j]
local friend = friends[j]
local enemy = findClosest(friend)
if enemy then
if enemy.team == "ogres" and friend:distanceTo(enemy) < 5 then
self:command(friend, "attack", enemy)
else
self:command(friend, "move", point)
end
else
self:command(friend, "move", point)
end
end
end
| mit |
greg-hellings/FrameworkBenchmarks | frameworks/Lua/lapis/web.lua | 72 | 5957 | local lapis = require("lapis")
local db = require("lapis.db")
local Model
do
local _obj_0 = require("lapis.db.model")
Model = _obj_0.Model
end
local config
do
local _obj_0 = require("lapis.config")
config = _obj_0.config
end
local insert
do
local _obj_0 = table
insert = _obj_0.insert
end
local sort
do
local _obj_0 = table
sort = _obj_0.sort
end
local min, random
do
local _obj_0 = math
min, random = _obj_0.min, _obj_0.random
end
local Fortune
do
local _parent_0 = Model
local _base_0 = { }
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, ...)
return _parent_0.__init(self, ...)
end,
__base = _base_0,
__name = "Fortune",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
Fortune = _class_0
end
local World
do
local _parent_0 = Model
local _base_0 = { }
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, ...)
return _parent_0.__init(self, ...)
end,
__base = _base_0,
__name = "World",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
World = _class_0
end
local Benchmark
do
local _parent_0 = lapis.Application
local _base_0 = {
["/"] = function(self)
return {
json = {
message = "Hello, World!"
}
}
end,
["/db"] = function(self)
local w = World:find(random(1, 10000))
return {
json = {
id = w.id,
randomNumber = w.randomnumber
}
}
end,
["/queries"] = function(self)
local num_queries = tonumber(self.params.queries) or 1
if num_queries < 2 then
local w = World:find(random(1, 10000))
return {
json = {
{
id = w.id,
randomNumber = w.randomnumber
}
}
}
end
local worlds = { }
num_queries = min(500, num_queries)
for i = 1, num_queries do
local w = World:find(random(1, 10000))
insert(worlds, {
id = w.id,
randomNumber = w.randomnumber
})
end
return {
json = worlds
}
end,
["/fortunes"] = function(self)
self.fortunes = Fortune:select("")
insert(self.fortunes, {
id = 0,
message = "Additional fortune added at request time."
})
sort(self.fortunes, function(a, b)
return a.message < b.message
end)
return {
layout = false
}, self:html(function()
raw('<!DOCTYPE HTML>')
return html(function()
head(function()
return title("Fortunes")
end)
return body(function()
return element("table", function()
tr(function()
th(function()
return text("id")
end)
return th(function()
return text("message")
end)
end)
local _list_0 = self.fortunes
for _index_0 = 1, #_list_0 do
local fortune = _list_0[_index_0]
tr(function()
td(function()
return text(fortune.id)
end)
return td(function()
return text(fortune.message)
end)
end)
end
end)
end)
end)
end)
end,
["/update"] = function(self)
local num_queries = tonumber(self.params.queries) or 1
if num_queries == 0 then
num_queries = 1
end
local worlds = { }
num_queries = min(500, num_queries)
for i = 1, num_queries do
local wid = random(1, 10000)
local world = World:find(wid)
world.randomnumber = random(1, 10000)
world:update("randomnumber")
insert(worlds, {
id = world.id,
randomNumber = world.randomnumber
})
end
if num_queries < 2 then
return {
json = {
worlds[1]
}
}
end
return {
json = worlds
}
end,
["/plaintext"] = function(self)
return {
content_type = "text/plain",
layout = false
}, "Hello, World!"
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
local _class_0 = setmetatable({
__init = function(self, ...)
return _parent_0.__init(self, ...)
end,
__base = _base_0,
__name = "Benchmark",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
return _parent_0[name]
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
Benchmark = _class_0
return _class_0
end
| bsd-3-clause |
thenumbernine/hydro-cl-lua | hydro/draw/vector_lic.lua | 1 | 5725 | local ffi = require 'ffi'
local class = require 'ext.class'
local file = require 'ext.file'
local gl = require 'ffi.OpenGL'
local GLTex2D = require 'gl.tex2d'
local Draw = require 'hydro.draw.draw'
local DrawVectorLIC = class(Draw)
DrawVectorLIC.integralMaxIter = 10
--[[
the xmin/xmax/ymin/ymax passed as arguments is the one shared with all graphs
but for LIC, we just need the cartesian range
--]]
function DrawVectorLIC:drawSolverWithVar(var, shader, xmin, xmax, ymin, ymax)
local solver = self.solver
local app = solver.app
-- hmm ... this is needed for sub-solvers
local origSolver = var.solver
var.solver = solver
local uniforms = shader.uniforms
solver:calcDisplayVarToTex(var)
local tex = solver:getTex(var)
tex:bind(0)
self.noiseTex:bind(2)
tex:setParameter(gl.GL_TEXTURE_MAG_FILTER, app.displayBilinearTextures and gl.GL_LINEAR or gl.GL_NEAREST)
gl.glBegin(gl.GL_QUADS)
gl.glVertex2d(xmin, ymin)
gl.glVertex2d(xmax, ymin)
gl.glVertex2d(xmax, ymax)
gl.glVertex2d(xmin, ymax)
gl.glEnd()
self.noiseTex:unbind(2)
tex:unbind(0)
var.solver = origSolver
end
function DrawVectorLIC:showDisplayVar(var, varName, ar, xmin, xmax, ymin, ymax)
local solver = self.solver
local app = solver.app
-- TODO allow a fixed, manual colormap range
-- NOTICE with AMR this will only get from the root node
-- which should at least have blitters of the children
local valueMin, valueMax
if var.heatMapFixedRange then
valueMin = var.heatMapValueMin
valueMax = var.heatMapValueMax
else
local component = solver.displayComponentFlatList[var.component]
local vectorField = solver:isVarTypeAVectorField(component.type)
if vectorField then
-- calc range of magnitude of vector variable
valueMin, valueMax = solver:calcDisplayVarRange(var, component.magn)
else
valueMin, valueMax = solver:calcDisplayVarRange(var)
end
var.heatMapValueMin = valueMin
var.heatMapValueMax = valueMax
end
if not self.noiseTex then
local noiseVol = app.drawVectorLICNoiseSize * app.drawVectorLICNoiseSize * 4
local noiseData = ffi.new('float[?]', noiseVol)
for i=0,noiseVol-1 do
noiseData[i] = math.random()
end
self.noiseTex = GLTex2D{
internalFormat = gl.GL_RGBA32F,
width = app.drawVectorLICNoiseSize,
height = app.drawVectorLICNoiseSize,
format = gl.GL_RGBA,
type = gl.GL_FLOAT,
data = noiseData,
minFilter = gl.GL_NEAREST,
magFilter = gl.GL_LINEAR,
wrap = {
s = gl.GL_REPEAT,
t = gl.GL_REPEAT,
},
}
end
local shader = solver.vectorLICShader
shader:use()
app.gradientTex:bind(1)
self:setupDisplayVarShader(shader, var, valueMin, valueMax)
if shader.uniforms.integralMaxIter then
gl.glUniform1i(shader.uniforms.integralMaxIter.loc, self.integralMaxIter)
end
gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
gl.glEnable(gl.GL_BLEND)
self:drawSolverWithVar(var, shader, xmin, xmax, ymin, ymax)
-- [[
if solver.amr then
local tmp = self.solver
for k,subsolver in pairs(solver.amr.child) do
self.solver = subsolver
self:drawSolverWithVar(var, shader, xmin, xmax, ymin, ymax)
end
self.solver = tmp
end
--]]
gl.glDisable(gl.GL_BLEND)
app.gradientTex:unbind(1)
gl.glActiveTexture(gl.GL_TEXTURE0)
shader:useNone()
-- gl.glDisable(gl.GL_DEPTH_TEST)
-- TODO only draw the first
app:drawGradientLegend(solver, var, varName, ar, valueMin, valueMax)
-- gl.glEnable(gl.GL_DEPTH_TEST)
end
function DrawVectorLIC:display(varName, ar, graph_xmin, graph_xmax, graph_ymin, graph_ymax)
local solver = self.solver
local app = solver.app
app.view:setup(ar)
local xmin, xmax, ymin, ymax
if app.view.getOrthoBounds then
xmin, xmax, ymin, ymax = app.view:getOrthoBounds(ar)
else
xmin = solver.cartesianMin.x
ymin = solver.cartesianMin.y
xmax = solver.cartesianMax.x
ymax = solver.cartesianMax.y
end
-- gl.glEnable(gl.GL_DEPTH_TEST)
local gridz = 0 --.1
gl.glColor3f(.1, .1, .1)
local xrange = xmax - xmin
local xstep = 10^math.floor(math.log(xrange, 10) - .5)
local xticmin = math.floor(xmin/xstep)
local xticmax = math.ceil(xmax/xstep)
gl.glBegin(gl.GL_LINES)
for x=xticmin,xticmax do
gl.glVertex3f(x*xstep,ymin, gridz)
gl.glVertex3f(x*xstep,ymax, gridz)
end
gl.glEnd()
local yrange = ymax - ymin
local ystep = 10^math.floor(math.log(yrange, 10) - .5)
local yticmin = math.floor(ymin/ystep)
local yticmax = math.ceil(ymax/ystep)
gl.glBegin(gl.GL_LINES)
for y=yticmin,yticmax do
gl.glVertex3f(xmin,y*ystep, gridz)
gl.glVertex3f(xmax,y*ystep, gridz)
end
gl.glEnd()
gl.glColor3f(.5, .5, .5)
gl.glBegin(gl.GL_LINES)
gl.glVertex3f(xmin, 0, gridz)
gl.glVertex3f(xmax, 0, gridz)
gl.glVertex3f(0, ymin, gridz)
gl.glVertex3f(0, ymax, gridz)
gl.glEnd()
-- NOTICE overlays of multiple solvers won't be helpful. It'll just draw over the last solver.
-- I've got to rethink the visualization
if not require 'hydro.solver.meshsolver':isa(solver) then
local var = solver.displayVarForName[varName]
if var and var.enabled then
self:prepareShader()
self:showDisplayVar(var, varName, ar, xmin, xmax, ymin, ymax)
end
end
-- gl.glDisable(gl.GL_DEPTH_TEST)
end
function DrawVectorLIC:prepareShader()
local solver = self.solver
if solver.vectorLICShader then return end
local vectorLICCode = assert(file'hydro/draw/vector_lic.shader':read())
solver.vectorLICShader = solver.GLProgram{
name = 'vector_lic',
vertexCode = solver.eqn:template(vectorLICCode, {
draw = self,
vertexShader = true,
}),
fragmentCode = solver.eqn:template(vectorLICCode, {
draw = self,
fragmentShader = true,
}),
uniforms = {
valueMin = 0,
valueMax = 0,
tex = 0,
gradientTex = 1,
noiseTex = 2,
},
}
end
return DrawVectorLIC
| mit |
shkan/telebot7 | plugins/img_google.lua | 660 | 3196 | do
local mime = require("mime")
local google_config = load_from_file('data/google.lua')
local cache = {}
--[[
local function send_request(url)
local t = {}
local options = {
url = url,
sink = ltn12.sink.table(t),
method = "GET"
}
local a, code, headers, status = http.request(options)
return table.concat(t), code, headers, status
end]]--
local function get_google_data(text)
local url = "http://ajax.googleapis.com/ajax/services/search/images?"
url = url.."v=1.0&rsz=5"
url = url.."&q="..URL.escape(text)
url = url.."&imgsz=small|medium|large"
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local res, code = http.request(url)
if code ~= 200 then
print("HTTP Error code:", code)
return nil
end
local google = json:decode(res)
return google
end
-- Returns only the useful google data to save on cache
local function simple_google_table(google)
local new_table = {}
new_table.responseData = {}
new_table.responseDetails = google.responseDetails
new_table.responseStatus = google.responseStatus
new_table.responseData.results = {}
local results = google.responseData.results
for k,result in pairs(results) do
new_table.responseData.results[k] = {}
new_table.responseData.results[k].unescapedUrl = result.unescapedUrl
new_table.responseData.results[k].url = result.url
end
return new_table
end
local function save_to_cache(query, data)
-- Saves result on cache
if string.len(query) <= 7 then
local text_b64 = mime.b64(query)
if not cache[text_b64] then
local simple_google = simple_google_table(data)
cache[text_b64] = simple_google
end
end
end
local function process_google_data(google, receiver, query)
if google.responseStatus == 403 then
local text = 'ERROR: Reached maximum searches per day'
send_msg(receiver, text, ok_cb, false)
elseif google.responseStatus == 200 then
local data = google.responseData
if not data or not data.results or #data.results == 0 then
local text = 'Image not found.'
send_msg(receiver, text, ok_cb, false)
return false
end
-- Random image from table
local i = math.random(#data.results)
local url = data.results[i].unescapedUrl or data.results[i].url
local old_timeout = http.TIMEOUT or 10
http.TIMEOUT = 5
send_photo_from_url(receiver, url)
http.TIMEOUT = old_timeout
save_to_cache(query, google)
else
local text = 'ERROR!'
send_msg(receiver, text, ok_cb, false)
end
end
function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local text_b64 = mime.b64(text)
local cached = cache[text_b64]
if cached then
process_google_data(cached, receiver, text)
else
local data = get_google_data(text)
process_google_data(data, receiver, text)
end
end
return {
description = "Search image with Google API and sends it.",
usage = "!img [term]: Random search an image with Google API.",
patterns = {
"^!img (.*)$"
},
run = run
}
end
| gpl-2.0 |
TH3GENERAL/GENERAL | DevTSHAKE/utils.lua | 74 | 30284 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = (loadfile "./libs/serpent.lua")()
feedparser = (loadfile "./libs/feedparser.lua")()
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
if msg.to.type == 'channel' then
return 'channel#id'..msg.to.id
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "data/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
if not text or type(text) == 'boolean' then
return
end
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
function post_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
post_large_msg_callback(cb_extra, true)
end
function post_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
post_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
post_msg(destination, my_text, post_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
-- Workarrond to format the message as previously was received
function backward_msg_format (msg)
for k,name in pairs({'from', 'to'}) do
local longid = msg[name].id
msg[name].id = msg[name].peer_id
msg[name].peer_id = longid
msg[name].type = msg[name].peer_type
end
if msg.action and (msg.action.user or msg.action.link_issuer) then
local user = msg.action.user or msg.action.link_issuer
local longid = user.id
user.id = user.peer_id
user.peer_id = longid
user.type = user.peer_type
end
return msg
end
--Table Sort
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
--End Table Sort
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(chat)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local data = load_data(_config.moderation.data)
local groups = 'groups'
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(chat)] then
if msg.to.type == 'chat' then
var = true
end
end
return var
end
end
function is_super_group(msg)
local var = false
local data = load_data(_config.moderation.data)
local groups = 'groups'
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(chat)] then
if msg.to.type == 'channel' then
var = true
end
return var
end
end
end
function is_log_group(msg)
local var = false
local data = load_data(_config.moderation.data)
local GBan_log = 'GBan_log'
if data[tostring(GBan_log)] then
if data[tostring(GBan_log)][tostring(msg.to.id)] then
if msg.to.type == 'channel' then
var = true
end
return var
end
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin1(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
local hash = 'support'
local support = redis:sismember(hash, user_id)
if support then
var = true
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user_any(user_id, chat_id)
local channel = 'channel#id'..chat_id
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
channel_kick(channel, user, ok_cb, false)
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
local channel = 'channel#id'..chat_id
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, false)
channel_kick(channel, user, ok_cb, false)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list for: [ID: "..chat_id.." ]:\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
local print_name = string.gsub(user_info.print_name, "_", " ")
local print_name = string.gsub(print_name, "", "")
text = text..k.." - "..print_name.." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "Global bans!\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
local print_name = string.gsub(user_info.print_name, "_", " ")
local print_name = string.gsub(print_name, "", "")
text = text..k.." - "..print_name.." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- Support Team
function support_add(support_id)
-- Save to redis
local hash = 'support'
redis:sadd(hash, support_id)
end
function is_support(support_id)
--Save on redis
local hash = 'support'
local support = redis:sismember(hash, support_id)
return support or false
end
function support_remove(support_id)
--Save on redis
local hash = 'support'
redis:srem(hash, support_id)
end
-- Whitelist
function is_whitelisted(user_id)
--Save on redis
local hash = 'whitelist'
local is_whitelisted = redis:sismember(hash, user_id)
return is_whitelisted or false
end
--Begin Chat Mutes
function set_mutes(chat_id)
mutes = {[1]= "Audio: no",[2]= "Photo: no",[3]= "All: no",[4]="Documents: no",[5]="Text: no",[6]= "Video: no",[7]= "Gifs: no"}
local hash = 'mute:'..chat_id
for k,v in pairsByKeys(mutes) do
setting = v
redis:sadd(hash, setting)
end
end
function has_mutes(chat_id)
mutes = {[1]= "Audio: no",[2]= "Photo: no",[3]= "All: no",[4]="Documents: no",[5]="Text: no",[6]= "Video: no",[7]= "Gifs: no"}
local hash = 'mute:'..chat_id
for k,v in pairsByKeys(mutes) do
setting = v
local has_mutes = redis:sismember(hash, setting)
return has_mutes or false
end
end
function rem_mutes(chat_id)
local hash = 'mute:'..chat_id
redis:del(hash)
end
function mute(chat_id, msg_type)
local hash = 'mute:'..chat_id
local yes = "yes"
local no = 'no'
local old_setting = msg_type..': '..no
local setting = msg_type..': '..yes
redis:srem(hash, old_setting)
redis:sadd(hash, setting)
end
function is_muted(chat_id, msg_type)
local hash = 'mute:'..chat_id
local setting = msg_type
local muted = redis:sismember(hash, setting)
return muted or false
end
function unmute(chat_id, msg_type)
--Save on redis
local hash = 'mute:'..chat_id
local yes = 'yes'
local no = 'no'
local old_setting = msg_type..': '..yes
local setting = msg_type..': '..no
redis:srem(hash, old_setting)
redis:sadd(hash, setting)
end
function mute_user(chat_id, user_id)
local hash = 'mute_user:'..chat_id
redis:sadd(hash, user_id)
end
function is_muted_user(chat_id, user_id)
local hash = 'mute_user:'..chat_id
local muted = redis:sismember(hash, user_id)
return muted or false
end
function unmute_user(chat_id, user_id)
--Save on redis
local hash = 'mute_user:'..chat_id
redis:srem(hash, user_id)
end
-- Returns chat_id mute list
function mutes_list(chat_id)
local hash = 'mute:'..chat_id
local list = redis:smembers(hash)
local text = "Mutes for: [ID: "..chat_id.." ]:\n\n"
for k,v in pairsByKeys(list) do
text = text.."Mute "..v.."\n"
end
return text
end
-- Returns chat_user mute list
function muted_user_list(chat_id)
local hash = 'mute_user:'..chat_id
local list = redis:smembers(hash)
local text = "Muted Users for: [ID: "..chat_id.." ]:\n\n"
for k,v in pairsByKeys(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
local print_name = string.gsub(user_info.print_name, "_", " ")
local print_name = string.gsub(print_name, "", "")
text = text..k.." - "..print_name.." ["..v.."]\n"
else
text = text..k.." - [ "..v.." ]\n"
end
end
return text
end
--End Chat Mutes
-- /id by reply
function get_message_callback_id(extra, success, result)
if type(result) == 'boolean' then
print('Old message :(')
return false
end
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.peer_id
send_large_msg(chat, result.from.peer_id)
else
return
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if type(result) == 'boolean' then
print('Old message :(')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_momod2(result.from.peer_id, result.to.peer_id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.peer_id, ok_cb, false)
channel_kick(channel, 'user#id'..result.from.peer_id, ok_cb, false)
else
return
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if type(result) == 'boolean' then
print('Old message :(')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.peer_id, ok_cb, false)
channel_kick(channel, 'user#id'..result.from.peer_id, ok_cb, false)
else
return
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if type(result) == 'boolean' then
print('Old message :(')
return false
end
if result.to.type == 'chat' or result.to.type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_momod2(result.from.peer_id, result.to.peer_id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.peer_id, result.to.peer_id)
send_large_msg(chat, "User "..result.from.peer_id.." Banned")
else
return
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if type(result) == 'boolean' then
print('Old message :(')
return false
end
if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then
local chat = 'chat#id'..result.to.peer_id
local channel = 'channel#id'..result.to.peer_id
if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(result.from.peer_id) then -- Ignore admins
return
end
ban_user(result.from.peer_id, result.to.peer_id)
send_large_msg(chat, "User "..result.from.peer_id.." Banned")
send_large_msg(channel, "User "..result.from.peer_id.." Banned")
else
return
end
end
| gpl-2.0 |
hafez16/senator | plugins/domaintools.lua | 359 | 1494 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function check(name)
local api = "https://domainsearch.p.mashape.com/index.php?"
local param = "name="..name
local url = api..param
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "application/json"
}
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return code end
local body = table.concat(respbody)
local body = json:decode(body)
--vardump(body)
local domains = "List of domains for '"..name.."':\n"
for k,v in pairs(body) do
print(k)
local status = " ❌ "
if v == "Available" then
status = " ✔ "
end
domains = domains..k..status.."\n"
end
return domains
end
local function run(msg, matches)
if matches[1] == "check" then
local name = matches[2]
return check(name)
end
end
return {
description = "Domain tools",
usage = {"!domain check [domain] : Check domain name availability.",
},
patterns = {
"^!domain (check) (.*)$",
},
run = run
}
| gpl-2.0 |
omid1212/hgbok | plugins/domaintools.lua | 359 | 1494 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function check(name)
local api = "https://domainsearch.p.mashape.com/index.php?"
local param = "name="..name
local url = api..param
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "application/json"
}
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return code end
local body = table.concat(respbody)
local body = json:decode(body)
--vardump(body)
local domains = "List of domains for '"..name.."':\n"
for k,v in pairs(body) do
print(k)
local status = " ❌ "
if v == "Available" then
status = " ✔ "
end
domains = domains..k..status.."\n"
end
return domains
end
local function run(msg, matches)
if matches[1] == "check" then
local name = matches[2]
return check(name)
end
end
return {
description = "Domain tools",
usage = {"!domain check [domain] : Check domain name availability.",
},
patterns = {
"^!domain (check) (.*)$",
},
run = run
}
| gpl-2.0 |
mirbot/zdgbbbrblsb-vbv | plugins/webshot.lua | 919 | 1473 | local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Send an screenshot of a website.",
usage = {
"!webshot [url]: Take an screenshot of the web and send it back to you."
},
patterns = {
"^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
| gpl-2.0 |
mms92/wire | lua/entities/gmod_wire_expression2/core/angle.lua | 10 | 10065 | /******************************************************************************\
Angle support
\******************************************************************************/
// wow... this is basically just vector-support, but renamed angle-support :P
// pitch, yaw, roll
registerType("angle", "a", { 0, 0, 0 },
function(self, input) return { input.p, input.y, input.r } end,
function(self, output) return Angle(output[1], output[2], output[3]) end,
function(retval)
if !istable(retval) then error("Return value is not a table, but a "..type(retval).."!",0) end
if #retval ~= 3 then error("Return value does not have exactly 3 entries!",0) end
end,
function(v)
return !istable(v) or #v ~= 3
end
)
local pi = math.pi
local floor, ceil = math.floor, math.ceil
/******************************************************************************/
__e2setcost(1) -- approximated
e2function angle ang()
return { 0, 0, 0 }
end
__e2setcost(2)
e2function angle ang(rv1)
return { rv1, rv1, rv1 }
end
e2function angle ang(rv1, rv2, rv3)
return { rv1, rv2, rv3 }
end
// Convert Vector -> Angle
e2function angle ang(vector rv1)
return {rv1[1],rv1[2],rv1[3]}
end
/******************************************************************************/
registerOperator("ass", "a", "a", function(self, args)
local op1, op2, scope = args[2], args[3], args[4]
local rv2 = op2[1](self, op2)
self.Scopes[scope][op1] = rv2
self.Scopes[scope].vclk[op1] = true
return rv2
end)
/******************************************************************************/
e2function number operator_is(angle rv1)
if rv1[1] != 0 || rv1[2] != 0 || rv1[3] != 0
then return 1 else return 0 end
end
__e2setcost(3)
e2function number operator==(angle rv1, angle rv2)
if rv1[1] - rv2[1] <= delta && rv2[1] - rv1[1] <= delta &&
rv1[2] - rv2[2] <= delta && rv2[2] - rv1[2] <= delta &&
rv1[3] - rv2[3] <= delta && rv2[3] - rv1[3] <= delta
then return 1 else return 0 end
end
e2function number operator!=(angle rv1, angle rv2)
if rv1[1] - rv2[1] > delta || rv2[1] - rv1[1] > delta ||
rv1[2] - rv2[2] > delta || rv2[2] - rv1[2] > delta ||
rv1[3] - rv2[3] > delta || rv2[3] - rv1[3] > delta
then return 1 else return 0 end
end
e2function number operator>=(angle rv1, angle rv2)
if rv2[1] - rv1[1] <= delta &&
rv2[2] - rv1[2] <= delta &&
rv2[3] - rv1[3] <= delta
then return 1 else return 0 end
end
e2function number operator<=(angle rv1, angle rv2)
if rv1[1] - rv2[1] <= delta &&
rv1[2] - rv2[2] <= delta &&
rv1[3] - rv2[3] <= delta
then return 1 else return 0 end
end
e2function number operator>(angle rv1, angle rv2)
if rv1[1] - rv2[1] > delta &&
rv1[2] - rv2[2] > delta &&
rv1[3] - rv2[3] > delta
then return 1 else return 0 end
end
e2function number operator<(angle rv1, angle rv2)
if rv2[1] - rv1[1] > delta &&
rv2[2] - rv1[2] > delta &&
rv2[3] - rv1[3] > delta
then return 1 else return 0 end
end
/******************************************************************************/
registerOperator("dlt", "a", "a", function(self, args)
local op1, scope = args[2], args[3]
local rv1, rv2 = self.Scopes[scope][op1], self.Scopes[scope]["$" .. op1]
return { rv1[1] - rv2[1], rv1[2] - rv2[2], rv1[3] - rv2[3] }
end)
__e2setcost(2)
e2function angle operator_neg(angle rv1)
return { -rv1[1], -rv1[2], -rv1[3] }
end
e2function angle operator+(rv1, angle rv2)
return { rv1 + rv2[1], rv1 + rv2[2], rv1 + rv2[3] }
end
e2function angle operator+(angle rv1, rv2)
return { rv1[1] + rv2, rv1[2] + rv2, rv1[3] + rv2 }
end
e2function angle operator+(angle rv1, angle rv2)
return { rv1[1] + rv2[1], rv1[2] + rv2[2], rv1[3] + rv2[3] }
end
e2function angle operator-(rv1, angle rv2)
return { rv1 - rv2[1], rv1 - rv2[2], rv1 - rv2[3] }
end
e2function angle operator-(angle rv1, rv2)
return { rv1[1] - rv2, rv1[2] - rv2, rv1[3] - rv2 }
end
e2function angle operator-(angle rv1, angle rv2)
return { rv1[1] - rv2[1], rv1[2] - rv2[2], rv1[3] - rv2[3] }
end
e2function angle operator*(angle rv1, angle rv2)
return { rv1[1] * rv2[1], rv1[2] * rv2[2], rv1[3] * rv2[3] }
end
e2function angle operator*(rv1, angle rv2)
return { rv1 * rv2[1], rv1 * rv2[2], rv1 * rv2[3] }
end
e2function angle operator*(angle rv1, rv2)
return { rv1[1] * rv2, rv1[2] * rv2, rv1[3] * rv2 }
end
e2function angle operator/(rv1, angle rv2)
return { rv1 / rv2[1], rv1 / rv2[2], rv1 / rv2[3] }
end
e2function angle operator/(angle rv1, rv2)
return { rv1[1] / rv2, rv1[2] / rv2, rv1[3] / rv2 }
end
e2function angle operator/(angle rv1, angle rv2)
return { rv1[1] / rv2[1], rv1[2] / rv2[2], rv1[3] / rv2[3] }
end
e2function number angle:operator[](index)
return this[floor(math.Clamp(index, 1, 3) + 0.5)]
end
e2function number angle:operator[](index, value)
this[floor(math.Clamp(index, 1, 3) + 0.5)] = value
return value
end
/******************************************************************************/
__e2setcost(5)
e2function angle angnorm(angle rv1)
return {(rv1[1] + 180) % 360 - 180,(rv1[2] + 180) % 360 - 180,(rv1[3] + 180) % 360 - 180}
end
e2function number angnorm(rv1)
return (rv1 + 180) % 360 - 180
end
__e2setcost(1)
e2function number angle:pitch()
return this[1]
end
e2function number angle:yaw()
return this[2]
end
e2function number angle:roll()
return this[3]
end
__e2setcost(2)
// SET methods that returns angles
e2function angle angle:setPitch(rv2)
return { rv2, this[2], this[3] }
end
e2function angle angle:setYaw(rv2)
return { this[1], rv2, this[3] }
end
e2function angle angle:setRoll(rv2)
return { this[1], this[2], rv2 }
end
/******************************************************************************/
__e2setcost(5)
e2function angle round(angle rv1)
return {
floor(rv1[1] + 0.5),
floor(rv1[2] + 0.5),
floor(rv1[3] + 0.5)
}
end
e2function angle round(angle rv1, decimals)
local shf = 10 ^ decimals
return {
floor(rv1[1] * shf + 0.5) / shf,
floor(rv1[2] * shf + 0.5) / shf,
floor(rv1[3] * shf + 0.5) / shf
}
end
e2function angle ceil(angle rv1)
return {
ceil(rv1[1]),
ceil(rv1[2]),
ceil(rv1[3])
}
end
e2function angle ceil(angle rv1, decimals)
local shf = 10 ^ decimals
return {
ceil(rv1[1] * shf) / shf,
ceil(rv1[2] * shf) / shf,
ceil(rv1[3] * shf) / shf
}
end
e2function angle floor(angle rv1)
return {
floor(rv1[1]),
floor(rv1[2]),
floor(rv1[3])
}
end
e2function angle floor(angle rv1, decimals)
local shf = 10 ^ decimals
return {
floor(rv1[1] * shf) / shf,
floor(rv1[2] * shf) / shf,
floor(rv1[3] * shf) / shf
}
end
// Performs modulo on p,y,r separately
e2function angle mod(angle rv1, rv2)
local p,y,r
if rv1[1] >= 0 then
p = rv1[1] % rv2
else p = rv1[1] % -rv2 end
if rv1[2] >= 0 then
y = rv1[2] % rv2
else y = rv1[2] % -rv2 end
if rv1[3] >= 0 then
r = rv1[3] % rv2
else r = rv1[3] % -rv2 end
return {p, y, r}
end
// Modulo where divisors are defined as an angle
e2function angle mod(angle rv1, angle rv2)
local p,y,r
if rv1[1] >= 0 then
p = rv1[1] % rv2[1]
else p = rv1[1] % -rv2[1] end
if rv1[2] >= 0 then
y = rv1[2] % rv2[2]
else y = rv1[2] % -rv2[2] end
if rv1[3] >= 0 then
y = rv1[3] % rv2[3]
else y = rv1[3] % -rv2[3] end
return {p, y, r}
end
// Clamp each p,y,r separately
e2function angle clamp(angle rv1, rv2, rv3)
local p,y,r
if rv1[1] < rv2 then p = rv2
elseif rv1[1] > rv3 then p = rv3
else p = rv1[1] end
if rv1[2] < rv2 then y = rv2
elseif rv1[2] > rv3 then y = rv3
else y = rv1[2] end
if rv1[3] < rv2 then r = rv2
elseif rv1[3] > rv3 then r = rv3
else r = rv1[3] end
return {p, y, r}
end
// Clamp according to limits defined by two min/max angles
e2function angle clamp(angle rv1, angle rv2, angle rv3)
local p,y,r
if rv1[1] < rv2[1] then p = rv2[1]
elseif rv1[1] > rv3[1] then p = rv3[1]
else p = rv1[1] end
if rv1[2] < rv2[2] then y = rv2[2]
elseif rv1[2] > rv3[2] then y = rv3[2]
else y = rv1[2] end
if rv1[3] < rv2[3] then r = rv2[3]
elseif rv1[3] > rv3[3] then r = rv3[3]
else r = rv1[3] end
return {p, y, r}
end
// Mix two angles by a given proportion (between 0 and 1)
e2function angle mix(angle rv1, angle rv2, rv3)
local p = rv1[1] * rv3 + rv2[1] * (1-rv3)
local y = rv1[2] * rv3 + rv2[2] * (1-rv3)
local r = rv1[3] * rv3 + rv2[3] * (1-rv3)
return {p, y, r}
end
__e2setcost(2)
// Circular shift function: shiftr( p,y,r ) = ( r,p,y )
e2function angle shiftR(angle rv1)
return {rv1[3], rv1[1], rv1[2]}
end
e2function angle shiftL(angle rv1)
return {rv1[2], rv1[3], rv1[1]}
end
__e2setcost(5)
// Returns 1 if the angle lies between (or is equal to) the min/max angles
e2function normal inrange(angle rv1, angle rv2, angle rv3)
if rv1[1] < rv2[1] then return 0 end
if rv1[2] < rv2[2] then return 0 end
if rv1[3] < rv2[3] then return 0 end
if rv1[1] > rv3[1] then return 0 end
if rv1[2] > rv3[2] then return 0 end
if rv1[3] > rv3[3] then return 0 end
return 1
end
// Rotate an angle around a vector by the given number of degrees
e2function angle angle:rotateAroundAxis(vector axis, degrees)
local ang = Angle(this[1], this[2], this[3])
local vec = Vector(axis[1], axis[2], axis[3]):GetNormal()
ang:RotateAroundAxis(vec, degrees)
return {ang.p, ang.y, ang.r}
end
// Convert the magnitude of the angle to radians
e2function angle toRad(angle rv1)
return {rv1[1] * pi / 180, rv1[2] * pi / 180, rv1[3] * pi / 180}
end
// Convert the magnitude of the angle to degrees
e2function angle toDeg(angle rv1)
return {rv1[1] * 180 / pi, rv1[2] * 180 / pi, rv1[3] * 180 / pi}
end
/******************************************************************************/
e2function vector angle:forward()
return Angle(this[1], this[2], this[3]):Forward()
end
e2function vector angle:right()
return Angle(this[1], this[2], this[3]):Right()
end
e2function vector angle:up()
return Angle(this[1], this[2], this[3]):Up()
end
e2function string toString(angle a)
return ("[%s,%s,%s]"):format(a[1],a[2],a[3])
end
e2function string angle:toString() = e2function string toString(angle a)
| apache-2.0 |
mirbot/zdgbbbrblsb-vbv | plugins/time.lua | 771 | 2865 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'It seems that in "'..area..'" they do not have a concept of time.'
end
local localTime, timeZoneId = get_time(lat,lng)
return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Displays the local time in an area",
usage = "!time [area]: Displays the local time in that area",
patterns = {"^!time (.*)$"},
run = run
}
| gpl-2.0 |
vipteam1/VIPTEAM | plugins/lock_emoji.lua | 1 | 2756 | --[[
▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Team name : ( 🌐 VIP_TEAM 🌐 )▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ File name : ( #اسم الملف هنا ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄ ▄▀ Guenat team: ( @VIP_TEAM1 ) ▀▄ ▄▀
▀▄ ▄▀ ▀▄ ▄▀
▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄
—]]
local function run(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['emoji'] == 'yes' then
if not is_momod(msg) then
delete_msg(msg.id, ok_cb, true)
end
end
end
return {patterns = {
"😞(.+)",
"😞",
"😐(.+)",
"😐",
"🙁(.+)",
"🙁",
"🌝(.+)",
"🌝",
"🤖(.+)",
"🤖",
"😲(.+)",
"😲",
"💋(.+)",
"💋",
"🙄(.+)",
"🙄",
"🤗(.+)",
"🤗",
"😱(.+)",
"😱",
"🤐(.+)",
"🤐",
"💩(.+)",
"💩",
"🌹(.+)",
"🌹",
"🖐(.+)",
"🖐",
"❤️(.+)",
"❤️",
"💗(.+)",
"💗",
"🤔(.+)",
"🤔",
"😖(.+)",
"😖",
"☹️(.+)",
"☹️",
"😔(.+)",
"😔",
"👾(.+)",
"👾",
"🚀(.+)",
"🚀",
"🌎🌍(.+)",
"🌍",
"🍦",
"😸(.+)",
"😺",
"😯(.+)",
"😯",
"🤒(.+)",
"🤒",
"😷(.+)",
"😷",
"🙀(.+)",
"🙀",
"🎪(.+)",
"🌚",
"🌚(.+)",
"😂",
"😂(.+)",
"😳",
"😳(.+)",
"😛",
"😛(.+)",
"😢",
"😢(.+)",
"😓",
"😓(.+)",
"😾",
"😾(.+)",
"👊🏻",
"👊🏻(.+)",
"✊🏻",
"✊🏻(.+)",
"👿",
"👿(.+)",
"👅",
"👅(.+)",
"🖕🏿",
"🖕🏿(.+)",
"😲",
"😲(.+)",
"👹",
"👹(.+)",
"😴",
"😴(.+)",
"☂",
"☂(.+)",
"🗣",
"🗣(.+)",
"⛄️",
"⛄️(.+)",
"😻",
"😻(.+)",
"😀(.+)",
"😀",
"😬(.+)",
"😬",
"😁(.+)",
"😁",
"😂(.+)",
"😂",
"😃(.+)",
"😃",
"😄(.+)",
"😄",
"😅",
"😆(.+)",
"😆",
"😇(.+)",
"😇",
"😉(.+)",
"😉",
"😊(.+)",
"😊",
"🙂(.+)",
"🙂",
"🙃(.+)",
"🙃",
"☺️(.+)",
"☺️",
"😋(.+)",
"😋",
"😌",
"😍(.+)",
"😍",
"😘(.+)",
"😘",
"😗(.+)",
"😗",
"😙(.+)",
"😙",
"😚(.+)",
"😚",
"😜(.+)",
"😜",
"😝(.+)",
"😝",
"🤑(.+)",
"🤑",
"🤓(.+)",
"🤓",
"😎(.+)",
"😎",
"🤗(.+)",
"🤗",
"😏(.+)",
"😏",
"😶(.+)",
"😶",
"😺(.+)",
"😺",
"😹",
"😼",
"😿",
"🌝",
"🌚",
"🌶",
"🖐🏼",
},run = run}
| gpl-2.0 |
sami2448/sam | plugins/wiki.lua | 2 | 4097 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
| gpl-2.0 |
RobertoMalatesta/ProDBG | tundra.lua | 1 | 4753 |
-----------------------------------------------------------------------------------------------------------------------
local mac_opts = {
"-Wall",
"-I.", "-DPRODBG_MAC",
"-Weverything", "-Werror",
"-Wno-unknown-warning-option",
"-Wno-c11-extensions",
"-Wno-variadic-macros",
"-Wno-c++98-compat-pedantic",
"-Wno-old-style-cast",
"-Wno-documentation",
"-Wno-reserved-id-macro",
"-Wno-missing-prototypes",
"-Wno-deprecated-declarations",
"-Wno-cast-qual",
"-Wno-gnu-anonymous-struct",
"-Wno-nested-anon-types",
"-Wno-padded",
"-Wno-c99-extensions",
"-Wno-missing-field-initializers",
"-Wno-weak-vtables",
"-Wno-format-nonliteral",
"-Wno-non-virtual-dtor",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local macosx = {
Env = {
CCOPTS = {
mac_opts,
},
CXXOPTS = {
mac_opts,
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++" },
PROGCOM = { "-lstdc++" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
local macosx_wx = {
Env = {
CCOPTS = {
mac_opts,
"-PRODBG_WX",
},
CXXOPTS = {
mac_opts,
"-PRODBG_WX",
},
},
Frameworks = { "Cocoa" },
}
local macosx_test = {
Env = {
CCOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
},
CXXOPTS = {
mac_opts,
"-Wno-everything",
"-coverage",
"-std=c++11",
},
SHLIBOPTS = { "-lstdc++", "-coverage" },
PROGCOM = { "-lstdc++", "-coverage" },
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
Frameworks = { "Cocoa" },
}
-----------------------------------------------------------------------------------------------------------------------
local gcc_opts = {
"-I.",
"-Wno-array-bounds", "-Wno-attributes", "-Wno-unused-value",
"-DOBJECT_DIR=\\\"$(OBJECTDIR)\\\"",
"-Wall", "-DPRODBG_UNIX",
"-fPIC",
{ "-O0", "-g"; Config = "*-*-debug" },
{ "-O3", "-g"; Config = "*-*-release" },
}
local gcc_env = {
Env = {
CCOPTS = {
gcc_opts,
},
CXXOPTS = {
gcc_opts,
"-std=c++11",
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
},
ReplaceEnv = {
PROGCOM = "$(LD) $(PROGOPTS) $(LIBPATH:p-L) -o $(@) -Wl,--start-group $(LIBS:p-l) $(<) -Wl,--end-group"
},
}
-----------------------------------------------------------------------------------------------------------------------
local win64_opts = {
"/DPRODBG_WIN",
"/EHsc", "/FS", "/MT", "/W3", "/I.", "/WX", "/DUNICODE", "/D_UNICODE", "/DWIN32", "/D_CRT_SECURE_NO_WARNINGS", "/wd4200", "/wd4152", "/wd4996", "/wd4389", "/wd4201", "/wd4152", "/wd4996", "/wd4389",
"\"/DOBJECT_DIR=$(OBJECTDIR:#)\"",
{ "/Od"; Config = "*-*-debug" },
{ "/O2"; Config = "*-*-release" },
}
local win64 = {
Env = {
GENERATE_PDB = "1",
CCOPTS = {
win64_opts,
},
CXXOPTS = {
win64_opts,
},
BGFX_SHADERC = "$(OBJECTDIR)$(SEP)bgfx_shaderc$(PROGSUFFIX)",
OBJCCOM = "meh",
},
}
-----------------------------------------------------------------------------------------------------------------------
Build {
Passes = {
BuildTools = { Name="Build Tools", BuildOrder = 1 },
GenerateSources = { Name="Generate sources", BuildOrder = 2 },
},
Units = {
"units.tools.lua",
"units.libs.lua",
"units.misc.lua",
"units.plugins.lua",
"units.prodbg.lua",
"units.tests.lua",
},
Configs = {
Config { Name = "macosx-clang", DefaultOnHost = "macosx", Inherit = macosx, Tools = { "clang-osx" } },
Config { Name = "macosx_test-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "macosx_wx-clang", SupportedHosts = { "macosx" }, Inherit = macosx_test, Tools = { "clang-osx" } },
Config { Name = "win64-msvc", DefaultOnHost = { "windows" }, Inherit = win64, Tools = { { "msvc" }, "generic-asm" } },
Config { Name = "linux-gcc", DefaultOnHost = { "linux" }, Inherit = gcc_env, Tools = { "gcc" } },
},
IdeGenerationHints = {
Msvc = {
-- Remap config names to MSVC platform names (affects things like header scanning & debugging)
PlatformMappings = {
['win64-msvc'] = 'x64',
},
-- Remap variant names to MSVC friendly names
VariantMappings = {
['release'] = 'Release',
['debug'] = 'Debug',
},
},
MsvcSolutions = {
['ProDBG.sln'] = { } -- will get everything
},
},
}
| mit |
mms92/wire | lua/entities/gmod_wire_fx_emitter.lua | 10 | 3723 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire FX Emitter"
ENT.WireDebugName = "FX Emitter"
function ENT:SetupDataTables()
self:NetworkVar( "Bool", 0, "On" )
self:NetworkVar( "Int", 0, "Effect" )
self:NetworkVar( "Float", 0, "Delay" )
self:NetworkVar( "Vector", 0, "FXDir" )
end
function ENT:GetFXPos()
return self:GetPos()
end
-- Effect registration
ENT.Effects = {}
ENT.fxcount = 0
local fx_emitter = ENT
ComboBox_Wire_FX_Emitter_Options = {}
function AddFXEmitterEffect(name, func, nicename)
fx_emitter.fxcount = fx_emitter.fxcount+1
// Maintain a global reference for these effects
ComboBox_Wire_FX_Emitter_Options[name] = fx_emitter.fxcount
if CLIENT then
fx_emitter.Effects[fx_emitter.fxcount] = func
language.Add( "wire_fx_emitter_"..name, nicename )
end
end
-- Modular effect adding.. stuff
include( "wire/fx_emitter_default.lua" )
if CLIENT then
ENT.Delay = 0.05
function ENT:Draw()
// Don't draw if we are in camera mode
local ply = LocalPlayer()
local wep = ply:GetActiveWeapon()
if ( wep:IsValid() ) then
local weapon_name = wep:GetClass()
if ( weapon_name == "gmod_camera" ) then return end
end
self.BaseClass.Draw( self )
end
function ENT:Think()
if not self:GetOn() then return end
if ( self.Delay > CurTime() ) then return end
self.Delay = CurTime() + self:GetDelay()
local Effect = self:GetEffect()
// Missing effect... replace it if possible :/
if ( !self.Effects[ Effect ] ) then if ( self.Effects[1] ) then Effect = 1 else return end end
local Angle = self:GetAngles()
local FXDir = self:GetFXDir()
if FXDir and not FXDir:IsZero() then Angle = FXDir:Angle() else self:GetUp():Angle() end
local FXPos = self:GetFXPos()
if not FXPos or FXDir:IsZero() then FXPos=self:GetPos() + Angle:Forward() * 12 end
local b, e = pcall( self.Effects[Effect], FXPos, Angle )
if (!b) then
// Report the error
Print(self.Effects)
Print(FXPos)
Print(Angle)
Msg("Error in Emitter "..tostring(Effect).."\n -> "..tostring(e).."\n")
// Remove the naughty function
self.Effects[ Effect ] = nil
end
end
return -- No more client
end
-- Server
function ENT:Initialize()
self:SetModel( "models/props_lab/tpplug.mdl" )
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self:DrawShadow( false )
self:SetCollisionGroup( COLLISION_GROUP_WEAPON )
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
self.Inputs = WireLib.CreateInputs(self, {"On", "Effect", "Delay", "Direction [VECTOR]"})
end
function ENT:Setup(delay, effect)
if delay then self:SetDelay(delay) end
if effect then self:SetEffect(effect) end
end
function ENT:TriggerInput( inputname, value, iter )
if inputname == "Direction" then
self:SetFXDir(value:GetNormal())
elseif inputname == "Effect" then
self:SetEffect(math.Clamp(value - value % 1, 1, self.fxcount))
elseif inputname == "On" then
self:SetOn(value ~= 0)
elseif inputname == "Delay" then
self:SetDelay(math.Clamp(value, 0.05, 20))
--elseif (inputname == "Position") then -- removed for excessive mingability
-- self:SetFXPos(value)
end
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
-- Old dupes stored this info here rather than as RegisterEntityClass vars
if info.Effect then self:SetEffect(info.Effect) end
if info.Delay then self:SetDelay(info.Delay) end
end
duplicator.RegisterEntityClass("gmod_wire_fx_emitter", WireLib.MakeWireEnt, "Data", "delay", "effect" )
-- Note: delay and effect are here for backwards compatibility, they're now stored in the DataTable
| apache-2.0 |
uzlonewolf/proxmark3 | client/scripts/formatMifare.lua | 6 | 5285 | local cmds = require('commands')
local getopt = require('getopt')
local bin = require('bin')
local lib14a = require('read14a')
local utils = require('utils')
example =[[
1. script run formatMifare
2. script run formatMifare -k aabbccddeeff -n 112233445566 -a FF0780
]]
author = "Iceman"
usage = "script run formatMifare -k <key>"
desc =[[
This script will generate 'hf mf wrbl' commands for each block to format a Mifare card.
Alla datablocks gets 0x00
As default the script sets the keys A/B to 0xFFFFFFFFFFFF
and the access bytes will become 0x78,0x77,0x88
The GDB will become 0x00
The script will skip the manufactoring block 0.
Arguments:
-h - this help
-k <key> - the current six byte key with write access
-n <key> - the new key that will be written to the card
-a <access> - the new access bytes that will be written to the card
]]
local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
local DEBUG = true -- the debug flag
local CmdString = 'hf mf wrbl %d B %s %s'
local numBlocks = 64
local numSectors = 16
---
-- A debug printout-function
function dbg(args)
if not DEBUG then
return
end
if type(args) == "table" then
local i = 1
while result[i] do
dbg(result[i])
i = i+1
end
else
print("###", args)
end
end
---
-- This is only meant to be used when errors occur
function oops(err)
print("ERROR: ",err)
end
---
-- Usage help
function help()
print(desc)
print("Example usage")
print(example)
end
--
-- Exit message
function ExitMsg(msg)
print( string.rep('--',20) )
print( string.rep('--',20) )
print(msg)
print()
end
--
-- Read information from a card
function GetCardInfo()
result, err = lib14a.read14443a(false, true)
if not result then
print(err)
return
end
print(("Found: %s"):format(result.name))
core.clearCommandBuffer()
if 0x18 == result.sak then -- NXP MIFARE Classic 4k | Plus 4k
-- IFARE Classic 4K offers 4096 bytes split into forty sectors,
-- of which 32 are same size as in the 1K with eight more that are quadruple size sectors.
numSectors = 40
elseif 0x08 == result.sak then -- NXP MIFARE CLASSIC 1k | Plus 2k
-- 1K offers 1024 bytes of data storage, split into 16 sector
numSectors = 16
elseif 0x09 == result.sak then -- NXP MIFARE Mini 0.3k
-- MIFARE Classic mini offers 320 bytes split into five sectors.
numSectors = 5
elseif 0x10 == result.sak then -- NXP MIFARE Plus 2k
numSectors = 32
elseif 0x01 == result.sak then -- NXP MIFARE TNP3xxx 1K
numSectors = 16
else
print("I don't know how many sectors there are on this type of card, defaulting to 16")
end
--[[
The mifare Classic 1k card has 16 sectors of 4 data blocks each.
The first 32 sectors of a mifare Classic 4k card consists of 4 data blocks and the remaining
8 sectors consist of 16 data blocks.
--]]
-- Defaults to 16 * 4 = 64 - 1 = 63
numBlocks = numSectors * 4 - 1
if numSectors > 32 then
numBlocks = 32*4+ (numSectors-32)*16 -1
end
end
local function main(args)
print( string.rep('--',20) )
print( string.rep('--',20) )
print()
local OldKey
local NewKey
local Accessbytes
-- Arguments for the script
for o, a in getopt.getopt(args, 'hk:n:a:') do
if o == "h" then return help() end
if o == "k" then OldKey = a end
if o == "n" then NewKey = a end
if o == "a" then Accessbytes = a end
end
-- validate input args.
OldKey = OldKey or 'FFFFFFFFFFFF'
if #(OldKey) ~= 12 then
return oops( string.format('Wrong length of write key (was %d) expected 12', #OldKey))
end
NewKey = NewKey or 'FFFFFFFFFFFF'
if #(NewKey) ~= 12 then
return oops( string.format('Wrong length of new key (was %d) expected 12', #NewKey))
end
--Accessbytes = Accessbytes or '787788'
Accessbytes = Accessbytes or 'FF0780'
if #(Accessbytes) ~= 6 then
return oops( string.format('Wrong length of accessbytes (was %d) expected 12', #Accessbytes))
end
GetCardInfo()
-- Show info
print( string.format('Estimating number of blocks: %d', numBlocks))
print( string.format('Old key: %s', OldKey))
print( string.format('New key: %s', NewKey))
print( string.format('New Access: %s', Accessbytes))
print( string.rep('--',20) )
-- Set new block data
local EMPTY_BL = string.rep('00',16)
local EMPTY_SECTORTRAIL = string.format('%s%s%s%s',NewKey,Accessbytes,'00',NewKey)
dbg( string.format('New sector-trailer : %s',EMPTY_SECTORTRAIL))
dbg( string.format('New emptyblock: %s',EMPTY_BL))
dbg('')
-- Ask
local dialogResult = utils.confirm("Do you want to erase this card")
if dialogResult == false then
return ExitMsg('Quiting it is then. Your wish is my command...')
end
print( string.rep('--',20) )
-- main loop
for block=0,numBlocks,1 do
local reminder = (block+1) % 4
local cmd
if reminder == 0 then
cmd = CmdString:format(block, OldKey , EMPTY_SECTORTRAIL)
else
cmd = CmdString:format(block, OldKey , EMPTY_BL)
end
if block ~= 0 then
print(cmd)
--core.console(cmd)
end
if core.ukbhit() then
print("aborted by user")
break
end
end
end
main(args) | gpl-2.0 |
DJDaemonix/Roboports-Extended | prototypes/roboports/roboport-mk2.lua | 1 | 6047 | data:extend
(
{
{
type = "roboport",
name = "roboport-mk2",
icon = "__base__/graphics/icons/roboport.png",
icon_size = 32,
flags = {"placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "roboport-mk2"},
max_health = 750,
corpse = "big-remnants",
collision_box = {{-1.7, -1.7}, {1.7, 1.7}},
selection_box = {{-2, -2}, {2, 2}},
resistances =
{
{
type = "fire",
percent = 60
},
{
type = "impact",
percent = 30
}
},
dying_explosion = "medium-explosion",
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
input_flow_limit = "10MW",
buffer_capacity = "200MJ"
},
recharge_minimum = "60MJ",
energy_usage = "75kW",
-- per one charge slot
charging_energy = "1500kW",
logistics_radius = 50,
construction_radius = 110,
charge_approach_distance = 5,
robot_slots_count = 10,
material_slots_count = 10,
stationing_offset = {0, 0},
charging_offsets =
{
{-1.5, -0.5}, {1.5, -0.5}, {1.5, 1.5}, {-1.5, 1.5},
},
base =
{
layers =
{
{
filename = "__base__/graphics/entity/roboport/roboport-base.png",
width = 143,
height = 135,
shift = {0.5, 0.25},
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-base.png",
width = 228,
height = 277,
shift = util.by_pixel(2, 7.75),
scale = 0.5
}
},
{
filename = "__base__/graphics/entity/roboport/roboport-shadow.png",
width = 147,
height = 102,
draw_as_shadow = true,
shift = util.by_pixel(28.5, 19.25),
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-shadow.png",
width = 294,
height = 201,
draw_as_shadow = true,
shift = util.by_pixel(28.5, 19.25),
scale = 0.5
}
}
}
},
base_patch =
{
filename = "__base__/graphics/entity/roboport/roboport-base-patch.png",
priority = "medium",
width = 69,
height = 50,
frame_count = 1,
shift = {0.03125, 0.203125},
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-base-patch.png",
priority = "medium",
width = 138,
height = 100,
frame_count = 1,
shift = util.by_pixel(1.5, 5),
scale = 0.5
}
},
base_animation =
{
filename = "__base__/graphics/entity/roboport/roboport-base-animation.png",
priority = "medium",
width = 42,
height = 31,
frame_count = 8,
animation_speed = 0.5,
shift = {-0.5315, -1.9375},
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-base-animation.png",
priority = "medium",
width = 83,
height = 59,
frame_count = 8,
animation_speed = 0.5,
shift = util.by_pixel(-17.75, -61.25),
scale = 0.5
}
},
door_animation_up =
{
filename = "__base__/graphics/entity/roboport/roboport-door-up.png",
priority = "medium",
width = 52,
height = 20,
frame_count = 16,
shift = {0.015625, -0.890625},
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-door-up.png",
priority = "medium",
width = 97,
height = 38,
frame_count = 16,
shift = util.by_pixel(-0.25, -29.5),
scale = 0.5
}
},
door_animation_down =
{
filename = "__base__/graphics/entity/roboport/roboport-door-down.png",
priority = "medium",
width = 52,
height = 22,
frame_count = 16,
shift = {0.015625, -0.234375},
hr_version = {
filename = "__base__/graphics/entity/roboport/hr-roboport-door-down.png",
priority = "medium",
width = 97,
height = 41,
frame_count = 16,
shift = util.by_pixel(-0.25,-9.75),
scale = 0.5
}
},
recharging_animation =
{
filename = "__base__/graphics/entity/roboport/roboport-recharging.png",
priority = "high",
width = 37,
height = 35,
frame_count = 16,
scale = 1.5,
animation_speed = 0.5
},
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
working_sound =
{
sound = { filename = "__base__/sound/roboport-working.ogg", volume = 0.6 },
max_sounds_per_type = 3,
audible_distance_modifier = 0.5,
probability = 1 / (5 * 60) -- average pause between the sound is 5 seconds
},
recharging_light = {intensity = 0.4, size = 5, color = {r = 1.0, g = 1.0, b = 1.0}},
request_to_open_door_timeout = 15,
spawn_and_station_height = -0.1,
draw_logistic_radius_visualization = true,
draw_construction_radius_visualization = true,
open_door_trigger_effect =
{
{
type = "play-sound",
sound = { filename = "__base__/sound/roboport-door.ogg", volume = 1.2 }
},
},
close_door_trigger_effect =
{
{
type = "play-sound",
sound = { filename = "__base__/sound/roboport-door.ogg", volume = 0.75 }
},
},
circuit_wire_connection_point = circuit_connector_definitions["roboport"].points,
circuit_connector_sprites = circuit_connector_definitions["roboport"].sprites,
circuit_wire_max_distance = default_circuit_wire_max_distance,
default_available_logistic_output_signal = {type = "virtual", name = "signal-X"},
default_total_logistic_output_signal = {type = "virtual", name = "signal-Y"},
default_available_construction_output_signal = {type = "virtual", name = "signal-Z"},
default_total_construction_output_signal = {type = "virtual", name = "signal-T"},
},
}
) | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.