repo_name
stringlengths 6
78
| path
stringlengths 4
206
| copies
stringclasses 281
values | size
stringlengths 4
7
| content
stringlengths 625
1.05M
| license
stringclasses 15
values |
---|---|---|---|---|---|
NatWeiss/RGP | src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/script/cocos2d/DrawPrimitives.lua | 98 | 12024 |
local dp_initialized = false
local dp_shader = nil
local dp_colorLocation = -1
local dp_color = { 1.0, 1.0, 1.0, 1.0 }
local dp_pointSizeLocation = -1
local dp_pointSize = 1.0
local SHADER_NAME_POSITION_U_COLOR = "ShaderPosition_uColor"
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
local function lazy_init()
if not dp_initialized then
dp_shader = cc.ShaderCache:getInstance():getProgram(SHADER_NAME_POSITION_U_COLOR)
--dp_shader:retain()
if nil ~= dp_shader then
dp_colorLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_color")
dp_pointSizeLocation = gl.getUniformLocation( dp_shader:getProgram(), "u_pointSize")
dp_Initialized = true
end
end
if nil == dp_shader then
print("Error:dp_shader is nil!")
return false
end
return true
end
local function setDrawProperty()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, dp_color, 1)
end
function ccDrawInit()
lazy_init()
end
function ccDrawFree()
dp_initialized = false
end
function ccDrawColor4f(r,g,b,a)
dp_color[1] = r
dp_color[2] = g
dp_color[3] = b
dp_color[4] = a
end
function ccPointSize(pointSize)
dp_pointSize = pointSize * cc.Director:getInstance():getContentScaleFactor()
end
function ccDrawColor4B(r,g,b,a)
dp_color[1] = r / 255.0
dp_color[2] = g / 255.0
dp_color[3] = b / 255.0
dp_color[4] = a / 255.0
end
function ccDrawPoint(point)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
local vertices = { point.x,point.y}
gl.bufferData(gl.ARRAY_BUFFER,2,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoints(points,numOfPoint)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoint do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoint * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
dp_shader:setUniformLocationWith1f(dp_pointSizeLocation, dp_pointSize)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.POINTS,0,numOfPoint)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawLine(origin,destination)
if not lazy_init() then
return
end
local vertexBuffer = {}
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = { origin.x, origin.y, destination.x, destination.y}
gl.bufferData(gl.ARRAY_BUFFER,4,vertices,gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINES ,0,2)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawPoly(points,numOfPoints,closePolygon)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
if closePolygon then
gl.drawArrays(gl.LINE_LOOP , 0, numOfPoints)
else
gl.drawArrays(gl.LINE_STRIP, 0, numOfPoints)
end
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawSolidPoly(points,numOfPoints,color)
if not lazy_init() then
return
end
local vertexBuffer = {}
local i = 1
local function initBuffer()
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
local vertices = {}
for i = 1, numOfPoints do
vertices[2 * i - 1] = points[i].x
vertices[2 * i] = points[i].y
end
gl.bufferData(gl.ARRAY_BUFFER, numOfPoints * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
gl.glEnableVertexAttribs( CCConstants.VERTEX_ATTRIB_FLAG_POSITION )
dp_shader:use()
dp_shader:setUniformsForBuiltins()
dp_shader:setUniformLocationWith4fv(dp_colorLocation, color, 1)
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, numOfPoints)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawRect(origin,destination)
ccDrawLine(CCPoint:__call(origin.x, origin.y), CCPoint:__call(destination.x, origin.y))
ccDrawLine(CCPoint:__call(destination.x, origin.y), CCPoint:__call(destination.x, destination.y))
ccDrawLine(CCPoint:__call(destination.x, destination.y), CCPoint:__call(origin.x, destination.y))
ccDrawLine(CCPoint:__call(origin.x, destination.y), CCPoint:__call(origin.x, origin.y))
end
function ccDrawSolidRect( origin,destination,color )
local vertices = { origin, CCPoint:__call(destination.x, origin.y) , destination, CCPoint:__call(origin.x, destination.y) }
ccDrawSolidPoly(vertices,4,color)
end
function ccDrawCircleScale( center, radius, angle, segments,drawLineToCenter,scaleX,scaleY)
if not lazy_init() then
return
end
local additionalSegment = 1
if drawLineToCenter then
additionalSegment = additionalSegment + 1
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + additionalSegment)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCircle(center, radius, angle, segments, drawLineToCenter)
ccDrawCircleScale(center, radius, angle, segments, drawLineToCenter, 1.0, 1.0)
end
function ccDrawSolidCircle(center, radius, angle, segments,scaleX,scaleY)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local coef = 2.0 * math.pi / segments
local i = 1
local vertices = {}
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
for i = 1, segments + 1 do
local rads = (i - 1) * coef
local j = radius * math.cos(rads + angle) * scaleX + center.x
local k = radius * math.sin(rads + angle) * scaleY + center.y
vertices[i * 2 - 1] = j
vertices[i * 2] = k
end
vertices[(segments + 2) * 2 - 1] = center.x
vertices[(segments + 2) * 2] = center.y
gl.bufferData(gl.ARRAY_BUFFER, (segments + 2) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.TRIANGLE_FAN , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawQuadBezier(origin, control, destination, segments)
if not lazy_init() then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local i = 1
local t = 0.0
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,2) * origin.x + 2.0 * (1 - t) * t * control.x + t * t * destination.x
vertices[2 * i] = math.pow(1 - t,2) * origin.y + 2.0 * (1 - t) * t * control.y + t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
function ccDrawCubicBezier(origin, control1, control2, destination, segments)
if not lazy_init then
return
end
local vertexBuffer = { }
local function initBuffer()
local vertices = { }
local t = 0
local i = 1
for i = 1, segments do
vertices[2 * i - 1] = math.pow(1 - t,3) * origin.x + 3.0 * math.pow(1 - t, 2) * t * control1.x + 3.0 * (1 - t) * t * t * control2.x + t * t * t * destination.x
vertices[2 * i] = math.pow(1 - t,3) * origin.y + 3.0 * math.pow(1 - t, 2) * t * control1.y + 3.0 * (1 - t) * t * t * control2.y + t * t * t * destination.y
t = t + 1.0 / segments
end
vertices[2 * (segments + 1) - 1] = destination.x
vertices[2 * (segments + 1)] = destination.y
vertexBuffer.buffer_id = gl.createBuffer()
gl.bindBuffer(gl.ARRAY_BUFFER, vertexBuffer.buffer_id)
gl.bufferData(gl.ARRAY_BUFFER, (segments + 1) * 2, vertices, gl.STATIC_DRAW)
gl.bindBuffer(gl.ARRAY_BUFFER, 0)
end
initBuffer()
setDrawProperty()
gl.bindBuffer(gl.ARRAY_BUFFER,vertexBuffer.buffer_id)
gl.vertexAttribPointer(CCConstants.VERTEX_ATTRIB_POSITION, 2, gl.FLOAT, false, 0, 0)
gl.drawArrays(gl.LINE_STRIP , 0, segments + 1)
gl.bindBuffer(gl.ARRAY_BUFFER,0)
end
| mit |
enginix/luasocket | test/smtptest.lua | 44 | 5376 | local sent = {}
local from = "diego@localhost"
local server = "localhost"
local rcpt = "luasocket@localhost"
local files = {
"/var/spool/mail/luasocket",
"/var/spool/mail/luasock1",
"/var/spool/mail/luasock2",
"/var/spool/mail/luasock3",
}
local t = socket.time()
local err
dofile("mbox.lua")
local parse = mbox.parse
dofile("testsupport.lua")
local total = function()
local t = 0
for i = 1, #sent do
t = t + sent[i].count
end
return t
end
local similar = function(s1, s2)
return
string.lower(string.gsub(s1, "%s", "")) ==
string.lower(string.gsub(s2, "%s", ""))
end
local fail = function(s)
s = s or "failed!"
print(s)
os.exit()
end
local readfile = function(name)
local f = io.open(name, "r")
if not f then
fail("unable to open file!")
return nil
end
local s = f:read("*a")
f:close()
return s
end
local empty = function()
for i,v in ipairs(files) do
local f = io.open(v, "w")
if not f then
fail("unable to open file!")
end
f:close()
end
end
local get = function()
local s = ""
for i,v in ipairs(files) do
s = s .. "\n" .. readfile(v)
end
return s
end
local check_headers = function(sent, got)
sent = sent or {}
got = got or {}
for i,v in pairs(sent) do
if not similar(v, got[i]) then fail("header " .. v .. "failed!") end
end
end
local check_body = function(sent, got)
sent = sent or ""
got = got or ""
if not similar(sent, got) then fail("bodies differ!") end
end
local check = function(sent, m)
io.write("checking ", m.headers.title, ": ")
for i = 1, #sent do
local s = sent[i]
if s.title == m.headers.title and s.count > 0 then
check_headers(s.headers, m.headers)
check_body(s.body, m.body)
s.count = s.count - 1
print("ok")
return
end
end
fail("not found")
end
local insert = function(sent, message)
if type(message.rcpt) == "table" then
message.count = #message.rcpt
else message.count = 1 end
message.headers = message.headers or {}
message.headers.title = message.title
table.insert(sent, message)
end
local mark = function()
local time = socket.time()
return { time = time }
end
local wait = function(sentinel, n)
local to
io.write("waiting for ", n, " messages: ")
while 1 do
local mbox = parse(get())
if n == #mbox then break end
if socket.time() - sentinel.time > 50 then
to = 1
break
end
socket.sleep(1)
io.write(".")
io.stdout:flush()
end
if to then fail("timeout")
else print("ok") end
end
local stuffed_body = [[
This message body needs to be
stuffed because it has a dot
.
by itself on a line.
Otherwise the mailer would
think that the dot
.
is the end of the message
and the remaining text would cause
a lot of trouble.
]]
insert(sent, {
from = from,
rcpt = {
"luasocket@localhost",
"luasock3@dell-diego.cs.princeton.edu",
"luasock1@dell-diego.cs.princeton.edu"
},
body = "multiple rcpt body",
title = "multiple rcpt",
})
insert(sent, {
from = from,
rcpt = {
"luasock2@localhost",
"luasock3",
"luasock1"
},
headers = {
header1 = "header 1",
header2 = "header 2",
header3 = "header 3",
header4 = "header 4",
header5 = "header 5",
header6 = "header 6",
},
body = stuffed_body,
title = "complex message",
})
insert(sent, {
from = from,
rcpt = rcpt,
server = server,
body = "simple message body",
title = "simple message"
})
insert(sent, {
from = from,
rcpt = rcpt,
server = server,
body = stuffed_body,
title = "stuffed message body"
})
insert(sent, {
from = from,
rcpt = rcpt,
headers = {
header1 = "header 1",
header2 = "header 2",
header3 = "header 3",
header4 = "header 4",
header5 = "header 5",
header6 = "header 6",
},
title = "multiple headers"
})
insert(sent, {
from = from,
rcpt = rcpt,
title = "minimum message"
})
io.write("testing host not found: ")
local c, e = socket.connect("wrong.host", 25)
local ret, err = socket.smtp.mail{
from = from,
rcpt = rcpt,
server = "wrong.host"
}
if ret or e ~= err then fail("wrong error message")
else print("ok") end
io.write("testing invalid from: ")
local ret, err = socket.smtp.mail{
from = ' " " (( _ * ',
rcpt = rcpt,
}
if ret or not err then fail("wrong error message")
else print(err) end
io.write("testing no rcpt: ")
local ret, err = socket.smtp.mail{
from = from,
}
if ret or not err then fail("wrong error message")
else print(err) end
io.write("clearing mailbox: ")
empty()
print("ok")
io.write("sending messages: ")
for i = 1, #sent do
ret, err = socket.smtp.mail(sent[i])
if not ret then fail(err) end
io.write("+")
io.stdout:flush()
end
print("ok")
wait(mark(), total())
io.write("parsing mailbox: ")
local mbox = parse(get())
print(#mbox .. " messages found!")
for i = 1, #mbox do
check(sent, mbox[i])
end
print("passed all tests")
print(string.format("done in %.2fs", socket.time() - t))
| mit |
ZipFile/vlc | share/lua/playlist/mpora.lua | 97 | 2565 | --[[
$Id$
Copyright © 2009 the VideoLAN team
Authors: Konstantin Pavlov (thresh@videolan.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "video%.mpora%.com/watch/" )
end
-- Parse function.
function parse()
p = {}
while true do
-- Try to find the video's title
line = vlc.readline()
if not line then break end
if string.match( line, "meta name=\"title\"" ) then
_,_,name = string.find( line, "content=\"(.*)\" />" )
end
if string.match( line, "image_src" ) then
_,_,arturl = string.find( line, "image_src\" href=\"(.*)\" />" )
end
if string.match( line, "video_src" ) then
_,_,video = string.find( line, 'href="http://video%.mpora%.com/ep/(.*)%.swf" />' )
end
end
if not name or not arturl or not video then return nil end
-- Try and get URL for SD video.
sd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/")
if not sd then return nil end
page = sd:read( 65653 )
sdurl = string.match( page, "url=\"(.*)\" />")
page = nil
table.insert( p, { path = sdurl; name = name; arturl = arturl; } )
-- Try and check if HD video is available.
checkhd = vlc.stream("http://api.mpora.com/tv/player/load/vid/"..video.."/platform/video/domain/video.mpora.com/" )
if not checkhd then return nil end
page = checkhd:read( 65653 )
hashd = tonumber( string.match( page, "<has_hd>(%d)</has_hd>" ) )
page = nil
if hashd then
hd = vlc.stream("http://api.mpora.com/tv/player/playlist/vid/"..video.."/hd/true/")
page = hd:read( 65653 )
hdurl = string.match( page, "url=\"(.*)\" />")
table.insert( p, { path = hdurl; name = name.." (HD)"; arturl = arturl; } )
end
return p
end
| gpl-2.0 |
falsechicken/chickens_riddim_plugins | plugins/command_setstatus.lua | 1 | 1427 | --[[
Command_SetStatus
Allows users to set bot status via command.
Licensed Under the GPLv2
--]]
local permissions = require("riddim/ai_utils/permissions");
local jid_tool = require("riddim/ai_utils/jid_tool");
local BOT;
local helpMessge = "Sets the status of the bot. Usage: @setstatus <status> or $DEFAULT to use config default.";
local CheckPermissions = function(_command)
if _command.stanza.attr.type == "groupchat" then
if permissions.HasPermission(_command.sender["jid"], "command_setstatus", BOT.config.permissions) == false then
return false;
end
return true;
else
if permissions.HasPermission(jid_tool.StripResourceFromJID(_command.sender["jid"]), "command_setstatus", BOT.config.permissions) == false then
return false;
end
return true;
end
end
function riddim.plugins.command_setstatus(_bot)
_bot:hook("commands/setstatus", SetStatus);
_bot.stream:add_plugin("presence");
BOT = _bot;
end
function SetStatus(_command)
if CheckPermissions(_command) then
if _command.param == nil then return helpMessge; end
if _command.param == "$DEFAULT" then
if BOT.config.default_status == nil then _command:reply("No default status in config."); return; end
BOT.stream:set_status({ msg = BOT.config.default_status });
return;
end
BOT.stream:set_status({ msg = _command.param });
return;
else
_command:reply("You are not authorized to set bot status.");
end
end
| gpl-2.0 |
bradchesney79/2015BeastRouterProject | openwrt/unsquash/squashfs-root/usr/lib/lua/luci/model/cbi/admin_network/network.lua | 48 | 2480 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
m = Map("network", translate("Interfaces"))
m.pageaction = false
m:section(SimpleSection).template = "admin_network/iface_overview"
-- Show ATM bridge section if we have the capabilities
if fs.access("/usr/sbin/br2684ctl") then
atm = m:section(TypedSection, "atm-bridge", translate("ATM Bridges"),
translate("ATM bridges expose encapsulated ethernet in AAL5 " ..
"connections as virtual Linux network interfaces which can " ..
"be used in conjunction with DHCP or PPP to dial into the " ..
"provider network."))
atm.addremove = true
atm.anonymous = true
atm.create = function(self, section)
local sid = TypedSection.create(self, section)
local max_unit = -1
m.uci:foreach("network", "atm-bridge",
function(s)
local u = tonumber(s.unit)
if u ~= nil and u > max_unit then
max_unit = u
end
end)
m.uci:set("network", sid, "unit", max_unit + 1)
m.uci:set("network", sid, "atmdev", 0)
m.uci:set("network", sid, "encaps", "llc")
m.uci:set("network", sid, "payload", "bridged")
m.uci:set("network", sid, "vci", 35)
m.uci:set("network", sid, "vpi", 8)
return sid
end
atm:tab("general", translate("General Setup"))
atm:tab("advanced", translate("Advanced Settings"))
vci = atm:taboption("general", Value, "vci", translate("ATM Virtual Channel Identifier (VCI)"))
vpi = atm:taboption("general", Value, "vpi", translate("ATM Virtual Path Identifier (VPI)"))
encaps = atm:taboption("general", ListValue, "encaps", translate("Encapsulation mode"))
encaps:value("llc", translate("LLC"))
encaps:value("vc", translate("VC-Mux"))
atmdev = atm:taboption("advanced", Value, "atmdev", translate("ATM device number"))
unit = atm:taboption("advanced", Value, "unit", translate("Bridge unit number"))
payload = atm:taboption("advanced", ListValue, "payload", translate("Forwarding mode"))
payload:value("bridged", translate("bridged"))
payload:value("routed", translate("routed"))
m.pageaction = true
end
local network = require "luci.model.network"
if network:has_ipv6() then
local s = m:section(NamedSection, "globals", "globals", translate("Global network options"))
local o = s:option(Value, "ula_prefix", translate("IPv6 ULA-Prefix"))
o.datatype = "ip6addr"
o.rmempty = true
m.pageaction = true
end
return m
| cc0-1.0 |
mcdonnelldean/eso-pad-merchant | PadMerchant/lib/LibAddonMenu-2.0/controls/iconpicker.lua | 8 | 13896 | --[[iconpickerData = {
type = "iconpicker",
name = "My Icon Picker",
tooltip = "Color Picker's tooltip text.",
choices = {"texture path 1", "texture path 2", "texture path 3"},
choicesTooltips = {"icon tooltip 1", "icon tooltip 2", "icon tooltip 3"}, --(optional)
getFunc = function() return db.var end,
setFunc = function(var) db.var = var doStuff() end,
maxColumns = 5, --(optional) number of icons in one row
visibleRows = 4.5, --(optional) number of visible rows
iconSize = 28, --(optional) size of the icons
defaultColor = ZO_ColorDef:New("FFFFFF"), --(optional) default color of the icons
width = "full", --or "half" (optional)
beforeShow = function(control, iconPicker) return preventShow end, --(optional)
disabled = function() return db.someBooleanSetting end, --or boolean (optional)
warning = "Will need to reload the UI.", --(optional)
default = defaults.var, --(optional)
reference = "MyAddonIconPicker" --(optional) unique global reference to control
} ]]
local widgetVersion = 2
local LAM = LibStub("LibAddonMenu-2.0")
if not LAM:RegisterWidget("iconpicker", widgetVersion) then return end
local wm = WINDOW_MANAGER
local cm = CALLBACK_MANAGER
local tinsert = table.insert
local IconPickerMenu = ZO_Object:Subclass()
local iconPicker
LAM.util.GetIconPickerMenu = function()
if not iconPicker then
iconPicker = IconPickerMenu:New("LAMIconPicker")
local sceneFragment = LAM:GetAddonSettingsFragment()
ZO_PreHook(sceneFragment, "OnHidden", function()
if not iconPicker.control:IsHidden() then
iconPicker:Clear()
end
end)
end
return iconPicker
end
function IconPickerMenu:New(...)
local object = ZO_Object.New(self)
object:Initialize(...)
return object
end
function IconPickerMenu:Initialize(name)
local control = wm:CreateTopLevelWindow(name)
control:SetDrawTier(DT_HIGH)
control:SetHidden(true)
self.control = control
local scrollContainer = wm:CreateControlFromVirtual(name .. "ScrollContainer", control, "ZO_ScrollContainer")
-- control:SetDimensions(control.container:GetWidth(), height) -- adjust to icon size / col count
scrollContainer:SetAnchorFill()
ZO_Scroll_SetUseFadeGradient(scrollContainer, false)
ZO_Scroll_SetHideScrollbarOnDisable(scrollContainer, false)
ZO_VerticalScrollbarBase_OnMouseExit(scrollContainer:GetNamedChild("ScrollBar")) -- scrollbar initialization seems to be broken so we force it to update the correct alpha value
local scroll = GetControl(scrollContainer, "ScrollChild")
self.scroll = scroll
self.scrollContainer = scrollContainer
local bg = wm:CreateControl(nil, scrollContainer, CT_BACKDROP)
bg:SetAnchor(TOPLEFT, scrollContainer, TOPLEFT, 0, -3)
bg:SetAnchor(BOTTOMRIGHT, scrollContainer, BOTTOMRIGHT, 2, 5)
bg:SetEdgeTexture("EsoUI\\Art\\Tooltips\\UI-Border.dds", 128, 16)
bg:SetCenterTexture("EsoUI\\Art\\Tooltips\\UI-TooltipCenter.dds")
bg:SetInsets(16, 16, -16, -16)
local mungeOverlay = wm:CreateControl(nil, bg, CT_TEXTURE)
mungeOverlay:SetTexture("EsoUI/Art/Tooltips/munge_overlay.dds")
mungeOverlay:SetDrawLevel(1)
mungeOverlay:SetAddressMode(TEX_MODE_WRAP)
mungeOverlay:SetAnchorFill()
local mouseOver = wm:CreateControl(nil, scrollContainer, CT_TEXTURE)
mouseOver:SetDrawLevel(2)
mouseOver:SetTexture("EsoUI/Art/Buttons/minmax_mouseover.dds")
mouseOver:SetHidden(true)
local function IconFactory(pool)
local icon = wm:CreateControl(name .. "Entry" .. pool:GetNextControlId(), scroll, CT_TEXTURE)
icon:SetMouseEnabled(true)
icon:SetDrawLevel(3)
icon:SetHandler("OnMouseEnter", function()
mouseOver:SetAnchor(TOPLEFT, icon, TOPLEFT, 0, 0)
mouseOver:SetAnchor(BOTTOMRIGHT, icon, BOTTOMRIGHT, 0, 0)
mouseOver:SetHidden(false)
if self.customOnMouseEnter then
self.customOnMouseEnter(icon)
else
self:OnMouseEnter(icon)
end
end)
icon:SetHandler("OnMouseExit", function()
mouseOver:ClearAnchors()
mouseOver:SetHidden(true)
if self.customOnMouseExit then
self.customOnMouseExit(icon)
else
self:OnMouseExit(icon)
end
end)
icon:SetHandler("OnMouseUp", function(control, ...)
PlaySound("Click")
icon.OnSelect(icon, icon.texture)
self:Clear()
end)
return icon
end
local function ResetFunction(icon)
icon:ClearAnchors()
end
self.iconPool = ZO_ObjectPool:New(IconFactory, ResetFunction)
self:SetMaxColumns(1)
self.icons = {}
self.color = ZO_DEFAULT_ENABLED_COLOR
EVENT_MANAGER:RegisterForEvent(name .. "_OnGlobalMouseUp", EVENT_GLOBAL_MOUSE_UP, function()
if self.refCount ~= nil then
local moc = wm:GetMouseOverControl()
if(moc:GetOwningWindow() ~= control) then
self.refCount = self.refCount - 1
if self.refCount <= 0 then
self:Clear()
end
end
end
end)
end
function IconPickerMenu:OnMouseEnter(icon)
InitializeTooltip(InformationTooltip, icon, TOPLEFT, 0, 0, BOTTOMRIGHT)
SetTooltipText(InformationTooltip, LAM.util.GetTooltipText(icon.tooltip))
InformationTooltipTopLevel:BringWindowToTop()
end
function IconPickerMenu:OnMouseExit(icon)
ClearTooltip(InformationTooltip)
end
function IconPickerMenu:SetMaxColumns(value)
self.maxCols = value ~= nil and value or 5
end
local DEFAULT_SIZE = 28
function IconPickerMenu:SetIconSize(value)
local iconSize = DEFAULT_SIZE
if value ~= nil then iconSize = math.max(iconSize, value) end
self.iconSize = iconSize
end
function IconPickerMenu:SetVisibleRows(value)
self.visibleRows = value ~= nil and value or 4.5
end
function IconPickerMenu:SetMouseHandlers(onEnter, onExit)
self.customOnMouseEnter = onEnter
self.customOnMouseExit = onExit
end
function IconPickerMenu:UpdateDimensions()
local iconSize = self.iconSize
local width = iconSize * self.maxCols + 20
local height = iconSize * self.visibleRows
self.control:SetDimensions(width, height)
local icons = self.icons
for i = 1, #icons do
local icon = icons[i]
icon:SetDimensions(iconSize, iconSize)
end
end
function IconPickerMenu:UpdateAnchors()
local iconSize = self.iconSize
local col, maxCols = 1, self.maxCols
local previousCol, previousRow
local scroll = self.scroll
local icons = self.icons
for i = 1, #icons do
local icon = icons[i]
icon:ClearAnchors()
if i == 1 then
icon:SetAnchor(TOPLEFT, scroll, TOPLEFT, 0, 0)
previousRow = icon
elseif col == 1 then
icon:SetAnchor(TOPLEFT, previousRow, BOTTOMLEFT, 0, 0)
previousRow = icon
else
icon:SetAnchor(TOPLEFT, previousCol, TOPRIGHT, 0, 0)
end
previousCol = icon
col = col >= maxCols and 1 or col + 1
end
end
function IconPickerMenu:Clear()
self.icons = {}
self.iconPool:ReleaseAllObjects()
self.control:SetHidden(true)
self.color = ZO_DEFAULT_ENABLED_COLOR
self.refCount = nil
self.parent = nil
self.customOnMouseEnter = nil
self.customOnMouseExit = nil
end
function IconPickerMenu:AddIcon(texturePath, callback, tooltip)
local icon, key = self.iconPool:AcquireObject()
icon:SetTexture(texturePath)
icon:SetColor(self.color:UnpackRGBA())
icon.texture = texturePath
icon.tooltip = tooltip
icon.OnSelect = callback
self.icons[#self.icons + 1] = icon
end
function IconPickerMenu:Show(parent)
if #self.icons == 0 then return false end
if not self.control:IsHidden() then self:Clear() return false end
self:UpdateDimensions()
self:UpdateAnchors()
local control = self.control
control:ClearAnchors()
control:SetAnchor(TOPLEFT, parent, BOTTOMLEFT, 0, 8)
control:SetHidden(false)
control:BringWindowToTop()
self.parent = parent
self.refCount = 2
return true
end
function IconPickerMenu:SetColor(color)
local icons = self.icons
self.color = color
for i = 1, #icons do
local icon = icons[i]
icon:SetColor(color:UnpackRGBA())
end
end
-------------------------------------------------------------
local function UpdateChoices(control, choices, choicesTooltips)
local data = control.data
if not choices then
choices, choicesTooltips = data.choices, data.choicesTooltips
end
local addedChoices = {}
local iconPicker = LAM.util.GetIconPickerMenu()
iconPicker:Clear()
for i = 1, #choices do
local texture = choices[i]
if not addedChoices[texture] then -- remove duplicates
iconPicker:AddIcon(choices[i], function(self, texture)
control.icon:SetTexture(texture)
data.setFunc(texture)
if control.panel.data.registerForRefresh then
cm:FireCallbacks("LAM-RefreshPanel", control)
end
end, choicesTooltips[i])
addedChoices[texture] = true
end
end
end
local function IsDisabled(control)
if type(control.data.disabled) == "function" then
return control.data.disabled()
else
return control.data.disabled
end
end
local function SetColor(control, color)
local icon = control.icon
if IsDisabled(control) then
icon:SetColor(ZO_DEFAULT_DISABLED_COLOR:UnpackRGBA())
else
icon.color = color or control.data.defaultColor or ZO_DEFAULT_ENABLED_COLOR
icon:SetColor(icon.color:UnpackRGBA())
end
local iconPicker = LAM.util.GetIconPickerMenu()
if iconPicker.parent == control.container and not iconPicker.control:IsHidden() then
iconPicker:SetColor(icon.color)
end
end
local function UpdateDisabled(control)
local disable = IsDisabled(control)
control.dropdown:SetMouseEnabled(not disable)
control.dropdownButton:SetEnabled(not disable)
local iconPicker = LAM.util.GetIconPickerMenu()
if iconPicker.parent == control.container and not iconPicker.control:IsHidden() then
iconPicker:Clear()
end
SetColor(control)
if disable then
control.label:SetColor(ZO_DEFAULT_DISABLED_COLOR:UnpackRGBA())
else
control.label:SetColor(ZO_DEFAULT_ENABLED_COLOR:UnpackRGBA())
end
end
local function UpdateValue(control, forceDefault, value)
if forceDefault then --if we are forcing defaults
value = control.data.default
control.data.setFunc(value)
control.icon:SetTexture(value)
elseif value then
control.data.setFunc(value)
--after setting this value, let's refresh the others to see if any should be disabled or have their settings changed
if control.panel.data.registerForRefresh then
cm:FireCallbacks("LAM-RefreshPanel", control)
end
else
value = control.data.getFunc()
control.icon:SetTexture(value)
end
end
local MIN_HEIGHT = 26
local HALF_WIDTH_LINE_SPACING = 2
local function SetIconSize(control, size)
local icon = control.icon
icon.size = size
icon:SetDimensions(size, size)
local height = size + 4
control.dropdown:SetDimensions(size + 20, height)
height = math.max(height, MIN_HEIGHT)
control.container:SetHeight(height)
if control.lineControl then
control.lineControl:SetHeight(MIN_HEIGHT + size + HALF_WIDTH_LINE_SPACING)
else
control:SetHeight(height)
end
local iconPicker = LAM.util.GetIconPickerMenu()
if iconPicker.parent == control.container and not iconPicker.control:IsHidden() then
iconPicker:SetIconSize(size)
iconPicker:UpdateDimensions()
iconPicker:UpdateAnchors()
end
end
function LAMCreateControl.iconpicker(parent, iconpickerData, controlName)
local control = LAM.util.CreateLabelAndContainerControl(parent, iconpickerData, controlName)
local function ShowIconPicker()
local iconPicker = LAM.util.GetIconPickerMenu()
if iconPicker.parent == control.container then
iconPicker:Clear()
else
iconPicker:SetMaxColumns(iconpickerData.maxColumns)
iconPicker:SetVisibleRows(iconpickerData.visibleRows)
iconPicker:SetIconSize(control.icon.size)
UpdateChoices(control)
iconPicker:SetColor(control.icon.color)
if iconpickerData.beforeShow then
if iconpickerData.beforeShow(control, iconPicker) then
iconPicker:Clear()
return
end
end
iconPicker:Show(control.container)
end
end
local iconSize = iconpickerData.iconSize ~= nil and iconpickerData.iconSize or DEFAULT_SIZE
control.dropdown = wm:CreateControl(nil, control.container, CT_CONTROL)
local dropdown = control.dropdown
dropdown:SetAnchor(LEFT, control.container, LEFT, 0, 0)
dropdown:SetMouseEnabled(true)
dropdown:SetHandler("OnMouseUp", ShowIconPicker)
dropdown:SetHandler("OnMouseEnter", function() ZO_Options_OnMouseEnter(control) end)
dropdown:SetHandler("OnMouseExit", function() ZO_Options_OnMouseExit(control) end)
control.icon = wm:CreateControl(nil, dropdown, CT_TEXTURE)
local icon = control.icon
icon:SetAnchor(LEFT, dropdown, LEFT, 3, 0)
icon:SetDrawLevel(2)
local dropdownButton = wm:CreateControlFromVirtual(nil, dropdown, "ZO_DropdownButton")
dropdownButton:SetDimensions(16, 16)
dropdownButton:SetHandler("OnClicked", ShowIconPicker)
dropdownButton:SetAnchor(RIGHT, dropdown, RIGHT, -3, 0)
control.dropdownButton = dropdownButton
control.bg = wm:CreateControl(nil, dropdown, CT_BACKDROP)
local bg = control.bg
bg:SetAnchor(TOPLEFT, dropdown, TOPLEFT, 0, -3)
bg:SetAnchor(BOTTOMRIGHT, dropdown, BOTTOMRIGHT, 2, 5)
bg:SetEdgeTexture("EsoUI/Art/Tooltips/UI-Border.dds", 128, 16)
bg:SetCenterTexture("EsoUI/Art/Tooltips/UI-TooltipCenter.dds")
bg:SetInsets(16, 16, -16, -16)
local mungeOverlay = wm:CreateControl(nil, bg, CT_TEXTURE)
mungeOverlay:SetTexture("EsoUI/Art/Tooltips/munge_overlay.dds")
mungeOverlay:SetDrawLevel(1)
mungeOverlay:SetAddressMode(TEX_MODE_WRAP)
mungeOverlay:SetAnchorFill()
if iconpickerData.warning then
control.warning = wm:CreateControlFromVirtual(nil, control, "ZO_Options_WarningIcon")
control.warning:SetAnchor(RIGHT, control.container, LEFT, -5, 0)
control.warning.data = {tooltipText = iconpickerData.warning}
end
if iconpickerData.disabled then
control.UpdateDisabled = UpdateDisabled
control:UpdateDisabled()
end
control.UpdateChoices = UpdateChoices
control.UpdateValue = UpdateValue
control:UpdateValue()
control.SetColor = SetColor
control:SetColor()
control.SetIconSize = SetIconSize
control:SetIconSize(iconSize)
if control.panel.data.registerForRefresh or control.panel.data.registerForDefaults then --if our parent window wants to refresh controls, then add this to the list
tinsert(control.panel.controlsToRefresh, control)
end
return control
end
| mit |
joaofvieira/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/rrdtool.lua | 46 | 3168 | -- 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("RRDTool Plugin Configuration"),
translate(
"The rrdtool plugin stores the collected data in rrd database " ..
"files, the foundation of the diagrams.<br /><br />" ..
"<strong>Warning: Setting the wrong values will result in a very " ..
"high memory consumption in the temporary directory. " ..
"This can render the device unusable!</strong>"
))
-- collectd_rrdtool config section
s = m:section( NamedSection, "collectd_rrdtool", "luci_statistics" )
-- collectd_rrdtool.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 1
-- collectd_rrdtool.datadir (DataDir)
datadir = s:option( Value, "DataDir", translate("Storage directory") )
datadir.default = "/tmp"
datadir.rmempty = true
datadir.optional = true
datadir:depends( "enable", 1 )
-- collectd_rrdtool.stepsize (StepSize)
stepsize = s:option( Value, "StepSize",
translate("RRD step interval"), translate("Seconds") )
stepsize.default = 30
stepsize.isinteger = true
stepsize.rmempty = true
stepsize.optional = true
stepsize:depends( "enable", 1 )
-- collectd_rrdtool.heartbeat (HeartBeat)
heartbeat = s:option( Value, "HeartBeat",
translate("RRD heart beat interval"), translate("Seconds") )
heartbeat.default = 60
heartbeat.isinteger = true
heartbeat.rmempty = true
heartbeat.optional = true
heartbeat:depends( "enable", 1 )
-- collectd_rrdtool.rrasingle (RRASingle)
rrasingle = s:option( Flag, "RRASingle",
translate("Only create average RRAs"), translate("reduces rrd size") )
rrasingle.default = true
rrasingle.rmempty = true
rrasingle.optional = true
rrasingle:depends( "enable", 1 )
-- collectd_rrdtool.rratimespans (RRATimespan)
rratimespans = s:option( Value, "RRATimespans",
translate("Stored timespans"), translate("seconds; multiple separated by space") )
rratimespans.default = "600 86400 604800 2678400 31622400"
rratimespans.rmempty = true
rratimespans.optional = true
rratimespans:depends( "enable", 1 )
-- collectd_rrdtool.rrarows (RRARows)
rrarows = s:option( Value, "RRARows", translate("Rows per RRA") )
rrarows.isinteger = true
rrarows.default = 100
rrarows.rmempty = true
rrarows.optional = true
rrarows:depends( "enable", 1 )
-- collectd_rrdtool.xff (XFF)
xff = s:option( Value, "XFF", translate("RRD XFiles Factor") )
xff.default = 0.1
xff.isnumber = true
xff.rmempty = true
xff.optional = true
xff:depends( "enable", 1 )
-- collectd_rrdtool.cachetimeout (CacheTimeout)
cachetimeout = s:option( Value, "CacheTimeout",
translate("Cache collected data for"), translate("Seconds") )
cachetimeout.isinteger = true
cachetimeout.default = 100
cachetimeout.rmempty = true
cachetimeout.optional = true
cachetimeout:depends( "enable", 1 )
-- collectd_rrdtool.cacheflush (CacheFlush)
cacheflush = s:option( Value, "CacheFlush",
translate("Flush cache after"), translate("Seconds") )
cacheflush.isinteger = true
cacheflush.default = 100
cacheflush.rmempty = true
cacheflush.optional = true
cacheflush:depends( "enable", 1 )
return m
| apache-2.0 |
eggBOY91/Arctic-Core | src/scripts/lua/LuaBridge/Stable Scripts/Azeroth/Karazhan/BOSS_Karazhan_Kilrek.lua | 30 | 1152 | function Kilrek_Broken_Pact(Unit, event, miscunit, misc)
if Unit:GetHealthPct() < 2 and Didthat == 0 then
Unit:FullCastSpellOnTarget(30065,Unit:GetUnitBySqlId(15688))
Unit:SendChatMessage(11, 0, "You let me down Terestian, you will pay for this...")
Didthat = 1
else
end
end
function Kilrek_FireBolt(Unit, event, miscunit, misc)
print "Kilrek FireBolt"
Unit:FullCastSpellOnTarget(15592,Unit:GetClosestPlayer())
Unit:SendChatMessage(11, 0, "Take that...")
end
function Kilrek_Summon_Imps(Unit, event, miscunit, misc)
print "Kilrek Summon Imps"
Unit:FullCastSpell(34237)
Unit:SendChatMessage(11, 0, "Help me...")
end
function Kilrek_Amplify_Flames(Unit, event, miscunit, misc)
print "Kilrek Amplify Flames"
Unit:FullCastSpellOnTarget(30053,Unit:GetClosestPlayer())
Unit:SendChatMessage(11, 0, "Take fire will hurt you more...")
end
function Kilrek(unit, event, miscunit, misc)
print "Kilrek"
unit:RegisterEvent("Kilrek_Broken_Pact",1000,1)
unit:RegisterEvent("Kilrek_FireBolt",8000,0)
unit:RegisterEvent("Kilrek_Summon_Imps",30000,0)
unit:RegisterEvent("Kilrek_Amplify_Flames",45000,0)
end
RegisterUnitEvent(17229,1,"Kilrek")
| agpl-3.0 |
Aminkavari/-xXD4RKXx- | plugins/banhammer.lua | 294 | 10470 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
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
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'kickme' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "!kickme : Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id> : Remove user from whitelist",
"!whitelist delete chat : Remove chat from whitelist",
"!ban user <user_id> : Kick user from chat and kicks it if joins chat again",
"!ban user <username> : Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id> : Unban user",
"!kick <user_id> : Kick user from chat group by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (.*)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (.*)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (.*)$",
"^!(ban) (delete) (.*)$",
"^!(superban) (user) (.*)$",
"^!(superban) (delete) (.*)$",
"^!(kick) (.*)$",
"^!(kickme)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
moteus/lua-voip | lua/voip/sip/impl/transport.lua | 2 | 4503 | local async_socket = require "async_socket"
local timer = require "async_socket.timer"
local SipCreateMsg = require "voip.sip.message".new
----------------------------------------------
local SIP_TRANSPORT = {} do
local cnn_method = {
"bind","connect","close","idle","is_async",
"send","sendto","recv","recvfrom","set_timeout",
"timeout","local_host","local_port","remote_host",
"remote_port", "is_closed", "is_connected"
}
for _, method_name in pairs(cnn_method) do
SIP_TRANSPORT[method_name] = function(self, ...)
return self.private_.cnn[method_name](self.private_.cnn, ...)
end
end
function SIP_TRANSPORT:new(idle_hook)
local cnn, err = async_socket.udp_client(idle_hook);
if not cnn then return nil, err end
local t = setmetatable({
private_ = {
timers = {
T1 = 0.5;
T2 = 64;
};
cnn = cnn;
trace = function() end;
}
},{__index=self})
return t
end
function SIP_TRANSPORT:trace(...)
self.private_.trace(...)
end
function SIP_TRANSPORT:recv(timeout)
local msg, err = self.private_.cnn:recv(timeout)
self:trace("RECV")
if not msg then
self:trace("RECV ERROR:", msg, err)
return nil, err
end
self:trace("RECV DONE:", msg)
return SipCreateMsg(msg)
end
function SIP_TRANSPORT:recvfrom(timeout)
local msg, err, port = self.private_.cnn:recvfrom(timeout)
self:trace("RECVFROM")
if not msg then
self:trace("RECV ERROR:", msg, err)
return nil, err
end
self:trace("RECV DONE:", msg, err, port)
return SipCreateMsg(msg), err, port
end
local function is_resp_match(req,resp)
local req_cseq = assert(req:getCSeq())
local req_cid = assert(req:getHeader('Call-ID'))
local resp_cseq = resp:getCSeq()
if type(resp_cseq) ~= 'number' then
return nil, 'wrong cseq'
end
if resp_cseq < req_cseq then -- old response
return nil, 'old cseq'
end
if resp:getHeader('Call-ID') ~= req_cid then
return nil, 'wrong call-id'
end
return true
end
function SIP_TRANSPORT:recv_response(timeout, req)
local rtimer
if timeout then
rtimer = timer:new()
rtimer:set_interval(timeout * 1000)
rtimer:start()
end
while true do
local resp, err = self:recv(timeout)
if not resp then return nil, err end
if not resp:getResponseLine() then
self:trace("INVALID SIP MESSAGE:", resp)
return nil, "bad_sip_response", resp
end
if not req then
return resp
end
local ok, err = is_resp_match(req, resp)
if ok then return resp end
self:trace("WRONG RESPONSE:", resp)
if timeout then
if rtimer:rest() == 0 then
return nil, 'timeout'
end
timeout = rtimer:rest() / 1000
end
end
end
-- timeout èñïîëüçóåòñÿ äëÿ îæèäàíèÿ êàæäîãî î÷åðåäíîãî
-- ñîîáùåíèÿ. Îáùååå âðåìÿ ìîæåò ïðåâûøàòü timeout
function SIP_TRANSPORT:recv_not_1xx(timeout, req)
local resp,err,msg
while true do
resp,err,msg = self:recv_response(timeout, req)
if not resp then return nil,err,msg end
if not resp:isResponse1xx() then return resp end
end
end
function SIP_TRANSPORT:send(timeout, msg)
self:trace("SEND: ", msg)
local ok, err = self.private_.cnn:send(timeout, tostring(msg))
self:trace("SEND RESULT:", ok, err)
return ok, err
end
function SIP_TRANSPORT:sendto(timeout, msg, host, port)
self:trace("SEND: ", msg)
local ok, err = self.private_.cnn:sendto(timeout, tostring(msg), host, port)
self:trace("SEND RESULT:", ok, err)
return ok, err
end
---
-- @return
function SIP_TRANSPORT:send_recv_T1(msg)
local TimerA=self.private_.timers.T1
local TimerB=self.private_.timers.T2
while true do
local ok, err = self:send(nil, msg) -- infinity
if not ok then return nil, err end
local resp, raw_msg
resp, err, raw_msg = self:recv_response(TimerA, msg)
if resp then return resp
elseif err ~= 'timeout' then
return nil, err, raw_msg
end
TimerA = TimerA * 2
if TimerA > TimerB then return nil, 'timeout' end
end
end
-- timeout - äëÿ îæèäàíèÿ îêîí÷àòåëüíîãî îòâåòà ïîñëå ïðåäâàðèòåëüíîãî
-- åñëè áûë ïðåäâàðèòåëüíûé îòâåò
function SIP_TRANSPORT:send_recv_T1_not_1xx(timeout, msg)
local resp, err, msg = self:send_recv_T1(msg)
if not resp then
return nil, err, msg
end
if not resp:isResponse1xx() then
return resp
end
return self:recv_not_1xx(timeout, msg)
end
end
----------------------------------------------
local _M = {}
_M.new = function(...) return SIP_TRANSPORT:new(...) end
return _M
| mit |
pazos/koreader | frontend/ui/data/keyboardlayouts/tr_keyboard.lua | 4 | 2401 | -- Start with the english keyboard layout (deep copy, to not alter it)
local tr_keyboard = require("util").tableDeepCopy(require("ui/data/keyboardlayouts/en_keyboard"))
local keys = tr_keyboard.keys
-- Insert 2 additional key at the end of first 3 rows.
-- 5th and 6th modes are from Kurdish and Azerbaijani alphabets.
-- Add Ğ, G with breve
table.insert(keys[1],
-- 1 2 3 4 5 6 7 8
{ "Ğ", "ğ", "«", "μ", "Ź", "ź", "γ", "σ", }
)
-- Add Ü, U with umlaut
table.insert(keys[1],
-- 1 2 3 4 5 6 7 8
{ "Ü", "ü", "»", "β", "Ə", "ə", "δ", "ψ", }
)
-- Add Ş, S with cedilla
table.insert(keys[2],
-- 1 2 3 4 5 6 7 8
{ "Ş", "ş", "`", "α", "Ḧ", "ḧ", "ε", "χ", }
)
-- Add İ and i, dotted I and i
table.insert(keys[2],
-- 1 2 3 4 5 6 7 8
{ "İ", "i", "₺", "θ", "Ẍ", "ẍ", "η", "τ", }
)
-- Add Ö, O with umlaut
table.insert(keys[3], 9,
-- 1 2 3 4 5 6 7 8
{ "Ö", "ö", "²", "π", "Ł", "ł", "ι", "ρ", }
)
-- Add Ç, C with cedilla
table.insert(keys[3], 10,
-- 1 2 3 4 5 6 7 8
{ "Ç", "ç", "℃", "ω", "Ř", "ř", "ν", "κ", }
)
-- Add forward slash and .com symbol to 4th row since we have lot of empty space
--and most phones do this.
table.insert(keys[4], 7,
-- 1 2 3 4 5 6 7 8
{ ".com", "/", "√", "λ", "\"", "\"", "ζ", "ξ", }
)
-- Make .com and Unicode buttons larger since we still have space.
keys[4][3].width = 1.5
keys[4][7].width = 1.5
-- Change lowercase "i" to "ı"
keys[1][8][2] = "ı"
-- Translate the "space" string
keys[4][4].label = "boşluk"
--Or remove / and move Ü to 3rd row.
--keys[4][7] = keys[3][11]
--keys[3][11] = keys[1][12]
--table.remove(keys[1], 12)
--Shrink Backspace, Shift, Sym, Unicode buttons to normal.
--keys[3][1].width = 1
--keys[3][11].width = 1
--keys[4][1].width = 1
--keys[4][3].width = 1
return tr_keyboard
| agpl-3.0 |
InfiniteRain/CS2D-AmplifiedScripting | classes/timer.lua | 1 | 5544 | -- Initializing the timer class
cas.timer = cas.class()
----------------------
-- Instance methods --
----------------------
-- Constructor. Creates a timer with a function it supposed to run.
function cas.timer:constructor(func)
-- Checks if all the passed parameters were correct.
if type(func) ~= "function" then
error("Passed \"func\" parameter is not valid. Function expected, ".. type(func) .." passed.", 2)
end
-- Assigning necessary fields.
self._funcLabel = "func"
self._repetitions = 0
local count = 1
while cas.timer._timerLabels[self._funcLabel] do
count = count + 1
self._funcLabel = "func" .. count
end
cas.timer._timerLabels[self._funcLabel] = true
self._func = func
cas.timer._debug:log("Timer \"".. tostring(self) .."\" initialized.")
end
-- Destructor.
function cas.timer:destructor()
if cas.timer._timerFuncs[self._funcLabel] and
not cas.timer._timerFuncs[self._funcLabel].repetition then -- Checks if the timer is being constantly run.
self:stop() -- If it is, stops the timer.
end
cas.timer._timerLabels[self._funcLabel] = nil
cas.timer._debug:log("Timer \"".. tostring(self) .."\" was garbage collected.")
end
-- Starts the timer with provided interval and repetitions.
function cas.timer:start(milliseconds, repetitions, ...)
-- Checks if all the passed parameters were correct.
if type(milliseconds) ~= "number" then
error("Passed \"milliseconds\" parameter is not valid. Number expected, ".. type(milliseconds) .." passed.", 2)
end
if repetitions then
if type(repetitions) ~= "number" then
error("Passed \"repetitions\" parameter is not valid. Number expected, ".. type(repetitions) .." passed.", 2)
end
end
if repetitions <= 0 then return end
-- Makes sure the timer isn't already running.
if cas.timer._timerFuncs[self._funcLabel] then
error("Timer has already started. Stop it before trying to start it again.", 2)
end
-- Makes the timer entry.
cas.timer._timerFuncs[self._funcLabel] = {
repetition = repetitions, -- Amount of repetitions left.
originalFunc = self._func, -- The original function, passed as the constructor parameter.
parameters = setmetatable({...}, {__mode = "kv"}),
func = function(label) -- Function which will be run by the timer itself, makes sure to
-- remove its entry from cas.timer._timerFuncs table once finished.
cas.timer._timerFuncs[label].originalFunc(unpack(cas.timer._timerFuncs[label].parameters))
cas.timer._timerFuncs[label].repetition = cas.timer._timerFuncs[label].repetition - 1
if cas.timer._timerFuncs[label].repetition <= 0 then
cas.timer._timerFuncs[label] = nil
cas.timer._debug:log("Timer \"".. tostring(self) .."\" has been stopped. (planned)")
end
end
}
-- Initiating the timer.
cas._cs2dCommands.timer(milliseconds, "cas.timer._timerFuncs.".. self._funcLabel ..".func", self._funcLabel, repetitions)
cas.timer._debug:log("Timer \"".. tostring(self) .."\" started with interval of ".. milliseconds .." and ".. repetitions .." repetitions.")
return self
end
-- Starts the timer with provided interval, will be run constantly until stopped.
function cas.timer:startConstantly(milliseconds, ...)
-- Checks if all the passed parameters were correct.
if type(milliseconds) ~= "number" then
error("Passed \"milliseconds\" parameter is not valid. Number expected, ".. type(milliseconds) .." passed.", 2)
end
-- Makes sure the timer isn't already running.
if cas.timer._timerFuncs[self._funcLabel] then
error("Timer has already started. Stop it before trying to start it again.", 2)
end
-- Makes the timer entry.
cas.timer._timerFuncs[self._funcLabel] = {
originalFunc = self._func,
parameters = setmetatable({...}, {__mode = "kv"}),
func = function(label)
cas.timer._timerFuncs[label].originalFunc(unpack(cas.timer._timerFuncs[label].parameters))
end
}
-- Initiating the timer.
cas._cs2dCommands.timer(milliseconds, "cas.timer._timerFuncs.".. self._funcLabel ..".func", self._funcLabel, 0)
cas.timer._debug:log("Timer \"".. tostring(self) .."\" started constantly with interval of ".. milliseconds ..".")
return self
end
-- Stops the timer.
function cas.timer:stop()
cas._cs2dCommands.freetimer("cas.timer._timerFuncs.".. self._funcLabel ..".func", self._funcLabel) -- Frees the timer.
cas.timer._timerFuncs[self._funcLabel] = nil -- Removes the timer entry.
cas.timer._debug:log("Timer \"".. tostring(self) .."\" has been stopped. (unplanned)")
return self
end
--== Getters ==--
-- Gets whether or not the timer is running.
function cas.timer:isRunning()
return cas.timer._timerFuncs[self._funcLabel] ~= nil
end
-- Gets whether or not the timer is being run constantly.
function cas.timer:isRunningConstantly()
if cas.timer._timerFuncs[self._funcLabel] then
return cas.timer._timerFuncs[self._funcLabel].repetition == nil
end
return false
end
-- Gets the current repetition.
function cas.timer:getRepetition()
if not cas.timer._timerFuncs[self._funcLabel] then
error("The timer is not running.", 2)
elseif cas.timer._timerFuncs[self._funcLabel].repetition == nil then
error("The timer is being run constantly.", 2)
end
return cas.timer._timerFuncs[self._funcLabel].repetition
end
-------------------
-- Static fields --
-------------------
cas.timer._timerLabels = {} -- Table used for timer labels.
cas.timer._timerFuncs = {} -- Table for timer entries.
cas.timer._debug = cas.debug.new(cas.color.yellow, "CAS Timer") -- Debug for timers.
--cas.timer._debug:setActive(true) | mit |
pazos/koreader | frontend/device/kobo/nickel_conf.lua | 5 | 7804 | --[[--
Access and modify values in `Kobo eReader.conf` used by Nickel.
Only PowerOptions:FrontLightLevel is currently supported.
]]
local dbg = require("dbg")
local NickelConf = {}
NickelConf.frontLightLevel = {}
NickelConf.frontLightState = {}
NickelConf.colorSetting = {}
NickelConf.autoColorEnabled = {}
local kobo_conf_path = '/mnt/onboard/.kobo/Kobo/Kobo eReader.conf'
local front_light_level_str = "FrontLightLevel"
local front_light_state_str = "FrontLightState"
local color_setting_str = "ColorSetting"
local auto_color_enabled_str = "AutoColorEnabled"
-- Nickel will set FrontLightLevel to 0 - 100
local re_FrontLightLevel = "^" .. front_light_level_str .. "%s*=%s*([0-9]+)%s*$"
-- Nickel will set FrontLightState to true (light on) or false (light off)
local re_FrontLightState = "^" .. front_light_state_str .. "%s*=%s*(.+)%s*$"
-- Nickel will set ColorSetting to 1500 - 6400
local re_ColorSetting = "^" .. color_setting_str .. "%s*=%s*([0-9]+)%s*$"
-- AutoColorEnabled is 'true' or 'false'
-- We do not support 'BedTime' (it is saved as QVariant in Nickel)
local re_AutoColorEnabled = "^" .. auto_color_enabled_str .. "%s*=%s*([a-z]+)%s*$"
local re_PowerOptionsSection = "^%[PowerOptions%]%s*"
local re_AnySection = "^%[.*%]%s*"
function NickelConf._set_kobo_conf_path(new_path)
kobo_conf_path = new_path
end
function NickelConf._read_kobo_conf(re_Match)
local value
local correct_section = false
local kobo_conf = io.open(kobo_conf_path, "r")
if kobo_conf then
for line in kobo_conf:lines() do
if string.match(line, re_PowerOptionsSection) then
correct_section = true
elseif string.match(line, re_AnySection) then
correct_section = false
elseif correct_section then
value = string.match(line, re_Match)
if value then
break
end
end
end
kobo_conf:close()
end
return value
end
--[[--
Get frontlight level.
@treturn int Frontlight level.
--]]
function NickelConf.frontLightLevel.get()
local new_intensity = NickelConf._read_kobo_conf(re_FrontLightLevel)
if new_intensity then
-- we need 0 to signal frontlight off for device that does not support
-- FrontLightState config, so don't normalize the value here yet.
return tonumber(new_intensity)
else
local fallback_fl_level = 1
assert(NickelConf.frontLightLevel.set(fallback_fl_level))
return fallback_fl_level
end
end
--[[--
Get frontlight state.
This entry will be missing for devices that do not have a hardware toggle button.
We return nil in this case.
@treturn int Frontlight state (or nil).
--]]
function NickelConf.frontLightState.get()
local new_state = NickelConf._read_kobo_conf(re_FrontLightState)
if new_state then
new_state = (new_state == "true") or false
end
return new_state
end
--[[--
Get color setting.
@treturn int Color setting.
--]]
function NickelConf.colorSetting.get()
local new_colorsetting = NickelConf._read_kobo_conf(re_ColorSetting)
if new_colorsetting then
return tonumber(new_colorsetting)
end
end
--[[--
Get auto color enabled.
@treturn bool Auto color enabled.
--]]
function NickelConf.autoColorEnabled.get()
local new_autocolor = NickelConf._read_kobo_conf(re_AutoColorEnabled)
if new_autocolor then
return (new_autocolor == "true")
end
end
--[[--
Write Kobo configuration.
@string re_Match Lua pattern.
@string key Kobo conf key.
@param value
@bool dontcreate Don't create if key doesn't exist.
--]]
function NickelConf._write_kobo_conf(re_Match, key, value, dont_create)
local kobo_conf = io.open(kobo_conf_path, "r")
local lines = {}
local found = false
local remaining
local correct_section = false
local new_value_line = key .. "=" .. tostring(value)
if kobo_conf then
local pos
for line in kobo_conf:lines() do
if string.match(line, re_AnySection) then
if correct_section then
-- found a new section after having found the correct one,
-- therefore the key was missing: let the code below add it
kobo_conf:seek("set", pos)
break
elseif string.match(line, re_PowerOptionsSection) then
correct_section = true
end
end
local old_value = string.match(line, re_Match)
if correct_section and old_value then
lines[#lines + 1] = new_value_line
found = true
break
else
lines[#lines + 1] = line
end
pos = kobo_conf:seek()
end
remaining = kobo_conf:read("*a")
kobo_conf:close()
end
if not found then
if dont_create then return true end
if not correct_section then
lines[#lines + 1] = "[PowerOptions]"
end
lines[#lines + 1] = new_value_line
end
local kobo_conf_w = assert(io.open(kobo_conf_path, "w"))
for i, line in ipairs(lines) do
kobo_conf_w:write(line, "\n")
end
if remaining then
kobo_conf_w:write(remaining)
end
kobo_conf_w:close()
return true
end
--[[--
Set frontlight level.
@int new_intensity
--]]
function NickelConf.frontLightLevel.set(new_intensity)
if type(new_intensity) ~= "number" or (not (new_intensity >= 0) and (not new_intensity <= 100)) then return end
return NickelConf._write_kobo_conf(re_FrontLightLevel,
front_light_level_str,
new_intensity)
end
dbg:guard(NickelConf.frontLightLevel, "set",
function(new_intensity)
assert(type(new_intensity) == "number",
"Wrong brightness value type (expected number)!")
assert(new_intensity >= 0 and new_intensity <= 100,
"Wrong brightness value given!")
end)
--[[--
Set frontlight state.
@bool new_state
--]]
function NickelConf.frontLightState.set(new_state)
if new_state == nil or type(new_state) ~= "boolean" then return end
return NickelConf._write_kobo_conf(re_FrontLightState,
front_light_state_str,
new_state,
-- Do not create if this entry is missing.
true)
end
dbg:guard(NickelConf.frontLightState, "set",
function(new_state)
assert(type(new_state) == "boolean",
"Wrong front light state value type (expected boolean)!")
end)
--[[--
Set color setting.
@int new_color >= 1500 and <= 6400
--]]
function NickelConf.colorSetting.set(new_color)
return NickelConf._write_kobo_conf(re_ColorSetting,
color_setting_str,
new_color)
end
dbg:guard(NickelConf.colorSetting, "set",
function(new_color)
assert(type(new_color) == "number",
"Wrong color value type (expected number)!")
assert(new_color >= 1500 and new_color <= 6400,
"Wrong colorSetting value given!")
end)
--[[--
Set auto color enabled.
@bool new_autocolor
--]]
function NickelConf.autoColorEnabled.set(new_autocolor)
return NickelConf._write_kobo_conf(re_AutoColorEnabled,
auto_color_enabled_str,
new_autocolor)
end
dbg:guard(NickelConf.autoColorEnabled, "set",
function(new_autocolor)
assert(type(new_autocolor) == "boolean",
"Wrong type for autocolor (expected boolean)!")
end)
return NickelConf
| agpl-3.0 |
pazos/koreader | spec/unit/random_spec.lua | 15 | 1031 | describe("random package tests", function()
local random
local function is_magic_char(c)
return c == "8" or c == "9" or c == "A" or c == "B"
end
setup(function()
random = require("frontend/random")
end)
it("should generate uuid without dash", function()
for i = 1, 10000 do
local uuid = random.uuid()
assert.Equals(uuid:len(), 32)
assert.Equals(uuid:sub(13, 13), "4")
assert.is_true(is_magic_char(uuid:sub(17, 17)))
end
end)
it("should generate uuid with dash", function()
for i = 1, 10000 do
local uuid = random.uuid(true)
assert.Equals(uuid:len(), 36)
assert.Equals(uuid:sub(9, 9), "-")
assert.Equals(uuid:sub(14, 14), "-")
assert.Equals(uuid:sub(19, 19), "-")
assert.Equals(uuid:sub(24, 24), "-")
assert.Equals(uuid:sub(15, 15), "4")
assert.is_true(is_magic_char(uuid:sub(20, 20)))
end
end)
end)
| agpl-3.0 |
InfiniteRain/CS2D-AmplifiedScripting | classes/color.lua | 1 | 3574 | -- Initializing the color class.
cas.color = cas.class()
--------------------
-- Static methods --
--------------------
-- Checks if the passed parameters are suitable for color representation. All the passed parameters
-- have to be numbers, being in range of 0 and 255 while not containing a floating point.
function cas.color.isCorrectFormat(...)
local numbers = {...}
local correctFormat = true
for key, value in pairs(numbers) do
if not (type(value) == "number" and value >= 0 and value <= 255 and value == math.floor(value)) then
correctFormat = false
break
end
end
return correctFormat
end
----------------------
-- Instance Methods --
----------------------
-- Constructor. Takes RGB color values as parameters to define color the instance is supposed
-- to represent.
function cas.color:constructor(red, green, blue)
if not cas.color.isCorrectFormat(red, green, blue) then
error("Passed parameters contained unsuitable values for color instance.", 2)
end
self._red = red
self._green = green
self._blue = blue
end
-- This method will be called whenever a tostring() function is called with the instance of this
-- class as an parameter. Returns a string which is used to change the message's color, in the
-- following format: "©<red><green><blue>", with necessary zeros added.
function cas.color:__tostring()
return string.format("%c%03d%03d%03d", 169, self._red, self._green, self._blue)
end
--== Setters ==--
-- Sets the color fields of the instance.
function cas.color:setRGB(red, green, blue)
if not cas.color.isCorrectFormat(red, green, blue) then
error("Passed parameters contained unsuitable values for color instance.", 2)
end
self._red = red
self._green = green
self._blue = blue
end
-- Sets the red color field of the instance.
function cas.color:setRed(red)
if not cas.color.isCorrectFormat(red) then
error("Passed parameter contained unsuitable value for color instance.", 2)
end
self._red = red
end
-- Sets the green color field of the instance.
function cas.color:setGreen(green)
if not cas.color.isCorrectFormat(red) then
error("Passed parameter contained unsuitable value for color instance.", 2)
end
self._green = green
end
-- Sets the blue color field of the instance.
function cas.color:setBlue(blue)
if not cas.color.isCorrectFormat(red) then
error("Passed parameter contained unsuitable value for color instance.", 2)
end
self._blue = blue
end
--== Getters ==--
-- Gets the color fields of the instance.
function cas.color:getRGB()
return self._red, self._green, self._blue
end
-- Gets the red color field of the instance.
function cas.color:getRed()
return self._red
end
-- Gets the green color field of the instance.
function cas.color:getGreen()
return self._green
end
-- Gets the blue color field of the instance.
function cas.color:getBlue()
return self._blue
end
-------------------
-- Static fields --
-------------------
--== Preset color values for ease of access ==--
cas.color.white = cas.color.new(255, 255, 255)
cas.color.lightGray = cas.color.new(196, 196, 196)
cas.color.gray = cas.color.new(128, 128, 128)
cas.color.darkGray = cas.color.new(64, 64, 64)
cas.color.black = cas.color.new(0, 0, 0)
cas.color.red = cas.color.new(255, 0, 0)
cas.color.pink = cas.color.new(255, 0, 128)
cas.color.orange = cas.color.new(255, 128, 0)
cas.color.yellow = cas.color.new(255, 255, 0)
cas.color.green = cas.color.new(0, 255, 0)
cas.color.magenta = cas.color.new(255, 0, 255)
cas.color.cyan = cas.color.new(0, 255, 255)
cas.color.blue = cas.color.new(0, 0, 255) | mit |
16cameronk/MyoScripts | PointerDebugOut.lua | 2 | 1822 | scriptId = 'com.jakechapeskie.pointer'
minMyoConnectVersion ='0.8.0'
scriptDetailsUrl = 'https://github.com/JakeChapeskie/MyoScripts'
scriptTitle = 'Pointer Connector'
myo.debug("Hold a fist and move around to see debug output")
function onForegroundWindowChange(app, title)
return true
end
function getMyoYawDegrees()
local yawValue = math.deg(myo.getYaw())
return yawValue
end
function getMyoPitchDegrees()
local PitchValue = math.deg(myo.getPitch())
return PitchValue
end
function degreeDiff(value, base)
local diff = value - base
if diff > 180 then
diff = diff - 360
elseif diff < -180 then
diff = diff + 360
end
return diff
end
PITCH_MOTION_THRESHOLD = 7 -- degrees
YAW_MOTION_THRESHOLD = 7 -- degrees
-- Set how the Myo Armband handles locking
myo.setLockingPolicy("none")
function onPeriodic()
local now = myo.getTimeMilliseconds()
if moveActive then
local relativeYaw = degreeDiff(getMyoYawDegrees(), yawReference)
if math.abs(relativeYaw)> YAW_MOTION_THRESHOLD then
if relativeYaw < 0 then
myo.debug("left")
else
myo.debug("right")
end
end
local relativePitch = degreeDiff(getMyoPitchDegrees(), pitchReference)
if math.abs(relativePitch)> PITCH_MOTION_THRESHOLD then
if relativePitch < 0 then
myo.debug("DOWN")
else
myo.debug("UP")
end
end
end
end
function activeAppName()
return activeApp
end
function onActiveChange(isActive)
if not isActive then
enabled = false
end
end
function onPoseEdge(pose, edge)
--myo.debug(pose)
local now = myo.getTimeMilliseconds()
if pose == "fist" then
myo.debug("RESET")
moveActive = edge == "on"
yawReference = getMyoYawDegrees()
pitchReference=getMyoPitchDegrees()
moveSince = now
end
end | mit |
ZipFile/vlc | share/lua/intf/dumpmeta.lua | 98 | 2125 | --[==========================================================================[
dumpmeta.lua: dump a file's meta data on stdout/stderr
--[==========================================================================[
Copyright (C) 2010 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
--[[ to dump meta data information in the debug output, run:
vlc -I luaintf --lua-intf dumpmeta coolmusic.mp3
Additional options can improve performance and output readability:
-V dummy -A dummy --no-video-title --no-media-library -q
--]]
local item
repeat
item = vlc.input.item()
until (item and item:is_preparsed())
-- preparsing doesn't always provide all the information we want (like duration)
repeat
until item:stats()["demux_read_bytes"] > 0
vlc.msg.info("name: "..item:name())
vlc.msg.info("uri: "..vlc.strings.decode_uri(item:uri()))
vlc.msg.info("duration: "..tostring(item:duration()))
vlc.msg.info("meta data:")
local meta = item:metas()
if meta then
for key, value in pairs(meta) do
vlc.msg.info(" "..key..": "..value)
end
else
vlc.msg.info(" no meta data available")
end
vlc.msg.info("info:")
for cat, data in pairs(item:info()) do
vlc.msg.info(" "..cat)
for key, value in pairs(data) do
vlc.msg.info(" "..key..": "..value)
end
end
vlc.misc.quit()
| gpl-2.0 |
zaeem55/meme | plugins/ar-help(2).lua | 1 | 4255 | do
local function run(msg, matches)
if is_momod(msg) and matches[1]== "مساعدة" then
return [[ ❣ رفع اداري >/: رفع ادمن في المجموعة
❣ تنزيل ادري >/ : حذف ادمن في المجوعة
❣ رفع ادمن >/ : رفع ادمن
❣ تنزيل ادمن >/ : حذف ادمن
❣ الادمنيه >/: لاظهار ادمنية المجموعة
❣ الاداريين >/: اضهار اداريين المجموعه
ـ ➖➖➖⚠️✅➖➖
✔️ قائمة الحظر… 😉والطرد.🏃🚪
❣ بلوك : لطرد العضو
❣ /دفره : لطرد العضو بالرد
❣ حظر : لحظر العظر
❣ الغاء الحظر : فتح الخظر عن العضو
❣ مغادره : للخروج من المجموعة
❣ كتم : لتفعيل الصمت على احد الاعضاء
❣ كتم : الغاء الصمت على العضو
❣ منع كلمه : لحضر الكلمة ب مجموعه
❣ الغاء المنع : لفتح حضر الكلمة
❣ قائمه المنع : لعرض الكلمات المحظورة
ـ ➖➖➖🔴☑️➖➖
✔️ الاوامر الايدي والمعلومات. ✅🔰
❣ ايدي : لاظهار ايدي المجموعه
❣ ايدي : لاظهار ايدي الشخص بلرد
❣ معلوماتي : اضهار المعلومات الخاصه بك
❣ معلومات المجموعه : اضهار معلومات بالمجموعة
❣ الاعدادات : اضهار اعدادات المجموعة
❣ اعدادات الوسائط : اضهار اعادادات الوسائط
ـ ➖➖🔶➖➖🔷➖
✔️ اوامر تحكم المجموعه .🔃💢
❣ القوانين : لاضهار القوانين
❣ ضع قوانين : لاظافة القوانين
❣ ضع وصف : لاظافه وصف حول
❣ ضع صوره : لوضع صورة
❣ ضع اسم : لوضع اسم
❣ ضع معرف >/: لوضع معرف للكروب
❣ تغير الرابط : لصنع الرابط او تغيرة
❣ الرابط : لضهور الرابط ب المجموعه
❣ الرابط خاص : للحصول على الرابط في الخاص
ـ🔸➖🔹➖🔸➖🔹➖
✔️ آوامر امان المجموعه...⚠️💢
❣ قفل الاضافه : لمنع الاضافه ب المجموعه
❣ قفل الاضافه : لسماح الاضافه ب ===
❣ قفل الدردشه : لمنع الدردشه للمجموعه
❣ فتح الدردشه : للسماح للدردشه للمجموعه
❣ قفل الصور : لمنع إرسال الصور
❣ فتح الصور : للسماح بإرسال الصور
❣ قفل الصوت : لمنع البصمات
❣ فتح الصوت : للسماح بإرسال البصمات
❣ قفل الفيديو : لمنع ارسال فديو
❣ فتح الفيديو : للسماح بإرسال فديو
❣ قفل الروابط : لمنع الروابط
❣ فتح الروابط : للسماح بإرسال روابط
❣ قفل التكرار : لمنع التكرار
❣ فتح التكرار : للسماح بلتكرار
❣ قفل الملصقات : لمنع الملصقات
❣ فتح الملصقات : للسماح بلملصقات
❣ قفل الصور المتحركه : لمنع الصور المتحركة
❣ فتح الصور المتحركه : للسماح بالصور المتحركة
❣ قفل الفايلات : لمنع ارسال الملفات
❣ فتح الفايلات : للسماح بإرسال الملفات
❣ قفل الكلايش : لمنع الكلايش الطويلة
❣ فتح الكلايش : للسماح بلكلايش الطويلة
❣ قفل الاضافه الجماعيه : لمنع الاعضاء من الاضافه
❣ فتح الاضافه الجماعيه : لسماح للاعضاء بالاضافه
❣ قفل اعاده توجيه : لمنع اعاديت توجيه
❣ فتح اعاده توجيه : للسماح باعادت توجيه
ـ🔸➖🔹➖🔸➖🔹➖
#المطور @ofuck
]]
end
if not is_momod(msg) then
return "للمشرفين فقط 😎🖕🏿"
end
end
return {
description = "Help list",
usage = "Help list",
patterns = {
"(مساعدة)"
},
run = run
}
end
| gpl-2.0 |
derElektrobesen/tntlua | notifications.lua | 5 | 6485 | --
-- A system to store and serve notifications in a social network.
-- Stores an association [user_id <-> list of notifications].
--
-- Each notification describes a recent event a user should get
-- informed about, and is represented by a notifcation_id.
--
-- Notification id is a fixed length string.
--
-- Notifications can belong to different types (photo evaluations,
-- unread messages, friend requests).
--
-- For each type, a FIFO queue of last ring_max notifications
-- is maintained, as well as the count of "unread" notifications.
--
-- The number of notification types can change.
--
-- The following storage schema is used:
--
-- space:
-- user_id total_unread type1_unread_count type1_ring
-- type2_unread_count type2_ring
-- type3_unread_count type3_ring
-- ....
-- Supported operations include:
--
-- notification_push(user_id, ring_no, notification_id)
-- - pushes a notification into the ring buffer associated with the
-- type, unless it's already there, incrementing the count of unread
-- notifications associated with the given ring, as well as the total
-- count. However, if unread_count is above ring_max, counters
-- are not incremented.
-- ring_no is indexed from 0 to ring_max - 1
--
-- notification_read(user_id, ring_no)
-- - read the notifications in the given ring.
-- This substracts the ring unread_count from the total
-- unread_count, and drops the ring unread_count to 0.
--
-- notification_total_unread_count(user_id)
-- - gets the total unread count
--
-- Removing duplicates
-- -------------------
--
-- On top of just maintaining FIFO queues for each type,
-- this set of Lua procedures ensures that each notification
-- in each FIFO is unique. When inserting a new notification id,
-- the FIFO is checked first whether the same id is already there.
-- If it's present in the queue, it's simply moved to the
-- beginning of the line, no duplicate is inserted.
-- Unread counters are incremented only if the old id was
-- already read.
-- namespace which stores all notifications
local space_no = 0
-- description of notification types
-- these ids describe notification id tail offset used by is_duplicate()
local notification_types = { 0, 0, 4, 0, 0 }
-- how many notifications of each type the associated
-- circular buffer keeps
local ring_max = 20
-- field index of the first ring in the tuple.
-- field 0 - user id, field 1 - total unread count, hence
local ring0_fieldno = 2
-- Find the tuple associated with user id or create a new
-- one.
function notification_find_or_insert(user_id)
local tuple = box.select(space_no, 0, user_id)
if tuple ~= nil then
return tuple
end
-- create an empty ring for each notification type
local rings = {}
for i = 1, #notification_types do
table.insert(rings, 0) -- unread count - 0
table.insert(rings, "") -- notification list - empty
end
box.insert(space_no, user_id, 0, unpack(rings))
-- we can't use the tuple returned by box.insert, since it could
-- have changed since.
return box.select(space_no, 0, user_id)
end
function notification_total_unread_count(user_id)
return box.unpack('i', notification_find_or_insert(user_id)[1])
end
function notification_unread_count(user_id, ring_no)
-- calculate the field no of the associated ring
local fieldno = ring0_fieldno + tonumber(ring_no) * 2
return box.unpack('i', notification_find_or_insert(user_id)[fieldno])
end
--
-- Find if id is already present in the given ring
-- return true and id offset when found,
-- false len(ring) when not found
--
local function is_duplicate(ring, id, tail_offset)
id_len = #id
id = string.sub(id, 1, id_len - tail_offset)
for i=1, #ring, id_len do
n_id = string.sub(ring, i, i+id_len-1 - tail_offset)
if n_id == id then
-- we're going to insert a new notifiation,
-- return the old notification offset relative to
-- the new field size
return true, i - 1 + id_len
end
end
return false, ring_max * id_len
end
--
-- Append a notification to its ring (one ring per notification type)
-- Update 'unread' counters, unless they are already at their max.
--
function notification_push(user_id, ring_no, id)
local fieldno = ring0_fieldno + tonumber(ring_no) * 2
-- insert the new id at the beginning of ring, truncate the tail
-- use box SPLICE operation for that
local format = ":p:p"
local args = { fieldno + 1, box.pack("ppp", 0, 0, id), fieldno + 1 }
--
-- check whether a duplicate id is already present
--
local tuple = notification_find_or_insert(user_id)
local _, dup_offset = is_duplicate(tuple[fieldno+1], id,
notification_types[ring_no+1])
--
-- if duplicate is there, dup_offset points at it.
-- otherwise it points at ring tail
--
table.insert(args, box.pack("ppp", dup_offset, #id, ""))
local unread_count = box.unpack('i', tuple[fieldno])
-- check if the counters need to be updated
if unread_count < ring_max and dup_offset > unread_count * #id then
-- prepend ++total_unread_count, ++unread_count to our update operation
format = "+p+p"..format
local args1 = args
args = { 1, 1, fieldno, 1 }
for _, v in ipairs(args1) do table.insert(args, v) end
end
return box.update(space_no, user_id, format, unpack(args))
end
-- Read a notification.
-- Return the total unread count, all other unread counts,
-- and ring data in question.
function notification_read(user_id, ring_no)
local unread_count = notification_unread_count(user_id, ring_no)
local fieldno = ring0_fieldno + tonumber(ring_no) * 2
local tuple = box.update(space_no, user_id, "-p-p",
1, unread_count, fieldno, unread_count)
local return_fields = {}
local k, v = tuple:next()
local k, v = tuple:next(k) -- skip user id
table.insert(return_fields, v) -- total unread count
k, v = tuple:next(k) -- now at the first ring
while k ~= nil do
table.insert(return_fields, v) -- insert unread count
k, v = tuple:next(k)
if k ~= nil then
k, v = tuple:next(k) -- skip this ring data
end
end
table.insert(return_fields, tuple[fieldno+1]) -- insert ring data
return return_fields
end
| bsd-2-clause |
dangersuperbot/super_boomrange | plugins/delmsgs.lua | 3 | 1887 | 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..'" پیام اخیر سوپر گروه حذف شد', ok_cb, false)
else
send_msg(extra.chatid, 'ℹ️ تمام پیام های سوپر گروه حذف شد', ok_cb, false)
end
end
local function allhistory(extra, suc, result)
for i=1, #result do
delete_msg(result[i].id, ok_cb, false)
end
if #result == 99 then
get_history(msg.to.peer_id, 100, allhistory , {chatid = msg.to.peer_id})
else
send_msg(extra.chatid, 'ℹ️ تمام پیام های سوپر گروه حذف شد', ok_cb, false)
end
end
local function run(msg, matches)
if matches[1] == 'delmsg' then
if permissions(msg.from.id, msg.to.id, "settings") then
if msg.to.type == 'channel' then
if tonumber(matches[2]) > 99 or tonumber(matches[2]) < 1 then
return '🚫 '..lang_text(msg.to.id, 'require_down100')
end
delete_msg(msg.id, ok_cb, false)
get_history(msg.to.peer_id, matches[2] + 1 , history , {chatid = msg.to.peer_id, con = matches[2]})
else
return '🚫 '..lang_text(msg.to.id, 'onlychannel')
end
else
return '🚫 '..lang_text(msg.to.id, 'require_mod')
end
elseif matches[1] == 'clear' then
if matches[2] == 'msgs' then
if permissions(msg.from.id, msg.to.id, "settings") then
if msg.to.type == 'channel' then
delete_msg(msg.id, ok_cb, false)
get_history(msg.to.peer_id, 100, allhistory , {chatid = msg.to.peer_id})
else
return '🚫 '..lang_text(msg.to.id, 'onlychannel')
end
else
return '🚫 '..lang_text(msg.to.id, 'require_mod')
end
end
end
end
return {
patterns = {
'^[!/#](remmsg) (%d*)$',
'^[!/#](clear) (msgs)$'
},
run = run
}
| gpl-2.0 |
szszss/CharmingTremblePlus | build/premake4.lua | 1 | 1308 | solution "CharmingTremblePlus"
configurations {"Release", "Debug"}
configuration "Release"
flags { "Optimize", "EnableSSE", "Unicode"}
configuration "Debug"
flags { "Symbols", "NoEditAndContinue" ,"Unicode"}
defines { "DEBUG"}
configuration{}
if os.is("Linux") then
if os.is64bit() then
platforms {"x64"}
else
platforms {"x32"}
end
else
platforms {"x32", "x64"}
end
if _ACTION == "xcode4" then
xcodebuildsettings
{
'ARCHS = "$(ARCHS_STANDARD_32_BIT) $(ARCHS_STANDARD_64_BIT)"',
'CLANG_CXX_LANGUAGE_STANDARD = "gnu++0x"',
'VALID_ARCHS = "x86_64 i386"',
}
end
act = ""
if _ACTION then
act = _ACTION
end
configuration {"x32"}
suffix = "_" .. act
configuration "x64"
suffix = "_" .. act .. "_64"
configuration {"x64", "debug"}
suffix = "_" .. act .. "_x64_debug"
configuration {"x64", "release"}
suffix = "_" .. act .. "_x64_release"
configuration {"x32", "debug"}
suffix = "_" .. act .. "_debug"
configuration{}
targetsuffix (suffix)
targetdir "../bin"
language "C++"
location("./" .. act)
--dofile("premakeHack.lua")
tbox_float = true
tbox_platform = true
tbox_asio = true
tbox_xml = true
tbox_charset = true
include "../src/"
--include "../lib/glfw/"
include "../lib/sdl/"
include "../lib/stb/"
--include "../lib/tbox/" | mit |
ZerothAngel/FtDScripts | ai/naval-ai-header.lua | 1 | 3118 | -- NAVAL AI
-- Target ranges that determine behavior
MinDistance = 300
MaxDistance = 500
-- Attack behavior (MinDistance < target range < MaxDistance)
-- All angles are relative to the target's bearing. So 0 heads
-- straight toward the target and 180 is straight away from it.
AttackAngle = 80
-- Drive fraction from -1 to 1.
-- If you have an urge to set this to 0, look instead at the
-- AttackDistance + AttackReverse options.
AttackDrive = 1
-- Evasion settings have two values:
-- The magnitude of evasive maneuvers, in degrees
-- And a time scale. Generally <1.0 works best,
-- smaller means slower.
-- Set to nil to disable, e.g. AttackEvasion = nil
AttackEvasion = { 10, .125 }
-- If set, it should be between MinDistance and MaxDistance.
-- Only applies when MinDistance < target range < MaxDistance.
-- To have any effect, AttackAngle should NOT be 90 degrees.
AttackDistance = nil
-- PID for adjusting AttackAngle when near AttackDistance.
-- Effective AttackAngle will be scaled between AttackAngle and
-- 180 - AttackAngle depending on output of PID.
AttackPIDConfig = {
Kp = .5,
Ti = 5,
Td = .1,
}
-- If true, then instead of flipping AttackAngle, AttackDrive will
-- be negated (so presumably your vehicle will go in reverse). The PID
-- above will be applied to the throttle instead.
AttackReverse = false
-- Closing behavior (target range > MaxDistance)
-- ClosingAngle should be <90 to actually close with the target.
ClosingAngle = 40
ClosingDrive = 1
ClosingEvasion = { 30, .25 }
-- Escape behavior (target range < MinDistance)
-- EscapeAngle should be >90 to actually head away from the target.
EscapeAngle = 120
EscapeDrive = 1
EscapeEvasion = { 20, .25 }
-- Air raid evasion
-- Overrides current evasion settings when target is
-- above a certain elevation (i.e. altitude relative to ground)
AirRaidAboveElevation = 50
AirRaidEvasion = { 40, .25 }
-- Preferred side to face toward enemy.
-- 1 = Starboard (right)
-- -1 = Port (left)
-- nil = No preference (will pick closest side)
PreferredBroadside = nil
-- If true, the ship will perform attack runs and bounce between
-- MinDistance and MaxDistance.
-- "Closing" settings are used if target range > MaxDistance
-- "Attack" settings are used until MinDistance is reached
-- "Escape" settings are then used until MaxDistance is reached,
-- then the next attack run is started.
AttackRuns = false
-- Forces an attack run after this many seconds. For times when
-- the target is faster than your ship, so your ship won't be
-- stuck constantly trying to escape.
ForceAttackTime = 30
-- Normally the attack run is ended once MinDistance is reached.
-- However this setting ensures that at least this many seconds were spent
-- attacking (either normally or forced). Useful against faster targets...
-- I guess. For best results, should take into account the time it takes to
-- rotate to the proper angle.
MinAttackTime = 10
-- Evasion values to use when in formation mode.
-- Can either explicitly set values or just copy one of the above.
FleetMoveEvasion = AttackEvasion
-- Return-to-origin settings
ReturnToOrigin = true
| mit |
demolitions/conkyurlio | planes/data.lua | 1 | 2805 | function initData()
data = {};
data["cpu"] = {};
for i = 1,config["cpunr"] do
data["cpu_" .. i] = {};
end
data["mem"] = {};
data["swp"] = {};
for key,value in pairs(config["hdd"]) do
data["hdd_" .. key] = {};
end
data["netdn"] = {};
data["netup"] = {};
-- print("AFTER INIT: " .. #data["cpu"]);
return data;
end
function readData()
data = initData();
-- print("BEFORE READ: " .. #data["cpu"]);
local datafile = io.open(config["datafile"], "r");
if datafile == nil then
print "nofile";
table.insert(data["cpu"], 0);
for i = 1,config["cpunr"] do
table.insert(data["cpu_" .. i], 0);
end
table.insert(data["mem"], 0);
table.insert(data["swp"], 0);
for key,value in pairs(config["hdd"]) do
table.insert(data["hdd_" .. key], 0);
end
table.insert(data["netdn"], 0);
table.insert(data["netup"], 0);
else
for line in datafile:lines(config["datafile"]) do
for key,tab in pairs(data) do
if (string.sub(line,0,string.len(key .. ":")) == key .. ":") then
-- if(key == "cpu") then
-- print("BEFORE LOAD: " .. #data["cpu"]);
-- end
table.insert(data[key], tonumber(trim(string.sub(line,string.len(key .. ": ")))))
-- if(key == "cpu") then
-- print("AFTER LOAD: " .. #data["cpu"]);
-- end
end
end
end
datafile:close(datafile);
end
-- print("AFTER READ: " .. #data["cpu"]);
return data;
end
function gatherData()
data = readData();
-- print("BEFORE DATA: " .. #data["cpu"]);
-- CPU LOAD
table.insert(data["cpu"], tonumber(trim(conky_parse("${cpu}"))));
for i = 1,config["cpunr"] do
table.insert(data["cpu_" .. i],tonumber(trim(conky_parse("${cpu cpu".. i .."}"))));
end
-- MEMORY USAGE
table.insert(data["mem"],tonumber(trim(conky_parse("${memperc}"))));
table.insert(data["swp"],tonumber(trim(conky_parse("${swapperc}"))));
-- NET USAGE
local ethname = conky_parse("${gw_iface}");
table.insert(data["netup"],tonumber(trim(conky_parse("${upspeedf " .. ethname .. "}"))));
table.insert(data["netdn"],tonumber(trim(conky_parse("${downspeedf " .. ethname .. "}"))));
-- FILESYSTEM USAGE
for key,value in pairs(config["hdd"]) do
table.insert(data["hdd_" .. key], tonumber(trim(conky_parse("${fs_used_perc " .. value .. "}"))));
end
-- print("AFTER DATA: " .. #data["cpu"]);
writeData(data)
return data;
end
function writeData(data)
-- print("BEFORE SAVE: " .. #data["cpu"]);
local datafile = io.open(config["datafile"], "w");
for key,tab in pairs(data) do
while (#tab > tonumber(config["samples"])) do
table.remove(tab,1);
end
for id,value in pairs(tab) do
local str = key .. ":" .. value .. "\n";
datafile:write(str);
end
end
datafile:close();
-- print("AFTER SAVE: " .. #data["cpu"]);
end
| gpl-2.0 |
pazos/koreader | spec/unit/size_spec.lua | 13 | 1291 | describe("Size module", function()
local Size
setup(function()
require("commonrequire")
Size = require("ui/size")
end)
describe("should get size", function()
it("for window border", function()
assert.is_true(Size.border.window >= 1)
end)
end)
it("should be nil for non-existent property", function()
assert.is_nil(Size.supercalifragilisticexpialidocious)
assert.is_nil(Size.border.supercalifragilisticexpialidocious)
end)
it("should fail for non-existent property when debug is activated", function()
local dbg = require("dbg")
dbg:turnOn()
Size = package.reload("ui/size")
local supercalifragilisticexpialidocious1 = function()
return Size.supercalifragilisticexpialidocious
end
local supercalifragilisticexpialidocious2 = function()
return Size.border.supercalifragilisticexpialidocious
end
assert.has_error(supercalifragilisticexpialidocious1, "Size: this property does not exist: Size.supercalifragilisticexpialidocious")
assert.has_error(supercalifragilisticexpialidocious2, "Size: this property does not exist: Size.border.supercalifragilisticexpialidocious")
dbg:turnOff()
end)
end)
| agpl-3.0 |
NatWeiss/RGP | src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/FadeOutTRTiles.lua | 7 | 2556 |
--------------------------------
-- @module FadeOutTRTiles
-- @extend TiledGrid3DAction
-- @parent_module cc
--------------------------------
-- brief Show the tile at specified position.<br>
-- param pos The position index of the tile should be shown.
-- @function [parent=#FadeOutTRTiles] turnOnTile
-- @param self
-- @param #vec2_table pos
-- @return FadeOutTRTiles#FadeOutTRTiles self (return value: cc.FadeOutTRTiles)
--------------------------------
-- brief Hide the tile at specified position.<br>
-- param pos The position index of the tile should be hide.
-- @function [parent=#FadeOutTRTiles] turnOffTile
-- @param self
-- @param #vec2_table pos
-- @return FadeOutTRTiles#FadeOutTRTiles self (return value: cc.FadeOutTRTiles)
--------------------------------
-- brief Show part of the tile.<br>
-- param pos The position index of the tile should be shown.<br>
-- param distance The percentage that the tile should be shown.
-- @function [parent=#FadeOutTRTiles] transformTile
-- @param self
-- @param #vec2_table pos
-- @param #float distance
-- @return FadeOutTRTiles#FadeOutTRTiles self (return value: cc.FadeOutTRTiles)
--------------------------------
-- brief Calculate the percentage a tile should be shown.<br>
-- param pos The position index of the tile.<br>
-- param time The current percentage of the action.<br>
-- return Return the percentage the tile should be shown.
-- @function [parent=#FadeOutTRTiles] testFunc
-- @param self
-- @param #size_table pos
-- @param #float time
-- @return float#float ret (return value: float)
--------------------------------
-- brief Create the action with the grid size and the duration.<br>
-- param duration Specify the duration of the FadeOutTRTiles action. It's a value in seconds.<br>
-- param gridSize Specify the size of the grid.<br>
-- return If the creation success, return a pointer of FadeOutTRTiles action; otherwise, return nil.
-- @function [parent=#FadeOutTRTiles] create
-- @param self
-- @param #float duration
-- @param #size_table gridSize
-- @return FadeOutTRTiles#FadeOutTRTiles ret (return value: cc.FadeOutTRTiles)
--------------------------------
--
-- @function [parent=#FadeOutTRTiles] clone
-- @param self
-- @return FadeOutTRTiles#FadeOutTRTiles ret (return value: cc.FadeOutTRTiles)
--------------------------------
--
-- @function [parent=#FadeOutTRTiles] update
-- @param self
-- @param #float time
-- @return FadeOutTRTiles#FadeOutTRTiles self (return value: cc.FadeOutTRTiles)
return nil
| mit |
joaofvieira/luci | modules/luci-base/luasrc/model/uci.lua | 49 | 4995 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local os = require "os"
local uci = require "uci"
local util = require "luci.util"
local table = require "table"
local setmetatable, rawget, rawset = setmetatable, rawget, rawset
local require, getmetatable = require, getmetatable
local error, pairs, ipairs = error, pairs, ipairs
local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack
-- The typical workflow for UCI is: Get a cursor instance from the
-- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.),
-- save the changes to the staging area via Cursor.save and finally
-- Cursor.commit the data to the actual config files.
-- LuCI then needs to Cursor.apply the changes so deamons etc. are
-- reloaded.
module "luci.model.uci"
cursor = uci.cursor
APIVERSION = uci.APIVERSION
function cursor_state()
return cursor(nil, "/var/state")
end
inst = cursor()
inst_state = cursor_state()
local Cursor = getmetatable(inst)
function Cursor.apply(self, configlist, command)
configlist = self:_affected(configlist)
if command then
return { "/sbin/luci-reload", unpack(configlist) }
else
return os.execute("/sbin/luci-reload %s >/dev/null 2>&1"
% table.concat(configlist, " "))
end
end
-- returns a boolean whether to delete the current section (optional)
function Cursor.delete_all(self, config, stype, comparator)
local del = {}
if type(comparator) == "table" then
local tbl = comparator
comparator = function(section)
for k, v in pairs(tbl) do
if section[k] ~= v then
return false
end
end
return true
end
end
local function helper (section)
if not comparator or comparator(section) then
del[#del+1] = section[".name"]
end
end
self:foreach(config, stype, helper)
for i, j in ipairs(del) do
self:delete(config, j)
end
end
function Cursor.section(self, config, type, name, values)
local stat = true
if name then
stat = self:set(config, name, type)
else
name = self:add(config, type)
stat = name and true
end
if stat and values then
stat = self:tset(config, name, values)
end
return stat and name
end
function Cursor.tset(self, config, section, values)
local stat = true
for k, v in pairs(values) do
if k:sub(1, 1) ~= "." then
stat = stat and self:set(config, section, k, v)
end
end
return stat
end
function Cursor.get_bool(self, ...)
local val = self:get(...)
return ( val == "1" or val == "true" or val == "yes" or val == "on" )
end
function Cursor.get_list(self, config, section, option)
if config and section and option then
local val = self:get(config, section, option)
return ( type(val) == "table" and val or { val } )
end
return nil
end
function Cursor.get_first(self, conf, stype, opt, def)
local rv = def
self:foreach(conf, stype,
function(s)
local val = not opt and s['.name'] or s[opt]
if type(def) == "number" then
val = tonumber(val)
elseif type(def) == "boolean" then
val = (val == "1" or val == "true" or
val == "yes" or val == "on")
end
if val ~= nil then
rv = val
return false
end
end)
return rv
end
function Cursor.set_list(self, config, section, option, value)
if config and section and option then
return self:set(
config, section, option,
( type(value) == "table" and value or { value } )
)
end
return false
end
-- Return a list of initscripts affected by configuration changes.
function Cursor._affected(self, configlist)
configlist = type(configlist) == "table" and configlist or {configlist}
local c = cursor()
c:load("ucitrack")
-- Resolve dependencies
local reloadlist = {}
local function _resolve_deps(name)
local reload = {name}
local deps = {}
c:foreach("ucitrack", name,
function(section)
if section.affects then
for i, aff in ipairs(section.affects) do
deps[#deps+1] = aff
end
end
end)
for i, dep in ipairs(deps) do
for j, add in ipairs(_resolve_deps(dep)) do
reload[#reload+1] = add
end
end
return reload
end
-- Collect initscripts
for j, config in ipairs(configlist) do
for i, e in ipairs(_resolve_deps(config)) do
if not util.contains(reloadlist, e) then
reloadlist[#reloadlist+1] = e
end
end
end
return reloadlist
end
-- curser, means it the parent unloads or loads configs, the sub state will
-- do so as well.
function Cursor.substate(self)
Cursor._substates = Cursor._substates or { }
Cursor._substates[self] = Cursor._substates[self] or cursor_state()
return Cursor._substates[self]
end
local _load = Cursor.load
function Cursor.load(self, ...)
if Cursor._substates and Cursor._substates[self] then
_load(Cursor._substates[self], ...)
end
return _load(self, ...)
end
local _unload = Cursor.unload
function Cursor.unload(self, ...)
if Cursor._substates and Cursor._substates[self] then
_unload(Cursor._substates[self], ...)
end
return _unload(self, ...)
end
| apache-2.0 |
bradchesney79/2015BeastRouterProject | openwrt/unsquash/squashfs-root/usr/lib/lua/luci/model/uci.lua | 49 | 4995 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
local os = require "os"
local uci = require "uci"
local util = require "luci.util"
local table = require "table"
local setmetatable, rawget, rawset = setmetatable, rawget, rawset
local require, getmetatable = require, getmetatable
local error, pairs, ipairs = error, pairs, ipairs
local type, tostring, tonumber, unpack = type, tostring, tonumber, unpack
-- The typical workflow for UCI is: Get a cursor instance from the
-- cursor factory, modify data (via Cursor.add, Cursor.delete, etc.),
-- save the changes to the staging area via Cursor.save and finally
-- Cursor.commit the data to the actual config files.
-- LuCI then needs to Cursor.apply the changes so deamons etc. are
-- reloaded.
module "luci.model.uci"
cursor = uci.cursor
APIVERSION = uci.APIVERSION
function cursor_state()
return cursor(nil, "/var/state")
end
inst = cursor()
inst_state = cursor_state()
local Cursor = getmetatable(inst)
function Cursor.apply(self, configlist, command)
configlist = self:_affected(configlist)
if command then
return { "/sbin/luci-reload", unpack(configlist) }
else
return os.execute("/sbin/luci-reload %s >/dev/null 2>&1"
% table.concat(configlist, " "))
end
end
-- returns a boolean whether to delete the current section (optional)
function Cursor.delete_all(self, config, stype, comparator)
local del = {}
if type(comparator) == "table" then
local tbl = comparator
comparator = function(section)
for k, v in pairs(tbl) do
if section[k] ~= v then
return false
end
end
return true
end
end
local function helper (section)
if not comparator or comparator(section) then
del[#del+1] = section[".name"]
end
end
self:foreach(config, stype, helper)
for i, j in ipairs(del) do
self:delete(config, j)
end
end
function Cursor.section(self, config, type, name, values)
local stat = true
if name then
stat = self:set(config, name, type)
else
name = self:add(config, type)
stat = name and true
end
if stat and values then
stat = self:tset(config, name, values)
end
return stat and name
end
function Cursor.tset(self, config, section, values)
local stat = true
for k, v in pairs(values) do
if k:sub(1, 1) ~= "." then
stat = stat and self:set(config, section, k, v)
end
end
return stat
end
function Cursor.get_bool(self, ...)
local val = self:get(...)
return ( val == "1" or val == "true" or val == "yes" or val == "on" )
end
function Cursor.get_list(self, config, section, option)
if config and section and option then
local val = self:get(config, section, option)
return ( type(val) == "table" and val or { val } )
end
return nil
end
function Cursor.get_first(self, conf, stype, opt, def)
local rv = def
self:foreach(conf, stype,
function(s)
local val = not opt and s['.name'] or s[opt]
if type(def) == "number" then
val = tonumber(val)
elseif type(def) == "boolean" then
val = (val == "1" or val == "true" or
val == "yes" or val == "on")
end
if val ~= nil then
rv = val
return false
end
end)
return rv
end
function Cursor.set_list(self, config, section, option, value)
if config and section and option then
return self:set(
config, section, option,
( type(value) == "table" and value or { value } )
)
end
return false
end
-- Return a list of initscripts affected by configuration changes.
function Cursor._affected(self, configlist)
configlist = type(configlist) == "table" and configlist or {configlist}
local c = cursor()
c:load("ucitrack")
-- Resolve dependencies
local reloadlist = {}
local function _resolve_deps(name)
local reload = {name}
local deps = {}
c:foreach("ucitrack", name,
function(section)
if section.affects then
for i, aff in ipairs(section.affects) do
deps[#deps+1] = aff
end
end
end)
for i, dep in ipairs(deps) do
for j, add in ipairs(_resolve_deps(dep)) do
reload[#reload+1] = add
end
end
return reload
end
-- Collect initscripts
for j, config in ipairs(configlist) do
for i, e in ipairs(_resolve_deps(config)) do
if not util.contains(reloadlist, e) then
reloadlist[#reloadlist+1] = e
end
end
end
return reloadlist
end
-- curser, means it the parent unloads or loads configs, the sub state will
-- do so as well.
function Cursor.substate(self)
Cursor._substates = Cursor._substates or { }
Cursor._substates[self] = Cursor._substates[self] or cursor_state()
return Cursor._substates[self]
end
local _load = Cursor.load
function Cursor.load(self, ...)
if Cursor._substates and Cursor._substates[self] then
_load(Cursor._substates[self], ...)
end
return _load(self, ...)
end
local _unload = Cursor.unload
function Cursor.unload(self, ...)
if Cursor._substates and Cursor._substates[self] then
_unload(Cursor._substates[self], ...)
end
return _unload(self, ...)
end
| cc0-1.0 |
NatWeiss/RGP | src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Tween.lua | 19 | 2495 |
--------------------------------
-- @module Tween
-- @extend ProcessBase
-- @parent_module ccs
--------------------------------
--
-- @function [parent=#Tween] getAnimation
-- @param self
-- @return ArmatureAnimation#ArmatureAnimation ret (return value: ccs.ArmatureAnimation)
--------------------------------
--
-- @function [parent=#Tween] gotoAndPause
-- @param self
-- @param #int frameIndex
-- @return Tween#Tween self (return value: ccs.Tween)
--------------------------------
-- Start the Process<br>
-- param movementBoneData the MovementBoneData include all FrameData<br>
-- param durationTo the number of frames changing to this animation needs.<br>
-- param durationTween the number of frames this animation actual last.<br>
-- param loop whether the animation is loop<br>
-- loop < 0 : use the value from MovementData get from Action Editor<br>
-- loop = 0 : this animation is not loop<br>
-- loop > 0 : this animation is loop<br>
-- param tweenEasing tween easing is used for calculate easing effect<br>
-- TWEEN_EASING_MAX : use the value from MovementData get from Action Editor<br>
-- -1 : fade out<br>
-- 0 : line<br>
-- 1 : fade in<br>
-- 2 : fade in and out
-- @function [parent=#Tween] play
-- @param self
-- @param #ccs.MovementBoneData movementBoneData
-- @param #int durationTo
-- @param #int durationTween
-- @param #int loop
-- @param #int tweenEasing
-- @return Tween#Tween self (return value: ccs.Tween)
--------------------------------
--
-- @function [parent=#Tween] gotoAndPlay
-- @param self
-- @param #int frameIndex
-- @return Tween#Tween self (return value: ccs.Tween)
--------------------------------
-- Init with a Bone<br>
-- param bone the Bone Tween will bind to
-- @function [parent=#Tween] init
-- @param self
-- @param #ccs.Bone bone
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#Tween] setAnimation
-- @param self
-- @param #ccs.ArmatureAnimation animation
-- @return Tween#Tween self (return value: ccs.Tween)
--------------------------------
-- Create with a Bone<br>
-- param bone the Bone Tween will bind to
-- @function [parent=#Tween] create
-- @param self
-- @param #ccs.Bone bone
-- @return Tween#Tween ret (return value: ccs.Tween)
--------------------------------
--
-- @function [parent=#Tween] Tween
-- @param self
-- @return Tween#Tween self (return value: ccs.Tween)
return nil
| mit |
MathieuDuponchelle/gdx | demos/pax-britannica/pax-britannica-android/assets/data/components/targeting.lua | 11 | 1526 | local v2 = require 'dokidoki.v2'
function on_screen(pos)
return pos.x >= game.constants.screen_left and
pos.x <= game.constants.screen_right and
pos.y >= game.constants.screen_bottom and
pos.y <= game.constants.screen_top
end
-- returns the closest target of the given type
function get_nearest_of_type(source, ship_type)
local ships = game.actors.get(ship_type)
-- find the closest one!
local closest_ship
local closest_square_magnitude
for _, ship in ipairs(ships) do
local square_magnitude = v2.sqrmag(ship.transform.pos - source.transform.pos)
if source.ship.player ~= ship.ship.player and on_screen(ship.transform.pos) and (not closest_ship or square_magnitude < closest_square_magnitude) then
closest_ship = ship
closest_square_magnitude = square_magnitude
end
end
return closest_ship
end
-- return a random ship of the desired type that's in range
function get_type_in_range(source, ship_type, range)
local ships = game.actors.get(ship_type)
local ships_in_range = {}
local range_squared = range * range
for _, ship in ipairs(ships) do
local square_magnitude = v2.sqrmag(ship.transform.pos - source.transform.pos)
if source.ship.player ~= ship.ship.player and on_screen(ship.transform.pos) and (square_magnitude < range_squared) then
ships_in_range[#ships_in_range+1] = ship
end
end
if #ships_in_range > 0 then
return ships_in_range[math.random(1, #ships_in_range)]
else
return false
end
end
| apache-2.0 |
yetsky/luci | applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-cdr.lua | 80 | 1878 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
cdr_csv = module:option(ListValue, "cdr_csv", "Comma Separated Values CDR Backend", "")
cdr_csv:value("yes", "Load")
cdr_csv:value("no", "Do Not Load")
cdr_csv:value("auto", "Load as Required")
cdr_csv.rmempty = true
cdr_custom = module:option(ListValue, "cdr_custom", "Customizable Comma Separated Values CDR Backend", "")
cdr_custom:value("yes", "Load")
cdr_custom:value("no", "Do Not Load")
cdr_custom:value("auto", "Load as Required")
cdr_custom.rmempty = true
cdr_manager = module:option(ListValue, "cdr_manager", "Asterisk Call Manager CDR Backend", "")
cdr_manager:value("yes", "Load")
cdr_manager:value("no", "Do Not Load")
cdr_manager:value("auto", "Load as Required")
cdr_manager.rmempty = true
cdr_mysql = module:option(ListValue, "cdr_mysql", "MySQL CDR Backend", "")
cdr_mysql:value("yes", "Load")
cdr_mysql:value("no", "Do Not Load")
cdr_mysql:value("auto", "Load as Required")
cdr_mysql.rmempty = true
cdr_pgsql = module:option(ListValue, "cdr_pgsql", "PostgreSQL CDR Backend", "")
cdr_pgsql:value("yes", "Load")
cdr_pgsql:value("no", "Do Not Load")
cdr_pgsql:value("auto", "Load as Required")
cdr_pgsql.rmempty = true
cdr_sqlite = module:option(ListValue, "cdr_sqlite", "SQLite CDR Backend", "")
cdr_sqlite:value("yes", "Load")
cdr_sqlite:value("no", "Do Not Load")
cdr_sqlite:value("auto", "Load as Required")
cdr_sqlite.rmempty = true
return cbimap
| apache-2.0 |
judos/hardCrafting | source/libs/lua/string.lua | 1 | 1232 | require "libs.logging"
function string.starts(str,prefix)
return string.sub(str,1,string.len(prefix))==prefix
end
function string.ends(str,suffix)
return suffix=='' or string.sub(str,-string.len(suffix))==suffix
end
-- See: http://lua-users.org/wiki/MakingLuaLikePhp
function split(str,divider) -- credit: http://richard.warburton.it
if divider=='' then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return str:find(divider,pos,true) end do
table.insert(arr,str:sub(pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,str:sub(pos)) -- Attach chars right of last divider
return arr
end
-- e.g. formatWith("%time - %msg",{time = "10pm", msg = "Hello"} -> "10pm - Hello"
function formatWith(formatStr,parameters)
if not parameters then
err("ERROR: missing parameters for formatWith in libs.lua.string")
parameters = {}
end
repeat
local before = formatStr
local tag = formatStr:match("%%(%a+)")
if tag then
if not parameters[tag] then parameters[tag]=tag end
formatStr = formatStr:gsub("%%"..tag, parameters[tag])
end
until tag == nil or before == formatStr
return formatStr
end | gpl-3.0 |
yetsky/luci | modules/freifunk/luasrc/model/cbi/freifunk/profile.lua | 56 | 2755 | --[[
LuCI - Lua Configuration Interface
Copyright 2011-2012 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
httc://www.apache.org/licenses/LICENSE-2.0
]]--
local uci = require "luci.model.uci".cursor()
local ipkg = require "luci.model.ipkg"
local community = uci:get("freifunk", "community", "name")
if community == nil then
luci.http.redirect(luci.dispatcher.build_url("admin", "freifunk", "profile_error"))
return
else
community = "profile_" .. community
m = Map(community, translate("Community settings"), translate("These are the settings of your local community."))
c = m:section(NamedSection, "profile", "community")
local name = c:option(Value, "name", "Name")
name.rmempty = false
local homepage = c:option(Value, "homepage", translate("Homepage"))
local cc = c:option(Value, "country", translate("Country code"))
function cc.cfgvalue(self, section)
return uci:get(community, "wifi_device", "country")
end
function cc.write(self, sec, value)
if value then
uci:set(community, "wifi_device", "country", value)
uci:save(community)
end
end
local ssid = c:option(Value, "ssid", translate("ESSID"))
ssid.rmempty = false
local prefix = c:option(Value, "mesh_network", translate("Mesh prefix"))
prefix.datatype = "ip4addr"
prefix.rmempty = false
local splash_net = c:option(Value, "splash_network", translate("Network for client DHCP addresses"))
splash_net.datatype = "ip4addr"
splash_net.rmempty = false
local splash_prefix = c:option(Value, "splash_prefix", translate("Client network size"))
splash_prefix.datatype = "range(0,32)"
splash_prefix.rmempty = false
local ipv6 = c:option(Flag, "ipv6", translate("Enable IPv6"))
ipv6.rmempty = true
local ipv6_config = c:option(ListValue, "ipv6_config", translate("IPv6 Config"))
ipv6_config:depends("ipv6", 1)
ipv6_config:value("static")
if ipkg.installed ("auto-ipv6-ib") then
ipv6_config:value("auto-ipv6-random")
ipv6_config:value("auto-ipv6-fromv4")
end
ipv6_config.rmempty = true
local ipv6_prefix = c:option(Value, "ipv6_prefix", translate("IPv6 Prefix"), translate("IPv6 network in CIDR notation."))
ipv6_prefix:depends("ipv6", 1)
ipv6_prefix.datatype = "ip6addr"
ipv6_prefix.rmempty = true
local vap = c:option(Flag, "vap", translate("VAP"), translate("Enable a virtual access point (VAP) by default if possible."))
vap.rmempty = true
local lat = c:option(Value, "latitude", translate("Latitude"))
lat.datatype = "range(-180, 180)"
lat.rmempty = false
local lon = c:option(Value, "longitude", translate("Longitude"))
lon.rmempty = false
return m
end
| apache-2.0 |
daniel-slaney/demirogue | src/prelude/table.lua | 3 | 3725 | --
-- misc/table.lua
--
-- Utility functions for working with tables.
--
-- TODO: random functions need optional generator argument.
-- TODO: luafun might be a better option for a lot of these.
--
function table.keys( tbl )
local result = {}
for k, _ in pairs(tbl) do
result[#result+1] = k
end
return result
end
-- Really just a shallow copy.
function table.copy( tbl )
local result = {}
for k, v in pairs(tbl) do
result[k] = v
end
return result
end
function table.count( tbl )
local result = 0
for _ in pairs(tbl) do
result = result + 1
end
return result
end
function table.append( tbl1, tbl2 )
for i = 1, #tbl2 do
tbl1[#tbl1+1] = tbl2[i]
end
return tbl1
end
function table.random( tbl )
local count = table.count(tbl)
local index = math.random(1, count)
local k = nil
for i = 1, index do
k = next(tbl, k)
end
return k, tbl[k]
end
function table.shuffle( tbl )
for i = 1, #tbl-1 do
local index = math.random(i, #tbl)
tbl[i], tbl[index] = tbl[index], tbl[i]
end
end
function table.reverse( tbl )
local size = #tbl
for index = 1, math.ceil(size * 0.5) do
local mirrorIndex = size - (index - 1)
tbl[index], tbl[mirrorIndex] = tbl[mirrorIndex], tbl[index]
end
return tbl
end
function table.inverse( tbl )
local result = {}
for k, v in pairs(tbl) do
result[v] = k
end
return result
end
function table.collect( tbl, func )
local result = {}
for k, v in pairs(tbl) do
result[k] = func(v)
end
return result
end
local _literals = {
boolean =
function ( value )
if value then
return 'true'
else
return 'false'
end
end,
number =
function ( value )
if math.floor(value) == value then
return string.format("%d", value)
else
return string.format("%.4f", value)
end
end,
string =
function ( value )
return string.format("%q", value)
end
}
-- TODO: maybe move to its own file.
function table.compile( tbl, option )
local parts = { 'return ' }
local pads = { [0] = '', ' ', ' ' }
local next = next
local string_rep = string.rep
local type = type
local _literals = _literals
local function aux( tbl, indent )
if next(tbl) == nil then
parts[#parts+1] = '{}'
return
end
parts[#parts+1] = '{\n'
local padding = pads[indent]
if not padding then
padding = string_rep(' ', indent)
pads[indent] = padding
end
local size = #tbl
-- First off let's do the array part.
for index = 1, size do
local v = tbl[index]
parts[#parts+1] = padding
local vt = type(v)
if vt ~= 'table' then
parts[#parts+1] = _literals[vt](v)
else
aux(v, indent + 2)
end
parts[#parts+1] = ',\n'
end
-- Now non-array parts. This uses secret knowledge of how lua works, the
-- next() function will iterate over array parts first so we can skip them.
local k = next(tbl, (size ~= 0) and size or nil)
while k ~= nil do
parts[#parts+1] = padding
parts[#parts+1] = '['
local kt = type(k)
if kt ~= 'table' then
parts[#parts+1] = _literals[kt](k)
else
aux(k, indent + 2)
end
parts[#parts+1] = '] = '
local v = tbl[k]
local vt = type(v)
if vt ~= 'table' then
parts[#parts+1] = _literals[vt](v)
else
aux(v, indent + 2)
end
parts[#parts+1] = ',\n'
k = next(tbl, k)
end
-- Closing braces are dedented.
indent = indent - 2
padding = pads[indent]
if not padding then
padding = string_rep(' ', indent)
pads[indent] = padding
end
if padding ~= '' then
parts[#parts+1] = padding
end
parts[#parts+1] = '}'
end
aux(tbl, 2)
-- This is to stop complaints about files not ending in a newline.
parts[#parts+1] = '\n'
local result = table.concat(parts)
return result
end
| bsd-3-clause |
rmtew/demirogue | src/prelude/table.lua | 3 | 3725 | --
-- misc/table.lua
--
-- Utility functions for working with tables.
--
-- TODO: random functions need optional generator argument.
-- TODO: luafun might be a better option for a lot of these.
--
function table.keys( tbl )
local result = {}
for k, _ in pairs(tbl) do
result[#result+1] = k
end
return result
end
-- Really just a shallow copy.
function table.copy( tbl )
local result = {}
for k, v in pairs(tbl) do
result[k] = v
end
return result
end
function table.count( tbl )
local result = 0
for _ in pairs(tbl) do
result = result + 1
end
return result
end
function table.append( tbl1, tbl2 )
for i = 1, #tbl2 do
tbl1[#tbl1+1] = tbl2[i]
end
return tbl1
end
function table.random( tbl )
local count = table.count(tbl)
local index = math.random(1, count)
local k = nil
for i = 1, index do
k = next(tbl, k)
end
return k, tbl[k]
end
function table.shuffle( tbl )
for i = 1, #tbl-1 do
local index = math.random(i, #tbl)
tbl[i], tbl[index] = tbl[index], tbl[i]
end
end
function table.reverse( tbl )
local size = #tbl
for index = 1, math.ceil(size * 0.5) do
local mirrorIndex = size - (index - 1)
tbl[index], tbl[mirrorIndex] = tbl[mirrorIndex], tbl[index]
end
return tbl
end
function table.inverse( tbl )
local result = {}
for k, v in pairs(tbl) do
result[v] = k
end
return result
end
function table.collect( tbl, func )
local result = {}
for k, v in pairs(tbl) do
result[k] = func(v)
end
return result
end
local _literals = {
boolean =
function ( value )
if value then
return 'true'
else
return 'false'
end
end,
number =
function ( value )
if math.floor(value) == value then
return string.format("%d", value)
else
return string.format("%.4f", value)
end
end,
string =
function ( value )
return string.format("%q", value)
end
}
-- TODO: maybe move to its own file.
function table.compile( tbl, option )
local parts = { 'return ' }
local pads = { [0] = '', ' ', ' ' }
local next = next
local string_rep = string.rep
local type = type
local _literals = _literals
local function aux( tbl, indent )
if next(tbl) == nil then
parts[#parts+1] = '{}'
return
end
parts[#parts+1] = '{\n'
local padding = pads[indent]
if not padding then
padding = string_rep(' ', indent)
pads[indent] = padding
end
local size = #tbl
-- First off let's do the array part.
for index = 1, size do
local v = tbl[index]
parts[#parts+1] = padding
local vt = type(v)
if vt ~= 'table' then
parts[#parts+1] = _literals[vt](v)
else
aux(v, indent + 2)
end
parts[#parts+1] = ',\n'
end
-- Now non-array parts. This uses secret knowledge of how lua works, the
-- next() function will iterate over array parts first so we can skip them.
local k = next(tbl, (size ~= 0) and size or nil)
while k ~= nil do
parts[#parts+1] = padding
parts[#parts+1] = '['
local kt = type(k)
if kt ~= 'table' then
parts[#parts+1] = _literals[kt](k)
else
aux(k, indent + 2)
end
parts[#parts+1] = '] = '
local v = tbl[k]
local vt = type(v)
if vt ~= 'table' then
parts[#parts+1] = _literals[vt](v)
else
aux(v, indent + 2)
end
parts[#parts+1] = ',\n'
k = next(tbl, k)
end
-- Closing braces are dedented.
indent = indent - 2
padding = pads[indent]
if not padding then
padding = string_rep(' ', indent)
pads[indent] = padding
end
if padding ~= '' then
parts[#parts+1] = padding
end
parts[#parts+1] = '}'
end
aux(tbl, 2)
-- This is to stop complaints about files not ending in a newline.
parts[#parts+1] = '\n'
local result = table.concat(parts)
return result
end
| bsd-3-clause |
leafo/aroma | nacl/lua-cjson-2.1.0/lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| mit |
yetsky/luci | protocols/ppp/luasrc/model/cbi/admin_network/proto_l2tp.lua | 59 | 1868 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local server, username, password
local ipv6, defaultroute, metric, peerdns, dns, mtu
server = section:taboption("general", Value, "server", translate("L2TP Server"))
server.datatype = "host"
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
uber/zanzibar | benchmarks/contacts_1KB.lua | 1 | 1558 | -- wrk -t12 -c400 -d30s -s ./benchmarks/contacts_1KB.lua http://localhost:8093/contacts/foo/contacts
-- go-torch -u http://localhost:8093/ -t5
wrk.method = "POST"
wrk.body = "{\"userUUID\":\"some-uuid\",\"contacts\":[{\"fragments\":[{\"type\":\"message\",\"text\":\"foobarbaz\"}],\"attributes\":{\"firstName\":\"steve\",\"lastName\":\"stevenson\",\"hasPhoto\":true,\"numFields\":10,\"timesContacted\":5,\"lastTimeContacted\":0,\"isStarred\":false,\"hasCustomRingtone\":false,\"isSendToVoicemail\":false,\"hasThumbnail\":false,\"namePrefix\":\"\",\"nameSuffix\":\"\"}},{\"fragments\":[{\"type\":\"message\",\"text\":\"foobarbaz\"}],\"attributes\":{\"firstName\":\"steve\",\"lastName\":\"stevenson\",\"hasPhoto\":true,\"numFields\":10,\"timesContacted\":5,\"lastTimeContacted\":0,\"isStarred\":false,\"hasCustomRingtone\":false,\"isSendToVoicemail\":false,\"hasThumbnail\":false,\"namePrefix\":\"\",\"nameSuffix\":\"\"}},{\"fragments\":[],\"attributes\":{\"firstName\":\"steve\",\"lastName\":\"stevenson\",\"hasPhoto\":true,\"numFields\":10,\"timesContacted\":5,\"lastTimeContacted\":0,\"isStarred\":false,\"hasCustomRingtone\":false,\"isSendToVoicemail\":false,\"hasThumbnail\":false,\"namePrefix\":\"\",\"nameSuffix\":\"\"}},{\"fragments\":[],\"attributes\":{\"firstName\":\"steve\",\"lastName\":\"stevenson\",\"hasPhoto\":true,\"numFields\":10,\"timesContacted\":5,\"lastTimeContacted\":0,\"isStarred\":false,\"hasCustomRingtone\":false,\"isSendToVoicemail\":false,\"hasThumbnail\":false,\"namePrefix\":\"\",\"nameSuffix\":\"\"}}],\"appType\":\"MY_APP\"}"
| mit |
pazos/koreader | plugins/evernote.koplugin/clip.lua | 4 | 10109 | local DocumentRegistry = require("document/documentregistry")
local DocSettings = require("docsettings")
local ReadHistory = require("readhistory")
local logger = require("logger")
local md5 = require("ffi/sha2").md5
local util = require("util")
local MyClipping = {
my_clippings = "/mnt/us/documents/My Clippings.txt",
history_dir = "./history",
}
function MyClipping:new(o)
if o == nil then o = {} end
setmetatable(o, self)
self.__index = self
return o
end
--[[
-- clippings: main table to store parsed highlights and notes entries
-- {
-- ["Title(Author Name)"] = {
-- {
-- {
-- ["page"] = 123,
-- ["time"] = 1398127554,
-- ["text"] = "Games of all sorts were played in homes and fields."
-- },
-- {
-- ["page"] = 156,
-- ["time"] = 1398128287,
-- ["text"] = "There Spenser settled down to gentleman farming.",
-- ["note"] = "This is a sample note.",
-- },
-- ["title"] = "Chapter I"
-- },
-- }
-- }
-- ]]
function MyClipping:parseMyClippings()
-- My Clippings format:
-- Title(Author Name)
-- Your Highlight on Page 123 | Added on Monday, April 21, 2014 10:08:07 PM
--
-- This is a sample highlight.
-- ==========
local file = io.open(self.my_clippings, "r")
local clippings = {}
if file then
local index = 1
local title, author, info, text
for line in file:lines() do
line = line:match("^%s*(.-)%s*$") or ""
if index == 1 then
title, author = self:getTitle(line)
clippings[title] = clippings[title] or {
title = title,
author = author,
}
elseif index == 2 then
info = self:getInfo(line)
-- elseif index == 3 then
-- should be a blank line, we skip this line
elseif index == 4 then
text = self:getText(line)
end
if line == "==========" then
if index == 5 then
-- entry ends normally
local clipping = {
page = info.page or info.location,
sort = info.sort,
time = info.time,
text = text,
}
-- we cannot extract chapter info so just insert clipping
-- to a place holder chapter
table.insert(clippings[title], { clipping })
end
index = 0
end
index = index + 1
end
end
return clippings
end
local extensions = {
[".pdf"] = true,
[".djvu"] = true,
[".epub"] = true,
[".fb2"] = true,
[".mobi"] = true,
[".txt"] = true,
[".html"] = true,
[".doc"] = true,
}
-- remove file extensions added by former KOReader
-- extract author name in "Title(Author)" format
-- extract author name in "Title - Author" format
function MyClipping:getTitle(line)
line = line:match("^%s*(.-)%s*$") or ""
if extensions[line:sub(-4):lower()] then
line = line:sub(1, -5)
elseif extensions[line:sub(-5):lower()] then
line = line:sub(1, -6)
end
local _, _, title, author = line:find("(.-)%s*%((.*)%)")
if not author then
_, _, title, author = line:find("(.-)%s*-%s*(.*)")
end
if not title then title = line end
return title:match("^%s*(.-)%s*$"), author
end
local keywords = {
["highlight"] = {
"Highlight",
"标注",
},
["note"] = {
"Note",
"笔记",
},
["bookmark"] = {
"Bookmark",
"书签",
},
}
local months = {
["Jan"] = 1,
["Feb"] = 2,
["Mar"] = 3,
["Apr"] = 4,
["May"] = 5,
["Jun"] = 6,
["Jul"] = 7,
["Aug"] = 8,
["Sep"] = 9,
["Oct"] = 10,
["Nov"] = 11,
["Dec"] = 12
}
local pms = {
["PM"] = 12,
["下午"] = 12,
}
function MyClipping:getTime(line)
if not line then return end
local _, _, year, month, day = line:find("(%d+)年(%d+)月(%d+)日")
if not year or not month or not day then
_, _, year, month, day = line:find("(%d%d%d%d)-(%d%d)-(%d%d)")
end
if not year or not month or not day then
for k, v in pairs(months) do
if line:find(k) then
month = v
_, _, day = line:find(" (%d?%d),")
_, _, year = line:find(" (%d%d%d%d)")
break
end
end
end
local _, _, hour, minute, second = line:find("(%d+):(%d+):(%d+)")
if year and month and day and hour and minute and second then
for k, v in pairs(pms) do
if line:find(k) then
hour = hour + v
break
end
end
local time = os.time({
year = year, month = month, day = day,
hour = hour, min = minute, sec = second,
})
return time
end
end
function MyClipping:getInfo(line)
local info = {}
line = line or ""
local _, _, part1, part2 = line:find("(.+)%s*|%s*(.+)")
-- find entry type and location
for sort, words in pairs(keywords) do
for _, word in ipairs(words) do
if part1 and part1:find(word) then
info.sort = sort
info.location = part1:match("(%d+-?%d+)")
break
end
end
end
-- find entry created time
info.time = self:getTime(part2 or "")
return info
end
function MyClipping:getText(line)
line = line or ""
return line:match("^%s*(.-)%s*$") or ""
end
-- get PNG string and md5 hash
function MyClipping:getImage(image)
--DEBUG("image", image)
local doc = DocumentRegistry:openDocument(image.file)
if doc then
local png = doc:clipPagePNGString(image.pos0, image.pos1,
image.pboxes, image.drawer)
--doc:clipPagePNGFile(image.pos0, image.pos1,
--image.pboxes, image.drawer, "/tmp/"..md5(png)..".png")
doc:close()
if png then return { png = png, hash = md5(png) } end
end
end
function MyClipping:parseHighlight(highlights, bookmarks, book)
--DEBUG("book", book.file)
for page, items in pairs(highlights) do
for _, item in ipairs(items) do
local clipping = {}
clipping.page = page
clipping.sort = "highlight"
clipping.time = self:getTime(item.datetime or "")
clipping.text = self:getText(item.text)
clipping.chapter = item.chapter
for _, bookmark in pairs(bookmarks) do
if bookmark.datetime == item.datetime and bookmark.text then
local tmp = string.gsub(bookmark.text, "Page %d+ ", "")
clipping.text = string.gsub(tmp, " @ %d%d%d%d%-%d%d%-%d%d %d%d:%d%d:%d%d", "")
end
end
if item.text == "" and item.pos0 and item.pos1 and
item.pos0.x and item.pos0.y and
item.pos1.x and item.pos1.y then
-- highlights in reflowing mode don't have page in pos
if item.pos0.page == nil then item.pos0.page = page end
if item.pos1.page == nil then item.pos1.page = page end
local image = {}
image.file = book.file
image.pos0, image.pos1 = item.pos0, item.pos1
image.pboxes = item.pboxes
image.drawer = item.drawer
clipping.image = self:getImage(image)
end
--- @todo Store chapter info when exporting highlights.
if clipping.text and clipping.text ~= "" or clipping.image then
table.insert(book, { clipping })
end
end
end
table.sort(book, function(v1, v2) return v1[1].page < v2[1].page end)
end
function MyClipping:parseHistoryFile(clippings, history_file, doc_file)
if lfs.attributes(history_file, "mode") ~= "file"
or not history_file:find(".+%.lua$") then
return
end
if lfs.attributes(doc_file, "mode") ~= "file" then return end
local ok, stored = pcall(dofile, history_file)
if ok then
if not stored then
logger.warn("An empty history file ",
history_file,
"has been found. The book associated is ",
doc_file)
return
elseif not stored.highlight then
return
end
local _, docname = util.splitFilePathName(doc_file)
local title, author = self:getTitle(util.splitFileNameSuffix(docname))
clippings[title] = {
file = doc_file,
title = title,
author = author,
}
self:parseHighlight(stored.highlight, stored.bookmarks, clippings[title])
end
end
function MyClipping:parseHistory()
local clippings = {}
for f in lfs.dir(self.history_dir) do
self:parseHistoryFile(clippings,
self.history_dir .. "/" .. f,
DocSettings:getPathFromHistory(f) .. "/" ..
DocSettings:getNameFromHistory(f))
end
for _, item in ipairs(ReadHistory.hist) do
self:parseHistoryFile(clippings,
DocSettings:getSidecarFile(item.file),
item.file)
end
return clippings
end
function MyClipping:parseCurrentDoc(view)
local clippings = {}
local path = view.document.file
local _, _, docname = path:find(".*/(.*)")
local title, author = self:getTitle(docname)
clippings[title] = {
file = view.document.file,
title = title,
author = author,
}
self:parseHighlight(view.highlight.saved, view.ui.bookmark.bookmarks, clippings[title])
return clippings
end
return MyClipping
| agpl-3.0 |
snassar/tess | etc/prosody/conf.avail/tess.cfg.lua | 1 | 1042 | -- Section for tess
VirtualHost "tess"
-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/etc/prosody/certs/example.com.key";
certificate = "/etc/prosody/certs/example.com.crt";
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components
-- Set up a MUC (multi-user chat) room server on conference.example.com:
Component "conference.tess" "muc"
-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
--Component "proxy.example.com" "proxy65"
---Set up an external component (default component port is 5347)
--Component "gateway.example.com"
-- component_secret = "password"
| gpl-3.0 |
johnymarek/tsdemuxer | xupnpd/src/plugins/staff/xupnpd_minaev.lua | 6 | 2445 | -- Copyright (C) 2011-2012 Anton Burdinuk
-- clark15b@gmail.com
-- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd
-- feed: archive
function minaev_updatefeed(feed,friendly_name)
local rc=false
local feed_url='http://www.minaevlive.ru/'..feed..'/'
local feed_name='minaev_'..string.gsub(feed,'/','_')
local feed_m3u_path=cfg.feeds_path..feed_name..'.m3u'
local tmp_m3u_path=cfg.tmp_path..feed_name..'.m3u'
local feed_data=http.download(feed_url)
if feed_data then
local dfd=io.open(tmp_m3u_path,'w+')
if dfd then
dfd:write('#EXTM3U name=\"',friendly_name or feed_name,'\" type=mp4 plugin=minaev\n')
local pattern=string.format('<h2>%%s*<a href="(/%s/%%w+/)">(.-)</a>%%s*</h2>',feed)
for u,name in string.gmatch(feed_data,pattern) do
local url=string.format('http://www.minaevlive.ru%s',u)
dfd:write('#EXTINF:0,',name,'\n',url,'\n')
end
dfd:close()
if util.md5(tmp_m3u_path)~=util.md5(feed_m3u_path) then
if os.execute(string.format('mv %s %s',tmp_m3u_path,feed_m3u_path))==0 then
if cfg.debug>0 then print('MinaevLive feed \''..feed_name..'\' updated') end
rc=true
end
else
util.unlink(tmp_m3u_path)
end
end
feed_data=nil
end
return rc
end
function minaev_sendurl(minaev_url,range)
local url=nil
if plugin_sendurl_from_cache(minaev_url,range) then return end
local clip_page=http.download(minaev_url)
if clip_page then
--http://media.russia.ru/minaevlive/120/sd.mp4
--http://media.russia.ru/minaevlive/120/hd720p.mp4
local u=string.match(clip_page,'.+<source src="(http://media.russia.ru/minaevlive/%w+/)%w+.mp4.+"')
if u then
url=u..'sd.mp4'
end
end
if url then
if cfg.debug>0 then print('MinaevLive Real URL: '..url) end
plugin_sendurl(minaev_url,url,range)
else
if cfg.debug>0 then print('MinaevLive clip is not found') end
plugin_sendfile('www/corrupted.mp4')
end
end
plugins['minaev']={}
plugins.minaev.name="MinaevLive"
plugins.minaev.desc="archive"
plugins.minaev.sendurl=minaev_sendurl
plugins.minaev.updatefeed=minaev_updatefeed
--minaev_updatefeed('archive')
--minaev_sendurl('http://www.minaevlive.ru/archive/link5bd88f9b/','')
| mit |
joaofvieira/luci | applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_config.lua | 61 | 1072 | -- Copyright 2009 Daniel Dickinson
-- Licensed to the public under the Apache License 2.0.
require("luci.controller.luci_diag.devinfo_common")
m = Map("luci_devinfo", translate("SIP Device Scanning Configuration"), translate("Configure scanning for supported SIP devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices."))
s = m:section(SimpleSection, "", translate("Use Configuration"))
b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)"))
b.value = ""
b.titleref = luci.dispatcher.build_url("admin", "status", "smap_devinfo")
scannet = m:section(TypedSection, "smap_scannet", translate("Scanning Configuration"), translate("Networks to scan for supported devices"))
scannet.addremove = true
scannet.anonymous = false
local ports
ports = scannet:option(Value, "ports", translate("Ports"))
ports.optional = true
ports.rmempty = true
luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet)
return m
| apache-2.0 |
bradchesney79/2015BeastRouterProject | openwrt/unsquash/squashfs-root/usr/lib/lua/luci/model/cbi/admin_network/proto_6rd.lua | 72 | 2039 | -- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local ipaddr, peeraddr, ip6addr, tunnelid, username, password
local defaultroute, metric, ttl, mtu
ipaddr = s:taboption("general", Value, "ipaddr",
translate("Local IPv4 address"),
translate("Leave empty to use the current WAN address"))
ipaddr.datatype = "ip4addr"
peeraddr = s:taboption("general", Value, "peeraddr",
translate("Remote IPv4 address"),
translate("This IPv4 address of the relay"))
peeraddr.rmempty = false
peeraddr.datatype = "ip4addr"
ip6addr = s:taboption("general", Value, "ip6prefix",
translate("IPv6 prefix"),
translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>"))
ip6addr.rmempty = false
ip6addr.datatype = "ip6addr"
ip6prefixlen = s:taboption("general", Value, "ip6prefixlen",
translate("IPv6 prefix length"),
translate("The length of the IPv6 prefix in bits"))
ip6prefixlen.placeholder = "16"
ip6prefixlen.datatype = "range(0,128)"
ip6prefixlen = s:taboption("general", Value, "ip4prefixlen",
translate("IPv4 prefix length"),
translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses."))
ip6prefixlen.placeholder = "0"
ip6prefixlen.datatype = "range(0,32)"
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface"))
ttl.placeholder = "64"
ttl.datatype = "range(1,255)"
mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface"))
mtu.placeholder = "1280"
mtu.datatype = "max(9200)"
| cc0-1.0 |
miraage/gladdy | Libs/AceDBOptions-3.0/AceDBOptions-3.0.lua | 2 | 15710 | --[[ $Id: AceDBOptions-3.0.lua 81438 2008-09-06 13:44:36Z nevcairiel $ ]]
local ACEDBO_MAJOR, ACEDBO_MINOR = "AceDBOptions-3.0", 7
local AceDBOptions, oldminor = LibStub:NewLibrary(ACEDBO_MAJOR, ACEDBO_MINOR)
if not AceDBOptions then return end -- No upgrade needed
AceDBOptions.optionTables = AceDBOptions.optionTables or {}
AceDBOptions.handlers = AceDBOptions.handlers or {}
--[[
Localization of AceDBOptions-3.0
]]
local L = {
default = "Default",
intro = "You can change the active database profile, so you can have different settings for every character.",
reset_desc = "Reset the current profile back to its default values, in case your configuration is broken, or you simply want to start over.",
reset = "Reset Profile",
reset_sub = "Reset the current profile to the default",
choose_desc = "You can either create a new profile by entering a name in the editbox, or choose one of the already exisiting profiles.",
new = "New",
new_sub = "Create a new empty profile.",
choose = "Existing Profiles",
choose_sub = "Select one of your currently available profiles.",
copy_desc = "Copy the settings from one existing profile into the currently active profile.",
copy = "Copy From",
delete_desc = "Delete existing and unused profiles from the database to save space, and cleanup the SavedVariables file.",
delete = "Delete a Profile",
delete_sub = "Deletes a profile from the database.",
delete_confirm = "Are you sure you want to delete the selected profile?",
profiles = "Profiles",
profiles_sub = "Manage Profiles",
}
local LOCALE = GetLocale()
if LOCALE == "deDE" then
L["default"] = "Standard"
L["intro"] = "Hier kannst du das aktive Datenbankprofile \195\164ndern, damit du verschiedene Einstellungen f\195\188r jeden Charakter erstellen kannst, wodurch eine sehr flexible Konfiguration m\195\182glich wird."
L["reset_desc"] = "Setzt das momentane Profil auf Standardwerte zur\195\188ck, f\195\188r den Fall das mit der Konfiguration etwas schief lief oder weil du einfach neu starten willst."
L["reset"] = "Profil zur\195\188cksetzen"
L["reset_sub"] = "Das aktuelle Profil auf Standard zur\195\188cksetzen."
L["choose_desc"] = "Du kannst ein neues Profil erstellen, indem du einen neuen Namen in der Eingabebox 'Neu' eingibst, oder w\195\164hle eines der vorhandenen Profile aus."
L["new"] = "Neu"
L["new_sub"] = "Ein neues Profil erstellen."
L["choose"] = "Vorhandene Profile"
L["choose_sub"] = "W\195\164hlt ein bereits vorhandenes Profil aus."
L["copy_desc"] = "Kopiere die Einstellungen von einem vorhandenen Profil in das aktive Profil."
L["copy"] = "Kopieren von..."
L["delete_desc"] = "L\195\182sche vorhandene oder unbenutzte Profile aus der Datenbank um Platz zu sparen und um die SavedVariables Datei 'sauber' zu halten."
L["delete"] = "Profil l\195\182schen"
L["delete_sub"] = "L\195\182scht ein Profil aus der Datenbank."
L["delete_confirm"] = "Willst du das ausgew\195\164hlte Profil wirklich l\195\182schen?"
L["profiles"] = "Profile"
L["profiles_sub"] = "Profile verwalten"
elseif LOCALE == "frFR" then
L["default"] = "D\195\169faut"
L["intro"] = "Vous pouvez changer le profil actuel afin d'avoir des param\195\168tres diff\195\169rents pour chaque personnage, permettant ainsi d'avoir une configuration tr\195\168s flexible."
L["reset_desc"] = "R\195\169initialise le profil actuel au cas o\195\185 votre configuration est corrompue ou si vous voulez tout simplement faire table rase."
L["reset"] = "R\195\169initialiser le profil"
L["reset_sub"] = "R\195\169initialise le profil actuel avec les param\195\168tres par d\195\169faut."
L["choose_desc"] = "Vous pouvez cr\195\169er un nouveau profil en entrant un nouveau nom dans la bo\195\174te de saisie, ou en choississant un des profils d\195\169j\195\160 existants."
L["new"] = "Nouveau"
L["new_sub"] = "Cr\195\169\195\169e un nouveau profil vierge."
L["choose"] = "Profils existants"
L["choose_sub"] = "Permet de choisir un des profils d\195\169j\195\160 disponibles."
L["copy_desc"] = "Copie les param\195\168tres d'un profil d\195\169j\195\160 existant dans le profil actuellement actif."
L["copy"] = "Copier \195\160 partir de"
L["delete_desc"] = "Supprime les profils existants inutilis\195\169s de la base de donn\195\169es afin de gagner de la place et de nettoyer le fichier SavedVariables."
L["delete"] = "Supprimer un profil"
L["delete_sub"] = "Supprime un profil de la base de donn\195\169es."
L["delete_confirm"] = "Etes-vous s\195\187r de vouloir supprimer le profil s\195\169lectionn\195\169 ?"
L["profiles"] = "Profils"
L["profiles_sub"] = "Gestion des profils"
elseif LOCALE == "koKR" then
L["default"] = "기본값"
L["intro"] = "모든 캐릭터의 다양한 설정과 사용중인 데이터베이스 프로필, 어느것이던지 매우 다루기 쉽게 바꿀수 있습니다."
L["reset_desc"] = "단순히 다시 새롭게 구성을 원하는 경우, 현재 프로필을 기본값으로 초기화 합니다."
L["reset"] = "프로필 초기화"
L["reset_sub"] = "현재의 프로필을 기본값으로 초기화 합니다"
L["choose_desc"] = "새로운 이름을 입력하거나, 이미 있는 프로필중 하나를 선택하여 새로운 프로필을 만들 수 있습니다."
L["new"] = "새로운 프로필"
L["new_sub"] = "새로운 프로필을 만듭니다."
L["choose"] = "프로필 선택"
L["choose_sub"] = "당신이 현재 이용할수 있는 프로필을 선택합니다."
L["copy_desc"] = "현재 사용중인 프로필에, 선택한 프로필의 설정을 복사합니다."
L["copy"] = "복사"
L["delete_desc"] = "데이터베이스에 사용중이거나 저장된 프로파일 삭제로 SavedVariables 파일의 정리와 공간 절약이 됩니다."
L["delete"] = "프로필 삭제"
L["delete_sub"] = "데이터베이스의 프로필을 삭제합니다."
L["delete_confirm"] = "정말로 선택한 프로필의 삭제를 원하십니까?"
L["profiles"] = "프로필"
L["profiles_sub"] = "프로필 설정"
elseif LOCALE == "esES" then
elseif LOCALE == "zhTW" then
L["default"] = "預設"
L["intro"] = "你可以選擇一個活動的資料設定檔,這樣你的每個角色就可以擁有不同的設定值,可以給你的插件設定帶來極大的靈活性。"
L["reset_desc"] = "將當前的設定檔恢復到它的預設值,用於你的設定檔損壞,或者你只是想重來的情況。"
L["reset"] = "重置設定檔"
L["reset_sub"] = "將當前的設定檔恢復為預設值"
L["choose_desc"] = "你可以通過在文本框內輸入一個名字創立一個新的設定檔,也可以選擇一個已經存在的設定檔。"
L["new"] = "新建"
L["new_sub"] = "新建一個空的設定檔。"
L["choose"] = "現有的設定檔"
L["choose_sub"] = "從當前可用的設定檔裏面選擇一個。"
L["copy_desc"] = "從當前某個已保存的設定檔複製到當前正使用的設定檔。"
L["copy"] = "複製自"
L["delete_desc"] = "從資料庫裏刪除不再使用的設定檔,以節省空間,並且清理SavedVariables檔。"
L["delete"] = "刪除一個設定檔"
L["delete_sub"] = "從資料庫裏刪除一個設定檔。"
L["delete_confirm"] = "你確定要刪除所選擇的設定檔嗎?"
L["profiles"] = "設定檔"
L["profiles_sub"] = "管理設定檔"
elseif LOCALE == "zhCN" then
L["default"] = "默认"
L["intro"] = "你可以选择一个活动的数据配置文件,这样你的每个角色就可以拥有不同的设置值,可以给你的插件配置带来极大的灵活性。"
L["reset_desc"] = "将当前的配置文件恢复到它的默认值,用于你的配置文件损坏,或者你只是想重来的情况。"
L["reset"] = "重置配置文件"
L["reset_sub"] = "将当前的配置文件恢复为默认值"
L["choose_desc"] = "你可以通过在文本框内输入一个名字创立一个新的配置文件,也可以选择一个已经存在的配置文件。"
L["new"] = "新建"
L["new_sub"] = "新建一个空的配置文件。"
L["choose"] = "现有的配置文件"
L["choose_sub"] = "从当前可用的配置文件里面选择一个。"
L["copy_desc"] = "从当前某个已保存的配置文件复制到当前正使用的配置文件。"
L["copy"] = "复制自"
L["delete_desc"] = "从数据库里删除不再使用的配置文件,以节省空间,并且清理SavedVariables文件。"
L["delete"] = "删除一个配置文件"
L["delete_sub"] = "从数据库里删除一个配置文件。"
L["delete_confirm"] = "你确定要删除所选择的配置文件么?"
L["profiles"] = "配置文件"
L["profiles_sub"] = "管理配置文件"
elseif LOCALE == "ruRU" then
L["default"] = "По умолчанию"
L["intro"] = "Вы можете сменить активный профиль БД, этим вы можете устанавливать различные настройки для каждого персонажа."
L["reset_desc"] = "Сброс текущего профиля на его стандартные значения, в том случаи если ваша конфигурация испорчена, или вы желаете всё перенастроить заново."
L["reset"] = "Сброс профиля"
L["reset"] = "Сброс текущего профиля на стандартный"
L["choose_desc"] = "Вы можете создать новый профиль введя название в поле ввода, или выбрать один из уже существующих профилей."
L["new"] = "Новый"
L["new_sub"] = "Создать новый чистый профиль."
L["choose"] = "Профиля"
L["choose_sub"] = "Выберите один из уже доступных профилей."
L["copy_desc"] = "Скопировать настройки профиля в на данный момент активный профиль."
L["copy"] = "Скопировать с"
L["delete_desc"] = "Удалить существующий и неиспользуемый профиль из БД для сохранения места, и очистить SavedVariables файл."
L["delete"] = "Удалить профиль"
L["delete_sub"] = "Удаления профиля из БД."
L["delete_confirm"] = "Вы уверены что вы хотите удалить выбранный профиль?"
L["profiles"] = "Профиля"
L["profiles_sub"] = "Управление профилями"
end
local defaultProfiles
local tmpprofiles = {}
--[[
getProfileList(db, common, nocurrent)
db - the db object to retrieve the profiles from
common (boolean) - if common is true, getProfileList will add the default profiles to the return list, even if they have not been created yet
nocurrent (boolean) - if true then getProfileList will not display the current profile in the list
]]--
local function getProfileList(db, common, nocurrent)
local profiles = {}
-- copy existing profiles into the table
local currentProfile = db:GetCurrentProfile()
for i,v in pairs(db:GetProfiles(tmpprofiles)) do
if not (nocurrent and v == currentProfile) then
profiles[v] = v
end
end
-- add our default profiles to choose from ( or rename existing profiles)
for k,v in pairs(defaultProfiles) do
if (common or profiles[k]) and not (nocurrent and k == currentProfile) then
profiles[k] = v
end
end
return profiles
end
--[[
OptionsHandlerPrototype
prototype class for handling the options in a sane way
]]
local OptionsHandlerPrototype = {}
--[[ Reset the profile ]]
function OptionsHandlerPrototype:Reset()
self.db:ResetProfile()
end
--[[ Set the profile to value ]]
function OptionsHandlerPrototype:SetProfile(info, value)
self.db:SetProfile(value)
end
--[[ returns the currently active profile ]]
function OptionsHandlerPrototype:GetCurrentProfile()
return self.db:GetCurrentProfile()
end
--[[
List all active profiles
you can control the output with the .arg variable
currently four modes are supported
(empty) - return all available profiles
"nocurrent" - returns all available profiles except the currently active profile
"common" - returns all avaialble profiles + some commonly used profiles ("char - realm", "realm", "class", "Default")
"both" - common except the active profile
]]
function OptionsHandlerPrototype:ListProfiles(info)
local arg = info.arg
local profiles
if arg == "common" and not self.noDefaultProfiles then
profiles = getProfileList(self.db, true, nil)
elseif arg == "nocurrent" then
profiles = getProfileList(self.db, nil, true)
elseif arg == "both" then -- currently not used
profiles = getProfileList(self.db, (not self.noDefaultProfiles) and true, true)
else
profiles = getProfileList(self.db)
end
return profiles
end
--[[ Copy a profile ]]
function OptionsHandlerPrototype:CopyProfile(info, value)
self.db:CopyProfile(value)
end
--[[ Delete a profile from the db ]]
function OptionsHandlerPrototype:DeleteProfile(info, value)
self.db:DeleteProfile(value)
end
--[[ fill defaultProfiles with some generic values ]]
local function generateDefaultProfiles(db)
defaultProfiles = {
["Default"] = L["default"],
[db.keys.char] = db.keys.char,
[db.keys.realm] = db.keys.realm,
[db.keys.class] = UnitClass("player")
}
end
--[[ create and return a handler object for the db, or upgrade it if it already existed ]]
local function getOptionsHandler(db, noDefaultProfiles)
if not defaultProfiles then
generateDefaultProfiles(db)
end
local handler = AceDBOptions.handlers[db] or { db = db, noDefaultProfiles = noDefaultProfiles }
for k,v in pairs(OptionsHandlerPrototype) do
handler[k] = v
end
AceDBOptions.handlers[db] = handler
return handler
end
--[[
the real options table
]]
local optionsTable = {
desc = {
order = 1,
type = "description",
name = L["intro"] .. "\n",
},
descreset = {
order = 9,
type = "description",
name = L["reset_desc"],
},
reset = {
order = 10,
type = "execute",
name = L["reset"],
desc = L["reset_sub"],
func = "Reset",
},
choosedesc = {
order = 20,
type = "description",
name = "\n" .. L["choose_desc"],
},
new = {
name = L["new"],
desc = L["new_sub"],
type = "input",
order = 30,
get = false,
set = "SetProfile",
},
choose = {
name = L["choose"],
desc = L["choose_sub"],
type = "select",
order = 40,
get = "GetCurrentProfile",
set = "SetProfile",
values = "ListProfiles",
arg = "common",
},
copydesc = {
order = 50,
type = "description",
name = "\n" .. L["copy_desc"],
},
copyfrom = {
order = 60,
type = "select",
name = L["copy"],
desc = L["copy_desc"],
get = false,
set = "CopyProfile",
values = "ListProfiles",
arg = "nocurrent",
},
deldesc = {
order = 70,
type = "description",
name = "\n" .. L["delete_desc"],
},
delete = {
order = 80,
type = "select",
name = L["delete"],
desc = L["delete_sub"],
get = false,
set = "DeleteProfile",
values = "ListProfiles",
arg = "nocurrent",
confirm = true,
confirmText = L["delete_confirm"],
},
}
--[[
GetOptionsTable(db)
db - the database object to create the options table for
creates and returns a option table to be used in your addon
]]
function AceDBOptions:GetOptionsTable(db, noDefaultProfiles)
local tbl = AceDBOptions.optionTables[db] or {
type = "group",
name = L["profiles"],
desc = L["profiles_sub"],
}
tbl.handler = getOptionsHandler(db, noDefaultProfiles)
tbl.args = optionsTable
AceDBOptions.optionTables[db] = tbl
return tbl
end
-- upgrade existing tables
for db,tbl in pairs(AceDBOptions.optionTables) do
tbl.handler = getOptionsHandler(db)
tbl.args = optionsTable
end
| mit |
philsiff/Red-Vs-Blue | Very Basic TDM [Gamemode]/gamemodes/vbtdm/gamemode/playerspawns/sv_spawns.lua | 1 | 9665 | --[[
For this spawn system to work, these lines need to be placed in the gamemode's init.lua:
function GM:PlayerSelectSpawn( ply )
local Team = ply:Team()
points = ents.FindByClass("team" .. Team)
if #points == 0 then
points = ents.FindByClass("info_player_start")
end
return points[math.random(#points)]
end
--]]
if not(SERVER) then return end
local map = string.Replace(game.GetMap(),"_","") //replace any underscores or
local map = string.Replace(map,".","") //periods, they don't work for file names
if (not file.IsDir("vbtdm/teamspawns","DATA")) then
file.CreateDir("vbtdm/teamspawns")
end
if not(file.Exists("vbtdm/teamspawns/"..map..".txt","DATA")) then
file.Write("vbtdm/teamspawns/"..map..".txt","")
print("[VBTDM] Wrote file : " .. "vbtdm/teamspawns/"..map..".txt")
end
function CheckSetSpawn(ply,text,public)
text = string.lower(text)
local exp = string.Explode(" ", text) //split it into 3 words
//set a spawn
if exp[1] == "!setspawn" then
if not(ply:IsAdmin()) then
umsg.Start("Error",ply)
umsg.String("This feature is for SuperAdmins only")
umsg.End()
return end
if #exp ~= 3 then //Incorrect number or arguments for the command
umsg.Start("Error",ply)
umsg.String("Format command as !setspawn team_name spawn_number")
umsg.End()
return
end
local Team = CheckTeam(exp[2])
if not(Team) then //If CheckTeam return false -- there wasn't a team
umsg.Start("Error",ply)
umsg.String("That team name doesn't exist. Format command as !setspawn team_name spawn_number")
umsg.End()
return
end
spawnnum = tonumber(exp[3])
//If the number isn't an int between 1 and 9
if not(spawnnum) or spawnnum < 1 or spawnnum > 9 or spawnnum ~= math.floor(spawnnum) then
umsg.Start("Error",ply)
umsg.String("That's not a valid spawn number(should be 1-9). Format command as !setspawn team_name spawn_number")
umsg.End()
return
end
if (spawnnum) or spawnnum < 1 or spawnnum > 9 or spawnnum ~= math.floor(spawnnum) or (Team) or #exp ~= 3 then
umsg.Start("Success",ply)
umsg.String("Successfully set spawn point "..exp[3].. " for team "..exp[2])
umsg.End()
end
if not(CheckCanSet(ply,Team,spawnnum)) then return end
WriteSpawn(ply,Team,spawnnum)
end
//remove a spawn
if exp[1] == "!removespawn" then
if not(ply:IsAdmin()) then
umsg.Start("Error",ply)
umsg.String("This feature is for SuperAdmins only")
umsg.End()
return end
if #exp ~= 3 then //Incorrect number or arguments for the command
umsg.Start("Error",ply)
umsg.String("Format command as !removespawn team_name spawn_number")
umsg.End()
return
end
local Team = CheckTeam(exp[2])
if not(Team) then //If CheckTeam return false -- there wasn't a team
umsg.Start("Error",ply)
umsg.String("That team name doesn't exist. Format command as !removespawn team_name spawn_number")
umsg.End()
return
end
spawnnum = tonumber(exp[3])
//If the number isn't an int between 1 and 9
if not(spawnnum) or spawnnum < 1 or spawnnum > 9 or spawnnum ~= math.floor(spawnnum) then
umsg.Start("Error",ply)
umsg.String("That's not a valid spawn number(should be 1-9). Format command as !removespawn team_name spawn_number")
umsg.End()
return
end
if (spawnnum) or spawnnum < 1 or spawnnum > 9 or spawnnum ~= math.floor(spawnnum) or (Team) or #exp ~= 3 then
umsg.Start("Success",ply)
umsg.String("Successfully removed spawn point "..exp[3].. " for team "..exp[2])
umsg.End()
end
RemoveSpawn(Team,spawnnum)
end
//Reload spawns
if exp[1] == "!reloadspawns" then
if not(ply:IsAdmin()) then
umsg.Start("Error",ply)
umsg.String("This feature is for SuperAdmins only")
umsg.End()
else
umsg.Start("Success",ply)
umsg.String("Successfully reloaded spawns")
umsg.End()
MakeSpawns()
return end
end
local checkspawnmodels = "1"
if (not file.IsDir("vbtdm/teamspawns","DATA")) then
file.CreateDir("vbtdm/teamspawns")
end
if not(file.Exists("vbtdm/teamspawns/showmodel.txt","DATA")) then
file.Write("vbtdm/teamspawns/showmodel.txt", checkspawnmodels)
print("[VBTDM] Wrote file: vbtdm/teamspawns/showmodel.txt")
end
//Turn Show Models On
if exp[1] == "!showspawnson" then
if not(ply:IsAdmin()) then
umsg.Start("Error",ply)
umsg.String("This feature is for SuperAdmins only")
umsg.End()
else
umsg.Start("Success",ply)
umsg.String("Spawn points are now visable")
umsg.End()
print("[VBTDM] Turning on spawn point models")
local checkspawnmodels = "1"
if (not file.IsDir("vbtdm/teamspawns","DATA")) then
file.CreateDir("vbtdm/teamspawns")
end
if not(file.Exists("vbtdm/teamspawns/showmodel.txt","DATA")) then
file.Write("vbtdm/teamspawns/showmodel.txt", checkspawnmodels)
print("[VBTDM] Wrote file: vbtdm/teamspawns/showmodel.txt")
end
file.Write("vbtdm/teamspawns/showmodel.txt", checkspawnmodels)
MakeSpawns()
return end
end
//Turn Show Models Off
if exp[1] == "!showspawnsoff" then
if not(ply:IsAdmin()) then
umsg.Start("Error",ply)
umsg.String("This feature is for SuperAdmins only")
umsg.End()
else
umsg.Start("Success",ply)
umsg.String("Spawn points are no longer visable")
umsg.End()
print("[VBTDM] Turning off spawn point models")
local checkspawnmodels = "0"
if (not file.IsDir("vbtdm/teamspawns","DATA")) then
file.CreateDir("vbtdm/teamspawns")
end
if not(file.Exists("vbtdm/teamspawns/showmodel.txt","DATA")) then
file.Write("vbtdm/teamspawns/showmodel.txt", checkspawnmodels)
print("[VBTDM] Wrote file: vbtdm/teamspawns/showmodel.txt")
end
file.Write("vbtdm/teamspawns/showmodel.txt", checkspawnmodels)
MakeSpawns()
return end
end
end
hook.Add("PlayerSay","CheckSetSpawn",CheckSetSpawn)
function CheckTeam(name)
local teams = team.GetAllTeams()
for k,v in pairs(teams) do
if string.lower(team.GetName(k)) == name then
return k
end
end
return false
end
function CheckCanSet(ply,Team,spawnnum)
return true
end
function RemoveSpawn(Team,spawnnum)
local map = string.Replace(game.GetMap(),"_","")
local map = string.Replace(map,".","")
local spawns = file.Read("vbtdm/teamspawns/"..map..".txt","DATA")
local lines = string.Explode("\n", spawns)
for i, line in ipairs(lines) do
local data = string.Explode(";", line)
local FileTeam = tonumber(data[1])
local PointNum = tonumber(data[2])
if FileTeam == Team and PointNum == spawnnum then
spawns = string.Replace(spawns,line.."\n","")
end
end
file.Write("vbtdm/teamspawns/" .. map .. ".txt",spawns)
MakeSpawns()
end
function WriteSpawn(ply,Team,spawnnum)
RemoveSpawn(Team,spawnnum)
local vAngle = ply:GetAimVector()
local UpAngle = tostring(vAngle:Angle())
local pos = ply:GetPos()
// local pyr = tostring(ply:GetAngles())
local data = string.Explode(" ", UpAngle)
map = string.Replace(game.GetMap(),"_","")
map = string.Replace(map,".","")
file.Append("vbtdm/teamspawns/"..map..".txt",Team ..";".. spawnnum .. ";" .. pos.x .. "," .. pos.y .. "," .. pos.z .. "," .. data[1] .."," .. data[2] .. "," .. data[3] .. "\n")
MakeSpawns()
end
function MakeSpawns()
//if not SpawnEnts then SpawnEnts = {} end
local Teams = nil
Teams = table.Copy(team.GetAllTeams())
local map = string.Replace(game.GetMap(),"_","")
local map = string.Replace(map,".","")
local spawns = file.Read("vbtdm/teamspawns/"..map..".txt","DATA")
lines = string.Explode("\n", spawns)
// Now let's loop through all the lines so we can split those too
for i, line in ipairs(lines) do
local data = string.Explode(";", line)
if #data ~= 3 then break end
local Team = tonumber(data[1])
local SpawnNum = tonumber(data[2])
local PosString = string.Explode(",",data[3])
local Pos = {}
Pos[1] = PosString[1]
Pos[2] = PosString[2]
Pos[3] = PosString[3]
Pos[4] = PosString[4]
Pos[5] = PosString[5]
Pos[6] = PosString[6]
// local Pos = (tonumber(PosString[1]),tonumber(PosString[2]),tonumber(PosString[3]),tonumber(PosString[4]),tonumber(PosString[5]),tonumber(PosString[6]))
// local PosAngle = Vector(tonumber(PosString[4]),tonumber(PosString[5]),tonumber(PosString[6]))
if not(Teams[Team].Spawns) then
Teams[Team].Spawns = {}
end
Teams[Team].Spawns[SpawnNum] = Pos // Add the pos to that team's spawns
end
//remove old spawn points, easier than keeping a table of all of them/checking to see if they're already made
local oldpoints = ents.FindByClass("team*")
for _,v in pairs(oldpoints) do v:Remove() end
//spawn the entities for the spawns
for k,v in pairs(Teams) do //k = team index, v= team
if v.Spawns && #v.Spawns > 0 then
for i,j in pairs(v.Spawns) do // i = spawn index, j = pos
local ent = ents.Create("team"..k)
MsgN("[VBTDM] Creating spawn point for team: "..team.GetName(k))
MsgN("[VBTDM] X: ".. j[1])
MsgN("[VBTDM] Y: ".. j[2])
MsgN("[VBTDM] Z: ".. j[3])
MsgN("[VBTDM] Pitch: ".. j[4])
MsgN("[VBTDM] Yaw: ".. j[5])
MsgN("[VBTDM] Roll: ".. j[6])
ent:SetPos(Vector(j[1],j[2],j[3]))
ent:SetAngles(Angle(tonumber(j[4]),tonumber(j[5]),tonumber(j[6])))
local checkmodels = tonumber(file.Read("vbtdm/teamspawns/showmodel.txt","DATA"))
if checkmodels == 1 then
ent:SetModel("models/props_trainstation/TrackSign03.mdl")
ent:SetColor(team.GetColor(k))
ent:Spawn()
end
//local EntIndex = table.insert(SpawnEnts,ent)
//SpawnEnts[EntIndex].Team = k
//SpawnEnts[EntIndex].SpawnNum = i
end
//team.SetSpawnPoint(k,"team"..k)
end
end
end
function MapChange()
MakeSpawns()
end
hook.Add("PlayerConnect","MakeSpawns", MapChange)
timer.Create( "Spawn_Creator", 1, 1, function()
MakeSpawns()
end) | mit |
pazos/koreader | plugins/evernote.koplugin/JoplinClient.lua | 3 | 3590 | local json = require("json")
local http = require("socket.http")
local ltn12 = require("ltn12")
local JoplinClient = {
server_ip = "localhost",
server_port = 41184,
auth_token = ""
}
function JoplinClient:new(o)
o = o or {}
self.__index = self
setmetatable(o, self)
return o
end
function JoplinClient:_makeRequest(url, method, request_body)
local sink = {}
local request_body_json = json.encode(request_body)
local source = ltn12.source.string(request_body_json)
http.request{
url = url,
method = method,
sink = ltn12.sink.table(sink),
source = source,
headers = {
["Content-Length"] = #request_body_json,
["Content-Type"] = "application/json"
}
}
if not sink[1] then
error("No response from Joplin Server")
end
local response = json.decode(sink[1])
if response.error then
error(response.error)
end
return response
end
function JoplinClient:ping()
local sink = {}
http.request{
url = "http://"..self.server_ip..":"..self.server_port.."/ping",
method = "GET",
sink = ltn12.sink.table(sink)
}
if sink[1] == "JoplinClipperServer" then
return true
else
return false
end
end
-- If successful returns id of found note.
function JoplinClient:findNoteByTitle(title, notebook_id)
local url = "http://"..self.server_ip..":"..self.server_port.."/notes?".."token="..self.auth_token.."&fields=id,title,parent_id"
local notes = self:_makeRequest(url, "GET")
for _, note in pairs(notes) do
if note.title == title then
if notebook_id == nil or note.parent_id == notebook_id then
return note.id
end
end
end
return false
end
-- If successful returns id of found notebook (folder).
function JoplinClient:findNotebookByTitle(title)
local url = "http://"..self.server_ip..":"..self.server_port.."/folders?".."token="..self.auth_token.."&".."query="..title
local folders = self:_makeRequest(url, "GET")
for _, folder in pairs(folders) do
if folder.title== title then
return folder.id
end
end
return false
end
-- If successful returns id of created notebook (folder).
function JoplinClient:createNotebook(title, created_time)
local request_body = {
title = title,
created_time = created_time
}
local url = "http://"..self.server_ip..":"..self.server_port.."/folders?".."token="..self.auth_token
local response = self:_makeRequest(url, "POST", request_body)
return response.id
end
-- If successful returns id of created note.
function JoplinClient:createNote(title, note, parent_id, created_time)
local request_body = {
title = title,
body = note,
parent_id = parent_id,
created_time = created_time
}
local url = "http://"..self.server_ip..":"..self.server_port.."/notes?".."token="..self.auth_token
local response = self:_makeRequest(url, "POST", request_body)
return response.id
end
-- If successful returns id of updated note.
function JoplinClient:updateNote(note_id, note, title, parent_id)
local request_body = {
body = note,
title = title,
parent_id = parent_id
}
local url = "http://"..self.server_ip..":"..self.server_port.."/notes/"..note_id.."?token="..self.auth_token
local response = self:_makeRequest(url, "PUT", request_body)
return response.id
end
return JoplinClient
| agpl-3.0 |
NatWeiss/RGP | src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/MenuItem.lua | 7 | 1678 |
--------------------------------
-- @module MenuItem
-- @extend Node
-- @parent_module cc
--------------------------------
-- Enables or disables the item.
-- @function [parent=#MenuItem] setEnabled
-- @param self
-- @param #bool value
-- @return MenuItem#MenuItem self (return value: cc.MenuItem)
--------------------------------
-- Activate the item.
-- @function [parent=#MenuItem] activate
-- @param self
-- @return MenuItem#MenuItem self (return value: cc.MenuItem)
--------------------------------
-- Returns whether or not the item is enabled.
-- @function [parent=#MenuItem] isEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- The item was selected (not activated), similar to "mouse-over".
-- @function [parent=#MenuItem] selected
-- @param self
-- @return MenuItem#MenuItem self (return value: cc.MenuItem)
--------------------------------
-- Returns whether or not the item is selected.
-- @function [parent=#MenuItem] isSelected
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- The item was unselected.
-- @function [parent=#MenuItem] unselected
-- @param self
-- @return MenuItem#MenuItem self (return value: cc.MenuItem)
--------------------------------
-- Returns the outside box.
-- @function [parent=#MenuItem] rect
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
-- js NA
-- @function [parent=#MenuItem] getDescription
-- @param self
-- @return string#string ret (return value: string)
return nil
| mit |
mjarco/sysdig | userspace/sysdig/chisels/v_incoming_connections.lua | 7 | 1768 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
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/>.
--]]
view_info =
{
id = "incoming_connections",
name = "New Connections",
description = "List every newly established network connection.",
tags = {"Default"},
view_type = "list",
applies_to = {"", "container.id", "proc.pid", "thread.tid", "proc.name", "fd.name", "fd.containername", "fd.sport", "fd.dport", "fd.port", "fd.lport", "fd.rport"},
filter = "evt.type=accept and evt.dir=< and evt.failed=false",
columns =
{
{
name = "TIME",
field = "evt.time",
description = "Time when the connection was received by this machine.",
colsize = 19,
},
{
name = "Connection",
field = "fd.name",
description = "Connection tuple details.",
colsize = 40,
},
{
tags = {"containers"},
name = "Container",
field = "container.name",
description = "Name of the container. What this field contains depends on the containerization technology. For example, for docker this is the content of the 'NAMES' column in 'docker ps'",
colsize = 15
},
{
name = "Command",
field = "proc.exeline",
aggregation = "MAX",
description = "Name and argyuments of the process that received the connection.",
colsize = 0
}
}
}
| gpl-2.0 |
NatWeiss/RGP | src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/script/network/DeprecatedNetworkFunc.lua | 61 | 1123 | if nil == cc.XMLHttpRequest then
return
end
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of WebSocket will be deprecated begin
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
local WebSocketDeprecated = { }
function WebSocketDeprecated.sendTextMsg(self, string)
deprecatedTip("WebSocket:sendTextMsg","WebSocket:sendString")
return self:sendString(string)
end
WebSocket.sendTextMsg = WebSocketDeprecated.sendTextMsg
function WebSocketDeprecated.sendBinaryMsg(self, table,tablesize)
deprecatedTip("WebSocket:sendBinaryMsg","WebSocket:sendString")
string.char(unpack(table))
return self:sendString(string.char(unpack(table)))
end
WebSocket.sendBinaryMsg = WebSocketDeprecated.sendBinaryMsg
end
--functions of WebSocket will be deprecated end
| mit |
siktirmirza/seq | plugins/prosend.lua | 1 | 3893 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1]:lower() == 'send' then
local file = matches[3]
if matches[2]:lower() == 'sticker' and not matches[4] then
send_document(receiver, "./media/"..file..".webp", ok_cb, false)
end
if matches[2]:lower() == 'photo' then
send_photo(receiver, "./media/"..file..".jpeg", ok_cb, false)
send_photo(receiver, "./media/"..file..".jpg", ok_cb, false)
send_photo(receiver, "./media/"..file..".png", ok_cb, false)
end
if matches[2]:lower() == 'GIF' and not matches[4] then
send_photo(receiver, "./media/"..file..".gif", ok_cb, false)
end
if matches[2]:lower() == 'music' then
send_audio(receiver, "./media/"..file..".mp3", ok_cb, false)
send_audio(receiver, "./media/"..file..".flac", ok_cb, false)
send_audio(receiver, "./media/"..file..".aac", ok_cb, false)
end
if matches[2]:lower() == 'video' then
send_photo(receiver, "./media/"..file..".avi", ok_cb, false)
send_photo(receiver, "./media/"..file..".mpeg", ok_cb, false)
send_photo(receiver, "./media/"..file..".mp4", ok_cb, false)
end
if matches[2]:lower() == 'file' and is_sudo(msg) then
local extension = matches[4]
send_document(receiver, "./media/"..file..'.'..extension, ok_cb, false)
end
if matches[2]:lower() == 'plug' and is_sudo(msg) then
send_document(receiver, "./plugins/"..file..".lua", ok_cb, false)
end
if matches[2]:lower() == 'dev' or matches[2] == 'm4ster' or matches[2] == 'master' or matches[2] == 'developer' or matches[2] == 'creator'then
local extension = matches[4]
if matches[3]:lower() == 'file' then
send_document(receiver, "./media/M4STER.png", ok_cb, false)
elseif matches[3] ~= 'file' or not matches[3] then
send_photo(receiver, "./media/M4STER.png", ok_cb, false)
end
end
if matches[2]:lower() == 'manual' and is_admin(msg) then
local ruta = matches[3]
local document = matches[4]
send_document(receiver, "./"..ruta.."/"..document, ok_cb, false)
end
end
if matches[1]:lower() == 'extensions' then
return 'No disponible actualmente'
end
if matches[1]:lower() == 'list' and matches[2]:lower() == 'files' then
return 'No disponible actualmente'
--send_document(receiver, "./media/files/files.txt", ok_cb, false)
end
end
return {
description = "Kicking ourself (bot) from unmanaged groups.",
usage = {
"!list files : Envía un archivo con los nombres de todo lo que se puede enviar",
"!extensions : Envía un mensaje con las extensiones para cada tipo de archivo permitidas",
"➖➖➖➖➖➖➖➖➖➖",
"!send sticker <nombre del sticker> : Envía ese sticker del servidor",
"!send photo <nombre de la foto> <extension de la foto> : Envía esa foto del servidor",
"!send GIF <nombre del GIF> : Envía ese GIF del servidor",
"!send music <nombre de la canción <extension de la canción> : Envía esa canción del servidor",
"!send video <nombre del video> <extension del video> : Envía ese video del servidor",
"!send file <nombre del archivo> <extension del archivo> : Envía ese archivo del servidor",
"!send plugin <Nombre del plugin> : Envía ese archivo del servidor",
"!send manual <Ruta de archivo> <Nombre del plugin> : Envía un archivo desde el directorio TeleSeed",
"!send dev : Envía una foto del desarrollador"
},
patterns = {
"^[!/]([Ss]end) (.*) (.*) (.*)$",
"^[!/]([Ss]end) (.*) (.*)$",
"^[!/]([Ss]end) (.*)$",
"^[!/]([Ll]ist) (files)$",
"^[!/]([Ee]xtensions)$",
"^([Ss]end) (.*) (.*) (.*)$",
"^([Ss]end) (.*) (.*)$",
"^([Ss]end) (.*)$",
"^([Ll]ist) (files)$",
"^([Ee]xtensions)$"
},
run = run
}
end
--MODDED by @M4STER_ANGEL
| gpl-2.0 |
eggBOY91/Arctic-Core | src/scripts/lua/Lua/0Misc/0LCF_Includes/LCF_Gameobject.lua | 18 | 2928 | --[[
* ArcEmu MMORPG Server
* Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/>
* Copyright (C) 2008-2010 <http://www.ArcEmu.org/>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*]]
local GAMEOBJECT = LCF.GOMethods
assert(GAMEOBJECT)
function GAMEOBJECT:SetUnclickable()
self:SetUInt32Value(LCF.GAMEOBJECT_FLAGS,0x1)
end
function GAMEOBJECT:SetClickable()
self:SetUInt32Value(LCF.GAMEOBJECT_FLAGS,0x0)
end
function GAMEOBJECT:IsUnclickable()
local flags = self:SetUInt32Value(LCF.GAMEOBJECT_FLAGS,0x1)
if(bit_and(flags,0x1) ) then
return true
end
return false
end
function GAMEOBJECT:IsClickable()
local flags = self:SetUInt32Value(LCF.GAMEOBJECT_FLAGS,0x1)
if(bit_and(flags,0x1) == 0 or bit_and(flags, 0x2) ~= 0) then
return true
end
return false
end
function GAMEOBJECT:Respawn()
self:SetPosition(self:GetX(),self:GetY(),self:GetZ(),self:GetO())
end
function GAMEOBJECT:Close()
self:SetByte(LCF.GAMEOBJECT_BYTES_1,0,1)
end
function GAMEOBJECT:IsOpen()
return (self:GetByte(LCF.GAMEOBJECT_BYTES_1,0) == 0)
end
function GAMEOBJECT:IsClosed()
return (self:GetByte(LCF.GAMEOBJECT_BYTES_1,0) == 1)
end
function GAMEOBJECT:Open()
self:SetByte(LCF.GAMEOBJECT_BYTES_1,0,0)
end
function GAMEOBJECT:RegisterLuaEvent(func,delay,repeats,...)
self:RegisterEvent(LCF:CreateClosure(func,self,unpack(arg)),delay,repeats)
end
function GAMEOBJECT:SetCreator(creator)
local guid = creator:GetGUID()
self:SetUInt64Value(LCF.OBJECT_FIELD_CREATED_BY,guid)
end
function GAMEOBJECT:GetLocalCreature(entry)
local x,y,z = self:GetLocation()
local crc = self:GetCreatureNearestCoords(x,y,z,entry)
return crc
end
function GAMEOBJECT:GetLocalGameObject(entry)
local x,y,z = self:GetLocation()
local go = self:GetGameObjectNearestCoords(x,y,z,entry)
return go
end
function GAMEOBJECT:SpawnLocalCreature(entry,faction,duration)
local x,y,z,o = self:GetLocation()
self:SpawnCreature(entry,x,y,z,o,faction,duration)
end
function GAMEOBJECT:SpawnLocalGameObject(entry,duration)
local x,y,z,o = self:GetLocation()
self:SpawnGameObject(entry,x,y,z,o,duration)
end
function GAMEOBJECT:GetCreator()
local creator_guid = self:GetUInt64Value(LCF.UNIT_FIELD_CREATEDBY)
if(creator_guid == nil) then
creator_guid = self:GetUInt64Value(LCF.UNIT_FIELD_SUMMONEDBY)
end
return self:GetObject(creator_guid)
end | agpl-3.0 |
disslove2-bot/Mr.Mj-BOT | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"!qr [text]",
'!qr "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
NatWeiss/RGP | src/cocos2d-js/frameworks/js-bindings/cocos2d-x/cocos/scripting/lua-bindings/auto/api/TextBMFont.lua | 12 | 2334 |
--------------------------------
-- @module TextBMFont
-- @extend Widget
-- @parent_module ccui
--------------------------------
-- init a bitmap font atlas with an initial string and the FNT file
-- @function [parent=#TextBMFont] setFntFile
-- @param self
-- @param #string fileName
-- @return TextBMFont#TextBMFont self (return value: ccui.TextBMFont)
--------------------------------
-- Gets the string length of the label.<br>
-- Note: This length will be larger than the raw string length,<br>
-- if you want to get the raw string length, you should call this->getString().size() instead<br>
-- return string length.
-- @function [parent=#TextBMFont] getStringLength
-- @param self
-- @return long#long ret (return value: long)
--------------------------------
--
-- @function [parent=#TextBMFont] setString
-- @param self
-- @param #string value
-- @return TextBMFont#TextBMFont self (return value: ccui.TextBMFont)
--------------------------------
--
-- @function [parent=#TextBMFont] getString
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
-- @overload self, string, string
-- @overload self
-- @function [parent=#TextBMFont] create
-- @param self
-- @param #string text
-- @param #string filename
-- @return TextBMFont#TextBMFont ret (return value: ccui.TextBMFont)
--------------------------------
--
-- @function [parent=#TextBMFont] createInstance
-- @param self
-- @return Ref#Ref ret (return value: cc.Ref)
--------------------------------
--
-- @function [parent=#TextBMFont] getVirtualRenderer
-- @param self
-- @return Node#Node ret (return value: cc.Node)
--------------------------------
-- Returns the "class name" of widget.
-- @function [parent=#TextBMFont] getDescription
-- @param self
-- @return string#string ret (return value: string)
--------------------------------
--
-- @function [parent=#TextBMFont] getVirtualRendererSize
-- @param self
-- @return size_table#size_table ret (return value: size_table)
--------------------------------
-- Default constructor<br>
-- js ctor<br>
-- lua new
-- @function [parent=#TextBMFont] TextBMFont
-- @param self
-- @return TextBMFont#TextBMFont self (return value: ccui.TextBMFont)
return nil
| mit |
LuaDist2/luarocks | test/mock-server.lua | 7 | 2067 | #!/usr/bin/env lua
--- A simple LuaRocks mock-server for testing.
local restserver = require("restserver")
local server = restserver:new():port(8080)
server:add_resource("api/tool_version", {
{
method = "GET",
path = "/",
produces = "application/json",
handler = function(query)
local json = { version = query.current }
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("api/1/{id:[0-9]+}/status", {
{
method = "GET",
path = "/",
produces = "application/json",
handler = function(query)
local json = { user_id = "123", created_at = "29.1.1993" }
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("/api/1/{id:[0-9]+}/check_rockspec", {
{
method = "GET",
path = "/",
produces = "application/json",
handler = function(query)
local json = {}
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("/api/1/{id:[0-9]+}/upload", {
{
method = "POST",
path = "/",
produces = "application/json",
handler = function(query)
local json = {module = "luasocket", version = {id = "1.0"}, module_url = "http://localhost/luasocket", manifests = "root", is_new = "is_new"}
return restserver.response():status(200):entity(json)
end
}
})
server:add_resource("/api/1/{id:[0-9]+}/upload_rock/{id:[0-9]+}", {
{
method = "POST",
path = "/",
produces = "application/json",
handler = function(query)
local json = {"rock","module_url"}
return restserver.response():status(200):entity(json)
end
}
})
-- SHUTDOWN this mock-server
server:add_resource("/shutdown", {
{
method = "GET",
path = "/",
handler = function(query)
os.exit()
return restserver.response():status(200):entity()
end
}
})
-- This loads the restserver.xavante plugin
server:enable("restserver.xavante"):start() | mit |
pazos/koreader | frontend/ui/widget/closebutton.lua | 5 | 2446 | --[[--
Button widget that shows an "×" and handles closing window when tapped
Example:
local CloseButton = require("ui/widget/closebutton")
local parent_widget = OverlapGroup:new{}
table.insert(parent_widget, CloseButton:new{
window = parent_widget,
})
UIManager:show(parent_widget)
]]
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local GestureRange = require("ui/gesturerange")
local InputContainer = require("ui/widget/container/inputcontainer")
local TextWidget = require("ui/widget/textwidget")
local Screen = require("device").screen
local CloseButton = InputContainer:new{
overlap_align = "right",
window = nil,
padding_left = Screen:scaleBySize(14), -- for larger touch area
padding_right = 0,
padding_top = 0,
padding_bottom = 0,
}
function CloseButton:init()
local text_widget = TextWidget:new{
text = "×",
face = Font:getFace("cfont", 30),
}
-- The text box height is greater than its width, and we want this × to be
-- diagonally aligned with the top right corner (assuming padding_right=0,
-- or padding_right = padding_top so the diagonal aligment is preserved).
local text_size = text_widget:getSize()
local text_width_pad = (text_size.h - text_size.w) / 2
self[1] = FrameContainer:new{
bordersize = 0,
padding = 0,
padding_top = self.padding_top,
padding_bottom = self.padding_bottom,
padding_left = self.padding_left,
padding_right = self.padding_right + text_width_pad,
text_widget,
}
self.ges_events.Close = {
GestureRange:new{
ges = "tap",
-- x and y coordinates for the widget is only known after the it is
-- drawn. so use callback to get range at runtime.
range = function() return self.dimen end,
},
doc = "Tap on close button",
}
self.ges_events.HoldClose = {
GestureRange:new{
ges = "hold_release",
range = function() return self.dimen end,
},
doc = "Hold on close button",
}
end
function CloseButton:onClose()
if self.window.onClose then
self.window:onClose()
end
return true
end
function CloseButton:onHoldClose()
if self.window.onHoldClose then
self.window:onHoldClose()
end
return true
end
return CloseButton
| agpl-3.0 |
klyone/wishbone-gen | target_wishbone.lua | 1 | 8942 | -- -*- Mode: LUA; tab-width: 2 -*-
MAX_ACK_LENGTH = 10;
function gen_wishbone_ports()
local ports = {
port(BIT, 0, "in", "rst_n_i", "", VPORT_WB),
port(BIT, 0, "in", "wb_clk_i", "", VPORT_WB),
};
if(address_bus_width > 0 ) then
table_join(ports, { port(SLV, address_bus_width, "in", "wb_addr_i", "", VPORT_WB) });
end
table_join(ports, {
port(SLV, DATA_BUS_WIDTH, "in", "wb_data_i", "", VPORT_WB),
port(SLV, DATA_BUS_WIDTH, "out", "wb_data_o", "", VPORT_WB),
port(BIT, 0, "in", "wb_cyc_i", "", VPORT_WB),
port(SLV, math.floor((DATA_BUS_WIDTH+7)/8), "in", "wb_sel_i", "", VPORT_WB),
port(BIT, 0, "in", "wb_stb_i", "", VPORT_WB),
port(BIT, 0, "in", "wb_we_i", "", VPORT_WB),
port(BIT, 0, "out", "wb_ack_o", "", VPORT_WB)
});
if(periph.irqcount > 0) then
table_join(ports, { port(BIT, 0, "out" ,"wb_irq_o", "", VPORT_WB); });
end
add_global_ports(ports);
end
function gen_wishbone_signals()
local width = math.max(1, address_bus_width);
local wb_sigs = { signal(SLV, MAX_ACK_LENGTH, "ack_sreg"),
signal(SLV, DATA_BUS_WIDTH, "rddata_reg"),
signal(SLV, DATA_BUS_WIDTH, "wrdata_reg"),
signal(SLV, DATA_BUS_WIDTH/8 , "bwsel_reg"),
signal(SLV, width, "rwaddr_reg"),
signal(BIT, 0, "ack_in_progress"),
signal(BIT, 0, "wr_int"),
signal(BIT, 0, "rd_int"),
signal(BIT, 0, "bus_clock_int"),
signal(SLV, DATA_BUS_WIDTH, "allones"),
signal(SLV, DATA_BUS_WIDTH, "allzeros")
};
add_global_signals(wb_sigs);
end
-- generates the entire Wishbone bus access logic
function gen_bus_logic_wishbone()
local s;
gen_wishbone_ports();
gen_wishbone_signals();
foreach_reg(ALL_REG_TYPES, function(reg)
gen_abstract_code(reg);
end );
local resetcode={};
local ackgencode={};
local preackcode={};
foreach_field(function(field, reg)
table_join(resetcode, field.reset_code_main);
end );
foreach_reg(ALL_REG_TYPES, function(reg)
table_join(resetcode, reg.reset_code_main);
end );
foreach_reg({TYPE_REG}, function(reg)
foreach_subfield(reg, function(field, reg)
table_join(ackgencode, field.ackgen_code);
table_join(preackcode, field.ackgen_code_pre);
end);
table_join(ackgencode, reg.ackgen_code);
table_join(preackcode, reg.ackgen_code_pre);
end);
local fsmcode={};
foreach_reg({TYPE_REG}, function(reg)
local acklen = find_max(reg, "acklen");
local rcode={};
local wcode={};
foreach_subfield(reg, function(field, reg) table_join(wcode, field.write_code); end );
foreach_subfield(reg, function(field, reg) table_join(rcode, field.read_code); end );
local padcode = fill_unused_bits("rddata_reg", reg);
table_join(wcode, reg.write_code);
table_join(rcode, reg.read_code);
local rwcode = {
vif(vequal("wb_we_i" ,1), {
wcode,
}, {
rcode,
padcode
}); };
if(not (reg.dont_emit_ack_code == true)) then -- we don't want the main generator to mess with ACK line for this register
table_join(rwcode, { va(vi("ack_sreg", math.max(acklen-1, 0)), 1); } );
table_join(rwcode, { va("ack_in_progress", 1); });
end
if(regbank_address_bits > 0) then
rwcode = { vcase(reg.base, rwcode); };
end
table_join(fsmcode, rwcode);
end );
if(regbank_address_bits > 0) then
table_join(fsmcode, { vcasedefault({
vcomment("prevent the slave from hanging the bus on invalid address");
va("ack_in_progress", 1);
va(vi("ack_sreg", 0), 1);
}); });
fsmcode = { vswitch(vi("rwaddr_reg", regbank_address_bits - 1, 0), fsmcode); };
end
if(periph.ramcount > 0) then
local ramswitchcode = {};
if(periph.fifocount + periph.regcount > 0) then
-- append the register bank CASE statement if there are any registers or FIFOs
ramswitchcode = { vcase (0, fsmcode); };
end
foreach_reg({TYPE_RAM}, function(reg)
local acklen = csel(options.register_data_output, 1, 0);
table_join(ramswitchcode, { vcase(reg.select_bits , {
vif(vequal("rd_int" ,1), {
va(vi("ack_sreg", 0), 1);
}, {
va(vi("ack_sreg", acklen), 1);
});
va("ack_in_progress", 1);
} ); } );
end);
table_join(ramswitchcode, {
vcasedefault({
vcomment("prevent the slave from hanging the bus on invalid address");
va("ack_in_progress", 1);
va(vi("ack_sreg", 0), 1);
})
});
fsmcode = { vswitch(vi("rwaddr_reg", address_bus_width-1, address_bus_width - address_bus_select_bits), ramswitchcode); };
end
fsmcode = { vif(vand(vequal("wb_cyc_i", 1), vequal("wb_stb_i", 1)), { fsmcode } ); };
local code = {
vcomment("Some internal signals assignments. For (foreseen) compatibility with other bus standards.");
va("wrdata_reg", "wb_data_i");
va("bwsel_reg", "wb_sel_i");
va("bus_clock_int", "wb_clk_i");
va("rd_int", vand("wb_cyc_i", vand("wb_stb_i", vnot("wb_we_i"))));
va("wr_int", vand("wb_cyc_i", vand("wb_stb_i", "wb_we_i")));
va("allones", vothers(1));
va("allzeros", vothers(0));
vcomment("");
vcomment("Main register bank access process.");
vsyncprocess("bus_clock_int", "rst_n_i", {
vreset(0, {
va("ack_sreg", 0);
va("ack_in_progress", 0);
va("rddata_reg", 0);
resetcode
});
vposedge ({
vcomment("advance the ACK generator shift register");
va(vi("ack_sreg", MAX_ACK_LENGTH-2, 0), vi("ack_sreg", MAX_ACK_LENGTH-1, 1));
va(vi("ack_sreg", MAX_ACK_LENGTH-1), 0);
vif(vequal("ack_in_progress", 1), {
vif(vequal(vi("ack_sreg", 0), 1), { ackgencode; va("ack_in_progress", 0); }, preackcode);
}, {
fsmcode
});
});
});
};
-- we have some RAMs in our slave?
if(periph.ramcount > 0) then
-- the data output is muxed between RAMs and register bank. Here we generate a combinatorial mux if we don't want the output to be registered. This gives us
-- memory access time of 2 clock cycles. Otherwise the ram output is handled by the main process.
if(not options.register_data_output) then
local sens_list = {"rddata_reg","rwaddr_reg"};
local mux_switch_code = {};
local mux_code = {vswitch(vi("rwaddr_reg", address_bus_width-1, address_bus_width - address_bus_select_bits), mux_switch_code); };
local output_mux_process = {vcomment("Data output multiplexer process"); vcombprocess(sens_list, mux_code);};
foreach_reg({TYPE_RAM}, function(reg)
table.insert(sens_list, reg.full_prefix.."_rddata_int");
local assign_code = { va(vi("wb_data_o", reg.width-1, 0), reg.full_prefix.."_rddata_int"); };
if(reg.width < DATA_BUS_WIDTH) then
table_join(assign_code, { va(vi("wb_data_o", DATA_BUS_WIDTH-1, reg.width), 0); });
end
table_join(mux_switch_code, { vcase(reg.select_bits, assign_code ); } );
end);
table.insert(sens_list, "wb_addr_i");
table_join(mux_switch_code, {vcasedefault(va("wb_data_o", "rddata_reg")); } );
table_join(code, output_mux_process);
end
-- now generate an address decoder for the RAMs, driving rd_i and wr_i lines.
local sens_list = { "wb_addr_i", "rd_int", "wr_int" };
local proc_body = { };
foreach_reg({TYPE_RAM}, function(reg)
-- table.insert(sens_list, reg.full_prefix.."_rddata_int");
table_join(proc_body, {vif(vequal(vi("wb_addr_i", address_bus_width-1, address_bus_width - address_bus_select_bits), reg.select_bits), {
va(reg.full_prefix.."_rd_int", "rd_int");
va(reg.full_prefix.."_wr_int", "wr_int");
}, {
va(reg.full_prefix.."_wr_int", 0);
va(reg.full_prefix.."_rd_int", 0);
}); });
end);
table_join(code, {vcomment("Read & write lines decoder for RAMs"); vcombprocess(sens_list, proc_body); });
else -- no RAMs in design? wire rddata_reg directly to wb_data_o
table_join(code, {vcomment("Drive the data output bus"); va("wb_data_o", "rddata_reg") } );
end
foreach_reg(ALL_REG_TYPES, function(reg)
if(reg.extra_code ~= nil) then
table_join(code, {vcomment("extra code for reg/fifo/mem: "..reg.name);});
table_join(code, reg.extra_code);
end
foreach_subfield(reg, function(field, reg)
if (field.extra_code ~= nil) then
table_join(code, {vcomment(field.name); field.extra_code});
end
end );
end);
if(address_bus_width > 0) then
table_join(code, { va("rwaddr_reg", "wb_addr_i"); });
else
table_join(code, { va("rwaddr_reg", vothers(0)); });
end
table_join(code, { vcomment("ACK signal generation. Just pass the LSB of ACK counter.");
va("wb_ack_o", vi("ack_sreg", 0));
});
return code;
end
| gpl-2.0 |
KTXSoftware/haxe_bin | std/lua/_lua/_hx_tostring.lua | 1 | 3309 |
function _hx_print_class(obj, depth)
local first = true
local result = ''
for k,v in pairs(obj) do
if _hx_hidden[k] == nil then
if first then
first = false
else
result = result .. ', '
end
if _hx_hidden[k] == nil then
result = result .. k .. ':' .. _hx_tostring(v, depth+1)
end
end
end
return '{ ' .. result .. ' }'
end
function _hx_print_enum(o, depth)
if o.length == 2 then
return o[0]
else
local str = o[0] .. "("
for i = 2, (o.length-1) do
if i ~= 2 then
str = str .. "," .. _hx_tostring(o[i], depth+1)
else
str = str .. _hx_tostring(o[i], depth+1)
end
end
return str .. ")"
end
end
function _hx_tostring(obj, depth)
if depth == nil then
depth = 0
elseif depth > 5 then
return "<...>"
end
local tstr = _G.type(obj)
if tstr == "string" then return obj
elseif tstr == "nil" then return "null"
elseif tstr == "number" then
if obj == _G.math.POSITIVE_INFINITY then return "Infinity"
elseif obj == _G.math.NEGATIVE_INFINITY then return "-Infinity"
elseif obj == 0 then return "0"
elseif obj ~= obj then return "NaN"
else return _G.tostring(obj)
end
elseif tstr == "boolean" then return _G.tostring(obj)
elseif tstr == "userdata" then
local mt = _G.getmetatable(obj)
if mt ~= nil and mt.__tostring ~= nil then
return _G.tostring(obj)
else
return "<userdata>"
end
elseif tstr == "function" then return "<function>"
elseif tstr == "thread" then return "<thread>"
elseif tstr == "table" then
if obj.__enum__ ~= nil then
return _hx_print_enum(obj, depth)
elseif obj.toString ~= nil and not _hx_is_array(obj) then return obj:toString()
elseif _hx_is_array(obj) then
if obj.length > 5 then
return "[...]"
else
str = ""
for i=0, (obj.length-1) do
if i == 0 then
str = str .. _hx_tostring(obj[i], depth+1)
else
str = str .. "," .. _hx_tostring(obj[i], depth+1)
end
end
return "[" .. str .. "]"
end
elseif obj.__class__ ~= nil then
return _hx_print_class(obj, depth)
else
first = true
buffer = {}
for k,v in pairs(obj) do
if _hx_hidden[k] == nil then
_G.table.insert(buffer, _hx_tostring(k, depth+1) .. ' : ' .. _hx_tostring(obj[k], depth+1))
end
end
return "{ " .. table.concat(buffer, ", ") .. " }"
end
else
_G.error("Unknown Lua type", 0)
return ""
end
end
function _hx_error(obj)
print(obj)
if obj.value then
_G.print("Runtime Error: " .. _hx_tostring(obj.value));
else
_G.print("Runtime Error: " .. tostring(obj));
end
if _G.debug and _G.debug.traceback then
_G.print(debug.traceback());
end
end
| lgpl-2.1 |
zaeem55/meme | plugins/ingroup.lua | 371 | 44212 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
local user_info = redis:hgetall('user:'..group_owner)
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
if user_info.username then
return "Group onwer is @"..user_info.username.." ["..group_owner.."]"
else
return "Group owner is ["..group_owner..']'
end
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |