repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
akh00/kong
kong/plugins/bot-detection/rules.lua
13
3575
-- List taken from https://github.com/ua-parser/uap-core/blob/master/regexes.yaml return { bots = { [[(Pingdom.com_bot_version_)(\d+)\.(\d+)]], -- Pingdom [[(facebookexternalhit)/(\d+)\.(\d+)]], -- Facebook [[Google.*/\+/web/snippet]], -- Google Plus [[(Twitterbot)/(\d+)\.(\d+)]], -- Twitter [[/((?:Ant-)?Nutch|[A-z]+[Bb]ot|[A-z]+[Ss]pider|Axtaris|fetchurl|Isara|ShopSalad|Tailsweep)[ \-](\d+)(?:\.(\d+)(?:\.(\d+))?)?]], -- Bots Pattern '/name-0.0' [[(008|Altresium|Argus|BaiduMobaider|BoardReader|DNSGroup|DataparkSearch|EDI|Goodzer|Grub|INGRID|Infohelfer|LinkedInBot|LOOQ|Nutch|PathDefender|Peew|PostPost|Steeler|Twitterbot|VSE|WebCrunch|WebZIP|Y!J-BR[A-Z]|YahooSeeker|envolk|sproose|wminer)/(\d+)(?:\.(\d+)(?:\.(\d+))?)?]], --Bots Pattern 'name/0.0' [[(MSIE) (\d+)\.(\d+)([a-z]\d?)?;.* MSIECrawler]], --MSIECrawler [[(Google-HTTP-Java-Client|Apache-HttpClient|http%20client|Python-urllib|HttpMonitor|TLSProber|WinHTTP|JNLP)(?:[ /](\d+)(?:\.(\d+)(?:\.(\d+))?)?)?]], -- Downloader ... [[(1470\.net crawler|50\.nu|8bo Crawler Bot|Aboundex|Accoona-[A-z]+-Agent|AdsBot-Google(?:-[a-z]+)?|altavista|AppEngine-Google|archive.*?\.org_bot|archiver|Ask Jeeves|[Bb]ai[Dd]u[Ss]pider(?:-[A-Za-z]+)*|bingbot|BingPreview|blitzbot|BlogBridge|BoardReader(?: [A-Za-z]+)*|boitho.com-dc|BotSeer|\b\w*favicon\w*\b|\bYeti(?:-[a-z]+)?|Catchpoint bot|[Cc]harlotte|Checklinks|clumboot|Comodo HTTP\(S\) Crawler|Comodo-Webinspector-Crawler|ConveraCrawler|CRAWL-E|CrawlConvera|Daumoa(?:-feedfetcher)?|Feed Seeker Bot|findlinks|Flamingo_SearchEngine|FollowSite Bot|furlbot|Genieo|gigabot|GomezAgent|gonzo1|(?:[a-zA-Z]+-)?Googlebot(?:-[a-zA-Z]+)?|Google SketchUp|grub-client|gsa-crawler|heritrix|HiddenMarket|holmes|HooWWWer|htdig|ia_archiver|ICC-Crawler|Icarus6j|ichiro(?:/mobile)?|IconSurf|IlTrovatore(?:-Setaccio)?|InfuzApp|Innovazion Crawler|InternetArchive|IP2[a-z]+Bot|jbot\b|KaloogaBot|Kraken|Kurzor|larbin|LEIA|LesnikBot|Linguee Bot|LinkAider|LinkedInBot|Lite Bot|Llaut|lycos|Mail\.RU_Bot|masidani_bot|Mediapartners-Google|Microsoft .*? Bot|mogimogi|mozDex|MJ12bot|msnbot(?:-media *)?|msrbot|netresearch|Netvibes|NewsGator[^/]*|^NING|Nutch[^/]*|Nymesis|ObjectsSearch|Orbiter|OOZBOT|PagePeeker|PagesInventory|PaxleFramework|Peeplo Screenshot Bot|PlantyNet_WebRobot|Pompos|Read%20Later|Reaper|RedCarpet|Retreiver|Riddler|Rival IQ|scooter|Scrapy|Scrubby|searchsight|seekbot|semanticdiscovery|Simpy|SimplePie|SEOstats|SimpleRSS|SiteCon|Slurp|snappy|Speedy Spider|Squrl Java|TheUsefulbot|ThumbShotsBot|Thumbshots\.ru|TwitterBot|URL2PNG|Vagabondo|VoilaBot|^vortex|Votay bot|^voyager|WASALive.Bot|Web-sniffer|WebThumb|WeSEE:[A-z]+|WhatWeb|WIRE|WordPress|Wotbox|www\.almaden\.ibm\.com|Xenu(?:.s)? Link Sleuth|Xerka [A-z]+Bot|yacy(?:bot)?|Yahoo[a-z]*Seeker|Yahoo! Slurp|Yandex\w+|YodaoBot(?:-[A-z]+)?|YottaaMonitor|Yowedo|^Zao|^Zao-Crawler|ZeBot_www\.ze\.bz|ZooShot|ZyBorg)(?:[ /]v?(\d+)(?:\.(\d+)(?:\.(\d+))?)?)?]], -- Bots [[(?:\/[A-Za-z0-9\.]+)? *([A-Za-z0-9 \-_\!\[\]:]*(?:[Aa]rchiver|[Ii]ndexer|[Ss]craper|[Bb]ot|[Ss]pider|[Cc]rawl[a-z]*))/(\d+)(?:\.(\d+)(?:\.(\d+))?)?]], -- Bots General matcher 'name/0.0' [[(?:\/[A-Za-z0-9\.]+)? *([A-Za-z0-9 _\!\[\]:]*(?:[Aa]rchiver|[Ii]ndexer|[Ss]craper|[Bb]ot|[Ss]pider|[Cc]rawl[a-z]*)) (\d+)(?:\.(\d+)(?:\.(\d+))?)?]], -- Bots General matcher 'name 0.0' [[((?:[A-z0-9]+|[A-z\-]+ ?)?(?: the )?(?:[Ss][Pp][Ii][Dd][Ee][Rr]|[Ss]crape|[A-Za-z0-9-]*(?:[^C][^Uu])[Bb]ot|[Cc][Rr][Aa][Ww][Ll])[A-z0-9]*)(?:(?:[ /]| v)(\d+)(?:\.(\d+)(?:\.(\d+))?)?)?]] -- Bots containing spider|scrape|bot(but not CUBOT)|Crawl } }
apache-2.0
mamaddeveloper/sedm
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
chtyim/infrastructure-puppet
modules/kibana_asf/files/JSON.lua
5
19816
local VERSION = 20111207.5 local OBJDEF = { VERSION = VERSION } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local match_start, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if not text:sub(start,start) == '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local val, new_i = grok_one(self, text, i) VALUE[key] = val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if not text:sub(start,start) == '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) table.insert(VALUE, val) i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- should never get here... JSON parse errors should have been caught earlier assert(false, value) return nil end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local seen_number_key = false local maximum_number_key for key in pairs(T) do if type(key) == 'number' then seen_number_key = true if not maximum_number_key or maximum_number_key < key then maximum_number_key = key end elseif type(key) == 'string' then table.insert(string_keys, key) else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if seen_number_key and #string_keys > 0 then -- -- Mixed key types... don't know what to do, so bail -- self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) elseif #string_keys == 0 then -- -- An array -- if seen_number_key then return nil, maximum_number_key -- an array else -- -- An empty table... -- if tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end else -- -- An object, so return a list of keys -- table.sort(string_keys) return string_keys end end -- -- Encode -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc) if value == nil then return nil end if type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc)) end result_value = "[" .. table.concat(ITEMS, ",") .. "]" elseif object_keys then -- -- An object -- -- -- We'll always sort the keys, so that comparisons can be made on -- the results, etc. The actual order is not particularly -- important (e.g. it doesn't matter what character set we sort -- as); it's only important that it be deterministic... the same -- every time. -- local PARTS = { } for _, key in ipairs(object_keys) do local encoded_key = encode_value(self, tostring(key), parents, etc) local encoded_val = encode_value(self, T[key], parents, etc) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end local encode_pretty_value -- must predeclare because it calls itself function encode_pretty_value(self, value, parents, indent, etc) if type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then return tostring(value) elseif type(value) == 'boolean' then return tostring(value) elseif type(value) == 'nil' then return 'null' elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) end parents[T] = true local result_value local object_keys = object_or_array(self, T, etc) if not object_keys then -- -- An array... -- local ITEMS = { } for i = 1, #T do table.insert(ITEMS, encode_pretty_value(self, T[i], parents, indent, etc)) end result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else -- -- An object -- can keys be numbers? -- local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_pretty_value(self, tostring(key), parents, "", etc) max_key_length = math.max(max_key_length, #encoded) table.insert(KEYS, encoded) end local key_indent = indent .. " " local subtable_indent = indent .. string.rep(" ", max_key_length + 2 + 4) local FORMAT = "%s%" .. tostring(max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_pretty_value(self, T[key], parents, subtable_indent, etc) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end local parents = {} return encode_value(self, value, parents, etc) end function OBJDEF:encode_pretty(value, etc) local parents = {} local subtable_indent = "" return encode_pretty_value(self, value, parents, subtable_indent, etc) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new()
apache-2.0
kennethlombardi/moai-components
Data/LunaTest/tests/EventSuite.lua
1
7526
module(..., package.seeall) local pickle = require("Pickle").pickle local PASSED = true local FAILED = false local testDirectory = "./Data/Scripts/Test/" function passResult() end local function START_THE_REACTOR() Event:initialize() end local function STOP_THE_REACTOR() Event:shutdown() end local function RESTART_THE_REACTOR() STOP_THE_REACTOR() Event = require("Event") START_THE_REACTOR() end function suite_setup() Event = require("Event") end function setup() RESTART_THE_REACTOR() end function test_twoObjectsListeningAndResponding() -- simulate 2 objects listening and responding to messages on a certain frame local eventsForFrame = {} table.insert(eventsForFrame, 42, { type = 'EXPLOSION_EVENT', arguments = {position = {x = 42, y = 42, z = 42}} }) local kitty = { name = "kitty", exploded = false, explosionPosition = {x = 0, y = 0, z = 0} } function kitty:onEvent(event) self.exploded = true self.explosionPosition.x = event.arguments.position.x self.explosionPosition.y = event.arguments.position.y self.explosionPosition.z = event.arguments.position.z event.arguments.position.z = 100 end local puppy = { name = "puppy", exploded = false, explosionPosition = {x = 1, y = 1, z = 1} } function puppy:onEvent(event) self.exploded = true self.explosionPosition.x = event.arguments.position.x self.explosionPosition.y = event.arguments.position.y self.explosionPosition.z = event.arguments.position.z end Event.listen("EXPLOSION_EVENT", kitty) Event.listen("EXPLOSION_EVENT", puppy) local frame = 0 while frame < 100 do if eventsForFrame[frame] then local event = eventsForFrame[frame] Event.send(event.type, event.arguments) table.remove(eventsForFrame, frame) end Event:update(0.016) frame = frame + 1 end local passed = PASSED and kitty.exploded == true and kitty.explosionPosition.x == 42 and kitty.explosionPosition.y == 42 and kitty.explosionPosition.z == 42 and puppy.exploded == true and puppy.explosionPosition.x == 42 and puppy.explosionPosition.y == 42 and puppy.explosionPosition.z == 100 -- kitty is a dick, got the message first, and changed it -- The fact I am checking so many assertions means I need to break this thing up into different functions assert_true(passed, "Object didn't get message, or first receiver didn't change message") end function test_listenToMessageThenIgnore() local kitty = { name = "kitty", exploded = true } function kitty:onEvent(event) if event.arguments.position.x > 0 then self.exploded = false elseif event.arguments.position.x == 0 then self.exploded = true end self.explosionPositionx = event.arguments.position.x end Event.listen("EXPLOSION_EVENT", kitty) Event.update() Event.send("EXPLOSION_EVENT", {position = {x = 1, y = 0, z = 0}}) Event.update() -- kitty should not explode (explosion missed) Event.ignore("EXPLOSION_EVENT", kitty) Event.send("EXPLOSION_EVENT", {position = {x = 0, y = 0, z = 0}}) Event.update() -- kitty should ignore the explosion event and exploded should be false local passed = PASSED and kitty.exploded == false and kitty.explosionPositionx == 1 -- kitty saw the x = 1 explosion but ignored the x = 0 explosion assert_true(passed, "Object: "..kitty.name.." did not ignore the message and exploded") end function test_listenToMessageThenIgnoreConfirmEventSystemHasZeroListeners() local kitty = {name = "kitty"} function kitty:onEvent(Event) end for i = 1, 100 do Event.listen("EXPLOSION_EVENT", kitty) Event.ignore("EXPLOSION_EVENT", kitty) end Event.listen("EXPLOSION_EVENT", kitty) Event.listen("EXPLOSION_EVENT", kitty) Event.listen("EXPLOSION_EVENT", kitty) Event.ignore("EXPLOSION_EVENT", kitty) -- probably shouldn't do this -- hooking directly under the event system to see how many listeners it has local listenerCount = Event._getListenerCount("EXPLOSION_EVENT") local passed = PASSED and listenerCount == 0 assert_true(passed, "A listener was not removed when it ignored the message EXPLOSION_EVENT") end function test_listenToTwoMessages() local kitty = {name = "kitty", sawExplosion = false, heardYell = false} function kitty:onEvent(event) if event.type == "YELL_EVENT" then self.heardYell = true elseif event.type == "EXPLOSION_EVENT" then self.sawExplosion = true end end -- Frame 1 Event.update() Event.listen("YELL_EVENT", kitty) Event.listen("EXPLOSION_EVENT", kitty) -- Frame 2 Event.update() Event.send("YELL_EVENT", {position = {x = 0, y = 0, z = 0}, volume = 100}) Event.send("EXPLOSION_EVENT", {position = {x = 0, y = 0, z = 0}}) -- Frame 3 Event.update() -- kitty should have heard a yell and seen an explosion local passed = PASSED and kitty.heardYell == true and kitty.sawExplosion == true assert_true(kitty.heardYell, "Kitty didn't hear a yell message") assert_true(kitty.sawExplosion, "Kitty didn't see the explosion message") end function test_objectSendsMessageInResponseToMessage() local kitty = {name = "kitty", positionx = 0, inDanger = true} local puppy = {name = "puppy", sawExplosion = false} function kitty:onEvent(event) if event.type == "YELL_EVENT" then -- move kitty -- kitty has good hearing and doesn't care about volume self.inDanger = false self.positionx = event.arguments.position.x end end function puppy:onEvent(event) if event.type == "EXPLOSION_EVENT" then Event.send("YELL_EVENT", {position = {x = 100, y = 100, z = 100}, volume = 100}) end end -- kitty will listen for a yell -- puppy will listen for the explosion and yell out its position of safety --Frame 1 Event.update() Event.listen("EXPLOSION_EVENT", puppy) Event.listen("YELL_EVENT", kitty) --Frame 2 Event.update() Event.send("EXPLOSION_EVENT", {position = {x = 0, y = 0, z = 0}}) --Frame 3 Event.update() -- puppy should get event notification and send out yell --Frame 4 Event.update() -- kitty should get the yell event local passed = PASSED and kitty.inDanger == false assert_false(kitty.inDanger, "Kitty didn't get the yell message") end function test_sendOneThousandMessagesAllMessagesFreedMemoryUseLessThanOrEqualAfter() Event.update() collectgarbage() local gcBefore = collectgarbage("count") for i = 1, 1000 do Event.send("EXPLOSION_EVENT", {position = {x = 0, y = 0, z = 0}}) end Event.update() collectgarbage() local gcAfter = collectgarbage("count") local passed = PASSED and gcAfter <= gcBefore assert_true(passed, "Memory usage grew by "..(gcAfter - gcBefore).."KB") end
mit
yozw/torch-dokx
luasrc/markdown.lua
3
3110
--- Handle Markdown generation local textx = require 'pl.text' -- This class opens and writes to a markdown file local MarkdownWriter = torch.class("dokx.MarkdownWriter") --[[ Constructor for MarkdownWriter Args: * `outputPath` - string; path to write to * `style` - string; 'repl' or 'html' - adjust the output style Returns: new MarkdownWriter object --]] function MarkdownWriter:__init(outputPath, style) self.outputFile = io.open(outputPath, 'w') local validStyles = { repl = true, html = true } if not validStyles[style] then error("MarkdownWriter.__init: '" .. tostring(style) .. "' is not a valid style") end self._style = style if not self.outputFile then error("could not open output file " .. outputPath) end end --[[ Append a string to the output Args: * `text` :: string; text to append Returns: nil --]] function MarkdownWriter:write(text) self.outputFile:write(text) end --[[ Add an anchor to the output Args: * `name` :: string; name for the anchor Returns: nil --]] function MarkdownWriter:anchor(name) if self._style == 'repl' then self:write([[<a name="]] .. name .. [["/>]] .. "\n") else self:write([[<a name="]] .. name .. [["></a>]] .. "\n") end end --[[ Add a heading to the output Args: * `text` :: string; the heading text * `level` :: int; level of the heading (lower means bigger) Returns: nil --]] function MarkdownWriter:heading(level, text, rhs) self:write("\n\n" .. string.rep("#", level) .. " ".. text .. " " .. string.rep("#", level) .. "\n\n") end --[[ Add markdown for a documented class Args: * `entity` :: dokx.Class object Returns: nil --]] function MarkdownWriter:class(entity) dokx.logger.debug("Outputting markdown for " .. entity:name()) self:anchor(entity:fullname() .. ".dok") if self._style == 'repl' then self:heading(3, entity:name()) else self:heading(2, entity:fullname()) end if entity:doc() then self:write(entity:doc()) end end --[[ Add markdown for a documented function Args: * `entity` :: DocumentedFunction object Returns: nil --]] function MarkdownWriter:documentedFunction(entity) dokx.logger.debug("Outputting markdown for " .. entity:name()) self:anchor(entity:fullname()) if self._style == 'repl' then self:heading(4, entity:name() .. "(" .. entity:args() .. ")") else self:heading(3, entity:fullname() .. "(" .. entity:args() .. ")") end self:write(entity:doc()) end --[[ Add markdown for an undocumented function Args: * `entity` :: Function object Returns: nil --]] function MarkdownWriter:undocumentedFunction(entity) dokx.logger.debug("Outputting markdown for " .. entity:name()) self:anchor(entity:fullname()) if self._style == 'repl' then self:write(" * `" .. entity:name() .. "`\n") else self:write(" * `" .. entity:fullname() .. "(" .. entity:args() .. ")" .. "`\n") end end --[[ Close the writer. _Must be called before exiting_. ]] function MarkdownWriter:close() io.close(self.outputFile) end
bsd-3-clause
dmccuskey/dmc-wamp
examples/dmc-wamp-subscribe/dmc_corona/dmc_sockets.lua
14
11066
--====================================================================-- -- dmc_corona/dmc_sockets.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Corona Library : DMC Sockets --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== DMC Corona Library Config --====================================================================-- --====================================================================-- --== Support Functions local Utils = {} -- make copying from dmc_utils easier function Utils.extend( fromTable, toTable ) function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end --====================================================================-- --== Configuration local dmc_lib_data -- boot dmc_corona with boot script or -- setup basic defaults if it doesn't exist -- if false == pcall( function() require( 'dmc_corona_boot' ) end ) then _G.__dmc_corona = { dmc_corona={}, } end dmc_lib_data = _G.__dmc_corona --====================================================================-- --== DMC Sockets --====================================================================-- --====================================================================-- --== Configuration dmc_lib_data.dmc_sockets = dmc_lib_data.dmc_sockets or {} local DMC_SOCKETS_DEFAULTS = { check_reads=true, check_writes=false, throttle_level=math.floor( 1000/15 ), -- MEDIUM } local dmc_sockets_data = Utils.extend( dmc_lib_data.dmc_sockets, DMC_SOCKETS_DEFAULTS ) --====================================================================-- --== Imports local Objects = require 'lua_objects' local socket = require 'socket' local Utils = require 'lua_utils' local TCPSocket = require 'dmc_sockets.tcp' local ATCPSocket = require 'dmc_sockets.async_tcp' --====================================================================-- --== Setup, Constants local ObjectBase = Objects.ObjectBase local ipairs = ipairs local mfloor = math.floor local sselect = socket.select local tinsert = table.insert local tonumber = tonumber local tostring = tostring local type = type local Singleton = nil --====================================================================-- --== Sockets Class --====================================================================-- local Sockets = newClass( ObjectBase, { name="DMC Socket" } ) --== Class Constants Sockets.__version = VERSION Sockets.NO_BLOCK = 0 Sockets.TCP = 'tcp' Sockets.ATCP = 'atcp' -- throttle socket checks, milliseconds delay Sockets.OFF = 0 Sockets.LOW = mfloor( 1000/30 ) -- ie, 30 FPS Sockets.MEDIUM = mfloor( 1000/15 ) -- ie, 15 FPS Sockets.HIGH = mfloor( 1000/1 ) -- ie, 1 FPS Sockets.DEFAULT = Sockets.MEDIUM --======================================================-- --== Start: Setup Lua Objects function Sockets:__init__( params ) -- print( "Sockets:__init__" ) params = params or {} self:superCall( '__init__', params ) --==-- --== Create Properties ==-- self._sockets = {} -- socket objects, keyed by object self._raw_socks = {} -- socket objects, keyed by socket self._raw_socks_list = {} -- socket self._check_read = nil self._check_write = nil self._socket_check_is_active = false self._socket_check_handler = nil --== Object References ==-- -- none end function Sockets:__undoInit__() -- print( "Sockets:__undoInit__" ) self._sockets = nil self._raw_socks = nil self._raw_socks_list = nil --==-- self:superCall( '__undoInit__' ) end function Sockets:__initComplete__() -- print( "Sockets:__initComplete__" ) self:superCall( '__initComplete__' ) --==-- -- initialize using setters self.check_reads = dmc_sockets_data.check_reads self.check_writes = dmc_sockets_data.check_writes if type( dmc_sockets_data.throttle_level ) == 'number' then self.throttle = dmc_sockets_data.throttle_level else self.throttle = Sockets.DEFAULT end end function Sockets:__undoInitComplete__() -- print( "Sockets:__undoInitComplete__" ) self:_removeSockets() --==-- self:superCall( '__undoInitComplete__' ) end -- END: Setup Lua Objects --====================================================================-- --====================================================================-- --== Public Methods function Sockets.__setters:throttle( value ) -- print( 'Sockets.__setters:throttle', value ) --== Sanity Check if type( value ) == 'string' then value = tonumber( value ) if value == nil then value = Sockets.DEFAULT end elseif type( value ) ~= 'number' then value = Sockets.DEFAULT end local f if value == self.OFF then f = self:createCallback( self._checkConnections ) else f = self:_createSocketCheckHandler( value ) end -- using setter self._socketCheck_handler = f end -- whether to check socket read availability -- function Sockets.__setters:check_reads( value ) -- print( 'Sockets.__setters:check_reads', value ) if value then self._check_read = self._raw_socks_list else self._check_read = nil end end -- whether to check socket write availability -- function Sockets.__setters:check_writes( value ) -- print( 'Sockets.__setters:check_writes', value ) if value then self._check_write = self._raw_socks_list else self._check_write = nil end end function Sockets:create( s_type, params ) -- print( 'Sockets:create', s_type, params ) params = params or {} --==-- if s_type == Sockets.TCP then params.master = self return TCPSocket:new( params ) elseif s_type == Sockets.ATCP then params.master = self return ATCPSocket:new( params ) elseif s_type == Sockets.UDP then error( "Sockets:create, UDP is not yet available" ) else error( "Sockets:create, Unknown socket type: " .. tostring( s_type ) ) end end --====================================================================-- --== Private Methods -- getter/setter: activate enterFrame for socket check -- function Sockets.__getters:check_is_active() return self._socket_check_is_active end -- @param value boolean function Sockets.__setters:check_is_active( value ) -- print( 'Sockets.__setters:check_is_active', value ) local f = self._socketCheck_handler if self._socket_check_is_active == value then return end if value == true and f then Runtime:addEventListener( 'enterFrame', f ) elseif f then Runtime:removeEventListener( 'enterFrame', f ) end self._socket_check_is_active = value end -- getter/setter: socket check handler function function Sockets.__getters:_socketCheck_handler() return self._socket_check_handler end -- @param value function function Sockets.__setters:_socketCheck_handler( func ) if self.check_is_active then Runtime:removeEventListener( 'enterFrame', self._socket_check_handler ) Runtime:addEventListener( 'enterFrame', func ) end self._socket_check_handler = func end -- @param socket DMC TCP Socket function Sockets:_connect( sock ) -- print( 'Sockets:_connect', sock ) self:_addSocket( sock ) end -- @param socket DMC TCP Socket function Sockets:_disconnect( sock ) -- print( 'Sockets:_disconnect', sock ) self:_removeSocket( sock ) end -- TODO: check this function Sockets:_removeSockets() -- print( "Sockets:_removeSockets" ) for i = #self._sockets, 1, -1 do -- local s = table.remove( self._sockets, 1 ) local s = self._sockets[ i ] self:_removeSocket( s ) end end function Sockets:_addSocket( sock ) -- print( "Sockets:_addSocket", sock ) local raw_sock = sock._socket local key -- save TCP lookup key = tostring( sock ) self._sockets[ key ] = sock -- save socket lookup key = tostring( raw_sock ) self._raw_socks[ key ] = sock -- save raw socket in list tinsert( self._raw_socks_list, raw_sock ) if #self._raw_socks_list then self.check_is_active = true end end function Sockets:_removeSocket( sock ) -- print( "Sockets:_removeSocket", sock ) local raw_sock = sock._socket local key Utils.removeFromTable( self._raw_socks_list, raw_sock ) key = tostring( raw_sock ) self._raw_socks[ key ] = nil key = tostring( sock ) self._sockets[ key ] = nil if #self._raw_socks_list == 0 then self.check_is_active = false end end function Sockets:_checkConnections() -- print( "Sockets:_checkConnections" ) local s_read, s_write, err = sselect( self._check_read, self._check_write, Sockets.NO_BLOCK ) if err ~= nil then return end for i, rs in ipairs( s_read ) do -- print( i, rs ) local sock = self._raw_socks[ tostring( rs ) ] if sock then sock:_readStatus( 'ok' ) else print( "ERROR IN SOCKET ") end end for i, rs in ipairs( s_write ) do -- print( i, rs ) local sock = self._raw_socks[ tostring( rs ) ] sock:_writeStatus( 'ok' ) end end --====================================================================-- --== Event Handlers function Sockets:_createSocketCheckHandler( value ) -- print("Sockets:_createSocketCheckHandler", value ) local timeout = value local last_check = system.getTimer() local f = function( event ) -- local current_time = system.getTimer() -- print( current_time, last_check, timeout ) self:_checkConnections() end return f end --====================================================================-- --== Create Socket Class Singleton --====================================================================-- Singleton = Sockets:new() return Singleton
mit
amir1213/aa
bot/utils.lua
494
23873
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..v.."\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n" else text = text..k.." - "..v.."\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
Alexx-G/openface
training/dataset-issue-132.lua
8
14611
-- Source: https://github.com/soumith/imagenet-multiGPU.torch/blob/master/dataset.lua -- Modified by Brandon Amos in Sept 2015 for OpenFace by adding -- `samplePeople` and `sampleTriplet`. require 'torch' torch.setdefaulttensortype('torch.FloatTensor') local ffi = require 'ffi' local argcheck = require 'argcheck' require 'sys' require 'xlua' require 'image' tds = require 'tds' local dataset = torch.class('dataLoader') local initcheck = argcheck{ pack=true, help=[[ A dataset class for images in a flat folder structure (folder-name is class-name). Optimized for extremely large datasets (upwards of 14 million images). Tested only on Linux (as it uses command-line linux utilities to scale up) ]], {check=function(paths) local out = true; for _,v in ipairs(paths) do if type(v) ~= 'string' then print('paths can only be of string input'); out = false end end return out end, name="paths", type="table", help="Multiple paths of directories with images"}, {name="sampleSize", type="table", help="a consistent sample size to resize the images"}, {name="split", type="number", help="Percentage of split to go to Training" }, {name="samplingMode", type="string", help="Sampling mode: random | balanced ", default = "balanced"}, {name="verbose", type="boolean", help="Verbose mode during initialization", default = false}, {name="loadSize", type="table", help="a size to load the images to, initially", opt = true}, {name="forceClasses", type="table", help="If you want this loader to map certain classes to certain indices, " .. "pass a classes table that has {classname : classindex} pairs." .. " For example: {3 : 'dog', 5 : 'cat'}" .. "This function is very useful when you want two loaders to have the same " .. "class indices (trainLoader/testLoader for example)", opt = true}, {name="sampleHookTrain", type="function", help="applied to sample during training(ex: for lighting jitter). " .. "It takes the image path as input", opt = true}, {name="sampleHookTest", type="function", help="applied to sample during testing", opt = true}, } function dataset:__init(...) -- argcheck local args = initcheck(...) print(args) for k,v in pairs(args) do self[k] = v end if not self.loadSize then self.loadSize = self.sampleSize; end if not self.sampleHookTrain then self.sampleHookTrain = self.defaultSampleHook end if not self.sampleHookTest then self.sampleHookTest = self.defaultSampleHook end -- find class names print('finding class names') self.classes = {} local classPaths = tds.Hash() if self.forceClasses then print('Adding forceClasses class names') for k,v in pairs(self.forceClasses) do self.classes[k] = v classPaths[k] = tds.Hash() end end -- loop over each paths folder, get list of unique class names, -- also store the directory paths per class -- for each class, print('Adding all path folders') for _,path in ipairs(self.paths) do for dirpath in paths.iterdirs(path) do dirpath = path .. '/' .. dirpath local class = paths.basename(dirpath) self.classes[#self.classes + 1] = class classPaths[#classPaths + 1] = dirpath end end print(#self.classes .. ' class names found') self.classIndices = {} for k,v in ipairs(self.classes) do self.classIndices[v] = k end -- find the image path names print('Finding path for each image') self.imagePath = torch.CharTensor() -- path to each image in dataset self.imageClass = torch.LongTensor() -- class index of each image (class index in self.classes) self.classList = {} -- index of imageList to each image of a particular class self.classListSample = self.classList -- the main list used when sampling data local counts = tds.Hash() local maxPathLength = 0 print('Calculating maximum class name length and counting files') local length = 0 local fullPaths = tds.Hash() -- iterate over classPaths for _,path in pairs(classPaths) do local count = 0 -- iterate over files in the class path for f in paths.iterfiles(path) do local fullPath = path .. '/' .. f maxPathLength = math.max(fullPath:len(), maxPathLength) count = count + 1 length = length + 1 fullPaths[#fullPaths + 1] = fullPath end counts[path] = count end assert(length > 0, "Could not find any image file in the given input paths") assert(maxPathLength > 0, "paths of files are length 0?") maxPathLength = maxPathLength + 1 self.imagePath:resize(length, maxPathLength):fill(0) local s_data = self.imagePath:data() local count = 0 for _,line in pairs(fullPaths) do ffi.copy(s_data, line) s_data = s_data + maxPathLength if self.verbose and count % 10000 == 0 then xlua.progress(count, length) end; count = count + 1 end self.numSamples = self.imagePath:size(1) if self.verbose then print(self.numSamples .. ' samples found.') end --========================================================================== print('Updating classList and imageClass appropriately') self.imageClass:resize(self.numSamples) local runningIndex = 0 for i=1,#self.classes do if self.verbose then xlua.progress(i, #(self.classes)) end local clsLength = counts[classPaths[i]] if clsLength == 0 then error('Class has zero samples: ' .. self.classes[i]) else self.classList[i] = torch.linspace(runningIndex + 1, runningIndex + clsLength, clsLength):long() self.imageClass[{{runningIndex + 1, runningIndex + clsLength}}]:fill(i) end runningIndex = runningIndex + clsLength end --========================================================================== if self.split == 100 then self.testIndicesSize = 0 else print('Splitting training and test sets to a ratio of ' .. self.split .. '/' .. (100-self.split)) self.classListTrain = {} self.classListTest = {} self.classListSample = self.classListTrain local totalTestSamples = 0 -- split the classList into classListTrain and classListTest for i=1,#self.classes do local list = self.classList[i] count = self.classList[i]:size(1) local splitidx = math.floor((count * self.split / 100) + 0.5) -- +round local perm = torch.randperm(count) self.classListTrain[i] = torch.LongTensor(splitidx) for j=1,splitidx do self.classListTrain[i][j] = list[perm[j]] end if splitidx == count then -- all samples were allocated to train set self.classListTest[i] = torch.LongTensor() else self.classListTest[i] = torch.LongTensor(count-splitidx) totalTestSamples = totalTestSamples + self.classListTest[i]:size(1) local idx = 1 for j=splitidx+1,count do self.classListTest[i][idx] = list[perm[j]] idx = idx + 1 end end end -- Now combine classListTest into a single tensor self.testIndices = torch.LongTensor(totalTestSamples) self.testIndicesSize = totalTestSamples local tdata = self.testIndices:data() local tidx = 0 for i=1,#self.classes do local list = self.classListTest[i] if list:dim() ~= 0 then local ldata = list:data() for j=0,list:size(1)-1 do tdata[tidx] = ldata[j] tidx = tidx + 1 end end end end end -- size(), size(class) function dataset:size(class, list) list = list or self.classList if not class then return self.numSamples elseif type(class) == 'string' then return list[self.classIndices[class]]:size(1) elseif type(class) == 'number' then return list[class]:size(1) end end -- size(), size(class) function dataset:sizeTrain(class) if self.split == 0 then return 0; end if class then return self:size(class, self.classListTrain) else return self.numSamples - self.testIndicesSize end end -- size(), size(class) function dataset:sizeTest(class) if self.split == 100 then return 0 end if class then return self:size(class, self.classListTest) else return self.testIndicesSize end end -- by default, just load the image and return it function dataset:defaultSampleHook(imgpath) local out = image.load(imgpath, 3, 'float') out = image.scale(out, self.sampleSize[3], self.sampleSize[2]) return out end -- getByClass function dataset:getByClass(class) local index = math.ceil(torch.uniform() * self.classListSample[class]:nElement()) local imgpath = ffi.string(torch.data(self.imagePath[self.classListSample[class][index]])) return self:sampleHookTrain(imgpath) end -- converts a table of samples (and corresponding labels) to a clean tensor local function tableToOutput(self, dataTable, scalarTable) local data, scalarLabels, labels local quantity = #scalarTable local samplesPerDraw if dataTable[1]:dim() == 3 then samplesPerDraw = 1 else samplesPerDraw = dataTable[1]:size(1) end if quantity == 1 and samplesPerDraw == 1 then data = dataTable[1] scalarLabels = scalarTable[1] labels = torch.LongTensor(#(self.classes)):fill(-1) labels[scalarLabels] = 1 else data = torch.Tensor(quantity * samplesPerDraw, self.sampleSize[1], self.sampleSize[2], self.sampleSize[3]) scalarLabels = torch.LongTensor(quantity * samplesPerDraw) labels = torch.LongTensor(quantity * samplesPerDraw, #(self.classes)):fill(-1) for i=1,#dataTable do local idx = (i-1)*samplesPerDraw data[{{idx+1,idx+samplesPerDraw}}]:copy(dataTable[i]) scalarLabels[{{idx+1,idx+samplesPerDraw}}]:fill(scalarTable[i]) labels[{{idx+1,idx+samplesPerDraw},{scalarTable[i]}}]:fill(1) end end return data, scalarLabels, labels end -- sampler, samples from the training set. function dataset:sample(quantity) if self.split == 0 then error('No training mode when split is set to 0') end quantity = quantity or 1 local dataTable = tds.Hash() local scalarTable = tds.Hash() for _=1,quantity do local class = torch.random(1, #self.classes) local out = self:getByClass(class) dataTable[#dataTable + 1] = out scalarTable[#scalarTable + 1] = class end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end -- Naively sample random triplets. function dataset:sampleTriplet(quantity) if self.split == 0 then error('No training mode when split is set to 0') end quantity = quantity or 1 local dataTable = {} local scalarTable = {} -- Anchors for _=1,quantity do local anchorClass = torch.random(1, #self.classes) table.insert(dataTable, self:getByClass(anchorClass)) table.insert(scalarTable, anchorClass) end -- Positives for i=1,quantity do local posClass = scalarTable[i] table.insert(dataTable, self:getByClass(posClass)) table.insert(scalarTable, posClass) end -- Negatives for i=1,quantity do local posClass = scalarTable[i] local negClass = posClass while negClass == posClass do negClass = torch.random(1, #self.classes) end table.insert(dataTable, self:getByClass(negClass)) table.insert(scalarTable, negClass) end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end function dataset:samplePeople(peoplePerBatch, imagesPerPerson) if self.split == 0 then error('No training mode when split is set to 0') end local classes = torch.randperm(#trainLoader.classes)[{{1,peoplePerBatch}}]:int() local numPerClass = torch.Tensor(peoplePerBatch) for i=1,peoplePerBatch do local n = math.min(self.classListSample[classes[i]]:nElement(), imagesPerPerson) numPerClass[i] = n end local data = torch.Tensor(numPerClass:sum(), self.sampleSize[1], self.sampleSize[2], self.sampleSize[3]) local dataIdx = 1 for i=1,peoplePerBatch do local cls = classes[i] local n = numPerClass[i] local shuffle = torch.randperm(n) for j=1,n do imgNum = self.classListSample[cls][shuffle[j]] imgPath = ffi.string(torch.data(self.imagePath[imgNum])) data[dataIdx] = self:sampleHookTrain(imgPath) dataIdx = dataIdx + 1 end end assert(dataIdx - 1 == numPerClass:sum()) return data, numPerClass end function dataset:get(i1, i2) local indices, quantity if type(i1) == 'number' then if type(i2) == 'number' then -- range of indices indices = torch.range(i1, i2); quantity = i2 - i1 + 1; else -- single index indices = {i1}; quantity = 1 end elseif type(i1) == 'table' then indices = i1; quantity = #i1; -- table elseif (type(i1) == 'userdata' and i1:nDimension() == 1) then indices = i1; quantity = (#i1)[1]; -- tensor else error('Unsupported input types: ' .. type(i1) .. ' ' .. type(i2)) end assert(quantity > 0) -- now that indices has been initialized, get the samples local dataTable = {} local scalarTable = {} for i=1,quantity do -- load the sample local idx = self.testIndices[indices[i]] local imgpath = ffi.string(torch.data(self.imagePath[idx])) local out = self:sampleHookTest(imgpath) table.insert(dataTable, out) table.insert(scalarTable, self.imageClass[idx]) end local data, scalarLabels, labels = tableToOutput(self, dataTable, scalarTable) return data, scalarLabels, labels end function dataset:test(quantity) if self.split == 100 then error('No test mode when you are not splitting the data') end local i = 1 local n = self.testIndicesSize local qty = quantity or 1 return function () if i+qty-1 <= n then local data, scalarLabelss, labels = self:get(i, i+qty-1) i = i + qty return data, scalarLabelss, labels end end end return dataset
apache-2.0
VurtualRuler98/kswep2
lua/autorun/kswep_testsound.lua
1
4469
if (SERVER) then AddCSLuaFile() end sound.Add({ name="weapon_kswep.single", volume=1.0, pitch={155,165}, sound="^weapons/sg550/sg550-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_law.single", volume=1.0, pitch={55,60}, sound="^weapons/357_fire2.wav", level=165, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_m4.single", volume=1.0, pitch={155,165}, sound="^weapons/m4a1/m4a1_unsil-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_akm.single", volume=1.0, pitch={175,185}, sound="^weapons/ak47/ak47-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_ak74.single", volume=1.0, pitch={200,205}, sound="^weapons/ak47/ak47-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_glock19.single", volume=1.0, pitch={185,195}, sound="^weapons/glock/glock18-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_fiveseven.single", volume=1.0, pitch={125,135}, sound="^weapons/fiveseven/fiveseven-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_nagant.single", volume=1.0, pitch={145,155}, sound="^weapons/pistol/pistol_fire3.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_p228.single", volume=1.0, pitch={185,195}, sound="^weapons/elite/elite-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_judge.single", volume=0.7, pitch={225,245}, sound="^weapons/deagle/deagle-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_mac11.single", volume=1, pitch={225,235}, sound="^weapons/usp/usp_unsil-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_p90.single", volume=1, pitch={245,255}, sound="^weapons/p90/p90-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_p238.single", volume=1.0, pitch={185,195}, sound="^weapons/g3sg1/g3sg1-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_mp5.single", volume=1.0, pitch={185,195}, sound="^weapons/mp5navy/mp5-1.wav", level=140, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_mp510.single", volume=1.0, pitch={175,185}, sound="^weapons/mp5navy/mp5-1.wav", level=140, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswep_test.single762", volume=1.0, pitch={125,135}, sound="^weapons/g3sg1/g3sg1-1.wav", level=145, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_awm.single", volume=1.0, pitch={195,205}, sound="^weapons/awp/awp1.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_shotgun.single", volume=1.0, pitch={120,120}, sound="^weapons/shotgun/shotgun_fire6.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_ghostgun.single", volume=1.0, pitch={70,75}, sound="^weapons/awp/awp1.wav", level=160, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_j22.single", volume=1, pitch={245,255}, sound="^weapons/sg552/sg552-1.wav", level=135, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswep.singlesilenced", volume=1, pitch={245,255}, sound="^weapons/sg550/sg550-1.wav", level=120, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_scout.single", volume=1.0, pitch={75,80}, sound="^weapons/scout/scout_fire-1.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_scout_556.single", volume=1.0, pitch={95,105}, sound="^weapons/scout/scout_fire-1.wav", level=155, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_scar17.single", volume=1.0, pitch={125,135}, sound="^weapons/g3sg1/g3sg1-1.wav", level=160, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_usp45.single", volume=1.0, pitch={165,170}, sound="^weapons/usp/usp_unsil-1.wav", level=140, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_usp45.single_sup", volume=0.7, pitch={205,210}, sound="^weapons/usp/usp_unsil-1.wav", level=110, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_m4.single_sup", volume=1.0, pitch={195,205}, sound="^weapons/m4a1/m4a1_unsil-1.wav", level=110, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kswept_300blk.single_sup", volume=0.6, pitch={185,190}, sound="^weapons/m4a1/m4a1_unsil-1.wav", level=110, channel=CHAN_WEAPON }) sound.Add({ name="weapon_kgrent_flashbang.detonate", volume=1, pitch={195,205}, sound="^weapons/aug/aug-1.wav", level=145, channel=CHAN_WEAPON })
apache-2.0
minism/love-analog
mono.lua
1
2077
local RATE = 44100 local BUFSIZE = RATE / 4 local BITS = 16 local CHANNELS = 1 local MonoOut = Module:extend() --- Speaker output module with built in sampler function MonoOut:init() Module.init(self, 'Mono Out', { ports = { Port('In') }, knobs = { Knob('Vol') } }) -- Sampling data self.activeSource = nil self.sampleQueue = Queue:new() self.sourceQueue = Queue:new() -- Offset playback timer from sampleTimer self.sampleTimer = time.every(BUFSIZE / RATE, self:sampleClosure()) self.playbackTimer = time.every(BUFSIZE / RATE, self:playbackClosure()) self.playbackTimer.timeLeft = (BUFSIZE / RATE) / 2 -- Global function counter self.ticks = 0 end function MonoOut:playbackClosure() return function() if self.locked then self.playbackTimer:stop() return end --- Play the next sample in queue if not self.sampleQueue:isEmpty() then local sample = self.sampleQueue:pop() local source = love.audio.newSource(sample) source:play() -- Put the source in the active queue self.sourceQueue:push(source) end end end function MonoOut:sampleClosure() return function () if self.locked then self.sampleTimer:stop() return end --- Generate a new sample from circuit connected to in port = self.ports[1].out if port then local sample = love.sound.newSoundData(BUFSIZE, RATE, BITS, CHANNELS) for i = 0, BUFSIZE - 1 do self.ticks = self.ticks + 1 local t = self.ticks / RATE sample:setSample(i, port.signal(t) * self.knobs[1].val) end self.sampleQueue:push(sample) -- Kill the top audio source in queue if not self.sourceQueue:isEmpty() then local source = self.sourceQueue:pop() source:stop() end end end end return MonoOut
bsd-2-clause
artynet/luci
modules/luci-base/luasrc/i18n.lua
10
1252
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. local tparser = require "luci.template.parser" local util = require "luci.util" local tostring = tostring module "luci.i18n" i18ndir = util.libpath() .. "/i18n/" context = util.threadlocal() default = "en" function setlanguage(lang) local code, subcode = lang:match("^([A-Za-z][A-Za-z])[%-_]([A-Za-z][A-Za-z])$") if not (code and subcode) then subcode = lang:match("^([A-Za-z][A-Za-z])$") if not subcode then return nil end end context.parent = code and code:lower() context.lang = context.parent and context.parent.."-"..subcode:lower() or subcode:lower() if tparser.load_catalog(context.lang, i18ndir) and tparser.change_catalog(context.lang) then return context.lang elseif context.parent then if tparser.load_catalog(context.parent, i18ndir) and tparser.change_catalog(context.parent) then return context.parent end end return nil end function translate(key) return tparser.translate(key) or key end function translatef(key, ...) return tostring(translate(key)):format(...) end function dump() local rv = {} tparser.get_translations(function(k, v) rv[k] = v end) return rv end
apache-2.0
dxmgame/dxm-cocos-demo
src/lua-coin-tree/Resources/src/cocos/ui/GuiConstants.lua
44
3020
if nil == ccui then return end ccui.BrightStyle = { none = -1, normal = 0, highlight = 1, } ccui.TextureResType = { localType = 0, plistType = 1, } ccui.TouchEventType = { began = 0, moved = 1, ended = 2, canceled = 3, } ccui.SizeType = { absolute = 0, percent = 1, } ccui.PositionType = { absolute = 0, percent = 1, } ccui.CheckBoxEventType = { selected = 0, unselected = 1, } ccui.TextFiledEventType = { attach_with_ime = 0, detach_with_ime = 1, insert_text = 2, delete_backward = 3, } ccui.LayoutBackGroundColorType = { none = 0, solid = 1, gradient = 2, } ccui.LayoutType = { ABSOLUTE = 0, VERTICAL = 1, HORIZONTAL = 2, RELATIVE = 3, } ccui.LayoutParameterType = { none = 0, linear = 1, relative = 2, } ccui.LinearGravity = { none = 0, left = 1, top = 2, right = 3, bottom = 4, centerVertical = 5, centerHorizontal = 6, } ccui.RelativeAlign = { alignNone = 0, alignParentTopLeft = 1, alignParentTopCenterHorizontal = 2, alignParentTopRight = 3, alignParentLeftCenterVertical = 4, centerInParent = 5, alignParentRightCenterVertical = 6, alignParentLeftBottom = 7, alignParentBottomCenterHorizontal = 8, alignParentRightBottom = 9, locationAboveLeftAlign = 10, locationAboveCenter = 11, locationAboveRightAlign = 12, locationLeftOfTopAlign = 13, locationLeftOfCenter = 14, locationLeftOfBottomAlign = 15, locationRightOfTopAlign = 16, locationRightOfCenter = 17, locationRightOfBottomAlign = 18, locationBelowLeftAlign = 19, locationBelowCenter = 20, locationBelowRightAlign = 21, } ccui.SliderEventType = {percentChanged = 0} ccui.LoadingBarDirection = { LEFT = 0, RIGHT = 1} ccui.ScrollViewDir = { none = 0, vertical = 1, horizontal = 2, both = 3, } ccui.ScrollViewMoveDir = { none = 0, up = 1, down = 2, left = 3, right = 4, } ccui.ScrollviewEventType = { scrollToTop = 0, scrollToBottom = 1, scrollToLeft = 2, scrollToRight = 3, scrolling = 4, bounceTop = 5, bounceBottom = 6, bounceLeft = 7, bounceRight = 8, } ccui.ListViewDirection = { none = 0, vertical = 1, horizontal = 2, } ccui.ListViewMoveDirection = { none = 0, up = 1, down = 2, left = 3, right = 4, } ccui.ListViewEventType = { ONSELECTEDITEM_START = 0, ONSELECTEDITEM_END = 1, } ccui.PageViewEventType = { turning = 0, } ccui.PVTouchDir = { touchLeft = 0, touchRight = 1, } ccui.ListViewGravity = { left = 0, right = 1, centerHorizontal = 2, top = 3, bottom = 4 , centerVertical = 5, } ccui.TextType = { SYSTEM = 0, TTF = 1, } ccui.LayoutComponent.HorizontalEdge = { None = 0, Left = 1, Right = 2, Center = 3, } ccui.LayoutComponent.VerticalEdge = { None = 0, Bottom = 1, Top = 2, Center = 3, }
mit
c4augustus/Urho3D
bin/Data/LuaScripts/35_SignedDistanceFieldText.lua
26
7747
-- Signed distance field text example. -- This sample demonstrates: -- - Creating a 3D scene with static content -- - Creating a 3D text use SDF Font -- - Displaying the scene using the Renderer subsystem -- - Handling keyboard and mouse input to move a freelook camera require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") -- Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple -- plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger -- (100 x 100 world units) local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a directional light to the world so that we can see something. The light scene node's orientation controls the -- light direction we will use the SetDirection() function which calculates the orientation from a forward direction vector. -- The light will use default settings (white light, no shadows) local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) -- The direction vector does not need to be normalized local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL -- Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a -- quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains -- LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll -- see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the -- same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the -- scene. local NUM_OBJECTS = 200 for i = 1, NUM_OBJECTS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0) mushroomNode:SetScale(0.5 + Random(2.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") local mushroomTitleNode = mushroomNode:CreateChild("MushroomTitle") mushroomTitleNode.position = Vector3(0.0, 1.2, 0.0) local mushroomTitleText = mushroomTitleNode:CreateComponent("Text3D") mushroomTitleText.text = "Mushroom " .. i mushroomTitleText:SetFont(cache:GetResource("Font", "Fonts/BlueHighway.sdf"), 24) mushroomTitleText.color = Color(1.0, 0.0, 0.0) if (i % 3) == 1 then mushroomTitleText.color = Color(0.0, 1.0, 0.0) mushroomTitleText.textEffect = TE_SHADOW mushroomTitleText.effectColor = Color(0.5, 0.5, 0.5) end if (i % 3) == 2 then mushroomTitleText.color = Color(1.0, 1.0, 0.0) mushroomTitleText.textEffect = TE_STROKE mushroomTitleText.effectColor = Color(0.5, 0.5, 0.5) end mushroomTitleText:SetAlignment(HA_CENTER, VA_CENTER) end -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") cameraNode:CreateComponent("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw +MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed -- Use the Translate() function (default local space) to move relative to the node's orientation. if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end
mit
BlubBlab/rom-bot
classes/pawn.lua
1
31003
PT_NONE = 0; PT_PLAYER = 1; PT_MONSTER = 2; PT_SIGIL = 3; PT_NPC = 4; PT_NODE = 4; RACE_HUMAN = 0; RACE_ELF = 1; RACE_DWARF = 2; CLASS_NONE = -1; CLASS_WARRIOR = 1; CLASS_SCOUT = 2; CLASS_ROGUE = 3; CLASS_MAGE = 4; CLASS_PRIEST = 5; CLASS_KNIGHT = 6; CLASS_WARDEN = 7; CLASS_DRUID = 8; CLASS_WARLOCK = 9; CLASS_CHAMPION = 10; NTYPE_WOOD = 1 NTYPE_ORE = 2 NTYPE_HERB = 3 ATTACKABLE_MASK_PLAYER = 0x10000; ATTACKABLE_MASK_MONSTER = 0x20000; ATTACKABLE_MASK_CLICKABLE = 0x1000; AGGRESSIVE_MASK_MONSTER = 0x100000; -- used in function.lua for openGiftbag() armorMap = { [CLASS_NONE] = "none", [CLASS_WARRIOR] = "chain", [CLASS_SCOUT] = "leather", [CLASS_ROGUE] = "leather", [CLASS_MAGE] = "cloth", [CLASS_PRIEST] = "cloth", [CLASS_KNIGHT] = "chain", [CLASS_WARDEN] = "chain", [CLASS_DRUID] = "cloth", [CLASS_WARLOCK] = "cloth", [CLASS_CHAMPION] = "chain", }; local classEnergyMap = { [CLASS_NONE] = "none", [CLASS_WARRIOR] = "rage", [CLASS_SCOUT] = "focus", [CLASS_ROGUE] = "energy", [CLASS_MAGE] = "mana", [CLASS_PRIEST] = "mana", [CLASS_KNIGHT] = "mana", [CLASS_WARDEN] = "mana", [CLASS_DRUID] = "mana", [CLASS_WARLOCK] = "focus", [CLASS_CHAMPION] = "rage", }; CPawn = class( function (self, ptr) self.Address = ptr; self.Name = "<UNKNOWN>"; self.Id = -1; self.GUID = 0; self.Type = PT_NONE; self.Class1 = CLASS_NONE; self.Class2 = CLASS_NONE; self.Guild = "<UNKNOWN>"; self.Level = 1; self.Level2 = 1; self.HP = 1000; self.LastHP = 0; self.MaxHP = 1000; self.MP = 1000; self.MaxMP = 1000; self.MP2 = 1000; self.MaxMP2 = 1000; self.Mana = 0; self.MaxMana = 0; self.Rage = 0; self.MaxRage = 0; self.Energy = 0; self.MaxEnergy = 0; self.Focus = 0; self.MaxFocus = 0; self.Race = RACE_HUMAN; self.X = 0.0; self.Y = 0.0; self.Z = 0.0; self.TargetPtr = 0; self.Direction = 0.0; self.Attackable = false; self.Alive = true; self.Mounted = false; self.Lootable = false; self.Aggressive = false; self.Harvesting = false; -- Whether or not we are currently harvesting self.Casting = false; self.TargetIcon = true self.InParty = false self.Swimming = false self.Speed = 50 self.IsPet = nil self.Buffs = {}; if( self.Address ~= 0 and self.Address ~= nil ) then self:update(); end end ); function memoryReadRepeat(_type, proc, address, offset) local readfunc; local ptr = false; local val; if( type(proc) ~= "userdata" ) then error("Invalid proc", 2); end if( type(address) ~= "number" ) then error("Invalid address", 2); end if( _type == "int" ) then readfunc = memoryReadInt; elseif( _type == "uint" ) then readfunc = memoryReadUInt; elseif( _type == "float" ) then readfunc = memoryReadFloat; elseif( _type == "byte" ) then readfunc = memoryReadByte; elseif( _type == "string" ) then readfunc = memoryReadString; elseif( _type == "intptr" ) then readfunc = memoryReadIntPtr; ptr = true; elseif( _type == "uintptr" ) then readfunc = memoryReadUIntPtr; ptr = true; elseif( _type == "byteptr" ) then readfunc = memoryReadBytePtr; ptr = true; else return nil; end for i = 1, 10 do if( ptr ) then val = readfunc(proc, address, offset); else val = readfunc(proc, address); end if( val ~= nil ) then return val; end end if( settings.options.DEBUGGING ) then printf("Error in memory reading: memoryread%s(proc,0x%X", _type, address) if ptr then if type(offset) == "number" then printf(" ,0x%X)\n",offset) elseif type(offset) == "table" then printf(" ,{") for k,v in pairs(offset) do printf("0x%X,",v) end printf("})\n") end else print(")") end end end function CPawn.new(address) local np = CPawn() np.Address = address return np end function CPawn:hasAddress() if self.Address == nil or self.Address == 0 then return false else return true end end function CPawn:update() local proc = getProc(); local memerrmsg = "Failed to read memory"; local tmp; if not self:exists() then -- Updates and checks pawn.Id return end self:updateName() self:updateAlive(); self:updateHP() -- Also updates MaxHP self:updateClass() self:updateMP() -- Also updates MP2, MaxMP, MaxMP2, Rage, Focus, Energy self:updateLastHP() self.Race = memoryReadRepeat("int", proc, self.Address + addresses.pawnRace_offset) or self.Race; self:updateGUID() self:updateType() self:updateHarvesting() self:updateCasting() self:updateBuffs() self:updateLootable() self.Level = memoryReadRepeat("int", proc, self.Address + addresses.pawnLevel_offset) or self.Level; self.Level2 = memoryReadRepeat("int", proc, self.Address + addresses.pawnLevel2_offset) or self.Level2; self:updateTargetPtr() self:updateXYZ() self:updateDirection() -- Also updates DirectionY local attackableFlag = memoryReadRepeat("uint", proc, self.Address + addresses.pawnAttackable_offset) if attackableFlag then self.Mounted = bitAnd(attackableFlag, 0x10000000) --=== Does icon appear when you click pawn ===-- if bitAnd(attackableFlag,0x10) then self.TargetIcon = true else self.TargetIcon = false end --=== InParty indicator ===-- if bitAnd(attackableFlag,0x80000000) then self.InParty = true else self.InParty = false end if( self.Type == PT_MONSTER ) then --printf("%s attackable flag: 0x%X\n", self.Name, attackableFlag); if( bitAnd(attackableFlag, ATTACKABLE_MASK_MONSTER) and bitAnd(attackableFlag, ATTACKABLE_MASK_CLICKABLE) ) then self.Attackable = true; else self.Attackable = false; end if( bitAnd(attackableFlag, AGGRESSIVE_MASK_MONSTER) ) then self.Aggressive = true; else self.Aggressive = false; end else self.Attackable = false; end end self:updateSpeed() tmp = memoryReadRepeat("byteptr",proc, self.Address + addresses.pawnSwim_offset1, addresses.pawnSwim_offset2) self.Swimming = (tmp == 3 or tmp == 4) self:updateIsPet() if( self.Alive ==nil or self.HP == nil or self.MaxHP == nil or self.MP == nil or self.MaxMP == nil or self.MP2 == nil or self.MaxMP2 == nil or self.Name == nil or self.Level == nil or self.Level2 == nil or self.TargetPtr == nil or self.X == nil or self.Y == nil or self.Z == nil or self.Attackable == nil ) then error("Error reading memory in CPawn:update()"); end end function CPawn:updateId() if not self:hasAddress() then self.Id = 0 self.Type = 0 self.Name = "<UNKNOWN>" return end -- Get Id local tmp = memoryReadRepeat("uint", getProc(), self.Address + addresses.pawnId_offset) or 0; if self.Id == -1 then -- First time. Get it. self.Id = tmp if self.Id > 999999 then self.Id = 0 end elseif self.Id >= PLAYERID_MIN and self.Id <= PLAYERID_MAX then -- player ids can change if tmp >= PLAYERID_MIN and tmp <= PLAYERID_MAX then self.Id = tmp end else -- see if it changed if tmp ~= self.Id then -- Id changed. Pawn no longer valid self.Id = 0 self.Type = 0 self.Name = "<UNKNOWN>" end end end function CPawn:exists() self:updateId() return self.Id ~= 0 end function CPawn:updateName() if not self:hasAddress() then self.Name = "<UNKNOWN>" return end showWarnings(false);-- Disable memory warnings for name reading only local namePtr = memoryReadRepeat("uint", getProc(), self.Address + addresses.pawnName_offset); if( namePtr == nil or namePtr == 0 ) then tmp = nil; else tmp = memoryReadString(getProc(), namePtr); -- Don't use memoryReadRepeat here; this CAN fail! end showWarnings(true); -- Re-enable warnings after reading -- UTF8 -> ASCII translation not for player names -- because that would need the whole table and there we normaly -- don't need it, we don't print player names in the MM window or so if( tmp == nil ) then self.Name = "<UNKNOWN>"; else -- time for only convert 8 characters is 0 ms -- time for convert the whole UTF8_ASCII.xml table is about 6-7 ms if( bot.ClientLanguage == "RU" ) then self.Name = utf82oem_russian(tmp); else self.Name = utf8ToAscii_umlauts(tmp); -- only convert umlauts end end end function CPawn:updateGUID() if not self:hasAddress() then self.GUID = 0 return end self.GUID = memoryReadUInt(getProc(), self.Address + addresses.pawnGUID_offset) or self.GUID; end function CPawn:updateType() if not self:hasAddress() then self.Type = PT_NONE return end self.Type = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnType_offset) or self.Type; end function CPawn:updateAlive() if not self:hasAddress() then self.Alive = false return end -- Check Alive flag local alive = memoryReadRepeat("int", getProc(), self.Address + addresses.charAlive_offset); self.Alive = not bitAnd(alive, 8) -- If 'alive' then also check if fading (only for mobs). if self.Alive then self:updateType() if self.Type == PT_MONSTER then self.Alive = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnFading_offset) == 0; end end end function CPawn:updateHP() if not self:hasAddress() then self.HP = 0 return end self.HP = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnHP_offset) or self.HP; self.MaxHP = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnMaxHP_offset) or self.MaxHP; end function CPawn:updateLastHP() if not self:hasAddress() then self.LastHP = 0 return end local tmpLastHP = memoryReadRepeat("uint", getProc(), self.Address + addresses.pawnLastHP_offset) if tmpLastHP then self.LastHP = tmpLastHP if player and self.LastHP ~= player.PawnLastHP then player.PawnLastHP = self.LastHP player.LastHitTime = getGameTime() end end end function CPawn:updateClass() if not self:hasAddress() then self.Class1 = CLASS_NONE; self.Class2 = CLASS_NONE; return end self.Class1 = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnClass1_offset) or self.Class1; self.Class2 = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnClass2_offset) or self.Class2; end function CPawn:updateMP() if not self:hasAddress() then self.MP = 0; self.MP2 = 0; return end self.MP = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnMP_offset) or self.MP; self.MaxMP = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnMaxMP_offset) or self.MaxMP; self.MP2 = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnMP2_offset) or self.MP2; self.MaxMP2 = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnMaxMP2_offset) or self.MaxMP2; if( self.MaxMP == 0 ) then -- Prevent division by zero for entities that have no mana self.MP = 1; self.MaxMP = 1; end if( self.MaxMP2 == 0 ) then -- Prevent division by zero for entities that have no secondary mana self.MP2 = 1; self.MaxMP2 = 1; end if self.Class1 == CLASS_NONE then self:updateClass() end -- Set the correct mana/rage/whatever local energyStorage1 = classEnergyMap[self.Class1]; local energyStorage2 = classEnergyMap[self.Class2]; if( energyStorage1 == energyStorage2 ) then energyStorage2 = "none"; end; if( energyStorage1 == "mana" ) then self.Mana = self.MP; self.MaxMana = self.MaxMP; elseif( energyStorage1 == "rage" ) then self.Rage = self.MP; self.MaxRage = self.MaxMP; elseif( energyStorage1 == "energy" ) then self.Energy = self.MP; self.MaxEnergy = self.MaxMP; elseif( energyStorage1 == "focus" ) then self.Focus = self.MP; self.MaxFocus = self.MaxMP; end if( energyStorage2 == "mana" ) then self.Mana = self.MP2; self.MaxMana = self.MaxMP2; elseif( energyStorage2 == "rage" ) then self.Rage = self.MP2; self.MaxRage = self.MaxMP2; elseif( energyStorage2 == "energy" ) then self.Energy = self.MP2; self.MaxEnergy = self.MaxMP2; elseif( energyStorage2 == "focus" ) then self.Focus = self.MP2; self.MaxFocus = self.MaxMP2; end end function CPawn:updateBuffs() if not self:hasAddress() then self.buffs = {}; return end local proc = getProc() local BuffSize = 0x54 local buffStart = memoryReadRepeat("uint", proc, self.Address + addresses.pawnBuffsStart_offset); local buffEnd = memoryReadRepeat("uint", proc, self.Address + addresses.pawnBuffsEnd_offset); self.Buffs = {} -- clear old values if buffStart == nil or buffEnd == nil or buffStart == 0 or buffEnd == 0 then return end if (buffEnd - buffStart)/ BuffSize > 50 then -- Something wrong, too many buffs return end for i = buffStart, buffEnd - 4, BuffSize do local tmp = {} --yrest(1) tmp.Id = memoryReadRepeat("int", proc, i + addresses.pawnBuffId_offset); local name = GetIdName(tmp.Id) if name ~= nil or name ~= "" then tmp.Name, tmp.Count = parseBuffName(name) tmp.TimeLeft = memoryReadRepeat("float", proc, i + addresses.pawnBuffTimeLeft_offset); tmp.Level = memoryReadRepeat("int", proc, i + addresses.pawnBuffLevel_offset); table.insert(self.Buffs,tmp) end end end function CPawn:updateLootable() if not self:hasAddress() then self.Lootable = false; return end local tmp = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnLootable_offset); if( tmp ) then self.Lootable = bitAnd(tmp, 0x4); else self.Lootable = false; end end function CPawn:updateHarvesting() if not self:hasAddress() then self.Harvesting = false; return end self.Harvesting = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnHarvesting_offset) ~= 0; end function CPawn:updateCasting() if not self:hasAddress() then self.Casting = false; return end self.Casting = (memoryReadRepeat("int", getProc(), self.Address + addresses.pawnCasting_offset) ~= 0); end function CPawn:updateLevel() if not self:hasAddress() then self.Level = 1; return end self.Level = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnLevel_offset) or self.Level; end function CPawn:updateTargetPtr() if not self:hasAddress() then self.TargetPtr = 0; return end local tmpTargetPtr = memoryReadRepeat("uint", getProc(), self.Address + addresses.pawnTargetPtr_offset) or 0 if tmpTargetPtr ~= 0 then self.TargetPtr = tmpTargetPtr return end if self.TargetPtr ~= 0 then -- Check if still valid local addressId = memoryReadRepeat("uint", getProc(), self.TargetPtr + addresses.pawnId_offset) or 0; if addressId == 0 or addressId > 999999 then -- The target no longer exists self.TargetPtr = 0 end end return 0 end function CPawn:updateXYZ() if not self:hasAddress() then self.X = 0; self.Y = 0; self.Z = 0; return end self.X = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnX_offset) or self.X; self.Y = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnY_offset) or self.Y; self.Z = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnZ_offset) or self.Z; end function CPawn:updateDirection() if not self:hasAddress() then return end local Vec1 = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnDirXUVec_offset); local Vec2 = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnDirZUVec_offset); local Vec3 = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnDirYUVec_offset); if( Vec1 == nil ) then Vec1 = 0.0; end; if( Vec2 == nil ) then Vec2 = 0.0; end; if( Vec3 == nil ) then Vec3 = 0.0; end; self.Direction = math.atan2(Vec2, Vec1); self.DirectionY = math.atan2(Vec3, (Vec1^2 + Vec2^2)^.5 ); end function CPawn:updateMounted() if not self:hasAddress() then self.Mounted = false; return end local attackableFlag = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnAttackable_offset) if attackableFlag then self.Mounted = bitAnd(attackableFlag, 0x10000000) end end function CPawn:updateInParty() if not self:hasAddress() then self.InParty = false; return end local attackableFlag = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnAttackable_offset) --=== InParty indicator ===-- if attackableFlag and bitAnd(attackableFlag,0x80000000) then self.InParty = true else self.InParty = false end end function CPawn:updateAttackable() if not self:exists() then return end self:updateType() if( self.Type == PT_MONSTER ) then local attackableFlag = memoryReadRepeat("int", getProc(), self.Address + addresses.pawnAttackable_offset) if attackableFlag then if( bitAnd(attackableFlag, ATTACKABLE_MASK_MONSTER) and bitAnd(attackableFlag, ATTACKABLE_MASK_CLICKABLE) ) then self.Attackable = true; else self.Attackable = false; end if( bitAnd(attackableFlag, AGGRESSIVE_MASK_MONSTER) ) then self.Aggressive = true; else self.Aggressive = false; end end else self.Attackable = false; end end function CPawn:updateSwimming() if not self:hasAddress() then return end local tmp = memoryReadRepeat("byteptr",getProc(), self.Address + addresses.pawnSwim_offset1, addresses.pawnSwim_offset2) self.Swimming = (tmp == 3 or tmp == 4) end function CPawn:updateIsPet() if not self:hasAddress() then self.IsPet = nil return end if self.IsPet == nil then -- not updated yet self.IsPet = memoryReadRepeat("uint",getProc(), self.Address + addresses.pawnIsPet_offset) if self.IsPet == 0 then self.IsPet = false end end end function CPawn:updateSpeed() self.Speed = memoryReadRepeat("float", getProc(), self.Address + addresses.pawnSpeed_offset) end function CPawn:haveTarget() -- Update TargetPtr self:updateTargetPtr() if( self.TargetPtr == 0 ) then return false; end; local tmp = CPawn.new(self.TargetPtr) if not tmp:isAlive() then return false end return true end function CPawn:getTarget() self:updateTargetPtr(); if( self.TargetPtr ) then return CPawn(self.TargetPtr); else return nil; end end function CPawn:isAlive() -- Check if still valid target if not self:exists() then return false end -- Dead self:updateHP() if( self.HP < 1 ) then return false; end -- Also dead (and has loot) self:updateLootable() if( self.Lootable ) then return false; end self:updateAlive() if( not self.Alive ) then return false; end return true end function CPawn:distanceToTarget() self:updateTargetPtr() if( self.TargetPtr == 0 ) then return 0; end; local target = CPawn.new(self.TargetPtr); target:updateXYZ() self:updateXYZ() local tx,ty,tz = target.X, target.Y, target.Z; local px,py,pz = self.X, self.Y, self.Z; return math.sqrt( (tx-px)*(tx-px) + (ty-py)*(ty-py) + (tz-pz)*(tz-pz) ); end function CPawn:hasBuff(buffname, count) local buff = self:getBuff(buffname, count) if buff then return true, buff.Count -- count returned for backward compatibility else return false, 0 end end function CPawn:hasDebuff(debuff, count) return self:hasBuff(debuff, count) end function CPawn:getBuff(buffnamesorids, count) self:updateBuffs() --it's a number so we do it simple if( type(tonumber(buffnamesorids)) == "number")then -- for each buff the pawn has for i, buff in pairs(self.Buffs) do -- compare against each 'buffname' if( tonumber(buffnamesorids) == buff.Id )then --print("we do it") return buff end end end if type(buffnamesorids) ~= "table" then local buffs = {} for buffname in string.gmatch(buffnamesorids,"[^,]+") do table.insert(buffs, buffname) end buffnamesorids = buffs end -- for each buff the pawn has for i, buff in pairs(self.Buffs) do -- compare against each 'buffname' for j,buffname in pairs(buffnamesorids) do if type(tonumber(buffname)) == "number" then buffname = tonumber(buffname) -- Get name from id local tmpbuffname = GetIdName(buffname) -- Take of end numbers tmpbuffname = parseBuffName(tmpbuffname) -- Use only if id has a name if tmpbuffname ~= "" then buffname = tmpbuffname end end if (buffname == buff.Name or buffname == buff.Id) and ( count == nil or buff.Count >= count ) then return buff end end end return false end function parseBuffName(buffname) if buffname == nil then return end local name, count -- First try and find '(3)' type count in name local tmpCount = string.match(buffname,"%((%d+)%)$") if tmpCount then count = tonumber(tmpCount) name = string.match(buffname,"(.*)%s%(%d+%)$") return name, count end -- Then try and find ' 3' type count in name local tmpCount = string.match(buffname,"%s(%d+)$") if tmpCount then count = tonumber(tmpCount) name = string.match(buffname,"(.*)%s%d+$") return name, count end -- Next try and find roman numeral number tmpCount = string.match(buffname,"%s([IVX]+)$") if tmpCount then -- Convert roman number to number if tmpCount == "I" then count = 1 elseif tmpCount == "II" then count = 2 elseif tmpCount == "III" then count = 3 elseif tmpCount == "IV" then count = 4 elseif tmpCount == "V" then count = 5 elseif tmpCount == "VI" then count = 6 elseif tmpCount == "VII" then count = 7 elseif tmpCount == "VIII" then count = 8 elseif tmpCount == "IX" then count = 9 elseif tmpCount == "X" then count = 10 end name = string.match(buffname,"(.*)%s[IVX]+$") return name, count end -- Buff not stackable return buffname, 1 end function CPawn:GetPartyIcon() self:updateGUID() local listStart = memoryReadRepeat("uintptr", getProc(), addresses.partyIconList_base, addresses.partyIconList_offset) for i = 0, 7 do local guid = memoryReadInt(getProc(), listStart + i * 12) if guid == self.GUID then return i + 1 end end end function CPawn:countMobs(inrange, onlyaggro, idorname) self:updateXYZ() local count = 0 local objectList = CObjectList(); objectList:update(); for i = 0,objectList:size() do local obj = objectList:getObject(i); if obj ~= nil and obj.Type == PT_MONSTER and (inrange == nil or inrange >= distance(self.X,self.Z,self.Y,obj.X,obj.Z,obj.Y) ) and (idorname == nil or idorname == obj.Name or idorname == obj.Id) then local pawn = CPawn.new(obj.Address) pawn:updateAlive() pawn:updateHP() pawn:updateAttackable() pawn:updateLevel() if pawn.Alive and pawn.HP >=1 and pawn.Attackable and pawn.Level > 1 then if onlyaggro == true then pawn:updateTargetPtr() if pawn.TargetPtr == player.Address then count = count + 1 end else count = count + 1 end end end end return count end function CPawn:findBestClickPoint(aoerange, skillrange, onlyaggro, evalFunc) -- Finds best place to click to get most mobs including this pawn. self:updateXYZ() player:updateXYZ() local MobList = {} local EPList = {} if( type(evalFunc) ~= "function" ) then --default func evalFunc = function (address,pawn) if pawn.Alive and pawn.HP >=1 and pawn.Attackable and pawn.Level > 1 then return true else return false end end; end local function CountMobsInRangeOfCoords(x,z) local c = 0 local excludeList = false; local included = false; local list = {} for k,mob in ipairs(MobList) do if distance(x,z,mob.X,mob.Z) <= aoerange then table.insert(list,k) c=c+1 end end return c, list end local function GetEquidistantPoints(p1, p2, dist) -- Returns the 2 points that are both 'dist' away from both p1 and p2 local xvec = p2.X - p1.X local zvec = p2.Z - p1.Z local ratio = math.sqrt(dist*dist/(xvec*xvec +zvec*zvec) - 0.25) -- transpose local newxvec = zvec * ratio local newzvec = xvec * ratio local ep1 = {X = (p1.X + p2.X)/2 + newxvec, Z = (p1.Z + p2.Z)/2 - newzvec} local ep2 = {X = (p1.X + p2.X)/2 - newxvec, Z = (p1.Z + p2.Z)/2 + newzvec} return ep1, ep2 end -- The value this function needs to beat or match (if aoe center is this pawn) local countmobs = self:countMobs(aoerange, onlyaggro) -- Check if user wants to bypass this function -- Blubblab:c I'dont need that -- if settings.profile.options.FORCE_BETTER_AOE_TARGETING == false then -- return countmobs, self.X, self.Z -- end -- First get list of mobs within (2 x aoerange) of this pawn and (skillrange + aoerange) from player. local objectList = CObjectList(); objectList:update(); for i = 0,objectList:size() do local obj = objectList:getObject(i); if obj ~= nil and obj.Type == PT_MONSTER and (settings.profile.options.FORCE_BETTER_AOE_TARGETING or 0.5 > math.abs(obj.Y - self.Y)) and -- only count mobs on flat floor, results would be unpredictable on hilly surfaces when clicking. aoerange*2 >= distance(self.X,self.Z,self.Y,obj.X,obj.Z,obj.Y) and (skillrange + aoerange >= distance(player.X, player.Z, obj.X, obj.Z)) then local pawn = CPawn.new(obj.Address); pawn:updateAlive() pawn:updateHP() pawn:updateAttackable() pawn:updateLevel() pawn:updateXYZ() -- For the rest of the function if evalFunc(pawn.Address,pawn)== true then if onlyaggro == true then pawn:updateTargetPtr() if pawn.TargetPtr == player.Address then table.insert(MobList,pawn) end else table.insert(MobList,pawn) end end end end -- Deal with easy solutions if countmobs > #MobList or #MobList < 2 then return countmobs, self.X, self.Z elseif #MobList == 2 then local averageX = (MobList[1].X + MobList[2].X)/2 local averageZ = (MobList[1].Z + MobList[2].Z)/2 return 2, averageX, averageZ end -- Get list of best equidistant points(EPs) and add list of mobs in range for each point local bestscore = 0 for p1 = 1, #MobList-1 do local mob1 = MobList[p1] for p2 = p1+1, #MobList do local mob2 = MobList[p2] local ep1, ep2 = GetEquidistantPoints(mob1, mob2, aoerange - 3) -- '-1' buffer -- Check ep1 and add local dist = distance(player.X, player.Z, ep1.X, ep1.Z) if aoerange >= distance(ep1, self) or (settings.profile.options.FORCE_BETTER_AOE_TARGETING and dist < settings.profile.options.MAX_TARGET_DIST and dist < settings.profile.options.COMBAT_DISTANCE) then -- EP doesn't miss primary target(self) local tmpcount, tmplist = CountMobsInRangeOfCoords(ep1.X, ep1.Z) if tmpcount > bestscore then bestscore = tmpcount EPList = {} -- Reset for higher scoring EPs end if tmpcount == bestscore then ep1.Mobs = tmplist table.insert(EPList,ep1) end end local dist2 = distance(player.X, player.Z, ep2.X, ep2.Z) -- Check ep2 and add if aoerange > distance(ep2,self) or (settings.profile.options.FORCE_BETTER_AOE_TARGETING and dist2 < settings.profile.options.MAX_TARGET_DIST and dist2 < settings.profile.options.COMBAT_DISTANCE)then -- EP doesn't miss primary target(self) local tmpcount, tmplist = CountMobsInRangeOfCoords(ep2.X, ep2.Z) if tmpcount > bestscore then bestscore = tmpcount EPList = {} -- Reset for higher scoring EPs end if tmpcount == bestscore then ep2.Mobs = tmplist table.insert(EPList,ep2) end end end end -- Is best score good enough to beat self:countMobs? if countmobs >= bestscore then return countmobs, self.X, self.Z end -- Sort EP mob lists for easy comparison for i = 1, #EPList do table.sort(EPList[i].Mobs) end -- Find a set of EPs with matching mob list to first local BestEPSet = {EPList[1]} for i = 2, #EPList do local match = true for k,v in ipairs(EPList[1].Mobs) do if v ~= EPList[i].Mobs[k] then match = false break end end -- Same points if match then table.insert(BestEPSet,EPList[i]) end end -- Get average of EP points. That is our target point local totalx, totalz = 0, 0 for k,v in ipairs(BestEPSet) do totalx = totalx + v.X totalz = totalz + v.Z end -- Average x,z local AverageX = totalx/#BestEPSet local AverageZ = totalz/#BestEPSet return bestscore, AverageX, AverageZ end -- returns true if this CPawn is registered as a friend function CPawn:isFriend( aggroonly) -- Is self still valid if not self:exists() then return false end -- Pets are friends if( player.PetPtr ~= 0 and self.Address == player.PetPtr ) then return true; end -- Following options need 'settings' if( not settings ) then return false; end; -- Are they in party self:updateInParty() if settings.profile.options.PARTY == true and self.InParty then return true end -- If passed above tests and not friend and only interested in pawn that cause aggro, then return false if aggroonly == true then return false end -- Are they on the friends list self:updateName() for i,v in pairs(settings.profile.friends) do if( string.find( string.lower(self.Name), string.lower(v), 1, true) ) or tonumber(v) == self.Id then return true; end end return false; end -- returns true if this CPawn target is registered as a friend function CPawn:targetIsFriend(aggroonly) -- Is self still valid if not self:exists() then return false end self:updateTargetPtr() if self.TargetPtr == 0 then return false end local target = CPawn.new(self.TargetPtr) return target:isFriend(aggroonly) end function CPawn:getRemainingCastTime() local casttime = memoryReadFloat( getProc(), self.Address + addresses.pawnCasting_offset) local castsofar = memoryReadFloat( getProc(), self.Address + addresses.pawnCastingElapsed_offset) if casttime and castsofar then return casttime - castsofar, casttime else return 0,0 end end function CPawn:isOnMobIgnoreList() for k, v in pairs(player.MobIgnoreList) do if v.Address == self.Address then -- Check if we can clear it if distance(player,player.LastPlaceMobIgnored) > 50 and os.clock()-v.Time > 10 then table.remove(player.MobIgnoreList,k) return false else return true end end end return false end function CPawn:getLastDamage() return RoMScript("igf_events:getLastEnemyDamage()") end function CPawn:getLastCriticalTime() return RoMScript("igf_events:getLastEnemyCriticalTime()") end function CPawn:getLastDodgeTime() return RoMScript("igf_events:getLastEnemyDodgeTime()") end
mit
tudelft/chdkptp
lua/util.lua
4
16416
--[[ Copyright (C) 2010-2014 <reyalp (at) gmail dot com> 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --]] --[[ common generic lua utilities utilities that depend on the chdkptp api go in chdku ]] local util={} --[[ to allow overriding, e.g. for gui --]] util.util_stderr = io.stderr util.util_stdout = io.stdout -- return version components as numbers -- _VERSION does not usally contain final (release) number function util.lua_version() if type(_VERSION) ~= 'string' then error('missing _VERSION') end local major,minor = string.match(_VERSION,'(%d+)%.(%d+)') return tonumber(major),tonumber(minor) end util.lua_ver_major,util.lua_ver_minor = util.lua_version() function util.is_lua_ver(major,minor) return (major == util.lua_ver_major and minor == util.lua_ver_minor) end function util.fprintf(f,...) local args={...} if #args == 0 or type(args[1]) ~= 'string' then args[1]='' end f:write(string.format(unpack(args))) end function util.printf(...) fprintf(util.util_stdout,...) end function util.warnf(format,...) fprintf(util.util_stderr,"WARNING: " .. format,...) end function util.errf(format,...) fprintf(util.util_stderr,"ERROR: " .. format,...) end --[[ force reload a module ]] function util.forcerequire(modname,...) package.loaded[modname] = nil return require(modname,...) end --[[ log2(n) = log(n)/log(2) ]] function util.log2(n) return math.log(n)/0.693147180559945 end --[[ round to nearest int, away from 0 ]] function util.round(n) local f=math.floor(n) if n > 0 then if n-f < 0.5 then return f end return math.ceil(n) else if n-f > 0.5 then return math.ceil(n) end return f end end --[[ return a function that prints if result of curlevel_fn is greater than vlevel for making different areas of code have different verbosity ]] function util.make_msgf(curlevel_fn,fixed_level) if type(curlevel_fn) ~= 'function' then error('expected function') end if type(fixed_level) == 'nil' then -- return a function that expects a verbosity level as the first arg, e.g. -- myprint(1,"foo") return function(vlevel,format,...) if curlevel_fn() >= vlevel then util.printf(format,...) end end elseif tonumber(fixed_level) then -- return a function that only prints at fixed level, e.g -- myprint("foo") return function(format,...) if curlevel_fn() >= fixed_level then util.printf(format,...) end end else error('invalid type') end end function util.err_traceback(err) return debug.traceback(err,2) end util.extend_table_max_depth = 10 local extend_table_r extend_table_r = function(target,source,seen,depth) if not seen then seen = {} end if not depth then depth = 1 end if depth > util.extend_table_max_depth then error('extend_table: max depth'); end -- a source could have references to the target, don't want to do that seen[target]=true if seen[source] then error('extend_table: cycles'); end seen[source]=true for k,v in pairs(source) do if type(v) == 'table' then if type(target[k]) ~= 'table' then target[k] = {} end extend_table_r(target[k],v,seen,depth+1) else target[k]=v end end return target end --[[ copy members of source into target by default, not deep so any tables will be copied as references returns target so you can do x=extend_table({},...) opts deep=bool - copy recursively keys={key,key...} - copy only specified subset of keys, if key in source is unset, target is unchanged if deep, cycles result in an error deep does not copy keys which are themselves tables (the key will be a reference to the original key table) ]] function util.extend_table(target,source,opts) if not opts then opts={} end if type(target) ~= 'table' then error('extend_table: target not table') end if source == nil then -- easier handling of default options return target end if type(source) ~= 'table' then error('extend_table: source not table') end if source == target then error('extend_table: source == target') end if opts.deep then return extend_table_r(target, source) elseif opts.keys then -- copy only specific keys for i,k in ipairs(opts.keys) do if type(source[k]) == 'table' and opts.deep then if type(target[k]) ~= 'table' then target[k]={} end extend_table_r(target[k],source[k]) elseif source[k] ~= nil then target[k] = source[k] end end else for k,v in pairs(source) do target[k]=v end end return target end --[[ swap keys and values dupe values will be lost ]] function util.flip_table(t) local r={} for k,v in pairs(t) do r[v]=k end return r end --[[ compare v1 and v2 table values are compared recursively, returning true if all key/values in v2 exist in v1 ]] util.compare_values_subset_defaults = { maxdepth=10 } function util.compare_values_subset(v1,v2,opts,seen,depth) if not depth then depth=1 opts = util.extend_table(util.extend_table({},util.compare_values_subset_defaults),opts) elseif depth > opts.maxdepth then error('compare_values_subset: maxdepth exceeded') end if v1 == v2 then return true end -- if not exactly equal, check table if type(v2) ~= 'table' or type(v1) ~= 'table' then return false end if not seen then seen={} elseif seen[v2] then error('compare_values_subset: cycle') end -- TODO this is restrictive, t={}, t2={t,t} will be treated as cycle seen[v2] = true for k,v in pairs(v2) do if not util.compare_values_subset(v,v1[k],opts,seen,depth+1) then return false end end return true end --[[ compare v1 and v2 tables are recursively checked for identical keys and values ]] function util.compare_values(v1,v2,opts) if util.compare_values_subset(v1,v2,opts) then return util.compare_values_subset(v2,v1,opts) end return false end --[[ does table have value in it ? ]] function util.in_table(table,value) if table == nil then return false end for k,v in pairs(table) do if v == value then return true end end end function util.table_amean(table) if #table == 0 then return nil end local sum = 0 for i=1,#table do sum = sum + table[i] end return sum/#table end --[[ return table with sum, min, max, mean and standard deviation of values in table all values are nil if table is empty ]] function util.table_stats(table) if #table == 0 then return {} end local sum = 0 local min = table[1] local max = table[1] for i=1,#table do sum = sum + table[i] if table[i] < min then min = table[i] end if table[i] > max then max = table[i] end end local mean = sum/#table local vsum = 0 for i=1,#table do vsum = vsum + (table[i] - mean)^2 end return { min=min, max=max, sum=sum, mean=mean, sd=math.sqrt(vsum/#table) } end --[[ --turn an integer into a zero based array of bits --]] function util.bit_unpack(n,limit) if not limit then limit = 31 end local t={} n=math.floor(n) for i=0,limit do t[i]=n%2 n=math.floor(n/2) end return t end function util.bit_packu(bits) local r=0 local limit = #bits if limit > 31 then limit = 31 end for i=0,limit do r = r + bits[i]*2^i end return r end --[[ --pack a 0 based array of bits into a string --]] function util.bit_packstr(bits) local bpos = 0 local bitval = 1 local byte = 0 local i = 0 local out = {} while bits[i] do if bits[i] == 1 then byte = byte + bitval end if bpos < 7 then bpos = bpos + 1 bitval = bitval*2 else table.insert(out,string.char(byte)) bpos = 0 bitval = 1 byte = 0 end i = i + 1 end -- final incomplete value, will be padded with 0s if bpos ~= 0 then table.insert(out,string.char(byte)) end return table.concat(out) end function util.bit_unpackstr(str) local bytes = {string.byte(str,1,-1)} local r = {} local o = 0 for _,b in ipairs(bytes) do bits = util.bit_unpack(b,7) for j=0,7 do r[o]=bits[j] o = o + 1 end end return r end function util.bit_unpacked_fmt(t) local b = {} local r = {} local bi=0 for i=0,#t do table.insert(b,t[i]) bi = bi + 1 if bi==8 then table.insert(r,string.reverse(table.concat(b))) b={} bi=0 end end if #b ~= 0 then for i=#b,7 do table.insert(b,'-') end table.insert(r,string.reverse(table.concat(b))) end return table.concat(r,' ') end --[[ concatinate numeric indexed elements of dst onto the end of src ]] function util.array_cat(dst,src,opts) opts = util.extend_table({ start=1, last=#src, dststart=#dst+1, },opts) local di = opts.dststart for i=opts.start,opts.last do dst[di] = src[i] di = di+1 end return dst end --[[ return a slice of numeric indexed elements of an array ]] function util.array_slice(t,opts) opts = util.extend_table({ start=1, last=#t, rstart=1, },opts) local r={} local ri = opts.rstart for i=opts.start,opts.last do r[ri] = t[i] ri = ri+1 end return r end --[[ convert values of an array to table of value=true ]] function util.flag_table(t) local r={} for i,v in ipairs(t) do r[v]=true end return r end --[[ return a (sub)table value with path indicated by arrray, e.g. table_path_get(t,'a','b','c') returns t.a.b.c missing subtables in path return nil, like a missing value ]] function util.table_path_get(t,...) return util.table_pathtable_get(t,{...}) end function util.table_pathtable_get(t,keys) local sub=t for i,key in ipairs(keys) do local v = sub[key] if i == #keys then return v end -- missing subtables are treated as nil if type(v) == 'nil' then return v end if type(v) ~= 'table' then error('expected table for '..table.concat(keys,'.',1,i)) end sub = v end end --[[ return a (sub)table value indexed by a string like foo.bar note numbers will be treated as string indexes ]] function util.table_pathstr_get(t,keystr) return util.table_pathtable_get(t,util.string_split(keystr,'.',{plain=true})) end --[[ sort a table by nested subtable values cmp is a function, or one of 'asc', 'des' or nil (=asc) ]] function util.table_path_sort(t,path,cmp) -- default, low to high like lua default if not cmp or cmp == 'asc' then cmp = function(a,b) return a < b end elseif cmp == 'des' then cmp = function(a,b) return a > b end end table.sort(t,function(a,b) return cmp(util.table_pathtable_get(a,path),util.table_pathtable_get(b,path)) end) end --[[ split str delimited by pattern pat, or plain text if opts.plain empty pat splits chars trailing delimiters generate empty strings with func, iterate over split strings ]] function util.string_split(str,pat,opts) opts = util.extend_table({ plain=false, start=1, empty=true, -- include empty strings from multiple / trailing delimiters (default func only) },opts) local r = {} local pos = opts.start local s,e if not opts.func then opts.func = function(v) if string.len(v) > 0 or opts.empty then table.insert(r,v) end end end if string.len(pat) == 0 then while true do local c = string.sub(str,pos,pos) if string.len(c) == 0 then return r end pos = pos+1 opts.func(c) end end while true do s, e = string.find(str,pat,pos,opts.plain) if not s then opts.func(string.sub(str,pos,-1)) break end opts.func(string.sub(str,pos,s-1)) pos = e + 1 end return r end --[[ very simple meta-table inheritance ]] function util.mt_inherit(t,base) local mt={ __index=function(table, key) return base[key] end } setmetatable(t,mt) return t end function util.hexdump(str,offset) local c, result, byte if not offset then offset = 0 end c = 0 result = '' for i=1,#str do if c == 0 then result = result .. string.format("%8x: ",offset) end result = result .. string.format("%02x ",string.byte(str,i)) c = c + 1 if c == 16 then c = 0 offset = offset + 16 result = result .. "| " .. string.gsub(string.sub(str,i-15,i),'[%c%z%s\128-\255]','.') .. '\n' end end if c ~= 0 then for i=1,16-c do result = result .. "-- " end result = result .. "| " .. string.gsub(string.sub(str,-c),'[%c%z%s\128-\255]','.') end return result end -- requires lbuf function util.hexdump_words(str,offset,fmt) if not offset then offset = 0 end if not fmt then fmt = '0x%08x' end local lb = lbuf.new(str) local s = '' for i=0,string.len(str)-4,4 do if i%16 == 0 then if i > 1 then s = s .. '\n' end s = s .. string.format('0x%08x:',offset+i) end s = s..string.format(' '..fmt,lb:get_u32(i)) end return s..'\n' end local serialize_r serialize_r = function(v,opts,r,seen,depth) local vt = type(v) if vt == 'nil' or vt == 'boolean' then table.insert(r,tostring(v)) return end if vt == 'number' then -- camera has problems with decimal constants that would be negative if opts.fix_bignum and v > 0x7FFFFFFF then table.insert(r,string.format("0x%x",v)) -- camera numbers are ints elseif opts.forceint then table.insert(r,string.format("%d",v)) else table.insert(r,tostring(v)) end return end if vt == 'string' then table.insert(r,string.format('%q',v)) return end if vt == 'table' then if not depth then depth = 1 end if depth >= opts.maxdepth then error('serialize: max depth') end if not seen then seen={} elseif seen[v] then if opts.err_cycle then error('serialize: cycle') else table.insert(r,'"cycle:'..tostring(v)..'"') return end end -- TODO this is restrictive, t={}, t2={t,t} will be treated as cycle seen[v] = true; table.insert(r,'{') for k,v1 in pairs(v) do if opts.pretty then table.insert(r,'\n'..string.rep(' ',depth)) end -- more compact/friendly format simple string keys -- TODO we could make integers more compact by doing array part first if type(k) == 'string' and string.match(k,'^[_%a][%a%d_]*$') then table.insert(r,k) else table.insert(r,'[') serialize_r(k,opts,r,seen,depth+1) table.insert(r,']') end table.insert(r,'=') serialize_r(v1,opts,r,seen,depth+1) table.insert(r,',') end if opts.pretty then table.insert(r,'\n'..string.rep(' ',depth-1)) end table.insert(r,'}') return end if opts.err_type then error('serialize: unsupported type ' .. vt, 2) else table.insert(r,'"'..tostring(v)..'"') end end util.serialize_defaults = { -- maximum nested depth maxdepth=10, -- ignore or error on various conditions err_type=true, -- bad type, e.g. function, userdata err_cycle=true, -- cyclic references pretty=true, -- indents and newlines fix_bignum=true, -- send values > 2^31 as hex, to avoid problems with camera conversion from decimal forceint=true, -- convert numbers to integer } --[[ serialize lua values options as documented above ]] function util.serialize(v,opts) local r={} serialize_r(v,util.extend_table(util.extend_table({},util.serialize_defaults),opts),r) return table.concat(r) end --[[ turn string back into lua data by executing it and returning the value the value is sandboxed in an empty function environment returns the resulting value, or false + an error message on failure check the message, since the serialized value might be false or nil! ]] -- lua 5.1 if type(setfenv) == 'function' then function util.unserialize(s) local f,err=loadstring('return ' .. s) if not f then return false, err end setfenv(f,{}) -- empty fenv local status,r=pcall(f) if status then return r end return false,r end else -- lua 5.2 function util.unserialize(s) local f,err=load('return ' .. s,nil,'t',{}) if not f then return false, err end local status,r=pcall(f) if status then return r end return false,r end end --[[ hacky hacky "import" values from a table into globals ]] function util.import(t,names) if names == nil then for name,val in pairs(t) do _G[name] = val end return end for i,name in ipairs(names) do if t[name] ~= nil then _G[name] = t[name] end end end return util
gpl-2.0
70hz/Hercules
tools/item_merge.lua
45
22377
-- Copyright (c) Hercules Dev Team, licensed under GNU GPL. -- See the LICENSE file -- Base Author: Dastgir @ http://hercules.ws -- -- This script requires lua 5.1 to run. getmetatable('').__call = string.sub require('math') --Bit Operators local tab = { -- tab[i][j] = xor(i-1, j-1) {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, }, {1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 13, 12, 15, 14, }, {2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13, }, {3, 2, 1, 0, 7, 6, 5, 4, 11, 10, 9, 8, 15, 14, 13, 12, }, {4, 5, 6, 7, 0, 1, 2, 3, 12, 13, 14, 15, 8, 9, 10, 11, }, {5, 4, 7, 6, 1, 0, 3, 2, 13, 12, 15, 14, 9, 8, 11, 10, }, {6, 7, 4, 5, 2, 3, 0, 1, 14, 15, 12, 13, 10, 11, 8, 9, }, {7, 6, 5, 4, 3, 2, 1, 0, 15, 14, 13, 12, 11, 10, 9, 8, }, {8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, }, {9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3, 2, 5, 4, 7, 6, }, {10, 11, 8, 9, 14, 15, 12, 13, 2, 3, 0, 1, 6, 7, 4, 5, }, {11, 10, 9, 8, 15, 14, 13, 12, 3, 2, 1, 0, 7, 6, 5, 4, }, {12, 13, 14, 15, 8, 9, 10, 11, 4, 5, 6, 7, 0, 1, 2, 3, }, {13, 12, 15, 14, 9, 8, 11, 10, 5, 4, 7, 6, 1, 0, 3, 2, }, {14, 15, 12, 13, 10, 11, 8, 9, 6, 7, 4, 5, 2, 3, 0, 1, }, {15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, }, } function bxor (a,b) local res, c = 0, 1 while a > 0 and b > 0 do local a2, b2 = math.fmod(a, 16), math.fmod(b, 16) res = res + tab[a2+1][b2+1]*c a = (a-a2)/16 b = (b-b2)/16 c = c*16 end res = res + a*c + b*c return res end local ff = 2^32 - 1 function bnot (a) return (ff - a) end function band (a,b) return ((a+b) - bxor(a,b))/2 end function bor (a,b) return (ff - band(ff - a, ff - b)) end function default_value(input,default) if (input==nil) then return default else return input end end print("-----------------------------------------------------------------") print("----------------- item_*.txt to ItemDB.conf --------------------") print("------------------- By Dastgir[Hercules] ------------------------") print("-----------------------------------------------------------------") if (arg[1]==nil) then --If any argument is missing, error print("Invalid Command:") print('Usage: item_merge.lua' ..' {item_db.conf}' ..' {item_trade.txt}' ..' {item_buyingstore.txt}' ..' {item_delay.txt}' ..' {item_nouse.txt}' ..' {item_stack.txt}' ..' {item_avail.txt}' ..' {output.conf}' --..' {sql_update_file.sql}' ) print("","If you have default names of *.txt files, then just run this tool") print("","","","\"item_merge.lua item_db.conf\"") os.exit() end arg[2] = default_value(arg[2],"item_trade.txt") arg[3] = default_value(arg[3],"item_buyingstore.txt") arg[4] = default_value(arg[4],"item_delay.txt") arg[5] = default_value(arg[5],"item_nouse.txt") arg[6] = default_value(arg[6],"item_stack.txt") arg[7] = default_value(arg[7],"item_avail.txt") arg[8] = default_value(arg[8],string.sub(arg[1],1,-6).."_converted.conf") function replace_char(pos, str, r) return str:sub(1, pos-1) .. r .. str:sub(pos+1) end function ltrim(trb) return (trb:gsub("^%s*", "")) end function file_exists(name) local f=io.open(name,"r") if f~=nil then io.close(f) return true else return false end end function d_t_s_quotes(s) --Double Quotes to Single Quotes and Comment Replacer s = s:gsub('\\\\',"\\") --Replace Lua Comments to C Style s = s:gsub('%-%-%[%[', '/%*') s = s:gsub("%-%-%]%]", '%*/') local newline = ParseCSVLine(s,"\n") if (#newline==0) then newline[1] = s end for i=1,#newline do if(string.sub(ltrim(newline[i]),1,2)=="--") then newline[i] = newline[i]:gsub("%-%-", '//', 1) end end s = MergeCSVLine(newline) return s end function st_fill_zero(s) --Fill remaining zero in Job Field of item_db zeros = "" if (s:len()>=8) then return s else for i=1,(8-s:len()) do zeros = zeros.."0" end zeros = zeros..""..s end --print(s:len(),zeros) return zeros end function newline(s,a) --Add Newline to Scripts Field if ((#(ParseCSVLine(s,"\n"))) > 1) then if(a==1) then return "\n" else return "\n\t" end else return "" end end function MergeCSVLine(linetbl) local merged_tbl = "" for j=1,#linetbl do if (j==#linetbl) then merged_tbl = merged_tbl..linetbl[j] else merged_tbl = merged_tbl..linetbl[j].."\n" end end return merged_tbl end function ParseCSVLine (line,sep) --Parse CSV for itemdb_*.txt fields local res = {} local pos = 1 sep = sep or ',' while true do local c = string.sub(line,pos,pos) if (c == "") then break end if (c == '"') then local txt = "" repeat local startp,endp = string.find(line,'^%b""',pos) txt = txt..string.sub(line,startp+1,endp-1) pos = endp + 1 c = string.sub(line,pos,pos) if (c == '"') then txt = txt..'"' end until (c ~= '"') table.insert(res,txt) assert(c == sep or c == "") pos = pos + 1 else local startp,endp = string.find(line,sep,pos) if (startp) then table.insert(res,string.sub(line,pos,startp-1)) pos = endp + 1 else table.insert(res,string.sub(line,pos)) break end end end return res end function deepcopy(orig) --Copy one table to other local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end setmetatable(copy, deepcopy(getmetatable(orig))) else -- number, string, boolean, etc copy = orig end return copy end function parse_line(line2,typl) --1=trade line_number = line_number+1 csv = ParseCSVLine(line2,",") csv1 = ParseCSVLine(csv[1],"\t") csv2 = ParseCSVLine(csv[1]," ") csv4 = tonumber(csv1[1]) if (csv4==nil) then csv4 = csv2[1] if (csv4 == nil) then csv4 = csv[1] end end k=tonumber(csv4) if (typl==3) then if (item_db2[k] ~= nil) then item_db2[k].BuyingStore = true --sql_update = sql_update.."UPDATE `item_db` SET `buyingstore` = 1 WHERE `id`="..csv4..";\n" end return end if (#csv<1) then return end k=tonumber(csv4) if (item_db2[k]~=nil) then if(typl>1 and typl~=3 and typl~=4 and typl~=7) then m=3 else m=2 end csv1 = ParseCSVLine(csv[m],"\t") csv2 = ParseCSVLine(csv[m]," ") csv3 = tonumber(csv1[1]) if (csv3==nil) then csv3 = csv2[1] if (csv3 == nil) then csv3 = csv[m] end end if (csv3==nil) then print("Invalid format on "..arg[m]..", line:"..line_number..", Skipping.") return end if (typl==2 and #csv==3) then item_db2[k].trade_flag = tonumber(csv[2]) item_db2[k].trade_override = tonumber(csv3) --sql_update = sql_update.."UPDATE `item_db` SET `trade_flag` = "..tonumber(csv[2]).." AND `trade_group` = "..tonumber(csv3).." WHERE `id`="..k..";\n" --No 3, since its parsed differently. elseif (typl==4 and #csv>=2) then if (tonumber(csv3)~=nil) then item_db2[k].Delay = tonumber(csv3) --sql_update = sql_update.."UPDATE `item_db` SET `delay` = "..tonumber(csv3).." WHERE `id`="..k..";\n" end elseif (typl==5 and #csv==3) then item_db2[k].nouse_flag = tonumber(csv[2]) item_db2[k].nouse_override = tonumber(csv3) --sql_update = sql_update.."UPDATE `item_db` SET `nouse_flag` = "..tonumber(csv[2]).." and `nouse_group` = "..tonumber(csv3).." WHERE `id`="..k..";\n" elseif (typl==6 and #csv==3) then item_db2[k].Stack1 = tonumber(csv[2]) item_db2[k].Stack2 = tonumber(csv3) --sql_update = sql_update.."UPDATE `item_db` SET `stack_amount` = "..tonumber(csv[2]).." and `stack_flag` = "..tonumber(csv3).." WHERE `id`="..k..";\n" elseif (typl==7 and #csv==2) then item_db2[k].Sprite = tonumber(csv3) --sql_update = sql_update.."UPDATE `item_db` SET `avail` = "..tonumber(csv3).." WHERE `id`="..k..";\n" else print("Invalid format on "..arg[typl]..", line:"..line_number..", Skipping.") --[[ --Debug Lines print("Invalid CSV",#csv,typl) for mo=1,#csv do print("csv["..mo.."]",csv[mo]) end os.exit() --]] end end return end function check_val(field) --Check if field null if (field == nil) then return("") end return(field) end function check_val_bool(field) --Checks boolean value if (field == false or field == "false") then return "false" elseif (field == true or field == "true") then return "true" end return "" end function check_val_two(field) --Check [a, b] types of field local field1,field2 field1 = "" field2 = "" if (field~=nil) then if (#field==2) then if (field[1][1] ~= nil and field[2] ~= nil) then field1 = field[1][1] field2 = field[2] elseif (field[1][1] ~= nil and field[2] == nil) then field1 = field[1][1] else field2 = field[2] end elseif(#field==1) then field1 = field[1] end end return field1, field2 end function item_db_write(s) --Write into item_db for i=1,65535 do ----Last ID till now if (s[i]~=nil) then s[i].Atk = check_val(s[i].Atk) s[i].Matk = check_val(s[i].Matk) s[i].EquipLv = check_val(s[i].EquipLv) if ((s[i].Atk == "" or s[i].Atk == 0) and (s[i].Matk == "" or s[i].Matk == 0)) then --Both Nil s[i].at = "" elseif (s[i].Atk ~= "" and (s[i].Matk == "" or s[i].Matk == 0)) then s[i].at = s[i].Atk elseif ((s[i].Atk == "" or s[i].Atk == 0) and s[i].Matk ~= "") then s[i].at = "0:"..s[i].Matk else s[i].at = s[i].Atk..":"..s[i].Matk end s[i].Refine = check_val_bool(s[i].Refine) s[i].BindOnEquip = check_val_bool(s[i].BindOnEquip) s[i].BuyingStore = check_val_bool(s[i].BuyingStore) s[i].Script = check_val(s[i].Script) s[i].OnEquipScript = check_val(s[i].OnEquipScript) s[i].OnUnequipScript = check_val(s[i].OnUnequipScript) s[i].ELv1, s[i].ELv2 = check_val_two(s[i].EquipLv) s[i].EquipMin = s[i].EquipLv[1] --Equip Min s[i].EquipMax = s[i].EquipLv[2] --Equip Max s[i].Script = d_t_s_quotes(s[i].Script) s[i].OnEquipScript = d_t_s_quotes(s[i].OnEquipScript) s[i].OnUnequipScript = d_t_s_quotes(s[i].OnUnequipScript) file3:write("{\n") --four Must fields to write. file3:write("\tId: "..(s[i].Id).."\n") file3:write("\tAegisName: \""..(s[i].AegisName).."\"\n") file3:write("\tName: \""..(s[i].Name).."\"\n") file3:write("\tType: "..(s[i].Type).."\n") if (check_val(s[i].Buy)~="") then file3:write("\tBuy: "..(s[i].Buy).."\n") end if (check_val(s[i].Sell)~="") then file3:write("\tSell: "..(s[i].Sell).."\n") end if (check_val(s[i].Weight)~="") then file3:write("\tWeight: "..(s[i].Weight).."\n") end if (s[i].Atk~="") then file3:write("\tAtk: "..(s[i].Atk).."\n") end if (s[i].Matk~="") then file3:write("\tMatk: "..(s[i].Matk).."\n") end if (check_val(s[i].Def)~="") then file3:write("\tDef: "..(s[i].Def).."\n") end if (check_val(s[i].Range)~="") then file3:write("\tRange: "..(s[i].Range).."\n") end if (check_val(s[i].Slots)~="") then file3:write("\tSlots: "..(s[i].Slots).."\n") end if (check_val(s[i].Job)~="") then file3:write("\tJob: 0x"..st_fill_zero(string.upper(string.format("%x",s[i].Job))).."\n") --Convert to Hex,Make it to UpperCase, Fill with zero's end if (check_val(s[i].Upper)~="") then file3:write("\tUpper: "..(s[i].Upper).."\n") end if (check_val(s[i].Gender)~="") then file3:write("\tGender: "..(s[i].Gender).."\n") end if (check_val(s[i].Loc)~="") then file3:write("\tLoc: "..(s[i].Loc).."\n") end if (check_val(s[i].WeaponLv)~="") then file3:write("\tWeaponLv: "..(s[i].WeaponLv).."\n") end if (s[i].ELv1~="" and s[i].ELv2~="" ) then --Both Not Empty file3:write("\tEquipLv: ["..(s[i].ELv1)..", "..(s[i].ELv2).."]\n") else if(s[i].ELv1~="") then --First not empty file3:write("\tEquipLv: "..(s[i].ELv1).."\n") end end if (check_val(s[i].Refine)~="") then file3:write("\tRefine: "..(s[i].Refine).."\n") end if (check_val(s[i].View)~="") then file3:write("\tView: "..(s[i].View).."\n") end if (s[i].BindOnEquip~="") then file3:write("\tBindOnEquip: "..(s[i].BindOnEquip).."\n") end if (s[i].BuyingStore~="") then file3:write("\tBuyingStore: true\n") end if (check_val(s[i].Delay) ~= "") then file3:write("\tDelay: "..(s[i].Delay).."\n") end if (check_val(s[i].trade_flag)~="" and check_val(s[i].trade_override)~="" ) then file3:write("\tTrade: {\n") if (s[i].trade_override > 0 and s[i].trade_override < 100) then file3:write("\t\toverride: ".. s[i].trade_override .."\n") end if (band(s[i].trade_flag,1)>0) then file3:write("\t\tnodrop: true\n") end if (band(s[i].trade_flag,2)>0) then file3:write("\t\tnotrade: true\n") end if (band(s[i].trade_flag,4)>0) then file3:write("\t\tpartneroverride: true\n") end if (band(s[i].trade_flag,8)>0) then file3:write("\t\tnoselltonpc: true\n") end if (band(s[i].trade_flag,16)>0) then file3:write("\t\tnocart: true\n") end if (band(s[i].trade_flag,32)>0) then file3:write("\t\tnostorage: true\n") end if (band(s[i].trade_flag,64)>0) then file3:write("\t\tnogstorage: true\n") end if (band(s[i].trade_flag,128)>0) then file3:write("\t\tnomail: true\n") end if (band(s[i].trade_flag,256)>0) then file3:write("\t\tnoauction: true\n") end file3:write("\t}\n") end if (check_val(s[i].nouse_flag)~="" and check_val(s[i].nouse_override)~="" ) then file3:write("\tNouse: {\n") if (tonumber(s[i].nouse_override) > 0 and tonumber(s[i].nouse_override) < 100) then file3:write("\t\toverride: ".. s[i].nouse_override .."\n") end if (band(s[i].nouse_flag,1)>0) then file3:write("\t\tsitting: true\n") end file3:write("\t}\n") end if check_val((s[i].Stack1)~="" and check_val(s[i].Stack2)~="" ) then file3:write("\tStack: ["..(s[i].Stack1)..", "..(s[i].Stack2).."]\n") end if (check_val(s[i].Sprite)~="" ) then file3:write("\tSprite: "..(s[i].Sprite).."\n") end if (s[i].Script ~= "") then file3:write("\tScript: <\""..newline(s[i].Script,1)..""..s[i].Script.."\">\n") end if (s[i].OnEquipScript ~= "") then file3:write("\tOnEquipScript: <\""..newline(s[i].OnEquipScript,1)..""..s[i].OnEquipScript.."\">\n") end if (s[i].OnUnequipScript ~= "") then file3:write("\tOnUnequipScript: <\""..newline(s[i].OnUnequipScript,1)..""..s[i].OnUnequipScript.."\">\n") end file3:write("},\n") end end end for i=1,7 do if (file_exists(arg[i])==false) then print("Error: ",arg[i]," Not Found") os.exit() end end file = assert(io.open(arg[1])) --Open ItemDB And Read its contents contents = file:read'*a' file:close() --Replacing Contents find = { '\\', '\'', '//', '/%*', '%*/', '<\"', '\">', 'Id([^:]?):([^\n]+)', 'AegisName([^:]?):([^\n]+)', 'Name([^:]?):([^\n]+)', 'Type([^:]?):([^\n]+)', 'Buy([^:]?):([^\n]+)', 'Sell([^:]?):([^\n]+)', 'Weight([^:]?):([^\n]+)', 'Atk([^:]?):([^\n]+)', 'Matk([^:]?):([^\n]+)', 'Def([^:]?):([^\n]+)', 'Range([^:]?):([^\n]+)', 'Slots([^:]?):([^\n]+)', 'Job([^:]?):([^\n]+)', 'Upper([^:]?):([^\n]+)', 'Gender([^:]?):([^\n]+)', 'Loc([^:]?):([^\n]+)', 'WeaponLv([^:]?):([^\n]+)', 'EquipLv([^:]?):([^\n]+)', 'Refine([^:]?):([^\n]+)', 'View([^:]?):([^\n]+)', 'BindOnEquip([^:]?):([^\n]+)', "BuyingStore([^:]?):([^\n]+)", "Delay([^:]?):([^\n]+)", "Stack([^:]?): %[([^,]+), ([^]]+)%]", "Sprite([^:]?):([^\n]+)", 'override([^:]?):([^\n]+)', 'nodrop([^:]?):([^\n]+)', 'notrade([^:]?):([^\n]+)', 'partneroverride([^:]?):([^\n]+)', 'noselltonpc([^:]?):([^\n]+)', 'nocart([^:]?):([^\n]+)', 'nostorage([^:]?):([^\n]+)', 'nogstorage([^:]?):([^\n]+)', 'nomail([^:]?):([^\n]+)', 'noauction([^:]?):([^\n]+)', 'sitting([^:]?):([^\n]+)', 'Script([^:]?):', 'OnEquipScript([^:]?):', 'OnUnequipScript([^:]?):', 'EquipLv([^=]?)= %[([^,]+), ([^]]+)%],', 'EquipLv([^=]?)= ([^,]+),', 'item_db: %(', '= ""', '= \n', ',,'} replace = {'\\\\', '\\\'', '--', '--[[', '--]]', '[==[', ']==],', 'Id%1=%2,', 'AegisName%1=%2,', 'Name%1=%2,', 'Type%1=%2,', 'Buy%1=%2,', 'Sell%1=%2,', 'Weight%1=%2,', 'Atk%1=%2,', 'Matk%1=%2,', 'Def%1=%2,', 'Range%1=%2,', 'Slots%1=%2,', 'Job%1=%2,', 'Upper%1=%2,', 'Gender%1=%2,', 'Loc%1=%2,', 'WeaponLv%1=%2,', 'EquipLv%1=%2,', 'Refine%1=%2,', 'View%1=%2,', 'BindOnEquip%1=%2,', "BuyingStore%1=%2,", "Delay%1=%2,", "Stack%1= {%2, %3},", "Sprite%1=%2,", 'override%1=%2,', 'nodrop%1=%2,', 'notrade%1=%2,', 'partneroverride%1=%2,', 'noselltonpc%1=%2,', 'nocart%1=%2,', 'nostorage%1=%2,', 'nogstorage%1=%2,', 'nomail%1=%2,', 'noauction%1=%2,', 'sitting%1=%2,', 'Script%1=', 'OnEquipScript%1=', 'OnUnequipScript%1=', 'EquipLv%1= {%2, %3},', 'EquipLv%1= {%2},', 'item_db = {', '= "",', '= "",\n', ',' } findk=0 if #find==#replace then --Check if both table matches start_time = os.time() print("-- Putting ",arg[1]," Items into Memory") --Replace Every Strings contents = contents:gsub("Nouse: {([^}]+)}","Nouse= {%1},") --It needs to be done first. contents = contents:gsub("Trade: {([^}]+)}","Trade= {%1},") --It needs to be done first. for i=1,#find do contents = contents:gsub(find[i],replace[i]) end --Check for last ) in item_db (it auto breaks if found, can have many empty lines on end) for i=1,1000000 do if (string.sub(contents,-i,-i) == ")") then findk = 1 contents = replace_char(contents:len()-i+1,contents,'}') end if (findk==1) then break end end else print('Error, Cannot Convert to Lua(Code:1['..#find..' '..#replace..'])') os.exit() end item_db = {} --Initialize Empty item_db table a = assert(loadstring(contents)) --Load the string as lua code a() --Execute it so it gets loaded into item_db table e_time = os.difftime((os.time())-start_time) --Time Taken print("---- Total Items Found"," = ",#item_db,"(".. e_time .."s)") csv = {} item_db2 = {} for i=1,#item_db do item_db2[item_db[i].Id] = deepcopy(item_db[i]) end --Initializing Global Tables csv = {} csv1 = {} csv2 = {} csv3 = "" csv4 = 0 --sql_update = "" k=0 line = "" --file4 = io.open(arg[9],"w") for m=2,7 do --arg[2] to arg[7] = item_*.txt line_number = 0 sp_file = assert(io.open(arg[m])) for line in sp_file:lines() do if ( line ~= "" and line:sub(1,2)~="//") then --If Line is comment or empty, don't parse it parse_line(line,m) end end print(arg[m],"Done") sp_file:close() --os.exit() end --file4:write(sql_update) --file4:close() print("-- Writing Item_DB") file3 = io.open(arg[8],"w") --Open Output File file3:write('item_db: (\n' ..'// Items Database\n' ..'//\n' ..'/******************************************************************************\n' ..' ************* Entry structure ************************************************\n' ..' ******************************************************************************\n' ..'{\n' ..' // =================== Mandatory fields ===============================\n' ..' Id: ID (int)\n' ..' AegisName: "Aegis_Name" (string)\n' ..' Name: "Item Name" (string)\n' ..' // =================== Optional fields ================================\n' ..' Type: Item Type (int, defaults to 3 = etc item)\n' ..' Buy: Buy Price (int, defaults to Sell * 2)\n' ..' Sell: Sell Price (int, defaults to Buy / 2)\n' ..' Weight: Item Weight (int, defaults to 0)\n' ..' Atk: Attack (int, defaults to 0)\n' ..' Matk: Magical Attack (int, defaults to 0, ignored in pre-re)\n' ..' Def: Defense (int, defaults to 0)\n' ..' Range: Attack Range (int, defaults to 0)\n' ..' Slots: Slots (int, defaults to 0)\n' ..' Job: Job mask (int, defaults to all jobs = 0xFFFFFFFF)\n' ..' Upper: Upper mask (int, defaults to any = 0x3f)\n' ..' Gender: Gender (int, defaults to both = 2)\n' ..' Loc: Equip location (int, required value for equipment)\n' ..' WeaponLv: Weapon Level (int, defaults to 0)\n' ..' EquipLv: Equip required level (int, defaults to 0)\n' ..' EquipLv: [min, max] (alternative syntax with min / max level)\n' ..' Refine: Refineable (boolean, defaults to true)\n' ..' View: View ID (int, defaults to 0)\n' ..' BindOnEquip: true/false (boolean, defaults to false)\n' ..' BuyingStore: true/false (boolean, defaults to false)\n' ..' Delay: Delay to use item (int, defaults to 0)\n' ..' Trade: { (defaults to no restrictions)\n' ..' override: GroupID (int, defaults to 100)\n' ..' nodrop: true/false (boolean, defaults to false)\n' ..' notrade: true/false (boolean, defaults to false)\n' ..' partneroverride: true/false (boolean, defaults to false)\n' ..' noselltonpc: true/false (boolean, defaults to false)\n' ..' nocart: true/false (boolean, defaults to false)\n' ..' nostorage: true/false (boolean, defaults to false)\n' ..' nogstorage: true/false (boolean, defaults to false)\n' ..' nomail: true/false (boolean, defaults to false)\n' ..' noauction: true/false (boolean, defaults to false)\n' ..' }\n' ..' Nouse: { (defaults to no restrictions)\n' ..' override: GroupID (int, defaults to 100)\n' ..' sitting: true/false (boolean, defaults to false)\n' ..' }\n' ..' Stack: [amount, type] (int, defaults to 0)\n' ..' Sprite: SpriteID (int, defaults to 0)\n' ..' Script: <"\n' ..' Script\n' ..' (it can be multi-line)\n' ..' ">\n' ..' OnEquipScript: <" OnEquip Script (can also be multi-line) ">\n' ..' OnUnequipScript: <" OnUnequip Script (can also be multi-line) ">\n' ..'},\n' ..'******************************************************************************/\n') item_db_write(item_db2) file3:write('\n)\n') file3:close() --Close Output File os.exit()
gpl-3.0
VurtualRuler98/kswep2
lua/weapons/weapon_kswept_model10.lua
1
2371
--[[ Copyright 2018 vurtual VurtualRuler98@gmail.com vurtual.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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- --Receiver-- if (SERVER) then AddCSLuaFile() end if (CLIENT) then SWEP.PrintName = "TEST Model 10" SWEP.Author = "vurtual" SWEP.Slot = 1 SWEP.SlotPos = 0 end SWEP.AdminSpawnable = true SWEP.Base = "weapon_kswep" SWEP.Category = "KSwep Secondary" SWEP.Spawnable = true list.Add("NPCUsableWeapons", { class = "weapon_kswept_model10", title = "TEST Model 10" } ) --Barrel-- SWEP.HandlingModifier=5 SWEP.Length=7 SWEP.Primary.Spread = 0.084 SWEP.RecoilMassModifier=1.8 SWEP.MuzzleVelMod=1 --Magazine-- SWEP.Caliber = "vammo_38special_FMJ" SWEP.MagClass="Speedloader" SWEP.MagSize = 6 SWEP.MagType="38REV" function SWEP:ReloadAct(force) self:ReloadMag(force) end --Rail-- SWEP.CanFlashlight=true SWEP.LAMAttachment="1" --Sight-- SWEP.IronSightHeight=0.5 SWEP.IronSightsPos = Vector(-4.7, 2, 0.55) SWEP.IronSightsAng = Vector(-0.8,-0.1,0) function SWEP:InitScopeData(def) def.sensitivity=1 def.name="Default" def.scopeheight=0 def.zero = { mils=false, bc=0.149, min=50, max=50, step=0, default=50, battlesight=false } def.style="crosshair" if (CLIENT) then self:SetOptic2D("Default") end end --Stock-- SWEP.DrawOnce=false SWEP.HoldType="revolver" SWEP.IdleType="normal" SWEP.NoLowerAnim=true SWEP.LoweredOffset = 2 SWEP.Primary.Sound = Sound("Weapon_kswept_glock19.Single") SWEP.UseHands = true SWEP.WorldModel = "models/weapons/w_357.mdl" SWEP.ViewModel = "models/weapons//c_357.mdl" SWEP.ViewModelFlip = false function SWEP:InitAnims(tbl) tbl.InitialDrawAnim=ACT_VM_READY end --Trigger-- SWEP.NPCBustDist=512 SWEP.NPCBurstMax=2 SWEP.NPCBurstMin=1 SWEP.NPCBurstTimeMin= 0.3 SWEP.NPCBurstTimeMax = 0.5 SWEP.HoldOpen=false SWEP.OpenBolt=true SWEP.DoubleAction=true SWEP.Primary.Delay = 0.2 function SWEP:PrimaryFire() self:NormalFire() end
apache-2.0
stephank/luci
libs/rpcc/luasrc/rpcc.lua
93
2227
--[[ LuCIRPCc (c) 2009 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local util = require "luci.util" local json = require "luci.json" local ltn12 = require "luci.ltn12" local nixio = require "nixio", require "nixio.util" local tostring, assert, setmetatable = tostring, assert, setmetatable local error = error --- LuCI RPC Client. -- @cstyle instance module "luci.rpcc" RQLIMIT = 32 * nixio.const.buffersize --- Create a new JSON-RPC stream client. -- @class function -- @param fd File descriptor -- @param v1 Use protocol version 1.0 -- @return RPC Client Client = util.class() function Client.__init__(self, fd, v1) self.fd = fd self.uniqueid = tostring(self):match("0x([a-f0-9]+)") self.msgid = 1 self.v1 = v1 end --- Request an RP call and get the response. -- @param method Remote method -- @param params Parameters -- @param notification Notification only? -- @return response function Client.request(self, method, params, notification) local oldchunk = self.decoder and self.decoder.chunk self.decoder = json.ActiveDecoder(self.fd:blocksource(nil, RQLIMIT)) self.decoder.chunk = oldchunk local reqid = self.msgid .. self.uniqueid local reqdata = json.Encoder({ id = (not notification) and (self.msgid .. self.uniqueid) or nil, jsonrpc = (not self.v1) and "2.0" or nil, method = method, params = params }) ltn12.pump.all(reqdata:source(), self.fd:sink()) if not notification then self.msgid = self.msgid + 1 local response = self.decoder:get() assert(response.id == reqid, "Invalid response id") if response.error then error(response.error.message or response.error) end return response.result end end --- Create a transparent RPC proxy. -- @param prefix Method prefix -- @return RPC Proxy object function Client.proxy(self, prefix) prefix = prefix or "" return setmetatable({}, { __call = function(proxy, ...) return self:request(prefix, {...}) end, __index = function(proxy, name) return self:proxy(prefix .. name .. ".") end }) end
apache-2.0
changeway/packages
lang/luaexpat/files/compat-5.1r5/compat-5.1.lua
251
6391
-- -- Compat-5.1 -- Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat) -- According to Lua 5.1 -- $Id: compat-5.1.lua,v 1.22 2006/02/20 21:12:47 carregal Exp $ -- _COMPAT51 = "Compat-5.1 R5" local LUA_DIRSEP = '/' local LUA_OFSEP = '_' local OLD_LUA_OFSEP = '' local POF = 'luaopen_' local LUA_PATH_MARK = '?' local LUA_IGMARK = ':' local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub -- -- avoid overwriting the package table if it's already there -- package = package or {} local _PACKAGE = package package.path = LUA_PATH or os.getenv("LUA_PATH") or ("./?.lua;" .. "/usr/local/share/lua/5.0/?.lua;" .. "/usr/local/share/lua/5.0/?/?.lua;" .. "/usr/local/share/lua/5.0/?/init.lua" ) package.cpath = LUA_CPATH or os.getenv("LUA_CPATH") or "./?.so;" .. "./l?.so;" .. "/usr/local/lib/lua/5.0/?.so;" .. "/usr/local/lib/lua/5.0/l?.so" -- -- make sure require works with standard libraries -- package.loaded = package.loaded or {} package.loaded.debug = debug package.loaded.string = string package.loaded.math = math package.loaded.io = io package.loaded.os = os package.loaded.table = table package.loaded.base = _G package.loaded.coroutine = coroutine local _LOADED = package.loaded -- -- avoid overwriting the package.preload table if it's already there -- package.preload = package.preload or {} local _PRELOAD = package.preload -- -- looks for a file `name' in given path -- local function findfile (name, pname) name = gsub (name, "%.", LUA_DIRSEP) local path = _PACKAGE[pname] assert (type(path) == "string", format ("package.%s must be a string", pname)) for c in gfind (path, "[^;]+") do c = gsub (c, "%"..LUA_PATH_MARK, name) local f = io.open (c) if f then f:close () return c end end return nil -- not found end -- -- check whether library is already loaded -- local function loader_preload (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) assert (type(_PRELOAD) == "table", "`package.preload' must be a table") return _PRELOAD[name] end -- -- Lua library loader -- local function loader_Lua (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "path") if not filename then return false end local f, err = loadfile (filename) if not f then error (format ("error loading module `%s' (%s)", name, err)) end return f end local function mkfuncname (name) name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", LUA_OFSEP) return POF..name end local function old_mkfuncname (name) --name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", OLD_LUA_OFSEP) return POF..name end -- -- C library loader -- local function loader_C (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "cpath") if not filename then return false end local funcname = mkfuncname (name) local f, err = loadlib (filename, funcname) if not f then funcname = old_mkfuncname (name) f, err = loadlib (filename, funcname) if not f then error (format ("error loading module `%s' (%s)", name, err)) end end return f end local function loader_Croot (name) local p = gsub (name, "^([^.]*).-$", "%1") if p == "" then return end local filename = findfile (p, "cpath") if not filename then return end local funcname = mkfuncname (name) local f, err, where = loadlib (filename, funcname) if f then return f elseif where ~= "init" then error (format ("error loading module `%s' (%s)", name, err)) end end -- create `loaders' table package.loaders = package.loaders or { loader_preload, loader_Lua, loader_C, loader_Croot, } local _LOADERS = package.loaders -- -- iterate over available loaders -- local function load (name, loaders) -- iterate over available loaders assert (type (loaders) == "table", "`package.loaders' must be a table") for i, loader in ipairs (loaders) do local f = loader (name) if f then return f end end error (format ("module `%s' not found", name)) end -- sentinel local sentinel = function () end -- -- new require -- function _G.require (modname) assert (type(modname) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local p = _LOADED[modname] if p then -- is it there? if p == sentinel then error (format ("loop or previous error loading module '%s'", modname)) end return p -- package is already loaded end local init = load (modname, _LOADERS) _LOADED[modname] = sentinel local actual_arg = _G.arg _G.arg = { modname } local res = init (modname) if res then _LOADED[modname] = res end _G.arg = actual_arg if _LOADED[modname] == sentinel then _LOADED[modname] = true end return _LOADED[modname] end -- findtable local function findtable (t, f) assert (type(f)=="string", "not a valid field name ("..tostring(f)..")") local ff = f.."." local ok, e, w = find (ff, '(.-)%.', 1) while ok do local nt = rawget (t, w) if not nt then nt = {} t[w] = nt elseif type(t) ~= "table" then return sub (f, e+1) end t = nt ok, e, w = find (ff, '(.-)%.', e+1) end return t end -- -- new package.seeall function -- function _PACKAGE.seeall (module) local t = type(module) assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")") local meta = getmetatable (module) if not meta then meta = {} setmetatable (module, meta) end meta.__index = _G end -- -- new module function -- function _G.module (modname, ...) local ns = _LOADED[modname] if type(ns) ~= "table" then ns = findtable (_G, modname) if not ns then error (string.format ("name conflict for module '%s'", modname)) end _LOADED[modname] = ns end if not ns._NAME then ns._NAME = modname ns._M = ns ns._PACKAGE = gsub (modname, "[^.]*$", "") end setfenv (2, ns) for i, f in ipairs (arg) do f (ns) end end
gpl-2.0
facebokiii/Uproject
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
Wiladams/LJIT2perfmon
fun.lua
1
28396
--- --- Lua Fun - a high-performance functional programming library for LuaJIT --- --- Copyright (c) 2013-2014 Roman Tsisyk <roman@tsisyk.com> --- --- Distributed under the MIT/X11 License. See COPYING.md for more details. --- local exports = {} local methods = {} -------------------------------------------------------------------------------- -- Tools -------------------------------------------------------------------------------- local return_if_not_empty = function(state_x, ...) if state_x == nil then return nil end return ... end local call_if_not_empty = function(fun, state_x, ...) if state_x == nil then return nil end return state_x, fun(...) end local function deepcopy(orig) -- used by cycle() local orig_type = type(orig) local copy if orig_type == 'table' then copy = {} for orig_key, orig_value in next, orig, nil do copy[deepcopy(orig_key)] = deepcopy(orig_value) end else copy = orig end return copy end local iterator_mt = { -- usually called by for-in loop __call = function(self, param, state) return self.gen(param, state) end; __tostring = function(self) return '<generator>' end; -- add all exported methods __index = methods; } local wrap = function(gen, param, state) return setmetatable({ gen = gen, param = param, state = state }, iterator_mt), param, state end exports.wrap = wrap local unwrap = function(self) return self.gen, self.param, self.state end methods.unwrap = unwrap -------------------------------------------------------------------------------- -- Basic Functions -------------------------------------------------------------------------------- local nil_gen = function(_param, _state) return nil end local string_gen = function(param, state) local state = state + 1 if state > #param then return nil end local r = string.sub(param, state, state) return state, r end local pairs_gen = pairs({ a = 0 }) -- get the generating function from pairs local map_gen = function(tab, key) local value local key, value = pairs_gen(tab, key) return key, key, value end local rawiter = function(obj, param, state) assert(obj ~= nil, "invalid iterator") if type(obj) == "table" then local mt = getmetatable(obj); if mt ~= nil then if mt == iterator_mt then return obj.gen, obj.param, obj.state elseif mt.__ipairs ~= nil then return mt.__ipairs(obj) elseif mt.__pairs ~= nil then return mt.__pairs(obj) end end if #obj > 0 then -- array return ipairs(obj) else -- hash return map_gen, obj, nil end elseif (type(obj) == "function") then return obj, param, state elseif (type(obj) == "string") then if #obj == 0 then return nil_gen, nil, nil end return string_gen, obj, 0 end error(string.format('object %s of type "%s" is not iterable', obj, type(obj))) end local iter = function(obj, param, state) return wrap(rawiter(obj, param, state)) end exports.iter = iter local method0 = function(fun) return function(self) return fun(self.gen, self.param, self.state) end end local method1 = function(fun) return function(self, arg1) return fun(arg1, self.gen, self.param, self.state) end end local method2 = function(fun) return function(self, arg1, arg2) return fun(arg1, arg2, self.gen, self.param, self.state) end end local export0 = function(fun) return function(gen, param, state) return fun(rawiter(gen, param, state)) end end local export1 = function(fun) return function(arg1, gen, param, state) return fun(arg1, rawiter(gen, param, state)) end end local export2 = function(fun) return function(arg1, arg2, gen, param, state) return fun(arg1, arg2, rawiter(gen, param, state)) end end local each = function(fun, gen, param, state) repeat state = call_if_not_empty(fun, gen(param, state)) until state == nil end methods.each = method1(each) exports.each = export1(each) methods.for_each = methods.each exports.for_each = exports.each methods.foreach = methods.each exports.foreach = exports.each -------------------------------------------------------------------------------- -- Generators -------------------------------------------------------------------------------- local range_gen = function(param, state) local stop, step = param[1], param[2] local state = state + step if state > stop then return nil end return state, state end local range_rev_gen = function(param, state) local stop, step = param[1], param[2] local state = state + step if state < stop then return nil end return state, state end local range = function(start, stop, step) if step == nil then if stop == nil then if start == 0 then return nil_gen, nil, nil end stop = start start = stop > 0 and 1 or -1 end step = start <= stop and 1 or -1 end assert(type(start) == "number", "start must be a number") assert(type(stop) == "number", "stop must be a number") assert(type(step) == "number", "step must be a number") assert(step ~= 0, "step must not be zero") if (step > 0) then return wrap(range_gen, {stop, step}, start - step) elseif (step < 0) then return wrap(range_rev_gen, {stop, step}, start - step) end end exports.range = range local duplicate_table_gen = function(param_x, state_x) return state_x + 1, unpack(param_x) end local duplicate_fun_gen = function(param_x, state_x) return state_x + 1, param_x(state_x) end local duplicate_gen = function(param_x, state_x) return state_x + 1, param_x end local duplicate = function(...) if select('#', ...) <= 1 then return wrap(duplicate_gen, select(1, ...), 0) else return wrap(duplicate_table_gen, {...}, 0) end end exports.duplicate = duplicate exports.replicate = duplicate exports.xrepeat = duplicate local tabulate = function(fun) assert(type(fun) == "function") return wrap(duplicate_fun_gen, fun, 0) end exports.tabulate = tabulate local zeros = function() return wrap(duplicate_gen, 0, 0) end exports.zeros = zeros local ones = function() return wrap(duplicate_gen, 1, 0) end exports.ones = ones local rands_gen = function(param_x, _state_x) return 0, math.random(param_x[1], param_x[2]) end local rands_nil_gen = function(_param_x, _state_x) return 0, math.random() end local rands = function(n, m) if n == nil and m == nil then return wrap(rands_nil_gen, 0, 0) end assert(type(n) == "number", "invalid first arg to rands") if m == nil then m = n n = 0 else assert(type(m) == "number", "invalid second arg to rands") end assert(n < m, "empty interval") return wrap(rands_gen, {n, m - 1}, 0) end exports.rands = rands -------------------------------------------------------------------------------- -- Slicing -------------------------------------------------------------------------------- local nth = function(n, gen_x, param_x, state_x) assert(n > 0, "invalid first argument to nth") -- An optimization for arrays and strings if gen_x == ipairs then return param_x[n] elseif gen_x == string_gen then if n < #param_x then return string.sub(param_x, n, n) else return nil end end for i=1,n-1,1 do state_x = gen_x(param_x, state_x) if state_x == nil then return nil end end return return_if_not_empty(gen_x(param_x, state_x)) end methods.nth = method1(nth) exports.nth = export1(nth) local head_call = function(state, ...) if state == nil then error("head: iterator is empty") end return ... end local head = function(gen, param, state) return head_call(gen(param, state)) end methods.head = method0(head) exports.head = export0(head) exports.car = exports.head methods.car = methods.head local tail = function(gen, param, state) state = gen(param, state) if state == nil then return wrap(nil_gen, nil, nil) end return wrap(gen, param, state) end methods.tail = method0(tail) exports.tail = export0(tail) exports.cdr = exports.tail methods.cdr = methods.tail local take_n_gen_x = function(i, state_x, ...) if state_x == nil then return nil end return {i, state_x}, ... end local take_n_gen = function(param, state) local n, gen_x, param_x = param[1], param[2], param[3] local i, state_x = state[1], state[2] if i >= n then return nil end return take_n_gen_x(i + 1, gen_x(param_x, state_x)) end local take_n = function(n, gen, param, state) assert(n >= 0, "invalid first argument to take_n") return wrap(take_n_gen, {n, gen, param}, {0, state}) end methods.take_n = method1(take_n) exports.take_n = export1(take_n) local take_while_gen_x = function(fun, state_x, ...) if state_x == nil or not fun(...) then return nil end return state_x, ... end local take_while_gen = function(param, state_x) local fun, gen_x, param_x = param[1], param[2], param[3] return take_while_gen_x(fun, gen_x(param_x, state_x)) end local take_while = function(fun, gen, param, state) assert(type(fun) == "function", "invalid first argument to take_while") return wrap(take_while_gen, {fun, gen, param}, state) end methods.take_while = method1(take_while) exports.take_while = export1(take_while) local take = function(n_or_fun, gen, param, state) if type(n_or_fun) == "number" then return take_n(n_or_fun, gen, param, state) else return take_while(n_or_fun, gen, param, state) end end methods.take = method1(take) exports.take = export1(take) local drop_n = function(n, gen, param, state) assert(n >= 0, "invalid first argument to drop_n") local i for i=1,n,1 do state = gen(param, state) if state == nil then return wrap(nil_gen, nil, nil) end end return wrap(gen, param, state) end methods.drop_n = method1(drop_n) exports.drop_n = export1(drop_n) local drop_while_x = function(fun, state_x, ...) if state_x == nil or not fun(...) then return state_x, false end return state_x, true, ... end local drop_while = function(fun, gen_x, param_x, state_x) assert(type(fun) == "function", "invalid first argument to drop_while") local cont, state_x_prev repeat state_x_prev = deepcopy(state_x) state_x, cont = drop_while_x(fun, gen_x(param_x, state_x)) until not cont if state_x == nil then return wrap(nil_gen, nil, nil) end return wrap(gen_x, param_x, state_x_prev) end methods.drop_while = method1(drop_while) exports.drop_while = export1(drop_while) local drop = function(n_or_fun, gen_x, param_x, state_x) if type(n_or_fun) == "number" then return drop_n(n_or_fun, gen_x, param_x, state_x) else return drop_while(n_or_fun, gen_x, param_x, state_x) end end methods.drop = method1(drop) exports.drop = export1(drop) local split = function(n_or_fun, gen_x, param_x, state_x) return take(n_or_fun, gen_x, param_x, state_x), drop(n_or_fun, gen_x, param_x, state_x) end methods.split = method1(split) exports.split = export1(split) methods.split_at = methods.split exports.split_at = exports.split methods.span = methods.split exports.span = exports.split -------------------------------------------------------------------------------- -- Indexing -------------------------------------------------------------------------------- local index = function(x, gen, param, state) local i = 1 for _k, r in gen, param, state do if r == x then return i end i = i + 1 end return nil end methods.index = method1(index) exports.index = export1(index) methods.index_of = methods.index exports.index_of = exports.index methods.elem_index = methods.index exports.elem_index = exports.index local indexes_gen = function(param, state) local x, gen_x, param_x = param[1], param[2], param[3] local i, state_x = state[1], state[2] local r while true do state_x, r = gen_x(param_x, state_x) if state_x == nil then return nil end i = i + 1 if r == x then return {i, state_x}, i end end end local indexes = function(x, gen, param, state) return wrap(indexes_gen, {x, gen, param}, {0, state}) end methods.indexes = method1(indexes) exports.indexes = export1(indexes) methods.elem_indexes = methods.indexes exports.elem_indexes = exports.indexes methods.indices = methods.indexes exports.indices = exports.indexes methods.elem_indices = methods.indexes exports.elem_indices = exports.indexes -------------------------------------------------------------------------------- -- Filtering -------------------------------------------------------------------------------- local filter1_gen = function(fun, gen_x, param_x, state_x, a) while true do if state_x == nil or fun(a) then break; end state_x, a = gen_x(param_x, state_x) end return state_x, a end -- call each other local filterm_gen local filterm_gen_shrink = function(fun, gen_x, param_x, state_x) return filterm_gen(fun, gen_x, param_x, gen_x(param_x, state_x)) end filterm_gen = function(fun, gen_x, param_x, state_x, ...) if state_x == nil then return nil end if fun(...) then return state_x, ... end return filterm_gen_shrink(fun, gen_x, param_x, state_x) end local filter_detect = function(fun, gen_x, param_x, state_x, ...) if select('#', ...) < 2 then return filter1_gen(fun, gen_x, param_x, state_x, ...) else return filterm_gen(fun, gen_x, param_x, state_x, ...) end end local filter_gen = function(param, state_x) local fun, gen_x, param_x = param[1], param[2], param[3] return filter_detect(fun, gen_x, param_x, gen_x(param_x, state_x)) end local filter = function(fun, gen, param, state) return wrap(filter_gen, {fun, gen, param}, state) end methods.filter = method1(filter) exports.filter = export1(filter) methods.remove_if = methods.filter exports.remove_if = exports.filter local grep = function(fun_or_regexp, gen, param, state) local fun = fun_or_regexp if type(fun_or_regexp) == "string" then fun = function(x) return string.find(x, fun_or_regexp) ~= nil end end return filter(fun, gen, param, state) end methods.grep = method1(grep) exports.grep = export1(grep) local partition = function(fun, gen, param, state) local neg_fun = function(...) return not fun(...) end return filter(fun, gen, param, state), filter(neg_fun, gen, param, state) end methods.partition = method1(partition) exports.partition = export1(partition) -------------------------------------------------------------------------------- -- Reducing -------------------------------------------------------------------------------- local foldl_call = function(fun, start, state, ...) if state == nil then return nil, start end return state, fun(start, ...) end local foldl = function(fun, start, gen_x, param_x, state_x) while true do state_x, start = foldl_call(fun, start, gen_x(param_x, state_x)) if state_x == nil then break; end end return start end methods.foldl = method2(foldl) exports.foldl = export2(foldl) methods.reduce = methods.foldl exports.reduce = exports.foldl local length = function(gen, param, state) if gen == ipairs or gen == string_gen then return #param end local len = 0 repeat state = gen(param, state) len = len + 1 until state == nil return len - 1 end methods.length = method0(length) exports.length = export0(length) local is_null = function(gen, param, state) return gen(param, deepcopy(state)) == nil end methods.is_null = method0(is_null) exports.is_null = export0(is_null) local is_prefix_of = function(iter_x, iter_y) local gen_x, param_x, state_x = iter(iter_x) local gen_y, param_y, state_y = iter(iter_y) local r_x, r_y for i=1,10,1 do state_x, r_x = gen_x(param_x, state_x) state_y, r_y = gen_y(param_y, state_y) if state_x == nil then return true end if state_y == nil or r_x ~= r_y then return false end end end methods.is_prefix_of = is_prefix_of exports.is_prefix_of = is_prefix_of local all = function(fun, gen_x, param_x, state_x) local r repeat state_x, r = call_if_not_empty(fun, gen_x(param_x, state_x)) until state_x == nil or not r return state_x == nil end methods.all = method1(all) exports.all = export1(all) methods.every = methods.all exports.every = exports.all local any = function(fun, gen_x, param_x, state_x) local r repeat state_x, r = call_if_not_empty(fun, gen_x(param_x, state_x)) until state_x == nil or r return not not r end methods.any = method1(any) exports.any = export1(any) methods.some = methods.any exports.some = exports.any local sum = function(gen, param, state) local s = 0 local r = 0 repeat s = s + r state, r = gen(param, state) until state == nil return s end methods.sum = method0(sum) exports.sum = export0(sum) local product = function(gen, param, state) local p = 1 local r = 1 repeat p = p * r state, r = gen(param, state) until state == nil return p end methods.product = method0(product) exports.product = export0(product) local min_cmp = function(m, n) if n < m then return n else return m end end local max_cmp = function(m, n) if n > m then return n else return m end end local min = function(gen, param, state) local state, m = gen(param, state) if state == nil then error("min: iterator is empty") end local cmp if type(m) == "number" then -- An optimization: use math.min for numbers cmp = math.min else cmp = min_cmp end for _, r in gen, param, state do m = cmp(m, r) end return m end methods.min = method0(min) exports.min = export0(min) methods.minimum = methods.min exports.minimum = exports.min local min_by = function(cmp, gen_x, param_x, state_x) local state_x, m = gen_x(param_x, state_x) if state_x == nil then error("min: iterator is empty") end for _, r in gen_x, param_x, state_x do m = cmp(m, r) end return m end methods.min_by = method1(min_by) exports.min_by = export1(min_by) methods.minimum_by = methods.min_by exports.minimum_by = exports.min_by local max = function(gen_x, param_x, state_x) local state_x, m = gen_x(param_x, state_x) if state_x == nil then error("max: iterator is empty") end local cmp if type(m) == "number" then -- An optimization: use math.max for numbers cmp = math.max else cmp = max_cmp end for _, r in gen_x, param_x, state_x do m = cmp(m, r) end return m end methods.max = method0(max) exports.max = export0(max) methods.maximum = methods.max exports.maximum = exports.max local max_by = function(cmp, gen_x, param_x, state_x) local state_x, m = gen_x(param_x, state_x) if state_x == nil then error("max: iterator is empty") end for _, r in gen_x, param_x, state_x do m = cmp(m, r) end return m end methods.max_by = method1(max_by) exports.max_by = export1(max_by) methods.maximum_by = methods.maximum_by exports.maximum_by = exports.maximum_by local totable = function(gen_x, param_x, state_x) local tab, key, val = {} while true do state_x, val = gen_x(param_x, state_x) if state_x == nil then break end table.insert(tab, val) end return tab end methods.totable = method0(totable) exports.totable = export0(totable) local tomap = function(gen_x, param_x, state_x) local tab, key, val = {} while true do state_x, key, val = gen_x(param_x, state_x) if state_x == nil then break end tab[key] = val end return tab end methods.tomap = method0(tomap) exports.tomap = export0(tomap) -------------------------------------------------------------------------------- -- Transformations -------------------------------------------------------------------------------- local map_gen = function(param, state) local gen_x, param_x, fun = param[1], param[2], param[3] return call_if_not_empty(fun, gen_x(param_x, state)) end local map = function(fun, gen, param, state) return wrap(map_gen, {gen, param, fun}, state) end methods.map = method1(map) exports.map = export1(map) local enumerate_gen_call = function(state, i, state_x, ...) if state_x == nil then return nil end return {i + 1, state_x}, i, ... end local enumerate_gen = function(param, state) local gen_x, param_x = param[1], param[2] local i, state_x = state[1], state[2] return enumerate_gen_call(state, i, gen_x(param_x, state_x)) end local enumerate = function(gen, param, state) return wrap(enumerate_gen, {gen, param}, {1, state}) end methods.enumerate = method0(enumerate) exports.enumerate = export0(enumerate) local intersperse_call = function(i, state_x, ...) if state_x == nil then return nil end return {i + 1, state_x}, ... end local intersperse_gen = function(param, state) local x, gen_x, param_x = param[1], param[2], param[3] local i, state_x = state[1], state[2] if i % 2 == 1 then return {i + 1, state_x}, x else return intersperse_call(i, gen_x(param_x, state_x)) end end -- TODO: interperse must not add x to the tail local intersperse = function(x, gen, param, state) return wrap(intersperse_gen, {x, gen, param}, {0, state}) end methods.intersperse = method1(intersperse) exports.intersperse = export1(intersperse) -------------------------------------------------------------------------------- -- Compositions -------------------------------------------------------------------------------- local function zip_gen_r(param, state, state_new, ...) if #state_new == #param / 2 then return state_new, ... end local i = #state_new + 1 local gen_x, param_x = param[2 * i - 1], param[2 * i] local state_x, r = gen_x(param_x, state[i]) if state_x == nil then return nil end table.insert(state_new, state_x) return zip_gen_r(param, state, state_new, r, ...) end local zip_gen = function(param, state) return zip_gen_r(param, state, {}) end -- A special hack for zip/chain to skip last two state, if a wrapped iterator -- has been passed local numargs = function(...) local n = select('#', ...) if n >= 3 then -- Fix last argument local it = select(n - 2, ...) if type(it) == 'table' and getmetatable(it) == iterator_mt and it.param == select(n - 1, ...) and it.state == select(n, ...) then return n - 2 end end return n end local zip = function(...) local n = numargs(...) if n == 0 then return wrap(nil_gen, nil, nil) end local param = { [2 * n] = 0 } local state = { [n] = 0 } local i, gen_x, param_x, state_x for i=1,n,1 do local it = select(n - i + 1, ...) gen_x, param_x, state_x = rawiter(it) param[2 * i - 1] = gen_x param[2 * i] = param_x state[i] = state_x end return wrap(zip_gen, param, state) end methods.zip = zip exports.zip = zip local cycle_gen_call = function(param, state_x, ...) if state_x == nil then local gen_x, param_x, state_x0 = param[1], param[2], param[3] return gen_x(param_x, deepcopy(state_x0)) end return state_x, ... end local cycle_gen = function(param, state_x) local gen_x, param_x, state_x0 = param[1], param[2], param[3] return cycle_gen_call(param, gen_x(param_x, state_x)) end local cycle = function(gen, param, state) return wrap(cycle_gen, {gen, param, state}, deepcopy(state)) end methods.cycle = method0(cycle) exports.cycle = export0(cycle) -- call each other local chain_gen_r1 local chain_gen_r2 = function(param, state, state_x, ...) if state_x == nil then local i = state[1] i = i + 1 if i > #param / 3 then return nil end local state_x = param[3 * i] return chain_gen_r1(param, {i, state_x}) end return {state[1], state_x}, ... end chain_gen_r1 = function(param, state) local i, state_x = state[1], state[2] local gen_x, param_x = param[3 * i - 2], param[3 * i - 1] return chain_gen_r2(param, state, gen_x(param_x, state[2])) end local chain = function(...) local n = numargs(...) if n == 0 then return wrap(nil_gen, nil, nil) end local param = { [3 * n] = 0 } local i, gen_x, param_x, state_x for i=1,n,1 do local elem = select(i, ...) gen_x, param_x, state_x = iter(elem) param[3 * i - 2] = gen_x param[3 * i - 1] = param_x param[3 * i] = state_x end return wrap(chain_gen_r1, param, {1, param[3]}) end methods.chain = chain exports.chain = chain -------------------------------------------------------------------------------- -- Operators -------------------------------------------------------------------------------- operator = { ---------------------------------------------------------------------------- -- Comparison operators ---------------------------------------------------------------------------- lt = function(a, b) return a < b end, le = function(a, b) return a <= b end, eq = function(a, b) return a == b end, ne = function(a, b) return a ~= b end, ge = function(a, b) return a >= b end, gt = function(a, b) return a > b end, ---------------------------------------------------------------------------- -- Arithmetic operators ---------------------------------------------------------------------------- add = function(a, b) return a + b end, div = function(a, b) return a / b end, floordiv = function(a, b) return math.floor(a/b) end, intdiv = function(a, b) local q = a / b if a >= 0 then return math.floor(q) else return math.ceil(q) end end, mod = function(a, b) return a % b end, mul = function(a, b) return a * b end, neq = function(a) return -a end, unm = function(a) return -a end, -- an alias pow = function(a, b) return a ^ b end, sub = function(a, b) return a - b end, truediv = function(a, b) return a / b end, ---------------------------------------------------------------------------- -- String operators ---------------------------------------------------------------------------- concat = function(a, b) return a..b end, len = function(a) return #a end, length = function(a) return #a end, -- an alias ---------------------------------------------------------------------------- -- Logical operators ---------------------------------------------------------------------------- land = function(a, b) return a and b end, lor = function(a, b) return a or b end, lnot = function(a) return not a end, truth = function(a) return not not a end, } exports.operator = operator methods.operator = operator exports.op = operator methods.op = operator -------------------------------------------------------------------------------- -- module definitions -------------------------------------------------------------------------------- -- a special syntax sugar to export all functions to the global table setmetatable(exports, { __call = function(t) for k, v in pairs(t) do _G[k] = v end end, }) return exports
mit
Mephostopilis/lua
lualib/StackTracePlus.lua
1
12175
-- tables local _G = _G local string, io, debug, coroutine = string, io, debug, coroutine -- functions local tostring, print, require = tostring, print, require local next, assert = next, assert local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs local error = error assert(debug, "debug table must be available at this point") local io_open = io.open local string_gmatch = string.gmatch local string_sub = string.sub local table_concat = table.concat local _M = { max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' } -- this tables should be weak so the elements in them won't become uncollectable local m_known_tables = { [_G] = "_G (global table)" } local function add_known_module(name, desc) local ok, mod = pcall(require, name) if ok then m_known_tables[mod] = desc end end add_known_module("string", "string module") add_known_module("io", "io module") add_known_module("os", "os module") add_known_module("table", "table module") add_known_module("math", "math module") add_known_module("package", "package module") add_known_module("debug", "debug module") add_known_module("coroutine", "coroutine module") -- lua5.2 add_known_module("bit32", "bit32 module") -- luajit add_known_module("bit", "bit module") add_known_module("jit", "jit module") -- lua5.3 if _VERSION >= "Lua 5.3" then add_known_module("utf8", "utf8 module") end local m_user_known_tables = {} local m_known_functions = {} for _, name in ipairs{ -- Lua 5.2, 5.1 "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", -- Lua 5.1 "gcinfo", "getfenv", "loadstring", "module", "newproxy", "setfenv", "unpack", -- TODO: add table.* etc functions } do if _G[name] then m_known_functions[_G[name]] = name end end local m_user_known_functions = {} local function safe_tostring (value) local ok, err = pcall(tostring, value) if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end end -- Private: -- Parses a line, looking for possible function definitions (in a very naïve way) -- Returns '(anonymous)' if no function name was found in the line local function ParseLine(line) assert(type(line) == "string") --print(line) local match = line:match("^%s*function%s+(%w+)") if match then --print("+++++++++++++function", match) return match end match = line:match("^%s*local%s+function%s+(%w+)") if match then --print("++++++++++++local", match) return match end match = line:match("^%s*local%s+(%w+)%s+=%s+function") if match then --print("++++++++++++local func", match) return match end match = line:match("%s*function%s*%(") -- this is an anonymous function if match then --print("+++++++++++++function2", match) return "(anonymous)" end return "(anonymous)" end -- Private: -- Tries to guess a function's name when the debug info structure does not have it. -- It parses either the file or the string where the function is defined. -- Returns '?' if the line where the function is defined is not found local function GuessFunctionName(info) --print("guessing function name") if type(info.source) == "string" and info.source:sub(1,1) == "@" then local file, err = io_open(info.source:sub(2), "r") if not file then print("file not found: "..tostring(err)) -- whoops! return "?" end local line for _ = 1, info.linedefined do line = file:read("*l") end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) else local line local lineNumber = 0 for l in string_gmatch(info.source, "([^\n]+)\n-") do lineNumber = lineNumber + 1 if lineNumber == info.linedefined then line = l break end end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) end end --- -- Dumper instances are used to analyze stacks and collect its information. -- local Dumper = {} Dumper.new = function(thread) local t = { lines = {} } for k,v in pairs(Dumper) do t[k] = v end t.dumping_same_thread = (thread == coroutine.running()) -- if a thread was supplied, bind it to debug.info and debug.get -- we also need to skip this additional level we are introducing in the callstack (only if we are running -- in the same thread we're inspecting) if type(thread) == "thread" then t.getinfo = function(level, what) if t.dumping_same_thread and type(level) == "number" then level = level + 1 end return debug.getinfo(thread, level, what) end t.getlocal = function(level, loc) if t.dumping_same_thread then level = level + 1 end return debug.getlocal(thread, level, loc) end else t.getinfo = debug.getinfo t.getlocal = debug.getlocal end return t end -- helpers for collecting strings to be used when assembling the final trace function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table_concat(self.lines) end --- -- Private: -- Iterates over the local variables of a given function. -- -- @param level The stack level where the function is. -- function Dumper:DumpLocals (level) local prefix = "\t " local i = 1 if self.dumping_same_thread then level = level + 1 end local name, value = self.getlocal(level, i) if not name then return end self:add("\tLocal variables:\r\n") while name do if type(value) == "number" then self:add_f("%s%s = number: %g\r\n", prefix, name, value) elseif type(value) == "boolean" then self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) elseif type(value) == "string" then self:add_f("%s%s = string: %q\r\n", prefix, name, value) elseif type(value) == "userdata" then self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) elseif type(value) == "nil" then self:add_f("%s%s = nil\r\n", prefix, name) elseif type(value) == "table" then if m_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) elseif m_user_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) else local txt = "{" for k,v in pairs(value) do txt = txt..safe_tostring(k)..":"..safe_tostring(v) if #txt > _M.max_tb_output_len then txt = txt.." (more...)" break end if next(value, k) then txt = txt..", " end end self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") end elseif type(value) == "function" then local info = self.getinfo(value, "nS") local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] if info.what == "C" then self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) else local source = info.short_src if source:sub(2,7) == "string" then source = source:sub(9) -- uno más, por el espacio que viene (string "Baragent.Main", por ejemplo) end --for k,v in pairs(info) do print(k,v) end fun_name = fun_name or GuessFunctionName(info) self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) end elseif type(value) == "thread" then self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) end i = i + 1 name, value = self.getlocal(level, i) end end --- -- Public: -- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. -- This function is suitable to be used as an error handler with pcall or xpcall -- -- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) -- @param message An optional error string or object. -- @param level An optional number telling at which level to start the traceback (default is 1) -- -- Returns a string with the stack trace and a string with the original error. -- function _M.stacktrace(thread, message, level) if type(thread) ~= "thread" then -- shift parameters left thread, message, level = nil, thread, message end thread = thread or coroutine.running() level = level or 1 local dumper = Dumper.new(thread) local original_error if type(message) == "table" then dumper:add("an error object {\r\n") local first = true for k,v in pairs(message) do if first then dumper:add(" ") first = false else dumper:add(",\r\n ") end dumper:add(safe_tostring(k)) dumper:add(": ") dumper:add(safe_tostring(v)) end dumper:add("\r\n}") original_error = dumper:concat_lines() elseif type(message) == "string" then dumper:add(message) original_error = message end dumper:add("\r\n") dumper:add[[ Stack Traceback =============== ]] --print(error_message) local level_to_show = level if dumper.dumping_same_thread then level = level + 1 end local info = dumper.getinfo(level, "nSlf") while info do if info.what == "main" then if string_sub(info.source, 1, 1) == "@" then dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline) else dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline) end elseif info.what == "C" then --print(info.namewhat, info.name) --for k,v in pairs(info) do print(k,v, type(v)) end local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) elseif info.what == "tail" then --print("tail") --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) dumper:add_f("(%d) tail call\r\n", level_to_show) dumper:DumpLocals(level) elseif info.what == "Lua" then local source = info.short_src local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name if source:sub(2, 7) == "string" then source = source:sub(9) end local was_guessed = false if not function_name or function_name == "?" then --for k,v in pairs(info) do print(k,v, type(v)) end function_name = GuessFunctionName(info) was_guessed = true end -- test if we have a file name local function_type = (info.namewhat == "") and "function" or info.namewhat if info.source and info.source:sub(1, 1) == "@" then dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") elseif info.source and info.source:sub(1,1) == '#' then dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") else dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source) end dumper:DumpLocals(level) else dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) end level = level + 1 level_to_show = level_to_show + 1 info = dumper.getinfo(level, "nSlf") end return dumper:concat_lines(), original_error end -- -- Adds a table to the list of known tables function _M.add_known_table(tab, description) if m_known_tables[tab] then error("Cannot override an already known table") end m_user_known_tables[tab] = description end -- -- Adds a function to the list of known functions function _M.add_known_function(fun, description) if m_known_functions[fun] then error("Cannot override an already known function") end m_user_known_functions[fun] = description end return _M
apache-2.0
moltafet35/ssssis
plugins/service_entergroup.lua
355
3585
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nDescription :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nRules :\n"..rules.."\n" end local sambutan = "You are in group '"..string.gsub(msg.to.print_name, "_", " ").."'\n" local text = sambutan..about..rules.."\n" local text = text.."Please welcome "..nama local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Bye '..bye_name..'!' end end return { description = "Service plugin that sends a custom message when an user enters a chat.", usage = "Welcoming new member.", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-2.0
dxmgame/dxm-cocos-demo
src/lua-fantasy-warrior-3d/src/custom/api/JumpBy3D.lua
9
1552
-------------------------------- -- @module JumpBy3D -- @extend ActionInterval -- @parent_module cc -------------------------------- -- initializes the action -- @function [parent=#JumpBy3D] initWithDuration -- @param self -- @param #float duration -- @param #vec3_table position -- @param #float height -- @param #int jumps -- @return bool#bool ret (return value: bool) -------------------------------- -- creates the action -- @function [parent=#JumpBy3D] create -- @param self -- @param #float duration -- @param #vec3_table position -- @param #float height -- @param #int jumps -- @return JumpBy3D#JumpBy3D ret (return value: cc.JumpBy3D) -------------------------------- -- -- @function [parent=#JumpBy3D] startWithTarget -- @param self -- @param #cc.Node target -- @return JumpBy3D#JumpBy3D self (return value: cc.JumpBy3D) -------------------------------- -- -- @function [parent=#JumpBy3D] clone -- @param self -- @return JumpBy3D#JumpBy3D ret (return value: cc.JumpBy3D) -------------------------------- -- -- @function [parent=#JumpBy3D] reverse -- @param self -- @return JumpBy3D#JumpBy3D ret (return value: cc.JumpBy3D) -------------------------------- -- -- @function [parent=#JumpBy3D] update -- @param self -- @param #float time -- @return JumpBy3D#JumpBy3D self (return value: cc.JumpBy3D) -------------------------------- -- -- @function [parent=#JumpBy3D] JumpBy3D -- @param self -- @return JumpBy3D#JumpBy3D self (return value: cc.JumpBy3D) return nil
mit
stephank/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua
80
1455
--[[ Luci configuration model for statistics - collectd unixsock plugin configuration (c) 2008 Freifunk Leipzig / 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$ ]]-- m = Map("luci_statistics", translate("Unixsock Plugin Configuration"), translate( "The unixsock plugin creates a unix socket which can be used " .. "to read collected data from a running collectd instance." )) -- collectd_unixsock config section s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" ) -- collectd_unixsock.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_unixsock.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile" ) socketfile.default = "/var/run/collect-query.socket" socketfile:depends( "enable", 1 ) -- collectd_unixsock.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup" ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_unixsock.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms" ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) return m
apache-2.0
aqasaeed/signalbot
plugins/Robot.lua
292
1641
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Robot is Online' end _config.disabled_channels[receiver] = false save_config() return "Robot is Online" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Robot is Offline" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is moderator then re-enable the channel --if is_sudo(msg) then if is_momod(msg) then if msg.text == "[!/]bot on" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'on' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'off' then return disable_channel(receiver) end end return { description = "Robot Switch", usage = { "/bot on : enable robot in group", "/bot off : disable robot in group" }, patterns = { "^[!/]bot? (on)", "^[!/]bot? (off)" }, run = run, privileged = true, --moderated = true, pre_process = pre_process }
gpl-2.0
devlaith/DEVLAITH
plugins/inpm.lua
19
9514
local function pre_process(msg) local to = msg.to.type local service = msg.service if to == 'user' and msg.fwd_from then if not is_support(msg.from.id) and not is_admin1(msg) then return end local user = 'user#id'..msg.from.id local from_id = msg.fwd_from.peer_id if msg.fwd_from.first_name then from_first_name = msg.fwd_from.first_name:gsub("_", " ") else from_first_name = "None" end if msg.fwd_from.last_name then from_last_name = msg.fwd_from.last_name:gsub("_", " ") else from_last_name = "None" end if msg.fwd_from.username then from_username = "@"..msg.fwd_from.username else from_username = "@[none]" end text = "User From Info:\n\nID: "..from_id.."\nFirst: "..from_first_name.."\nLast: "..from_last_name.."\nUsername: "..from_username send_large_msg(user, text) end return msg end local function chat_list(msg) i = 1 local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use #join (ID) to join*\n\n' for k,v in pairsByKeys(data[tostring(groups)]) do local group_id = v if data[tostring(group_id)] then settings = data[tostring(group_id)]['settings'] end if settings then if not settings.public then public = 'no' else public = settings.public end end for m,n in pairsByKeys(settings) do --if m == 'public' then --public = n --end if public == 'no' then group_info = "" elseif m == 'set_name' and public == 'yes' then name = n:gsub("", "") chat_name = name:gsub("‮", "") group_name_id = name .. '\n(ID: ' ..group_id.. ')\n\n' if name:match("[\216-\219][\128-\191]") then group_info = i..' - \n'..group_name_id else group_info = i..' - '..group_name_id end i = i + 1 end end message = message..group_info end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end function super_help() local help_text = tostring(_config.help_text_super) return help_text end local function run(msg, matches) local to = msg.to.type local service = msg.service local name_log = user_print_name(msg.from) if to == 'user' or service or is_admin1(msg) and to == "chat" or to == "channel" then if is_gbanned(msg.from.id) then return 'You are globally banned.' end if matches[1] == 'join' then local data = load_data(_config.moderation.data) if matches[2]:lower() == 'english' and matches[3]:lower() == 'support' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to join English support") local target = 1041751030 local long_id = data[tostring(target)]['long_id'] if is_banned(msg.from.id, tostring(target)) then return 'You are banned.' end if data[tostring(target)]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, tostring(target)) then return 'Group is private.' end if is_admin1(msg) then user_type = 'admin' else user_type = "regular" end group_name = data[tostring(target)]['settings']['set_name'] local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) elseif matches[2]:lower() == 'persian' and matches[3]:lower() == 'support' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to join Persian support") local target = 1017700355 local long_id = data[tostring(target)]['long_id'] if is_banned(msg.from.id, tostring(target)) then return 'You are banned.' end if data[tostring(target)]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, '36088606') then return 'Group is private.' end if is_admin1(msg) then user_type = 'admin' else user_type = "regular" end group_name = data[tostring(target)]['settings']['set_name'] local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) elseif string.match(matches[2], '^%d+$') then local long_id = tostring(data[tostring(matches[2])]['long_id']) if not data[tostring(matches[2])] then return "Chat not found." end group_name = data[tostring(matches[2])]['settings']['set_name'] if is_admin1(msg) then user_type = 'admin' local receiver = get_receiver(msg) local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_set_admin(channel, user, ok_cb, false) end if is_support(msg.from.id) and not is_admin1(msg) and not is_owner2(msg.fom.id, matches[2]) then user_type = "support" local receiver = get_receiver(msg) local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_set_mod(channel, user, ok_cb, false) end if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end if not is_support(msg.from.id) and not is_admin1(msg) then user_type = "regular" local chat = long_id local channel = long_id local user = msg.from.peer_id chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) end end end end if msg.service and user_type == "support" and msg.action.type == "chat_add_user" and msg.from.id == 0 then local user_id = msg.action.user.id local user_name = msg.action.user.print_name local username = msg.action.user.username local group_name = string.gsub(msg.to.print_name, '_', ' ') savelog(msg.from.id, "Added Support member "..user_name.." to chat "..group_name.." (ID:"..msg.to.id..")") if username then send_large_msg("user#id"..user_id, "Added support member\n@"..username.."["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) else send_large_msg("user#id"..user_id, "Added support member\n["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) end end if msg.service and user_type == "admin" and msg.action.type == "chat_add_user" and msg.from.id == 0 then local user_id = msg.action.user.id local user_name = msg.action.user.print_name local username = msg.action.user.username savelog(msg.from.id, "Added Admin "..user_name.." "..user_id.." to chat "..group_name.." (ID:"..msg.to.id..")") if username then send_large_msg("user#id"..user_id, "Added admin\n@"..username.."["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) else send_large_msg("user#id"..user_id, "Added admin:\n["..user_id.."] to chat:\n 👥 "..group_name.." (ID:"..msg.to.id..")" ) end end if msg.service and user_type == "regular" and msg.action.type == "chat_add_user" and msg.from.id == 0 then local user_id = msg.action.user.id local user_name = msg.action.user.print_name print("Added "..user_id.." to chat "..msg.to.print_name.." (ID:"..msg.to.id..")") savelog(msg.from.id, "Added "..user_name.." to chat "..msg.to.print_name.." (ID:"..msg.to.id..")") send_large_msg("user#id"..user_id, "Added you to chat:\n\n"..group_name.." (ID:"..msg.to.id..")") end if matches[1] == 'helpp' and msg.to.type == 'user' or matches[1] == 'pmhelp' and is_admin1(msg) and msg.to.type ~= 'user' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] used pm help") text = "Welcome to TeleSeed!\n\nTo get a list of TeleSeed groups use /chats or /chatlist for a document list of chats.\n\nTo get a new TeleSeed group, contact a support group:\n\nFor English support, use: /join English support\n\nFor Persian support, use: /join Persian support\n\nFor more information, check out our channels:\n\n@TeleseedCH [English]\n@Iranseed [Persian]\n\nThanks for using @TeleSeed!" return text end if matches[1] == 'superhelp' and is_admin1(msg)then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() elseif matches[1] == 'superhelp' and to == "user" then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'chats' and is_admin1(msg)then return chat_list(msg) elseif matches[1] == 'chats' and to == 'user' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /chats") return chat_list(msg) end if matches[1] == 'chatlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /chatlist") if is_admin1(msg) and msg.to.type == 'chat' or msg.to.type == 'channel' then chat_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/listed_groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type == 'user' then chat_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end return { patterns = { "^[#!/](help)$", "^[#!/](pmhelp)$", "^[#!/](superhelp)$", "^[#!/](chats)$", "^[#!/](chatlist)$", "^[#!/](join) (%d+)$", "^[#!/](join) (.*) (support)$", "^[#!/](kickme) (.*)$", "^!!tgservice (chat_add_user)$", }, run = run, pre_process = pre_process }
gpl-2.0
Daniex0r/project-roleplay-rp
resources/system-prac/c_job_framework.lua
1
1375
job = 0 localPlayer = getLocalPlayer() function playerSpawn() local logged = getElementData(localPlayer, "loggedin") if (logged==1) then job = tonumber(getElementData(localPlayer, "job")) if (job==1) then -- TRUCKER displayTruckerJob() else resetTruckerJob() end if (job==2) then -- TAXI displayTaxiJob() else resetTaxiJob() end if (job==3) then -- BUS displayBusJob() else resetBusJob() end end end addEventHandler("onClientPlayerSpawn", localPlayer, function() setTimer(playerSpawn, 1000, 1) end ) function quitJob(job) if (job==1) then -- TRUCKER JOB resetTruckerJob() outputChatBox("Zwolniłeś sie.", 0, 255, 0) elseif (job==2) then -- TAXI JOB resetTaxiJob() outputChatBox("Zwolniłeś sie.", 0, 255, 0) elseif (job==3) then -- BUS JOB resetBusJob() outputChatBox("Możesz sie już zwolnić.", 0, 255, 0) elseif (job==4) then -- CITY MAINTENANCE outputChatBox("Zwolniłeś sie.", 0, 255, 0) triggerServerEvent("cancelCityMaintenance", localPlayer) elseif (job==5) then -- MECHANIC outputChatBox("Zwolniłeś sie.", 0, 255, 0) elseif (job==6) then -- LOCKSMITH outputChatBox("Zwolniłeś sie.", 0, 255, 0) end end addEvent("quitJob", true) addEventHandler("quitJob", getLocalPlayer(), quitJob) fileDelete("c_job_framework.lua")
gpl-2.0
marshmellow42/proxmark3
client/lualibs/default_toys.lua
10
19294
local _names = { --[[ decimal, hexadecimal, ccc, elements, group, name --]] {"0", "0000", "0030", "air", "regular", "Whirlwind"}, --{"0", "0000", "0030", "air", "regular", "Elite Whirlwind"}, --{"0", "0000", "0030", "air", "regular", "Polar Whirlwind"}, {"1", "0100", "0030", "air", "regular", "Sonic Boom"}, {"2", "0200", "0030", "air", "regular", "Warnado"}, {"3", "0300", "0030", "air", "regular", "Lightning Rod"}, {"4", "0400", "0030", "earth", "regular", "Bash"}, --{"4", "0400", "0030", "earth", "regular", "Birthday Bash"}, {"5", "0500", "0030", "earth", "regular", "Terrafin"}, --{"5", "0500", "0030", "earth", "regular", "Elite Terrafin"}, {"6", "0600", "0030", "earth", "regular", "Dino Rang"}, {"7", "0700", "0030", "earth", "regular", "Prism Break"}, --lightcore {"8", "0800", "0030", "fire", "regular", "Sunburn"}, {"9", "0900", "0030", "fire", "regular", "Eruptor"}, --lightcore --{"9", "0900", "0030", "fire", "regular", "Elite Eruptor"}, --{"9", "0900", "0030", "fire", "regular", "Volcanic Eruptor"}, {"10", "0a00", "0030", "fire", "regular", "Ignitor"}, {"11", "0b00", "0030", "fire", "regular", "Flameslinger"}, --{"11", "0b00", "0030", "fire", "regular", "Cupid Flameslinger"}, {"12", "0c00", "0030", "water", "regular", "Zap"}, {"13", "0d00", "0030", "water", "regular", "Wham Shell"}, {"14", "0e00", "0030", "water", "regular", "Gill Grunt"}, --{"14", "0e00", "0030", "water", "regular", "Elite Gill Grunt"}, --{"14", "0e00", "0030", "water", "regular", "Tidal Wave Gill Grunt"}, {"15", "0f00", "0030", "water", "regular", "Slam Bam"}, --{"15", "0f00", "0030", "water", "regular", "Surfer Slam Bam"}, {"16", "1000", "0030", "magic", "regular", "Spyro"}, {"17", "1100", "0030", "magic", "regular", "Voodood"}, {"18", "1200", "0030", "magic", "regular", "Double Trouble"}, --{"18", "1200", "0030", "magic", "regular", "Royal Double Trouble"}, {"19", "1300", "0030", "tech", "regular", "Trigger Happy"}, --{"19", "1300", "0030", "tech", "regular", "Elite Trigger Happy"}, --{"19", "1300", "0030", "tech", "regular", "Springtime Trigger Happy"}, {"20", "1400", "0030", "tech", "regular", "Drobot"}, {"21", "1500", "0030", "tech", "regular", "Drill Sergeant"}, {"22", "1600", "0030", "tech", "regular", "Boomer"}, --{"22", "1600", "0030", "tech", "regular", "Lucky Boomer"}, {"23", "1700", "0030", "magic", "regular", "Wrecking Ball"}, --{"23", "1700", "0030", "magic", "regular", "Buddy Wrecking Ball"}, {"24", "1800", "0030", "life", "regular", "Camo"}, {"25", "1900", "0030", "life", "regular", "Zook"}, {"26", "1a00", "0030", "life", "regular", "Stealth Elf"}, --{"26", "1a00", "0030", "life", "regular", "Elite Stealth Elf"}, --{"26", "1a00", "0528", "life", "regular", "Dark Stealth Elf"}, {"26", "1a00", "0528", "life", "swapforce", "Ninja Stealth Elf"}, {"27", "1b00", "0030", "life", "regular", "Stump Smash"}, {"27", "1b00", "0118", "life", "regular", "Stump Smash"}, --{"27", "1b00", "0030", "life", "regular", "Autumn Stump Smash"}, {"28", "1c00", "0030", "magic", "regular", "Dark Spyro"}, --{"28", "1c00", "0030", "magic", "regular", "Elite Spyro"}, {"29", "1d00", "0030", "undead", "regular", "Hex"}, --{"29", "1d00", "0030", "undead", "regular", "Hallows' Eve Hex"}, {"30", "1e00", "0030", "undead", "regular", "Chop Chop"}, --{"30", "1e00", "0030", "undead", "regular", "Elite Chop Chop"}, --{"30", "1e00", "0030", "undead", "regular", "Grill Master Chop Chop"}, {"31", "1f00", "0030", "undead", "regular", "Ghost Roaster"}, {"32", "2000", "0030", "undead", "regular", "Cynder"}, --{"32", "2000", "0030", "undead", "regular", "Skeletal Cynder"}, {"100", "6400", "0030", "air", "giant", "Jet Vac"}, --{"100", "6400", "0030", "air", "giant", "Full blast Jet Vac"}, {"101", "6500", "0030", "air", "giant", "Swarm"}, {"102", "6600", "0030", "earth", "giant", "Crusher"}, {"103", "6700", "0030", "earth", "giant", "Flashwing"}, --{"103", "6700", "0030", "earth", "giant", "Jade Flashwing"}, {"104", "6800", "0030", "fire", "giant", "Hot Head"}, {"105", "6900", "0030", "fire", "giant", "Hot Dog"}, --{"105", "6900", "0030", "fire", "giant", "Molten Hot Dog"}, {"106", "6a00", "0030", "water", "giant", "Chill"}, {"107", "6b00", "0030", "water", "giant", "Thumpback"}, --{"107", "6b00", "0030", "water", "giant", "Admiral Thumpback"}, {"108", "6c00", "0030", "magic", "giant", "Pop Fizz"}, --{"108", "6c00", "0030", "magic", "giant", "Hoppity Pop Fizz"}, {"108", "6c00", "023c", "magic", "giant", "Love Potion Pop Fizz"}, --{"108", "6c00", "0030", "magic", "giant", "Punch Pop Fizz"}, --{"108", "6c00", "0030", "magic", "giant", "Fizzy Frenzy Pop Fizz"}, {"109", "6d00", "0030", "magic", "giant", "Nin Jini"}, {"110", "6e00", "0030", "tech", "giant", "Bouncer"}, {"111", "6f00", "0030", "tech", "giant", "Sprocket"}, {"112", "7000", "0030", "life", "giant", "Tree Rex"}, --{"112", "7000", "0030", "life", "giant", "Gnarly Tree Rex"}, {"113", "7100", "0030", "life", "giant", "Shroomboom"}, --{"113", "7100", "0030", "life", "giant", "Sure shot Shroomboom"}, {"114", "7200", "0030", "undead", "giant", "Eye Broawl"}, {"115", "7300", "0030", "undead", "giant", "Fright Rider"}, {"200", "c800", "0030", "", "item", "Anvil Rain"}, {"201", "c900", "0030", "", "item", "Platinum Treasure Chest"}, {"202", "ca00", "0030", "", "item", "Healing Elixer"}, {"203", "cb00", "0030", "", "item", "Ghost Pirate Swords"}, {"204", "cc00", "0030", "", "item", "Time Twist Hourglass"}, {"205", "cd00", "0030", "", "item", "Sky Iron Shield"}, {"206", "ce00", "0030", "", "item", "Winged Boots"}, {"207", "cf00", "0030", "", "item", "Sparx"}, {"208", "d000", "0030", "", "item", "Cannon"}, {"209", "d100", "0030", "", "item", "Scorpion Striker"}, {"210", "d200", "0230", "magic", "trap", "Biter's Bane"}, {"210", "d200", "0830", "magic", "trap", "Sorcerous Skull"}, -- legendary Sorcerous Skull? {"210", "d200", "0b30", "magic", "trap", "Axe Of Illusion"}, {"210", "d200", "0e30", "magic", "trap", "Arcane Hourglass"}, {"210", "d200", "1230", "magic", "trap", "Spell Slapper"}, {"210", "d200", "1430", "magic", "trap", "Rune Rocket"}, {"211", "d300", "0130", "water", "trap", "Tidal Tiki"}, {"211", "d300", "0230", "water", "trap", "Wet Walter"}, {"211", "d300", "0630", "water", "trap", "Flood Flask"}, -- legendary flood flask? {"211", "d300", "0730", "water", "trap", "Soaking Staff"}, {"211", "d300", "0b30", "water", "trap", "Aqua Axe"}, {"211", "d300", "1630", "water", "trap", "Frost Helm"}, {"212", "d400", "0330", "air", "trap", "Breezy Bird"}, {"212", "d400", "0630", "air", "trap", "Drafty Decanter"}, {"212", "d400", "0d30", "air", "trap", "Tempest Timer"}, {"212", "d400", "1030", "air", "trap", "Cloudy Cobra"}, {"212", "d400", "1130", "air", "trap", "Storm Warning"}, {"212", "d400", "1830", "air", "trap", "Cycone Saber"}, {"213", "d500", "0430", "undead", "trap", "Spirit Sphere"}, {"213", "d500", "0830", "undead", "trap", "Spectral Skull"}, {"213", "d500", "0b30", "undead", "trap", "Haunted Hatchet"}, {"213", "d500", "0c30", "undead", "trap", "Grim Gripper"}, {"213", "d500", "1030", "undead", "trap", "Spooky Snake"}, {"213", "d500", "1730", "undead", "trap", "Dream Piercer"}, {"214", "d600", "0030", "tech", "trap", "tech Totem"}, {"214", "d600", "0730", "tech", "trap", "Automatic Angel"}, {"214", "d600", "0930", "tech", "trap", "Factory Flower"}, {"214", "d600", "0c30", "tech", "trap", "Grabbing Gadget"}, {"214", "d600", "1630", "tech", "trap", "Makers Mana"}, {"214", "d600", "1a30", "tech", "trap", "Topsy techy"}, {"215", "d700", "0530", "fire", "trap", "Eternal Flame"}, {"215", "d700", "0930", "fire", "trap", "fire Flower"}, {"215", "d700", "1130", "fire", "trap", "Scorching Stopper"}, {"215", "d700", "1230", "fire", "trap", "Searing Spinner"}, {"215", "d700", "1730", "fire", "trap", "Spark Spear"}, {"215", "d700", "1b30", "fire", "trap", "Blazing Belch"}, {"216", "d800", "0030", "earth", "trap", "Banded Boulder"}, {"216", "d800", "0330", "earth", "trap", "Rock Hawk"}, {"216", "d800", "0a30", "earth", "trap", "Slag Hammer"}, {"216", "d800", "0e30", "earth", "trap", "Dust Of Time"}, {"216", "d800", "1330", "earth", "trap", "Spinning Sandstorm"}, {"216", "d800", "1a30", "earth", "trap", "Rubble Trouble"}, {"217", "d900", "0330", "life", "trap", "Oak Eagle"}, {"217", "d900", "0530", "life", "trap", "Emerald Energy"}, {"217", "d900", "0a30", "life", "trap", "Weed Whacker"}, {"217", "d900", "1030", "life", "trap", "Seed Serpent"}, {"217", "d900", "1830", "life", "trap", "Jade Blade"}, {"217", "d900", "1b30", "life", "trap", "Shrub Shrieker"}, {"218", "da00", "0030", "dark", "trap", "dark Dagger"}, {"218", "da00", "1430", "dark", "trap", "Shadow Spider"}, {"218", "da00", "1a30", "dark", "trap", "Ghastly Grimace"}, {"219", "db00", "0030", "light", "trap", "Shining Ship"}, {"219", "db00", "0f30", "light", "trap", "Heavenly Hawk"}, {"219", "db00", "1b30", "light", "trap", "Beam Scream"}, {"220", "dc00", "3030", "kaos", "trap", "Kaos trap!"}, --{"220", "dc00", "3130", "kaos", "trap", "Ultimate Kaos trap!"}, ? {"230", "e600", "0030", "none", "item", "Hand Of Fate"}, {"231", "e700", "0030", "none", "item", "Piggy Bank"}, {"232", "e800", "0030", "none", "item", "Rocket Ram"}, {"233", "e900", "0030", "none", "item", "Tiki Speaky"}, {"300", "2c01", "0030", "none", "location", "Dragons Peak"}, {"301", "2d01", "0030", "none", "location", "Empire Of Ice"}, {"302", "2e01", "0030", "none", "location", "Pirate Seas"}, {"303", "2f01", "0030", "none", "location", "darklight Crypt"}, {"304", "3001", "0030", "none", "location", "Volcanic Vault"}, {"305", "3101", "0030", "none", "location", "Mirror Of Mystery"}, {"306", "3201", "0030", "none", "location", "Nightmare Express"}, {"307", "3301", "0030", "light", "location", "Sunscraper Spire"}, {"308", "3401", "0030", "dark", "location", "Midnight Museum"}, {"404", "9401", "0030", "earth", "legendary","Bash"}, {"416", "a001", "0030", "magic", "legendary", "Spyro"}, --{"", "", "0030", "magic", "legendary", "Deja Vu"}, {"419", "a301", "0030", "tech", "legendary", "Trigger Happy"}, --{"", "", "0030", "tech", "legendary", "bouncer"}, --{"", "", "0030", "tech", "legendary", "jawbreaker"}, {"430", "ae01", "0030", "undead", "legendary", "Chop Chop"}, --{"", "", "0030", "undead", "legendary", "grim creeper"}, --{"", "", "0030", "undead", "legendary", "night shift"}, --{"", "", "0030", "air", "legendary", "blades"}, --{"", "", "0030", "air", "legendary", "jet vac"}, --{"", "", "0030", "air", "legendary", "Free Ranger"}, --{"", "", "0030", "life", "legendary", "stealth elf"}, --{"", "", "0030", "life", "legendary", "Bushwhack"}, --{"", "", "0030", "fire", "legendary", "ignitor"}, --{"", "", "0030", "water", "legendary", "slam bam"}, --{"", "", "0030", "water", "legendary", "chill"}, --{"", "", "0030", "", "legendary", "zoo lou"}, {"450", "c201", "0030", "air", "trapmaster", "Gusto"}, --{"450", "c201", "0234", "air", "trapmaster", "Special Gusto"}, {"451", "c301", "0030", "air", "trapmaster", "Thunderbolt"}, --{"451", "c301", "0234", "air", "trapmaster", "Special Thunderbolt"}, {"452", "c401", "0030", "air", "regular", "Fling Kong"}, {"453", "c501", "0030", "air", "regular", "Blades"}, {"454", "c601", "0030", "earth", "trapmaster", "Wallop"}, --{"454", "c601", "0234", "earth", "trapmaster", "Special Wallop"}, {"455", "c701", "0030", "earth", "trapmaster", "Head Rush"}, {"455", "c701", "0234", "earth", "trapmaster", "Nitro Head Rush"}, {"456", "c801", "0030", "earth", "regular", "Fist Bump"}, {"457", "c901", "0030", "earth", "regular", "Rocky Roll"}, --{"457", "c901", "0030", "earth", "regular", "Rocky Egg Roll"}, {"458", "ca01", "0030", "fire", "trapmaster", "Wildfire"}, {"458", "ca01", "0234", "fire", "trapmaster", "Dark Wildfire"}, {"459", "cb01", "0030", "fire", "trapmaster", "Ka Boom"}, --{"459", "cb01", "0234", "fire", "trapmaster", "Special Ka Boom"}, {"460", "cc01", "0030", "fire", "regular", "Trail Blazer"}, {"461", "cd01", "0030", "fire", "regular", "Torch"}, {"462", "ce01", "0030", "water", "trapmaster", "Snap Shot"}, {"462", "ce01", "0234", "water", "trapmaster", "Dark Snap Shot"}, {"462", "6c00", "023c", "water", "trapmaster", "Instant Snap Shot"}, --, "water", "trapmaster", "Merry Snap Shot"}, {"463", "cf01", "0030", "water", "trapmaster", "Lob Star"}, {"463", "cf01", "0234", "water", "trapmaster", "Winterfest Lob Star"}, {"464", "d001", "0030", "water", "regular", "Flip Wreck"}, {"465", "d101", "0030", "water", "regular", "Echo"}, {"466", "d201", "0030", "magic", "trapmaster", "Blastermind"}, --{"466", "d201", "0234", "magic", "trapmaster", "Special Blastermind"}, {"467", "d301", "0030", "magic", "trapmaster", "Enigma"}, --{"467", "d301", "0234", "magic", "trapmaster", "Special Enigma"}, {"468", "d401", "0030", "magic", "regular", "Deja Vu"}, {"469", "d501", "0030", "magic", "regular", "Cobra Cadabra"}, --{"469", "d501", "0030", "magic", "regular", "Charming Cobra Cadabra"}, --{"469", "d501", "0030", "magic", "regular", "King Cobra Cadabra"}, {"470", "d601", "0030", "tech", "trapmaster", "Jawbreaker"}, --{"470", "d601", "0234", "tech", "trapmaster", "Special Jawbreaker"}, --{"470", "d601", "0234", "tech", "trapmaster", "Knockout Jawbreaker"}, {"471", "d701", "0030", "tech", "trapmaster", "Gearshift"}, --{"471", "d701", "0234", "tech", "trapmaster", "Special Gearshift"}, {"472", "d801", "0030", "tech", "regular", "Chopper"}, {"473", "d901", "0030", "tech", "regular", "Tread Head"}, {"474", "da01", "0030", "life", "trapmaster", "Bushwhack"}, --{"474", "da01", "0234", "life", "trapmaster", "Special Bushwhack"}, {"475", "db01", "0030", "life", "trapmaster", "Tuff Luck"}, --{"475", "db01", "0234", "life", "trapmaster", "Special Tuff Luck"}, {"476", "dc01", "0030", "life", "regular", "Food Fight"}, {"476", "dc01", "0612", "life", "regular", "LightCore Food Fight"}, --{"476", "dc01", "0030", "life", "regular", "Dark Food Fight"}, --{"476", "dc01", "0030", "life", "regular", "Frosted Food Fight"}, --{"476", "dc01", "0030", "life", "regular", "Instant Food Fight"}, {"477", "dd01", "0030", "life", "regular", "High Five"}, {"478", "de01", "0030", "undead", "trapmaster", "Krypt King"}, {"478", "de01", "0234", "undead", "trapmaster", "Nitro Krypt King"}, {"479", "df01", "0030", "undead", "trapmaster", "Short Cut"}, --{"479", "df01", "0234", "undead", "trapmaster", "Special Short Cut"}, {"480", "e001", "0030", "undead", "regular", "Bat Spin"}, {"481", "e101", "0030", "undead", "regular", "Funny Bone"}, {"481", "e101", "0612", "undead", "regular", "LightCore Funny Bone"}, --{"481", "e101", "0030", "undead", "regular", "Fortune Funny Bone"}, {"482", "e201", "0030", "light", "trapmaster", "Knight light"}, --{"482", "e201", "0234", "light", "trapmaster", "Special Knight light"}, {"483", "e301", "0030", "light", "regular", "Spotlight"}, --{"483", "e301", "0234", "light", "regular", "Special Spotlight"}, {"484", "e401", "0030", "dark", "trapmaster", "Knight Mare"}, --{"484", "e401", "0234", "dark", "trapmaster", "Special Knight Mare"}, {"485", "e501", "0030", "dark", "regular", "Blackout"}, --{"485", "e501", "0234", "dark", "regular", "Special Blackout"}, -- MINI's {"502", "f601", "0030", "earth", "mini", "Bop"}, {"505", "f901", "0030", "earth", "mini", "Terrabite"}, {"506", "fa01", "0030", "air", "mini", "Breeze"}, {"508", "fc01", "0030", "air", "mini", "Pet Vac"}, --{"508", "fc01", "0030", "air", "mini", "Power Punch Pet Vac"}, {"507", "fb01", "0030", "fire", "mini", "Weeruptor"}, --{"507", "fb01", "0030", "fire", "mini", "Eggsellent Weeruptor"}, {"509", "fd01", "0030", "fire", "mini", "Small Fry"}, {"510", "fe01", "0030", "tech", "mini", "Drobit"}, {"519", "0702", "0030", "tech", "mini", "Trigger Snappy"}, {"526", "0e02", "0030", "life", "mini", "Whisper Elf"}, {"540", "1c02", "0030", "life", "mini", "Barkley"}, --{"540", "1c02", "0030", "life", "mini", "Gnarly Barkley"}, {"541", "1d02", "0030", "water", "mini", "Thumpling"}, {"514", "0202", "0030", "water", "mini", "Gill Runt"}, {"542", "1e02", "0030", "magic", "mini", "mini Jini"}, {"503", "f701", "0030", "magic", "mini", "Spry"}, {"504", "f801", "0030", "undead", "mini", "Hijinx"}, {"543", "1f02", "0030", "undead", "mini", "Eye Small"}, {"3000", "b80b", "0030", "air", "mini", "Scratch", "SWAPFORCE"}, {"3001", "b90b", "0030", "air", "SWAPFORCE", "Pop Thorn"}, --{"3001", "b90b", "0030", "air", "SWAPFORCE", "Buttered Pop Thorn"}, {"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Slobber Tooth"}, --{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Dark Slobber Tooth"}, --{"3002", "ba0b", "0030", "earth", "SWAPFORCE", "Sundae Slobber Tooth"}, {"3003", "bb0b", "0030", "earth", "SWAPFORCE", "Scorp"}, {"3004", "bc0b", "0030", "fire", "SWAPFORCE", "Fryno"}, {"3004", "bc0b", "0138", "fire", "SWAPFORCE", "Hog Wild Fryno"}, --{"3004", "bc0b", "0138", "fire", "SWAPFORCE", "Flip flop Fryno"}, {"3005", "bd0b", "0030", "fire", "SWAPFORCE", "Smolderdash"}, {"3006", "be0b", "0030", "life", "SWAPFORCE", "Bumble Blast"}, --{"3006", "be0b", "0030", "life", "SWAPFORCE", "Jolly Bumble Blast"}, {"3007", "bf0b", "0030", "life", "SWAPFORCE", "Zoo Lou"}, {"3008", "c00b", "0030", "magic", "SWAPFORCE", "Dune Bug"}, {"3009", "c10b", "0030", "magic", "SWAPFORCE", "Star Strike"}, --{"3009", "c10b", "0030", "magic", "SWAPFORCE", "Enchanted Star Strike"}, --{"3009", "c10b", "0030", "magic", "SWAPFORCE", "Mystic Star Strike"}, {"3010", "c20b", "0030", "tech", "SWAPFORCE", "Countdown"}, --{"3010", "c20b", "0030", "tech", "SWAPFORCE", "Kickoff Countdown"}, --{"3010", "c20b", "0030", "tech", "SWAPFORCE", "New Year's Countdown"}, {"3011", "c30b", "0030", "tech", "SWAPFORCE", "Wind Up"}, {"3012", "c40b", "0030", "undead", "SWAPFORCE", "Roller Brawl"}, --{"3012", "c40b", "0030", "undead", "SWAPFORCE", "Snowler Roller Brawl"}, {"3013", "c50b", "0030", "undead", "SWAPFORCE", "Grim Creeper"}, {"3014", "c60b", "0030", "water", "SWAPFORCE", "Rip Tide"}, {"3015", "c70b", "0030", "water", "SWAPFORCE", "Punk Shock"}, --{"", "", "0030", "water", "SWAPFORCE", "Hoot Loop"}, --{"", "", "0030", "water", "SWAPFORCE", "Trap Shadow"}, --{"", "", "0030", "water", "SWAPFORCE", "Wash Buckler"}, --{"", "", "0030", "water", "SWAPFORCE", "Freeze Blade"}, --{"", "", "0030", "fire", "SWAPFORCE", "Magna Charge"}, --{"", "", "0030", "fire", "SWAPFORCE", "Spy Rise"}, --{"", "", "0030", "fire", "SWAPFORCE", "Doom Stone"}, --{"", "", "0030", "fire", "SWAPFORCE", "Rubble Rouser"}, --{"", "", "0030", "fire", "SWAPFORCE", "Blast Zone"} --{"", "", "0030", "fire", "SWAPFORCE", "Fire Kraken"}, --{"", "", "0030", "fire", "SWAPFORCE", "Rattle Shake"}, --{"", "", "0030", "fire", "SWAPFORCE", "Night Shift"}, --{"", "", "0030", "life", "SWAPFORCE", "Stink Bomb"}, --{"", "", "0030", "life", "SWAPFORCE", "Grilla Drilla"}, --{"", "", "0030", "air", "SWAPFORCE", "Free Ranger"}, --{"", "", "0030", "air", "SWAPFORCE", "Boom Jet"}, } local function find( main, sub) main = main:lower() sub = sub:lower() for k, v in pairs(_names) do if ( v[2]:lower() == main and v[3]:lower() == sub) then return v end end return nil end local function list() print ("Type\tSub\tElement\tGame Name") print (string.rep('=', 54)) for k, v in pairs(_names) do print(("%s\t%s\t%s\t%-9s\t%s"):format(v[2],v[3],v[4], v[5], v[6] )) end end return { Find = find, List = list, }
gpl-2.0
5620g/pp
plugins/arabic_lock.lua
234
1405
antiarabic = {}-- An empty table for solving multiple kicking problem do local function run(msg, matches) if is_momod(msg) then -- Ignore mods,owner,admins return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_arabic'] then if data[tostring(msg.to.id)]['settings']['lock_arabic'] == 'yes' then if is_whitelisted(msg.from.id) then return end if antiarabic[msg.from.id] == true then return end if msg.to.type == 'chat' then local receiver = get_receiver(msg) local username = msg.from.username local name = msg.from.first_name if username and is_super_group(msg) then send_large_msg(receiver , "Arabic/Persian is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") else send_large_msg(receiver , "Arabic/Persian is not allowed here\nName: "..name.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (arabic was locked) ") local chat_id = msg.to.id local user_id = msg.from.id kick_user(user_id, chat_id) end antiarabic[msg.from.id] = true end end return end local function cron() antiarabic = {} -- Clear antiarabic table end return { patterns = { "([\216-\219][\128-\191])" }, run = run, cron = cron } end
gpl-2.0
dmccuskey/dmc-wamp
dmc_corona_boot.lua
47
15406
--====================================================================-- -- dmc_corona_boot.lua -- -- utility to read in configuration file for dmc-corona-library -- -- Documentation: --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2013-2015 David McCuskey. All Rights Reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]] --====================================================================-- --== DMC Corona Library : DMC Corona Boot --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "1.5.2" --====================================================================-- --== Imports local has_json, json = pcall( require, 'json' ) if not has_json then json = nil end --====================================================================-- --== Setup, Constants local sfind = string.find local sgmatch = string.gmatch local sgsub = string.gsub local tconcat = table.concat local tinsert = table.insert local tremove = table.remove --====================================================================-- --== Setup Support --====================================================================-- local Utils = {} -- make copying from dmc_utils easier function Utils.extend( fromTable, toTable ) function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end -- split string up in parts, using separator -- returns array of pieces function Utils.split( str, sep ) if sep == nil then sep = "%s" end local t, i = {}, 1 for str in string.gmatch( str, "([^"..sep.."]+)") do t[i] = str i = i + 1 end return t end function Utils.propertyIn( list, property ) for i = 1, #list do if list[i] == property then return true end end return false end function Utils.guessPathPlatform( path ) -- print( "Utils.guessPathPlatform", path ) local win, ios = 0, 0 for match in sgmatch( path, '\\' ) do win=win+1 end for match in sgmatch( path, '/' ) do ios=ios+1 end if win>ios then return '\\' else return '/' end end -- takes System Path to Lua module dot -- eg, lib.dmc_lua.lua_object >> lib/dmc_lua/lua_object -- function Utils.sysPathToRequirePath( sys_path ) -- print( "sysPathToRequirePath", sys_path ) local sys_tbl = Utils.split( sys_path, Utils.guessPathPlatform( sys_path ) ) -- clean off any dots for i=#sys_tbl, 1, -1 do if sys_tbl[i]=='.' then tremove( sys_tbl, i ) end end return tconcat( sys_tbl, '.' ) end --== Start lua_files copies ==-- -- version 0.2.0 local File = {} --======================================================-- -- fileExists() function File.fileExists( file_path ) -- print( "File.fileExists", file_path ) local has_file, _ = pcall( function() local result = assert( io.open( file_path, 'r' ) ) io.close( result ) end) return has_file end --====================================================================-- --== readFile() ==-- function File._openCloseFile( file_path, read_f, options ) -- print( "File.readFile", file_path ) assert( type(file_path)=='string', "file path is not string" ) assert( type(read_f)=='function', "read function is not function" ) --==-- local fh = assert( io.open(file_path, 'r') ) local contents = read_f( fh ) io.close( fh ) return contents end function File._readLines( fh ) local contents = {} for line in fh:lines() do tinsert( contents, line ) end return contents end function File.readFileLines( file_path, options ) return File._openCloseFile( file_path, File._readLines, options ) end function File._readContents( fh ) return fh:read( '*all' ) end function File.readFileContents( file_path, options ) return File._openCloseFile( file_path, File._readContents, options ) end function File.readFile( file_path, options ) options = options or {} options.lines = options.lines == nil and true or options.lines --==-- if options.lines == true then return File.readFileLines( file_path, options ) else return File.readFileContents( file_path, options ) end end --====================================================================-- --== read/write JSONFile() ==-- function File.convertJsonToLua( json_str ) assert( json ~= nil, 'JSON library not loaded' ) assert( type(json_str)=='string' ) assert( #json_str > 0 ) --==-- local data = json.decode( json_str ) assert( data~=nil, "Error reading JSON file, probably malformed data" ) return data end --====================================================================-- --== readConfigFile() ==-- -- types of possible keys for a line local KEY_TYPES = { 'boolean', 'bool', 'file', 'integer', 'int', 'json', 'path', 'string', 'str' } function File.getLineType( line ) -- print( "File.getLineType", #line, line ) assert( type(line)=='string' ) --==-- local is_section, is_key = false, false if #line > 0 then is_section = ( string.find( line, '%[%u', 1, false ) == 1 ) is_key = ( string.find( line, '%u', 1, false ) == 1 ) end return is_section, is_key end function File.processSectionLine( line ) -- print( "File.processSectionLine", line ) assert( type(line)=='string', "expected string as parameter" ) assert( #line > 0 ) --==-- local key = line:match( "%[([%u_]+)%]" ) assert( type(key) ~= 'nil', "key not found in line: "..tostring(line) ) return string.lower( key ) -- use only lowercase inside of module end function File.processKeyLine( line ) -- print( "File.processKeyLine", line ) assert( type(line)=='string', "expected string as parameter" ) assert( #line > 0 ) --==-- -- split up line into key/value local raw_key, raw_val = line:match( "([%u_:]+)%s*=%s*(.-)%s*$" ) -- split up key parts local keys = {} for k in string.gmatch( raw_key, "([^:]+)") do tinsert( keys, #keys+1, k ) end -- trim off quotes, make sure balanced local q1, q2, trim q1, trim, q2 = raw_val:match( "^(['\"]?)(.-)(['\"]?)$" ) assert( q1 == q2, "quotes must match" ) -- process key and value local key_name, key_type = unpack( keys ) key_name = File.processKeyName( key_name ) key_type = File.processKeyType( key_type ) -- get final value local key_value if key_type and Utils.propertyIn( KEY_TYPES, key_type ) then local method = 'castTo_'..key_type key_value = File[method]( trim ) else key_value = File.castTo_string( trim ) end return key_name, key_value end function File.processKeyName( name ) -- print( "File.processKeyName", name ) assert( type(name)=='string', "expected string as parameter" ) assert( #name > 0, "no length for name" ) --==-- return string.lower( name ) -- use only lowercase inside of module end -- allows nil to be passed in function File.processKeyType( name ) -- print( "File.processKeyType", name ) --==-- if type(name)=='string' then name = string.lower( name ) -- use only lowercase inside of module end return name end function File.castTo_boolean( value ) assert( type(value)=='string' ) --==-- if value == 'true' then return true else return false end end File.castTo_bool = File.castTo_boolean function File.castTo_file( value ) return File.castTo_string( value ) end function File.castTo_integer( value ) assert( type(value)=='string' ) --==-- local num = tonumber( value ) assert( type(num) == 'number' ) return num end File.castTo_int = File.castTo_integer function File.castTo_json( value ) assert( type(value)=='string' ) --==-- return File.convertJsonToLua( value ) end function File.castTo_path( value ) assert( type(value)=='string' ) --==-- return string.gsub( value, '[/\\]', "." ) end function File.castTo_string( value ) assert( type(value)~='nil' and type(value)~='table' ) return tostring( value ) end File.castTo_str = File.castTo_string function File.parseFileLines( lines, options ) -- print( "parseFileLines", #lines ) assert( options, "options parameter expected" ) assert( options.default_section, "options table requires 'default_section' entry" ) --==-- local curr_section = options.default_section local config_data = {} config_data[ curr_section ]={} for _, line in ipairs( lines ) do local is_section, is_key = File.getLineType( line ) -- print( line, is_section, is_key ) if is_section then curr_section = File.processSectionLine( line ) if not config_data[ curr_section ] then config_data[ curr_section ]={} end elseif is_key then local key, val = File.processKeyLine( line ) config_data[ curr_section ][key] = val end end return config_data end -- @param file_path string full path to file -- function File.readConfigFile( file_path, options ) -- print( "File.readConfigFile", file_path ) options = options or {} options.default_section = options.default_section or File.DEFAULT_CONFIG_SECTION --==-- return File.parseFileLines( File.readFileLines( file_path ), options ) end --== End lua_files copies ==-- --====================================================================-- --== Setup DMC Corona Library Config --====================================================================-- --[[ This is standard code to bootstrap the dmc-corona-library it looks for a configuration file to read --]] local DMC_CORONA_CONFIG_FILE = 'dmc_corona.cfg' local DMC_CORONA_DEFAULT_SECTION = 'dmc_corona' -- locations of third party libs used by dmc_corona local THIRD_LIBS = {} --- add 'lib/dmc' location tinsert( THIRD_LIBS, tconcat( {'lib','dmc_lua'}, '.' ) ) local REQ_STACK = {} local function pushStack( value ) -- print( "pre stack (pre):", #REQ_STACK) tinsert( REQ_STACK, value ) end local function popStack() -- print( "pop stack (pre):", #REQ_STACK) if REQ_STACK == 0 then -- print( "nothing ins stack") error( "!!!! nothing in stack" ) end return tremove( REQ_STACK ) end local wrapError, unwrapError, processError wrapError = function( stack, message, level ) -- we package or unpackage local package = { stack, message, level } return processError( stack, package ) end unwrapError = function( package ) return unpack( package ) end processError = function( stack, package ) if stack==0 then local stack, message, level = unwrapError( package ) return message, level else return package end end local function newRequireFunction( module_name ) -- print( "dmc_require: ", module_name ) assert( type(module_name)=='string', "dmc_require: expected string module name" ) --==-- local _paths = _G.__dmc_require.paths local _require = _G.__dmc_require.require local lua_paths = Utils.extend( _paths, {} ) tinsert( lua_paths, 1, '' ) -- add search at root-level local err_tbl = {} local library, err = nil, nil local idx = 1 pushStack( module_name ) repeat local mod_path = lua_paths[idx] local path = ( mod_path=='' and mod_path or mod_path..'.' ) .. module_name local has_module, result = pcall( _require, path ) if has_module then library = result elseif type( result )=='table' then -- this is a packaged error from the call-stack -- now we're just trying to show it -- so we have to unwind the call-stack err = result else -- we just got error from Lua, so we need to handle it if sfind( result, "module '.+' not found" ) then -- "module not found" -- pass on this because we could have more places to check elseif sfind( result, "error loading module" ) then -- "error loading module" -- we can't proceed with this error, so -- package up to travel back up call-stack result="\n\n"..result err = wrapError( #REQ_STACK, result, 2 ) else -- we have some unknown error err = wrapError( #REQ_STACK, result, 3 ) end end idx=idx+1 until err or library or idx > #lua_paths popStack() if err then error( processError( #REQ_STACK, err ) ) elseif not library then -- print("not found") local emsg = string.format( "\nThe module '%s' not found in archive:", tostring( module_name) ) error( wrapError( #REQ_STACK, debug.traceback( emsg ), 3 )) end return library end -- read in the config file for dmc-corona local function readDMCConfiguration() -- print( "readDMCConfiguration" ) -- check if a module has tried to read config if _G.__dmc_corona ~= nil then return end local file_path, config_data local dmc_lib_data file_path = system.pathForFile( DMC_CORONA_CONFIG_FILE, system.ResourceDirectory ) if file_path ~= nil then config_data = File.readConfigFile( file_path, { default_section=DMC_CORONA_DEFAULT_SECTION } ) end -- make sure we have defaults for data areas _G.__dmc_corona = config_data or {} dmc_lib_data = _G.__dmc_corona dmc_lib_data.dmc_corona = dmc_lib_data.dmc_corona or {} end local function setupDMCRequireStruct() -- print( "setupDMCRequireStruct" ) if _G.__dmc_require ~= nil then return end _G.__dmc_require = { paths={}, require=_G.require, -- orig require method pkg_path = package.path -- orig package path } end local function setupRequireLoading() -- print( "setupRequireLoading" ) if _G.__dmc_require ~= nil then return end setupDMCRequireStruct() local dmc_corona_info = _G.__dmc_corona.dmc_corona local req_paths = _G.__dmc_require.paths local sys2reqPath = Utils.sysPathToRequirePath local path_info = dmc_corona_info.lua_path or {} -- modify the search paths, also adding 3rd party lib locations for i=1,#path_info do local mod_path, third_path mod_path = sys2reqPath( path_info[i] ) -- print( ">s1", mod_path ) tinsert( req_paths, mod_path ) for i=1,#THIRD_LIBS do third_path = THIRD_LIBS[i] -- print( ">s2", mod_path..'.'..third_path ) tinsert( req_paths, mod_path..'.'..third_path ) end end end -- useRequireLoading() -- setup alternate require() method -- local function useRequireLoading() -- print( "useRequireLoading" ) setupRequireLoading() -- must be first _G.require=newRequireFunction end -- setupModuleLoadingMethod() -- local function setupModuleLoadingMethod( ) -- print( "setupModuleLoadingMethod" ) setupRequireLoading() -- must be first _G.require=newRequireFunction end readDMCConfiguration() setupModuleLoadingMethod()
mit
ToxicFrog/ttymor
tty.lua
1
7406
tty = {} flags.register "debug-rendering-stack" { help = "Log each window as it's pushed or popped"; } -- Stack of rendering states. local stack = {} local top = nil -- Buffer for current frame. local buf = {} -- position of cursor local X,Y = 0,0 -- Initialize the tty. function tty.init() os.execute('stty raw isig -echo') local w,h = tty.termsize() stack[1] = { x = 0, y = 0; -- Offset of the drawing region. All drawing commands are relative to this. w = w, h = h; -- Width and height of the drawing region. cx = 0, cy = 0; -- Offset of the clipping rectangle. cw = w, ch = h; -- Width and height of the clipping rectangle. colour = { 255, 255, 255 }; style = 'o'; } stack[1].__index = stack[1] top = stack[1] tty.csi('h', '?', 47) -- DECSET alternate screen buffer tty.csi('l', '?', 25) -- DECRST cursor tty.flip() log.info('TTY initialized: %dx%d', w, h) return w,h end function tty.deinit() buf = {} tty.csi('l', '?', 47) -- DECRST alternate screen buffer tty.csi('h', '?', 25) -- DECSET cursor tty.flip() os.execute('stty cooked echo') log.info('TTY deinitialized') end -- return size of terminal function tty.termsize() local data = io.popen('stty -a'):read('*a') local w = data:match('columns (%d+)'):tonumber() local h = data:match('rows (%d+)'):tonumber() return w,h end -- return dimensions of top of rendering stack, i.e. size of clipping region function tty.size() return top.cw,top.ch end function tty.bounds() return top end function tty.flip() io.write(table.concat(buf, "")) buf = {} end -- Check if the given (absolute) coordinates are inside the current clipping region. local function in_bounds(x, y) return top.cx <= x and x < (top.cx + top.cw) and top.cy <= y and y < (top.cy + top.ch) end local function absolute(x, y) return x + top.x, y + top.y end -- Push a new drawing region onto the stack. -- We first translate the window into absolute coordinates; then we compute the -- new clipping region by intersecting the new window with the old clipping -- region, and store that as part of the pushed window. -- The drawing region can also contain colour and style keys, which will be -- applied when it is pushed and restored to the old values when it is popped. -- Any parameters not specified will be inherited from the top. function tty.push(win) -- Create the new window with x,y translated into absolute coordinates. local new_top = setmetatable({ name = getmetafield(win, '__tostring') and tostring(win) or win.name or tostring(win); x = win.x + top.x; y = win.y + top.y; w = win.w, h = win.h; colour = win.colour; style = win.style; }, top) new_top.__index = new_top if flags.parsed.debug_rendering_stack then indent = (" "):rep(#stack-1) log.debug("tty.push:%s%s (%d,%d) %dx%d", indent, new_top.name, new_top.x, new_top.y, new_top.w, new_top.h) end -- Calculate the new clipping region. new_top.cx = new_top.x:bound(top.cx, top.cx + top.cw) new_top.cy = new_top.y:bound(top.cy, top.cy + top.ch) -- 34 new_top.cw = (new_top.x + new_top.w):bound(top.cx, top.cx + top.cw) - new_top.cx new_top.ch = (new_top.y + new_top.h):bound(top.cy, top.cy + top.ch) - new_top.cy -- Apply new colour/style settings. tty.colour(unpack(new_top.colour)) tty.style(new_top.style) table.insert(stack, new_top) top = stack[#stack] return tty.size() end function tty.pop() assert(#stack > 1, "tty window stack underflow") local win = table.remove(stack) local new_top = stack[#stack] tty.colour(unpack(new_top.colour)) tty.style(new_top.style) if flags.parsed.debug_rendering_stack then indent = (" "):rep(#stack-1) log.debug("tty.pop:%s%s", indent, top.name) end top = new_top return tty.size() end function tty.clear() tty.csi('J', 2) end function tty.csi(command, ...) buf[#buf+1] = '\x1B[' .. table.concat({...}, ';') .. command end function tty.put(x, y, text) -- Convert to absolute coordinates. x,y = absolute(x,y) -- Silently drop draws outside the clipping region. if not in_bounds(x, y) then return end assertf(type(text) == 'string', 'Invalid input to tty.put(): %s', text) tty.move(x,y) buf[#buf+1] = text -- invalidate the cursor position X,Y = nil,nil end -- Position the cursor at the given ABSOLUTE coordinates. -- Takes (0,0) coordinates, converts to screen (1,1). function tty.move(x, y) -- Check that the new cursor position is within the bounds of the current -- clipping region. tty.put() should ensure that this check is never violated. assertf(in_bounds(x, y), "out of bounds draw: %d,%d", x, y) -- We add 1 to each since the TTY wants (1,1) based coordinates. x,y = x+1,y+1 -- Skip if this is where the cursor is already, so we don't emit lots of -- duplicate drawing commands. if x == X and y == Y then return end X,Y = x,y -- And since the TTY wants (row,col) rather than (x,y), we flip the arguments. tty.csi('H', Y, X) end local FG,BG = nil,nil function tty.colour(r,g,b, br,bg,bb) local fg = r..';'..g..';'..b if FG ~= fg then tty.csi('m', 38, 2, r, g, b) FG = fg end if br then tty.bgcolour(br, bg, bb) else tty.bgcolour(0, 0, 0) end end function tty.bgcolour(r,g,b) local bg = r..';'..g..';'..b if BG ~= bg then tty.csi('m', 48, 2, r, g, b) BG = bg end end local styles = { o = 0; b = 1; i = 3; u = 4; v = 7; s = 9; O = 0; B = 22; I = 23; U = 24; V = 27; S = 29; } local STYLE = nil function tty.style(chars) chars = chars or '' local codes = {} for char in chars:gmatch('.') do if styles[char] then table.insert(codes, styles[char]) end if char == 'o' or char == 'O' then FG,BG = nil,nil end end local style = table.concat(codes, ';') if style ~= STYLE then tty.csi('m', style) STYLE = style end end local keynames = { [' '] = 'space'; ['\x1B[A'] = 'up'; ['\x1B[B'] = 'down'; ['\x1B[C'] = 'right'; ['\x1B[D'] = 'left'; ['\x1B[H'] = 'home'; ['\x1B[F'] = 'end'; ['\x1B[5~'] = 'pgup'; ['\x1B[6~'] = 'pgdn'; ['\x1B\x1B'] = 'esc'; ['\x1B[2~'] = 'ins'; ['\x1B[3~'] = 'del'; ['\x7F'] = 'backspace'; } for char in ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'):gmatch('.') do keynames[char:lower()] = char keynames[char] = "s-"..char keynames['\x1B'..char:lower()] = "m-"..char keynames['\x1B'..char] = "m-s-"..char keynames[string.char(char:byte() - 0x40)] = "c-"..char end keynames['\t'] = 'tab' keynames['\n'] = 'enter' keynames['\r'] = 'enter' local function keyname(k) return keynames[k] or k end function tty.readkey() -- read a single keystroke from the terminal. One keystroke may be multiple characters! -- keys are either: -- CSI <digits> ~ (special keys) -- CSI <letter> (arrow keys and others) -- ESC <uppercase> (meta-shift-*) -- ESC <lowercase> (meta-*) -- ESC ESC ('escape' pressed twice) -- a single character in the range \x01-\x1A (ctrl-letter) -- a single printable character local key = io.read(1) if key ~= '\x1B' then return keyname(key) end key = key..io.read(1) if keynames[key] then return keyname(key) end local digit = io.read(1) if not digit:match('%d') then return keyname(key..digit) else key = key..digit repeat key = key..io.read(1) until key:match('~$') return keyname(key) end end
mit
UnluckyNinja/PathOfBuilding
Data/2_6/Minions.lua
1
7177
-- Path of Building -- -- Minion Data -- Monster data (c) Grinding Gear Games -- local minions, mod = ... minions["RaisedZombie"] = { name = "Raised Zombie", life = 2.55, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 1.5, damageSpread = 0.4, attackTime = 1.755, attackRange = 9, damageFixup = 0.33, limit = "ActiveZombieLimit", skillList = { "Melee", "ZombieSlam", }, modList = { mod("Armour", "INC", 40), }, } minions["SummonedChaosGolem"] = { name = "Chaos Golem", life = 4.8, energyShield = 0.2, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 60, damage = 2.48, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, damageFixup = 0.22, limit = "ActiveGolemLimit", skillList = { "Melee", "ChaosElementalCascadeSummoned", "SandstormChaosElementalSummoned", }, modList = { }, } minions["SummonedFlameGolem"] = { name = "Flame Golem", life = 3.75, energyShield = 0.4, fireResist = 70, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 1.5, damageSpread = 0.2, attackTime = 1.5, attackRange = 4, damageFixup = 0.22, limit = "ActiveGolemLimit", skillList = { "FireElementalFlameRedSummoned", "FireElementalMortarSummoned", "FireElementalConeSummoned", }, modList = { }, } minions["SummonedIceGolem"] = { name = "Ice Golem", life = 4.05, energyShield = 0.4, fireResist = 40, coldResist = 70, lightningResist = 40, chaosResist = 20, damage = 3.06, damageSpread = 0.2, attackTime = 1.275, attackRange = 4, damageFixup = 0.33, limit = "ActiveGolemLimit", skillList = { "Melee", "IceElementalIceCyclone", "IceElementalSpearSummoned", }, modList = { }, } minions["SummonedLightningGolem"] = { name = "Lightning Golem", life = 3.75, energyShield = 0.2, fireResist = 40, coldResist = 40, lightningResist = 70, chaosResist = 20, damage = 1.5, damageSpread = 0.2, attackTime = 1.755, attackRange = 6, damageFixup = 0.22, limit = "ActiveGolemLimit", skillList = { "LightningGolemArcSummoned", "MonsterProjectileSpellLightningGolemSummoned", "LightningGolemWrath", }, modList = { }, } minions["SummonedStoneGolem"] = { name = "Stone Golem", life = 5.25, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 3, damageSpread = 0.2, attackTime = 1.5, attackRange = 6, weaponType1 = "One Handed Sword", limit = "ActiveGolemLimit", skillList = { "Melee", "RockGolemSlam", "RockGolemWhirlingBlades", }, modList = { }, } minions["SummonedRagingSpirit"] = { name = "Raging Spirit", life = 1.8, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0.77, damageSpread = 0.2, attackTime = 0.855, attackRange = 6, limit = "ActiveRagingSpiritLimit", skillList = { "PlayerRagingSpiritMeleeAttack", }, modList = { mod("PhysicalDamageConvertToFire", "BASE", 50), mod("PhysicalMin", "BASE", 4, ModFlag.Attack), mod("PhysicalMax", "BASE", 5, ModFlag.Attack), mod("Speed", "MORE", 40, ModFlag.Attack), }, } minions["SummonedEssenceSpirit"] = { name = "Essence Spirit", life = 1.8, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0.77, damageSpread = 0.2, attackTime = 0.855, attackRange = 6, skillList = { "RagingSpiritMeleeAttack", "SpectralSkullShieldCharge", }, modList = { mod("Speed", "MORE", 40, ModFlag.Attack), mod("Condition:FullLife", "FLAG", true), }, } minions["SummonedSpectralWolf"] = { name = "Spectral Wolf Companion", life = 4.5, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 1.5, damageSpread = 0.2, attackTime = 1.5, attackRange = 9, weaponType1 = "Dagger", limit = "ActiveWolfLimit", skillList = { "Melee", }, modList = { }, } minions["RaisedSkeleton"] = { name = "Skeleton Warrior", life = 1.05, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 1.72, damageSpread = 0.4, attackTime = 1.305, attackRange = 6, damageFixup = 0.33, weaponType1 = "One Handed Sword", weaponType2 = "Shield", limit = "ActiveSkeletonLimit", skillList = { "Melee", }, modList = { }, } minions["RaisedSkeletonCaster"] = { name = "Skeleton Mage", life = 1.05, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0.98, damageSpread = 0.3, attackTime = 1.605, attackRange = 46, damageFixup = 0.33, limit = "ActiveSkeletonLimit", skillList = { "SkeletonProjectileFire", "SkeletonProjectileCold", "SkeletonProjectileLightning", }, modList = { }, } minions["RaisedSkeletonArcher"] = { name = "Skeleton Archer", life = 1.05, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0.98, damageSpread = 0.16, attackTime = 1.995, attackRange = 40, damageFixup = 0.33, weaponType1 = "Bow", limit = "ActiveSkeletonLimit", skillList = { "Melee", }, modList = { }, } minions["Clone"] = { name = "Clone", life = 1, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 1, damageSpread = 0, attackTime = 1.245, attackRange = 4, skillList = { "Melee", }, modList = { mod("EnergyShield", "BASE", 10), mod("SkillData", "LIST", { key = "attackRateCap", value = 1.84 }), }, } minions["SpiderMinion"] = { name = "Spider Minion", life = 1.8, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 1.32, damageSpread = 0.2, attackTime = 1.44, attackRange = 3, weaponType1 = "One Handed Sword", limit = "ActiveSpiderLimit", skillList = { "Melee", "SpiderMinionLeapSlam", }, modList = { }, } minions["AnimatedWeapon"] = { name = "Animated Weapon", life = 4, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0, damageSpread = 0, attackTime = 1.5, attackRange = 4, skillList = { "Melee", }, modList = { }, } minions["AnimatedArmour"] = { name = "Animated Guardian", life = 4.5, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0, damageSpread = 0, attackTime = 1.5, attackRange = 4, skillList = { "Melee", }, modList = { mod("Speed", "MORE", 10, ModFlag.Attack, 0, { type = "Condition", var = "DualWielding" }), mod("PhysicalDamage", "MORE", 20, ModFlag.Attack, 0, { type = "Condition", var = "DualWielding" }), mod("BlockChance", "BASE", 15, 0, 0, { type = "Condition", var = "DualWielding" }), }, } minions["IcyRagingSpirit"] = { name = "Grave Spirit", life = 3, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 2, damageSpread = 0.2, attackTime = 0.855, attackRange = 6, skillList = { "RagingSpiritMeleeAttack", }, modList = { mod("PhysicalDamageConvertToCold", "BASE", 50), mod("Speed", "MORE", 40, ModFlag.Attack), }, } minions["UniqueAnimatedWeapon"] = { name = "Dancing Dervish", life = 4, fireResist = 40, coldResist = 40, lightningResist = 40, chaosResist = 20, damage = 0, damageSpread = 0, attackTime = 1.5, attackRange = 60, skillList = { "Melee", "DancingDervishCyclone", }, modList = { }, }
mit
artynet/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/openvpn.lua
5
1823
-- Copyright 2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.openvpn", package.seeall) function item() return luci.i18n.translate("OpenVPN") end function rrdargs( graph, plugin, plugin_instance ) local inst = plugin_instance:gsub("^openvpn%.(.+)%.status$", "%1") return { { title = "%%H: OpenVPN \"%s\" - Traffic" % inst, vlabel = "Bytes/s", data = { instances = { if_octets = { "traffic", "overhead" } }, sources = { if_octets = { "tx", "rx" } }, options = { if_octets_traffic_tx = { weight = 0, title = "Bytes (TX)", total = true, color = "00ff00" }, if_octets_overhead_tx = { weight = 1, title = "Overhead (TX)", total = true, color = "ff9900" }, if_octets_overhead_rx = { weight = 2, title = "Overhead (RX)", total = true, flip = true, color = "ff00ff" }, if_octets_traffic_rx = { weight = 3, title = "Bytes (RX)", total = true, flip = true, color = "0000ff" } } } }, { title = "%%H: OpenVPN \"%s\" - Compression" % inst, vlabel = "Bytes/s", data = { instances = { compression = { "data_out", "data_in" } }, sources = { compression = { "uncompressed", "compressed" } }, options = { compression_data_out_uncompressed = { weight = 0, title = "Uncompressed (TX)", total = true, color = "00ff00" }, compression_data_out_compressed = { weight = 1, title = "Compressed (TX)", total = true, color = "008800" }, compression_data_in_compressed = { weight = 2, title = "Compressed (RX)", total = true, flip = true, color = "000088" }, compression_data_in_uncompressed = { weight = 3, title = "Uncompressed (RX)", total = true, flip = true, color = "0000ff" } } } } } end
apache-2.0
moltafet35/ssssis
plugins/pokedex.lua
626
1668
do local images_enabled = true; local function get_sprite(path) local url = "http://pokeapi.co/"..path print(url) local b,c = http.request(url) local data = json:decode(b) local image = data.image return image end local function callback(extra) send_msg(extra.receiver, extra.text, ok_cb, false) end local function send_pokemon(query, receiver) local url = "http://pokeapi.co/api/v1/pokemon/" .. query .. "/" local b,c = http.request(url) local pokemon = json:decode(b) if pokemon == nil then return 'No pokémon found.' end -- api returns height and weight x10 local height = tonumber(pokemon.height)/10 local weight = tonumber(pokemon.weight)/10 local text = 'Pokédex ID: ' .. pokemon.pkdx_id ..'\nName: ' .. pokemon.name ..'\nWeight: ' .. weight.." kg" ..'\nHeight: ' .. height.." m" ..'\nSpeed: ' .. pokemon.speed local image = nil if images_enabled and pokemon.sprites and pokemon.sprites[1] then local sprite = pokemon.sprites[1].resource_uri image = get_sprite(sprite) end if image then image = "http://pokeapi.co"..image local extra = { receiver = receiver, text = text } send_photo_from_url(receiver, image, callback, extra) else return text end end local function run(msg, matches) local receiver = get_receiver(msg) local query = URL.escape(matches[1]) return send_pokemon(query, receiver) end return { description = "Pokedex searcher for Telegram", usage = "!pokedex [Name/ID]: Search the pokédex for Name/ID and get info of the pokémon!", patterns = { "^!pokedex (.*)$", "^!pokemon (.+)$" }, run = run } end
gpl-2.0
tudelft/chdkptp
lua/camtests.lua
5
10588
--[[ Copyright (C) 2013-2014 <reyalp (at) gmail dot com> 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, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ]] --[[ some tests to run against the camera --]] local m={} function m.make_stats(stats) local r={ total=0 } if #stats == 0 then return r end for i,v in ipairs(stats) do if not r.max or v > r.max then r.max = v end if not r.min or v < r.min then r.min = v end r.total = r.total + v end r.mean = r.total/#stats return r end --[[ repeatedly start scripts, measuring time opts:{ count=number -- number of iterations code=string -- code to run } ]] function m.exectime(opts) opts = util.extend_table({count=100, code="dummy=1"},opts) if not con:is_connected() then error('not connected') end local times={} local tstart = ustime.new() for i=1,opts.count do local t0 = ustime.new() con:exec(opts.code,{nodefaultlib=true}) table.insert(times,ustime.diff(t0)/1000000) -- wait for the script to be done con:wait_status{run=false} end local wall_time = ustime.diff(tstart)/1000000 local stats = m.make_stats(times) printf("exec %d mean %.4f min %.4f max %.4f total %.4f (%.4f/sec) wall %.4f (%.4f/sec)\n", opts.count, stats.mean, stats.min, stats.max, stats.total, opts.count / stats.total, wall_time, opts.count / wall_time) end --[[ repeatedly exec code and wait for return, checking that returned value = retval opts:{ count=number -- number of iterations code=string -- code to run, should return something retval=value -- value code is expected to return } --]] function m.execwaittime(opts) opts = util.extend_table({count=100, code="return 1",retval=1},opts) if not con:is_connected() then error('not connected') end local times={} local tstart = ustime.new() for i=1,opts.count do local t0 = ustime.new() local r = con:execwait(opts.code,{nodefaultlib=true,poll=50}) if r ~= opts.retval then error('bad retval '..tostring(r) .. ' ~= '..tostring(opts.retval)) end table.insert(times,ustime.diff(t0)/1000000) end local wall_time = ustime.diff(tstart)/1000000 local stats = m.make_stats(times) printf("execw %d mean %.4f min %.4f max %.4f total %.4f (%.4f/sec) wall %.4f (%.4f/sec)\n", opts.count, stats.mean, stats.min, stats.max, stats.total, opts.count / stats.total, wall_time, opts.count / wall_time) end --[[ repeatedly time memory transfers from cam opts:{ count=number -- number of iterations size=number -- size to transfer addr=number -- address to transfer from (default 0x1900) } ]] function m.xfermem(opts) opts = util.extend_table({count=100, size=1024*1024,addr=0x1900},opts) if not con:is_connected() then error('not connected') end local times={} local tstart = ustime.new() for i=1,opts.count do local t0 = ustime.new() local v=con:getmem(opts.addr,opts.size) table.insert(times,ustime.diff(t0)/1000000) end local wall_time = ustime.diff(tstart)/1000000 local stats = m.make_stats(times) printf("%d x %d bytes mean %.4f min %.4f max %.4f total %.4f (%d byte/sec) wall %.4f (%d byte/sec)\n", opts.count, opts.size, stats.mean, stats.min, stats.max, stats.total, opts.count*opts.size / stats.total, wall_time, opts.count*opts.size / wall_time) end local tests = {} function m.cliexec(cmd) local status,err=cli:execute(cmd) if not status then error(err,2) end cli:print_status(true,err) end -- return output on success instead of printing function m.cliexec_ret_ok(cmd) local status,err=cli:execute(cmd) if not status then error(err,2) end return err end -- return output on on fail, assert on success function m.cliexec_ret_fail(cmd) local status,err=cli:execute(cmd) if not status then return err end assert('command succeeded when expected to fail') end function m.makelocalfile(path,content) fsutil.mkdir_m(fsutil.dirname(path)) local fh,err=io.open(path,'wb') if not fh then error(err) end local status=true if content:len() > 0 then status,err = fh:write(content) end fh:close() assert(status,err) end function m.readlocalfile(path) assert(lfs.attributes(path,'mode') == 'file') local fh,err=io.open(path,'rb') if not fh then error(err) end local content=fh:read('*a') fh:close() assert(content) return content end function m.comparefiles(path1,path2) local mode=lfs.attributes(path1,'mode') assert(mode == lfs.attributes(path2,'mode')) if mode ~= 'file' then return end assert(m.readlocalfile(path1)==m.readlocalfile(path2)) end function tests.xfer() m.xfermem({count=50}) end function tests.exectimes() m.execwaittime({count=50}) m.exectime({count=50}) end function tests.exec_errors() con:exec('sleep(500)') local status,err=con:exec_pcall('print"test"') assert((not status) and err.etype == 'execlua_scriptrun') -- test killscript if compatible if con:is_ver_compatible(2,6) then con:execwait('print"kill"',{clobber=true}) else -- otherwise just wait sys.sleep(600) end status,err=con:exec_pcall('bogus(') assert((not status) and err.etype == 'execlua_compile') end function tests.not_connected() if con:is_connected() then error('already connected') end local status,err=con:script_status_pcall() assert((not status) and err.ptp_rc == ptp.ERROR_NOT_CONNECTED) end -- prepare for connected tests by connecting -- devspec is a string for connect function tests.connect(devspec) local devs=chdk.list_usb_devices() if #devs == 0 then error('no usb devices available') end if con:is_connected() then error('already connected') end local cmd = 'c' if devspec then cmd = cmd .. ' ' .. devspec else printf('using default device\n') end m.cliexec(cmd) assert(con:is_connected()) end function tests.list_connected() local list=m.cliexec_ret_ok('list') local lines=util.string_split(list,'\n',{plain=true,empty=false}) for i,l in ipairs(lines) do -- match the current (marked *) device, grab bus and dev name local bus,dev=string.match(lines[1],'^%*%d+:.*b=([%S]+) d=([%S]+)') if bus then assert(bus==con.condev.bus and dev==con.condev.dev) return true end end error('current dev not found') end function tests.wait_status() local status=con:wait_status{msg=true,timeout=100} assert(status.timeout) local pstatus,status=con:wait_status_pcall{msg=true,timeout=100,timeout_error=true} assert(status.etype=='timeout') end function tests.msgfuncs() -- test script not running local status,err=con:write_msg_pcall("test") assert((not status) and err.etype == 'msg_notrun') -- test flushmsgs con:exec('write_usb_msg("msg1") return 2,3') con:wait_status{run=false} status = con:script_status() assert(status.msg == true) con:flushmsgs() status = con:script_status() assert(status.msg == false) con:exec('write_usb_msg("msg2") return 1') local m=con:wait_msg({mtype='user'}) assert(m.type=='user' and m.value == 'msg2') m=con:wait_msg({mtype='return'}) assert(m.type=='return' and m.value == 1) status,err=pcall(con.wait_msg,con,{mtype='return',timeout=100}) assert(err.etype=='timeout',tostring(err)) con:exec('return 1') status,err=pcall(con.wait_msg,con,{mtype='user'}) assert(err.etype=='wrongmsg',tostring(err)) end function tests.filexfer() local ldir='camtest' for i,size in ipairs({511,512,4096}) do local fn=string.format('test%d.dat',size) local lfn=string.format('%s/%s',ldir,fn) local dfn=string.format('%s/d_%s',ldir,fn) local s1=string.rep('x',size) m.makelocalfile(lfn,s1) m.cliexec('u '..lfn) m.cliexec('d '..fn .. ' ' .. dfn) local s2=m.readlocalfile(dfn) assert(s1==s2) m.cliexec('rm '..fn) end fsutil.rm_r(ldir) end function tests.mfilexfer() local ldir='camtest' -- names are in caps since cam may change, client may be case sensitive m.makelocalfile(ldir..'/up/EMPTY.TXT','') m.makelocalfile(ldir..'/up/ONE.TXT','one') m.makelocalfile(ldir..'/up/SUB1/SUB.TXT',string.rep('subtext',1000)) fsutil.mkdir_m(ldir..'/up/EMPTYSUB') m.cliexec('mup '..ldir..'/up muptest') m.cliexec('mdl muptest '..ldir..'/dn') m.comparefiles(ldir..'/up/EMPTY.TXT',ldir..'/dn/EMPTY.TXT') m.comparefiles(ldir..'/up/ONE.TXT',ldir..'/dn/ONE.TXT') m.comparefiles(ldir..'/up/SUB1/SUB.TXT',ldir..'/dn/SUB1/SUB.TXT') m.comparefiles(ldir..'/up/EMPTYSUB',ldir..'/dn/EMPTYSUB') m.cliexec('rm muptest') -- test on non-existing dir local s=m.cliexec_ret_fail('mdl muptest '..ldir) assert(string.sub(s,1,10) == 'A/muptest:') -- exact message varies by cam fsutil.rm_r(ldir) end function tests.msgs() local mt=require'extras/msgtest' assert(mt.test({size=1,sizeinc=1,count=100,verbose=0})) assert(con:wait_status{run=false}) assert(mt.test({size=10,sizeinc=10,count=100,verbose=0})) end function tests.reconnect() assert(con:is_connected()) m.cliexec('reconnect') assert(con:is_connected()) end function tests.disconnect() m.cliexec('dis') assert(not con:is_connected()) end function m.run(name,...) printf('%s:start\n',name) status,msg = xpcall(tests[name],errutil.format_traceback,...) printf('%s:',name) if status then m.passed = m.passed + 1 printf('ok\n') return true else m.failed = m.failed + 1 printf('failed %s\n',msg) return false end end --[[ opts:{ devspec=<usb device spec> -- specify which device to use, default to first available bench=bool -- run "benchmark" tests filexfer=bool -- run file transfer tests } NOTE filexfer creates and deletes various hard coded paths, both locally and on the camera ]] function m.runbatch(opts) opts = util.extend_table({},opts) -- if connect fails, don't try to run anything else m.passed = 0 m.failed = 0 if not m.run('connect',opts.devspec) then printf('aborted\n') return false end m.run('list_connected') m.run('wait_status') m.run('exec_errors') m.run('msgfuncs') if opts.bench then m.run('exectimes') m.run('xfer') m.run('msgs') end if opts.filexfer then m.run('filexfer') m.run('mfilexfer') end m.run('reconnect') m.run('disconnect') m.run('not_connected') printf("passed %d\nfailed %d\n",m.passed,m.failed) return m.failed == 0 end return m
gpl-2.0
djkamran021/BY
plugins/groupmanager.lua
2
154855
local function modadd(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then if not lang then return '_You are not bot admin_' else return 'شما مدیر ربات نمیباشید' end end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not lang then return '_Group is already added_' else return 'گروه در لیست گروه های مدیریتی ربات هم اکنون موجود است' end end -- create data array in moderation.json data[tostring(msg.to.id)] = { owners = {}, mods ={}, banned ={}, is_silent_users ={}, filterlist ={}, whitelist ={}, settings = { set_name = msg.to.title, lock_link = 'yes', lock_tag = 'yes', lock_spam = 'yes', lock_webpage = 'no', lock_mention = 'no', lock_markdown = 'no', lock_flood = 'yes', lock_bots = 'yes', lock_pin = 'no', welcome = 'no', lock_join = 'no', }, mutes = { mute_fwd = 'no', mute_audio = 'no', mute_video = 'no', mute_contact = 'no', mute_text = 'no', mute_photos = 'no', mute_gif = 'no', mute_loc = 'no', mute_doc = 'no', mute_sticker = 'no', mute_voice = 'no', mute_all = 'no', mute_keyboard = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) if not lang then return '*Group has been added*' else return 'گروه با موفقیت به لیست گروه های مدیریتی ربات افزوده شد' end end local function modrem(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then if not lang then return '_You are not bot admin_' else return 'شما مدیر ربات نمیباشید' end end local data = load_data(_config.moderation.data) local receiver = msg.to.id if not data[tostring(msg.to.id)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end 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) if not lang then return '*Group has been removed*' else return 'گروه با موفیت از لیست گروه های مدیریتی ربات حذف شد' end end local function config_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) print(serpent.block(data)) for k,v in pairs(data.members_) do local function config_mods(arg, data) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then return end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) end tdcli_function ({ ID = "GetUser", user_id_ = v.user_id_ }, config_mods, {chat_id=arg.chat_id,user_id=v.user_id_}) if data.members_[k].status_.ID == "ChatMemberStatusCreator" then owner_id = v.user_id_ local function config_owner(arg, data) print(serpent.block(data)) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then return end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) end tdcli_function ({ ID = "GetUser", user_id_ = owner_id }, config_owner, {chat_id=arg.chat_id,user_id=owner_id}) end end if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_All group admins has been promoted and group creator is now group owner_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_تمام ادمین های گروه به مقام مدیر منتصب شدند و سازنده گروه به مقام مالک گروه منتصب شد_", 0, "md") end end local function filter_word(msg, word) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)]['filterlist'] then data[tostring(msg.to.id)]['filterlist'] = {} save_data(_config.moderation.data, data) end if data[tostring(msg.to.id)]['filterlist'][(word)] then if not lang then return "_Word_ *"..word.."* _is already filtered_" else return "_کلمه_ *"..word.."* _از قبل فیلتر بود_" end end data[tostring(msg.to.id)]['filterlist'][(word)] = true save_data(_config.moderation.data, data) if not lang then return "_Word_ *"..word.."* _added to filtered words list_" else return "_کلمه_ *"..word.."* _به لیست کلمات فیلتر شده اضافه شد_" end end local function unfilter_word(msg, word) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)]['filterlist'] then data[tostring(msg.to.id)]['filterlist'] = {} save_data(_config.moderation.data, data) end if data[tostring(msg.to.id)]['filterlist'][word] then data[tostring(msg.to.id)]['filterlist'][(word)] = nil save_data(_config.moderation.data, data) if not lang then return "_Word_ *"..word.."* _removed from filtered words list_" elseif lang then return "_کلمه_ *"..word.."* _از لیست کلمات فیلتر شده حذف شد_" end else if not lang then return "_Word_ *"..word.."* _is not filtered_" elseif lang then return "_کلمه_ *"..word.."* _از قبل فیلتر نبود_" end end end local function modlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return "_Group is not added_" else return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است" end end -- determine if table is empty if next(data[tostring(msg.to.id)]['mods']) == nil then --fix way if not lang then return "_No_ *moderator* _in this group_" else return "در حال حاضر هیچ مدیری برای گروه انتخاب نشده است" end end if not lang then message = '*List of moderators :*\n' else message = '*لیست مدیران گروه :*\n' end for k,v in pairs(data[tostring(msg.to.id)]['mods']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function ownerlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.to.id)] then if not lang then return "_Group is not added_" else return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است" end end -- determine if table is empty if next(data[tostring(msg.to.id)]['owners']) == nil then --fix way if not lang then return "_No_ *owner* _in this group_" else return "در حال حاضر هیچ مالکی برای گروه انتخاب نشده است" end end if not lang then message = '*List of owners :*\n' else message = '*لیست مالکین گروه :*\n' end for k,v in pairs(data[tostring(msg.to.id)]['owners']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function action_by_reply(arg, data) local hash = "gp_lang:"..data.chat_id_ local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if not administration[tostring(data.chat_id_)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if cmd == "setmanager" then local function manager_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end channel_set_admin(arg.chat_id, data.id_) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group manager*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *ادمین گروه شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, manager_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "remmanager" then local function rem_manager_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end channel_demote(arg.chat_id, data.id_) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer_ *group manager*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از ادمینی گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, rem_manager_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "setwhitelist" then local function setwhitelist_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, setwhitelist_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "remwhitelist" then local function remwhitelist_cb(arg, data) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, remwhitelist_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "setowner" then local function owner_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "promote" then local function promote_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, promote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "remowner" then local function rem_owner_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, rem_owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "demote" then local function demote_cb(arg, data) local administration = load_data(_config.moderation.data) if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, demote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "id" then local function id_cb(arg, data) return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md") end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, id_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not administration[tostring(arg.chat_id)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = ' '..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "setmanager" then channel_set_admin(arg.chat_id, data.id_) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group manager*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *ادمین گروه شد*", 0, "md") end end if cmd == "remmanager" then channel_demote(arg.chat_id, data.id_) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer_ *group manager*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از ادمینی گروه برکنار شد*", 0, "md") end end if cmd == "setwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md") end end if cmd == "remwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md") end end if cmd == "setowner" then if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end if cmd == "promote" then if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end if cmd == "remowner" then if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end if cmd == "demote" then if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end if cmd == "id" then return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md") end if cmd == "res" then if not lang then text = "Result for [ "..check_markdown(data.type_.user_.username_).." ] :\n" .. ""..check_markdown(data.title_).."\n" .. " ["..data.id_.."]" else text = "اطلاعات برای [ "..check_markdown(data.type_.user_.username_).." ] :\n" .. "".. check_markdown(data.title_) .."\n" .. " [".. data.id_ .."]" end return tdcli.sendMessage(arg.chat_id, 0, 1, text, 1, 'md') end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not administration[tostring(arg.chat_id)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if not tonumber(arg.user_id) then return false end if data.id_ then if data.first_name_ then if data.username_ then user_name = ' '..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "setmanager" then channel_set_admin(arg.chat_id, data.id_) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group manager*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *ادمین گروه شد*", 0, "md") end end if cmd == "remmanager" then channel_demote(arg.chat_id, data.id_) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer_ *group manager*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از ادمینی گروه برکنار شد*", 0, "md") end end if cmd == "setwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md") end end if cmd == "remwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md") end end if cmd == "setowner" then if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end if cmd == "promote" then if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end if cmd == "remowner" then if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end if cmd == "demote" then if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end if cmd == "whois" then if data.username_ then username = ' '..check_markdown(data.username_) else if not lang then username = 'not found' else username = 'ندارد' end end if not lang then return tdcli.sendMessage(arg.chat_id, 0, 1, 'Info for [ '..data.id_..' ] :\nUserName : '..username..'\nName : '..data.first_name_, 1) else return tdcli.sendMessage(arg.chat_id, 0, 1, 'اطلاعات برای [ '..data.id_..' ] :\nیوزرنیم : '..username..'\nنام : '..data.first_name_, 1) end end else if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User not founded_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end ---------------Lock Link------------------- local function lock_link(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_link = data[tostring(target)]["settings"]["lock_link"] if lock_link == "yes" then if not lang then return "*Link* _Posting Is Already Locked_" elseif lang then return "ارسال لینک در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_link"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Link* _Posting Has Been Locked_" else return "ارسال لینک در گروه ممنوع شد" end end end local function unlock_link(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_link = data[tostring(target)]["settings"]["lock_link"] if lock_link == "no" then if not lang then return "*Link* _Posting Is Not Locked_" elseif lang then return "ارسال لینک در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_link"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Link* _Posting Has Been Unlocked_" else return "ارسال لینک در گروه آزاد شد" end end end ---------------Lock Tag------------------- local function lock_tag(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_tag = data[tostring(target)]["settings"]["lock_tag"] if lock_tag == "yes" then if not lang then return "*Tag* _Posting Is Already Locked_" elseif lang then return "ارسال تگ در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_tag"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Tag* _Posting Has Been Locked_" else return "ارسال تگ در گروه ممنوع شد" end end end local function unlock_tag(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_tag = data[tostring(target)]["settings"]["lock_tag"] if lock_tag == "no" then if not lang then return "*Tag* _Posting Is Not Locked_" elseif lang then return "ارسال تگ در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_tag"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Tag* _Posting Has Been Unlocked_" else return "ارسال تگ در گروه آزاد شد" end end end ---------------Lock Mention------------------- local function lock_mention(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_mention = data[tostring(target)]["settings"]["lock_mention"] if lock_mention == "yes" then if not lang then return "*Mention* _Posting Is Already Locked_" elseif lang then return "ارسال فراخوانی افراد هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_mention"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mention* _Posting Has Been Locked_" else return "ارسال فراخوانی افراد در گروه ممنوع شد" end end end local function unlock_mention(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_mention = data[tostring(target)]["settings"]["lock_mention"] if lock_mention == "no" then if not lang then return "*Mention* _Posting Is Not Locked_" elseif lang then return "ارسال فراخوانی افراد در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_mention"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mention* _Posting Has Been Unlocked_" else return "ارسال فراخوانی افراد در گروه آزاد شد" end end end ---------------Lock Arabic-------------- local function lock_arabic(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"] if lock_arabic == "yes" then if not lang then return "*Arabic/Persian* _Posting Is Already Locked_" elseif lang then return "ارسال کلمات عربی/فارسی در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_arabic"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Arabic/Persian* _Posting Has Been Locked_" else return "ارسال کلمات عربی/فارسی در گروه ممنوع شد" end end end local function unlock_arabic(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"] if lock_arabic == "no" then if not lang then return "*Arabic/Persian* _Posting Is Not Locked_" elseif lang then return "ارسال کلمات عربی/فارسی در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_arabic"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Arabic/Persian* _Posting Has Been Unlocked_" else return "ارسال کلمات عربی/فارسی در گروه آزاد شد" end end end ---------------Lock Edit------------------- local function lock_edit(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_edit = data[tostring(target)]["settings"]["lock_edit"] if lock_edit == "yes" then if not lang then return "*Editing* _Is Already Locked_" elseif lang then return "ویرایش پیام هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_edit"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Editing* _Has Been Locked_" else return "ویرایش پیام در گروه ممنوع شد" end end end local function unlock_edit(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_edit = data[tostring(target)]["settings"]["lock_edit"] if lock_edit == "no" then if not lang then return "*Editing* _Is Not Locked_" elseif lang then return "ویرایش پیام در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_edit"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Editing* _Has Been Unlocked_" else return "ویرایش پیام در گروه آزاد شد" end end end ---------------Lock spam------------------- local function lock_spam(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_spam = data[tostring(target)]["settings"]["lock_spam"] if lock_spam == "yes" then if not lang then return "*Spam* _Is Already Locked_" elseif lang then return "ارسال هرزنامه در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_spam"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Spam* _Has Been Locked_" else return "ارسال هرزنامه در گروه ممنوع شد" end end end local function unlock_spam(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_spam = data[tostring(target)]["settings"]["lock_spam"] if lock_spam == "no" then if not lang then return "*Spam* _Posting Is Not Locked_" elseif lang then return "ارسال هرزنامه در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_spam"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Spam* _Posting Has Been Unlocked_" else return "ارسال هرزنامه در گروه آزاد شد" end end end ---------------Lock Flood------------------- local function lock_flood(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_flood = data[tostring(target)]["settings"]["lock_flood"] if lock_flood == "yes" then if not lang then return "*Flooding* _Is Already Locked_" elseif lang then return "ارسال پیام مکرر در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_flood"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Flooding* _Has Been Locked_" else return "ارسال پیام مکرر در گروه ممنوع شد" end end end local function unlock_flood(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_flood = data[tostring(target)]["settings"]["lock_flood"] if lock_flood == "no" then if not lang then return "*Flooding* _Is Not Locked_" elseif lang then return "ارسال پیام مکرر در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_flood"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Flooding* _Has Been Unlocked_" else return "ارسال پیام مکرر در گروه آزاد شد" end end end ---------------Lock Bots------------------- local function lock_bots(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_bots = data[tostring(target)]["settings"]["lock_bots"] if lock_bots == "yes" then if not lang then return "*Bots* _Protection Is Already Enabled_" elseif lang then return "محافظت از گروه در برابر ربات ها هم اکنون فعال است" end else data[tostring(target)]["settings"]["lock_bots"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Bots* _Protection Has Been Enabled_" else return "محافظت از گروه در برابر ربات ها فعال شد" end end end local function unlock_bots(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_bots = data[tostring(target)]["settings"]["lock_bots"] if lock_bots == "no" then if not lang then return "*Bots* _Protection Is Not Enabled_" elseif lang then return "محافظت از گروه در برابر ربات ها غیر فعال است" end else data[tostring(target)]["settings"]["lock_bots"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Bots* _Protection Has Been Disabled_" else return "محافظت از گروه در برابر ربات ها غیر فعال شد" end end end ---------------Lock Join------------------- local function lock_join(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_join = data[tostring(target)]["settings"]["lock_join"] if lock_join == "yes" then if not lang then return "*Lock Join* _Is Already Locked_" elseif lang then return "ورود به گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_join"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Lock Join* _Has Been Locked_" else return "ورود به گروه ممنوع شد" end end end local function unlock_join(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_join = data[tostring(target)]["settings"]["lock_join"] if lock_join == "no" then if not lang then return "*Lock Join* _Is Not Locked_" elseif lang then return "ورود به گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_join"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Lock Join* _Has Been Unlocked_" else return "ورود به گروه آزاد شد" end end end ---------------Lock Markdown------------------- local function lock_markdown(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"] if lock_markdown == "yes" then if not lang then return "*Markdown* _Posting Is Already Locked_" elseif lang then return "ارسال پیام های دارای فونت در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_markdown"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Markdown* _Posting Has Been Locked_" else return "ارسال پیام های دارای فونت در گروه ممنوع شد" end end end local function unlock_markdown(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"] if lock_markdown == "no" then if not lang then return "*Markdown* _Posting Is Not Locked_" elseif lang then return "ارسال پیام های دارای فونت در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_markdown"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Markdown* _Posting Has Been Unlocked_" else return "ارسال پیام های دارای فونت در گروه آزاد شد" end end end ---------------Lock Webpage------------------- local function lock_webpage(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"] if lock_webpage == "yes" then if not lang then return "*Webpage* _Is Already Locked_" elseif lang then return "ارسال صفحات وب در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_webpage"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Webpage* _Has Been Locked_" else return "ارسال صفحات وب در گروه ممنوع شد" end end end local function unlock_webpage(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"] if lock_webpage == "no" then if not lang then return "*Webpage* _Is Not Locked_" elseif lang then return "ارسال صفحات وب در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_webpage"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Webpage* _Has Been Unlocked_" else return "ارسال صفحات وب در گروه آزاد شد" end end end ---------------Lock Pin------------------- local function lock_pin(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_pin = data[tostring(target)]["settings"]["lock_pin"] if lock_pin == "yes" then if not lang then return "*Pinned Message* _Is Already Locked_" elseif lang then return "سنجاق کردن پیام در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_pin"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Pinned Message* _Has Been Locked_" else return "سنجاق کردن پیام در گروه ممنوع شد" end end end local function unlock_pin(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_pin = data[tostring(target)]["settings"]["lock_pin"] if lock_pin == "no" then if not lang then return "*Pinned Message* _Is Not Locked_" elseif lang then return "سنجاق کردن پیام در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_pin"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Pinned Message* _Has Been Unlocked_" else return "سنجاق کردن پیام در گروه آزاد شد" end end end function group_settings(msg, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local data = load_data(_config.moderation.data) local target = msg.to.id if data[tostring(target)] then if data[tostring(target)]["settings"]["num_msg_max"] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['num_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end if data[tostring(target)]["settings"]["set_char"] then SETCHAR = tonumber(data[tostring(target)]['settings']['set_char']) print('custom'..SETCHAR) else SETCHAR = 40 end if data[tostring(target)]["settings"]["time_check"] then TIME_CHECK = tonumber(data[tostring(target)]['settings']['time_check']) print('custom'..TIME_CHECK) else TIME_CHECK = 2 end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_link"] then data[tostring(target)]["settings"]["lock_link"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_tag"] then data[tostring(target)]["settings"]["lock_tag"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_mention"] then data[tostring(target)]["settings"]["lock_mention"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_arabic"] then data[tostring(target)]["settings"]["lock_arabic"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_edit"] then data[tostring(target)]["settings"]["lock_edit"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_spam"] then data[tostring(target)]["settings"]["lock_spam"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_flood"] then data[tostring(target)]["settings"]["lock_flood"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_bots"] then data[tostring(target)]["settings"]["lock_bots"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_markdown"] then data[tostring(target)]["settings"]["lock_markdown"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_webpage"] then data[tostring(target)]["settings"]["lock_webpage"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["welcome"] then data[tostring(target)]["settings"]["welcome"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_pin"] then data[tostring(target)]["settings"]["lock_pin"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_join"] then data[tostring(target)]["settings"]["lock_join"] = "no" end end local expire_date = '' local expi = redis:ttl('ExpireDate:'..msg.to.id) if expi == -1 then if lang then expire_date = 'نامحدود!' else expire_date = 'Unlimited!' end else local day = math.floor(expi / 86400) + 1 if lang then expire_date = day..' روز' else expire_date = day..' Days' end end local cmdss = redis:hget('group:'..msg.to.id..':cmd', 'bot') local cmdsss = '' if lang then if cmdss == 'owner' then cmdsss = cmdsss..'اونر و بالاتر' elseif cmdss == 'moderator' then cmdsss = cmdsss..'مدیر و بالاتر' else cmdsss = cmdsss..'کاربر و بالاتر' end else if cmdss == 'owner' then cmdsss = cmdsss..'Owner or higher' elseif cmdss == 'moderator' then cmdsss = cmdsss..'Moderator or higher' else cmdsss = cmdsss..'Member or higher' end end if not lang then local settings = data[tostring(target)]["settings"] text = "*Group Settings:*\n_Lock edit :_ *"..settings.lock_edit.."*\n_Lock links :_ *"..settings.lock_link.."*\n_Lock tags :_ *"..settings.lock_tag.."*\n_Lock Join :_ *"..settings.lock_join.."*\n_Lock flood :_ *"..settings.lock_flood.."*\n_Lock spam :_ *"..settings.lock_spam.."*\n_Lock mention :_ *"..settings.lock_mention.."*\n_Lock arabic :_ *"..settings.lock_arabic.."*\n_Lock webpage :_ *"..settings.lock_webpage.."*\n_Lock markdown :_ *"..settings.lock_markdown.."*\n_Group welcome :_ *"..settings.welcome.."*\n_Lock pin message :_ *"..settings.lock_pin.."*\n_Bots protection :_ *"..settings.lock_bots.."*\n_Flood sensitivity :_ *"..NUM_MSG_MAX.."*\n_Character sensitivity :_ *"..SETCHAR.."*\n_Flood check time :_ *"..TIME_CHECK.."*\n*____________________*\n_Bot Commands :_ *"..cmdsss.."*\n_Expire Date :_ *"..expire_date.."*\n*Bot channel*: \n*Group Language* : *EN*" else local settings = data[tostring(target)]["settings"] text = "*تنظیمات گروه:*\n_قفل ویرایش پیام :_ *"..settings.lock_edit.."*\n_قفل لینک :_ *"..settings.lock_link.."*\n_قفل ورود :_ *"..settings.lock_join.."*\n_قفل تگ :_ *"..settings.lock_tag.."*\n_قفل پیام مکرر :_ *"..settings.lock_flood.."*\n_قفل هرزنامه :_ *"..settings.lock_spam.."*\n_قفل فراخوانی :_ *"..settings.lock_mention.."*\n_قفل عربی :_ *"..settings.lock_arabic.."*\n_قفل صفحات وب :_ *"..settings.lock_webpage.."*\n_قفل فونت :_ *"..settings.lock_markdown.."*\n_پیام خوشآمد گویی :_ *"..settings.welcome.."*\n_قفل سنجاق کردن :_ *"..settings.lock_pin.."*\n_محافظت در برابر ربات ها :_ *"..settings.lock_bots.."*\n_حداکثر پیام مکرر :_ *"..NUM_MSG_MAX.."*\n_حداکثر حروف مجاز :_ *"..SETCHAR.."*\n_زمان بررسی پیام های مکرر :_ *"..TIME_CHECK.."*\n*____________________*\n_دستورات ربات :_ *"..cmdsss.."*\n_تاریخ انقضا :_ *"..expire_date.."*\n*کانال ما*: \n_زبان سوپرگروه_ : *فارسی*" end text = string.gsub(text, 'yes', '✅') text = string.gsub(text, 'no', '❌') if lang and tonumber(NUM_MSG_MAX) < 10 then text = string.gsub(text, '0', '0⃣') text = string.gsub(text, '1', '1⃣') text = string.gsub(text, '2', '2️⃣') text = string.gsub(text, '3', '3️⃣') text = string.gsub(text, '4', '4️⃣') text = string.gsub(text, '5', '5️⃣') text = string.gsub(text, '6', '6️⃣') text = string.gsub(text, '7', '7️⃣') text = string.gsub(text, '8', '8️⃣') text = string.gsub(text, '9', '9️⃣') elseif not lang then text = string.gsub(text, '0', '0⃣') text = string.gsub(text, '1', '1⃣') text = string.gsub(text, '2', '2️⃣') text = string.gsub(text, '3', '3️⃣') text = string.gsub(text, '4', '4️⃣') text = string.gsub(text, '5', '5️⃣') text = string.gsub(text, '6', '6️⃣') text = string.gsub(text, '7', '7️⃣') text = string.gsub(text, '8', '8️⃣') text = string.gsub(text, '9', '9️⃣') end return text end --------Mutes--------- ---------------Mute Gif------------------- local function mute_gif(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_gif = data[tostring(target)]["mutes"]["mute_gif"] if mute_gif == "yes" then if not lang then return "*Mute Gif* _Is Already Enabled_" elseif lang then return "بیصدا کردن تصاویر متحرک فعال است" end else data[tostring(target)]["mutes"]["mute_gif"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Gif* _Has Been Enabled_" else return "بیصدا کردن تصاویر متحرک فعال شد" end end end local function unmute_gif(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_gif = data[tostring(target)]["mutes"]["mute_gif"] if mute_gif == "no" then if not lang then return "*Mute Gif* _Is Already Disabled_" elseif lang then return "بیصدا کردن تصاویر متحرک غیر فعال بود" end else data[tostring(target)]["mutes"]["mute_gif"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Gif* _Has Been Disabled_" else return "بیصدا کردن تصاویر متحرک غیر فعال شد" end end end ---------------Mute Game------------------- local function mute_game(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_game = data[tostring(target)]["mutes"]["mute_game"] if mute_game == "yes" then if not lang then return "*Mute Game* _Is Already Enabled_" elseif lang then return "بیصدا کردن بازی های تحت وب فعال است" end else data[tostring(target)]["mutes"]["mute_game"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Game* _Has Been Enabled_" else return "بیصدا کردن بازی های تحت وب فعال شد" end end end local function unmute_game(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_game = data[tostring(target)]["mutes"]["mute_game"] if mute_game == "no" then if not lang then return "*Mute Game* _Is Already Disabled_" elseif lang then return "بیصدا کردن بازی های تحت وب غیر فعال است" end else data[tostring(target)]["mutes"]["mute_game"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Game* _Has Been Disabled_" else return "بیصدا کردن بازی های تحت وب غیر فعال شد" end end end ---------------Mute Inline------------------- local function mute_inline(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_inline = data[tostring(target)]["mutes"]["mute_inline"] if mute_inline == "yes" then if not lang then return "*Mute Inline* _Is Already Enabled_" elseif lang then return "بیصدا کردن کیبورد شیشه ای فعال است" end else data[tostring(target)]["mutes"]["mute_inline"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Inline* _Has Been Enabled_" else return "بیصدا کردن کیبورد شیشه ای فعال شد" end end end local function unmute_inline(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_inline = data[tostring(target)]["mutes"]["mute_inline"] if mute_inline == "no" then if not lang then return "*Mute Inline* _Is Already Disabled_" elseif lang then return "بیصدا کردن کیبورد شیشه ای غیر فعال است" end else data[tostring(target)]["mutes"]["mute_inline"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Inline* _Has Been Disabled_" else return "بیصدا کردن کیبورد شیشه ای غیر فعال شد" end end end ---------------Mute Text------------------- local function mute_text(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_text = data[tostring(target)]["mutes"]["mute_text"] if mute_text == "yes" then if not lang then return "*Mute Text* _Is Already Enabled_" elseif lang then return "بیصدا کردن متن فعال است" end else data[tostring(target)]["mutes"]["mute_text"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Text* _Has Been Enabled_" else return "بیصدا کردن متن فعال شد" end end end local function unmute_text(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_text = data[tostring(target)]["mutes"]["mute_text"] if mute_text == "no" then if not lang then return "*Mute Text* _Is Already Disabled_" elseif lang then return "بیصدا کردن متن غیر فعال است" end else data[tostring(target)]["mutes"]["mute_text"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Text* _Has Been Disabled_" else return "بیصدا کردن متن غیر فعال شد" end end end ---------------Mute photo------------------- local function mute_photo(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_photo = data[tostring(target)]["mutes"]["mute_photo"] if mute_photo == "yes" then if not lang then return "*Mute Photo* _Is Already Enabled_" elseif lang then return "بیصدا کردن عکس فعال است" end else data[tostring(target)]["mutes"]["mute_photo"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Photo* _Has Been Enabled_" else return "بیصدا کردن عکس فعال شد" end end end local function unmute_photo(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_photo = data[tostring(target)]["mutes"]["mute_photo"] if mute_photo == "no" then if not lang then return "*Mute Photo* _Is Already Disabled_" elseif lang then return "بیصدا کردن عکس غیر فعال است" end else data[tostring(target)]["mutes"]["mute_photo"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Photo* _Has Been Disabled_" else return "بیصدا کردن عکس غیر فعال شد" end end end ---------------Mute Video------------------- local function mute_video(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_video = data[tostring(target)]["mutes"]["mute_video"] if mute_video == "yes" then if not lang then return "*Mute Video* _Is Already Enabled_" elseif lang then return "بیصدا کردن فیلم فعال است" end else data[tostring(target)]["mutes"]["mute_video"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Video* _Has Been Enabled_" else return "بیصدا کردن فیلم فعال شد" end end end local function unmute_video(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_video = data[tostring(target)]["mutes"]["mute_video"] if mute_video == "no" then if not lang then return "*Mute Video* _Is Already Disabled_" elseif lang then return "بیصدا کردن فیلم غیر فعال است" end else data[tostring(target)]["mutes"]["mute_video"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Video* _Has Been Disabled_" else return "بیصدا کردن فیلم غیر فعال شد" end end end ---------------Mute Audio------------------- local function mute_audio(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_audio = data[tostring(target)]["mutes"]["mute_audio"] if mute_audio == "yes" then if not lang then return "*Mute Audio* _Is Already Enabled_" elseif lang then return "بیصدا کردن آهنگ فعال است" end else data[tostring(target)]["mutes"]["mute_audio"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Audio* _Has Been Enabled_" else return "بیصدا کردن آهنگ فعال شد" end end end local function unmute_audio(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_audio = data[tostring(target)]["mutes"]["mute_audio"] if mute_audio == "no" then if not lang then return "*Mute Audio* _Is Already Disabled_" elseif lang then return "بیصدا کردن آهنک غیر فعال است" end else data[tostring(target)]["mutes"]["mute_audio"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Audio* _Has Been Disabled_" else return "بیصدا کردن آهنگ غیر فعال شد" end end end ---------------Mute Voice------------------- local function mute_voice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_voice = data[tostring(target)]["mutes"]["mute_voice"] if mute_voice == "yes" then if not lang then return "*Mute Voice* _Is Already Enabled_" elseif lang then return "بیصدا کردن صدا فعال است" end else data[tostring(target)]["mutes"]["mute_voice"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Voice* _Has Been Enabled_" else return "بیصدا کردن صدا فعال شد" end end end local function unmute_voice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_voice = data[tostring(target)]["mutes"]["mute_voice"] if mute_voice == "no" then if not lang then return "*Mute Voice* _Is Already Disabled_" elseif lang then return "بیصدا کردن صدا غیر فعال است" end else data[tostring(target)]["mutes"]["mute_voice"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Voice* _Has Been Disabled_" else return "بیصدا کردن صدا غیر فعال شد" end end end ---------------Mute Sticker------------------- local function mute_sticker(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_sticker = data[tostring(target)]["mutes"]["mute_sticker"] if mute_sticker == "yes" then if not lang then return "*Mute Sticker* _Is Already Enabled_" elseif lang then return "بیصدا کردن برچسب فعال است" end else data[tostring(target)]["mutes"]["mute_sticker"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Sticker* _Has Been Enabled_" else return "بیصدا کردن برچسب فعال شد" end end end local function unmute_sticker(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_sticker = data[tostring(target)]["mutes"]["mute_sticker"] if mute_sticker == "no" then if not lang then return "*Mute Sticker* _Is Already Disabled_" elseif lang then return "بیصدا کردن برچسب غیر فعال است" end else data[tostring(target)]["mutes"]["mute_sticker"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Sticker* _Has Been Disabled_" else return "بیصدا کردن برچسب غیر فعال شد" end end end ---------------Mute Contact------------------- local function mute_contact(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_contact = data[tostring(target)]["mutes"]["mute_contact"] if mute_contact == "yes" then if not lang then return "*Mute Contact* _Is Already Enabled_" elseif lang then return "بیصدا کردن مخاطب فعال است" end else data[tostring(target)]["mutes"]["mute_contact"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Contact* _Has Been Enabled_" else return "بیصدا کردن مخاطب فعال شد" end end end local function unmute_contact(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_contact = data[tostring(target)]["mutes"]["mute_contact"] if mute_contact == "no" then if not lang then return "*Mute Contact* _Is Already Disabled_" elseif lang then return "بیصدا کردن مخاطب غیر فعال است" end else data[tostring(target)]["mutes"]["mute_contact"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Contact* _Has Been Disabled_" else return "بیصدا کردن مخاطب غیر فعال شد" end end end ---------------Mute Forward------------------- local function mute_forward(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_forward = data[tostring(target)]["mutes"]["mute_forward"] if mute_forward == "yes" then if not lang then return "*Mute Forward* _Is Already Enabled_" elseif lang then return "بیصدا کردن نقل قول فعال است" end else data[tostring(target)]["mutes"]["mute_forward"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Forward* _Has Been Enabled_" else return "بیصدا کردن نقل قول فعال شد" end end end local function unmute_forward(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_forward = data[tostring(target)]["mutes"]["mute_forward"] if mute_forward == "no" then if not lang then return "*Mute Forward* _Is Already Disabled_" elseif lang then return "بیصدا کردن نقل قول غیر فعال است" end else data[tostring(target)]["mutes"]["mute_forward"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Forward* _Has Been Disabled_" else return "بیصدا کردن نقل قول غیر فعال شد" end end end ---------------Mute Location------------------- local function mute_location(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_location = data[tostring(target)]["mutes"]["mute_location"] if mute_location == "yes" then if not lang then return "*Mute Location* _Is Already Enabled_" elseif lang then return "بیصدا کردن موقعیت فعال است" end else data[tostring(target)]["mutes"]["mute_location"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Location* _Has Been Enabled_" else return "بیصدا کردن موقعیت فعال شد" end end end local function unmute_location(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_location = data[tostring(target)]["mutes"]["mute_location"] if mute_location == "no" then if not lang then return "*Mute Location* _Is Already Disabled_" elseif lang then return "بیصدا کردن موقعیت غیر فعال است" end else data[tostring(target)]["mutes"]["mute_location"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Location* _Has Been Disabled_" else return "بیصدا کردن موقعیت غیر فعال شد" end end end ---------------Mute Document------------------- local function mute_document(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_document = data[tostring(target)]["mutes"]["mute_document"] if mute_document == "yes" then if not lang then return "*Mute Document* _Is Already Enabled_" elseif lang then return "بیصدا کردن اسناد فعال لست" end else data[tostring(target)]["mutes"]["mute_document"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Document* _Has Been Enabled_" else return "بیصدا کردن اسناد فعال شد" end end end local function unmute_document(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_document = data[tostring(target)]["mutes"]["mute_document"] if mute_document == "no" then if not lang then return "*Mute Document* _Is Already Disabled_" elseif lang then return "بیصدا کردن اسناد غیر فعال است" end else data[tostring(target)]["mutes"]["mute_document"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Document* _Has Been Disabled_" else return "بیصدا کردن اسناد غیر فعال شد" end end end ---------------Mute TgService------------------- local function mute_tgservice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_tgservice = data[tostring(target)]["mutes"]["mute_tgservice"] if mute_tgservice == "yes" then if not lang then return "*Mute TgService* _Is Already Enabled_" elseif lang then return "بیصدا کردن خدمات تلگرام فعال است" end else data[tostring(target)]["mutes"]["mute_tgservice"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute TgService* _Has Been Enabled_" else return "بیصدا کردن خدمات تلگرام فعال شد" end end end local function unmute_tgservice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local mute_tgservice = data[tostring(target)]["mutes"]["mute_tgservice"] if mute_tgservice == "no" then if not lang then return "*Mute TgService* _Is Already Disabled_" elseif lang then return "بیصدا کردن خدمات تلگرام غیر فعال است" end else data[tostring(target)]["mutes"]["mute_tgservice"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute TgService* _Has Been Disabled_" else return "بیصدا کردن خدمات تلگرام غیر فعال شد" end end end ---------------Mute Keyboard------------------- local function mute_keyboard(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_keyboard = data[tostring(target)]["mutes"]["mute_keyboard"] if mute_keyboard == "yes" then if not lang then return "*Mute Keyboard* _Is Already Enabled_" elseif lang then return "بیصدا کردن صفحه کلید فعال است" end else data[tostring(target)]["mutes"]["mute_keyboard"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Keyboard* _Has Been Enabled_" else return "بیصدا کردن صفحه کلید فعال شد" end end end local function unmute_keyboard(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local mute_keyboard = data[tostring(target)]["mutes"]["mute_keyboard"] if mute_keyboard == "no" then if not lang then return "*Mute Keyboard* _Is Already Disabled_" elseif lang then return "بیصدا کردن صفحه کلید غیرفعال است" end else data[tostring(target)]["mutes"]["mute_keyboard"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute TgService* _Has Been Disabled_" else return "بیصدا کردن صفحه کلید غیرفعال شد" end end end ----------MuteList--------- local function mutes(msg, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local data = load_data(_config.moderation.data) local target = msg.to.id if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_gif"] then data[tostring(target)]["mutes"]["mute_gif"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_text"] then data[tostring(target)]["mutes"]["mute_text"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_photo"] then data[tostring(target)]["mutes"]["mute_photo"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_video"] then data[tostring(target)]["mutes"]["mute_video"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_audio"] then data[tostring(target)]["mutes"]["mute_audio"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_voice"] then data[tostring(target)]["mutes"]["mute_voice"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_sticker"] then data[tostring(target)]["mutes"]["mute_sticker"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_contact"] then data[tostring(target)]["mutes"]["mute_contact"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_forward"] then data[tostring(target)]["mutes"]["mute_forward"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_location"] then data[tostring(target)]["mutes"]["mute_location"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_document"] then data[tostring(target)]["mutes"]["mute_document"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_tgservice"] then data[tostring(target)]["mutes"]["mute_tgservice"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_inline"] then data[tostring(target)]["mutes"]["mute_inline"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_game"] then data[tostring(target)]["mutes"]["mute_game"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_keyboard"] then data[tostring(target)]["mutes"]["mute_keyboard"] = "no" end end local hash = "muteall:"..msg.to.id local check_time = redis:ttl(hash) day = math.floor(check_time / 86400) bday = check_time % 86400 hours = math.floor( bday / 3600) bhours = bday % 3600 min = math.floor(bhours / 60) sec = math.floor(bhours % 60) if not lang then if not redis:get(hash) or check_time == -1 then mute_all1 = 'no' elseif tonumber(check_time) > 1 and check_time < 60 then mute_all1 = '_enable for_ *'..sec..'* _sec_' elseif tonumber(check_time) > 60 and check_time < 3600 then mute_all1 = '_enable for_ '..min..' _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then mute_all1 = '_enable for_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' elseif tonumber(check_time) > 86400 then mute_all1 = '_enable for_ *'..day..'* _day_ *'..hours..'* _hour_ *'..min..'* _min_ *'..sec..'* _sec_' end elseif lang then if not redis:get(hash) or check_time == -1 then mute_all2 = '*no*' elseif tonumber(check_time) > 1 and check_time < 60 then mute_all2 = '_فعال برای_ *'..sec..'* _ثانیه_' elseif tonumber(check_time) > 60 and check_time < 3600 then mute_all2 = '_فعال برای_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه_' elseif tonumber(check_time) > 3600 and tonumber(check_time) < 86400 then mute_all2 = '_فعال برای_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه_' elseif tonumber(check_time) > 86400 then mute_all2 = '_فعال برای_ *'..day..'* _روز و_ *'..hours..'* _ساعت و_ *'..min..'* _دقیقه و_ *'..sec..'* _ثانیه_' end end if not lang then local mutes = data[tostring(target)]["mutes"] text = " *Group Mute List* : \n_Mute gif :_ *"..mutes.mute_gif.."*\n_Mute text :_ *"..mutes.mute_text.."*\n_Mute inline :_ *"..mutes.mute_inline.."*\n_Mute game :_ *"..mutes.mute_game.."*\n_Mute photo :_ *"..mutes.mute_photo.."*\n_Mute video :_ *"..mutes.mute_video.."*\n_Mute audio :_ *"..mutes.mute_audio.."*\n_Mute voice :_ *"..mutes.mute_voice.."*\n_Mute sticker :_ *"..mutes.mute_sticker.."*\n_Mute contact :_ *"..mutes.mute_contact.."*\n_Mute forward :_ *"..mutes.mute_forward.."*\n_Mute location :_ *"..mutes.mute_location.."*\n_Mute document :_ *"..mutes.mute_document.."*\n_Mute TgService :_ *"..mutes.mute_tgservice.."*\n_Mute Keyboard :_ *"..mutes.mute_keyboard.."*\n_Mute All :_ "..mute_all1.."\n*____________________*\n*Bot channel*: \n*Group Language* : *EN*" else local mutes = data[tostring(target)]["mutes"] text = " *لیست بیصدا ها* : \n_بیصدا تصاویر متحرک :_ *"..mutes.mute_gif.."*\n_بیصدا متن :_ *"..mutes.mute_text.."*\n_بیصدا کیبورد شیشه ای :_ *"..mutes.mute_inline.."*\n_بیصدا بازی های تحت وب :_ *"..mutes.mute_game.."*\n_بیصدا عکس :_ *"..mutes.mute_photo.."*\n_بیصدا فیلم :_ *"..mutes.mute_video.."*\n_بیصدا آهنگ :_ *"..mutes.mute_audio.."*\n_بیصدا صدا :_ *"..mutes.mute_voice.."*\n_بیصدا برچسب :_ *"..mutes.mute_sticker.."*\n_بیصدا مخاطب :_ *"..mutes.mute_contact.."*\n_بیصدا نقل قول :_ *"..mutes.mute_forward.."*\n_بیصدا موقعیت :_ *"..mutes.mute_location.."*\n_بیصدا اسناد :_ *"..mutes.mute_document.."*\n_بیصدا خدمات تلگرام :_ *"..mutes.mute_tgservice.."*\n_بیصدا صفحه کلید :_ *"..mutes.mute_keyboard.."*\n_بیصدا همه پیام ها :_ "..mute_all2.."\n*____________________*\n*Bot channel*: \n_زبان سوپرگروه_ : *فارسی*" end text = string.gsub(text, 'yes', '🔇') text = string.gsub(text, 'no', '🔉') return text end local function run(msg, matches) if is_banned(msg.from.id, msg.to.id) or is_gbanned(msg.from.id, msg.to.id) or is_silent_user(msg.from.id, msg.to.id) then return false end local cmd = redis:hget('group:'..msg.to.id..':cmd', 'bot') local mutealll = redis:get('group:'..msg.to.id..':muteall') local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local chat = msg.to.id local user = msg.from.id if cmd == 'moderator' and not is_mod(msg) or cmd == 'owner' and not is_owner(msg) or mutealll and not is_mod(msg) then return else if msg.to.type ~= 'pv' then if matches[1]:lower() == "id" or matches[1] == 'ایدی' then if not matches[2] and not msg.reply_id then local function getpro(arg, data) if data.photos_[0] then if not lang then tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'Chat ID : '..msg.to.id..'\nUser ID : '..msg.from.id,dl_cb,nil) elseif lang then tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'شناسه گروه : '..msg.to.id..'\nشناسه شما : '..msg.from.id,dl_cb,nil) end else if not lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, "`You Have Not Profile Photo...!`\n\n> *Chat ID :* `"..msg.to.id.."`\n*User ID :* `"..msg.from.id.."`", 1, 'md') elseif lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, "_شما هیچ عکسی ندارید...!_\n\n> _شناسه گروه :_ `"..msg.to.id.."`\n_شناسه شما :_ `"..msg.from.id.."`", 1, 'md') end end end tdcli_function ({ ID = "GetUserProfilePhotos", user_id_ = msg.from.id, offset_ = 0, limit_ = 1 }, getpro, nil) end if msg.reply_id and not matches[2] then tdcli.getMessage(msg.to.id, msg.reply_id, action_by_reply, {chat_id=msg.to.id,cmd="id"}) end if matches[2] and #matches[2] > 3 and not matches[3] then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="id"}) end end if (matches[1]:lower() == "pin" or matches[1] == 'سنجاق') and is_mod(msg) and msg.reply_id then local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"] if lock_pin == 'yes' then if is_owner(msg) then data[tostring(chat)]['pin'] = msg.reply_id save_data(_config.moderation.data, data) tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1) if not lang then return "*Message Has Been Pinned*" elseif lang then return "پیام سجاق شد" end elseif not is_owner(msg) then return end elseif lock_pin == 'no' then data[tostring(chat)]['pin'] = msg.reply_id save_data(_config.moderation.data, data) tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1) if not lang then return "*Message Has Been Pinned*" elseif lang then return "پیام سجاق شد" end end end if (matches[1]:lower() == 'unpin' or matches[1] == 'حذف سنجاق') and is_mod(msg) then local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"] if lock_pin == 'yes' then if is_owner(msg) then tdcli.unpinChannelMessage(msg.to.id) if not lang then return "*Pin message has been unpinned*" elseif lang then return "پیام سنجاق شده پاک شد" end elseif not is_owner(msg) then return end elseif lock_pin == 'no' then tdcli.unpinChannelMessage(msg.to.id) if not lang then return "*Pin message has been unpinned*" elseif lang then return "پیام سنجاق شده پاک شد" end end end if matches[1]:lower() == "add" or matches[1] == 'افزودن' then return modadd(msg) end if matches[1]:lower() == "rem" or matches[1] == 'حذف گروه' then return modrem(msg) end if (matches[1]:lower() == "setmanager" or matches[1] == 'ادمین گروه') and is_owner(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="setmanager"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="setmanager"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="setmanager"}) end end if (matches[1]:lower() == "remmanager" or matches[1] == 'حذف ادمین گروه') and is_owner(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="remmanager"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="remmanager"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="remmanager"}) end end if (matches[1]:lower() == "whitelist" or matches[1] == 'لیست سفید') and matches[2] == "+" and is_mod(msg) then if not matches[3] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="setwhitelist"}) end if matches[3] and string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[3], }, action_by_id, {chat_id=msg.to.id,user_id=matches[3],cmd="setwhitelist"}) end if matches[3] and not string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[3] }, action_by_username, {chat_id=msg.to.id,username=matches[3],cmd="setwhitelist"}) end end if (matches[1]:lower() == "whitelist" or matches[1] == 'لیست سفید') and matches[2] == "-" and is_mod(msg) then if not matches[3] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="remwhitelist"}) end if matches[3] and string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[3], }, action_by_id, {chat_id=msg.to.id,user_id=matches[3],cmd="remwhitelist"}) end if matches[3] and not string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[3] }, action_by_username, {chat_id=msg.to.id,username=matches[3],cmd="remwhitelist"}) end end if (matches[1]:lower() == "setowner" or matches[1] == 'مالک') and is_admin(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="setowner"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="setowner"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="setowner"}) end end if (matches[1]:lower() == "remowner" or matches[1] == 'حذف مالک') and is_admin(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="remowner"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="remowner"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="remowner"}) end end if (matches[1]:lower() == "promote" or matches[1] == 'مدیر') and is_owner(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="promote"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="promote"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="promote"}) end end if (matches[1]:lower() == "demote" or matches[1] == 'حذف مدیر') and is_owner(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="demote"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="demote"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="demote"}) end end if (matches[1]:lower() == "lock" or matches[1] == 'قفل') and is_mod(msg) then local target = msg.to.id if not lang then if matches[2] == "link" then return lock_link(msg, data, target) end if matches[2] == "tag" then return lock_tag(msg, data, target) end if matches[2] == "mention" then return lock_mention(msg, data, target) end if matches[2] == "arabic" then return lock_arabic(msg, data, target) end if matches[2] == "edit" then return lock_edit(msg, data, target) end if matches[2] == "spam" then return lock_spam(msg, data, target) end if matches[2] == "flood" then return lock_flood(msg, data, target) end if matches[2] == "bots" then return lock_bots(msg, data, target) end if matches[2] == "markdown" then return lock_markdown(msg, data, target) end if matches[2] == "webpage" then return lock_webpage(msg, data, target) end if matches[2] == "pin" and is_owner(msg) then return lock_pin(msg, data, target) end if matches[2] == "join" then return lock_join(msg, data, target) end if matches[2] == 'cmds' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator') return 'cmds has been locked for member' end else if matches[2] == 'لینک' then return lock_link(msg, data, target) end if matches[2] == 'تگ' then return lock_tag(msg, data, target) end if matches[2] == 'فراخوانی' then return lock_mention(msg, data, target) end if matches[2] == 'عربی' then return lock_arabic(msg, data, target) end if matches[2] == 'ویرایش' then return lock_edit(msg, data, target) end if matches[2] == 'هرزنامه' then return lock_spam(msg, data, target) end if matches[2] == 'پیام مکرر' then return lock_flood(msg, data, target) end if matches[2] == 'ربات' then return lock_bots(msg, data, target) end if matches[2] == 'فونت' then return lock_markdown(msg, data, target) end if matches[2] == 'وب' then return lock_webpage(msg, data, target) end if matches[2] == 'سنجاق' and is_owner(msg) then return lock_pin(msg, data, target) end if matches[2] == "ورود" then return lock_join(msg, data, target) end if matches[2] == 'دستورات' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator') return 'دستورات برای کاربر عادی قفل شد' end end end if (matches[1]:lower() == "unlock" or matches[1] == 'باز') and is_mod(msg) then local target = msg.to.id if not lang then if matches[2] == "link" then return unlock_link(msg, data, target) end if matches[2] == "tag" then return unlock_tag(msg, data, target) end if matches[2] == "mention" then return unlock_mention(msg, data, target) end if matches[2] == "arabic" then return unlock_arabic(msg, data, target) end if matches[2] == "edit" then return unlock_edit(msg, data, target) end if matches[2] == "spam" then return unlock_spam(msg, data, target) end if matches[2] == "flood" then return unlock_flood(msg, data, target) end if matches[2] == "bots" then return unlock_bots(msg, data, target) end if matches[2] == "markdown" then return unlock_markdown(msg, data, target) end if matches[2] == "webpage" then return unlock_webpage(msg, data, target) end if matches[2] == "pin" and is_owner(msg) then return unlock_pin(msg, data, target) end if matches[2] == "join" then return unlock_join(msg, data, target) end if matches[2] == 'cmds' then redis:del('group:'..msg.to.id..':cmd') return 'cmds has been unlocked for member' end else if matches[2] == 'لینک' then return unlock_link(msg, data, target) end if matches[2] == 'تگ' then return unlock_tag(msg, data, target) end if matches[2] == 'فراخوانی' then return unlock_mention(msg, data, target) end if matches[2] == 'عربی' then return unlock_arabic(msg, data, target) end if matches[2] == 'ویرایش' then return unlock_edit(msg, data, target) end if matches[2] == 'هرزنامه' then return unlock_spam(msg, data, target) end if matches[2] == 'پیام مکرر' then return unlock_flood(msg, data, target) end if matches[2] == 'ربات' then return unlock_bots(msg, data, target) end if matches[2] == 'فونت' then return unlock_markdown(msg, data, target) end if matches[2] == 'وب' then return unlock_webpage(msg, data, target) end if matches[2] == 'سنجاق' and is_owner(msg) then return unlock_pin(msg, data, target) end if matches[2] == "ورود" then return unlock_join(msg, data, target) end if matches[2] == 'دستورات' then redis:del('group:'..msg.to.id..':cmd') return 'دستورات برای کاربر عادی باز شد' end end end if (matches[1]:lower() == "mute" or matches[1] == 'بیصدا') and is_mod(msg) then local target = msg.to.id if not lang then if matches[2] == "gif" then return mute_gif(msg, data, target) end if matches[2] == "text" then return mute_text(msg ,data, target) end if matches[2] == "photo" then return mute_photo(msg ,data, target) end if matches[2] == "video" then return mute_video(msg ,data, target) end if matches[2] == "audio" then return mute_audio(msg ,data, target) end if matches[2] == "voice" then return mute_voice(msg ,data, target) end if matches[2] == "sticker" then return mute_sticker(msg ,data, target) end if matches[2] == "contact" then return mute_contact(msg ,data, target) end if matches[2] == "forward" then return mute_forward(msg ,data, target) end if matches[2] == "location" then return mute_location(msg ,data, target) end if matches[2] == "document" then return mute_document(msg ,data, target) end if matches[2] == "tgservice" then return mute_tgservice(msg ,data, target) end if matches[2] == "inline" then return mute_inline(msg ,data, target) end if matches[2] == "game" then return mute_game(msg ,data, target) end if matches[2] == "keyboard" then return mute_keyboard(msg ,data, target) end if matches[2] == 'all' then local hash = 'muteall:'..msg.to.id redis:set(hash, true) return "*Mute All* _has been enabled_" end else if matches[2] == 'تصاویر متحرک' then return mute_gif(msg, data, target) end if matches[2] == 'متن' then return mute_text(msg ,data, target) end if matches[2] == 'عکس' then return mute_photo(msg ,data, target) end if matches[2] == 'فیلم' then return mute_video(msg ,data, target) end if matches[2] == 'اهنگ' then return mute_audio(msg ,data, target) end if matches[2] == 'صدا' then return mute_voice(msg ,data, target) end if matches[2] == 'برچسب' then return mute_sticker(msg ,data, target) end if matches[2] == 'مخاطب' then return mute_contact(msg ,data, target) end if matches[2] == 'نقل قول' then return mute_forward(msg ,data, target) end if matches[2] == 'موقعیت' then return mute_location(msg ,data, target) end if matches[2] == 'اسناد' then return mute_document(msg ,data, target) end if matches[2] == 'خدمات تلگرام' then return mute_tgservice(msg ,data, target) end if matches[2] == 'کیبورد شیشه ای' then return mute_inline(msg ,data, target) end if matches[2] == 'بازی' then return mute_game(msg ,data, target) end if matches[2] == 'صفحه کلید' then return mute_keyboard(msg ,data, target) end if matches[2]== 'همه' then local hash = 'muteall:'..msg.to.id redis:set(hash, true) return "بیصدا کردن گروه فعال شد" end end end if (matches[1]:lower() == "unmute" or matches[1] == 'باصدا') and is_mod(msg) then local target = msg.to.id if not lang then if matches[2] == "gif" then return unmute_gif(msg, data, target) end if matches[2] == "text" then return unmute_text(msg, data, target) end if matches[2] == "photo" then return unmute_photo(msg ,data, target) end if matches[2] == "video" then return unmute_video(msg ,data, target) end if matches[2] == "audio" then return unmute_audio(msg ,data, target) end if matches[2] == "voice" then return unmute_voice(msg ,data, target) end if matches[2] == "sticker" then return unmute_sticker(msg ,data, target) end if matches[2] == "contact" then return unmute_contact(msg ,data, target) end if matches[2] == "forward" then return unmute_forward(msg ,data, target) end if matches[2] == "location" then return unmute_location(msg ,data, target) end if matches[2] == "document" then return unmute_document(msg ,data, target) end if matches[2] == "tgservice" then return unmute_tgservice(msg ,data, target) end if matches[2] == "inline" then return unmute_inline(msg ,data, target) end if matches[2] == "game" then return unmute_game(msg ,data, target) end if matches[2] == "keyboard" then return unmute_keyboard(msg ,data, target) end if matches[2] == 'all' then local hash = 'muteall:'..msg.to.id redis:del(hash) return "*Mute All* _has been disabled_" end else if matches[2] == 'تصاویر متحرک' then return unmute_gif(msg, data, target) end if matches[2] == 'متن' then return unmute_text(msg, data, target) end if matches[2] == 'عکس' then return unmute_photo(msg ,data, target) end if matches[2] == 'فیلم' then return unmute_video(msg ,data, target) end if matches[2] == 'اهنگ' then return unmute_audio(msg ,data, target) end if matches[2] == 'صدا' then return unmute_voice(msg ,data, target) end if matches[2] == 'برچسب' then return unmute_sticker(msg ,data, target) end if matches[2] == 'مخاطب' then return unmute_contact(msg ,data, target) end if matches[2] == 'نقل قول' then return unmute_forward(msg ,data, target) end if matches[2] == 'موقعیت' then return unmute_location(msg ,data, target) end if matches[2] == 'اسناد' then return unmute_document(msg ,data, target) end if matches[2] == 'خدمات تلگرام' then return unmute_tgservice(msg ,data, target) end if matches[2] == 'کیبورد شیشه ای' then return unmute_inline(msg ,data, target) end if matches[2] == 'بازی' then return unmute_game(msg ,data, target) end if matches[2] == 'صفحه کلید' then return unmute_keyboard(msg ,data, target) end if matches[2]=='همه' and is_mod(msg) then local hash = 'muteall:'..msg.to.id redis:del(hash) return "گروه ازاد شد و افراد می توانند دوباره پست بگذارند" end end end if (matches[1]:lower() == 'cmds' or matches[1] == 'دستورات') and is_owner(msg) then if not lang then if matches[2]:lower() == 'owner' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'owner') return 'cmds set for owner or higher' end if matches[2]:lower() == 'moderator' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator') return 'cmds set for moderator or higher' end if matches[2]:lower() == 'member' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'member') return 'cmds set for member or higher' end else if matches[2] == 'مالک' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'owner') return 'دستورات برای مدیرکل به بالا دیگر جواب می دهد' end if matches[2] == 'مدیر' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'moderator') return 'دستورات برای مدیر به بالا دیگر جواب می دهد' end if matches[2] == 'کاربر' then redis:hset('group:'..msg.to.id..':cmd', 'bot', 'member') return 'دستورات برای کاربر عادی به بالا دیگر جواب می دهد' end end end if (matches[1]:lower() == "gpinfo" or matches[1] == 'اطلاعات گروه') and is_mod(msg) and msg.to.type == "channel" then local function group_info(arg, data) if not lang then ginfo = "*Group Info :*\n_Admin Count :_ *"..data.administrator_count_.."*\n_Member Count :_ *"..data.member_count_.."*\n_Kicked Count :_ *"..data.kicked_count_.."*\n_Group ID :_ *"..data.channel_.id_.."*" elseif lang then ginfo = "*اطلاعات گروه :*\n_تعداد مدیران :_ *"..data.administrator_count_.."*\n_تعداد اعضا :_ *"..data.member_count_.."*\n_تعداد اعضای حذف شده :_ *"..data.kicked_count_.."*\n_شناسه گروه :_ *"..data.channel_.id_.."*" end tdcli.sendMessage(arg.chat_id, arg.msg_id, 1, ginfo, 1, 'md') end tdcli.getChannelFull(msg.to.id, group_info, {chat_id=msg.to.id,msg_id=msg.id}) end if (matches[1]:lower() == 'newlink' or matches[1] == 'لینک جدید') and is_mod(msg) and not matches[2] then local function callback_link (arg, data) local administration = load_data(_config.moderation.data) if not data.invite_link_ then administration[tostring(msg.to.id)]['settings']['linkgp'] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_Bot is not group creator_\n_set a link for group with using_ /setlink", 1, 'md') elseif lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_ربات سازنده گروه نیست_\n_با دستور_ setlink/ _لینک جدیدی برای گروه ثبت کنید_", 1, 'md') end else administration[tostring(msg.to.id)]['settings']['linkgp'] = data.invite_link_ save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "*Newlink Created*", 1, 'md') elseif lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_لینک جدید ساخته شد_", 1, 'md') end end end tdcli.exportChatInviteLink(msg.to.id, callback_link, nil) end if (matches[1]:lower() == 'newlink' or matches[1] == 'لینک جدید') and is_mod(msg) and (matches[2] == 'pv' or matches[2] == 'خصوصی') then local function callback_link (arg, data) local result = data.invite_link_ local administration = load_data(_config.moderation.data) if not result then administration[tostring(msg.to.id)]['settings']['linkgp'] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_Bot is not group creator_\n_set a link for group with using_ /setlink", 1, 'md') elseif lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_ربات سازنده گروه نیست_\n_با دستور_ setlink/ _لینک جدیدی برای گروه ثبت کنید_", 1, 'md') end else administration[tostring(msg.to.id)]['settings']['linkgp'] = result save_data(_config.moderation.data, administration) if not lang then tdcli.sendMessage(user, msg.id, 1, "*Newlink Group* _:_ `"..msg.to.id.."`\n"..result, 1, 'md') return tdcli.sendMessage(msg.to.id, msg.id, 1, "*New link Was Send In Your Private Message*", 1, 'md') elseif lang then tdcli.sendMessage(user, msg.id, 1, "*لینک جدید گروه* _:_ `"..msg.to.id.."`\n"..result, 1, 'md') return tdcli.sendMessage(msg.to.id, msg.id, 1, "_لینک جدید ساخته شد و در پیوی شما ارسال شد_", 1, 'md') end end end tdcli.exportChatInviteLink(msg.to.id, callback_link, nil) end if (matches[1]:lower() == 'setlink' or matches[1] == 'تنظیم لینک') and is_owner(msg) then if not matches[2] then data[tostring(chat)]['settings']['linkgp'] = 'waiting' save_data(_config.moderation.data, data) if not lang then return '_Please send the new group_ *link* _now_' else return 'لطفا لینک گروه خود را ارسال کنید' end end data[tostring(chat)]['settings']['linkgp'] = matches[2] save_data(_config.moderation.data, data) if not lang then return '_Group Link Was Saved Successfully._' else return 'لینک گروه شما با موفقیت ذخیره شد' end end if msg.text then local is_link = msg.text:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.text:match("^([https?://w]*.?t.me/joinchat/%S+)$") if is_link and data[tostring(chat)]['settings']['linkgp'] == 'waiting' and is_owner(msg) then data[tostring(chat)]['settings']['linkgp'] = msg.text save_data(_config.moderation.data, data) if not lang then return "*Newlink* _has been set_" else return "لینک جدید ذخیره شد" end end end if (matches[1]:lower() == 'link' or matches[1] == 'لینک') and is_mod(msg) and not matches[2] then local linkgp = data[tostring(chat)]['settings']['linkgp'] if not linkgp then if not lang then return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink" else return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید" end end if not lang then text = "<b>Group Link :</b>\n"..linkgp else text = "<b>لینک گروه :</b>\n"..linkgp end return tdcli.sendMessage(chat, msg.id, 1, text, 1, 'html') end if (matches[1]:lower() == 'link' or matches[1] == 'لینک') and (matches[2] == 'pv' or matches[2] == 'خصوصی') then if is_mod(msg) then local linkgp = data[tostring(chat)]['settings']['linkgp'] if not linkgp then if not lang then return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink" else return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید" end end if not lang then tdcli.sendMessage(chat, msg.id, 1, "<b>link Was Send In Your Private Message</b>", 1, 'html') tdcli.sendMessage(user, "", 1, "<b>Group Link "..msg.to.title.." :</b>\n"..linkgp, 1, 'html') else tdcli.sendMessage(chat, msg.id, 1, "<b>لینک گروه در پیوی شما ارسال شد</b>", 1, 'html') tdcli.sendMessage(user, "", 1, "<b>لینک گروه "..msg.to.title.." :</b>\n"..linkgp, 1, 'html') end end end if (matches[1]:lower() == "setrules" or matches[1] == 'تنظیم قوانین') and matches[2] and is_mod(msg) then data[tostring(chat)]['rules'] = matches[2] save_data(_config.moderation.data, data) if not lang then return "*Group rules* _has been set_" else return "قوانین گروه ثبت شد" end end if matches[1]:lower() == "rules" or matches[1] == 'قوانین' then if not data[tostring(chat)]['rules'] then if not lang then rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n " elseif lang then rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n " end else rules = "*Group Rules :*\n"..data[tostring(chat)]['rules'] end return rules end if (matches[1]:lower() == "res" or matches[1] == 'کاربری') and matches[2] and is_mod(msg) then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="res"}) end if (matches[1]:lower() == "whois" or matches[1] == 'شناسه') and matches[2] and string.match(matches[2], '^%d+$') and is_mod(msg) then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="whois"}) end if matches[1]:lower() == 'setchar' or matches[1]:lower() == 'حداکثر حروف مجاز' then if not is_mod(msg) then return end local chars_max = matches[2] data[tostring(msg.to.id)]['settings']['set_char'] = chars_max save_data(_config.moderation.data, data) if not lang then return "*Character sensitivity* _has been set to :_ *[ "..matches[2].." ]*" else return "_حداکثر حروف مجاز در پیام تنظیم شد به :_ *[ "..matches[2].." ]*" end end if (matches[1]:lower() == 'setflood' or matches[1] == 'تنظیم پیام مکرر') and is_mod(msg) then if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 50 then return "_Wrong number, range is_ *[2-50]*" end local flood_max = matches[2] data[tostring(chat)]['settings']['num_msg_max'] = flood_max save_data(_config.moderation.data, data) if not lang then return "_Group_ *flood* _sensitivity has been set to :_ *[ "..matches[2].." ]*" else return '_محدودیت پیام مکرر به_ *'..tonumber(matches[2])..'* _تنظیم شد._' end end if (matches[1]:lower() == 'setfloodtime' or matches[1] == 'تنظیم زمان بررسی') and is_mod(msg) then if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 10 then return "_Wrong number, range is_ *[2-10]*" end local time_max = matches[2] data[tostring(chat)]['settings']['time_check'] = time_max save_data(_config.moderation.data, data) if not lang then return "_Group_ *flood* _check time has been set to :_ *[ "..matches[2].." ]*" else return "_حداکثر زمان بررسی پیام های مکرر تنظیم شد به :_ *[ "..matches[2].." ]*" end end if (matches[1]:lower() == 'clean' or matches[1] == 'پاک کردن') and is_owner(msg) then if not lang then if matches[2] == 'mods' then if next(data[tostring(chat)]['mods']) == nil then return "_No_ *moderators* _in this group_" end for k,v in pairs(data[tostring(chat)]['mods']) do data[tostring(chat)]['mods'][tostring(k)] = nil save_data(_config.moderation.data, data) end return "_All_ *moderators* _has been demoted_" end if matches[2] == 'filterlist' then if next(data[tostring(chat)]['filterlist']) == nil then return "*Filtered words list* _is empty_" end for k,v in pairs(data[tostring(chat)]['filterlist']) do data[tostring(chat)]['filterlist'][tostring(k)] = nil save_data(_config.moderation.data, data) end return "*Filtered words list* _has been cleaned_" end if matches[2] == 'rules' then if not data[tostring(chat)]['rules'] then return "_No_ *rules* _available_" end data[tostring(chat)]['rules'] = nil save_data(_config.moderation.data, data) return "*Group rules* _has been cleaned_" end if matches[2] == 'welcome' then if not data[tostring(chat)]['setwelcome'] then return "*Welcome Message not set*" end data[tostring(chat)]['setwelcome'] = nil save_data(_config.moderation.data, data) return "*Welcome message* _has been cleaned_" end if matches[2] == 'about' then if msg.to.type == "chat" then if not data[tostring(chat)]['about'] then return "_No_ *description* _available_" end data[tostring(chat)]['about'] = nil save_data(_config.moderation.data, data) elseif msg.to.type == "channel" then tdcli.changeChannelAbout(chat, "", dl_cb, nil) end return "*Group description* _has been cleaned_" end else if matches[2] == 'مدیران' then if next(data[tostring(chat)]['mods']) == nil then return "هیچ مدیری برای گروه انتخاب نشده است" end for k,v in pairs(data[tostring(chat)]['mods']) do data[tostring(chat)]['mods'][tostring(k)] = nil save_data(_config.moderation.data, data) end return "تمام مدیران گروه تنزیل مقام شدند" end if matches[2] == 'لیست فیلتر' then if next(data[tostring(chat)]['filterlist']) == nil then return "_لیست کلمات فیلتر شده خالی است_" end for k,v in pairs(data[tostring(chat)]['filterlist']) do data[tostring(chat)]['filterlist'][tostring(k)] = nil save_data(_config.moderation.data, data) end return "_لیست کلمات فیلتر شده پاک شد_" end if matches[2] == 'قوانین' then if not data[tostring(chat)]['rules'] then return "قوانین برای گروه ثبت نشده است" end data[tostring(chat)]['rules'] = nil save_data(_config.moderation.data, data) return "قوانین گروه پاک شد" end if matches[2] == 'خوشآمد' then if not data[tostring(chat)]['setwelcome'] then return "پیام خوشآمد گویی ثبت نشده است" end data[tostring(chat)]['setwelcome'] = nil save_data(_config.moderation.data, data) return "پیام خوشآمد گویی پاک شد" end if matches[2] == 'درباره' then if msg.to.type == "chat" then if not data[tostring(chat)]['about'] then return "پیامی مبنی بر درباره گروه ثبت نشده است" end data[tostring(chat)]['about'] = nil save_data(_config.moderation.data, data) elseif msg.to.type == "channel" then tdcli.changeChannelAbout(chat, "", dl_cb, nil) end return "پیام مبنی بر درباره گروه پاک شد" end end end if (matches[1]:lower() == 'clean' or matches[1] == 'پاک کردن') and is_admin(msg) then if not lang then if matches[2] == 'owners' then if next(data[tostring(chat)]['owners']) == nil then return "_No_ *owners* _in this group_" end for k,v in pairs(data[tostring(chat)]['owners']) do data[tostring(chat)]['owners'][tostring(k)] = nil save_data(_config.moderation.data, data) end return "_All_ *owners* _has been demoted_" end else if matches[2] == 'مالکان' then if next(data[tostring(chat)]['owners']) == nil then return "مالکی برای گروه انتخاب نشده است" end for k,v in pairs(data[tostring(chat)]['owners']) do data[tostring(chat)]['owners'][tostring(k)] = nil save_data(_config.moderation.data, data) end return "تمامی مالکان گروه تنزیل مقام شدند" end end end if (matches[1]:lower() == "setname" or matches[1] == 'تنظیم نام') and matches[2] and is_mod(msg) then local gp_name = matches[2] tdcli.changeChatTitle(chat, gp_name, dl_cb, nil) end if (matches[1]:lower() == "setabout" or matches[1] == 'تنظیم درباره') and matches[2] and is_mod(msg) then if msg.to.type == "channel" then tdcli.changeChannelAbout(chat, matches[2], dl_cb, nil) elseif msg.to.type == "chat" then data[tostring(chat)]['about'] = matches[2] save_data(_config.moderation.data, data) end if not lang then return "*Group description* _has been set_" else return "پیام مبنی بر درباره گروه ثبت شد" end end if matches[1]:lower() == "about" or matches[1] == 'درباره' and msg.to.type == "chat" then if not data[tostring(chat)]['about'] then if not lang then about = "_No_ *description* _available_" elseif lang then about = "پیامی مبنی بر درباره گروه ثبت نشده است" end else about = "*Group Description :*\n"..data[tostring(chat)]['about'] end return about end if (matches[1]:lower() == 'filter' or matches[1] == 'فیلتر') and is_mod(msg) then return filter_word(msg, matches[2]) end if (matches[1]:lower() == 'unfilter' or matches[1] == 'حذف فیلتر') and is_mod(msg) then return unfilter_word(msg, matches[2]) end if (matches[1]:lower() == 'config' or matches[1] == 'پیکربندی') and is_admin(msg) then tdcli.getChannelMembers(msg.to.id, 0, 'Administrators', 200, config_cb, {chat_id=msg.to.id}) end if (matches[1]:lower() == 'filterlist' or matches[1] == 'لیست فیلتر') and is_mod(msg) then return filter_list(msg) end if (matches[1]:lower() == "modlist" or matches[1] == 'لیست مدیران') and is_mod(msg) then return modlist(msg) end if (matches[1]:lower() == "whitelist" or matches[1] == 'لیست سفید') and not matches[2] and is_mod(msg) then return whitelist(msg.to.id) end if (matches[1]:lower() == "ownerlist" or matches[1] == 'لیست مالکان') and is_owner(msg) then return ownerlist(msg) end if (matches[1]:lower() == "settings" or matches[1] == 'تنظیمات') and is_mod(msg) then return group_settings(msg, target) end if (matches[1]:lower() == "mutelist" or matches[1] == 'لیست بیصدا') and is_mod(msg) then return mutes(msg, target) end if matches[1]:lower() == "setlang" and is_owner(msg) then local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if matches[2] == "fa" then redis:set(hash, true) return "*زبان گروه تنظیم شد به : فارسی*"..BDRpm end end if matches[1] == 'زبان انگلیسی' then local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) redis:del(hash) return "_Group Language Set To:_ EN"..BDRpm end if (matches[1] == 'mutetime' or matches[1] == 'زمان بیصدا') and is_mod(msg) then local hash = 'muteall:'..msg.to.id local hour = tonumber(matches[2]) local num1 = (tonumber(hour) * 3600) local minutes = tonumber(matches[3]) local num2 = (tonumber(minutes) * 60) local second = tonumber(matches[4]) local num3 = tonumber(second) local num4 = tonumber(num1 + num2 + num3) redis:setex(hash, num4, true) if not lang then return "_Mute all has been enabled for_ \n⏺ *hours :* `"..matches[2].."`\n⏺ *minutes :* `"..matches[3].."`\n⏺ *seconds :* `"..matches[4].."`"..BDRpm elseif lang then return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[2].."\n⏺ دقیقه : "..matches[3].."\n⏺ ثانیه : "..matches[4]..BDRpm end end if (matches[1] == 'mutehours' or matches[1]== 'ساعت بیصدا') and is_mod(msg) then local hash = 'muteall:'..msg.to.id local hour = matches[2] local num1 = tonumber(hour) * 3600 local num4 = tonumber(num1) redis:setex(hash, num4, true) if not lang then return "Mute all has been enabled for \n⏺ hours : "..matches[2]..BDRpm elseif lang then return "بی صدا کردن فعال شد در \n⏺ ساعت : "..matches[2]..BDRpm end end if (matches[1] == 'muteminutes' or matches[1]== 'دقیقه بیصدا') and is_mod(msg) then local hash = 'muteall:'..msg.to.id local minutes = matches[2] local num2 = tonumber(minutes) * 60 local num4 = tonumber(num2) redis:setex(hash, num4, true) if not lang then return "Mute all has been enabled for \n⏺ minutes : "..matches[2]..BDRpm elseif lang then return "بی صدا کردن فعال شد در \n⏺ دقیقه : "..matches[2]..BDRpm end end if (matches[1] == 'muteseconds' or matches[1] == 'ثانیه بیصدا') and is_mod(msg) then local hash = 'muteall:'..msg.to.id local second = matches[2] local num3 = tonumber(second) local num4 = tonumber(num3) redis:setex(hash, num3, true) if not lang then return "Mute all has been enabled for \n⏺ seconds : "..matches[2]..BDRpm elseif lang then return "بی صدا کردن فعال شد در \n⏺ ثانیه : "..matches[2]..BDRpm end end if (matches[1] == 'muteall' or matches[1] == 'موقعیت') and (matches[2] == 'status' or matches[2] == 'بیصدا') and is_mod(msg) then local hash = 'muteall:'..msg.to.id local mute_time = redis:ttl(hash) if tonumber(mute_time) < 0 then if not lang then return '_Mute All is Disable._' else return '_بیصدا بودن گروه غیر فعال است._' end else if not lang then return mute_time.." Sec" elseif lang then return mute_time.."ثانیه" end end end if (matches[1]:lower() == "help" or matches[1] == 'راهنما') and is_mod(msg) then if not lang then text = [[ *Beyond Bot Commands:* *!setmanager* `[username|id|reply]` _Add User To Group Admins(CreatorBot)_ *!Remmanager* `[username|id|reply]` _Remove User From Owner List(CreatorBot)_ *!setowner* `[username|id|reply]` _Set Group Owner(Multi Owner)_ *!remowner* `[username|id|reply]` _Remove User From Owner List_ *!promote* `[username|id|reply]` _Promote User To Group Admin_ *!demote* `[username|id|reply]` _Demote User From Group Admins List_ *!setflood* `[2-50]` _Set Flooding Number_ *!silent* `[username|id|reply]` _Silent User From Group_ *!unsilent* `[username|id|reply]` _Unsilent User From Group_ *!kick* `[username|id|reply]` _Kick User From Group_ *!ban* `[username|id|reply]` _Ban User From Group_ *!unban* `[username|id|reply]` _UnBan User From Group_ *!res* `[username]` _Show User ID_ *!id* `[reply]` _Show User ID_ *!whois* `[id]` _Show User's Username And Name_ *!lock* `[link | join | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin | cmds]` _If This Actions Lock, Bot Check Actions And Delete Them_ *!unlock* `[link | join | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin | cmds]` _If This Actions Unlock, Bot Not Delete Them_ *!mute* `[all | gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]` _If This Actions Lock, Bot Check Actions And Delete Them_ *!mutetime* `(hour) (minute) (seconds)` _Mute group at this time_ *!mutehours* `(number)` _Mute group at this time_ *!muteminutes* `(number)` _Mute group at this time_ *!muteseconds* `(number)` _Mute group at this time_ *!unmute* `[all | gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]` _If This Actions Unlock, Bot Not Delete Them_ *!set*`[rules | name | link | about | welcome]` _Bot Set Them_ *!clean* `[bans | mods | bots | rules | about | silentlist | filtelist | welcome]` _Bot Clean Them_ *!filter* `[word]` _Word filter_ *!unfilter* `[word]` _Word unfilter_ *!pin* `[reply]` _Pin Your Message_ *!unpin* _Unpin Pinned Message_ *!welcome enable/disable* _Enable Or Disable Group Welcome_ *!settings* _Show Group Settings_ *!cmds* `[member | moderator | owner]` _set cmd_ *!mutelist* _Show Mutes List_ *!whitelist* `[+ | -]` _Add User To White List_ *!silentlist* _Show Silented Users List_ *!filterlist* _Show Filtered Words List_ *!banlist* _Show Banned Users List_ *!ownerlist* _Show Group Owners List_ *!whitelist* _Show Group whitelist List_ *!modlist* _Show Group Moderators List_ *!rules* _Show Group Rules_ *!about* _Show Group Description_ *!id* _Show Your And Chat ID_ *!gpinfo* _Show Group Information_ *!newlink* _Create A New Link_ *!newlink pv* _Create A New Link The Pv_ *!link* _Show Group Link_ *!link pv* _Send Group Link In Your Private Message_ *!setlang fa* _Set Persian Language_ *!setwelcome [text]* _set Welcome Message_ *!helptools* _Show Tools Help_ *!helpfun* _Show Fun Help_ *!helpmute* _Show mute Help_ _You Can Use_ *[!/#]* _To Run The Commands_ _This Help List Only For_ *Moderators/Owners!* _Its Means, Only Group_ *Moderators/Owners* _Can Use It!_ *Good luck ;)*]] elseif lang then text = [[ *دستورات ربات بیوند:* *ادمین گروه* `[username|id|reply]` _افزودن ادمین گروه(درصورت اینکه ربات سازنده گروه)_ *حذف ادمین گروه* `[username|id|reply]` _حذف ادمین گروه(درصورت اینکه ربات سازنده گروه)_ *مالک* `[username|id|reply]` _انتخاب مالک گروه(قابل انتخاب چند مالک)_ *حذف مالک* `[username|id|reply]` _حذف کردن فرد از فهرست مالکان گروه_ *مدیر* `[username|id|reply]` _ارتقا مقام کاربر به مدیر گروه_ *حذف مدیر* `[username|id|reply]` _تنزیل مقام مدیر به کاربر_ *تنظیم پیام مکرر* `[2-50]` _تنظیم حداکثر تعداد پیام مکرر_ *سکوت* `[username|id|reply]` _بیصدا کردن کاربر در گروه_ *!حذف سکوت* `[username|id|reply]` _در آوردن کاربر از حالت بیصدا در گروه_ *!اخراج* `[username|id|reply]` _حذف کاربر از گروه_ *!بن* `[username|id|reply]` _مسدود کردن کاربر از گروه_ *!حذف بن* `[username|id|reply]` _در آوردن از حالت مسدودیت کاربر از گروه_ *کاربری* `[username]` _نمایش شناسه کاربر_ *ایدی* `[reply]` _نمایش شناسه کاربر_ *شناسه* `[id]` _نمایش نام کاربر, نام کاربری و اطلاعات حساب_ *قفل* `[لینک | ورود | تگ | ویرایش | عربی | وب | ربات |هرزنامه | پیام مکرر | فونت | فراخوانی | سنجاق]` _در صورت قفل بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_ *باز* `[لینک | ورود | تگ | ویرایش | عربی | وب | ربات |هرزنامه | پیام مکرر | فونت | فراخوانی | سنجاق]` _در صورت قفل نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_ *بیصدا* `[همه | تصاویر متحرک | عکس | اسناد | برچسب | صفحه کلید | فیلم | متن | نقل قول | موقعیت | اهنگ | صدا | مخاطب | کیبورد شیشه ای|بازی|خدمات تلگرام|]` _در صورت بیصدد بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_ *زمان بیصدا* `(ساعت) (دقیقه) (ثانیه)` _بیصدا کردن گروه با ساعت و دقیقه و ثانیه_ *ساعت بیصدا* `(عدد)` _بیصدا کردن گروه در ساعت_ *دقیقه بیصدا* `(عدد)` _بیصدا کردن گروه در دقیقه_ *ثانیه بیصدا* `(عدد)` _بیصدا کردن گروه در ثانیه_ *باصدا* `[همه | تصاویر متحرک | عکس | اسناد | برچسب | صفحه کلید | فیلم | متن | نقل قول | موقعیت | اهنگ | صدا | مخاطب | کیبورد شیشه ای|بازی|خدمات تلگرام|]` _در صورت بیصدا نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_ *تنظیم*`[قوانین | نام | لینک | درباره | خوشآمد]` _ربات آنهارا ثبت خواهد کرد_ *پاک کردن* `[بن | مدیران | ربات | قوانین | درباره | لیست سکوت | خوشآمد]` _ربات آنهارا پاک خواهد کرد_ *لیست سفید* `[+|-]` _افزودن افراد به لیست سفید_ *فیلتر* `[کلمه]` _فیلتر‌کلمه مورد نظر_ *حذف فیلتر* `[کلمه]` _ازاد کردن کلمه مورد نظر_ *سنجاق* `[reply]` _ربات پیام شمارا در گروه سنجاق خواهد کرد_ *حذف سنجاق* _ربات پیام سنجاق شده در گروه را حذف خواهد کرد_ *!خوشآمد فعال/غیرفعال* _فعال یا غیرفعال کردن خوشآمد گویی_ *تنظیمات* _نمایش تنظیمات گروه_ *دستورات* `[کاربر | مدیر | مالک]` _نتخاب کردن قفل cmd بر چه مدیریتی_ *لیست بیصدا* _نمایش فهرست بیصدا های گروه_ *لیست بیصدا* _نمایش فهرست افراد بیصدا_ *فیلتر لیست* _نمایش لیست کلمات فیلتر شده_ *لیست سفید* _نمایش افراد سفید شده از گروه_ *لیست بن* _نمایش افراد مسدود شده از گروه_ *لیست مالکان* _نمایش فهرست مالکان گروه_ *لیست مدیران* _نمایش فهرست مدیران گروه_ *قوانین* _نمایش قوانین گروه_ *درباره* _نمایش درباره گروه_ *ایدی* _نمایش شناسه شما و گروه_ *اطلاعات گروه* _نمایش اطلاعات گروه_ *لینک جدید* _ساخت لینک جدید_ *لینک جدید خصوصی* _ساخت لینک جدید در پیوی_ *لینک* _نمایش لینک گروه_ *لینک خصوصی* _ارسال لینک گروه به چت خصوصی شما_ *زبان انگلیسی* _تنظیم زبان انگلیسی_ *!تنظیم خوشآمد [متن]* _ثبت پیام خوش آمد گویی_ *!راهنما ابزار* _نمایش راهنمای ابزار_ *!راهنما سرگرمی* _نمایش راهنمای سرگرمی_ *!راهنما بیصدا* _نمایش دستورات بیصدا های گروه_ _این راهنما فقط برای مدیران/مالکان گروه میباشد! این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_ *موفق باشید ;)*]] end return text end --------------------- Welcome ----------------------- if (matches[1]:lower() == "welcome" or matches[1] == 'خوشآمد') and is_mod(msg) then if not lang then if matches[2] == "enable" then welcome = data[tostring(chat)]['settings']['welcome'] if welcome == "yes" then return "_Group_ *welcome* _is already enabled_" else data[tostring(chat)]['settings']['welcome'] = "yes" save_data(_config.moderation.data, data) return "_Group_ *welcome* _has been enabled_" end end if matches[2] == "disable" then welcome = data[tostring(chat)]['settings']['welcome'] if welcome == "no" then return "_Group_ *Welcome* _is already disabled_" else data[tostring(chat)]['settings']['welcome'] = "no" save_data(_config.moderation.data, data) return "_Group_ *welcome* _has been disabled_" end end else if matches[2] == "فعال" then welcome = data[tostring(chat)]['settings']['welcome'] if welcome == "yes" then return "_خوشآمد گویی از قبل فعال بود_" else data[tostring(chat)]['settings']['welcome'] = "yes" save_data(_config.moderation.data, data) return "_خوشآمد گویی فعال شد_" end end if matches[2] == "غیرفعال" then welcome = data[tostring(chat)]['settings']['welcome'] if welcome == "no" then return "_خوشآمد گویی از قبل فعال نبود_" else data[tostring(chat)]['settings']['welcome'] = "no" save_data(_config.moderation.data, data) return "_خوشآمد گویی غیرفعال شد_" end end end end if (matches[1]:lower() == "setwelcome" or matches[1] == 'تنظیم خوشآمد') and matches[2] and is_mod(msg) then data[tostring(chat)]['setwelcome'] = matches[2] save_data(_config.moderation.data, data) if not lang then return "_Welcome Message Has Been Set To :_\n*"..matches[2].."*\n\n*You can use :*\n_{gpname} Group Name_\n_{rules} ➣ Show Group Rules_\n_{time} ➣ Show time english _\n_{date} ➣ Show date english _\n_{timefa} ➣ Show time persian _\n_{datefa} ➣ show date persian _\n_{name} ➣ New Member First Name_\n_{username} ➣ New Member Username_" else return "_پیام خوشآمد گویی تنظیم شد به :_\n*"..matches[2].."*\n\n*شما میتوانید از*\n_{gpname} نام گروه_\n_{rules} ➣ نمایش قوانین گروه_\n_{time} ➣ ساعت به زبان انگلیسی _\n_{date} ➣ تاریخ به زبان انگلیسی _\n_{timefa} ➣ ساعت به زبان فارسی _\n_{datefa} ➣ تاریخ به زبان فارسی _\n_{name} ➣ نام کاربر جدید_\n_{username} ➣ نام کاربری کاربر جدید_\n_استفاده کنید_" end end end end end local checkmod = true ----------------------------------------- local function pre_process(msg) local chat = msg.to.id local user = msg.from.id local hash = "gp_lang:"..chat local lang = redis:get(hash) local data = load_data(_config.moderation.data) if checkmod and msg.text and msg.to.type == 'channel' then tdcli.getChannelMembers(msg.to.id, 0, 'Administrators', 200, function(a, b) local secchk = true checkmod = false for k,v in pairs(b.members_) do if v.user_id_ == tonumber(our_id) then secchk = false end end if secchk then checkmod = false if not lang then return tdcli.sendMessage(msg.to.id, 0, 1, '_Robot isn\'t Administrator, Please promote to Admin!_', 1, "md") else return tdcli.sendMessage(msg.to.id, 0, 1, '_لطفا برای کارکرد کامل دستورات، ربات را به مدیر گروه ارتقا دهید._', 1, "md") end end end, nil) end local function welcome_cb(arg, data) local url , res = http.request('http://irapi.ir/time/') if res ~= 200 then return "No connection" end local jdat = json:decode(url) administration = load_data(_config.moderation.data) if administration[arg.chat_id]['setwelcome'] then welcome = administration[arg.chat_id]['setwelcome'] else if not lang then welcome = "*Welcome Dude*" elseif lang then welcome = "_خوش آمدید_" end end if administration[tostring(arg.chat_id)]['rules'] then rules = administration[arg.chat_id]['rules'] else if not lang then rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n " elseif lang then rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n " end end if data.username_ then user_name = " "..check_markdown(data.username_) else user_name = "" end local welcome = welcome:gsub("{rules}", rules) local welcome = welcome:gsub("{name}", check_markdown(data.first_name_..' '..(data.last_name_ or ''))) local welcome = welcome:gsub("{username}", user_name) local welcome = welcome:gsub("{time}", jdat.ENtime) local welcome = welcome:gsub("{date}", jdat.ENdate) local welcome = welcome:gsub("{timefa}", jdat.FAtime) local welcome = welcome:gsub("{datefa}", jdat.FAdate) local welcome = welcome:gsub("{gpname}", arg.gp_name) tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, welcome, 0, "md") end if data[tostring(chat)] and data[tostring(chat)]['settings'] then if msg.adduser then welcome = data[tostring(msg.to.id)]['settings']['welcome'] if welcome == "yes" then tdcli.getUser(msg.adduser, welcome_cb, {chat_id=chat,msg_id=msg.id_,gp_name=msg.to.title}) else return false end end if msg.joinuser then welcome = data[tostring(msg.to.id)]['settings']['welcome'] if welcome == "yes" then tdcli.getUser(msg.sender_user_id_, welcome_cb, {chat_id=chat,msg_id=msg.id_,gp_name=msg.to.title}) else return false end end end return msg end return { patterns ={ command .. "([Ii]d)$", command .. "([Aa]dd)$", command .. "([Rr]em)$", command .. "([Ii]d) (.*)$", command .. "([Pp]in)$", command .. "([Uu]npin)$", command .. "([Gg]pinfo)$", command .. "([Ss]etmanager)$", command .. "([Ss]etmanager) (.*)$", command .. "([Rr]emmanager)$", command .. "([Rr]emmanager) (.*)$", command .. "([Ww]hitelist) ([+-])$", command .. "([Ww]hitelist) ([+-]) (.*)$", command .. "([Ww]hitelist)$", command .. "([Ss]etowner)$", command .. "([Ss]etowner) (.*)$", command .. "([Rr]emowner)$", command .. "([Rr]emowner) (.*)$", command .. "([Pp]romote)$", command .. "([Pp]romote) (.*)$", command .. "([Dd]emote)$", command .. "([Dd]emote) (.*)$", command .. "([Mm]odlist)$", command .. "([Oo]wnerlist)$", command .. "([Ll]ock) (.*)$", command .. "([Uu]nlock) (.*)$", command .. "([Mm]ute) (.*)$", command .. "([Uu]nmute) (.*)$", command .. "([Ll]ink)$", command .. "([Ll]ink) (pv)$", command .. "([Ss]etlink)$", command .. "([Ss]etlink) ([https?://w]*.?telegram.me/joinchat/%S+)$", command .. "([Ss]etlink) ([https?://w]*.?t.me/joinchat/%S+)$", command .. "([Nn]ewlink)$", command .. "([Nn]ewlink) (pv)$", command .. "([Rr]ules)$", command .. "([Ss]ettings)$", command .. "([Mm]utelist)$", command .. "([Ss]etrules) (.*)$", command .. "([Aa]bout)$", command .. "([Ss]etabout) (.*)$", command .. "([Ss]etname) (.*)$", command .. "([Cc]lean) (.*)$", command .. "([Ss]etflood) (%d+)$", command .. "([Ss]etchar) (%d+)$", command .. "([Ss]etfloodtime) (%d+)$", command .. "([Rr]es) (.*)$", command .. "([Cc]mds) (.*)$", command .. "([Ww]hois) (%d+)$", command .. "([Hh]elp)$", command .. "([Ss]etlang) (fa)$", command .. "([Ff]ilter) (.*)$", command .. "([Uu]nfilter) (.*)$", command .. "([Ff]ilterlist)$", command .. "([Cc]onfig)$", command .. "([Ss]etwelcome) (.*)", command .. "([Ww]elcome) (.*)$", command .. '([Mm]uteall) (status)$', command .. '([Hh]elpmute)$', command .. '([Mm]utetime) (%d+) (%d+) (%d+)$', command .. '([Mm]utehours) (%d+)$', command .. '([Mm]uteminutes) (%d+)$', command .. '([Mm]uteseconds) (%d+)$', "^([https?://w]*.?telegram.me/joinchat/%S+)$", "^([https?://w]*.?t.me/joinchat/%S+)$", "^([Ii][Dd])$", "^([Aa][Dd][Dd])$", "^([Rr][Ee][Mm])$", "^([Ii][Dd]) (.*)$", "^([Pp][Ii][Nn])$", "^([Uu][Nn][Pp][Ii][Nn])$", "^([Gg][Pp][Ii][Nn][Ff][Oo])$", "^([Ss][Ee][Tt][Mm][Aa][Nn][Aa][Gg][Ee][Rr])$", "^([Ss][Ee][Tt][Mm][Aa][Nn][Aa][Gg][Ee][Rr]) (.*)$", "^([Rr][Ee][Mm][Mm][Aa][Nn][Aa][Gg][Ee][Rr])$", "^([Rr][Ee][Mm][Mm][Aa][Nn][Aa][Gg][Ee][Rr]) (.*)$", "^([Ww][Hh][Ii][Tt][Ee][Ll][Ii][Ss][Tt]) ([+-])$", "^([Ww][Hh][Ii][Tt][Ee][Ll][Ii][Ss][Tt]) ([+-]) (.*)$", "^([Ww][Hh][Ii][Tt][Ee][Ll][Ii][Ss][Tt])$", "^([Ss][Ee][Tt][Oo][Ww][Nn][Ee][Rr])$", "^([Ss][Ee][Tt][Oo][Ww][Nn][Ee][Rr]) (.*)$", "^([Rr][Ee][Mm][Oo][Ww][Nn][Ee][Rr])$", "^([Rr][Ee][Mm][Oo][Ww][Nn][Ee][Rr]) (.*)$", "^([Pp][Rr][Oo][Mm][Oo][Tt][Ee])$", "^([Pp][Rr][Oo][Mm][Oo][Tt][Ee]) (.*)$", "^([Dd][Ee][Mm][Oo][Tt][Ee])$", "^([Dd][Ee][Mm][Oo][Tt][Ee]) (.*)$", "^([Mm][Oo][Dd][Ll][Ii][Ss][Tt])$", "^([Oo][Ww][Nn][Ee][Rr][Ll][Ii][Ss][Tt])$", "^([Ll][Oo][Cc][Kk]) (.*)$", "^([Uu][Nn][Ll][Oo][Cc][Kk]) (.*)$", "^([Mm][Uu][Tt][Ee]) (.*)$", "^([Uu][Nn][Mm][Uu][Tt][Ee]) (.*)$", "^([Ll][Ii][Nn][Kk])$", "^([Ll][Ii][Nn][Kk]) (pv)$", "^([Ss][Ee][Tt][Ll][Ii][Nn][Kk])$", "^([Ss][Ee][Tt][Ll][Ii][Nn][Kk]) ([https?://w]*.?telegram.me/joinchat/%S+)$", "^([Ss][Ee][Tt][Ll][Ii][Nn][Kk]) ([https?://w]*.?[Tt].me/joinchat/%S+)$", "^([Nn][Ee][Ww][Ll][Ii][Nn][Kk])$", "^([Nn][Ee][Ww][Ll][Ii][Nn][Kk]) (pv)$", "^([Rr][Uu][Ll][Ee][Ss])$", "^([Ss][Ee][Tt][Tt][Ii][Nn][Gg][Ss])$", "^([Mm][Uu][Tt][Ee][Ll][Ii][Ss][Tt])$", "^([Ss][Ee][Tt][Rr][Uu][Ll][Ee][Ss]) (.*)$", "^([Aa][Bb][Oo][Uu][Tt])$", "^([Ss][Ee][Tt][Aa][Bb][Oo][Uu][Tt]) (.*)$", "^([Ss][Ee][Tt][Nn][Aa][Mm][Ee]) (.*)$", "^([Cc][Ll][Ee][Aa][Nn]) (.*)$", "^([Ss][Ee][Tt][Ff][Ll][Oo][Oo][Dd]) (%d+)$", "^([Ss][Ee][Tt][Cc][Hh][Aa][Rr]) (%d+)$", "^([Ss][Ee][Tt][Ff][Ll][Oo][Oo][Dd][Tt][Ii][Mm][Ee]) (%d+)$", "^([Rr][Ee][Ss]) (.*)$", "^([Cc][Mm][Dd][Ss]) (.*)$", "^([Ww][Hh][Oo][Ii][Ss]) (%d+)$", "^([Hh][Ee][Ll][Pp])$", "^([Ss][Ee][Tt][Ll][Aa][Nn][Gg]) (fa)$", "^([Ff][Ii][Ll][Tt][Ee][Rr]) (.*)$", "^([Uu][Nn][Ff][Ii][Ll][Tt][Ee][Rr]) (.*)$", "^([Ff][Ii][Ll][Tt][Ee][Rr][Ll][Ii][Ss][Tt])$", "^([Cc][Oo][Nn][Ff][Ii][Gg])$", "^([Ss][Ee][Tt][Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)", "^([Ww][Ee][Ll][Cc][Oo][Mm][Ee]) (.*)", '^([Mm]uteall) (status)$', '^([Hh]elpmute)$', '^([Mm]utetime) (%d+) (%d+) (%d+)$', '^([Mm]utehours) (%d+)$', '^([Mm]uteminutes) (%d+)$', '^([Mm]uteseconds) (%d+)$', }, patterns_fa = { '^(ایدی)$', '^(ایدی) (.*)$', '^(تنظیمات)$', '^(سنجاق)$', '^(حذف سنجاق)$', '^(افزودن)$', '^(حذف گروه)$', '^(ادمین گروه)$', '^(ادمین گروه) (.*)$', '^(حذف ادمین گروه) (.*)$', '^(حذف ادمین گروه)$', '^(لیست سفید) ([+-]) (.*)$', '^(لیست سفید) ([+-])$', '^(لیست سفید)$', '^(مالک)$', '^(مالک) (.*)$', '^(حذف مالک) (.*)$', '^(حذف مالک)$', '^(مدیر)$', '^(مدیر) (.*)$', '^(حذف مدیر)$', '^(حذف مدیر) (.*)$', '^(قفل) (.*)$', '^(باز) (.*)$', '^(بیصدا) (.*)$', '^(باصدا) (.*)$', '^(لینک جدید)$', '^(لینک جدید) (خصوصی)$', '^(اطلاعات گروه)$', '^(دستورات) (.*)$', '^(قوانین)$', '^(لینک)$', '^(تنظیم لینک)$', '^(تنظیم لینک) ([https?://w]*.?telegram.me/joinchat/%S+)$', '^(تنظیم لینک) ([https?://w]*.?t.me/joinchat/%S+)$', '^(تنظیم قوانین) (.*)$', '^(لینک) (خصوصی)$', '^(کاربری) (.*)$', '^(شناسه) (%d+)$', '^(تنظیم پیام مکرر) (%d+)$', '^(تنظیم زمان بررسی) (%d+)$', '^(حداکثر حروف مجاز) (%d+)$', '^(پاک کردن) (.*)$', '^(درباره)$', '^(تنظیم نام) (.*)$', '^(تنظیم درباره) (.*)$', '^(لیست فیلتر)$', '^(لیست بیصدا)$', '^(لیست مالکان)$', '^(لیست مدیران)$', '^(راهنما)$', '^(پیکربندی)$', '^(فیلتر) (.*)$', '^(حذف فیلتر) (.*)$', '^(خوشآمد) (.*)$', '^(تنظیم خوشآمد) (.*)$', '^(راهنما بیصدا)$', '^(ساعت بیصدا) (%d+)$', '^(دقیقه بیصدا) (%d+)$', '^(ثانیه بیصدا) (%d+)$', '^(موقعیت) (بیصدا)$', '^(زمان بیصدا) (%d+) (%d+) (%d+)$', '^(زبان انگلیسی)$', '^([https?://w]*.?telegram.me/joinchat/%S+)$', '^([https?://w]*.?t.me/joinchat/%S+)$' }, run=run, pre_process = pre_process } -- ##
gpl-3.0
Mephostopilis/lua
fixmath/test_bounce.lua
1
2008
require "fixmath.bounce" -- Create a b3World object. local m_world = bounce.b3World() local gravity = { x= 0.0, y = -9.8, z = 0.0} m_world:SetGravity(gravity) local timeStep = 1.0 / 60.0 local velocityIterations = 8 local positionIterations = 2 local groundDef = {} local ground = m_world:CreateBody(groundDef) local groundBox = bounce.b3BoxHull() local scale = {} scale.position = { x = 0, y = 0, z = 0} scale.rotation = bounce.b3Mat33.b3Diagonal(10.0, 1.0, 10.0) groundBox:SetTransform(scale) local groundShape = bounce.b3HullShape() groundShape.m_hull = groundBox local groundBoxDef = {} groundBoxDef.shape = groundShape ground:CreateShape(groundBoxDef) -- create box local bodydef = {} bodydef.type = 3 bodydef.position = { x = 0, y = 10, z = 0 } -- bodydef.orientation = { a = 0, b = 0, c = 0, d = 1} -- bodydef.linearVelocity = { x = 0, y = 0, z = 0} bodydef.angularVelocity = { x = 0, y = bounce.b3R32.PI(), z = 0} -- bodydef.gravityScale = 1 local body = m_world:CreateBody(bodydef) local position = body:GetPosition() print(string.format("x = %f, y = %f, z = %f", bounce.b3R32.ToFloat32(position.x), bounce.b3R32.ToFloat32(position.y), bounce.b3R32.ToFloat32(position.z))) print("----------------------") -- hull local bodyBox = bounce.b3BoxHull() bodyBox:SetIdentity() local bodyShape = bounce.b3HullShape() bodyShape.m_hull = bodyBox local shapedef = { shape = bodyShape } shapedef.density = 1 body:CreateShape( shapedef ) -- body:ApplyForceToCenter({ x = 0, y = 10, z = 0}, false) -- body:SetLinearVelocity({ x = 100, y = 0, z = 100 }) for i=1,10 do -- // Call the function below to simulate a single physics step. m_world:Step(timeStep, velocityIterations, positionIterations) local position = body:GetPosition() print(string.format("x = %f, y = %f, z = %f", bounce.b3R32.ToFloat32(position.x), bounce.b3R32.ToFloat32(position.y), bounce.b3R32.ToFloat32(position.z))) -- local trans = body:GetTransform() -- for k,v in pairs(trans.translation) do -- print(k,v) -- end end
apache-2.0
xanathar/lualinq
src/grimq_dbg_header.lua
1
1536
-- ------------------------------------------------------------------------ -- This project is developed by Marco Mastropaolo (Xanathar) -- as a personal project and is in no way affiliated with Almost Human. -- You can use this scripts in any Legend of Grimrock dungeon you want; -- credits are appreciated though not necessary. -- ------------------------------------------------------------------------ -- If you want to use this code in a Lua project outside Grimrock, -- please refer to the files and license included -- at http://code.google.com/p/lualinq/ -- ------------------------------------------------------------------------ --------------------------------------------------------------------------- -- CONFIGURATION OPTIONS -- --------------------------------------------------------------------------- -- change this if you don't want all secrets to be "auto" AUTO_ALL_SECRETS = true -- how much log information is printed: 3 => verbose, 2 => info, 1 => only warning and errors, 0 => only errors, -1 => silent LOG_LEVEL = 2 -- prefix for the printed logs LOG_PREFIX = "GrimQ: " -- set this to false when the allEntities bug gets fixed for faster iterations PATCH_ALLENTITIES_BUG = true --------------------------------------------------------------------------- -- IMPLEMENTATION BELOW, DO NOT CHANGE --------------------------------------------------------------------------- VERSION_SUFFIX = ".DEBUG" MAXLEVEL = 1 CONTAINERITEM_MAXSLOTS = 10
bsd-3-clause
kickinrad/healerhealer
patient.lua
1
11145
patient = { ailments={skin=nil, sweating=0, bloodshot=0, sunken=0, welts=0, spots=0}, skin={k=nil, r=nil, g=nil, b=nil, img=love.graphics.newImage("assets/character/skin.png")}, shirt={r=nil, g=nil, b=nil, img=love.graphics.newImage("assets/character/shirt.png")}, hair={r=nil, g=nil, b=nil, img=love.graphics.newImage("assets/character/hair.png")}, eyes={r=nil, g=nil, b=nil, img=love.graphics.newImage("assets/character/eyes.png")}, pants={r=nil, g=nil, b=nil, img=love.graphics.newImage("assets/character/pants.png")}, shoes={r=nil, g=nil, b=nil, img=love.graphics.newImage("assets/character/shoes.png")} } ailments = { spots=love.graphics.newImage("assets/character/spots.png"), sweating=love.graphics.newImage("assets/character/sweating.png"), welts=love.graphics.newImage("assets/character/welts.png"), sunken=love.graphics.newImage("assets/character/sunken.png"), bloodshot=love.graphics.newImage("assets/character/bloodshot.png") } dialogue = { grey = { "My skin is grey as ash, and my heart seems black as soot.", -- 1 "The vibrance has fled from my bones! Not a cheer in sight.", -- 2 "Dear healer, it seems my skin is as bleak as I.", -- 3 "Am I not a sad sight, brother? This dull flesh dulls yet its owners heart.", -- 4 "What a dreadful shade. Wrought no doubt by a spirit as wretched as its taste in colors.", -- 5 "What a horrible night to have a curse." -- 6 }, redskin = { "Make haste, healer. My time is limited and my temper is low.", -- 1 "My blood is boiling. I can scarcely see through this fierce red.", -- 2 "With my skin as this, what sets me apart from unholy wretches below?", -- 3 "My veins are fire. Please, healer, qwell this burning...", -- 4 "I have never seeemed so... flustered. Do not flatter yourself, healer. It is not you." -- 5 }, sweating = { "I am soaked head to toe. My feverish fits grow graver by the day.", -- 1 "God, what a wreck am I. Perhaps I am sweating out these vile spirits.", -- 2 "Please, a drop of water, healer... I am so parched.", -- 3 "My haze is frienzied, brother... Anything...Anything for respite from the nightmares...", -- 4 "Please, a lasting care, healer. I have drenched all of my good attire." -- 5 }, bloodshot = { "I have forsaken sleep for days. These bleeding eyes simply cannot close.", -- 1 "I cannot bear the site of you, healer. I swear it be my eyes speeking there, not I.", -- 2 "All my sight is bathed in red. Does this shade not haunt your vision too, healer?", -- 3 "For want of an ointment these damn eyes of my glow red as embers. Can you stop this burning, healer?", -- 4 "These sight-seers of mine are something beastly." -- 5 }, sunken = { "I have seen portents, healer, terrible portents, etched into my eyes...", -- 1 "Sleep is death, healer.", -- 2 "These eyes have borne witness to wickedness, my healer. True wickedness.", -- 3 "This ghast-eyed spectre I behold in the looking glass surely cannot be I.", "The spirits claw at me, healer. Can you not see it in my eyes?" }, welts = { "Can one ever leave a blemished fool such as I?", -- 1 "What a twisted creature I have become. Bumps and boils as some sort of ogre.", -- 2 "The Black Death took my grandmother and my grandfather. Has it come for me too?" }, spots = { "I can see constellations in my skin.", -- 1 "My skin is aflame, healer. I scratch and scratch, as though to rend it from my bones." } } local patTimerMax = 0.5 local patTimer = 0 function getDialogue() returnArray = {} -- return this table lmao -- change to if/else tree for later when adding patient ailment checks if patient.ailments.skin == "grey" then rand = rng:random(1, table.getn(dialogue.grey)) -- random number from 1 - value.size table.insert(returnArray, dialogue.grey[rand]) end if patient.ailments.skin == "red" then rand = rng:random(1, table.getn(dialogue.redskin)) -- random number from 1 - value.size table.insert(returnArray, dialogue.redskin[rand]) end if patient.ailments.sweating == 1 then rand = rng:random(1, table.getn(dialogue.sweating)) -- random number from 1 - value.size table.insert(returnArray, dialogue.sweating[rand]) end if patient.ailments.bloodshot == 1 then rand = rng:random(1, table.getn(dialogue.bloodshot)) -- random number from 1 - value.size table.insert(returnArray, dialogue.bloodshot[rand]) end if patient.ailments.sunken == 1 then rand = rng:random(1, table.getn(dialogue.sunken)) -- random number from 1 - value.size table.insert(returnArray, dialogue.sunken[rand]) end if patient.ailments.welts == 1 then rand = rng:random(1, table.getn(dialogue.welts)) -- random number from 1 - value.size table.insert(returnArray, dialogue.welts[rand]) end if patient.ailments.spots == 1 then rand = rng:random(1, table.getn(dialogue.spots)) -- random number from 1 - value.size table.insert(returnArray, dialogue.spots[rand]) end -- return array of dialogue return returnArray end function loadPatient(difficulty) for i=1, difficulty do --print("test") done = 0 while (done==0) do rand = rng:random(1,7) if (rand==1 and patient.ailments.skin==nil) then patient.ailments.skin="red" done = 1 end if (rand==2 and patient.ailments.skin==nil) then patient.ailments.skin="grey" done = 1 end if (rand==3 and patient.ailments.sweating==0) then patient.ailments.sweating=1 done = 1 end if (rand==4 and patient.ailments.bloodshot==0) then patient.ailments.bloodshot=1 done = 1 end if (rand==5 and patient.ailments.sunken==0) then patient.ailments.sunken=1 done = 1 end if (rand==6 and patient.ailments.welts==0) then patient.ailments.welts=1 done = 1 end if (rand==7 and patient.ailments.spots==0) then patient.ailments.spots=1 done = 1 end end end if(patient.ailments.skin=="red") then patient.skin.r=163 patient.skin.g=92 patient.skin.b=85 elseif (patient.ailments.skin=="grey") then patient.skin.r=192 patient.skin.g=192 patient.skin.b=192 else patient.skin.k=rng:random(-3,3) patient.skin.r=168.8+38.5*patient.skin.k patient.skin.g=122.5+32.1*patient.skin.k patient.skin.b=96.7+26.3*patient.skin.k end patient.shirt.r=rng:random(1,255) patient.shirt.g=rng:random(1,255) patient.shirt.b=rng:random(1,255) patient.hair.r=rng:random(100,150) patient.hair.g=rng:random(60,80) patient.hair.b=rng:random(10,30) patient.eyes.r=rng:random(10,40) patient.eyes.g=rng:random(10,40) patient.eyes.b=rng:random(10,40) patient.pants.r=rng:random(1,255) patient.pants.g=rng:random(1,255) patient.pants.b=rng:random(1,255) patient.shoes.r=rng:random(1,255) patient.shoes.g=rng:random(1,255) patient.shoes.b=rng:random(1,255) if(patient.ailments.skin=="red") then patient.skin.r=233 patient.skin.g=98 patient.skin.b=98 end loadSayings() end function updatePatient(dt) if patTimer <=0 then finished = 0 end if patTimer > 0 then patTimer = patTimer - (1 * dt) end end function drawPatient() if (finished==0) then love.graphics.setColor(patient.skin.r,patient.skin.g,patient.skin.b,255) love.graphics.draw(patient.skin.img, 580, 250, 0, 1, 1, 100, 100) drawAilments() love.graphics.setColor(patient.shirt.r,patient.shirt.g,patient.shirt.b,255) love.graphics.draw(patient.shirt.img, 580, 250, 0, 1, 1, 100, 100) love.graphics.setColor(patient.pants.r,patient.pants.g,patient.pants.b,255) love.graphics.draw(patient.pants.img, 580, 250, 0, 1, 1, 100, 100) love.graphics.setColor(patient.shoes.r,patient.shoes.g,patient.shoes.b,255) love.graphics.draw(patient.shoes.img, 580, 250, 0, 1, 1, 100, 100) love.graphics.setColor(patient.hair.r,patient.hair.g,patient.hair.b,255) love.graphics.draw(patient.hair.img, 580, 250, 0, 1, 1, 100, 100) end end function drawAilments() if(patient.ailments.spots==1) then love.graphics.setColor(130,0,0,190) love.graphics.draw(ailments.spots, 580, 250, 0, 1, 1, 100, 100) end if(patient.ailments.sweating==1) then love.graphics.setColor(185,238,251,180) love.graphics.draw(ailments.sweating, 580, 250, 0, 1, 1, 100, 100) end if(patient.ailments.welts==1) then love.graphics.setColor(205,78,78,160) love.graphics.draw(ailments.welts, 580, 250, 0, 1, 1, 100, 100) end if(patient.ailments.sunken==1) then love.graphics.setColor(0,0,0,80) love.graphics.draw(ailments.sunken, 580, 250, 0, 1, 1, 100, 100) end if(patient.ailments.bloodshot==1) then love.graphics.setColor(208,77,64,200) love.graphics.draw(ailments.bloodshot, 580, 250, 0, 1, 1, 100, 100) else love.graphics.setColor(patient.eyes.r,patient.eyes.g,patient.eyes.b,255) love.graphics.draw(patient.eyes.img, 580, 250, 0, 1, 1, 100, 100) end end function getCures() cures = {} if (patient.ailments.skin=="red") then table.insert(cures, {"Aloe", "Dove's Wing", "Olive Twig", "Rosemary", "Sow's Milk", 1}) end if (patient.ailments.skin=="grey") then table.insert(cures, {"Aloe", "Cat's Paw", "Cat's Paw", "Dragonfly's Wing", "Fox's Tail", 2}) end if (patient.ailments.sweating==1) then table.insert(cures, {"Ash", "Bog Water", "Rosemary", "Salt", "Vinegar", 3}) end if (patient.ailments.bloodshot==1) then table.insert(cures, {"Mandrake Root", "Sage's Eye", "Toad's Tongue", "Wheat", "Witch's Hair", 4}) end if (patient.ailments.sunken==1) then table.insert(cures, {"Fox's Tail", "Quail Egg", "Vinegar", "Vinegar", "Wolf Fang", 5}) end if (patient.ailments.welts==1) then table.insert(cures, {"Croc Scales", "Frog", "Mandrake Root", "Newt Tongue", "Rat's Tail", 6}) end if (patient.ailments.spots==1) then table.insert(cures, {"Cat's Paw", "Dahlia", "Familiar's Blood", "Wolf Fang", "Wolf Fang", 7}) end return cures end function cure(num) --print("trying to cure") --print("num:",num) if (num==1 or num ==2) then patient.ailments.skin=nil --print("ayy") fixSkin() end if (num==3) then patient.ailments.sweating=0 fixSkin() end if (num==4) then patient.ailments.bloodshot=0 end if (num==5) then patient.ailments.sunken=0 end if (num==6) then patient.ailments.welts=0 end if (num==7) then patient.ailments.spots=0 end drawPatient() drawAilments() return checkIfCured() end function checkIfCured() if (patient.ailments.skin==nil and patient.ailments.sweating==0 and patient.ailments.bloodshot==0 and patient.ailments.sunken==0 and patient.ailments.welts==0 and patient.ailments.spots==0) then --patient is cured code here print("CURED!!!!") score = score+1 finished = 1 if score < 4 and score > 0 then -- if score is 1 - 4 rand = rng:random(1, score) + 1 loadPatient(rand) else -- else difficulty is 2 loadPatient(2) end -- get dialogue now --loadSayings() setMsg("Patient has been cured!") patTimer = patTimerMax return 1 else end return 0 end function killPatient() if score > 0 then score = score - 1 end setMsg(" Wrong treatment!") end function fixSkin() patient.skin.k=rng:random(-3,3) patient.skin.r=168.8+38.5*patient.skin.k patient.skin.g=122.5+32.1*patient.skin.k patient.skin.b=96.7+26.3*patient.skin.k end
mit
UnluckyNinja/PathOfBuilding
Data/3_0/Bases/shield.lua
1
30696
-- This file is automatically generated, do not edit! -- Item data (c) Grinding Gear Games local itemBases = ... itemBases["Splintered Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, armour = { BlockChance = 24, ArmourBase = 9, MovementPenalty = 3, }, req = { str = 10, }, } itemBases["Corroded Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 23, ArmourBase = 46, MovementPenalty = 3, }, req = { level = 5, str = 20, }, } itemBases["Rawhide Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 26, ArmourBase = 53, MovementPenalty = 3, }, req = { level = 11, str = 33, }, } itemBases["Cedar Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(20-30) to maximum Life", armour = { BlockChance = 25, ArmourBase = 108, MovementPenalty = 3, }, req = { level = 17, str = 46, }, } itemBases["Copper Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(30-40) to maximum Life", armour = { BlockChance = 24, ArmourBase = 191, MovementPenalty = 3, }, req = { level = 24, str = 62, }, } itemBases["Reinforced Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 23, ArmourBase = 287, MovementPenalty = 3, }, req = { level = 30, str = 76, }, } itemBases["Painted Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(20-30) to maximum Life", armour = { BlockChance = 25, ArmourBase = 217, MovementPenalty = 3, }, req = { level = 35, str = 87, }, } itemBases["Buckskin Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 26, ArmourBase = 177, MovementPenalty = 3, }, req = { level = 39, str = 96, }, } itemBases["Mahogany Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(20-30) to maximum Life", armour = { BlockChance = 25, ArmourBase = 265, MovementPenalty = 3, }, req = { level = 43, str = 105, }, } itemBases["Bronze Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(30-40) to maximum Life", armour = { BlockChance = 24, ArmourBase = 367, MovementPenalty = 3, }, req = { level = 47, str = 114, }, } itemBases["Girded Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 23, ArmourBase = 481, MovementPenalty = 3, }, req = { level = 51, str = 123, }, } itemBases["Crested Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(20-30) to maximum Life", armour = { BlockChance = 25, ArmourBase = 338, MovementPenalty = 3, }, req = { level = 55, str = 132, }, } itemBases["Shagreen Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 26, ArmourBase = 261, MovementPenalty = 3, }, req = { level = 58, str = 139, }, } itemBases["Ebony Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(20-30) to maximum Life", armour = { BlockChance = 25, ArmourBase = 412, MovementPenalty = 3, }, req = { level = 61, str = 159, }, } itemBases["Ezomyte Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(30-40) to maximum Life", armour = { BlockChance = 24, ArmourBase = 522, MovementPenalty = 3, }, req = { level = 64, str = 159, }, } itemBases["Colossal Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(10-20) to maximum Life", armour = { BlockChance = 23, ArmourBase = 632, MovementPenalty = 3, }, req = { level = 67, str = 159, }, } itemBases["Pinnacle Tower Shield"] = { type = "Shield", subType = "Armour", tags = { default = true, armour = true, shield = true, str_armour = true, str_shield = true, }, implicit = "+(20-30) to maximum Life", armour = { BlockChance = 25, ArmourBase = 467, MovementPenalty = 3, }, req = { level = 70, str = 159, }, } itemBases["Goathide Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 25, EvasionBase = 12, MovementPenalty = 3, }, req = { dex = 13, }, } itemBases["Pine Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 26, EvasionBase = 43, MovementPenalty = 3, }, req = { level = 8, dex = 26, }, } itemBases["Painted Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "6% increased Movement Speed", armour = { BlockChance = 24, EvasionBase = 109, MovementPenalty = 3, }, req = { level = 16, dex = 44, }, } itemBases["Hammered Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 27, EvasionBase = 96, MovementPenalty = 3, }, req = { level = 23, dex = 60, }, } itemBases["War Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "9% increased Movement Speed", armour = { BlockChance = 26, EvasionBase = 145, MovementPenalty = 3, }, req = { level = 29, dex = 74, }, } itemBases["Gilded Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "6% increased Movement Speed", armour = { BlockChance = 25, EvasionBase = 197, MovementPenalty = 3, }, req = { level = 34, dex = 85, }, } itemBases["Oak Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 26, EvasionBase = 188, MovementPenalty = 3, }, req = { level = 38, dex = 94, }, } itemBases["Enameled Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "6% increased Movement Speed", armour = { BlockChance = 24, EvasionBase = 277, MovementPenalty = 3, }, req = { level = 42, dex = 103, }, } itemBases["Corrugated Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 27, EvasionBase = 189, MovementPenalty = 3, }, req = { level = 46, dex = 112, }, } itemBases["Battle Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "9% increased Movement Speed", armour = { BlockChance = 26, EvasionBase = 246, MovementPenalty = 3, }, req = { level = 50, dex = 121, }, } itemBases["Golden Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "6% increased Movement Speed", armour = { BlockChance = 25, EvasionBase = 310, MovementPenalty = 3, }, req = { level = 54, dex = 130, }, } itemBases["Ironwood Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 26, EvasionBase = 280, MovementPenalty = 3, }, req = { level = 57, dex = 136, }, } itemBases["Lacquered Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "6% increased Movement Speed", armour = { BlockChance = 24, EvasionBase = 440, MovementPenalty = 3, }, req = { level = 60, dex = 159, }, } itemBases["Vaal Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "3% increased Movement Speed", armour = { BlockChance = 27, EvasionBase = 275, MovementPenalty = 3, }, req = { level = 63, dex = 159, }, } itemBases["Crusader Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "9% increased Movement Speed", armour = { BlockChance = 26, EvasionBase = 330, MovementPenalty = 3, }, req = { level = 66, dex = 159, }, } itemBases["Imperial Buckler"] = { type = "Shield", subType = "Evasion", tags = { default = true, armour = true, shield = true, dex_armour = true, dex_shield = true, }, implicit = "6% increased Movement Speed", armour = { BlockChance = 25, EvasionBase = 385, MovementPenalty = 3, }, req = { level = 69, dex = 159, }, } itemBases["Twig Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(10-15)% increased Spell Damage", armour = { BlockChance = 22, EnergyShieldBase = 5, MovementPenalty = 3, }, req = { int = 15, }, } itemBases["Yew Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(5-10)% increased Spell Damage", armour = { BlockChance = 24, EnergyShieldBase = 9, MovementPenalty = 3, }, req = { level = 9, int = 28, }, } itemBases["Bone Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(15-20)% increased Spell Damage", armour = { BlockChance = 22, EnergyShieldBase = 14, MovementPenalty = 3, }, req = { level = 15, int = 42, }, } itemBases["Tarnished Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(5-10)% increased Spell Damage", armour = { BlockChance = 24, EnergyShieldBase = 20, MovementPenalty = 3, }, req = { level = 23, int = 60, }, } itemBases["Jingling Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(10-15)% increased Spell Damage", armour = { BlockChance = 23, EnergyShieldBase = 24, MovementPenalty = 3, }, req = { level = 28, int = 71, }, } itemBases["Brass Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, armour = { BlockChance = 25, EnergyShieldBase = 33, MovementPenalty = 3, }, req = { level = 33, int = 82, }, } itemBases["Walnut Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(5-10)% increased Spell Damage", armour = { BlockChance = 24, EnergyShieldBase = 30, MovementPenalty = 3, }, req = { level = 37, int = 92, }, } itemBases["Ivory Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(15-20)% increased Spell Damage", armour = { BlockChance = 22, EnergyShieldBase = 33, MovementPenalty = 3, }, req = { level = 41, int = 100, }, } itemBases["Ancient Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(5-10)% increased Spell Damage", armour = { BlockChance = 24, EnergyShieldBase = 36, MovementPenalty = 3, }, req = { level = 45, int = 110, }, } itemBases["Chiming Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(10-15)% increased Spell Damage", armour = { BlockChance = 23, EnergyShieldBase = 39, MovementPenalty = 3, }, req = { level = 49, int = 118, }, } itemBases["Thorium Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, armour = { BlockChance = 25, EnergyShieldBase = 51, MovementPenalty = 3, }, req = { level = 53, int = 128, }, } itemBases["Lacewood Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(5-10)% increased Spell Damage", armour = { BlockChance = 24, EnergyShieldBase = 45, MovementPenalty = 3, }, req = { level = 56, int = 134, }, } itemBases["Fossilised Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(15-20)% increased Spell Damage", armour = { BlockChance = 22, EnergyShieldBase = 47, MovementPenalty = 3, }, req = { level = 59, int = 141, }, } itemBases["Vaal Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(5-10)% increased Spell Damage", armour = { BlockChance = 24, EnergyShieldBase = 53, MovementPenalty = 3, }, req = { level = 62, int = 159, }, } itemBases["Harmonic Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, implicit = "(10-15)% increased Spell Damage", armour = { BlockChance = 23, EnergyShieldBase = 55, MovementPenalty = 3, }, req = { level = 65, int = 159, }, } itemBases["Titanium Spirit Shield"] = { type = "Shield", subType = "Energy Shield", tags = { default = true, armour = true, shield = true, int_armour = true, focus = true, }, armour = { BlockChance = 25, EnergyShieldBase = 64, MovementPenalty = 3, }, req = { level = 68, int = 159, }, } itemBases["Rotted Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "60% increased Block Recovery", armour = { BlockChance = 23, ArmourBase = 13, EvasionBase = 13, MovementPenalty = 3, }, req = { level = 5, str = 10, dex = 10, }, } itemBases["Fir Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "180% increased Block Recovery", armour = { BlockChance = 23, ArmourBase = 29, EvasionBase = 29, MovementPenalty = 3, }, req = { level = 12, str = 19, dex = 19, }, } itemBases["Studded Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "60% increased Block Recovery", armour = { BlockChance = 26, ArmourBase = 46, EvasionBase = 46, MovementPenalty = 3, }, req = { level = 20, str = 28, dex = 28, }, } itemBases["Scarlet Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, armour = { BlockChance = 25, ArmourBase = 87, EvasionBase = 87, MovementPenalty = 3, }, req = { level = 27, str = 37, dex = 37, }, } itemBases["Splendid Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "120% increased Block Recovery", armour = { BlockChance = 24, ArmourBase = 75, EvasionBase = 75, MovementPenalty = 3, }, req = { level = 33, str = 44, dex = 44, }, } itemBases["Maple Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "180% increased Block Recovery", armour = { BlockChance = 23, ArmourBase = 88, EvasionBase = 88, MovementPenalty = 3, }, req = { level = 39, str = 52, dex = 52, }, } itemBases["Spiked Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "60% increased Block Recovery", armour = { BlockChance = 26, ArmourBase = 102, EvasionBase = 102, MovementPenalty = 3, }, req = { level = 45, str = 58, dex = 58, }, } itemBases["Crimson Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, armour = { BlockChance = 25, ArmourBase = 155, EvasionBase = 155, MovementPenalty = 3, }, req = { level = 49, str = 64, dex = 64, }, } itemBases["Baroque Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "120% increased Block Recovery", armour = { BlockChance = 24, ArmourBase = 122, EvasionBase = 122, MovementPenalty = 3, }, req = { level = 54, str = 70, dex = 70, }, } itemBases["Teak Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "180% increased Block Recovery", armour = { BlockChance = 23, ArmourBase = 131, EvasionBase = 131, MovementPenalty = 3, }, req = { level = 58, str = 74, dex = 74, }, } itemBases["Spiny Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "60% increased Block Recovery", armour = { BlockChance = 26, ArmourBase = 154, EvasionBase = 154, MovementPenalty = 3, }, req = { level = 62, str = 85, dex = 85, }, } itemBases["Cardinal Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, armour = { BlockChance = 25, ArmourBase = 209, EvasionBase = 209, MovementPenalty = 3, }, req = { level = 66, str = 85, dex = 85, }, } itemBases["Elegant Round Shield"] = { type = "Shield", subType = "Armour/Evasion", tags = { default = true, armour = true, shield = true, str_dex_armour = true, str_dex_shield = true, }, implicit = "120% increased Block Recovery", armour = { BlockChance = 24, ArmourBase = 148, EvasionBase = 148, MovementPenalty = 3, }, req = { level = 70, str = 85, dex = 85, }, } itemBases["Plank Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+4% to all Elemental Resistances", armour = { BlockChance = 22, ArmourBase = 18, EnergyShieldBase = 4, MovementPenalty = 3, }, req = { level = 7, str = 13, int = 13, }, } itemBases["Linden Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+4% to all Elemental Resistances", armour = { BlockChance = 24, ArmourBase = 43, EnergyShieldBase = 10, MovementPenalty = 3, }, req = { level = 13, str = 20, int = 20, }, } itemBases["Reinforced Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, armour = { BlockChance = 26, ArmourBase = 65, EnergyShieldBase = 14, MovementPenalty = 3, }, req = { level = 20, str = 28, int = 28, }, } itemBases["Layered Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+8% to all Elemental Resistances", armour = { BlockChance = 24, ArmourBase = 62, EnergyShieldBase = 13, MovementPenalty = 3, }, req = { level = 27, str = 37, int = 37, }, } itemBases["Ceremonial Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+12% to all Elemental Resistances", armour = { BlockChance = 22, ArmourBase = 77, EnergyShieldBase = 16, MovementPenalty = 3, }, req = { level = 34, str = 46, int = 46, }, } itemBases["Etched Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+4% to all Elemental Resistances", armour = { BlockChance = 24, ArmourBase = 127, EnergyShieldBase = 25, MovementPenalty = 3, }, req = { level = 40, str = 52, int = 52, }, } itemBases["Steel Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, armour = { BlockChance = 26, ArmourBase = 146, EnergyShieldBase = 29, MovementPenalty = 3, }, req = { level = 46, str = 60, int = 60, }, } itemBases["Laminated Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+8% to all Elemental Resistances", armour = { BlockChance = 24, ArmourBase = 113, EnergyShieldBase = 22, MovementPenalty = 3, }, req = { level = 50, str = 64, int = 64, }, } itemBases["Angelic Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+12% to all Elemental Resistances", armour = { BlockChance = 22, ArmourBase = 124, EnergyShieldBase = 24, MovementPenalty = 3, }, req = { level = 55, str = 70, int = 70, }, } itemBases["Branded Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+4% to all Elemental Resistances", armour = { BlockChance = 24, ArmourBase = 186, EnergyShieldBase = 36, MovementPenalty = 3, }, req = { level = 59, str = 76, int = 76, }, } itemBases["Champion Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, armour = { BlockChance = 26, ArmourBase = 215, EnergyShieldBase = 42, MovementPenalty = 3, }, req = { level = 62, str = 85, int = 85, }, } itemBases["Mosaic Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+8% to all Elemental Resistances", armour = { BlockChance = 24, ArmourBase = 147, EnergyShieldBase = 28, MovementPenalty = 3, }, req = { level = 65, str = 85, int = 85, }, } itemBases["Archon Kite Shield"] = { type = "Shield", subType = "Armour/Energy Shield", tags = { default = true, armour = true, shield = true, str_int_armour = true, str_int_shield = true, }, implicit = "+12% to all Elemental Resistances", armour = { BlockChance = 22, ArmourBase = 156, EnergyShieldBase = 30, MovementPenalty = 3, }, req = { level = 68, str = 85, int = 85, }, } itemBases["Spiked Bundle"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Attacks", armour = { BlockChance = 24, EvasionBase = 13, EnergyShieldBase = 4, MovementPenalty = 3, }, req = { level = 5, dex = 10, int = 10, }, } itemBases["Driftwood Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Attacks", armour = { BlockChance = 24, EvasionBase = 46, EnergyShieldBase = 10, MovementPenalty = 3, }, req = { level = 12, dex = 19, int = 19, }, } itemBases["Alloyed Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Spell Damage", armour = { BlockChance = 25, EvasionBase = 56, EnergyShieldBase = 12, MovementPenalty = 3, }, req = { level = 20, dex = 28, int = 28, }, } itemBases["Burnished Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "4% chance to Dodge Attacks", armour = { BlockChance = 26, EvasionBase = 62, EnergyShieldBase = 13, MovementPenalty = 3, }, req = { level = 27, dex = 37, int = 37, }, } itemBases["Ornate Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "4% chance to Dodge Spell Damage", armour = { BlockChance = 24, EvasionBase = 120, EnergyShieldBase = 24, MovementPenalty = 3, }, req = { level = 33, dex = 44, int = 44, }, } itemBases["Redwood Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Attacks", armour = { BlockChance = 24, EvasionBase = 142, EnergyShieldBase = 28, MovementPenalty = 3, }, req = { level = 39, dex = 52, int = 52, }, } itemBases["Compound Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Spell Damage", armour = { BlockChance = 25, EvasionBase = 122, EnergyShieldBase = 24, MovementPenalty = 3, }, req = { level = 45, dex = 58, int = 58, }, } itemBases["Polished Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "4% chance to Dodge Attacks", armour = { BlockChance = 26, EvasionBase = 111, EnergyShieldBase = 22, MovementPenalty = 3, }, req = { level = 49, dex = 64, int = 64, }, } itemBases["Sovereign Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "4% chance to Dodge Spell Damage", armour = { BlockChance = 24, EvasionBase = 195, EnergyShieldBase = 38, MovementPenalty = 3, }, req = { level = 54, dex = 70, int = 70, }, } itemBases["Alder Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Attacks", armour = { BlockChance = 24, EvasionBase = 209, EnergyShieldBase = 41, MovementPenalty = 3, }, req = { level = 58, dex = 74, int = 74, }, } itemBases["Ezomyte Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "2% chance to Dodge Spell Damage", armour = { BlockChance = 25, EvasionBase = 181, EnergyShieldBase = 35, MovementPenalty = 3, }, req = { level = 62, dex = 85, int = 85, }, } itemBases["Mirrored Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "4% chance to Dodge Attacks", armour = { BlockChance = 26, EvasionBase = 151, EnergyShieldBase = 29, MovementPenalty = 3, }, req = { level = 66, dex = 85, int = 85, }, } itemBases["Supreme Spiked Shield"] = { type = "Shield", subType = "Evasion/Energy Shield", tags = { default = true, armour = true, shield = true, dex_int_armour = true, dex_int_shield = true, }, implicit = "4% chance to Dodge Spell Damage", armour = { BlockChance = 24, EvasionBase = 242, EnergyShieldBase = 47, MovementPenalty = 3, }, req = { level = 70, dex = 85, int = 85, }, } itemBases["Golden Flame"] = { type = "Shield", hidden = true, tags = { default = true, armour = true, shield = true, not_for_sale = true, }, implicit = "+(11-19)% to Chaos Resistance", armour = { BlockChance = 20, MovementPenalty = 3, }, req = { level = 15, }, }
mit
errmor91/gamecode4
Assets/Scripts/PreInit.lua
44
11576
--======================================================================== -- PreInit.lua : Script that's run when the scripting system is initialized -- -- Part of the GameCode4 Application -- -- GameCode4 is the sample application that encapsulates much of the source code -- discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David -- "Rez" Graham, published by Charles River Media. -- ISBN-10: 1133776574 | ISBN-13: 978-1133776574 -- -- If this source code has found it's way to you, and you think it has helped you -- in any way, do the authors a favor and buy a new copy of the book - there are -- detailed explanations in it that compliment this code well. Buy a copy at Amazon.com -- by clicking here: -- http://www.amazon.com/gp/product/1133776574/ref=olp_product_details?ie=UTF8&me=&seller= -- -- There's a companion web site at http://www.mcshaffry.com/GameCode/ -- -- The source code is managed and maintained through Google Code: -- http://code.google.com/p/gamecode4/ -- -- (c) Copyright 2012 Michael L. McShaffry and David Graham -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU Lesser GPL v3 -- 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 -- http://www.gnu.org/licenses/lgpl-3.0.txt for more details. -- -- You should have received a copy of the GNU Lesser GPL v3 -- along with this program; if not, write to the Free Software -- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. -- --======================================================================== -- This file is run immediately after Lua is created but before the rest of the game initializes. This is the place -- to put any language extentions or pure utility functions/classes you write. ----------------------------------------------------------------------------------------------------------------------- -- Redifinition of require() and dofile(). This is needed to allow scripts to go through the resource system. ----------------------------------------------------------------------------------------------------------------------- do local OldRequire = require; -- save the old require() function local resourceIdMap = {}; -- map of resource id's we've already loaded require = function(script) -- If we haven't already loaded this file, try to load it now if (not resourceIdMap[script]) then if (LoadAndExecuteScriptResource(script)) then resourceIdMap[script] = true; else -- failed to load file through the resource system so fall back to the old method OldRequire(script); end end end end do local OldPrint = print; -- save the old print() function print = function(text) if (text ~= nil) then Log(text); else Log("<nil>"); end end end ----------------------------------------------------------------------------------------------------------------------- -- Utility functions ----------------------------------------------------------------------------------------------------------------------- Utils = {}; -- Concatenate the contents of the parameter list, separated by the string delimiter (just like in perl) -- example: Utils.Join(", ", {"Anna", "Bob", "Charlie", "Dolores"}) -- results: "Anna, Bob, Charlie, Dolores" function Utils.Join(delimiter, list) local len = table.getn(list) if len == 0 then return "" end local string = list[1] for i = 2, len do string = string .. delimiter .. list[i] end return string end -- Split text into a list consisting of the strings in text, separated by strings matching delimiter (which may be a pattern). -- example: Utils.Split(",%s*", "Anna, Bob, Charlie,Dolores") -- results: {"Anna", "Bob", "Charlie", "Delores"} function Utils.Split(delimiter, text) local list = {} local pos = 1 if string.find("", delimiter, 1) then -- this would result in endless loops --error("delimiter matches empty string!") print("delimiter matches empty string!") end while 1 do local first, last = string.find(text, delimiter, pos) if first then -- found? if first < pos then print("[WARNING] Lua Split() function failed; first < pos\nfirst = "..first.."; last = "..last.."; pos = "..pos); break end table.insert(list, string.sub(text, pos, first-1)) pos = last + 1 else table.insert(list, string.sub(text, pos)) break end end return list end function Utils.ConvertBoolToString(bool) if (bool == true) then return "true"; else return "false"; end end function Utils.DumpTable(table) for key, val in pairs(table) do print(key, val); end end -- private function used by Utils.DumpObject() function Utils._BuildMemberSet(obj, memberSet) if (obj.__index ~= nil and obj ~= obj.__index) then Utils._BuildMemberSet(obj.__index, memberSet); end for key, val in pairs(obj) do if (key ~= "__index" and memberSet[key] == nil) then memberSet[key] = true; end end end function Utils.DumpObject(obj) -- There might be copies of the same variable at various levels in the hierarchy so we need to build an -- exclusive set of names. local memberSet = {}; Utils._BuildMemberSet(obj, memberSet); -- Loop through the set of member names and print them out, along with the value from the original object's -- perspective. for key, val in pairs(memberSet) do print(key, obj[key]); end end ----------------------------------------------------------------------------------------------------------------------- -- Math stuff -- [rez] Note: These have been moved to C++. I left the old implementations here for educational purposes. ----------------------------------------------------------------------------------------------------------------------- GccMath = {}; --[[ -- not used.... function GccMath.ClampToUnsignedPI(val) local _2PI = math.pi * 2; if (val < 0) then return val + _2PI; elseif (val > _2PI) then return val - _2PI; else return val; end end --]] --[[ function GccMath.GetVectorFromRotation(angleRadians) lookAt = Vec3:Create(); local angle = angleRadians - (math.pi / 2); if (angle < 0) then angle = angle + math.pi * 2; end lookAt.x = math.cos(angle); lookAt.y = math.sin(angle); lookAt:Normalize(); -- just in case return lookAt; end --]] --[[ function GccMath.WrapPi(wrapMe) local twoPi = 2 * math.pi; if (math.abs(wrapMe) > math.pi) then wrapMe = wrapMe + math.pi; wrapMe = wrapMe - (math.floor(wrapMe * (1 / twoPi)) * twoPi); wrapMe = wrapMe - math.pi; end return wrapMe; end --]] --[[ function GccMath.GetYRotationFromVector(lookAtVec3) local zUnit = {x = 0, y = 0, z = 1}; -- 0 orientation means staring down the positive Z axis local angle = (math.atan2(lookAtVec3.z, lookAtVec3.x * -1) - math.atan2(zUnit.z, zUnit.x)); return GccMath.WrapPi(angle); end --]] ----------------------------------------------------------------------------------------------------------------------- -- Classes & Inheritance - Chapter 12, page 349 ----------------------------------------------------------------------------------------------------------------------- function class(baseClass, body) local ret = body or {}; -- if there's a base class, attach our new class to it if (baseClass ~= nil) then setmetatable(ret, ret); ret.__index = baseClass; ret.base = baseClass; end -- Add the Create() function. This will end up being added to each subclass which isn't ideal. This -- function should probably be stored in a single place so we only have to create it once. -- -self: The self pointer that's calling this function. -- -constructionData: The table sent in as construction data. Think of it like a constructor. -- -originalSubClass: Used for recursion. Don't pass anything into this parameter, it's filled -- automatically. It's used in case the C++ side needs access to the leaf -- subclass that is being instantiated. For an example, see ScriptProcess -- in C++. ret.Create = function(self, constructionData, originalSubClass) local obj; if (self.__index ~= nil) then if (originalSubClass ~= nil) then obj = self.__index:Create(constructionData, originalSubClass); else obj = self.__index:Create(constructionData, self); end else obj = constructionData or {}; end setmetatable(obj, obj); obj.__index = self; -- copy any operators over if (self.__operators ~= nil) then for key, val in pairs(self.__operators) do obj[key] = val; end end return obj; end -- Returns true if otherClass appears in this objects class hierarchy anywhere. ret.IsInstance = function(self, otherClass) local cls = self.__index; while cls do if cls == otherClass then return true end cls = cls.base end return false end return ret; end ----------------------------------------------------------------------------------------------------------------------- -- Vec3 class ----------------------------------------------------------------------------------------------------------------------- Vec3 = class(nil, { x = 0, y = 0, z = 0, __operators = {}, }); function Vec3:Length() return math.sqrt((self.x * self.x) + (self.y * self.y) + (self.z * self.z)); end function Vec3:Length2() return ((self.x * self.x) + (self.y * self.y) + (self.z * self.z)); end function Vec3:Normalize() local len = self:Length(); self.x = self.x / len; self.y = self.y / len; self.z = self.z / len; end function Vec3.__operators.__add(left, right) local temp = Vec3:Create(); if (type(right) == "number") then temp.x = left.x + right; temp.y = left.y + right; temp.z = left.z + right; else temp.x = left.x + right.x; temp.y = left.y + right.y; temp.z = left.z + right.z; end return temp; end function Vec3.__operators.__sub(left, right) local temp = Vec3:Create(); if (type(right) == "number") then temp.x = left.x - right; temp.y = left.y - right; temp.z = left.z - right; else temp.x = left.x - right.x; temp.y = left.y - right.y; temp.z = left.z - right.z; end return temp; end function Vec3.__operators.__mul(left, right) local temp = Vec3:Create(); if (type(right) == "number") then temp.x = left.x * right; temp.y = left.y * right; temp.z = left.z * right; else temp.x = left.x * right.x; temp.y = left.y * right.y; temp.z = left.z * right.z end return temp; end function Vec3.__operators.__div(left, right) local temp = Vec3:Create(); if (type(right) == "number") then temp.x = left.x / right; temp.y = left.y / right; temp.z = left.z / right; else temp.x = left.x / right.x; temp.y = left.y / right.y; temp.z = left.z / right.z; end return temp; end ----------------------------------------------------------------------------------------------------------------------- -- Event system ----------------------------------------------------------------------------------------------------------------------- Event = {}; EventType = {};
lgpl-3.0
artynet/luci
applications/luci-app-nft-qos/luasrc/model/cbi/nft-qos/nft-qos.lua
7
7240
-- Copyright 2018 Rosy Song <rosysong@rosinson.com> -- Licensed to the public under the Apache License 2.0. local uci = require("luci.model.uci").cursor() local wa = require("luci.tools.webadmin") local fs = require("nixio.fs") local ipc = require("luci.ip") local def_rate_dl = uci:get("nft-qos", "default", "static_rate_dl") local def_rate_ul = uci:get("nft-qos", "default", "static_rate_ul") local def_unit_dl = uci:get("nft-qos", "default", "static_unit_dl") local def_unit_ul = uci:get("nft-qos", "default", "static_unit_ul") local def_up = uci:get("nft-qos", "default", "dynamic_bw_up") local def_down = uci:get("nft-qos", "default", "dynamic_bw_down") local limit_enable = uci:get("nft-qos", "default", "limit_enable") local limit_type = uci:get("nft-qos", "default", "limit_type") local enable_priority = uci:get("nft-qos", "default", "priority_enable") local has_ipv6 = fs.access("/proc/net/ipv6_route") m = Map("nft-qos", translate("Qos over Nftables")) -- -- Taboptions -- s = m:section(TypedSection, "default", translate("NFT-QoS Settings")) s.addremove = false s.anonymous = true s:tab("limit", "Limit Rate") s:tab("priority", "Traffic Priority") -- -- Static -- o = s:taboption("limit", Flag, "limit_enable", translate("Limit Enable"), translate("Enable Limit Rate Feature")) o.default = limit_enable or o.enabled o.rmempty = false o = s:taboption("limit", ListValue, "limit_type", translate("Limit Type"), translate("Type of Limit Rate")) o.default = limit_static or "static" o:depends("limit_enable","1") o:value("static", "Static") o:value("dynamic", "Dynamic") o = s:taboption("limit", Value, "static_rate_dl", translate("Default Download Rate"), translate("Default value for download rate")) o.datatype = "uinteger" o.default = def_rate_dl or '50' o:depends("limit_type","static") o = s:taboption("limit", ListValue, "static_unit_dl", translate("Default Download Unit"), translate("Default unit for download rate")) o.default = def_unit_dl or "kbytes" o:depends("limit_type","static") o:value("bytes", "Bytes/s") o:value("kbytes", "KBytes/s") o:value("mbytes", "MBytes/s") o = s:taboption("limit", Value, "static_rate_ul", translate("Default Upload Rate"), translate("Default value for upload rate")) o.datatype = "uinteger" o.default = def_rate_ul or '50' o:depends("limit_type","static") o = s:taboption("limit", ListValue, "static_unit_ul", translate("Default Upload Unit"), translate("Default unit for upload rate")) o.default = def_unit_ul or "kbytes" o:depends("limit_type","static") o:value("bytes", "Bytes/s") o:value("kbytes", "KBytes/s") o:value("mbytes", "MBytes/s") -- -- Dynamic -- o = s:taboption("limit", Value, "dynamic_bw_down", translate("Download Bandwidth (Mbps)"), translate("Default value for download bandwidth")) o.default = def_up or '100' o.datatype = "uinteger" o:depends("limit_type","dynamic") o = s:taboption("limit", Value, "dynamic_bw_up", translate("Upload Bandwidth (Mbps)"), translate("Default value for upload bandwidth")) o.default = def_down or '100' o.datatype = "uinteger" o:depends("limit_type","dynamic") o = s:taboption("limit", Value, "dynamic_cidr", translate("Target Network (IPv4/MASK)"), translate("Network to be apply, e.g. 192.168.1.0/24, 10.2.0.0/16, etc")) o.datatype = "cidr4" ipc.routes({ family = 4, type = 1 }, function(rt) o.default = rt.dest end) o:depends("limit_type","dynamic") if has_ipv6 then o = s:taboption("limit", Value, "dynamic_cidr6", translate("Target Network6 (IPv6/MASK)"), translate("Network to be apply, e.g. AAAA::BBBB/64, CCCC::1/128, etc")) o.datatype = "cidr6" o:depends("limit_type","dynamic") end o = s:taboption("limit", DynamicList, "limit_whitelist", translate("White List for Limit Rate")) o.datatype = "ipaddr" o:depends("limit_enable","1") -- -- Priority -- o = s:taboption("priority", Flag, "priority_enable", translate("Enable Traffic Priority"), translate("Enable this feature")) o.default = enable_priority or o.enabled o.rmempty = false o = s:taboption("priority", ListValue, "priority_netdev", translate("Default Network Interface"), translate("Network Interface for Traffic Shaping, e.g. br-lan, eth0.1, eth0, etc")) o:depends("priority_enable", "1") wa.cbi_add_networks(o) -- -- Static Limit Rate - Download Rate -- if limit_enable == "1" and limit_type == "static" then x = m:section(TypedSection, "download", translate("Static QoS-Download Rate")) x.anonymous = true x.addremove = true x.template = "cbi/tblsection" o = x:option(Value, "hostname", translate("Hostname")) o.datatype = "hostname" o.default = 'undefined' if has_ipv6 then o = x:option(Value, "ipaddr", translate("IP Address(V4 / V6)")) else o = x:option(Value, "ipaddr", translate("IP Address(V4 Only)")) end o.datatype = "ipaddr" if nixio.fs.access("/tmp/dhcp.leases") or nixio.fs.access("/var/dhcp6.leases") then o.titleref = luci.dispatcher.build_url("admin", "status", "overview") end o = x:option(Value, "macaddr", translate("MAC (optional)")) o.rmempty = true o.datatype = "macaddr" o = x:option(Value, "rate", translate("Rate")) o.default = def_rate_dl or '50' o.size = 4 o.datatype = "uinteger" o = x:option(ListValue, "unit", translate("Unit")) o.default = def_unit_dl or "kbytes" o:value("bytes", "Bytes/s") o:value("kbytes", "KBytes/s") o:value("mbytes", "MBytes/s") -- -- Static Limit Rate - Upload Rate -- y = m:section(TypedSection, "upload", translate("Static QoS-Upload Rate")) y.anonymous = true y.addremove = true y.template = "cbi/tblsection" o = y:option(Value, "hostname", translate("Hostname")) o.datatype = "hostname" o.default = 'undefined' if has_ipv6 then o = y:option(Value, "ipaddr", translate("IP Address(V4 / V6)")) else o = y:option(Value, "ipaddr", translate("IP Address(V4 Only)")) end o.datatype = "ipaddr" if nixio.fs.access("/tmp/dhcp.leases") or nixio.fs.access("/var/dhcp6.leases") then o.titleref = luci.dispatcher.build_url("admin", "status", "overview") end o = y:option(Value, "macaddr", translate("MAC (optional)")) o.rmempty = true o.datatype = "macaddr" o = y:option(Value, "rate", translate("Rate")) o.default = def_rate_ul or '50' o.size = 4 o.datatype = "uinteger" o = y:option(ListValue, "unit", translate("Unit")) o.default = def_unit_ul or "kbytes" o:value("bytes", "Bytes/s") o:value("kbytes", "KBytes/s") o:value("mbytes", "MBytes/s") end -- -- Traffic Priority Settings -- if enable_priority == "1" then s = m:section(TypedSection, "priority", translate("Traffic Priority Settings")) s.anonymous = true s.addremove = true s.template = "cbi/tblsection" o = s:option(ListValue, "protocol", translate("Protocol")) o.default = "tcp" o:value("tcp", "TCP") o:value("udp", "UDP") o:value("udplite", "UDP-Lite") o:value("sctp", "SCTP") o:value("dccp", "DCCP") o = s:option(ListValue, "priority", translate("Priority")) o.default = "1" o:value("-400", "1") o:value("-300", "2") o:value("-225", "3") o:value("-200", "4") o:value("-150", "5") o:value("-100", "6") o:value("0", "7") o:value("50", "8") o:value("100", "9") o:value("225", "10") o:value("300", "11") o = s:option(Value, "service", translate("Service"), translate("e.g. https, 23, (separator is comma)")) o.default = '?' o = s:option(Value, "comment", translate("Comment")) o.default = '?' end return m
apache-2.0
camchenry/shaderview
libs/class.lua
9
3066
--[[ Copyright (c) 2010-2013 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local function include_helper(to, from, seen) if from == nil then return to elseif type(from) ~= 'table' then return from elseif seen[from] then return seen[from] end seen[from] = to for k,v in pairs(from) do k = include_helper({}, k, seen) -- keys might also be tables if to[k] == nil then to[k] = include_helper({}, v, seen) end end return to end -- deeply copies `other' into `class'. keys in `other' that are already -- defined in `class' are omitted local function include(class, other) return include_helper(class, other, {}) end -- returns a deep copy of `other' local function clone(other) return setmetatable(include({}, other), getmetatable(other)) end local function new(class) -- mixins class = class or {} -- class can be nil local inc = class.__includes or {} if getmetatable(inc) then inc = {inc} end for _, other in ipairs(inc) do if type(other) == "string" then other = _G[other] end include(class, other) end -- class implementation class.__index = class class.init = class.init or class[1] or function() end class.include = class.include or include class.clone = class.clone or clone -- constructor call return setmetatable(class, {__call = function(c, ...) local o = setmetatable({}, c) o:init(...) return o end}) end -- interface for cross class-system compatibility (see https://github.com/bartbes/Class-Commons). if class_commons ~= false and not common then common = {} function common.class(name, prototype, parent) return new{__includes = {prototype, parent}} end function common.instance(class, ...) return class(...) end end -- the module return setmetatable({new = new, include = include, clone = clone}, {__call = function(_,...) return new(...) end})
mit
kalyanreddyemani/hpg-bigdata
hpg-bigdata-core/native/third-party/samtools/misc/r2plot.lua
28
2877
#!/usr/bin/env luajit function string:split(sep, n) local a, start = {}, 1; sep = sep or "%s+"; repeat local b, e = self:find(sep, start); if b == nil then table.insert(a, self:sub(start)); break end a[#a+1] = self:sub(start, b - 1); start = e + 1; if n and #a == n then table.insert(a, self:sub(start)); break end until start > #self; return a; end function io.xopen(fn, mode) mode = mode or 'r'; if fn == nil then return io.stdin; elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout; elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w'); elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w'); else return io.open(fn, mode) end end local eps = {}; function eps.func(fp) fp = fp or io.stdout fp:write("/C { dup 255 and 255 div exch dup -8 bitshift 255 and 255 div 3 1 roll -16 bitshift 255 and 255 div 3 1 roll setrgbcolor } bind def\n") fp:write("/L { 4 2 roll moveto lineto } bind def\n") fp:write("/LX { dup 4 -1 roll exch moveto lineto } bind def\n") fp:write("/LY { dup 4 -1 roll moveto exch lineto } bind def\n") fp:write("/LS { 3 1 roll moveto show } bind def\n") fp:write("/RS { dup stringwidth pop 4 -1 roll exch sub 3 -1 roll moveto show } bind def\n") fp:write("/B { 4 copy 3 1 roll exch 6 2 roll 8 -2 roll moveto lineto lineto lineto closepath } bind def\n") end function eps.font(ft, size, fp) fp = fp or io.stdout fp:write(string.format('/FS %d def\n', size)); fp:write('/FS4 FS 4 div def\n'); fp:write('/' .. ft .. ' findfont FS scalefont setfont\n'); end local scale = 8; if #arg == 0 then print("Usage: r2plot.lua <in.txt>"); os.exit(1) end local fp = io.xopen(arg[1]); local n = tonumber(fp:read()); print('%!PS-Adobe-3.0 EPSF-3.0'); print('%%' .. string.format('BoundingBox: -%d -%d %.3f %.3f\n', 10*scale, scale, (n+1)*scale, (n+1)*scale)); print(string.format('%.3f setlinewidth', scale)); print(string.format('/plot { setgray moveto 0 %d rlineto } def', scale)); print(string.format('/plothalf { setgray moveto 0 %.2f rlineto } def', scale/2)); eps.func(); eps.font('Helvetica', scale-1); local i = 1; for l in fp:lines() do local t = l:split('\t'); print(string.format("%d %d FS4 add (%s) RS", (i-1)*scale-2, (i-1)*scale, t[1])); for j = 2, #t do if tonumber(t[j]) > 0.01 then print(string.format('%.2f %.2f %.2f plot stroke', (i-1+.5)*scale, (j-2)*scale, 1.-t[j])); end end i = i + 1; end for j = 1, 21 do print(string.format('%.2f %.2f %.2f plothalf stroke', -8*scale, (j-1) * scale/2, 1.-(j-1)/20)); end print('showpage');
apache-2.0
hnyman/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/system.lua
78
2244
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.util") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) s = m:section(TypedSection, "system", "") s.anonymous = true s.addremove = false local sysinfo = luci.util.ubus("system", "info") or { } local boardinfo = luci.util.ubus("system", "board") or { } local uptime = sysinfo.uptime or 0 local loads = sysinfo.load or { 0, 0, 0 } local memory = sysinfo.memory or { total = 0, free = 0, buffered = 0, shared = 0 } s:option(DummyValue, "_system", translate("Model")).value = boardinfo.model or "?" s:option(DummyValue, "_cpu", translate("System")).value = boardinfo.system or "?" s:option(DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0) s:option(DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s)", tonumber(memory.total) / 1024 / 1024, 100 * memory.buffered / memory.total, tostring(translate("buffered")), 100 * memory.free / memory.total, tostring(translate("free")) ) s:option(DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("Hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
apache-2.0
Noltari/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/system.lua
78
2244
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.util") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) s = m:section(TypedSection, "system", "") s.anonymous = true s.addremove = false local sysinfo = luci.util.ubus("system", "info") or { } local boardinfo = luci.util.ubus("system", "board") or { } local uptime = sysinfo.uptime or 0 local loads = sysinfo.load or { 0, 0, 0 } local memory = sysinfo.memory or { total = 0, free = 0, buffered = 0, shared = 0 } s:option(DummyValue, "_system", translate("Model")).value = boardinfo.model or "?" s:option(DummyValue, "_cpu", translate("System")).value = boardinfo.system or "?" s:option(DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0) s:option(DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s)", tonumber(memory.total) / 1024 / 1024, 100 * memory.buffered / memory.total, tostring(translate("buffered")), 100 * memory.free / memory.total, tostring(translate("free")) ) s:option(DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("Hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
apache-2.0
tsharly/TSHARLY
plugins/lockfwd.lua
1
1095
do local function pre_process(msg) local hash = 'mate:'..msg.to.id if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) then delete_msg(msg.id, ok_cb, true) return "done" end return msg end local function taha(msg, matches) chat_id = msg.to.id if is_momod(msg) and matches[1] == 'قفل التوجيه' then local hash = 'mate:'..msg.to.id redis:set(hash, true) return "تم قفل اعاده توجيه في المجموعه🚩🔒" elseif is_momod(msg) and matches[1] == 'فتح التوجيه' then local hash = 'mate:'..msg.to.id redis:del(hash) return "تم فتح اعاده توجيه في المجموعه 🚩�🔒" end end return { patterns = { '^(قفل التوجيه)$', '^(فتح التوجيه)$', '^[/!#](قفل التوجيه)$', '^[/!#](فتح التوجيه)$' }, run = taha, pre_process = pre_process } end
gpl-2.0
hnyman/luci
applications/luci-app-dockerman/luasrc/model/cbi/dockerman/images.lua
3
7928
--[[ LuCI - Lua Configuration Interface Copyright 2019 lisaac <https://github.com/lisaac/luci-app-dockerman> ]]-- local docker = require "luci.model.docker" local dk = docker.new() local containers, images, res local m, s, o res = dk.images:list() if res.code < 300 then images = res.body else return end res = dk.containers:list({ query = { all=true } }) if res.code < 300 then containers = res.body else return end function get_images() local data = {} for i, v in ipairs(images) do local index = v.Created .. v.Id data[index]={} data[index]["_selected"] = 0 data[index]["id"] = v.Id:sub(8) data[index]["_id"] = '<a href="javascript:new_tag(\''..v.Id:sub(8,20)..'\')" class="dockerman-link" title="'..translate("New tag")..'">' .. v.Id:sub(8,20) .. '</a>' if v.RepoTags and next(v.RepoTags)~=nil then for i, v1 in ipairs(v.RepoTags) do data[index]["_tags"] =(data[index]["_tags"] and ( data[index]["_tags"] .. "<br />" )or "") .. ((v1:match("<none>") or (#v.RepoTags == 1)) and v1 or ('<a href="javascript:un_tag(\''..v1..'\')" class="dockerman_link" title="'..translate("Remove tag")..'" >' .. v1 .. '</a>')) if not data[index]["tag"] then data[index]["tag"] = v1 end end else data[index]["_tags"] = v.RepoDigests[1] and v.RepoDigests[1]:match("^(.-)@.+") data[index]["_tags"] = (data[index]["_tags"] and data[index]["_tags"] or "<none>" ).. ":<none>" end data[index]["_tags"] = data[index]["_tags"]:gsub("<none>","&lt;none&gt;") for ci,cv in ipairs(containers) do if v.Id == cv.ImageID then data[index]["_containers"] = (data[index]["_containers"] and (data[index]["_containers"] .. " | ") or "").. '<a href='..luci.dispatcher.build_url("admin/docker/container/"..cv.Id)..' class="dockerman_link" title="'..translate("Container detail")..'">'.. cv.Names[1]:sub(2).."</a>" end end data[index]["_size"] = string.format("%.2f", tostring(v.Size/1024/1024)).."MB" data[index]["_created"] = os.date("%Y/%m/%d %H:%M:%S",v.Created) end return data end local image_list = get_images() m = SimpleForm("docker", translate("Docker - Images"), translate("On this page all images are displayed that are available on the system and with which a container can be created.")) m.submit=false m.reset=false local pull_value={ _image_tag_name="", _registry="index.docker.io" } s = m:section(SimpleSection, translate("Pull Image"), translate("By entering a valid image name with the corresponding version, the docker image can be downloaded from the configured registry.")) s.template="cbi/nullsection" o = s:option(Value, "_image_tag_name") o.template = "dockerman/cbi/inlinevalue" o.placeholder="lisaac/luci:latest" o.write = function(self, section, value) local hastag = value:find(":") if not hastag then value = value .. ":latest" end pull_value["_image_tag_name"] = value end o = s:option(Button, "_pull") o.inputtitle= translate("Pull") o.template = "dockerman/cbi/inlinebutton" o.inputstyle = "add" o.write = function(self, section) local tag = pull_value["_image_tag_name"] local json_stringify = luci.jsonc and luci.jsonc.stringify if tag and tag ~= "" then docker:write_status("Images: " .. "pulling" .. " " .. tag .. "...\n") local res = dk.images:create({query = {fromImage=tag}}, docker.pull_image_show_status_cb) if res and res.code == 200 and (res.body[#res.body] and not res.body[#res.body].error and res.body[#res.body].status and (res.body[#res.body].status == "Status: Downloaded newer image for ".. tag)) then docker:clear_status() else docker:append_status("code:" .. res.code.." ".. (res.body[#res.body] and res.body[#res.body].error or (res.body.message or res.message)).. "\n") end else docker:append_status("code: 400 please input the name of image name!") end luci.http.redirect(luci.dispatcher.build_url("admin/docker/images")) end s = m:section(SimpleSection, translate("Import Image"), translate("When pressing the Import button, both a local image can be loaded onto the system and a valid image tar can be downloaded from remote.")) o = s:option(DummyValue, "_image_import") o.template = "dockerman/images_import" s = m:section(Table, image_list, translate("Images overview")) o = s:option(Flag, "_selected","") o.disabled = 0 o.enabled = 1 o.default = 0 o.write = function(self, section, value) image_list[section]._selected = value end o = s:option(DummyValue, "_tags", translate("RepoTags")) o.rawhtml = true o = s:option(DummyValue, "_containers", translate("Containers")) o.rawhtml = true o = s:option(DummyValue, "_size", translate("Size")) o = s:option(DummyValue, "_created", translate("Created")) o = s:option(DummyValue, "_id", translate("ID")) o.rawhtml = true local remove_action = function(force) local image_selected = {} for k in pairs(image_list) do if image_list[k]._selected == 1 then image_selected[#image_selected+1] = (image_list[k]["_tags"]:match("<br />") or image_list[k]["_tags"]:match("&lt;none&gt;")) and image_list[k].id or image_list[k].tag end end if next(image_selected) ~= nil then local success = true docker:clear_status() for _, img in ipairs(image_selected) do local query docker:append_status("Images: " .. "remove" .. " " .. img .. "...") if force then query = {force = true} end local msg = dk.images:remove({ id = img, query = query }) if msg.code ~= 200 then docker:append_status("code:" .. msg.code.." ".. (msg.body.message and msg.body.message or msg.message).. "\n") success = false else docker:append_status("done\n") end end if success then docker:clear_status() end luci.http.redirect(luci.dispatcher.build_url("admin/docker/images")) end end s = m:section(SimpleSection) s.template = "dockerman/apply_widget" s.err = docker:read_status() s.err = s.err and s.err:gsub("\n","<br />"):gsub(" ","&#160;") if s.err then docker:clear_status() end s = m:section(Table,{{}}) s.notitle=true s.rowcolors=false s.template="cbi/nullsection" o = s:option(Button, "remove") o.inputtitle= translate("Remove") o.template = "dockerman/cbi/inlinebutton" o.inputstyle = "remove" o.forcewrite = true o.write = function(self, section) remove_action() end o = s:option(Button, "forceremove") o.inputtitle= translate("Force Remove") o.template = "dockerman/cbi/inlinebutton" o.inputstyle = "remove" o.forcewrite = true o.write = function(self, section) remove_action(true) end o = s:option(Button, "save") o.inputtitle= translate("Save") o.template = "dockerman/cbi/inlinebutton" o.inputstyle = "edit" o.forcewrite = true o.write = function (self, section) local image_selected = {} for k in pairs(image_list) do if image_list[k]._selected == 1 then image_selected[#image_selected + 1] = image_list[k].id end end if next(image_selected) ~= nil then local names, first for _, img in ipairs(image_selected) do names = names and (names .. "&names=".. img) or img end local cb = function(res, chunk) if res.code == 200 then if not first then first = true luci.http.header('Content-Disposition', 'inline; filename="images.tar"') luci.http.header('Content-Type', 'application\/x-tar') end luci.ltn12.pump.all(chunk, luci.http.write) else if not first then first = true luci.http.prepare_content("text/plain") end luci.ltn12.pump.all(chunk, luci.http.write) end end docker:write_status("Images: " .. "save" .. " " .. table.concat(image_selected, "\n") .. "...") local msg = dk.images:get({query = {names = names}}, cb) if msg.code ~= 200 then docker:append_status("code:" .. msg.code.." ".. (msg.body.message and msg.body.message or msg.message).. "\n") success = false else docker:clear_status() end end end o = s:option(Button, "load") o.inputtitle= translate("Load") o.template = "dockerman/images_load" o.inputstyle = "add" return m
apache-2.0
adminomega/exterme-orginal
plugins/id.lua
226
4260
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' for k,v in pairs(result.members) do text = text .. v.print_name .. " (user#id" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')' if is_chat_msg(msg) then text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end elseif matches[1] == "member" and matches[2] == "@" then local nick = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local receiver = extra.receiver local nick = extra.nick local found for k,user in pairs(result.members) do if user.username == nick then found = user end end if not found then send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "ID: "..found.id send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, nick=nick}) elseif matches[1] == "members" and matches[2] == "name" then local text = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local members = result.members local receiver = extra.receiver local text = extra.text local founds = {} for k,member in pairs(members) do local fields = {'first_name', 'print_name', 'username'} for k,field in pairs(fields) do if member[field] and type(member[field]) == "string" then if member[field]:match(text) then local id = tostring(member.id) founds[id] = member end end end end if next(founds) == nil then -- Empty table send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "" for k,user in pairs(founds) do local first_name = user.first_name or "" local print_name = user.print_name or "" local user_name = user.user_name or "" local id = user.id or "" -- This would be funny text = text.."First name: "..first_name.."\n" .."Print name: "..print_name.."\n" .."User name: "..user_name.."\n" .."ID: "..id end send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, text=text}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id member @<user_name>: Return the member @<user_name> ID from the current chat", "!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat" }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (member) (@)(.+)", "^!id (members) (name) (.+)" }, run = run }
gpl-2.0
LaFamiglia/Illarion-Content
item/id_6_scissors.lua
1
3506
--[[ Illarion Server 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 (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 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/>. ]] -- UPDATE items SET itm_script='item.id_6_scissors' WHERE itm_id IN (6); local common = require("base.common") local entrailscutting = require("content.gatheringcraft.entrailscutting") local licence = require("base.licence") local threadproducing = require("content.gatheringcraft.threadproducing") local weaving = require("content.gatheringcraft.weaving") local woolcutting = require("content.gatheringcraft.woolcutting") local metal = require("item.general.metal") local M = {} M.LookAtItem = metal.LookAtItem function getLoom(User) local LOOM = 169; local item = common.GetFrontItem(User); if (item ~= nil and item.id == LOOM) then return item; end item = common.GetItemInArea(User.pos, LOOM); return item; end function getWheel(User) local WHEEL = 171; local item = common.GetFrontItem(User); if (item ~= nil and item.id == WHEEL) then return item; end item = common.GetItemInArea(User.pos, WHEEL); return item; end function getSheep(User) local targetCharacter = common.GetFrontCharacter(User); -- check for sheep in front if (targetCharacter ~= nil and targetCharacter:getRace()==18) then return targetCharacter; end -- look for a nearby sheep for x=-1,1 do for y=-1,1 do local pos = position(User.pos.x+x,User.pos.y+y,User.pos.z); if ( world:isCharacterOnField(pos) ) then targetCharacter = world:getCharacterOnField(pos); if ( targetCharacter:getRace() == 18 ) then return targetCharacter; end end end end return nil; end function M.UseItem(User, SourceItem, ltstate) local target; -- check for sheep target = getSheep(User); if (target ~= nil) then woolcutting.StartGathering(User, target, ltstate); return; end -- check for spinning wheel target = getWheel(User); if (target ~= nil) then if licence.licence(User) then --checks if user is citizen or has a licence return -- avoids crafting if user is neither citizen nor has a licence end threadproducing.StartGathering(User, target, ltstate); return; end -- check for loom target = getLoom(User); if (target ~= nil) then if licence.licence(User) then --checks if user is citizen or has a licence return -- avoids crafting if user is neither citizen nor has a licence end weaving.StartGathering(User, target, ltstate); return; end -- check for entrails in inventory if (User:countItemAt("all", 63) > 0) then entrailscutting.StartGathering(User, nil, ltstate); return; end -- there is nothing to work with common.HighInformNLS( User, "Du brauchst entweder ein Schaf, um es zu scheren, musst for einem Spinnrad oder Webstuhl stehen, oder brauchst Eingeweide, um sie zu Garn zu zerschneiden.", "You need either a sheep for shearing it, or need to stand in front of a spinning wheel or loom, or need entrails for cutting it and thus producing thread." ); end return M
agpl-3.0
matthiasweller/Oxide-Plugins
Oxide 2/0friendsAPI.lua
1
14688
PLUGIN.Title = "FriendsAPI" PLUGIN.Description = "An API to manage friends" PLUGIN.Author = "#Domestos" PLUGIN.Version = V(1, 2, 4) PLUGIN.ResourceID = 686 local debugMode = false function PLUGIN:Init() command.AddChatCommand("friend", self.Object, "cmdFriend") command.AddConsoleCommand("friendsapi.debug", self.Object, "ccmdDebug") self:LoadDefaultConfig() self:LoadDataFile() end function PLUGIN:LoadDefaultConfig() self.Config.Settings = self.Config.Settings or {} self.Config.Settings.MaxFriends = self.Config.Settings.MaxFriends or 30 self.Config.Messages = self.Config.Messages or {} self.Config.Messages.List = self.Config.Messages.List or "Friends {count}: " self.Config.Messages.NoFriends = self.Config.Messages.NoFriends or "You dont have friends :(" self.Config.Messages.NotOnFriendlist = self.Config.Messages.NotOnFriendlist or "{target} not found on your friendlist" self.Config.Messages.FriendRemoved = self.Config.Messages.FriendRemoved or "{target} was removed from your friendlist" self.Config.Messages.PlayerNotFound = self.Config.Messages.PlayerNotFound or "Player not found" self.Config.Messages.CantAddSelf = self.Config.Messages.CantAddSelf or "You cant add yourself" self.Config.Messages.AlreadyOnList = self.Config.Messages.AlreadyOnList or "{target} is already your friend" self.Config.Messages.FriendAdded = self.Config.Messages.FriendAdded or "{target} is now your friend" self.Config.Messages.FriendlistFull = self.Config.Messages.FriendlistFull or "Your friendlist is full" self.Config.Messages.HelpText = self.Config.Messages.HelpText or "use /friend <add|remove|list> <name/steamID> to add/remove/list friends" end -- -------------------------------- -- datafile handling -- -------------------------------- local DataFile = "friends" local Data = {} function PLUGIN:LoadDataFile() local data = datafile.GetDataTable(DataFile) Data = data or {} end function PLUGIN:SaveDataFile() datafile.SaveDataTable(DataFile) end -- -------------------------------- -- prints to server console -- -------------------------------- local function printToConsole(msg) global.ServerConsole.PrintColoured(System.ConsoleColor.Cyan, msg) end -- -------------------------------- -- debug print -- -------------------------------- local function debug(msg) if not debugMode then return end global.ServerConsole.PrintColoured(System.ConsoleColor.Yellow, msg) end -- -------------------------------- -- try to find a BasePlayer -- returns (int) numFound, (table) playerTbl -- -------------------------------- local function FindPlayer(NameOrIpOrSteamID, checkSleeper) local playerTbl = {} local playerList = global.BasePlayer.activePlayerList:GetEnumerator() while playerList:MoveNext() do if playerList.Current then local currPlayer = playerList.Current local currSteamID = rust.UserIDFromPlayer(currPlayer) local currIP = currPlayer.net.connection.ipaddress if currPlayer.displayName == NameOrIpOrSteamID or currSteamID == NameOrIpOrSteamID or currIP == NameOrIpOrSteamID then table.insert(playerTbl, currPlayer) return #playerTbl, playerTbl end local matched, _ = string.find(currPlayer.displayName:lower(), NameOrIpOrSteamID:lower(), 1, true) if matched then table.insert(playerTbl, currPlayer) end end end if checkSleeper then local sleeperList = global.BasePlayer.sleepingPlayerList:GetEnumerator() while sleeperList:MoveNext() do if sleeperList.Current then local currPlayer = sleeperList.Current local currSteamID = rust.UserIDFromPlayer(currPlayer) if currPlayer.displayName == NameOrIpOrSteamID or currSteamID == NameOrIpOrSteamID then table.insert(playerTbl, currPlayer) return #playerTbl, playerTbl end local matched, _ = string.find(currPlayer.displayName:lower(), NameOrIpOrSteamID:lower(), 1, true) if matched then table.insert(playerTbl, currPlayer) end end end end return #playerTbl, playerTbl end -- -------------------------------- -- builds output messages by replacing wildcards -- -------------------------------- local function buildOutput(str, tags, replacements) for i = 1, #tags do str = str:gsub(tags[i], replacements[i]) end return str end -- -------------------------------- -- handles chat command /friend -- -------------------------------- function PLUGIN:cmdFriend(player, _, args) debug("## [FriendsAPI debug] cmdFriend() ##") if not player then return end local args = self:ArgsToTable(args, "chat") local func, target = args[1], args[2] local playerSteamID = rust.UserIDFromPlayer(player) debug("func: "..tostring(func)) debug("target: "..tostring(target)) if not func or func ~= "add" and func ~= "remove" and func ~= "list" then rust.SendChatMessage(player, "Syntax: /friend <add/remove> <name/steamID> or /friend list") return end if func ~= "list" and not target then rust.SendChatMessage(player, "Syntax: /friend <add/remove> <name/steamID>") return end if func == "list" then local friendlist = self:GetFriendlist(playerSteamID) if friendlist then local i, playerCount = 1, 0 local friendlistString = "" local friendlistTbl = {} -- build friendlist string for _, value in pairs(friendlist) do playerCount = playerCount + 1 friendlistString = friendlistString..value..", " if playerCount == 8 then friendlistTbl[i] = friendlistString friendlistString = "" playerCount = 0 i = i + 1 end end -- remove comma at the end if friendlistString:sub(-2, -2) == "," then friendlistString = friendlistString:sub(1, -3) end debug("friendlistString: "..friendlistString) -- output friendlist if #friendlistTbl >= 1 then rust.SendChatMessage(player, buildOutput(self.Config.Messages.List, {"{count}"}, {"["..tostring(#friendlist).."/"..tostring(self.Config.Settings.MaxFriends).."]"})) for i = 1, #friendlistTbl do rust.SendChatMessage(player, friendlistTbl[i]) end rust.SendChatMessage(player, friendlistString) else rust.SendChatMessage(player, buildOutput(self.Config.Messages.List, {"{count}"}, {"["..tostring(#friendlist).."/"..tostring(self.Config.Settings.MaxFriends).."]"})..friendlistString) end return end debug("no friends") rust.SendChatMessage(player, self.Config.Messages.NoFriends) return end local numFound, targetPlayerTbl = FindPlayer(target, true) debug("numFound: "..tostring(numFound)) if numFound == 0 then rust.SendChatMessage(player, self.Config.Messages.PlayerNotFound) return end if numFound > 1 then local targetNameString = "" for i = 1, numFound do targetNameString = targetNameString..targetPlayerTbl[i].displayName..", " end rust.SendChatMessage(player, "Found more than one player, be more specific:") rust.SendChatMessage(player, targetNameString) return end local targetPlayer = targetPlayerTbl[1] local targetName = targetPlayer.displayName local targetSteamID = rust.UserIDFromPlayer(targetPlayer) debug("targetName: "..targetName) debug("targetSteamID "..targetSteamID) if func == "remove" then local removed = self:removeFriend(playerSteamID, targetSteamID) debug("removed: "..tostring(removed)) if not removed then rust.SendChatMessage(player, buildOutput(self.Config.Messages.NotOnFriendlist, {"{target}"}, {targetName})) else rust.SendChatMessage(player, buildOutput(self.Config.Messages.FriendRemoved, {"{target}"}, {targetName})) end return end if func == "add" then if player == targetPlayer then rust.SendChatMessage(player, self.Config.Messages.CantAddSelf) return end local added = self:addFriend(player, targetSteamID, targetName) debug("added: "..tostring(added)) if added == "max" then rust.SendChatMessage(player, self.Config.Messages.FriendlistFull) return end if not added then rust.SendChatMessage(player, buildOutput(self.Config.Messages.AlreadyOnList, {"{target}"}, {targetName})) else rust.SendChatMessage(player, buildOutput(self.Config.Messages.FriendAdded, {"{target}"}, {targetName})) end return end end -- -------------------------------- -- returns true if player was removed -- returns false if not (not on friendlist) -- -------------------------------- function PLUGIN:removeFriend(playerSteamID, target) local playerData = self:GetPlayerData(playerSteamID) if not playerData then return false end for key, _ in pairs(playerData.Friends) do if playerData.Friends[key].steamID == target or playerData.Friends[key].name == target then table.remove(playerData.Friends, key) if #playerData.Friends == 0 then Data[playerSteamID] = nil end self:SaveDataFile() return true end end return false end -- -------------------------------- -- returns true if friend was added -- returns false if not (is already on friendlist) -- -------------------------------- function PLUGIN:addFriend(player, targetSteamID, targetName) local playerSteamID = rust.UserIDFromPlayer(player) local playerName = player.displayName local playerData = self:GetPlayerData(playerSteamID, playerName, true) if #playerData.Friends >= self.Config.Settings.MaxFriends then return "max" end for key, _ in pairs(playerData.Friends) do if playerData.Friends[key].steamID == targetSteamID then return false end end local newFriend = {["name"] = targetName, ["steamID"] = targetSteamID} table.insert(playerData.Friends, newFriend) self:SaveDataFile() return true end -- -------------------------------- -- returns true when player has target on friendlist -- returns false if not -- -------------------------------- function PLUGIN:HasFriend(playerSteamID, target) local playerData = self:GetPlayerData(playerSteamID) if not playerData then return false end for key, _ in pairs(playerData.Friends) do if playerData.Friends[key].steamID == target or playerData.Friends[key].name == target then return true end end return false end -- -------------------------------- -- returns true when player is on targets friendlist -- returns false if hes not -- -------------------------------- function PLUGIN:IsFriendFrom(player, targetSteamID) local playerData = self:GetPlayerData(targetSteamID) if not playerData then return false end for key, _ in pairs(playerData.Friends) do if playerData.Friends[key].steamID == player or playerData.Friends[key].name == player then return true end end return false end -- -------------------------------- -- returns true when player and target are friends -- returns false when they are not -- -------------------------------- function PLUGIN:areFriends(playerSteamID, targetSteamID) local hasFriend = self:HasFriend(playerSteamID, targetSteamID) local isFriend = self:IsFriendFrom(playerSteamID, targetSteamID) if hasFriend and isFriend then return true end return false end -- -------------------------------- -- returns a players friendlist as table -- if known, the table will return the names, if not it returns steamID -- returns false if player has no friends -- -------------------------------- function PLUGIN:GetFriendlist(playerSteamID) local playerData = self:GetPlayerData(playerSteamID) if not playerData then return false end local friends = {} for key, _ in pairs(playerData.Friends) do friends[key] = playerData.Friends[key].name end return friends end -- -------------------------------- -- returns args as a table -- -------------------------------- function PLUGIN:ArgsToTable(args, src) local argsTbl = {} if src == "chat" then local length = args.Length for i = 0, length - 1, 1 do argsTbl[i + 1] = args[i] end return argsTbl end if src == "console" then local i = 1 while args:HasArgs(i) do argsTbl[i] = args:GetString(i - 1) i = i + 1 end return argsTbl end return argsTbl end -- -------------------------------- -- returns table with player data -- -------------------------------- function PLUGIN:GetPlayerData(playerSteamID, playerName, addNewEntry) local playerData = Data[playerSteamID] if not playerData and addNewEntry then playerData = {} playerData.SteamID = playerSteamID playerData.Name = playerName playerData.Friends = {} Data[playerSteamID] = playerData self:SaveDataFile() end return playerData end -- -------------------------------- -- sends the helptext -- -------------------------------- function PLUGIN:SendHelpText(player) rust.SendChatMessage(player, self.Config.Messages.HelpText) end -- -------------------------------- -- activate/deactivate debug mode -- -------------------------------- function PLUGIN:ccmdDebug(arg) if arg.connection then return end -- terminate if not server console local args = self:ArgsToTable(arg, "console") if args[1] == "true" then debugMode = true printToConsole("[FriendsAPI]: debug mode activated") elseif args[1] == "false" then debugMode = false printToConsole("[FriendsAPI]: debug mode deactivated") else printToConsole("Syntax: friendsapi.debug true/false") end end
mit
Death15/swatch
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
shahabsaf1/copy-infernal
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
agentsnazz/sb-mods
Theatre/concerteq/objects/generic/follower/Bfollower/Bfollower.lua
1
7388
function init(args) self.state = stateMachine.create({ "attackState", "scanState" }) entity.setAnimationState("movement", "idle") entity.setInteractive(false) entity.setAllOutboundNodes(false) end -------------------------------------------------------------------------------- function main(args) self.state.update(entity.dt()) end -------------------------------------------------------------------------------- function toAbsolutePosition(offset) if entity.direction() > 0 then return vec2.add(entity.position(), offset) else return vec2.sub(entity.position(), offset) end end -------------------------------------------------------------------------------- function getBasePosition() local baseOffset = entity.configParameter("baseOffset") return toAbsolutePosition(baseOffset) end -------------------------------------------------------------------------------- function setAimAngle(basePosition, targetAimAngle) entity.rotateGroup("gun", -targetAimAngle) local tipOffset = entity.configParameter("tipOffset") local tipPosition = toAbsolutePosition(tipOffset) local aimAngle = entity.currentRotationAngle("gun") local facingDirection = entity.direction() local aimVector = vec2.rotate(world.distance(tipPosition, basePosition), aimAngle * facingDirection) tipPosition = vec2.add(vec2.dup(basePosition), aimVector) tipOffset = world.distance(tipPosition, entity.position()) vec2.norm(aimVector) local laserVector = vec2.mul(aimVector, entity.configParameter("maxLaserLength")) local laserEndpoint = vec2.add({ tipPosition[1], tipPosition[2] }, laserVector) local blocks = world.collisionBlocksAlongLine(tipPosition, laserEndpoint, true, 1) if #blocks > 0 then local blockPosition = blocks[1] local delta = world.distance(blockPosition, tipPosition) local x0, x1 = blockPosition[1], blockPosition[1] + 1 if delta[1] < 0 then x0, x1 = x1, x0 end local y0, y1 = blockPosition[2], blockPosition[2] + 1 if delta[2] < 0 then y0, y1 = y1, y0 end local xIntersection = vec2.intersect(tipPosition, laserEndpoint, { x0, y0 }, { x0, y1 }) local yIntersection = vec2.intersect(tipPosition, laserEndpoint, { x0, y0 }, { x1, y0 }) if yIntersection == nil then if xIntersection ~= nil then laserEndpoint = xIntersection end elseif xIntersection == nil then if yIntersection ~= nil then laserEndpoint = yIntersection end else local xSegment = world.distance(xIntersection, tipPosition) local ySegment = world.distance(yIntersection, tipPosition) if world.magnitude(xSegment) > world.magnitude(ySegment) then laserEndpoint = yIntersection else laserEndpoint = xIntersection end end end world.debugLine(tipPosition, laserEndpoint, "red") return -aimAngle, tipPosition, laserEndpoint end -------------------------------------------------------------------------------- scanState = {} function scanState.enter() return { timer = -entity.configParameter("rotationPauseTime"), direction = 1 } end function scanState.enteringState(stateData) entity.setAnimationState("beam", "visible") end function scanState.update(dt, stateData) local rotationRange = vec2.mul(entity.configParameter("rotationRange"), math.pi / 360) local rotationTime = entity.configParameter("rotationTime") local angle = util.easeInOutQuad( util.clamp(stateData.timer, 0, rotationTime) / rotationTime, rotationRange[1], rotationRange[2] ) if stateData.direction < 0 then angle = rotationRange[2] - angle end if stateData.timer < 0 or stateData.timer > rotationTime then entity.setAnimationState("movement", "idle") else entity.setAnimationState("movement", "idle") end local basePosition = getBasePosition() local aimAngle, laserOrigin, laserEndpoint = setAimAngle(basePosition, angle) local length = world.magnitude(laserOrigin, laserEndpoint) entity.scaleGroup("beam", { length, 10.0 }) local targetId = scanState.findTarget(laserOrigin, laserEndpoint) if targetId ~= 0 then self.state.pickState(targetId) return true end stateData.timer = stateData.timer + dt if stateData.timer > rotationTime then stateData.timer = -entity.configParameter("rotationPauseTime") stateData.direction = -stateData.direction end return false end function scanState.leavingState(stateData) entity.setAnimationState("beam", "invisible") end function scanState.findTarget(startPosition, endPosition) local selfId = entity.id() local entityIds = world.entityLineQuery(startPosition, endPosition, { validTargetOf = selfId }) for i, entityId in ipairs(entityIds) do if entityId ~= selfId then return entityId end end return 0 end -------------------------------------------------------------------------------- attackState = {} function attackState.enterWith(targetId) entity.rotateGroup("gun", entity.currentRotationAngle("gun")) entity.setAnimationState("movement", "attack") entity.setAllOutboundNodes(true) return { timer = 0, fireTimer = 0, fireOffsetIndex = 1, targetId = targetId } end function attackState.update(dt, stateData) local targetPosition = world.entityPosition(stateData.targetId) if targetPosition == nil then entity.setAnimationState("movement", "idle") entity.setAllOutboundNodes(false) return true end local basePosition = getBasePosition() local toTarget = world.distance(targetPosition, basePosition) local desiredAimAngle = vec2.angle(toTarget) * entity.direction() if desiredAimAngle > math.pi then desiredAimAngle = 2 * math.pi - desiredAimAngle end local rotationRange = vec2.mul(entity.configParameter("rotationRange"), math.pi / 180) desiredAimAngle = util.clamp(desiredAimAngle, rotationRange[1], rotationRange[2]) local aimAngle, laserOrigin, laserEndpoint = setAimAngle(basePosition, desiredAimAngle) if not attackState.isVisible(laserOrigin, laserEndpoint, stateData.targetId) then entity.rotateGroup("gun", entity.currentRotationAngle("gun")) stateData.timer = stateData.timer + dt else stateData.fireTimer = stateData.fireTimer - dt if stateData.fireTimer <= 0 then local fireDirection = vec2.norm(vec2.sub(vec2.dup(laserEndpoint), laserOrigin)) local firePosition = vec2.dup(laserOrigin) local fireOffsets = entity.configParameter("fireOffsets") local fireOffset = fireOffsets[stateData.fireOffsetIndex] local orthoDirection = { -fireDirection[2], fireDirection[1] } vec2.add(firePosition, vec2.mul(orthoDirection, fireOffset)) world.spawnProjectile("Blight", firePosition, entity.id(), fireDirection) stateData.fireTimer = entity.configParameter("fireCooldown") stateData.fireOffsetIndex = util.incWrap(stateData.fireOffsetIndex, #fireOffsets) end stateData.timer = 0 end if stateData.timer > entity.configParameter("targetHoldTime") then entity.setAnimationState("movement", "idle") entity.setAllOutboundNodes(false) return true end return false end function attackState.isVisible(startPosition, endPosition, targetId) local entityIds = world.entityLineQuery(startPosition, endPosition) for i, entityId in ipairs(entityIds) do if entityId == targetId then return true end end return false end
unlicense
ninjalulz/forgottenserver
data/spells/scripts/custom/polymorph.lua
10
1084
local condition = Condition(CONDITION_OUTFIT) condition:setParameter(CONDITION_PARAM_TICKS, 20000) condition:setOutfit(0, 230, 0, 0, 0, 0) condition:setOutfit(0, 231, 0, 0, 0, 0) condition:setOutfit(0, 232, 0, 0, 0, 0) condition:setOutfit(0, 233, 0, 0, 0, 0) condition:setOutfit(0, 234, 0, 0, 0, 0) condition:setOutfit(0, 235, 0, 0, 0, 0) condition:setOutfit(0, 236, 0, 0, 0, 0) condition:setOutfit(0, 237, 0, 0, 0, 0) condition:setOutfit(0, 238, 0, 0, 0, 0) condition:setOutfit(0, 239, 0, 0, 0, 0) condition:setOutfit(0, 240, 0, 0, 0, 0) condition:setOutfit(0, 241, 0, 0, 0, 0) condition:setOutfit(0, 242, 0, 0, 0, 0) condition:setOutfit(0, 243, 0, 0, 0, 0) condition:setOutfit(0, 244, 0, 0, 0, 0) condition:setOutfit(0, 245, 0, 0, 0, 0) condition:setOutfit(0, 246, 0, 0, 0, 0) condition:setOutfit(0, 247, 0, 0, 0, 0) local combat = Combat() combat:setParameter(COMBAT_PARAM_EFFECT, CONST_ME_MAGIC_GREEN) combat:setArea(createCombatArea(AREA_SQUARE1X1)) combat:addCondition(condition) function onCastSpell(creature, variant, isHotkey) return combat:execute(creature, variant) end
gpl-2.0
Noltari/luci
applications/luci-app-advanced-reboot/luasrc/controller/advanced_reboot.lua
2
12852
-- Copyright 2017-2018 Stan Grishin <stangri@melmac.net> -- Licensed to the public under the Apache License 2.0. module("luci.controller.advanced_reboot", package.seeall) devices = { -- deviceName, boardName, partition1, partition2, offset, envVar1, envVar1Value1, envVar1Value2, envVar2, envVar2Value1, envVar2Value2 {"Linksys EA3500", "linksys-audi", "mtd3", "mtd5", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys E4200v2/EA4500", "linksys-viper", "mtd3", "mtd5", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys EA6350v3", "linksys-ea6350v3", "mtd10", "mtd12", 192, "boot_part", 1, 2}, {"Linksys EA8500", "ea8500", "mtd13", "mtd15", 32, "boot_part", 1, 2}, -- {"Linksys EA9500", "linksys-panamera", "mtd3", "mtd6", 28, "boot_part", 1, 2}, {"Linksys WRT1200AC", "linksys-caiman", "mtd4", "mtd6", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys WRT1900AC", "linksys-mamba", "mtd4", "mtd6", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys WRT1900ACv2", "linksys-cobra", "mtd4", "mtd6", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys WRT1900ACS", "linksys-shelby", "mtd4", "mtd6", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys WRT3200ACM", "linksys-rango", "mtd5", "mtd7", 32, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"Linksys WRT32X", "linksys-venom", "mtd5", "mtd7", nil, "boot_part", 1, 2, "bootcmd", "run nandboot", "run altnandboot"}, {"ZyXEL NBG6817","nbg6817","mmcblk0p4","mmcblk0p7", 32, nil, 255, 1} } errorMessage = nil rom_board_name = luci.util.trim(luci.sys.exec("cat /tmp/sysinfo/board_name")) for i=1, #devices do device_board_name = devices[i][2]:gsub('%p','') if rom_board_name and rom_board_name:gsub('%p',''):match(device_board_name) then device_name = devices[i][1] partition_one_mtd = devices[i][3] or nil partition_two_mtd = devices[i][4] or nil partition_skip = devices[i][5] or nil boot_envvar1 = devices[i][6] or nil boot_envvar1_partition_one = tonumber(devices[i][7]) or nil boot_envvar1_partition_two = tonumber(devices[i][8]) or nil boot_envvar2 = devices[i][9] or nil boot_envvar2_partition_one = devices[i][10] or nil boot_envvar2_partition_two = devices[i][11] or nil if partition_one_mtd and partition_skip then partition_one_label = luci.util.trim(luci.sys.exec("dd if=/dev/" .. partition_one_mtd .. " bs=1 skip=" .. partition_skip .. " count=128" .. " 2>/dev/null")) n, partition_one_version = string.match(partition_one_label, '(Linux)-([%d|.]+)') end if partition_two_mtd and partition_skip then partition_two_label = luci.util.trim(luci.sys.exec("dd if=/dev/" .. partition_two_mtd .. " bs=1 skip=" .. partition_skip .. " count=128" .. " 2>/dev/null")) n, partition_two_version = string.match(partition_two_label, '(Linux)-([%d|.]+)') end if partition_one_label and string.find(partition_one_label, "LEDE") then partition_one_os = "LEDE" end if partition_one_label and string.find(partition_one_label, "OpenWrt") then partition_one_os = "OpenWrt" end if partition_one_label and string.find(partition_one_label, "Linksys") then partition_one_os = "Linksys" end if partition_two_label and string.find(partition_two_label, "LEDE") then partition_two_os = "LEDE" end if partition_two_label and string.find(partition_two_label, "OpenWrt") then partition_two_os = "OpenWrt" end if partition_two_label and string.find(partition_two_label, "Linksys") then partition_two_os = "Linksys" end if device_name and device_name == "ZyXEL NBG6817" then if not partition_one_os then partition_one_os = "ZyXEL" end if not partition_two_os then partition_two_os = "ZyXEL" end end if device_name and device_name == "Linksys WRT32X" then if not partition_one_os then partition_one_os = "Unknown/Compressed" end if not partition_two_os then partition_two_os = "Unknown/Compressed" end end if not partition_one_os then partition_one_os = "Unknown" end if not partition_two_os then partition_two_os = "Unknown" end if partition_one_os and partition_one_version then partition_one_os = partition_one_os .. " (Linux " .. partition_one_version .. ")" end if partition_two_os and partition_two_version then partition_two_os = partition_two_os .. " (Linux " .. partition_two_version .. ")" end if device_name and device_name == "ZyXEL NBG6817" then if not zyxelFlagPartition then zyxelFlagPartition = luci.util.trim(luci.sys.exec("source /lib/functions.sh; find_mtd_part 0:DUAL_FLAG")) end if not zyxelFlagPartition then errorMessage = errorMessage or "" .. luci.i18n.translate("Unable to find Dual Boot Flag Partition." .. " ") luci.util.perror(luci.i18n.translate("Unable to find Dual Boot Flag Partition.")) else current_partition = tonumber(luci.sys.exec("dd if=" .. zyxelFlagPartition .. " bs=1 count=1 2>/dev/null | hexdump -n 1 -e '1/1 \"%d\"'")) end else if nixio.fs.access("/usr/sbin/fw_printenv") and nixio.fs.access("/usr/sbin/fw_setenv") then current_partition = tonumber(luci.util.trim(luci.sys.exec("/usr/sbin/fw_printenv -n " .. boot_envvar1))) end end other_partition = current_partition == boot_envvar1_partition_two and boot_envvar1_partition_one or boot_envvar1_partition_two end end function index() entry({"admin", "system", "advanced_reboot"}, template("advanced_reboot/advanced_reboot"), _("Advanced Reboot"), 90) entry({"admin", "system", "advanced_reboot", "reboot"}, post("action_reboot")) entry({"admin", "system", "advanced_reboot", "alternative_reboot"}, post("action_altreboot")) entry({"admin", "system", "advanced_reboot", "power_off"}, post("action_poweroff")) end function action_reboot() local uci = require "luci.model.uci".cursor() luci.template.render("admin_system/applyreboot", { title = luci.i18n.translate("Rebooting..."), msg = luci.i18n.translate("The system is rebooting now.<br /> DO NOT POWER OFF THE DEVICE!<br /> Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."), addr = luci.ip.new(uci:get("network", "lan", "ipaddr")) or "192.168.1.1" }) luci.sys.reboot() end function action_altreboot() local uci = require "luci.model.uci".cursor() local zyxelFlagPartition, zyxelBootFlag, zyxelNewBootFlag, errorCode, curEnvSetting, newEnvSetting errorMessage = nil errorCode = 0 if luci.http.formvalue("cancel") then luci.http.redirect(luci.dispatcher.build_url('admin/system/advanced_reboot')) return end local step = tonumber(luci.http.formvalue("step") or 1) if step == 1 then if device_name and nixio.fs.access("/usr/sbin/fw_printenv") and nixio.fs.access("/usr/sbin/fw_setenv") then luci.template.render("advanced_reboot/alternative_reboot",{}) else luci.template.render("advanced_reboot/advanced_reboot",{errorMessage = luci.i18n.translate("No access to fw_printenv or fw_printenv!")}) end elseif step == 2 then if boot_envvar1 or boot_envvar2 then -- Linksys devices if boot_envvar1 then curEnvSetting = tonumber(luci.util.trim(luci.sys.exec("/usr/sbin/fw_printenv -n " .. boot_envvar1))) if not curEnvSetting then errorMessage = errorMessage .. luci.i18n.translate("Unable to obtain firmware environment variable") .. ": " .. boot_envvar1 .. ". " luci.util.perror(luci.i18n.translate("Unable to obtain firmware environment variable") .. ": " .. boot_envvar1 .. ".") else newEnvSetting = curEnvSetting == boot_envvar1_partition_one and boot_envvar1_partition_two or boot_envvar1_partition_one errorCode = luci.sys.call("/usr/sbin/fw_setenv " .. boot_envvar1 .. " " .. newEnvSetting) if errorCode ~= 0 then errorMessage = errorMessage or "" .. luci.i18n.translate("Unable to set firmware environment variable") .. ": " .. boot_envvar1 .. " " .. luci.i18n.translate("to") .. " " .. newEnvSetting .. ". " luci.util.perror(luci.i18n.translate("Unable to set firmware environment variable") .. ": " .. boot_envvar1 .. " " .. luci.i18n.translate("to") .. " " .. newEnvSetting .. ".") end end end if boot_envvar2 then curEnvSetting = luci.util.trim(luci.sys.exec("/usr/sbin/fw_printenv -n " .. boot_envvar2)) if not curEnvSetting then errorMessage = errorMessage or "" .. luci.i18n.translate("Unable to obtain firmware environment variable") .. ": " .. boot_envvar2 .. ". " luci.util.perror(luci.i18n.translate("Unable to obtain firmware environment variable") .. ": " .. boot_envvar2 .. ".") else newEnvSetting = curEnvSetting == boot_envvar2_partition_one and boot_envvar2_partition_two or boot_envvar2_partition_one errorCode = luci.sys.call("/usr/sbin/fw_setenv " .. boot_envvar2 .. " '" .. newEnvSetting .. "'") if errorCode ~= 0 then errorMessage = errorMessage or "" .. luci.i18n.translate("Unable to set firmware environment variable") .. ": " .. boot_envvar2 .. " " .. luci.i18n.translate("to") .. " " .. newEnvSetting .. ". " luci.util.perror(luci.i18n.translate("Unable to set firmware environment variable") .. ": " .. boot_envvar2 .. " " .. luci.i18n.translate("to") .. " " .. newEnvSetting .. ".") end end end else -- NetGear device if not zyxelFlagPartition then zyxelFlagPartition = luci.util.trim(luci.sys.exec("source /lib/functions.sh; find_mtd_part 0:DUAL_FLAG")) end if not zyxelFlagPartition then errorMessage = errorMessage .. luci.i18n.translate("Unable to find Dual Boot Flag Partition." .. " ") luci.util.perror(luci.i18n.translate("Unable to find Dual Boot Flag Partition.")) else zyxelBootFlag = tonumber(luci.sys.exec("dd if=" .. zyxelFlagPartition .. " bs=1 count=1 2>/dev/null | hexdump -n 1 -e '1/1 \"%d\"'")) zyxelNewBootFlag = zyxelBootFlag and zyxelBootFlag == 1 and "\\xff" or "\\x01" if zyxelNewBootFlag then errorCode = luci.sys.call("printf \"" .. zyxelNewBootFlag .. "\" >" .. zyxelFlagPartition ) if errorCode ~= 0 then errorMessage = errorMessage or "" .. luci.i18n.translate("Unable to set Dual Boot Flag Partition entry for partition") .. ": " .. zyxelFlagPartition .. ". " luci.util.perror(luci.i18n.translate("Unable to set Dual Boot Flag Partition entry for partition") .. ": " .. zyxelFlagPartition .. ".") end end end end if not errorMessage then luci.template.render("admin_system/applyreboot", { title = luci.i18n.translate("Rebooting..."), msg = luci.i18n.translate("The system is rebooting to an alternative partition now.<br /> DO NOT POWER OFF THE DEVICE!<br /> Wait a few minutes before you try to reconnect. It might be necessary to renew the address of your computer to reach the device again, depending on your settings."), addr = luci.ip.new(uci:get("network", "lan", "ipaddr")) or "192.168.1.1" }) luci.sys.reboot() else luci.template.render("advanced_reboot/advanced_reboot",{ rom_board_name=rom_board_name, device_name=device_name, boot_envvar1_partition_one=boot_envvar1_partition_one, partition_one_os=partition_one_os, boot_envvar1_partition_two=boot_envvar1_partition_two, partition_two_os=partition_two_os, current_partition=current_partition, errorMessage = errorMessage}) end end end function action_poweroff() local uci = require "luci.model.uci".cursor() if luci.http.formvalue("cancel") then luci.http.redirect(luci.dispatcher.build_url('admin/system/advanced_reboot')) return end local step = tonumber(luci.http.formvalue("step") or 1) if step == 1 then if nixio.fs.access("/sbin/poweroff") then luci.template.render("advanced_reboot/power_off",{}) else luci.template.render("advanced_reboot/advanced_reboot",{}) end elseif step == 2 then luci.template.render("admin_system/applyreboot", { title = luci.i18n.translate("Shutting down..."), msg = luci.i18n.translate("The system is shutting down now.<br /> DO NOT POWER OFF THE DEVICE!<br /> It might be necessary to renew the address of your computer to reach the device again, depending on your settings."), addr = luci.ip.new(uci:get("network", "lan", "ipaddr")) or "192.168.1.1" }) luci.sys.call("/sbin/poweroff") end end
apache-2.0
ninjalulz/forgottenserver
data/scripts/lib/event_callbacks.lua
1
3775
-- Creature EVENT_CALLBACK_ONCHANGEOUTFIT = 1 EVENT_CALLBACK_ONCHANGEMOUNT = 2 EVENT_CALLBACK_ONAREACOMBAT = 3 EVENT_CALLBACK_ONTARGETCOMBAT = 4 EVENT_CALLBACK_ONHEAR = 5 -- Party EVENT_CALLBACK_ONJOIN = 6 EVENT_CALLBACK_ONLEAVE = 7 EVENT_CALLBACK_ONDISBAND = 8 EVENT_CALLBACK_ONSHAREEXPERIENCE = 9 -- Player EVENT_CALLBACK_ONBROWSEFIELD = 10 EVENT_CALLBACK_ONLOOK = 11 EVENT_CALLBACK_ONLOOKINBATTLELIST = 12 EVENT_CALLBACK_ONLOOKINTRADE = 13 EVENT_CALLBACK_ONLOOKINSHOP = 14 EVENT_CALLBACK_ONTRADEREQUEST = 15 EVENT_CALLBACK_ONTRADEACCEPT = 16 EVENT_CALLBACK_ONTRADECOMPLETED = 17 EVENT_CALLBACK_ONMOVEITEM = 18 EVENT_CALLBACK_ONITEMMOVED = 19 EVENT_CALLBACK_ONMOVECREATURE = 20 EVENT_CALLBACK_ONREPORTRULEVIOLATION = 21 EVENT_CALLBACK_ONREPORTBUG = 22 EVENT_CALLBACK_ONTURN = 23 EVENT_CALLBACK_ONGAINEXPERIENCE = 24 EVENT_CALLBACK_ONLOSEEXPERIENCE = 25 EVENT_CALLBACK_ONGAINSKILLTRIES = 26 EVENT_CALLBACK_ONWRAPITEM = 27 -- Monster EVENT_CALLBACK_ONDROPLOOT = 28 EVENT_CALLBACK_ONSPAWN = 29 -- last (for correct table counting) EVENT_CALLBACK_LAST = EVENT_CALLBACK_ONSPAWN local callbacks = { -- Creature ["onChangeOutfit"] = EVENT_CALLBACK_ONCHANGEOUTFIT, ["onChangeMount"] = EVENT_CALLBACK_ONCHANGEMOUNT, ["onAreaCombat"] = EVENT_CALLBACK_ONAREACOMBAT, ["onTargetCombat"] = EVENT_CALLBACK_ONTARGETCOMBAT, ["onHear"] = EVENT_CALLBACK_ONHEAR, -- Party ["onJoin"] = EVENT_CALLBACK_ONJOIN, ["onLeave"] = EVENT_CALLBACK_ONLEAVE, ["onDisband"] = EVENT_CALLBACK_ONDISBAND, ["onShareExperience"] = EVENT_CALLBACK_ONSHAREEXPERIENCE, -- Player ["onBrowseField"] = EVENT_CALLBACK_ONBROWSEFIELD, ["onLook"] = EVENT_CALLBACK_ONLOOK, ["onLookInBattleList"] = EVENT_CALLBACK_ONLOOKINBATTLELIST, ["onLookInTrade"] = EVENT_CALLBACK_ONLOOKINTRADE, ["onLookInShop"] = EVENT_CALLBACK_ONLOOKINSHOP, ["onTradeRequest"] = EVENT_CALLBACK_ONTRADEREQUEST, ["onTradeAccept"] = EVENT_CALLBACK_ONTRADEACCEPT, ["onTradeCompleted"] = EVENT_CALLBACK_ONTRADECOMPLETED, ["onMoveItem"] = EVENT_CALLBACK_ONMOVEITEM, ["onItemMoved"] = EVENT_CALLBACK_ONITEMMOVED, ["onMoveCreature"] = EVENT_CALLBACK_ONMOVECREATURE, ["onReportRuleViolation"] = EVENT_CALLBACK_ONREPORTRULEVIOLATION, ["onReportBug"] = EVENT_CALLBACK_ONREPORTBUG, ["onTurn"] = EVENT_CALLBACK_ONTURN, ["onGainExperience"] = EVENT_CALLBACK_ONGAINEXPERIENCE, ["onLoseExperience"] = EVENT_CALLBACK_ONLOSEEXPERIENCE, ["onGainSkillTries"] = EVENT_CALLBACK_ONGAINSKILLTRIES, ["onWrapItem"] = EVENT_CALLBACK_ONWRAPITEM, -- Monster ["onDropLoot"] = EVENT_CALLBACK_ONDROPLOOT, ["onSpawn"] = EVENT_CALLBACK_ONSPAWN } -- can't be overwritten on /reload global/libs now if not EventCallbackData then EventCallbackData = {} for i = 1, EVENT_CALLBACK_LAST do EventCallbackData[i] = {} end end EventCallback = {} setmetatable(EventCallback, { __index = function(self) if isScriptsInterface() then return self else return nil end end, __newindex = function(self, key, value) if isScriptsInterface() then if self[key] then local ecd = EventCallbackData ecd[callbacks[key]][#ecd == nil and 1 or #ecd[callbacks[key]] + 1] = value end else return nil end end, __call = function(self, callbackType, ...) local result local key, event = next(EventCallbackData[callbackType]) repeat result = {event(...)} key, event = next(EventCallbackData[callbackType], key) until event == nil or (result[1] ~= nil and (result[1] == false or table.contains({EVENT_CALLBACK_ONAREACOMBAT, EVENT_CALLBACK_ONTARGETCOMBAT}, callbackType) and result[1] ~= RETURNVALUE_NOERROR)) return unpack(result) end }) function hasEventCallback(callbackType) if #EventCallbackData[callbackType] == 0 then return false end return true end
gpl-2.0
snabbnfv-goodies/snabbswitch
src/lib/json.lua
29
10286
-- JSON4Lua: JSON encoding / decoding support for the Lua language. -- json Module. -- Author: Craig Mason-Jones -- Homepage: http://json.luaforge.net/ -- Version: 0.9.40 -- This module is released under the MIT License (MIT). -- -- NOTE: This is only the decode functionality ripped out from JSON4Lua. -- See: https://github.com/craigmj/json4lua module(..., package.seeall) local math = require('math') local string = require("string") local table = require("table") local base = _G -- Private functions local decode_scanArray local decode_scanComment local decode_scanConstant local decode_scanNumber local decode_scanObject local decode_scanString local decode_scanWhitespace --- Decodes a JSON string and returns the decoded value as a Lua data structure / value. -- @param s The string to scan. -- @param [startPos] Optional starting position where the JSON string is located. Defaults to 1. -- @param Lua object, number The object that was scanned, as a Lua table / string / number / boolean or nil, -- and the position of the first character after -- the scanned JSON object. function decode(s, startPos) startPos = startPos and startPos or 1 startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=string.len(s), 'Unterminated JSON encoded object found at position in [' .. s .. ']') local curChar = string.sub(s,startPos,startPos) -- Object if curChar=='{' then return decode_scanObject(s,startPos) end -- Array if curChar=='[' then return decode_scanArray(s,startPos) end -- Number if string.find("+-0123456789.e", curChar, 1, true) then return decode_scanNumber(s,startPos) end -- String if curChar==[["]] or curChar==[[']] then return decode_scanString(s,startPos) end if string.sub(s,startPos,startPos+1)=='/*' then return decode(s, decode_scanComment(s,startPos)) end -- Otherwise, it must be a constant return decode_scanConstant(s,startPos) end --- The null function allows one to specify a null value in an associative array (which is otherwise -- discarded if you set the value with 'nil' in Lua. Simply set t = { first=json.null } function null() return null -- so json.null() will also return null ;-) end ----------------------------------------------------------------------------- -- Internal, PRIVATE functions. -- Following a Python-like convention, I have prefixed all these 'PRIVATE' -- functions with an underscore. ----------------------------------------------------------------------------- --- Scans an array from JSON into a Lua object -- startPos begins at the start of the array. -- Returns the array and the next starting position -- @param s The string being scanned. -- @param startPos The starting position for the scan. -- @return table, int The scanned array as a table, and the position of the next character to scan. function decode_scanArray(s,startPos) local array = {} -- The return value local stringLen = string.len(s) base.assert(string.sub(s,startPos,startPos)=='[','decode_scanArray called but array does not start at position ' .. startPos .. ' in string:\n'..s ) startPos = startPos + 1 -- Infinite loop for array elements repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen,'JSON String ended unexpectedly scanning array.') local curChar = string.sub(s,startPos,startPos) if (curChar==']') then return array, startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON String ended unexpectedly scanning array.') object, startPos = decode(s,startPos) table.insert(array,object) until false end --- Scans a comment and discards the comment. -- Returns the position of the next character following the comment. -- @param string s The JSON string to scan. -- @param int startPos The starting position of the comment function decode_scanComment(s, startPos) base.assert( string.sub(s,startPos,startPos+1)=='/*', "decode_scanComment called but comment does not start at position " .. startPos) local endPos = string.find(s,'*/',startPos+2) base.assert(endPos~=nil, "Unterminated comment in string at " .. startPos) return endPos+2 end --- Scans for given constants: true, false or null -- Returns the appropriate Lua type, and the position of the next character to read. -- @param s The string being scanned. -- @param startPos The position in the string at which to start scanning. -- @return object, int The object (true, false or nil) and the position at which the next character should be -- scanned. function decode_scanConstant(s, startPos) local consts = { ["true"] = true, ["false"] = false, ["null"] = nil } local constNames = {"true","false","null"} for i,k in base.pairs(constNames) do --print ("[" .. string.sub(s,startPos, startPos + string.len(k) -1) .."]", k) if string.sub(s,startPos, startPos + string.len(k) -1 )==k then return consts[k], startPos + string.len(k) end end base.assert(nil, 'Failed to scan constant from string ' .. s .. ' at starting position ' .. startPos) end --- Scans a number from the JSON encoded string. -- (in fact, also is able to scan numeric +- eqns, which is not -- in the JSON spec.) -- Returns the number, and the position of the next character -- after the number. -- @param s The string being scanned. -- @param startPos The position at which to start scanning. -- @return number, int The extracted number and the position of the next character to scan. function decode_scanNumber(s,startPos) local endPos = startPos+1 local stringLen = string.len(s) local acceptableChars = "+-0123456789.e" while (string.find(acceptableChars, string.sub(s,endPos,endPos), 1, true) and endPos<=stringLen ) do endPos = endPos + 1 end local stringValue = 'return ' .. string.sub(s,startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to scan number [ ' .. stringValue .. '] in JSON string at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON object into a Lua object. -- startPos begins at the start of the object. -- Returns the object and the next starting position. -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return table, int The scanned object as a table and the position of the next character to scan. function decode_scanObject(s,startPos) local object = {} local stringLen = string.len(s) local key, value base.assert(string.sub(s,startPos,startPos)=='{','decode_scanObject called but object does not start at position ' .. startPos .. ' in string:\n' .. s) startPos = startPos + 1 repeat startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly while scanning object.') local curChar = string.sub(s,startPos,startPos) if (curChar=='}') then return object,startPos+1 end if (curChar==',') then startPos = decode_scanWhitespace(s,startPos+1) end base.assert(startPos<=stringLen, 'JSON string ended unexpectedly scanning object.') -- Scan the key key, startPos = decode(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) startPos = decode_scanWhitespace(s,startPos) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) base.assert(string.sub(s,startPos,startPos)==':','JSON object key-value assignment mal-formed at ' .. startPos) startPos = decode_scanWhitespace(s,startPos+1) base.assert(startPos<=stringLen, 'JSON string ended unexpectedly searching for value of key ' .. key) value, startPos = decode(s,startPos) object[key]=value until false -- infinite loop while key-value pairs are found end --- Scans a JSON string from the opening inverted comma or single quote to the -- end of the string. -- Returns the string extracted as a Lua string, -- and the position of the next non-string character -- (after the closing inverted comma or single quote). -- @param s The string being scanned. -- @param startPos The starting position of the scan. -- @return string, int The extracted string as a Lua string, and the next character to parse. function decode_scanString(s,startPos) base.assert(startPos, 'decode_scanString(..) called without start position') local startChar = string.sub(s,startPos,startPos) base.assert(startChar==[[']] or startChar==[["]],'decode_scanString called for a non-string') local escaped = false local endPos = startPos + 1 local bEnded = false local stringLen = string.len(s) repeat local curChar = string.sub(s,endPos,endPos) -- Character escaping is only used to escape the string delimiters if not escaped then if curChar==[[\]] then escaped = true else bEnded = curChar==startChar end else -- If we're escaped, we accept the current character come what may escaped = false end endPos = endPos + 1 base.assert(endPos <= stringLen+1, "String decoding failed: unterminated string at position " .. endPos) until bEnded local stringValue = 'return ' .. string.sub(s, startPos, endPos-1) local stringEval = base.loadstring(stringValue) base.assert(stringEval, 'Failed to load string [ ' .. stringValue .. '] in JSON4Lua.decode_scanString at position ' .. startPos .. ' : ' .. endPos) return stringEval(), endPos end --- Scans a JSON string skipping all whitespace from the current start position. -- Returns the position of the first non-whitespace character, or nil if the whole end of string is reached. -- @param s The string being scanned -- @param startPos The starting position where we should begin removing whitespace. -- @return int The first position where non-whitespace was encountered, or string.len(s)+1 if the end of string -- was reached. function decode_scanWhitespace(s,startPos) local whitespace=" \n\r\t" local stringLen = string.len(s) while ( string.find(whitespace, string.sub(s,startPos,startPos), 1, true) and startPos <= stringLen) do startPos = startPos + 1 end return startPos end
apache-2.0
camchenry/shaderview
globals.lua
1
4491
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! -- !! This flag controls the ability to toggle the debug view. !! -- !! You will want to turn this to 'true' when you publish your game. !! -- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! RELEASE = false -- Enables the debug stats DEBUG = not RELEASE CONFIG = { graphics = { filter = { -- FilterModes: linear (blurry) / nearest (blocky) -- Default filter used when scaling down down = "nearest", -- Default filter used when scaling up up = "nearest", -- Amount of anisotropic filter performed anisotropy = 1, } }, window = { icon = 'assets/images/icon.png' }, debug = { -- The key (scancode) that will toggle the debug state. -- Scancodes are independent of keyboard layout so it will always be in the same -- position on the keyboard. The positions are based on an American layout. key = '`', stats = { font = nil, -- set after fonts are created fontSize = 16, lineHeight = 18, foreground = {1, 1, 1, 1}, shadow = {0, 0, 0, 1}, shadowOffset = {x = 1, y = 1}, position = {x = 8, y = love.graphics.getHeight()-170}, kilobytes = false, }, -- Error screen config error = { font = nil, -- set after fonts are created fontSize = 16, background = {.1, .31, .5}, foreground = {1, 1, 1}, shadow = {0, 0, 0, .88}, shadowOffset = {x = 1, y = 1}, position = {x = 70, y = 70}, }, } } local function makeFont(path) return setmetatable({}, { __index = function(t, size) local f = love.graphics.newFont(path, size) rawset(t, size, f) return f end }) end Fonts = { default = nil, regular = makeFont 'assets/fonts/FiraSans-Regular.ttf', bold = makeFont 'assets/fonts/FiraSans-Bold.ttf', light = makeFont 'assets/fonts/FiraSans-Light.ttf', monospace = makeFont 'assets/fonts/FiraCode-Regular.ttf', } Fonts.default = Fonts.regular CONFIG.debug.stats.font = Fonts.monospace CONFIG.debug.stats.position.y = love.graphics.getHeight() - CONFIG.debug.stats.font[CONFIG.debug.stats.fontSize]:getHeight()*6 CONFIG.debug.error.font = Fonts.monospace Shaderview = { version = "v0.2.0", } Keybinds = {} shaders = {} shader_name_lookup = {} shader_uniforms = {} shader_sends = {} textures = {} Threads = { filechange = love.thread.newThread('threads/filechange.lua'), } Lume = require 'libs.lume' Husl = require 'libs.husl' Class = require 'libs.class' Vector = require 'libs.vector' State = require 'libs.state' Signal = require 'libs.signal' Inspect = require 'libs.inspect' Camera = require 'libs.camera' Timer = require 'libs.timer' Input = require 'libs.boipushy' Suit = require 'libs.suit' States = { game = require 'states.game', splash = require 'states.splash', } Active_Project = {} local function basename(str) return string.gsub(str, "(.*/)(.*)", "%2") end function copy_directory(source, dest, dir_name, depth) local source_info = love.filesystem.getInfo(source) if not depth then depth = 1 end if not source_info then error("Source folder '" .. source .. "' does not exist.") end local files = love.filesystem.getDirectoryItems(source) if depth == 1 then dest_src_name = basename(source) if dir_name then dest = dest .. '/' .. dir_name else dest = dest .. '/' .. basename(source) end end dest = dest .. '/' source = source .. '/' local info = love.filesystem.getInfo(dest, 'directory') if not info then love.filesystem.createDirectory(dest) end for _, file in ipairs(files) do local info = love.filesystem.getInfo(source .. file) if info.type == "directory" then copy_directory(source .. file, dest .. file, nil, depth + 1) elseif info.type == "file" then love.filesystem.write(dest .. file, love.filesystem.read(source .. file)) end end end
mit
bsmr-games/lipsofsuna
data/system/database.lua
1
2353
--- TODO:doc -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module system.database -- @alias Database local Class = require("system/class") local Packet = require("system/packet") if not Los.program_load_extension("database") then error("loading extension `database' failed") end ------------------------------------------------------------------------------ --- TODO:doc -- @type Database local Database = Class("Database") --- Opens a database. -- @param clss Database class. -- @param name Database name. -- @return New database. Database.new = function(clss, name) local self = Class.new(clss) self.handle = Los.database_new(name) if not self.handle then assert(self.handle, string.format("creating database %q failed", name)) end return self end --- Queries the database.<br/> -- Executes an SQLite query and returns the results in a table. The returned -- table contains a list of tables that denote the rows of the result. The row -- tables further contain a list of values that denote the contents of the columns.<br/> -- You can avoid escaping the arguments required by the query by writing a `?' in -- place of the argument in the query and then passing the value in the binding -- array. The binding array is a simple table that contains the arguments in the -- same order as the query. -- @param self Database. -- @param a Query string. -- @param b Array of values to bind to the statement. -- @return Table of rows. Database.query = function(self, a, b) -- Translate packets to handles. local s if b then s = {} for k,v in pairs(b) do s[k] = (type(v) == "table") and v.handle or v end end -- Perform the query. local t = Los.database_query(self.handle, a, s) if not t then return end -- Translate handles to packets. for k1,v1 in pairs(t) do for k2,v2 in pairs(v1) do if type(v2) == "userdata" then v1[k2] = Packet:new_from_handle(v2) end end end return t end --- Gets the approximate memory used by all databases. -- @param self Database class. -- @return Size in bytes. Database.get_memory_used = function(self) return Los.database_get_memory_used() end return Database
gpl-3.0
bsmr-games/lipsofsuna
data/system/password.lua
1
1183
--- TODO:doc -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module system.password -- @alias Password local Class = require("system/class") if not Los.program_load_extension("password") then error("loading extension `password' failed") end ------------------------------------------------------------------------------ --- TODO:doc -- @type Password local Password = Class("Password") --- Creates a password hash. -- @param self Program class. -- @param pass Password string. -- @param salt Salt string. -- @param rounds Number of PBKDF2 rounds. -- @return Password hash as a hexadecimal string. Password.hash = function(self, pass, salt, rounds) return Los.program_hash_password(pass, salt, rounds) end --- Generates a random password salt string. -- @param self Program class. -- @param length String length. -- @return Password salt string. Password.random_salt = function(self, length) return Los.program_random_salt(length) end return Password
gpl-3.0
nood32/MEEDOBOT
plugins/save.lua
1
23684
--[[ ✄╔═╗╔═╗─────╔═══╗──╔══╗──╔════╗dev:@meedo1133 ✄║║╚╝║║─────╚╗╔╗║──║╔╗║──║╔╗╔╗║dev:@hema1133 ✄║╔╗╔╗╠══╦══╗║║║╠══╣╚╝╚╦═╩╣║║╚╝cha:@meedoyemen ✄║║║║║║║═╣║═╣║║║║╔╗║╔═╗║╔╗║║║ fbk:@mmalhossainy ✄║║║║║║║═╣║═╬╝╚╝║╚╝║╚═╝║╚╝║║║ gml:meedoyemen@gmail.com ✄╚╝╚╝╚╩══╩══╩═══╩══╩═══╩══╝╚╝ inst:@meedoyemen ]]-- do -------------Clean Msg ------------- local function clean_msg(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..' messages were deleted', ok_cb, false) else send_msg(extra.chatid, 'Error Deleting messages', ok_cb, false) end end -------------Save file------------- local function save_file_reply(extra, success, result) msg = extra.msg name = extra.name adress = extra.adress receiver = get_receiver(msg) if success then file = './'..adress..'/'..name..'' print('File saving to:', result) os.rename(result, file) print('File moved to:', file) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -----------------Reply_here------------- local function reply_here(extra, success, result) reply_msg(extra.Reply, text, ok_cb, false) end ------------- RUN ------------- function run(msg, matches) ------------- GROUP TYPE ------------- if matches[1] == "set" and matches[2] == "type" and matches[3] then if msg.to.type == "user" then return end if not is_sudo(msg) then return 'You Are Not Allow To set Group Type !' end data = load_data(_config.moderation.data) group_type = data[tostring(msg.to.id)]['group_type'] data[tostring(msg.to.id)]['group_type'] = matches[3] save_data(_config.moderation.data, data) return 'Group Type Seted To : '..matches[3] end -------------SET LINK ------------- if matches[1] == "set" and matches[2] == "link" and is_owner(msg) then if msg.to.type == "user" then return end if not is_owner(msg) then return "You Are Not Allow To Set Link" end waiting = redis:set('setlink:','waiting:'..msg.from.id) return 'Now Send Group Link!' else output = redis:get('setlink:') if output == 'waiting:'..msg.from.id then if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and redis:set('setlink:','waiting:'..msg.from.id) and is_owner(msg) then setted = redis:set('setlink:',msg.text) return 'New Link Seted!' end end end -------------DEL LINK ------------- if matches[1] == "del" and matches[2] == "link" and is_owner(msg) then if msg.to.type == "user" then return end if not is_owner(msg) then return "You Are Not Allow To Delete Group Link!" end redis:del('setlink:','waiting:'..msg.from.id) return "Group Link Has Been deleted"end end ------------- LINK ------------- if matches[1] == "link" and is_momod(msg) then output = redis:get('setlink:') receiver = get_receiver(msg) if output then send_msg(receiver,"Link for: ["..msg.to.title.."] \n➖➖➖➖➖➖\n"..output..'\n➖➖➖➖➖➖\n\n@StePh',ok_cb,false) else return '' end end ------------- Git ------------- if matches[1] == "git" then if msg.to.type == "user" then return end url = "https://api.github.com/users/"..URL.escape(matches[2]) jstr, res = https.request(url) jdat = JSON.decode(jstr) if jdat.message then return 'No data found' end text = jdat.login..'\nFollowers: '..jdat.followers..'\nFollowings: '..jdat.following..'\nRepos: '..jdat.public_repos..'\nProfile URL: '..jdat.html_url..'\n\n@Hextor Team' file = download_to_file(jdat.avatar_url,'Hextor.jpg') if msg.to.type == "chat" then send_photo('chat#id'..msg.to.id,file,ok_cb,false) elseif msg.to.type == "channel" then send_photo('channel#id'..msg.to.id,file,ok_cb,false) return text end end ------------- Git User ------------- if matches[1] == "gituser" then if msg.to.type == "user" then return end url = "https://api.github.com/repos/"..URL.escape(matches[2]).."/"..URL.escape(matches[3]) jstr, res = https.request(url) jdat = JSON.decode(jstr) if jdat.message then return 'No data found' end text = jdat.owner.login..' / '..jdat.name text = text..'\n______________________________\nLanguage: '..jdat.language ..'\nForks: '..jdat.forks_count ..'\nIssues: '..jdat.open_issues ..'\nRepo URL: '..jdat.html_url file = download_to_file(jdat.owner.avatar_url,'Hextor.jpg') if msg.to.type == "chat" then photo_caption('chat#id'..msg.to.id,file,text,ok_cb,false) elseif msg.to.type == "channel" then photo_caption('channel#id'..msg.to.id,file,text,ok_cb,false) end end ------------- Git dl ------------- if matches[1] == "gitdl" then if msg.to.type == "user" then return end day = os.date("%I") hash = 'github:dl:'..day..':'..msg.from.id is_github = redis:get(hash) if is_github and not is_sudo(msg) then return "After 1Minute request \n(server Busy)" elseif not is_github then redis:set(hash, true) end url = "https://codeload.github.com/"..matches[2]..'/'..matches[3].."/zip/master" file = download_to_file(url,matches[2]..'|@Hextor_ch.zip') if msg.to.type == 'channel' then send_document('channel#id'..msg.to.id,file,ok_cb,false) elseif msg.to.type == 'chat' then send_document('chat#id'..msg.to.id,file,ok_cb,false) end end ------------- Add plugin ------------- if matches[1] == 'addplugin' and is_sudo(msg) then if not is_sudo(msg) then return "You Are Not Allow To Add Plugin" end name = matches[2] text = matches[3] file = io.open("./plugins/"..name, "w") file:write(text) file:flush() file:close() return "Add plugin successful " end ------------- Download plugin ------------- if matches[1] == "dl" and matches[2] == "plugin" and is_sudo(msg) then if not is_sudo(msg) then return "You Are Not Allow To Download Plugins!" end receiver = get_receiver(msg) send_document(receiver, "./plugins/"..matches[3]..".lua", ok_cb, false) send_document(receiver, "./plugins/"..matches[3], ok_cb, false) end -------------Show Plugins ------------- if matches [1] == "show" and is_sudo(msg) then if not is_sudo(msg) then return "You Are Not Allow To show Plugins!" end file = io.open("./plugins/"..matches[2], "r") text = file:read("*all") return text end -------------save file Reply ------------- if matches[1] == 'save' and is_sudo(msg) then if not is_sudo(msg) then return "You Are Not Allow To save Files!" end if msg.reply_id then adress = matches[2] name = matches[3] load_document(msg.reply_id, save_file_reply, {msg=msg,name=name,adress=adress}) return 'الملف '..name..' ✅ تم ارساله الى المجلد: \n📂 '..adress end end -------------Dl file Via Bot ------------- if matches [1] == "dlfile" and is_owner(msg) then if not is_owner(msg) then return "You Are Not Allow To Dl Files Via BOT" end file = download_to_file(matches[2],matches[3]) send_document(get_receiver(msg),file,ok_cb,false) return "Uploading the File" end if matches[1] == "dl" and matches[2] == "file" and is_sudo(msg) then if not is_sudo(msg) then return "You Are Not Allow To Dl Files Via BOT" end receiver = get_receiver(msg) send_document(receiver, ""..matches[3].."/"..matches[4], ok_cb, false) end -------------Delete Plugins ------------- if matches[1] == "delplugin" and is_sudo(msg) then if not is_sudo(msg) then return "You Are Not Allow To Delete Plugins!" end io.popen("cd plugins && rm "..matches[2]..".lua") return "Delete plugin successful " end ------------- Feedback ------------- if matches[1] == "feedback" then if msg.reply_id then hour = os.date("%M") feedback_hash = 'feedback:'..hour..':'..msg.from.id is_feedback = redis:get(feedback_hash) if is_feedback then return "#Error\nIn one minute you can ask for your support" elseif not is_feedback then redis:set(feedback_hash, true) fwd_msg('user#id184413821', msg.reply_id, ok_cb, false) return 'Your question was sent successfully (by Reply)' end end if #matches == 2 then hour = os.date("%M") feedback_hash = 'feedback:'..hour..':'..msg.from.id is_feedback = redis:get(feedback_hash) if is_feedback then return "#Error\nIn one minute you can ask for your support" elseif not is_feedback then redis:set(feedback_hash, true) text = "New Feedback \n----------------------\n" text = text..'Name : '..user_print_name(msg.from) text = text..'\nUsername : '..('@'..msg.from.username or ' ') text = text..'\nID : '..msg.from.id text = text..'\n\nPm :'..matches[2] send_large_msg('user#id184413821', text.."\n", ok_cb, false) end return "Your question was sent successfully (Text)" end end ------------- Short Link------------- if matches[1] == "short" then yeo = http.request('http://yeo.ir/api.php?url='..URL.escape(matches[2])..'=') opz = http.request('http://api.gpmod.ir/shorten/?url='..URL.escape(matches[2])..'&username=janjo.urmia2@gmail.com') u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(matches[2])) text = 'Your link was shortened to 4 website \n\nBase Link :'..matches[2]..'\n➖➖➖➖\n'.. '\n\nShort By Yeo :\n'..yeo.. '\n\nShort By Opizo :\n'..opz.. '\n\nShort By U2s :\n'..u2s return text end -------------Create File------------- if matches[1]:lower() == "createfile" and matches[2] and is_owner(msg) then if msg.to.type == "user" then return end if not is_owner(msg) then return "You Are Not Allow To Create File!" end name = matches[2] text = matches[3] file = io.open("./data/"..name, "w") file:write(text) file:flush() file:close() send_document(get_receiver(msg), "./data/"..name, ok_cb, false) end -------------reply msg------------- if matches[1] == "reply" and is_momod(msg) then if msg.to.type == "user" then return end if not is_momod(msg) then return "You Are Not Allow To use Reply " end if msg.reply_id then receiver = get_receiver(msg) Reply = msg.reply_id text = matches[2] reply_msg(msg.reply_id,text,ok_cb,false) else text = matches[2] reply_msg(msg.id, text, ok_cb, false) end end -------------Translate------------- if matches[1] == "tr" then url = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a&format=plain&lang='..URL.escape(matches[2])..'&text='..URL.escape(matches[3])) data = json:decode(url) return 'Language : '..data.lang..'\nMeaning : '..data.text[1] end -------------Echo------------- if matches[1] == "echo" then if msg.to.type == "user" then return end text = matches[2] b = 1 while b ~= 0 do text = text:trim() text,b = text:gsub('^/+','') text,b = text:gsub('^!+','') text,b = text:gsub('^#+','') text,b = text:gsub('([Kk][Ii][Cc][Kk][Mm][Ee])','Bie') end return text end -------------Voice------------- if matches[1] == "voice" then if msg.to.type == "user" then return end if string.len(matches[2]) > 25 then return "More than 25 characters are not allowed" end hour = os.date("%M") hash_voice = 'voice::'..hour..':'..msg.from.id is_voice = redis:get(hash_voice) if is_voice then return "After 1Minute request \n(server Busy)" elseif not is_voice then redis:set(hash_voice, true) text = matches[2] b = 1 while b ~= 0 do voice = text:trim() text,b = text:gsub(' ','.') end url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..voice receiver = get_receiver(msg) file = download_to_file(url,'Hextor.ogg') send_audio(get_receiver(msg), file, ok_cb , false) end end -------------Mean------------- if matches[1] == "mean" then http = http.request('http://api.vajehyab.com/v2/public/?q='..URL.escape(matches[2])) data = json:decode(http) return 'Word : '..(data.data.title or data.search.q)..'\n\nMeaning : '..(data.data.text or '----' )..'\n\nSource : '..(data.data.source or '----' )..'\n\n'..(data.error.message or '')..'\n' end -------------Clean Msg------------- if matches[1] == 'clean' and matches[2] == "msg" and is_owner(msg) then if msg.to.type == "user" then return end if msg.to.type == 'chat' then return "Only in the Super Group" end if not is_owner(msg) then return "You Are Not Allow To clean Msgs!" end if tonumber(matches[3]) > 100 or tonumber(matches[3]) < 10 then return "Minimum clean 10 and maximum clean is 100" end get_history(msg.to.peer_id, matches[3] + 1 , clean_msg , { chatid = msg.to.peer_id,con = matches[3]}) end -------------Delete BAN&Gban list ------------- if matches[1]:lower() == 'del' then data = load_data(_config.moderation.data) if matches[2] == 'gbanlist' then if msg.to.type == "user" then return end if not is_sudo(msg) then return "You Are Not Allow To clean GlobalBan List!" end hash = 'gbanned' data[tostring(msg.to.id)]['gbanlist'] = nil save_data(_config.moderation.data, data) redis:del(hash) return "Global Ban List Has been Cleared!" end if matches[2] == 'banlist' and is_owner(msg) then if msg.to.type == "user" then return end if not is_owner(msg) then return "You Are Not Allow To clean ban List!" end hash = 'banned:'..msg.to.id data[tostring(msg.to.id)]['banlist'] = nil save_data(_config.moderation.data, data) redis:del(hash) return "Ban List Has been Cleared!" end end -------------Link PV ------------- if matches[1] == 'link' and matches[2]== "link" or matches[1] == "linkpv" then if msg.to.type == "user" then return end if not is_momod(msg) then return "You Are Not Allow To Use Link PV!" end data = load_data(_config.moderation.data) group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first!" end text = "Group Link :\n"..group_link send_large_msg('user#id'..msg.from.id, text.."\n", ok_cb, false) return "Link Was Send To Your Pv!" end -------------Support ------------- if matches[1] == 'support' then data = load_data(_config.moderation.data) support = '1065607686' group_link = data[tostring(support)]['settings']['set_link'] text = "Supoort Link : \n"..group_link return text end -------------Converter ------------- if matches[1]:lower() == 'ar' and matches[2] then if msg.to.type == "user" then return end text = matches[2]:lower() if string.len(text) > 100 then return "More than 100 characters are not allowed" end if string.match(text, 'a') then text = string.gsub(text, 'a', "ش") end if string.match(text, 'b') then text = string.gsub(text, 'b', "ذ") end if string.match(text, 'c') then text = string.gsub(text, 'c', "ز") end if string.match(text, 'd') then text = string.gsub(text, 'd', "ی") end if string.match(text, 'e') then text = string.gsub(text, 'e', "ث") end if string.match(text, 'f') then text = string.gsub(text, 'f', "ب") end if string.match(text, 'g') then text = string.gsub(text, 'g', "ل") end if string.match(text, 'h') then text = string.gsub(text, 'h', "ا") end if string.match(text, 'i') then text = string.gsub(text, 'i', "ه") end if string.match(text, 'j') then text = string.gsub(text, 'j', "ت") end if string.match(text, 'k') then text = string.gsub(text, 'k', "ن") end if string.match(text, 'l') then text = string.gsub(text, 'l', "م") end if string.match(text, 'm') then text = string.gsub(text, 'm', "ئ") end if string.match(text, 'n') then text = string.gsub(text, 'n', "د") end if string.match(text, 'o') then text = string.gsub(text, 'o', "خ") end if string.match(text, 'p') then text = string.gsub(text, 'p', "ح") end if string.match(text, 'q') then text = string.gsub(text, 'q', "ض") end if string.match(text, 'r') then text = string.gsub(text, 'r', "ق") end if string.match(text, 's') then text = string.gsub(text, 's', "س") end if string.match(text, 't') then text = string.gsub(text, 't', "ف") end if string.match(text, 'u') then text = string.gsub(text, 'u', "ع") end if string.match(text, 'v') then text = string.gsub(text, 'v', "ر") end if string.match(text, 'w') then text = string.gsub(text, 'w', "ص") end if string.match(text, 'x') then text = string.gsub(text, 'x', "ط") end if string.match(text, 'y') then text = string.gsub(text, 'y', "غ") end if string.match(text, 'z') then text = string.gsub(text, 'z', "ظ") end if string.match(text, ',') then text = string.gsub(text, ',', "و") end if string.match(text, "`") then text = string.gsub(text, '`', "پ") end if string.match(text, "'") then text = string.gsub(text, "'", "گ") end if string.match(text, ';') then text = string.gsub(text, ';', "ک") end if string.match(text, ']') then text = string.gsub(text, ']', "چ") end return text elseif matches[1]:lower() == 'en' and matches[2] then if msg.to.type == "user" then return end text = matches[2]:lower() if string.len(text) > 100 then return "More than 100 characters are not allowed" end if string.match(text, 'ش') then text = string.gsub(text, 'ش', "a") end if string.match(text, 'ذ') then text = string.gsub(text, 'ذ', "b") end if string.match(text, 'ز') then text = string.gsub(text, 'ز', "c") end if string.match(text, 'ی') then text = string.gsub(text, 'ی', "d") end if string.match(text, 'ث') then text = string.gsub(text, 'ث', "e") end if string.match(text, 'ب') then text = string.gsub(text, 'ب', "f") end if string.match(text, 'ل') then text = string.gsub(text, 'ل', "g") end if string.match(text, 'ا') then text = string.gsub(text, 'ا', "h") end if string.match(text, 'ه') then text = string.gsub(text, 'ه', "i") end if string.match(text, 'ت') then text = string.gsub(text, 'ت', "j") end if string.match(text, 'ن') then text = string.gsub(text, 'ن', "k") end if string.match(text, 'م') then text = string.gsub(text, 'م', "l") end if string.match(text, 'ئ') then text = string.gsub(text, 'ئ', "m") end if string.match(text, "د") then text = string.gsub(text, 'د', "n") end if string.match(text, 'خ') then text = string.gsub(text, 'خ', "o") end if string.match(text, 'ح') then text = string.gsub(text, 'ح', "p") end if string.match(text, 'ض') then text = string.gsub(text, 'ض', "q") end if string.match(text, 'ق') then text = string.gsub(text, 'ق', "r") end if string.match(text, 'س') then text = string.gsub(text, 'س', "s") end if string.match(text, 'ف') then text = string.gsub(text, 'ف', "t") end if string.match(text, 'ع') then text = string.gsub(text, 'ع', "u") end if string.match(text, 'ر') then text = string.gsub(text, 'ر', "v") end if string.match(text, 'ص') then text = string.gsub(text, 'ص', "w") end if string.match(text, 'ط') then text = string.gsub(text, 'ط', "x") end if string.match(text, 'غ') then text = string.gsub(text, 'غ', "y") end if string.match(text, 'ظ') then text = string.gsub(text, 'ظ', "z") end if string.match(text, 'چ') then text = string.gsub(text, 'چ', "ch") end if string.match(text, 'خ') then text = string.gsub(text, 'خ', "kh") end return text end -------------reverse Character text ------------- if matches[1]:lower() == 'roll' then if msg.to.type == "user" then return end roll = string.reverse(matches[2]) return roll end -------------Count Character text ------------- if matches[1]:lower() == 'count' then if msg.to.type == "user" then return end count = string.len(matches[2]) return count end -------------Terminal ------------- if matches[1] == "run" and is_sudo(msg) then if msg.to.type == "user" then return end if not is_sudo(msg) then return "You aren't allowed!" end cmd = io.popen(matches[2]) result = cmd:read('*all') cmd:close() send_large_msg(get_receiver(msg), result, ok_cb, false) return end end end return { patterns = { "^[!/]([Aa]ddplugin) (.+) (.*)$", "^[!/]([Cc]reatefile) ([^%s]+) (.+)$", "^[!/]([Cc]lean) (msg) (%d*)$", "^[!/]([Cc]ount) (.*)", "^[!/]([Dd]el) ([Ll]ink)$", "^[!/]([Dd]l) ([Pp]lugin) (.*)$", "^[!/]([Dd]elplugin) (.*)$", "^[!/]([Dd]lfile) (.*) (.*)$", "^[!/]([Dd]l) (file) (.*)/(.*)$", "^[!/]([Dd]el) (.*)$", "^[!/]([Ee]cho) (.*)$", "^[!/]([Ee]n) (.*)$", "^[!/]([Ff]eedback)$", "^[!/]([Ff]eedback) (.*)$", "^[!/]([a]r) (.*)$", "^[!/]([Gg]it) (.*)", "^[!/]([Gg]ituser) (.*)/(.*)", "^[!/]([Gg]itdl) (.*)/(.*)", "^[!/]([Ll]ink)$", "^[!/]([Ll]inkpv)$", "^[!/]([Ll]ink) ([Pp]v)$", "^[!/]([Mm]ean) (.*)$", "^[!/]([Rr]eply) (.*)$", "^[!/]([Rr]oll) (.*)", "^[!/]([Rr]un) (.*)$", "^[!/]([Ss]ave) (.*)/(.*)$", "^[!/]([Ss]et) ([Tt]ype) (.*)$", "^[!/]([Ss]et) ([Ll]ink)", "^[!/]([Ss]how) (.*)$", "^[!/]([Ss]hort) (.*)$", "^[!/]([Tt]r) ([^%s]+) (.*)$", "^[!/]([Vv]oice) (.*)$", "%[(document)%]", "%[(photo)%]", "^(https://telegram.me/joinchat/%S+)$", "^(.*)$", }, run = run, } --[[ ✄╔═╗╔═╗─────╔═══╗──╔══╗──╔════╗dev:@meedo1133 ✄║║╚╝║║─────╚╗╔╗║──║╔╗║──║╔╗╔╗║dev:@hema1133 ✄║╔╗╔╗╠══╦══╗║║║╠══╣╚╝╚╦═╩╣║║╚╝cha:@meedoyemen ✄║║║║║║║═╣║═╣║║║║╔╗║╔═╗║╔╗║║║ fbk:@mmalhossainy ✄║║║║║║║═╣║═╬╝╚╝║╚╝║╚═╝║╚╝║║║ gml:meedoyemen@gmail.com ✄╚╝╚╝╚╩══╩══╩═══╩══╩═══╩══╝╚╝ inst:@meedoyemen ]]--
gpl-2.0
danielga/luachip
lua/weapons/gmod_tool/stools/luachip.lua
1
2417
TOOL.Category = "Construction" TOOL.Name = "#tool.luachip.name" TOOL.RequiresTraceHit = true TOOL.DefaultModel = "models/beer/wiremod/gate_e2.mdl" TOOL.ClientConVar = { model = TOOL.DefaultModel } cleanup.Register("luachips") if SERVER then CreateConVar("sbox_maxluachips", 5) function TOOL:LeftClick(trace) local owner = self:GetOwner() if not owner:IsAdmin() then -- for now only allow admins to use this return false end if not util.IsValidPhysicsObject(trace.Entity, trace.PhysicsBone) then return false end if luachip.RequestCode(owner, trace.Entity) then return true end if not owner:CheckLimit("luachips") then return false end local entity = ents.Create("luachip") if not IsValid(entity) then return false end local model = self:GetClientInfo("model") if not util.IsValidModel(model) then model = self.DefaultModel end entity:SetModel(model) local ang = trace.HitNormal:Angle() ang.pitch = ang.pitch + 90 entity:SetAngles(ang) entity:SetPos(trace.HitPos) entity:SetPlayer(owner) entity:Spawn() entity:SetPos(trace.HitPos - trace.HitNormal * entity:OBBMins().z) local weld = constraint.Weld(entity, trace.Entity, 0, trace.PhysicsBone, 0, true, false) undo.Create("luachip") undo.AddEntity(entity) undo.AddEntity(weld) undo.SetPlayer(owner) undo.Finish() owner:AddCount("luachips", entity) owner:AddCleanup("luachips", entity) return luachip.RequestCode(owner, entity) end function TOOL:RightClick(trace) local owner = self:GetOwner() if not owner:IsAdmin() then -- for now only allow admins to use this return false end if luachip.SendCode(owner, trace.Entity) then return true end return luachip.OpenEditor(owner) end function TOOL:Reload(trace) local owner = self:GetOwner() if not owner:IsAdmin() then -- for now only allow admins to use this return false end if luachip.Reset(owner, trace.Entity) then return true end return false end else language.Add("tool.luachip.name", "LuaChip") language.Add("tool.luachip.desc", "Creates LuaChips that allow you to execute Lua on the server") language.Add("tool.luachip.0", "Left click to spawn/update LuaChips. Right click to edit LuaChips or open the editor. Reload to reset LuaChips.") function TOOL.BuildCPanel(CPanel, FaceEntity) CPanel:AddControl("Header", {Description = "#tool.luachip.desc"}) end end
bsd-3-clause
FastTM/Fast-Unique
plugins/private_settings.lua
1
2538
local plugin = {} local function get_button_description(key) if key == 'rules_on_join' then return _("When you join a group moderated by this bot, you will receive the group rules in private") elseif key == 'reports' then return _("If enabled, you will receive all the messages reported with the @admin command in the groups you are moderating") else return _("Description not available") end end local function change_private_setting(user_id, key) local hash = 'user:'..user_id..':settings' local val = 'off' local current_status = (db:hget(hash, key)) or config.private_settings[key] if current_status == 'off' then val = 'on' end db:hset(hash, key, val) end local function doKeyboard_privsett(user_id) local hash = 'user:'..user_id..':settings' local user_settings = db:hgetall(hash) if not next(user_settings) then user_settings = config.private_settings else for key, default_status in pairs(config.private_settings) do if not user_settings[key] then user_settings[key] = default_status end end end local keyboard = {inline_keyboard = {}} local button_names = { ['rules_on_join'] = _('Rules on join'), ['reports'] = _('Users reports') } for key, status in pairs(user_settings) do local icon if status == 'on' then icon = '✅' else icon = '❌'end table.insert(keyboard.inline_keyboard, {{text = button_names[key], callback_data = 'myset:alert:'..key}, {text = icon, callback_data = 'myset:switch:'..key}}) end return keyboard end function plugin.onTextMessage(msg, blocks) if msg.chat.type == 'private' then local keyboard = doKeyboard_privsett(msg.from.id) api.sendMessage(msg.from.id, _('Change your private settings'), true, keyboard) end end function plugin.onCallbackQuery(msg, blocks) if blocks[1] == 'alert' then api.answerCallbackQuery(msg.cb_id, get_button_description(blocks[2]), true) else change_private_setting(msg.from.id, blocks[2]) local keyboard = doKeyboard_privsett(msg.from.id) api.editMarkup(msg.from.id, msg.message_id, keyboard) api.answerCallbackQuery(msg.cb_id, _('⚙ Setting applied')) end end plugin.triggers = { onTextMessage = {config.cmd..'(mysettings)$'}, onCallbackQuery = { '^###cb:myset:(alert):(.*)$', '^###cb:myset:(switch):(.*)$', } } return plugin
gpl-2.0
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/linux/ioctl.lua
13
10152
-- ioctls, filling in as needed -- note there are some architecture dependent values local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local abi = require "syscall.abi" local s, t = types.s, types.t local strflag = require "syscall.helpers".strflag local arch = require("syscall.linux." .. abi.arch .. ".ioctl") local bit = require "syscall.bit" local band = bit.band local function bor(...) local r = bit.bor(...) if r < 0 then r = r + 4294967296 end -- TODO see note in NetBSD return r end local lshift = bit.lshift local rshift = bit.rshift -- these can vary by architecture local IOC = arch.IOC or { SIZEBITS = 14, DIRBITS = 2, NONE = 0, WRITE = 1, READ = 2, } IOC.READWRITE = IOC.READ + IOC.WRITE IOC.NRBITS = 8 IOC.TYPEBITS = 8 IOC.NRMASK = lshift(1, IOC.NRBITS) - 1 IOC.TYPEMASK = lshift(1, IOC.TYPEBITS) - 1 IOC.SIZEMASK = lshift(1, IOC.SIZEBITS) - 1 IOC.DIRMASK = lshift(1, IOC.DIRBITS) - 1 IOC.NRSHIFT = 0 IOC.TYPESHIFT = IOC.NRSHIFT + IOC.NRBITS IOC.SIZESHIFT = IOC.TYPESHIFT + IOC.TYPEBITS IOC.DIRSHIFT = IOC.SIZESHIFT + IOC.SIZEBITS local function ioc(dir, ch, nr, size) if type(ch) == "string" then ch = ch:byte() end return bor(lshift(dir, IOC.DIRSHIFT), lshift(ch, IOC.TYPESHIFT), lshift(nr, IOC.NRSHIFT), lshift(size, IOC.SIZESHIFT)) end local singletonmap = { int = "int1", char = "char1", uint = "uint1", uint32 = "uint32_1", uint64 = "uint64_1", } local function _IOC(dir, ch, nr, tp) if not tp or type(tp) == "number" then return ioc(dir, ch, nr, tp or 0) end local size = s[tp] local singleton = singletonmap[tp] ~= nil tp = singletonmap[tp] or tp return {number = ioc(dir, ch, nr, size), read = dir == IOC.READ or dir == IOC.READWRITE, write = dir == IOC.WRITE or dir == IOC.READWRITE, type = t[tp], singleton = singleton} end -- used to create numbers local _IO = function(ch, nr) return _IOC(IOC.NONE, ch, nr, 0) end local _IOR = function(ch, nr, tp) return _IOC(IOC.READ, ch, nr, tp) end local _IOW = function(ch, nr, tp) return _IOC(IOC.WRITE, ch, nr, tp) end local _IOWR = function(ch, nr, tp) return _IOC(IOC.READWRITE, ch, nr, tp) end -- used to decode ioctl numbers.. local _IOC_DIR = function(nr) return band(rshift(nr, IOC.DIRSHIFT), IOC.DIRMASK) end local _IOC_TYPE = function(nr) return band(rshift(nr, IOC.TYPESHIFT), IOC.TYPEMASK) end local _IOC_NR = function(nr) return band(rshift(nr, IOC.NRSHIFT), IOC.NRMASK) end local _IOC_SIZE = function(nr) return band(rshift(nr, IOC.SIZESHIFT), IOC.SIZEMASK) end -- ...and for the drivers/sound files... IOC.IN = lshift(IOC.WRITE, IOC.DIRSHIFT) IOC.OUT = lshift(IOC.READ, IOC.DIRSHIFT) IOC.INOUT = lshift(bor(IOC.WRITE, IOC.READ), IOC.DIRSHIFT) local IOCSIZE_MASK = lshift(IOC.SIZEMASK, IOC.SIZESHIFT) local IOCSIZE_SHIFT = IOC.SIZESHIFT -- VFIO driver writer decided not to use standard IOR/IOW alas local function vfio(dir, nr, tp) local ch = ";" nr = nr + 100 -- vfio base dir = IOC[string.upper(dir)] local io = _IOC(dir, ch, nr, tp) if type(io) == "number" then return io end -- if just IO, not return io.number = ioc(IOC.NONE, ch, nr, 0) -- number encode nothing, but we want to know anyway return io end local ioctl = strflag { -- termios, non standard values generally 0x54 = 'T' TCGETS = {number = 0x5401, read = true, type = "termios"}, TCSETS = 0x5402, TCSETSW = 0x5403, TCSETSF = 0x5404, TCSBRK = 0x5409, -- takes literal number TCXONC = 0x540A, TCFLSH = 0x540B, -- takes literal number TIOCEXCL = 0x540C, TIOCNXCL = 0x540D, TIOCSCTTY = 0x540E, TIOCGPGRP = 0x540F, TIOCSPGRP = 0x5410, TIOCOUTQ = 0x5411, TIOCSTI = 0x5412, TIOCGWINSZ = {number = 0x5413, read = true, type = "winsize"}, TIOCSWINSZ = {number = 0x5414, write = true, type = "winsize"}, TIOCMGET = 0x5415, TIOCMBIS = 0x5416, TIOCMBIC = 0x5417, TIOCMSET = 0x5418, TIOCGSOFTCAR = 0x5419, TIOCSSOFTCAR = 0x541A, FIONREAD = 0x541B, TIOCLINUX = 0x541C, TIOCCONS = 0x541D, TIOCGSERIAL = 0x541E, TIOCSSERIAL = 0x541F, TIOCPKT = 0x5420, FIONBIO = 0x5421, TIOCNOTTY = 0x5422, TIOCSETD = 0x5423, TIOCGETD = 0x5424, TCSBRKP = 0x5425, TIOCSBRK = 0x5427, TIOCCBRK = 0x5428, TIOCGSID = 0x5429, TCGETS2 = _IOR('T', 0x2A, "termios2"), TCSETS2 = _IOW('T', 0x2B, "termios2"), TCSETSW2 = _IOW('T', 0x2C, "termios2"), TCSETSF2 = _IOW('T', 0x2D, "termios2"), TIOCGPTN = _IOR('T', 0x30, "uint"), TIOCSPTLCK = _IOW('T', 0x31, "int"), TIOCGDEV = _IOR('T', 0x32, "uint"), TCGETX = 0x5432, TCSETX = 0x5433, TCSETXF = 0x5434, TCSETXW = 0x5435, TIOCSIG = _IOW('T', 0x36, "int"), TIOCVHANGUP = 0x5437, FIONCLEX = 0x5450, FIOCLEX = 0x5451, FIOASYNC = 0x5452, TIOCSERCONFIG = 0x5453, TIOCSERGWILD = 0x5454, TIOCSERSWILD = 0x5455, TIOCGLCKTRMIOS = 0x5456, TIOCSLCKTRMIOS = 0x5457, TIOCSERGSTRUCT = 0x5458, TIOCSERGETLSR = 0x5459, TIOCSERGETMULTI = 0x545A, TIOCSERSETMULTI = 0x545B, TIOCMIWAIT = 0x545C, TIOCGICOUNT = 0x545D, FIOQSIZE = 0x5460, -- socket ioctls from linux/sockios.h - for many of these you can use netlink instead FIOSETOWN = 0x8901, SIOCSPGRP = 0x8902, FIOGETOWN = 0x8903, SIOCGPGRP = 0x8904, SIOCATMARK = 0x8905, SIOCGSTAMP = 0x8906, SIOCGSTAMPNS = 0x8907, SIOCADDRT = 0x890B, SIOCDELRT = 0x890C, SIOCRTMSG = 0x890D, SIOCGIFINDEX = 0x8933, SIOCDARP = 0x8953, SIOCGARP = 0x8954, SIOCSARP = 0x8955, SIOCBRADDBR = 0x89a0, SIOCBRDELBR = 0x89a1, SIOCBRADDIF = 0x89a2, SIOCBRDELIF = 0x89a3, -- event system EVIOCGVERSION = _IOR('E', 0x01, "int"), EVIOCGID = _IOR('E', 0x02, "input_id"), EVIOCGREP = _IOR('E', 0x03, "uint2"), EVIOCSREP = _IOW('E', 0x03, "uint2"), EVIOCGKEYCODE = _IOR('E', 0x04, "uint2"), EVIOCGKEYCODE_V2 = _IOR('E', 0x04, "input_keymap_entry"), EVIOCSKEYCODE = _IOW('E', 0x04, "uint2"), EVIOCSKEYCODE_V2 = _IOW('E', 0x04, "input_keymap_entry"), EVIOCGNAME = function(len) return _IOC(IOC.READ, 'E', 0x06, len) end, EVIOCGPHYS = function(len) return _IOC(IOC.READ, 'E', 0x07, len) end, EVIOCGUNIQ = function(len) return _IOC(IOC.READ, 'E', 0x08, len) end, EVIOCGPROP = function(len) return _IOC(IOC.READ, 'E', 0x09, len) end, EVIOCGKEY = function(len) return _IOC(IOC.READ, 'E', 0x18, len) end, EVIOCGLED = function(len) return _IOC(IOC.READ, 'E', 0x19, len) end, EVIOCGSND = function(len) return _IOC(IOC.READ, 'E', 0x1a, len) end, EVIOCGSW = function(len) return _IOC(IOC.READ, 'E', 0x1b, len) end, EVIOCGBIT = function(ev, len) return _IOC(IOC.READ, 'E', 0x20 + ev, len) end, EVIOCGABS = function(abs) return _IOR('E', 0x40 + abs, "input_absinfo") end, EVIOCSABS = function(abs) return _IOW('E', 0xc0 + abs, "input_absinfo") end, EVIOCSFF = _IOC(IOC.WRITE, 'E', 0x80, "ff_effect"), EVIOCRMFF = _IOW('E', 0x81, "int"), EVIOCGEFFECTS = _IOR('E', 0x84, "int"), EVIOCGRAB = _IOW('E', 0x90, "int"), -- input devices UI_DEV_CREATE = _IO ('U', 1), UI_DEV_DESTROY = _IO ('U', 2), UI_SET_EVBIT = _IOW('U', 100, "int"), UI_SET_KEYBIT = _IOW('U', 101, "int"), -- tun/tap TUNSETNOCSUM = _IOW('T', 200, "int"), TUNSETDEBUG = _IOW('T', 201, "int"), TUNSETIFF = _IOW('T', 202, "int"), TUNSETPERSIST = _IOW('T', 203, "int"), TUNSETOWNER = _IOW('T', 204, "int"), TUNSETLINK = _IOW('T', 205, "int"), TUNSETGROUP = _IOW('T', 206, "int"), TUNGETFEATURES = _IOR('T', 207, "uint"), TUNSETOFFLOAD = _IOW('T', 208, "uint"), TUNSETTXFILTER = _IOW('T', 209, "uint"), TUNGETIFF = _IOR('T', 210, "uint"), TUNGETSNDBUF = _IOR('T', 211, "int"), TUNSETSNDBUF = _IOW('T', 212, "int"), TUNATTACHFILTER= _IOW('T', 213, "sock_fprog"), TUNDETACHFILTER= _IOW('T', 214, "sock_fprog"), TUNGETVNETHDRSZ= _IOR('T', 215, "int"), TUNSETVNETHDRSZ= _IOW('T', 216, "int"), TUNSETQUEUE = _IOW('T', 217, "int"), -- from linux/vhost.h VHOST_VIRTIO 0xAF VHOST_GET_FEATURES = _IOR(0xAF, 0x00, "uint64"), VHOST_SET_FEATURES = _IOW(0xAF, 0x00, "uint64"), VHOST_SET_OWNER = _IO(0xAF, 0x01), VHOST_RESET_OWNER = _IO(0xAF, 0x02), VHOST_SET_MEM_TABLE = _IOW(0xAF, 0x03, "vhost_memory"), VHOST_SET_LOG_BASE = _IOW(0xAF, 0x04, "uint64"), VHOST_SET_LOG_FD = _IOW(0xAF, 0x07, "int"), VHOST_SET_VRING_NUM = _IOW(0xAF, 0x10, "vhost_vring_state"), VHOST_SET_VRING_ADDR = _IOW(0xAF, 0x11, "vhost_vring_addr"), VHOST_SET_VRING_BASE = _IOW(0xAF, 0x12, "vhost_vring_state"), VHOST_GET_VRING_BASE = _IOWR(0xAF, 0x12, "vhost_vring_state"), VHOST_SET_VRING_KICK = _IOW(0xAF, 0x20, "vhost_vring_file"), VHOST_SET_VRING_CALL = _IOW(0xAF, 0x21, "vhost_vring_file"), VHOST_SET_VRING_ERR = _IOW(0xAF, 0x22, "vhost_vring_file"), VHOST_NET_SET_BACKEND= _IOW(0xAF, 0x30, "vhost_vring_file"), -- from linux/vfio.h type is ';' base is 100 VFIO_GET_API_VERSION = vfio('NONE', 0), VFIO_CHECK_EXTENSION = vfio('WRITE', 1, "uint32"), -- allow user defined ioctls _IO = _IO, _IOR = _IOR, _IOW = _IOW, _IOWR = _IOWR, } local override = arch.ioctl or {} if type(override) == "function" then override = override(_IO, _IOR, _IOW, _IOWR) end for k, v in pairs(override) do ioctl[k] = v end -- allow names for types in table ioctls for k, v in pairs(ioctl) do if type(v) == "table" and type(v.type) == "string" then v.type = t[v.type] end end -- alternate names ioctl.TIOCINQ = ioctl.FIONREAD return ioctl end return {init = init}
apache-2.0
LaFamiglia/Illarion-Content
item/altars.lua
1
22990
--[[ Illarion Server 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 (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 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/>. ]] --Priest magic: Becoming a devotee, change devotion, become a priest by using an altar --Altars are dedicated to gods, encoded in the data value --Overview of queststatus: --401 contains the ID of the god the character is devoted to --402 contains the ID of the god the character is a priest of. MUST be equal to 401 or 0. --Elder Gods --1: Ushara - Goddess of earth --2: Brágon - God of fire --3: Eldan - God of spirit --4: Tanora/Zelphia - Goddess of water --5: Findari - Goddess of air --Younger Gods --6: Nargùn - God of chaos --7: Elara - Goddess of wisdom and knowledge --8: Adron - God of festivities and wine --9: Oldra - Goddess of life and fertility --10: Cherga - Goddess of spirits and the underworld --11: Malachín - God of battle and hunting --12: Irmorom - God of trade and craftsmanship --13: Sirani - Goddess of love and pleasure --14: Zhambra - God of friendship and loyalty --15: Ronagan - God of thieves and shadows --16: Moshran - God of blood and bones --[[ The five: 553,137,0 Cherga: 892,388,0 Adron: 734,312,0 Adron: 955,835,3 Moshran: 673,391,2 Moshran: 563,548,-6 Nargun: 255,293,-5 Nargun: 786,443,0 Ronagan: 414,275,-6 Irmorom: 312,232,1 Ushara: 657,681,0 Tanora: 630,594,0 Eldan: 959,790,0 Findari: 899,835,5 Elara: 909,829,2 Bragon: 903,773,5 Malachin: 137,678,1 Zhambra: 142,564,0 Sirani: 176,761,0 Sirani: 176,762,0 Oldra: 799, 757 0]] local common = require("base.common") local gods = require("content.gods") local lookat = require("base.lookat") local M = {} --These are the items I need to become a devotee local devoteItems={}; devoteItems[1]={733,316,2588}; --Ushara: Stone block, Quartz sand, Brick devoteItems[2]={314,236,43}; --Brágon: potash, Gold ignot, Candle devoteItems[3]={256,2745,155}; --Eldan: Raw diamonds, Parchment, Sibanac leaf devoteItems[4]={52,253,72}; --Tanora: Bucket of water, Raw sapphire, Fishing rod devoteItems[5]={64,463,65}; --Findari: Arrow, Quill, Short Bow devoteItems[6]={80,356,733}; --Nargùn: Banana, Slouch hat, Stone block devoteItems[7]={2745,43,463}; --Elara: Parchment, Candle, Quill devoteItems[8]={223,2500,388}; --Adron: Iron Goblet, Bottle of Wine, Grapes devoteItems[9]={258,534,259}; --Oldra: Flail, Onion seeds, Grain devoteItems[10]={24,43,182}; --Cherga: Shovel, Candle, Black shirt devoteItems[11]={19,65,2586}; --Malachín: Metal shield, Short bow, Fur devoteItems[12]={3077,23,2140}; --Irmorom: Silver coin, Hammer, Tongs devoteItems[13]={235,144,174}; --Sirani: Gold ring, Virgins weed, Red cloth devoteItems[14]={2760,17,78}; --Zhambra: Rope, Wooden shield, Short sword devoteItems[15]={2760,190,48}; --Ronagan: Rope, Ornate dagger, Leather gloves devoteItems[16]={16,63,2757}; --Moshran: Orcish helmet, Entrails, Scimitar --These are the items I need to become a priest. Not relevant for now since there is no priest magic. local priestItems={}; priestItems[1]={2416,40,26,726,735}; --Ushara: Brown priest robe, Cleric's staff, Clay, Coarse sand, Raw stone priestItems[2]={2419,40,391,46,234}; --Brágon: Red priest robe, Cleric's staff, Torch, Ruby, Gold nugget priestItems[3]={2418,40,41,285,463}; --Eldan: Grey priest robe, Cleric's staff, Glass ignot, Diamond, Quill priestItems[4]={193,40,2496,284,279}; --Tanora: Blue robe, Cleric's staff, Bottle of Water, Sapphire, Sapphire ring priestItems[5]={2421,40,2780,322,166}; --Findari: White priest robe, Cleric's staff, Longbow, Wind arrow, Big empty bottle priestItems[6]={2418,445,355,225,290}; --Nargùn: Grey priest robe, Wooden sword, Salmon, Crown, Cabbage priestItems[7]={368,76,397,3110,222}; --Elara: Yellow priest robe, Mage's staff, Oil lamp, Pell, Amulet priestItems[8]={2419,224,335,2744,155}; --Adron: Red priest robe, Golden goblet, Lute, Pipe, Sibanac leaf priestItems[9]={2416,271,126,2786,249}; --Oldra: Brown priest robe, Scythe, Sickle, Branch, Bundle of grain priestItems[10]={2420,271,138,314,726}; --Cherga: Black priest robe, Scythe, Night angels blossom, potash, Coarse sand priestItems[11]={2421,20,391,2291,78}; --Malachín: White priest robe, Large metal shield, Torch, Salkamaerian Paladin's helmet, Shortsword priestItems[12]={2418,226,74,2763,2752}; --Irmorom: Gray priest robe, War Hammer, Hatchet, Pickaxe, Carving tools priestItems[13]={2421,40,280,354,222}; --Sirani: White priest robe, Cleric's staff, Diamond ring, Strawberry cake, Amulet priestItems[14]={368,20,2701,40,333}; --Zhambra: Yellow priest robe, Large metal shield, Longsword, Cleric's staff, Horn priestItems[15]={2420,2689,384,365,285}; --Ronagan: Black priest robe, Poisoned ornate dagger, Thieves gloves, Half leather armor, Diamond priestItems[16]={2420,552,39,69,2746}; --Moshran: Black priest robe, Deer meat, Skull staff, Raw leather, razor blade local function tellStuff(list,lang) local text=""; text=text..world:getItemName(list[1],lang); for i=2,#list do text=text..", "; text=text..world:getItemName(list[i],lang); end return text; end local function checkStuff(User,list) for i=1,#list do if User:countItem(list[i])<1 then return false; end end return true; end local function deleteStuff(User,list) for i=1,#list do User:eraseItem(list[i],1); end end local function checkAudience(god, position) local theCandidates=world:getPlayersInRangeOf(position,10); local counter=0; for i=1,#theCandidates do local candidate=theCandidates[i]; if candidate:getQuestProgress(401) == god then counter=counter+1; end end if counter>3 then --I need three other characters with the same devotion around return true; else return false; end end local function ZeniaAltar(User, SourceItem) if User:getQuestProgress(502) == 1 then User:setQuestProgress(502, 2) --Prayer done User:inform("[Quest status] Du hast gebetet und hoffentlich Zenia damit erfreut. Kehre zu ihr zurück", "[Quest status] You feel as if you have prayed sufficient to please Zenia. Please return to her.") elseif User:getQuestProgress(502) == 8 and User:countItemAt("all", 2760) >= 4 and User:countItemAt("all", 3) >= 5 and User:countItemAt("all", 26) >= 10 and User:countItemAt("all", 73) >= 10 then -- Take raft items User:eraseItem(2760, 4) User:eraseItem(3, 5) User:eraseItem(26, 10) User:eraseItem(73, 10) User:setQuestProgress(502, 9) -- You made a raft. User:inform("[Quest status] Du sieht, nach dem Beten, dass die Materialien sich von selbst zu einem kleinen Floss zusammenfügen. Du klettert darauf und wird zu einer kleinen Insel transportiert.", "[Quest status] After praying, you see the items magically form a small raft. You climb on board and are transported to a small island.") User:warp(position(753, 351, -9)) world:gfx(11, User.pos) world:makeSound(9, User.pos) elseif User:getQuestProgress(502) == 8 then -- You dropped something you needed. User:inform("Sie müssen alle Einzelteile für Floß und Gebet.", "You need all items for raft and prayer.") elseif User:getQuestProgress(502) == 10 and User:countItemAt("all",355) >= 10 then -- Revisit Zenia User:eraseItem(355, 10) User:setQuestProgress(502, 9) -- Ready to leave again. User:inform("[Quest status] Du sieht, nach dem Beten, einen hellen Lichtblitz und das kleine Floss erscheint im Wasser. Nachdem du darauf geklettert bist, wirst du zurück auf die kleine Insel gebracht.", "[Quest status] After praying, you see a bright light flash and your small raft magically appears in the water. Climbing onto it, you are transported back to the small island.") User:warp(position(753, 351, -9)) world:gfx(11, User.pos) world:makeSound(9, User.pos) elseif User:getQuestProgress(502) == 10 then -- You dropped something you needed. User:inform("Sie verfügen nicht über die richtigen Elemente für das Gebet.", "You lack the proper items for prayer.") end end function M.LookAtItem( User, Item ) local thisGod = tonumber(Item:getData("god")) if thisGod==nil then thisGod = 0; end; --Tell the user who's altar that is if thisGod==gods.GOD_NONE or thisGod>gods.GOD_THEFIVE then --undedicated altar lookat.SetSpecialName(Item, "Ungeweihter Altar","Undedicated altar") elseif thisGod > gods.GOD_NONE then --dedicated altar lookat.SetSpecialName(Item, "Altar "..gods.GOD_DE[thisGod].."s, "..gods.DESCRIPTION_DE[thisGod]..".", "Altar of "..gods.GOD_EN[thisGod]..", the "..gods.DESCRIPTION_EN[thisGod].."."); if (thisGod > 5) then -- anything else is only for the younger gods --Now send the user some infos what he should do if he wants to become a devotee, change dedication or become a priest local devotion = User:getQuestProgress(401) local priesthood = User:getQuestProgress(402) --Check for corrupted status if priesthood ~= 0 and devotion ~= priesthood and User:getMagicType()== 1 then --Error! The character is a priest, but not a priest of "his" god! common.InformNLS(User,"[Fehler] Bitte informiere einen Entwickler. Der Priesterstatus deines Charakters ist fehlerhaft.","[Error] Please inform a developer, the priest status of your character is flawed."); return; --bailing out end --Error! The character is not a priest, but has a priest quest status! Or player uses priest magic but has no dedicated god! if (priesthood ~= 0 and User:getMagicType()~= 1) or (priesthood == 0 and User:getMagicType()== 1) then common.InformNLS(User,"[Fehler] Bitte informiere einen Entwickler. Der Priesterstatus deines Charakters ist fehlerhaft.","[Error] Please inform a developer, the priest status of your character is flawed."); return; --bailing out end --Check what the User is and send him instructions accordingly if (devotion == 0) then --a noob without a god lookat.SetSpecialDescription(Item,"Um euch "..gods.GOD_DE[thisGod].." zu weihen, werdet ihr folgendes opfern müssen: "..tellStuff(devoteItems[thisGod],User:getPlayerLanguage()),"To devote yourself to "..gods.GOD_EN[thisGod]..", you'll have to donate: "..tellStuff(devoteItems[thisGod],User:getPlayerLanguage())); elseif (devotion == thisGod) then -- devoted to this god common.InformNLS(User, "Der Anblick von "..gods.GOD_DE[thisGod].."s Altar erfüllt dich in deiner Ergebenheit mit Stolz.", "Beholding the altar of "..gods.GOD_EN[thisGod].." makes you feel proud of your devotion."); --For enabling becoming a priest, use the stuff below. Doesn't make any sense without priest magic, though. -- TODO needs adjustment. --[[ if User:getMagicType()== 0 and User:getMagicFlags(0)~= 0 then --a mage! Can't become priest common.InformNLS(User,"Ein Magier kann leider kein Priester werden.","As a magician, you cannot become a priest anymore."); elseif User:getMagicType()== 2 and User:getMagicFlags(2)~= 0 then --a bard! Can't become priest common.InformNLS(User,"Ein Barde kann leider kein Priester werden.","As a bard, you cannot become a priest anymore."); elseif User:getMagicType()== 3 and User:getMagicFlags(3)~= 0 then --a druid! Can't become priest common.InformNLS(User,"Ein Druide kann leider kein Priester werden.","As a druid, you cannot become a priest anymore."); else --a noob, may become priest common.InformNLS(User,"Um ein Priester "..godName[thisGod].."s zu werden, werdet ihr folgendes opfern müssen:","To become a priest of "..godName[thisGod]..", you'll have to donate:"); User:inform(tellStuff(priestItems[thisGod],User:getPlayerLanguage())); --stuff4priest end ]] elseif devotion ~= thisGod then -- devoted to another god if (priesthood == 0) then common.InformNLS(User,"Als Anhänger einer anderen Gottheit werdet ihr eurem Gott abschwören müssen, um euch "..gods.GOD_DE[thisGod].." zu weihen.","As devotee of another god, you'll have to abjure your god to devote yourself to "..gods.GOD_EN[thisGod].."."); common.InformNLS(User,"Um euch "..gods.GOD_DE[thisGod].." zu weihen, werdet ihr folgendes opfern müssen:","To devote yourself to "..gods.GOD_EN[thisGod]..", you'll have to donate:"); User:inform(tellStuff(devoteItems[thisGod],User:getPlayerLanguage())); --stuff4devotee else common.InformNLS(User,"Als Priester einer anderen Gottheit müßtet ihr eurer Gottheit abschwören, um ein Priester "..gods.GOD_DE[thisGod].."s zu werden.","As priest of another god, you'll have to abjure your god to become a priest of "..gods.GOD_EN[thisGod].."."); common.InformNLS(User,"Um ein Priester "..gods.GOD_DE[thisGod].."s zu werden, werdet ihr folgendes opfern müssen:","To devote yourself to "..gods.GOD_EN[thisGod]..", you'll have to donate:"); User:inform(tellStuff(devoteItems[thisGod],User:getPlayerLanguage())); --stuff4devotee User:inform(tellStuff(priestItems[thisGod],User:getPlayerLanguage())); --stuff4priest end end end -- younger gods end --dedicated altar return lookat.GenerateLookAt(User, Item, lookat.NONE) end --function function M.UseItem(User, SourceItem, ltstate) -- Lake of Life Altar if SourceItem.pos == position(763, 336, -9) then --Zenia's Altar ZeniaAltar(User, SourceItem) return end local thisGod = tonumber(SourceItem:getData("god")) if thisGod==nil then thisGod = 0; end; --Depending on who's altar that is and who uses it, execute different actions if thisGod==gods.GOD_NONE or thisGod>gods.GOD_THEFIVE then --undedicated altar common.InformNLS(User,"Ihr berührt den Altar, die Abwesenheit göttlichen Wirkens ist offensichtlich.","You touch the altar, the absence of divine blessing is obvious."); elseif thisGod > gods.GOD_NONE then --dedicated altar if (thisGod > 5) then -- anything else is only for the younger gods --Now send the user some infos what he should do if he wants to become a devotee, change dedication or become a priest local devotion = User:getQuestProgress(401) local priesthood = User:getQuestProgress(402) --Check for corrupted status if priesthood ~= 0 and devotion ~= priesthood and User:getMagicType()== 1 then --Error! The character is a priest, but not a priest of "his" god! common.InformNLS(User,"[Fehler] Bitte informiere einen Entwickler. Der Priesterstatus deines Charakters ist fehlerhaft.","[Error] Please inform a developer, the priest status of your character is flawed."); return; --bailing out end --Error! The character is not a priest, but has a priest quest status! Or player uses priest magic but has no dedicated god! if (priesthood ~= 0 and User:getMagicType()~= 1) or (priesthood == 0 and User:getMagicType()== 1) then common.InformNLS(User,"[Fehler] Bitte informiere einen Entwickler. Der Priesterstatus deines Charakters ist fehlerhaft.","[Error] Please inform a developer, the priest status of your character is flawed."); return; --bailing out end --Check what the User is and send him instructions accordingly if (devotion == 0) then --a noob without a god if checkStuff(User,devoteItems[thisGod]) then deleteStuff(User,devoteItems[thisGod]); common.InformNLS(User,"Ihr empfangt den Segen "..gods.GOD_DE[thisGod].."s und weiht euer Leben dem Glaube an die Gottheit. Euer Opfer:","You receive the blessing of "..gods.GOD_EN[thisGod].." and devote your life to the faith in the divinity. Your donation:"); world:gfx(16,User.pos); world:makeSound(13,User.pos); User:setQuestProgress(401,thisGod); --become devotee User:setQuestProgress(402,0); --the char was no priest before - must not be one afterwards else --does not have the stuff common.InformNLS(User,"Um euch "..gods.GOD_DE[thisGod].." zu weihen, werdet ihr folgendes opfern müssen:","To devote yourself to "..gods.GOD_EN[thisGod]..", you'll have to donate:"); end User:inform(tellStuff(devoteItems[thisGod],User:getPlayerLanguage())); --stuff4devotee elseif (devotion == thisGod) then -- devoted to this god common.InformNLS(User, "Ihr betet zu "..gods.GOD_DE[thisGod].." und bekräftigt euren Glauben.", "You pray to "..gods.GOD_EN[thisGod].." and confirm your faith."); if (priesthood == 0) then common.InformNLS(User, "[INFO] An dieser Stelle könntest du Priester werden, aber Priestermagie ist noch nicht verfügbar.", "[INFO] At this point you could become a priest, but priest magic is not available yet."); --Below, even more stuff that only makes sense with priest magic. Code makes devotees become priests. --[[ if User:getMagicType()== 0 and User:getMagicFlags(0)~= 0 then --a mage! Can't become priest common.InformNLS(User,"Ein Magier kann leider kein Priester werden.","As a magician, you cannot become a priest anymore."); elseif User:getMagicType()== 2 and User:getMagicFlags(2)~= 0 then --a bard! Can't become priest common.InformNLS(User,"Ein Barde kann leider kein Priester werden.","As a bard, you cannot become a priest anymore."); elseif User:getMagicType()== 3 and User:getMagicFlags(3)~= 0 then --a druid! Can't become priest common.InformNLS(User,"Ein Druide kann leider kein Priester werden.","As a druid, you cannot become a priest anymore."); else --a noob, may become priest if checkAudience(thisGod,User.pos) then if checkStuff(User,priestItems[thisGod]) then deleteStuff(User,priestItems[thisGod]); common.InformNLS(User,"Ihr empfangt die Weihe eines Priesters "..godName[thisGod].."s. Euer Opfer:","You receive the ordination to the priesthood of "..godName[thisGod]..". Your donation:"); world:gfx(31,User.pos); world:makeSound(13,User.pos); User:setQuestProgress(402,thisGod); --become priest of this god User:setMagicType(1); User:teachMagic(1,1); --priest runes User:teachMagic(1,2); User:teachMagic(1,3); else --does not have the stuff common.InformNLS(User,"Um ein Priester "..godName[thisGod].."s zu werden, werdet ihr folgendes opfern müssen:","To become a priest of "..godName[thisGod]..", you'll have to donate:"); end --item check User:inform(tellStuff(priestItems[thisGod],User:getPlayerLanguage())); --stuff4priest else --not enough devotees around common.InformNLS(User,"Um die Priesterweihe zu empfangen müßt ihr wenigstens drei Anhänger "..godName[thisGod].."s zu einer Messe versammeln.","To receive the ordination to the priesthood of "..godName[thisGod]..", you'll have to gather at least three devotees for a mass."); end --audience check end --noob --]] end elseif devotion ~= thisGod then -- devoted to another god if (priesthood == 0) then if checkStuff(User,devoteItems[thisGod]) then deleteStuff(User,devoteItems[thisGod]); common.InformNLS(User,"Ihr empfangt den Segen "..gods.GOD_DE[thisGod].."s und weiht euer Leben dem Glaube an die Gottheit. Euer Opfer:","You receive the blessing of "..gods.GOD_EN[thisGod].." and devote your life to the faith in the divinity. Your donation:"); world:gfx(16,User.pos); world:makeSound(13,User.pos); User:setQuestProgress(401,thisGod); --become devotee User:setQuestProgress(402,0); --the char was no priest before - must not be one afterwards else --does not have the stuff common.InformNLS(User,"Um euch "..gods.GOD_DE[thisGod].." zu weihen, werdet ihr folgendes opfern müssen:","To devote yourself to "..gods.GOD_EN[thisGod]..", you'll have to donate:"); end User:inform(tellStuff(devoteItems[thisGod],User:getPlayerLanguage())); --stuff4devotee else common.InformNLS(User, "[INFO] An dieser Stelle könntest du Priester werden, aber Priestermagie ist noch nicht verfügbar.", "[INFO] At this point you could become a priest, but priest magic is not available yet."); -- useless without priest magic --[[ if checkAudience(thisGod,User.pos) then if checkStuff(User,devoteItems[thisGod]) and checkStuff(User,priestItems[thisGod]) then deleteStuff(User,devoteItems[thisGod]); common.InformNLS(User,"Ihr schwört eurem alten Glauben ab und empfangt die Weihe eines Priesters "..godName[thisGod].."s. Euer Opfer:","You abjure your old faith and receive the ordination to the priesthood of "..godName[thisGod]..". Your donation:"); world:gfx(16,User.pos); world:makeSound(13,User.pos); User:setQuestProgress(401,thisGod); --become devotee of this god User:setQuestProgress(402,thisGod); --become priest of this god else --does not have the stuff common.InformNLS(User,"Um ein Priester "..godName[thisGod].."s zu werden, werdet ihr folgendes opfern müssen:","To become a priest of "..godName[thisGod]..", you'll have to donate:"); end else --not enough devotees around common.InformNLS(User,"Um die Priesterweihe zu empfangen müßt ihr wenigstens drei Anhänger "..godName[thisGod].."s zu einer Messe versammeln.","To receive the ordination to the priesthood of "..godName[thisGod]..", you'll have to gather at least three devotees for a mass."); end --audience check User:inform(tellStuff(devoteItems[thisGod],User:getPlayerLanguage())); --stuff4devotee User:inform(tellStuff(priestItems[thisGod],User:getPlayerLanguage())); --stuff4priest --]] end end else -- elder gods common.InformNLS(User, "Du kannst kein Anhänger der alten Götter werden.", "You cannot become a devotee of the elder gods."); end end --dedicated altar end --function return M
agpl-3.0
decimad/luabind-deboostified
examples/glut/glut_bindings.lua
38
1543
quit = false function resize_func(w, h) local ratio = w / h print('====== resize') glMatrixMode(gl.PROJECTION) glLoadIdentity() glViewport(0,0,w,h) gluPerspective(45,ratio,1,1000) glMatrixMode(gl.MODELVIEW) glLoadIdentity() end angle = 0 angle2 = 0 previous_time = 0 function display_func() if quit then return end local cur_time = glutGet(glut.ELAPSED_TIME) local delta = (cur_time - previous_time) / 1000 previous_time = cur_time glClear(gl.COLOR_BUFFER_BIT + gl.DEPTH_BUFFER_BIT) glPushMatrix() glTranslate(0,0,-5) glRotate(angle, 0, 1, 0) glRotate(angle2, 0, 0, 1) glColor3(1,0,0) -- glutWireSphere(0.75, 10, 10) glutSolidTeapot(0.75) -- glColor3(1,1,1) -- glutWireTeapot(0.75) glPopMatrix() angle = angle + 200 * delta angle2 = angle2 + 170 * delta frames = frames + 1 if math.mod(frames, 100) == 0 then local fps = frames * 1000 / (glutGet(glut.ELAPSED_TIME) - start_time); print('fps: ' .. fps .. ' time: ' .. glutGet(glut.ELAPSED_TIME) .. ' frames: ' .. frames) end glutSwapBuffers() end function keyboard_func(key,x,y) print('keyboard' .. key) if key == 27 then glutDestroyWindow(window) quit = true end end glutInitWindowSize(600,600) glutInitWindowPosition(0,0) glutInitDisplayMode(glut.RGB + glut.DOUBLE + glut.DEPTH) window = glutCreateWindow("luabind, glut-bindings") glutDisplayFunc(display_func) glutIdleFunc(display_func) glutKeyboardFunc(keyboard_func) glutReshapeFunc(resize_func) resize_func(600,600) start_time = glutGet(glut.ELAPSED_TIME) frames = 0 glutMainLoop()
mit
gwx/tome-grayswandir-weaponry
data/objects/clubs.lua
1
2377
if config.settings.tome.grayswandir_weaponry_clubs ~= false then newEntity{ define_as = 'BASE_CLUB', slot = 'MAINHAND', dual_wieldable = true, type = 'weapon', subtype='club', add_name = ' (#COMBAT#)', display = '/', color=colors.LIGHT_RED, image = 'object/generic_club.png', moddable_tile = '%s_club', encumber = 3, rarity = 7, exotic = true, combat = { talented = 'mace', damrange = 1.4, physspeed = 1, sound = {'actions/melee', pitch=0.6, vol=1.2}, sound_miss = {'actions/melee', pitch=0.6, vol=1.2}}, desc = [[Blunt and deadly.]], randart_able = '/data/general/objects/random-artifacts/generic.lua', egos = '/data-grayswandir-weaponry/egos/clubs.lua', egos_chance = {prefix = resolvers.mbonus(40, 5), suffix = resolvers.mbonus(40, 5),}, } newEntity{ base = 'BASE_CLUB', name = 'elm club', short_name = 'elm', level_range = {1, 10}, require = { stat = { str=11 }, }, cost = 5, material_level = 1, combat = { dam = resolvers.rngavg(11,14), apr = 2, physcrit = 0.5, dammod = {str=1}, }, } newEntity{ base = 'BASE_CLUB', name = 'ash club', short_name = 'ash', level_range = {10, 20}, require = { stat = { str=16 }, }, cost = 10, material_level = 2, combat = { dam = resolvers.rngavg(11,17), apr = 3, physcrit = 1, dammod = {str=1}, }, } newEntity{ base = 'BASE_CLUB', name = 'yew club', short_name = 'yew', level_range = {20, 30}, require = { stat = { str=24 }, }, cost = 15, material_level = 3, combat = { dam = resolvers.rngavg(24,30), apr = 4, physcrit = 1.5, dammod = {str=1}, }, } newEntity{ base = 'BASE_CLUB', name = 'elven-wood club', short_name = 'e.wood', level_range = {30, 40}, require = { stat = { str=35 }, }, cost = 25, material_level = 4, combat = { dam = resolvers.rngavg(33,40), apr = 5, physcrit = 2.5, dammod = {str=1}, }, } newEntity{ base = 'BASE_MACE', name = 'dragonbone club', short_name = 'dragonbone', level_range = {40, 50}, require = { stat = { str=48 }, }, cost = 35, material_level = 5, combat = { dam = resolvers.rngavg(43,48), apr = 6, physcrit = 3, dammod = {str=1}, }, } end
gpl-3.0
qq779089973/ramod
luci/libs/core/luasrc/ltn12.lua
83
11303
--[[ LuaSocket 2.0.2 license Copyright � 2004-2007 Diego Nehab Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- --[[ Changes made by LuCI project: * Renamed to luci.ltn12 to avoid collisions with luasocket * Added inline documentation ]]-- ----------------------------------------------------------------------------- -- LTN12 - Filters, sources, sinks and pumps. -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id$ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local table = require("table") local base = _G --- Diego Nehab's LTN12 - Filters, sources, sinks and pumps. -- See http://lua-users.org/wiki/FiltersSourcesAndSinks for design concepts module("luci.ltn12") filter = {} source = {} sink = {} pump = {} -- 2048 seems to be better in windows... BLOCKSIZE = 2048 _VERSION = "LTN12 1.0.1" ----------------------------------------------------------------------------- -- Filter stuff ----------------------------------------------------------------------------- --- LTN12 Filter constructors -- @class module -- @name luci.ltn12.filter --- Return a high level filter that cycles a low-level filter -- by passing it each chunk and updating a context between calls. -- @param low Low-level filter -- @param ctx Context -- @param extra Extra argument passed to the low-level filter -- @return LTN12 filter function filter.cycle(low, ctx, extra) base.assert(low) return function(chunk) local ret ret, ctx = low(ctx, chunk, extra) return ret end end --- Chain a bunch of filters together. -- (thanks to Wim Couwenberg) -- @param ... filters to be chained -- @return LTN12 filter function filter.chain(...) local n = table.getn(arg) local top, index = 1, 1 local retry = "" return function(chunk) retry = chunk and retry while true do if index == top then chunk = arg[index](chunk) if chunk == "" or top == n then return chunk elseif chunk then index = index + 1 else top = top+1 index = top end else chunk = arg[index](chunk or "") if chunk == "" then index = index - 1 chunk = retry elseif chunk then if index == n then return chunk else index = index + 1 end else base.error("filter returned inappropriate nil") end end end end end ----------------------------------------------------------------------------- -- Source stuff ----------------------------------------------------------------------------- --- LTN12 Source constructors -- @class module -- @name luci.ltn12.source -- create an empty source local function empty() return nil end --- Create an empty source. -- @return LTN12 source function source.empty() return empty end --- Return a source that just outputs an error. -- @param err Error object -- @return LTN12 source function source.error(err) return function() return nil, err end end --- Create a file source. -- @param handle File handle ready for reading -- @param io_err IO error object -- @return LTN12 source function source.file(handle, io_err) if handle then return function() local chunk = handle:read(BLOCKSIZE) if not chunk then handle:close() end return chunk end else return source.error(io_err or "unable to open file") end end --- Turn a fancy source into a simple source. -- @param src fancy source -- @return LTN12 source function source.simplify(src) base.assert(src) return function() local chunk, err_or_new = src() src = err_or_new or src if not chunk then return nil, err_or_new else return chunk end end end --- Create a string source. -- @param s Data -- @return LTN12 source function source.string(s) if s then local i = 1 return function() local chunk = string.sub(s, i, i+BLOCKSIZE-1) i = i + BLOCKSIZE if chunk ~= "" then return chunk else return nil end end else return source.empty() end end --- Creates rewindable source. -- @param src LTN12 source to be made rewindable -- @return LTN12 source function source.rewind(src) base.assert(src) local t = {} return function(chunk) if not chunk then chunk = table.remove(t) if not chunk then return src() else return chunk end else t[#t+1] = chunk end end end --- Chain a source and a filter together. -- @param src LTN12 source -- @param f LTN12 filter -- @return LTN12 source function source.chain(src, f) base.assert(src and f) local last_in, last_out = "", "" local state = "feeding" local err return function() if not last_out then base.error('source is empty!', 2) end while true do if state == "feeding" then last_in, err = src() if err then return nil, err end last_out = f(last_in) if not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end elseif last_out ~= "" then state = "eating" if last_in then last_in = "" end return last_out end else last_out = f(last_in) if last_out == "" then if last_in == "" then state = "feeding" else base.error('filter returned ""') end elseif not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end else return last_out end end end end end --- Create a source that produces contents of several sources. -- Sources will be used one after the other, as if they were concatenated -- (thanks to Wim Couwenberg) -- @param ... LTN12 sources -- @return LTN12 source function source.cat(...) local src = table.remove(arg, 1) return function() while src do local chunk, err = src() if chunk then return chunk end if err then return nil, err end src = table.remove(arg, 1) end end end ----------------------------------------------------------------------------- -- Sink stuff ----------------------------------------------------------------------------- --- LTN12 sink constructors -- @class module -- @name luci.ltn12.sink --- Create a sink that stores into a table. -- @param t output table to store into -- @return LTN12 sink function sink.table(t) t = t or {} local f = function(chunk, err) if chunk then t[#t+1] = chunk end return 1 end return f, t end --- Turn a fancy sink into a simple sink. -- @param snk fancy sink -- @return LTN12 sink function sink.simplify(snk) base.assert(snk) return function(chunk, err) local ret, err_or_new = snk(chunk, err) if not ret then return nil, err_or_new end snk = err_or_new or snk return 1 end end --- Create a file sink. -- @param handle file handle to write to -- @param io_err IO error -- @return LTN12 sink function sink.file(handle, io_err) if handle then return function(chunk, err) if not chunk then handle:close() return 1 else return handle:write(chunk) end end else return sink.error(io_err or "unable to open file") end end -- creates a sink that discards data local function null() return 1 end --- Create a sink that discards data. -- @return LTN12 sink function sink.null() return null end --- Create a sink that just returns an error. -- @param err Error object -- @return LTN12 sink function sink.error(err) return function() return nil, err end end --- Chain a sink with a filter. -- @param f LTN12 filter -- @param snk LTN12 sink -- @return LTN12 sink function sink.chain(f, snk) base.assert(f and snk) return function(chunk, err) if chunk ~= "" then local filtered = f(chunk) local done = chunk and "" while true do local ret, snkerr = snk(filtered, err) if not ret then return nil, snkerr end if filtered == done then return 1 end filtered = f(done) end else return 1 end end end ----------------------------------------------------------------------------- -- Pump stuff ----------------------------------------------------------------------------- --- LTN12 pump functions -- @class module -- @name luci.ltn12.pump --- Pump one chunk from the source to the sink. -- @param src LTN12 source -- @param snk LTN12 sink -- @return Chunk of data or nil if an error occured -- @return Error object function pump.step(src, snk) local chunk, src_err = src() local ret, snk_err = snk(chunk, src_err) if chunk and ret then return 1 else return nil, src_err or snk_err end end --- Pump all data from a source to a sink, using a step function. -- @param src LTN12 source -- @param snk LTN12 sink -- @param step step function (optional) -- @return 1 if the operation succeeded otherwise nil -- @return Error object function pump.all(src, snk, step) base.assert(src and snk) step = step or pump.step while true do local ret, err = step(src, snk) if not ret then if err then return nil, err else return 1 end end end end
mit
299299/Urho3D
Source/ThirdParty/LuaJIT/dynasm/dasm_arm.lua
33
34598
------------------------------------------------------------------------------ -- DynASM ARM module. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "arm", description = "DynASM ARM module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable, rawget = assert, setmetatable, rawget local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub local concat, sort, insert = table.concat, table.sort, table.insert local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local ror, tohex = bit.ror, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", "IMMV8", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n <= 0x000fffff then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") if n <= 0x000fffff then insert(actlist, pos+1, n) n = map_action.ESC * 0x10000 end actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. -- Ext. register name -> int. name. local map_archdef = { sp = "r13", lr = "r14", pc = "r15", } -- Int. register name -> ext. name. local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", } local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) return map_reg_rev[s] or s end local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, } local map_cond = { eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7, hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14, hs = 2, lo = 3, } ------------------------------------------------------------------------------ -- Template strings for ARM instructions. local map_op = { -- Basic data processing instructions. and_3 = "e0000000DNPs", eor_3 = "e0200000DNPs", sub_3 = "e0400000DNPs", rsb_3 = "e0600000DNPs", add_3 = "e0800000DNPs", adc_3 = "e0a00000DNPs", sbc_3 = "e0c00000DNPs", rsc_3 = "e0e00000DNPs", tst_2 = "e1100000NP", teq_2 = "e1300000NP", cmp_2 = "e1500000NP", cmn_2 = "e1700000NP", orr_3 = "e1800000DNPs", mov_2 = "e1a00000DPs", bic_3 = "e1c00000DNPs", mvn_2 = "e1e00000DPs", and_4 = "e0000000DNMps", eor_4 = "e0200000DNMps", sub_4 = "e0400000DNMps", rsb_4 = "e0600000DNMps", add_4 = "e0800000DNMps", adc_4 = "e0a00000DNMps", sbc_4 = "e0c00000DNMps", rsc_4 = "e0e00000DNMps", tst_3 = "e1100000NMp", teq_3 = "e1300000NMp", cmp_3 = "e1500000NMp", cmn_3 = "e1700000NMp", orr_4 = "e1800000DNMps", mov_3 = "e1a00000DMps", bic_4 = "e1c00000DNMps", mvn_3 = "e1e00000DMps", lsl_3 = "e1a00000DMws", lsr_3 = "e1a00020DMws", asr_3 = "e1a00040DMws", ror_3 = "e1a00060DMws", rrx_2 = "e1a00060DMs", -- Multiply and multiply-accumulate. mul_3 = "e0000090NMSs", mla_4 = "e0200090NMSDs", umaal_4 = "e0400090DNMSs", -- v6 mls_4 = "e0600090DNMSs", -- v6T2 umull_4 = "e0800090DNMSs", umlal_4 = "e0a00090DNMSs", smull_4 = "e0c00090DNMSs", smlal_4 = "e0e00090DNMSs", -- Halfword multiply and multiply-accumulate. smlabb_4 = "e1000080NMSD", -- v5TE smlatb_4 = "e10000a0NMSD", -- v5TE smlabt_4 = "e10000c0NMSD", -- v5TE smlatt_4 = "e10000e0NMSD", -- v5TE smlawb_4 = "e1200080NMSD", -- v5TE smulwb_3 = "e12000a0NMS", -- v5TE smlawt_4 = "e12000c0NMSD", -- v5TE smulwt_3 = "e12000e0NMS", -- v5TE smlalbb_4 = "e1400080NMSD", -- v5TE smlaltb_4 = "e14000a0NMSD", -- v5TE smlalbt_4 = "e14000c0NMSD", -- v5TE smlaltt_4 = "e14000e0NMSD", -- v5TE smulbb_3 = "e1600080NMS", -- v5TE smultb_3 = "e16000a0NMS", -- v5TE smulbt_3 = "e16000c0NMS", -- v5TE smultt_3 = "e16000e0NMS", -- v5TE -- Miscellaneous data processing instructions. clz_2 = "e16f0f10DM", -- v5T rev_2 = "e6bf0f30DM", -- v6 rev16_2 = "e6bf0fb0DM", -- v6 revsh_2 = "e6ff0fb0DM", -- v6 sel_3 = "e6800fb0DNM", -- v6 usad8_3 = "e780f010NMS", -- v6 usada8_4 = "e7800010NMSD", -- v6 rbit_2 = "e6ff0f30DM", -- v6T2 movw_2 = "e3000000DW", -- v6T2 movt_2 = "e3400000DW", -- v6T2 -- Note: the X encodes width-1, not width. sbfx_4 = "e7a00050DMvX", -- v6T2 ubfx_4 = "e7e00050DMvX", -- v6T2 -- Note: the X encodes the msb field, not the width. bfc_3 = "e7c0001fDvX", -- v6T2 bfi_4 = "e7c00010DMvX", -- v6T2 -- Packing and unpacking instructions. pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6 pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6 sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6 sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6 sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6 sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6 sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6 sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6 uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6 uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6 uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6 uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6 uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6 uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6 -- Saturating instructions. qadd_3 = "e1000050DMN", -- v5TE qsub_3 = "e1200050DMN", -- v5TE qdadd_3 = "e1400050DMN", -- v5TE qdsub_3 = "e1600050DMN", -- v5TE -- Note: the X for ssat* encodes sat_imm-1, not sat_imm. ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6 usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6 ssat16_3 = "e6a00f30DXM", -- v6 usat16_3 = "e6e00f30DXM", -- v6 -- Parallel addition and subtraction. sadd16_3 = "e6100f10DNM", -- v6 sasx_3 = "e6100f30DNM", -- v6 ssax_3 = "e6100f50DNM", -- v6 ssub16_3 = "e6100f70DNM", -- v6 sadd8_3 = "e6100f90DNM", -- v6 ssub8_3 = "e6100ff0DNM", -- v6 qadd16_3 = "e6200f10DNM", -- v6 qasx_3 = "e6200f30DNM", -- v6 qsax_3 = "e6200f50DNM", -- v6 qsub16_3 = "e6200f70DNM", -- v6 qadd8_3 = "e6200f90DNM", -- v6 qsub8_3 = "e6200ff0DNM", -- v6 shadd16_3 = "e6300f10DNM", -- v6 shasx_3 = "e6300f30DNM", -- v6 shsax_3 = "e6300f50DNM", -- v6 shsub16_3 = "e6300f70DNM", -- v6 shadd8_3 = "e6300f90DNM", -- v6 shsub8_3 = "e6300ff0DNM", -- v6 uadd16_3 = "e6500f10DNM", -- v6 uasx_3 = "e6500f30DNM", -- v6 usax_3 = "e6500f50DNM", -- v6 usub16_3 = "e6500f70DNM", -- v6 uadd8_3 = "e6500f90DNM", -- v6 usub8_3 = "e6500ff0DNM", -- v6 uqadd16_3 = "e6600f10DNM", -- v6 uqasx_3 = "e6600f30DNM", -- v6 uqsax_3 = "e6600f50DNM", -- v6 uqsub16_3 = "e6600f70DNM", -- v6 uqadd8_3 = "e6600f90DNM", -- v6 uqsub8_3 = "e6600ff0DNM", -- v6 uhadd16_3 = "e6700f10DNM", -- v6 uhasx_3 = "e6700f30DNM", -- v6 uhsax_3 = "e6700f50DNM", -- v6 uhsub16_3 = "e6700f70DNM", -- v6 uhadd8_3 = "e6700f90DNM", -- v6 uhsub8_3 = "e6700ff0DNM", -- v6 -- Load/store instructions. str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL", strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL", ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL", ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL", strh_2 = "e00000b0DL", strh_3 = "e00000b0DL", ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL", ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL", strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL", ldm_2 = "e8900000oR", ldmia_2 = "e8900000oR", ldmfd_2 = "e8900000oR", ldmda_2 = "e8100000oR", ldmfa_2 = "e8100000oR", ldmdb_2 = "e9100000oR", ldmea_2 = "e9100000oR", ldmib_2 = "e9900000oR", ldmed_2 = "e9900000oR", stm_2 = "e8800000oR", stmia_2 = "e8800000oR", stmfd_2 = "e8800000oR", stmda_2 = "e8000000oR", stmfa_2 = "e8000000oR", stmdb_2 = "e9000000oR", stmea_2 = "e9000000oR", stmib_2 = "e9800000oR", stmed_2 = "e9800000oR", pop_1 = "e8bd0000R", push_1 = "e92d0000R", -- Branch instructions. b_1 = "ea000000B", bl_1 = "eb000000B", blx_1 = "e12fff30C", bx_1 = "e12fff10M", -- Miscellaneous instructions. nop_0 = "e1a00000", mrs_1 = "e10f0000D", bkpt_1 = "e1200070K", -- v5T svc_1 = "ef000000T", swi_1 = "ef000000T", ud_0 = "e7f001f0", -- VFP instructions. ["vadd.f32_3"] = "ee300a00dnm", ["vadd.f64_3"] = "ee300b00Gdnm", ["vsub.f32_3"] = "ee300a40dnm", ["vsub.f64_3"] = "ee300b40Gdnm", ["vmul.f32_3"] = "ee200a00dnm", ["vmul.f64_3"] = "ee200b00Gdnm", ["vnmul.f32_3"] = "ee200a40dnm", ["vnmul.f64_3"] = "ee200b40Gdnm", ["vmla.f32_3"] = "ee000a00dnm", ["vmla.f64_3"] = "ee000b00Gdnm", ["vmls.f32_3"] = "ee000a40dnm", ["vmls.f64_3"] = "ee000b40Gdnm", ["vnmla.f32_3"] = "ee100a40dnm", ["vnmla.f64_3"] = "ee100b40Gdnm", ["vnmls.f32_3"] = "ee100a00dnm", ["vnmls.f64_3"] = "ee100b00Gdnm", ["vdiv.f32_3"] = "ee800a00dnm", ["vdiv.f64_3"] = "ee800b00Gdnm", ["vabs.f32_2"] = "eeb00ac0dm", ["vabs.f64_2"] = "eeb00bc0Gdm", ["vneg.f32_2"] = "eeb10a40dm", ["vneg.f64_2"] = "eeb10b40Gdm", ["vsqrt.f32_2"] = "eeb10ac0dm", ["vsqrt.f64_2"] = "eeb10bc0Gdm", ["vcmp.f32_2"] = "eeb40a40dm", ["vcmp.f64_2"] = "eeb40b40Gdm", ["vcmpe.f32_2"] = "eeb40ac0dm", ["vcmpe.f64_2"] = "eeb40bc0Gdm", ["vcmpz.f32_1"] = "eeb50a40d", ["vcmpz.f64_1"] = "eeb50b40Gd", ["vcmpze.f32_1"] = "eeb50ac0d", ["vcmpze.f64_1"] = "eeb50bc0Gd", vldr_2 = "ed100a00dl|ed100b00Gdl", vstr_2 = "ed000a00dl|ed000b00Gdl", vldm_2 = "ec900a00or", vldmia_2 = "ec900a00or", vldmdb_2 = "ed100a00or", vpop_1 = "ecbd0a00r", vstm_2 = "ec800a00or", vstmia_2 = "ec800a00or", vstmdb_2 = "ed000a00or", vpush_1 = "ed2d0a00r", ["vmov.f32_2"] = "eeb00a40dm|eeb00a00dY", -- #imm is VFPv3 only ["vmov.f64_2"] = "eeb00b40Gdm|eeb00b00GdY", -- #imm is VFPv3 only vmov_2 = "ee100a10Dn|ee000a10nD", vmov_3 = "ec500a10DNm|ec400a10mDN|ec500b10GDNm|ec400b10GmDN", vmrs_0 = "eef1fa10", vmrs_1 = "eef10a10D", vmsr_1 = "eee10a10D", ["vcvt.s32.f32_2"] = "eebd0ac0dm", ["vcvt.s32.f64_2"] = "eebd0bc0dGm", ["vcvt.u32.f32_2"] = "eebc0ac0dm", ["vcvt.u32.f64_2"] = "eebc0bc0dGm", ["vcvtr.s32.f32_2"] = "eebd0a40dm", ["vcvtr.s32.f64_2"] = "eebd0b40dGm", ["vcvtr.u32.f32_2"] = "eebc0a40dm", ["vcvtr.u32.f64_2"] = "eebc0b40dGm", ["vcvt.f32.s32_2"] = "eeb80ac0dm", ["vcvt.f64.s32_2"] = "eeb80bc0GdFm", ["vcvt.f32.u32_2"] = "eeb80a40dm", ["vcvt.f64.u32_2"] = "eeb80b40GdFm", ["vcvt.f32.f64_2"] = "eeb70bc0dGm", ["vcvt.f64.f32_2"] = "eeb70ac0GdFm", -- VFPv4 only: ["vfma.f32_3"] = "eea00a00dnm", ["vfma.f64_3"] = "eea00b00Gdnm", ["vfms.f32_3"] = "eea00a40dnm", ["vfms.f64_3"] = "eea00b40Gdnm", ["vfnma.f32_3"] = "ee900a40dnm", ["vfnma.f64_3"] = "ee900b40Gdnm", ["vfnms.f32_3"] = "ee900a00dnm", ["vfnms.f64_3"] = "ee900b00Gdnm", -- NYI: Advanced SIMD instructions. -- NYI: I have no need for these instructions right now: -- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh -- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe -- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb -- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2 } -- Add mnemonics for "s" variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "s" then local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2) t[sub(k, 1, -3).."s"..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r(1?[0-9])$") if r then r = tonumber(r) if r <= 15 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_gpr_pm(expr) local pm, expr2 = match(expr, "^([+-]?)(.*)$") return parse_gpr(expr2), (pm == "-") end local function parse_vr(expr, tp) local t, r = match(expr, "^([sd])([0-9]+)$") if t == tp then r = tonumber(r) if r <= 31 then if t == "s" then return shr(r, 1), band(r, 1) end return band(r, 15), shr(r, 4) end end werror("bad register name `"..expr.."'") end local function parse_reglist(reglist) reglist = match(reglist, "^{%s*([^}]*)}$") if not reglist then werror("register list expected") end local rr = 0 for p in gmatch(reglist..",", "%s*([^,]*),") do local rbit = shl(1, parse_gpr(gsub(p, "%s+$", ""))) if band(rr, rbit) ~= 0 then werror("duplicate register `"..p.."'") end rr = rr + rbit end return rr end local function parse_vrlist(reglist) local ta, ra, tb, rb = match(reglist, "^{%s*([sd])([0-9]+)%s*%-%s*([sd])([0-9]+)%s*}$") ra, rb = tonumber(ra), tonumber(rb) if ta and ta == tb and ra and rb and ra <= 31 and rb <= 31 and ra <= rb then local nr = rb+1 - ra if ta == "s" then return shl(shr(ra,1),12)+shl(band(ra,1),22) + nr else return shl(band(ra,15),12)+shl(shr(ra,4),22) + nr*2 + 0x100 end end werror("register list expected") end local function parse_imm(imm, bits, shift, scale, signed) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_imm12(imm) local n = tonumber(imm) if n then local m = band(n) for i=0,-15,-1 do if shr(m, 8) == 0 then return m + shl(band(i, 15), 8) end m = ror(m, 2) end werror("out of range immediate `"..imm.."'") else waction("IMM12", 0, imm) return 0 end end local function parse_imm16(imm) imm = match(imm, "^#(.*)$") if not imm then werror("expected immediate operand") end local n = tonumber(imm) if n then if shr(n, 16) == 0 then return band(n, 0x0fff) + shl(band(n, 0xf000), 4) end werror("out of range immediate `"..imm.."'") else waction("IMM16", 32*16, imm) return 0 end end local function parse_imm_load(imm, ext) local n = tonumber(imm) if n then if ext then if n >= -255 and n <= 255 then local up = 0x00800000 if n < 0 then n = -n; up = 0 end return shl(band(n, 0xf0), 4) + band(n, 0x0f) + up end else if n >= -4095 and n <= 4095 then if n >= 0 then return n+0x00800000 end return -n end end werror("out of range immediate `"..imm.."'") else waction(ext and "IMML8" or "IMML12", 32768 + shl(ext and 8 or 12, 5), imm) return 0 end end local function parse_shift(shift, gprok) if shift == "rrx" then return 3 * 32 else local s, s2 = match(shift, "^(%S+)%s*(.*)$") s = map_shift[s] if not s then werror("expected shift operand") end if sub(s2, 1, 1) == "#" then return parse_imm(s2, 5, 7, 0, false) + shl(s, 5) else if not gprok then werror("expected immediate shift operand") end return shl(parse_gpr(s2), 8) + shl(s, 5) + 16 end end end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end local function parse_load(params, nparams, n, op) local oplo = band(op, 255) local ext, ldrd = (oplo ~= 0), (oplo == 208) local d if (ldrd or oplo == 240) then d = band(shr(op, 12), 15) if band(d, 1) ~= 0 then werror("odd destination register") end end local pn = params[n] local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$") local p2 = params[n+1] if not p1 then if not p2 then if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then local mode, n, s = parse_label(pn, false) waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1) return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0) end local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12), format(tp.ctypefmt, tailr)) return op + shl(d, 16) + 0x01000000 + (ext and 0x00400000 or 0) end end end werror("expected address operand") end if wb == "!" then op = op + 0x00200000 end if p2 then if wb == "!" then werror("bad use of '!'") end local p3 = params[n+2] op = op + shl(parse_gpr(p1), 16) local imm = match(p2, "^#(.*)$") if imm then local m = parse_imm_load(imm, ext) if p3 then werror("too many parameters") end op = op + m + (ext and 0x00400000 or 0) else local m, neg = parse_gpr_pm(p2) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 then op = op + parse_shift(p3) end end else local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$") op = op + shl(parse_gpr(p1a), 16) + 0x01000000 if p2 ~= "" then local imm = match(p2, "^,%s*#(.*)$") if imm then local m = parse_imm_load(imm, ext) op = op + m + (ext and 0x00400000 or 0) else local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$") local m, neg = parse_gpr_pm(p2a) if ldrd and (m == d or m-1 == d) then werror("register conflict") end op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000) if p3 ~= "" then if ext then werror("too many parameters") end op = op + parse_shift(p3) end end else if wb == "!" then werror("bad use of '!'") end op = op + (ext and 0x00c00000 or 0x00800000) end end return op end local function parse_vload(q) local reg, imm = match(q, "^%[%s*([^,%s]*)%s*(.*)%]$") if reg then local d = shl(parse_gpr(reg), 16) if imm == "" then return d end imm = match(imm, "^,%s*#(.*)$") if imm then local n = tonumber(imm) if n then if n >= -1020 and n <= 1020 and n%4 == 0 then return d + (n >= 0 and n/4+0x00800000 or -n/4) end werror("out of range immediate `"..imm.."'") else waction("IMMV8", 32768 + 32*8, imm) return d end end else if match(q, "^[<>=%-]") or match(q, "^extern%s+") then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n + 0x2800, s, 1) return 15 * 65536 end local reg, tailr = match(q, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local d, tp = parse_gpr(reg) if tp then waction("IMMV8", 32768 + 32*8, format(tp.ctypefmt, tailr)) return shl(d, 16) end end end werror("expected address operand") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. local function parse_template(params, template, nparams, pos) local op = tonumber(sub(template, 1, 8), 16) local n = 1 local vr = "s" -- Process each character. for p in gmatch(sub(template, 9), ".") do local q = params[n] if p == "D" then op = op + shl(parse_gpr(q), 12); n = n + 1 elseif p == "N" then op = op + shl(parse_gpr(q), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(q), 8); n = n + 1 elseif p == "M" then op = op + parse_gpr(q); n = n + 1 elseif p == "d" then local r,h = parse_vr(q, vr); op = op+shl(r,12)+shl(h,22); n = n + 1 elseif p == "n" then local r,h = parse_vr(q, vr); op = op+shl(r,16)+shl(h,7); n = n + 1 elseif p == "m" then local r,h = parse_vr(q, vr); op = op+r+shl(h,5); n = n + 1 elseif p == "P" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm12(imm) + 0x02000000 else op = op + parse_gpr(q) end n = n + 1 elseif p == "p" then op = op + parse_shift(q, true); n = n + 1 elseif p == "L" then op = parse_load(params, nparams, n, op) elseif p == "l" then op = op + parse_vload(q) elseif p == "B" then local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) elseif p == "C" then -- blx gpr vs. blx label. if match(q, "^([%w_]+):(r1?[0-9])$") or match(q, "^r(1?[0-9])$") then op = op + parse_gpr(q) else if op < 0xe0000000 then werror("unconditional instruction") end local mode, n, s = parse_label(q, false) waction("REL_"..mode, n, s, 1) op = 0xfa000000 end elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "o" then local r, wb = match(q, "^([^!]*)(!?)$") op = op + shl(parse_gpr(r), 16) + (wb == "!" and 0x00200000 or 0) n = n + 1 elseif p == "R" then op = op + parse_reglist(q); n = n + 1 elseif p == "r" then op = op + parse_vrlist(q); n = n + 1 elseif p == "W" then op = op + parse_imm16(q); n = n + 1 elseif p == "v" then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 elseif p == "w" then local imm = match(q, "^#(.*)$") if imm then op = op + parse_imm(q, 5, 7, 0, false); n = n + 1 else op = op + shl(parse_gpr(q), 8) + 16 end elseif p == "X" then op = op + parse_imm(q, 5, 16, 0, false); n = n + 1 elseif p == "Y" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 8) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xf0), 12) + band(imm, 0x0f) elseif p == "K" then local imm = tonumber(match(q, "^#(.*)$")); n = n + 1 if not imm or shr(imm, 16) ~= 0 then werror("bad immediate operand") end op = op + shl(band(imm, 0xfff0), 4) + band(imm, 0x000f) elseif p == "T" then op = op + parse_imm(q, 24, 0, 0, false); n = n + 1 elseif p == "s" then -- Ignored. else assert(false) end end wputpos(pos, op) end map_op[".template__"] = function(params, template, nparams) if not params then return template:gsub("%x%x%x%x%x%x%x%x", "") end -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions. if secpos+3 > maxsecpos then wflush() end local pos = wpos() local lpos, apos, spos = #actlist, #actargs, secpos local ok, err for t in gmatch(template, "[^|]+") do ok, err = pcall(parse_template, params, t, nparams, pos) if ok then return end secpos = spos actlist[lpos+1] = nil actlist[lpos+2] = nil actlist[lpos+3] = nil actargs[apos+1] = nil actargs[apos+2] = nil actargs[apos+3] = nil end error(err, 0) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = function(t, k) local v = map_coreop[k] if v then return v end local k1, cc, k2 = match(k, "^(.-)(..)([._].*)$") local cv = map_cond[cc] if cv then local v = rawget(t, k1..k2) if type(v) == "string" then local scv = format("%x", cv) return gsub(scv..sub(v, 2), "|e", "|"..scv) end end end }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
chelog/brawl
gamemodes/brawl/gamemode/modules/base/modes/ffa_dm/sv_mode.lua
1
2563
function MODE:Think() if GetGlobalInt( "brawl.RoundState" ) < 3 then for k, ply in pairs( player.GetAll() ) do if not IsValid( ply ) then continue end if ply:Frags() >= self.maxKills then brawl.EndRound({ winner = ply }) end end end end local intermissionTime = 10 function MODE:EndRound( data ) if data.winner then local ply = data.winner if not IsValid( ply ) then return end timer.Simple( intermissionTime, brawl.NewRound ) SetGlobalFloat( "RoundStart", CurTime() + intermissionTime ) SetGlobalInt( "brawl.RoundState", 3 ) brawl.NotifyAll({ Color(255,212,50), ply:Name(), color_white, " won the round!" }) ply:AddXP( 1000, "Round winner" ) end end function MODE:NewRound( type ) local delay = 6.1 game.CleanUpMap() brawl.CleanUpMap() for k, ply in pairs( player.GetAll() ) do if not ply:GetNWBool( "SpectateOnly" ) then ply:SetFrags( 0 ) ply:SetDeaths( 0 ) ply:KillSilent() ply:UnSpectate() ply:SetNWBool( "Spectating", false ) ply:Spawn() ply:Freeze( true ) net.Start( "brawl.round.start" ) net.WriteFloat( delay ) net.WriteString( self.name ) net.WriteString( self.agenda ) net.Send( ply ) end end SetGlobalInt( "brawl.RoundState", 1 ) timer.Simple( delay, function() for k, ply in pairs( player.GetAll() ) do ply:Freeze( false ) end SetGlobalInt( "brawl.RoundState", 2 ) brawl.NotifyAll( "A new round has started!" ) end) end function MODE:PlayerSpawn( ply ) local spawn = brawl.points.findFarthestSpawn( ply ) if spawn.pos then ply:SetPos( spawn.pos + Vector(0,0,5) ) end if spawn.ang then ply:SetEyeAngles( spawn.ang ) end ply:LoadModel() ply:LoadWeapons() ply:LoadSkills() end function MODE:DeathThink( ply ) local spawnTime = ply:GetNWFloat( "RespawnTime" ) if CurTime() >= spawnTime then if ply:GetNWBool( "SpectateOnly" ) then ply:StartSpectating() else ply:Spawn() end end return false end function MODE:PlayerCanTalkTo( listener, talker, team, text ) return true end function MODE:PlayerCanSpectate( ply, ent ) return true end function MODE:PlayerInitialSpawn( ply ) timer.Simple(0, function() local delay = 6.1 ply:KillSilent() ply:SetNWFloat( "RespawnTime", CurTime() + delay ) ply:SetTeam( 1001 ) ply:SetScore( -1 ) net.Start( "brawl.round.start" ) net.WriteFloat( delay ) net.WriteString( self.name ) net.WriteString( self.agenda ) net.Send( ply ) end) end function MODE:PlayerDeath( ply ) ply:SetNWFloat( "RespawnTime", CurTime() + 8 ) end
gpl-3.0
rrze-likwid/likwid
examples/Lua-likwidAPI.lua
2
2871
#!<PREFIX>/bin/likwid-lua --[[ * ======================================================================================= * * Filename: Lua-likwidAPI.lua * * Description: Example how to use the LIKWID API in Lua scripts * * Version: <VERSION> * Released: <DATE> * * Author: Thomas Roehl (tr), thomas.roehl@googlemail.com * Project: likwid * * Copyright (C) 2015 RRZE, University Erlangen-Nuremberg * * This program is free software: you can redistribute it and/or modify it under * the terms of the GNU General Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your option) any later * version. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * this program. If not, see <http://www.gnu.org/licenses/>. * * ======================================================================================= ]] package.path = package.path .. ';<PREFIX>/share/lua/?.lua' local likwid = require("likwid") EVENTSET = "INSTR_RETIRED_ANY:FIXC0" cpuinfo = likwid.getCpuInfo() cputopo = likwid.getCpuTopology() print(string.format("Likwid example on a %s with %d CPUs", cpuinfo.name, cputopo.numHWThreads)) local cpus = {} for i, cpu in pairs(cputopo.threadPool) do table.insert(cpus, cpu.apicId) end if likwid.init(#cpus, cpus) ~= 0 then print("Failed to initialize LIKWID's performance monitoring module") likwid.putTopology() os.exit(1) end local gid = likwid.addEventSet(EVENTSET) if gid <= 0 then print(string.format("Failed to add events %s to LIKWID's performance monitoring module", EVENTSET)) likwid.finalize() likwid.putTopology() os.exit(1) end if likwid.setupCounters(gid) < 0 then printf(string.format("Failed to setup group %d in LIKWID's performance monitoring module\n", gid)) likwid.finalize() likwid.putTopology() os.exit(1) end if likwid.startCounters() < 0 then printf(string.format("Failed to start group %d in LIKWID's performance monitoring module\n", gid)) likwid.finalize() likwid.putTopology() os.exit(1) end -- Application code likwid.sleep(2) if likwid.stopCounters() < 0 then printf(string.format("Failed to stop group %d in LIKWID's performance monitoring module\n", gid)) likwid.finalize() likwid.putTopology() os.exit(1) end for i,cpu in pairs(cpus) do result = likwid.getResult(gid, 1, i) print(string.format("Measurement result for event set %s at CPU %d: %f", EVENTSET, cpu, result)) end likwid.finalize()
gpl-3.0
dismantl/luci-0.12
protocols/hso/luasrc/model/cbi/admin_network/proto_hso.lua
14
4573
--[[ LuCI - Lua Configuration Interface Copyright 2015 Stanislas Bertrand <stanislasbertrand@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local hsoname,hsotype,hsointerface local device, apn, service, pincode, username, password local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand device = section:taboption("general", Value, "device", translate("Control interface")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/ttyHS*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do hsoname = string.gsub(node,"/dev/","") hsotype = nixio.fs.readfile("/sys/class/tty/" .. hsoname .. "/hsotype") device:value(node, hsotype .. " (" .. node ..")" ) if string.find(hsotype,"Application") ~= nil then device.default = node end end end service = section:taboption("general", Value, "service", translate("Service Type")) service.default = "umts" service:value("umts", "UMTS/GPRS") service:value("umts_only", translate("UMTS only")) service:value("gprs_only", translate("GPRS only")) apn = section:taboption("general", Value, "apn", translate("APN")) pincode = section:taboption("general", Value, "pincode", translate("PIN")) 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 maxwait = section:taboption("advanced", Value, "maxwait", translate("Modem init timeout"), translate("Maximum amount of seconds to wait for the modem to become ready")) maxwait.placeholder = "20" maxwait.datatype = "min(1)" 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" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger"
apache-2.0
qq779089973/ramod
luci/applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_config.lua
80
1153
--[[ LuCI - Lua Configuration Interface (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.controller.luci_diag.devinfo_common") m = Map("luci_devinfo", translate("Network Device Scanning Configuration"), translate("Configure scanning for 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", "netdiscover_devinfo") scannet = m:section(TypedSection, "netdiscover_scannet", translate("Scanning Configuration"), translate("Networks to scan for devices")) scannet.addremove = true scannet.anonymous = false luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet) return m
mit
UberWaffe/OpenRA
mods/ra/maps/allies-02-classic/allies02.lua
1
2440
JeepReinforcements = { "e1", "e1", "e1", "jeep" } JeepReinforcementsInterval = 15 TruckNames = { "truk", "truk", "truk" } TruckInterval = 25 TruckDelay = 75 FirstJeepReinforcementsDelay = 125 SecondJeepReinforcementsDelay = 250 SendMcvReinforcements = function() Media.PlaySpeechNotification("ReinforcementsArrived") local mcv = Actor.Create("mcv", { Owner = player, Location = ReinforcementsEntryPoint.Location }) Actor.Move(mcv, McvDeployPoint.Location) Actor.DeployTransform(mcv) end SendJeepReinforcements = function() Media.PlaySpeechNotification("ReinforcementsArrived") Reinforcements.Reinforce(player, JeepReinforcements, ReinforcementsEntryPoint.Location, ReinforcementsRallyPoint.Location, JeepReinforcementsInterval) end RunInitialActivities = function() Actor.Harvest(Harvester) end MissionAccomplished = function() Mission.MissionOver({ player }, nil, true) Media.PlayMovieFullscreen("montpass.vqa") end MissionFailed = function() Mission.MissionOver(nil, { player }, true) Media.PlayMovieFullscreen("frozen.vqa") end Tick = function() Mission.TickTakeOre(ussr) if Mission.RequiredUnitsAreDestroyed(player) then MissionFailed() end if not trucksSent and Mission.RequiredUnitsAreDestroyed(ussr) and Mission.RequiredUnitsAreDestroyed(badGuy) then SendTrucks() trucksSent = true end end SendTrucks = function() Media.PlaySpeechNotification("ConvoyApproaching") OpenRA.RunAfterDelay(TruckDelay, function() local trucks = Reinforcements.Reinforce(france, TruckNames, TruckEntryPoint.Location, TruckRallyPoint.Location, TruckInterval, function(truck) Actor.Move(truck, TruckExitPoint.Location) Actor.RemoveSelf(truck) end) local trucksTeam = Team.New(trucks) Team.AddEventHandler(trucksTeam.OnAllRemovedFromWorld, MissionAccomplished) Team.AddEventHandler(trucksTeam.OnAnyKilled, MissionFailed) end) end WorldLoaded = function() player = OpenRA.GetPlayer("Greece") france = OpenRA.GetPlayer("France") ussr = OpenRA.GetPlayer("USSR") badGuy = OpenRA.GetPlayer("BadGuy") RunInitialActivities() SendMcvReinforcements() OpenRA.RunAfterDelay(FirstJeepReinforcementsDelay, SendJeepReinforcements) OpenRA.RunAfterDelay(SecondJeepReinforcementsDelay, SendJeepReinforcements) OpenRA.SetViewportCenterPosition(ReinforcementsEntryPoint.CenterPosition) Media.PlayMovieFullscreen("ally2.vqa", function() Media.PlayMovieFullscreen("mcv.vqa", Media.PlayRandomMusic) end) end
gpl-3.0
jason9263/JasonAI
torch/2_supervised/4_train.lua
1
7013
---------------------------------------------------------------------- -- This script demonstrates how to define a training procedure, -- irrespective of the model/loss functions chosen. -- -- It shows how to: -- + construct mini-batches on the fly -- + define a closure to estimate (a noisy) loss -- function, as well as its derivatives wrt the parameters of the -- model to be trained -- + optimize the function, according to several optmization -- methods: SGD, L-BFGS. -- -- Clement Farabet ---------------------------------------------------------------------- require 'torch' -- torch require 'xlua' -- xlua provides useful tools, like progress bars require 'optim' -- an optimization package, for online and batch methods ---------------------------------------------------------------------- -- parse command line arguments if not opt then print '==> processing options' cmd = torch.CmdLine() cmd:text() cmd:text('SVHN Training/Optimization') cmd:text() cmd:text('Options:') cmd:option('-save', 'results', 'subdirectory to save/log experiments in') cmd:option('-visualize', false, 'visualize input data and weights during training') cmd:option('-plot', false, 'live plot') cmd:option('-optimization', 'SGD', 'optimization method: SGD | ASGD | CG | LBFGS') cmd:option('-learningRate', 1e-3, 'learning rate at t=0') cmd:option('-batchSize', 1, 'mini-batch size (1 = pure stochastic)') cmd:option('-weightDecay', 0, 'weight decay (SGD only)') cmd:option('-momentum', 0, 'momentum (SGD only)') cmd:option('-t0', 1, 'start averaging at t0 (ASGD only), in nb of epochs') cmd:option('-maxIter', 2, 'maximum nb of iterations for CG and LBFGS') cmd:text() opt = cmd:parse(arg or {}) end ---------------------------------------------------------------------- -- CUDA? if opt.type == 'cuda' then model:cuda() criterion:cuda() end ---------------------------------------------------------------------- print '==> defining some tools' -- classes classes = {'1','2','3','4','5','6','7','8','9','0'} -- This matrix records the current confusion across classes confusion = optim.ConfusionMatrix(classes) -- Log results to files trainLogger = optim.Logger(paths.concat(opt.save, 'train.log')) testLogger = optim.Logger(paths.concat(opt.save, 'test.log')) -- Retrieve parameters and gradients: -- this extracts and flattens all the trainable parameters of the mode -- into a 1-dim vector if model then parameters,gradParameters = model:getParameters() end ---------------------------------------------------------------------- print '==> configuring optimizer' if opt.optimization == 'CG' then optimState = { maxIter = opt.maxIter } optimMethod = optim.cg elseif opt.optimization == 'LBFGS' then optimState = { learningRate = opt.learningRate, maxIter = opt.maxIter, nCorrection = 10 } optimMethod = optim.lbfgs elseif opt.optimization == 'SGD' then optimState = { learningRate = opt.learningRate, weightDecay = opt.weightDecay, momentum = opt.momentum, learningRateDecay = 1e-7 } optimMethod = optim.sgd elseif opt.optimization == 'ASGD' then optimState = { eta0 = opt.learningRate, t0 = trsize * opt.t0 } optimMethod = optim.asgd else error('unknown optimization method') end ---------------------------------------------------------------------- print '==> defining training procedure' function train() -- epoch tracker epoch = epoch or 1 -- local vars local time = sys.clock() -- set model to training mode (for modules that differ in training and testing, like Dropout) model:training() -- shuffle at each epoch shuffle = torch.randperm(trsize) -- do one epoch print('==> doing epoch on training data:') print("==> online epoch # " .. epoch .. ' [batchSize = ' .. opt.batchSize .. ']') for t = 1,trainData:size(),opt.batchSize do -- disp progress xlua.progress(t, trainData:size()) -- create mini batch local inputs = {} local targets = {} for i = t,math.min(t+opt.batchSize-1,trainData:size()) do -- load new sample local input = trainData.data[shuffle[i]] local target = trainData.labels[shuffle[i]] if opt.type == 'double' then input = input:double() if opt.loss == 'mse' then target = target:double() end elseif opt.type == 'cuda' then input = input:cuda(); if opt.loss == 'mse' then target = target:cuda() end end table.insert(inputs, input) table.insert(targets, target) end -- create closure to evaluate f(X) and df/dX local feval = function(x) -- get new parameters if x ~= parameters then parameters:copy(x) end -- reset gradients gradParameters:zero() -- f is the average of all criterions local f = 0 -- evaluate function for complete mini batch for i = 1,#inputs do -- estimate f local output = model:forward(inputs[i]) local err = criterion:forward(output, targets[i]) f = f + err -- estimate df/dW local df_do = criterion:backward(output, targets[i]) model:backward(inputs[i], df_do) -- update confusion confusion:add(output, targets[i]) end -- normalize gradients and f(X) gradParameters:div(#inputs) f = f/#inputs -- return f and df/dX return f,gradParameters end -- optimize on current mini-batch if optimMethod == optim.asgd then _,_,average = optimMethod(feval, parameters, optimState) else optimMethod(feval, parameters, optimState) end end -- time taken time = sys.clock() - time time = time / trainData:size() print("\n==> time to learn 1 sample = " .. (time*1000) .. 'ms') -- print confusion matrix print(confusion) -- update logger/plot trainLogger:add{['% mean class accuracy (train set)'] = confusion.totalValid * 100} if opt.plot then trainLogger:style{['% mean class accuracy (train set)'] = '-'} trainLogger:plot() end -- save/log current net local filename = paths.concat(opt.save, 'model.net') os.execute('mkdir -p ' .. sys.dirname(filename)) print('==> saving model to '..filename) torch.save(filename, model) -- next epoch confusion:zero() epoch = epoch + 1 end
apache-2.0
gwx/tome-grayswandir-weird-wyrmic
data/libs/auto-temps-0.lua
5
1697
-- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. superload('mod.class.Actor', function(_M) --- Apply the temporary values defined in a table. -- The values will be recorded in source.__tmpvals to be automatically -- discarded at the appropriate time. -- @param source The source we're applying the values from/to. -- @param values The table of {attribute -> increase} values we're applying. Defaults to source.temps. function _M:autoTemporaryValues(source, values) values = values or source.temps for attribute, value in pairs(values) do self:effectTemporaryValue(source, attribute, value) end return source end --- Remove the temporary values defined by autoTemporaryValues, or similar calls. -- Removes all values in source.__tmpvals. -- @param source The source we're applying the values of. function _M:autoTemporaryValuesRemove(source) values = values or source.temps if not source.__tmpvals then return end for _, val in pairs(source.__tmpvals) do self:removeTemporaryValue(val[1], val[2]) end source.__tmpvals = nil end end)
gpl-3.0
299299/Urho3D
bin/Data/LuaScripts/01_HelloWorld.lua
24
1882
-- This first example, maintaining tradition, prints a "Hello World" message. -- Furthermore it shows: -- - Using the Sample utility functions as a base for the application -- - Adding a Text element to the graphical user interface -- - Subscribing to and handling of update events require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create "Hello World" Text CreateText() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_FREE) -- Finally, hook-up this HelloWorld instance to handle update events SubscribeToEvents() end function CreateText() -- Construct new Text object local helloText = Text:new() -- Set String to display helloText.text = "Hello World from Urho3D!" -- Set font and text color helloText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 30) helloText.color = Color(0.0, 1.0, 0.0) -- Align Text center-screen helloText.horizontalAlignment = HA_CENTER helloText.verticalAlignment = VA_CENTER -- Add Text instance to the UI root element ui.root:AddChild(helloText) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Do nothing for now, could be extended to eg. animate the display end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Hat0']]\">" .. " <attribute name=\"Is Visible\" value=\"false\" />" .. " </add>" .. "</patch>" end
mit
LaFamiglia/Illarion-Content
item/id_2052_stretcher.lua
1
1145
--[[ Illarion Server 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 (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 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/>. ]] -- UPDATE items SET itm_script='item.id_2052_stretcher' WHERE itm_id = 2052; local licence = require("base.licence") local leatherproducing = require("content.gatheringcraft.leatherproducing") local M = {} function M.UseItem(User, SourceItem, ltstate) if licence.licence(User) then --checks if user is citizen or has a licence return -- avoids crafting if user is neither citizen nor has a licence end leatherproducing.StartGathering(User, SourceItem, ltstate); end return M
agpl-3.0
dwicke/L-BFGS-B-Lua
src/luatest.lua
1
1174
package.path = package.path..";../../?/init.lua" package.path = package.path..";../../?.lua" require "luawrapper" function getf(action1, action2) local x1,y1 = -10,-10 local h1 = 100 local s1 = 4.0 local f1 = h1*(1 - (((action1-x1)/s1)*((action1-x1)/s1)) - (((action2-y1)/s1)*((action2-y1)/s1))) + 50 print ("lua f = ".. f1 .. " actions = " .. action1 .. " " .. action2) return -f1 end function getgrad(action1, action2) local x1,y1 = -10,-10 local h1 = 100 local s1 = 4.0 local f1 = { 2*h1* ((action1-x1)/(s1*s1)), 2*h1* ((action2-y1)/(s1*s1)) } return f1 end function init() local upperB = {0, 0} local lowerB = {-20,-20} x = getInputArray() x[1] = 0.1 x[2] = 4 setNumberVars(2) setUpperBound(upperB) setLowerBound(lowerB) setf(getf(x[1], x[2])) setGrad(getgrad(x[1], x[2])) startLBFGSB() end function pulse() setf(getf(x[1], x[2])) setGrad(getgrad(x[1], x[2])) return pulseLBFGSB() end function main() init() count = 0 print("count = " .. count) while pulse() == false do print("final x vals = " .. x[1] .. " " .. x[2]) print("the count is " .. count) count = count + 1 end end main()
bsd-3-clause
kitool/gamecode4
Extra/UtilityDemo/utility.lua
44
7963
-- Utility.lua -- A simple utility game -- A "better" random seed. This was taken from http://lua-users.org/wiki/MathLibraryTutorial math.randomseed(tonumber(tostring(os.time()):reverse():sub(1,6))) ----------------------------------------------------------------------------------------------------------------------- -- Actor ----------------------------------------------------------------------------------------------------------------------- Actor = class(nil, { _name = "<unnamed>", _hp = 100, _mp = 3, _minDamage = nil, -- must be overridden _maxDamage = nil, -- must be overridden _minHeal = 20, _maxHeal = 45, }); function Actor:DoAction(action, opponent) if (action == "attack") then local dead = self:_Attack(opponent); return dead; elseif (action == "run") then local success = self:_Run(); return success; elseif (action == "heal") then self:_Heal(); return false; else print("Unknown action: " .. action); return false; end end function Actor:PrintStatus() print(self._name .. "; hp = " .. self._hp .. "; mp = " .. self._mp); end function Actor:Hit(damage) self._hp = self._hp - damage; if (self._hp < 0) then print(self._name .. " is dead!"); return true; end return false; end function Actor:GetHp() return self._hp; end function Actor:GetMp() return self._mp; end function Actor:GetMinDamage() return self._minDamage; end function Actor:GetMaxDamage() return self._maxDamage; end function Actor:GetMinHeal() return self._minHeal; end function Actor:GetMaxHeal() return self._maxHeal; end function Actor:_Attack(opponent) assert(self._minDamage ~= nil and self._maxDamage ~= nil); local damage = math.random(self._minDamage, self._maxDamage); print(self._name .. " struck for " .. damage .. " damage"); return opponent:Hit(damage); end function Actor:_Run() if (math.random() > 0.5) then print(self._name .. " ran away!"); return true; else print(self._name .. " failed to run away!"); return false; end end function Actor:_Heal() if (self._mp > 0) then local healAmount = math.random(self._minHeal, self._maxHeal); print(self._name .. " healed " .. healAmount .. " hp."); self._hp = self._hp + healAmount; self._mp = self._mp - 1; else print(self._name .. " attempted to heal but had no MP left"); end end ----------------------------------------------------------------------------------------------------------------------- -- Teapot ----------------------------------------------------------------------------------------------------------------------- Teapot = class(Actor, { _name = "Teapot", _minDamage = 10, _maxDamage = 20, _mp = 5, -- teapots are more magical _actions = { "attack", "heal", "run" }; }); function Teapot:Decide(opponent) local bestUtility = 0; local bestAction = nil; for i, action in ipairs(self._actions) do -- build the world state local tempWorldState = WorldState:Create(); tempWorldState:Build(self, opponent); -- apply the action tempWorldState:ApplyAction(action, self, opponent); -- grab the utility local utility = tempWorldState:GetUtility(); if (utility > bestUtility) then bestUtility = utility; bestAction = action; end print("\tScoring action '" .. action .. "': utility = " .. utility); end print("\tChose " .. bestAction); return bestAction; end -- This is the world state object used by the teapot WorldState = class(nil, { opponentHp = nil, opponentMp = nil, survivalChance = nil, -- the chance that we won't die next attack, from 0 - 1 }); function WorldState:Build(teapot, opponent) self.opponentHp = opponent:GetHp(); self.opponentMp = opponent:GetMp(); self.survivalChance = self:_CalculateSurvivalChance(teapot:GetHp(), opponent); self.killChance = 1 - self:_CalculateSurvivalChance(opponent:GetHp(), teapot); end function WorldState:ApplyAction(action, teapot, opponent) if (action == "attack") then local averageDamage = ((teapot:GetMaxDamage() - teapot:GetMinDamage()) / 2) + teapot:GetMinDamage(); self.opponentHp = self.opponentHp - averageDamage; self.killChance = 1 - self:_CalculateSurvivalChance(self.opponentHp, teapot); elseif (action == "run") then self.survivalChance = 0.5; elseif (action == "heal") then if (teapot:GetMp() > 0) then local averageHeal = ((teapot:GetMaxHeal() - teapot:GetMinHeal()) / 2) + teapot:GetMinHeal(); local newHp = teapot:GetHp() + averageHeal; self.survivalChance = self:_CalculateSurvivalChance(newHp, opponent); end else print("Unknown action: " .. action); return false; end end function WorldState:GetUtility() local lifeScore = 100 * self.survivalChance; -- a state in which we're alive grants 100 points, modified by the chance that we might survive local attackScore = 100 - self.opponentHp; -- a state in which the opponent is hurt is always good; teapot will get more aggressive as player is hurt attackScore = attackScore + (attackScore * self.killChance); -- adjust the attack score by up to double if the opponent is within a turn of death return lifeScore + attackScore; end function WorldState:_CalculateSurvivalChance(defenderHp, attacker) if (defenderHp > attacker:GetMaxDamage()) then return 1; elseif (defenderHp <= attacker:GetMinDamage()) then return 0; else local range = attacker:GetMaxDamage() - attacker:GetMinDamage(); local percentage = (defenderHp - attacker:GetMinDamage()) / range; return percentage; end end ----------------------------------------------------------------------------------------------------------------------- -- Player ----------------------------------------------------------------------------------------------------------------------- Player = class(Actor, { _name = "Player", _minDamage = 15, _maxDamage = 30, }); ----------------------------------------------------------------------------------------------------------------------- -- Game class ----------------------------------------------------------------------------------------------------------------------- Game = class(nil, { _player = nil, _teapot = nil, }); function Game:Start() self._player = Player:Create(); self._teapot = Teapot:Create(); print("A Teapot draws near! Command?"); print("1) Attack"); print("2) Run"); print("3) Heal"); print("4) Status"); print("Q to quit"); end function Game:Update(action) -- player runs action local gameOver = self._player:DoAction(action, self._teapot); -- check for game end if (gameOver) then self:_Reset(); return; end -- teapot action action = self._teapot:Decide(self._player); gameOver = self._teapot:DoAction(action, self._player); -- check for game end if (gameOver) then self:_Reset(); return; end self:ShowStatus(); end function Game:ShowStatus() self._player:PrintStatus(); self._teapot:PrintStatus(); end function Game:_Reset() print("Game over!\n\n"); self:Start(); end ----------------------------------------------------------------------------------------------------------------------- -- Global game object ----------------------------------------------------------------------------------------------------------------------- g_game = Game:Create(); g_game:Start(); ----------------------------------------------------------------------------------------------------------------------- -- Player commands ----------------------------------------------------------------------------------------------------------------------- function Attack() g_game:Update("attack"); end function Run() g_game:Update("run"); end function Heal() g_game:Update("heal"); end function Status() g_game:ShowStatus(); end
lgpl-3.0
luiseduardohdbackup/WarriorQuest
WarriorQuest/runtime/mac/PrebuiltRuntimeLua.app/Contents/Resources/ltn12.lua
71
8331
----------------------------------------------------------------------------- -- LTN12 - Filters, sources, sinks and pumps. -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local table = require("table") local base = _G local _M = {} if module then -- heuristic for exporting a global package table ltn12 = _M end local filter,source,sink,pump = {},{},{},{} _M.filter = filter _M.source = source _M.sink = sink _M.pump = pump -- 2048 seems to be better in windows... _M.BLOCKSIZE = 2048 _M._VERSION = "LTN12 1.0.3" ----------------------------------------------------------------------------- -- Filter stuff ----------------------------------------------------------------------------- -- returns a high level filter that cycles a low-level filter function filter.cycle(low, ctx, extra) base.assert(low) return function(chunk) local ret ret, ctx = low(ctx, chunk, extra) return ret end end -- chains a bunch of filters together -- (thanks to Wim Couwenberg) function filter.chain(...) local arg = {...} local n = select('#',...) local top, index = 1, 1 local retry = "" return function(chunk) retry = chunk and retry while true do if index == top then chunk = arg[index](chunk) if chunk == "" or top == n then return chunk elseif chunk then index = index + 1 else top = top+1 index = top end else chunk = arg[index](chunk or "") if chunk == "" then index = index - 1 chunk = retry elseif chunk then if index == n then return chunk else index = index + 1 end else base.error("filter returned inappropriate nil") end end end end end ----------------------------------------------------------------------------- -- Source stuff ----------------------------------------------------------------------------- -- create an empty source local function empty() return nil end function source.empty() return empty end -- returns a source that just outputs an error function source.error(err) return function() return nil, err end end -- creates a file source function source.file(handle, io_err) if handle then return function() local chunk = handle:read(_M.BLOCKSIZE) if not chunk then handle:close() end return chunk end else return source.error(io_err or "unable to open file") end end -- turns a fancy source into a simple source function source.simplify(src) base.assert(src) return function() local chunk, err_or_new = src() src = err_or_new or src if not chunk then return nil, err_or_new else return chunk end end end -- creates string source function source.string(s) if s then local i = 1 return function() local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1) i = i + _M.BLOCKSIZE if chunk ~= "" then return chunk else return nil end end else return source.empty() end end -- creates rewindable source function source.rewind(src) base.assert(src) local t = {} return function(chunk) if not chunk then chunk = table.remove(t) if not chunk then return src() else return chunk end else table.insert(t, chunk) end end end function source.chain(src, f) base.assert(src and f) local last_in, last_out = "", "" local state = "feeding" local err return function() if not last_out then base.error('source is empty!', 2) end while true do if state == "feeding" then last_in, err = src() if err then return nil, err end last_out = f(last_in) if not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end elseif last_out ~= "" then state = "eating" if last_in then last_in = "" end return last_out end else last_out = f(last_in) if last_out == "" then if last_in == "" then state = "feeding" else base.error('filter returned ""') end elseif not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end else return last_out end end end end end -- creates a source that produces contents of several sources, one after the -- other, as if they were concatenated -- (thanks to Wim Couwenberg) function source.cat(...) local arg = {...} local src = table.remove(arg, 1) return function() while src do local chunk, err = src() if chunk then return chunk end if err then return nil, err end src = table.remove(arg, 1) end end end ----------------------------------------------------------------------------- -- Sink stuff ----------------------------------------------------------------------------- -- creates a sink that stores into a table function sink.table(t) t = t or {} local f = function(chunk, err) if chunk then table.insert(t, chunk) end return 1 end return f, t end -- turns a fancy sink into a simple sink function sink.simplify(snk) base.assert(snk) return function(chunk, err) local ret, err_or_new = snk(chunk, err) if not ret then return nil, err_or_new end snk = err_or_new or snk return 1 end end -- creates a file sink function sink.file(handle, io_err) if handle then return function(chunk, err) if not chunk then handle:close() return 1 else return handle:write(chunk) end end else return sink.error(io_err or "unable to open file") end end -- creates a sink that discards data local function null() return 1 end function sink.null() return null end -- creates a sink that just returns an error function sink.error(err) return function() return nil, err end end -- chains a sink with a filter function sink.chain(f, snk) base.assert(f and snk) return function(chunk, err) if chunk ~= "" then local filtered = f(chunk) local done = chunk and "" while true do local ret, snkerr = snk(filtered, err) if not ret then return nil, snkerr end if filtered == done then return 1 end filtered = f(done) end else return 1 end end end ----------------------------------------------------------------------------- -- Pump stuff ----------------------------------------------------------------------------- -- pumps one chunk from the source to the sink function pump.step(src, snk) local chunk, src_err = src() local ret, snk_err = snk(chunk, src_err) if chunk and ret then return 1 else return nil, src_err or snk_err end end -- pumps all data from a source to a sink, using a step function function pump.all(src, snk, step) base.assert(src and snk) step = step or pump.step while true do local ret, err = step(src, snk) if not ret then if err then return nil, err else return 1 end end end end return _M
mit
LaFamiglia/Illarion-Content
monster/race_78_golden_skeleton/id_783_magus.lua
1
1470
--[[ Illarion Server 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 (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 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/>. ]] --ID 783, Golden Magus, Level: 5, Armourtype: light, Weapontype: concussion local goldenSkeletons = require("monster.race_78_golden_skeleton.base") local mageBehaviour = require("monster.base.behaviour.mage") local monstermagic = require("monster.base.monstermagic") local magic = monstermagic() magic.addWarping{probability = 0.15, usage = magic.ONLY_NEAR_ENEMY} magic.addIceball{probability = 0.05, damage = {from = 1000, to = 2000} } magic.addVioletFlame{probability = 0.03, damage = {from = 500, to = 1000}, targetCount = 3} magic.addHealing{probability = 0.05, damage = {from = 1000, to = 2000}} magic.addHealing{probability = 0.05, damage = {from = 500, to = 1000}, targetCount = 3} local M = goldenSkeletons.generateCallbacks() M = magic.addCallbacks(M) return mageBehaviour.addCallbacks(magic, M)
agpl-3.0
skatsuta/aerospike-training
book/answers/RecordUDF/Go/udf/example.lua
9
1433
function example_function(rec, userid, profile) local ret = map() -- Initialize the return value (a map) if not aerospike:exists(rec) then -- Check to see that the record exists ret['status'] = 'DOES NOT EXIST' -- Set the return status else local x = rec['bin1'] -- Get the value from record bin named "bin1" rec['bin2'] = (x / 2) -- Set the value in record bin named "bin2" if x < 0 then aerospike:remove(rec) -- Delete the entire record ret['status'] = 'DELETE' -- Populate the return status elseif x > 100 then rec['bin3'] = nil -- Delete record bin named "bin3" ret['status'] = 'VALUE TOO HIGH' -- Populate the return status else local myuserid = userid -- Get the UDF argument "userid" local myprofile = profile -- Get the UDF argument "profile" ret['status'] = 'OK' -- Populate the return status ret['userdata'] = map{ -- Populate return value map myuserid = userid, otheruserid = rec['userid'], match_score = getMatchScore(myprofile, rec['profile']) } end aerospike:update(rec) -- Update the main record end return ret -- Return the Return value and/or status end
mit
noahdesu/legion
bindings/lua/examples/circuit/circuit.lua
2
1356
-- Copyright 2015 Stanford University -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. require('legionlib') require('circuit_tasks') require('circuit_defs') binding = LegionLib:init_binding("circuit_tasks.lua") binding:set_top_level_task_id(CIRCUIT_MAIN) binding:register_single_task(CIRCUIT_MAIN, "circuit_main", Processor.LOC_PROC, false) binding:register_index_task(CALC_NEW_CURRENTS, "calculate_currents_task", Processor.LOC_PROC, true) binding:register_index_task(DISTRIBUTE_CHARGE, "distribute_charge_task", Processor.LOC_PROC, true) binding:register_index_task(UPDATE_VOLTAGES, "update_voltages_task", Processor.LOC_PROC, true) binding:register_reduction_op(REDUCE_ID, ReductionType.PLUS, PrimType.float) binding:start(arg)
apache-2.0
SirSepehr/Sepehr
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 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, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
MustaphaTR/OpenRA
mods/ra/maps/fall-of-greece-2-evacuation/evacuation-AI.lua
7
3468
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] AttackGroup = { } SovietInfantry = { "e1", "e2" } SovietVehicles = { "3tnk", "3tnk", "v2rl" } SovietAircraftType = { "yak" } Yaks = { } AttackPaths = { AttackRight, AttackLeft } AttackGroupSizes = { easy = 8, normal = 9, hard = 10 } ProductionInterval = { easy = DateTime.Seconds(20), normal = DateTime.Seconds(10), hard = DateTime.Seconds(5) } SendAttackGroup = function() if #AttackGroup < AttackGroupSize then return end local path = Utils.Random(AttackPaths) Utils.Do(AttackGroup, function(unit) if not unit.IsDead then unit.AttackMove(path.Location) Trigger.OnIdle(unit, unit.Hunt) end end) AttackGroup = { } end ProduceInfantry = function() if USSRRax.IsDead or USSRRax.Owner ~= USSR then return end USSR.Build({ Utils.Random(SovietInfantry) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceInfantry) end) end ProduceVehicles = function() if USSRWarFactory.IsDead or USSRWarFactory.Owner ~= USSR then return end USSR.Build({ Utils.Random(SovietVehicles) }, function(units) table.insert(AttackGroup, units[1]) SendAttackGroup() Trigger.AfterDelay(ProductionInterval[Difficulty], ProduceVehicles) end) end ProduceAircraft = function() if Airfield.IsDead or Airfield.Owner ~= USSR then return end USSR.Build(SovietAircraftType, function(units) local yak = units[1] Yaks[#Yaks + 1] = yak Trigger.OnKilled(yak, ProduceAircraft) local alive = Utils.Where(Yaks, function(y) return not y.IsDead end) if #alive < 2 then Trigger.AfterDelay(DateTime.Seconds(ProductionInterval[Difficulty] / 2), ProduceAircraft) end InitializeAttackAircraft(yak, Allies) end) end ParadropDelays = { easy = { DateTime.Minutes(1), DateTime.Minutes(2) }, normal = { DateTime.Seconds(45), DateTime.Seconds(105) }, hard = { DateTime.Seconds(30), DateTime.Seconds(90) } } ParadropLZs = { ParaLZ1.CenterPosition, ParaLZ2.CenterPosition, ParaLZ3.CenterPosition, ParaLZ4.CenterPosition } Paradrop = function() if Airfield.IsDead or Airfield.Owner ~= USSR then return end local aircraft = StandardDrop.TargetParatroopers(Utils.Random(ParadropLZs)) Utils.Do(aircraft, function(a) Trigger.OnPassengerExited(a, function(t, p) IdleHunt(p) end) end) Trigger.AfterDelay(Utils.RandomInteger(ParadropDelay[1], ParadropDelay[2]), Paradrop) end ActivateAI = function() local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == USSR and self.HasProperty("StartBuildingRepairs") end) Utils.Do(buildings, function(actor) Trigger.OnDamaged(actor, function(building) if building.Owner == USSR and building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) end) ParadropDelay = ParadropDelays[Difficulty] AttackGroupSize = AttackGroupSizes[Difficulty] Trigger.AfterDelay(DateTime.Seconds(30), ProduceInfantry) Trigger.AfterDelay(DateTime.Minutes(3), ProduceVehicles) Trigger.AfterDelay(DateTime.Minutes(4), Paradrop) Trigger.AfterDelay(DateTime.Minutes(5), ProduceAircraft) end
gpl-3.0
Godfather021/yag
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
mamadtnt/ya
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
snabbnfv-goodies/snabbswitch
lib/ljsyscall/syscall/openbsd/types.lua
24
9707
-- OpenBSD types local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local function init(types) local abi = require "syscall.abi" local t, pt, s, ctypes = types.t, types.pt, types.s, types.ctypes local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local addtype, addtype_var, addtype_fn, addraw2 = h.addtype, h.addtype_var, h.addtype_fn, h.addraw2 local ptt, reviter, mktype, istype, lenfn, lenmt, getfd, newfn = h.ptt, h.reviter, h.mktype, h.istype, h.lenfn, h.lenmt, h.getfd, h.newfn local ntohl, ntohl, ntohs, htons, octal = h.ntohl, h.ntohl, h.ntohs, h.htons, h.octal local c = require "syscall.openbsd.constants" local mt = {} -- metatables local addtypes = { } local addstructs = { } for k, v in pairs(addtypes) do addtype(types, k, v) end for k, v in pairs(addstructs) do addtype(types, k, v, lenmt) end -- 32 bit dev_t, 24 bit minor, 8 bit major, but minor is a cookie and neither really used just legacy local function makedev(major, minor) if type(major) == "table" then major, minor = major[1], major[2] end local dev = major or 0 if minor then dev = bit.bor(minor, bit.lshift(major, 8)) end return dev end mt.device = { index = { major = function(dev) return bit.bor(bit.band(bit.rshift(dev.dev, 8), 0xff)) end, minor = function(dev) return bit.band(dev.dev, 0xffff00ff) end, device = function(dev) return tonumber(dev.dev) end, }, newindex = { device = function(dev, major, minor) dev.dev = makedev(major, minor) end, }, __new = function(tp, major, minor) return ffi.new(tp, makedev(major, minor)) end, } addtype(types, "device", "struct {dev_t dev;}", mt.device) mt.stat = { index = { dev = function(st) return t.device(st.st_dev) end, mode = function(st) return st.st_mode end, ino = function(st) return tonumber(st.st_ino) end, nlink = function(st) return st.st_nlink end, uid = function(st) return st.st_uid end, gid = function(st) return st.st_gid end, rdev = function(st) return t.device(st.st_rdev) end, atime = function(st) return st.st_atim.time end, ctime = function(st) return st.st_ctim.time end, mtime = function(st) return st.st_mtim.time end, birthtime = function(st) return st.st_birthtim.time end, size = function(st) return tonumber(st.st_size) end, blocks = function(st) return tonumber(st.st_blocks) end, blksize = function(st) return tonumber(st.st_blksize) end, flags = function(st) return st.st_flags end, gen = function(st) return st.st_gen end, type = function(st) return bit.band(st.st_mode, c.S_I.FMT) end, todt = function(st) return bit.rshift(st.type, 12) end, isreg = function(st) return st.type == c.S_I.FREG end, isdir = function(st) return st.type == c.S_I.FDIR end, ischr = function(st) return st.type == c.S_I.FCHR end, isblk = function(st) return st.type == c.S_I.FBLK end, isfifo = function(st) return st.type == c.S_I.FIFO end, islnk = function(st) return st.type == c.S_I.FLNK end, issock = function(st) return st.type == c.S_I.FSOCK end, iswht = function(st) return st.type == c.S_I.FWHT end, }, } -- add some friendlier names to stat, also for luafilesystem compatibility mt.stat.index.access = mt.stat.index.atime mt.stat.index.modification = mt.stat.index.mtime mt.stat.index.change = mt.stat.index.ctime local namemap = { file = mt.stat.index.isreg, directory = mt.stat.index.isdir, link = mt.stat.index.islnk, socket = mt.stat.index.issock, ["char device"] = mt.stat.index.ischr, ["block device"] = mt.stat.index.isblk, ["named pipe"] = mt.stat.index.isfifo, } mt.stat.index.typename = function(st) for k, v in pairs(namemap) do if v(st) then return k end end return "other" end addtype(types, "stat", "struct stat", mt.stat) mt.flock = { index = { type = function(self) return self.l_type end, whence = function(self) return self.l_whence end, start = function(self) return self.l_start end, len = function(self) return self.l_len end, pid = function(self) return self.l_pid end, sysid = function(self) return self.l_sysid end, }, newindex = { type = function(self, v) self.l_type = c.FCNTL_LOCK[v] end, whence = function(self, v) self.l_whence = c.SEEK[v] end, start = function(self, v) self.l_start = v end, len = function(self, v) self.l_len = v end, pid = function(self, v) self.l_pid = v end, sysid = function(self, v) self.l_sysid = v end, }, __new = newfn, } addtype(types, "flock", "struct flock", mt.flock) mt.dirent = { index = { fileno = function(self) return tonumber(self.d_fileno) end, reclen = function(self) return self.d_reclen end, namlen = function(self) return self.d_namlen end, type = function(self) return self.d_type end, name = function(self) return ffi.string(self.d_name, self.d_namlen) end, toif = function(self) return bit.lshift(self.d_type, 12) end, -- convert to stat types }, __len = function(self) return self.d_reclen end, } mt.dirent.index.ino = mt.dirent.index.fileno -- alternate name -- TODO previously this allowed lower case values, but this static version does not -- could add mt.dirent.index[tolower(k)] = mt.dirent.index[k] but need to do consistently elsewhere for k, v in pairs(c.DT) do mt.dirent.index[k] = function(self) return self.type == v end end addtype(types, "dirent", "struct dirent", mt.dirent) mt.fdset = { index = { fds_bits = function(self) return self.__fds_bits end, }, } addtype(types, "fdset", "fd_set", mt.fdset) -- TODO see Linux notes. Also maybe can be shared with BSDs, have not checked properly -- TODO also remove WIF prefixes. mt.wait = { __index = function(w, k) local _WSTATUS = bit.band(w.status, octal("0177")) local _WSTOPPED = octal("0177") local WTERMSIG = _WSTATUS local EXITSTATUS = bit.band(bit.rshift(w.status, 8), 0xff) local WIFEXITED = (_WSTATUS == 0) local tab = { WIFEXITED = WIFEXITED, WIFSTOPPED = bit.band(w.status, 0xff) == _WSTOPPED, WIFSIGNALED = _WSTATUS ~= _WSTOPPED and _WSTATUS ~= 0 } if tab.WIFEXITED then tab.EXITSTATUS = EXITSTATUS end if tab.WIFSTOPPED then tab.WSTOPSIG = EXITSTATUS end if tab.WIFSIGNALED then tab.WTERMSIG = WTERMSIG end if tab[k] then return tab[k] end local uc = 'W' .. k:upper() if tab[uc] then return tab[uc] end end } function t.waitstatus(status) return setmetatable({status = status}, mt.wait) end local signames = {} for k, v in pairs(c.SIG) do signames[v] = k end mt.siginfo = { index = { signo = function(s) return s.si_signo end, errno = function(s) return s.si_errno end, code = function(s) return s.si_code end, pid = function(s) return s.si_pid end, uid = function(s) return s.si_uid end, status = function(s) return s.si_status end, addr = function(s) return s.si_addr end, value = function(s) return s.si_value end, trapno = function(s) return s._fault._trapno end, timerid = function(s) return s._timer._timerid end, overrun = function(s) return s._timer._overrun end, mqd = function(s) return s._mesgq._mqd end, band = function(s) return s._poll._band end, signame = function(s) return signames[s.signo] end, }, newindex = { signo = function(s, v) s.si_signo = v end, errno = function(s, v) s.si_errno = v end, code = function(s, v) s.si_code = v end, pid = function(s, v) s.si_pid = v end, uid = function(s, v) s.si_uid = v end, status = function(s, v) s.si_status = v end, addr = function(s, v) s.si_addr = v end, value = function(s, v) s.si_value = v end, trapno = function(s, v) s._fault._trapno = v end, timerid = function(s, v) s._timer._timerid = v end, overrun = function(s, v) s._timer._overrun = v end, mqd = function(s, v) s._mesgq._mqd = v end, band = function(s, v) s._poll._band = v end, }, __len = lenfn, } addtype(types, "siginfo", "siginfo_t", mt.siginfo) -- sigaction, standard POSIX behaviour with union of handler and sigaction addtype_fn(types, "sa_sigaction", "void (*)(int, siginfo_t *, void *)") mt.sigaction = { index = { handler = function(sa) return sa.__sigaction_u.__sa_handler end, sigaction = function(sa) return sa.__sigaction_u.__sa_sigaction end, mask = function(sa) return sa.sa_mask end, flags = function(sa) return tonumber(sa.sa_flags) end, }, newindex = { handler = function(sa, v) if type(v) == "string" then v = pt.void(c.SIGACT[v]) end if type(v) == "number" then v = pt.void(v) end sa.__sigaction_u.__sa_handler = v end, sigaction = function(sa, v) if type(v) == "string" then v = pt.void(c.SIGACT[v]) end if type(v) == "number" then v = pt.void(v) end sa.__sigaction_u.__sa_sigaction = v end, mask = function(sa, v) if not ffi.istype(t.sigset, v) then v = t.sigset(v) end sa.sa_mask = v end, flags = function(sa, v) sa.sa_flags = c.SA[v] end, }, __new = function(tp, tab) local sa = ffi.new(tp) if tab then for k, v in pairs(tab) do sa[k] = v end end if tab and tab.sigaction then sa.sa_flags = bit.bor(sa.flags, c.SA.SIGINFO) end -- this flag must be set if sigaction set return sa end, } addtype(types, "sigaction", "struct sigaction", mt.sigaction) return types end return {init = init}
apache-2.0
hnyman/luci
applications/luci-app-unbound/luasrc/model/cbi/unbound/zone-details.lua
3
3473
-- Copyright 2018 Eric Luehrsen <ericluehrsen@gmail.com> -- Licensed to the public under the Apache License 2.0. local sy = require "luci.sys" local ds = require "luci.dispatcher" local hp = require "luci.http" local m7, s7 local ena, flb, zty, znm, srv, rlv, tlu local prt, tlp, tli, url arg[1] = arg[1] or "" m7 = Map("unbound") m7.redirect = ds.build_url("admin/services/unbound/zones") if (arg[1] == "") then hp.redirect(m7.redirect) return else s7 = m7:section(NamedSection, arg[1], "zone", translatef("Directed Zone"), translatef("Edit a forward, stub, or zone-file-cache zone " .. "for Unbound to use instead of recursion.")) s7.anonymous = true s7.addremove = false ena = s7:option(Flag, "enabled", translate("Enabled"), translate("Enable this directed zone")) ena.rmempty = false flb = s7:option(Flag, "fallback", translate("Fall Back"), translate("Allow open recursion when record not in zone")) flb.rmempty = false zty = s7:option(ListValue, "zone_type", translate("Zone Type")) zty:value("auth_zone", translate("Authoritative (zone file)")) zty:value("stub_zone", translate("Stub (forced recursion)")) zty:value("forward_zone", translate("Forward (simple handoff)")) zty.rmempty = false znm = s7:option(DynamicList, "zone_name", translate("Zone Names"), translate("Zone (Domain) names included in this zone combination")) znm.placeholder="new.example.net." srv = s7:option(DynamicList, "server", translate("Servers"), translate("Servers for this zone; see README.md for optional form")) srv.placeholder="192.0.2.53" ast = s7:option(ListValue, "dns_assist", translate("DNS Plugin"), translate("Check for local program to allow forward to localhost")) ast:value("none", translate("(none)")) ast:value("bind", "bind") ast:value("dnsmasq", "dnsmasq") ast:value("ipset-dns", "ipset-dns") ast:value("nsd", "nsd") rlv = s7:option(Flag, "resolv_conf", translate("Use 'resolv.conf.auto'"), translate("Forward to upstream nameservers (ISP)")) rlv:depends("zone_type", "forward_zone") tlu = s7:option(Flag, "tls_upstream", translate("DNS over TLS"), translate("Connect to servers using TLS")) tlu:depends("zone_type", "forward_zone") prt = s7:option(Value, "port", translate("Server Port"), translate("Port servers will receive queries on")) prt:depends("tls_upstream", false) prt.datatype = "port" prt.placeholder="53" tlp = s7:option(Value, "tls_port", translate("Server TLS Port"), translate("Port servers will receive queries on")) tlp:depends("tls_upstream", true) tlp.datatype = "port" tlp.placeholder="853" tli = s7:option(Value, "tls_index", translate("TLS Name Index"), translate("Domain name to verify TLS certificate")) tli:depends("tls_upstream", true) tli.placeholder="dns.example.net" url = s7:option(Value, "url_dir", translate("Zone Download URL"), translate("Directory only part of URL")) url:depends("zone_type", "auth_zone") url.placeholder="https://www.example.net/dl/zones/" end function m7.on_commit(self) if sy.init.enabled("unbound") then -- Restart Unbound with configuration sy.call("/etc/init.d/unbound restart >/dev/null 2>&1") else sy.call("/etc/init.d/unbound stop >/dev/null 2>&1") end end return m7
apache-2.0
MustaphaTR/OpenRA
mods/ra/maps/ant-01/ant-attack.lua
7
2347
--[[ Copyright 2007-2022 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. For more information, see COPYING. ]] timeTracker = 0 amount = 1 SendAnts = true AttackAngles = { { waypoint4.Location, waypoint18.Location, waypoint5.Location, waypoint15.Location }, { waypoint20.Location, waypoint2.Location }, { waypoint21.Location, waypoint10.Location, waypoint2.Location }, { waypoint7.Location, waypoint17.Location, waypoint1.Location }, { waypoint8.Location, waypoint9.Location, waypoint19.Location } } AttackInterval = { easy = DateTime.Seconds(40), normal = DateTime.Seconds(30), hard = DateTime.Seconds(25) } AntTypes = { "scoutant", "fireant" } MaxAnts = { easy = 3, normal = 5, hard = 6 } MaxFireAnts = { easy = 2, normal = 3, hard = 4 } StartAntAttack = function() local path = Utils.Random(AttackAngles) local antType = "scoutant" local index = 0 local amount = 1 local timeTracker = GetTicks() if timeTracker > DateTime.Minutes(6) then antType = Utils.Random(AntTypes) end if antType == "warriorant" and Difficulty == "easy" then antType = "scoutant" end if Difficulty == "normal" and timeTracker < DateTime.Minutes(6) and antType == "scoutant" then antType = "warriorant" elseif Difficulty == "hard" and timeTracker < DateTime.Minutes(8) and antType == "scoutant" then antType = "warriorant" end local max = MaxAnts[Difficulty] - math.ceil(timeTracker / DateTime.Minutes(6)) if timeTracker > DateTime.Minutes(3) and antType == "fireant" then amount = Utils.RandomInteger(1, MaxFireAnts[Difficulty]) elseif timeTracker > 15 and antType == "fireant" then antType = "scoutant" else amount = Utils.RandomInteger(1, max) end for i = 0,amount,1 do Reinforcements.Reinforce(AntMan, { antType }, path, DateTime.Seconds(5), function(actor) actor.AttackMove(CPos.New(65, 65)) Trigger.OnIdle(actor, function() actor.Hunt() end) end) end -- Setup next wave if SendAnts then Trigger.AfterDelay(AttackInterval[Difficulty], function() StartAntAttack() end) end end EndAntAttack = function() SendAnts = false end
gpl-3.0
Hzj-jie/koreader-base
spec/unit/zeromq_spec.lua
4
2306
local ffi = require("ffi") local zyre = ffi.load("libs/libzyre.so.1") local filemq = ffi.load("libs/libfmq.so.1") ffi.cdef[[ int zre_msg_test(bool verbose); void zyre_peer_test(bool verbose); void zyre_group_test(bool verbose); void zyre_node_test(bool verbose); void zyre_event_test(bool verbose); void zyre_test(bool verbose); int fmq_msg_test(bool verbose); int fmq_server_test(bool verbose); int fmq_client_test(bool verbose); ]] describe("Zyre module #notest", function() it("should pass self test", function() local verbose = true zyre.zre_msg_test(verbose) zyre.zyre_peer_test(verbose) zyre.zyre_group_test(verbose) zyre.zyre_node_test(verbose) zyre.zyre_event_test(verbose) zyre.zyre_test(verbose) end) end) local anonymous_cfg = [[ # Configure server to allow anonymous access # security echo = I: server accepts anonymous access anonymous = 1 ]] local server_test_cfg = [[ # Configure server for plain access # server monitor = 1 # Check mount points heartbeat = 1 # Heartbeat to clients # publish # location = physicalpath # virtual = virtualpath # publish # location = physicalpath # virtual = virtualpath security echo = I: use guest/guest to login to server # These are SASL mechanisms we accept anonymous = 0 plain = 1 account login = guest password = guest group = guest account login = super password = secret group = admin ]] local client_test_cfg = [[ # Configure server for plain access # client heartbeat = 1 # Interval in seconds inbox = ./fmqroot/recv resync = 1 # inbox # path = ./some/directory # subscribe # path = /logs security plain login = guest password = guest ]] describe("FileMQ module #notest", function() io.open("anonymous.cfg", "w"):write(anonymous_cfg) io.open("server_test.cfg", "w"):write(server_test_cfg) io.open("client_test.cfg", "w"):write(client_test_cfg) it("should pass self test", function() local verbose = true filemq.fmq_msg_test(verbose) filemq.fmq_server_test(verbose) filemq.fmq_client_test(verbose) end) end)
agpl-3.0
soundsrc/premake-core
modules/gmake2/tests/test_gmake2_pch.lua
11
4768
-- -- test_gmake2_pch.lua -- Validate the setup for precompiled headers in makefiles. -- (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local p = premake local suite = test.declare("gmake2_pch") local p = premake local gmake2 = p.modules.gmake2 local project = p.project -- -- Setup and teardown -- local wks, prj function suite.setup() os.chdir(_TESTS_DIR) gmake2.cpp.initialize() wks, prj = test.createWorkspace() end local function prepareVars() local cfg = test.getconfig(prj, "Debug") gmake2.cpp.pch(cfg) end local function prepareRules() local cfg = test.getconfig(prj, "Debug") gmake2.cpp.pchRules(cfg.project) end local function prepareFlags() local project = test.getproject(wks, 1) gmake2.cpp.createRuleTable(project) gmake2.cpp.createFileTable(project) gmake2.cpp.outputFileRuleSection(project) end -- -- If no header has been set, nothing should be output. -- function suite.noConfig_onNoHeaderSet() prepareVars() test.isemptycapture() end -- -- If a header is set, but the NoPCH flag is also set, then -- nothing should be output. -- function suite.noConfig_onHeaderAndNoPCHFlag() pchheader "include/myproject.h" flags "NoPCH" files { 'a.cpp', 'b.cpp' } prepareFlags() test.capture [[ # File Rules # ############################################# $(OBJDIR)/a.o: a.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/b.o: b.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end -- -- If a header is specified and the NoPCH flag is not set, then -- the header can be used. -- function suite.config_onPchEnabled() pchheader "include/myproject.h" prepareVars() test.capture [[ PCH = include/myproject.h PCH_PLACEHOLDER = $(OBJDIR)/$(notdir $(PCH)) GCH = $(PCH_PLACEHOLDER).gch ]] end -- -- The PCH can be specified relative the an includes search path. -- function suite.pch_searchesIncludeDirs() pchheader "premake.h" includedirs { "../../../src/host" } prepareVars() test.capture [[ PCH = ../../../src/host/premake.h ]] end -- -- Verify the format of the PCH rules block for a C++ file. -- function suite.buildRules_onCpp() pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) $(OBJECTS): $(GCH) | $(PCH_PLACEHOLDER) $(GCH): $(PCH) | prebuild @echo $(notdir $<) $(SILENT) $(CXX) -x c++-header $(ALL_CXXFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" $(PCH_PLACEHOLDER): $(GCH) | $(OBJDIR) ifeq (posix,$(SHELLTYPE)) $(SILENT) touch "$@" else $(SILENT) echo $null >> "$@" endif else $(OBJECTS): | prebuild endif ]] end -- -- Verify the format of the PCH rules block for a C file. -- function suite.buildRules_onC() language "C" pchheader "include/myproject.h" prepareRules() test.capture [[ ifneq (,$(PCH)) $(OBJECTS): $(GCH) | $(PCH_PLACEHOLDER) $(GCH): $(PCH) | prebuild @echo $(notdir $<) $(SILENT) $(CC) -x c-header $(ALL_CFLAGS) -o "$@" -MF "$(@:%.gch=%.d)" -c "$<" $(PCH_PLACEHOLDER): $(GCH) | $(OBJDIR) ifeq (posix,$(SHELLTYPE)) $(SILENT) touch "$@" else $(SILENT) echo $null >> "$@" endif else $(OBJECTS): | prebuild endif ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.findsPCH_onIncludeDirs() location "MyProject" pchheader "premake.h" includedirs { "../../../src/host" } prepareVars() test.capture [[ PCH = ../../../../src/host/premake.h ]] end -- -- If the header is located on one of the include file -- search directories, it should get found automatically. -- function suite.PCHFlag() pchheader "include/myproject.h" files { 'a.cpp', 'b.cpp' } prepareFlags() test.capture [[ # File Rules # ############################################# $(OBJDIR)/a.o: a.cpp @echo $(notdir $<) $(SILENT) $(CXX) -include $(PCH_PLACEHOLDER) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/b.o: b.cpp @echo $(notdir $<) $(SILENT) $(CXX) -include $(PCH_PLACEHOLDER) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end function suite.PCHFlag_PerFile() pchheader "include/myproject.h" files { 'a.cpp', 'b.cpp' } filter { "files:a.cpp" } flags "NoPCH" prepareFlags() test.capture [[ # File Rules # ############################################# $(OBJDIR)/a.o: a.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/b.o: b.cpp @echo $(notdir $<) $(SILENT) $(CXX) -include $(PCH_PLACEHOLDER) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end
bsd-3-clause
BHYCHIK/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
eagle14/Snippy
plugins/stats.lua
24
3698
do local NUM_MSG_MAX = 1 local TIME_CHECK = 1 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..'👤|'..user_id..'|🗣' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = '' for k,user in pairs(users_info) do text = text..user.name..' => '..user.msgs..'\n-----------' end return text end -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood local kick = chat_del_user(chat_id , user_id, ok_cb, true) vardump(kick) if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false) print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
Noltari/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/df.lua
5
1637
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.df", package.seeall) function item() return luci.i18n.translate("Disk Space Usage") end function rrdargs( graph, plugin, plugin_instance, dtype ) local df_complex = { title = "%H: Disk space usage on %pi", vlabel = "Bytes", number_format = "%5.1lf%sB", data = { instances = { df_complex = { "free", "used", "reserved" } }, options = { df_complex_free = { color = "00ff00", overlay = false, title = "free" }, df_complex_used = { color = "ff0000", overlay = false, title = "used" }, df_complex_reserved = { color = "0000ff", overlay = false, title = "reserved" } } } } local percent_bytes = { title = "%H: Disk space usage on %pi", vlabel = "Percent", number_format = "%5.2lf %%", data = { instances = { percent_bytes = { "free", "used", "reserved" } }, options = { percent_bytes_free = { color = "00ff00", overlay = false, title = "free" }, percent_bytes_used = { color = "ff0000", overlay = false, title = "used" }, percent_bytes_reserved = { color = "0000ff", overlay = false, title = "reserved" } } } } local types = graph.tree:data_types( plugin, plugin_instance ) local p = {} for _, t in ipairs(types) do if t == "percent_bytes" then p[#p+1] = percent_bytes end if t == "df_complex" then p[#p+1] = df_complex end end return p end
apache-2.0
bsmr-games/lipsofsuna
data/system/billboard.lua
1
2397
--- Renderable billboard. -- -- Lips of Suna is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as -- published by the Free Software Foundation, either version 3 of the -- License, or (at your option) any later version. -- -- @module system.billboard -- @alias Billboard local Class = require("system/class") if not Los.program_load_extension("billboard") then error("loading extension `billboard' failed") end ------------------------------------------------------------------------------ --- Renderable billboard. -- @type Billboard local Billboard = Class("Billboard") --- Creates a new billboard set. -- @param clss Billboard class. -- @return Billboard. Billboard.new = function(clss, model) local self = Class.new(clss) self.handle = Los.billboard_new() return self end --- Adds a billboard to the billboard set. -- @param self Billboard. -- @param pos Position vector. Billboard.add = function(self, pos) Los.billboard_add(self.handle, pos.x, pos.y, pos.z) end --- Clears the billboard set. -- @param self Billboard. Billboard.clear = function(self) Los.billboard_clear(self.handle) end --- Sets the material of the billboard set. -- @param self Billboard. -- @param name Material name. Billboard.set_material = function(self, name) Los.billboard_set_material(self.handle, name) end --- Sets the position of the billboard set. -- @param self Billboard. -- @param v Vector. Billboard.set_position = function(self, v) Los.billboard_set_position(self.handle, v.x, v.y, v.z) end --- Sets the render queue of the billboard set. -- @param self Billboard. -- @param name Queue name. Billboard.set_render_queue = function(self, name) Los.billboard_set_render_queue(self.handle, name) end --- Sets the rotation of the billboard set. -- @param self Billboard. -- @param v Quaternion. Billboard.set_rotation = function(self, v) Los.billboard_set_rotation(self.handle, v.x, v.y, v.z, v.w) end --- Sets the size of the billboard set. -- @param self Billboard. -- @param w Width. -- @param h Height. Billboard.set_size = function(self, w, h) Los.billboard_set_size(self.handle, w, h) end --- Sets the size of the billboard set. -- @param self Billboard. -- @param v True to make visible. False otherwise. Billboard.set_visible = function(self, v) Los.billboard_set_visible(self.handle, v) end return Billboard
gpl-3.0
tinybearc/sdkbox-ga-sample
cpp/cocos2d/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua
146
1793
-------------------------------- -- @module plugin -------------------------------------------------------- -- the plugin PluginProtocol -- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module -------------------------------------------------------- -- the plugin PluginManager -- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module -------------------------------------------------------- -- the plugin ProtocolAnalytics -- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module -------------------------------------------------------- -- the plugin ProtocolIAP -- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module -------------------------------------------------------- -- the plugin ProtocolAds -- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module -------------------------------------------------------- -- the plugin ProtocolShare -- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module -------------------------------------------------------- -- the plugin ProtocolSocial -- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module -------------------------------------------------------- -- the plugin ProtocolUser -- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module -------------------------------------------------------- -- the plugin AgentManager -- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module -------------------------------------------------------- -- the plugin FacebookAgent -- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module return nil
mit