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
cenouro/dotfiles
lua/user/nvim-lspconfig.lua
1
2480
-- Mappings. -- See `:help vim.diagnostic.*` for documentation on any of the below functions local opts = { noremap = true, silent = true } vim.keymap.set('n', '<space>e', vim.diagnostic.open_float, opts) vim.keymap.set('n', '[d', vim.diagnostic.goto_prev, opts) vim.keymap.set('n', ']d', vim.diagnostic.goto_next, opts) vim.keymap.set('n', '<space>q', vim.diagnostic.setloclist, opts) -- Use an on_attach function to only map the following keys -- after the language server attaches to the current buffer local on_attach = function(client, bufnr) -- Mappings. -- See `:help vim.lsp.*` for documentation on any of the below functions local bufopts = { noremap = true, silent = true, buffer = bufnr } vim.keymap.set('n', 'gD', vim.lsp.buf.declaration, bufopts) vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts) vim.keymap.set('n', 'K', vim.lsp.buf.hover, bufopts) vim.keymap.set('n', 'gi', vim.lsp.buf.implementation, bufopts) vim.keymap.set('n', '<C-k>', vim.lsp.buf.signature_help, bufopts) vim.keymap.set('n', '<space>wa', vim.lsp.buf.add_workspace_folder, bufopts) vim.keymap.set('n', '<space>wr', vim.lsp.buf.remove_workspace_folder, bufopts) vim.keymap.set('n', '<space>wl', function() print(vim.inspect(vim.lsp.buf.list_workspace_folders())) end, bufopts) vim.keymap.set('n', '<space>D', vim.lsp.buf.type_definition, bufopts) vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, bufopts) vim.keymap.set('n', '<space>ca', vim.lsp.buf.code_action, bufopts) vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts) vim.keymap.set('n', '<space>f', vim.lsp.buf.formatting, bufopts) end local lsp_flags = { -- This is the default in Nvim 0.7+ debounce_text_changes = 150, } local capabilities = vim.lsp.protocol.make_client_capabilities() capabilities = require('cmp_nvim_lsp').update_capabilities(capabilities) require('lspconfig').sumneko_lua.setup({ on_attach = on_attach, capabilities = capabilities, lsp_flags = lsp_flags, settings = { Lua = { runtime = { version = 'LuaJIT' }, diagnostics = { globals = { 'vim' } }, workspace = { library = vim.api.nvim_get_runtime_file('', true) }, telemetry = { enable = false } } }}) require('lspconfig').sorbet.setup({ on_attach = on_attach, capabilities = capabilities, lsp_flags = lsp_flags, cmd = { 'bundle', 'exec', 'srb', 'tc', '--lsp', '--disable-watchman' } })
unlicense
anshkumar/yugioh-glaze
assets/script/c76214441.lua
3
1763
--ライフ・コーディネイター function c76214441.initial_effect(c) --Negate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(76214441,0)) e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_CHAINING) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e1:SetRange(LOCATION_HAND) e1:SetCondition(c76214441.discon) e1:SetCost(c76214441.discost) e1:SetTarget(c76214441.distg) e1:SetOperation(c76214441.disop) c:RegisterEffect(e1) end function c76214441.discon(e,tp,eg,ep,ev,re,r,rp) if ep==tp or (re:GetHandler():IsType(TYPE_SPELL+TYPE_TRAP) and not re:IsHasType(EFFECT_TYPE_ACTIVATE)) or not Duel.IsChainNegatable(ev) then return false end local ex,cg,ct,cp,cv=Duel.GetOperationInfo(ev,CATEGORY_DAMAGE) if ex then return true end ex,cg,ct,cp,cv=Duel.GetOperationInfo(ev,CATEGORY_RECOVER) return ex and ((cp~=PLAYER_ALL and Duel.IsPlayerAffectedByEffect(cp,EFFECT_REVERSE_RECOVER)) or (cp==PLAYER_ALL and (Duel.IsPlayerAffectedByEffect(0,EFFECT_REVERSE_RECOVER) or Duel.IsPlayerAffectedByEffect(1,EFFECT_REVERSE_RECOVER)))) end function c76214441.discost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsDiscardable() end Duel.SendtoGrave(e:GetHandler(),REASON_COST+REASON_DISCARD) end function c76214441.distg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0) end end function c76214441.disop(e,tp,eg,ep,ev,re,r,rp) Duel.NegateActivation(ev) if re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end
gpl-2.0
Julzso23/upwardsjourney
resources/lua/controls.lua
1
3387
jpm.controls = {} jpm.controls.delay = 0.3 jpm.controls.timer = jpm.controls.delay function jpm.controls.keyboard(dt) if jpm.controls.timer < 0.5 then jpm.controls.timer = jpm.controls.timer + dt end --Make the game close with alt+f4 if love.keyboard.isDown("lalt") and love.keyboard.isDown("f4") then love.event.quit() end --Define what the left and right keys are local left = love.keyboard.isDown("left") or love.keyboard.isDown("a") local right = love.keyboard.isDown("right") or love.keyboard.isDown("d") if not jpm.core.paused then if love.keyboard.isDown("escape") then jpm.core.paused = true end --Move the player in the corresponding direction if left then jpm.players[1]:move("left", dt, 1) end if right then jpm.players[1]:move("right", dt, 1) end --If the player presses both keys or neither, idle the player if left and right then jpm.players[1]:idle() end if not left and not right then jpm.players[1]:idle() end else if jpm.controls.timer >= jpm.controls.delay then if left then jpm.controls.timer = 0 if jpm.menu.id > 1 then jpm.menu.id = jpm.menu.id - 1 jpm.menu.direction = "left" else jpm.menu.id = #jpm.menu.cur jpm.menu.direction = "right" end end if right then jpm.controls.timer = 0 if jpm.menu.id < #jpm.menu.cur then jpm.menu.id = jpm.menu.id + 1 jpm.menu.direction = "right" else jpm.menu.id = 1 jpm.menu.direction = "left" end end end end end function jpm.controls.controller(dt) --This is set up for the buttons on an Xbox360 gamepad --Define what the left and right keys are to avoid idle animation conflicts local left = love.keyboard.isDown("left") or love.keyboard.isDown("a") local right = love.keyboard.isDown("right") or love.keyboard.isDown("d") if #love.joystick.getJoysticks() >= 1 then local gamepad = love.joystick.getJoysticks()[1] local axis = gamepad:getGamepadAxis("leftx") if not jpm.core.paused then if gamepad:isGamepadDown("a") then if jpm.players[1].boost > 0 then if jpm.players[1].y > 60 then jpm.players[1].boost = jpm.players[1].boost - 50*dt jpm.players[1]:move("up", dt, 0.5) end else jpm.players[1].boost = 0 end end if gamepad:isGamepadDown("start") then jpm.core.paused = true end --Move the character a certain amount depending on the amount the stick is moved if axis < -0.15 then jpm.players[1]:move("left", dt, -axis) end if axis > 0.15 then jpm.players[1]:move("right", dt, axis) end if axis > -0.15 and axis < 0.15 and not left and not right then jpm.players[1]:idle() end else if jpm.controls.timer >= jpm.controls.delay then if axis < -0.4 then jpm.controls.timer = 0 if jpm.menu.id > 1 then jpm.menu.id = jpm.menu.id - 1 jpm.menu.direction = "left" else jpm.menu.id = #jpm.menu.cur jpm.menu.direction = "right" end end if axis > 0.4 then jpm.controls.timer = 0 if jpm.menu.id < #jpm.menu.cur then jpm.menu.id = jpm.menu.id + 1 jpm.menu.direction = "right" else jpm.menu.id = 1 jpm.menu.direction = "left" end end end end end end
apache-2.0
anshkumar/yugioh-glaze
assets/script/c73347079.lua
3
1793
--RR-フォース・ストリクス function c73347079.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,4,2) c:EnableReviveLimit() --atk/def local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(c73347079.adval) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENCE) c:RegisterEffect(e2) --search local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCost(c73347079.thcost) e3:SetTarget(c73347079.thtg) e3:SetOperation(c73347079.thop) c:RegisterEffect(e3) end function c73347079.filter(c) return c:IsFaceup() and c:IsRace(RACE_WINDBEAST) end function c73347079.adval(e,c) return Duel.GetMatchingGroupCount(c73347079.filter,c:GetControler(),LOCATION_MZONE,0,c)*500 end function c73347079.thcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c73347079.thfilter(c) return c:GetLevel()==4 and c:IsRace(RACE_WINDBEAST) and c:IsAttribute(ATTRIBUTE_DARK) and c:IsAbleToHand() end function c73347079.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c73347079.thfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c73347079.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c73347079.thfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
rickyHong/nn_lib_torch
SpatialUpSamplingNearest.lua
6
1974
local SpatialUpSamplingNearest, parent = torch.class('nn.SpatialUpSamplingNearest', 'nn.Module') --[[ Applies a 2D up-sampling over an input image composed of several input planes. The upsampling is done using the simple nearest neighbor technique. The Y and X dimensions are assumed to be the last 2 tensor dimensions. For instance, if the tensor is 4D, then dim 3 is the y dimension and dim 4 is the x. owidth = width*scale_factor oheight = height*scale_factor --]] function SpatialUpSamplingNearest:__init(scale) parent.__init(self) self.scale_factor = scale if self.scale_factor < 1 then error('scale_factor must be greater than 1') end if math.floor(self.scale_factor) ~= self.scale_factor then error('scale_factor must be integer') end self.inputSize = torch.LongStorage(4) self.outputSize = torch.LongStorage(4) self.usage = nil end function SpatialUpSamplingNearest:updateOutput(input) if input:dim() ~= 4 and input:dim() ~= 3 then error('SpatialUpSamplingNearest only support 3D or 4D tensors') end -- Copy the input size local xdim = input:dim() local ydim = input:dim() - 1 for i = 1, input:dim() do self.inputSize[i] = input:size(i) self.outputSize[i] = input:size(i) end self.outputSize[ydim] = self.outputSize[ydim] * self.scale_factor self.outputSize[xdim] = self.outputSize[xdim] * self.scale_factor -- Resize the output if needed if input:dim() == 3 then self.output:resize(self.outputSize[1], self.outputSize[2], self.outputSize[3]) else self.output:resize(self.outputSize) end input.nn.SpatialUpSamplingNearest_updateOutput(self, input) return self.output end function SpatialUpSamplingNearest:updateGradInput(input, gradOutput) self.gradInput:resizeAs(input) input.nn.SpatialUpSamplingNearest_updateGradInput(self, input, gradOutput) return self.gradInput end
bsd-3-clause
anshkumar/yugioh-glaze
assets/script/c16906241.lua
3
1117
--セイクリッド・レスカ function c16906241.initial_effect(c) --summon success local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(16906241,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetTarget(c16906241.sptg) e2:SetOperation(c16906241.spop) c:RegisterEffect(e2) end function c16906241.filter(c,e,tp) return c:IsSetCard(0x53) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c16906241.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c16906241.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c16906241.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c16906241.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP_DEFENCE) end end
gpl-2.0
Arashbrsh/kings-BOT
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
assassinboy208/eagleTG
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
hadirahimi1380/botahriman
plugins/get.lua
613
1067
local function get_variables_hash(msg) if msg.to.type == 'chat' then return 'chat:'..msg.to.id..':variables' end if msg.to.type == 'user' then return 'user:'..msg.from.id..':variables' end end local function list_variables(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do text = text..names[i]..'\n' end return text end end local function get_value(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return'Not found, use "!get" to list variables' else return var_name..' => '..value end end end local function run(msg, matches) if matches[2] then return get_value(msg, matches[2]) else return list_variables(msg) end end return { description = "Retrieves variables saved with !set", usage = "!get (value_name): Returns the value_name value.", patterns = { "^(!get) (.+)$", "^!get$" }, run = run }
gpl-2.0
anshkumar/yugioh-glaze
assets/script/c87649699.lua
9
1145
--ナチュル・ラグウィード function c87649699.initial_effect(c) local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(87649699,0)) e1:SetCategory(CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetRange(LOCATION_MZONE) e1:SetCode(EVENT_DRAW) e1:SetCondition(c87649699.condition) e1:SetCost(c87649699.cost) e1:SetTarget(c87649699.target) e1:SetOperation(c87649699.operation) c:RegisterEffect(e1) end function c87649699.condition(e,tp,eg,ep,ev,re,r,rp) return ep~=tp and Duel.GetCurrentPhase()~=PHASE_DRAW end function c87649699.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c87649699.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,2) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(2) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2) end function c87649699.operation(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Draw(p,d,REASON_EFFECT) end
gpl-2.0
hbomb79/DynaCode
src/Classes/NodeUtil/NodeScrollContainer.lua
2
12795
abstract class "NodeScrollContainer" extends "NodeContainer" { yOffset = 0; xOffset = 0; cache = { nodeHeight = 0; nodeWidth = 0; xScrollPosition = 0; yScrollPosition = 0; xScrollSize = 0; yScrollSize = 0; xDisplayPosition = 0; yDisplayPosition = 0; xActive = false; yActive = false; lastMouse = 0; }; horizontalPadding = 0; verticalPadding = 0; currentScrollbar = false; autoDraw = true; trackColour = 128; barColour = 256; activeBarColour = colours.lightBlue; } function NodeScrollContainer:cacheAllInformation() self:cacheNodeSizes() self:cacheScrollbarInformation() end function NodeScrollContainer:cacheScrollbarInformation() self:cacheRequiredScrollbars() self:cacheDisplaySize() self:cacheScrollSizes() self:cacheScrollPositions() end function NodeScrollContainer:cacheDisplaySize() local cache = self.cache local xEnabled, yEnabled = cache.xActive, cache.yActive cache.displayWidth, cache.displayHeight = self.width - ( yEnabled and 1 or 0 ), self.height - ( xEnabled and 1 or 0 ) end function NodeScrollContainer:cacheNodeSizes() local x, y = 0, 0 local nodes = self.nodes local node for i = 1, #nodes do node = nodes[ i ] x = math.max( x, node.X + node.width - 1 ) y = math.max( y, node.Y + node.height - 1 ) end local cache = self.cache cache.nodeWidth = x cache.nodeHeight = y -- self.cache = cache end function NodeScrollContainer:cacheRequiredScrollbars() local cache = self.cache local width, height = cache.nodeWidth > self.width, cache.nodeHeight > self.height cache.xActive = width or ( height and cache.nodeWidth > self.width - 1 ) cache.yActive = height or ( width and cache.nodeHeight > self.height - 1 ) end function NodeScrollContainer:cacheScrollSizes() local cache = self.cache local dWidth, dHeight = cache.displayWidth, cache.displayHeight local xSize = math.ceil( dWidth / cache.nodeWidth * dWidth - .5 ) local ySize = math.ceil( dHeight / cache.nodeHeight * dHeight - .5 ) cache.xScrollSize, cache.yScrollSize = xSize, ySize end function NodeScrollContainer:cacheScrollPositions() local cache = self.cache if cache.xActive then local xPos local pos = math.ceil( self.xOffset / cache.nodeWidth * cache.displayWidth ) if pos < 1 then -- scroll bar is off screen xPos = 1 elseif pos == 1 and self.xOffset ~= 0 then -- scrollbar appears in the starting position even though the offset is not at the start xPos = 2 else xPos = pos end if self.xOffset == 0 then cache.xDisplayPosition = 1 elseif self.xOffset == cache.nodeWidth - cache.displayWidth then cache.xDisplayPosition = cache.displayWidth - cache.xScrollSize + 1 else cache.xDisplayPosition = pos end cache.xScrollPosition = xPos end if cache.yActive then local yPos local pos = math.ceil( self.yOffset / cache.nodeHeight * cache.displayHeight ) if pos < 1 then yPos = 1 elseif pos == 1 and self.yOffset ~= 0 then yPos = 2 else yPos = pos end if self.yOffset == 0 then cache.yDisplayPosition = 1 elseif self.yOffset == cache.nodeHeight - cache.displayHeight then cache.yDisplayPosition = cache.displayHeight - cache.yScrollSize + 1 else cache.yDisplayPosition = pos end cache.yScrollPosition = yPos end end function NodeScrollContainer:drawScrollbars() local canvas = self.canvas local cache = self.cache local trackColour, activeBarColour, barColour, width = self.trackColour, self.activeBarColour, self.barColour, self.width if cache.xActive then -- Draw the horizontal scrollbar & track local bg = self.currentScrollbar == "x" and self.activeBarColour or self.barColour canvas:drawArea( 1, self.height, cache.displayWidth, 1, self.trackColour, trackColour ) canvas:drawArea( cache.xDisplayPosition, self.height, cache.xScrollSize, 1, bg, bg ) end if cache.yActive then -- Draw the vertical scrollbar & track local bg = self.currentScrollbar == "y" and self.activeBarColour or self.barColour canvas:drawArea( width, 1, 1, cache.displayHeight, trackColour, trackColour ) canvas:drawArea( width, cache.yDisplayPosition, 1, cache.yScrollSize, bg, bg ) end if cache.xActive and cache.yActive then canvas:drawArea( width, self.height, 1, 1, trackColour, trackColour ) end end function NodeScrollContainer:drawContent( force ) -- Draw the nodes if they are visible in the container. local nodes = self.nodes local canvas = self.canvas canvas:clear() local xO, yO = -self.xOffset, -self.yOffset local manDraw = force or self.forceRedraw local autoDraw = self.autoDraw local node for i = 1, #nodes do node = nodes[ i ] if node.changed or node.forceRedraw or manDraw then node:draw( xO, yO, force ) if autoDraw then node.canvas:drawToCanvas( canvas, node.X + xO, node.Y + yO ) end end end end function NodeScrollContainer:draw( xO, yO, force ) if self.recacheAllNextDraw then self:cacheAllInformation() self.recacheAllNextDraw = false else if self.recacheNodeInformationNextDraw then self:cacheNodeSizes() self.recacheNodeInformationNextDraw = false end if self.recacheScrollInformationNextDraw then self:cacheScrollbarInformation() self.recacheScrollInformationNextDraw = false end end self:drawContent( force ) self:drawScrollbars( force ) end --[[ Event Handling ]]-- function NodeScrollContainer:onAnyEvent( event ) -- First, ship to nodes. If the event comes back unhandled then try to use it. local cache, x, y = self.cache if event.main == "MOUSE" then x, y = event:getRelative( self ) end if not ( (x or y) and event.sub == "CLICK" and ( cache.xActive and y == self.height or cache.yActive and x == self.width ) ) then self:submitEvent( event ) end if not event.handled then local ownerApplication = self.stage.application local hotkey = ownerApplication.hotkey if event.main == "MOUSE" then local sub = event.sub if event:isInNode( self ) then self.stage:redirectKeyboardFocus( self ) if sub == "CLICK" then -- Was this on a scrollbar? if cache.xActive then if y == self.height then -- its on the track so we will stop this event from propagating further. event.handled = true if x >= cache.xScrollPosition and x <= cache.xScrollPosition + cache.xScrollSize then self.currentScrollbar = "x" self.lastMouse = x self.changed = true end end end if cache.yActive then if x == self.width then event.handled = true if y >= cache.yScrollPosition and y <= cache.yScrollPosition + cache.yScrollSize - 1 then self.currentScrollbar = "y" self.lastMouse = y self.changed = true end end end elseif sub == "SCROLL" then if cache.xActive and (not cache.yActive or hotkey.keys.shift) then -- scroll the horizontal bar self.xOffset = math.max( math.min( self.xOffset + event.misc, cache.nodeWidth - cache.displayWidth ), 0 ) self.changed = true self:cacheScrollPositions() elseif cache.yActive then -- scroll the vertical bar self.yOffset = math.max( math.min( self.yOffset + event.misc, cache.nodeHeight - cache.displayHeight ), 0 ) self.changed = true self:cacheScrollPositions() end end else if self.focused then self.stage:removeKeyboardFocus( self ) end end if event.handled then return end -- We needn't continue. if sub == "DRAG" then local current = self.currentScrollbar if current == "x" then local newPos, newOffset = cache.xScrollPosition + ( x < self.lastMouse and -1 or 1 ) log("w", "Last mouse location: "..tostring( self.lastMouse )..", Current mouse location: "..tostring( x )..", Current position: "..tostring( cache.xScrollPosition )..", new position: "..tostring( newPos ) ) if newPos <= 1 then newOffset = 0 else newOffset = math.max( math.min( math.floor( ( newPos ) * ( ( cache.nodeWidth - .5 ) / cache.displayWidth ) ), cache.nodeWidth - cache.displayWidth ), 0 ) end log( "w", "New offset from position: "..tostring( newOffset ) ) self.xOffset = newOffset self.lastMouse = x elseif current == "y" then local newPos = cache.yScrollPosition + ( y - self.lastMouse ) local newOffset if newPos <= 1 then newOffset = 0 else newOffset = math.max( math.min( math.floor( ( newPos ) * ( ( cache.nodeHeight - .5 ) / cache.displayHeight ) ), cache.nodeHeight - cache.displayHeight ), 0 ) end self.yOffset = newOffset self.lastMouse = y end self.changed = true self:cacheScrollPositions() elseif sub == "UP" then self.currentScrollbar = nil self.lastMouse = nil self.changed = true end elseif self.focused and event.main == "KEY" then if event.sub == "KEY" and hotkey.keys.shift then local function setOffset( target, value ) self[target.."Offset"] = value self.changed = true self:cacheScrollPositions() end -- offset adjustment if event.key == keys.up then -- Shift the offset up (reduce) setOffset( "y", math.max( self.yOffset - self.height, 0 ) ) elseif event.key == keys.down then setOffset( "y", math.min( self.yOffset + self.height, cache.nodeHeight - cache.displayHeight ) ) elseif event.key == keys.left then setOffset( "x", math.max( self.xOffset - self.width, 0 ) ) elseif event.key == keys.right then setOffset( "x", math.min( self.xOffset + self.width, cache.nodeWidth - cache.displayWidth ) ) end end end end end function NodeScrollContainer:submitEvent( event ) local main = event.main local oX, oY, oPb if main == "MOUSE" then oPb = event.inParentBounds event.inParentBounds = event:isInNode( self ) oX, oY = event:getPosition() event:convertToRelative( self ) event.X = event.X + self.xOffset event.Y = event.Y + self.yOffset end local nodes, node = self.nodes for i = 1, #nodes do nodes[ i ]:handleEvent( event ) end if main == "MOUSE" then event.X, event.Y, event.inParentBounds = oX, oY, oPb end end function NodeScrollContainer:onFocusLost() self.focused = false; self.acceptKeyboard = false; end function NodeScrollContainer:onFocusGain() self.focused = true; self.acceptKeyboard = true; end function NodeScrollContainer:getCursorInformation() return false end -- this has no cursor --[[ Intercepts ]]-- function NodeScrollContainer:addNode( node ) self.super:addNode( node ) self.recacheAllNextDraw = true end function NodeScrollContainer:removeNode( n ) self.super:removeNode( n ) self.recacheAllNextDraw = true end
mit
freifunk-gluon/luci
applications/luci-asterisk/luasrc/asterisk/cc_idd.lua
92
7735
--[[ LuCI - Asterisk - International Direct Dialing Prefixes and Country Codes Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module "luci.asterisk.cc_idd" CC_IDD = { -- Country, CC, IDD { "Afghanistan", "93", "00" }, { "Albania", "355", "00" }, { "Algeria", "213", "00" }, { "American Samoa", "684", "00" }, { "Andorra", "376", "00" }, { "Angola", "244", "00" }, { "Anguilla", "264", "011" }, { "Antarctica", "672", "" }, { "Antigua", "268", "011" }, { "Argentina", "54", "00" }, { "Armenia", "374", "00" }, { "Aruba", "297", "00" }, { "Ascension Island", "247", "00" }, { "Australia", "61", "0011" }, { "Austria", "43", "00" }, { "Azberbaijan", "994", "00" }, { "Bahamas", "242", "011" }, { "Bahrain", "973", "00" }, { "Bangladesh", "880", "00" }, { "Barbados", "246", "011" }, { "Barbuda", "268", "011" }, { "Belarus", "375", "810" }, { "Belgium", "32", "00" }, { "Belize", "501", "00" }, { "Benin", "229", "00" }, { "Bermuda", "441", "011" }, { "Bhutan", "975", "00" }, { "Bolivia", "591", "00" }, { "Bosnia", "387", "00" }, { "Botswana", "267", "00" }, { "Brazil", "55", "00" }, { "British Virgin Islands", "284", "011" }, { "Brunei", "673", "00" }, { "Bulgaria", "359", "00" }, { "Burkina Faso", "226", "00" }, { "Burma (Myanmar)", "95", "00" }, { "Burundi", "257", "00" }, { "Cambodia", "855", "001" }, { "Cameroon", "237", "00" }, { "Canada", "1", "011" }, { "Cape Verde Islands", "238", "0" }, { "Cayman Islands", "345", "011" }, { "Central African Rep.", "236", "00" }, { "Chad", "235", "15" }, { "Chile", "56", "00" }, { "China", "86", "00" }, { "Christmas Island", "61", "0011" }, { "Cocos Islands", "61", "0011" }, { "Colombia", "57", "00" }, { "Comoros", "269", "00" }, { "Congo", "242", "00" }, { "Congo, Dem. Rep. of", "243", "00" }, { "Cook Islands", "682", "00" }, { "Costa Rica", "506", "00" }, { "Croatia", "385", "00" }, { "Cuba", "53", "119" }, { "Cyprus", "357", "00" }, { "Czech Republic", "420", "00" }, { "Denmark", "45", "00" }, { "Diego Garcia", "246", "00" }, { "Djibouti", "253", "00" }, { "Dominica", "767", "011" }, { "Dominican Rep.", "809", "011" }, { "Ecuador", "593", "00" }, { "Egypt", "20", "00" }, { "El Salvador", "503", "00" }, { "Equatorial Guinea", "240", "00" }, { "Eritrea", "291", "00" }, { "Estonia", "372", "00" }, { "Ethiopia", "251", "00" }, { "Faeroe Islands", "298", "00" }, { "Falkland Islands", "500", "00" }, { "Fiji Islands", "679", "00" }, { "Finland", "358", "00" }, { "France", "33", "00" }, { "French Antilles", "596", "00" }, { "French Guiana", "594", "00" }, { "French Polynesia", "689", "00" }, { "Gabon", "241", "00" }, { "Gambia", "220", "00" }, { "Georgia", "995", "810" }, { "Germany", "49", "00" }, { "Ghana", "233", "00" }, { "Gibraltar", "350", "00" }, { "Greece", "30", "00" }, { "Greenland", "299", "00" }, { "Grenada", "473", "011" }, { "Guadeloupe", "590", "00" }, { "Guam", "671", "011" }, { "Guantanamo Bay", "5399", "00" }, { "Guatemala", "502", "00" }, { "Guinea", "224", "00" }, { "Guinea Bissau", "245", "00" }, { "Guyana", "592", "001" }, { "Haiti", "509", "00" }, { "Honduras", "504", "00" }, { "Hong Kong", "852", "001" }, { "Hungary", "36", "00" }, { "Iceland", "354", "00" }, { "India", "91", "00" }, { "Indonesia", "62", { "001", "008" } }, { "Iran", "98", "00" }, { "Iraq", "964", "00" }, { "Ireland", "353", "00" }, { "Israel", "972", "00" }, { "Italy", "39", "00" }, { "Ivory Coast", "225", "00" }, { "Jamaica", "876", "011" }, { "Japan", "81", "001" }, { "Jordan", "962", "00" }, { "Kazakhstan", "7", "810" }, { "Kenya", "254", "000" }, { "Kiribati", "686", "00" }, { "Korea, North", "850", "00" }, { "Korea, South", "82", "001" }, { "Kuwait", "965", "00" }, { "Kyrgyzstan", "996", "00" }, { "Laos", "856", "00" }, { "Latvia", "371", "00" }, { "Lebanon", "961", "00" }, { "Lesotho", "266", "00" }, { "Liberia", "231", "00" }, { "Libya", "218", "00" }, { "Liechtenstein", "423", "00" }, { "Lithuania", "370", "00" }, { "Luxembourg", "352", "00" }, { "Macau", "853", "00" }, { "Macedonia", "389", "00" }, { "Madagascar", "261", "00" }, { "Malawi", "265", "00" }, { "Malaysia", "60", "00" }, { "Maldives", "960", "00" }, { "Mali", "223", "00" }, { "Malta", "356", "00" }, { "Mariana Islands", "670", "011" }, { "Marshall Islands", "692", "011" }, { "Martinique", "596", "00" }, { "Mauritania", "222", "00" }, { "Mauritius", "230", "00" }, { "Mayotte Islands", "269", "00" }, { "Mexico", "52", "00" }, { "Micronesia", "691", "011" }, { "Midway Island", "808", "011" }, { "Moldova", "373", "00" }, { "Monaco", "377", "00" }, { "Mongolia", "976", "001" }, { "Montserrat", "664", "011" }, { "Morocco", "212", "00" }, { "Mozambique", "258", "00" }, { "Myanmar (Burma)", "95", "00" }, { "Namibia", "264", "00" }, { "Nauru", "674", "00" }, { "Nepal", "977", "00" }, { "Netherlands", "31", "00" }, { "Netherlands Antilles", "599", "00" }, { "Nevis", "869", "011" }, { "New Caledonia", "687", "00" }, { "New Zealand", "64", "00" }, { "Nicaragua", "505", "00" }, { "Niger", "227", "00" }, { "Nigeria", "234", "009" }, { "Niue", "683", "00" }, { "Norfolk Island", "672", "00" }, { "Norway", "47", "00" }, { "Oman", "968", "00" }, { "Pakistan", "92", "00" }, { "Palau", "680", "011" }, { "Palestine", "970", "00" }, { "Panama", "507", "00" }, { "Papua New Guinea", "675", "05" }, { "Paraguay", "595", "002" }, { "Peru", "51", "00" }, { "Philippines", "63", "00" }, { "Poland", "48", "00" }, { "Portugal", "351", "00" }, { "Puerto Rico", { "787", "939" }, "011" }, { "Qatar", "974", "00" }, { "Reunion Island", "262", "00" }, { "Romania", "40", "00" }, { "Russia", "7", "810" }, { "Rwanda", "250", "00" }, { "St. Helena", "290", "00" }, { "St. Kitts", "869", "011" }, { "St. Lucia", "758", "011" }, { "St. Perre & Miquelon", "508", "00" }, { "St. Vincent", "784", "011" }, { "San Marino", "378", "00" }, { "Sao Tome & Principe", "239", "00" }, { "Saudi Arabia", "966", "00" }, { "Senegal", "221", "00" }, { "Serbia", "381", "99" }, { "Seychelles", "248", "00" }, { "Sierra Leone", "232", "00" }, { "Singapore", "65", "001" }, { "Slovakia", "421", "00" }, { "Slovenia", "386", "00" }, { "Solomon Islands", "677", "00" }, { "Somalia", "252", "00" }, { "South Africa", "27", "09" }, { "Spain", "34", "00" }, { "Sri Lanka", "94", "00" }, { "Sudan", "249", "00" }, { "Suriname", "597", "00" }, { "Swaziland", "268", "00" }, { "Sweden", "46", "00" }, { "Switzerland", "41", "00" }, { "Syria", "963", "00" }, { "Taiwan", "886", "002" }, { "Tajikistan", "992", "810" }, { "Tanzania", "255", "00" }, { "Thailand", "66", "001" }, { "Togo", "228", "00" }, { "Tonga", "676", "00" }, { "Trinidad & Tobago", "868", "011" }, { "Tunisia", "216", "00" }, { "Turkey", "90", "00" }, { "Turkmenistan", "993", "810" }, { "Turks & Caicos", "649", "011" }, { "Tuvalu", "688", "00" }, { "Uganda", "256", "000" }, { "Ukraine", "380", "810" }, { "United Arab Emirates", "971", "00" }, { "United Kingdom", "44", "00" }, { "Uruguay", "598", "00" }, { "USA", "1", "011" }, { "US Virgin Islands", "340", "011" }, { "Uzbekistan", "998", "810" }, { "Vanuatu", "678", "00" }, { "Vatican City", "39", "00" }, { "Venezuela", "58", "00" }, { "Vietnam", "84", "00" }, { "Wake Island", "808", "00" }, { "Wallis & Futuna", "681", "19" }, { "Western Samoa", "685", "00" }, { "Yemen", "967", "00" }, { "Yugoslavia", "381", "99" }, { "Zambia", "260", "00" }, { "Zimbabwe", "263", "00" } }
apache-2.0
ara8586/b.v4
plugins/banhammer.lua
1
37084
local function pre_process(msg) if msg.to.type ~= 'pv' then chat = msg.to.id user = msg.from.id local function check_newmember(arg, data) test = load_data(_config.moderation.data) lock_bots = test[arg.chat_id]['settings']['lock_bots'] local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.type_.ID == "UserTypeBot" then if not is_owner(arg.msg) and lock_bots == 'yes' then kick_user(data.id_, arg.chat_id) end end if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_banned(data.id_, arg.chat_id) then if not lang then tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is banned_", 0, "md") else tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از گروه محروم است_", 0, "md") end kick_user(data.id_, arg.chat_id) end if is_gbanned(data.id_) then if not lang then tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_User_ "..user_name.." *[ "..data.id_.." ]* _is globally banned_", 0, "md") else tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, "_کاربر_ "..user_name.." *[ "..data.id_.." ]* _از تمام گروه های ربات محروم است_", 0, "md") end kick_user(data.id_, arg.chat_id) end end if msg.adduser then tdcli_function ({ ID = "GetUser", user_id_ = msg.adduser }, check_newmember, {chat_id=chat,msg_id=msg.id,user_id=user,msg=msg}) end if msg.joinuser then tdcli_function ({ ID = "GetUser", user_id_ = msg.joinuser }, check_newmember, {chat_id=chat,msg_id=msg.id,user_id=user,msg=msg}) end if msg.text and tonumber(msg.from.id) == 157059515 and msg.text:match("id") then return false end end -- return msg end local function action_by_reply(arg, data) local hash = "gp_lang:"..data.chat_id_ local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "ban" then local function ban_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 is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md") end end if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 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_ }, ban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "unban" then local function unban_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)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][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_ *unbanned*", 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_ }, unban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "silent" then local function silent_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 is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md") end end if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][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_.."* _added to_ *silent users 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_ }, silent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "unsilent" then local function unsilent_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)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][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_.."* _removed from_ *silent users 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_ }, unsilent_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "banall" then local function gban_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['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md") end end if is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md") end end administration['gban_users'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 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_ }, gban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "unbanall" then local function ungban_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['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if not is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md") end end administration['gban_users'][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_ *globally unbanned*", 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_ }, ungban_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "kick" then if is_mod1(data.chat_id_, data.sender_user_id_) then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md") end else kick_user(data.sender_user_id_, data.chat_id_) end end if cmd == "delall" then if is_mod1(data.chat_id_, data.sender_user_id_) then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md") end else tdcli.deleteMessagesFromUser(data.chat_id_, data.sender_user_id_, dl_cb, nil) if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_All_ *messages* _of_ *[ "..data.sender_user_id_.." ]* _has been_ *deleted*", 0, "md") elseif lang then return tdcli.sendMessage(data.chat_id_, "", 0, "*تمام پیام های* *[ "..data.sender_user_id_.." ]* *پاک شد*", 0, "md") end end 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 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 == "ban" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't ban_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه، و ادمین های ربات رو از گروه محروم کنید*", 0, "md") end end if administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* * از گروه محروم بود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم شد*", 0, "md") end end if cmd == "unban" then if not administration[tostring(arg.chat_id)]['banned'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه محروم نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['banned'][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_ *unbanned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه خارج شد*", 0, "md") end end if cmd == "silent" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't silent_ *mods,owners and bot admins*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه، و ادمین های ربات بگیرید*", 0, "md") end end if administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن رو نداشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][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_.."* _added to_ *silent users list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو از دست داد*", 0, "md") end end if cmd == "unsilent" then if not administration[tostring(arg.chat_id)]['is_silent_users'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *silent*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل توانایی چت کردن را داشت*", 0, "md") end end administration[tostring(arg.chat_id)]['is_silent_users'][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_.."* _removed from_ *silent users list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *توانایی چت کردن رو به دست آورد*", 0, "md") end end if cmd == "banall" then if not administration['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't_ *globally ban* _other admins_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید ادمین های ربات رو از تمامی گروه های ربات محروم کنید*", 0, "md") end end if is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم بود*", 0, "md") end end administration['gban_users'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) kick_user(data.id_, arg.chat_id) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از تمام گروه های ربات محروم شد*", 0, "md") end end if cmd == "unbanall" then if not administration['gban_users'] then administration['gban_users'] = {} save_data(_config.moderation.data, administration) end if not is_gbanned(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not_ *globally banned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از گروه های ربات محروم نبود*", 0, "md") end end administration['gban_users'][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_ *globally unbanned*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از محرومیت گروه های ربات خارج شد*", 0, "md") end end if cmd == "kick" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't kick_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md") end else kick_user(data.id_, arg.chat_id) end end if cmd == "delall" then if is_mod1(arg.chat_id, data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_You can't delete messages_ *mods,owners and bot admins*", 0, "md") elseif lang then return tdcli.sendMessage(arg.chat_id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md") end else tdcli.deleteMessagesFromUser(arg.chat_id, data.id_, dl_cb, nil) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_All_ *messages* _of_ "..user_name.." *[ "..data.id_.." ]* _has been_ *deleted*", 0, "md") elseif lang then return tdcli.sendMessage(arg.chat_id, "", 0, "*تمام پیام های* "..user_name.." *[ "..data.id_.." ]* *پاک شد*", 0, "md") end 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 local function run(msg, matches) local userid = tonumber(matches[2]) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) chat = msg.to.id user = msg.from.id if msg.to.type ~= 'pv' then if matches[1] == "kick" or matches[1] == "کیک" and is_mod(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="kick"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, userid) then if not lang then tdcli.sendMessage(msg.to.id, "", 0, "_You can't kick mods,owners or bot admins_", 0, "md") elseif lang then tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو اخراج کنید*", 0, "md") end else kick_user(matches[2], msg.to.id) end 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="kick"}) end end if matches[1] == "delall" or matches[1] == "حذف همه" and is_mod(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="delall"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, userid) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't delete messages mods,owners or bot admins_", 0, "md") elseif lang then return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید پیام های مدیران،صاحبان گروه و ادمین های ربات رو پاک کنید*", 0, "md") end else tdcli.deleteMessagesFromUser(msg.to.id, matches[2], dl_cb, nil) if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_All_ *messages* _of_ *[ "..matches[2].." ]* _has been_ *deleted*", 0, "md") elseif lang then return tdcli.sendMessage(msg.to.id, "", 0, "*تمامی پیام های* *[ "..matches[2].." ]* *پاک شد*", 0, "md") end end 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="delall"}) end end end if matches[1] == "banall" 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="banall"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_admin1(userid) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't globally ban other admins_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید ادمین های ربات رو از گروه های ربات محروم کنید*", 0, "md") end end if is_gbanned(matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "*User "..matches[2].." is already globally banned*", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم بود*", 0, "md") end end data['gban_users'][tostring(matches[2])] = "" save_data(_config.moderation.data, data) kick_user(matches[2], msg.to.id) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "*User "..matches[2].." has been globally banned*", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از تمام گروه هار ربات محروم شد*", 0, "md") end 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="banall"}) end end if matches[1] == "unbanall" 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="unbanall"}) end if matches[2] and string.match(matches[2], '^%d+$') then if not is_gbanned(matches[2]) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "*User "..matches[2].." is not globally banned*", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه های ربات محروم نبود*", 0, "md") end end data['gban_users'][tostring(matches[2])] = nil save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "*User "..matches[2].." has been globally unbanned*", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از محرومیت گروه های ربات خارج شد*", 0, "md") end 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="unbanall"}) end end if msg.to.type ~= 'pv' then if matches[1] == "ban" or matches[1] == "بن" and is_mod(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="ban"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, userid) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't ban mods,owners or bot admins_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید مدیران،صاحبان گروه و ادمین های ربات رو از گروه محروم کنید*", 0, "md") end end if is_banned(matches[2], msg.to.id) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is already banned_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه محروم بود*", 0, "md") end end data[tostring(chat)]['banned'][tostring(matches[2])] = "" save_data(_config.moderation.data, data) kick_user(matches[2], msg.to.id) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." has been banned_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از گروه محروم شد*", 0, "md") end 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="ban"}) end end if matches[1] == "unban" or matches[1] == "رفع بن" and is_mod(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="unban"}) end if matches[2] and string.match(matches[2], '^%d+$') then if not is_banned(matches[2], msg.to.id) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is not banned_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از گروه محروم نبود*", 0, "md") end end data[tostring(chat)]['banned'][tostring(matches[2])] = nil save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." has been unbanned_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." از محرومیت گروه خارج شد*", 0, "md") end 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="unban"}) end end if matches[1] == "silent" or matches[1] == "سایلنت" and is_mod(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="silent"}) end if matches[2] and string.match(matches[2], '^%d+$') then if is_mod1(msg.to.id, userid) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_You can't silent mods,leaders or bot admins_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*شما نمیتوانید توانایی چت کردن رو از مدیران،صاحبان گروه و ادمین های ربات بگیرید*", 0, "md") end end if is_silent_user(matches[2], chat) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is already silent_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو نداشت*", 0, "md") end end data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = "" save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." added to silent users list_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." توانایی چت کردن رو از دست داد*", 0, "md") end 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="silent"}) end end if matches[1] == "unsilent" or matches[1] == "رفع سایلنت" and is_mod(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="unsilent"}) end if matches[2] and string.match(matches[2], '^%d+$') then if not is_silent_user(matches[2], chat) then if not lang then return tdcli.sendMessage(msg.to.id, "", 0, "_User "..matches[2].." is not silent_", 0, "md") else return tdcli.sendMessage(msg.to.id, "", 0, "*کاربر "..matches[2].." از قبل توانایی چت کردن رو داشت*", 0, "md") end end data[tostring(chat)]['is_silent_users'][tostring(matches[2])] = nil save_data(_config.moderation.data, data) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 0, "_User "..matches[2].." removed from silent users list_", 0, "md") else return tdcli.sendMessage(msg.to.id, msg.id, 0, "*کاربر "..matches[2].." توانایی چت کردن رو به دست آورد*", 0, "md") end 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="unsilent"}) end end if matches[1]:lower() == 'clean' or matches[1]:lower() == 'پاک کردن' and is_owner(msg) then if matches[2] == 'bans' then if next(data[tostring(chat)]['banned']) == nil then if not lang then return "_No_ *banned* _users in this group_" else return "*هیچ کاربری از این گروه محروم نشده*" end end for k,v in pairs(data[tostring(chat)]['banned']) do data[tostring(chat)]['banned'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *banned* _users has been unbanned_" else return "*تمام کاربران محروم شده از گروه از محرومیت خارج شدند*" end end if matches[2] == 'silents' or matches[2] == "سایلنت ها" then if next(data[tostring(chat)]['is_silent_users']) == nil then if not lang then return "_No_ *silent* _users in this group_" else return "*لیست کاربران سایلنت شده خالی است*" end end for k,v in pairs(data[tostring(chat)]['is_silent_users']) do data[tostring(chat)]['is_silent_users'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "*Silent list* _has been cleaned_" else return "*لیست کاربران سایلنت شده پاک شد*" end end end end if matches[1]:lower() == 'clean' or matches[1]:lower() == 'پاک کردن' and is_sudo(msg) then if matches[2] == 'gbans' or matches[2] == "جی بن ها" then if next(data['gban_users']) == nil then if not lang then return "_No_ *globally banned* _users available_" else return "*هیچ کاربری از گروه های ربات محروم نشده*" end end for k,v in pairs(data['gban_users']) do data['gban_users'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *globally banned* _users has been unbanned_" else return "*تمام کاربرانی که از گروه های ربات محروم بودند از محرومیت خارج شدند*" end end end if matches[1] == "gbanlist" or matches[1] == "لیست جی بن" and is_admin(msg) then return gbanned_list(msg) end if msg.to.type ~= 'pv' then if matches[1] == "silentlist" or matches[1] == "لیست سایلنت" and is_mod(msg) then return silent_users_list(chat) end if matches[1] == "banlist" or matches[1] == "لیست بن" and is_mod(msg) then return banned_list(chat) end end end return { patterns = { "^[!/#](banall)$", "^(جی بن)$", "^[!/#](banall) (.*)$", "^(جی بن)$", "^[!/#](unbanall)$", "^(رفع جی بن)$", "^[!/#](unbanall) (.*)$", "^(رفع جی بن)$", "^[!/#](gbanlist)$", "^(لیست جی بن)$", "^[!/#](ban)$", "^(بن)$", "^[!/#](ban) (.*)$", "^(بن)$", "^[!/#](unban)$", "^(رفع بن)$", "^[!/#](unban) (.*)$", "^(رفع بن)$", "^[!/#](banlist)$", "^(لیست بن)$", "^[!/#](silent)$", "^(سایلنت)$", "^[!/#](silent) (.*)$", "^(سایلنت)$", "^[!/#](unsilent)$", "^(رفع سایلنت)$", "^[!/#](unsilent) (.*)$", "^(رفع سایلنت)$", "^[!/#](silentlist)$", "^(لیست سایلنت)$", "^[!/#](kick)$", "^(کیک)$", "^[!/#](kick) (.*)$", "^(کیک)$", "^[!/#](delall)$", "^(حذف همه)$", "^[!/#](delall) (.*)$", "^(حذف همه)$", "^[!/#](clean) (.*)$", "^(پاک کردن)$" }, run = run, pre_process = pre_process }
gpl-3.0
PocoCraftSource/FiveNightsatFreddysGMod
gamemode/spawnmenu/toolpanel.lua
1
2093
include( 'controlpanel.lua' ) local PANEL = {} AccessorFunc( PANEL, "m_TabID", "TabID" ) --[[--------------------------------------------------------- Name: Paint -----------------------------------------------------------]] function PANEL:Init() self.List = vgui.Create( "DCategoryList", self ) self.List:Dock( LEFT ) self.List:SetWidth( 130 ) self.Content = vgui.Create( "DCategoryList", self ) self.Content:Dock( FILL ) self.Content:DockMargin( 6, 0, 0, 0 ) self:SetWide( 390 ) if ( ScrW() > 1280 ) then self:SetWide( 460 ) end end --[[--------------------------------------------------------- Name: LoadToolsFromTable -----------------------------------------------------------]] function PANEL:LoadToolsFromTable( inTable ) local inTable = table.Copy( inTable ) for k, v in pairs( inTable ) do if ( istable( v ) ) then -- Remove these from the table so we can -- send the rest of the table to the other -- function local Name = v.ItemName local Label = v.Text v.ItemName = nil v.Text = nil self:AddCategory( Name, Label, v ) end end end --[[--------------------------------------------------------- Name: AddCategory -----------------------------------------------------------]] function PANEL:AddCategory( Name, Label, tItems ) local Category = self.List:Add( Label ) Category:SetCookieName( "ToolMenu." .. tostring( Name ) ) local bAlt = true for k, v in pairs( tItems ) do local item = Category:Add( v.Text ) item.DoClick = function( button ) spawnmenu.ActivateTool( button.Name ) end item.ControlPanelBuildFunction = v.CPanelFunction item.Command = v.Command item.Name = v.ItemName item.Controls = v.Controls item.Text = v.Text end self:InvalidateLayout() end function PANEL:SetActive( cp ) local kids = self.Content:GetCanvas():GetChildren() for k, v in pairs( kids ) do v:SetVisible( false ) end self.Content:AddItem( cp ) cp:SetVisible( true ) cp:Dock( TOP ) end vgui.Register( "ToolPanel", PANEL, "Panel" )
gpl-2.0
anshkumar/yugioh-glaze
assets/script/c77841719.lua
3
1810
--ヴェルズ・コッペリアル function c77841719.initial_effect(c) --cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) c:RegisterEffect(e1) --control local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_CONTROL) e2:SetDescription(aux.Stringid(77841719,0)) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCode(EVENT_LEAVE_FIELD) e2:SetCondition(c77841719.condition) e2:SetTarget(c77841719.target) e2:SetOperation(c77841719.operation) c:RegisterEffect(e2) end function c77841719.condition(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousPosition(POS_FACEUP) and not c:IsLocation(LOCATION_DECK) and c:GetPreviousControler()==tp and rp~=tp end function c77841719.filter(c) return c:IsFaceup() and c:IsControlerCanBeChanged() end function c77841719.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and c77841719.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c77841719.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONTROL) local g=Duel.SelectTarget(tp,c77841719.filter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_CONTROL,g,1,0,0) end function c77841719.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() local tct=1 if Duel.GetTurnPlayer()~=tp then tct=2 elseif Duel.GetCurrentPhase()==PHASE_END then tct=3 end if tc:IsFaceup() and tc:IsRelateToEffect(e) and not Duel.GetControl(tc,tp,PHASE_END,tct) then if not tc:IsImmuneToEffect(e) and tc:IsAbleToChangeControler() then Duel.Destroy(tc,REASON_EFFECT) end end end
gpl-2.0
BooM-amour/neweagle
plugins/admin.lua
60
6680
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function get_contact_list_callback (cb_extra, success, result) local text = " " for k,v in pairs(result) do if v.print_name and v.id and v.phone then text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n" end end local file = io.open("contact_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format local file = io.open("contact_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format end local function user_info_callback(cb_extra, success, result) result.access_hash = nil result.flags = nil result.phone = nil if result.username then result.username = '@'..result.username end result.print_name = result.print_name:gsub("_","") local text = serpent.block(result, {comment=false}) text = text:gsub("[{}]", "") text = text:gsub('"', "") text = text:gsub(",","") if cb_extra.msg.to.type == "chat" then send_large_msg("chat#id"..cb_extra.msg.to.id, text) else send_large_msg("user#id"..cb_extra.msg.to.id, text) end end local function get_dialog_list_callback(cb_extra, success, result) local text = "" for k,v in pairs(result) do if v.peer then if v.peer.type == "chat" then text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")" else if v.peer.print_name and v.peer.id then text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]" end if v.peer.username then text = text.."("..v.peer.username..")" end if v.peer.phone then text = text.."'"..v.peer.phone.."'" end end end if v.message then text = text..'\nlast msg >\nmsg id = '..v.message.id if v.message.text then text = text .. "\n text = "..v.message.text end if v.message.action then text = text.."\n"..serpent.block(v.message.action, {comment=false}) end if v.message.from then if v.message.from.print_name then text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]" end if v.message.from.username then text = text.."( "..v.message.from.username.." )" end if v.message.from.phone then text = text.."' "..v.message.from.phone.." '" end end end text = text.."\n\n" end local file = io.open("dialog_list.txt", "w") file:write(text) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format local file = io.open("dialog_list.json", "w") file:write(json:encode_pretty(result)) file:flush() file:close() send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then--join by group link local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end if matches[1] == "contactlist" then get_contact_list(get_contact_list_callback, {target = msg.from.id}) return "I've sent contact list with both json and text format to your private" end if matches[1] == "delcontact" then del_contact("user#id"..matches[2],ok_cb,false) return "User "..matches[2].." removed from contact list" end if matches[1] == "dialoglist" then get_dialog_list(get_dialog_list_callback, {target = msg.from.id}) return "I've sent dialog list with both json and text format to your private" end if matches[1] == "whois" then user_info("user#id"..matches[2],user_info_callback,{msg=msg}) end return end return { usage = { "pm: Send Pm To Priavate Chat.", "block: Block User [id].", "unblock: Unblock User [id].", "markread on: Reads Messages agancy Bot.", "markread off: Don't Reads Messages agancy Bot.", "setbotphoto: Set New Photo For Bot Account.", "contactlist: Send A List Of Bot Contacts.", "dialoglist: Send A Dialog Of Chat.", "delcontact: Delete Contact.", "import: Added Bot In Group With Link.", }, patterns = { "^(pm) (%d+) (.*)$", "^(import) (.*)$", "^(unblock) (%d+)$", "^(block) (%d+)$", "^(markread) (on)$", "^(markread) (off)$", "^(setbotphoto)$", "%[(photo)%]", "^(contactlist)$", "^(dialoglist)$", "^(delcontact) (%d+)$", "^(whois) (%d+)$" }, run = run, }
gpl-2.0
sjznxd/lc-20130302
applications/luci-radvd/luasrc/model/cbi/radvd/prefix.lua
74
3766
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sid = arg[1] local utl = require "luci.util" m = Map("radvd", translatef("Radvd - Prefix"), translate("Radvd is a router advertisement daemon for IPv6. " .. "It listens to router solicitations and sends router advertisements " .. "as described in RFC 4861.")) m.redirect = luci.dispatcher.build_url("admin/network/radvd") if m.uci:get("radvd", sid) ~= "prefix" then luci.http.redirect(m.redirect) return end s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration")) s.addremove = false s:tab("general", translate("General")) s:tab("advanced", translate("Advanced")) -- -- General -- o = s:taboption("general", Flag, "ignore", translate("Enable")) o.rmempty = false function o.cfgvalue(...) local v = Flag.cfgvalue(...) return v == "1" and "0" or "1" end function o.write(self, section, value) Flag.write(self, section, value == "1" and "0" or "1") end o = s:taboption("general", Value, "interface", translate("Interface"), translate("Specifies the logical interface name this section belongs to")) o.template = "cbi/network_netlist" o.nocreate = true o.optional = false function o.formvalue(...) return Value.formvalue(...) or "-" end function o.validate(self, value) if value == "-" then return nil, translate("Interface required") end return value end function o.write(self, section, value) m.uci:set("radvd", section, "ignore", 0) m.uci:set("radvd", section, "interface", value) end o = s:taboption("general", DynamicList, "prefix", translate("Prefixes"), translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used")) o.optional = true o.datatype = "ip6addr" o.placeholder = translate("default") function o.cfgvalue(self, section) local l = { } local v = m.uci:get_list("radvd", section, "prefix") for v in utl.imatch(v) do l[#l+1] = v end return l end o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"), translate("Indicates that this prefix can be used for on-link determination (RFC4861)")) o.rmempty = false o.default = "1" o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"), translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)")) o.rmempty = false o.default = "1" -- -- Advanced -- o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"), translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6")) o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"), translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 86400 o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"), translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred.")) o.datatype = 'or(uinteger,"infinity")' o.placeholder = 14400 o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"), translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option")) o.template = "cbi/network_netlist" o.nocreate = true o.unspecified = true return m
apache-2.0
anshkumar/yugioh-glaze
assets/script/c32559361.lua
6
2975
--CNo.9 天蓋妖星カオス・ダイソン・スフィア function c32559361.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,10,3) c:EnableReviveLimit() --material local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(32559361,0)) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_BATTLE_START) e1:SetTarget(c32559361.target) e1:SetOperation(c32559361.operation) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(32559361,1)) e2:SetCategory(CATEGORY_DAMAGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetTarget(c32559361.damtg) e2:SetOperation(c32559361.damop) c:RegisterEffect(e2) --damage2 local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(32559361,2)) e3:SetCategory(CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetRange(LOCATION_MZONE) e3:SetCountLimit(1) e3:SetCondition(c32559361.damcon) e3:SetCost(c32559361.damcost) e3:SetTarget(c32559361.damtg2) e3:SetOperation(c32559361.damop2) c:RegisterEffect(e3) end c32559361.xyz_number=9 function c32559361.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() local tc=c:GetBattleTarget() if chk==0 then return tc and c:IsType(TYPE_XYZ) and not tc:IsType(TYPE_TOKEN) and tc:IsAbleToChangeControler() end end function c32559361.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=c:GetBattleTarget() if c:IsRelateToEffect(e) and c:IsFaceup() and tc:IsRelateToBattle() and not tc:IsImmuneToEffect(e) then local og=tc:GetOverlayGroup() if og:GetCount()>0 then Duel.SendtoGrave(og,REASON_RULE) end Duel.Overlay(c,Group.FromCards(tc)) end end function c32559361.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():GetOverlayCount()>0 end local ct=e:GetHandler():GetOverlayCount() Duel.SetTargetPlayer(1-tp) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ct*300) end function c32559361.damop(e,tp,eg,ep,ev,re,r,rp) local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local ct=e:GetHandler():GetOverlayCount() Duel.Damage(p,ct*300,REASON_EFFECT) end function c32559361.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetOverlayGroup():IsExists(Card.IsCode,1,nil,1992816) end function c32559361.damcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,99,REASON_COST) local ct=Duel.GetOperatedGroup():GetCount() e:SetLabel(ct) end function c32559361.damtg2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local ct=e:GetLabel() Duel.SetTargetPlayer(1-tp) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ct*800) end function c32559361.damop2(e,tp,eg,ep,ev,re,r,rp) local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER) local ct=e:GetLabel() Duel.Damage(p,ct*800,REASON_EFFECT) end
gpl-2.0
anshkumar/yugioh-glaze
assets/script/c1639384.lua
3
2206
--神竜騎士フェルグラント function c1639384.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,8,2) c:EnableReviveLimit() --negate local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(1639384,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCost(c1639384.cost) e1:SetTarget(c1639384.target) e1:SetOperation(c1639384.operation) c:RegisterEffect(e1) end function c1639384.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c1639384.filter(c) return c:IsFaceup() end function c1639384.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c1639384.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c1639384.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c1639384.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) end function c1639384.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then Duel.NegateRelatedChain(tc,RESET_TURN_SET) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetValue(RESET_TURN_SET) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+RESET_END) tc:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_CANNOT_DISABLE) e3:SetRange(LOCATION_MZONE) e3:SetCode(EFFECT_IMMUNE_EFFECT) e3:SetValue(c1639384.efilter) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e3) end end function c1639384.efilter(e,te) return te:GetOwner()~=e:GetOwner() end
gpl-2.0
TurBoss/Zero-K-Infrastructure
ZeroKLobby_NET4.0/Benchmarker/Benchmarks/Configs/ZKL_default/LuaUI/Config/ZK_order.lua
12
4858
-- Widget Order List (0 disables a widget) return { ["AA Command Helper"] = 14, AdvPlayersList = 0, ["Ally Resource Bars"] = 0, AllyCursors = 59, AnimatorGUI = 0, ["Attack AoE"] = 50, ["Attack Warning"] = 55, ["Auto First Build Facing"] = 15, ["Auto Group"] = 53, ["Auto Patrol Nanos"] = 16, ["Auto Reclaim/Heal/Assist"] = 0, ["Auto Repair"] = 0, ["Auto Set Retreat @60"] = 0, ["Automatic Tip Dispenser"] = 0, Autoquit = 17, ["Ballistic Calculator"] = 0, ["Blast Radius"] = 18, BlobShadow = 0, ["BloomShader (v0.31) (unstable)"] = 0, BlurApi = 0, ["Bounty & Marketplace Icons (experimental)"] = 0, BuildETA = 12, ["Building Starter"] = 74, CALayout = 0, ["CEG Spawner"] = 0, CameraRecorder = 0, CameraShake = 19, ["Central Build AI"] = 0, ["Chat Shortcut"] = 0, ["Chili Chat 2.1"] = 68, ["Chili Chat Bubbles"] = 20, ["Chili Core Selector"] = 75, ["Chili Crude Player List"] = 69, ["Chili Deluxe Player List - Alpha 2.02"] = 0, ["Chili Docking"] = 70, ["Chili FactoryBar"] = 0, ["Chili Framework"] = 71, ["Chili Gesture Menu"] = 78, ["Chili Integral Menu"] = 80, ["Chili Keyboard Menu"] = 0, ["Chili Minimap"] = 3, ["Chili Radial Build Menu"] = 0, ["Chili Rejoining Progress Bar"] = 21, ["Chili Resource Bars"] = 22, ["Chili Selections & CursorTip"] = 23, ["Chili Vote Display"] = 11, ["Chili Widget Selector"] = 4, ChiliInspector = 0, ChiliProfiler = 0, ["Clippy Comments"] = 52, ["Cloak Fire State"] = 13, ["Cloaker Guard"] = 75, ComCounter = 24, ["Combo Overhead/Free Camera (experimental)"] = 0, ["Comm Marker"] = 0, ["Comm-n-Elo Startpos. Info"] = 0, CommandInsert = 60, ["Commander Name Tags "] = 0, ["Constructor Auto Assist"] = 25, ["Context Menu"] = 26, ["Custom Cursor Sets"] = 5, CustomFormations2 = 79, DCIcon = 0, Darkening = 27, ["Decoration Handler"] = 28, ["Defense Range Zero-K"] = 12345, ["Dev Commands"] = 0, ["Disable Mouse Toggle"] = 0, ["Display DPS"] = 0, ["Double-Click Fight"] = 0, ["Dynamic Avoidance System"] = 0, ["EPIC Menu"] = 2, ["Easy Facing"] = 0, ["External VR Grid"] = 0, ["FPS Log"] = 0, ["FPS Log direct"] = 49, ["Ferry Points"] = 29, ["Gadget Icons"] = 61, ["Ghost Site"] = 53, Halo = 0, HealthBars = 9, ["Hide map marks and cursor"] = 7, ["Highlight Geos"] = 30, IdleBuildersNEW = 0, ["Image Preloader"] = 74, ["Jumpjet GUI"] = 77, ["Keep Target"] = 31, ["Keybind Updater v0.9.4"] = 0, ["Lag (AFK) monitor"] = 72, ["Lasso Terraform GUI"] = 81, ["Local Team Colors"] = 6, ["Local Widgets Config"] = 32, LockCamera = 0, ["LogFlush Disabler"] = 12345, Lups = 73, LupsManager = 66, LupsStats = 0, ["Map Draw Blocker"] = 0, ["Map Edge Barrier"] = 0, ["Map Edge Extension"] = 33, MessageBoxes = 51, MetalFeatures = 34, ["Mex Placement Handler"] = 35, ["Mexspot Fetcher"] = 6, ["MiniMap Start Boxes"] = 12345, MinimapEvents = 36, ["Missile Silo Range"] = 37, ["Modular Comm Info"] = 13, ["Music Player"] = 38, ["News Ticker"] = 0, Night = 0, ["Nightvision Shader"] = 0, NoDuplicateOrders = 54, Noises = 8, Nubtron = 56, ["Nuke Button Zero-K"] = 0, Objectives = 52, Outline = 0, ["Pause Screen"] = 39, ["Persistent Build Spacing"] = 40, ["PlanetWars Info"] = 12345, ["Point Tracker"] = 41, ["Rank Icons 2"] = 62, ["Receive Units Indicator"] = 82, ReclaimInfo = 42, ["Replace Cloak Con Orders"] = 0, ["Replay control buttons"] = 12345, ["Resource Stat Writer"] = 0, ["Restricted Zones"] = 76, Retreat = 43, ["Select Keys"] = 53, ["Selection Send"] = 63, ["Selection Squares"] = 0, SelectionCircle = 0, ["Shared Functions"] = 1, ["Shield Guard"] = 64, ["Show All Commands"] = 0, ["Smart Nanos"] = 0, ["Smoke Signal"] = 0, SmoothScroll = 54, SpecRun = 0, ["Specialmap Hide Decals"] = 0, ["Specific Unit Reclaimer"] = 0, ["Spectate Selected Team"] = 44, Spotter = 0, ["Starlight Drawer"] = 0, ["Start Point Remover & Comm Selector"] = 58, ["Startup Info and Selector"] = 55, ["State Icons"] = 65, ["State Reverse Toggle"] = 45, Stereo3D = 46, Stockpiler = 56, ["Stuck Keys"] = 0, ["TeamCommEnds & Lavarise indicator"] = 13, TeamPlatter = 0, ["Test Version Warning"] = 0, ["Text To Speech Control"] = 47, ["Transport AI"] = 57, Transporting = 0, ["Unit Icons"] = 10, ["Unit Marker Zero-K"] = 12345, ["Unit Mover"] = 0, ["Unit Start State"] = 57, UnitGroups = 0, UnitNoStuckInFactory = 55, UnitShapes = 58, ["Units on Fire"] = 67, ["Vertical Line on Radar Dots"] = 0, ["Voice Assistant"] = 48, Voices = 0, WidgetProfiler = 0, Widget_Fps_Log = 49, XrayHaloSelections = 0, XrayShader = 0, chiliGUIDemo = 0, lastWidgetDetailLevel = 2, unit_waypoint_dragger = 0, version = 8, }
gpl-3.0
zwhfly/openwrt-luci
modules/niu/luasrc/controller/niu/traffic.lua
49
1218
--[[ LuCI - Lua Development Framework Copyright 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 require = require module "luci.controller.niu.traffic" function index() local toniu = {on_success_to={"niu"}} local e = entry({"niu", "traffic"}, alias("niu"), "Network Traffic", 30) e.niu_dbtemplate = "niu/traffic" e.niu_dbtasks = true e.niu_dbicon = "icons32/preferences-system-network.png" if fs.access("/etc/config/firewall") then entry({"niu", "traffic", "portfw"}, cbi("niu/traffic/portfw", toniu), "Manage Port Forwarding", 1) end if fs.access("/etc/config/qos") then entry({"niu", "traffic", "qos"}, cbi("niu/traffic/qos", toniu), "Manage Prioritization (QoS)", 2) end entry({"niu", "traffic", "routes"}, cbi("niu/traffic/routes", toniu), "Manage Traffic Routing", 30) entry({"niu", "traffic", "conntrack"}, call("cnntrck"), "Display Local Network Activity", 50) end function cnntrck() require "luci.template".render("niu/traffic/conntrack") end
apache-2.0
exch-bms2/beatoraja
skin/default/skinselect/skinselectmain.lua
1
12950
local function append_all(list, list1) for i, v in ipairs(list1) do table.insert(list, v) end end local property = { } local filepath = { } local header = { type = 9, name = "beatoraja default (lua)", w = 1280, h = 720, scene = 3000, input = 500, fadeout = 500, property = property, filepath = filepath } local function main() local skin = {} for k, v in pairs(header) do skin[k] = v end skin.source = { {id = 0, path = "../skinselect.png"}, } skin.font = { {id = 0, path = "../VL-Gothic-Regular.ttf"} } skin.image = { {id = "preview-bg", src = 0, x = 0, y = 664, w = 640, h = 360}, {id = "arrow-l", src = 0, x = 989, y = 0, w = 12, h = 12}, {id = "arrow-r", src = 0, x = 1001, y = 0, w = 12, h = 12}, {id = "arrow-l-active", src = 0, x = 989, y = 12, w = 12, h = 12}, {id = "arrow-r-active", src = 0, x = 1001, y = 12, w = 12, h = 12}, {id = "scroll-bg", src = 0, x = 1014, y = 0, w = 10, h = 251}, {id = "button-skin", src = 0, x = 640, y = 0, w = 0, h = 0, act = 190, click = 2}, {id = "button-custom-1", src = 0, x = 640, y = 10, w = 120, h = 48, act = 220, click = 2}, {id = "button-custom-2", src = 0, x = 640, y = 10, w = 120, h = 48, act = 221, click = 2}, {id = "button-custom-3", src = 0, x = 640, y = 10, w = 120, h = 48, act = 222, click = 2}, {id = "button-custom-4", src = 0, x = 640, y = 10, w = 120, h = 48, act = 223, click = 2}, {id = "button-custom-5", src = 0, x = 640, y = 10, w = 120, h = 48, act = 224, click = 2}, {id = "button-custom-6", src = 0, x = 640, y = 10, w = 120, h = 48, act = 225, click = 2}, {id = "type-off-5" , src = 0, x = 0, y = 0, w = 300, h = 30}, {id = "type-off-6" , src = 0, x = 0, y = 30, w = 300, h = 30}, {id = "type-off-7" , src = 0, x = 0, y = 60, w = 300, h = 30}, {id = "type-off-15" , src = 0, x = 0, y = 90, w = 300, h = 30}, {id = "type-off-10" , src = 0, x = 0, y = 120, w = 300, h = 30}, {id = "type-off-8" , src = 0, x = 0, y = 150, w = 300, h = 30}, {id = "type-off-9" , src = 0, x = 0, y = 180, w = 300, h = 30}, {id = "type-off-11" , src = 0, x = 0, y = 210, w = 300, h = 30}, {id = "type-off-0" , src = 0, x = 0, y = 240, w = 300, h = 30}, {id = "type-off-12" , src = 0, x = 0, y = 270, w = 300, h = 30}, {id = "type-off-2" , src = 0, x = 0, y = 300, w = 300, h = 30}, {id = "type-off-1" , src = 0, x = 0, y = 330, w = 300, h = 30}, {id = "type-off-13" , src = 0, x = 0, y = 360, w = 300, h = 30}, {id = "type-off-3" , src = 0, x = 0, y = 390, w = 300, h = 30}, {id = "type-off-4" , src = 0, x = 0, y = 420, w = 300, h = 30}, {id = "type-off-14" , src = 0, x = 0, y = 450, w = 300, h = 30}, {id = "type-off-16" , src = 0, x = 0, y = 480, w = 300, h = 30}, {id = "type-off-18" , src = 0, x = 0, y = 510, w = 300, h = 30}, {id = "type-off-17" , src = 0, x = 0, y = 540, w = 300, h = 30}, {id = "type-on-5" , src = 0, x = 300, y = 0, w = 300, h = 30}, {id = "type-on-6" , src = 0, x = 300, y = 30, w = 300, h = 30}, {id = "type-on-7" , src = 0, x = 300, y = 60, w = 300, h = 30}, {id = "type-on-15" , src = 0, x = 300, y = 90, w = 300, h = 30}, {id = "type-on-10" , src = 0, x = 300, y = 120, w = 300, h = 30}, {id = "type-on-8" , src = 0, x = 300, y = 150, w = 300, h = 30}, {id = "type-on-9" , src = 0, x = 300, y = 180, w = 300, h = 30}, {id = "type-on-11" , src = 0, x = 300, y = 210, w = 300, h = 30}, {id = "type-on-0" , src = 0, x = 300, y = 240, w = 300, h = 30}, {id = "type-on-12" , src = 0, x = 300, y = 270, w = 300, h = 30}, {id = "type-on-2" , src = 0, x = 300, y = 300, w = 300, h = 30}, {id = "type-on-1" , src = 0, x = 300, y = 330, w = 300, h = 30}, {id = "type-on-13" , src = 0, x = 300, y = 360, w = 300, h = 30}, {id = "type-on-3" , src = 0, x = 300, y = 390, w = 300, h = 30}, {id = "type-on-4" , src = 0, x = 300, y = 420, w = 300, h = 30}, {id = "type-on-14" , src = 0, x = 300, y = 450, w = 300, h = 30}, {id = "type-on-16" , src = 0, x = 300, y = 480, w = 300, h = 30}, {id = "type-on-18" , src = 0, x = 300, y = 510, w = 300, h = 30}, {id = "type-on-17" , src = 0, x = 300, y = 540, w = 300, h = 30}, } skin.imageset = { {id = "type-0" , images = {"type-off-0", "type-on-0"}, act = 170, ref = 170}, {id = "type-1" , images = {"type-off-1", "type-on-1"}, act = 171, ref = 171}, {id = "type-2" , images = {"type-off-2", "type-on-2"}, act = 172, ref = 172}, {id = "type-3" , images = {"type-off-3", "type-on-3"}, act = 173, ref = 173}, {id = "type-4" , images = {"type-off-4", "type-on-4"}, act = 174, ref = 174}, {id = "type-5" , images = {"type-off-5", "type-on-5"}, act = 175, ref = 175}, {id = "type-6" , images = {"type-off-6", "type-on-6"}, act = 176, ref = 176}, {id = "type-7" , images = {"type-off-7", "type-on-7"}, act = 177, ref = 177}, {id = "type-8" , images = {"type-off-8", "type-on-8"}, act = 178, ref = 178}, {id = "type-9" , images = {"type-off-9", "type-on-9"}, act = 179, ref = 179}, {id = "type-10" , images = {"type-off-10", "type-on-10"}, act = 180, ref = 180}, {id = "type-11" , images = {"type-off-11", "type-on-11"}, act = 181, ref = 181}, {id = "type-12" , images = {"type-off-12", "type-on-12"}, act = 182, ref = 182}, {id = "type-13" , images = {"type-off-13", "type-on-13"}, act = 183, ref = 183}, {id = "type-14" , images = {"type-off-14", "type-on-14"}, act = 184, ref = 184}, {id = "type-15" , images = {"type-off-15", "type-on-15"}, act = 185, ref = 185}, {id = "type-16" , images = {"type-off-16", "type-on-16"}, act = 386, ref = 386}, {id = "type-17" , images = {"type-off-17", "type-on-17"}, act = 387, ref = 387}, {id = "type-18" , images = {"type-off-18", "type-on-18"}, act = 388, ref = 388}, } skin.value = {} skin.text = { {id = "skin-name", font = 0, size = 24, align = 1, ref = 50}, {id = "custom-label-1", font = 0, size = 24, align = 2, ref = 100}, {id = "custom-label-2", font = 0, size = 24, align = 2, ref = 101}, {id = "custom-label-3", font = 0, size = 24, align = 2, ref = 102}, {id = "custom-label-4", font = 0, size = 24, align = 2, ref = 103}, {id = "custom-label-5", font = 0, size = 24, align = 2, ref = 104}, {id = "custom-label-6", font = 0, size = 24, align = 2, ref = 105}, {id = "custom-value-1", font = 0, size = 24, align = 1, ref = 110}, {id = "custom-value-2", font = 0, size = 24, align = 1, ref = 111}, {id = "custom-value-3", font = 0, size = 24, align = 1, ref = 112}, {id = "custom-value-4", font = 0, size = 24, align = 1, ref = 113}, {id = "custom-value-5", font = 0, size = 24, align = 1, ref = 114}, {id = "custom-value-6", font = 0, size = 24, align = 1, ref = 115}, } skin.slider = { {id = "scroll-fg", src = 0, x = 1007, y = 252, w = 17, h = 24, angle = 2, range = 232, type = 7}, } skin.destination = { {id = "button-skin", dst = { {x = 450, y = 350, w = 680, h = 360}, }}, {id = "preview-bg", dst = { {x = 470, y = 350, w = 640, h = 360}, }}, {id = "skin-name", dst = { {x = 790, y = 310, w = 640, h = 24}, }}, {id = "arrow-l", dst = { {x = 448, y = 514, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1120, y = 514, w = 12, h = 12}, }}, {id = "arrow-l-active", dst = { {x = 448, y = 514, w = 12, h = 12} }, mouseRect = {x = 2, y = -164, w = 340, h = 360}}, {id = "arrow-r-active", dst = { {x = 1120, y = 514, w = 12, h = 12} }, mouseRect = {x = -330, y = -164, w = 340, h = 360}}, {id = "button-custom-1", dst = { {x = 780, y = 252, w = 440, h = 48}, }}, {id = "button-custom-2", dst = { {x = 780, y = 204, w = 440, h = 48}, }}, {id = "button-custom-3", dst = { {x = 780, y = 156, w = 440, h = 48}, }}, {id = "button-custom-4", dst = { {x = 780, y = 108, w = 440, h = 48}, }}, {id = "button-custom-5", dst = { {x = 780, y = 60, w = 440, h = 48}, }}, {id = "button-custom-6", dst = { {x = 780, y = 12, w = 440, h = 48}, }}, {id = "custom-label-1", dst = { {x = 720, y = 264, w = 400, h = 24}, }}, {id = "custom-label-2", dst = { {x = 720, y = 216, w = 400, h = 24}, }}, {id = "custom-label-3", dst = { {x = 720, y = 168, w = 400, h = 24}, }}, {id = "custom-label-4", dst = { {x = 720, y = 120, w = 400, h = 24}, }}, {id = "custom-label-5", dst = { {x = 720, y = 72, w = 400, h = 24}, }}, {id = "custom-label-6", dst = { {x = 720, y = 24, w = 400, h = 24}, }}, {id = "custom-value-1", dst = { {x = 1000, y = 264, w = 400, h = 24}, }}, {id = "custom-value-2", dst = { {x = 1000, y = 216, w = 400, h = 24}, }}, {id = "custom-value-3", dst = { {x = 1000, y = 168, w = 400, h = 24}, }}, {id = "custom-value-4", dst = { {x = 1000, y = 120, w = 400, h = 24}, }}, {id = "custom-value-5", dst = { {x = 1000, y = 72, w = 400, h = 24}, }}, {id = "custom-value-6", dst = { {x = 1000, y = 24, w = 400, h = 24}, }}, {id = "arrow-l", dst = { {x = 788, y = 270, w = 12, h = 12}, }}, {id = "arrow-l", dst = { {x = 788, y = 222, w = 12, h = 12}, }}, {id = "arrow-l", dst = { {x = 788, y = 174, w = 12, h = 12}, }}, {id = "arrow-l", dst = { {x = 788, y = 126, w = 12, h = 12}, }}, {id = "arrow-l", dst = { {x = 788, y = 78, w = 12, h = 12}, }}, {id = "arrow-l", dst = { {x = 788, y = 30, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1200, y = 270, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1200, y = 222, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1200, y = 174, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1200, y = 126, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1200, y = 78, w = 12, h = 12}, }}, {id = "arrow-r", dst = { {x = 1200, y = 30, w = 12, h = 12}, }}, {id = "arrow-l-active", dst = { {x = 788, y = 270, w = 12, h = 12}, }, mouseRect = {x = -8, y = -18, w = 220, h = 48}}, {id = "arrow-l-active", dst = { {x = 788, y = 222, w = 12, h = 12}, }, mouseRect = {x = -8, y = -18, w = 220, h = 48}}, {id = "arrow-l-active", dst = { {x = 788, y = 174, w = 12, h = 12}, }, mouseRect = {x = -8, y = -18, w = 220, h = 48}}, {id = "arrow-l-active", dst = { {x = 788, y = 126, w = 12, h = 12}, }, mouseRect = {x = -8, y = -18, w = 220, h = 48}}, {id = "arrow-l-active", dst = { {x = 788, y = 78, w = 12, h = 12}, }, mouseRect = {x = -8, y = -18, w = 220, h = 48}}, {id = "arrow-l-active", dst = { {x = 788, y = 30, w = 12, h = 12}, }, mouseRect = {x = -8, y = -18, w = 220, h = 48}}, {id = "arrow-r-active", dst = { {x = 1200, y = 270, w = 12, h = 12}, }, mouseRect = {x = -200, y = -18, w = 220, h = 48}}, {id = "arrow-r-active", dst = { {x = 1200, y = 222, w = 12, h = 12}, }, mouseRect = {x = -200, y = -18, w = 220, h = 48}}, {id = "arrow-r-active", dst = { {x = 1200, y = 174, w = 12, h = 12}, }, mouseRect = {x = -200, y = -18, w = 220, h = 48}}, {id = "arrow-r-active", dst = { {x = 1200, y = 126, w = 12, h = 12}, }, mouseRect = {x = -200, y = -18, w = 220, h = 48}}, {id = "arrow-r-active", dst = { {x = 1200, y = 78, w = 12, h = 12}, }, mouseRect = {x = -200, y = -18, w = 220, h = 48}}, {id = "arrow-r-active", dst = { {x = 1200, y = 30, w = 12, h = 12}, }, mouseRect = {x = -200, y = -18, w = 220, h = 48}}, {id = "scroll-bg", dst = { {x = 1260, y = 24, w = 10, h = 264}, }}, {id = "scroll-fg", blend = 2, dst = { {x = 1256, y = 260, w = 17, h = 24}, }}, {id = "type-5", dst = { {x = 0, y = 630, w = 300, h = 30}, }}, {id = "type-6", dst = { {x = 0, y = 600, w = 300, h = 30}, }}, {id = "type-7", dst = { {x = 0, y = 570, w = 300, h = 30}, }}, {id = "type-15", dst = { {x = 0, y = 540, w = 300, h = 30}, }}, {id = "type-10", dst = { {x = 0, y = 510, w = 300, h = 30}, }}, {id = "type-8", dst = { {x = 0, y = 480, w = 300, h = 30}, }}, {id = "type-9", dst = { {x = 0, y = 450, w = 300, h = 30}, }}, {id = "type-11", dst = { {x = 0, y = 420, w = 300, h = 30}, }}, {id = "type-0", dst = { {x = 0, y = 360, w = 300, h = 30}, }}, {id = "type-12", dst = { {x = 0, y = 330, w = 300, h = 30}, }}, {id = "type-2", dst = { {x = 0, y = 300, w = 300, h = 30}, }}, {id = "type-1", dst = { {x = 0, y = 270, w = 300, h = 30}, }}, {id = "type-13", dst = { {x = 0, y = 240, w = 300, h = 30}, }}, {id = "type-3", dst = { {x = 0, y = 210, w = 300, h = 30}, }}, {id = "type-4", dst = { {x = 0, y = 180, w = 300, h = 30}, }}, {id = "type-14", dst = { {x = 0, y = 150, w = 300, h = 30}, }}, {id = "type-16", dst = { {x = 0, y = 120, w = 300, h = 30}, }}, {id = "type-18", dst = { {x = 0, y = 90, w = 300, h = 30}, }}, {id = "type-17", dst = { {x = 0, y = 60, w = 300, h = 30}, }}, } skin.skinSelect = { defaultType = 6, customOffsetStyle = 0, customPropertyCount = 6, sampleBMS = {} } return skin end return { header = header, main = main }
gpl-3.0
anshkumar/yugioh-glaze
assets/script/c5050644.lua
3
2668
--アロマガーデン function c5050644.initial_effect(c) --activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --recover 1 local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_RECOVER+CATEGORY_ATKCHANGE+CATEGORY_DEFCHANGE) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_FZONE) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetCountLimit(1) e2:SetCondition(c5050644.recon1) e2:SetTarget(c5050644.retg1) e2:SetOperation(c5050644.reop1) c:RegisterEffect(e2) --recover 2 local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_RECOVER) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e3:SetCode(EVENT_TO_GRAVE) e3:SetRange(LOCATION_FZONE) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetCondition(c5050644.recon2) e3:SetTarget(c5050644.retg2) e3:SetOperation(c5050644.reop2) c:RegisterEffect(e3) end function c5050644.cfilter1(c) return c:IsFaceup() and c:IsSetCard(0xc9) end function c5050644.recon1(e,tp,eg,ep,ev,re,r,rp) return Duel.IsExistingMatchingCard(c5050644.cfilter1,tp,LOCATION_MZONE,0,1,nil) end function c5050644.retg1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(500) Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,500) end function c5050644.reop1(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Recover(p,d,REASON_EFFECT) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetTargetRange(LOCATION_MZONE,0) e1:SetValue(500) e1:SetReset(RESET_PHASE+RESET_END+RESET_OPPO_TURN) Duel.RegisterEffect(e1,tp) local e2=e1:Clone() e2:SetCode(EFFECT_UPDATE_DEFENCE) Duel.RegisterEffect(e2,tp) end function c5050644.cfilter2(c,tp) return c:IsSetCard(0xc9) and c:IsReason(REASON_DESTROY) and c:IsReason(REASON_BATTLE+REASON_EFFECT) and c:GetPreviousControler()==tp and c:IsPreviousLocation(LOCATION_MZONE) and c:IsPreviousPosition(POS_FACEUP) end function c5050644.recon2(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c5050644.cfilter2,1,nil,tp) end function c5050644.retg2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsRelateToEffect(e) end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,1000) end function c5050644.reop2(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Recover(p,d,REASON_EFFECT) end
gpl-2.0
freifunk-gluon/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk/dialzones.lua
91
3529
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: trunks.lua 4025 2009-01-11 23:37:21Z jow $ ]]-- local ast = require("luci.asterisk") local uci = require("luci.model.uci").cursor() --[[ Dialzone overview table ]] if not arg[1] then zonemap = Map("asterisk", "Dial Zones", [[ Dial zones hold patterns of dialed numbers to match. Each zone has one or more trunks assigned. If the first trunk is congested, Asterisk will try to use the next available connection. If all trunks fail, then the following zones in the parent dialplan are tried. ]]) local zones, znames = ast.dialzone.zones() zonetbl = zonemap:section(Table, zones, "Zone Overview") zonetbl.sectionhead = "Zone" zonetbl.addremove = true zonetbl.anonymous = false zonetbl.extedit = luci.dispatcher.build_url( "admin", "asterisk", "dialplans", "zones", "%s" ) function zonetbl.cfgsections(self) return znames end function zonetbl.parse(self) for k, v in pairs(self.map:formvaluetable( luci.cbi.REMOVE_PREFIX .. self.config ) or {}) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end uci:delete("asterisk", k) uci:save("asterisk") self.data[k] = nil for i = 1,#znames do if znames[i] == k then table.remove(znames, i) break end end end Table.parse(self) end zonetbl:option(DummyValue, "description", "Description") zonetbl:option(DummyValue, "addprefix") match = zonetbl:option(DummyValue, "matches") function match.cfgvalue(self, s) return table.concat(zones[s].matches, ", ") end trunks = zonetbl:option(DummyValue, "trunk") trunks.template = "asterisk/cbi/cell" function trunks.cfgvalue(self, s) return ast.tools.hyperlinks(zones[s].trunks) end return zonemap --[[ Zone edit form ]] else zoneedit = Map("asterisk", "Edit Dialzone") entry = zoneedit:section(NamedSection, arg[1]) entry.title = "Zone %q" % arg[1]; back = entry:option(DummyValue, "_overview", "Back to dialzone overview") back.value = "" back.titleref = luci.dispatcher.build_url( "admin", "asterisk", "dialplans", "zones" ) desc = entry:option(Value, "description", "Description") function desc.cfgvalue(self, s, ...) return Value.cfgvalue(self, s, ...) or s end trunks = entry:option(MultiValue, "uses", "Used trunks") trunks.widget = "checkbox" uci:foreach("asterisk", "sip", function(s) if s.provider == "yes" then trunks:value( "SIP/%s" % s['.name'], "SIP/%s (%s)" %{ s['.name'], s.host or 'n/a' } ) end end) match = entry:option(DynamicList, "match", "Number matches") intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)") aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)") ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)") lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers") lzone:value("", "no special treatment of local numbers") for _, z in ipairs(ast.dialzone.zones()) do lzone:value(z.name, "%q (%s)" %{ z.name, z.description }) end --for _, v in ipairs(find_outgoing_contexts(zoneedit.uci)) do -- lzone:value(unpack(v)) --end lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)") return zoneedit end
apache-2.0
zhaoxin54430/zhaoxin_test
src_routing/bird-openwrt/bird4-openwrt/src/model/overview.lua
7
2745
--[[ Copyright (C) 2014 - Eloi Carbó Solé (GSoC2014) BGP/Bird integration with OpenWRT and QMP 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/>. ]]-- require("luci.sys") local http = require "luci.http" local uci = require "luci.model.uci" local uciout = uci.cursor() m=Map("bird4", "Bird4 UCI configuration helper", "") -- Named section: "bird" s_bird_uci = m:section(NamedSection, "bird", "bird", "Bird4 file settings", "") s_bird_uci.addremove = False uuc = s_bird_uci:option(Flag, "use_UCI_config", "Use UCI configuration", "Use UCI configuration instead of the /etc/bird4.conf file") ucf = s_bird_uci:option(Value, "UCI_config_File", "UCI File", "Specify the file to place the UCI-translated configuration") ucf.default = "/tmp/bird4.conf" -- Named Section: "table" s_bird_table = m:section(TypedSection, "table", "Tables configuration", "Configuration of the tables used in the protocols") s_bird_table.addremove = true s_bird_table.anonymous = true name = s_bird_table:option(Value, "name", "Table name", "Descriptor ID of the table") -- Named section: "global" s_bird_global = m:section(NamedSection, "global", "global", "Global options", "Basic Bird4 settings") s_bird_global.addremove = False id = s_bird_global:option(Value, "router_id", "Router ID", "Identification number of the router. By default, is the router's IP.") lf = s_bird_global:option(Value, "log_file", "Log File", "File used to store log related data.") l = s_bird_global:option(MultiValue, "log", "Log", "Set which elements do you want to log.") l:value("all", "All") l:value("info", "Info") l:value("warning","Warning") l:value("error","Error") l:value("fatal","Fatal") l:value("debug","Debug") l:value("trace","Trace") l:value("remote","Remote") l:value("auth","Auth") d = s_bird_global:option(MultiValue, "debug", "Debug", "Set which elements do you want to debug.") d:value("all", "All") d:value("states","States") d:value("routes","Routes") d:value("filters","Filters") d:value("interfaces","Interfaces") d:value("events","Events") d:value("packets","Packets") function m.on_commit(self,map) luci.sys.call('/etc/init.d/bird4 stop; /etc/init.d/bird4 start') end return m
gpl-2.0
anshkumar/yugioh-glaze
assets/script/c5373478.lua
5
1816
--サイバー・ドラゴン・ツヴァイ function c5373478.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCondition(c5373478.atkcon) e1:SetValue(300) c:RegisterEffect(e1) --change code local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(5373478,0)) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetCost(c5373478.cost) e2:SetOperation(c5373478.cdop) c:RegisterEffect(e2) --code local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CHANGE_CODE) e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e3:SetRange(LOCATION_GRAVE) e3:SetValue(70095154) c:RegisterEffect(e3) end function c5373478.atkcon(e) local phase=Duel.GetCurrentPhase() return (phase==PHASE_DAMAGE or phase==PHASE_DAMAGE_CAL) and Duel.GetAttacker()==e:GetHandler() and Duel.GetAttackTarget()~=nil end function c5373478.costfilter(c) return c:IsType(TYPE_SPELL) and not c:IsPublic() end function c5373478.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c5373478.costfilter,tp,LOCATION_HAND,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM) local g=Duel.SelectMatchingCard(tp,c5373478.costfilter,tp,LOCATION_HAND,0,1,1,nil) Duel.ConfirmCards(1-tp,g) Duel.ShuffleHand(tp) end function c5373478.cdop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsFacedown() or not c:IsRelateToEffect(e) then return end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_CODE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(70095154) c:RegisterEffect(e1) end
gpl-2.0
mikeller/nodemcu-firmware
lua_modules/redis/redis.lua
86
2621
------------------------------------------------------------------------------ -- Redis client module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- local redis = dofile("redis.lua").connect(host, port) -- redis:publish("chan1", foo") -- redis:subscribe("chan1", function(channel, msg) print(channel, msg) end) ------------------------------------------------------------------------------ local M do -- const local REDIS_PORT = 6379 -- cache local pairs, tonumber = pairs, tonumber -- local publish = function(self, chn, s) self._fd:send(("*3\r\n$7\r\npublish\r\n$%d\r\n%s\r\n$%d\r\n%s\r\n"):format( #chn, chn, #s, s )) -- TODO: confirmation? then queue of answers needed end local subscribe = function(self, chn, handler) -- TODO: subscription to all channels, with single handler self._fd:send(("*2\r\n$9\r\nsubscribe\r\n$%d\r\n%s\r\n"):format( #chn, chn )) self._handlers[chn] = handler -- TODO: confirmation? then queue of answers needed end local unsubscribe = function(self, chn) self._handlers[chn] = false end -- NB: pity we can not just augment what net.createConnection returns local close = function(self) self._fd:close() end local connect = function(host, port) local _fd = net.createConnection(net.TCP, 0) local self = { _fd = _fd, _handlers = { }, -- TODO: consider metatables? close = close, publish = publish, subscribe = subscribe, unsubscribe = unsubscribe, } _fd:on("connection", function() --print("+FD") end) _fd:on("disconnection", function() -- FIXME: this suddenly occurs. timeout? --print("-FD") end) _fd:on("receive", function(fd, s) --print("IN", s) -- TODO: subscription to all channels -- lookup message pattern to determine channel and payload -- NB: pairs() iteration gives no fixed order! for chn, handler in pairs(self._handlers) do local p = ("*3\r\n$7\r\nmessage\r\n$%d\r\n%s\r\n$"):format(#chn, chn) if s:find(p, 1, true) then -- extract and check message length -- NB: only the first TCP packet considered! local _, start, len = s:find("(%d-)\r\n", #p) if start and tonumber(len) == #s - start - 2 and handler then handler(chn, s:sub(start + 1, -2)) -- ends with \r\n end end end end) _fd:connect(port or REDIS_PORT, host) return self end -- expose M = { connect = connect, } end return M
mit
anshkumar/yugioh-glaze
assets/script/c95286165.lua
3
1816
--融合解除 function c95286165.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TODECK+CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c95286165.target) e1:SetOperation(c95286165.activate) c:RegisterEffect(e1) end function c95286165.filter(c) return c:IsFaceup() and c:IsType(TYPE_FUSION) and c:IsAbleToExtra() end function c95286165.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c95286165.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c95286165.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectTarget(tp,c95286165.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0) end function c95286165.mgfilter(c,e,tp,fusc) return not c:IsControler(tp) or not c:IsLocation(LOCATION_GRAVE) or bit.band(c:GetReason(),0x40008)~=0x40008 or c:GetReasonCard()~=fusc or not c:IsCanBeSpecialSummoned(e,0,tp,false,false) or c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c95286165.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if not (tc:IsRelateToEffect(e) and tc:IsFaceup()) then return end local mg=tc:GetMaterial() local sumable=true local sumtype=tc:GetSummonType() if Duel.SendtoDeck(tc,nil,0,REASON_EFFECT)==0 or bit.band(sumtype,SUMMON_TYPE_FUSION)~=SUMMON_TYPE_FUSION or mg:GetCount()==0 or mg:GetCount()>Duel.GetLocationCount(tp,LOCATION_MZONE) or mg:IsExists(c95286165.mgfilter,1,nil,e,tp,tc) then sumable=false end if sumable and Duel.SelectYesNo(tp,aux.Stringid(95286165,0)) then Duel.BreakEffect() Duel.SpecialSummon(mg,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
adan830/UpAndAway
code/brains/gummybearbrain.lua
2
3200
BindGlobal() local CFG = TheMod:GetConfig() require "behaviours/chaseandattack" require "behaviours/runaway" require "behaviours/wander" require "behaviours/doaction" require "behaviours/avoidlight" require "behaviours/panic" require "behaviours/attackwall" require "behaviours/useshield" local GummyBearBrain = Class(Brain, function(self, inst) Brain._ctor(self, inst) end) local function EatFoodAction(inst) local target = FindEntity(inst, CFG.GUMMYBEAR.SEE_FOOD_DIST, function(item) return inst.components.eater:CanEat(item) and item:IsOnValidGround() end) if target then return BufferedAction(inst, target, ACTIONS.EAT) end end local function GoHomeAction(inst) if inst.components.homeseeker and inst.components.homeseeker.home and inst.components.homeseeker.home:IsValid() and inst.components.homeseeker.home.components.childspawner then return BufferedAction(inst, inst.components.homeseeker.home, ACTIONS.GOHOME) end end local function InvestigateAction(inst) local investigatePos = inst.components.knownlocations and inst.components.knownlocations:GetLocation("investigate") if investigatePos then return BufferedAction(inst, nil, ACTIONS.INVESTIGATE, nil, investigatePos, nil, 1) end end local function GetFaceTargetFn(inst) return inst.components.follower.leader end local function KeepFaceTargetFn(inst, target) return inst.components.follower.leader == target end function GummyBearBrain:OnStart() local root = PriorityNode( { WhileNode( function() return self.inst.components.health.takingfiredamage end, "OnFire", Panic(self.inst)), IfNode(function() return self.inst:HasTag("spider_hider") end, "IsHider", UseShield(self.inst, CFG.GUMMYBEAR.DAMAGE_UNTIL_SHIELD, CFG.GUMMYBEAR.SHIELD_TIME, CFG.GUMMYBEAR.AVOID_PROJECTILE_ATTACKS)), AttackWall(self.inst), ChaseAndAttack(self.inst, CFG.GUMMYBEAR.MAX_CHASE_TIME), DoAction(self.inst, function() return EatFoodAction(self.inst) end ), Follow(self.inst, function() return self.inst.components.follower.leader end, CFG.GUMMYBEAR.MIN_FOLLOW_DIST, CFG.GUMMYBEAR.TARGET_FOLLOW_DIST, CFG.GUMMYBEAR.MAX_FOLLOW_DIST), IfNode(function() return self.inst.components.follower.leader ~= nil end, "HasLeader", FaceEntity(self.inst, GetFaceTargetFn, KeepFaceTargetFn )), DoAction(self.inst, function() return InvestigateAction(self.inst) end ), -- WhileNode(function() return not GetPseudoClock():IsDay() end, "IsDay", --DoAction(self.inst, function() return GoHomeAction(self.inst) end ) ), Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, CFG.GUMMYBEAR.MAX_WANDER_DIST) },1) self.bt = BT(self.inst, root) end function GummyBearBrain:OnInitializationComplete() self.inst.components.knownlocations:RememberLocation("home", Point(self.inst.Transform:GetWorldPosition())) end return GummyBearBrain
gpl-2.0
fmidev/himan
himan-scripts/LVP.lua
1
1328
logger:Info("Calculating LVP (Low Visibility Procedures) probability") local Missing = missingf local probLVP = {} local producer = configuration:GetSourceProducer(0) local ensSize = tonumber(radon:GetProducerMetaData(producer, "ensemble size")) if not ensSize then logger.Error("Ensemble size not found from database for producer " .. producer:GetId()) return end local ens1 = lagged_ensemble(param("VV2-M"), "MEPS_LAGGED_ENSEMBLE", ensSize) local ens2 = lagged_ensemble(param("CEIL-2-M"), "MEPS_LAGGED_ENSEMBLE", ensSize) ens1:Fetch(configuration, current_time, current_level) ens2:Fetch(configuration, current_time, current_level) local lagEnsSize = ens1:Size() ens1:ResetLocation() ens2:ResetLocation() local i = 0 while ens1:NextLocation() and ens2:NextLocation() do i = i+1 local vals1 = ens1:Values() local vals2 = ens2:Values() local numLVP = 0 probLVP[i] = Missing for j = 1, #vals1 do local val1 = vals1[j] local val2 = vals2[j] * 3.2808 if val1 < 600 or val2 <= 200 then numLVP = numLVP + 1 end end probLVP[i] = numLVP / lagEnsSize end local probParam = param("PROB-LVP-1") result:SetForecastType(forecast_type(HPForecastType.kStatisticalProcessing)) result:SetParam(probParam) result:SetValues(probLVP) luatool:WriteToFile(result)
mit
Tiger66639/premake-core
tests/actions/vstudio/vc2010/test_globals.lua
2
4633
-- -- tests/actions/vstudio/vc2010/test_globals.lua -- Validate generation of the Globals property group. -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_vs2010_globals") local vc2010 = premake.vstudio.vc2010 -- -- Setup -- local sln, prj function suite.setup() _ACTION = "vs2010" sln = test.createsolution() end local function prepare() prj = premake.solution.getproject(sln, 1) vc2010.globals(prj) end -- -- Check the structure with the default project values. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> ]] end -- -- Ensure CLR support gets enabled for Managed C++ projects. -- function suite.keywordIsCorrect_onManagedC() clr "On" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <TargetFrameworkVersion>v4.0</TargetFrameworkVersion> <Keyword>ManagedCProj</Keyword> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> ]] end -- -- Ensure custom target framework version correct for Managed C++ projects. -- function suite.frameworkVersionIsCorrect_onSpecificVersion() clr "On" framework "4.5" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <Keyword>ManagedCProj</Keyword> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> ]] end function suite.frameworkVersionIsCorrect_on2013() _ACTION = "vs2013" clr "On" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <IgnoreWarnCompileDuplicatedFilename>true</IgnoreWarnCompileDuplicatedFilename> <TargetFrameworkVersion>v4.5</TargetFrameworkVersion> <Keyword>ManagedCProj</Keyword> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> ]] end -- -- Omit Keyword and RootNamespace for non-Windows projects. -- function suite.noKeyword_onNotWindows() system "Linux" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> </PropertyGroup> ]] end -- -- Include Keyword and RootNamespace for mixed system projects. -- function suite.includeKeyword_onMixedConfigs() filter "Debug" system "Windows" filter "Release" system "Linux" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> ]] end -- -- Makefile projects set new keyword and drop the root namespace. -- function suite.keywordIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <Keyword>MakeFileProj</Keyword> </PropertyGroup> ]] end function suite.keywordIsCorrect_onNone() kind "None" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <Keyword>MakeFileProj</Keyword> </PropertyGroup> ]] end --- -- If the project name differs from the project filename, output a -- <ProjectName> element to indicate that. --- function suite.addsFilename_onDifferentFilename() filename "MyProject_2012" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <Keyword>Win32Proj</Keyword> <RootNamespace>MyProject</RootNamespace> <ProjectName>MyProject</ProjectName> </PropertyGroup> ]] end -- -- VS 2013 adds the <IgnoreWarnCompileDuplicatedFilename> to get rid -- of spurious warnings when the same filename is present in different -- configurations. -- function suite.structureIsCorrect_on2013() _ACTION = "vs2013" prepare() test.capture [[ <PropertyGroup Label="Globals"> <ProjectGuid>{42B5DBC6-AE1F-903D-F75D-41E363076E92}</ProjectGuid> <IgnoreWarnCompileDuplicatedFilename>true</IgnoreWarnCompileDuplicatedFilename> <Keyword>Win32Proj</Keyword> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> ]] end
bsd-3-clause
anshkumar/yugioh-glaze
assets/script/c68670547.lua
9
1286
--闇竜の黒騎士 function c68670547.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(68670547,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetTarget(c68670547.sptg) e1:SetOperation(c68670547.spop) c:RegisterEffect(e1) end function c68670547.filter(c,e,tp) return c:IsLevelBelow(4) and c:IsRace(RACE_ZOMBIE) and c:IsReason(REASON_BATTLE) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c68670547.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(1-tp) and c68670547.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c68670547.filter,tp,0,LOCATION_GRAVE,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c68670547.filter,tp,0,LOCATION_GRAVE,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c68670547.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsRace(RACE_ZOMBIE) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
Dith3r/FrameworkBenchmarks
frameworks/Lua/lapis/web.lua
72
5957
local lapis = require("lapis") local db = require("lapis.db") local Model do local _obj_0 = require("lapis.db.model") Model = _obj_0.Model end local config do local _obj_0 = require("lapis.config") config = _obj_0.config end local insert do local _obj_0 = table insert = _obj_0.insert end local sort do local _obj_0 = table sort = _obj_0.sort end local min, random do local _obj_0 = math min, random = _obj_0.min, _obj_0.random end local Fortune do local _parent_0 = Model local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "Fortune", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end Fortune = _class_0 end local World do local _parent_0 = Model local _base_0 = { } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "World", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end World = _class_0 end local Benchmark do local _parent_0 = lapis.Application local _base_0 = { ["/"] = function(self) return { json = { message = "Hello, World!" } } end, ["/db"] = function(self) local w = World:find(random(1, 10000)) return { json = { id = w.id, randomNumber = w.randomnumber } } end, ["/queries"] = function(self) local num_queries = tonumber(self.params.queries) or 1 if num_queries < 2 then local w = World:find(random(1, 10000)) return { json = { { id = w.id, randomNumber = w.randomnumber } } } end local worlds = { } num_queries = min(500, num_queries) for i = 1, num_queries do local w = World:find(random(1, 10000)) insert(worlds, { id = w.id, randomNumber = w.randomnumber }) end return { json = worlds } end, ["/fortunes"] = function(self) self.fortunes = Fortune:select("") insert(self.fortunes, { id = 0, message = "Additional fortune added at request time." }) sort(self.fortunes, function(a, b) return a.message < b.message end) return { layout = false }, self:html(function() raw('<!DOCTYPE HTML>') return html(function() head(function() return title("Fortunes") end) return body(function() return element("table", function() tr(function() th(function() return text("id") end) return th(function() return text("message") end) end) local _list_0 = self.fortunes for _index_0 = 1, #_list_0 do local fortune = _list_0[_index_0] tr(function() td(function() return text(fortune.id) end) return td(function() return text(fortune.message) end) end) end end) end) end) end) end, ["/update"] = function(self) local num_queries = tonumber(self.params.queries) or 1 if num_queries == 0 then num_queries = 1 end local worlds = { } num_queries = min(500, num_queries) for i = 1, num_queries do local wid = random(1, 10000) local world = World:find(wid) world.randomnumber = random(1, 10000) world:update("randomnumber") insert(worlds, { id = world.id, randomNumber = world.randomnumber }) end if num_queries < 2 then return { json = { worlds[1] } } end return { json = worlds } end, ["/plaintext"] = function(self) return { content_type = "text/plain", layout = false }, "Hello, World!" end } _base_0.__index = _base_0 setmetatable(_base_0, _parent_0.__base) local _class_0 = setmetatable({ __init = function(self, ...) return _parent_0.__init(self, ...) end, __base = _base_0, __name = "Benchmark", __parent = _parent_0 }, { __index = function(cls, name) local val = rawget(_base_0, name) if val == nil then return _parent_0[name] else return val end end, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 if _parent_0.__inherited then _parent_0.__inherited(_parent_0, _class_0) end Benchmark = _class_0 return _class_0 end
bsd-3-clause
shirat74/sile
lua-libraries/std/tree.lua
6
6900
--[[-- Tree container. Derived from @{std.container}, and inherits Container's metamethods. Note that Functions listed below are only available from the Tree prototype return by requiring this module, because Container objects cannot have object methods. @classmod std.tree @see std.container ]] local base = require "std.base" local Container = require "std.container" local List = require "std.list" local func = require "std.functional" local prototype = (require "std.object").prototype local Tree -- forward declaration --- Tree iterator which returns just numbered leaves, in order. -- @function ileaves -- @static -- @tparam tree|table tr tree or tree-like table -- @treturn function iterator function -- @treturn tree|table the tree `tr` local ileaves = base.ileaves --- Tree iterator which returns just leaves. -- @function leaves -- @static -- @tparam tree|table tr tree or tree-like table -- @treturn function iterator function -- @treturn tree|table the tree, `tr` local leaves = base.leaves --- Make a deep copy of a tree, including any metatables. -- -- To make fast shallow copies, use @{std.table.clone}. -- @tparam table|tree t table or tree to be cloned -- @tparam boolean nometa if non-nil don't copy metatables -- @treturn table|tree a deep copy of `t` local function clone (t, nometa) assert (type (t) == "table", "bad argument #1 to 'clone' (table expected, got " .. type (t) .. ")") local r = {} if not nometa then setmetatable (r, getmetatable (t)) end local d = {[t] = r} local function copy (o, x) for i, v in pairs (x) do if type (v) == "table" then if not d[v] then d[v] = {} if not nometa then setmetatable (d[v], getmetatable (v)) end o[i] = copy (d[v], v) else o[i] = d[v] end else o[i] = v end end return o end return copy (r, t) end --- Tree iterator. -- @tparam function it iterator function -- @tparam tree|table tr tree or tree-like table -- @treturn string type ("leaf", "branch" (pre-order) or "join" (post-order)) -- @treturn table path to node ({i\_1...i\_k}) -- @return node local function _nodes (it, tr) local p = {} local function visit (n) if type (n) == "table" then coroutine.yield ("branch", p, n) for i, v in it (n) do table.insert (p, i) visit (v) table.remove (p) end coroutine.yield ("join", p, n) else coroutine.yield ("leaf", p, n) end end return coroutine.wrap (visit), tr end --- Tree iterator over all nodes. -- -- The returned iterator function performs a depth-first traversal of -- `tr`, and at each node it returns `{node-type, tree-path, tree-node}` -- where `node-type` is `branch`, `join` or `leaf`; `tree-path` is a -- list of keys used to reach this node, and `tree-node` is the current -- node. -- -- Given a `tree` to represent: -- -- + root -- +-- node1 -- | +-- leaf1 -- | '-- leaf2 -- '-- leaf 3 -- -- tree = std.tree { std.tree { "leaf1", "leaf2"}, "leaf3" } -- -- A series of calls to `tree.nodes` will return: -- -- "branch", {}, {{"leaf1", "leaf2"}, "leaf3"} -- "branch", {1}, {"leaf1", "leaf"2") -- "leaf", {1,1}, "leaf1" -- "leaf", {1,2}, "leaf2" -- "join", {1}, {"leaf1", "leaf2"} -- "leaf", {2}, "leaf3" -- "join", {}, {{"leaf1", "leaf2"}, "leaf3"} -- -- Note that the `tree-path` reuses the same table on each iteration, so -- you must `table.clone` a copy if you want to take a snap-shot of the -- current state of the `tree-path` list before the next iteration -- changes it. -- @tparam tree|table tr tree or tree-like table to iterate over -- @treturn function iterator function -- @treturn tree|table the tree, `tr` -- @see inodes local function nodes (tr) assert (type (tr) == "table", "bad argument #1 to 'nodes' (table expected, got " .. type (tr) .. ")") return _nodes (pairs, tr) end --- Tree iterator over numbered nodes, in order. -- -- The iterator function behaves like @{nodes}, but only traverses the -- array part of the nodes of `tr`, ignoring any others. -- @tparam tree|table tr tree to iterate over -- @treturn function iterator function -- @treturn tree|table the tree, `tr` -- @see nodes local function inodes (tr) assert (type (tr) == "table", "bad argument #1 to 'inodes' (table expected, got " .. type (tr) .. ")") return _nodes (ipairs, tr) end --- Destructively deep-merge one tree into another. -- @tparam tree|table t destination tree or table -- @tparam tree|table u tree or table with nodes to merge -- @treturn tree|table `t` with nodes from `u` merged in -- @see std.table.merge local function merge (t, u) assert (type (t) == "table", "bad argument #1 to 'merge' (table expected, got " .. type (t) .. ")") assert (type (u) == "table", "bad argument #2 to 'merge' (table expected, got " .. type (u) .. ")") for ty, p, n in nodes (u) do if ty == "leaf" then t[p] = n end end return t end --- @export local _functions = { clone = clone, ileaves = ileaves, inodes = inodes, leaves = leaves, merge = merge, nodes = nodes, } --- Tree prototype object. -- @table std.tree -- @string[opt="Tree"] _type type of Tree, returned by -- @{std.object.prototype} -- @tfield[opt={}] table|function _init a table of field names, or -- initialisation function, see @{std.object.__call} -- @tfield nil|table _functions a table of module functions not copied -- by @{std.object.__call} Tree = Container { -- Derived object type. _type = "Tree", --- Tree `__index` metamethod. -- @function __index -- @param i non-table, or list of keys `{i\_1 ... i\_n}` -- @return `self[i]...[i\_n]` if i is a table, or `self[i]` otherwise -- @todo the following doesn't treat list keys correctly -- e.g. self[{{1, 2}, {3, 4}}], maybe flatten first? __index = function (self, i) if type (i) == "table" and #i > 0 then return List.foldl (func.op["[]"], self, i) else return rawget (self, i) end end, --- Tree `__newindex` metamethod. -- -- Sets `self[i\_1]...[i\_n] = v` if i is a table, or `self[i] = v` otherwise -- @function __newindex -- @param i non-table, or list of keys `{i\_1 ... i\_n}` -- @param v value __newindex = function (self, i, v) if type (i) == "table" then for n = 1, #i - 1 do if prototype (self[i[n]]) ~= "Tree" then rawset (self, i[n], Tree {}) end self = self[i[n]] end rawset (self, i[#i], v) else rawset (self, i, v) end end, _functions = base.merge (_functions, { -- backwards compatibility. new = function (t) return Tree (t or {}) end, }), } return Tree
mit
anshkumar/yugioh-glaze
assets/script/c38450736.lua
3
2921
--甲虫装機 ウィーグ function c38450736.initial_effect(c) --equip local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetDescription(aux.Stringid(38450736,0)) e1:SetCategory(CATEGORY_EQUIP) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetTarget(c38450736.eqtg) e1:SetOperation(c38450736.eqop) c:RegisterEffect(e1) --equip effect local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_EQUIP) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetValue(1000) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_EQUIP) e3:SetCode(EFFECT_UPDATE_DEFENCE) e3:SetValue(1000) c:RegisterEffect(e3) --atkup local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(38450736,1)) e3:SetCategory(CATEGORY_ATKCHANGE) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e3:SetCode(EVENT_LEAVE_FIELD) e3:SetCondition(c38450736.atkcon) e3:SetTarget(c38450736.atktg) e3:SetOperation(c38450736.atkop) c:RegisterEffect(e3) end function c38450736.filter(c) return c:IsSetCard(0x56) and c:IsType(TYPE_MONSTER) and not c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c38450736.eqtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0 and Duel.IsExistingMatchingCard(c38450736.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,nil,1,tp,LOCATION_GRAVE+LOCATION_HAND) end function c38450736.eqop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end if c:IsFacedown() or not c:IsRelateToEffect(e) then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) local g=Duel.SelectMatchingCard(tp,c38450736.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,1,nil) local tc=g:GetFirst() if tc then if not Duel.Equip(tp,tc,c,true) then return end local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_COPY_INHERIT+EFFECT_FLAG_OWNER_RELATE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_EQUIP_LIMIT) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetValue(c38450736.eqlimit) tc:RegisterEffect(e1) end end function c38450736.eqlimit(e,c) return e:GetOwner()==c end function c38450736.atkcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ec=c:GetEquipTarget() e:SetLabelObject(ec) return ec and c:IsLocation(LOCATION_GRAVE) and ec:IsFaceup() and ec:IsLocation(LOCATION_MZONE) end function c38450736.atktg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local ec=e:GetLabelObject() Duel.SetTargetCard(ec) end function c38450736.atkop(e,tp,eg,ep,ev,re,r,rp) local ec=e:GetLabelObject() if ec:IsLocation(LOCATION_MZONE) and ec:IsFaceup() and ec:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(1000) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) ec:RegisterEffect(e1) end end
gpl-2.0
anshkumar/yugioh-glaze
assets/script/c89397517.lua
3
2701
--レジェンド・オブ・ハート function c89397517.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_REMOVE+CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,89397517+EFFECT_COUNT_CODE_OATH) e1:SetCost(c89397517.cost) e1:SetTarget(c89397517.target) e1:SetOperation(c89397517.activate) c:RegisterEffect(e1) end function c89397517.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,2000) and Duel.CheckReleaseGroup(tp,Card.IsRace,1,nil,RACE_WARRIOR) end Duel.PayLPCost(tp,2000) local sg=Duel.SelectReleaseGroup(tp,Card.IsRace,1,1,nil,RACE_WARRIOR) Duel.Release(sg,REASON_COST) end function c89397517.rmfilter(c) return c:IsSetCard(0xa1) and c:IsType(TYPE_SPELL) and c:IsAbleToRemove() end function c89397517.spfilter(c,e,tp) return c:IsSetCard(0xa0) and c:IsType(TYPE_MONSTER) and c:IsCanBeSpecialSummoned(e,0,tp,true,true) and not c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c89397517.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c89397517.rmfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,nil) and Duel.IsExistingMatchingCard(c89397517.spfilter,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_DECK,0,1,nil,e,tp) end local g=Duel.GetMatchingGroup(c89397517.rmfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_DECK) end function c89397517.activate(e,tp,eg,ep,ev,re,r,rp) local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return end local rmg=Duel.GetMatchingGroup(c89397517.rmfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,nil) local rmct=rmg:GetClassCount(Card.GetCode) local spg=Duel.GetMatchingGroup(c89397517.spfilter,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_DECK,0,nil,e,tp) local spct=spg:GetClassCount(Card.GetCode) local ct=math.min(3,ft,spct,rmct) if ct==0 then return end local g=Group.CreateGroup() repeat Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local tc=rmg:Select(tp,1,1,nil):GetFirst() rmg:Remove(Card.IsCode,nil,tc:GetCode()) g:AddCard(tc) ct=ct-1 until ct<1 or not Duel.SelectYesNo(tp,aux.Stringid(89397517,0)) Duel.Remove(g,POS_FACEUP,REASON_EFFECT) ct=g:FilterCount(Card.IsLocation,nil,LOCATION_REMOVED) while ct>0 do Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tc=spg:Select(tp,1,1,nil):GetFirst() spg:Remove(Card.IsCode,nil,tc:GetCode()) Duel.SpecialSummonStep(tc,0,tp,tp,true,true,POS_FACEUP) tc:CompleteProcedure() ct=ct-1 end Duel.SpecialSummonComplete() end
gpl-2.0
bullno1/MoaiNao
sample-project/src/main.lua
1
1317
print("Hai, can haz cheeze burgerz???") local viewport = MOAIViewport.new () local devWidth, devHeight = MOAIGfxDevice.getViewSize() viewport:setSize(devWidth, devHeight) viewport:setScale(devWidth, -devHeight) viewport:setOffset(-1, 1) local layer = MOAILayer2D.new () layer:setViewport(viewport) MOAISim.pushRenderPass (layer) gfxQuad = MOAIGfxQuad2D.new () gfxQuad:setTexture ( "cathead.png" ) gfxQuad:setRect ( -64, -64, 64, 64 ) gfxQuad:setUVRect ( 1, 0, 0, 1) prop = MOAIProp2D.new () prop:setDeck ( gfxQuad ) layer:insertProp ( prop ) prop:moveRot ( 360 * 6, 1.5 * 10 ) prop:seekLoc ( devWidth / 2, devHeight / 2, 1.5 * 10, MOAIEaseType.SMOOTH) local touchDeck = MOAIScriptDeck.new() local touchSensor = MOAIInputMgr.device.touch touchDeck:setDrawCallback(function(index, xOff, yOff, xScale, yScale) for _, id in ipairs{touchSensor:getActiveTouches()} do local x, y = touchSensor:getTouch(id) MOAIGfxDevice.setPenColor(1, 1, 1, 0.75) MOAIDraw.fillCircle (x, y, 10, 10) MOAIGfxDevice.setPenColor(0, 0, 1, 0.75) MOAIDraw.drawLine (x, -devHeight, x, devHeight) MOAIDraw.drawLine (-devWidth, y, devWidth, y) end end) touchDeck:setRect(-devWidth, -devHeight, devWidth, devHeight) local prop = MOAIProp2D.new() prop:setDeck(touchDeck) layer:insertProp(prop) prop:setBlendMode(MOAIProp2D.BLEND_ADD)
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/ActionTimelineNode.lua
11
1809
-------------------------------- -- @module ActionTimelineNode -- @extend Node -- @parent_module ccs -------------------------------- -- -- @function [parent=#ActionTimelineNode] getRoot -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- -- @function [parent=#ActionTimelineNode] getActionTimeline -- @param self -- @return ActionTimeline#ActionTimeline ret (return value: ccs.ActionTimeline) -------------------------------- -- -- @function [parent=#ActionTimelineNode] setActionTimeline -- @param self -- @param #ccs.ActionTimeline action -- @return ActionTimelineNode#ActionTimelineNode self (return value: ccs.ActionTimelineNode) -------------------------------- -- -- @function [parent=#ActionTimelineNode] init -- @param self -- @param #cc.Node root -- @param #ccs.ActionTimeline action -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ActionTimelineNode] setRoot -- @param self -- @param #cc.Node root -- @return ActionTimelineNode#ActionTimelineNode self (return value: ccs.ActionTimelineNode) -------------------------------- -- -- @function [parent=#ActionTimelineNode] create -- @param self -- @param #cc.Node root -- @param #ccs.ActionTimeline action -- @return ActionTimelineNode#ActionTimelineNode ret (return value: ccs.ActionTimelineNode) -------------------------------- -- -- @function [parent=#ActionTimelineNode] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ActionTimelineNode] ActionTimelineNode -- @param self -- @return ActionTimelineNode#ActionTimelineNode self (return value: ccs.ActionTimelineNode) return nil
mit
Tatuy/uatibia-www
other/Znote AAC/LUA/TFS_10/talkaction shopsystem/znoteshop.lua
2
3160
-- Znote Shop v1.0 for Znote AAC on TFS 1.1 function onSay(player, words, param) local storage = 54073 -- Make sure to select non-used storage. This is used to prevent SQL load attacks. local cooldown = 15 -- in seconds. if player:getStorageValue(storage) <= os.time() then player:setStorageValue(storage, os.time() + cooldown) -- Create the query local orderQuery = db.storeQuery("SELECT `id`, `type`, `itemid`, `count` FROM `znote_shop_orders` WHERE `account_id` = " .. player:getAccountId() .. " LIMIT 1;") -- Detect if we got any results if orderQuery ~= false then -- Fetch order values local q_id = result.getNumber(orderQuery, "id") local q_type = result.getNumber(orderQuery, "type") local q_itemid = result.getNumber(orderQuery, "itemid") local q_count = result.getNumber(orderQuery, "count") result.free(orderQuery) -- ORDER TYPE 1 (Regular item shop products) if q_type == 1 then -- Get wheight if player:getFreeCapacity() >= ItemType(q_itemid):getWeight(q_count) then db.query("DELETE FROM `znote_shop_orders` WHERE `id` = " .. q_id .. ";") player:addItem(q_itemid, q_count) player:sendTextMessage(MESSAGE_INFO_DESCR, "Congratulations! You have received " .. q_count .. " x " .. ItemType(q_itemid):getName() .. "!") else player:sendTextMessage(MESSAGE_STATUS_WARNING, "Need more CAP!") end end -- ORDER TYPE 5 (Outfit and addon) if q_type == 5 then -- Make sure player don't already have this outfit and addon if not player:hasOutfit(q_itemid, q_count) then db.query("DELETE FROM `znote_shop_orders` WHERE `id` = " .. q_id .. ";") player:addOutfit(q_itemid) player:addOutfitAddon(q_itemid, q_count) player:sendTextMessage(MESSAGE_INFO_DESCR, "Congratulations! You have received a new outfit!") else player:sendTextMessage(MESSAGE_STATUS_WARNING, "You already have this outfit and addon!") end end -- ORDER TYPE 6 (Mounts) if q_type == 6 then -- Make sure player don't already have this outfit and addon if not player:hasMount(q_itemid) then db.query("DELETE FROM `znote_shop_orders` WHERE `id` = " .. q_id .. ";") player:addMount(q_itemid) player:sendTextMessage(MESSAGE_INFO_DESCR, "Congratulations! You have received a new mount!") else player:sendTextMessage(MESSAGE_STATUS_WARNING, "You already have this mount!") end end -- Add custom order types here -- Type 1 is for itemids (Already coded here) -- Type 2 is for premium (Coded on web) -- Type 3 is for gender change (Coded on web) -- Type 4 is for character name change (Coded on web) -- Type 5 is for character outfit and addon (Already coded here) -- Type 6 is for mounts (Already coded here) -- So use type 7+ for custom stuff, like etc packages. -- if q_type == 7 then -- end else player:sendTextMessage(MESSAGE_STATUS_WARNING, "You have no orders.") end else player:sendTextMessage(MESSAGE_STATUS_CONSOLE_BLUE, "Can only be executed once every " .. cooldown .. " seconds. Remaining cooldown: " .. player:getStorageValue(storage) - os.time()) end return false end
apache-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/libzq/auto_buildings/api/ZQDeviceInfo.lua
2
4827
-------------------------------- -- @module ZQDeviceInfo -- @parent_module zq -------------------------------- -- -- @function [parent=#ZQDeviceInfo] cpu_usage -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] device_uuid -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] os_is_android -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] memory_all -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] version_cpp -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] os_is_ios -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] device_network -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] cpu_core -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] bundle_id -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] device_hardware -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] uuid -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] vibrate -- @param self -- @return ZQDeviceInfo#ZQDeviceInfo self (return value: zq.ZQDeviceInfo) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] clipboard -- @param self -- @param #string text -- @return ZQDeviceInfo#ZQDeviceInfo self (return value: zq.ZQDeviceInfo) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] bundle_name -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] memory_used -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] memory_free -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] os_is_mobile -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] browser_useragent -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] keyboard_exist -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] device_telecom -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] os_is_mac -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] open_browser -- @param self -- @param #string url -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] quit_game -- @param self -- @return ZQDeviceInfo#ZQDeviceInfo self (return value: zq.ZQDeviceInfo) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] keyboard_close -- @param self -- @return ZQDeviceInfo#ZQDeviceInfo self (return value: zq.ZQDeviceInfo) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] device_os_version -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] version_short -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] keep_awake -- @param self -- @param #bool keep -- @return ZQDeviceInfo#ZQDeviceInfo self (return value: zq.ZQDeviceInfo) -------------------------------- -- -- @function [parent=#ZQDeviceInfo] getInstance -- @param self -- @return ZQDeviceInfo#ZQDeviceInfo ret (return value: zq.ZQDeviceInfo) return nil
mit
JarnoVgr/Mr.Green-MTA-Resources
resources/[web]/irc/scripts/loading.lua
4
10921
--------------------------------------------------------------------- -- Project: irc -- Author: MCvarial -- Contact: mcvarial@gmail.com -- Version: 1.0.0 -- Date: 31.10.2010 --------------------------------------------------------------------- local adTimer ------------------------------------ -- Loading ------------------------------------ addEventHandler("onResourceStart",resourceRoot, function () -- Parse rights file. local rightsFile = fileOpen("scripts/rights.txt",true) if rightsFile then local missingRights = {} for i,line in ipairs (split(fileRead(rightsFile,fileGetSize(rightsFile)),44)) do line = string.sub(line,2) if not hasObjectPermissionTo(getThisResource(),"function."..line,true) then table.insert(missingRights,"function."..line) end end if #missingRights ~= 0 then outputServerLog("IRC: "..#missingRights.." missing rights: ") for i,missingRight in ipairs (missingRights) do outputServerLog(" - "..missingRight) end outputServerLog("Please give the irc resource these rights or it will not work properly!") end else outputServerLog("IRC: could not start resource, the rights file can't be loaded!") outputServerLog("IRC: restart the resource to retry") return end -- Is the resource up-to-date? function checkVersion (res,version) if res ~= "ERROR" and version then if getNumberFromVersion(version) > getNumberFromVersion(getResourceInfo(getThisResource(),"version")) then outputServerLog("IRC: resource is outdated, newest version: "..version) setTimer(outputIRC,10000,1,"The irc resource is outdated, newest version: "..version) end end end --callRemote("http://community.mtasa.com/mta/resources.php",checkVersion,"version","irc") -- Start the ads. addEvent("onIRCPlayerDelayedJoin",true) if get("irc-notice") == "true" then local timeout = tonumber(get("irc-notice-timeout")) if timeout then if timeout == 0 then addEventHandler("onIRCPlayerDelayedJoin",root,showContinuousAd) else adTimer = setTimer(showAd,timeout*1000,0) end end end -- Parse functions file. local functionsFile = fileOpen("scripts/functions.txt",true) if functionsFile then for i,line in ipairs (split(fileRead(functionsFile,fileGetSize(functionsFile)),44)) do if gettok(line,1,21) ~= "--" then local functionName = gettok(line,2,32) _G[(functionName)] = function (...) local args = {...} for i,arg in ipairs (args) do local expectedArgType = gettok(line,(2+i),32) if expectedArgType and type(arg) ~= expectedArgType and not (expectedArgType or string.find(expectedArgType,")")) then outputServerLog("IRC: Bad argument #"..i.." @ '"..gettok(line,2,32).."' "..expectedArgType.." expected, got "..type(arg)) return end end if _G[("func_"..functionName)] then return _G[("func_"..functionName)](...) else outputServerLog("Function '"..functionName.."' does not exist") return false end end end end fileClose(functionsFile) else outputServerLog("IRC: could not start resource, the functions file can't be loaded!") outputServerLog("IRC: restart the resource to retry") return end -- parse acl file local aclFile = xmlLoadFile("acl.xml") if aclFile then local i = 0 -- for each command we find while(xmlFindChild(aclFile,"command",i)) do local child = xmlFindChild(aclFile,"command",i) local attrs = xmlNodeGetAttributes(child) acl[attrs.name] = attrs i = i + 1 end xmlUnloadFile(aclFile) else outputServerLog("IRC: could not start resource, the acl file can't be loaded!") outputServerLog("IRC: restart the resource to retry") return end -- Is the sockets module loaded? if not sockOpen then outputServerLog("IRC: could not start resource, the sockets module isn't loaded!") outputServerLog("IRC: restart the resource to retry") return end -- start irc addons for i,resource in ipairs (getResources()) do local info = getResourceInfo(resource,"addon") if info and info == "irc" then startResource(resource) end end triggerEvent("onIRCResourceStart",root) addIRCCommands() internalConnect() end ) addEventHandler("onResourceStop",resourceRoot, function () for i,server in ipairs (ircGetServers()) do ircDisconnect(server,"resource stopped") end servers = {} channels = {} users = {} -- stop irc addons for i,resource in ipairs (getResources()) do local info = getResourceInfo(resource,"addon") if info and info == "irc" then stopResource(resource) end end end ) function internalConnect () -- Parse settings file. local settingsFile = xmlLoadFile("settings.xml") if settingsFile then for i,server in ipairs (xmlNodeGetChildren(settingsFile)) do local host = xmlNodeGetAttribute(server,"host") local nick = xmlNodeGetAttribute(server,"nick") local channels = xmlNodeGetAttribute(server,"channels") local port = tonumber(xmlNodeGetAttribute(server,"port")) or 6667 local password = xmlNodeGetAttribute(server,"password") or false local secure = xmlNodeGetAttribute(server,"secure") or false local nspass = xmlNodeGetAttribute(server,"nickservpass") or false if not host then outputServerLog("IRC: problem with server #"..i..", no host given!") elseif not nick then outputServerLog("IRC: problem with server #"..i..", no nick given!") elseif not channels then outputServerLog("IRC: problem with server #"..i..", no channels given!") else local server = ircConnect(host,nick,port,password,secure) if server then if nspass then ircIdentify(server,nspass) end for i,channel in ipairs (split(channels,44)) do ircJoin(server,gettok(channel,1,32),gettok(channel,2,32)) end else outputServerLog("IRC: problem with server #"..i..", could not connect ("..tostring(getSocketErrorString(sockError)..")")) end end end xmlUnloadFile(settingsFile) else outputServerLog("IRC: could not start resource, the settings.xml can't be parsed!") outputServerLog("IRC: restart the resource to retry") return end end function showAd () for i,channel in ipairs (ircGetChannels()) do if ircIsEchoChannel(channel) then --outputChatBox("Join us on irc! Server: "..ircGetServerHost(ircGetChannelServer(channel)).." Channel: "..ircGetChannelName(channel),root,0,255,0) triggerClientEvent("showAd",root,ircGetServerHost(ircGetChannelServer(channel)),ircGetChannelName(channel),tonumber(get("irc-notice-duration"))) return end end end function showContinuousAd () for i,channel in ipairs (ircGetChannels()) do if ircIsEchoChannel(channel) then triggerClientEvent(source,"showAd",root,ircGetServerHost(ircGetChannelServer(channel)),ircGetChannelName(channel),0) return end end end
mit
shadoalzupedy/shadow
plugins/banhammer1.lua
2
16468
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Aziz < @TH3_GHOST > # our channel: @DevPointTeam # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] local function pre_process(msg) local data = load_data(_config.moderation.data) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned and not is_momod2(msg.from.id, msg.to.id) or is_gbanned(user_id) and not is_admin2(msg.from.id) then -- Check it with redis print('User is banned!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) >= 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) >= 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' or msg.to.type == 'channel' then local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function banall_by_reply(extra, success, result) if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then local chat = 'chat#id'..result.to.peer_id local channel = 'channel#id'..result.to.peer_id if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(result.from.peer_id) then -- Ignore admins return end banall_user(result.from.peer_id) send_large_msg(chat, "User "..result.from.peer_id.." Golobally Banned") send_large_msg(channel, "User "..result.from.peer_id.." Golobally Banned") else return end end local function unbanall_by_reply(extra, success, result) if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then local user_id = result.from.peer_id local chat = 'chat#id'..result.to.peer_id local channel = 'channel#id'..result.to.peer_id if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(result.from.peer_id) then -- Ignore admins return end if is_gbanned(result.from.peer_id) then return result.from.peer_id..' is already un-Gbanned.' end if not is_gbanned(result.from.peer_id) then unbanall_user(result.from.peer_id) send_large_msg(chat, "User "..result.from.peer_id.." Golobally un-Banned") send_large_msg(channel, "User "..result.from.peer_id.." Golobally un-Banned") end end end local function unban_by_reply(extra, success, result) if result.to.peer_type == 'chat' or result.to.peer_type == 'channel' then local chat = 'chat#id'..result.to.peer_id local channel = 'channel#id'..result.to.peer_id if tonumber(result.from.peer_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(result.from.peer_id) then -- Ignore admins return end send_large_msg(chat, "User "..result.from.peer_id.." un-Banned") send_large_msg(channel, "User "..result.from.peer_id.." un-Banned") local hash = 'banned:'..result.to.peer_id redis:srem(hash, result.from.peer_id) else return end end local function kick_ban_res(extra, success, result) local chat_id = extra.chat_id local chat_type = extra.chat_type if chat_type == "chat" then receiver = 'chat#id'..chat_id else receiver = 'channel#id'..chat_id end if success == 0 then return send_large_msg(receiver, "Cannot find user by that username!") end local member_id = result.peer_id local user_id = member_id local member = result.username local from_id = extra.from_id local get_cmd = extra.get_cmd if get_cmd == "kick" then if member_id == from_id then send_large_msg(receiver, "You can't kick yourself") return end if is_momod2(member_id, chat_id) and not is_admin2(sender) then send_large_msg(receiver, "You can't kick mods/owner/admins") return end kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then send_large_msg(receiver, "You can't ban mods/owner/admins") return end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') banall_user(member_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally unbanned') unbanall_user(member_id) end end local function run(msg, matches) local support_id = msg.from.id if matches[1]:lower() == 'id' and msg.to.type == "chat" or msg.to.type == "user" then if msg.to.type == "user" then return "Your id : "..msg.from.id end if type(msg.reply_id) ~= "nil" then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") local text = "_🇮🇷 Group ID : _*"..msg.to.id.."*\n_🇮🇷 Group Name : _*"..msg.to.title.."*" send_api_msg(msg, get_receiver_api(msg), text, true, 'md') end end if matches[1]:lower() == 'دعبلني' and msg.to.type == "chat" then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin1(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'دي' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") local receiver = get_receiver(msg) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(matches[2], msg.to.id) send_large_msg(receiver, 'User ['..matches[2]..'] banned') else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'بره' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if not is_admin1(msg) and not is_support(support_id) then return end if matches[1]:lower() == 'حضر عام' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") local receiver = get_receiver(msg) savelog(msg.to.id, name.." ["..msg.from.id.."] banedall user ".. matches[2]) banall_user(matches[2]) send_large_msg(receiver, 'User ['..matches[2]..'] bannedalled') else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'الغاء العام' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,unbanall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin1(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") local receiver = get_receiver(msg) savelog(msg.to.id, name.." ["..msg.from.id.."] unbanedall user ".. matches[2]) unbanall_user(matches[2]) send_large_msg(receiver, 'User ['..matches[2]..'] unbannedalled') else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'الغاء الحضر' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin1(msg) then msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id elseif string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") local receiver = get_receiver(msg) savelog(msg.to.id, name.." ["..msg.from.id.."] unban user ".. matches[2]) unbanall_user(matches[2]) send_large_msg(receiver, 'العضو الحيوان 😡 ['..matches[2]..'] تم طرده ☺️❤️ ') else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id, chat_type = msg.to.type } local username = string.gsub(matches[2], '@', '') resolve_username(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "المطرودين" then -- Global ban list return banall_list() end end return { patterns = { "^[#!/](حضر عام) (.*)$", "^[#!/](حضر عام)$", "^[#!/](الغاء العام)$", "^[#!/]([Bb]anlist) (.*)$", "^[#!/]([Bb]anlist)$", "^[#!/](المطرودين)$", "^[#!/](دعبلني)", "^[#!/](بره)$", "^[#!/](دي)$", "^[#!/](دي) (.*)$", "^[#!/](الغاء الحضر) (.*)$", "^[#!/](الغاء العام) (.*)$", "^[#!/](الغاء العام)$", "^[#!/](بره) (.*)$", "^[#!/](الغاء الحضر)$", "^[#!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/script/cocos2d/OpenglConstants.lua
100
27127
if not gl then return end gl.GCCSO_SHADER_BINARY_FJ = 0x9260 gl._3DC_XY_AMD = 0x87fa gl._3DC_X_AMD = 0x87f9 gl.ACTIVE_ATTRIBUTES = 0x8b89 gl.ACTIVE_ATTRIBUTE_MAX_LENGTH = 0x8b8a gl.ACTIVE_PROGRAM_EXT = 0x8259 gl.ACTIVE_TEXTURE = 0x84e0 gl.ACTIVE_UNIFORMS = 0x8b86 gl.ACTIVE_UNIFORM_MAX_LENGTH = 0x8b87 gl.ALIASED_LINE_WIDTH_RANGE = 0x846e gl.ALIASED_POINT_SIZE_RANGE = 0x846d gl.ALL_COMPLETED_NV = 0x84f2 gl.ALL_SHADER_BITS_EXT = 0xffffffff gl.ALPHA = 0x1906 gl.ALPHA16F_EXT = 0x881c gl.ALPHA32F_EXT = 0x8816 gl.ALPHA8_EXT = 0x803c gl.ALPHA8_OES = 0x803c gl.ALPHA_BITS = 0xd55 gl.ALPHA_TEST_FUNC_QCOM = 0xbc1 gl.ALPHA_TEST_QCOM = 0xbc0 gl.ALPHA_TEST_REF_QCOM = 0xbc2 gl.ALREADY_SIGNALED_APPLE = 0x911a gl.ALWAYS = 0x207 gl.AMD_compressed_3DC_texture = 0x1 gl.AMD_compressed_ATC_texture = 0x1 gl.AMD_performance_monitor = 0x1 gl.AMD_program_binary_Z400 = 0x1 gl.ANGLE_depth_texture = 0x1 gl.ANGLE_framebuffer_blit = 0x1 gl.ANGLE_framebuffer_multisample = 0x1 gl.ANGLE_instanced_arrays = 0x1 gl.ANGLE_pack_reverse_row_order = 0x1 gl.ANGLE_program_binary = 0x1 gl.ANGLE_texture_compression_dxt3 = 0x1 gl.ANGLE_texture_compression_dxt5 = 0x1 gl.ANGLE_texture_usage = 0x1 gl.ANGLE_translated_shader_source = 0x1 gl.ANY_SAMPLES_PASSED_CONSERVATIVE_EXT = 0x8d6a gl.ANY_SAMPLES_PASSED_EXT = 0x8c2f gl.APPLE_copy_texture_levels = 0x1 gl.APPLE_framebuffer_multisample = 0x1 gl.APPLE_rgb_422 = 0x1 gl.APPLE_sync = 0x1 gl.APPLE_texture_format_BGRA8888 = 0x1 gl.APPLE_texture_max_level = 0x1 gl.ARM_mali_program_binary = 0x1 gl.ARM_mali_shader_binary = 0x1 gl.ARM_rgba8 = 0x1 gl.ARRAY_BUFFER = 0x8892 gl.ARRAY_BUFFER_BINDING = 0x8894 gl.ATC_RGBA_EXPLICIT_ALPHA_AMD = 0x8c93 gl.ATC_RGBA_INTERPOLATED_ALPHA_AMD = 0x87ee gl.ATC_RGB_AMD = 0x8c92 gl.ATTACHED_SHADERS = 0x8b85 gl.BACK = 0x405 gl.BGRA8_EXT = 0x93a1 gl.BGRA_EXT = 0x80e1 gl.BGRA_IMG = 0x80e1 gl.BINNING_CONTROL_HINT_QCOM = 0x8fb0 gl.BLEND = 0xbe2 gl.BLEND_COLOR = 0x8005 gl.BLEND_DST_ALPHA = 0x80ca gl.BLEND_DST_RGB = 0x80c8 gl.BLEND_EQUATION = 0x8009 gl.BLEND_EQUATION_ALPHA = 0x883d gl.BLEND_EQUATION_RGB = 0x8009 gl.BLEND_SRC_ALPHA = 0x80cb gl.BLEND_SRC_RGB = 0x80c9 gl.BLUE_BITS = 0xd54 gl.BOOL = 0x8b56 gl.BOOL_VEC2 = 0x8b57 gl.BOOL_VEC3 = 0x8b58 gl.BOOL_VEC4 = 0x8b59 gl.BUFFER = 0x82e0 gl.BUFFER_ACCESS_OES = 0x88bb gl.BUFFER_MAPPED_OES = 0x88bc gl.BUFFER_MAP_POINTER_OES = 0x88bd gl.BUFFER_OBJECT_EXT = 0x9151 gl.BUFFER_SIZE = 0x8764 gl.BUFFER_USAGE = 0x8765 gl.BYTE = 0x1400 gl.CCW = 0x901 gl.CLAMP_TO_BORDER_NV = 0x812d gl.CLAMP_TO_EDGE = 0x812f gl.COLOR_ATTACHMENT0 = 0x8ce0 gl.COLOR_ATTACHMENT0_NV = 0x8ce0 gl.COLOR_ATTACHMENT10_NV = 0x8cea gl.COLOR_ATTACHMENT11_NV = 0x8ceb gl.COLOR_ATTACHMENT12_NV = 0x8cec gl.COLOR_ATTACHMENT13_NV = 0x8ced gl.COLOR_ATTACHMENT14_NV = 0x8cee gl.COLOR_ATTACHMENT15_NV = 0x8cef gl.COLOR_ATTACHMENT1_NV = 0x8ce1 gl.COLOR_ATTACHMENT2_NV = 0x8ce2 gl.COLOR_ATTACHMENT3_NV = 0x8ce3 gl.COLOR_ATTACHMENT4_NV = 0x8ce4 gl.COLOR_ATTACHMENT5_NV = 0x8ce5 gl.COLOR_ATTACHMENT6_NV = 0x8ce6 gl.COLOR_ATTACHMENT7_NV = 0x8ce7 gl.COLOR_ATTACHMENT8_NV = 0x8ce8 gl.COLOR_ATTACHMENT9_NV = 0x8ce9 gl.COLOR_ATTACHMENT_EXT = 0x90f0 gl.COLOR_BUFFER_BIT = 0x4000 gl.COLOR_BUFFER_BIT0_QCOM = 0x1 gl.COLOR_BUFFER_BIT1_QCOM = 0x2 gl.COLOR_BUFFER_BIT2_QCOM = 0x4 gl.COLOR_BUFFER_BIT3_QCOM = 0x8 gl.COLOR_BUFFER_BIT4_QCOM = 0x10 gl.COLOR_BUFFER_BIT5_QCOM = 0x20 gl.COLOR_BUFFER_BIT6_QCOM = 0x40 gl.COLOR_BUFFER_BIT7_QCOM = 0x80 gl.COLOR_CLEAR_VALUE = 0xc22 gl.COLOR_EXT = 0x1800 gl.COLOR_WRITEMASK = 0xc23 gl.COMPARE_REF_TO_TEXTURE_EXT = 0x884e gl.COMPILE_STATUS = 0x8b81 gl.COMPRESSED_RGBA_ASTC_10x10_KHR = 0x93bb gl.COMPRESSED_RGBA_ASTC_10x5_KHR = 0x93b8 gl.COMPRESSED_RGBA_ASTC_10x6_KHR = 0x93b9 gl.COMPRESSED_RGBA_ASTC_10x8_KHR = 0x93ba gl.COMPRESSED_RGBA_ASTC_12x10_KHR = 0x93bc gl.COMPRESSED_RGBA_ASTC_12x12_KHR = 0x93bd gl.COMPRESSED_RGBA_ASTC_4x4_KHR = 0x93b0 gl.COMPRESSED_RGBA_ASTC_5x4_KHR = 0x93b1 gl.COMPRESSED_RGBA_ASTC_5x5_KHR = 0x93b2 gl.COMPRESSED_RGBA_ASTC_6x5_KHR = 0x93b3 gl.COMPRESSED_RGBA_ASTC_6x6_KHR = 0x93b4 gl.COMPRESSED_RGBA_ASTC_8x5_KHR = 0x93b5 gl.COMPRESSED_RGBA_ASTC_8x6_KHR = 0x93b6 gl.COMPRESSED_RGBA_ASTC_8x8_KHR = 0x93b7 gl.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8c03 gl.COMPRESSED_RGBA_PVRTC_2BPPV2_IMG = 0x9137 gl.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 0x8c02 gl.COMPRESSED_RGBA_PVRTC_4BPPV2_IMG = 0x9138 gl.COMPRESSED_RGBA_S3TC_DXT1_EXT = 0x83f1 gl.COMPRESSED_RGBA_S3TC_DXT3_ANGLE = 0x83f2 gl.COMPRESSED_RGBA_S3TC_DXT5_ANGLE = 0x83f3 gl.COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 0x8c01 gl.COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 0x8c00 gl.COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83f0 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR = 0x93db gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR = 0x93d8 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR = 0x93d9 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR = 0x93da gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR = 0x93dc gl.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR = 0x93dd gl.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR = 0x93d0 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR = 0x93d1 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR = 0x93d2 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR = 0x93d3 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR = 0x93d4 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR = 0x93d5 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR = 0x93d6 gl.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR = 0x93d7 gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV = 0x8c4d gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV = 0x8c4e gl.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV = 0x8c4f gl.COMPRESSED_SRGB_S3TC_DXT1_NV = 0x8c4c gl.COMPRESSED_TEXTURE_FORMATS = 0x86a3 gl.CONDITION_SATISFIED_APPLE = 0x911c gl.CONSTANT_ALPHA = 0x8003 gl.CONSTANT_COLOR = 0x8001 gl.CONTEXT_FLAG_DEBUG_BIT = 0x2 gl.CONTEXT_ROBUST_ACCESS_EXT = 0x90f3 gl.COUNTER_RANGE_AMD = 0x8bc1 gl.COUNTER_TYPE_AMD = 0x8bc0 gl.COVERAGE_ALL_FRAGMENTS_NV = 0x8ed5 gl.COVERAGE_ATTACHMENT_NV = 0x8ed2 gl.COVERAGE_AUTOMATIC_NV = 0x8ed7 gl.COVERAGE_BUFFERS_NV = 0x8ed3 gl.COVERAGE_BUFFER_BIT_NV = 0x8000 gl.COVERAGE_COMPONENT4_NV = 0x8ed1 gl.COVERAGE_COMPONENT_NV = 0x8ed0 gl.COVERAGE_EDGE_FRAGMENTS_NV = 0x8ed6 gl.COVERAGE_SAMPLES_NV = 0x8ed4 gl.CPU_OPTIMIZED_QCOM = 0x8fb1 gl.CULL_FACE = 0xb44 gl.CULL_FACE_MODE = 0xb45 gl.CURRENT_PROGRAM = 0x8b8d gl.CURRENT_QUERY_EXT = 0x8865 gl.CURRENT_VERTEX_ATTRIB = 0x8626 gl.CW = 0x900 gl.DEBUG_CALLBACK_FUNCTION = 0x8244 gl.DEBUG_CALLBACK_USER_PARAM = 0x8245 gl.DEBUG_GROUP_STACK_DEPTH = 0x826d gl.DEBUG_LOGGED_MESSAGES = 0x9145 gl.DEBUG_NEXT_LOGGED_MESSAGE_LENGTH = 0x8243 gl.DEBUG_OUTPUT = 0x92e0 gl.DEBUG_OUTPUT_SYNCHRONOUS = 0x8242 gl.DEBUG_SEVERITY_HIGH = 0x9146 gl.DEBUG_SEVERITY_LOW = 0x9148 gl.DEBUG_SEVERITY_MEDIUM = 0x9147 gl.DEBUG_SEVERITY_NOTIFICATION = 0x826b gl.DEBUG_SOURCE_API = 0x8246 gl.DEBUG_SOURCE_APPLICATION = 0x824a gl.DEBUG_SOURCE_OTHER = 0x824b gl.DEBUG_SOURCE_SHADER_COMPILER = 0x8248 gl.DEBUG_SOURCE_THIRD_PARTY = 0x8249 gl.DEBUG_SOURCE_WINDOW_SYSTEM = 0x8247 gl.DEBUG_TYPE_DEPRECATED_BEHAVIOR = 0x824d gl.DEBUG_TYPE_ERROR = 0x824c gl.DEBUG_TYPE_MARKER = 0x8268 gl.DEBUG_TYPE_OTHER = 0x8251 gl.DEBUG_TYPE_PERFORMANCE = 0x8250 gl.DEBUG_TYPE_POP_GROUP = 0x826a gl.DEBUG_TYPE_PORTABILITY = 0x824f gl.DEBUG_TYPE_PUSH_GROUP = 0x8269 gl.DEBUG_TYPE_UNDEFINED_BEHAVIOR = 0x824e gl.DECR = 0x1e03 gl.DECR_WRAP = 0x8508 gl.DELETE_STATUS = 0x8b80 gl.DEPTH24_STENCIL8_OES = 0x88f0 gl.DEPTH_ATTACHMENT = 0x8d00 gl.DEPTH_BITS = 0xd56 gl.DEPTH_BUFFER_BIT = 0x100 gl.DEPTH_BUFFER_BIT0_QCOM = 0x100 gl.DEPTH_BUFFER_BIT1_QCOM = 0x200 gl.DEPTH_BUFFER_BIT2_QCOM = 0x400 gl.DEPTH_BUFFER_BIT3_QCOM = 0x800 gl.DEPTH_BUFFER_BIT4_QCOM = 0x1000 gl.DEPTH_BUFFER_BIT5_QCOM = 0x2000 gl.DEPTH_BUFFER_BIT6_QCOM = 0x4000 gl.DEPTH_BUFFER_BIT7_QCOM = 0x8000 gl.DEPTH_CLEAR_VALUE = 0xb73 gl.DEPTH_COMPONENT = 0x1902 gl.DEPTH_COMPONENT16 = 0x81a5 gl.DEPTH_COMPONENT16_NONLINEAR_NV = 0x8e2c gl.DEPTH_COMPONENT16_OES = 0x81a5 gl.DEPTH_COMPONENT24_OES = 0x81a6 gl.DEPTH_COMPONENT32_OES = 0x81a7 gl.DEPTH_EXT = 0x1801 gl.DEPTH_FUNC = 0xb74 gl.DEPTH_RANGE = 0xb70 gl.DEPTH_STENCIL_OES = 0x84f9 gl.DEPTH_TEST = 0xb71 gl.DEPTH_WRITEMASK = 0xb72 gl.DITHER = 0xbd0 gl.DMP_shader_binary = 0x1 gl.DONT_CARE = 0x1100 gl.DRAW_BUFFER0_NV = 0x8825 gl.DRAW_BUFFER10_NV = 0x882f gl.DRAW_BUFFER11_NV = 0x8830 gl.DRAW_BUFFER12_NV = 0x8831 gl.DRAW_BUFFER13_NV = 0x8832 gl.DRAW_BUFFER14_NV = 0x8833 gl.DRAW_BUFFER15_NV = 0x8834 gl.DRAW_BUFFER1_NV = 0x8826 gl.DRAW_BUFFER2_NV = 0x8827 gl.DRAW_BUFFER3_NV = 0x8828 gl.DRAW_BUFFER4_NV = 0x8829 gl.DRAW_BUFFER5_NV = 0x882a gl.DRAW_BUFFER6_NV = 0x882b gl.DRAW_BUFFER7_NV = 0x882c gl.DRAW_BUFFER8_NV = 0x882d gl.DRAW_BUFFER9_NV = 0x882e gl.DRAW_BUFFER_EXT = 0xc01 gl.DRAW_FRAMEBUFFER_ANGLE = 0x8ca9 gl.DRAW_FRAMEBUFFER_APPLE = 0x8ca9 gl.DRAW_FRAMEBUFFER_BINDING_ANGLE = 0x8ca6 gl.DRAW_FRAMEBUFFER_BINDING_APPLE = 0x8ca6 gl.DRAW_FRAMEBUFFER_BINDING_NV = 0x8ca6 gl.DRAW_FRAMEBUFFER_NV = 0x8ca9 gl.DST_ALPHA = 0x304 gl.DST_COLOR = 0x306 gl.DYNAMIC_DRAW = 0x88e8 gl.ELEMENT_ARRAY_BUFFER = 0x8893 gl.ELEMENT_ARRAY_BUFFER_BINDING = 0x8895 gl.EQUAL = 0x202 gl.ES_VERSION_2_0 = 0x1 gl.ETC1_RGB8_OES = 0x8d64 gl.ETC1_SRGB8_NV = 0x88ee gl.EXTENSIONS = 0x1f03 gl.EXT_blend_minmax = 0x1 gl.EXT_color_buffer_half_float = 0x1 gl.EXT_debug_label = 0x1 gl.EXT_debug_marker = 0x1 gl.EXT_discard_framebuffer = 0x1 gl.EXT_map_buffer_range = 0x1 gl.EXT_multi_draw_arrays = 0x1 gl.EXT_multisampled_render_to_texture = 0x1 gl.EXT_multiview_draw_buffers = 0x1 gl.EXT_occlusion_query_boolean = 0x1 gl.EXT_read_format_bgra = 0x1 gl.EXT_robustness = 0x1 gl.EXT_sRGB = 0x1 gl.EXT_separate_shader_objects = 0x1 gl.EXT_shader_framebuffer_fetch = 0x1 gl.EXT_shader_texture_lod = 0x1 gl.EXT_shadow_samplers = 0x1 gl.EXT_texture_compression_dxt1 = 0x1 gl.EXT_texture_filter_anisotropic = 0x1 gl.EXT_texture_format_BGRA8888 = 0x1 gl.EXT_texture_rg = 0x1 gl.EXT_texture_storage = 0x1 gl.EXT_texture_type_2_10_10_10_REV = 0x1 gl.EXT_unpack_subimage = 0x1 gl.FALSE = 0x0 gl.FASTEST = 0x1101 gl.FENCE_CONDITION_NV = 0x84f4 gl.FENCE_STATUS_NV = 0x84f3 gl.FIXED = 0x140c gl.FJ_shader_binary_GCCSO = 0x1 gl.FLOAT = 0x1406 gl.FLOAT_MAT2 = 0x8b5a gl.FLOAT_MAT3 = 0x8b5b gl.FLOAT_MAT4 = 0x8b5c gl.FLOAT_VEC2 = 0x8b50 gl.FLOAT_VEC3 = 0x8b51 gl.FLOAT_VEC4 = 0x8b52 gl.FRAGMENT_SHADER = 0x8b30 gl.FRAGMENT_SHADER_BIT_EXT = 0x2 gl.FRAGMENT_SHADER_DERIVATIVE_HINT_OES = 0x8b8b gl.FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT = 0x8a52 gl.FRAMEBUFFER = 0x8d40 gl.FRAMEBUFFER_ATTACHMENT_ANGLE = 0x93a3 gl.FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT = 0x8210 gl.FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT = 0x8211 gl.FRAMEBUFFER_ATTACHMENT_OBJECT_NAME = 0x8cd1 gl.FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE = 0x8cd0 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES = 0x8cd4 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE = 0x8cd3 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL = 0x8cd2 gl.FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT = 0x8d6c gl.FRAMEBUFFER_BINDING = 0x8ca6 gl.FRAMEBUFFER_COMPLETE = 0x8cd5 gl.FRAMEBUFFER_INCOMPLETE_ATTACHMENT = 0x8cd6 gl.FRAMEBUFFER_INCOMPLETE_DIMENSIONS = 0x8cd9 gl.FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT = 0x8cd7 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE = 0x8d56 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE = 0x8d56 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT = 0x8d56 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG = 0x9134 gl.FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV = 0x8d56 gl.FRAMEBUFFER_UNDEFINED_OES = 0x8219 gl.FRAMEBUFFER_UNSUPPORTED = 0x8cdd gl.FRONT = 0x404 gl.FRONT_AND_BACK = 0x408 gl.FRONT_FACE = 0xb46 gl.FUNC_ADD = 0x8006 gl.FUNC_REVERSE_SUBTRACT = 0x800b gl.FUNC_SUBTRACT = 0x800a gl.GENERATE_MIPMAP_HINT = 0x8192 gl.GEQUAL = 0x206 gl.GPU_OPTIMIZED_QCOM = 0x8fb2 gl.GREATER = 0x204 gl.GREEN_BITS = 0xd53 gl.GUILTY_CONTEXT_RESET_EXT = 0x8253 gl.HALF_FLOAT_OES = 0x8d61 gl.HIGH_FLOAT = 0x8df2 gl.HIGH_INT = 0x8df5 gl.IMG_multisampled_render_to_texture = 0x1 gl.IMG_program_binary = 0x1 gl.IMG_read_format = 0x1 gl.IMG_shader_binary = 0x1 gl.IMG_texture_compression_pvrtc = 0x1 gl.IMG_texture_compression_pvrtc2 = 0x1 gl.IMPLEMENTATION_COLOR_READ_FORMAT = 0x8b9b gl.IMPLEMENTATION_COLOR_READ_TYPE = 0x8b9a gl.INCR = 0x1e02 gl.INCR_WRAP = 0x8507 gl.INFO_LOG_LENGTH = 0x8b84 gl.INNOCENT_CONTEXT_RESET_EXT = 0x8254 gl.INT = 0x1404 gl.INT_10_10_10_2_OES = 0x8df7 gl.INT_VEC2 = 0x8b53 gl.INT_VEC3 = 0x8b54 gl.INT_VEC4 = 0x8b55 gl.INVALID_ENUM = 0x500 gl.INVALID_FRAMEBUFFER_OPERATION = 0x506 gl.INVALID_OPERATION = 0x502 gl.INVALID_VALUE = 0x501 gl.INVERT = 0x150a gl.KEEP = 0x1e00 gl.KHR_debug = 0x1 gl.KHR_texture_compression_astc_ldr = 0x1 gl.LEQUAL = 0x203 gl.LESS = 0x201 gl.LINEAR = 0x2601 gl.LINEAR_MIPMAP_LINEAR = 0x2703 gl.LINEAR_MIPMAP_NEAREST = 0x2701 gl.LINES = 0x1 gl.LINE_LOOP = 0x2 gl.LINE_STRIP = 0x3 gl.LINE_WIDTH = 0xb21 gl.LINK_STATUS = 0x8b82 gl.LOSE_CONTEXT_ON_RESET_EXT = 0x8252 gl.LOW_FLOAT = 0x8df0 gl.LOW_INT = 0x8df3 gl.LUMINANCE = 0x1909 gl.LUMINANCE16F_EXT = 0x881e gl.LUMINANCE32F_EXT = 0x8818 gl.LUMINANCE4_ALPHA4_OES = 0x8043 gl.LUMINANCE8_ALPHA8_EXT = 0x8045 gl.LUMINANCE8_ALPHA8_OES = 0x8045 gl.LUMINANCE8_EXT = 0x8040 gl.LUMINANCE8_OES = 0x8040 gl.LUMINANCE_ALPHA = 0x190a gl.LUMINANCE_ALPHA16F_EXT = 0x881f gl.LUMINANCE_ALPHA32F_EXT = 0x8819 gl.MALI_PROGRAM_BINARY_ARM = 0x8f61 gl.MALI_SHADER_BINARY_ARM = 0x8f60 gl.MAP_FLUSH_EXPLICIT_BIT_EXT = 0x10 gl.MAP_INVALIDATE_BUFFER_BIT_EXT = 0x8 gl.MAP_INVALIDATE_RANGE_BIT_EXT = 0x4 gl.MAP_READ_BIT_EXT = 0x1 gl.MAP_UNSYNCHRONIZED_BIT_EXT = 0x20 gl.MAP_WRITE_BIT_EXT = 0x2 gl.MAX_3D_TEXTURE_SIZE_OES = 0x8073 gl.MAX_COLOR_ATTACHMENTS_NV = 0x8cdf gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS = 0x8b4d gl.MAX_CUBE_MAP_TEXTURE_SIZE = 0x851c gl.MAX_DEBUG_GROUP_STACK_DEPTH = 0x826c gl.MAX_DEBUG_LOGGED_MESSAGES = 0x9144 gl.MAX_DEBUG_MESSAGE_LENGTH = 0x9143 gl.MAX_DRAW_BUFFERS_NV = 0x8824 gl.MAX_EXT = 0x8008 gl.MAX_FRAGMENT_UNIFORM_VECTORS = 0x8dfd gl.MAX_LABEL_LENGTH = 0x82e8 gl.MAX_MULTIVIEW_BUFFERS_EXT = 0x90f2 gl.MAX_RENDERBUFFER_SIZE = 0x84e8 gl.MAX_SAMPLES_ANGLE = 0x8d57 gl.MAX_SAMPLES_APPLE = 0x8d57 gl.MAX_SAMPLES_EXT = 0x8d57 gl.MAX_SAMPLES_IMG = 0x9135 gl.MAX_SAMPLES_NV = 0x8d57 gl.MAX_SERVER_WAIT_TIMEOUT_APPLE = 0x9111 gl.MAX_TEXTURE_IMAGE_UNITS = 0x8872 gl.MAX_TEXTURE_MAX_ANISOTROPY_EXT = 0x84ff gl.MAX_TEXTURE_SIZE = 0xd33 gl.MAX_VARYING_VECTORS = 0x8dfc gl.MAX_VERTEX_ATTRIBS = 0x8869 gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS = 0x8b4c gl.MAX_VERTEX_UNIFORM_VECTORS = 0x8dfb gl.MAX_VIEWPORT_DIMS = 0xd3a gl.MEDIUM_FLOAT = 0x8df1 gl.MEDIUM_INT = 0x8df4 gl.MIN_EXT = 0x8007 gl.MIRRORED_REPEAT = 0x8370 gl.MULTISAMPLE_BUFFER_BIT0_QCOM = 0x1000000 gl.MULTISAMPLE_BUFFER_BIT1_QCOM = 0x2000000 gl.MULTISAMPLE_BUFFER_BIT2_QCOM = 0x4000000 gl.MULTISAMPLE_BUFFER_BIT3_QCOM = 0x8000000 gl.MULTISAMPLE_BUFFER_BIT4_QCOM = 0x10000000 gl.MULTISAMPLE_BUFFER_BIT5_QCOM = 0x20000000 gl.MULTISAMPLE_BUFFER_BIT6_QCOM = 0x40000000 gl.MULTISAMPLE_BUFFER_BIT7_QCOM = 0x80000000 gl.MULTIVIEW_EXT = 0x90f1 gl.NEAREST = 0x2600 gl.NEAREST_MIPMAP_LINEAR = 0x2702 gl.NEAREST_MIPMAP_NEAREST = 0x2700 gl.NEVER = 0x200 gl.NICEST = 0x1102 gl.NONE = 0x0 gl.NOTEQUAL = 0x205 gl.NO_ERROR = 0x0 gl.NO_RESET_NOTIFICATION_EXT = 0x8261 gl.NUM_COMPRESSED_TEXTURE_FORMATS = 0x86a2 gl.NUM_PROGRAM_BINARY_FORMATS_OES = 0x87fe gl.NUM_SHADER_BINARY_FORMATS = 0x8df9 gl.NV_coverage_sample = 0x1 gl.NV_depth_nonlinear = 0x1 gl.NV_draw_buffers = 0x1 gl.NV_draw_instanced = 0x1 gl.NV_fbo_color_attachments = 0x1 gl.NV_fence = 0x1 gl.NV_framebuffer_blit = 0x1 gl.NV_framebuffer_multisample = 0x1 gl.NV_generate_mipmap_sRGB = 0x1 gl.NV_instanced_arrays = 0x1 gl.NV_read_buffer = 0x1 gl.NV_read_buffer_front = 0x1 gl.NV_read_depth = 0x1 gl.NV_read_depth_stencil = 0x1 gl.NV_read_stencil = 0x1 gl.NV_sRGB_formats = 0x1 gl.NV_shadow_samplers_array = 0x1 gl.NV_shadow_samplers_cube = 0x1 gl.NV_texture_border_clamp = 0x1 gl.NV_texture_compression_s3tc_update = 0x1 gl.NV_texture_npot_2D_mipmap = 0x1 gl.OBJECT_TYPE_APPLE = 0x9112 gl.OES_EGL_image = 0x1 gl.OES_EGL_image_external = 0x1 gl.OES_compressed_ETC1_RGB8_texture = 0x1 gl.OES_compressed_paletted_texture = 0x1 gl.OES_depth24 = 0x1 gl.OES_depth32 = 0x1 gl.OES_depth_texture = 0x1 gl.OES_element_index_uint = 0x1 gl.OES_fbo_render_mipmap = 0x1 gl.OES_fragment_precision_high = 0x1 gl.OES_get_program_binary = 0x1 gl.OES_mapbuffer = 0x1 gl.OES_packed_depth_stencil = 0x1 gl.OES_required_internalformat = 0x1 gl.OES_rgb8_rgba8 = 0x1 gl.OES_standard_derivatives = 0x1 gl.OES_stencil1 = 0x1 gl.OES_stencil4 = 0x1 gl.OES_surfaceless_context = 0x1 gl.OES_texture_3D = 0x1 gl.OES_texture_float = 0x1 gl.OES_texture_float_linear = 0x1 gl.OES_texture_half_float = 0x1 gl.OES_texture_half_float_linear = 0x1 gl.OES_texture_npot = 0x1 gl.OES_vertex_array_object = 0x1 gl.OES_vertex_half_float = 0x1 gl.OES_vertex_type_10_10_10_2 = 0x1 gl.ONE = 0x1 gl.ONE_MINUS_CONSTANT_ALPHA = 0x8004 gl.ONE_MINUS_CONSTANT_COLOR = 0x8002 gl.ONE_MINUS_DST_ALPHA = 0x305 gl.ONE_MINUS_DST_COLOR = 0x307 gl.ONE_MINUS_SRC_ALPHA = 0x303 gl.ONE_MINUS_SRC_COLOR = 0x301 gl.OUT_OF_MEMORY = 0x505 gl.PACK_ALIGNMENT = 0xd05 gl.PACK_REVERSE_ROW_ORDER_ANGLE = 0x93a4 gl.PALETTE4_R5_G6_B5_OES = 0x8b92 gl.PALETTE4_RGB5_A1_OES = 0x8b94 gl.PALETTE4_RGB8_OES = 0x8b90 gl.PALETTE4_RGBA4_OES = 0x8b93 gl.PALETTE4_RGBA8_OES = 0x8b91 gl.PALETTE8_R5_G6_B5_OES = 0x8b97 gl.PALETTE8_RGB5_A1_OES = 0x8b99 gl.PALETTE8_RGB8_OES = 0x8b95 gl.PALETTE8_RGBA4_OES = 0x8b98 gl.PALETTE8_RGBA8_OES = 0x8b96 gl.PERCENTAGE_AMD = 0x8bc3 gl.PERFMON_GLOBAL_MODE_QCOM = 0x8fa0 gl.PERFMON_RESULT_AMD = 0x8bc6 gl.PERFMON_RESULT_AVAILABLE_AMD = 0x8bc4 gl.PERFMON_RESULT_SIZE_AMD = 0x8bc5 gl.POINTS = 0x0 gl.POLYGON_OFFSET_FACTOR = 0x8038 gl.POLYGON_OFFSET_FILL = 0x8037 gl.POLYGON_OFFSET_UNITS = 0x2a00 gl.PROGRAM = 0x82e2 gl.PROGRAM_BINARY_ANGLE = 0x93a6 gl.PROGRAM_BINARY_FORMATS_OES = 0x87ff gl.PROGRAM_BINARY_LENGTH_OES = 0x8741 gl.PROGRAM_OBJECT_EXT = 0x8b40 gl.PROGRAM_PIPELINE_BINDING_EXT = 0x825a gl.PROGRAM_PIPELINE_OBJECT_EXT = 0x8a4f gl.PROGRAM_SEPARABLE_EXT = 0x8258 gl.QCOM_alpha_test = 0x1 gl.QCOM_binning_control = 0x1 gl.QCOM_driver_control = 0x1 gl.QCOM_extended_get = 0x1 gl.QCOM_extended_get2 = 0x1 gl.QCOM_perfmon_global_mode = 0x1 gl.QCOM_tiled_rendering = 0x1 gl.QCOM_writeonly_rendering = 0x1 gl.QUERY = 0x82e3 gl.QUERY_OBJECT_EXT = 0x9153 gl.QUERY_RESULT_AVAILABLE_EXT = 0x8867 gl.QUERY_RESULT_EXT = 0x8866 gl.R16F_EXT = 0x822d gl.R32F_EXT = 0x822e gl.R8_EXT = 0x8229 gl.READ_BUFFER_EXT = 0xc02 gl.READ_BUFFER_NV = 0xc02 gl.READ_FRAMEBUFFER_ANGLE = 0x8ca8 gl.READ_FRAMEBUFFER_APPLE = 0x8ca8 gl.READ_FRAMEBUFFER_BINDING_ANGLE = 0x8caa gl.READ_FRAMEBUFFER_BINDING_APPLE = 0x8caa gl.READ_FRAMEBUFFER_BINDING_NV = 0x8caa gl.READ_FRAMEBUFFER_NV = 0x8ca8 gl.RED_BITS = 0xd52 gl.RED_EXT = 0x1903 gl.RENDERBUFFER = 0x8d41 gl.RENDERBUFFER_ALPHA_SIZE = 0x8d53 gl.RENDERBUFFER_BINDING = 0x8ca7 gl.RENDERBUFFER_BLUE_SIZE = 0x8d52 gl.RENDERBUFFER_DEPTH_SIZE = 0x8d54 gl.RENDERBUFFER_GREEN_SIZE = 0x8d51 gl.RENDERBUFFER_HEIGHT = 0x8d43 gl.RENDERBUFFER_INTERNAL_FORMAT = 0x8d44 gl.RENDERBUFFER_RED_SIZE = 0x8d50 gl.RENDERBUFFER_SAMPLES_ANGLE = 0x8cab gl.RENDERBUFFER_SAMPLES_APPLE = 0x8cab gl.RENDERBUFFER_SAMPLES_EXT = 0x8cab gl.RENDERBUFFER_SAMPLES_IMG = 0x9133 gl.RENDERBUFFER_SAMPLES_NV = 0x8cab gl.RENDERBUFFER_STENCIL_SIZE = 0x8d55 gl.RENDERBUFFER_WIDTH = 0x8d42 gl.RENDERER = 0x1f01 gl.RENDER_DIRECT_TO_FRAMEBUFFER_QCOM = 0x8fb3 gl.REPEAT = 0x2901 gl.REPLACE = 0x1e01 gl.REQUIRED_TEXTURE_IMAGE_UNITS_OES = 0x8d68 gl.RESET_NOTIFICATION_STRATEGY_EXT = 0x8256 gl.RG16F_EXT = 0x822f gl.RG32F_EXT = 0x8230 gl.RG8_EXT = 0x822b gl.RGB = 0x1907 gl.RGB10_A2_EXT = 0x8059 gl.RGB10_EXT = 0x8052 gl.RGB16F_EXT = 0x881b gl.RGB32F_EXT = 0x8815 gl.RGB565 = 0x8d62 gl.RGB565_OES = 0x8d62 gl.RGB5_A1 = 0x8057 gl.RGB5_A1_OES = 0x8057 gl.RGB8_OES = 0x8051 gl.RGBA = 0x1908 gl.RGBA16F_EXT = 0x881a gl.RGBA32F_EXT = 0x8814 gl.RGBA4 = 0x8056 gl.RGBA4_OES = 0x8056 gl.RGBA8_OES = 0x8058 gl.RGB_422_APPLE = 0x8a1f gl.RG_EXT = 0x8227 gl.SAMPLER = 0x82e6 gl.SAMPLER_2D = 0x8b5e gl.SAMPLER_2D_ARRAY_SHADOW_NV = 0x8dc4 gl.SAMPLER_2D_SHADOW_EXT = 0x8b62 gl.SAMPLER_3D_OES = 0x8b5f gl.SAMPLER_CUBE = 0x8b60 gl.SAMPLER_CUBE_SHADOW_NV = 0x8dc5 gl.SAMPLER_EXTERNAL_OES = 0x8d66 gl.SAMPLES = 0x80a9 gl.SAMPLE_ALPHA_TO_COVERAGE = 0x809e gl.SAMPLE_BUFFERS = 0x80a8 gl.SAMPLE_COVERAGE = 0x80a0 gl.SAMPLE_COVERAGE_INVERT = 0x80ab gl.SAMPLE_COVERAGE_VALUE = 0x80aa gl.SCISSOR_BOX = 0xc10 gl.SCISSOR_TEST = 0xc11 gl.SGX_BINARY_IMG = 0x8c0a gl.SGX_PROGRAM_BINARY_IMG = 0x9130 gl.SHADER = 0x82e1 gl.SHADER_BINARY_DMP = 0x9250 gl.SHADER_BINARY_FORMATS = 0x8df8 gl.SHADER_BINARY_VIV = 0x8fc4 gl.SHADER_COMPILER = 0x8dfa gl.SHADER_OBJECT_EXT = 0x8b48 gl.SHADER_SOURCE_LENGTH = 0x8b88 gl.SHADER_TYPE = 0x8b4f gl.SHADING_LANGUAGE_VERSION = 0x8b8c gl.SHORT = 0x1402 gl.SIGNALED_APPLE = 0x9119 gl.SLUMINANCE8_ALPHA8_NV = 0x8c45 gl.SLUMINANCE8_NV = 0x8c47 gl.SLUMINANCE_ALPHA_NV = 0x8c44 gl.SLUMINANCE_NV = 0x8c46 gl.SRC_ALPHA = 0x302 gl.SRC_ALPHA_SATURATE = 0x308 gl.SRC_COLOR = 0x300 gl.SRGB8_ALPHA8_EXT = 0x8c43 gl.SRGB8_NV = 0x8c41 gl.SRGB_ALPHA_EXT = 0x8c42 gl.SRGB_EXT = 0x8c40 gl.STACK_OVERFLOW = 0x503 gl.STACK_UNDERFLOW = 0x504 gl.STATE_RESTORE = 0x8bdc gl.STATIC_DRAW = 0x88e4 gl.STENCIL_ATTACHMENT = 0x8d20 gl.STENCIL_BACK_FAIL = 0x8801 gl.STENCIL_BACK_FUNC = 0x8800 gl.STENCIL_BACK_PASS_DEPTH_FAIL = 0x8802 gl.STENCIL_BACK_PASS_DEPTH_PASS = 0x8803 gl.STENCIL_BACK_REF = 0x8ca3 gl.STENCIL_BACK_VALUE_MASK = 0x8ca4 gl.STENCIL_BACK_WRITEMASK = 0x8ca5 gl.STENCIL_BITS = 0xd57 gl.STENCIL_BUFFER_BIT = 0x400 gl.STENCIL_BUFFER_BIT0_QCOM = 0x10000 gl.STENCIL_BUFFER_BIT1_QCOM = 0x20000 gl.STENCIL_BUFFER_BIT2_QCOM = 0x40000 gl.STENCIL_BUFFER_BIT3_QCOM = 0x80000 gl.STENCIL_BUFFER_BIT4_QCOM = 0x100000 gl.STENCIL_BUFFER_BIT5_QCOM = 0x200000 gl.STENCIL_BUFFER_BIT6_QCOM = 0x400000 gl.STENCIL_BUFFER_BIT7_QCOM = 0x800000 gl.STENCIL_CLEAR_VALUE = 0xb91 gl.STENCIL_EXT = 0x1802 gl.STENCIL_FAIL = 0xb94 gl.STENCIL_FUNC = 0xb92 gl.STENCIL_INDEX1_OES = 0x8d46 gl.STENCIL_INDEX4_OES = 0x8d47 gl.STENCIL_INDEX8 = 0x8d48 gl.STENCIL_PASS_DEPTH_FAIL = 0xb95 gl.STENCIL_PASS_DEPTH_PASS = 0xb96 gl.STENCIL_REF = 0xb97 gl.STENCIL_TEST = 0xb90 gl.STENCIL_VALUE_MASK = 0xb93 gl.STENCIL_WRITEMASK = 0xb98 gl.STREAM_DRAW = 0x88e0 gl.SUBPIXEL_BITS = 0xd50 gl.SYNC_CONDITION_APPLE = 0x9113 gl.SYNC_FENCE_APPLE = 0x9116 gl.SYNC_FLAGS_APPLE = 0x9115 gl.SYNC_FLUSH_COMMANDS_BIT_APPLE = 0x1 gl.SYNC_GPU_COMMANDS_COMPLETE_APPLE = 0x9117 gl.SYNC_OBJECT_APPLE = 0x8a53 gl.SYNC_STATUS_APPLE = 0x9114 gl.TEXTURE = 0x1702 gl.TEXTURE0 = 0x84c0 gl.TEXTURE1 = 0x84c1 gl.TEXTURE10 = 0x84ca gl.TEXTURE11 = 0x84cb gl.TEXTURE12 = 0x84cc gl.TEXTURE13 = 0x84cd gl.TEXTURE14 = 0x84ce gl.TEXTURE15 = 0x84cf gl.TEXTURE16 = 0x84d0 gl.TEXTURE17 = 0x84d1 gl.TEXTURE18 = 0x84d2 gl.TEXTURE19 = 0x84d3 gl.TEXTURE2 = 0x84c2 gl.TEXTURE20 = 0x84d4 gl.TEXTURE21 = 0x84d5 gl.TEXTURE22 = 0x84d6 gl.TEXTURE23 = 0x84d7 gl.TEXTURE24 = 0x84d8 gl.TEXTURE25 = 0x84d9 gl.TEXTURE26 = 0x84da gl.TEXTURE27 = 0x84db gl.TEXTURE28 = 0x84dc gl.TEXTURE29 = 0x84dd gl.TEXTURE3 = 0x84c3 gl.TEXTURE30 = 0x84de gl.TEXTURE31 = 0x84df gl.TEXTURE4 = 0x84c4 gl.TEXTURE5 = 0x84c5 gl.TEXTURE6 = 0x84c6 gl.TEXTURE7 = 0x84c7 gl.TEXTURE8 = 0x84c8 gl.TEXTURE9 = 0x84c9 gl.TEXTURE_2D = 0xde1 gl.TEXTURE_3D_OES = 0x806f gl.TEXTURE_BINDING_2D = 0x8069 gl.TEXTURE_BINDING_3D_OES = 0x806a gl.TEXTURE_BINDING_CUBE_MAP = 0x8514 gl.TEXTURE_BINDING_EXTERNAL_OES = 0x8d67 gl.TEXTURE_BORDER_COLOR_NV = 0x1004 gl.TEXTURE_COMPARE_FUNC_EXT = 0x884d gl.TEXTURE_COMPARE_MODE_EXT = 0x884c gl.TEXTURE_CUBE_MAP = 0x8513 gl.TEXTURE_CUBE_MAP_NEGATIVE_X = 0x8516 gl.TEXTURE_CUBE_MAP_NEGATIVE_Y = 0x8518 gl.TEXTURE_CUBE_MAP_NEGATIVE_Z = 0x851a gl.TEXTURE_CUBE_MAP_POSITIVE_X = 0x8515 gl.TEXTURE_CUBE_MAP_POSITIVE_Y = 0x8517 gl.TEXTURE_CUBE_MAP_POSITIVE_Z = 0x8519 gl.TEXTURE_DEPTH_QCOM = 0x8bd4 gl.TEXTURE_EXTERNAL_OES = 0x8d65 gl.TEXTURE_FORMAT_QCOM = 0x8bd6 gl.TEXTURE_HEIGHT_QCOM = 0x8bd3 gl.TEXTURE_IMAGE_VALID_QCOM = 0x8bd8 gl.TEXTURE_IMMUTABLE_FORMAT_EXT = 0x912f gl.TEXTURE_INTERNAL_FORMAT_QCOM = 0x8bd5 gl.TEXTURE_MAG_FILTER = 0x2800 gl.TEXTURE_MAX_ANISOTROPY_EXT = 0x84fe gl.TEXTURE_MAX_LEVEL_APPLE = 0x813d gl.TEXTURE_MIN_FILTER = 0x2801 gl.TEXTURE_NUM_LEVELS_QCOM = 0x8bd9 gl.TEXTURE_OBJECT_VALID_QCOM = 0x8bdb gl.TEXTURE_SAMPLES_IMG = 0x9136 gl.TEXTURE_TARGET_QCOM = 0x8bda gl.TEXTURE_TYPE_QCOM = 0x8bd7 gl.TEXTURE_USAGE_ANGLE = 0x93a2 gl.TEXTURE_WIDTH_QCOM = 0x8bd2 gl.TEXTURE_WRAP_R_OES = 0x8072 gl.TEXTURE_WRAP_S = 0x2802 gl.TEXTURE_WRAP_T = 0x2803 gl.TIMEOUT_EXPIRED_APPLE = 0x911b gl.TIMEOUT_IGNORED_APPLE = 0xffffffffffffffff gl.TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE = 0x93a0 gl.TRIANGLES = 0x4 gl.TRIANGLE_FAN = 0x6 gl.TRIANGLE_STRIP = 0x5 gl.TRUE = 0x1 gl.UNKNOWN_CONTEXT_RESET_EXT = 0x8255 gl.UNPACK_ALIGNMENT = 0xcf5 gl.UNPACK_ROW_LENGTH = 0xcf2 gl.UNPACK_SKIP_PIXELS = 0xcf4 gl.UNPACK_SKIP_ROWS = 0xcf3 gl.UNSIGNALED_APPLE = 0x9118 gl.UNSIGNED_BYTE = 0x1401 gl.UNSIGNED_INT = 0x1405 gl.UNSIGNED_INT64_AMD = 0x8bc2 gl.UNSIGNED_INT_10_10_10_2_OES = 0x8df6 gl.UNSIGNED_INT_24_8_OES = 0x84fa gl.UNSIGNED_INT_2_10_10_10_REV_EXT = 0x8368 gl.UNSIGNED_NORMALIZED_EXT = 0x8c17 gl.UNSIGNED_SHORT = 0x1403 gl.UNSIGNED_SHORT_1_5_5_5_REV_EXT = 0x8366 gl.UNSIGNED_SHORT_4_4_4_4 = 0x8033 gl.UNSIGNED_SHORT_4_4_4_4_REV_EXT = 0x8365 gl.UNSIGNED_SHORT_4_4_4_4_REV_IMG = 0x8365 gl.UNSIGNED_SHORT_5_5_5_1 = 0x8034 gl.UNSIGNED_SHORT_5_6_5 = 0x8363 gl.UNSIGNED_SHORT_8_8_APPLE = 0x85ba gl.UNSIGNED_SHORT_8_8_REV_APPLE = 0x85bb gl.VALIDATE_STATUS = 0x8b83 gl.VENDOR = 0x1f00 gl.VERSION = 0x1f02 gl.VERTEX_ARRAY_BINDING_OES = 0x85b5 gl.VERTEX_ARRAY_OBJECT_EXT = 0x9154 gl.VERTEX_ATTRIB_ARRAY_BUFFER_BINDING = 0x889f gl.VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE = 0x88fe gl.VERTEX_ATTRIB_ARRAY_DIVISOR_NV = 0x88fe gl.VERTEX_ATTRIB_ARRAY_ENABLED = 0x8622 gl.VERTEX_ATTRIB_ARRAY_NORMALIZED = 0x886a gl.VERTEX_ATTRIB_ARRAY_POINTER = 0x8645 gl.VERTEX_ATTRIB_ARRAY_SIZE = 0x8623 gl.VERTEX_ATTRIB_ARRAY_STRIDE = 0x8624 gl.VERTEX_ATTRIB_ARRAY_TYPE = 0x8625 gl.VERTEX_SHADER = 0x8b31 gl.VERTEX_SHADER_BIT_EXT = 0x1 gl.VIEWPORT = 0xba2 gl.VIV_shader_binary = 0x1 gl.WAIT_FAILED_APPLE = 0x911d gl.WRITEONLY_RENDERING_QCOM = 0x8823 gl.WRITE_ONLY_OES = 0x88b9 gl.Z400_BINARY_AMD = 0x8740 gl.ZERO = 0x0 gl.VERTEX_ATTRIB_POINTER_VEC3 = 0 gl.VERTEX_ATTRIB_POINTER_COLOR4B = 1
mit
Innixma/dex
packs/Dex1/Scripts/defaultLevels/base_2.lua
2
1219
-- include useful files execScript("utils.lua") execScript("common.lua") execScript("commonpatterns.lua") -- this function adds a pattern to the timeline based on a key function addPattern(mKey) if mKey == 0 then cWallEx(math.random(0, getSides()), math.random(0, 0)) wait(getPerfectDelay(THICKNESS) * 6) end end -- shuffle the keys, and then call them to add all the patterns -- shuffling is better than randomizing - it guarantees all the patterns will be called keys = { 0 } keys = shuffle(keys) index = 0 -- onLoad is an hardcoded function that is called when the level is started/restarted function onLoad() end -- onStep is an hardcoded function that is called when the level timeline is empty -- onStep should contain your pattern spawning logic function onStep() addPattern(keys[index]) index = index + 1 if index - 1 == table.getn(keys) then index = 1 end end -- onIncrement is an hardcoded function that is called when the level difficulty is incremented function onIncrement() end -- onUnload is an hardcoded function that is called when the level is closed/restarted function onUnload() end -- onUpdate is an hardcoded function that is called every frame function onUpdate(mFrameTime) end
mit
Shell64/LuaWebserver2
Bin/Windows_x64/socket/socket/ftp.lua
144
9120
----------------------------------------------------------------------------- -- FTP support for the Lua language -- LuaSocket toolkit. -- Author: Diego Nehab -- RCS ID: $Id: ftp.lua,v 1.45 2007/07/11 19:25:47 diego Exp $ ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local table = require("table") local string = require("string") local math = require("math") local socket = require("socket") local url = require("socket.url") local tp = require("socket.tp") local ltn12 = require("ltn12") module("socket.ftp") ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- -- timeout in seconds before the program gives up on a connection TIMEOUT = 60 -- default port for ftp service PORT = 21 -- this is the default anonymous password. used when no password is -- provided in url. should be changed to your e-mail. USER = "ftp" PASSWORD = "anonymous@anonymous.org" ----------------------------------------------------------------------------- -- Low level FTP API ----------------------------------------------------------------------------- local metat = { __index = {} } function open(server, port, create) local tp = socket.try(tp.connect(server, port or PORT, TIMEOUT, create)) local f = base.setmetatable({ tp = tp }, metat) -- make sure everything gets closed in an exception f.try = socket.newtry(function() f:close() end) return f end function metat.__index:portconnect() self.try(self.server:settimeout(TIMEOUT)) self.data = self.try(self.server:accept()) self.try(self.data:settimeout(TIMEOUT)) end function metat.__index:pasvconnect() self.data = self.try(socket.tcp()) self.try(self.data:settimeout(TIMEOUT)) self.try(self.data:connect(self.pasvt.ip, self.pasvt.port)) end function metat.__index:login(user, password) self.try(self.tp:command("user", user or USER)) local code, reply = self.try(self.tp:check{"2..", 331}) if code == 331 then self.try(self.tp:command("pass", password or PASSWORD)) self.try(self.tp:check("2..")) end return 1 end function metat.__index:pasv() self.try(self.tp:command("pasv")) local code, reply = self.try(self.tp:check("2..")) local pattern = "(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)%D(%d+)" local a, b, c, d, p1, p2 = socket.skip(2, string.find(reply, pattern)) self.try(a and b and c and d and p1 and p2, reply) self.pasvt = { ip = string.format("%d.%d.%d.%d", a, b, c, d), port = p1*256 + p2 } if self.server then self.server:close() self.server = nil end return self.pasvt.ip, self.pasvt.port end function metat.__index:port(ip, port) self.pasvt = nil if not ip then ip, port = self.try(self.tp:getcontrol():getsockname()) self.server = self.try(socket.bind(ip, 0)) ip, port = self.try(self.server:getsockname()) self.try(self.server:settimeout(TIMEOUT)) end local pl = math.mod(port, 256) local ph = (port - pl)/256 local arg = string.gsub(string.format("%s,%d,%d", ip, ph, pl), "%.", ",") self.try(self.tp:command("port", arg)) self.try(self.tp:check("2..")) return 1 end function metat.__index:send(sendt) self.try(self.pasvt or self.server, "need port or pasv first") -- if there is a pasvt table, we already sent a PASV command -- we just get the data connection into self.data if self.pasvt then self:pasvconnect() end -- get the transfer argument and command local argument = sendt.argument or url.unescape(string.gsub(sendt.path or "", "^[/\\]", "")) if argument == "" then argument = nil end local command = sendt.command or "stor" -- send the transfer command and check the reply self.try(self.tp:command(command, argument)) local code, reply = self.try(self.tp:check{"2..", "1.."}) -- if there is not a a pasvt table, then there is a server -- and we already sent a PORT command if not self.pasvt then self:portconnect() end -- get the sink, source and step for the transfer local step = sendt.step or ltn12.pump.step local readt = {self.tp.c} local checkstep = function(src, snk) -- check status in control connection while downloading local readyt = socket.select(readt, nil, 0) if readyt[tp] then code = self.try(self.tp:check("2..")) end return step(src, snk) end local sink = socket.sink("close-when-done", self.data) -- transfer all data and check error self.try(ltn12.pump.all(sendt.source, sink, checkstep)) if string.find(code, "1..") then self.try(self.tp:check("2..")) end -- done with data connection self.data:close() -- find out how many bytes were sent local sent = socket.skip(1, self.data:getstats()) self.data = nil return sent end function metat.__index:receive(recvt) self.try(self.pasvt or self.server, "need port or pasv first") if self.pasvt then self:pasvconnect() end local argument = recvt.argument or url.unescape(string.gsub(recvt.path or "", "^[/\\]", "")) if argument == "" then argument = nil end local command = recvt.command or "retr" self.try(self.tp:command(command, argument)) local code = self.try(self.tp:check{"1..", "2.."}) if not self.pasvt then self:portconnect() end local source = socket.source("until-closed", self.data) local step = recvt.step or ltn12.pump.step self.try(ltn12.pump.all(source, recvt.sink, step)) if string.find(code, "1..") then self.try(self.tp:check("2..")) end self.data:close() self.data = nil return 1 end function metat.__index:cwd(dir) self.try(self.tp:command("cwd", dir)) self.try(self.tp:check(250)) return 1 end function metat.__index:type(type) self.try(self.tp:command("type", type)) self.try(self.tp:check(200)) return 1 end function metat.__index:greet() local code = self.try(self.tp:check{"1..", "2.."}) if string.find(code, "1..") then self.try(self.tp:check("2..")) end return 1 end function metat.__index:quit() self.try(self.tp:command("quit")) self.try(self.tp:check("2..")) return 1 end function metat.__index:close() if self.data then self.data:close() end if self.server then self.server:close() end return self.tp:close() end ----------------------------------------------------------------------------- -- High level FTP API ----------------------------------------------------------------------------- local function override(t) if t.url then local u = url.parse(t.url) for i,v in base.pairs(t) do u[i] = v end return u else return t end end local function tput(putt) putt = override(putt) socket.try(putt.host, "missing hostname") local f = open(putt.host, putt.port, putt.create) f:greet() f:login(putt.user, putt.password) if putt.type then f:type(putt.type) end f:pasv() local sent = f:send(putt) f:quit() f:close() return sent end local default = { path = "/", scheme = "ftp" } local function parse(u) local t = socket.try(url.parse(u, default)) socket.try(t.scheme == "ftp", "wrong scheme '" .. t.scheme .. "'") socket.try(t.host, "missing hostname") local pat = "^type=(.)$" if t.params then t.type = socket.skip(2, string.find(t.params, pat)) socket.try(t.type == "a" or t.type == "i", "invalid type '" .. t.type .. "'") end return t end local function sput(u, body) local putt = parse(u) putt.source = ltn12.source.string(body) return tput(putt) end put = socket.protect(function(putt, body) if base.type(putt) == "string" then return sput(putt, body) else return tput(putt) end end) local function tget(gett) gett = override(gett) socket.try(gett.host, "missing hostname") local f = open(gett.host, gett.port, gett.create) f:greet() f:login(gett.user, gett.password) if gett.type then f:type(gett.type) end f:pasv() f:receive(gett) f:quit() return f:close() end local function sget(u) local gett = parse(u) local t = {} gett.sink = ltn12.sink.table(t) tget(gett) return table.concat(t) end command = socket.protect(function(cmdt) cmdt = override(cmdt) socket.try(cmdt.host, "missing hostname") socket.try(cmdt.command, "missing command") local f = open(cmdt.host, cmdt.port, cmdt.create) f:greet() f:login(cmdt.user, cmdt.password) f.try(f.tp:command(cmdt.command, cmdt.argument)) if cmdt.check then f.try(f.tp:check(cmdt.check)) end f:quit() return f:close() end) get = socket.protect(function(gett) if base.type(gett) == "string" then return sget(gett) else return tget(gett) end end)
lgpl-2.1
opentechinstitute/luci
modules/admin-full/luasrc/model/cbi/admin_system/system.lua
37
5651
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.fs") require("luci.config") local m, s, o local has_ntpd = luci.fs.access("/usr/sbin/ntpd") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) m:chain("luci") s = m:section(TypedSection, "system", translate("System Properties")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("logging", translate("Logging")) s:tab("language", translate("Language and Style")) -- -- System Properties -- o = s:taboption("general", DummyValue, "_systime", translate("Local Time")) o.template = "admin_system/clock_status" o = s:taboption("general", Value, "hostname", translate("Hostname")) o.datatype = "hostname" function o.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end o = s:taboption("general", ListValue, "zonename", translate("Timezone")) o:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do o:value(zone[1]) end function o.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) local timezone = lookup_zone(value) or "GMT0" self.map.uci:set("system", section, "timezone", timezone) luci.fs.writefile("/etc/TZ", timezone .. "\n") end -- -- Logging -- o = s:taboption("logging", Value, "log_size", translate("System log buffer size"), "kiB") o.optional = true o.placeholder = 16 o.datatype = "uinteger" o = s:taboption("logging", Value, "log_ip", translate("External system log server")) o.optional = true o.placeholder = "0.0.0.0" o.datatype = "ip4addr" o = s:taboption("logging", Value, "log_port", translate("External system log server port")) o.optional = true o.placeholder = 514 o.datatype = "port" o = s:taboption("logging", ListValue, "conloglevel", translate("Log output level")) o:value(8, translate("Debug")) o:value(7, translate("Info")) o:value(6, translate("Notice")) o:value(5, translate("Warning")) o:value(4, translate("Error")) o:value(3, translate("Critical")) o:value(2, translate("Alert")) o:value(1, translate("Emergency")) o = s:taboption("logging", ListValue, "cronloglevel", translate("Cron Log Level")) o.default = 8 o:value(5, translate("Debug")) o:value(8, translate("Normal")) o:value(9, translate("Warning")) -- -- Langauge & Style -- o = s:taboption("language", ListValue, "_lang", translate("Language")) o:value("auto") local i18ndir = luci.i18n.i18ndir .. "base." for k, v in luci.util.kspairs(luci.config.languages) do local file = i18ndir .. k:gsub("_", "-") if k:sub(1, 1) ~= "." and luci.fs.access(file .. ".lmo") then o:value(k, v) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "lang") end function o.write(self, section, value) m.uci:set("luci", "main", "lang", value) end o = s:taboption("language", ListValue, "_mediaurlbase", translate("Design")) for k, v in pairs(luci.config.themes) do if k:sub(1, 1) ~= "." then o:value(v, k) end end function o.cfgvalue(...) return m.uci:get("luci", "main", "mediaurlbase") end function o.write(self, section, value) m.uci:set("luci", "main", "mediaurlbase", value) end -- -- NTP -- if has_ntpd then -- timeserver setup was requested, create section and reload page if m:formvalue("cbid.system._timeserver._enable") then m.uci:section("system", "timeserver", "ntp", { server = { "0.openwrt.pool.ntp.org", "1.openwrt.pool.ntp.org", "2.openwrt.pool.ntp.org", "3.openwrt.pool.ntp.org" } } ) m.uci:save("system") luci.http.redirect(luci.dispatcher.build_url("admin/system", arg[1])) return end local has_section = false m.uci:foreach("system", "timeserver", function(s) has_section = true return false end) if not has_section then s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.cfgsections = function() return { "_timeserver" } end x = s:option(Button, "_enable") x.title = translate("Time Synchronization is not configured yet.") x.inputtitle = translate("Set up Time Synchronization") x.inputstyle = "apply" else s = m:section(TypedSection, "timeserver", translate("Time Synchronization")) s.anonymous = true s.addremove = false o = s:option(Flag, "enable", translate("Enable NTP client")) o.rmempty = false function o.cfgvalue(self) return luci.sys.init.enabled("sysntpd") and self.enabled or self.disabled end function o.write(self, section, value) if value == self.enabled then luci.sys.init.enable("sysntpd") luci.sys.call("env -i /etc/init.d/sysntpd start >/dev/null") else luci.sys.call("env -i /etc/init.d/sysntpd stop >/dev/null") luci.sys.init.disable("sysntpd") end end o = s:option(Flag, "enable_server", translate("Provide NTP server")) o:depends("enable", "1") o = s:option(DynamicList, "server", translate("NTP server candidates")) o.datatype = "host" o:depends("enable", "1") -- retain server list even if disabled function o.remove() end end end return m
apache-2.0
OTRD5k/Free-D
Plugin/Main/ClassGetter/Libraries.lua
1
3335
local module = {} module.float2hex = function(n) if n == 0.0 then return 0.0 end local sign = 0 if n < 0.0 then sign = 0x80 n = -n end local mant, expo = math.frexp(n) local hext = {} if mant ~= mant then hext[#hext+1] = string.char(0xFF, 0x88, 0x00, 0x00) elseif mant == math.huge or expo > 0x80 then if sign == 0 then hext[#hext+1] = string.char(0x7F, 0x80, 0x00, 0x00) else hext[#hext+1] = string.char(0xFF, 0x80, 0x00, 0x00) end elseif (mant == 0.0 and expo == 0) or expo < -0x7E then hext[#hext+1] = string.char(sign, 0x00, 0x00, 0x00) else expo = expo + 0x7E mant = (mant * 2.0 - 1.0) * math.ldexp(0.5, 24) hext[#hext+1] = string.char(sign + math.floor(expo / 0x2), (expo % 0x2) * 0x80 + math.floor(mant / 0x10000), math.floor(mant / 0x100) % 0x100, mant % 0x100) end return tonumber(string.gsub(table.concat(hext),"(.)", function (c) return string.format("%02X%s",string.byte(c),"") end), 16) end module.splittobytes = function(floatstring) local length = string.len(floatstring) for i=length, 7 do floatstring = "0" .. floatstring end return string.upper(floatstring) end module.Num = 0 module.ExportVertex = function(x,y,z, color3) local stringv = Instance.new("StringValue") stringv.Value = "asfasd" --[[if color3 ~= nil then --couldnt get materials to work right sadly local r = color3.r local g = color3.g local b = color3.b local part = Instance.new("Part") part.Parent = game.Workspace part.CFrame = CFrame.new(0,module.Num*2,0) part.BrickColor = BrickColor.new(color3) module.Num = module.Num +1 print(r .. " " .. g .. " " .. b) r = string.upper(module.splittobytes(("%x"):format(module.float2hex(r)))) g = string.upper(module.splittobytes(("%x"):format(module.float2hex(g)))) b = string.upper(module.splittobytes(("%x"):format(module.float2hex(b)))) stringv.Value = "FREE-D" .. " ADD VERT " .. string.upper(module.splittobytes(("%x"):format(module.float2hex(x)))) .. string.upper(module.splittobytes(("%x"):format(module.float2hex(y)))) .. string.upper(module.splittobytes(("%x"):format(module.float2hex(z)))) .. r .. g .. b else stringv.Value = "FREE-D" .. " ADD VERT " .. string.upper(module.splittobytes(("%x"):format(module.float2hex(x)))) .. string.upper(module.splittobytes(("%x"):format(module.float2hex(y)))) .. string.upper(module.splittobytes(("%x"):format(module.float2hex(z)))) .. "3F800000" .. "3F800000" .. "3F800000" end--]] stringv.Value = "FREE-D" .. " ADD VERT " .. string.upper(module.splittobytes(("%x"):format(module.float2hex(x)))) .. string.upper(module.splittobytes(("%x"):format(module.float2hex(y)))) .. string.upper(module.splittobytes(("%x"):format(module.float2hex(z)))) .. "3F800000" .. "3F800000" .. "3F800000" end module.ExportFace = function(v1, v2, v3) local stringv = Instance.new("StringValue") stringv.Value = "asfasd" stringv.Value = "FREE-D" .. " ADD FACE " .. module.splittobytes(("%x"):format(v1)) .. module.splittobytes(("%x"):format(v2)) .. module.splittobytes(("%x"):format(v3)) end return module
gpl-2.0
sumefsp/zile
lib/zile/FileString.lua
1
8222
-- Copyright (c) 2011-2014 Free Software Foundation, Inc. -- -- This file is part of GNU Zile. -- -- 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, 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/>. --[[-- Mutable strings with line-ending encodings All the indexes passed to methods use 1-based counting. @classmod zile.FileString ]] local MutableString = require "zile.MutableString" local Object = require "std.object" -- Formats of end-of-line coding_eol_lf = "\n" coding_eol_crlf = "\r\n" coding_eol_cr = "\r" -- Maximum number of EOLs to check before deciding eol type arbitrarily. local max_eol_check_count = 3 ------ -- An line-ending encoding string buffer object. -- @table FileString -- @param s a MutableString -- @string eol line ending encoding local FileString -- documentation below to stop LDoc complaining there are no docs!! local function bytes (self) return #self.s end ------ -- Number of bytes in the string. -- @function bytes -- @treturn int byte length of string --- Concatenate another string. -- @string src additional string -- @treturn FileString modified concatenated object local function cat (self, src) local oldlen = #self.s self.s:insert (oldlen + 1, src:len (self.eol)) return self:replace (oldlen + 1, src) end --- Position of first end-of-line following `o`. -- @int o start position -- @treturn int position of first following end-of-line local function end_of_line (self, o) local next = self.find (self.s, self.eol, o) return next or #self.s + 1 end --- Create an unused `n` byte _hole_. -- Enlarge the array if necessary and move everything starting at -- `from`, `n` bytes to the right. -- @function insert -- @int from index of the first byte of the new _hole_ -- @int n number of empty bytes to insert local function insert (self, from, n) self.s:insert (from, n) end --- Encoded length. -- @string eol_type line-end string -- @treturn int length of string using `eol_type` line endings local function len (self, eol_type) -- FIXME in Lua 5.2 use __len metamethod return self:bytes () + self:lines () * (#eol_type - #self.eol) end --- Number of lines. -- @treturn int number of lines. local function lines (self) local lines, next = -1, 1 repeat next = self:next_line (next) lines = lines + 1 until not next return lines end --- Move `n` bytes from `from` to `to`. The two byte strings may -- overlap. -- @int to start of destination within this MutableString -- @int from start of source bytes within the MutableString -- @int n number of bytes to move local function move (self, to, from, n) self.s:move (to, from, n) end --- Position of start of immediately following line. -- @int o start position -- @treturn int position of start of next line local function next_line (self, o) local eo = self:end_of_line (o) return eo <= #self.s and eo + #self.eol or nil end --- Position of start of immediately preceding line. -- @int o start position -- @treturn int position of start of previous line local function prev_line (self, o) local so = self:start_of_line (o) return so ~= 1 and self:start_of_line (so - #self.eol) or nil end --- Remove `n` bytes starting at `from`. -- There is no _hole_ afterwards; the following bytes are moved up to -- fill it. The total size of the MutableString may be reduced. -- @function remove -- @int from index of first byte to remove -- @int n number of bytes to remove local function remove (self, from, n) self.s:remove (from, n) end --- Overwrite bytes starting at `from` with bytes from `rep`. -- @int from index of first byte to replace -- @string src replacement string local function replace (self, from, src) local s = 1 local len = #src.s while len > 0 do local next = src.s:find (src.eol, s + #src.eol + 1) local line_len = next and next - s or len self.s:replace (from, src.s:sub (s, s + line_len)) from = from + line_len len = len - line_len s = next if len > 0 then self.s:replace (from, self.eol) s = s + #src.eol len = len - #src.eol from = from + #self.eol end end return self end --- Position of first end-of-line preceding `o`. -- @int o start position -- @treturn int position of first preceding end-of-line local function start_of_line (self, o) local prev = self.rfind (self.s, self.eol, o) return prev and prev + #self.eol or 1 end --- Set `n` bytes starting at `from` to the first character of `c`. -- @int from index of first byte to set -- @string c a one character string -- @int n number of bytes to set local function set (self, from, c, n) self.s:set (from, c, n) end --- Return a copy of a substring of this MutableString. -- @int from the index of the first element to copy. -- @int[opt=end-of-string] to the index of the last element to copy. -- @treturn string a new Lua string local function sub (self, from, to) return self.s:sub (from, to) end --- @export local methods = { bytes = bytes, cat = cat, end_of_line = end_of_line, insert = insert, len = len, lines = lines, move = move, next_line = next_line, prev_line = prev_line, remove = remove, replace = replace, start_of_line = start_of_line, set = set, sub = sub, } FileString = Object { _type = "FileString", --- Instantiate a newly cloned object. -- @function __call -- @string s a Lua string -- @string eol line-ending encoding -- @treturn FileString a new FileString object _init = function (self, s, eol) if eol then -- if eol supplied, use it self.eol = eol else -- otherwise, guess local first_eol = true local total_eols = 0 self.eol = coding_eol_lf local i = 1 while i <= #s and total_eols < max_eol_check_count do local c = s[i] if c == '\n' or c == '\r' then local this_eol_type total_eols = total_eols + 1 if c == '\n' then this_eol_type = coding_eol_lf elseif i == #s or s[i + 1] ~= '\n' then this_eol_type = coding_eol_cr else this_eol_type = coding_eol_crlf i = i + 1 end if first_eol then -- This is the first end-of-line. self.eol = this_eol_type first_eol = false elseif self.eol ~= this_eol_type then -- This EOL is different from the last; arbitrarily choose LF. self.eol = coding_eol_lf break end end i = i + 1 end end if type (s) == "string" then self.s = MutableString (s) if #self.eol == 1 then -- Use faster search functions for single-char eols. self.find, self.rfind = MutableString.chr, MutableString.rchr else self.find, self.rfind = MutableString.find, MutableString.rfind end else self.s = s -- Non-MutableStrings have to provide their own find and rfind -- functions. self.find, self.rfind = self.s.find, self.s.rfind end return self end, --- Return the string contents. -- @function __tostring __tostring = function (self) return tostring (self.s) end, --- Return the `n`th character. -- @function __index -- @int n 1-based index -- @treturn string the character at index `n` __index = function (self, n) return case (type (n), { -- Do character lookup with an integer... number = function () return self.s[n] end, -- ...otherwise dispatch to method table. function () return methods[n] end, }) end, } return FileString
gpl-3.0
luanorlandi/Swift-Space-Battle
src/main.lua
2
1067
--[[ -------------------------------------------------------------------------------- This is a free game developed by Luan Orlandi in project of scientific research at ICMC-USP, guided by Leandro Fiorini Aurichi and supported by CNPq For more information, access https://github.com/luanorlandi/Swift-Space-Battle -------------------------------------------------------------------------------- ]] MOAILogMgr.setLogLevel(MOAILogMgr.LOG_NONE) require "file/saveLocation" require "file/strings" require "math/area" require "math/util" require "window/window" window = Window:new() require "interface/priority" require "loop/ingame" require "loop/inmenu" require "loop/inintro" require "input/input" input = Input:new() input:tryEnableKeyboard() input:tryEnableMouse() input:tryEnableTouch() local timeThread = MOAICoroutine.new() timeThread:run(getTime) local introThread = MOAICoroutine.new() introThread:run(introLoop) --local menuThread = MOAICoroutine.new() --menuThread:run(menuLoop) --local mainThread = MOAICoroutine.new() --mainThread:run(gameLoop)
gpl-3.0
lizh06/premake-core
tests/tools/test_snc.lua
16
3478
-- -- tests/test_snc.lua -- Automated test suite for the SNC toolset interface. -- Copyright (c) 2012-2013 Jason Perkins and the Premake project -- local suite = test.declare("tools_snc") local snc = premake.tools.snc -- -- Setup/teardown -- local wks, prj, cfg function suite.setup() wks, prj = test.createWorkspace() system "PS3" end local function prepare() cfg = test.getconfig(prj, "Debug") end -- -- Check the selection of tools based on the target system. -- function suite.tools_onDefaults() prepare() test.isnil(snc.gettoolname(cfg, "cc")) test.isnil(snc.gettoolname(cfg, "cxx")) test.isnil(snc.gettoolname(cfg, "ar")) end function suite.tools_onPS3() system "PS3" prepare() test.isnil(snc.gettoolname(cfg, "cc")) test.isnil(snc.gettoolname(cfg, "cxx")) test.isnil(snc.gettoolname(cfg, "ar")) end -- -- By default, the -MMD -MP are used to generate dependencies. -- function suite.cppflags_defaultWithMMD() prepare() test.isequal({ "-MMD", "-MP" }, snc.getcppflags(cfg)) end -- -- Check the translation of CFLAGS. -- function suite.cflags_onFatalWarnings() flags { "FatalWarnings" } prepare() test.isequal({ "-Xquit=2" }, snc.getcflags(cfg)) end -- -- Check the optimization flags. -- function suite.cflags_onNoOptimize() optimize "Off" prepare() test.isequal({ "-O0" }, snc.getcflags(cfg)) end function suite.cflags_onOptimize() optimize "On" prepare() test.isequal({ "-O1" }, snc.getcflags(cfg)) end function suite.cflags_onOptimizeSize() optimize "Size" prepare() test.isequal({ "-Os" }, snc.getcflags(cfg)) end function suite.cflags_onOptimizeSpeed() optimize "Speed" prepare() test.isequal({ "-O2" }, snc.getcflags(cfg)) end function suite.cflags_onOptimizeFull() optimize "Full" prepare() test.isequal({ "-O3" }, snc.getcflags(cfg)) end function suite.cflags_onOptimizeDebug() optimize "Debug" prepare() test.isequal({ "-Od" }, snc.getcflags(cfg)) end -- -- Turn on exceptions and RTTI by default, to match the other Premake supported toolsets. -- function suite.cxxflags_onDefault() prepare() test.isequal({ "-Xc+=exceptions", "-Xc+=rtti" }, snc.getcxxflags(cfg)) end -- -- Check the translation of LDFLAGS. -- function suite.cflags_onDefaults() prepare() test.isequal({ "-s" }, snc.getldflags(cfg)) end -- -- Check the formatting of linked libraries. -- function suite.links_onSystemLibs() links { "fs_stub", "net_stub" } prepare() test.isequal({ "-lfs_stub", "-lnet_stub" }, snc.getlinks(cfg)) end -- -- When linking to a static sibling library, the relative path to the library -- should be used instead of the "-l" flag. This prevents linking against a -- shared library of the same name, should one be present. -- function suite.links_onStaticSiblingLibrary() links { "MyProject2" } test.createproject(wks) system "Linux" kind "StaticLib" location "MyProject2" targetdir "lib" prepare() test.isequal({ "lib/libMyProject2.a" }, snc.getlinks(cfg)) end -- -- When linking object files, leave off the "-l". -- function suite.links_onObjectFile() links { "generated.o" } prepare() test.isequal({ "generated.o" }, snc.getlinks(cfg)) end -- -- Check handling of forced includes. -- function suite.forcedIncludeFiles() forceincludes { "stdafx.h", "include/sys.h" } prepare() test.isequal({'-include stdafx.h', '-include include/sys.h'}, snc.getforceincludes(cfg)) end
bsd-3-clause
ld-test/hotswap
src/hotswap/ev.lua
11
1130
local posix = require "posix" local ev = require "ev" local xxhash = require "xxhash" local Hotswap = getmetatable (require "hotswap") local Ev = {} function Ev.new (t) return Hotswap.new { new = Ev.new, observe = Ev.observe, loop = t and t.loop or ev.Loop.default, observed = {}, hashes = {}, seed = 0x5bd1e995, } end function Ev:observe (name, filename) if self.observed [name] then return end do local file = assert (io.open (filename, "r")) self.hashes [name] = xxhash.xxh32 (file:read "*all", self.seed) file:close () end local hotswap = self local current = filename repeat local stat = ev.Stat.new (function () local file = assert (io.open (filename, "r")) local hash = xxhash.xxh32 (file:read "*all", self.seed) file:close () if hash ~= self.hashes [name] then hotswap.loaded [name] = nil hotswap.try_require (name) end end, current) self.observed [current] = stat stat:start (hotswap.loop) current = posix.readlink (current) until not current end return Ev.new ()
mit
maxrio/packages981213
net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/interfaceconfig.lua
4
7228
-- ------ extra functions ------ -- function interfaceCheck() metricValue = ut.trim(sys.exec("uci -p /var/state get network." .. arg[1] .. ".metric")) if metricValue == "" then -- no metric errorNoMetric = 1 else -- if metric exists create list of interface metrics to compare against for duplicates uci.cursor():foreach("mwan3", "interface", function (section) local metricValue = ut.trim(sys.exec("uci -p /var/state get network." .. section[".name"] .. ".metric")) metricList = metricList .. section[".name"] .. " " .. metricValue .. "\n" end ) -- compare metric against list local metricDuplicateNumbers, metricDuplicates = sys.exec("echo '" .. metricList .. "' | awk '{print $2}' | uniq -d"), "" for line in metricDuplicateNumbers:gmatch("[^\r\n]+") do metricDuplicates = sys.exec("echo '" .. metricList .. "' | grep '" .. line .. "' | awk '{print $1}'") errorDuplicateMetricList = errorDuplicateMetricList .. metricDuplicates end if sys.exec("echo '" .. errorDuplicateMetricList .. "' | grep -w " .. arg[1]) ~= "" then errorDuplicateMetric = 1 end end -- check if this interface has a higher reliability requirement than track IPs configured local trackingNumber = tonumber(ut.trim(sys.exec("echo $(uci -p /var/state get mwan3." .. arg[1] .. ".track_ip) | wc -w"))) if trackingNumber > 0 then local reliabilityNumber = tonumber(ut.trim(sys.exec("uci -p /var/state get mwan3." .. arg[1] .. ".reliability"))) if reliabilityNumber and reliabilityNumber > trackingNumber then errorReliability = 1 end end -- check if any interfaces are not properly configured in /etc/config/network or have no default route in main routing table if ut.trim(sys.exec("uci -p /var/state get network." .. arg[1])) == "interface" then local interfaceDevice = ut.trim(sys.exec("uci -p /var/state get network." .. arg[1] .. ".ifname")) if interfaceDevice == "uci: Entry not found" or interfaceDevice == "" then errorNetConfig = 1 errorRoute = 1 else local routeCheck = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $1}'")) if routeCheck == "" then errorRoute = 1 end end else errorNetConfig = 1 errorRoute = 1 end end function interfaceWarnings() -- display warning messages at the top of the page local warns, lineBreak = "", "" if errorReliability == 1 then warns = "<font color=\"ff0000\"><strong>WARNING: this interface has a higher reliability requirement than there are tracking IP addresses!</strong></font>" lineBreak = "<br /><br />" end if errorRoute == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface has no default route in the main routing table!</strong></font>" lineBreak = "<br /><br />" end if errorNetConfig == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface is configured incorrectly or not at all in /etc/config/network!</strong></font>" lineBreak = "<br /><br />" end if errorNoMetric == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this interface has no metric configured in /etc/config/network!</strong></font>" elseif errorDuplicateMetric == 1 then warns = warns .. lineBreak .. "<font color=\"ff0000\"><strong>WARNING: this and other interfaces have duplicate metrics configured in /etc/config/network!</strong></font>" end return warns end -- ------ interface configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" arg[1] = arg[1] or "" metricValue = "" metricList = "" errorDuplicateMetricList = "" errorNoMetric = 0 errorDuplicateMetric = 0 errorRoute = 0 errorNetConfig = 0 errorReliability = 0 interfaceCheck() m5 = Map("mwan3", translate("MWAN Interface Configuration - ") .. arg[1], translate(interfaceWarnings())) m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "interface") mwan_interface = m5:section(NamedSection, arg[1], "interface", "") mwan_interface.addremove = false mwan_interface.dynamic = false enabled = mwan_interface:option(ListValue, "enabled", translate("Enabled")) enabled.default = "1" enabled:value("1", translate("Yes")) enabled:value("0", translate("No")) track_ip = mwan_interface:option(DynamicList, "track_ip", translate("Tracking IP"), translate("This IP address will be pinged to dermine if the link is up or down. Leave blank to assume interface is always online")) track_ip.datatype = "ipaddr" reliability = mwan_interface:option(Value, "reliability", translate("Tracking reliability"), translate("Acceptable values: 1-100. This many Tracking IP addresses must respond for the link to be deemed up")) reliability.datatype = "range(1, 100)" reliability.default = "1" count = mwan_interface:option(ListValue, "count", translate("Ping count")) count.default = "1" count:value("1") count:value("2") count:value("3") count:value("4") count:value("5") timeout = mwan_interface:option(ListValue, "timeout", translate("Ping timeout")) timeout.default = "2" timeout:value("1", translate("1 second")) timeout:value("2", translate("2 seconds")) timeout:value("3", translate("3 seconds")) timeout:value("4", translate("4 seconds")) timeout:value("5", translate("5 seconds")) timeout:value("6", translate("6 seconds")) timeout:value("7", translate("7 seconds")) timeout:value("8", translate("8 seconds")) timeout:value("9", translate("9 seconds")) timeout:value("10", translate("10 seconds")) interval = mwan_interface:option(ListValue, "interval", translate("Ping interval")) interval.default = "5" interval:value("1", translate("1 second")) interval:value("3", translate("3 seconds")) interval:value("5", translate("5 seconds")) interval:value("10", translate("10 seconds")) interval:value("20", translate("20 seconds")) interval:value("30", translate("30 seconds")) interval:value("60", translate("1 minute")) interval:value("300", translate("5 minutes")) interval:value("600", translate("10 minutes")) interval:value("900", translate("15 minutes")) interval:value("1800", translate("30 minutes")) interval:value("3600", translate("1 hour")) down = mwan_interface:option(ListValue, "down", translate("Interface down"), translate("Interface will be deemed down after this many failed ping tests")) down.default = "3" down:value("1") down:value("2") down:value("3") down:value("4") down:value("5") down:value("6") down:value("7") down:value("8") down:value("9") down:value("10") up = mwan_interface:option(ListValue, "up", translate("Interface up"), translate("Downed interface will be deemed up after this many successful ping tests")) up.default = "3" up:value("1") up:value("2") up:value("3") up:value("4") up:value("5") up:value("6") up:value("7") up:value("8") up:value("9") up:value("10") metric = mwan_interface:option(DummyValue, "metric", translate("Metric"), translate("This displays the metric assigned to this interface in /etc/config/network")) metric.rawhtml = true function metric.cfgvalue(self, s) if errorNoMetric == 0 then return metricValue else return "&#8212;" end end return m5
gpl-2.0
HEYAHONG/nodemcu-firmware
lua_examples/pipeutils.lua
6
2213
-- A collection of pipe-based utility functions -- A convenience wrapper for chunking data arriving in bursts into more sizable -- blocks; `o` will be called once per chunk. The `flush` method can be used to -- drain the internal buffer. `flush` MUST be called at the end of the stream, -- **even if the stream is a multiple of the chunk size** due to internal -- buffering. Flushing results in smaller chunk(s) being output, of course. local function chunker(o, csize, prio) assert (type(o) == "function" and type(csize) == "number" and 1 <= csize) local p = pipe.create(function(p) -- wait until it looks very likely that read is going to succeed -- and we won't have to unread. This may hold slightly more than -- a chunk in the underlying pipe object. if 256 * (p:nrec() - 1) <= csize then return nil end local d = p:read(csize) if #d < csize then p:unread(d) return false else o(d) return true end end, prio or node.task.LOW_PRIORITY) return { flush = function() for d in p:reader(csize) do o(d) end end, write = function(d) p:write(d) end } end -- Stream and decode lines of complete base64 blocks, calling `o(data)` with -- decoded chunks or calling `e(badinput, errorstr)` on error; the error -- callback must ensure that this conduit is never written to again. local function debase64(o, e, prio) assert (type(o) == "function" and type(e) == "function") local p = pipe.create(function(p) local s = p:read("\n+") if s:sub(-1) == "\n" then -- guard against incomplete line s = s:match("^%s*(%S*)%s*$") if #s ~= 0 then -- guard against empty line local ok, d = pcall(encoder.fromBase64, s) if ok then o(d) else e(s, d); return false end end return true else p:unread(s) return false end end, prio or node.task.LOW_PRIORITY) return { write = function(d) p:write(d) end } end return { chunker = chunker, debase64 = debase64, }
mit
ecnumjc/NAMAS
summary/beam_search.lua
9
7932
-- -- Copyright (c) 2015, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. -- -- Author: Alexander M Rush <srush@seas.harvard.edu> -- Sumit Chopra <spchopra@fb.com> -- Jason Weston <jase@fb.com> -- A beam search decoder local data = require('summary.data') local features = require('summary.features') local util = require('summary.util') local beam = {} local INF = 1e9 function beam.addOpts(cmd) cmd:option('-allowUNK', false, "Allow generating <unk>.") cmd:option('-fixedLength', true, "Produce exactly -length words.") cmd:option('-blockRepeatWords', false, "Disallow generating a word twice.") cmd:option('-lmWeight', 1.0, "Weight for main model.") cmd:option('-beamSize', 100, "Size of the beam.") cmd:option('-extractive', false, "Force fully extractive summary.") cmd:option('-abstractive', false, "Force fully abstractive summary.") cmd:option('-recombine', false, "Used hypothesis recombination.") features.addOpts(cmd) end function beam.init(opt, mlp, aux_model, article_to_title, dict) local new_beam = {} setmetatable(new_beam, { __index = beam }) new_beam.opt = opt new_beam.K = opt.beamSize new_beam.mlp = mlp new_beam.aux_model = aux_model new_beam.article_to_title = article_to_title new_beam.dict = dict -- Special Symbols. new_beam.UNK = dict.symbol_to_index["<unk>"] new_beam.START = dict.symbol_to_index["<s>"] new_beam.END = dict.symbol_to_index["</s>"] return new_beam end -- Helper: convert flat index to matrix. local function flat_to_rc(v, indices, flat_index) local row = math.floor((flat_index - 1) / v:size(2)) + 1 return row, indices[row][(flat_index - 1) % v:size(2) + 1] end -- Helper: find kmax of vector. local function find_k_max(pool, mat) local v = pool:forward(mat:t()):t() local orig_indices = pool.indices:t():add(1) return v:contiguous(), orig_indices end -- Use beam search to generate a summary of -- the article of length <= len. function beam:generate(article, len) local n = len local K = self.K local W = self.opt.window -- Initialize the extractive features. local feat_gen = features.init(self.opt, self.article_to_title) feat_gen:match_words(self.START, article) local F = feat_gen.num_features local FINAL_VAL = 1000 -- Initilize the charts. -- scores[i][k] is the log prob of the k'th hyp of i words. -- hyps[i][k] contains the words in k'th hyp at -- i word (left padded with W <s>) tokens. -- feats[i][k][f] contains the feature count of -- the f features for the k'th hyp at word i. local result = {} local scores = torch.zeros(n+1, K):float() local hyps = torch.zeros(n+1, K, W+n+1):long() local feats = torch.zeros(n+1, K, F):float() hyps:fill(self.START) -- Initilialize used word set. -- words_used[i][k] is a set of the words used in the i,k hyp. local words_used = {} if self.opt.blockRepeatWords then for i = 1, n + 1 do words_used[i] = {} for k = 1, K do words_used[i][k] = {} end end end -- Find k-max columns of a matrix. -- Use 2*k in case some are invalid. local pool = nn.TemporalKMaxPooling(2*K) -- Main loop of beam search. for i = 1, n do local cur_beam = hyps[i]:narrow(2, i+1, W) local cur_K = K -- (1) Score all next words for each context in the beam. -- log p(y_{i+1} | y_c, x) for all y_c local input = data.make_input(article, cur_beam, cur_K) local model_scores = self.mlp:forward(input) local out = model_scores:clone():double() out:mul(self.opt.lmWeight) -- If length limit is reached, next word must be end. local finalized = (i == n) and self.opt.fixedLength if finalized then out[{{}, self.END}]:add(FINAL_VAL) else -- Apply hard constraints. out[{{}, self.START}] = -INF if not self.opt.allowUNK then out[{{}, self.UNK}] = -INF end if self.opt.fixedLength then out[{{}, self.END}] = -INF end -- Add additional extractive features. feat_gen:add_features(out, cur_beam) end -- Only take first row when starting out. if i == 1 then cur_K = 1 out = out:narrow(1, 1, 1) model_scores = model_scores:narrow(1, 1, 1) end -- Prob of summary is log p + log p(y_{i+1} | y_c, x) for k = 1, cur_K do out[k]:add(scores[i][k]) end -- (2) Retain the K-best words for each hypothesis using GPU. -- This leaves a KxK matrix which we flatten to a K^2 vector. local max_scores, mat_indices = find_k_max(pool, out:cuda()) local flat = max_scores:view(max_scores:size(1) * max_scores:size(2)):float() -- 3) Construct the next hypotheses by taking the next k-best. local seen_ngram = {} for k = 1, K do for _ = 1, 100 do -- (3a) Pull the score, index, rank, and word of the -- current best in the table, and then zero it out. local score, index = flat:max(1) if finalized then score[1] = score[1] - FINAL_VAL end scores[i+1][k] = score[1] local prev_k, y_i1 = flat_to_rc(max_scores, mat_indices, index[1]) flat[index[1]] = -INF -- (3b) Is this a valid next word? local blocked = (self.opt.blockRepeatWords and words_used[i][prev_k][y_i1]) blocked = blocked or (self.opt.extractive and not feat_gen:has_ngram({y_i1})) blocked = blocked or (self.opt.abstractive and feat_gen:has_ngram({y_i1})) -- Hypothesis recombination. local new_context = {} if self.opt.recombine then for j = i+2, i+W do table.insert(new_context, hyps[i][prev_k][j]) end table.insert(new_context, y_i1) blocked = blocked or util.has(seen_ngram, new_context) end -- (3c) Add the word, its score, and its features to the -- beam. if not blocked then -- Update tables with new hypothesis. for j = 1, i+W do local pword = hyps[i][prev_k][j] hyps[i+1][k][j] = pword words_used[i+1][k][pword] = true end hyps[i+1][k][i+W+1] = y_i1 words_used[i+1][k][y_i1] = true -- Keep track of hypotheses seen. if self.opt.recombine then util.add(seen_ngram, new_context) end -- Keep track of features used (For MERT) feats[i+1][k]:copy(feats[i][prev_k]) feat_gen:compute(feats[i+1][k], hyps[i+1][k], model_scores[prev_k][y_i1], y_i1, i) -- If we have produced an END symbol, push to stack. if y_i1 == self.END then table.insert(result, {i+1, scores[i+1][k], hyps[i+1][k]:clone(), feats[i+1][k]:clone()}) scores[i+1][k] = -INF end break end end end end -- Sort by score. table.sort(result, function (a, b) return a[2] > b[2] end) -- Return the scores and hypotheses at the final stage. return result end return beam
bsd-3-clause
satanevil/copy-creed
plugins/inpm.lua
243
3007
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
robbie-cao/mooncake
mos-pub.lua
1
1079
#!/usr/bin/env lua local posix = require("posix") mqtt = require("mosquitto") client = mqtt.new() local BROKER = "test.muabaobao.com" local UPDATE_TOPIC_NAME = "/mua/sys/upgrade" local TEST_UPDATE_TOPIC_NAME = "/mua/test/upgrade" local MSM_TOPIC_DOMAIN = "/mua/msm/" local MSM_DEFAULT_TOPIC_NAME = "/mua/msm/general" local MSM_DEFAULT_TEST_TOPIC_NAME = "/mua/msm/general_test" tag = arg[1] if not tag or tag == "" then tag = tostring(os.date("%H%M%S")) end P = print local function print(...) t = posix.gettimeofday() P(string.format("%08d.%06d", t.sec, t.usec), tag, ...) end client.ON_CONNECT = function(...) print("Publisher Connected", ...) end client.ON_PUBLISH = function(...) print("Send:", ...) end client:connect(BROKER) while true do t = posix.gettimeofday() msg = "Message - timestamp: " .. string.format("%08d.%06d", t.sec, t.usec) client:publish(MSM_TOPIC_DOMAIN, msg) print("Send: " .. msg) sleep = "sleep " .. tostring(math.random()) os.execute(sleep) end client:loop_forever()
mit
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/script/framework/extends/UIPageView.lua
57
1384
--[[ Copyright (c) 2011-2014 chukong-inc.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]] local PageView = ccui.PageView function PageView:onEvent(callback) self:addEventListener(function(sender, eventType) local event = {} if eventType == 0 then event.name = "TURNING" end event.target = sender callback(event) end) return self end
mit
ncarlson/eiga
runtime/modules/image/image.lua
1
1176
-- Copyright (C) 2012 Nicholas Carlson -- -- 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. if not eiga.image then eiga.image = {} end return eiga.image
mit
cyberz-eu/octopus
extensions/core/src/template.lua
1
1324
local exception = require "exception" local eval = require "eval" local parse = require "parse" package.loaded.TEMPLATES = {} local function configuration (templateName) local TEMPLATES = package.loaded.TEMPLATES local octopusHostDir = ngx.var.octopusHostDir if TEMPLATES[octopusHostDir] then return TEMPLATES[octopusHostDir][templateName] else local templatesConfig = dofile(octopusHostDir .. "/build/src/html.lua") TEMPLATES[octopusHostDir] = templatesConfig return templatesConfig[templateName] end end package.loaded.TEMPLATES_CACHE = {} local template = {} setmetatable(template, { __index = function (t, templateName) local CACHE = package.loaded.TEMPLATES_CACHE local key if templateName:find("global.", 1, true) then key = templateName else key = ngx.var.octopusHostDir .. ":" .. templateName end local cached = CACHE[key] if cached then local view = cached return function (context, arguments) return parse(view, context, arguments) end end local scripts = configuration(templateName) if scripts then local view = eval.file(scripts[#scripts], {}) CACHE[key] = view return function (context, arguments) return parse(view, context, arguments) end end exception("html template " .. templateName .. " does not exists") end }) return template
bsd-2-clause
rderimay/Focus-Points
focuspoints.lrdevplugin/FocusPointPrefs.lua
2
1339
--[[ Copyright 2016 JWhizzbang Inc Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local LrView = import "LrView" local LrPrefs = import "LrPrefs" local bind = LrView.bind FocusPointPrefs = {} function FocusPointPrefs.genSectionsForBottomOfDialog( viewFactory, p ) local prefs = LrPrefs.prefsForPlugin( nil ) return { { title = "Logging", viewFactory:row { bind_to_object = prefs, spacing = viewFactory:control_spacing(), viewFactory:popup_menu { title = "Logging level", value = bind 'loggingLevel', items = { { title = "None", value = "NONE"}, { title = "Error", value = "ERROR"}, { title = "Warn", value = "WARN"}, { title = "Info", value = "INFO"}, { title = "Debug", value = "DEBUG"}, } }, }, }, } end
apache-2.0
shadoalzupedy/shadow
plugins/anti_spam.lua
191
5291
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Save stats on Redis if msg.to.type == 'channel' then -- User is on channel local hash = 'channel:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end if msg.to.type == 'user' then -- User is on chat local hash = 'PM:'..msg.from.id redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is on or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id local chat = msg.to.id local whitelist = "whitelist" local is_whitelisted = redis:sismember(whitelist, user) -- Ignore mods,owner and admins if is_momod(msg) then return msg end if is_whitelisted == true then return msg end local receiver = get_receiver(msg) if msg.to.type == 'user' then local max_msg = 7 * 1 print(msgs) if msgs >= max_msg then print("Pass2") send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.") savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.") block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private end end if kicktable[user] == true then return end delete_msg(msg.id, ok_cb, false) kick_user(user, chat) local username = msg.from.username local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", "") if msg.to.type == 'chat' or msg.to.type == 'channel' then if username then savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked") else savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "Flooding is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nStatus: User kicked") end end -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) if msg.from.username ~= nil then username = msg.from.username else username = "---" end local print_name = user_print_name(msg.from):gsub("‮", "") local name = print_name:gsub("_", "") --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)") local GBan_log = 'GBan_log' local GBan_log = data[tostring(GBan_log)] for k,v in pairs(GBan_log) do log_SuperGroup = v gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)" --send it to log group/channel send_large_msg(log_SuperGroup, gban_text) end end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/tests/lua-tests/src/NavMeshTest/NavMeshTest.lua
6
15269
local AgentUserData = { time = 0 } local function jump(v1, v2, height, t) local out = {} out.x = v1.x + t * (v2.x - v1.x) out.y = v1.y + t * (v2.y - v1.y) out.z = v1.z + t * (v2.z - v1.z) out.y = out.y + height * math.sin(math.pi * t) return out end local actionManager = cc.Director:getInstance():getActionManager() ---------------------------------------- ----NavMeshBaseTestDemo ---------------------------------------- local NavMeshBaseTestDemo = class("NavMeshBaseTestDemo", function () -- body local scene = cc.Scene:createWithPhysics() return scene end) function NavMeshBaseTestDemo:ctor() TestCastScene.initWithLayer(self) TestCastScene.titleLabel:setString(self:title()) TestCastScene.subtitleLabel:setString(self:subtitle()) self:init() local function onNodeEvent(event) if "enter" == event then self:onEnter() elseif "exit" == event then self:onExit() end end self:registerScriptHandler(onNodeEvent) end function NavMeshBaseTestDemo:title() return "Physics3D Test" end function NavMeshBaseTestDemo:subtitle() return "" end function NavMeshBaseTestDemo:init() self._angle = 0.0 self._agents = {} local size = cc.Director:getInstance():getWinSize() self._camera = cc.Camera:createPerspective(30.0, size.width / size.height, 1.0, 1000.0) self._camera:setPosition3D(cc.vec3(0.0, 50.0, 100.0)) self._camera:lookAt(cc.vec3(0.0, 0.0, 0.0), cc.vec3(0.0, 1.0, 0.0)) self._camera:setCameraFlag(cc.CameraFlag.USER1) self:addChild(self._camera) self:registerTouchEvent() self:initScene() self:scheduleUpdateWithPriorityLua(function(dt) if #self._agents == 0 then return end if not self._resumeFlag and nil ~= self._agentNode then self._resumeFlag = true actionManager:resumeTarget(self._agentNode) end local currentVelocity = nil local speed = 0 for i = 1, #self._agents do currentVelocity = self._agents[i][1]:getCurrentVelocity() speed = math.sqrt(currentVelocity.x * currentVelocity.x + currentVelocity.y * currentVelocity.y + currentVelocity.z * currentVelocity.z) * 0.2 if speed < 0 then speed = 0.0 end self._agents[i][2]:setSpeed(speed) end end, 0) self:extend() end function NavMeshBaseTestDemo:onEnter() local hitResult = {} local ret = false local physicsWorld = self:getPhysics3DWorld() ret, hitResult = physicsWorld:rayCast(cc.vec3(0.0, 50.0, 0.0), cc.vec3(0.0, -50.0, 0.0), hitResult) self:createAgent(hitResult.hitPosition) end function NavMeshBaseTestDemo:onExit() self:unscheduleUpdate() end function NavMeshBaseTestDemo:registerTouchEvent() end function NavMeshBaseTestDemo:extend() end function NavMeshBaseTestDemo:initScene() self:getPhysics3DWorld():setDebugDrawEnable(false) local trianglesList = cc.Bundle3D:getTrianglesList("NavMesh/scene.obj") local rbDes = {} rbDes.mass = 0.0 rbDes.shape = cc.Physics3DShape:createMesh(trianglesList, math.floor(#trianglesList / 3)) local rigidBody = cc.Physics3DRigidBody:create(rbDes) local component = cc.Physics3DComponent:create(rigidBody) local sprite = cc.Sprite3D:create("NavMesh/scene.obj") sprite:addComponent(component) sprite:setCameraMask(cc.CameraFlag.USER1) self:addChild(sprite) self:setPhysics3DDebugCamera(self._camera) local navMesh = cc.NavMesh:create("NavMesh/all_tiles_tilecache.bin", "NavMesh/geomset.txt") navMesh:setDebugDrawEnable(true) self:setNavMesh(navMesh) self:setNavMeshDebugCamera(self._camera) local ambientLight = cc.AmbientLight:create(cc.c3b(64, 64, 64)) ambientLight:setCameraMask(cc.CameraFlag.USER1) self:addChild(ambientLight) local dirLight = cc.DirectionLight:create(cc.vec3(1.2, -1.1, 0.5), cc.c3b(255, 255, 255)) dirLight:setCameraMask(cc.CameraFlag.USER1) self:addChild(dirLight) end function NavMeshBaseTestDemo:createAgent(pos) local filePath = "Sprite3DTest/girl.c3b" local navMeshAgentParam = {} navMeshAgentParam.radius = 2.0 navMeshAgentParam.height = 8.0 navMeshAgentParam.maxSpeed = 8.0 local agent = cc.NavMeshAgent:create(navMeshAgentParam) local agentNode = cc.Sprite3D:create(filePath) agent:setOrientationRefAxes(cc.vec3(-1.0, 0.0, 1.0)) agent.userdata = 0.0 agentNode:setScale(0.05) agentNode:addComponent(agent) local node = cc.Node:create() node:addChild(agentNode) node:setPosition3D(pos) node:setCameraMask(cc.CameraFlag.USER1) self:addChild(node) local animation = cc.Animation3D:create(filePath) local animate = cc.Animate3D:create(animation) if nil ~= animate then agentNode:runAction(cc.RepeatForever:create(animate)) animate:setSpeed(0.0) end self._agents[#self._agents + 1] = {agent, animate} end function NavMeshBaseTestDemo:createObstacle(pos) local obstacle = cc.NavMeshObstacle:create(2.0, 8.0) local obstacleNode = cc.Sprite3D:create("Sprite3DTest/cylinder.c3b") obstacleNode:setPosition3D(cc.vec3(pos.x, pos.y -0.5, pos.z)) obstacleNode:setRotation3D(cc.vec3(-90.0, 0.0, 0.0)) obstacleNode:setScale(0.3) obstacleNode:addComponent(obstacle) obstacleNode:setCameraMask(cc.CameraFlag.USER1) self:addChild(obstacleNode) end function NavMeshBaseTestDemo:moveAgents(des) if #self._agents == 0 then return end local agent = nil for i = 1, #self._agents do self._agents[i][1]:move(des, function (agent, totalTimeAfterMove) local data = agent.userdata if agent:isOnOffMeshLink() then agent:setAutoTraverseOffMeshLink(false) agent:setAutoOrientation(false) local linkdata = agent:getCurrentOffMeshLinkData() agent:getOwner():setPosition3D(jump(linkdata.startPosition, linkdata.endPosition, 10.0, data)) local dir = cc.vec3(linkdata.endPosition.x - linkdata.startPosition.x, linkdata.endPosition.y - linkdata.startPosition.y, linkdata.endPosition.z - linkdata.startPosition.z) dir.y = 0.0 dir = cc.vec3normalize(dir) local axes = cc.vec3(0.0, 0.0, 0.0) local refAxes = cc.vec3(-1.0, 0.0, 1.0) refAxes = cc.vec3normalize(refAxes) axes = vec3_cross(refAxes, dir, axes) local angle = refAxes.x * dir.x + refAxes.y * dir.y + refAxes.z * dir.z local quaternion = cc.quaternion_createFromAxisAngle(axes, math.acos(angle)) agent:getOwner():setRotationQuat(quaternion) agent.userdata = agent.userdata + 0.01 if 1.0 < agent.userdata then agent:completeOffMeshLink() agent:setAutoOrientation(true) agent.userdata = 0.0 end end end) end end ---------------------------------------- ----NavMeshBaseTestDemo ---------------------------------------- local NavMeshBasicTestDemo = class("NavMeshBasicTestDemo", NavMeshBaseTestDemo) function NavMeshBasicTestDemo:title() return "Navigation Mesh Test" end function NavMeshBasicTestDemo:subtitle() return "Basic Test" end function NavMeshBasicTestDemo:registerTouchEvent() local listener = cc.EventListenerTouchAllAtOnce:create() listener:registerScriptHandler(function(touches, event) self._needMoveAgents = true end,cc.Handler.EVENT_TOUCHES_BEGAN) listener:registerScriptHandler(function(touches, event) if #touches > 0 and self._camera ~= nil then local touch = touches[1] local delta = touch:getDelta() self._angle = self._angle - delta.x * math.pi / 180.0 self._camera:setPosition3D(cc.vec3(100.0 * math.sin(self._angle), 50.0, 100.0 * math.cos(self._angle))) self._camera:lookAt(cc.vec3(0.0, 0.0, 0.0), cc.vec3(0.0, 1.0, 0.0)) if (delta.x * delta.x + delta.y * delta.y) > 16 then self._needMoveAgents = false end end end, cc.Handler.EVENT_TOUCHES_MOVED) listener:registerScriptHandler(function(touches, event) if not self._needMoveAgents then return end local physicsWorld = self:getPhysics3DWorld() if #touches > 0 then local touch = touches[1] local location = touch:getLocationInView() local nearP = cc.vec3(location.x, location.y, 0.0) local farP = cc.vec3(location.x, location.y, 1.0) local size = cc.Director:getInstance():getWinSize() nearP = self._camera:unproject(size, nearP, nearP) farP = self._camera:unproject(size, farP, farP) local hitResult = {} local ret = false ret, hitResult = physicsWorld:rayCast(nearP, farP, hitResult) self:moveAgents(hitResult.hitPosition) end end, cc.Handler.EVENT_TOUCHES_ENDED) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) end function NavMeshBasicTestDemo:extend() local ttfConfig = {} ttfConfig.fontFilePath = "fonts/arial.ttf" ttfConfig.fontSize = 15 local debugLabel = cc.Label:createWithTTF(ttfConfig,"Debug Draw ON") local menuItem = cc.MenuItemLabel:create(debugLabel) menuItem:registerScriptTapHandler(function (tag, sender) local scene = cc.Director:getInstance():getRunningScene() local enabledDebug = not scene:getNavMesh():isDebugDrawEnabled() scene:getNavMesh():setDebugDrawEnable(enabledDebug) if enabledDebug then debugLabel:setString("DebugDraw ON") else debugLabel:setString("DebugDraw OFF") end end) menuItem:setAnchorPoint(cc.p(0.0, 1.0)) menuItem:setPosition(cc.p(VisibleRect:left().x, VisibleRect:top().y - 100)) local menu = cc.Menu:create(menuItem) menu:setPosition(cc.p(0.0, 0.0)) self:addChild(menu) end ---------------------------------------- ----NavMeshAdvanceTestDemo ---------------------------------------- local NavMeshAdvanceTestDemo = class("NavMeshAdvanceTestDemo", NavMeshBaseTestDemo) function NavMeshAdvanceTestDemo:title() return "Navigation Mesh Test" end function NavMeshAdvanceTestDemo:subtitle() return "Advance Test" end function NavMeshAdvanceTestDemo:registerTouchEvent() local listener = cc.EventListenerTouchAllAtOnce:create() listener:registerScriptHandler(function(touches, event) self._needMoveAgents = true end,cc.Handler.EVENT_TOUCHES_BEGAN) listener:registerScriptHandler(function(touches, event) if #touches > 0 and self._camera ~= nil then local touch = touches[1] local delta = touch:getDelta() self._angle = self._angle - delta.x * math.pi / 180.0 self._camera:setPosition3D(cc.vec3(100.0 * math.sin(self._angle), 50.0, 100.0 * math.cos(self._angle))) self._camera:lookAt(cc.vec3(0.0, 0.0, 0.0), cc.vec3(0.0, 1.0, 0.0)) if (delta.x * delta.x + delta.y * delta.y) > 16 then self._needMoveAgents = false end end end, cc.Handler.EVENT_TOUCHES_MOVED) listener:registerScriptHandler(function(touches, event) if not self._needMoveAgents then return end local physicsWorld = self:getPhysics3DWorld() if #touches > 0 then local touch = touches[1] local location = touch:getLocationInView() local nearP = cc.vec3(location.x, location.y, 0.0) local farP = cc.vec3(location.x, location.y, 1.0) local size = cc.Director:getInstance():getWinSize() nearP = self._camera:unproject(size, nearP, nearP) farP = self._camera:unproject(size, farP, farP) local hitResult = {} local ret = false ret, hitResult = physicsWorld:rayCast(nearP, farP, hitResult) self:moveAgents(hitResult.hitPosition) end end, cc.Handler.EVENT_TOUCHES_ENDED) local eventDispatcher = self:getEventDispatcher() eventDispatcher:addEventListenerWithSceneGraphPriority(listener, self) end function NavMeshAdvanceTestDemo:extend() local ttfConfig = {} ttfConfig.fontFilePath = "fonts/arial.ttf" ttfConfig.fontSize = 15 local obstacleLabel = cc.Label:createWithTTF(ttfConfig,"Create Obstacle") local menuItem0 = cc.MenuItemLabel:create(obstacleLabel) menuItem0:registerScriptTapHandler(function (tag, sender) local scene = cc.Director:getInstance():getRunningScene() local x = math.random(-50, 50) local z = math.random(-50.0, 50.0) local hitResult = {} local ret = false ret, hitResult = scene:getPhysics3DWorld():rayCast(cc.vec3(x, 50.0, z), cc.vec3(x, -50.0, z), hitResult) self:createObstacle(hitResult.hitPosition) end) menuItem0:setAnchorPoint(cc.p(0.0, 1.0)) menuItem0:setPosition(cc.p(VisibleRect:left().x, VisibleRect:top().y - 50)) local agentLabel = cc.Label:createWithTTF(ttfConfig,"Create Agent") local menuItem1 = cc.MenuItemLabel:create(agentLabel) menuItem1:registerScriptTapHandler(function (tag, sender) local scene = cc.Director:getInstance():getRunningScene() local x = math.random(-50, 50) local z = math.random(-50.0, 50.0) local hitResult = {} local ret = false ret, hitResult = scene:getPhysics3DWorld():rayCast(cc.vec3(x, 50.0, z), cc.vec3(x, -50.0, z), hitResult) self:createAgent(hitResult.hitPosition) end) menuItem1:setAnchorPoint(cc.p(0.0, 1.0)) menuItem1:setPosition(cc.p(VisibleRect:left().x, VisibleRect:top().y - 100)) local debugLabel = cc.Label:createWithTTF(ttfConfig,"Debug Draw ON") local menuItem2 = cc.MenuItemLabel:create(debugLabel) menuItem2:registerScriptTapHandler(function (tag, sender) local scene = cc.Director:getInstance():getRunningScene() local enabledDebug = not scene:getNavMesh():isDebugDrawEnabled() scene:getNavMesh():setDebugDrawEnable(enabledDebug) if enabledDebug then debugLabel:setString("DebugDraw ON") else debugLabel:setString("DebugDraw OFF") end end) menuItem2:setAnchorPoint(cc.p(0.0, 1.0)) menuItem2:setPosition(cc.p(VisibleRect:left().x, VisibleRect:top().y - 150)) local menu = cc.Menu:create(menuItem0, menuItem1, menuItem2) menu:setPosition(cc.p(0.0, 0.0)) self:addChild(menu) end ---------------------------------------- ----NavMeshTest ---------------------------------------- function NavMeshTest() Helper.usePhysics = true TestCastScene.createFunctionTable = { NavMeshBasicTestDemo.create, NavMeshAdvanceTestDemo.create, } local scene = NavMeshBasicTestDemo.create() scene:addChild(CreateBackMenuItem()) return scene end
mit
opentechinstitute/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-format.lua
80
3636
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true format_au = module:option(ListValue, "format_au", "Sun Microsystems AU format (signed linear)", "") format_au:value("yes", "Load") format_au:value("no", "Do Not Load") format_au:value("auto", "Load as Required") format_au.rmempty = true format_g723 = module:option(ListValue, "format_g723", "G.723.1 Simple Timestamp File Format", "") format_g723:value("yes", "Load") format_g723:value("no", "Do Not Load") format_g723:value("auto", "Load as Required") format_g723.rmempty = true format_g726 = module:option(ListValue, "format_g726", "Raw G.726 (16/24/32/40kbps) data", "") format_g726:value("yes", "Load") format_g726:value("no", "Do Not Load") format_g726:value("auto", "Load as Required") format_g726.rmempty = true format_g729 = module:option(ListValue, "format_g729", "Raw G729 data", "") format_g729:value("yes", "Load") format_g729:value("no", "Do Not Load") format_g729:value("auto", "Load as Required") format_g729.rmempty = true format_gsm = module:option(ListValue, "format_gsm", "Raw GSM data", "") format_gsm:value("yes", "Load") format_gsm:value("no", "Do Not Load") format_gsm:value("auto", "Load as Required") format_gsm.rmempty = true format_h263 = module:option(ListValue, "format_h263", "Raw h263 data", "") format_h263:value("yes", "Load") format_h263:value("no", "Do Not Load") format_h263:value("auto", "Load as Required") format_h263.rmempty = true format_jpeg = module:option(ListValue, "format_jpeg", "JPEG (Joint Picture Experts Group) Image", "") format_jpeg:value("yes", "Load") format_jpeg:value("no", "Do Not Load") format_jpeg:value("auto", "Load as Required") format_jpeg.rmempty = true format_pcm = module:option(ListValue, "format_pcm", "Raw uLaw 8khz Audio support (PCM)", "") format_pcm:value("yes", "Load") format_pcm:value("no", "Do Not Load") format_pcm:value("auto", "Load as Required") format_pcm.rmempty = true format_pcm_alaw = module:option(ListValue, "format_pcm_alaw", "load => .so ; Raw aLaw 8khz PCM Audio support", "") format_pcm_alaw:value("yes", "Load") format_pcm_alaw:value("no", "Do Not Load") format_pcm_alaw:value("auto", "Load as Required") format_pcm_alaw.rmempty = true format_sln = module:option(ListValue, "format_sln", "Raw Signed Linear Audio support (SLN)", "") format_sln:value("yes", "Load") format_sln:value("no", "Do Not Load") format_sln:value("auto", "Load as Required") format_sln.rmempty = true format_vox = module:option(ListValue, "format_vox", "Dialogic VOX (ADPCM) File Format", "") format_vox:value("yes", "Load") format_vox:value("no", "Do Not Load") format_vox:value("auto", "Load as Required") format_vox.rmempty = true format_wav = module:option(ListValue, "format_wav", "Microsoft WAV format (8000hz Signed Line", "") format_wav:value("yes", "Load") format_wav:value("no", "Do Not Load") format_wav:value("auto", "Load as Required") format_wav.rmempty = true format_wav_gsm = module:option(ListValue, "format_wav_gsm", "Microsoft WAV format (Proprietary GSM)", "") format_wav_gsm:value("yes", "Load") format_wav_gsm:value("no", "Do Not Load") format_wav_gsm:value("auto", "Load as Required") format_wav_gsm.rmempty = true return cbimap
apache-2.0
opentechinstitute/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/dns.lua
78
1344
--[[ Luci configuration model for statistics - collectd dns 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$ ]]-- require("luci.sys") m = Map("luci_statistics", translate("DNS Plugin Configuration"), translate( "The dns plugin collects detailled statistics about dns " .. "related traffic on selected interfaces." )) -- collectd_dns config section s = m:section( NamedSection, "collectd_dns", "luci_statistics" ) -- collectd_dns.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_dns.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Monitor interfaces") ) interfaces.widget = "select" interfaces.size = 5 interfaces:depends( "enable", 1 ) interfaces:value("any") for k, v in pairs(luci.sys.net.devices()) do interfaces:value(v) end -- collectd_dns.ignoresources (IgnoreSource) ignoresources = s:option( Value, "IgnoreSources", translate("Ignore source addresses") ) ignoresources.default = "127.0.0.1" ignoresources:depends( "enable", 1 ) return m
apache-2.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[gameplay]/gcshop/horns/horns_c.lua
1
29859
local screenWidth, screenHeight = guiGetScreenSize() downloadHornList = {} hornsTable = { [1] = "Birdo-geluidje", [2] = "Boo-gebulder", [3] = "Come on! - Wario", [4] = "Dry Bones-gegiechel", [5] = "Hatsjwao! Oh sorry.. - Luigi", [6] = "Hey Stinky! - Mario", [7] = "Mushroom! - Toadette", [8] = "Peach-annoy", [9] = "Toad-boeee", [10] = "Yoshi-cool geluid", [11] = "You know I'll win! - Daisy", [12] = "You're lousy! - Waluigi", [13] = "The Dukes of hazzard", [14] = "Adios", [15] = "Aww crap", [16] = "Bad Boys", [17] = "Beat it!", [18] = "Billnye", [19] = "Callonme", [20] = "Come out", [21] = "Do'h", [22] = "English", [23] = "Feel good", [24] = "Haha", [25] = "Hello", [26] = "Madness", [27] = "Muh", [28] = "Muhaha", [29] = "Noobs", [30] = "Omg", [31] = "Sparta", [32] = "Suck", [33] = "Suckers", [34] = "Wazza", [35] = "Woohoo", [36] = "Yaba", [37] = "stewie", [38] = "titten", [39] = "buggle call", [40] = "random", [41] = "ring", [42] = "mario win", [43] = "goodbadugly", [44] = "who cares", [45] = "loser", [46] = "noooo", [47] = "cartman", [48] = "such a noob", [49] = "Screw you, that's funny", [50] = "hello again", [51] = "haaaaaai", [52] = "knock knock", [53] = "giggity", [54] = "shade aran", [55] = "YES,YES.", [56] = "Burn baby burn.", [57] = "Cry some moar!", [58] = "Davaj do svidanija", [59] = "WHAT YOU GONNA DO", [60] = "Dr.Zaius", [61] = "Here we go", [62] = "Holy Shit", [63] = "It's my life", [64] = "JAAZZZZ", [65] = "Let's get ready to rumble", [66] = "What did you say nigga!?", [67] = "Not a big surprise", [68] = "Livin' on a prayer", [69] = "Low Rider", [70] = "MammaMia", [71] = "Mariodeath", [72] = "My horse is amazing", [73] = "U can't touch this", [74] = "We are the champions", [75] = "We will rock you", [76] = "Bye have a great time", [77] = "Damn son! Where'd you find this", [78] = "Denied!", [79] = "Derp!1!", [80] = "Fart SFX", [81] = "Fatality", [82] = "Finish him!", [83] = "Giggity", [84] = "Gotya bitch", [85] = "Headshot!", [86] = "Hehe! Alright", [87] = "Here We Go!", [88] = "Like A Baus", [89] = "Prepare to be astonished", [90] = "Smoke Weed Everyday", [91] = "Tah daah", [92] = "That's nasty", [93] = "Toasty!", [94] = "Whaaat", [95] = "You got knocked the fuck out", [96] = "You suck sound effect", [97] = "Haha You Suck", [98] = "Imma bust you up", [99] = "It's on, Baby", [100] = "Mess with the best", [101] = "That's gotta hurt", [102] = "Yo Whassup", [103] = "F--k you ceelo", [104] = "Stewie Mummy", [105] = "Hah, Ghaay", [106] = "J's on my feet", [107] = "Jim Carrey", [108] = "Minion laugh", [109] = "My nigga my nigga", [110] = "Darude - Sandstorm", [111] = "So it begins", [112] = "What are you doing", [113] = "Whoooaah", [114] = "Wiggle wiggle wiggle", [115] = "You shall not pass!", [116] = "Higher", [117] = "I need a dollar", [118] = "M-O Wall-E", [119] = "Wall-E", [120] = "Help!..nope", [121] = "I dare you", [122] = "Iragenerghvjksah", [123] = "KAR Spring Breeze", [124] = "Let's do this again", [125] = "Oh you", [126] = "Brush heavy's hair!", [127] = "OKTOBERFEST MAGGOT", [128] = "Full of SANDWITCHES!", [129] = "Scary", [130] = "Ugly, AAAH", [131] = "You're not a real soldier!", [132] = "1,2,3 Let's GO!", [133] = "Airporn", [134] = "Black & Yellow", [135] = "Don't look down", [136] = "Dreamscape", [137] = "GET NOSOCOPED!", [138] = "Oh baby a triple", [139] = "Put your hands up!!!", [140] = "Really, nigga?", [141] = "Schnappi", [142] = "Smoke Weed Everyday remix", [143] = "Spacemen", [144] = "They call it Merther!", [145] = "Sad violin air horn", [146] = "Fucking bi#@h!", [147] = "Nice and strong Cena", [148] = "Dikke BMW", [149] = "Burp!", [150] = "Meep-meep!", [151] = "Angels are crying", [152] = "Bocka bass", [153] = "I can't get no sleep", [154] = "Ja pierdole kurwa", [155] = "Komodo", [156] = "Let go", [157] = "Pop Hold it Down", [158] = "Sacrifice", [159] = "Single ladies", [160] = "Feel Good Drag", [161] = "They see me rollin", [162] = "OH. MY. GOD.", [163] = "F1 Horn", [164] = "Evil Laugh", [165] = "Antonioooo", [166] = "Hero", [167] = "GTALibertyCity", [168] = "PersonalJesus", [169] = "Unforgiven", [170] = "Kappa", [171] = "Adele - Hello", [172] = "Magiiiik", [173] = "Keep the Change You Filthy Animal", [174] = "Crazy santa", [175] = "Dumb Florida Moron", [176] = "AMG", [177] = "Audi", [178] = "Chase the sun", [179] = "Give Me A Sign", [180] = "Heads Will Roll (A Trak remix)", [181] = "Holy Ghost", [182] = "I Am Jacks Hungry Heart Vocal 2", [183] = "I Am Jacks Hungry Heart Vocal", [184] = "I Am Jacks Hungry Heart", [185] = "I Believe In Dreams", [186] = "I Can't Stop", [187] = "Insomnia", [188] = "Komodoo", [189] = "Love Sex American Express", [190] = "Nighttrain", [191] = "Step it up", [192] = "Tobi King", [193] = "Tsunami", [194] = "DubStep!!", [195] = "Disturbed - Fear", [196] = "Knife Party - Nya", [197] = "Feel Dog Inc", [198] = "Reality - Melody", [199] = "Reality - Original", [200] = "Bellini - Samba De Janeiro", [201] = "Do You See Me Now?", [202] = "WAR, WAR NEVER CHANGES!", [203] = "Laugh", [204] = "Mr FuckFace", [205] = "Leeroy", [206] = "MadLaugh1", [207] = "MadLaugh2", [208] = "MadLaugh3", [209] = "MadLaugh4", [210] = "Out Of My Way", [211] = "Gazuj", [212] = "One click headshop", [213] = "DubStep 2", [214] = "Detonate", [215] = "Want To Want Me", [216] = "Bring It On!", [217] = "Cant handle the truth", [218] = "Eminem My Salsa", [219] = "Für Elise", [220] = "Gooooodmorning Vietnaaam", [221] = "HELP ME !! ", [222] = "I'm a Metalhead ", [223] = "I'm Batman ", [224] = "more hate..", [225] = "Rational Gaze", [226] = "The Watcher", [227] = "Use force luke", [228] = "weird thunder", [229] = "Wohoohue salsa", [230] = "Chilling y'all", [231] = "Im... Faaalling !", [232] = "You R so F_cked !", [233] = "Its time to dueell", [234] = "Metins horn", [235] = "frontliner-halos", [236] = "Chicken", [237] = "Mom", [238] = "Spanish Flea Quick", [239] = "Spanish Flea", [240] = "Xfile", [241] = "Tutturuu", [242] = "Benny Hill Theme", [243] = "Groove Street!", [244] = "Lenteja", [245] = "Cannonball", [246] = "Hotel-California", [247] = "I need a doctor, call me a doctor", [248] = "Jump", [249] = "Let it go", [250] = "Mehter 2", [251] = "Mehter", [252] = "Midnight", [253] = "No Money In The Bank", [254] = "Number Of The Beast", [255] = "Otpusti", [256] = "Powerslave", [257] = "Que boludo - Coco Basile", [258] = "Surface", [259] = "The Trooper", [260] = "GLP Dubstep", [261] = "Espectacular", [262] = "I Am Optimus Prime", [263] = "NyanCat", [264] = "Said-Nya", [265] = "Thriller", [266] = "CUZ IMA MUTHAPHUKIN NINJAA", [267] = "JUMP MOTHERFUCKER JUMP", [268] = "Tuco - It's me Tuco", [269] = "Tuco - SandyFuck", [270] = "Say what again", [271] = "CJ - my fuckin car", [272] = "CJ - ah shit", [273] = "CJ - asshole", [274] = "CJ - sorry", [275] = "CJ - fool", [276] = "Big Smoke - move out", [277] = "Ryder - busta", [278] = "Ryder - move it", [279] = "Sweet - speed up", [280] = "Sweet - ass on fire", [281] = "OG Loc - woah", [282] = "OG Loc - look out", [283] = "Catalina - idiota", [284] = "Catalina - car on fire", [285] = "Catalina - mistake", [286] = "Old man - ass burns", [287] = "Old man - whoopin", [288] = "The Truth - brain in gear", [289] = "Big Smoke - burger order", [290] = "Excuse me, princess", [291] = "TF2 - knee slap", [292] = "Saving Light 1", [293] = "Saving Light 2", [294] = "Fart SFX 2", [295] = "Hello motherfucker", [296] = "CJ - shut up", [297] = "CJ - did you buy your license?", [298] = "CJ - move your body", [299] = "CJ - rollercoaster", [300] = "Sweet - oh fuck", [301] = "Ryder - shit, man", [302] = "Pingu - Noot noot!", [303] = "Pingu - Angry noot noot!", [304] = "Me Arnold Swarzenegger", [305] = "Learning computer", [306] = "John Kimble", [307] = "Aaarg", [308] = "How are you", [309] = "Arnold song", [310] = "Women respect", [311] = "Fuck you asshole", [312] = "Don't do that", [313] = "Ryder nigga", [314] = "Relax man", [315] = "All we had to do was follow the damn train", [316] = "Aah oeh oeh", [317] = "Law have mercy on me", [318] = "Come on damn bitch", [319] = "Slowmotion ooh", [320] = "Keep up motherfucker", [321] = "Darude - Russian Sandstorm", [322] = "I smoke 2 joints", [323] = "Worthless Madafuca", [324] = "Weher the hood", [325] = "Wasted", [326] = "Osas", [327] = "TRIPALOSKY", [328] = "FUCK HER RIGHT IN THE PU**Y", [329] = "Take Out Your Clothes", [330] = "Surprise muthafucka", [331] = "Stig Song", [332] = "Siuu", [333] = "Shooting Stars", [334] = "Sandy Polish Song", [335] = "Pokemon GO EveryDay", [336] = "Oh no its retarded", [337] = "Move Bii Get Out", [338] = "Lose my mind", [339] = "John Cena", [340] = "Ice Ice Baby", [341] = "I Dont Fuck With U", [342] = "How Could This Happen To Me", [343] = "Ho Ho Ho Muthafucka!", [344] = "FU*K YOU", [345] = "First blood", [346] = "Evil Laugh", [347] = "Epic Sax Boy", [348] = "Eat a sack of baby d-cks!", [349] = "EA Sports", [350] = "Dont Worry Be happy", [351] = "DO IT JUST DO IT", [352] = "Courage Laugh", [353] = "China China China Trump", [354] = "Can't be stopped", [355] = "Boom Headshot", [356] = "aint nobody fuckin my wife", [357] = "aaaaaaaa laugh", [358] = "Dota", [359] = "Fuck it all", [360] = "My D*ck Is Big", [361] = "Ouuh MotherF*cker", [362] = "Tic Tac MotherF*cker", [363] = "Hey Newbo", [364] = "U Got One Shoot", [365] = "Vadia Vadia", [366] = "Wuajaja", [367] = "Bruh", [368] = "Five Hours", [369] = "Omen", [370] = "Out Of Space", [371] = "Ready4Pumpin", [372] = "Still D.R.E. beat", [373] = "VooDoo People", [374] = "ESKETIIIT", [375] = "EsketitEsketitESKETIIIT", [376] = "Hello There", [377] = "Retard", [378] = "Why you heff to be mad", [379] = "You spin me right round", [380] = "The Ting Go Skrra", [381] = "Spooky Scary Skeletons", [382] = "Gibberish", [383] = "Haka", [384] = "Turn Down For What", [385] = "DARE", [386] = "Harley-Davidson", [387] = "Davis", [388] = "Kylie", [389] = "Wololo", [390] = "Don't Poison Your hert", [391] = "UMTSSUMTSS", [392] = "Shut the fuck UP", [393] = "Mmm Mmm yeah yeah", [394] = "Kung Flo Fighting", [395] = "Fuck dat pssy", [396] = "Suck a dick", [397] = "Princeless", [398] = "Tokyo Race", [399] = "Drunk Singer", [400] = "BMW i8", [401] = "Cant Touch This V2", [402] = "Ijueputa", [403] = "EXTREME FAP", [404] = "Whats Good Niegah", [405] = "Eat it Nigga", [406] = "Hop Hop", [407] = "Why are you running", [408] = "Mad Turk", [409] = "Escobar", [410] = "K.O in Mid Air", [411] = "RAP GOD", [412] = "1 2 3 Lets Go", [413] = "DMX", [414] = "It's over 9000!!", [415] = "Watch Bitch", [416] = "Gaaaryyyy", [417] = "Yeah Boyyyy", [418] = "Michaeeeel", [419] = "Fuck Cop John Kimble", [420] = "Mother Russia", [421] = "Give me candy nigga", [422] = "Turk things", [423] = "Why hurt babe", [424] = "Shit game bro", } function onShopInit(tabPanel) shopTabPanel = tabPanel --triggerServerEvent('getHornsData', localPlayer) if isElement(hornsTab) then return end --// Tab Panels //-- hornsTab = guiCreateTab("Custom Horns", shopTabPanel) buyHornsTabPanel = guiCreateTabPanel(35, 30, 641, 381, false, hornsTab) buyHornsTab = guiCreateTab("Buy horns", buyHornsTabPanel) perkTab = guiCreateTab("Horn Perks", buyHornsTabPanel) --// Gridlists //-- availableHornsList = guiCreateGridList(0.05, 0.15, 0.42, 0.66, true, buyHornsTab) guiGridListSetSortingEnabled(availableHornsList, false) local column = guiGridListAddColumn(availableHornsList, "Available horns", 0.9) for id, horn in ipairs(hornsTable) do local row = guiGridListAddRow(availableHornsList) guiGridListSetItemText(availableHornsList, row, column, tostring(id) .. ") " .. horn, false, false) end -- myHornsList = guiCreateGridList(0.53, 0.15, 0.42, 0.66, true, buyHornsTab) guiGridListSetSortingEnabled(myHornsList, false) myHornsNameColumn = guiGridListAddColumn(myHornsList, "My horns", 0.7) myHornsKeyColumn = guiGridListAddColumn(myHornsList, "Key", 0.2) --// Labels //-- guiCreateLabel(0.05, 0.04, 0.9, 0.15, 'Select a horn out of the left box and press "Buy" to buy for regular usage or double-click to listen it.', true, buyHornsTab) guiCreateLabel(0.06, 0.105, 0.9, 0.15, 'Double-click to listen horn:', true, buyHornsTab) guiCreateLabel(0.04, 0.08, 0.9, 0.15, "Horns can only be used 3 times per map (10 secs cool-off). However, you can buy\nunlimited usage of the custom horn for 5000 GC. This item applies to all horns.", true, perkTab) guiCreateLabel(0.54, 0.105, 0.9, 0.15, 'Double-click to bind horn to a key:', true, buyHornsTab) guiCreateLabel(0.753, 0.94, 0.9, 0.15, '(for gamepads)', true, buyHornsTab) --// Buttons //-- local buy = guiCreateButton(0.05, 0.83, 0.22, 0.12, "Buy selected horn\nPrice: 2000 GC (each)", true, buyHornsTab) local unbindall = guiCreateButton(0.53, 0.83, 0.14, 0.12, "Unbind\nall horns", true, buyHornsTab) local bindForGamepads = guiCreateButton(0.69, 0.83, 0.26, 0.12, "Bind to a horn control name\n(Esc -> Settings -> Binds)", true, buyHornsTab) unlimited = guiCreateButton(0.77, 0.05, 0.20, 0.15, "Buy unlimited usage\nPrice: 5000 GC", true, perkTab) --// Event Handlers //-- addEventHandler("onClientGUIClick", buy, buyButton, false) addEventHandler("onClientGUIDoubleClick", myHornsList, preBindKeyForHorn, false) addEventHandler("onClientGUIDoubleClick", availableHornsList, playButton, false) addEventHandler("onClientGUIClick", unbindall, unbindAllHorns, false) addEventHandler("onClientGUIClick", bindForGamepads, bindToHornControlName, false) addEventHandler("onClientGUIClick", unlimited, unlimitedHorn, false) end addEvent('onShopInit', true) addEventHandler('onShopInit', root, onShopInit) local previewHornList = {} function playButton(button, state) if button == "left" and state == "up" then local row, col = guiGridListGetSelectedItem(availableHornsList) if row == -1 or row == false then return end row = row + 1 local extension extension = ".mp3" table.insert(previewHornList, "horns/files/" .. tostring(row) .. extension) downloadFile("horns/files/" .. tostring(row) .. extension) end end function buyButton(button, state) if button == "left" and state == "up" then local row, col = guiGridListGetSelectedItem(availableHornsList) if row == -1 or row == false then outputChatBox("Select a horn first", 255, 0, 0) return end row = row + 1 triggerServerEvent('onPlayerBuyHorn', localPlayer, row) end end ------------------ -- Horn binding -- ------------------ function bindToHornControlName(button, state) if button == "left" and state == "up" then local row, col = guiGridListGetSelectedItem(myHornsList) if row == -1 or row == false then outputChatBox("Select a horn first", 255, 0, 0) return end soundName = guiGridListGetItemData(myHornsList, row, col) bindKeyForHorn("horn") end end function getKeyForHorn(key, state) if state then if key == "escape" then unbindKeyForHorn() cancelEvent() else bindKeyForHorn(key) end removeEventHandler("onClientKey", root, getKeyForHorn) destroyElement(bindingWindow) end end function preBindKeyForHorn() local row, col = guiGridListGetSelectedItem(source) if row == -1 or row == false then outputChatBox("Select a horn first", 255, 0, 0) return end soundName = guiGridListGetItemData(source, row, col) bindingWindow = guiCreateWindow(0.4 * screenWidth / 1920, 0.45 * screenHeight / 1080, 0.2 * screenWidth / 1920, 0.08 * screenHeight / 1080, "Binding a key to horn", true) guiCreateLabel(0.25, 0.5, 1, 1, "Press a key to bind or escape to clear", true, bindingWindow) guiWindowSetMovable(bindingWindow, false) guiSetAlpha(bindingWindow, 1) addEventHandler("onClientKey", root, getKeyForHorn) end function bindKeyForHorn(keyNew) for i, j in ipairs(hornsTable) do if j == soundName then hornBinded = false bindsXML = xmlLoadFile('horns/binds-' .. getElementData(localPlayer, "mrgreen_gc_forumID") .. '.xml') for x = 0, 1000 do local bindNode = xmlFindChild(bindsXML, "bind", x) if bindNode then local keyOld = xmlNodeGetAttribute(bindNode, "key") local hornID = xmlNodeGetAttribute(bindNode, "hornID") if hornID == tostring(i) then xmlNodeSetAttribute(bindNode, "key", keyNew) triggerServerEvent("bindHorn", localPlayer, keyNew, i, soundName, false) triggerServerEvent("unbindHorn", localPlayer, keyOld) xmlSaveFile(bindsXML) hornBinded = true end else --elseif no bindNode then create it: if not hornBinded then local bindNode = xmlCreateChild(bindsXML, "bind") xmlNodeSetAttribute(bindNode, "key", keyNew) xmlNodeSetAttribute(bindNode, "hornID", i) xmlNodeSetAttribute(bindNode, "hornName", soundName) triggerServerEvent("bindHorn", localPlayer, keyNew, i, soundName, false) xmlSaveFile(bindsXML) end xmlUnloadFile(bindsXML) triggerServerEvent('getHornsData', localPlayer) break end end end end end function unbindKeyForHorn() for i, j in ipairs(hornsTable) do if j == soundName then bindsXML = xmlLoadFile('horns/binds-' .. getElementData(localPlayer, "mrgreen_gc_forumID") .. '.xml') for x = 0, 1000 do local bindNode = xmlFindChild(bindsXML, "bind", x) if bindNode then local key = xmlNodeGetAttribute(bindNode, "key") local hornID = xmlNodeGetAttribute(bindNode, "hornName") if hornID == soundName then xmlDestroyNode(bindNode) triggerServerEvent("unbindHorn", localPlayer, key) xmlSaveFile(bindsXML) xmlUnloadFile(bindsXML) triggerServerEvent('getHornsData', localPlayer) break end end end end end end function unbindAllHorns() triggerServerEvent("unbindAllHorns", resourceRoot) bindsXML = xmlLoadFile('horns/binds-' .. getElementData(localPlayer, "mrgreen_gc_forumID") .. '.xml') for i = 0, 1000 do if bindsXML then local bindNode = xmlFindChild(bindsXML, "bind", i) if bindNode then local key = xmlNodeGetAttribute(bindNode, "key") if key ~= nil then triggerServerEvent("unbindHorn", localPlayer, key) end else bindsXML = xmlCreateFile('horns/binds-' .. getElementData(localPlayer, "mrgreen_gc_forumID") .. '.xml', "binds") xmlSaveFile(bindsXML) xmlUnloadFile(bindsXML) triggerServerEvent('getHornsData', localPlayer) break end end end end function unlimitedHorn(button, state) if button == "left" and state == "up" then triggerServerEvent('onPlayerBuyUnlimitedHorn', localPlayer) end end addEvent('onClientSuccessBuyHorn', true) addEventHandler('onClientSuccessBuyHorn', root, function(success) if success then outputChatBox("Horn successfully bought") triggerServerEvent('getHornsData', localPlayer) else outputChatBox("Either not logged in, or not enough GC, or you already have this horn.") end end) addEvent("hornsLogin", true) addEventHandler("hornsLogin", root, function(isUnlimited, forumid) setElementData(localPlayer, "mrgreen_gc_forumID", forumid) if isUnlimited then guiSetText(unlimited, "Buy unlimited usage\nPrice: 5000 GC\nBought!") guiSetEnabled(unlimited, false) end triggerServerEvent('getHornsData', localPlayer) end) addEvent("hornsLogout", true) addEventHandler("hornsLogout", root, function() triggerServerEvent("unbindAllHorns", resourceRoot) guiGridListClear(myHornsList) guiSetText(unlimited, "Buy unlimited usage\nPrice: 5000 GC") guiSetEnabled(unlimited, true) end) addEvent('sendHornsData', true) addEventHandler('sendHornsData', root, function(boughtHorns) guiGridListClear(myHornsList) for i, j in ipairs(boughtHorns) do local row = guiGridListAddRow(myHornsList) guiGridListSetItemText(myHornsList, row, myHornsNameColumn, tostring(j) .. ") " .. hornsTable[tonumber(j)], false, false) guiGridListSetItemData(myHornsList, row, myHornsNameColumn, hornsTable[tonumber(j)]) guiGridListSetItemText(myHornsList, row, myHornsKeyColumn, getKeyBoundToHorn(tostring(j)), false, false) end end) function getKeyBoundToHorn(horn) bindsXML = xmlLoadFile('horns/binds-' .. getElementData(localPlayer, "mrgreen_gc_forumID") .. '.xml') if not bindsXML then bindsXML = xmlCreateFile('horns/binds-' .. getElementData(localPlayer, "mrgreen_gc_forumID") .. '.xml', "binds") xmlSaveFile(bindsXML) end for i = 0, 1000 do local bindNode = xmlFindChild(bindsXML, "bind", i) if bindNode then local key = xmlNodeGetAttribute(bindNode, "key") local hornID = xmlNodeGetAttribute(bindNode, "hornID") if key ~= nil and horn == hornID then if string.len(hornID) >= 5 then triggerServerEvent("bindHorn", localPlayer, key, hornID, nil, true) elseif string.len(hornID) >= 1 and string.len(hornID) <= 3 then triggerServerEvent("bindHorn", localPlayer, key, hornID, nil, false) end xmlUnloadFile(bindsXML) return key end else xmlUnloadFile(bindsXML) return "-" end end end soundTimer = {} killOtherTimer = {} local screenSizex, screenSizey = guiGetScreenSize() local guix = screenSizex * 0.1 local guiy = screenSizex * 0.1 local globalscale = 1.35 local globalalpha = 1 icon = {} function createSoundForCar(car, horn) if not isElement(car) then return end if getElementType(car) == "player" then car = getPedOccupiedVehicle(car) end -- If var car = player then turn car into an actual car element if isElement(icon[car]) then destroyElement(icon[car]) end if isTimer(soundTimer[car]) then killTimer(soundTimer[car]) end if isTimer(killOtherTimer[car]) then killTimer(killOtherTimer[car]) end icon[car] = guiCreateStaticImage(0, 0, guix, guiy, "horns/icon.png", false) guiSetVisible(icon[car], false) local x, y, z = getElementPosition(car) local sound = playSound3D(horn, x, y, z, false) -- Horn argument is passed as path setSoundMaxDistance(sound, 50) setSoundSpeed(sound, getGameSpeed() or 1) -- change horn pitch as gamespeed changes local length = getSoundLength(sound) length = length * 1000 -- update horn icon position/alpha soundTimer[car] = setTimer(function(sound, car) if not isElement(sound) or not isElement(car) then return end local rx, ry, rz = getElementPosition(car) setElementPosition(sound, rx, ry, rz) setSoundSpeed(sound, getGameSpeed() or 1) -- change horn pitch local target = getCameraTarget() local playerx, playery, playerz = getElementPosition(getPedOccupiedVehicle(localPlayer)) if target then playerx, playery, playerz = getElementPosition(target) end cp_x, cp_y, cp_z = getElementPosition(car) local dist = getDistanceBetweenPoints3D(cp_x, cp_y, cp_z, playerx, playery, playerz) if dist and dist < 40 and (isLineOfSightClear(cp_x, cp_y, cp_z, playerx, playery, playerz, true, false, false, false)) then local screenX, screenY = getScreenFromWorldPosition(cp_x, cp_y, cp_z) local scaled = screenSizex * (1 / (2 * (dist + 5))) * .85 local relx, rely = scaled * globalscale, scaled * globalscale guiSetAlpha(icon[car], globalalpha) guiSetSize(icon[car], relx, rely, false) if (screenX and screenY) then guiSetPosition(icon[car], screenX - relx / 2, screenY - rely / 1.3, false) guiSetVisible(icon[car], true) else guiSetVisible(icon[car], false) end else guiSetVisible(icon[car], false) end end, 50, 0, sound, car) killOtherTimer[car] = setTimer(function(theTimer, car) if isTimer(theTimer) then killTimer(theTimer) if isElement(icon[car]) then destroyElement(icon[car]) end end end, length, 50, soundTimer[car], car) end addEvent("onPlayerUsingHorn", true) function playerUsingHorn(horn, car) if (getElementData(source, "state") == "alive") and (getElementData(localPlayer, "state") == "alive") and (soundsOn == true) and (getElementData(localPlayer, "dim") == getElementData(source, "dim")) and getPedOccupiedVehicle(localPlayer) then local x, y, z = getElementPosition(getPedOccupiedVehicle(localPlayer)) local rx, ry, rz = getElementPosition(car) local playerTriggered = getVehicleOccupant(car) if not playerTriggered or getElementType(playerTriggered) ~= "player" then return end -- DO THIS IN OTHER FUNCTION -- if getDistanceBetweenPoints3D(x,y,z,rx,ry,rz) < 40 then -- Download file first, then do this local extension = ".mp3" local hornPath = "horns/files/" .. horn .. extension table.insert(downloadHornList, { horn = hornPath, player = playerTriggered }) downloadFile(hornPath) end end addEventHandler("onPlayerUsingHorn", root, playerUsingHorn) function getHornSource(path, preview) local found = {} local remove = {} if preview then for num, t in ipairs(previewHornList) do if t == path then found = true table.insert(remove, num) end end if #remove > 0 then for _, i in ipairs(remove) do table.remove(previewHornList, i) end end else for num, t in ipairs(downloadHornList) do if t.horn == path then table.insert(found, t.player) table.insert(remove, num) end end if #remove > 0 then for _, i in ipairs(remove) do table.remove(downloadHornList, i) end end end return found end function onHornDownloadComplete(path, succes) if not succes then outputDebugString("GCSHOP: " .. path .. " failed to download (horns_c)") return false end if #previewHornList > 0 then local prevSource = getHornSource(path, true) if isElement(hornPreview) then stopSound(hornPreview) end if prevSource then hornPreview = playSound(path, false) end end local hornSource = getHornSource(path) if #hornSource > 0 then for _, p in ipairs(hornSource) do createSoundForCar(p, path) end end end addEventHandler("onClientFileDownloadComplete", resourceRoot, onHornDownloadComplete) soundsOn = true addEvent('onClientSuccessBuyUnlimitedUsage', true) addEventHandler('onClientSuccessBuyUnlimitedUsage', root, function(success) if success then guiSetText(unlimited, "Buy unlimited usage\nPrice: 5000 GC\nBought!") guiSetEnabled(unlimited, false) end end)
mit
luigiScarso/luatexjit
source/texk/web2c/luatexdir/luazlib/test_zlib.lua
3
3016
-- $Id: test_zlib.lua,v 1.3 2004/07/22 19:10:47 tngd Exp $ -- zlib = loadlib("./lzlib.so", "luaopen_zlib")() local function line(header, c) header = header or '' c = c or '-' print(string.rep(string.sub(c, 1, 1), 78 - string.len(header))..header) end local function ipart(value) return value - math.mod(value, 1) end local function bitvalues(value, bstart, num) value = ipart(value / 2^bstart) return math.mod(value, 2^num) end line(' zlib '..zlib.version(), '=') line(' adler32') local adler = zlib.adler32() print('adler32 init : '..adler) adler = zlib.adler32(adler, 'some text') print('updated adler: '..adler) adler = zlib.adler32(adler, 'some text') print('updated adler: '..adler) adler = zlib.adler32(adler, 'some text') print('updated adler: '..adler) adler = zlib.adler32(adler, 'some text') print('updated adler: '..adler) adler = zlib.adler32(adler, 'some text') print('updated adler: '..adler) adler = zlib.adler32(adler, 'some textd') print('updated adler: '..adler) line(' crc32') local crc = zlib.crc32() print('crc32 init : '..crc) crc = zlib.crc32(crc, 'some text') print('updated crc: '..crc) crc = zlib.crc32(crc, 'some text') print('updated crc: '..crc) crc = zlib.crc32(crc, 'some text') print('updated crc: '..crc) crc = zlib.crc32(crc, 'some text') print('updated crc: '..crc) crc = zlib.crc32(crc, 'some text') print('updated crc: '..crc) crc = zlib.crc32(crc, 'some textd') print('updated crc: '..crc) line(' deflate/inflate') local us f = io.open('lzlib.c') -- f = io.open('../all.tar') us = f:read('*a') f:close() do -- local block local f, cs, zd, zi, aux_res, res, ret, count print('file length : '..string.len(us)) cs = '' zd = zlib.compressobj(1) print('deflate stream : '..tostring(zd)) cs = cs .. zd:compress(string.sub(us, 1, string.len(us)/2)) cs = cs .. zd:compress(string.sub(us, string.len(us)/2+1)) cs = cs .. zd:flush() print('compressed length : '..string.len(cs)) print('compressed adler : '..tostring(zd:adler())) zd:close() zi = zlib.decompressobj() print('inflate stream : '..tostring(zi)) res = '' res = res .. zi:decompress(string.sub(cs, 1, 10)) res = res .. zi:decompress(string.sub(cs, 11)) res = res .. zi:flush() print('uncompressed length : '..string.len(res)) print('uncompressed adler : '..tostring(zi:adler())) zi:close() print('result == uncompressed : '..tostring(res == us)) print('compression ratio : '..tostring(string.len(us)/string.len(cs))) end -- local block collectgarbage() line(' compress/uncompress') do -- local block local cs, res print('file length : '..string.len(us)) cs = zlib.compress(us,1) print('compressed length : '..string.len(cs)) res = zlib.decompress(cs) print('compressed length : '..string.len(res)) print('result == uncompressed : '..tostring(res == us)) print('compression ratio : '..tostring(string.len(us)/string.len(cs))) end -- local block line(' zlib '..zlib.version(), '=')
gpl-2.0
Frenzie/koreader-base
spec/unit/koptcontext_spec.lua
3
8613
local ffi = require("ffi") local KOPTContext = require("ffi/koptcontext") local mupdf = require("ffi/mupdf") local k2pdfopt = ffi.load("libs/libk2pdfopt.so.2") local sample_pdf = "spec/base/unit/data/Alice.pdf" local paper_pdf = "spec/base/unit/data/Paper.pdf" describe("KOPTContext module", function() local sample_pdf_doc local paper_pdf_doc setup(function() sample_pdf_doc = mupdf.openDocument(sample_pdf) paper_pdf_doc = mupdf.openDocument(paper_pdf) end) teardown(function() sample_pdf_doc:close() paper_pdf_doc:close() end) it("should be created", function() local kc = KOPTContext.new() assert.is_not_nil(kc) end) describe("set/get API", function() it("should set/get wrap", function() local kc = KOPTContext.new() for wrap = 0, 1 do kc:setWrap(wrap) assert.equals(kc:getWrap(), wrap) end end) it("should set/get trim", function() local kc = KOPTContext.new() for trim = 0, 1 do kc:setTrim(trim) assert.equals(kc:getTrim(), trim) end end) it("should set/get zoom", function() local kc = KOPTContext.new() for zoom = 0.2, 2.0, 0.2 do kc:setZoom(zoom) assert.equals(kc:getZoom(), zoom) end end) it("should set/get BBox", function() local kc = KOPTContext.new() local bbox = {10, 20, 500, 400} kc:setBBox(unpack(bbox)) assert.are.same({kc:getBBox()}, bbox) end) it("should set/get language", function() local kc = KOPTContext.new() local lang = "eng" kc:setLanguage(lang) assert.are.same(kc:getLanguage(), lang) end) end) it("should copy bmp from other context", function() local kc1 = KOPTContext.new() assert.are.same({kc1.dst.width, kc1.dst.height}, {0, 0}) local kc2 = KOPTContext.new() local page = sample_pdf_doc:openPage(1) page:toBmp(kc2.dst, 300) page:close() kc1:copyDestBMP(kc2) assert.are_not.same({kc1.dst.width, kc1.dst.height}, {0, 0}) assert.are.same({kc1.dst.width, kc1.dst.height}, {kc2.dst.width, kc2.dst.height}) end) it("should be used as reflowing context", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(2) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) assert(kc.dst.size_allocated ~= 0) assert.are_not.same({kc.dst.width, kc.dst.height}, {0, 0}) end) it("should get larger reflowed page with larger original page", function() local kc1 = KOPTContext.new() local kc2 = KOPTContext.new() local page = sample_pdf_doc:openPage(2) page:toBmp(kc1.src, 167) page:toBmp(kc2.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc1) k2pdfopt.k2pdfopt_reflow_bmp(kc2) assert(kc1.dst.height < kc2.dst.height) end) it("should get reflowed word boxes", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(3) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) local boxes = kc:getReflowedWordBoxes("dst", 0, 0, kc.dst.width, kc.dst.height) for i = 1, #boxes do for j = 1, #boxes[i] do local box = boxes[i][j] assert.are_not_nil(box.x0, box.y0, box.x1, box.y1) end end end) it("should get native word boxes", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(4) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) local boxes = kc:getNativeWordBoxes("dst", 0, 0, kc.dst.width, kc.dst.height) for i = 1, #boxes do for j = 1, #boxes[i] do local box = boxes[i][j] assert.are_not_nil(box.x0, box.y0, box.x1, box.y1) end end end) it("should transform native postion to reflowed position", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(5) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) for j = 0, 800, 100 do for i = 0, 600, 100 do local x, y = kc:nativeToReflowPosTransform(i, j) assert.are_not_nil(x, y) end end end) it("should transform reflow postion to native position", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(5) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) for j = 0, 800, 100 do for i = 0, 600, 100 do local x, y = kc:reflowToNativePosTransform(i, j, 0.5, 0.5) assert.are_not_nil(x, y) end end end) it("should get OCR word from tesseract OCR engine", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(5) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) local word = kc:getTOCRWord("dst", 280, 60, 100, 40, "data", "eng", 3, 0, 0) assert.are_same(word, "Alice") kc:freeOCR() end) it("should free dst bitmap after reflowing", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(6) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) assert(kc.dst.size_allocated ~= 0) kc:free() assert(kc.dst.size_allocated == 0) end) it("should get page textblock at any relative location", function() local kc = KOPTContext.new() local page = paper_pdf_doc:openPage(1) page:toBmp(kc.src, 150) page:close() kc.page_width, kc.page_height = kc.src.width, kc.src.height kc:findPageBlocks() local block = kc:getPageBlock(0.6, 0.5) assert.truthy(block.x1 > 0 and block.x0 > 0) assert.truthy(block.x1 - block.x0 < 0.5) -- we know this is a two-column page assert.truthy(block.x0 <= 0.6 and block.x1 >= 0.6) assert.truthy(block.y0 <= 0.5 and block.y1 >= 0.5) block = nil -- luacheck: ignore 311 for y = 0, 1, 0.2 do for x = 0, 1, 0.2 do block = kc:getPageBlock(x, y) if block then assert.truthy(block.x1 > 0 and block.x0 > 0) assert.truthy(block.x1 - block.x0 < 0.5) assert.truthy(block.x0 <= x and block.x1 >= x) assert.truthy(block.y0 <= y and block.y1 >= y) end end end end) it("should convert koptcontext to/from table", function() local kc = KOPTContext.new() kc:setLanguage("eng") local page = sample_pdf_doc:openPage(6) page:toBmp(kc.src, 300) page:close() k2pdfopt.k2pdfopt_reflow_bmp(kc) local kc_table = KOPTContext.totable(kc) local new_kc = KOPTContext.fromtable(kc_table) local new_kc_table = KOPTContext.totable(new_kc) assert.are.same(kc_table.bbox, new_kc_table.bbox) assert.are.same(kc_table.language, new_kc_table.language) assert.are.same(kc_table.dst_data, new_kc_table.dst_data) assert.are.same(kc_table.src_data, new_kc_table.src_data) assert.are.same(kc_table.rboxa, new_kc_table.rboxa) assert.are.same(kc_table.rnai, new_kc_table.rnai) assert.are.same(kc_table.nboxa, new_kc_table.nboxa) assert.are.same(kc_table.nnai, new_kc_table.nnai) assert.are.same(kc_table.rectmaps, new_kc_table.rectmaps) kc:free() new_kc:free() end) it("should export src bitmap to PNG file", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(1) page:toBmp(kc.src, 300) page:close() kc:exportSrcPNGFile(nil, nil, "/tmp/src.png") end) it("should export src bitmap to PNG string", function() local kc = KOPTContext.new() local page = sample_pdf_doc:openPage(1) page:toBmp(kc.src, 300) page:close() local png = kc:exportSrcPNGString("none") assert.truthy(png) end) end)
agpl-3.0
AliKhodadad/zed-spam
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
ioiasff/khp
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
ashkanpj/fire
plugins/quotes.lua
651
1630
local quotes_file = './data/quotes.lua' local quotes_table function read_quotes_file() local f = io.open(quotes_file, "r+") if f == nil then print ('Created a new quotes file on '..quotes_file) serialize_to_file({}, quotes_file) else print ('Quotes loaded: '..quotes_file) f:close() end return loadfile (quotes_file)() end function save_quote(msg) local to_id = tostring(msg.to.id) if msg.text:sub(11):isempty() then return "Usage: !addquote quote" end if quotes_table == nil then quotes_table = {} end if quotes_table[to_id] == nil then print ('New quote key to_id: '..to_id) quotes_table[to_id] = {} end local quotes = quotes_table[to_id] quotes[#quotes+1] = msg.text:sub(11) serialize_to_file(quotes_table, quotes_file) return "done!" end function get_quote(msg) local to_id = tostring(msg.to.id) local quotes_phrases quotes_table = read_quotes_file() quotes_phrases = quotes_table[to_id] return quotes_phrases[math.random(1,#quotes_phrases)] end function run(msg, matches) if string.match(msg.text, "!quote$") then return get_quote(msg) elseif string.match(msg.text, "!addquote (.+)$") then quotes_table = read_quotes_file() return save_quote(msg) end end return { description = "Save quote", description = "Quote plugin, you can create and retrieve random quotes", usage = { "!addquote [msg]", "!quote", }, patterns = { "^!addquote (.+)$", "^!quote$", }, run = run }
gpl-2.0
luigiScarso/luatexjit
source/texk/web2c/luatexdir/dynasm/dasm_ppc.lua
15
37064
------------------------------------------------------------------------------ -- DynASM PPC module. -- -- Copyright (C) 2005-2012 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "ppc", description = "DynASM PPC module", version = "1.3.0", vernum = 10300, release = "2011-05-05", 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 = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift local tohex = 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", } -- 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 <= 0xffffff 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") 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. local map_archdef = { sp = "r1" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r1" then return "sp" end return s end local map_cond = { lt = 0, gt = 1, eq = 2, so = 3, ge = 4, le = 5, ne = 6, ns = 7, } ------------------------------------------------------------------------------ -- Template strings for PPC instructions. local map_op = { tdi_3 = "08000000ARI", twi_3 = "0c000000ARI", mulli_3 = "1c000000RRI", subfic_3 = "20000000RRI", cmplwi_3 = "28000000XRU", cmplwi_2 = "28000000-RU", cmpldi_3 = "28200000XRU", cmpldi_2 = "28200000-RU", cmpwi_3 = "2c000000XRI", cmpwi_2 = "2c000000-RI", cmpdi_3 = "2c200000XRI", cmpdi_2 = "2c200000-RI", addic_3 = "30000000RRI", ["addic._3"] = "34000000RRI", addi_3 = "38000000RR0I", li_2 = "38000000RI", la_2 = "38000000RD", addis_3 = "3c000000RR0I", lis_2 = "3c000000RI", lus_2 = "3c000000RU", bc_3 = "40000000AAK", bcl_3 = "40000001AAK", bdnz_1 = "42000000K", bdz_1 = "42400000K", sc_0 = "44000000", b_1 = "48000000J", bl_1 = "48000001J", rlwimi_5 = "50000000RR~AAA.", rlwinm_5 = "54000000RR~AAA.", rlwnm_5 = "5c000000RR~RAA.", ori_3 = "60000000RR~U", nop_0 = "60000000", oris_3 = "64000000RR~U", xori_3 = "68000000RR~U", xoris_3 = "6c000000RR~U", ["andi._3"] = "70000000RR~U", ["andis._3"] = "74000000RR~U", lwz_2 = "80000000RD", lwzu_2 = "84000000RD", lbz_2 = "88000000RD", lbzu_2 = "8c000000RD", stw_2 = "90000000RD", stwu_2 = "94000000RD", stb_2 = "98000000RD", stbu_2 = "9c000000RD", lhz_2 = "a0000000RD", lhzu_2 = "a4000000RD", lha_2 = "a8000000RD", lhau_2 = "ac000000RD", sth_2 = "b0000000RD", sthu_2 = "b4000000RD", lmw_2 = "b8000000RD", stmw_2 = "bc000000RD", lfs_2 = "c0000000FD", lfsu_2 = "c4000000FD", lfd_2 = "c8000000FD", lfdu_2 = "cc000000FD", stfs_2 = "d0000000FD", stfsu_2 = "d4000000FD", stfd_2 = "d8000000FD", stfdu_2 = "dc000000FD", ld_2 = "e8000000RD", -- NYI: displacement must be divisible by 4. ldu_2 = "e8000001RD", lwa_2 = "e8000002RD", std_2 = "f8000000RD", stdu_2 = "f8000001RD", -- Primary opcode 19: mcrf_2 = "4c000000XX", isync_0 = "4c00012c", crnor_3 = "4c000042CCC", crnot_2 = "4c000042CC=", crandc_3 = "4c000102CCC", crxor_3 = "4c000182CCC", crclr_1 = "4c000182C==", crnand_3 = "4c0001c2CCC", crand_3 = "4c000202CCC", creqv_3 = "4c000242CCC", crset_1 = "4c000242C==", crorc_3 = "4c000342CCC", cror_3 = "4c000382CCC", crmove_2 = "4c000382CC=", bclr_2 = "4c000020AA", bclrl_2 = "4c000021AA", bcctr_2 = "4c000420AA", bcctrl_2 = "4c000421AA", blr_0 = "4e800020", blrl_0 = "4e800021", bctr_0 = "4e800420", bctrl_0 = "4e800421", -- Primary opcode 31: cmpw_3 = "7c000000XRR", cmpw_2 = "7c000000-RR", cmpd_3 = "7c200000XRR", cmpd_2 = "7c200000-RR", tw_3 = "7c000008ARR", subfc_3 = "7c000010RRR.", subc_3 = "7c000010RRR~.", mulhdu_3 = "7c000012RRR.", addc_3 = "7c000014RRR.", mulhwu_3 = "7c000016RRR.", isel_4 = "7c00001eRRRC", isellt_3 = "7c00001eRRR", iselgt_3 = "7c00005eRRR", iseleq_3 = "7c00009eRRR", mfcr_1 = "7c000026R", mfocrf_2 = "7c100026RG", mtcrf_2 = "7c000120GR", mtocrf_2 = "7c100120GR", lwarx_3 = "7c000028RR0R", ldx_3 = "7c00002aRR0R", lwzx_3 = "7c00002eRR0R", slw_3 = "7c000030RR~R.", cntlzw_2 = "7c000034RR~", sld_3 = "7c000036RR~R.", and_3 = "7c000038RR~R.", cmplw_3 = "7c000040XRR", cmplw_2 = "7c000040-RR", cmpld_3 = "7c200040XRR", cmpld_2 = "7c200040-RR", subf_3 = "7c000050RRR.", sub_3 = "7c000050RRR~.", ldux_3 = "7c00006aRR0R", dcbst_2 = "7c00006c-RR", lwzux_3 = "7c00006eRR0R", cntlzd_2 = "7c000074RR~", andc_3 = "7c000078RR~R.", td_3 = "7c000088ARR", mulhd_3 = "7c000092RRR.", mulhw_3 = "7c000096RRR.", ldarx_3 = "7c0000a8RR0R", dcbf_2 = "7c0000ac-RR", lbzx_3 = "7c0000aeRR0R", neg_2 = "7c0000d0RR.", lbzux_3 = "7c0000eeRR0R", popcntb_2 = "7c0000f4RR~", not_2 = "7c0000f8RR~%.", nor_3 = "7c0000f8RR~R.", subfe_3 = "7c000110RRR.", sube_3 = "7c000110RRR~.", adde_3 = "7c000114RRR.", stdx_3 = "7c00012aRR0R", stwcx_3 = "7c00012cRR0R.", stwx_3 = "7c00012eRR0R", prtyw_2 = "7c000134RR~", stdux_3 = "7c00016aRR0R", stwux_3 = "7c00016eRR0R", prtyd_2 = "7c000174RR~", subfze_2 = "7c000190RR.", addze_2 = "7c000194RR.", stdcx_3 = "7c0001acRR0R.", stbx_3 = "7c0001aeRR0R", subfme_2 = "7c0001d0RR.", mulld_3 = "7c0001d2RRR.", addme_2 = "7c0001d4RR.", mullw_3 = "7c0001d6RRR.", dcbtst_2 = "7c0001ec-RR", stbux_3 = "7c0001eeRR0R", add_3 = "7c000214RRR.", dcbt_2 = "7c00022c-RR", lhzx_3 = "7c00022eRR0R", eqv_3 = "7c000238RR~R.", eciwx_3 = "7c00026cRR0R", lhzux_3 = "7c00026eRR0R", xor_3 = "7c000278RR~R.", mfspefscr_1 = "7c0082a6R", mfxer_1 = "7c0102a6R", mflr_1 = "7c0802a6R", mfctr_1 = "7c0902a6R", lwax_3 = "7c0002aaRR0R", lhax_3 = "7c0002aeRR0R", mftb_1 = "7c0c42e6R", mftbu_1 = "7c0d42e6R", lwaux_3 = "7c0002eaRR0R", lhaux_3 = "7c0002eeRR0R", sthx_3 = "7c00032eRR0R", orc_3 = "7c000338RR~R.", ecowx_3 = "7c00036cRR0R", sthux_3 = "7c00036eRR0R", or_3 = "7c000378RR~R.", mr_2 = "7c000378RR~%.", divdu_3 = "7c000392RRR.", divwu_3 = "7c000396RRR.", mtspefscr_1 = "7c0083a6R", mtxer_1 = "7c0103a6R", mtlr_1 = "7c0803a6R", mtctr_1 = "7c0903a6R", dcbi_2 = "7c0003ac-RR", nand_3 = "7c0003b8RR~R.", divd_3 = "7c0003d2RRR.", divw_3 = "7c0003d6RRR.", cmpb_3 = "7c0003f8RR~R.", mcrxr_1 = "7c000400X", subfco_3 = "7c000410RRR.", subco_3 = "7c000410RRR~.", addco_3 = "7c000414RRR.", ldbrx_3 = "7c000428RR0R", lswx_3 = "7c00042aRR0R", lwbrx_3 = "7c00042cRR0R", lfsx_3 = "7c00042eFR0R", srw_3 = "7c000430RR~R.", srd_3 = "7c000436RR~R.", subfo_3 = "7c000450RRR.", subo_3 = "7c000450RRR~.", lfsux_3 = "7c00046eFR0R", lswi_3 = "7c0004aaRR0A", sync_0 = "7c0004ac", lwsync_0 = "7c2004ac", ptesync_0 = "7c4004ac", lfdx_3 = "7c0004aeFR0R", nego_2 = "7c0004d0RR.", lfdux_3 = "7c0004eeFR0R", subfeo_3 = "7c000510RRR.", subeo_3 = "7c000510RRR~.", addeo_3 = "7c000514RRR.", stdbrx_3 = "7c000528RR0R", stswx_3 = "7c00052aRR0R", stwbrx_3 = "7c00052cRR0R", stfsx_3 = "7c00052eFR0R", stfsux_3 = "7c00056eFR0R", subfzeo_2 = "7c000590RR.", addzeo_2 = "7c000594RR.", stswi_3 = "7c0005aaRR0A", stfdx_3 = "7c0005aeFR0R", subfmeo_2 = "7c0005d0RR.", mulldo_3 = "7c0005d2RRR.", addmeo_2 = "7c0005d4RR.", mullwo_3 = "7c0005d6RRR.", dcba_2 = "7c0005ec-RR", stfdux_3 = "7c0005eeFR0R", addo_3 = "7c000614RRR.", lhbrx_3 = "7c00062cRR0R", sraw_3 = "7c000630RR~R.", srad_3 = "7c000634RR~R.", srawi_3 = "7c000670RR~A.", sradi_3 = "7c000674RR~H.", eieio_0 = "7c0006ac", lfiwax_3 = "7c0006aeFR0R", sthbrx_3 = "7c00072cRR0R", extsh_2 = "7c000734RR~.", extsb_2 = "7c000774RR~.", divduo_3 = "7c000792RRR.", divwou_3 = "7c000796RRR.", icbi_2 = "7c0007ac-RR", stfiwx_3 = "7c0007aeFR0R", extsw_2 = "7c0007b4RR~.", divdo_3 = "7c0007d2RRR.", divwo_3 = "7c0007d6RRR.", dcbz_2 = "7c0007ec-RR", -- Primary opcode 30: rldicl_4 = "78000000RR~HM.", rldicr_4 = "78000004RR~HM.", rldic_4 = "78000008RR~HM.", rldimi_4 = "7800000cRR~HM.", rldcl_4 = "78000010RR~RM.", rldcr_4 = "78000012RR~RM.", -- Primary opcode 59: fdivs_3 = "ec000024FFF.", fsubs_3 = "ec000028FFF.", fadds_3 = "ec00002aFFF.", fsqrts_2 = "ec00002cF-F.", fres_2 = "ec000030F-F.", fmuls_3 = "ec000032FF-F.", frsqrtes_2 = "ec000034F-F.", fmsubs_4 = "ec000038FFFF~.", fmadds_4 = "ec00003aFFFF~.", fnmsubs_4 = "ec00003cFFFF~.", fnmadds_4 = "ec00003eFFFF~.", -- Primary opcode 63: fdiv_3 = "fc000024FFF.", fsub_3 = "fc000028FFF.", fadd_3 = "fc00002aFFF.", fsqrt_2 = "fc00002cF-F.", fsel_4 = "fc00002eFFFF~.", fre_2 = "fc000030F-F.", fmul_3 = "fc000032FF-F.", frsqrte_2 = "fc000034F-F.", fmsub_4 = "fc000038FFFF~.", fmadd_4 = "fc00003aFFFF~.", fnmsub_4 = "fc00003cFFFF~.", fnmadd_4 = "fc00003eFFFF~.", fcmpu_3 = "fc000000XFF", fcpsgn_3 = "fc000010FFF.", fcmpo_3 = "fc000040XFF", mtfsb1_1 = "fc00004cA", fneg_2 = "fc000050F-F.", mcrfs_2 = "fc000080XX", mtfsb0_1 = "fc00008cA", fmr_2 = "fc000090F-F.", frsp_2 = "fc000018F-F.", fctiw_2 = "fc00001cF-F.", fctiwz_2 = "fc00001eF-F.", mtfsfi_2 = "fc00010cAA", -- NYI: upshift. fnabs_2 = "fc000110F-F.", fabs_2 = "fc000210F-F.", frin_2 = "fc000310F-F.", friz_2 = "fc000350F-F.", frip_2 = "fc000390F-F.", frim_2 = "fc0003d0F-F.", mffs_1 = "fc00048eF.", -- NYI: mtfsf, mtfsb0, mtfsb1. fctid_2 = "fc00065cF-F.", fctidz_2 = "fc00065eF-F.", fcfid_2 = "fc00069cF-F.", -- Primary opcode 4, SPE APU extension: evaddw_3 = "10000200RRR", evaddiw_3 = "10000202RAR~", evsubw_3 = "10000204RRR~", evsubiw_3 = "10000206RAR~", evabs_2 = "10000208RR", evneg_2 = "10000209RR", evextsb_2 = "1000020aRR", evextsh_2 = "1000020bRR", evrndw_2 = "1000020cRR", evcntlzw_2 = "1000020dRR", evcntlsw_2 = "1000020eRR", brinc_3 = "1000020fRRR", evand_3 = "10000211RRR", evandc_3 = "10000212RRR", evxor_3 = "10000216RRR", evor_3 = "10000217RRR", evmr_2 = "10000217RR=", evnor_3 = "10000218RRR", evnot_2 = "10000218RR=", eveqv_3 = "10000219RRR", evorc_3 = "1000021bRRR", evnand_3 = "1000021eRRR", evsrwu_3 = "10000220RRR", evsrws_3 = "10000221RRR", evsrwiu_3 = "10000222RRA", evsrwis_3 = "10000223RRA", evslw_3 = "10000224RRR", evslwi_3 = "10000226RRA", evrlw_3 = "10000228RRR", evsplati_2 = "10000229RS", evrlwi_3 = "1000022aRRA", evsplatfi_2 = "1000022bRS", evmergehi_3 = "1000022cRRR", evmergelo_3 = "1000022dRRR", evcmpgtu_3 = "10000230XRR", evcmpgtu_2 = "10000230-RR", evcmpgts_3 = "10000231XRR", evcmpgts_2 = "10000231-RR", evcmpltu_3 = "10000232XRR", evcmpltu_2 = "10000232-RR", evcmplts_3 = "10000233XRR", evcmplts_2 = "10000233-RR", evcmpeq_3 = "10000234XRR", evcmpeq_2 = "10000234-RR", evsel_4 = "10000278RRRW", evsel_3 = "10000278RRR", evfsadd_3 = "10000280RRR", evfssub_3 = "10000281RRR", evfsabs_2 = "10000284RR", evfsnabs_2 = "10000285RR", evfsneg_2 = "10000286RR", evfsmul_3 = "10000288RRR", evfsdiv_3 = "10000289RRR", evfscmpgt_3 = "1000028cXRR", evfscmpgt_2 = "1000028c-RR", evfscmplt_3 = "1000028dXRR", evfscmplt_2 = "1000028d-RR", evfscmpeq_3 = "1000028eXRR", evfscmpeq_2 = "1000028e-RR", evfscfui_2 = "10000290R-R", evfscfsi_2 = "10000291R-R", evfscfuf_2 = "10000292R-R", evfscfsf_2 = "10000293R-R", evfsctui_2 = "10000294R-R", evfsctsi_2 = "10000295R-R", evfsctuf_2 = "10000296R-R", evfsctsf_2 = "10000297R-R", evfsctuiz_2 = "10000298R-R", evfsctsiz_2 = "1000029aR-R", evfststgt_3 = "1000029cXRR", evfststgt_2 = "1000029c-RR", evfststlt_3 = "1000029dXRR", evfststlt_2 = "1000029d-RR", evfststeq_3 = "1000029eXRR", evfststeq_2 = "1000029e-RR", efsadd_3 = "100002c0RRR", efssub_3 = "100002c1RRR", efsabs_2 = "100002c4RR", efsnabs_2 = "100002c5RR", efsneg_2 = "100002c6RR", efsmul_3 = "100002c8RRR", efsdiv_3 = "100002c9RRR", efscmpgt_3 = "100002ccXRR", efscmpgt_2 = "100002cc-RR", efscmplt_3 = "100002cdXRR", efscmplt_2 = "100002cd-RR", efscmpeq_3 = "100002ceXRR", efscmpeq_2 = "100002ce-RR", efscfd_2 = "100002cfR-R", efscfui_2 = "100002d0R-R", efscfsi_2 = "100002d1R-R", efscfuf_2 = "100002d2R-R", efscfsf_2 = "100002d3R-R", efsctui_2 = "100002d4R-R", efsctsi_2 = "100002d5R-R", efsctuf_2 = "100002d6R-R", efsctsf_2 = "100002d7R-R", efsctuiz_2 = "100002d8R-R", efsctsiz_2 = "100002daR-R", efststgt_3 = "100002dcXRR", efststgt_2 = "100002dc-RR", efststlt_3 = "100002ddXRR", efststlt_2 = "100002dd-RR", efststeq_3 = "100002deXRR", efststeq_2 = "100002de-RR", efdadd_3 = "100002e0RRR", efdsub_3 = "100002e1RRR", efdcfuid_2 = "100002e2R-R", efdcfsid_2 = "100002e3R-R", efdabs_2 = "100002e4RR", efdnabs_2 = "100002e5RR", efdneg_2 = "100002e6RR", efdmul_3 = "100002e8RRR", efddiv_3 = "100002e9RRR", efdctuidz_2 = "100002eaR-R", efdctsidz_2 = "100002ebR-R", efdcmpgt_3 = "100002ecXRR", efdcmpgt_2 = "100002ec-RR", efdcmplt_3 = "100002edXRR", efdcmplt_2 = "100002ed-RR", efdcmpeq_3 = "100002eeXRR", efdcmpeq_2 = "100002ee-RR", efdcfs_2 = "100002efR-R", efdcfui_2 = "100002f0R-R", efdcfsi_2 = "100002f1R-R", efdcfuf_2 = "100002f2R-R", efdcfsf_2 = "100002f3R-R", efdctui_2 = "100002f4R-R", efdctsi_2 = "100002f5R-R", efdctuf_2 = "100002f6R-R", efdctsf_2 = "100002f7R-R", efdctuiz_2 = "100002f8R-R", efdctsiz_2 = "100002faR-R", efdtstgt_3 = "100002fcXRR", efdtstgt_2 = "100002fc-RR", efdtstlt_3 = "100002fdXRR", efdtstlt_2 = "100002fd-RR", efdtsteq_3 = "100002feXRR", efdtsteq_2 = "100002fe-RR", evlddx_3 = "10000300RR0R", evldd_2 = "10000301R8", evldwx_3 = "10000302RR0R", evldw_2 = "10000303R8", evldhx_3 = "10000304RR0R", evldh_2 = "10000305R8", evlwhex_3 = "10000310RR0R", evlwhe_2 = "10000311R4", evlwhoux_3 = "10000314RR0R", evlwhou_2 = "10000315R4", evlwhosx_3 = "10000316RR0R", evlwhos_2 = "10000317R4", evstddx_3 = "10000320RR0R", evstdd_2 = "10000321R8", evstdwx_3 = "10000322RR0R", evstdw_2 = "10000323R8", evstdhx_3 = "10000324RR0R", evstdh_2 = "10000325R8", evstwhex_3 = "10000330RR0R", evstwhe_2 = "10000331R4", evstwhox_3 = "10000334RR0R", evstwho_2 = "10000335R4", evstwwex_3 = "10000338RR0R", evstwwe_2 = "10000339R4", evstwwox_3 = "1000033cRR0R", evstwwo_2 = "1000033dR4", evmhessf_3 = "10000403RRR", evmhossf_3 = "10000407RRR", evmheumi_3 = "10000408RRR", evmhesmi_3 = "10000409RRR", evmhesmf_3 = "1000040bRRR", evmhoumi_3 = "1000040cRRR", evmhosmi_3 = "1000040dRRR", evmhosmf_3 = "1000040fRRR", evmhessfa_3 = "10000423RRR", evmhossfa_3 = "10000427RRR", evmheumia_3 = "10000428RRR", evmhesmia_3 = "10000429RRR", evmhesmfa_3 = "1000042bRRR", evmhoumia_3 = "1000042cRRR", evmhosmia_3 = "1000042dRRR", evmhosmfa_3 = "1000042fRRR", evmwhssf_3 = "10000447RRR", evmwlumi_3 = "10000448RRR", evmwhumi_3 = "1000044cRRR", evmwhsmi_3 = "1000044dRRR", evmwhsmf_3 = "1000044fRRR", evmwssf_3 = "10000453RRR", evmwumi_3 = "10000458RRR", evmwsmi_3 = "10000459RRR", evmwsmf_3 = "1000045bRRR", evmwhssfa_3 = "10000467RRR", evmwlumia_3 = "10000468RRR", evmwhumia_3 = "1000046cRRR", evmwhsmia_3 = "1000046dRRR", evmwhsmfa_3 = "1000046fRRR", evmwssfa_3 = "10000473RRR", evmwumia_3 = "10000478RRR", evmwsmia_3 = "10000479RRR", evmwsmfa_3 = "1000047bRRR", evmra_2 = "100004c4RR", evdivws_3 = "100004c6RRR", evdivwu_3 = "100004c7RRR", evmwssfaa_3 = "10000553RRR", evmwumiaa_3 = "10000558RRR", evmwsmiaa_3 = "10000559RRR", evmwsmfaa_3 = "1000055bRRR", evmwssfan_3 = "100005d3RRR", evmwumian_3 = "100005d8RRR", evmwsmian_3 = "100005d9RRR", evmwsmfan_3 = "100005dbRRR", evmergehilo_3 = "1000022eRRR", evmergelohi_3 = "1000022fRRR", evlhhesplatx_3 = "10000308RR0R", evlhhesplat_2 = "10000309R2", evlhhousplatx_3 = "1000030cRR0R", evlhhousplat_2 = "1000030dR2", evlhhossplatx_3 = "1000030eRR0R", evlhhossplat_2 = "1000030fR2", evlwwsplatx_3 = "10000318RR0R", evlwwsplat_2 = "10000319R4", evlwhsplatx_3 = "1000031cRR0R", evlwhsplat_2 = "1000031dR4", evaddusiaaw_2 = "100004c0RR", evaddssiaaw_2 = "100004c1RR", evsubfusiaaw_2 = "100004c2RR", evsubfssiaaw_2 = "100004c3RR", evaddumiaaw_2 = "100004c8RR", evaddsmiaaw_2 = "100004c9RR", evsubfumiaaw_2 = "100004caRR", evsubfsmiaaw_2 = "100004cbRR", evmheusiaaw_3 = "10000500RRR", evmhessiaaw_3 = "10000501RRR", evmhessfaaw_3 = "10000503RRR", evmhousiaaw_3 = "10000504RRR", evmhossiaaw_3 = "10000505RRR", evmhossfaaw_3 = "10000507RRR", evmheumiaaw_3 = "10000508RRR", evmhesmiaaw_3 = "10000509RRR", evmhesmfaaw_3 = "1000050bRRR", evmhoumiaaw_3 = "1000050cRRR", evmhosmiaaw_3 = "1000050dRRR", evmhosmfaaw_3 = "1000050fRRR", evmhegumiaa_3 = "10000528RRR", evmhegsmiaa_3 = "10000529RRR", evmhegsmfaa_3 = "1000052bRRR", evmhogumiaa_3 = "1000052cRRR", evmhogsmiaa_3 = "1000052dRRR", evmhogsmfaa_3 = "1000052fRRR", evmwlusiaaw_3 = "10000540RRR", evmwlssiaaw_3 = "10000541RRR", evmwlumiaaw_3 = "10000548RRR", evmwlsmiaaw_3 = "10000549RRR", evmheusianw_3 = "10000580RRR", evmhessianw_3 = "10000581RRR", evmhessfanw_3 = "10000583RRR", evmhousianw_3 = "10000584RRR", evmhossianw_3 = "10000585RRR", evmhossfanw_3 = "10000587RRR", evmheumianw_3 = "10000588RRR", evmhesmianw_3 = "10000589RRR", evmhesmfanw_3 = "1000058bRRR", evmhoumianw_3 = "1000058cRRR", evmhosmianw_3 = "1000058dRRR", evmhosmfanw_3 = "1000058fRRR", evmhegumian_3 = "100005a8RRR", evmhegsmian_3 = "100005a9RRR", evmhegsmfan_3 = "100005abRRR", evmhogumian_3 = "100005acRRR", evmhogsmian_3 = "100005adRRR", evmhogsmfan_3 = "100005afRRR", evmwlusianw_3 = "100005c0RRR", evmwlssianw_3 = "100005c1RRR", evmwlumianw_3 = "100005c8RRR", evmwlsmianw_3 = "100005c9RRR", -- NYI: Book E instructions. } -- Add mnemonics for "." variants. do local t = {} for k,v in pairs(map_op) do if sub(v, -1) == "." then local v2 = sub(v, 1, 7)..char(byte(v, 8)+1)..sub(v, 9, -2) t[sub(k, 1, -3).."."..sub(k, -2)] = v2 end end for k,v in pairs(t) do map_op[k] = v end end -- Add more branch mnemonics. for cond,c in pairs(map_cond) do local b1 = "b"..cond local c1 = shl(band(c, 3), 16) + (c < 4 and 0x01000000 or 0) -- bX[l] map_op[b1.."_1"] = tohex(0x40800000 + c1).."K" map_op[b1.."y_1"] = tohex(0x40a00000 + c1).."K" map_op[b1.."l_1"] = tohex(0x40800001 + c1).."K" map_op[b1.."_2"] = tohex(0x40800000 + c1).."-XK" map_op[b1.."y_2"] = tohex(0x40a00000 + c1).."-XK" map_op[b1.."l_2"] = tohex(0x40800001 + c1).."-XK" -- bXlr[l] map_op[b1.."lr_0"] = tohex(0x4c800020 + c1) map_op[b1.."lrl_0"] = tohex(0x4c800021 + c1) map_op[b1.."ctr_0"] = tohex(0x4c800420 + c1) map_op[b1.."ctrl_0"] = tohex(0x4c800421 + c1) -- bXctr[l] map_op[b1.."lr_1"] = tohex(0x4c800020 + c1).."-X" map_op[b1.."lrl_1"] = tohex(0x4c800021 + c1).."-X" map_op[b1.."ctr_1"] = tohex(0x4c800420 + c1).."-X" map_op[b1.."ctrl_1"] = tohex(0x4c800421 + c1).."-X" end ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[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-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_cr(expr) local r = match(expr, "^cr([0-7])$") if r then return tonumber(r) end werror("bad condition register name `"..expr.."'") end local function parse_cond(expr) local r, cond = match(expr, "^4%*cr([0-7])%+(%w%w)$") if r then r = tonumber(r) local c = map_cond[cond] if c and c < 4 then return r*4+c end end werror("bad condition bit name `"..expr.."'") end local function parse_imm(imm, bits, shift, scale, signed) 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.."'") elseif match(imm, "^r([1-3]?[0-9])$") or match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_shiftmask(imm, isshift) local n = tonumber(imm) if n then if shr(n, 6) == 0 then local lsb = band(imm, 31) local msb = imm - lsb return isshift and (shl(lsb, 11)+shr(msb, 4)) or (shl(lsb, 6)+msb) end werror("out of range immediate `"..imm.."'") elseif match(imm, "^r([1-3]?[0-9])$") or match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then werror("expected immediate operand, got register") else werror("NYI: parameterized 64 bit shift/mask") end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end return shl(r, 16) + parse_imm(imm, 16, 0, 0, true) end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 16) end end werror("bad displacement `"..disp.."'") end local function parse_u5disp(disp, scale) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end return shl(r, 16) + parse_imm(imm, 5, 11, scale, false) end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if r == 0 then werror("cannot use r0 in displacement") end if tp then waction("IMM", scale*1024+5*32+11, format(tp.ctypefmt, tailr)) return shl(r, 16) end end werror("bad displacement `"..disp.."'") 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 ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n, rs = 1, 26 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 3 positions (rlwinm). if secpos+3 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "R" then rs = rs - 5; op = op + shl(parse_gpr(params[n]), rs); n = n + 1 elseif p == "F" then rs = rs - 5; op = op + shl(parse_fpr(params[n]), rs); n = n + 1 elseif p == "A" then rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, false); n = n + 1 elseif p == "S" then rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, true); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "D" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "2" then op = op + parse_u5disp(params[n], 1); n = n + 1 elseif p == "4" then op = op + parse_u5disp(params[n], 2); n = n + 1 elseif p == "8" then op = op + parse_u5disp(params[n], 3); n = n + 1 elseif p == "C" then rs = rs - 5; op = op + shl(parse_cond(params[n]), rs); n = n + 1 elseif p == "X" then rs = rs - 5; op = op + shl(parse_cr(params[n]), rs+2); n = n + 1 elseif p == "W" then op = op + parse_cr(params[n]); n = n + 1 elseif p == "G" then op = op + parse_imm(params[n], 8, 12, 0, false); n = n + 1 elseif p == "H" then op = op + parse_shiftmask(params[n], true); n = n + 1 elseif p == "M" then op = op + parse_shiftmask(params[n], false); n = n + 1 elseif p == "J" or p == "K" then local mode, n, s = parse_label(params[n], false) if p == "K" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "0" then if band(shr(op, rs), 31) == 0 then werror("cannot use r0") end elseif p == "=" or p == "%" then local t = band(shr(op, p == "%" and rs+5 or rs), 31) rs = rs - 5 op = op + shl(t, rs) elseif p == "~" then local mm = shl(31, rs) local lo = band(op, mm) local hi = band(op, shl(mm, 5)) op = op - lo - hi + shl(lo, 5) + shr(hi, 5) elseif p == "-" then rs = rs - 5 elseif p == "." then -- Ignored. else assert(false) end end wputpos(pos, op) 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 = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
gpl-2.0
ctfuckme/asasasas
plugins/id.lua
13
2706
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 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' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (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 else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) 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 <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
shadoalzupedy/shadow
plugins/lock_fwd.lua
11
1683
--[[ # #ـــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ #:(( # For More Information ....! # Developer : Aziz < @TH3_GHOST > # our channel: @DevPointTeam # Version: 1.1 #:)) #ــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــــ # ]] do local function pre_process(msg) --Checking mute local hash = 'mate:'..msg.to.id if redis:get(hash) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) and not is_admin1(msg) then delete_msg(msg.id, ok_cb, true) send_large_msg(get_receiver(msg), 'عزيزي '..msg.from.first_name..'\nممنوع عمل اعادة توجيه من القنوات هنا التزم بقوانين المجموعة 👋👮\n#username @'..msg.from.username) return "done" end return msg end local function DevPoint(msg, matches) chat_id = msg.to.id if is_momod(msg) and matches[1] == 'lock' then local hash = 'mate:'..msg.to.id redis:set(hash, true) return "" elseif is_momod(msg) and matches[1] == 'unlock' then local hash = 'mate:'..msg.to.id redis:del(hash) return "" end end return { patterns = { '^[/!#](lock) fwd$', '^[/!#](unlock) fwd$' }, run = DevPoint, pre_process = pre_process } end
gpl-2.0
robbie-cao/mooncake
uvt.lua
1
1526
local uv = require('luv') -- Create a handle to a uv_timer_t local timer = uv.new_timer() local f = function () -- timer here is the value we passed in before from new_timer. print ("Awake!") end --[[ -- This will wait 1000ms and then continue inside the callback timer:start(1000, 0, f) --]] -- Create a new signal handler local sigint = uv.new_signal() -- Define a handler function uv.signal_start(sigint, "sigint", function(signal) print("got " .. signal .. ", shutting down") uv.stop() -- os.exit() end) print("Sleeping"); -- Simple echo program local stdin = uv.new_tty(0, true) stdin:read_start(function (err, data) assert(not err, err) if data then if string.find(data, "start") then print("START") timer:start(1000, 0, f) elseif string.find(data, "repeat") then print("repeat") timer:start(0, 1000, f) elseif string.find(data, "stop") then print("STOP") timer:stop() elseif string.find(data, "quit") then print("QUIT") timer:close() uv.stop() else print("UNKNOWN") end else stdin:close() end end) -- uv.run will block and wait for all events to run. -- When there are no longer any active handles, it will return uv.run() --[[ -- You must always close your uv handles or you'll leak memory -- We can't depend on the GC since it doesn't know enough about libuv. timer:close() --]] print("End")
mit
Zefiros-Software/ZPM
src/manifest/manifests.lua
1
2957
--[[ @cond ___LICENSE___ -- Copyright (c) 2017 Zefiros Software. -- -- 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. -- -- @endcond --]] Manifests = newclass "Manifests" function Manifests:init(loader, registries) self.loader = loader self.registries = registries self.manifests = {} end function Manifests:load() for name, ext in pairs(self.loader.config("install.manifests")) do local ok, validOrMessage = pcall(zpm.validate.manifests, ext) if ok and validOrMessage == true then self.loader[name] = self:_createPackages(name, ext) self.manifests[name] = Manifest(self.loader, self.loader[name], name, ext) for _, dir in ipairs(self.registries:getDirectories()) do self.manifests[name]:load(dir) end else warningf("Failed to load manifest definition '%s':\n%s\n^~~~~~~~\n\n%s", name, json.encode_pretty(ext), validOrMessage) end end end function Manifests:getLoadOrder() local result = {} local dependencyTypes = zpm.util.toArray(self.loader.config("install.manifests")) table.sort(dependencyTypes, function(t1, t2) return iif(t1[next(t1)].order ~= nil, t1[next(t1)].order, -1) < iif(t2[next(t2)].order ~= nil, t2[next(t2)].order, -1) end) for _, name in ipairs(dependencyTypes) do if name[next(name)].order then result = zpm.util.concat(result, next(name)) end end return result end function Manifests:__call(tpe, vendorPattern, namePattern, pred) if not self.manifests[tpe] then return {} end return self.manifests[tpe]:search(vendorPattern, namePattern, pred) end function Manifests:_createPackages(name, ext) local factory = Packages if ext.class and _G[ext.class] then factory = _G[ext.class] end return factory(self.loader, ext, name, ext.name) end
mit
jaequery/cmd-key-happy
lua-5.1.4/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
mit
TyRoXx/lua-with-cmake
lua51/lua-5.1.5/test/sort.lua
889
1494
-- two implementations of a sort function -- this is an example only. Lua has now a built-in function "sort" -- extracted from Programming Pearls, page 110 function qsort(x,l,u,f) if l<u then local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u x[l],x[m]=x[m],x[l] -- swap pivot to first position local t=x[l] -- pivot value m=l local i=l+1 while i<=u do -- invariant: x[l+1..m] < t <= x[m+1..i-1] if f(x[i],t) then m=m+1 x[m],x[i]=x[i],x[m] -- swap x[i] and x[m] end i=i+1 end x[l],x[m]=x[m],x[l] -- swap pivot to a valid place -- x[l+1..m-1] < x[m] <= x[m+1..u] qsort(x,l,m-1,f) qsort(x,m+1,u,f) end end function selectionsort(x,n,f) local i=1 while i<=n do local m,j=i,i+1 while j<=n do if f(x[j],x[m]) then m=j end j=j+1 end x[i],x[m]=x[m],x[i] -- swap x[i] and x[m] i=i+1 end end function show(m,x) io.write(m,"\n\t") local i=1 while x[i] do io.write(x[i]) i=i+1 if x[i] then io.write(",") end end io.write("\n") end function testsorts(x) local n=1 while x[n] do n=n+1 end; n=n-1 -- count elements show("original",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort",x) selectionsort(x,n,function (x,y) return x>y end) show("after reverse selection sort",x) qsort(x,1,n,function (x,y) return x<y end) show("after quicksort again",x) end -- array to be sorted x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"} testsorts(x)
mit
cyberz-eu/octopus
extensions/baseline/src/BaselineHtmlTemplate.lua
1
1374
return [[ <!DOCTYPE html> <html lang="en"> <head> <title id="title">{{title}}</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="{{description}}" /> <meta name="keywords" content="{{keywords}}" /> <meta name="author" content="{{author}}"> {{externalCSS}} <link rel="stylesheet" type="text/css" href="/baseline/static/css/font-awesome.min.css" /> <link rel="stylesheet" type="text/css" href="/build/static/widgets.css" /> <style type="text/css"> {{customCSS}} </style> <!--[if lte IE 8]><script src="/baseline/static/js/html5shiv.js"></script><![endif]--> <script type="text/javascript" src="/baseline/static/js/jquery.min.js"></script> <script type="text/javascript" src="/baseline/static/js/skel.min.js"></script> <script type="text/javascript" src="/baseline/static/js/skel-layers.min.js"></script> <noscript> <link rel="stylesheet" type="text/css" href="/baseline/static/js/skel.css" /> </noscript> {{externalJS}} <script type="text/javascript" src="/build/static/widgets.js"></script> <script type="text/javascript"> {{customJS}} </script> </head> <body id="top"> <div id="widgets"></div> <div id="popups"></div> <script type="text/javascript"> {{initJS}} </script> </body> </html> ]]
bsd-2-clause
lizh06/premake-core
tests/actions/vstudio/vc2010/test_filters.lua
6
3772
-- -- tests/actions/vstudio/vc2010/test_filters.lua -- Validate generation of file filter blocks in Visual Studio 2010 C/C++ projects. -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- local suite = test.declare("vs2010_filters") local vc2010 = premake.vstudio.vc2010 -- -- Setup/teardown -- local wks, prj function suite.setup() premake.action.set("vs2010") wks = test.createWorkspace() end local function prepare(group) prj = test.getproject(wks) vc2010.filterGroups(prj) end -- -- Check contents of the different file groups. -- function suite.itemGroup_onClInclude() files { "hello.h" } prepare() test.capture [[ <ItemGroup> <ClInclude Include="hello.h" /> </ItemGroup> ]] end function suite.itemGroup_onResourceSection() files { "hello.rc" } prepare() test.capture [[ <ItemGroup> <ResourceCompile Include="hello.rc" /> </ItemGroup> ]] end function suite.itemGroup_onNoneSection() files { "hello.txt" } prepare() test.capture [[ <ItemGroup> <None Include="hello.txt" /> </ItemGroup> ]] end function suite.itemGroup_onMixed() files { "hello.c", "hello.h", "hello.rc", "hello.txt" } prepare() test.capture [[ <ItemGroup> <ClInclude Include="hello.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="hello.c" /> </ItemGroup> <ItemGroup> <None Include="hello.txt" /> </ItemGroup> <ItemGroup> <ResourceCompile Include="hello.rc" /> </ItemGroup> ]] end -- -- Files with a build rule go into a custom build section. -- function suite.itemGroup_onBuildRule() files { "hello.cg" } filter "files:**.cg" buildcommands { "cgc $(InputFile)" } buildoutputs { "$(InputName).obj" } prepare("CustomBuild") test.capture [[ <ItemGroup> <CustomBuild Include="hello.cg" /> </ItemGroup> ]] end function suite.itemGroup_onSingleConfigBuildRule() files { "hello.cg" } filter { "Release", "files:**.cg" } buildcommands { "cgc $(InputFile)" } buildoutputs { "$(InputName).obj" } prepare("CustomBuild") test.capture [[ <ItemGroup> <CustomBuild Include="hello.cg" /> </ItemGroup> ]] end -- -- Files located at the root (in the same folder as the project) do not -- need a filter identifier. -- function suite.noFilter_onRootFiles() files { "hello.c", "goodbye.c" } prepare() test.capture [[ <ItemGroup> <ClCompile Include="goodbye.c" /> <ClCompile Include="hello.c" /> </ItemGroup> ]] end -- -- Check the filter with a real path. -- function suite.filter_onRealPath() files { "src/hello.c", "hello.h" } prepare() test.capture [[ <ItemGroup> <ClInclude Include="hello.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="src\hello.c"> <Filter>src</Filter> </ClCompile> </ItemGroup> ]] end -- -- Check the filter with a virtual path. -- function suite.filter_onVpath() files { "src/hello.c", "hello.h" } vpaths { ["Source Files"] = "**.c" } prepare() test.capture [[ <ItemGroup> <ClInclude Include="hello.h" /> </ItemGroup> <ItemGroup> <ClCompile Include="src\hello.c"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> ]] end -- -- Check handling of files using custom rules. -- function suite.filter_onCustomRule() rules "Animation" files { "hello.dae" } rule "Animation" fileextension ".dae" prepare() test.capture [[ <ItemGroup> <Animation Include="hello.dae" /> </ItemGroup> ]] end -- -- Check handling of .asm files -- function suite.itemGroup_onNoneSection() files { "hello.asm" } prepare() test.capture [[ <ItemGroup> <Masm Include="hello.asm" /> </ItemGroup> ]] end
bsd-3-clause
LuaDist2/oil
lua/loop/collection/UnorderedArray.lua
12
1495
-------------------------------------------------------------------------------- ---------------------- ## ##### ##### ###### ----------------------- ---------------------- ## ## ## ## ## ## ## ----------------------- ---------------------- ## ## ## ## ## ###### ----------------------- ---------------------- ## ## ## ## ## ## ----------------------- ---------------------- ###### ##### ##### ## ----------------------- ---------------------- ----------------------- ----------------------- Lua Object-Oriented Programming ------------------------ -------------------------------------------------------------------------------- -- Project: LOOP Class Library -- -- Release: 2.3 beta -- -- Title : Array Optimized for Insertion/Removal that Doesn't Garantee Order -- -- Author : Renato Maia <maia@inf.puc-rio.br> -- -------------------------------------------------------------------------------- local table = require "table" local oo = require "loop.base" module("loop.collection.UnorderedArray", oo.class) function add(self, value) self[#self + 1] = value end function remove(self, index) local size = #self if index == size then self[size] = nil elseif (index > 0) and (index < size) then self[index], self[size] = self[size], nil end end
mit
DEKHTIARJonathan/BilletterieUTC
badgingServer/Install/swigwin-3.0.7/Examples/lua/exception/runme.lua
2
2192
-- file: example.lua ---- importing ---- if string.sub(_VERSION,1,7)=='Lua 5.0' then -- lua5.0 doesnt have a nice way to do this lib=loadlib('example.dll','luaopen_example') or loadlib('example.so','luaopen_example') assert(lib)() else -- lua 5.1 does require('example') end -- throw a lot of exceptions: -- you must catch exceptions using pcall and then checking the result t = example.Test() print "calling t:unknown()" ok,res=pcall(function() t:unknown() end) if ok then print " that worked! Funny" else print(" call failed with error:",res) end print "calling t:simple()" ok,res=pcall(function() t:simple() end) if ok then print " that worked! Funny" else print(" call failed with error:",res) end print "calling t:message()" ok,res=pcall(function() t:message() end) if ok then print " that worked! Funny" else print(" call failed with error:",res) end print "calling t:hosed()" ok,res=pcall(function() t:hosed() end) if ok then print " that worked! Funny" else print(" call failed with error:",res.code,res.msg) end -- this is a rather strange way to perform the multiple catch of exceptions print "calling t:mutli()" for i=1,3 do ok,res=pcall(function() t:multi(i) end) if ok then print " that worked! Funny" else if swig_type(res)=="Exc *" then print(" call failed with Exc exception:",res.code,res.msg) else print(" call failed with error:",res) end end end -- this is a bit crazy, but it shows obtaining of the stacktrace function a() b() end function b() t:message() end print [[ Now let's call function a() which calls b() which calls into C++ which will throw an exception!]] ok,res=pcall(a) if ok then print " that worked! Funny" else print(" call failed with error:",res) end print "Now let's do the same using xpcall(a,debug.traceback)" ok,res=xpcall(a,debug.traceback) if ok then print " that worked! Funny" else print(" call failed with error:",res) end print "As you can see, the xpcall gives a nice stacktrace to work with" ok,res=pcall(a) print(ok,res) ok,res=xpcall(a,debug.traceback) print(ok,res)
apache-2.0
JarnoVgr/Mr.Green-MTA-Resources
resources/[web]/interchat/receive.lua
2
5259
---------------------------------------------- -- Receive.lua -- -- Respond to requests from other servers -- ---------------------------------------------- ----------------- -- F2 redirect -- ----------------- local joiningSerials = {} function playerRedirect ( serial, playtime, tick, hoursPlayed ) joiningSerials[serial] = {tick=getTickCount(), playtime=playtime} triggerEvent('onPlayerReplaceTime', root, serial, tick, hoursPlayed) return { serial = serial } end function onPlayerConnect(nick, ip, username, serial) if joiningSerials[serial] then if getTickCount() - joiningSerials[serial].tick <= 10 * 1000 then local player = getPlayerFromName(nick) setElementData(player, 'redirectedFrom', other_server) else for s, t in pairs(joiningSerials) do if getTickCount() - t.tick >= 10 * 1000 then joiningSerials[s] = nil end end end end end addEventHandler('onPlayerConnect', root, onPlayerConnect) function onPlayerJoin() local j = joiningSerials[getPlayerSerial(source)] if j then setElementData(source, 'playtime', j.playtime) joiningSerials[getPlayerSerial(source)] = nil end end addEventHandler('onPlayerJoin', root, onPlayerJoin) ------------------------- -- Chat, use the + prefix ------------------------- function playerChatBoxRemote ( name, message) local out = "[" .. other_server:upper() .. "] " .. tostring(name) .. "> " .. tostring(message) .. "" outputChatBox(out, root, 0xFF, 0xD7, 0x00) outputServerLog(out) exports.irc:outputIRC("08[" .. other_server:upper() .. "] " .. tostring(name) .. "> " .. tostring(message) .. "") triggerEvent('onInterchatMessage', resourceRoot, other_server:upper(), tostring(name), tostring(message)) return { name = name, message = message } end ------------- -- Players -- ------------- function sendPlayerNames ( player ) local players = getElementsByType('player') local names = {} if #players > 0 then for k,p in ipairs(players) do names[k] = removeColorCoding(getPlayerName(p)) end return player, tostring(#players), tostring(getMaxPlayers()), table.concat(names, ", ") else return player, '0', '' end end function removeColorCoding ( name ) return type(name)=='string' and string.gsub ( name, '#%x%x%x%x%x%x', '' ) or name end ------------ -- Admins -- ------------ function sendAdminNames ( serial ) local admins = {} local awayString = " (away)" for k, v in ipairs (getElementsByType("player")) do if hasObjectPermissionTo ( v, "general.adminpanel", false ) then local away = "" if exports.anti:isPlayerAFK(v) then away = awayString end admins[#admins+1] = getPlayerName(v) : gsub ( '#%x%x%x%x%x%x', '' ) ..away end end local moderators = {} for k, v in ipairs (getElementsByType("player")) do if hasObjectPermissionTo ( v, "command.k", false ) and not hasObjectPermissionTo ( v, "general.adminpanel", false ) then local away = "" if exports.anti:isPlayerAFK(v) then away = awayString end moderators[#moderators+1] = getPlayerName(v) : gsub ( '#%x%x%x%x%x%x', '' ) .. away end end return serial, table.concat ( admins, ', ' ), table.concat ( moderators, ', ' ) end -------------- -- Map info -- -------------- function sendMapInfo ( name, author, gmname, outputMap, returnMapInfo ) if outputMap then outputChatBox("[" .. other_server:upper() .. "] Map started: '" .. name .. "' / Gamemode: "..gmname, root, 0xFF, 0xD7, 0x00) end triggerClientEvent("updateF2GUI", resourceRoot, other_server.." Map", "Map: "..name.."\nAuthor: "..author) if returnMapInfo then outputDebugString("returnMapInfo", 3) if not mapInfo then local s = getElementData( getResourceRootElement( getResourceFromName("race") ) , "info") if s then mapInfo = s.mapInfo else mapInfo = {} end end return mapInfo end end --------------- -- GC logins -- --------------- function greencoinsLogin ( forumID ) triggerEvent ( 'onOtherServerGCLogin', resourceRoot, forumID ) end addEvent('onOtherServerGCLogin') ------------------ -- Mutes & bans -- ------------------ function aAddSerialUnmuteTimer ( serial, length ) exports.admin:aAddSerialUnmuteTimer(serial, tonumber(length)) return 'ok' end function addSyncBan ( ip, serial, reason, seconds ) addBan ( ip or nil, nil, serial or nil, root, tostring(reason or '') .. ' sync_banned', tonumber(seconds) and tonumber(seconds) > 0 and (tonumber(seconds) - getRealTime().timestamp) or 0) end ---------------------- -- Unbans -- ---------------------- function removeSyncBan ( admin, ip, serial ) if ip then for _, ban in ipairs( getBans() ) do if getBanIP(ban) == ip then removeBan ( ban, admin ) end end elseif serial then for _, ban in ipairs( getBans() ) do if getBanSerial(ban) == string.upper(serial) then removeBan ( ban, admin ) end end end end ------------- -- Testing -- ------------- function testConnection() outputDebugString'Interchat: other server connecting' return 'connection ok' end ----------------------- -- Online players F2 -- ----------------------- function sendOnlinePlayers() local players = #getElementsByType('player') return { players = players, maxPlayers = getMaxPlayers() } end
mit
youssef-emad/shogun
tests/integration/lua_modular/generator.lua
21
1204
package.path = package.path .. ";../../../src/interfaces/lua_modular/?.lua;" package.cpath = package.cpath .. ";../../../src/interfaces/lua_modular/?.so;/usr/local/lib/?.so" require("lfs") example_dir = '../../examples/undocumented/lua_modular' test_dir = '../../../testsuite/tests' blacklist = {"load.lua", "MatrixTest.lua", "VectorTest.lua"} function get_test_mod(tests) lfs.chdir(example_dir) local r = {} for _, v in pairs(tests) do local flag = 0 if string.sub(v, -3) ~= "lua" then flag = 1 end for _, n in pairs(blacklist) do if n == v then flag = 1 break end end if flag == 0 then mod = string.sub(v, 1, string.len(v)-4) table.insert(r, mod) end end return r end function setup_tests(tests) if not tests then local files={} for i in io.popen("ls " .. example_dir):lines() do table.insert(files, i) end table.sort(files) return files else return tests end end function generator(tests) r = get_test_mod(tests) for _, t in pairs(r) do require(t) for i = 1, #parameter_list do f = loadstring("a=" .. t .. "(unpack(parameter_list[" .. i .. "]))") f() print("OK") end end end tests = setup_tests(...) generator(tests)
gpl-3.0
neftalimich/YGOPro_AI_Fluffal
ai/decks/Fluffal/FluffalBattle.lua
1
13237
------------------------ -------- BATTLE -------- ------------------------ FluffalAtt={ 39246582, -- Fluffal Dog 13241004, -- Fluffal Penguin 73240432, -- Edge Imp Cotton Eater 97567736, -- Edge Imp Tomahawk 91034681, -- Frightfur Daredevil 80889750, -- Frightfur Sabre-Tooth 40636712, -- Frightfur Kraken 10383554, -- Frightfur Leo 85545073, -- Frightfur Bear 11039171, -- Frightfur Wolf 00464362, -- Frightfur Tiger 57477163, -- Frightfur Sheep 41209827, -- Starve Venom Fusion Dragon 42110604, -- Hi-Speedroid Chanbara 83531441, -- Dante } FluffalDef={ 98280324, -- Fluffal Sheep 87246309, -- Fluffal Octopus 02729285, -- Fluffal Cat 38124994, -- Fluffal Rabit 06142488, -- Fluffal Mouse 72413000, -- Fluffal Wings 81481818, -- Fluffal Patchwork 79109599, -- King of the Swamp 06205579, -- Parasite Fusioner 67441435, -- Glow-Up Bulb } function FluffalPosition(id,available) -- FLUFFAL POSITION result = nil if AIGetStrongestAttack() < OppGetStrongestAttack() and CardsMatchingFilter(OppMon(),FluffalDisvantageFilter) > 0 and id ~= 41209827 -- FStarve then return POS_FACEUP_DEFENSE end for i=1,#FluffalAtt do if FluffalAtt[i]==id then result = POS_FACEUP_ATTACK end end for i=1,#FluffalDef do if FluffalDef[i]==id then result = 4 -- POS_FACEUP_DEFENSE? end end if id == 57477163 and GlobalIFusion == 2 then -- FSheep by IFusion return 4 -- POS_FACEUP_DEFENSE? end if id == 57477163 then -- FSheep --print("FSheep") local frightfurAtk = 2000 + FrightfurBoost(id) if GlobalFSheep == 1 then frightfurAtk = frightfurAtk + 800 end print("FSheep - Atk: "..frightfurAtk) if FluffalCanAttack(OppMon(),frightfurAtk) == 0 and FluffalCannotAttack(OppMon(),frightfurAtk,FilterPosition,POS_FACEUP_ATTACK) > 0 and frightfurAtk < 3200 then result = 4 -- POS_FACEUP_DEFENSE? else result = 1 -- POS_FACEUP_ATTACK end end if id == 40636712 then -- FKraken local frightfurAtk = 2200 + FrightfurBoost(40636712) print("FKraken Atk: "..frightfurAtk) if frightfurAtk < 3000 and #OppMon() == 1 and CardsMatchingFilter(OppMon(),FKrakenSendFilter) > 0 and AIGetStrongestAttack() <= OppGetStrongestAttDef() and frightfurAtk <= OppGetStrongestAttDef() or #OppMon() > 1 and FluffalCanAttack(OppMon(),frightfurAtk) == 0 or not BattlePhaseCheck() and frightfurAtk < 3000 or CardsMatchingFilter(OppMon(),FKrakenSendFilter) == 0 and frightfurAtk <= OppGetStrongestAttDef() then result = 4 -- POS_FACEUP_DEFENSE? end end if (not BattlePhaseCheck() or AI.GetCurrentPhase() == PHASE_MAIN2) and ( id == 65331686 -- Owl or id == 61173621 -- Chain or id == 30068120 -- Sabres or id == 40636712 -- FKraken or id == 83531441 -- Dante ) then result = 4 -- POS_FACEUP_DEFENSE? end if id == 03113836 -- GKSeraphinite and GlobalEffectId == 07394770 -- BFusion then result = 4 end return result end function FluffalBattleCommand(cards,activatable) -- FLUFFAL BATTLE COMMAND ApplyATKBoosts(cards) for i=1,#cards do cards[i].index = i end local targets = OppMon() local attackable = {} local mustattack = {} for i=1,#targets do if targets[i]:is_affected_by(EFFECT_CANNOT_BE_BATTLE_TARGET)==0 then attackable[#attackable+1]=targets[i] end if targets[i]:is_affected_by(EFFECT_MUST_BE_ATTACKED)>0 then mustattack[#mustattack+1]=targets[i] end end if #mustattack>0 then targets = mustattack else targets = attackable end ApplyATKBoosts(targets) -- Frightfur Attack if HasIDNotNegated(cards,57477163) -- FSheep and CardsMatchingFilter(OppST(),FilterPosition,POS_FACEDOWN) > 0 and ( CanWinBattle(cards[CurrentIndex],targets,false,false) or #targets == 0 ) then return Attack(IndexByID(cards,57477163)) end if HasIDNotNegated(cards,85545073) -- FBear and CanWinBattle(cards[CurrentIndex],targets,true,false) then return Attack(IndexByID(cards,85545073)) end if HasIDNotNegated(cards,10383554) -- FLeo and CanWinBattle(cards[CurrentIndex],targets,false,false) then return Attack(IndexByID(cards,10383554)) end if HasIDNotNegated(cards,40636712) -- FKraken and CanWinBattle(cards[CurrentIndex],targets,false,false) and cards[CurrentIndex]:is_affected_by(EFFECT_CANNOT_DIRECT_ATTACK) > 0 then return Attack(IndexByID(cards,40636712)) end if HasIDNotNegated(cards,57477163) -- FSheep and ( CanWinBattle(cards[CurrentIndex],targets,false,false) or #targets == 0 ) then return Attack(IndexByID(cards,57477163)) end if HasIDNotNegated(cards,91034681) -- FDaredevil and CanWinBattle(cards[CurrentIndex],targets,false,false) and CardsMatchingFilter(targets,FilterPosition,POS_DEFENSE) == #targets then return Attack(IndexByID(cards,91034681)) end if HasIDNotNegated(cards,80889750) -- FSabreTooth and CanWinBattle(cards[CurrentIndex],targets,false,false) and CardsMatchingFilter(targets,FilterPosition,POS_ATTACK) == #targets then return Attack(IndexByID(cards,80889750)) end return nil end function FluffalAttackTarget(cards,attacker) -- FLUFFAL ATTACK TARGET local id = attacker.id local result ={attacker} --print("1",attacker.id,attacker.attack,attacker.bonus) result = {} local atk = attacker.attack if NotNegated(attacker) then -- Frightfur Sheep if id == 57477163 and CanWinBattle(attacker,cards,true,false) then return FrighfurAttackTarget(cards,attacker,false) end end return nil end function FluffalAttackBoost(cards) -- FLUFFAL BOOST for i=1,#cards do local c = cards[i] if c.id == 42110604 then -- Chanbara c.attack = c.attack + 200 end if c.id == 57477163 then -- FSheep local boost = FrightfurBoost(0,0) if c.attack - boost == c.base_attack and OPTCheck(57477163) and AI.GetPlayerLP(1) > 800 and CardsMatchingFilter(OppMon(),FilterPosition,POS_FACEUP_ATTACK) > 0 then c.bonus = 800 c.attack = c.attack + 800 end end end end -- ATTACK FUNCTIONS function FrighfurAttackTarget(cards,source,ignorebonus,filter,opt) local atk = source.attack local bonus = 0 --print("3",source.id,source.attack,source.bonus) if source.bonus and source.bonus > 0 then bonus = source.bonus end if ignorebonus then atk = math.max(0,atk - bonus) end local result = nil for i=1,#cards do local c = cards[i] c.index = i c.prio = 0 if FilterPosition(c,POS_FACEUP_ATTACK) then if c.attack<atk or (CrashCheck(source) and c.attack==atk and AIGetStrongestAttack()<=c.attack) then if atk-bonus<=c.attack and CanWinBattle(source,cards,nil,true) and AIGetStrongestAttack(true)>c.attack then c.prio = 1 else c.prio = c.attack end else c.prio = c.attack * -1 end -- FSheep own boost if source.id == 57477163 and OPTCheck(57477163) then if c.attack >= atk-bonus and c.attack <= atk then c.prio = c.attack * 9999 - (atk-c.attack) end end end if FilterPosition(c,POS_DEFENSE) then -- FSheep own boost if source.id == 57477163 and bonus == 800 then if FilterPublic(c) then if c.defense<(atk-bonus) then c.prio = math.max(c.defense - 1,c.attack) else c.prio = (atk-bonus) - c.defense end end else if FilterPublic(c) then if c.defense<atk then c.prio = math.max(c.defense - 1,c.attack) else c.prio = atk - c.defense end end end end if filter and (opt and not filter(c,opt) or opt==nil and not filter(c)) then c.prio = (c.prio or 0)-99999 end if c.prio and c.prio>0 and not BattleTargetCheck(c,source) then c.prio = -4 end if not AttackBlacklistCheck(c,source) then c.prio = (c.prio or 0)-99999 end if CanFinishGame(source,c) then c.prio=99999 end if FilterPosition(c,POS_DEFENSE) and FilterPrivate(c) then if atk>=1500 then c.prio = -1 else c.prio = -2 end end if c.prio and c.prio>0 and FilterPublic(c) then if FilterType(c,TYPE_SYNCHRO+TYPE_RITUAL+TYPE_XYZ+TYPE_FUSION) then c.prio = c.prio + 1 end if FilterType(c,TYPE_EFFECT) then c.prio = c.prio + 1 end if c.level>4 then c.prio = c.prio + 1 end end if CurrentOwner(c)==1 then c.prio = -1*c.prio end end table.sort(cards,function(a,b) return a.prio > b.prio end) --print("table:") --print("attacker: "..source.id..", atk: "..atk) --for i=1,#cards do --print(i..") id: "..cards[i].id.." index: "..cards[i].index.." prio: "..cards[i].prio) --end result={cards[1].index} return result end function FrightfurBoost(frightfurId,extra) if extra == nil then extra = 1 end local boost = 0 local frightfurs = CountFrightfurMon(AIMon()) + extra -- Own local fluffals = CountFluffal(AIMon()) if frightfurId == 80889750 -- FSabreTooth then if CountFrightfurMon(AIGrave()) > 0 then frightfurs = frightfurs + 1 if not HasIDNotNegated(AIMon(),00464362,true) -- FTiger Field and HasIDNotNegated(AIGrave(),00464362,true) -- FTiger Grave then boost = boost + (frightfurs * 300) end end boost = boost + 400 end if frightfurId == 00464362 -- FTiger then boost = boost + (frightfurs * 300) end if frightfurId == 57477163 -- FSheep and CardsMatchingFilter(OppMon(),FilterPosition,POS_ATTACK) > 0 and OPTCheck(57477163) and AI.GetPlayerLP(1) > 800 then boost = boost + 800 end boost = boost + (400 * CardsMatchingFilter(AIMon(),FSabreToothFilter)) --FSabreTooth if HasIDNotNegated(AIMon(),00464362,true) -- FTiger then boost = boost + ((frightfurs + fluffals)* 300) end return boost end function FluffalCanAttack(cards,attack,filter,opt) local result = 0 for i=1, #cards do local c = cards[i] if ( FilterAttackMax(c,attack-1) and FilterPosition(c,POS_ATTACK) or FilterDefenseMax(c,attack-1) and FilterPosition(c,POS_DEFENSE) ) and FilterCheck(c,filter,opt) then result = result + 1 end end return result end function FluffalCannotAttack(cards,attack,filter,opt) local result = 0 for i=1, #cards do local c = cards[i] if ( FilterAttackMin(c,attack) and FilterPosition(c,POS_ATTACK) or FilterDefenseMin(c,attack) and FilterPosition(c,POS_DEFENSE) ) and FilterCheck(c,filter,opt) then result = result + 1 end end return result end function ExpectedDamageMichelet(player,filter,opt) if player == nil then player = 1 end local oppMons = {} local aiAtts = {} local aiHasAttacked = 0 aiAtts = SubGroup(AIMon(),FilterPosition,POS_ATTACK) oppMons = SubGroup(OppMon(),FilterLocation,LOCATION_MZONE) if player == 2 then aiAtts = SubGroup(OppMon(),FilterPosition,POS_ATTACK) oppMons = SubGroup(AIMon(),FilterLocation,LOCATION_MZONE) end if #aiAtts > 0 then table.sort(aiAtts, function(a,b) return a.attack < b.attack end) end if #oppMons > 0 then table.sort(oppMons, function(a,b) local attDefA = 0 local attDefB = 0 if FilterPosition(a,POS_ATTACK) then attDefA = a.attack else attDefA = a.defense end if FilterPosition(b,POS_ATTACK) then attDefB = b.attack else attDefB = b.defense end return attDefA > attDefB end ) end local damageExpectedInBattle = 0 for i=1, #oppMons do local oppM = oppMons[i] local oppAttDef = oppM.defense local dealDamage = false if FilterPosition(oppM,POS_ATTACK) then dealDamage = true oppAttDef = oppM.attack end --print("oppMon - id: "..oppM.id.." - AttDef: "..oppAttDef) for j=1, #aiAtts do local aiM = aiAtts[j] local aiAtt = aiM.attack if FilterCheck(aiM,filter,opt) then if not oppM.HasBeenDefeated and not aiM.HasAttacked and AvailableAttacks(aiM) > 0 then --print("aiAtt: "..aiAtt.." vs oppAttDef: "..oppAttDef) if aiAtt > oppAttDef then aiM.HasAttacked = true oppM.HasBeenDefeated = true aiHasAttacked = aiHasAttacked + 1 if dealDamage then damageExpectedInBattle = damageExpectedInBattle + (aiAtt - oppAttDef) end end end end end if not oppM.HasBeenDefeated then damageExpectedInBattle = damageExpectedInBattle - oppAttDef end end --print("DamageExpected - In Battle: ".. damageExpectedInBattle) local damageExpectedDirect = 0 if aiHasAttacked >= #oppMons or #oppMons == 0 then for j=1, #aiAtts do local aiM = aiAtts[j] local aiAtt = aiM.attack --print("aiMon - id: "..aiM.id.." - Att: "..aiAtt) if FilterCheck(aiM,filter,opt) then if not aiM.HasAttacked and not FilterAffected(aiM,EFFECT_CANNOT_DIRECT_ATTACK) then --print("DirectDamage: "..(aiAtt * AvailableAttacks(aiM))) damageExpectedDirect = damageExpectedDirect + (aiAtt * AvailableAttacks(aiM)) end end end end --print("DamageExpected - Direct: ".. damageExpectedDirect) return damageExpectedInBattle + damageExpectedDirect end
mit
mobarski/sandbox
scite/old/wscite_zzz/lexers/notused/forth.lua
3
1829
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE. -- Forth LPeg lexer. local l = require('lexer') local token, word_match = l.token, l.word_match local P, R, S = lpeg.P, lpeg.R, lpeg.S local M = {_NAME = 'forth'} -- Whitespace. local ws = token(l.WHITESPACE, l.space^1) -- Comments. local line_comment = S('|\\') * l.nonnewline^0 local block_comment = '(*' * (l.any - '*)')^0 * P('*)')^-1 local comment = token(l.COMMENT, line_comment + block_comment) -- Strings. local s_str = 's' * l.delimited_range('"', true, true) local dot_str = '.' * l.delimited_range('"', true, true) local f_str = 'f' * l.delimited_range('"', true, true) local dq_str = l.delimited_range('"', true, true) local string = token(l.STRING, s_str + dot_str + f_str + dq_str) -- Numbers. local number = token(l.NUMBER, P('-')^-1 * l.digit^1 * (S('./') * l.digit^1)^-1) -- Keywords. local keyword = token(l.KEYWORD, word_match({ 'swap', 'drop', 'dup', 'nip', 'over', 'rot', '-rot', '2dup', '2drop', '2over', '2swap', '>r', 'r>', 'and', 'or', 'xor', '>>', '<<', 'not', 'negate', 'mod', '/mod', '1+', '1-', 'base', 'hex', 'decimal', 'binary', 'octal', '@', '!', 'c@', 'c!', '+!', 'cell+', 'cells', 'char+', 'chars', 'create', 'does>', 'variable', 'variable,', 'literal', 'last', '1,', '2,', '3,', ',', 'here', 'allot', 'parse', 'find', 'compile', -- Operators. 'if', '=if', '<if', '>if', '<>if', 'then', 'repeat', 'until', 'forth', 'macro' }, '2><1-@!+3,=')) -- Identifiers. local identifier = token(l.IDENTIFIER, (l.alnum + S('+-*=<>.?/\'%,_$'))^1) -- Operators. local operator = token(l.OPERATOR, S(':;<>+*-/()[]')) M._rules = { {'whitespace', ws}, {'keyword', keyword}, {'string', string}, {'identifier', identifier}, {'comment', comment}, {'number', number}, {'operator', operator}, } return M
mit
neale/CS-program
325-Algorithms/project3/lin-regression.lua
1
2133
-- LinearRegression.lua -- define class LinearRegression -- torch libraries require 'nn' require 'optim' -- local libraries require 'Trainer' require 'Validations' do local LinearRegression = torch.class('LinearRegression') function LinearRegression:__init(inputs, targets, numDimensions) -- validate parameters Validations.isTable(self, 'self') Validations.isNotNil(inputs, 'inputs') Validations.isNotNil(targets, 'targets') Validations.isIntegerGt0(numDimensions, 'numDimensions') -- save data for type validations self.inputs = inputs self.targets = targets -- define model self.model = nn.Sequential() local numOutputs = 1 self.model:add(nn.Linear(numDimensions, numOutputs)) -- define loss function self.criterion = nn.MSECriterion() -- initialize a trainer object self.trainer = Trainer(inputs, targets, self.model, self.criterion) end function LinearRegression:estimate(query) -- validate parameters Validations.isTable(self, 'self') Validations.isNotNil(query, 'query') return self.trainer:estimate(query) end function LinearRegression:getCriterion() Validations.isTable(self, 'self') return self.trainer:getCriterion() end function LinearRegression:getModel() Validations.isTable(self, 'self') return self.trainer:getModel() end function LinearRegression:train(nextBatch, opt) -- validate parameters Validations.isTable(self, 'self') Validations.isFunction(nextBatch, 'nextBatch') assert(opt, 'opt not supplied') -- more validation is done in Trainer -- validate that an input is a Tensor and a target is a Tensor local indices = nextBatch(self.inputs, nil) for k, index in pairs(indices) do Validations.isTensor(self.inputs[index], '1st input') Validations.isTensor(self.targets[index], '1st target') break end self.trainer:train(nextBatch, opt) end end -- class LinearRegression
unlicense
hussian1997/bot_Iraq1997
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-2.0
speedduck/Minetest-obsidian-tools
init.lua
1
2365
minetest.register_tool("obsidiantools:sword_obsidian", { description = "Obsidian Sword", inventory_image = "obsidiantools_sword_obsidian.png", tool_capabilities = { full_punch_interval = 0.8, max_drop_level=1, groupcaps={ snappy={times={[1]=2.2, [2]=1.1, [3]=0.35}, uses=40, maxlevel=2} }, damage_groups = {fleshy=7}, } }) minetest.register_tool("obsidiantools:pick_obsidian", { description = "Obsidian Pick", inventory_image = "obsidiantools_pick_obsidian.png", tool_capabilities = { full_punch_interval = 0.8, max_drop_level=1, groupcaps={ cracky = {times={[1]=2.2, [2]=1.1, [3]=0.55}, uses=25, maxlevel=3}, }, damage_groups = {fleshy=2}, } }) minetest.register_craft({ output = 'obsidiantools:sword_obsidian', recipe = { {'sean:obsidian_alloy'}, {'sean:obsidian_alloy'}, {'default:stick'}, } }) minetest.register_craft({ output = 'obsidiantools:pick_obsidian', recipe = { {'sean:obsidian_alloy', 'sean:obsidian_alloy', 'sean:obsidian_alloy'}, {'', 'default:stick', ''}, {'', 'default:stick', ''}, } }) minetest.register_craftitem("obsidiantools:obsidian_alloy", { description = "Obisidian Alloy", inventory_image = "obsidian_alloy.png", -- on_drop = function(itemstack, dropper, pos) -- Prints a random number and removes one item from the stack -- minetest.chat_send_all(math.random()) -- itemstack:take_item() -- return itemstack -- end, }) minetest.register_craft({ output = 'obsidiantools:obsidian_alloy', recipe = { {'default:obsidian','default:bronze_ingot','default:gold_ingot'}, {'default:obsidian','default:bronze_ingot','default:gold_ingot'}, } }) minetest.register_node("obsidiantools:obsidianalloyblock", { description = "Obsidian Alloy Block", tiles = {"obsidiantools_obsidian_alloy_block.png"}, is_ground_content = true, groups = {cracky=1,level=2} }) minetest.register_craft({ output = 'obsidiantools:obsidianalloyblock', recipe = { {'obsidiantools:obsidian_alloy', 'obsidiantools:obsidian_alloy', 'obsidiantools:obsidian_alloy'}, {'obsidiantools:obsidian_alloy', 'obsidiantools:obsidian_alloy', 'obsidiantools:obsidian_alloy'}, {'obsidiantools:obsidian_alloy', 'obsidiantools:obsidian_alloy', 'obsidiantools:obsidian_alloy'}, } }) minetest.register_craft({ output = 'obsidiantools:obsidian_alloy 9', recipe = { {'obsidiantools:obsidianalloyblock'}, } })
gpl-3.0
darkdukey/sdkbox-facebook-sample-v2
samples/Lua/TestLua/Resources/luaScript/TouchesTest/Paddle.lua
4
1493
require "extern" require "luaScript/VisibleRect" Paddle = class("Paddle", function(texture) return CCSprite:createWithTexture(texture) end) Paddle.__index = Paddle local kPaddleStateGrabbed = 0 local kPaddleStateUngrabbed = 1 Paddle.m_state = kPaddleStateGrabbed function Paddle:rect() local s = self:getTexture():getContentSize() return CCRectMake(-s.width / 2, -s.height / 2, s.width, s.height) end function Paddle:containsTouchLocation(x,y) local position = ccp(self:getPosition()) local s = self:getTexture():getContentSize() local touchRect = CCRectMake(-s.width / 2 + position.x, -s.height / 2 + position.y, s.width, s.height) local b = touchRect:containsPoint(ccp(x,y)) return b end function Paddle:ccTouchBegan(x, y) if (self.m_state ~= kPaddleStateUngrabbed) then return false end self.m_state = kPaddleStateGrabbed; return true; end function Paddle:ccTouchMoved(x, y) self:setPosition( ccp(x,y) ); end function Paddle:ccTouchEnded(x, y) self.m_state = kPaddleStateUngrabbed; end function Paddle:onTouch(eventType, x, y) if eventType == "began" then return self:ccTouchBegan(x,y) elseif eventType == "moved" then return self:ccTouchMoved(x,y) elseif eventType == "ended" then return self:ccTouchEnded(x, y) end end function Paddle:paddleWithTexture(aTexture) local pPaddle = Paddle.new(aTexture); self.m_state = kPaddleStateUngrabbed; return pPaddle; end
mit
youssef-emad/shogun
examples/undocumented/lua_modular/kernel_comm_ulong_string_modular.lua
21
1367
require 'modshogun' require 'load' traindat = load_dna('../data/fm_train_dna.dat') testdat = load_dna('../data/fm_test_dna.dat') parameter_list = {{traindat,testdat,3,0,false},{traindat,testdat,4,0,false}} function kernel_comm_ulong_string_modular (fm_train_dna,fm_test_dna, order, gap, reverse) --charfeat=modshogun.StringCharFeatures(modshogun.DNA) --charfeat:set_features(fm_train_dna) --feats_train=modshogun.StringUlongFeatures(charfeat:get_alphabet()) --feats_train:obtain_from_char(charfeat, order-1, order, gap, reverse) --preproc=modshogun.SortUlongString() --preproc:init(feats_train) --feats_train:add_preprocessor(preproc) --feats_train:apply_preprocessor() --charfeat=modshogun.StringCharFeatures(modshogun.DNA) --charfeat:set_features(fm_test_dna) --feats_test=modshogun.StringUlongFeatures(charfeat:get_alphabet()) --feats_test:obtain_from_char(charfeat, order-1, order, gap, reverse) --feats_test:add_preprocessor(preproc) --feats_test:apply_preprocessor() --use_sign=false --kernel=modshogun.CommUlongStringKernel(feats_train, feats_train, use_sign) --km_train=kernel:get_kernel_matrix() --kernel:init(feats_train, feats_test) --km_test=kernel:get_kernel_matrix() --return km_train,km_test,kernel end if debug.getinfo(3) == nill then print 'CommUlongString' kernel_comm_ulong_string_modular(unpack(parameter_list[1])) end
gpl-3.0
hussian1997/bot_Iraq1997
plugins/filter.lua
8
3262
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY(@AHMED_ALOBIDE) ▀▄ ▄▀ ▀▄ ▄▀ BY(@hussian_9) ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function addword(msg, name) local hash = 'chat:'..msg.to.id..':badword' redis:hset(hash, name, 'newword') return "تم منع هذه الكلمة في المجموعة 📌📫\n>"..name end local function get_variables_hash(msg) return 'chat:'..msg.to.id..':badword' end local function list_variablesbad(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = 'قائمة الكلمات المحظورة 🚫🌀 :\n\n' for i=1, #names do text = text..'> '..names[i]..'\n' end return text else return end end function clear_commandbad(msg, var_name) --Save on redis local hash = get_variables_hash(msg) redis:del(hash, var_name) return 'تم مسح الكلمات الممنوعة 🏌⛳️' end local function list_variables2(msg, value) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do if string.match(value, names[i]) and not is_momod(msg) then if msg.to.type == 'channel' then delete_msg(msg.id,ok_cb,false) else kick_user(msg.from.id, msg.to.id) end return end --text = text..names[i]..'\n' end end end local function get_valuebad(msg, var_name) local hash = get_variables_hash(msg) if hash then local value = redis:hget(hash, var_name) if not value then return else return value end end end function clear_commandsbad(msg, cmd_name) --Save on redis local hash = get_variables_hash(msg) redis:hdel(hash, cmd_name) return ''..cmd_name..' تم السماح بالكلمة 🦁🎋' end local function run(msg, matches) if matches[2] == 'block' then if not is_momod(msg) then return 'للمدراء والادمنية فقط Ⓜ️💡' end local name = string.sub(matches[3], 1, 50) local text = addword(msg, name) return text end if matches[2] == 'blocks word' then return list_variablesbad(msg) elseif matches[2] == 'clean' then if not is_momod(msg) then return 'Only Owners :))' end local asd = '1' return clear_commandbad(msg, asd) elseif matches[2] == 'unblock' or matches[2] == 'rw' then if not is_momod(msg) then return 'Only Owners :))' end return clear_commandsbad(msg, matches[3]) else local name = user_print_name(msg.from) return list_variables2(msg, matches[1]) end end return { patterns = { "^([!/#])(rw) (.*)$", "^([!/#])(block) (.*)$", "^([!/#])(unblock) (.*)$", "^([!/#])(blocks word)$", "^([!/#])(clean) blocks word$", "^(.+)$", }, run = run }
gpl-2.0
romanchyla/nodemcu-firmware
lua_modules/lm92/lm92.lua
19
5241
-- ****************************************************** -- LM92 module for ESP8266 with nodeMCU -- -- Written by Levente Tamas <levente.tamas@navicron.com> -- -- modify by Garberoglio Leonardo <leogarberoglio@gmail.com> -- -- GNU LGPL, see https://www.gnu.org/copyleft/lesser.html -- ****************************************************** -- Module Bits local moduleName = ... local M = {} _G[moduleName] = M -- Default ID local id = 0 -- Local vars local address = 0 -- read regs for len number of bytes -- return table with data local function read_reg(reg_addr, len) local ret={} local c local x i2c.start(id) i2c.address(id, address ,i2c.TRANSMITTER) i2c.write(id,reg_addr) i2c.stop(id) i2c.start(id) i2c.address(id, address,i2c.RECEIVER) c=i2c.read(id,len) for x=1,len,1 do tc=string.byte(c,x) table.insert(ret,tc) end i2c.stop(id) return ret end --write reg with data table local function write_reg(reg_addr, data) i2c.start(id) i2c.address(id, address, i2c.TRANSMITTER) i2c.write(id, reg_addr) i2c.write(id, data) i2c.stop(id) end --write comparison reg with 2 bytes local function write_comp_reg(reg_addr, msb, lsb) i2c.start(id) i2c.address(id, address, i2c.TRANSMITTER) i2c.write(id, reg_addr) i2c.write(id, msb) i2c.write(id, lsb) i2c.stop(id) end -- initialize i2c -- d: sda -- c: scl -- a: i2c addr 0x48|A1<<1|A0 (A0-A1: chip pins) function M.init(d,c,a) if (d ~= nil) and (c ~= nil) and (d >= 0) and (d <= 11) and (c >= 0) and ( c <= 11) and (d ~= l) and (a ~= nil) and (a >= 0x48) and (a <= 0x4b ) then sda = d scl = c address = a i2c.start(id) res = i2c.address(id, address, i2c.TRANSMITTER) --verify that the address is valid i2c.stop(id) if (res == false) then print("device not found") return nil end else print("i2c configuration failed") return nil end i2c.setup(id,sda,scl,i2c.SLOW) end -- Return the temperature data function M.getTemperature() local temperature local tmp=read_reg(0x00,2) --read 2 bytes from the temperature register temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits if (temperature>=0x1000) then temperature= temperature-0x2000 --convert the two's complement end return temperature * 0.0625 end -- Put the LM92 into shutdown mode function M.shutdown() write_reg(0x01,0x01) end -- Bring the LM92 out of shutdown mode function M.wakeup() write_reg(0x01,0x00) end -- Write the LM92 Thyst SET POINT function M.setThyst(data_wr) local tmp = data_wr / 0.0625 if (tmp>=0x1000) then tmp= tmp-0x2000 --convert the two's complement end tmp = bit.lshift(tmp,3) local lsb = bit.band(tmp, 0x00FF) tmp = bit.rshift(bit.band(tmp, 0xFF00),8) write_comp_reg(0x02,tmp, lsb) end -- Write the LM92 T_crit SET POINT function M.setTcrit(data_wr) local tmp = data_wr / 0.0625 if (tmp>=0x1000) then tmp= tmp-0x2000 --convert the two's complement end tmp = bit.lshift(tmp,3) local lsb = bit.band(tmp, 0x00FF) tmp = bit.rshift(bit.band(tmp, 0xFF00),8) write_comp_reg(0x03,tmp, lsb) end -- Write the LM92 Tlow SET POINT function M.setTlow(data_wr) local tmp = data_wr / 0.0625 if (tmp>=0x1000) then tmp= tmp-0x2000 --convert the two's complement end tmp = bit.lshift(tmp,3) local lsb = bit.band(tmp, 0x00FF) tmp = bit.rshift(bit.band(tmp, 0xFF00),8) write_comp_reg(0x04,tmp, lsb) end -- Write the LM92 T_high SET POINT function M.setThigh(data_wr) local tmp = data_wr / 0.0625 if (tmp>=0x1000) then tmp= tmp-0x2000 --convert the two's complement end tmp = bit.lshift(tmp,3) local lsb = bit.band(tmp, 0x00FF) tmp = bit.rshift(bit.band(tmp, 0xFF00),8) write_comp_reg(0x05,tmp, lsb) end -- Read the LM92 Thyst SET POINT function M.getThyst() local temperature local tmp=read_reg(0x02,2) --read 2 bytes from the Hysteresis register temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits if (temperature>=0x1000) then temperature= temperature-0x2000 --convert the two's complement end return temperature * 0.0625 end -- Read the LM92 T_crit SET POINT function M.getTcrit() local temperature local tmp=read_reg(0x03,2) --read 2 bytes from the T Critical register temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits if (temperature>=0x1000) then temperature= temperature-0x2000 --convert the two's complement end return temperature * 0.0625 end -- Read the LM92 Tlow SET POINT function M.getTlow() local temperature local tmp=read_reg(0x04,2) --read 2 bytes from the T Low register temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits if (temperature>=0x1000) then temperature= temperature-0x2000 --convert the two's complement end return temperature * 0.0625 end -- Read the LM92 T_high SET POINT function M.getThigh() local temperature local tmp=read_reg(0x05,2) --read 2 bytes from the T High register temperature=bit.rshift(tmp[1]*256+tmp[2],3) --lower 3 bits are status bits if (temperature>=0x1000) then temperature= temperature-0x2000 --convert the two's complement end return temperature * 0.0625 end return M
mit
lizh06/premake-core
tests/actions/make/cs/test_response.lua
7
1976
-- -- tests/actions/make/cs/test_response.lua -- Validate the list of objects for a response file used by a makefile. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- local suite = test.declare("make_cs_response") local make = premake.make -- -- Setup -- local wks, prj function suite.setup() premake.action.set("vs2010") wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks, 1) end -- -- Create a project with a lot of files to force the generation of response files. -- This makes sure they can be processed in Windows since else we reach the command -- line length max limit. -- function suite.listResponse() prepare() make.csResponseFile(prj) test.capture [[ RESPONSE += $(OBJDIR)/MyProject.rsp ]] end function suite.listResponseTargets() prepare() make.csTargetRules(prj) test.capture [[ $(TARGET): $(SOURCES) $(EMBEDFILES) $(DEPENDS) $(RESPONSE) $(SILENT) $(CSC) /nologo /out:$@ $(FLAGS) $(REFERENCES) @$(RESPONSE) $(patsubst %,/resource:%,$(EMBEDFILES)) ]] end function suite.listResponseRules() files { "foo.cs", "bar.cs", "dir/foo.cs" } prepare() make.csResponseRules(prj) end function suite.listResponseRulesPosix() _OS = "linux" suite.listResponseRules() test.capture [[ $(RESPONSE): MyProject.make @echo Generating response file ifeq (posix,$(SHELLTYPE)) $(SILENT) rm -f $(RESPONSE) else $(SILENT) if exist $(RESPONSE) del $(OBJDIR)\MyProject.rsp endif @echo bar.cs >> $(RESPONSE) @echo dir/foo.cs >> $(RESPONSE) @echo foo.cs >> $(RESPONSE) ]] end function suite.listResponseRulesWindows() _OS = "windows" suite.listResponseRules() test.capture [[ $(RESPONSE): MyProject.make @echo Generating response file ifeq (posix,$(SHELLTYPE)) $(SILENT) rm -f $(RESPONSE) else $(SILENT) if exist $(RESPONSE) del $(OBJDIR)\MyProject.rsp endif @echo bar.cs >> $(RESPONSE) @echo dir\foo.cs >> $(RESPONSE) @echo foo.cs >> $(RESPONSE) ]] end
bsd-3-clause
mahdib9/89
plugins/rss.lua
700
5434
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then if not is_sudo(msg) then return "Only sudo users can sync the RSS." end cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
gpl-2.0
UB12/y_r
plugins/rss.lua
700
5434
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then if not is_sudo(msg) then return "Only sudo users can sync the RSS." end cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
gpl-2.0
aminaleahmad/merbots
plugins/rss.lua
700
5434
local function get_base_redis(id, option, extra) local ex = '' if option ~= nil then ex = ex .. ':' .. option if extra ~= nil then ex = ex .. ':' .. extra end end return 'rss:' .. id .. ex end local function prot_url(url) local url, h = string.gsub(url, "http://", "") local url, hs = string.gsub(url, "https://", "") local protocol = "http" if hs == 1 then protocol = "https" end return url, protocol end local function get_rss(url, prot) local res, code = nil, 0 if prot == "http" then res, code = http.request(url) elseif prot == "https" then res, code = https.request(url) end if code ~= 200 then return nil, "Error while doing the petition to " .. url end local parsed = feedparser.parse(res) if parsed == nil then return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?" end return parsed, nil end local function get_new_entries(last, nentries) local entries = {} for k,v in pairs(nentries) do if v.id == last then return entries else table.insert(entries, v) end end return entries end local function print_subs(id) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) local text = id .. ' are subscribed to:\n---------\n' for k,v in pairs(subs) do text = text .. k .. ") " .. v .. '\n' end return text end local function subscribe(id, url) local baseurl, protocol = prot_url(url) local prothash = get_base_redis(baseurl, "protocol") local lasthash = get_base_redis(baseurl, "last_entry") local lhash = get_base_redis(baseurl, "subs") local uhash = get_base_redis(id) if redis:sismember(uhash, baseurl) then return "You are already subscribed to " .. url end local parsed, err = get_rss(url, protocol) if err ~= nil then return err end local last_entry = "" if #parsed.entries > 0 then last_entry = parsed.entries[1].id end local name = parsed.feed.title redis:set(prothash, protocol) redis:set(lasthash, last_entry) redis:sadd(lhash, id) redis:sadd(uhash, baseurl) return "You had been subscribed to " .. name end local function unsubscribe(id, n) if #n > 3 then return "I don't think that you have that many subscriptions." end n = tonumber(n) local uhash = get_base_redis(id) local subs = redis:smembers(uhash) if n < 1 or n > #subs then return "Subscription id out of range!" end local sub = subs[n] local lhash = get_base_redis(sub, "subs") redis:srem(uhash, sub) redis:srem(lhash, id) local left = redis:smembers(lhash) if #left < 1 then -- no one subscribed, remove it local prothash = get_base_redis(sub, "protocol") local lasthash = get_base_redis(sub, "last_entry") redis:del(prothash) redis:del(lasthash) end return "You had been unsubscribed from " .. sub end local function cron() -- sync every 15 mins? local keys = redis:keys(get_base_redis("*", "subs")) for k,v in pairs(keys) do local base = string.match(v, "rss:(.+):subs") -- Get the URL base local prot = redis:get(get_base_redis(base, "protocol")) local last = redis:get(get_base_redis(base, "last_entry")) local url = prot .. "://" .. base local parsed, err = get_rss(url, prot) if err ~= nil then return end local newentr = get_new_entries(last, parsed.entries) local subscribers = {} local text = '' -- Send only one message with all updates for k2, v2 in pairs(newentr) do local title = v2.title or 'No title' local link = v2.link or v2.id or 'No Link' text = text .. "[rss](" .. link .. ") - " .. title .. '\n' end if text ~= '' then local newlast = newentr[1].id redis:set(get_base_redis(base, "last_entry"), newlast) for k2, receiver in pairs(redis:smembers(v)) do send_msg(receiver, text, ok_cb, false) end end end end local function run(msg, matches) local id = "user#id" .. msg.from.id if is_chat_msg(msg) then id = "chat#id" .. msg.to.id end if matches[1] == "!rss"then return print_subs(id) end if matches[1] == "sync" then if not is_sudo(msg) then return "Only sudo users can sync the RSS." end cron() end if matches[1] == "subscribe" or matches[1] == "sub" then return subscribe(id, matches[2]) end if matches[1] == "unsubscribe" or matches[1] == "uns" then return unsubscribe(id, matches[2]) end end return { description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.", usage = { "!rss: Get your rss (or chat rss) subscriptions", "!rss subscribe (url): Subscribe to that url", "!rss unsubscribe (id): Unsubscribe of that id", "!rss sync: Download now the updates and send it. Only sudo users can use this option." }, patterns = { "^!rss$", "^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$", "^!rss (unsubscribe) (%d+)$", "^!rss (uns) (%d+)$", "^!rss (sync)$" }, run = run, cron = cron }
gpl-2.0
Telecat-full/-Telecat-Full
plugins/Welcome.lua
114
3529
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = string.gsub(chat_name, '_', ' ') or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function description_rules(msg, nama) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then local about = "" local rules = "" if data[tostring(msg.to.id)]["description"] then about = data[tostring(msg.to.id)]["description"] about = "\nAbout :\n"..about.."\n" end if data[tostring(msg.to.id)]["rules"] then rules = data[tostring(msg.to.id)]["rules"] rules = "\nRules :\n"..rules.."\n" end local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n" local text = sambutan..about..rules.."\n" local receiver = get_receiver(msg) send_large_msg(receiver, text, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end --vardump(msg) if matches[1] == "chat_add_user" then if not msg.action.user.username then nama = string.gsub(msg.action.user.print_name, "_", " ") else nama = "@"..msg.action.user.username end chat_new_user(msg) description_rules(msg, nama) elseif matches[1] == "chat_add_user_link" then if not msg.from.username then nama = string.gsub(msg.from.print_name, "_", " ") else nama = "@"..msg.from.username end chat_new_user_link(msg) description_rules(msg, nama) elseif matches[1] == "chat_del_user" then local bye_name = msg.action.user.first_name return 'Sikout '..bye_name end end return { description = "Welcoming Message", usage = "send message to new member", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$", "^!!tgservice (chat_del_user)$", }, run = run }
gpl-2.0
sumefsp/zile
lib/zile/search.lua
1
6365
-- Search and replace functions -- -- Copyright (c) 2010-2014 Free Software Foundation, Inc. -- -- This file is part of GNU Zile. -- -- 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, 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/>. -- Return true if there are no upper-case letters in the given string. -- If `regex' is true, ignore escaped letters. function no_upper (s, regex) local quote_flag = false for i = 1, #s do if regex and s[i] == '\\' then quote_flag = not quote_flag elseif not quote_flag and s[i] == string.upper (s[i]) then return false end end return true end local re_flags = rex_gnu.flags () local re_find_err local function find_substr (as, s, forward, notbol, noteol, regex, icase) local ret if not regex then s = string.gsub (s, "([$^.*[%]\\+?])", "\\%1") end local from, to = 1, #as local ok, r = pcall (rex_gnu.new, s, icase and re_flags.ICASE or 0) if ok then local ef = 0 if notbol then ef = bit32.bor (ef, re_flags.not_bol) end if noteol then ef = bit32.bor (ef, re_flags.not_eol) end if not forward then ef = bit32.bor (ef, re_flags.backward) end local match_from, match_to = r:find (as, nil, ef) if match_from then if forward then ret = match_to + from else ret = match_from + from - 1 end end else re_find_err = r end return ret end function search (s, forward, regexp) if #s < 1 then return false end -- Attempt match. local o = get_buffer_pt (cur_bp) local notbol = forward and o > 1 local noteol = not forward and o <= get_buffer_size (cur_bp) local downcase = eval.get_variable ("case_fold_search") and no_upper (s, regexp) local as = (forward and get_buffer_post_point or get_buffer_pre_point) (cur_bp) local pos = find_substr (as, s, forward, notbol, noteol, regexp, downcase) if not pos then return false end goto_offset (pos + (forward and (get_buffer_pt (cur_bp) - 1) or 0)) thisflag.need_resync = true return true end local last_search function do_search (forward, regexp, pattern) local ok = false local ms if not pattern then ms = minibuf_read (string.format ("%s%s: ", regexp and "RE search" or "Search", forward and "" or " backward"), last_search or "") pattern = ms end if not pattern then return keyboard_quit () end if #pattern > 0 then last_search = pattern if not search (pattern, forward, regexp) then minibuf_error (string.format ("Search failed: \"%s\"", pattern)) else ok = true end end return ok end -- Incremental search engine. function isearch (forward, regexp) local old_mark if cur_wp.bp.mark then old_mark = copy_marker (cur_wp.bp.mark) end cur_wp.bp.isearch = true local last = true local pattern = "" local start = get_buffer_pt (cur_bp) local cur = start while true do -- Make the minibuf message. local buf = string.format ("%sI-search%s: %s", (last and (regexp and "Regexp " or "") or (regexp and "Failing regexp " or "Failing ")), forward and "" or " backward", pattern) -- Regex error. if re_find_err then if string.sub (re_find_err, 1, 10) == "Premature " or string.sub (re_find_err, 1, 10) == "Unmatched " or string.sub (re_find_err, 1, 8) == "Invalid " then re_find_err = "incomplete input" end buf = buf .. string.format (" [%s]", re_find_err) re_find_err = nil end minibuf_write (buf) local c = getkey (GETKEY_DEFAULT) if c == keycode "\\C-g" then goto_offset (start) thisflag.need_resync = true -- Quit. keyboard_quit () -- Restore old mark position. if cur_bp.mark then unchain_marker (cur_bp.mark) end cur_bp.mark = old_mark break elseif c == keycode "\\BACKSPACE" then if #pattern > 0 then pattern = string.sub (pattern, 1, -2) cur = start goto_offset (start) thisflag.need_resync = true else ding () end elseif c == keycode "\\C-q" then minibuf_write (string.format ("%s^Q-", buf)) pattern = pattern .. string.char (getkey_unfiltered (GETKEY_DEFAULT)) elseif c == keycode "\\C-r" or c == keycode "\\C-s" then -- Invert direction. if c == keycode "\\C-r" then forward = false elseif c == keycode "\\C-s" then forward = true end if #pattern > 0 then -- Find next match. cur = get_buffer_pt (cur_bp) -- Save search string. last_search = pattern elseif last_search then pattern = last_search end elseif c.META or c.CTRL or c == keycode "\\RET" or term_keytobyte (c) == nil then if c == keycode "\\RET" and #pattern == 0 then do_search (forward, regexp) else if #pattern > 0 then -- Save mark. set_mark () cur_bp.mark.o = start -- Save search string. last_search = pattern minibuf_echo ("Mark saved when search started") else minibuf_clear () end if c ~= keycode "\\RET" then ungetkey (c) end end break else pattern = pattern .. string.char (term_keytobyte (c)) end if #pattern > 0 then local pt = get_buffer_pt (cur_bp) goto_offset (cur) last = search (pattern, forward, regexp) else last = true end if thisflag.need_resync then window_resync (cur_wp) term_redisplay () end end -- done cur_wp.bp.isearch = false return true end
gpl-3.0
tianxiawuzhei/cocos-quick-cpp
publibs/cocos2dx/cocos/scripting/lua-bindings/auto/api/PointLight.lua
11
1236
-------------------------------- -- @module PointLight -- @extend BaseLight -- @parent_module cc -------------------------------- -- get or set range -- @function [parent=#PointLight] getRange -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#PointLight] setRange -- @param self -- @param #float range -- @return point_table#point_table self (return value: point_table) -------------------------------- -- Creates a point light.<br> -- param position The light's position<br> -- param color The light's color.<br> -- param range The light's range.<br> -- return The new point light. -- @function [parent=#PointLight] create -- @param self -- @param #vec3_table position -- @param #color3b_table color -- @param #float range -- @return point_table#point_table ret (return value: point_table) -------------------------------- -- -- @function [parent=#PointLight] getLightType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- -- @function [parent=#PointLight] PointLight -- @param self -- @return point_table#point_table self (return value: point_table) return nil
mit
TheAgonist/NRAdmin
lstm2/util/CharSplitLMMinibatchLoader.lua
1
9038
-- Modified from https://github.com/oxford-cs-ml-2015/practical6 -- the modification included support for train/val/test splits local CharSplitLMMinibatchLoader = {} CharSplitLMMinibatchLoader.__index = CharSplitLMMinibatchLoader function CharSplitLMMinibatchLoader.create(data_dir, batch_size, seq_length, split_fractions) -- split_fractions is e.g. {0.9, 0.05, 0.05} local self = {} setmetatable(self, CharSplitLMMinibatchLoader) local input_file = path.join(data_dir, 'input.txt') local vocab_file = path.join(data_dir, 'vocab.t7') local tensor_file = path.join(data_dir, 'data.t7') -- fetch file attributes to determine if we need to rerun preprocessing local run_prepro = false if (path.exists(vocab_file) or path.exists(tensor_file)) then -- prepro files do not exist, generate them print('vocab.t7 and data.t7 do not exist. Running preprocessing...') run_prepro = true else -- check if the input file was modified since last time we -- ran the prepro. if so, we have to rerun the preprocessing local input_attr = lfs.attributes(input_file) local vocab_attr = lfs.attributes(vocab_file) local tensor_attr = lfs.attributes(tensor_file) if input_attr.modification > vocab_attr.modification or input_attr.modification > tensor_attr.modification then print('vocab.t7 or data.t7 detected as stale. Re-running preprocessing...') run_prepro = true end end if run_prepro then -- construct a tensor with all the data, and vocab file print('one-time setup: preprocessing input text file ' .. input_file .. '...') CharSplitLMMinibatchLoader.text_to_tensor(input_file, vocab_file, tensor_file) end print('loading data files...') local data = torch.load(tensor_file) self.vocab_mapping = torch.load(vocab_file) -- cut off the end so that it divides evenly local len = data:size(1) if len % (batch_size * seq_length) ~= 0 then print('cutting off end of data so that the batches/sequences divide evenly') data = data:sub(1, batch_size * seq_length * math.floor(len / (batch_size * seq_length))) end -- count vocab self.vocab_size = 0 for _ in pairs(self.vocab_mapping) do self.vocab_size = self.vocab_size + 1 end -- self.batches is a table of tensors print('reshaping tensor...') self.batch_size = batch_size self.seq_length = seq_length local ydata = data:clone() ydata:sub(1,-2):copy(data:sub(2,-1)) ydata[-1] = data[1] --ydata is data backwards --Data is one dimentioal --print(data:dim()) self.x_batches = data:view(batch_size, -1):split(seq_length, 2) -- #rows = #batches --print(data:view(batch_size,-1)) --self.x_batches = self.split(self.x_batches, data, seq_length, 55, 1) --print(data:view(batch_size,-1)) print(self.x_batches[1]) self.nbatches = #self.x_batches self.y_batches = ydata:view(batch_size, -1):split(seq_length, 2) -- #rows = #batches --self.y_batches = self.split(self.y_batches,ydata, seq_length, 55, 1) assert(#self.x_batches == #self.y_batches) -- lets try to be he lpful here if self.nbatches < 50 then print('WARNING: less than 50 batches in the data in total? Looks like very small dataset. You probably want to use smaller batch_size and/or seq_length.') end -- perform safety checks on split_fractions assert(split_fractions[1] >= 0 and split_fractions[1] <= 1, 'bad split fraction ' .. split_fractions[1] .. ' for train, not between 0 and 1') assert(split_fractions[2] >= 0 and split_fractions[2] <= 1, 'bad split fraction ' .. split_fractions[2] .. ' for val, not between 0 and 1') assert(split_fractions[3] >= 0 and split_fractions[3] <= 1, 'bad split fraction ' .. split_fractions[3] .. ' for test, not between 0 and 1') if split_fractions[3] == 0 then -- catch a common special case where the user might not want a test set self.ntrain = math.floor(self.nbatches * split_fractions[1]) self.nval = self.nbatches - self.ntrain self.ntest = 0 else -- divide data to train/val and allocate rest to test self.ntrain = math.floor(self.nbatches * split_fractions[1]) self.nval = math.floor(self.nbatches * split_fractions[2]) self.ntest = self.nbatches - self.nval - self.ntrain -- the rest goes to test (to ensure this adds up exactly) end self.split_sizes = {self.ntrain, self.nval, self.ntest} self.batch_ix = {0,0,0} print(string.format('data load done. Number of data batches in train: %d, val: %d, test: %d', self.ntrain, self.nval, self.ntest)) collectgarbage() return self end function CharSplitLMMinibatchLoader:reset_batch_pointer(split_index, batch_index) batch_index = batch_index or 0 self.batch_ix[split_index] = batch_index end function CharSplitLMMinibatchLoader:next_batch(split_index) if self.split_sizes[split_index] == 0 then -- perform a check here to make sure the user isn't screwing something up local split_names = {'train', 'val', 'test'} print('ERROR. Code requested a batch for split ' .. split_names[split_index] .. ', but this split has no data.') os.exit() -- crash violently end -- split_index is integer: 1 = train, 2 = val, 3 = test self.batch_ix[split_index] = self.batch_ix[split_index] + 1 if self.batch_ix[split_index] > self.split_sizes[split_index] then self.batch_ix[split_index] = 1 -- cycle around to beginning end -- pull out the correct next batch local ix = self.batch_ix[split_index] if split_index == 2 then ix = ix + self.ntrain end -- offset by train set size if split_index == 3 then ix = ix + self.ntrain + self.nval end -- offset by train + val --print(self.x_batches[ix]) return self.x_batches[ix], self.y_batches[ix] end -- *** STATIC method *** function CharSplitLMMinibatchLoader.text_to_tensor(in_textfile, out_vocabfile, out_tensorfile) local timer = torch.Timer() print('loading text file...') local cache_len = 10000 local rawdata local tot_len = 0 local f = assert(io.open(in_textfile, "r")) -- create vocabulary if it doesn't exist yet print('creating vocabulary mapping...') -- record all characters to a set local unordered = {} rawdata = f:read(cache_len) repeat for char in rawdata:gmatch'.' do --print(char) if not unordered[char] then unordered[char] = true end end --print(unordered) tot_len = tot_len + #rawdata rawdata = f:read(cache_len) until not rawdata f:close() -- sort into a table (i.e. keys become 1..N) local ordered = {} for char in pairs(unordered) do ordered[#ordered + 1] = char end table.sort(ordered) -- invert `ordered` to create the char->int mapping local vocab_mapping = {} for i, char in ipairs(ordered) do vocab_mapping[char] = i end --print(vocab_mapping) -- construct a tensor with all the data print('putting data into tensor...') local data = torch.ByteTensor(tot_len) -- store it into 1D first, then rearrange f = assert(io.open(in_textfile, "r")) local currlen = 0 rawdata = f:read(cache_len) repeat for i=1, #rawdata do data[currlen+i] = vocab_mapping[rawdata:sub(i, i)] -- lua has no string indexing using [] end currlen = currlen + #rawdata rawdata = f:read(cache_len) --print(rawdata) until not rawdata f:close() print("======================================") print(data) -- save output preprocessed files print('saving ' .. out_vocabfile) torch.save(out_vocabfile, vocab_mapping) print('saving ' .. out_tensorfile) torch.save(out_tensorfile, data) --print(vocab_mapping) --print(data) end function CharSplitLMMinibatchLoader.split_tensor_by_char(in_tensor, char) local splitTensor = torch.ByteTensor(in_tensor.length()) end function CharSplitLMMinibatchLoader.split(result, tensor, splitSize,char , dim) --print(tensor[1]) if torch.type(result) == 'table' then dim = splitSize splitSize = tensor tensor = result result = {} else result={} -- empty existing result table before using it for k,v in pairs(result) do result[k] = nil end end --print(result[0]) dim = dim or 1 local start = 2 local i=2 -- print(tensor) while start <= tensor:size(dim) do i=start while start<=tensor:size(dim) and tensor[i]==char and i<=tensor:size(dim) do i=i+1 end local size = math.min(i, tensor:size(dim) - start + 1) local split = tensor:narrow(dim, start, size) table.insert(result, split) start = start + size end --print(result) return result end return CharSplitLMMinibatchLoader
mit