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
mikar/awesome34-themes
dunzor2/theme.lua
1
6576
-- dunzor2, awesome3 theme, by dunz0r --{{{ Main local awful = require("awful") awful.util = require("awful.util") theme = {} home = os.getenv("HOME") config = awful.util.getdir("config") shared = "/usr/share/awesome" if not awful.util.file_readable(shared .. "/icons/awesome16.png") then shared = "/usr/share/local/awesome" end sharedicons = shared .. "/icons" sharedthemes = shared .. "/themes" themes = config .. "/themes" themename = "/dunzor2" if not awful.util.file_readable(themes .. themename .. "/theme.lua") then themes = sharedthemes end themedir = themes .. themename wallpaper1 = themedir .. "/background.jpg" wallpaper2 = themedir .. "/background.png" wallpaper3 = sharedthemes .. "/zenburn/zenburn-background.png" wallpaper4 = sharedthemes .. "/default/background.png" wpscript = home .. "/.wallpaper" if awful.util.file_readable(wallpaper1) then theme.wallpaper_cmd = { "awsetbg " .. wallpaper1 } elseif awful.util.file_readable(wallpaper2) then theme.wallpaper_cmd = { "awsetbg " .. wallpaper2 } elseif awful.util.file_readable(wpscript) then theme.wallpaper_cmd = { "sh " .. wpscript } elseif awful.util.file_readable(wallpaper3) then theme.wallpaper_cmd = { "awsetbg " .. wallpaper3 } else theme.wallpaper_cmd = { "awsetbg " .. wallpaper4 } end if awful.util.file_readable(config .. "/vain/init.lua") then theme.useless_gap_width = "3" end --}}} theme.font = "Montecarlo 7" theme.bg_normal = "#1a1a1a" theme.bg_focus = "#3e3e3e" theme.bg_urgent = "#303030" theme.bg_minimize = "#444444" theme.fg_normal = "#898989" theme.fg_focus = "#a6a600" theme.fg_unfocus = "#606060" theme.fg_urgent = "#98565e" theme.fg_highlight = "#98565e" theme.fg_minimize = "#98565e" theme.border_width = "1" theme.border_normal = "#000000" theme.border_focus = "#a6a600" theme.border_marked = "#91231c" -- widget colours theme.wid_rl = "#98565e" theme.wid_rh = "#cfa3a9" theme.wid_gl = "#66825d" theme.wid_gh = "#caf7bb" theme.wid_yl = "#969176" theme.wid_yh = "#fff8bc" theme.wid_bl = "#4d6585" theme.wid_bh = "#83aebe" theme.wid_ml = "#967395" theme.wid_mh = "#bba9cf" theme.wid_cl = "#5f7f7b" theme.wid_ch = "#96cccc" -- There are other variable sets -- overriding the default one when -- defined, the sets are: -- [taglist|tasklist]_[bg|fg]_[focus|urgent] -- titlebar_[bg|fg]_[normal|focus] -- Example: --theme.taglist_bg_focus = "#ff0000" -- {{{ Widgets -- You can add as many variables as -- you wish and access them by using -- beautiful.variable in your rc.lua theme.fg_widget = "#AECF96" theme.fg_center_widget = "#88A175" theme.fg_end_widget = "#FF5656" theme.bg_widget = "#494B4F" theme.border_widget = "#3F3F3F" -- }}} -- {{{ Mouse finder theme.mouse_finder_color = "#CC9393" -- mouse_finder_[timeout|animate_timeout|radius|factor] -- }}} -- {{{ Menu -- Variables set for theming the menu: -- menu_[bg|fg]_[normal|focus] -- menu_[border_color|border_width] theme.menu_height = "15" theme.menu_width = "100" -- }}} -- {{{ Icons -- {{{ Taglist theme.taglist_squares_sel = sharedthemes .. "/zenburn/taglist/squarefz.png" theme.taglist_squares_unsel = sharedthemes .. "/zenburn/taglist/squarez.png" --theme.taglist_squares_resize = "false" -- }}} -- {{{ Misc theme.awesome_icon = sharedthemes .. "/zenburn/awesome-icon.png" theme.menu_submenu_icon = sharedthemes .. "/default/submenu.png" theme.tasklist_floating_icon = sharedthemes .. "/default/tasklist/floatingw.png" -- }}} -- {{{ Layout theme.layout_tile = sharedthemes .. "/zenburn/layouts/tile.png" theme.layout_tileleft = sharedthemes .. "/zenburn/layouts/tileleft.png" theme.layout_tilebottom = sharedthemes .. "/zenburn/layouts/tilebottom.png" theme.layout_tiletop = sharedthemes .. "/zenburn/layouts/tiletop.png" theme.layout_fairv = sharedthemes .. "/zenburn/layouts/fairv.png" theme.layout_fairh = sharedthemes .. "/zenburn/layouts/fairh.png" theme.layout_spiral = sharedthemes .. "/zenburn/layouts/spiral.png" theme.layout_dwindle = sharedthemes .. "/zenburn/layouts/dwindle.png" theme.layout_max = sharedthemes .. "/zenburn/layouts/max.png" theme.layout_fullscreen = sharedthemes .. "/zenburn/layouts/fullscreen.png" theme.layout_magnifier = sharedthemes .. "/zenburn/layouts/magnifier.png" theme.layout_floating = sharedthemes .. "/zenburn/layouts/floating.png" -- }}} -- {{{ Titlebar theme.titlebar_close_button_focus = sharedthemes .. "/zenburn/titlebar/close_focus.png" theme.titlebar_close_button_normal = sharedthemes .. "/zenburn/titlebar/close_normal.png" theme.titlebar_ontop_button_focus_active = sharedthemes .. "/zenburn/titlebar/ontop_focus_active.png" theme.titlebar_ontop_button_normal_active = sharedthemes .. "/zenburn/titlebar/ontop_normal_active.png" theme.titlebar_ontop_button_focus_inactive = sharedthemes .. "/zenburn/titlebar/ontop_focus_inactive.png" theme.titlebar_ontop_button_normal_inactive = sharedthemes .. "/zenburn/titlebar/ontop_normal_inactive.png" theme.titlebar_sticky_button_focus_active = sharedthemes .. "/zenburn/titlebar/sticky_focus_active.png" theme.titlebar_sticky_button_normal_active = sharedthemes .. "/zenburn/titlebar/sticky_normal_active.png" theme.titlebar_sticky_button_focus_inactive = sharedthemes .. "/zenburn/titlebar/sticky_focus_inactive.png" theme.titlebar_sticky_button_normal_inactive = sharedthemes .. "/zenburn/titlebar/sticky_normal_inactive.png" theme.titlebar_floating_button_focus_active = sharedthemes .. "/zenburn/titlebar/floating_focus_active.png" theme.titlebar_floating_button_normal_active = sharedthemes .. "/zenburn/titlebar/floating_normal_active.png" theme.titlebar_floating_button_focus_inactive = sharedthemes .. "/zenburn/titlebar/floating_focus_inactive.png" theme.titlebar_floating_button_normal_inactive = sharedthemes .. "/zenburn/titlebar/floating_normal_inactive.png" theme.titlebar_maximized_button_focus_active = sharedthemes .. "/zenburn/titlebar/maximized_focus_active.png" theme.titlebar_maximized_button_normal_active = sharedthemes .. "/zenburn/titlebar/maximized_normal_active.png" theme.titlebar_maximized_button_focus_inactive = sharedthemes .. "/zenburn/titlebar/maximized_focus_inactive.png" theme.titlebar_maximized_button_normal_inactive = sharedthemes .. "/zenburn/titlebar/maximized_normal_inactive.png" -- }}} -- }}} theme.awesome_icon = sharedicons .. "/awesome16.png" return theme -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
mit
openwhisk/apigateway
scripts/lua/management/routes/tenants.lua
3
4573
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You 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. -- --- @module tenants -- Management interface for tenants for the gateway local cjson = require "cjson" local utils = require "lib/utils" local request = require "lib/request" local tenants = require "management/lib/tenants" local _M = {}; --- Check for tenant id from uri and use existing tenant if it already exists in redis -- @param red Redis client instance local function checkForExistingTenant(dataStore) local id = ngx.var.tenant_id local existing -- Get object from redis if id ~= nil and id ~= '' then existing = dataStore:getTenant(id) if existing == nil then dataStore:close() request.err(404, utils.concatStrings({"Unknown Tenant id ", id})) end end return existing end local function addTenant(dataStore) -- Open connection to redis or use one from connection pool -- Check for tenant id and use existingTenant if it already exists in redis local existingTenant = checkForExistingTenant(dataStore) -- Read in the PUT JSON Body ngx.req.read_body() local args = ngx.req.get_body_data() if not args then dataStore:close() request.err(400, "Missing request body") end -- Convert json into Lua table local decoded = cjson.decode(args) -- Check for tenant id in JSON body if existingTenant == nil and decoded.id ~= nil then existingTenant = dataStore:getTenant(decoded.id) if existingTenant == nil then request.err(404, utils.concatStrings({"Unknown Tenant id ", decoded.id})) end end -- Error checking local res, err = utils.tableContainsAll(decoded, {"namespace", "instance"}) if res == false then dataStore:close() request.err(err.statusCode, err.message) end -- Return tenant object local tenantObj = tenants.addTenant(dataStore, decoded, existingTenant) tenantObj = cjson.encode(tenantObj) request.success(200, tenantObj) end --- Get one or all tenants from the gateway -- GET /v1/tenants local function getTenants(dataStore) local queryParams = ngx.req.get_uri_args() local id = ngx.var.tenant_id if id == '' then local tenantList = tenants.getAllTenants(dataStore, queryParams) tenantList = (next(tenantList) == nil) and "[]" or cjson.encode(tenantList) dataStore:close() request.success(200, tenantList) else local query = ngx.var.query if query ~= '' then if query ~= "apis" then dataStore:close() request.err(400, "Invalid request") else local apiList = tenants.getTenantAPIs(dataStore, id, queryParams) apiList = (next(apiList) == nil) and "[]" or cjson.encode(apiList) dataStore:close() request.success(200, apiList) end else local tenant = tenants.getTenant(dataStore, id) tenant = cjson.encode(tenant) dataStore:close() request.success(200, tenant) end end end --- Delete tenant from gateway -- DELETE /v1/tenants/<id> local function deleteTenant(dataStore) local id = ngx.var.tenant_id if id == nil or id == '' then request.err(400, "No id specified.") end local tenant = dataStore:getTenant(id) if tenant == nil then dataStore:close() request.err(404, utils.concatStrings({"Unknown tenant id ", id})) end tenants.deleteTenant(dataStore, id) request.success(200, cjson.encode({})) end --- Request handler for routing tenant calls appropriately function _M.requestHandler(dataStore) local requestMethod = ngx.req.get_method() ngx.header.content_type = "application/json; charset=utf-8" if requestMethod == "GET" then getTenants(dataStore) elseif requestMethod == "PUT" or requestMethod == "POST" then addTenant(dataStore) elseif requestMethod == "DELETE" then deleteTenant(dataStore) else request.err(400, "Invalid verb.") end end return _M
mit
Blackdutchie/Zero-K
LuaRules/Configs/MetalSpots/Grts_Messa_008.lua
17
1312
return { spots = { -- Four metal spots in center {x = 6162, z = 6750, metal = 3}, {x = 5546, z = 6128, metal = 3}, {x = 6138, z = 5562, metal = 3}, {x = 6747, z = 6152, metal = 3}, -- 12 starting spots (2x3 on each side) {x = 1093, z = 9286, metal = 3}, {x = 1174, z = 7125, metal = 3}, {x = 1208, z = 3882, metal = 3}, {x = 1801, z = 1770, metal = 3}, {x = 11211, z = 3015, metal = 3}, {x = 11127, z = 5179, metal = 3}, {x = 11097, z = 8424, metal = 3}, {x = 10505, z = 10535, metal = 3}, {x = 1110, z = 8144, metal = 3}, {x = 1488, z = 2740, metal = 3}, {x = 11178, z = 4078, metal = 3}, {x = 10853, z = 9452, metal = 3}, -- 8 "pairs" of metal spots -- they are close, but not right next to one another {x = 2734, z = 9944, metal = 3}, {x = 2871, z = 10981, metal = 3}, {x = 5140, z = 8906, metal = 3}, {x = 4199, z = 7650, metal = 3}, {x = 7151, z = 3406, metal = 3}, {x = 8069, z = 4661, metal = 3}, {x = 3010, z = 2775, metal = 3}, {x = 3718, z = 1396, metal = 3}, {x = 8607, z = 10905, metal = 3}, {x = 9275, z = 9512, metal = 3}, {x = 2911, z = 5460, metal = 3}, {x = 4391, z = 4782, metal = 3}, {x = 7771, z = 7617, metal = 3}, {x = 9411, z = 6824, metal = 3}, {x = 9522, z = 2360, metal = 3}, {x = 9419, z = 1328, metal = 3}, } }
gpl-2.0
openwhisk/apigateway
tests/scripts/lua/lib/request.lua
4
1588
-- -- Licensed to the Apache Software Foundation (ASF) under one or more -- contributor license agreements. See the NOTICE file distributed with -- this work for additional information regarding copyright ownership. -- The ASF licenses this file to You 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 fakengx = require 'fakengx' local request = require 'lib/request' local cjson = require 'cjson' describe('Testing Request module', function() before_each(function() _G.ngx = fakengx.new() end) it('should return correct error response', function() local code = 500 local msg = 'Internal server error\n' request.err(code ,msg) local expected = cjson.encode{status = code, message = 'Error: ' .. msg} local actual = ngx._body assert.are.same(expected .. '\n', actual) assert.are.equal(code, ngx._exit) end) it('should return correct success response', function() local code = 200 local msg ='Success!\n' request.success(code, msg) assert.are.equal(msg .. '\n', ngx._body) assert.are.equal(code, ngx._exit) end) end)
mit
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/zones/conclave-vault/rooms/room4.lua
1
1816
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local def = { numbers = '.', [[#!!!!#!!!!#]], [[!2221#1222!]], [[!22#####22!]], [[!.........!]], [[!.........!]], [[!..#####..!]], [[!..21#12..!]], [[!2221#1222!]], [[!..21#12..!]], [[!..#####..!]], [[!.........!]], [[!.........!]], [[!22#####22!]], [[!2221#1222!]], [[#!!!!#!!!!#]], } return function(gen, id) local room = gen:roomParse(def) return { name="conclave-ogre-2"..room.w.."x"..room.h, w=room.w, h=room.h, generator = function(self, x, y, is_lit) gen:roomFrom(id, x, y, is_lit, room) for _, spot in ipairs(room.spots[1]) do local e = gen.zone:makeEntity(gen.level, "actor", {special_rarity="vat_rarity"}, nil, true) if e then gen:roomMapAddEntity(x + spot.x, y + spot.y, "actor", e) gen.map.room_map[x + spot.x][y + spot.y].special = true end end for _, spot in ipairs(room.spots[2]) do game.level.map(x + spot.x, y + spot.y, gen.map.TRIGGER, engine.Entity.new{ on_move = function(self, x, y, who) if who and game.zone.awaken_ogres then game.zone.awaken_ogres(who, x, y, 4) end end}) end end} end
gpl-3.0
Blackdutchie/Zero-K
units/nsaclash.lua
1
7047
unitDef = { unitname = [[nsaclash]], name = [[Scalpel]], description = [[Skirmisher/Anti-Heavy Hovercraft]], acceleration = 0.0435, activateWhenBuilt = true, brakeRate = 0.205, buildCostEnergy = 220, buildCostMetal = 220, builder = false, buildPic = [[nsaclash.png]], buildTime = 220, canAttack = true, canGuard = true, canHover = true, canMove = true, canPatrol = true, category = [[HOVER]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[38 38 38]], collisionVolumeTest = 1, collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { description_bp = [[Hovercraft escaramuçador]], description_de = [[Skirmisher Gleiter (Anti-Heavy)]], description_fr = [[Hovercraft Tirailleur]], description_pl = [[Poduszkowiec harcownik]], helptext = [[Use the Scalpel for hit-and-run attacks. Has a long reload time and not too many hit points, and should always be kept at range with the enemy. An arcing projectile allows it to shoot over obstacles and friendly units.]], helptext_de = [[Nutze den Scalpel für Schlag-und-Renn Attacken. Er hat eine lange Nachladezeit und nicht allzu viele Lebenspunkte. Er sollte immer auf Distanz zum Feind gehalten werden. Die bogenförmige Schussbahn ermöglicht es über Hindernisse und freundliche Einheiten zu schießen.]], helptext_bp = [[Scalpel é um escaramuçador: Use-o para ataques de bater e correr. Demora para recarregar e n?o é muito resistente, devendo sempre ser mantido a distância do inimigo. Seus projéteis de trajetória curva superam obstáculos.]], helptext_fr = [[Le Scalpel est un tirailleur, il est utile pour harrasser l'ennemi ? l'aide de son lance roquette. Il tire des roquettes ? t?te chercheuse au dessus des obstacles, mais son temps de rechargement, sa maniabilit? et son faible blindage le rendent vuln?rable aux contre attaques.]], helptext_pl = [[Scalpel najlepiej nadaje sie do atakow nekajacych. Dlugi czas przeladowania i niska wytrzymalosc powoduja, ze wymaga ochrony i poswiecenia uwagi, by nie zblizal sie zbytnio do wrogich jednostek. Zakrzywiona trajektoria pociskow pozwala Scalpelowi na strzelanie ponad przeszkodami i sojuszniczymi jednostkami.]], modelradius = [[19]], turnatfullspeed = [[1]], }, explodeAs = [[BIG_UNITEX]], footprintX = 3, footprintZ = 3, iconType = [[hoverskirm]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, mass = 153, maxDamage = 680, maxSlope = 18, maxVelocity = 2.1, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[HOVER3]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[nsaclash.s3o]], script = [[nsaclash.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:HEAVYHOVERS_ON_GROUND]], [[custom:JANUSMUZZLE]], [[custom:JANUSBACK]], }, }, side = [[ARM]], sightDistance = 495, smoothAnim = true, turninplace = 0, turnRate = 480, workerTime = 0, weapons = { { def = [[MISSILE]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER SUB]], }, }, weaponDefs = { MISSILE = { name = [[Heavy Missile Battery]], areaOfEffect = 96, cegTag = [[missiletrailyellow]], craterBoost = 1, craterMult = 1.4, damage = { default = 311, }, fireStarter = 70, fixedlauncher = true, flightTime = 3.5, impulseBoost = 0.75, impulseFactor = 0.3, interceptedByShieldType = 2, leadlimit = 0, model = [[wep_m_dragonsfang.s3o]], projectiles = 2, range = 450, reloadtime = 10, smokeTrail = true, soundHit = [[explosion/ex_med5]], soundHitVolume = 8, soundStart = [[weapon/missile/rapid_rocket_fire2]], soundStartVolume = 7, startVelocity = 190, texture2 = [[lightsmoketrail]], tracks = true, trajectoryHeight = 0.4, turnRate = 24000, turret = true, weaponAcceleration = 90, weaponTimer = 3, weaponType = [[MissileLauncher]], weaponVelocity = 200, }, }, featureDefs = { DEAD = { description = [[Wreckage - Scalpel]], blocking = true, category = [[corpses]], damage = 680, energy = 0, featureDead = [[DEAD2]], featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[20]], hitdensity = [[100]], metal = 88, object = [[nsaclash_dead.s3o]], reclaimable = true, reclaimTime = 88, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, DEAD2 = { description = [[Debris - Scalpel]], blocking = false, category = [[heaps]], damage = 680, energy = 0, featureDead = [[HEAP]], featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[4]], hitdensity = [[100]], metal = 88, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 88, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Scalpel]], blocking = false, category = [[heaps]], damage = 620, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 2, footprintZ = 2, height = [[4]], hitdensity = [[100]], metal = 44, object = [[debris2x2c.s3o]], reclaimable = true, reclaimTime = 44, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ nsaclash = unitDef })
gpl-2.0
electricpandafishstudios/Spoon
game/engines/te4-1.4.1/engine/interface/GameTargeting.lua
1
16543
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" require "engine.KeyBind" local Dialog = require "engine.ui.Dialog" local Map = require "engine.Map" local Target = require "engine.Target" --- Handles default targeting interface & display -- @classmod engine.generator.interface.GameTargeting module(..., package.seeall, class.make) --- Initializes targeting function _M:init() self.target = Target.new(Map, self.player) self.target.target.entity = self.player self.old_tmx, self.old_tmy = 0, 0 self.target_style = "lock" -- Allow scrolling when targetting self.target.on_set_target = function(self, how) if self.key ~= self.targetmode_key then return end local dx, dy = game.level.map:moveViewSurround(self.target.x, self.target.y, 1, 1, true) if how == "mouse" and (dx ~= 0 or dy ~= 0) then local cx, cy = core.mouse.get() core.mouse.set(cx - game.level.map.tile_w * dx, cy - game.level.map.tile_h * dy) end end end --- Maintain the current target each tick -- Make sure the target still exists function _M:targetOnTick() if self.target.target.entity and not self.level:hasEntity(self.target.target.entity) then self.target.target.entity = false end end --- Display the tooltip, if any function _M:targetDisplayTooltip(dx, dy, force, nb_keyframes) -- Tooltip is displayed over all else if self.level and self.level.map and self.level.map.finished then local tmx, tmy -- Display a tooltip if available if self.tooltip_x then if type(self.tooltip_x) == "table" then self.tooltip:toScreen(self.tooltip.last_display_x, self.tooltip.last_display_y, nb_keyframes) else tmx, tmy = self.level.map:getMouseTile(self.tooltip_x , self.tooltip_y) self.tooltip:displayAtMap(tmx, tmy, dx, dy, nil, force, nb_keyframes) end end -- Move target around if self.old_tmx ~= tmx or self.old_tmy ~= tmy then self.target.target.x, self.target.target.y = tmx, tmy end self.old_tmx, self.old_tmy = tmx, tmy end end --- Forces the tooltip to pop with the given text function _M:tooltipDisplayAtMap(x, y, text, extra, force, nb_keyframes) self.tooltip:displayAtMap(nil, nil, x, y, text, force, nb_keyframes) if extra and type(extra) == "table" then if extra.up then self.tooltip.last_display_y = self.tooltip.last_display_y - self.tooltip.h end end self.tooltip_x = {} end --- Enter/leave targeting mode -- This is the "meat" of this interface, do not expect to understand it easily, it mixes some nasty stuff -- This require the Game to have both a "key" field (this is the default) and a "normal_key" field<br/> -- It will switch over to a special keyhandler and then restore the "normal_key" one function _M:targetMode(v, msg, co, typ) local old = self.target_mode self.target_mode = v if not v then Map:setViewerFaction((self.always_target == true or self.always_target == "old") and self.player.faction or nil) if msg then self.log(type(msg) == "string" and msg or "Tactical display disabled. Press shift+'t' to enable.") end self.level.map.changed = true self.targetmode_trigger_hotkey = nil self.target:setActive(false) if tostring(old) == "exclusive" then local x, y, e = self.target.target.x, self.target.target.y, self.target.target.entity local fct = function(notok) if notok then self.target.target.entity = nil self.target.target.x = nil self.target.target.y = nil x, y, e = nil, nil, nil end self.key = self.normal_key self.key:setCurrent() if self.target_co then local co = self.target_co self.target_co = nil self.target.target.x, self.target.target.y, self.target.target.entity = x, y, e local ok, err = coroutine.resume(co, self.target.target.x, self.target.target.y, self.target.target.entity) if not ok and err then print(debug.traceback(co)) error(err) end end end if self.target_warning and self.target.target.x == self.player.x and self.target.target.y == self.player.y then Dialog:yesnoPopup(type(self.target_warning) == "string" and self.target_warning or "Target yourself?", "Are you sure you want to target yourself?", fct, "No", "Yes", nil, true) else fct(false) end end else Map:setViewerFaction(self.player.faction) if msg then self.log(type(msg) == "string" and msg or "Tactical display enabled. Press shift+'t' to disable.") end self.level.map.changed = true self.target:setActive(true, typ) self.target_style = "lock" self.target_warning = true if type(typ) == "table" and typ.talent then self.target_warning = typ.talent.name elseif type(typ) == "table" and typ.__name then self.target_warning = typ.__name end -- Exclusive mode means we disable the current key handler and use a specific one -- that only allows targetting and resumes talent coroutine when done if tostring(v) == "exclusive" then self.target_co = co self.key = self.targetmode_key self.key:setCurrent() local do_scan = true if self.target_no_star_scan or ( self.target.target.entity and self.level.map.seens(self.target.target.entity.x, self.target.target.entity.y) and self.player ~= self.target.target.entity ) then if type(typ) == "table" and typ.first_target ~= "friend" and self.player:reactionToward(self.target.target.entity) >= 0 then else do_scan = false end end if do_scan then local filter = nil if not (type(typ) == "table" and typ.no_first_target_filter) then if type(typ) == "table" and typ.first_target and typ.first_target == "friend" then filter = function(a) return self.player:reactionToward(a) >= 0 end else filter = function(a) return self.player:reactionToward(a) < 0 end end end self.target:scan(5, nil, self.player.x, self.player.y, filter, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) end if self.target.target.entity and self.target.target.entity.x and self.target.target.entity.y then self.target.target.x, self.target.target.y = self.target.target.entity.x, self.target.target.entity.y end end if self.target.target.x then self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end end end function _M:targetTriggerHotkey(i) self.targetmode_trigger_hotkey = i end --- This setups the default keybindings for targeting function _M:targetSetupKey() local accept = function() self:targetMode(false, false) self.tooltip_x, self.tooltip_y = nil, nil end self.targetmode_key = engine.KeyBind.new() self.targetmode_key:addCommands{ _SPACE=accept, [{"_SPACE","ctrl"}]=accept, [{"_RETURN","ctrl"}]=accept, [{"_KP_ENTER","ctrl"}]=accept } if engine.interface and engine.interface.PlayerHotkeys then engine.interface.PlayerHotkeys:bindAllHotkeys(self.targetmode_key, function(i) if self.targetmode_trigger_hotkey == i then accept() end end) end self.targetmode_key:addBinds { TACTICAL_DISPLAY = accept, ACCEPT = accept, EXIT = function() self.target.target.entity = nil self.target.target.x = nil self.target.target.y = nil self:targetMode(false, false) self.tooltip_x, self.tooltip_y = nil, nil end, -- Targeting movement RUN_LEFT = function() self.target:freemove(4) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_RIGHT = function() self.target:freemove(6) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_UP = function() self.target:freemove(8) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_DOWN = function() self.target:freemove(2) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_LEFT_DOWN = function() self.target:freemove(1) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_RIGHT_DOWN = function() self.target:freemove(3) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_LEFT_UP = function() self.target:freemove(7) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, RUN_RIGHT_UP = function() self.target:freemove(9) self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_LEFT = function() if self.target_style == "lock" then self.target:scan(4, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(4, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(4) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_RIGHT = function() if self.target_style == "lock" then self.target:scan(6, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(6, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(6) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_UP = function() if self.target_style == "lock" then self.target:scan(8, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(8, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(8) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_DOWN = function() if self.target_style == "lock" then self.target:scan(2, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(2, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(2) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_LEFT_DOWN = function() if self.target_style == "lock" then self.target:scan(1, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(1, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(1) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_RIGHT_DOWN = function() if self.target_style == "lock" then self.target:scan(3, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(3, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(3) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_LEFT_UP = function() if self.target_style == "lock" then self.target:scan(7, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(7, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(7) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_RIGHT_UP = function() if self.target_style == "lock" then self.target:scan(9, nil, nil, nil, nil, self.target.target_type and type(self.target.target_type) == "table" and self.target.target_type.scan_on) elseif self.target_style == "immediate" then self.target:setDirFrom(9, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return else self.target:freemove(9) end self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, MOVE_STAY = function() if self.target_style == "immediate" then self.target:setDirFrom(5, self.target.target.entity or self.player) self.targetmode_key:triggerVirtual("ACCEPT") return end self.target:setSpot(self.target.source_actor.x, self.target.source_actor.y, "freemove") self.tooltip_x, self.tooltip_y = self.level.map:getTileToScreen(self.target.target.x, self.target.target.y) end, SCREENSHOT = function() self.normal_key:triggerVirtual("SCREENSHOT") end, } end --- Handle mouse event for targeting -- @return true if the event was handled function _M:targetMouse(button, mx, my, xrel, yrel, event) if not self.level then return end -- Move tooltip self.tooltip_x, self.tooltip_y = mx, my local tmx, tmy = self.level.map:getMouseTile(mx, my) self.target:setSpot(tmx, tmy, "mouse") if self.key == self.targetmode_key then -- Target with mouse if button == "none" and xrel and yrel and event == "motion" then self.target:setSpotInMotion(tmx, tmy, "mouse") -- Accept target elseif button == "left" and not xrel and not yrel and event == "button" then self:targetMode(false, false) self.tooltip_x, self.tooltip_y = nil, nil -- Cancel target elseif not xrel and not yrel and event == "button" then self.target.target.entity = nil self.target.target.x = nil self.target.target.y = nil self:targetMode(false, false) self.tooltip_x, self.tooltip_y = nil, nil end return true end end --- Player requests a target -- This method should be called by your Player:getTarget() method, it will handle everything -- @param typ the targeting parameters function _M:targetGetForPlayer(typ) if self.target.forced then return unpack(self.target.forced) end if coroutine.running() and typ then local msg self.target_no_star_scan = nil if type(typ) == "string" then msg, typ = typ, nil elseif type(typ) == "table" then if typ.default_target then self.target.target.entity = typ.default_target self.target_no_star_scan = true end msg = typ.msg end self:targetMode("exclusive", msg, coroutine.running(), typ) if self.target.target.x and config.settings.auto_accept_target and not typ.immediate_keys and not typ.nolock and not typ.nowarning and not typ.no_restrict then self.target_co = nil self:targetMode(false, false) self.tooltip_x, self.tooltip_y = nil, nil return self.target.target.x, self.target.target.y, self.target.target.entity end if typ.immediate_keys then self.target_style = "immediate" end if typ.nolock then self.target_style = "free" end if typ.nowarning then self.target_warning = false end return coroutine.yield() end return self.target.target.x, self.target.target.y, self.target.target.entity end --- Player wants to set its target -- This method should be called by your Player:setTarget() method, it will handle everything function _M:targetSetForPlayer(target) self.target.target.entity = target self.target.target.x = (type(target) == "table" and target.x) or nil self.target.target.y = (type(target) == "table" and target.y) or nil end
gpl-3.0
Blackdutchie/Zero-K
LuaUI/Widgets/unit_icons.lua
5
9458
------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Unit Icons", desc = "v0.033 Shows icons above units", author = "CarRepairer and GoogleFrog", date = "2012-01-28", license = "GNU GPL, v2 or later", layer = -10,-- enabled = true, -- loaded by default? } end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local echo = Spring.Echo local spGetUnitDefID = Spring.GetUnitDefID local spIsUnitInView = Spring.IsUnitInView local spGetUnitViewPosition = Spring.GetUnitViewPosition local spGetGameFrame = Spring.GetGameFrame local glDepthTest = gl.DepthTest local glDepthMask = gl.DepthMask local glAlphaTest = gl.AlphaTest local glTexture = gl.Texture local glTexRect = gl.TexRect local glTranslate = gl.Translate local glBillboard = gl.Billboard local glDrawFuncAtUnit = gl.DrawFuncAtUnit local glPushMatrix = gl.PushMatrix local glPopMatrix = gl.PopMatrix local GL_GREATER = GL.GREATER local min = math.min local max = math.max local floor = math.floor local abs = math.abs local iconsize = 5 local forRadarIcons = true ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- options_path = 'Settings/Interface/Hovering Icons' options = { iconsize = { name = 'Hovering Icon Size', type = 'number', value = 30, min=10, max = 40, OnChange = function(self) iconsize = self.value end }, forRadarIcons = { name = 'Draw on Icons', desc = 'Draws state icons when zoomed out.', type = 'bool', value = true, OnChange = function(self) forRadarIcons = self.value end }, } options.iconsize.OnChange(options.iconsize) ---------------------------------------------------------------------------------------- ---------------------------------------------------------------------------------------- local unitHeights = {} local iconOrders = {} local iconOrders_order = {} local iconoffset = 22 local iconUnitTexture = {} --local textureUnitsXshift = {} local textureData = {} local textureIcons = {} local textureOrdered = {} local textureColors = {} --local xshiftUnitTexture = {} local hideIcons = {} local pulseIcons = {} WG.icons = {} ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function OrderIcons() iconOrders_order = {} for iconName, _ in pairs(iconOrders) do iconOrders_order[#iconOrders_order+1] = iconName end table.sort(iconOrders_order, function(a,b) return iconOrders[ a ] < iconOrders[ b ] end) end local function OrderIconsOnUnit(unitID ) local iconCount = 0 for i=1, #iconOrders_order do local iconName = iconOrders_order[i] if (not hideIcons[iconName]) and iconUnitTexture[iconName] and iconUnitTexture[iconName][unitID] then iconCount = iconCount + 1 end end local xshift = (0.5 - iconCount*0.5)*iconsize for i=1, #iconOrders_order do local iconName = iconOrders_order[i] local texture = iconUnitTexture[iconName] and iconUnitTexture[iconName][unitID] if texture then if hideIcons[iconName] then --textureUnitsXshift[texture][unitID] = nil textureData[texture][iconName][unitID] = nil else --textureUnitsXshift[texture][unitID] = xshift textureData[texture][iconName][unitID] = xshift xshift = xshift + iconsize end end end end local function SetOrder(iconName, order) iconOrders[iconName] = order OrderIcons() end local function ReOrderIconsOnUnits() local units = Spring.GetAllUnits() for i=1,#units do OrderIconsOnUnit(units[i]) end end function WG.icons.SetDisplay( iconName, show ) local hide = (not show) or nil curHide = hideIcons[iconName] if curHide ~= hide then hideIcons[iconName] = hide ReOrderIconsOnUnits() end end function WG.icons.SetOrder( iconName, order ) SetOrder(iconName, order) end function WG.icons.SetPulse( iconName, pulse ) pulseIcons[iconName] = pulse end function WG.icons.SetUnitIcon( unitID, data ) local iconName = data.name local texture = data.texture local color = data.color if not iconOrders[iconName] then SetOrder(iconName, math.huge) end local oldTexture = iconUnitTexture[iconName] and iconUnitTexture[iconName][unitID] if oldTexture then --textureUnitsXshift[oldTexture][unitID] = nil textureData[oldTexture][iconName][unitID] = nil iconUnitTexture[iconName][unitID] = nil if (not hideIcons[iconName])then OrderIconsOnUnit(unitID) end end if not texture then return end --[[ if not textureUnitsXshift[texture] then textureUnitsXshift[texture] = {} end textureUnitsXshift[texture][unitID] = 0 --]] --new if not textureData[texture] then textureData[texture] = {} end if not textureData[texture][iconName] then textureData[texture][iconName] = {} end textureData[texture][iconName][unitID] = 0 if color then if not textureColors[unitID] then textureColors[unitID] = {} end textureColors[unitID][iconName] = color end if not iconUnitTexture[iconName] then iconUnitTexture[iconName] = {} end iconUnitTexture[iconName][unitID] = texture if not unitHeights[unitID] then local ud = UnitDefs[spGetUnitDefID(unitID)] if (ud == nil) then unitHeights[unitID] = nil else --unitHeights[unitID] = ud.height + iconoffset unitHeights[unitID] = Spring.GetUnitHeight(unitID) + iconoffset end end OrderIconsOnUnit(unitID) end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- function widget:UnitDestroyed(unitID, unitDefID, unitTeam) unitHeights[unitID] = nil --xshiftUnitTexture[unitID] = nil end ------------------------------------------------------------------------------------- ------------------------------------------------------------------------------------- local function DrawFuncAtUnitIcon2(unitID, xshift, yshift) local x,y,z = spGetUnitViewPosition(unitID) glPushMatrix() glTranslate(x,y,z) glTranslate(0,yshift,0) glBillboard() glTexRect(xshift -iconsize*0.5, -5, xshift + iconsize*0.5, iconsize-5) glPopMatrix() end local function DrawUnitFunc(xshift, yshift) glTranslate(0,yshift,0) glBillboard() glTexRect(xshift - iconsize*0.5, -9, xshift + iconsize*0.5, iconsize-9) end local function DrawWorldFunc() if Spring.IsGUIHidden() then return end if (next(unitHeights) == nil) then return -- avoid unnecessary GL calls end local gameFrame = spGetGameFrame() local fade = min( abs((gameFrame % 60) - 20) / 20, 1 ) gl.Color(1,1,1,1) glDepthMask(true) glDepthTest(true) glAlphaTest(GL_GREATER, 0.001) --for texture, units in pairs(textureUnitsXshift) do for texture, curTextureData in pairs(textureData) do for iconName, units in pairs(curTextureData) do glTexture(texture) for unitID,xshift in pairs(units) do local textureColor = textureColors[unitID] and textureColors[unitID][iconName] if textureColor then gl.Color( textureColor ) elseif pulseIcons[iconName] then gl.Color( 1,1,1,fade ) end local unitInView = spIsUnitInView(unitID) if unitInView and xshift and unitHeights and unitHeights[unitID] then if forRadarIcons then DrawFuncAtUnitIcon2(unitID, xshift, unitHeights[unitID]) else glDrawFuncAtUnit(unitID, false, DrawUnitFunc,xshift,unitHeights[unitID]) end end if textureColor or pulseIcons[iconName] then gl.Color(1,1,1,1) end end end --new end glTexture(false) glAlphaTest(false) glDepthTest(false) glDepthMask(false) end function widget:DrawWorld() DrawWorldFunc() end function widget:DrawWorldRefraction() DrawWorldFunc() end -- drawscreen method -- the problem with this one is it draws at same size regardless of how far away the unit is --[[ function widget:DrawScreenEffects() if Spring.IsGUIHidden() then return end if (next(unitHeights) == nil) then return -- avoid unnecessary GL calls end gl.Color(1,1,1,1) glDepthMask(true) glDepthTest(true) glAlphaTest(GL_GREATER, 0.001) for texture, units in pairs(textureUnitsXshift) do glTexture( texture ) for unitID,xshift in pairs(units) do gl.PushMatrix() local x,y,z = Spring.GetUnitPosition(unitID) y = y + (unitHeights[unitID] or 0) x,y,z = Spring.WorldToScreenCoords(x,y,z) glTranslate(x,y,z) if xshift and unitHeights then glTranslate(xshift,0,0) --glBillboard() glTexRect(-iconsize*0.5, -9, iconsize*0.5, iconsize-9) end gl.PopMatrix() end end glTexture(false) glAlphaTest(false) glDepthTest(false) glDepthMask(false) end ]] function widget:Initialize() end function widget:Shutdown() --for texture,_ in pairs(textureUnitsXshift) do for texture,_ in pairs(textureData) do gl.DeleteTexture(texture) end end ------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------
gpl-2.0
sleepingwit/premake-core
modules/vstudio/tests/vc200x/test_project.lua
14
4173
-- -- tests/actions/vstudio/vc200x/test_project.lua -- Validate generation of the opening <VisualStudioProject> element. -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_vs200x_project") local vc200x = p.vstudio.vc200x -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2008") wks = test.createWorkspace() uuid "AE61726D-187C-E440-BD07-2556188A6565" end local function prepare() prj = test.getproject(wks, 1) vc200x.visualStudioProject(prj) end -- -- Verify the version numbers for each action. -- function suite.hasCorrectVersion_on2005() p.action.set("vs2005") prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="8.00" ]] end function suite.hasCorrectVersion_on2008() p.action.set("vs2008") prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" ]] end -- -- Check the structure with the default project values. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="Win32Proj" TargetFrameworkVersion="0" > ]] end -- -- Use the correct keyword for Managed C++ projects. -- function suite.keywordIsCorrect_onManagedC() clr "On" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="ManagedCProj" ]] end -- -- Omit Keyword and RootNamespace for non-Windows projects. -- function suite.noKeyword_onNotWindows() system "Linux" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" TargetFrameworkVersion="196613" > ]] end -- -- Include Keyword and RootNamespace for mixed system projects. -- function suite.includeKeyword_onMixedConfigs() filter "Debug" system "Windows" filter "Release" system "Linux" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="Win32Proj" TargetFrameworkVersion="0" > ]] end -- -- Makefile projects set new keyword. It should also drop the root -- namespace, but I need to figure out a better way to test for -- empty configurations in the project first. -- function suite.keywordIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end function suite.keywordIsCorrect_onNone() kind "None" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end --- -- Makefile projects which do not support all of the solution configurations -- add back the RootNamespace element. --- function suite.keywordIsCorrect_onMakefileWithMixedConfigs() removeconfigurations { "Release" } kind "Makefile" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end function suite.keywordIsCorrect_onNoneWithMixedConfigs() removeconfigurations { "Release" } kind "None" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end
bsd-3-clause
kuoruan/lede-luci
libs/luci-lib-nixio/docsrc/nixio.UnifiedIO.lua
16
5900
--- Unified high-level I/O utility API for Files, Sockets and TLS-Sockets. -- These functions are added to the object function tables by doing <strong> -- require "nixio.util"</strong>, can be used on all nixio IO Descriptors and -- are based on the shared low-level read() and write() functions. -- @cstyle instance module "nixio.UnifiedIO" --- Test whether the I/O-Descriptor is a socket. -- @class function -- @name UnifiedIO.is_socket -- @return boolean --- Test whether the I/O-Descriptor is a TLS socket. -- @class function -- @name UnifiedIO.is_tls_socket -- @return boolean --- Test whether the I/O-Descriptor is a file. -- @class function -- @name UnifiedIO.is_file -- @return boolean --- Read a block of data and wait until all data is available. -- @class function -- @name UnifiedIO.readall -- @usage This function uses the low-level read function of the descriptor. -- @usage If the length parameter is omitted, this function returns all data -- that can be read before an end-of-file, end-of-stream, connection shutdown -- or similar happens. -- @usage If the descriptor is non-blocking this function may fail with EAGAIN. -- @param length Bytes to read (optional) -- @return data that was successfully read if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return data that was successfully read even if an error occurred --- Write a block of data and wait until all data is written. -- @class function -- @name UnifiedIO.writeall -- @usage This function uses the low-level write function of the descriptor. -- @usage If the descriptor is non-blocking this function may fail with EAGAIN. -- @param block Bytes to write -- @return bytes that were successfully written if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occurred --- Create a line-based iterator. -- Lines may end with either \n or \r\n, these control chars are not included -- in the return value. -- @class function -- @name UnifiedIO.linesource -- @usage This function uses the low-level read function of the descriptor. -- @usage <strong>Note:</strong> This function uses an internal buffer to read -- ahead. Do NOT mix calls to read(all) and the returned iterator. If you want -- to stop reading line-based and want to use the read(all) functions instead -- you can pass "true" to the iterator which will flush the buffer -- and return the bufferd data. -- @usage If the limit parameter is omitted, this function uses the nixio -- buffersize (8192B by default). -- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 source. -- @param limit Line limit -- @return Line-based Iterator --- Create a block-based iterator. -- @class function -- @name UnifiedIO.blocksource -- @usage This function uses the low-level read function of the descriptor. -- @usage The blocksize given is only advisory and to be seen as an upper limit, -- if an underlying read returns less bytes the chunk is nevertheless returned. -- @usage If the limit parameter is omitted, the iterator returns data -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage The iterator will not buffer so it is safe to mix with calls to read. -- @usage If the descriptor is non-blocking the iterator may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 source. -- @param blocksize Advisory blocksize (optional) -- @param limit Amount of data to consume (optional) -- @return Block-based Iterator --- Create a sink. -- This sink will simply write all data that it receives and optionally -- close the descriptor afterwards. -- @class function -- @name UnifiedIO.sink -- @usage This function uses the writeall function of the descriptor. -- @usage If the descriptor is non-blocking the sink may fail with EAGAIN. -- @usage The iterator can be used as an LTN12 sink. -- @param close_when_done (optional, boolean) -- @return Sink --- Copy data from the current descriptor to another one. -- @class function -- @name UnifiedIO.copy -- @usage This function uses the blocksource function of the source descriptor -- and the sink function of the target descriptor. -- @usage If the limit parameter is omitted, data is copied -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage If the descriptor is non-blocking the function may fail with EAGAIN. -- @param fdout Target Descriptor -- @param size Bytes to copy (optional) -- @return bytes that were successfully written if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occurred --- Copy data from the current descriptor to another one using kernel-space -- copying if possible. -- @class function -- @name UnifiedIO.copyz -- @usage This function uses the sendfile() syscall to copy the data or the -- blocksource function of the source descriptor and the sink function -- of the target descriptor as a fallback mechanism. -- @usage If the limit parameter is omitted, data is copied -- until an end-of-file, end-of-stream, connection shutdown or similar happens. -- @usage If the descriptor is non-blocking the function may fail with EAGAIN. -- @param fdout Target Descriptor -- @param size Bytes to copy (optional) -- @return bytes that were successfully written if no error occurred -- @return - reserved for error code - -- @return - reserved for error message - -- @return bytes that were successfully written even if an error occurred --- Close the descriptor. -- @class function -- @name UnifiedIO.close -- @usage If the descriptor is a TLS-socket the underlying descriptor is -- closed without touching the TLS connection. -- @return true
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/dialogs/Birther.lua
1
59423
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Dialog = require "engine.ui.Dialog" local Birther = require "engine.Birther" local List = require "engine.ui.List" local TreeList = require "engine.ui.TreeList" local Button = require "engine.ui.Button" local Dropdown = require "engine.ui.Dropdown" local Textbox = require "engine.ui.Textbox" local Checkbox = require "engine.ui.Checkbox" local Textzone = require "engine.ui.Textzone" local ImageList = require "engine.ui.ImageList" local TextzoneList = require "engine.ui.TextzoneList" local Separator = require "engine.ui.Separator" local NameGenerator = require "engine.NameGenerator" local NameGenerator2 = require "engine.NameGenerator2" local Savefile = require "engine.Savefile" local Module = require "engine.Module" local Tiles = require "engine.Tiles" local Particles = require "engine.Particles" local CharacterVaultSave = require "engine.CharacterVaultSave" local Object = require "mod.class.Object" local OptionTree = require "mod.dialogs.OptionTree" module(..., package.seeall, class.inherit(Birther)) --- Instanciates a birther for the given actor function _M:init(title, actor, order, at_end, quickbirth, w, h) self.quickbirth = quickbirth self.actor = actor:cloneFull() self.actor_base = actor self.order = order self.at_end = at_end self.selected_cosmetic_unlocks = {} self.tiles = Tiles.new(64, 64, nil, nil, true, nil) Dialog.init(self, title and title or "Character Creation", w or 600, h or 400) self.obj_list = Object:loadList("/data/general/objects/objects.lua") self.obj_list_by_name = {} for i, e in ipairs(self.obj_list) do if e.name and (e.rarity or e.define_as) then self.obj_list_by_name[e.name] = e end end self.descriptors = {} self.descriptors_by_type = {} self.c_ok = Button.new{text=" Play! ", fct=function() self:atEnd("created") end} self.c_random = Button.new{text="Random!", fct=function() self:randomBirth() end} self.c_premade = Button.new{text="Load premade", fct=function() self:loadPremadeUI() end} self.c_tile = Button.new{text="Select custom tile", fct=function() self:selectTile() end} self.c_cancel = Button.new{text="Cancel", fct=function() self:atEnd("quit") end} self.c_tut = Button.new{text="Tutorial", fct=function() self:tutorial() end} self.c_options = Button.new{text="Customize", fct=function() self:customizeOptions() end} self.c_options.hide = true self.c_extra_options = Button.new{text="Extra Options", fct=function() self:extraOptions() end} self.c_extra_options.hide = #game.extra_birth_option_defs == 0 self.c_name = Textbox.new{title="Name: ", text=(not config.settings.cheat and game.player_name == "player") and "" or game.player_name, chars=30, max_len=50, fct=function() if config.settings.cheat then self:makeDefault() end end, on_change=function() self:setDescriptor() end, on_mouse = function(button) if button == "right" then self:randomName() end end} self.c_female = Checkbox.new{title="Female", default=true, fct=function() end, on_change=function(s) self.c_male.checked = not s self:setDescriptor("sex", s and "Female" or "Male") end } self.c_male = Checkbox.new{title="Male", default=false, fct=function() end, on_change=function(s) self.c_female.checked = not s self:setDescriptor("sex", s and "Male" or "Female") end } self:generateCampaigns() self.c_campaign_text = Textzone.new{auto_width=true, auto_height=true, text="Campaign: "} self.c_campaign = Dropdown.new{width=400, fct=function(item) self:campaignUse(item) end, on_select=function(item) self:updateDesc(item) end, list=self.all_campaigns, nb_items=#self.all_campaigns} self:generateDifficulties() self.c_difficulty_text = Textzone.new{auto_width=true, auto_height=true, text="Difficulty: "} self.c_difficulty = Dropdown.new{width=100, fct=function(item) self:difficultyUse(item) end, on_select=function(item) self:updateDesc(item) end, list=self.all_difficulties, nb_items=#self.all_difficulties} self:generatePermadeaths() self.c_permadeath_text = Textzone.new{auto_width=true, auto_height=true, text="Permadeath: "} self.c_permadeath = Dropdown.new{width=150, fct=function(item) self:permadeathUse(item) end, on_select=function(item) self:updateDesc(item) end, list=self.all_permadeaths, nb_items=#self.all_permadeaths} self.c_desc = TextzoneList.new{width=math.floor(self.iw / 3 - 10), height=self.ih - self.c_female.h - self.c_ok.h - self.c_difficulty.h - self.c_campaign.h - 10, scrollbar=true, pingpong=20, no_color_bleed=true} self:setDescriptor("base", "base") self:setDescriptor("world", self.default_campaign) self:setDescriptor("difficulty", self.default_difficulty) self:setDescriptor("permadeath", self.default_permadeath) self:setDescriptor("sex", "Female") self:generateRaces() self.c_race = TreeList.new{width=math.floor(self.iw / 3 - 10), height=self.ih - self.c_female.h - self.c_ok.h - (self.c_extra_options.hide and 0 or self.c_extra_options.h) - self.c_difficulty.h - self.c_campaign.h - 10, scrollbar=true, columns={ {width=100, display_prop="name"}, }, tree=self.all_races, fct=function(item, sel, v) self:raceUse(item, sel, v) end, select=function(item, sel) self:updateDesc(item) end, on_expand=function(item) end, on_drawitem=function(item) end, } self:generateClasses() self.c_class = TreeList.new{width=math.floor(self.iw / 3 - 10), height=self.ih - self.c_female.h - self.c_ok.h - self.c_difficulty.h - self.c_campaign.h - 10, scrollbar=true, columns={ {width=100, display_prop="name"}, }, tree=self.all_classes, fct=function(item, sel, v) self:classUse(item, sel, v) end, select=function(item, sel) self:updateDesc(item) end, on_expand=function(item) end, on_drawitem=function(item) end, } self.cur_order = 1 self.sel = 1 self:loadUI{ -- First line {left=0, top=0, ui=self.c_name}, {left=self.c_name, top=0, ui=self.c_female}, {left=self.c_female, top=0, ui=self.c_male}, -- Second line {left=0, top=self.c_name, ui=self.c_campaign_text}, {left=self.c_campaign_text, top=self.c_name, ui=self.c_campaign}, -- Third line {left=0, top=self.c_campaign, ui=self.c_difficulty_text}, {left=self.c_difficulty_text, top=self.c_campaign, ui=self.c_difficulty}, {left=self.c_difficulty, top=self.c_campaign, ui=self.c_permadeath_text}, {left=self.c_permadeath_text, top=self.c_campaign, ui=self.c_permadeath}, {right=0, top=self.c_name, ui=self.c_tut}, -- Lists {left=0, top=self.c_permadeath, ui=self.c_race}, {left=self.c_race, top=self.c_permadeath, ui=self.c_class}, {right=0, top=self.c_permadeath, ui=self.c_desc}, -- Buttons {left=0, bottom=0, ui=self.c_ok, hidden=true}, {left=self.c_ok, bottom=0, ui=self.c_random}, {left=self.c_random, bottom=0, ui=self.c_premade}, {left=self.c_premade, bottom=0, ui=self.c_tile}, {left=self.c_tile, bottom=0, ui=self.c_options}, {right=0, bottom=0, ui=self.c_cancel}, {left=0, bottom=self.c_ok, ui=self.c_extra_options}, } self:setupUI() if self.descriptors_by_type.difficulty == "Tutorial" then self:permadeathUse(self.all_permadeaths[1], 1) self:raceUse(self.all_races[1], 1) self:raceUse(self.all_races[1].nodes[1], 2) self:classUse(self.all_classes[1], 1) self:classUse(self.all_classes[1].nodes[1], 2) end for i, item in ipairs(self.c_campaign.c_list.list) do if self.default_campaign == item.id then self.c_campaign.c_list.sel = i break end end for i, item in ipairs(self.c_difficulty.c_list.list) do if self.default_difficulty == item.id then self.c_difficulty.c_list.sel = i break end end for i, item in ipairs(self.c_permadeath.c_list.list) do if self.default_permadeath == item.id then self.c_permadeath.c_list.sel = i break end end if config.settings.tome.default_birth and config.settings.tome.default_birth.sex then self.c_female.checked = config.settings.tome.default_birth.sex == "Female" self.c_male.checked = config.settings.tome.default_birth.sex ~= "Female" self:setDescriptor("sex", self.c_female.checked and "Female" or "Male") end self:setFocus(self.c_campaign) self:setFocus(self.c_name) if not profile.mod.allow_build.tutorial_done then self:setFocus(self.c_tut) self.c_tut.glow = 0.70 end end function _M:checkNew(fct) local savename = self.c_name.text:gsub("[^a-zA-Z0-9_-.]", "_") if fs.exists(("/save/%s/game.teag"):format(savename)) then Dialog:yesnoPopup("Overwrite character?", "There is already a character with this name, do you want to overwrite it?", function(ret) if not ret then fct() end end, "No", "Yes") else fct() end end function _M:applyingDescriptor(i, d) if d.unlockable_talents_types then for t, v in pairs(d.unlockable_talents_types) do if profile.mod.allow_build[v[3]] then local mastery if type(v) == "table" then v, mastery = v[1], v[2] else v, mastery = v, 0 end self.actor:learnTalentType(t, v) self.actor.talents_types_mastery[t] = (self.actor.talents_types_mastery[t] or 0) + mastery end end end if d.party_copy then local copy = table.clone(d.party_copy, true) -- Append array part while #copy > 0 do local f = table.remove(copy) table.insert(game.party, f) end -- Copy normal data table.merge(game.party, copy, true) end self:applyGameState(d) end function _M:applyGameState(d) if d.game_state then local copy = table.clone(d.game_state, true) -- Append array part while #copy > 0 do local f = table.remove(copy) table.insert(game.state.birth, f) end -- Copy normal data table.merge(game.state.birth, copy, true) end if d.game_state_execute then d.game_state_execute() end end function _M:atEnd(v) if v == "created" and not self.ui_by_ui[self.c_ok].hidden then self:checkNew(function() local ps = self.actor:getParticlesList() for i, p in ipairs(ps) do self.actor:removeParticles(p) end self.actor:defineDisplayCallback() self.actor:removeAllMOs() game:unregisterDialog(self) self.actor = self.actor_base if self.has_custom_tile then self:setTile(self.has_custom_tile.f, self.has_custom_tile.w, self.has_custom_tile.h, true) self.actor.has_custom_tile = self.has_custom_tile.f end self:resetAttachementSpots() -- Prevent the game from auto-assigning talents if necessary. if (not config.settings.tome.autoassign_talents_on_birth) and not game.state.birth.always_learn_birth_talents then for _, d in pairs(self.descriptors) do local unlearned_talents = { } if (d.talents ~= nil and (d.type == "race" or d.type == "subrace" or d.type == "class" or d.type == "subclass")) then for t_id, t_level in pairs(d.talents) do local talent = self.actor:getTalentFromId(t_id) if (talent ~= nil and not talent.no_unlearn_last) then --[[ Award talent points based on the highest available level of the talent This is in the potential case of a player selecting a race with two points in phase door and Archmage as his class. Archmage starts with one point in phase door. Cases like this may result in a conflict of what the player might expect to get back in points. The highest amount of points is always awarded to the player (two, in this case). ]] if (unlearned_talents[talent] == nil) then unlearned_talents[talent] = t_level elseif (unlearned_talents[talent] < t_level) then unlearned_talents[talent] = t_level end self.actor:learnPool(talent) print("[BIRTHER] Ignoring auto-assign for " .. t_id .. " (from " .. d.type .. " descriptor \"" .. d.name .. "\")") d.talents[t_id] = nil end end -- Give the player the appropriate amount of talent points for talent, t_level in pairs(unlearned_talents) do if (talent.generic == true) then self.actor.unused_generics = self.actor.unused_generics + t_level else self.actor.unused_talents = self.actor.unused_talents + t_level end end end end end self:apply() if self.has_custom_tile then self.actor.make_tile = nil self.actor.moddable_tile = nil end self:applyCosmeticActor(true) game:setPlayerName(self.c_name.text) local save = Savefile.new(game.save_name) save:delete() save:close() game:saveSettings("tome.default_birth", ("tome.default_birth = {permadeath=%q, difficulty=%q, sex=%q, campaign=%q}\n"):format(self.actor.descriptor.permadeath, self.actor.descriptor.difficulty, self.actor.descriptor.sex, self.actor.descriptor.world)) self.at_end(false) end) elseif v == "loaded" then self:checkNew(function() game:unregisterDialog(self) game:setPlayerName(self.c_name.text) for type, kind in pairs(game.player.descriptor) do local d = self:getBirthDescriptor(type, kind) if d then self:applyGameState(d) end end self.at_end(true) end) elseif v == "quit" then util.showMainMenu() end end --- Make a default character when using cheat mode, for easier testing function _M:makeDefault() self:setDescriptor("sex", "Female") self:setDescriptor("world", "Maj'Eyal") self:setDescriptor("difficulty", "Normal") self:setDescriptor("permadeath", "Adventure") self:setDescriptor("race", "Human") self:setDescriptor("subrace", "Cornac") self:setDescriptor("class", "Warrior") self:setDescriptor("subclass", "Berserker") __module_extra_info.no_birth_popup = true self:atEnd("created") end --- Run one of the tutorials function _M:tutorial() local run = function(t) self:setDescriptor("sex", "Female") self:setDescriptor("world", "Maj'Eyal") self:setDescriptor("difficulty", "Tutorial") self:setDescriptor("permadeath", "Adventure") self:setDescriptor("race", "Tutorial Human") self:setDescriptor("subrace", "Tutorial "..t) self:setDescriptor("class", "Tutorial Adventurer") self:setDescriptor("subclass", "Tutorial Adventurer") self:randomName() self:atEnd("created") end local d = Dialog.new("Tutorials", 280, 100) local basic = Button.new{text="Basic Gameplay (recommended)", fct=function() run("Basic") d.key:triggerVirtual("EXIT") end} -- local stats = Button.new{text="Stats and effects (advanced players)", fct=function() run("Stats") d.key:triggerVirtual("EXIT") end} local cancel = Button.new{text="Cancel", fct=function() d.key:triggerVirtual("EXIT") end} local sep = Separator.new{dir="vertical", size=230} d:loadUI{ {hcenter=0, top=0, ui=basic}, -- {hcenter=0, top=basic.h, ui=stats}, {hcenter=0, bottom=cancel.h, ui=sep}, {hcenter=0, bottom=0, ui=cancel}, } d:setupUI(false, true) d.key:addBind("EXIT", function() game:unregisterDialog(d) end) game:registerDialog(d) end function _M:randomBirth() -- Random sex local sex = rng.percent(50) self.c_male.checked = sex self.c_female.checked = not sex self:setDescriptor("sex", sex and "Male" or "Female") self.descriptors_by_type.race = nil self.descriptors_by_type.subrace = nil self.descriptors_by_type.class = nil self.descriptors_by_type.subclass = nil --[[ -- Random campaign local camp, camp_id = nil repeat camp, camp_id = rng.table(self.c_campaign.c_list.list) until not camp.locked self.c_campaign.c_list.sel = camp_id self:campaignUse(camp) -- Random difficulty local diff, diff_id = nil repeat diff, diff_id = rng.table(self.c_difficulty.c_list.list) until diff.name ~= "Tutorial" and not diff.locked self.c_difficulty.c_list.sel = diff_id self:difficultyUse(diff) --]] -- Random race local race, race_id = nil repeat race, race_id = rng.table(self.all_races) until not race.locked self:raceUse(race) -- Random subrace local subrace, subrace_id = nil repeat subrace, subrace_id = rng.table(self.all_races[race_id].nodes) until not subrace.locked self:raceUse(subrace) -- Random class local class, class_id = nil repeat class, class_id = rng.table(self.all_classes) until not class or not class.locked self:classUse(class) -- Random subclass if class then local subclass, subclass_id = nil repeat subclass, subclass_id = rng.table(self.all_classes[class_id].nodes) until not subclass.locked self:classUse(subclass) end self:randomName() end function _M:randomName() if not self.descriptors_by_type.sex or not self.descriptors_by_type.subrace then return end local sex_def = self.birth_descriptor_def.sex[self.descriptors_by_type.sex] local race_def = self.birth_descriptor_def.subrace[self.descriptors_by_type.subrace] if race_def.copy.random_name_def then local namegen = NameGenerator2.new("/data/languages/names/"..race_def.copy.random_name_def:gsub("#sex#", sex_def.copy.female and "female" or "male")..".txt") self.c_name:setText(namegen:generate(nil, race_def.copy.random_name_min_syllables, race_def.copy.random_name_max_syllables)) else local namegen = NameGenerator.new((not sex_def.copy.female) and { phonemesVocals = "a, e, i, o, u, y", phonemesConsonants = "b, c, ch, ck, cz, d, dh, f, g, gh, h, j, k, kh, l, m, n, p, ph, q, r, rh, s, sh, t, th, ts, tz, v, w, x, z, zh", syllablesStart = "Aer, Al, Am, An, Ar, Arm, Arth, B, Bal, Bar, Be, Bel, Ber, Bok, Bor, Bran, Breg, Bren, Brod, Cam, Chal, Cham, Ch, Cuth, Dag, Daim, Dair, Del, Dr, Dur, Duv, Ear, Elen, Er, Erel, Erem, Fal, Ful, Gal, G, Get, Gil, Gor, Grin, Gun, H, Hal, Han, Har, Hath, Hett, Hur, Iss, Khel, K, Kor, Lel, Lor, M, Mal, Man, Mard, N, Ol, Radh, Rag, Relg, Rh, Run, Sam, Tarr, T, Tor, Tul, Tur, Ul, Ulf, Unr, Ur, Urth, Yar, Z, Zan, Zer", syllablesMiddle = "de, do, dra, du, duna, ga, go, hara, kaltho, la, latha, le, ma, nari, ra, re, rego, ro, rodda, romi, rui, sa, to, ya, zila", syllablesEnd = "bar, bers, blek, chak, chik, dan, dar, das, dig, dil, din, dir, dor, dur, fang, fast, gar, gas, gen, gorn, grim, gund, had, hek, hell, hir, hor, kan, kath, khad, kor, lach, lar, ldil, ldir, leg, len, lin, mas, mnir, ndil, ndur, neg, nik, ntir, rab, rach, rain, rak, ran, rand, rath, rek, rig, rim, rin, rion, sin, sta, stir, sus, tar, thad, thel, tir, von, vor, yon, zor", rules = "$s$v$35m$10m$e", } or { phonemesVocals = "a, e, i, o, u, y", syllablesStart = "Ad, Aer, Ar, Bel, Bet, Beth, Ce'N, Cyr, Eilin, El, Em, Emel, G, Gl, Glor, Is, Isl, Iv, Lay, Lis, May, Ner, Pol, Por, Sal, Sil, Vel, Vor, X, Xan, Xer, Yv, Zub", syllablesMiddle = "bre, da, dhe, ga, lda, le, lra, mi, ra, ri, ria, re, se, ya", syllablesEnd = "ba, beth, da, kira, laith, lle, ma, mina, mira, na, nn, nne, nor, ra, rin, ssra, ta, th, tha, thra, tira, tta, vea, vena, we, wen, wyn", rules = "$s$v$35m$10m$e", }) self.c_name:setText(namegen:generate()) end end function _M:on_focus(id, ui) if self.focus_ui and self.focus_ui.ui == self.c_name then self.c_desc:switchItem(self.c_name, "This is the name of your character.\nRight mouse click to generate a random name based on race and sex.") elseif self.focus_ui and self.focus_ui.ui == self.c_female then self.c_desc:switchItem(self.c_female, self.birth_descriptor_def.sex.Female.desc) elseif self.focus_ui and self.focus_ui.ui == self.c_male then self.c_desc:switchItem(self.c_male, self.birth_descriptor_def.sex.Male.desc) elseif self.focus_ui and self.focus_ui.ui == self.c_campaign then local item = self.c_campaign.c_list.list[self.c_campaign.c_list.sel] self.c_desc:switchItem(item, item.desc) elseif self.focus_ui and self.focus_ui.ui == self.c_difficulty then local item = self.c_difficulty.c_list.list[self.c_difficulty.c_list.sel] self.c_desc:switchItem(item, item.desc) elseif self.focus_ui and self.focus_ui.ui == self.c_permadeath then local item = self.c_permadeath.c_list.list[self.c_permadeath.c_list.sel] self.c_desc:switchItem(item, item.desc) end end function _M:updateDesc(item) if item and item.desc then self.c_desc:switchItem(item, item.desc) end end function _M:campaignUse(item) if not item then return end if item.locked then self.c_campaign.c_list.sel = self.c_campaign.previous else self:setDescriptor("world", item.id) self:generateDifficulties() self:generatePermadeaths() self:generateRaces() self:generateClasses() end end function _M:difficultyUse(item) if not item then return end if item.locked then self.c_difficulty.c_list.sel = self.c_difficulty.previous else self:setDescriptor("difficulty", item.id) self:generatePermadeaths() self:generateRaces() self:generateRaces() self:generateClasses() end end function _M:permadeathUse(item) if not item then return end if item.locked then self.c_permadeath.c_list.sel = self.c_permadeath.previous if item.locked_select then item.locked_select(self) end else self:setDescriptor("permadeath", item.id) self:generateRaces() self:generateClasses() end end function _M:raceUse(item, sel, v) if not item then return end if item.nodes then for i, item in ipairs(self.c_race.tree) do if item.shown then self.c_race:treeExpand(false, item) end end self.c_race:treeExpand(nil, item) elseif not item.locked and item.basename then if self.sel_race then self.sel_race.name = self.sel_race.basename self.c_race:drawItem(self.sel_race) end self:setDescriptor("race", item.pid) self:setDescriptor("subrace", item.id) self.sel_race = item self.sel_race.name = tstring{{"font","bold"}, {"color","LIGHT_GREEN"}, self.sel_race.basename:toString(), {"font","normal"}} self.c_race:drawItem(item) self:generateClasses() end end function _M:classUse(item, sel, v) if not item then return end if item.nodes then for i, item in ipairs(self.c_class.tree) do if item.shown then self.c_class:treeExpand(false, item) end end self.c_class:treeExpand(nil, item) elseif not item.locked and item.basename then if self.sel_class then self.sel_class.name = self.sel_class.basename self.c_class:drawItem(self.sel_class) end self:setDescriptor("class", item.pid) self:setDescriptor("subclass", item.id) self.sel_class = item self.sel_class.name = tstring{{"font","bold"}, {"color","LIGHT_GREEN"}, self.sel_class.basename:toString(), {"font","normal"}} self.c_class:drawItem(item) end end function _M:updateDescriptors() self.descriptors = {} table.insert(self.descriptors, self.birth_descriptor_def.base[self.descriptors_by_type.base]) table.insert(self.descriptors, self.birth_descriptor_def.world[self.descriptors_by_type.world]) table.insert(self.descriptors, self.birth_descriptor_def.difficulty[self.descriptors_by_type.difficulty]) table.insert(self.descriptors, self.birth_descriptor_def.permadeath[self.descriptors_by_type.permadeath]) table.insert(self.descriptors, self.birth_descriptor_def.sex[self.descriptors_by_type.sex]) if self.descriptors_by_type.subrace then table.insert(self.descriptors, self.birth_descriptor_def.race[self.descriptors_by_type.race]) table.insert(self.descriptors, self.birth_descriptor_def.subrace[self.descriptors_by_type.subrace]) end if self.descriptors_by_type.subclass then table.insert(self.descriptors, self.birth_descriptor_def.class[self.descriptors_by_type.class]) table.insert(self.descriptors, self.birth_descriptor_def.subclass[self.descriptors_by_type.subclass]) end self.cosmetic_unlocks = {} for _, d in ipairs(self.descriptors) do if d.cosmetic_unlock then for u, datas in pairs(d.cosmetic_unlock) do for _, data in ipairs(datas) do if profile.mod.allow_build[u] and (not data.check or data.check(self)) then table.insert(self.cosmetic_unlocks, data) end end end end end table.sort(self.cosmetic_unlocks, function(a, b) return a.name < b.name end) self.c_options.hide = #self.cosmetic_unlocks == 0 end function _M:isDescriptorSet(key, val) return self.descriptors_by_type[key] == val end function _M:setDescriptor(key, val) if key then self.descriptors_by_type[key] = val print("[BIRTHER] set descriptor", key, val) end self:updateDescriptors() self:setTile() local ok = self.c_name.text:len() >= 2 for i, o in ipairs(self.order) do if not self.descriptors_by_type[o] then ok = false print("Missing ", o) break end end self:toggleDisplay(self.c_ok, ok) end function _M:isDescriptorAllowed(d, ignore_type) self:updateDescriptors() if type(ignore_type) == "string" then ignore_type = {[ignore_type] = true} end ignore_type = ignore_type or {} local allowed = true local type = d.type print("[BIRTHER] checking allowance for ", d.name, d.type, "::", table.serialize(ignore_type, nil, true)) for j, od in ipairs(self.descriptors) do if od.descriptor_choices and od.descriptor_choices[type] and not ignore_type[type] then local what = util.getval(od.descriptor_choices[type][d.name], self) or util.getval(od.descriptor_choices[type].__ALL__, self) if what and what == "allow" then allowed = true elseif what and what == "nolore" then allowed = "nolore" elseif what and what == "allow-nochange" then if not allowed then allowed = true end elseif what and (what == "never" or what == "disallow") then allowed = false elseif what and what == "forbid" then allowed = nil end print("[BIRTHER] test against ", od.name, "=>", what, allowed) if allowed == nil then break end end end if d.special_check and not d.special_check(self) then return nil end -- Check it is allowed return allowed and not d.never_show end function _M:getLock(d) if not d.locked then return false end local ret = d.locked(self) if ret == "hide" then return "hide" end return not ret end function _M:generateCampaigns() local locktext = "\n\n#GOLD#This is a locked birth option. Performing certain actions and completing certain quests will make locked campaigns, races and classes permanently available." local list = {} for i, d in ipairs(self.birth_descriptor_def.world) do if self:isDescriptorAllowed(d, {difficulty=true, permadeath=true, race=true, subrace=true, class=true, subclass=true}) then local locked = self:getLock(d) if locked == true then list[#list+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}:toString(), id=d.name, locked=true, desc=util.getval(d.locked_desc, self)..locktext } elseif locked == false then local desc = d.desc if type(desc) == "table" then desc = table.concat(d.desc, "\n") end list[#list+1] = { name = tstring{d.display_name}:toString(), id=d.name, desc=desc } if util.getval(d.selection_default) then self.default_campaign = d.name end end end end self.all_campaigns = list if not self.default_campaign then self.default_campaign = list[1].id end end function _M:generateDifficulties() local locktext = "\n\n#GOLD#This is a locked birth option. Performing certain actions and completing certain quests will make locked campaigns, races and classes permanently available." local list = {} local oldsel = nil if self.c_difficulty then oldsel = self.c_difficulty.c_list.list[self.c_difficulty.c_list.sel].id end for i, d in ipairs(self.birth_descriptor_def.difficulty) do if self:isDescriptorAllowed(d, {permadeath=true, race=true, subrace=true, class=true, subclass=true}) then local locked = self:getLock(d) if locked == true then list[#list+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}:toString(), id=d.name, locked=true, desc=util.getval(d.locked_desc, self)..locktext } elseif locked == false then local desc = d.desc if type(desc) == "table" then desc = table.concat(d.desc, "\n") end list[#list+1] = { name = tstring{d.display_name}:toString(), id=d.name, desc=desc } if oldsel == d.name then oldsel = #list end if util.getval(d.selection_default) then self.default_difficulty = d.name end end end end self.all_difficulties = list if self.c_difficulty then self.c_difficulty.c_list.list = self.all_difficulties self.c_difficulty.c_list:generate() if type(oldsel) == "number" then self.c_difficulty.c_list.sel = oldsel end end end function _M:generatePermadeaths() local locktext = "\n\n#GOLD#This is a locked birth option. Performing certain actions and completing certain quests will make locked campaigns, races and classes permanently available." local list = {} local oldsel = nil if self.c_permadeath then oldsel = self.c_permadeath.c_list.list[self.c_permadeath.c_list.sel].id end for i, d in ipairs(self.birth_descriptor_def.permadeath) do if self:isDescriptorAllowed(d, {race=true, subrace=true, class=true, subclass=true}) then local locked = self:getLock(d) if locked == true then list[#list+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}:toString(), id=d.name, locked=true, desc=util.getval(d.locked_desc, self)..locktext, locked_select=d.locked_select } elseif locked == false then local desc = d.desc if type(desc) == "table" then desc = table.concat(d.desc, "\n") end list[#list+1] = { name = tstring{d.display_name}:toString(), id=d.name, desc=desc } if oldsel == d.name then oldsel = #list end if util.getval(d.selection_default) then self.default_permadeath = d.name end end end end self.all_permadeaths = list if self.c_permadeath then self.c_permadeath.c_list.list = self.all_permadeaths self.c_permadeath.c_list:generate() if type(oldsel) == "number" then self.c_permadeath.c_list.sel = oldsel end end end function _M:generateRaces() local locktext = "\n\n#GOLD#This is a locked birth option. Performing certain actions and completing certain quests will make locked campaigns, races and classes permanently available." local oldtree = {} for i, t in ipairs(self.all_races or {}) do oldtree[t.id] = t.shown end local tree = {} local newsel = nil for i, d in ipairs(self.birth_descriptor_def.race) do if self:isDescriptorAllowed(d, {class=true, subclass=true}) then local nodes = {} for si, sd in ipairs(self.birth_descriptor_def.subrace) do if d.descriptor_choices.subrace[sd.name] == "allow" then local locked = self:getLock(sd) if locked == true then nodes[#nodes+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}, id=sd.name, pid=d.name, locked=true, desc=util.getval(sd.locked_desc, self)..locktext } elseif locked == false then local desc = sd.desc if type(desc) == "table" then desc = table.concat(sd.desc, "\n") end nodes[#nodes+1] = { name = sd.display_name, basename = sd.display_name, id=sd.name, pid=d.name, desc=desc } if self.sel_race and self.sel_race.id == sd.name then newsel = nodes[#nodes] end end end end local locked = self:getLock(d) if locked == true then tree[#tree+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}, id=d.name, shown = oldtree[d.name], nodes = nodes, locked=true, desc=util.getval(d.locked_desc, self)..locktext } elseif locked == false then local desc = d.desc if type(desc) == "table" then desc = table.concat(d.desc, "\n") end tree[#tree+1] = { name = tstring{{"font", "italic"}, {"color", "LIGHT_SLATE"}, d.display_name, {"font", "normal"}}, id=d.name, shown = oldtree[d.name], nodes = nodes, desc=desc } end end end self.all_races = tree if self.c_race then self.c_race.tree = self.all_races self.c_race:generate() if newsel then self:raceUse(newsel) else self.sel_race = nil self:setDescriptor("race", nil) self:setDescriptor("subrace", nil) end if self.descriptors_by_type.difficulty == "Tutorial" then self:raceUse(tree[1], 1) self:raceUse(tree[1].nodes[1], 2) end end end function _M:generateClasses() local locktext = "\n\n#GOLD#This is a locked birth option. Performing certain actions and completing certain quests will make locked campaigns, races and classes permanently available." local oldtree = {} for i, t in ipairs(self.all_classes or {}) do oldtree[t.id] = t.shown end local tree = {} local newsel = nil for i, d in ipairs(self.birth_descriptor_def.class) do if self:isDescriptorAllowed(d, {subclass=true}) then local nodes = {} for si, sd in ipairs(self.birth_descriptor_def.subclass) do if (d.descriptor_choices.subclass[sd.name] == "allow" or d.descriptor_choices.subclass[sd.name] == "allow-nochange" or d.descriptor_choices.subclass[sd.name] == "nolore") and self:isDescriptorAllowed(sd, {subclass=true, class=true}) then local locked = self:getLock(sd) if locked == true then nodes[#nodes+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}, id=sd.name, pid=d.name, locked=true, desc=util.getval(sd.locked_desc, self)..locktext } elseif locked == false then local old = self.descriptors_by_type.subclass self.descriptors_by_type.subclass = nil local how = self:isDescriptorAllowed(sd, {class=true}) self.descriptors_by_type.subclass = old local desc = sd.desc if type(desc) == "table" then desc = table.concat(sd.desc, "\n") end if how == "nolore" and self.descriptors_by_type.subrace then desc = "#CRIMSON#Playing this class with the race you selected does not make much sense lore-wise. You can still do it but might miss on some special quests/...#WHITE#\n" .. desc end nodes[#nodes+1] = { name = sd.display_name, basename=sd.display_name, id=sd.name, pid=d.name, desc=desc, def=sd } if self.sel_class and self.sel_class.id == sd.name then newsel = nodes[#nodes] end end end end local locked = self:getLock(d) if locked == true then tree[#tree+1] = { name = tstring{{"font", "italic"}, {"color", "GREY"}, "-- locked --", {"font", "normal"}}, id=d.name, shown=oldtree[d.name], nodes = nodes, locked=true, desc=util.getval(d.locked_desc, self)..locktext } elseif locked == false then local desc = d.desc if type(desc) == "table" then desc = table.concat(d.desc, "\n") end tree[#tree+1] = { name = tstring{{"font", "italic"}, {"color", "LIGHT_SLATE"}, d.display_name, {"font", "normal"}}, id=d.name, shown=oldtree[d.name], nodes = nodes, desc=desc } end end end self.all_classes = tree if self.c_class then self.c_class.tree = self.all_classes self.c_class:generate() if newsel then self:classUse(newsel) else self.sel_class = nil self:setDescriptor("class", nil) self:setDescriptor("subclass", nil) end if self.descriptors_by_type.difficulty == "Tutorial" then self:classUse(tree[1], 1) self:classUse(tree[1].nodes[1], 2) elseif tree[1].id == "None" then self:classUse(tree[1], 1) self:classUse(tree[1].nodes[1], 2) end end end function _M:loadPremade(pm) local fallback = pm.force_fallback -- Load the entities directly if not fallback and pm.module_version and pm.module_version[1] == game.__mod_info.version[1] and pm.module_version[2] == game.__mod_info.version[2] and pm.module_version[3] == game.__mod_info.version[3] then savefile_pipe:ignoreSaveToken(true) local qb = savefile_pipe:doLoad(pm.short_name, "entity", "engine.CharacterVaultSave", "character") savefile_pipe:ignoreSaveToken(false) -- Load the player directly if qb then game.party = qb game.player = nil game.party:setPlayer(1, true) self.c_name:setText(game.player.name) self:atEnd("loaded") else fallback = true end else fallback = true end -- Fill in the descriptors and validate if fallback then local ok = 0 -- Name self.c_name:setText(pm.short_name) -- Sex self.c_male.checked = pm.descriptors.sex == "Male" self.c_female.checked = pm.descriptors.sex == "Female" self:setDescriptor("sex", pm.descriptors.sex and "Male" or "Female") -- Campaign for i, item in ipairs(self.all_campaigns) do if not item.locked and item.id == pm.descriptors.world then self:campaignUse(item) self.c_campaign.c_list.sel = i ok = ok + 1 break end end -- Difficulty for i, item in ipairs(self.all_difficulties) do if not item.locked and item.id == pm.descriptors.difficulty then self:difficultyUse(item) self.c_difficulty.c_list.sel = i ok = ok + 1 break end end -- Permadeath for i, item in ipairs(self.all_permadeaths) do if not item.locked and item.id == pm.descriptors.permadeath then self:permadeathUse(item) self.c_permadeath.c_list.sel = i ok = ok + 1 break end end -- Race for i, pitem in ipairs(self.all_races) do for j, item in ipairs(pitem.nodes) do if not item.locked and item.id == pm.descriptors.subrace and pitem.id == pm.descriptors.race then self:raceUse(pitem) self:raceUse(item) ok = ok + 1 break end end end -- Class for i, pitem in ipairs(self.all_classes) do for j, item in ipairs(pitem.nodes) do if not item.locked and item.id == pm.descriptors.subclass and pitem.id == pm.descriptors.class then self:classUse(pitem) self:classUse(item) ok = ok + 1 break end end end if ok == 4 then self:atEnd("created") end end end function _M:loadPremadeUI() local lss = Module:listVaultSavesForCurrent() local d = Dialog.new("Characters Vault", 600, 550) local sel = nil local sep = Separator.new{dir="horizontal", size=400} local desc = TextzoneList.new{width=220, height=400} local list list = List.new{width=350, list=lss, height=400, fct=function(item) local oldsel, oldscroll = list.sel, list.scroll if sel == item then self:loadPremade(sel) game:unregisterDialog(d) end if sel then sel.color = nil end item.color = colors.simple(colors.LIGHT_GREEN) sel = item list:generate() list.sel, list.scroll = oldsel, oldscroll end, select=function(item) desc:switchItem(item, item.description) end } local load = Button.new{text=" Load ", fct=function() if sel then self:loadPremade(sel) game:unregisterDialog(d) end end} local del = Button.new{text="Delete", fct=function() if sel then self:yesnoPopup(sel.name, "Really delete premade: "..sel.name, function(ret) if ret then local vault = CharacterVaultSave.new(sel.short_name) vault:delete() vault:close() lss = Module:listVaultSavesForCurrent() list.list = lss list:generate() sel = nil end end) end end} d:loadUI{ {left=0, top=0, ui=list}, {left=list, top=0, ui=sep}, {right=0, top=0, ui=desc}, {left=0, bottom=0, ui=load}, {right=0, bottom=0, ui=del}, } d:setupUI(true, true) d.key:addBind("EXIT", function() game:unregisterDialog(d) end) game:registerDialog(d) end -- Disable stuff from the base Birther function _M:updateList() end function _M:selectType(type) end function _M:on_register() if __module_extra_info.auto_quickbirth then local qb_short_name = __module_extra_info.auto_quickbirth:gsub("[^a-zA-Z0-9_-.]", "_") local lss = Module:listVaultSavesForCurrent() for i, pm in ipairs(lss) do if pm.short_name == qb_short_name then self:loadPremade(pm) break end end end end -- Display the player tile function _M:innerDisplay(x, y, nb_keyframes) if self.actor.image then self.actor:toScreen(self.tiles, x + self.iw - 64, y, 64, 64) elseif self.actor.image and self.actor.add_mos then self.actor:toScreen(self.tiles, x + self.iw - 64, y - 64, 128, 64) end end --- Fake a body & starting equipment function _M:fakeEquip(v) if not v then self.actor.body = nil self.actor.inven = {} else self.actor.inven = {} local fake_body = { INVEN = 1000, QS_MAINHAND = 1, QS_OFFHAND = 1, MAINHAND = 1, OFFHAND = 1, FINGER = 2, NECK = 1, LITE = 1, BODY = 1, HEAD = 1, CLOAK = 1, HANDS = 1, BELT = 1, FEET = 1, TOOL = 1, QUIVER = 1 } self.actor.body = fake_body self.actor:initBody() local c = self.birth_descriptor_def.class[self.descriptors_by_type.class or "Warrior"] local sc = self.birth_descriptor_def.subclass[self.descriptors_by_type.subclass or "Berserker"] local function apply_equip(r) for i, f in ipairs(r[1]) do local o = self.obj_list_by_name[f.name] if o and o.slot then o = o:clone() o:resolve() o:resolve(nil, true) local inven = self.actor:getInven(o.slot) if inven[1] and o.offslot then inven = self.actor:getInven(o.offslot) end if not inven[1] then inven[1] = o end end end end for _, r in pairs(c.copy or {}) do if type(r) == "table" and r.__resolver == "equip" then apply_equip(r) end end for _, r in pairs(sc.copy or {}) do if type(r) == "table" and r.__resolver == "equip" then apply_equip(r) end end end end function _M:resetAttachementSpots() self.actor.attachement_spots = nil if self.has_custom_tile then self.actor.attachement_spots = self.has_custom_tile.f return end local dbr = self.birth_descriptor_def.race[self.descriptors_by_type.race or "Human"] local dr = self.birth_descriptor_def.subrace[self.descriptors_by_type.subrace or "Cornac"] local ds = self.birth_descriptor_def.sex[self.descriptors_by_type.sex or "Female"] local moddable_attachement_spots = dr.moddable_attachement_spots or dbr.moddable_attachement_spots local moddable_attachement_spots_sexless = dr.moddable_attachement_spots_sexless or dbr.moddable_attachement_spots_sexless if moddable_attachement_spots then if moddable_attachement_spots_sexless then self.actor.attachement_spots = "dolls_"..moddable_attachement_spots.."_all" elseif self.descriptors_by_type.sex == "Female" then self.actor.attachement_spots = "dolls_"..moddable_attachement_spots.."_female" else self.actor.attachement_spots = "dolls_"..moddable_attachement_spots.."_male" end end end function _M:setTile(f, w, h, last) self.actor:removeAllMOs() if not f then if not self.has_custom_tile then local dbr = self.birth_descriptor_def.race[self.descriptors_by_type.race or "Human"] local dr = self.birth_descriptor_def.subrace[self.descriptors_by_type.subrace or "Cornac"] local ds = self.birth_descriptor_def.sex[self.descriptors_by_type.sex or "Female"] self.actor.image = "player/"..(self.descriptors_by_type.subrace or "Cornac"):lower():gsub("[^a-z0-9_]", "_").."_"..(self.descriptors_by_type.sex or "Female"):lower():gsub("[^a-z0-9_]", "_")..".png" self.actor.add_mos = nil self.actor.female = ds.copy.female self.actor.male = ds.copy.male self.actor.moddable_tile = dr.copy.moddable_tile self.actor.moddable_tile_base = dr.copy.moddable_tile_base self.actor.moddable_tile_ornament = dr.copy.moddable_tile_ornament self.actor.moddable_tile_ornament2 = dr.copy.moddable_tile_ornament2 end else self.actor.make_tile = nil self.actor.moddable_tile = nil if h > w then self.actor.image = "invis.png" self.actor.add_mos = {{image=f, display_h=2, display_y=-1}} else self.actor.add_mos = nil self.actor.image = f end self.has_custom_tile = {f=f,w=w,h=h} end self:resetAttachementSpots() if not last then -- Add an example particles if any local ps = self.actor:getParticlesList("all") for i, p in ipairs(ps) do self.actor:removeParticles(p) end if self.actor.shader_auras then self.actor.shader_auras = {} end if self.descriptors_by_type.subclass then local d = self.birth_descriptor_def.subclass[self.descriptors_by_type.subclass] if d and d.birth_example_particles then local p = d.birth_example_particles if type(p) == "table" then p = rng.table(p) end p = util.getval(p, self.actor) if type(p) == "string" then self.actor:addParticles(Particles.new(p, 1)) end end end self:fakeEquip(true) self:applyCosmeticActor(false) self.actor:updateModdableTile() self:fakeEquip(false) else self:applyCosmeticActor(true) end end local to_reset_cosmetic = {} function _M:applyCosmeticActor(last) for i, d in ipairs(to_reset_cosmetic) do d.reset(self.actor) end to_reset_cosmetic = {} local list = {} for i, d in ipairs(self.cosmetic_unlocks) do if self.selected_cosmetic_unlocks[d.name] and d.on_actor then list[#list+1] = d if not d.priority then d.priority = 1 end end end table.sort(list, function(a,b) return a.priority < b.priority end) for i, d in ipairs(list) do d.on_actor(self.actor, self, last) if not last and d.reset then to_reset_cosmetic[#to_reset_cosmetic+1] = d end end end function _M:selectExplorationNoDonations() Dialog:yesnoLongPopup("Exploration mode", [[Exploration mode provides the characters using it with infinite lives. Tales of Maj'Eyal is meant to be a very replayable game in which you get better by learning from mistakes (and thus from dying too). I realize this can not please everybody and after multiple requests I have decided to grant exploration mode to donators, because it will allow player that like the game to see it all if they wish. Beware though, infinite lives does not mean the difficulty is reduced, only that you can try as much as you want without restarting. If you'd like to use this feature and find this game good you should consider donating. It will help ensure its survival. While this is a free game that I am doing for fun, if it can help feed my family a bit I certainly will not complain as real life can be harsh sometimes. You will need an online profile active and connected for the tile selector to enable. If you choose to donate now you will need to restart the game to be granted access. Donators will also gain access to the custom tiles for their characters.]], 400, function(ret) if not ret then game:registerDialog(require("mod.dialogs.Donation").new("exploration-mode")) end end, "Later", "Donate!") end function _M:selectTileNoDonations() Dialog:yesnoLongPopup("Custom tiles", [[Custom Tiles have been added as a thank you to everyone that has donated to ToME. They are a fun cosmetic feature that allows you to choose a tile for your character from a list of nearly 180 (with more to be added over time), ranging from special humanoid tiles to downright wonky ones! If you'd like to use this feature and find this game good you should consider donating. It will help ensure its survival. While this is a free game that I am doing for fun, if it can help feed my family a bit I certainly will not complain as real life can be harsh sometimes. You will need an online profile active and connected for the tile selector to enable. If you choose to donate now you will need to restart the game to be granted access. Donators will also gain access to the Exploration Mode featuring infinite lives.]], 400, function(ret) if not ret then game:registerDialog(require("mod.dialogs.Donation").new("custom-tiles")) end end, "Later", "Donate!") end function _M:selectTile() local d = Dialog.new("Select a Tile", 600, 550) local list = { "npc/alchemist_golem.png", "npc/armored_skeleton_warrior.png", "npc/barrow_wight.png", "npc/construct_golem_alchemist_golem.png", "npc/degenerated_skeleton_warrior.png", "npc/elder_vampire.png", "npc/emperor_wight.png", "npc/forest_wight.png", "npc/golem.png", "npc/grave_wight.png", "npc/horror_corrupted_dremling.png", "npc/horror_corrupted_drem_master.png", "npc/horror_eldritch_headless_horror.png", "npc/horror_eldritch_luminous_horror.png", "npc/horror_eldritch_worm_that_walks.png", "npc/horror_temporal_cronolith_clone.png", "npc/humanoid_dwarf_dwarven_earthwarden.png", "npc/humanoid_dwarf_dwarven_guard.png", "npc/humanoid_dwarf_dwarven_paddlestriker.png", "npc/humanoid_dwarf_dwarven_summoner.png", "npc/humanoid_dwarf_lumberjack.png", "npc/humanoid_dwarf_norgan.png", "npc/humanoid_dwarf_ziguranth_warrior.png", "npc/humanoid_elenulach_thief.png", "npc/humanoid_elf_anorithil.png", "npc/humanoid_elf_elven_archer.png", "npc/humanoid_elf_elven_sun_mage.png", "npc/humanoid_elf_fillarel_aldaren.png", "npc/humanoid_elf_limmir_the_jeweler.png", "npc/humanoid_elf_star_crusader.png", "npc/humanoid_halfling_derth_guard.png", "npc/humanoid_halfling_halfling_citizen.png", "npc/humanoid_halfling_halfling_gardener.png", "npc/humanoid_halfling_halfling_guard.png", "npc/humanoid_halfling_halfling_slinger.png", "npc/humanoid_halfling_master_slinger.png", "npc/humanoid_halfling_protector_myssil.png", "npc/humanoid_halfling_sm_halfling.png", "npc/humanoid_human_alchemist.png", "npc/humanoid_human_aluin_the_fallen.png", "npc/humanoid_human_apprentice_mage.png", "npc/humanoid_human_arcane_blade.png", "npc/humanoid_human_argoniel.png", "npc/humanoid_human_assassin.png", "npc/humanoid_human_bandit_lord.png", "npc/humanoid_human_bandit.png", "npc/humanoid_human_ben_cruthdar__the_cursed.png", "npc/humanoid_human_blood_mage.png", "npc/humanoid_human_celia.png", "npc/humanoid_human_cryomancer.png", "npc/humanoid_human_cutpurse.png", "npc/humanoid_human_derth_guard.png", "npc/humanoid_human_enthralled_slave.png", "npc/humanoid_human_fallen_sun_paladin_aeryn.png", "npc/humanoid_human_fire_wyrmic.png", "npc/humanoid_human_fryjia_loren.png", "npc/humanoid_human_geomancer.png", "npc/humanoid_human_gladiator.png", "npc/humanoid_human_great_gladiator.png", "npc/humanoid_human_harno__herald_of_last_hope.png", "npc/humanoid_human_hexer.png", "npc/humanoid_human_high_gladiator.png", "npc/humanoid_human_high_slinger.png", "npc/humanoid_human_high_sun_paladin_aeryn.png", "npc/humanoid_human_high_sun_paladin_rodmour.png", "npc/humanoid_human_human_citizen.png", "npc/humanoid_human_human_farmer.png", "npc/humanoid_human_human_guard.png", "npc/humanoid_human_human_sun_paladin.png", "npc/humanoid_human_ice_wyrmic.png", "npc/humanoid_human_last_hope_guard.png", "npc/humanoid_human_linaniil_supreme_archmage.png", "npc/humanoid_human_lumberjack.png", "npc/humanoid_human_martyr.png", "npc/humanoid_human_master_alchemist.png", "npc/humanoid_human_multihued_wyrmic.png", "npc/humanoid_human_necromancer.png", "npc/humanoid_human_pyromancer.png", "npc/humanoid_human_reaver.png", "npc/humanoid_human_rej_arkatis.png", "npc/humanoid_human_riala_shalarak.png", "npc/humanoid_human_rogue.png", "npc/humanoid_human_sand_wyrmic.png", "npc/humanoid_human_shadowblade.png", "npc/humanoid_human_shady_cornac_man.png", "npc/humanoid_human_slave_combatant.png", "npc/humanoid_human_slinger.png", "npc/humanoid_human_spectator02.png", "npc/humanoid_human_spectator03.png", "npc/humanoid_human_spectator.png", "npc/humanoid_human_storm_wyrmic.png", "npc/humanoid_human_subject_z.png", "npc/humanoid_human_sun_paladin_guren.png", "npc/humanoid_human_tannen.png", "npc/humanoid_human_tempest.png", "npc/humanoid_human_thief.png", "npc/humanoid_human_trickster.png", "npc/humanoid_human_urkis__the_high_tempest.png", "npc/humanoid_human_valfred_loren.png", "npc/humanoid_human_ziguranth_wyrmic.png", "npc/humanoid_orc_brotoq_the_reaver.png", "npc/humanoid_orc_fiery_orc_wyrmic.png", "npc/humanoid_orc_golbug_the_destroyer.png", "npc/humanoid_orc_gorbat__supreme_wyrmic_of_the_pride.png", "npc/humanoid_orc_grushnak__battlemaster_of_the_pride.png", "npc/humanoid_orc_icy_orc_wyrmic.png", "npc/humanoid_orc_krogar.png", "npc/humanoid_orc_massok_the_dragonslayer.png", "npc/humanoid_orc_orc_archer.png", "npc/humanoid_orc_orc_assassin.png", "npc/humanoid_orc_orc_berserker.png", "npc/humanoid_orc_orc_blood_mage.png", "npc/humanoid_orc_orc_corruptor.png", "npc/humanoid_orc_orc_cryomancer.png", "npc/humanoid_orc_orc_elite_berserker.png", "npc/humanoid_orc_orc_elite_fighter.png", "npc/humanoid_orc_orc_fighter.png", "npc/humanoid_orc_orc_grand_master_assassin.png", "npc/humanoid_orc_orc_grand_summoner.png", "npc/humanoid_orc_orc_high_cryomancer.png", "npc/humanoid_orc_orc_high_pyromancer.png", "npc/humanoid_orc_orc_mage_hunter.png", "npc/humanoid_orc_orc_master_assassin.png", "npc/humanoid_orc_orc_master_wyrmic.png", "npc/humanoid_orc_orc_necromancer.png", "npc/humanoid_orc_orc_pyromancer.png", "npc/humanoid_orc_orc_soldier.png", "npc/humanoid_orc_orc_summoner.png", "npc/humanoid_orc_orc_warrior.png", "npc/humanoid_orc_rak_shor_cultist.png", "npc/humanoid_orc_rak_shor__grand_necromancer_of_the_pride.png", "npc/humanoid_orc_ukruk_the_fierce.png", "npc/humanoid_orc_vor__grand_geomancer_of_the_pride.png", "npc/humanoid_orc_warmaster_gnarg.png", "npc/humanoid_shalore_archmage_tarelion.png", "npc/humanoid_shalore_elandar.png", "npc/humanoid_shalore_elvala_guard.png", "npc/humanoid_shalore_elven_blood_mage.png", "npc/humanoid_shalore_elven_corruptor.png", "npc/humanoid_shalore_elven_cultist.png", "npc/humanoid_shalore_elven_elite_warrior.png", "npc/humanoid_shalore_elven_guard.png", "npc/humanoid_shalore_elven_mage.png", "npc/humanoid_shalore_elven_tempest.png", "npc/humanoid_shalore_elven_warrior.png", "npc/humanoid_shalore_grand_corruptor.png", "npc/humanoid_shalore_mean_looking_elven_guard.png", "npc/humanoid_shalore_rhaloren_inquisitor.png", "npc/humanoid_shalore_shalore_rune_master.png", "npc/humanoid_thalore_thalore_hunter.png", "npc/humanoid_thalore_thalore_wilder.png", "npc/humanoid_thalore_ziguranth_summoner.png", "npc/humanoid_yaech_blood_master.png", "npc/humanoid_yaech_murgol__the_yaech_lord.png", "npc/humanoid_yaech_slaver.png", "npc/humanoid_yaech_yaech_diver.png", "npc/humanoid_yaech_yaech_hunter.png", "npc/humanoid_yaech_yaech_mindslayer.png", "npc/humanoid_yaech_yaech_psion.png", "npc/humanoid_yeek_yeek_wayist.png", "npc/humanoid_yeek_yeek_summoner.png", "npc/humanoid_yeek_yeek_psionic.png", "npc/humanoid_yeek_yeek_mindslayer.png", "npc/humanoid_yeek_yeek_commoner_01.png", "npc/humanoid_yeek_yeek_commoner_02.png", "npc/humanoid_yeek_yeek_commoner_03.png", "npc/humanoid_yeek_yeek_commoner_04.png", "npc/humanoid_yeek_yeek_commoner_05.png", "npc/humanoid_yeek_yeek_commoner_06.png", "npc/humanoid_yeek_yeek_commoner_07.png", "npc/humanoid_yeek_yeek_commoner_08.png", "npc/jawa_01.png", "npc/lesser_vampire.png", "npc/master_skeleton_archer.png", "npc/master_skeleton_warrior.png", "npc/master_vampire.png", "npc/skeleton_archer.png", "npc/skeleton_mage.png", "npc/skeleton_warrior.png", "npc/undead_skeleton_cowboy.png", "npc/the_master.png", "npc/vampire_lord.png", "npc/vampire.png", "npc/undead_skeleton_filio_flightfond.png", "npc/undead_ghoul_borfast_the_broken.png", "npc/horror_eldritch_umbral_horror.png", "npc/demon_major_general_of_urh_rok.png", "npc/demon_major_shasshhiy_kaish.png", "npc/undead_vampire_arch_zephyr.png", "npc/undead_ghoul_rotting_titan.png", "npc/humanoid_human_townsfolk_aimless_looking_merchant01_64.png", "npc/humanoid_human_townsfolk_battlescarred_veteran01_64.png", "npc/humanoid_human_townsfolk_blubbering_idiot01_64.png", "npc/humanoid_human_townsfolk_boilcovered_wretch01_64.png", "npc/humanoid_human_townsfolk_farmer_maggot01_64.png", "npc/humanoid_human_townsfolk_filthy_street_urchin01_64.png", "npc/humanoid_human_townsfolk_mangy_looking_leper01_64.png", "npc/humanoid_human_townsfolk_meanlooking_mercenary01_64.png", "npc/humanoid_human_townsfolk_pitiful_looking_beggar01_64.png", "npc/humanoid_human_townsfolk_singing_happy_drunk01_64.png", "npc/humanoid_human_townsfolk_squinteyed_rogue01_64.png", "npc/humanoid_human_townsfolk_village_idiot01_64.png", "npc/humanoid_naga_lady_zoisla_the_tidebringer.png", "npc/humanoid_naga_naga_nereid.png", "npc/humanoid_naga_naga_tidecaller.png", "npc/humanoid_naga_naga_tidewarden.png", "npc/humanoid_naga_slasul.png", "npc/naga_myrmidon_2.png", "npc/naga_myrmidon_no_armor.png", "npc/naga_myrmidon.png", "npc/naga_psyren2_2.png", "npc/naga_psyren2.png", "npc/naga_psyren.png", "npc/naga_tide_huntress_2.png", "npc/naga_tide_huntress.png", "npc/snowman01.png", "npc/snaproot_pimp.png", "npc/R2D2_01.png", "npc/humanoid_female_sluttymaid.png", "npc/humanoid_male_sluttymaid.png", "player/ascii_player_dorfhelmet_01_64.png", "player/ascii_player_fedora_feather_04_64.png", "player/ascii_player_helmet_02_64.png", "player/ascii_player_mario_01_64.png", "player/ascii_player_rogue_cloak_01_64.png", "player/ascii_player_wizardhat_01_64.png", "player/ascii_player_gentleman_01_64.png", "player/ascii_player_red_hood_01.png", "player/ascii_player_pink_amazone_01.png", "player/ascii_player_bunny_01.png", "player/ascii_player_exotic_01.png", "player/ascii_player_shopper_01.png", } fs.mkdir("/data/gfx/custom-tiles/") for file in fs.iterate("/data/gfx/custom-tiles/", function(file) return file:find("%.png") end) do list[#list+1] = "custom-tiles/"..file end self:triggerHook{"Birther:donatorTiles", list=list} local remove = Button.new{text="Use default tile", width=240, fct=function() game:unregisterDialog(d) self.has_custom_tile = nil self:setTile() end} local custom = Button.new{text="Use custom-made tile", width=240, fct=function() self:simpleLongPopup("Howto: Custom-made tiles", ([[You can use your own custom tiles if you are a donator. For the game to use them you must simply respect a few rules: - they must be 64x64 or 64x128 tiles - they must be saved as PNG files - you must place them in folder #LIGHT_BLUE#%s#WHITE# Once you have done so, simply restart the game and the tiles will be listed at the bottom of the list.]]):format(fs.getRealPath("/data/gfx/custom-tiles/")), 500) end} local list = ImageList.new{width=500, height=500, tile_w=64, tile_h=64, padding=10, scrollbar=true, list=list, fct=function(item) game:unregisterDialog(d) if not self:isDonator() then self:selectTileNoDonations() else self:setTile(item.f, item.w, item.h) end end} d:loadUI{ {left=0, top=0, ui=list}, {left=0, bottom=0, ui=remove}, {left=250, bottom=0, ui=custom}, } d:setupUI(true, true) d.key:addBind("EXIT", function() game:unregisterDialog(d) end) game:registerDialog(d) end function _M:isDonator() return profile:isDonator(1) end function _M:customizeOptions() local d = Dialog.new("Customization Options", 600, 550) local sel = nil local list list = List.new{width=450, list=self.cosmetic_unlocks, height=400, fct=function(item) if not item.donator or self:isDonator() then self.selected_cosmetic_unlocks[item.name] = not self.selected_cosmetic_unlocks[item.name] item.color = self.selected_cosmetic_unlocks[item.name] and colors.simple(colors.LIGHT_GREEN) or nil end local oldsel, oldscroll = list.sel, list.scroll list:generate() list.sel, list.scroll = oldsel, oldscroll self:setTile() end, } d:loadUI{ {left=0, top=0, ui=list}, } d:setupUI(true, true) d.key:addBind("EXIT", function() game:unregisterDialog(d) end) game:registerDialog(d) end function _M:extraOptions() local options = OptionTree.new(game.extra_birth_option_defs, 'Birth Options', 600, 550) options:initialize() game:registerDialog(options) end
gpl-3.0
saraedum/luci-packages-old
protocols/core/luasrc/model/cbi/admin_network/proto_static.lua
8
2297
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local ifc = net:get_interface() local ipaddr, netmask, gateway, broadcast, dns, accept_ra, send_rs, ip6addr, ip6gw local macaddr, mtu, metric ipaddr = section:taboption("general", Value, "ipaddr", translate("IPv4 address")) ipaddr.datatype = "ip4addr" netmask = section:taboption("general", Value, "netmask", translate("IPv4 netmask")) netmask.datatype = "ip4addr" netmask:value("255.255.255.0") netmask:value("255.255.0.0") netmask:value("255.0.0.0") gateway = section:taboption("general", Value, "gateway", translate("IPv4 gateway")) gateway.datatype = "ip4addr" broadcast = section:taboption("general", Value, "broadcast", translate("IPv4 broadcast")) broadcast.datatype = "ip4addr" dns = section:taboption("general", DynamicList, "dns", translate("Use custom DNS servers")) dns.datatype = "ipaddr" dns.cast = "string" if luci.model.network:has_ipv6() then accept_ra = s:taboption("general", Flag, "accept_ra", translate("Accept router advertisements")) accept_ra.default = accept_ra.disabled send_rs = s:taboption("general", Flag, "send_rs", translate("Send router solicitations")) send_rs.default = send_rs.enabled send_rs:depends("accept_ra", "") ip6addr = section:taboption("general", Value, "ip6addr", translate("IPv6 address")) ip6addr.datatype = "ip6addr" ip6addr:depends("accept_ra", "") ip6gw = section:taboption("general", Value, "ip6gw", translate("IPv6 gateway")) ip6gw.datatype = "ip6addr" ip6gw:depends("accept_ra", "") end macaddr = section:taboption("advanced", Value, "macaddr", translate("Override MAC address")) macaddr.placeholder = ifc and ifc:mac() or "00:00:00:00:00:00" macaddr.datatype = "macaddr" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(1500)" metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger"
apache-2.0
kuoruan/lede-luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_system/admin.lua
4
3234
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local fs = require "nixio.fs" m = Map("system", translate("Router Password"), translate("Changes the administrator password for accessing the device")) s = m:section(TypedSection, "_dummy", "") s.addremove = false s.anonymous = true pw1 = s:option(Value, "pw1", translate("Password")) pw1.password = true pw2 = s:option(Value, "pw2", translate("Confirmation")) pw2.password = true function s.cfgsections() return { "_pass" } end function m.parse(map) local v1 = pw1:formvalue("_pass") local v2 = pw2:formvalue("_pass") if v1 and v2 and #v1 > 0 and #v2 > 0 then if v1 == v2 then if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then m.message = translate("Password successfully changed!") else m.message = translate("Unknown Error, password not changed!") end else m.message = translate("Given password confirmation did not match, password not changed!") end end Map.parse(map) end if fs.access("/etc/config/dropbear") then m2 = Map("dropbear", translate("SSH Access"), translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server")) s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance")) s.anonymous = true s.addremove = true ni = s:option(Value, "Interface", translate("Interface"), translate("Listen only on the given interface or, if unspecified, on all")) ni.template = "cbi/network_netlist" ni.nocreate = true ni.unspecified = true pt = s:option(Value, "Port", translate("Port"), translate("Specifies the listening port of this <em>Dropbear</em> instance")) pt.datatype = "port" pt.default = 22 pa = s:option(Flag, "PasswordAuth", translate("Password authentication"), translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication")) pa.enabled = "on" pa.disabled = "off" pa.default = pa.enabled pa.rmempty = false ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"), translate("Allow the <em>root</em> user to login with password")) ra.enabled = "on" ra.disabled = "off" ra.default = ra.enabled gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"), translate("Allow remote hosts to connect to local SSH forwarded ports")) gp.enabled = "on" gp.disabled = "off" gp.default = gp.disabled s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"), translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication.")) s2.addremove = false s2.anonymous = true s2.template = "cbi/tblsection" function s2.cfgsections() return { "_keys" } end keys = s2:option(TextValue, "_data", "") keys.wrap = "off" keys.rows = 3 function keys.cfgvalue() return fs.readfile("/etc/dropbear/authorized_keys") or "" end function keys.write(self, section, value) return fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n")) end function keys.remove(self, section, value) return fs.writefile("/etc/dropbear/authorized_keys", "") end end return m, m2
apache-2.0
sleepingwit/premake-core
modules/vstudio/tests/sln2005/test_dependencies.lua
15
2331
-- -- tests/actions/vstudio/sln2005/test_dependencies.lua -- Validate generation of Visual Studio 2005+ solution project dependencies. -- Copyright (c) 2009-2012 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("vstudio_sln2005_dependencies") local sln2005 = p.vstudio.sln2005 -- -- Setup -- local wks, prj1, prj2 function suite.setup() p.action.set("vs2005") wks, prj1 = test.createWorkspace() uuid "AE61726D-187C-E440-BD07-2556188A6565" prj2 = test.createproject(wks) uuid "2151E83B-997F-4A9D-955D-380157E88C31" prj3 = test.createproject(wks) uuid "CAA68162-8B96-11E1-8D5E-5885BBE59B18" links "MyProject" dependson "MyProject2" end local function prepare(language) prj1.language = language prj2.language = language prj2 = test.getproject(wks, 2) sln2005.projectdependencies(prj2) prj3.language = language prj3 = test.getproject(wks, 3) sln2005.projectdependencies(prj3) end -- -- Verify dependencies between C++ projects are listed. -- function suite.dependency_onCppProjects() prepare("C++") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end -- -- Verify dependencies between C# projects are listed. -- function suite.dependency_onCSharpProjects() prepare("C#") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end -- -- Most C# references should go into the project rather than the solution, -- but until I know the conditions, put everything here to be safe. -- function suite.dependency_onCSharpProjectsVs2010() p.action.set("vs2010") prepare("C#") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end -- -- Verify dependencies between projects C# are listed for VS2012. -- function suite.dependency_onCSharpProjectsVs2012() p.action.set("vs2012") prepare("C#") test.capture [[ ProjectSection(ProjectDependencies) = postProject {2151E83B-997F-4A9D-955D-380157E88C31} = {2151E83B-997F-4A9D-955D-380157E88C31} EndProjectSection ]] end
bsd-3-clause
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/chats/alchemist-golem.lua
1
2532
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local change_inven = function(npc, player) local d local titleupdator = player:getEncumberTitleUpdator(("Equipment(%s) <=> Inventory(%s)"):format(npc.name:capitalize(), player.name:capitalize())) d = require("mod.dialogs.ShowEquipInven").new(titleupdator(), npc, nil, function(o, inven, item, button, event) if not o then return end local ud = require("mod.dialogs.UseItemDialog").new(event == "button", npc, o, item, inven, function(_, _, _, stop) d:generate() d:generateList() d:updateTitle(titleupdator()) if stop then game:unregisterDialog(d) end end, true, player) game:registerDialog(ud) end, nil, player) game:registerDialog(d) end local change_talents = function(npc, player) local LevelupDialog = require "mod.dialogs.LevelupDialog" local ds = LevelupDialog.new(npc, nil, nil) game:registerDialog(ds) end local change_tactics = function(npc, player) game.party:giveOrders(npc) end local change_control = function(npc, player) game.party:select(npc) end local change_name = function(npc, player) local d = require("engine.dialogs.GetText").new("Change your golem's name", "Name", 2, 25, function(name) if name then npc.name = name.." (servant of "..player.name..")" npc.changed = true end end) game:registerDialog(d) end local ans = { {"I want to change your equipment.", action=change_inven}, {"I want to change your talents.", action=change_talents}, {"I want to change your tactics.", action=change_tactics}, {"I want to take direct control.", action=change_control}, {"I want to change your name.", action=change_name}, {"Nothing, let's go."}, } newChat{ id="welcome", text = [[#LIGHT_GREEN#*The golem talks in a monotonous voice*#WHITE# Yes master.]], answers = ans } return "welcome"
gpl-3.0
tdubourg/geobombing
mobileapp/corona/config/Sprites.lua
1
3409
require("consts") ----------------------------------------------------------------------------------------- -- -- Author: Aurélien Defossez -- (c) 2014 Tabemasu Games (www.tabemasu.com) -- -- Sprites configuration -- -- Parameters: -- frameCount: The number of frames defining the animation (default is 1) -- If frameCount > 1, then the source images should be suffixed by _01, _02 -- and so on -- (e.g. zombie_attack_right_blue_01.png and zombie_attack_right_blue_02.png) -- period: The period in seconds to play the whole animation. -- (Optional if there is only one frame) -- loopCount: Tells how many times the animation loops (Default is 0, indefinitely). -- randomStartFrame: Starts at a random frame (Default is false). -- attachments: A list of possible attachments to the sprite, with these parameters: -- animation: The attachment animation -- positions: The attachment positions relative to the sprite position -- ----------------------------------------------------------------------------------------- return { sheets = { sprites = { level = { background = {}, foreground = {} }, man = { leftwalk = { frameCount = 4, period = 0.4 -- loopCount = 1 }, leftstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, rightwalk = { frameCount = 4, period = 0.4 -- loopCount = 1 }, rightstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, upwalk = { frameCount = 2, period = 0.3 -- loopCount = 1 }, upstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, downwalk = { frameCount = 2, period = 0.3 -- loopCount = 1 }, downstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, death = { frameCount = 2, period = DEATH_ANIM_PERIOD, loopCount = 1 }, }, manc = { leftwalk = { frameCount = 4, period = 0.4 -- loopCount = 1 }, leftstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, rightwalk = { frameCount = 4, period = 0.4 -- loopCount = 1 }, rightstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, upwalk = { frameCount = 2, period = 0.3 -- loopCount = 1 }, upstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, downwalk = { frameCount = 2, period = 0.3 -- loopCount = 1 }, downstand = { frameCount = 2, period = 0.9 -- loopCount = 1 }, death = { frameCount = 2, period = DEATH_ANIM_PERIOD, loopCount = 1 }, }, bomb = { idle = { frameCount = 2, period = BOMB_PULSE_PERIOD, }, explode = { frameCount = 8, period = EXPLOSION_PERIOD, loopCount = 1 } }, bombc = { idle = { frameCount = 2, period = BOMB_PULSE_PERIOD, }, } } }, ----------------------------------------------------------------------------------------- -- Sprite attachments configuration -- -- Parameters: -- spriteSet: The attachment spriteSet -- toBack: If true, add the attachment below the sprite (optional, default is false) -- ----------------------------------------------------------------------------------------- attachments = { } }
lgpl-3.0
simeneuro/simeneurobot
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
nimaghorbani/nimatelegram
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
mahdibagheri/aqa-mp3
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
Blackdutchie/Zero-K
gamedata/modularcomms/weapons/gaussrifle.lua
12
1428
local name = "commweapon_gaussrifle" local weaponDef = { name = [[Gauss Rifle]], alphaDecay = 0.12, areaOfEffect = 16, avoidfeature = false, bouncerebound = 0.15, bounceslip = 1, cegTag = [[gauss_tag_l]], craterBoost = 0, craterMult = 0, customParams = { slot = [[5]], muzzleEffectFire = [[custom:flashmuzzle1]], single_hit_multi = true, }, damage = { default = 140, planes = 140, subs = 7, }, explosionGenerator = [[custom:gauss_hit_m]], groundbounce = 1, impactOnly = true, impulseBoost = 0, impulseFactor = 0, interceptedByShieldType = 1, noExplode = true, noSelfDamage = true, numbounce = 40, range = 420, reloadtime = 2.5, rgbColor = [[0.5 1 1]], separation = 0.5, size = 0.8, sizeDecay = -0.1, soundHit = [[weapon/gauss_hit]], soundHitVolume = 3, soundStart = [[weapon/gauss_fire]], soundStartVolume = 2.5, stages = 32, turret = true, waterbounce = 1, weaponType = [[Cannon]], weaponVelocity = 2200, } return name, weaponDef
gpl-2.0
Blackdutchie/Zero-K
LuaUI/Widgets/gui_recv_indicator.lua
12
20188
local versionName = "v1.294" function widget:GetInfo() return { name = "Receive Units Indicator", desc = versionName .. " Notify users of received units from unit transfer", author = "msafwan", date = "Jan 30, 2012", --minor clean up: June 25, 2013 license = "GNU GPL, v2 or later", layer = 20, enabled = true -- loaded by default? } end --------------------------------------------------------------------------------- --Imports------------------------------------------------------------------------ local osClock = os.clock local spMarkerErasePosition = Spring.MarkerErasePosition local spMarkerAddPoint = Spring.MarkerAddPoint local spGetUnitPosition = Spring.GetUnitPosition local spGetUnitsInCylinder = Spring.GetUnitsInCylinder local spAreTeamsAllied = Spring.AreTeamsAllied local spValidUnitID = Spring.ValidUnitID local spIsAABBInView = Spring.IsAABBInView local spGetGameFrame = Spring.GetGameFrame --Copied From gui_point_tracker.lua---------------------------------------------- local glLineWidth = gl.LineWidth local glColor = gl.Color local glDrawGroundCircle = gl.DrawGroundCircle local glPopMatrix = gl.PopMatrix local glPushMatrix = gl.PushMatrix local spWorldToScreenCoords = Spring.WorldToScreenCoords local abs = math.abs local strSub = string.sub local GL_FRONT_AND_BACK = GL.FRONT_AND_BACK local GL_FILL = GL.FILL local glShape = gl.Shape local GL_TRIANGLES = GL.TRIANGLES local glPolygonMode = gl.PolygonMode local glText = gl.Text --end---------------------------------------------------------------------------- --------------------------------------------------------------------------------- local myTeamID_gbl = -1 --//variable: myTeamID local receivedUnitList_gbl = {} --//variable: store unitID and its corresponding unitPosition local givenByTeamID_gbl = -1 --//variable: store sender's ID local gameID_to_playerName_gbl = {} local knownMarkerPosition_gbl = {} local knownCirclePosition_gbl = {} local notifyCapture_gbl = {} local knownMarkerPositionEMPTY_gbl = true --//variable: a flag. Used because those table did not start filling at index 1, thus unable to check them (with #) if it is truely empty or not. local knownCirclePositionEMPTY_gbl = true --//variable: a flag local receivedUnitListEMPTY_gbl = true --//variable: a flag local minimumNeighbor_gbl = 3 --//constant: minimum neighboring (units) before considered a cluster local neighborhoodRadius_gbl = 600 --//constant: neighborhood radius. Distance from each unit where neighborhoodList are generated. local radiusThreshold_gbl = 300 --//constant: density threshold where border is detected. Huge value means 2 cluster are combined, small value mean all unit disassociated local waitConstant_gbl = 1 --//constant: default interval (in second) for 'widget:Update()' to be executed local waitDuration_gbl = waitConstant_gbl --//variable: determine how frequently 'widget:Update()' is executed local markerLife_gbl = 4 --//constant: wait (in second) before marker expired (to prevent clutter) local circleLife_gbl = 6 local maximumLife_gbl = 20 --//constant: wait (in second) before marker & circle forcefully expired (to prevent clutter) local iNotLagging = true --//variable: indicate if player(me) is lagging in current game. If I'm lagging then do not count any received units (because I might be in state of rejoining and those units I saw are probably just a replay). --Copied From gui_point_tracker.lua & minimap_event.lua-------------------------- local circleList_gbl =nil local circleDivs =16 local lineWidth = 2 -- set to 0 to remove outlines local vsX, vsY, sMidX,sMidY = 0,0,0,0 --//variable: screen size local myColor_gbl = {0,0,0} local edgeMarkerSize = 16 local on = true local blinkPeriod = 0.25 local maxAlpha = 1 local ttl = 15 local timePart = 0 local fontSize = 16 local maxLabelLength = 16 --end---------------------------------------------------------------------------- --------------------------------------------------------------------------------- --Add Marker--------------------------------------------------------------------- -- 1 function. local function AddMarker (cluster, unitIDNoise, receivedUnitList) local givenByTeamID = givenByTeamID_gbl local gameID_to_playerName = gameID_to_playerName_gbl local knownMarkerPosition = knownMarkerPosition_gbl local knownCirclePosition = knownCirclePosition_gbl local knownCirclePositionEMPTY = knownCirclePositionEMPTY_gbl ------ --// extract cluster information and add mapMarker. local currentIndex=0 local playerName = gameID_to_playerName[givenByTeamID+1] local now = osClock() for index=1 , #cluster do local sumX, sumY,sumZ, unitCount,meanX, meanY, meanZ = 0,0 ,0 ,0 ,0,0,0 local maxX, minX, maxZ, minZ, radiiX, radiiZ, avgRadii = 0,99999,0,99999, 0,0,0 for unitIndex=1, #cluster[index] do local unitID = cluster[index][unitIndex] local x,y,z= receivedUnitList[unitID][1],receivedUnitList[unitID][2],receivedUnitList[unitID][3] --// get stored unit position sumX= sumX+x sumY = sumY+y sumZ = sumZ+z if x> maxX then maxX= x end if x<minX then minX=x end if z> maxZ then maxZ= z end if z<minZ then minZ=z end unitCount=unitCount+1 end meanX = sumX/unitCount --//calculate center of cluster meanY = sumY/unitCount meanZ = sumZ/unitCount local label = unitCount .. " units received from ".. playerName spMarkerAddPoint(meanX,meanY,meanZ, label) knownMarkerPosition[(#knownMarkerPosition or 0)+1] = {meanX, meanY, meanZ, birth = now, age=0} knownMarkerPositionEMPTY = false radiiX = ((maxX - meanX)+ (meanX - minX))/2 radiiZ = ((maxZ - meanZ)+ (meanZ - minZ))/2 avgRadii = (radiiX + radiiZ) /2 knownCirclePosition[(#knownCirclePosition or 0)+1] = {meanX, 0, meanZ, true, avgRadii+100, strSub(label, 1, maxLabelLength), birth = now, age=0, false} --//add circle knownCirclePositionEMPTY = false currentIndex = index end currentIndex=currentIndex+1 if #unitIDNoise>0 then --//IF outlier list is not empty local addMarker = true local notIgnore = true local label = "Unit received from ".. playerName if #unitIDNoise >= 6 and currentIndex > 1 then --//IF the outlier list is greater than 5, and there already discernable cluster, then no need to add individual marker. addMarker = false end for j= 1 ,#unitIDNoise do local x,y,z=spGetUnitPosition(unitIDNoise[j]) if x~=nil then --// exclude 'nil'. Unit under construction usually return 'nil'. if j>= 6 and currentIndex > 1 then --//IF current index is greater than 5, and there already discernable cluster, then no need to hi-light individual units. notIgnore=false end if addMarker then spMarkerAddPoint(x,y,z, label) knownMarkerPosition[(#knownMarkerPosition or 0)+1] = {x, y, z, birth = now, age = 0} end --// add marker knownCirclePosition[(#knownCirclePosition or 0)+1] = {x, 0, z, notIgnore, 100, strSub(label, 1, maxLabelLength), birth = now, age = 0} knownCirclePositionEMPTY = false currentIndex=currentIndex+1 end end end ------ givenByTeamID_gbl = -1 --//reset value knownMarkerPosition_gbl = knownMarkerPosition knownCirclePosition_gbl = knownCirclePosition knownCirclePositionEMPTY_gbl = knownCirclePositionEMPTY end --------------------------------------------------------------------------------- --Periodic Function---------------------------------------------------------------- --3 functions local elapsedTime = 0 --//variable: ... function widget:Update(n) elapsedTime= elapsedTime + n timePart = timePart + n if (timePart > blinkPeriod and blinkPeriod > 0) then timePart = timePart - blinkPeriod on = not on end if elapsedTime < waitDuration_gbl then return end elapsedTime = 0 local viewSizeX, viewSizeY = widgetHandler:GetViewSizes() widget:ViewResize(viewSizeX, viewSizeY) if (receivedUnitListEMPTY_gbl == false) then --// if 'receivedUnitList' is not empty: assume ALL unitID was received, calculate the cluster, and add marker. local receivedUnitList = receivedUnitList_gbl local myTeamID = myTeamID_gbl local minimumNeighbor = minimumNeighbor_gbl local neighborhoodRadius = neighborhoodRadius_gbl local radiusThreshold = radiusThreshold_gbl local cluster={} local unitIDNoise ={} ------ --cluster, unitIDNoise = DBSCAN_cluster (myTeamID, minimumNeighbor, neighborhoodRadius, cluster, receivedUnitList, unitIDNoise) --//method 1 cluster, unitIDNoise = WG.OPTICS_cluster (receivedUnitList, neighborhoodRadius, minimumNeighbor, myTeamID, radiusThreshold) --//method 2. Better (WG.OPTICS_cluster is located in api_shared_functions.lua) AddMarker(cluster, unitIDNoise, receivedUnitList) ------ receivedUnitListEMPTY_gbl = true --//flag the table as empty waitDuration_gbl = waitConstant_gbl --// reset 'widget:Update()' update interval receivedUnitList_gbl = {} --//reset 'receivedUnitList' content end if (knownMarkerPositionEMPTY_gbl==false) then --//Function: delete marker when it expired local knownMarkerPosition = knownMarkerPosition_gbl local now = osClock() local markerLife = markerLife_gbl local maximumLife = maximumLife_gbl local waitDuration = waitDuration_gbl local knownMarkerPositionEMPTY = knownMarkerPositionEMPTY_gbl ----- knownMarkerPositionEMPTY = true for i,_ in pairs(knownMarkerPosition) do if knownMarkerPosition[i] ~= nil then local x, y ,z = knownMarkerPosition[i][1], knownMarkerPosition[i][2], knownMarkerPosition[i][3] local inView = spIsAABBInView(x,y,z, x,y,z ) if inView then --//if inView then calculate marker age and/or erase it local markerAge = knownMarkerPosition[i].age if markerAge >= markerLife then --//if marker age exceed marker life then delete it spMarkerErasePosition (x,y,z) knownMarkerPosition[i] = nil --//set to nil here so that next content (inserted using # will put it here, filling the space) else --//if marker age not yet exceed marker life then add age knownMarkerPosition[i].age = knownMarkerPosition[i].age +waitDuration end else --//if not in view: check for marker actual age local markerAge = now - knownMarkerPosition[i].birth if markerAge >= maximumLife then knownMarkerPosition[i] = nil end end end knownMarkerPositionEMPTY = false end ----- knownMarkerPosition_gbl = knownMarkerPosition knownMarkerPositionEMPTY_gbl = knownMarkerPositionEMPTY end if (knownCirclePositionEMPTY_gbl== false) then --//Function: remove circle when it expired local knownCirclePosition = knownCirclePosition_gbl local now = osClock() local circleLife = circleLife_gbl local maximumLife = maximumLife_gbl local waitDuration = waitDuration_gbl local knownCirclePositionEMPTY = knownCirclePositionEMPTY_gbl ----- knownCirclePositionEMPTY = true for i,_ in pairs(knownCirclePosition) do if knownCirclePosition[i] ~= nil then local x, y ,z = knownCirclePosition[i][1], knownCirclePosition[i][2], knownCirclePosition[i][3] local inView = spIsAABBInView(x,y,z, x,y,z ) if inView then --//if inView then calculate circle age and/or erase it local circleAge = knownCirclePosition[i].age if circleAge >= circleLife then --//if circle age exceed circle life then delete it spMarkerErasePosition (x,y,z) knownCirclePosition[i] = nil --//set to nil here so that next content (inserted using # will put it here, filling the space) else --//if circle age not yet exceed circle life then add age knownCirclePosition[i].age = knownCirclePosition[i].age +waitDuration end else --//if not in view: check for circle actual age local circleAge = now - knownCirclePosition[i].birth if circleAge >= maximumLife then knownCirclePosition[i] = nil end end end knownCirclePositionEMPTY = false end ----- knownCirclePosition_gbl = knownCirclePosition knownCirclePositionEMPTY_gbl = knownCirclePositionEMPTY end end function widget:UnitGiven(unitID, unitDefID, unitTeamID, oldTeamID) --//will be executed repeatedly if there's more than 1 unit transfer if iNotLagging then if spValidUnitID(unitID) and unitTeamID == myTeamID_gbl then --if my unit if spAreTeamsAllied(unitTeamID, oldTeamID) or notifyCapture_gbl[oldTeamID] then --if from my ally, or from a captured enemy unit --myTeamID_gbl = unitTeamID --//uncomment this and comment 'unitTeamID == myTeamID_gbl' (above) when testing notifyCapture_gbl[oldTeamID] = false local x,y,z = spGetUnitPosition(unitID) receivedUnitList_gbl[unitID]={x,y,z} receivedUnitListEMPTY_gbl = false --//flag the table as not empty givenByTeamID_gbl = oldTeamID waitDuration_gbl = 0.2 -- tell widget:Update() to wait 0.2 more second before start adding mapMarker elapsedTime = 0 -- tell widget:Update() to reset timer end end end end function widget:Initialize() local myPlayerID=Spring.GetMyPlayerID() local _, _, spec = Spring.GetPlayerInfo(myPlayerID) if spec then widgetHandler:RemoveWidget() return false end --//widget will not load if we are a spectator. ----- localize global variable: local gameID_to_playerName = gameID_to_playerName_gbl local myTeamID = myTeamID_gbl local notifyCapture = notifyCapture_gbl local myColor = myColor_gbl ----- -- local playerList = Spring.GetPlayerRoster() --//check playerIDList for players -- for i = 1, #playerList do -- local teamID = playerList[i][3] -- local playerName = playerList[i][1] -- gameID_to_playerName[teamID+1] = playerName -- end myTeamID = Spring.GetMyTeamID() --//get my teamID. Used to filter receivedUnitList from our own unit. local teamList = Spring.GetTeamList() --//check teamIDlist for AI for j= 1, #teamList do local teamID = teamList[j] notifyCapture[teamID] = true local _,playerID, _, isAI = Spring.GetTeamInfo(teamID) if isAI then local _, aiName = Spring.GetAIInfo(teamID) gameID_to_playerName[teamID+1] = aiName elseif not isAI then local playerName = Spring.GetPlayerInfo(playerID) gameID_to_playerName[teamID+1] = playerName or "Gaia" end end --circleList_gbl = gl.CreateList(function() --Reference: minimap_events.lua (Dave Rodgers). Create circle -- gl.BeginEnd(GL.TRIANGLE_FAN, function() --//fill circle with opaque color -- for i = 0, circleDivs - 1 do -- local r = 2.0 * math.pi * (i / circleDivs) -- local cosv = math.cos(r) -- local sinv = math.sin(r) -- gl.TexCoord(cosv, sinv) -- gl.Vertex(cosv, 0, sinv) -- end -- end) -- if (lineWidth > 0) then --//outline circle -- gl.BeginEnd(GL.LINE_LOOP, function() -- for i = 0, circleDivs - 1 do -- local r = 2.0 * math.pi * (i / circleDivs) -- local cosv = math.cos(r) -- local sinv = math.sin(r) -- gl.TexCoord(cosv, sinv) -- gl.Vertex(cosv, 0, sinv) -- end -- end) -- end -- end) local myPlayerID = Spring.GetMyTeamID() local r, g, b = Spring.GetTeamColor(myPlayerID) myColor = {r,g,b} ----- gameID_to_playerName_gbl = gameID_to_playerName myTeamID_gbl = myTeamID notifyCapture_gbl = notifyCapture myColor_gbl = myColor end --------------------------------------------------------------------------------- --Widget's Turn-Off/On switch----------------------------------------------------- --2 functions function widget:PlayerChanged(playerID) if Spring.GetSpectatingState() then widgetHandler:RemoveWidget() end --//widget will unload when we become spectator. end function widget:GameProgress(serverFrameNum) --//see if me are lagging behind the server in the current game. If me is lagging then trigger a switch, (this switch will tell the widget to stop counting received units). local myFrameNum = spGetGameFrame() local frameNumDiff = serverFrameNum - myFrameNum if frameNumDiff > 120 then --// 120 frame means: a 4 second lag. Consider me is lagging if my frame differ from server by more than 4 second. iNotLagging = false else --// consider me not lagging if my frame differ from server's frame for less than 4 second. iNotLagging = true end end --------------------------------------------------------------------------------- --Visual FX---------------------------------------------------------------- --3 functions function widget:DrawScreen() --Reference: gui_point_tracker.lua (Evil4Zerggin) if #knownCirclePosition_gbl~= nil then for i,_ in pairs(knownCirclePosition_gbl) do local sX,sY,sZ = spWorldToScreenCoords(knownCirclePosition_gbl[i][1], knownCirclePosition_gbl[i][2], knownCirclePosition_gbl[i][3]) if (sX >= 0 and sY >= 0 and sX <= vsX and sY <= vsY) then --if within view then: draw circle on screen -- glPushMatrix() -- glLineWidth(2) -- gl.Rotate(270, 1, 0, 0) -- glColor(myColor_gbl[1],myColor_gbl[2],myColor_gbl[3], 0.3) -- gl.Translate(sX, 0, sY) -- gl.Scale(knownCirclePosition_gbl[i][4], 1, knownCirclePosition_gbl[i][4]) -- gl.CallList(circleList_gbl) -- glColor(1,1,1,1) -- glLineWidth(1) -- glPopMatrix() else --//if outside view then: draw arrow on edge of the screen glPushMatrix() glLineWidth(1) if (on) and (knownCirclePosition_gbl[i][4]) then local alpha = 1 --alpha = maxAlpha * (os.clock() - knownCirclePosition_gbl[i][4]) / ttl glColor(myColor_gbl[1],myColor_gbl[2],myColor_gbl[3], alpha) --out of screen glPolygonMode(GL_FRONT_AND_BACK, GL_FILL) --flip if behind screen if (sZ > 1) then sX = sMidX - sX sY = sMidY - sY end local xRatio = sMidX / abs(sX - sMidX) local yRatio = sMidY / abs(sY - sMidY) local edgeDist, vertices, textX, textY, textOptions if (xRatio < yRatio) then edgeDist = (sY - sMidY) * xRatio + sMidY if (sX > 0) then vertices = { {v = {vsX, edgeDist, 0}}, {v = {vsX - edgeMarkerSize, edgeDist + edgeMarkerSize, 0}}, {v = {vsX - edgeMarkerSize, edgeDist - edgeMarkerSize, 0}}, } textX = vsX - edgeMarkerSize textY = edgeDist - fontSize * 0.5 textOptions = "rn" else vertices = { {v = {0, edgeDist, 0}}, {v = {edgeMarkerSize, edgeDist - edgeMarkerSize, 0}}, {v = {edgeMarkerSize, edgeDist + edgeMarkerSize, 0}}, } textX = edgeMarkerSize textY = edgeDist - fontSize * 0.5 textOptions = "n" end else edgeDist = (sX - sMidX) * yRatio + sMidX if (sY > 0) then vertices = { {v = {edgeDist, vsY, 0}}, {v = {edgeDist - edgeMarkerSize, vsY - edgeMarkerSize, 0}}, {v = {edgeDist + edgeMarkerSize, vsY - edgeMarkerSize, 0}}, } textX = edgeDist textY = vsY - edgeMarkerSize - fontSize textOptions = "cn" else vertices = { {v = {edgeDist, 0, 0}}, {v = {edgeDist + edgeMarkerSize, edgeMarkerSize, 0}}, {v = {edgeDist - edgeMarkerSize, edgeMarkerSize, 0}}, } textX = edgeDist textY = edgeMarkerSize textOptions = "cn" end end glShape(GL_TRIANGLES, vertices) glColor(1, 1, 1, alpha) glText(knownCirclePosition_gbl[i][6], textX, textY, fontSize, textOptions) end glColor(1,1,1,1) glLineWidth(1) glPopMatrix() end end end end function widget:DrawWorld() --Reference: minimap_events.lua (Dave Rodgers), gfx_stereo3d.lua (Carrepairer, jK) if #knownCirclePosition_gbl~= nil then for i,_ in pairs(knownCirclePosition_gbl) do --// draw circle on the ground local x,y,z,r = knownCirclePosition_gbl[i][1], knownCirclePosition_gbl[i][2], knownCirclePosition_gbl[i][3], knownCirclePosition_gbl[i][5] local inView = spIsAABBInView(x-r,y-r,z-r, x+r,y+r,z+r ) if inView and (on) then glPushMatrix() glLineWidth(2) glColor(myColor_gbl[1],myColor_gbl[2],myColor_gbl[3], 0.3) glDrawGroundCircle(x,y,z, r, 32) glLineWidth(1) glColor(1,1,1,1) glPopMatrix() end end end end function widget:ViewResize(viewSizeX, viewSizeY) vsX = viewSizeX vsY = viewSizeY sMidX = viewSizeX * 0.5 sMidY = viewSizeY * 0.5 end function widget:Shutdown() gl.DeleteList(circleList_gbl) end
gpl-2.0
xAleXXX007x/Witcher-RolePlay
witcherrp/entities/weapons/nut_bow_long.lua
1
1066
AddCSLuaFile() SWEP.PrintName = "Длинный лук" SWEP.Slot = 0 SWEP.SlotPos = 1 SWEP.DrawAmmo = true SWEP.DrawCrosshair = false SWEP.Category = "WitcherRP" SWEP.Author = "" SWEP.Base = "nut_bow_base" SWEP.Instructions = "" SWEP.Contact = "" SWEP.Purpose = "" SWEP.ViewModelFOV = 72 SWEP.ViewModelFlip = false SWEP.Spawnable = true SWEP.AdminSpawnable = true SWEP.ViewModel = "models/morrowind/steel/longbow/v_steel_longbow.mdl" SWEP.WorldModel = "models/morrowind/steel/longbow/w_steel_longbow.mdl" SWEP.Primary.Damage = 45 SWEP.Primary.Delay = 2 SWEP.Primary.Velocity = 2500 SWEP.Primary.ClipSize = -1 // Size of a clip SWEP.Primary.DefaultClip = 0 // Default number of bullets in a clip SWEP.Primary.Automatic = true // Automatic/Semi Auto SWEP.Primary.Ammo = "XBowBolt" SWEP.Crosshair = true SWEP.Secondary.ClipSize = -1 // Size of a clip SWEP.Secondary.DefaultClip = -1 // Default number of bullets in a clip SWEP.Secondary.Automatic = false // Automatic/Semi Auto SWEP.Secondary.Ammo = "none"
mit
lmangani/ntopng
scripts/lua/inc/password_dialog.lua
1
7006
print [[ <style type='text/css'> .largegroup { width:500px } </style> <div id="password_dialog" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="password_dialog_label" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"><i class="fa fa-times"></i></button> <h3 id="password_dialog_label">Manage User <span id="password_dialog_title"></span></h3> </div> <div class="modal-body"> <div id="password_alert_placeholder"></div> <script> password_alert = function() {} password_alert.error = function(message) { $('#password_alert_placeholder').html('<div class="alert alert-danger"><button type="button" class="close" data-dismiss="alert">x</button>' + message + '</div>'); } password_alert.success = function(message) { $('#password_alert_placeholder').html('<div class="alert alert-success"><button type="button" class="close" data-dismiss="alert">x</button>' + message + '</div>'); } </script> <form data-toggle="validator" id="form_password_reset" class="form-horizontal" method="get" action="password_reset.lua"> ]] print('<input id="csrf" name="csrf" type="hidden" value="'..ntop.getRandomCSRFValue()..'" />\n') print [[ <input id="password_dialog_username" type="hidden" name="username" value="" /> <div class="control-group"> ]] user_group = ntop.getUserGroup() if(user_group ~= "administrator") then print [[ <div class="form-group has-feedback"> <label for="" class="control-label">Old User Password</label> <div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span> <input id="old_password_input" type="password" name="old_password" value="" class="form-control"> </div> </div> ]] end print [[ <div class="form-group has-feedback"> <label for="" class="control-label">New User Password</label> <div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span> <input id="new_password_input" type="password" name="new_password" value="" class="form-control" pattern="^[\w]{1,}$" required> </div> </div> <div class="form-group has-feedback"> <label for="" class="control-label">Confirm New User Password</label> <div class="input-group"><span class="input-group-addon"><i class="fa fa-lock"></i></span> <input id="confirm_new_password_input" type="password" name="confirm_new_password" value="" class="form-control" pattern="^[\w]{1,}$" required> </div> </div> <div class="form-group has-feedback"> <button id="password_reset_submit" class="btn btn-primary btn-block">Change User Password</button> </div> </form> ]] if(user_group=="administrator") then print [[ <div id="pref_part_separator"><hr/></div> <form data-toggle="validator" id="form_pref_change" class="form-horizontal" method="get" action="change_user_prefs.lua"> <input id="pref_dialog_username" type="hidden" name="username" value="" /> <div class="form-group has-feedback"> <label class="input-label">User Role</label> <div class="controls"> <select id="host_role_select" name="host_role" class="form-control"> <option value="standard">Non Privileged User</option> <option value="administrator">Administrator</option> </select> </div> </div> <div class="form-group has-feedback"> <label class="control-label">Allowed Networks</label> <div class="input-group"><span class="input-group-addon"><span class="glyphicon glyphicon-tasks"></span></span> <input id="networks_input" type="text" name="networks" value="" class="form-control" required> </div> <small>Comma separated list of networks this user can view. Example: 192.168.1.0/24,172.16.0.0/16</small> </div> <div class="form-group has-feedback"> <button id="pref_change" class="btn btn-primary btn-block">Change User Preferences</button> </div> </form> ]] end print [[<script> var frmpassreset = $('#form_password_reset'); frmpassreset.submit(function () { if(!isValid($("#new_password_input").val())) { password_alert.error("Password contains invalid chars (a-z, A-Z, 0-9, and _)"); return(false); } if($("#new_password_input").val().length < 5) { password_alert.error("Password too short (< 5 characters)"); return(false); } if($("#new_password_input").val() != $("#confirm_new_password_input").val()) { password_alert.error("Passwords don't match"); return(false); } $.ajax({ type: frmpassreset.attr('method'), url: frmpassreset.attr('action'), data: frmpassreset.serialize(), success: function (data) { var response = jQuery.parseJSON(data); if(response.result == 0) { password_alert.success(response.message); window.location.href = 'users.lua'; } else password_alert.error(response.message); ]] if(user_group ~= "administrator") then print('$("old_password_input").text("");\n'); end print [[ $("new_password_input").text(""); $("confirm_new_password_input").text(""); } }); return false; }); var frmprefchange = $('#form_pref_change'); frmprefchange.submit(function () { var ok = true; if($("#networks_input").val().length == 0) { password_alert.error("Network list not specified"); ok = false; } else { var arrayOfStrings = $("#networks_input").val().split(","); for (var i=0; i < arrayOfStrings.length; i++) { if(!is_network_mask(arrayOfStrings[i])) { password_alert.error("Invalid network list specified ("+arrayOfStrings[i]+")"); ok = false; } } } if(ok) { $.ajax({ type: frmprefchange.attr('method'), url: frmprefchange.attr('action'), data: frmprefchange.serialize(), success: function (response) { if(response.result == 0) { password_alert.success(response.message); window.location.href = 'users.lua'; } else password_alert.error(response.message); } }); } return false; }); </script> </div> <!-- modal-body --> <script> function reset_pwd_dialog(user) { $.getJSON('get_user_info.lua?user='+user, function(data) { $('#password_dialog_title').text(data.username); $('#password_dialog_username').val(data.username); $('#pref_dialog_username').val(data.username); $('#old_password_input').val(''); $('#new_password_input').val(''); $('#confirm_password_input').val(''); $('#host_role_select option[value = '+data.group+']').attr('selected','selected'); $('#networks_input').val(data.allowed_nets); $('#form_pref_change').show(); $('#pref_part_separator').show(); $('#password_alert_placeholder').html(''); $('#add_user_alert_placeholder').html(''); }); return(true); } $('#password_reset_submit').click(function() { $('#form_password_reset').submit(); }); </script> </div> </div> </div> <!-- password_dialog --> ]]
gpl-3.0
saraedum/luci-packages-old
applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
apache-2.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/class/Projectile.lua
1
3328
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" require "engine.Projectile" local Combat = require "mod.class.interface.Combat" module(..., package.seeall, class.inherit(engine.Projectile)) _M.logCombat = Combat.logCombat function _M:init(t, no_default) engine.Projectile.init(self, t, no_default) end --- Moves a projectile on the map -- We override it to allow for movement animations function _M:move(x, y, force) local ox, oy = self.x, self.y local moved = engine.Projectile.move(self, x, y, force) if moved and not force and ox and oy and (ox ~= self.x or oy ~= self.y) and config.settings.tome.smooth_move > 0 then self:setMoveAnim(ox, oy, config.settings.tome.smooth_move, 0) end return moved end function _M:tooltip(x, y) local tstr = tstring{"Projectile: ", self.name} if self.src and self.src.name then local hostile = self.src.faction and game.player:reactionToward(self.src) or 0 local color = {"color", "LIGHT_GREEN"} if hostile < 0 then color = {"color", "LIGHT_RED"} elseif hostile == 0 then color = {"color", "LIGHT_BLUE"} end tstr:add(true, "Origin: ", color, self.src.name, {"color", "LAST"}) end if self.project and self.project.def and self.project.def.typ then if self.project.def.x then tstr:add(true, ("Speed: %d%% %s"):format(self.energy.mod*100, game.level.map:compassDirection(self.project.def.x - self.x, self.project.def.y - self.y) or "")) end if self.project.def.typ.selffire then local x = self.project.def.typ.selffire if x == true then x = 100 end tstr:add(true, "Affect origin chance: ", tostring(x), "%") end if self.project.def.typ.friendlyfire then local x = self.project.def.typ.friendlyfire if x == true then x = 100 end tstr:add(true, "Affect origin's friends chance: ", tostring(x), "%") end end if config.settings.cheat then tstr:add(true, "UID: ", tostring(self.uid), true, "Coords: ", tostring(x), "x", tostring(y)) if self.homing then tstr:add((" homing: %s(%s, %s)"):format(self.homing.target.name, self.homing.target.x,self.homing.target.y)) else tstr:add(" range: ", tostring(self.project.def.typ.range or "nil"), " ==> (", tostring(self.project.def.x), ",", tostring(self.project.def.y), ")") end end return tstr end function _M:resolveSource() if self.src then return self.src:resolveSource() else return self end end --gets the full name of the projectile function _M:getName() local name = self.name or "projectile" if self.src and self.src.name then return self.src.name:capitalize().."'s "..name else return name end end
gpl-3.0
BrokenScience/EconomyMod
EconomyMod_0.0.5/control.lua
1
1405
require("helpers.helpers") -- debug_messages: # = "Message" if not debug_messages then debug_messages = {} end script.on_init(init) script.on_configuration_changed(init) function init() --math.randomseed(os.time()) end -- Test gui control script.on_event("Eco", function(event) local player = game.players[event.player_index] if player.gui.center.test then player.gui.center.test.destroy() else test_open(player) end end) function test_open(player) -- Set up gui local main_frame = player.gui.center.add({type = "frame", name = "test", direction = "vertical", style = "debuggery"}) local frame = main_frame.add({type = "scroll-pane", name = "test-scroll", horizontal_scroll_policy = "auto", vertical_scroll_policy = "auto", style = "test-style"}) local debuggery = main_frame.add({type = "scroll-pane", name = "debuggery", horizontal_scroll_policy = "auto", vertical_scroll_policy = "auto", style = "test-style"}) -- Add inital start message debug_messages = {"start"} if table.count(debug_messages) > 0 then debuggery.add({type = "label", name = next_name(), caption = table.count(debug_messages)}) for __, message in pairs(debug_messages) do debuggery.add({type = "label", name = next_name(), caption = message}) end end for __, item in pairs(item_order) do frame.add({type = "label", name = next_name(), caption = item}) end debuggery.add(debug_messages) end
mit
afds/thrift
test/lua/test_basic_server.lua
30
3451
-- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. require('ThriftTest_ThriftTest') require('TSocket') require('TBufferedTransport') require('TFramedTransport') require('THttpTransport') require('TCompactProtocol') require('TJsonProtocol') require('TBinaryProtocol') require('TServer') require('liblualongnumber') -------------------------------------------------------------------------------- -- Handler TestHandler = ThriftTestIface:new{} -- Stops the server function TestHandler:testVoid() end function TestHandler:testString(str) return str end function TestHandler:testBool(bool) return bool end function TestHandler:testByte(byte) return byte end function TestHandler:testI32(i32) return i32 end function TestHandler:testI64(i64) return i64 end function TestHandler:testDouble(d) return d end function TestHandler:testBinary(by) return by end function TestHandler:testStruct(thing) return thing end -------------------------------------------------------------------------------- -- Test local server function teardown() if server then server:close() end end function parseArgs(rawArgs) local opt = { protocol='binary', transport='buffered', port='9090', } for i, str in pairs(rawArgs) do if i > 0 then k, v = string.match(str, '--(%w+)=(%w+)') assert(opt[k] ~= nil, 'Unknown argument') opt[k] = v end end return opt end function testBasicServer(rawArgs) local opt = parseArgs(rawArgs) -- Handler & Processor local handler = TestHandler:new{} assert(handler, 'Failed to create handler') local processor = ThriftTestProcessor:new{ handler = handler } assert(processor, 'Failed to create processor') -- Server Socket local socket = TServerSocket:new{ port = opt.port } assert(socket, 'Failed to create server socket') -- Transport & Factory local transports = { buffered = TBufferedTransportFactory, framed = TFramedTransportFactory, http = THttpTransportFactory, } assert(transports[opt.transport], 'Failed to create framed transport factory') local trans_factory = transports[opt.transport]:new{} local protocols = { binary = TBinaryProtocolFactory, compact = TCompactProtocolFactory, json = TJSONProtocolFactory, } local prot_factory = protocols[opt.protocol]:new{} assert(prot_factory, 'Failed to create binary protocol factory') -- Simple Server server = TSimpleServer:new{ processor = processor, serverTransport = socket, transportFactory = trans_factory, protocolFactory = prot_factory } assert(server, 'Failed to create server') -- Serve server:serve() server = nil end testBasicServer(arg) teardown()
apache-2.0
behrouz-mansoori/faranesh
plugins/tools.lua
1
21359
--Begin Tools.lua :) local SUDO = 123456789 -- put Your ID here! <=== local function index_function(user_id) for k,v in pairs(_config.admins) do if user_id == v[1] then print(k) return k end end -- If not found return false end local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end local function already_sudo(user_id) for k,v in pairs(_config.sudo_users) do if user_id == v then return k end end -- If not found return false end local function reload_plugins( ) plugins = {} load_plugins() end local function sudolist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = "*List of sudo users :*\n" else text = "_لیست سودو های ربات :_\n" end for i=1,#sudo_users do text = text..i.." - "..sudo_users[i].."\n" end return text end local function adminlist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = '*List of bot admins :*\n' else text = "_لیست ادمین های ربات :_\n" end local compare = text local i = 1 for v,user in pairs(_config.admins) do text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n' i = i +1 end if compare == text then if not lang then text = '_No_ *admins* _available_' else text = '_ادمینی برای ربات تعیین نشده_' end end return text end local function action_by_reply(arg, data) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "adminprom" then local function adminprom_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 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_ }, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "admindem" then local function admindem_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local nameid = index_function(tonumber(data.id_)) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 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_ }, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "visudo" then local function visudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 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_ }, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "desudo" then local function desudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 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_ }, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd 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 == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(arg.user_id) then return false end if data.id_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function run(msg, matches) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if tonumber(msg.sender_user_id_) == SUDO then if matches[1] == "visudo" then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="visudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="visudo"}) 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.chat_id_,username=matches[2],cmd="visudo"}) end end if matches[1] == "desudo" then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="desudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="desudo"}) 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.chat_id_,username=matches[2],cmd="desudo"}) end end end if matches[1] == "adminprom" and is_sudo(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="adminprom"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="adminprom"}) 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.chat_id_,username=matches[2],cmd="adminprom"}) end end if matches[1] == "admindem" and is_sudo(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="admindem"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="admindem"}) 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.chat_id_,username=matches[2],cmd="admindem"}) end end if matches[1] == 'creategroup' and is_admin(msg) then local text = matches[2] tdcli.createNewGroupChat({[0] = msg.sender_user_id_}, text) if not lang then return '_Group Has Been Created!_' else return '_گروه ساخته شد!_' end end if matches[1] == 'createsuper' and is_admin(msg) then local text = matches[2] tdcli.createNewChannelChat({[0] = msg.sender_user_id_}, text) if not lang then return '_SuperGroup Has Been Created!_' else return '_سوپر گروه ساخته شد!_' end end if matches[1] == 'tosuper' and is_admin(msg) then local id = msg.chat_id_ tdcli.migrateGroupChatToChannelChat(id) if not lang then return '_Group Has Been Changed To SuperGroup!_' else return '_گروه به سوپر گروه تبدیل شد!_' end end if matches[1] == 'import' and is_admin(msg) then tdcli.importChatInviteLink(matches[2]) if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'setbotname' and is_sudo(msg) then tdcli.changeName(matches[2]) if not lang then return '_Bot Name Changed To:_ *'..matches[2]..'*' else return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*' end end if matches[1] == 'setbotusername' and is_sudo(msg) then tdcli.changeUsername(matches[2]) if not lang then return '_Bot Username Changed To:_ @'..matches[2] else return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..'' end end if matches[1] == 'delbotusername' and is_sudo(msg) then tdcli.changeUsername('') if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'markread' then if matches[2] == 'on' then redis:set('markread','on') if not lang then return '_Markread >_ *ON*' else return '_تیک دوم >_ *روشن*' end end if matches[2] == 'off' then redis:set('markread','off') if not lang then return '_Markread >_ *OFF*' else return '_تیک دوم >_ *خاموش*' end end end if matches[1] == 'bc' and is_admin(msg) then tdcli.sendMessage(matches[2], 0, 0, matches[3], 0) end if matches[1] == 'broadcast' and is_sudo(msg) then local data = load_data(_config.moderation.data) local bc = matches[2] for k,v in pairs(data) do tdcli.sendMessage(k, 0, 0, bc, 0) end end if matches[1] == 'sudolist' and is_sudo(msg) then return sudolist(msg) end if matches[1] == 'permag' then return tdcli.sendMessage(msg.chat_id_, msg.id_, 1, _config.info_text, 1, 'html') end if matches[1] == 'adminlist' and is_admin(msg) then return adminlist(msg) end if matches[1] == 'leave' and is_admin(msg) then tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil) end if matches[1] == 'autoleave' and is_admin(msg) then local hash = 'auto_leave_bot' --Enable Auto Leave if matches[2] == 'enable' then redis:del(hash) return 'Auto leave has been enabled' --Disable Auto Leave elseif matches[2] == 'disable' then redis:set(hash, true) return 'Auto leave has been disabled' --Auto Leave Status elseif matches[2] == 'status' then if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end end end return { patterns = { "^[!/#](visudo)$", "^[!/#](desudo)$", "^[!/#](sudolist)$", "^[!/#](visudo) (.*)$", "^[!/#](desudo) (.*)$", "^[!/#](adminprom)$", "^[!/#](admindem)$", "^[!/#](adminlist)$", "^[!/#](adminprom) (.*)$", "^[!/#](admindem) (.*)$", "^[!/#](leave)$", "^[!/#](autoleave) (.*)$", "^[!/#](permag)$", "^[!/#](creategroup) (.*)$", "^[!/#](createsuper) (.*)$", "^[!/#](tosuper)$", "^[!/#](import) (.*)$", "^[!/#](setbotname) (.*)$", "^[!/#](setbotusername) (.*)$", "^[!/#](delbotusername) (.*)$", "^[!/#](markread) (.*)$", "^[!/#](bc) (%d+) (.*)$", "^[!/#](broadcast) (.*)$", }, run = run }
gpl-3.0
electricpandafishstudios/Spoon
game/modules/tome-1.4.1/data/talents/chronomancy/temporal-archery.lua
1
4996
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2016 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local archerPreUse = Talents.archerPreUse newTalent{ name = "Phase Shot", type = {"chronomancy/temporal-archery", 1}, require = temporal_req1, points = 5, paradox = function (self, t) return getParadoxCost(self, t, 6) end, cooldown = 3, no_energy = "fake", range = 10, tactical = { ATTACK = {TEMPORAL = 2} }, on_pre_use = function(self, t, silent) return archerPreUse(self, t, silent) end, requires_target = true, action = function(self, t) local tg = {type="bolt"} local targets = self:archeryAcquireTargets(tg) if not targets then return end self:archeryShoot(targets, t, nil, {mult=self:combatTalentWeaponDamage(t, 1.1, 1.9), damtype=DamageType.TEMPORAL, apr=1000}) return true end, info = function(self, t) local weapon = 100 * self:combatTalentWeaponDamage(t, 1.1, 1.9) return ([[You fire a shot that phases out of time and space allowing it to virtually ignore armor. The shot will deal %d%% weapon damage as temporal damage to its target.]]): format(damDesc(self, DamageType.TEMPORAL, weapon)) end } newTalent{ name = "Unerring Shot", type = {"chronomancy/temporal-archery", 2}, require = temporal_req2, points = 5, paradox = function (self, t) return getParadoxCost(self, t, 10) end, cooldown = 8, no_energy = "fake", range = 10, tactical = { ATTACK = {PHYSICAL = 2} }, on_pre_use = function(self, t, silent) return archerPreUse(self, t, silent) end, requires_target = true, action = function(self, t) local tg = {type="bolt"} local targets = self:archeryAcquireTargets(tg) if not targets then return end self:setEffect(self.EFF_ATTACK, 1, {power=100}) self:archeryShoot(targets, t, nil, {mult=self:combatTalentWeaponDamage(t, 1.1, 2.1)}) return true end, info = function(self, t) local weapon = 100 * self:combatTalentWeaponDamage(t, 1.1, 1.9) return ([[You focus your aim and fire a shot with great accuracy, inflicting %d%% weapon damage. Afterwords your attack will remain improved for one turn as the chronomantic effects linger.]]) :format(weapon) end, } newTalent{ name = "Perfect Aim", type = {"chronomancy/temporal-archery", 3}, require = temporal_req3, mode = "sustained", points = 5, sustain_paradox = 30, cooldown = 10, tactical = { BUFF = 2 }, no_energy = true, getPower = function(self, t) return 10 + self:combatTalentSpellDamage(t, 10, 40, getParadoxSpellpower(self, t)) end, activate = function(self, t) local power = t.getPower(self, t) return { ccp = self:addTemporaryValue("combat_critical_power", power), pid = self:addTemporaryValue("combat_physcrit", power / 2), sid = self:addTemporaryValue("combat_spellcrit", power / 2), } end, deactivate = function(self, t, p) self:removeTemporaryValue("combat_critical_power", p.ccp) self:removeTemporaryValue("combat_physcrit", p.pid) self:removeTemporaryValue("combat_spellcrit", p.sid) return true end, info = function(self, t) local power = t.getPower(self, t) return ([[You focus your aim, increasing your critical damage multiplier by %d%% and your physical and spell critical strike chance by %d%% The effect will scale with your Spellpower.]]):format(power, power / 2) end, } newTalent{ name = "Quick Shot", type = {"chronomancy/temporal-archery", 4}, require = temporal_req4, points = 5, paradox = function (self, t) return getParadoxCost(self, t, 20) end, cooldown = function(self, t) return math.ceil(self:combatTalentLimit(t, 0, 13, 5)) end, -- Limit >0 no_energy = true, range = 10, tactical = { ATTACK = {PHYSICAL = 2} }, on_pre_use = function(self, t, silent) return archerPreUse(self, t, silent) end, requires_target = true, action = function(self, t) local old = self.energy.value local targets = self:archeryAcquireTargets() if not targets then return end self:archeryShoot(targets, t, nil, {mult=self:combatTalentWeaponDamage(t, 1, 1.5)}) self.energy.value = old return true end, info = function(self, t) local weapon = 100 * self:combatTalentWeaponDamage(t, 1, 1.5) return ([[You pause time around you long enough to fire a single shot, doing %d%% damage. The damage will scale with your Paradox and the cooldown will go down with more talent points invested.]]):format(weapon) end, }
gpl-3.0
teslamint/luci
applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua
141
1054
--[[ netdiscover_devinfo - SIP Device Information (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.netdiscover_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.netdiscover_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug) luci.controller.luci_diag.netdiscover_common.action_links(m, true) return m
apache-2.0
jjimenezg93/ai-behaviours
moai/3rdparty/luasocket-2.0.2/etc/forward.lua
61
2077
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if table.getn(arg) < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
mit
Blackdutchie/Zero-K
LuaRules/Configs/cai/strategies.lua
4
7640
--[[ example buildTasksMods buildTasksMods = function(buildConfig) buildConfig.robots.factoryByDefId[UnitDefNames['factorycloak'].id].importance = 0 buildConfig.robots.factoryByDefId[UnitDefNames['factoryshield'].id].importance = 1 buildConfig.robots.factoryByDefId[UnitDefNames['factoryveh'].id].importance = 0 buildConfig.robots.factoryByDefId[UnitDefNames['factoryspider'].id].importance = 0 end, --]] local function noFunc() end -- these buildTaskMods function by editing the config supplied as the arg local function BuildTasksMod_Blitz(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factorycloak'].id].importance = 1.1 factory[UnitDefNames['factoryshield'].id].importance = 0.9 factory[UnitDefNames['factoryveh'].id].importance = 1.2 factory[UnitDefNames['factoryhover'].id].importance = 1.2 factory[UnitDefNames['factoryspider'].id].importance = 0.8 factory[UnitDefNames['factoryjump'].id].importance = 0.8 for fac, data in pairs(factory) do if not data.airFactory then data[3].importanceMult = data[3].importanceMult*1.2 -- more raiders data[4].importanceMult = data[4].importanceMult*0.8 -- fewer arty data[5].importanceMult = data[5].importanceMult*1.15 -- more assaults data[6].importanceMult = data[6].importanceMult*0.9 -- fewer skirms data[7].importanceMult = data[7].importanceMult*0.9 -- fewer riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.8 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 0.9 end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.8 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 0.9 end end end local function BuildTasksMod_Pusher(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factoryshield'].id].importance = 1.1 factory[UnitDefNames['factoryhover'].id].importance = 0.9 factory[UnitDefNames['factoryspider'].id].importance = 0.9 factory[UnitDefNames['factorytank'].id].importance = 1.1 for fac, data in pairs(factory) do if not data.airFactory then data[3].importanceMult = data[3].importanceMult*0.9 -- fewer raiders data[4].importanceMult = data[4].importanceMult*1.1 -- more arty data[6].importanceMult = data[6].importanceMult*1.2 -- more skirms data[7].importanceMult = data[7].importanceMult*1.1 -- more riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.9 end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 0.9 end end end local function BuildTasksMod_Defensive(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factorycloak'].id].importance = 0.9 factory[UnitDefNames['factoryshield'].id].importance = 1.1 factory[UnitDefNames['factoryveh'].id].importance = 1.1 factory[UnitDefNames['factoryhover'].id].importance = 0.8 factory[UnitDefNames['factoryspider'].id].importance = 0.8 factory[UnitDefNames['factoryjump'].id].importance = 1.1 factory[UnitDefNames['factorytank'].id].importance = 1.1 for fac, data in pairs(factory) do if not data.airFactory then data[3].importanceMult = data[3].importanceMult*0.8 -- fewer raiders data[4].importanceMult = data[4].importanceMult*0.9 -- less arty data[5].importanceMult = data[5].importanceMult*0.9 -- fewer assaults data[6].importanceMult = data[6].importanceMult*1.1 -- more skirms data[7].importanceMult = data[7].importanceMult*1.2 -- more riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 1.2 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 1.2 end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 1.2 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 1.2 end end end local function BuildTasksMod_Lolz(buildConfig) local factory = buildConfig.robots.factoryByDefId factory[UnitDefNames['factorycloak'].id].importance = 0 factory[UnitDefNames['factoryshield'].id].importance = 0 factory[UnitDefNames['factoryveh'].id].importance = 0 factory[UnitDefNames['factoryhover'].id].importance = 0 factory[UnitDefNames['factoryspider'].id].importance = 0 factory[UnitDefNames['factoryjump'].id].importance = 1 factory[UnitDefNames['factorytank'].id].importance = 0 factory[UnitDefNames['factoryjump'].id].minFacCount = 0 for fac, data in pairs(factory) do if not data.airFactory then --data[3].importanceMult = data[3].importanceMult*0.8 -- fewer raiders --data[4].importanceMult = data[4].importanceMult*0.9 -- less arty --data[5].importanceMult = data[5].importanceMult*0.9 -- fewer assaults data[6].importanceMult = data[6].importanceMult*5 -- more moderators!!! --data[7].importanceMult = data[7].importanceMult*1.2 -- more riots end for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] data.airDefenceQuota[i] = data.airDefenceQuota[i] end end local econ = buildConfig.robots.econByDefId for econBldg, data in pairs(econ) do for i=1,3 do data.defenceQuota[i] = data.defenceQuota[i] * 1.2 data.airDefenceQuota[i] = data.airDefenceQuota[i] * 1.2 end end end strategies = { [1] = { -- standard name = "Standard", chance = 0.2, commanders = { count = 2, [1] = {ID = "armcom1", chance = 0.5}, [2] = {ID = "armcom1", chance = 0.5}, }, buildTasksMods = noFunc, conAndEconHandlerMods = {}, }, [2] = { -- blitz name = "Blitz", chance = 0.2, commanders = { count = 2, [1] = {ID = "armcom1", chance = 0.5}, [2] = {ID = "armcom1", chance = 0.5}, }, buildTasksMods = BuildTasksMod_Blitz, conAndEconHandlerMods = {}, }, [3] = { -- pusher name = "Push", chance = 0.2, commanders = { count = 2, [1] = {ID = "armcom1", chance = 0.5}, [2] = {ID = "armcom1", chance = 0.5}, }, buildTasksMods = BuildTasksMod_Pusher, conAndEconHandlerMods = {}, }, [4] = { -- defensive name = "Defensive", chance = 0.2, commanders = { count = 2, [1] = {ID = "armcom1", chance = 0.4}, [2] = {ID = "armcom1", chance = 0.6}, }, buildTasksMods = BuildTasksMod_Defensive, conAndEconHandlerMods = {}, }, [5] = { -- econ -- FIXME: doesn't do anything right now name = "Econ", chance = 0.2, commanders = { count = 2, [1] = {ID = "armcom1", chance = 0.7}, [2] = {ID = "armcom1", chance = 0.3}, }, buildTasksMods = noFunc, conAndEconHandlerMods = {}, }, [6] = { -- lolz name = "lolz", chance = 0, commanders = { count = 1, [1] = {ID = "armcom1", chance = 1}, }, buildTasksMods = BuildTasksMod_Lolz, conAndEconHandlerMods = {}, }, } local function SelectComm(player, team, strat) local count = strategies[strat].commanders.count local rand = math.random() local commName local total = 0 for i = 1, count do total = total + strategies[strat].commanders[i].chance if rand < total then commName = strategies[strat].commanders[i].ID Spring.SetTeamRulesParam(team, "start_unit", commName) Spring.Echo("CAI: team "..team.." has selected strategy: "..strategies[strat].name..", using commander "..commName) break end end end function SelectRandomStrat(player, team) local count = #strategies local rand = math.random() local stratIndex = 1 local total = 0 for i = 1, count do total = total + strategies[i].chance if rand <= total then SelectComm(player, team, i) stratIndex = i break end end return stratIndex end
gpl-2.0
teslamint/luci
applications/luci-app-upnp/luasrc/controller/upnp.lua
20
1886
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.upnp", package.seeall) function index() if not nixio.fs.access("/etc/config/upnpd") then return end local page page = entry({"admin", "services", "upnp"}, cbi("upnp/upnp"), _("UPnP")) page.dependent = true entry({"admin", "services", "upnp", "status"}, call("act_status")).leaf = true entry({"admin", "services", "upnp", "delete"}, post("act_delete")).leaf = true end function act_status() local ipt = io.popen("iptables --line-numbers -t nat -xnvL MINIUPNPD 2>/dev/null") if ipt then local fwd = { } while true do local ln = ipt:read("*l") if not ln then break elseif ln:match("^%d+") then local num, proto, extport, intaddr, intport = ln:match("^(%d+).-([a-z]+).-dpt:(%d+) to:(%S-):(%d+)") if num and proto and extport and intaddr and intport then num = tonumber(num) extport = tonumber(extport) intport = tonumber(intport) fwd[#fwd+1] = { num = num, proto = proto:upper(), extport = extport, intaddr = intaddr, intport = intport } end end end ipt:close() luci.http.prepare_content("application/json") luci.http.write_json(fwd) end end function act_delete(num) local idx = tonumber(num) local uci = luci.model.uci.cursor() if idx and idx > 0 then luci.sys.call("iptables -t filter -D MINIUPNPD %d 2>/dev/null" % idx) luci.sys.call("iptables -t nat -D MINIUPNPD %d 2>/dev/null" % idx) local lease_file = uci:get("upnpd", "config", "upnp_lease_file") if lease_file and nixio.fs.access(lease_file) then luci.sys.call("sed -i -e '%dd' %q" %{ idx, lease_file }) end luci.http.status(200, "OK") return end luci.http.status(400, "Bad request") end
apache-2.0
mahdibagheri/aqa-mp3
plugins/weather.lua
274
1531
do local BASE_URL = "http://api.openweathermap.org/data/2.5/weather" local function get_weather(location) print("Finding weather in ", location) location = string.gsub(location," ","+") local url = BASE_URL url = url..'?q='..location url = url..'&units=metric' url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f' local b, c, h = http.request(url) if c ~= 200 then return nil end local weather = json:decode(b) local city = weather.name local country = weather.sys.country local temp = 'The temperature in '..city ..' (' ..country..')' ..' is '..weather.main.temp..'°C' local conditions = 'Current conditions are: ' .. weather.weather[1].description if weather.weather[1].main == 'Clear' then conditions = conditions .. ' ☀' elseif weather.weather[1].main == 'Clouds' then conditions = conditions .. ' ☁☁' elseif weather.weather[1].main == 'Rain' then conditions = conditions .. ' ☔' elseif weather.weather[1].main == 'Thunderstorm' then conditions = conditions .. ' ☔☔☔☔' end return temp .. '\n' .. conditions end local function run(msg, matches) local city = 'Madrid,ES' if matches[1] ~= '!weather' then city = matches[1] end local text = get_weather(city) if not text then text = 'Can\'t get weather from that city.' end return text end return { description = "weather in that city (Madrid is default)", usage = "!weather (city)", patterns = { "^!weather$", "^!weather (.*)$" }, run = run } end
gpl-2.0
sleepingwit/premake-core
modules/android/tests/test_android_project.lua
3
3624
local p = premake local suite = test.declare("test_android_project") local vc2010 = p.vstudio.vc2010 local android = p.modules.android -- -- Setup -- local wks, prj function suite.setup() p.action.set("vs2015") wks, prj = test.createWorkspace() end local function prepare() system "android" local cfg = test.getconfig(prj, "Debug", platform) vc2010.clCompile(cfg) end local function preparePropertyGroup() system "android" local cfg = test.getconfig(prj, "Debug", platform) vc2010.propertyGroup(cfg) android.androidApplicationType(cfg) end function suite.minVisualStudioVersion_14() preparePropertyGroup() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'"> <Keyword>Android</Keyword> <RootNamespace>MyProject</RootNamespace> <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion> <ApplicationType>Android</ApplicationType> <ApplicationTypeRevision>2.0</ApplicationTypeRevision>]] end function suite.minVisualStudioVersion_15() p.action.set("vs2017") preparePropertyGroup() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'"> <Keyword>Android</Keyword> <RootNamespace>MyProject</RootNamespace> <MinimumVisualStudioVersion>15.0</MinimumVisualStudioVersion> <ApplicationType>Android</ApplicationType> <ApplicationTypeRevision>3.0</ApplicationTypeRevision>]] end function suite.minVisualStudioVersion_16() p.action.set("vs2019") preparePropertyGroup() test.capture [[ <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Android'"> <Keyword>Android</Keyword> <RootNamespace>MyProject</RootNamespace> <MinimumVisualStudioVersion>16.0</MinimumVisualStudioVersion> <ApplicationType>Android</ApplicationType> <ApplicationTypeRevision>3.0</ApplicationTypeRevision>]] end function suite.noOptions() prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.rttiOff() rtti "Off" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.rttiOn() rtti "On" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <RuntimeTypeInfo>true</RuntimeTypeInfo> ]] end function suite.exceptionHandlingOff() exceptionhandling "Off" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> </ClCompile>]] end function suite.exceptionHandlingOn() exceptionhandling "On" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <ExceptionHandling>Enabled</ExceptionHandling> ]] end function suite.cppdialect_cpp11() cppdialect "C++11" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++11</CppLanguageStandard> ]] end function suite.cppdialect_cpp14() cppdialect "C++14" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++1y</CppLanguageStandard> ]] end function suite.cppdialect_cpp17() cppdialect "C++17" prepare() test.capture [[ <ClCompile> <PrecompiledHeader>NotUsing</PrecompiledHeader> <Optimization>Disabled</Optimization> <CppLanguageStandard>c++1z</CppLanguageStandard> ]] end
bsd-3-clause
samuelmaddock/zombie-escape
ZombieEscape/gamemode/modules/hud/cl_transparency.lua
1
1290
/*--------------------------------------------------------- Player Transparency Distance opacity opacity Thanks to Jetboom for the code (Zombie Survival) ---------------------------------------------------------*/ CVars.PlayerOpacity = CreateClientConVar( "ze_playeropacity", 1, true, false ) CVars.PlayerOpacityDistance = CreateClientConVar( "ze_playeropacity_dist", 80, true, false ) local undomodelblend = false local matWhite = Material("models/debug/debugwhite") function GM:PrePlayerDraw( ply ) if !IsValid(LocalPlayer()) then return end if !CVars.PlayerOpacity:GetBool() then return end if LocalPlayer():Team() == ply:Team() then local radius = CVars.PlayerOpacityDistance:GetInt() or 80 if radius > 0 then local eyepos = EyePos() local dist = ply:NearestPoint(eyepos):Distance(eyepos) if dist < radius then local blend = math.max((dist / radius) ^ 1.4, 0.04) render.SetBlend(blend) if blend < 0.4 then render.ModelMaterialOverride(matWhite) render.SetColorModulation(0.2, 0.2, 0.2) end undomodelblend = true end end end end function GM:PostPlayerDraw( ply ) if undomodelblend then render.SetBlend(1) render.ModelMaterialOverride() render.SetColorModulation(1, 1, 1) undomodelblend = false end end
mit
moltafet35/darkness
plugins/groupmanager.lua
136
11323
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin!" end local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.' end local function set_description(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set group description to:\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function set_rules(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules return rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name has been locked' end end local function unlock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_momod(msg) then return "For moderators only!" end local settings = data[tostring(msg.to.id)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end function run(msg, matches) --vardump(msg) if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] return create_group(msg) end if not is_chat_msg(msg) then return "This is not a group chat." end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if msg.media and is_chat_msg(msg) and is_momod(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end if matches[1] == 'group' and matches[2] == 'lock' then --group lock * if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock * if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == 'settings' then return show_group_settings(msg, data) end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Plugin to manage group chat.", usage = { "!creategroup <group_name> : Create a new group (admin only)", "!setabout <description> : Set group description", "!about : Read group description", "!setrules <rules> : Set group rules", "!rules : Read group rules", "!setname <new_name> : Set group name", "!setphoto : Set group photo", "!group <lock|unlock> name : Lock/unlock group name", "!group <lock|unlock> photo : Lock/unlock group photo", "!group <lock|unlock> member : Lock/unlock group member", "!group settings : Show group settings" }, patterns = { "^!(creategroup) (.*)$", "^!(setabout) (.*)$", "^!(about)$", "^!(setrules) (.*)$", "^!(rules)$", "^!(setname) (.*)$", "^!(setphoto)$", "^!(group) (lock) (.*)$", "^!(group) (unlock) (.*)$", "^!(group) (settings)$", "^!!tgservice (.+)$", "%[(photo)%]", }, run = run, } end
gpl-2.0
AlexandreCA/darkstar
scripts/zones/Port_San_dOria/npcs/Solgierte.lua
13
1357
----------------------------------- -- Area: Port San d'Oria -- NPC: Solgierte -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x237); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
tartina/ardour
share/scripts/_route_template_generic_midi.lua
2
2647
ardour { ["type"] = "EditorAction", name = "Generic MIDI Track", description = [[Example]] } -- If a route_setup function is present in an Editor Action Script -- the script is also listed in the "add track/bus" dialog as meta-template -- -- The function is expected to return a Lua table. The table may be empty. function route_setup () return { -- keys control which AddRouteDialog controls are made sensitive. -- The following keys accept a default value to pre-seed the dialog. ['how_many'] = 1, ['name'] = 'MIDI', ['channels'] = nil, ['track_mode'] = nil, ['strict_io'] = true, -- these keys just need to be set (to something other than nil) -- in order to set the control sensitives ['insert_at'] = ARDOUR.PresentationInfo.max_order, ['group'] = false, -- return value will be a RouteGroup* ['instrument'] = true, -- return value will be a PluginInfoPtr } end -- The Script can be used as EditorAction in which case it can -- optionally provide instantiation parmaters function action_params () return { ['how_many'] = { title = "How Many tracks to add", default = "1" }, ["name"] = { title = "Track Name Prefix", default = "MIDI" }, ["instrument"] = { title = "Add Instrument", default = "true" }, } end function factory (params) return function () -- When called from the AddRouteDialog, 'params' will be a table with -- keys as described in route_setup() above. local p = params or route_setup () local name = p["name"] or 'Audio' local how_many = p["how_many"] or 1 local insert_at = p["insert_at"] or ARDOUR.PresentationInfo.max_order; local group = p["group"] or nil local strict_io = p["strict_io"] or false local instrument = p["instrument"] or nil -- used in 'action-script mode' if instrument == "true" then instrument = ARDOUR.LuaAPI.new_plugin_info ("http://gareus.org/oss/lv2/gmsynth", ARDOUR.PluginType.LV2) -- general midi synth if instrument:isnil () then instrument = ARDOUR.LuaAPI.new_plugin_info ("https://community.ardour.org/node/7596", ARDOUR.PluginType.LV2) -- reasonable synth end if instrument:isnil () then LuaDialog.Message ("MIDI track add", "Cannot find instrument plugin", LuaDialog.MessageType.Info, LuaDialog.ButtonType.Close):run () return end end -- add no instrument if type (instrument) ~= "userdata" then instrument = ARDOUR.PluginInfo () end Session:new_midi_track( ARDOUR.ChanCount(ARDOUR.DataType ("midi"), 1), ARDOUR.ChanCount(ARDOUR.DataType ("audio"), 2), strict_io, instrument, nil, group, how_many, name, insert_at, ARDOUR.TrackMode.Normal, true) end end
gpl-2.0
TannerRogalsky/love.js
spec/main.lua
1
2771
local test_files = love.filesystem.getDirectoryItems('tests') local tests = {} for i,test_file in ipairs(test_files) do local base = test_file:match('([%w_]+)%.lua') if base then tests[base] = require('tests/' .. base) test_files[i] = base end end local selected_test_file_index = 1 local width = love.graphics.getWidth() local font = love.graphics.getFont() local font_height = font:getHeight() local dy = font_height * 3 local widest_text_width = 0 local horizontal_padding = 2 for _,test_file in ipairs(test_files) do local text_width = font:getWidth(test_file) if text_width > widest_text_width then widest_text_width = text_width end end widest_text_width = widest_text_width + horizontal_padding * 2 local function draw_test_list() for i,test_file in ipairs(test_files) do local y = (i - 1) * dy + font_height / 2 love.graphics.setColor(255, 255, 255) love.graphics.print(test_file, horizontal_padding, y) if i == selected_test_file_index then love.graphics.setColor(255, 0, 255) else love.graphics.setColor(255, 255, 0) end love.graphics.rectangle('line', 0, y - font_height, widest_text_width, dy) end love.graphics.setColor(255, 255, 255) love.graphics.line(widest_text_width, 0, widest_text_width, love.graphics.getHeight()) end function love.load(args) test_canvas = love.graphics.newCanvas(love.graphics.getWidth() - widest_text_width, love.graphics.getHeight()) current_test = tests[test_files[selected_test_file_index]]() end function love.update(dt) if current_test and current_test.update then current_test:update(dt) end end function love.draw() draw_test_list() if current_test and current_test.draw then love.graphics.setCanvas(test_canvas) love.graphics.clear() current_test:draw(test_canvas) love.graphics.setCanvas() love.graphics.draw(test_canvas, widest_text_width, 0) end end function love.keypressed(key, scancode, isrepeat) if current_test and current_test.keypressed then current_test:keypressed(key, scancode, isrepeat) end end function love.mousemoved(x, y, dx, dy) if current_test and current_test.mousemoved then current_test:mousemoved(x, y, dx, dy) end end function love.mousepressed(x, y, button, istouch) if x < widest_text_width then local i = math.ceil(y / dy) if i <= #test_files then selected_test_file_index = i current_test = tests[test_files[selected_test_file_index]]() end elseif current_test and current_test.mousepressed then current_test:mousepressed(x, y, button, istouch) end end function love.mousereleased(x, y, button, istouch) if current_test and current_test.mousereleased then current_test:mousereleased(x, y, button, istouch) end end
mit
AlexandreCA/update
scripts/zones/Tavnazian_Safehold/npcs/Caiphimonride.lua
37
1316
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Caiphimonride -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CAIPHIMONRIDE_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 0x40b6,8478, --Longsword 0x43B7,8, --Rusty Bolt 0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet) 0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet) showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/update
scripts/globals/spells/bluemagic/enervation.lua
18
2037
----------------------------------------- -- Spell: Enervation -- Lowers the defense and magical defense of enemies within range -- Spell cost: 48 MP -- Monster Type: Beastmen -- Spell Type: Magical (Dark) -- Blue Magic Points: 5 -- Stat Bonus: HP-5, MP+5 -- Level: 67 -- Casting Time: 6 seconds -- Recast Time: 60 seconds -- Magic Bursts on: Compression, Gravitation, and Darkness -- Combos: Counter ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffectOne = EFFECT_DEFENSE_DOWN; local typeEffectTwo = EFFECT_MAGIC_DEF_DOWN; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local duration = 30 * resist; local returnEffect = typeEffectOne; if (resist >= 0.5) then if (target:hasStatusEffect(typeEffectOne) and target:hasStatusEffect(typeEffectTwo)) then -- the def/mag def down does not overwrite the same debuff from any other source spell:setMsg(75); -- no effect elseif (target:hasStatusEffect(typeEffectOne)) then target:addStatusEffect(typeEffectTwo,8,0,duration); returnEffect = typeEffectTwo; spell:setMsg(236); elseif (target:hasStatusEffect(typeEffectTwo)) then target:addStatusEffect(typeEffectOne,10,0,duration); spell:setMsg(236); else target:addStatusEffect(typeEffectOne,10,0,duration); target:addStatusEffect(typeEffectTwo,8,0,duration); spell:setMsg(236); end; end; return returnEffect; end;
gpl-3.0
AlexandreCA/update
scripts/globals/weaponskills/thunder_thrust.lua
28
1289
----------------------------------- -- Thunder Thrust -- Polearm weapon skill -- Skill Level: 30 -- Deals lightning elemental damage to enemy. Damage varies with TP. -- Aligned with the Light Gorget & Thunder Gorget. -- Aligned with the Light Belt & Thunder Belt. -- Element: Lightning -- Modifiers: STR:40% ; INT:40% -- 100%TP 200%TP 300%TP -- 1.50 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1.5; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_LIGHTNING; params.skill = SKILL_POL; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Windurst_Waters/npcs/Moari-Kaaori.lua
12
3975
----------------------------------- -- Area: Windurst Waters -- NPC: Moari-Kaaori -- Working 100% ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local SayFlowers = player:getQuestStatus(WINDURST,SAY_IT_WITH_FLOWERS); local FlowerProgress = player:getVar("FLOWER_PROGRESS"); local offer = trade:getItem(); if (player:getVar("FLOWER_PROGRESS") == 2) then if (trade:hasItemQty(950, 1) and trade:getItemCount() == 1) then if (SayFlowers == QUEST_COMPLETED) then player:startEvent(0x020D,GIL_RATE*400); elseif (SayFlowers == QUEST_ACCEPTED) then player:startEvent(0x0208); end elseif (offer == 941 or offer == 948 or offer == 949 or offer == 956 or offer == 957 or offer == 958) then player:startEvent(0x020A); -- Brought wrong flowers. end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SayFlowers = player:getQuestStatus(WINDURST,SAY_IT_WITH_FLOWERS); local FlowerProgress = player:getVar("FLOWER_PROGRESS"); local zoned = player:getLocalVar("FLOWER_ZONE"); if (FlowerProgress == 2) then player:startEvent(0x0203); -- Waiting for trade. elseif (zoned == 1) then -- Must zone to retry quest. player:startEvent(0x0209); elseif (SayFlowers == QUEST_AVAILABLE and player:getFameLevel(WINDURST) >= 2) then player:startEvent(0x0202); -- Begin Say It with Flowers. elseif (SayFlowers == QUEST_COMPLETED and zoned == 0) then player:startEvent(0x020B); -- Repeat Say It with Flowers. else player:startEvent(0x0200); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0202 and option == 1) then if (player:getQuestStatus(WINDURST,SAY_IT_WITH_FLOWERS) == QUEST_COMPLETED) then player:setVar("FLOWER_PROGRESS",2); else player:addQuest(WINDURST,SAY_IT_WITH_FLOWERS); end elseif (csid == 0x0208) then -- First completion, Iron Sword awarded. player:tradeComplete(); player:completeQuest(WINDURST,SAY_IT_WITH_FLOWERS); player:addFame(WINDURST,30); player:addItem(16536); player:messageSpecial(ITEM_OBTAINED,16536); player:setVar("FLOWER_PROGRESS",0); player:setLocalVar("FLOWER_ZONE",1); player:setTitle(CUPIDS_FLORIST); elseif (csid == 0x020A) then -- Wrong flowers so complete quest, but smaller reward/fame and no title. player:completeQuest(WINDURST,SAY_IT_WITH_FLOWERS); player:tradeComplete(); player:addGil(100); player:messageSpecial(GIL_OBTAINED,100); player:addFame(WINDURST,10); player:setLocalVar("FLOWER_ZONE",1); player:setVar("FLOWER_PROGRESS",0); elseif (csid == 0x020D) then -- Repeatable quest rewards. player:tradeComplete(); player:addFame(WINDURST,30); player:addGil(GIL_RATE*400); player:setVar("FLOWER_PROGRESS",0); player:setLocalVar("FLOWER_ZONE",1); player:setTitle(CUPIDS_FLORIST); elseif (csid == 0x020B) then player:setVar("FLOWER_PROGRESS",2); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Kazham/npcs/Nti_Badolsoma.lua
15
1053
----------------------------------- -- Area: Kazham -- NPC: Nti Badolsoma -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B2); -- scent from Blue Rafflesias else player:startEvent(0x0058); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/update
scripts/globals/weaponskills/vorpal_thrust.lua
30
1397
----------------------------------- -- Vorpal Thrust -- Polearm weapon skill -- Skill Level: 175 -- Delivers a single-hit attack. Chance of params.critical varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Aqua Gorget & Light Gorget. -- Aligned with the Aqua Belt & Light Belt. -- Element: None -- Modifiers: STR:50% ; AGI:50% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.2; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.3; params.crit200 = 0.6; params.crit300 = 0.9; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.5; params.agi_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
pedro-andrade-inpe/ca
lua/Growth.lua
1
1212
--- Simple growth model. A given population starts from the center of space -- and grows randomly. -- @arg data.dim The x and y dimensions of space. -- @arg data.finalTime A number with the final time of the simulation. -- @arg data.probability The probability of a cell to become alive once -- it has an alive neighbor. -- @image growth.bmp Growth = Model{ finalTime = 100, dim = 100, probability = 0.15, random = true, init = function(model) model.cell = Cell{ init = function(cell) if cell.x == model.dim / 2 and cell.y == model.dim / 2 then cell.state = "alive" else cell.state = "empty" end end, execute = function(cell) local count = countNeighbors(cell, "alive") if cell.past.state == "empty" and count > 0 and Random():number() < model.probability then cell.state = "alive" end end } model.cs = CellularSpace{ xdim = model.dim, instance = model.cell, } model.cs:createNeighborhood{strategy = "vonneumann"} model.map = Map{ target = model.cs, select = "state", value = {"alive", "empty"}, color = {"white", "black"} } model.timer = Timer{ Event{action = model.cs}, Event{action = model.map} } end }
gpl-3.0
niedzielski/premake-4.4-beta4
tests/base/test_action.lua
59
1366
-- -- tests/base/test_action.lua -- Automated test suite for the action list. -- Copyright (c) 2009 Jason Perkins and the Premake project -- T.action = { } -- -- Setup/teardown -- local fake = { trigger = "fake", description = "Fake action used for testing", } function T.action.setup() premake.action.list["fake"] = fake solution "MySolution" configurations "Debug" project "MyProject" premake.bake.buildconfigs() end function T.action.teardown() premake.action.list["fake"] = nil end -- -- Tests for call() -- function T.action.CallCallsExecuteIfPresent() local called = false fake.execute = function () called = true end premake.action.call("fake") test.istrue(called) end function T.action.CallCallsOnSolutionIfPresent() local called = false fake.onsolution = function () called = true end premake.action.call("fake") test.istrue(called) end function T.action.CallCallsOnProjectIfPresent() local called = false fake.onproject = function () called = true end premake.action.call("fake") test.istrue(called) end function T.action.CallSkipsCallbacksIfNotPresent() test.success(premake.action.call, "fake") end -- -- Tests for set() -- function T.action.set_SetsActionOS() local oldos = _OS _OS = "linux" premake.action.set("vs2008") test.isequal(_OS, "windows") _OS = oldos end
bsd-3-clause
paly2/minetest-minetestforfun-server
mods/fishing/fishes.lua
1
3708
------------------------------------------------------------------------------------------- -- Fishing - crabman77 version -- Rewrited from original Fishing - Mossmanikin's version - Fishes 0.0.4 -- License (code & textures): WTFPL ----------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------- -- Fish ----------------------------------------------------------------------------------------------- minetest.register_craftitem("fishing:fish_raw", { description = fishing_setting.func.S("Fish"), groups = {}, inventory_image = "fishing_fish_raw.png", on_use = minetest.item_eat(2), }) ----------------------------------------------------- -- Roasted Fish ----------------------------------------------------- minetest.register_craftitem("fishing:fish_cooked", { description = fishing_setting.func.S("Roasted Fish"), groups = {}, inventory_image = "fishing_fish_cooked.png", on_use = minetest.item_eat(4), }) ----------------------------------------------------- -- Sushi ----------------------------------------------------- minetest.register_craftitem("fishing:sushi", { description = fishing_setting.func.S("Sushi (Hoso Maki)"), groups = {}, inventory_image = "fishing_sushi.png", on_use = minetest.item_eat(6), }) ----------------------------------------------------------------------------------------------- -- clownfish ----------------------------------------------------------------------------------------------- minetest.register_craftitem("fishing:clownfish_raw", { description = fishing_setting.func.S("Clownfish"), groups = {}, inventory_image = "fishing_clownfish_raw.png", on_use = minetest.item_eat(2), }) ----------------------------------------------------------------------------------------------- -- bluewhite ----------------------------------------------------------------------------------------------- minetest.register_craftitem("fishing:bluewhite_raw", { description = fishing_setting.func.S("Bluewhite"), groups = {}, inventory_image = "fishing_bluewhite_raw.png", on_use = minetest.item_eat(2), }) ----------------------------------------------------------------------------------------------- -- Whatthef... it's a freakin' Shark! ----------------------------------------------------------------------------------------------- minetest.register_craftitem("fishing:shark_raw", { description = fishing_setting.func.S("Shark"), groups = {}, inventory_image = "fishing_shark_raw.png", on_use = minetest.item_eat(2), }) ----------------------------------------------------- -- Roasted Shark ----------------------------------------------------- minetest.register_craftitem("fishing:shark_cooked", { description = fishing_setting.func.S("Roasted Shark"), groups = {}, inventory_image = "fishing_shark_cooked.png", on_use = minetest.item_eat(6), }) ----------------------------------------------------------------------------------------------- -- Pike ----------------------------------------------------------------------------------------------- minetest.register_craftitem("fishing:pike_raw", { description = fishing_setting.func.S("Northern Pike"), groups = {}, inventory_image = "fishing_pike_raw.png", on_use = minetest.item_eat(2), }) ----------------------------------------------------- -- Roasted Pike ----------------------------------------------------- minetest.register_craftitem("fishing:pike_cooked", { description = fishing_setting.func.S("Roasted Northern Pike"), groups = {}, inventory_image = "fishing_pike_cooked.png", on_use = minetest.item_eat(6), })
unlicense
AlexandreCA/update
scripts/zones/West_Sarutabaruta/npcs/Roshina-Kuleshuna_WW.lua
30
3078
----------------------------------- -- Area: West Sarutabaruta -- NPC: Roshina-Kuleshuna, W.W. -- Type: Outpost Conquest Guards -- @pos -11.322 -13.459 317.696 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Sarutabaruta/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = SARUTABARUTA; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Western_Adoulin/npcs/Fleuricette.lua
2
1035
----------------------------------- -- Area: Western Adoulin -- NPC: Fleuricette -- Location: D-8 ----------------------------------- package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Adoulin/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x4B0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/update
scripts/zones/Bastok_Markets/npcs/Loulia.lua
37
1076
----------------------------------- -- Area: Bastok Markets -- NPC: Loulia -- Type: Room Renters -- @zone: 235 -- @pos -176.212 -9 -25.049 -- -- Auto-Script: Requires Verification. Validated standard dialog - thrydwolf 12/8/2011 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01e7); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
anubis34/luaGLEW
luaglew_test/loadtga.lua
1
1507
------------------------------------------------------------------ -- A simple TGA loader. -- Loads the TGA file with the given fileName. -- Supports only 24 or 32 bits color TGAs with no compression. ------------------------------------------------------------------ function LoadTGA(fileName) local file = io.open(fileName, "rb") if file == nil then return nil, "Unnable to open file '" .. fileName .. "'." end local texture = {} local header = file:read(18) if header == nil then return nil, "Error loading header data." end texture.components = header:byte(17) / 8 texture.width = header:byte(14) * 256 + header:byte(13) texture.height = header:byte(16) * 256 + header:byte(15) texture.target = "GL_TEXTURE_2D" texture.type = "GL_UNSIGNED_BYTE" texture.format = (texture.components == 4) and "GL_RGBA" or "GL_RGB" if header:byte(3) ~= 2 then return nil, "Unsupported tga type. Only 24/32 bits uncompressed images are supported." end --texture.data = {} for j=1, texture.height do local line = {} for i=1, texture.width do data = file:read(texture.components) if data == nil then return nil, "Error loading data." end table.insert(line, data:byte(3)) table.insert(line, data:byte(2)) table.insert(line, data:byte(1)) if texture.components == 4 then table.insert(line, data:byte(4)) end end table.insert(texture, line) end file:close() return texture end
mit
AlexandreCA/update
scripts/globals/items/loaf_of_homemade_bread.lua
35
1131
----------------------------------------- -- ID: 5228 -- Item: loaf_of_homemade_bread -- Food Effect: 30Min, All Races ----------------------------------------- -- Agility 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5228); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/timbre_timbers_salad.lua
35
1471
----------------------------------------- -- ID: 4321 -- Item: timbre_timbers_salad -- Food Effect: 240Min, All Races ----------------------------------------- -- Magic 20 -- Agility 5 -- Vitality -1 -- Ranged ACC % 8 -- Ranged ACC Cap 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4321); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 20); target:addMod(MOD_AGI, 5); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_RACCP, 8); target:addMod(MOD_FOOD_RACC_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 20); target:delMod(MOD_AGI, 5); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_RACCP, 8); target:delMod(MOD_FOOD_RACC_CAP, 15); end;
gpl-3.0
AlexandreCA/update
scripts/zones/Yuhtunga_Jungle/npcs/Robino-Mobino.lua
17
1857
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Robino-Mobino -- @pos -244 0 -401 123 ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Yuhtunga_Jungle/TextIDs"); local region = ELSHIMOLOWLANDS; local csid = 0x7ff4; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/globals/spells/bluemagic/occultation.lua
46
1612
----------------------------------------- -- Spell: Occultation -- Creates shadow images that each absorb a single attack directed at you -- Spell cost: 138 MP -- Monster Type: Seethers -- Spell Type: Magical (Wind) -- Blue Magic Points: 3 -- Stat Bonus: VIT+3 CHR-2 -- Level: 88 -- Casting Time: 2 seconds -- Recast Time: 1 minute, 30 seconds -- -- Combos: Evasion Bonus ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end;----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_BLINK; local skill = caster:getSkillLevel(BLUE_SKILL); local power = (skill / 50); local duration = 300; -- 400 skill = 8 shadows, 450 = 9 shadows, so I am assuming every 50 skill is a shadow. -- Also assuming minimum of 2 shadows. -- I've never seen the spell cast with under 100 skill, so I could be wrong. if (skill < 100) then power = 2; end; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Full_Moon_Fountain/npcs/Moon_Spiral.lua
27
1442
----------------------------------- -- Area: Full Moon Fountain -- NPC: Moon Spiral -- Involved in Quests: The Moonlit Path -- @pos -302 9 -260 170 ----------------------------------- package.loaded["scripts/zones/Full_Moon_Fountain/TextIDs"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Full_Moon_Fountain/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) printf("onUpdate CSID: %u",csid); printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) printf("onFinish CSID: %u",csid); printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Upper_Jeuno/npcs/Mairee.lua
27
1734
----------------------------------- -- Area: Upper Jeuno -- NPC: Mairee -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/chocobo"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 20) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); player:startEvent(0x2712,price,gil); else player:startEvent(0x2715); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x2712 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); player:setPos(486,8,-160,0x80,0x69); end end end;
gpl-3.0
AlexandreCA/update
scripts/commands/changejob.lua
26
1936
--------------------------------------------------------------------------------------------------- -- func: changejob -- desc: Changes the players current job. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "si" }; function onTrigger(player, job, level) local jobList = { ["war"] = 1, ["mnk"] = 2, ["whm"] = 3, ["blm"] = 4, ["rdm"] = 5, ["thf"] = 6, ["pld"] = 7, ["drk"] = 8, ["bst"] = 9, ["brd"] = 10, ["rng"] = 11, ["sam"] = 12, ["nin"] = 13, ["drg"] = 14, ["smn"] = 15, ["blu"] = 16, ["cor"] = 17, ["pup"] = 18, ["dnc"] = 19, ["sch"] = 20, ["geo"] = 21, ["run"] = 22 }; if (job == nil) then player:PrintToPlayer("You must enter a job id or short-name."); return; end local jobId = 0; if (tonumber(job) ~= nil and tonumber(job) ~= 0) then jobId = job; else jobId = jobList[ string.lower( job ) ]; if (jobId == nil) then player:PrintToPlayer( string.format( "Invalid job '%s' given. Use short name or id. e.g. WAR", job ) ); return; end end -- Ensure player entered a valid id.. if (jobId <= 0 or jobId > 22) then player:PrintToPlayer( "Invalid job id given; must be between 1 and 22. Or use a short name e.g. WAR" ); return; end -- Change the players job.. player:changeJob( jobId ); -- Attempt to set the players level.. if (level ~= nil and level > 0 and level <= 99) then player:setLevel( level ); else player:PrintToPlayer( "Invalid level given. Level must be between 1 and 99!" ); end end
gpl-3.0
AlexandreCA/update
scripts/zones/Beadeaux/npcs/The_Mute.lua
19
1258
----------------------------------- -- Area: Beadeaux -- NPC: ??? -- @pos -166.230 -1 -73.685 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beadeaux/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local duration = math.random(600,900); if (player:getQuestStatus(BASTOK,THE_CURSE_COLLECTOR) == QUEST_ACCEPTED and player:getVar("cCollectSilence") == 0) then player:setVar("cCollectSilence",1); end player:addStatusEffect(EFFECT_SILENCE,0,0,duration); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
martolini/Vana
scripts/portals/s4tornado_enter.lua
1
1031
--[[ Copyright (C) 2008-2015 Vana Development Team 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] -- Cloud Balcony, Night Lord quest if getJob() == 412 then map = false; if getItemAmount(4001110) > 0 and isQuestInactive(6230) then map = true; elseif isQuestActive(6230) then map = true; elseif isQuestCompleted(6230) and isQuestInactive(6231) then map = true; end if map then playPortalSe(); setMap(922020200); end end
gpl-2.0
AlexandreCA/update
scripts/zones/Valkurm_Dunes/npcs/Stone_Monument.lua
32
1285
----------------------------------- -- Area: Valkurm Dunes -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -311.299 -4.420 -138.878 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00008); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/update
scripts/globals/spells/raiton_san.lua
17
1627
----------------------------------------- -- Spell: Raiton: San -- Deals lightning damage to an enemy and lowers its resistance against earth. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_RAITON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_RAITON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if(caster:getMerit(MERIT_RAITON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_RAITON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_RAITON_SAN) - 5; end; if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(134,1,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_EARTHRES); return dmg; end;
gpl-3.0
AlexandreCA/update
scripts/zones/Castle_Zvahl_Baileys/TextIDs.lua
9
1092
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. come back after sorting your inventory. ITEM_OBTAINED = 6543; -- Obtained: <item>. GIL_OBTAINED = 6544; -- Obtained <number> gil. KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7216; -- You unlock the chest! CHEST_FAIL = 7217; -- Fails to open the chest. CHEST_TRAP = 7218; -- The chest was trapped! CHEST_WEAK = 7219; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7220; -- The chest was a mimic! CHEST_MOOGLE = 7221; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7222; -- The chest was but an illusion... CHEST_LOCKED = 7223; -- The chest appears to be locked. -- Quest dialog SENSE_OF_FOREBODING = 6558; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 7546; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
commodo/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/nat_traffic.lua
79
1251
local function scrape() -- documetation about nf_conntrack: -- https://www.frozentux.net/iptables-tutorial/chunkyhtml/x1309.html nat_metric = metric("node_nat_traffic", "gauge" ) for e in io.lines("/proc/net/nf_conntrack") do -- output(string.format("%s\n",e )) local fields = space_split(e) local src, dest, bytes; bytes = 0; for _, field in ipairs(fields) do if src == nil and string.match(field, '^src') then src = string.match(field,"src=([^ ]+)"); elseif dest == nil and string.match(field, '^dst') then dest = string.match(field,"dst=([^ ]+)"); elseif string.match(field, '^bytes') then local b = string.match(field, "bytes=([^ ]+)"); bytes = bytes + b; -- output(string.format("\t%d %s",ii,field )); end end -- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) .- bytes=([^ ]+)"); -- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) sport=[^ ]+ dport=[^ ]+ packets=[^ ]+ bytes=([^ ]+)") local labels = { src = src, dest = dest } -- output(string.format("src=|%s| dest=|%s| bytes=|%s|", src, dest, bytes )) nat_metric(labels, bytes ) end end return { scrape = scrape }
gpl-2.0
AlexandreCA/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/Sarcophagus.lua
12
4691
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Sarcophagus -- Involved in Quest: The Requiem (BARD AF2) -- @pos -420 8 500 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- sarcophagusNumber ----------------------------------- function sarcophagusNumber(X,Z) if (X <= -423 and X >= -426 and Z >= 494 and Z <= 499) then return 1; elseif (X <= -418 and X >= -423 and Z >= 500 and Z <= 505) then return 2; elseif (X <= -415 and X >= -418 and Z >= 500 and Z <= 505) then return 3; elseif (X <= -410 and X >= -415 and Z >= 500 and Z <= 505) then return 4; elseif (X <= -410 and X >= -415 and Z >= 494 and Z <= 499) then return 5; end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("TheRequiemCS") == 3 and trade:hasItemQty(4154,1) and trade:getItemCount() == 1) then if (player:getVar("TheRequiemRandom") == 0) then player:setVar("TheRequiemRandom",math.random(1,5)); end if (sarcophagusNumber(npc:getXPos(),npc:getZPos()) == player:getVar("TheRequiemRandom") and player:getVar("TheRequiemYumKilled") == 0) then player:tradeComplete(); player:messageSpecial(SENSE_OF_FOREBODING); player:setVar("TheRequiemAlreadyPoped",1); SpawnMob(17576264,300):updateClaim(player); -- Spawn Yum Kimil NM @pos -414 8 499 SpawnMob(17576267,180):updateClaim(player); -- Spawn Owl Guardian NM @pos -414 8 501 SpawnMob(17576266,180):updateClaim(player); -- Spawn Dog Guardian NM @pos -414 8 497 else player:messageSpecial(NOTHING_HAPPENED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ANewDawn = player:getQuestStatus(JEUNO,A_NEW_DAWN); local ANewDawnEvent = player:getVar("ANewDawn_Event"); -- BST AF3 Quest if (sarcophagusNumber(npc:getXPos(),npc:getZPos()) == 4 and ANewDawn == QUEST_ACCEPTED) then if (ANewDawnEvent == 4) then for i = 17576267, 17576269 do if (GetMobAction(i) == 0) then SpawnMob(i,180):updateClaim(player); -- Spawn Sturm, Taifun and Trombe. end end elseif (ANewDawnEvent == 5) then player:startEvent(0x002d); end -- BRD AF Quest elseif (sarcophagusNumber(npc:getXPos(),npc:getZPos()) == player:getVar("TheRequiemRandom")) then if (player:getVar("TheRequiemYumKilled") == 1) then player:startEvent(0x002e); elseif (player:getVar("TheRequiemAlreadyPoped") == 1) then player:messageSpecial(SENSE_OF_FOREBODING); SpawnMob(17576264):updateClaim(player); -- Spawn Yum Kimil NM @pos -414 8 499 SpawnMob(17576267):updateClaim(player); -- Spawn Owl Guardian NM @pos -414 8 501 SpawnMob(17576266):updateClaim(player); -- Spawn Dog Guardian NM @pos -414 8 497 end -- Standard Dialogue else player:messageSpecial(SARCOPHAGUS_CANNOT_BE_OPENED); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002e) then player:setVar("TheRequiemCS",0); player:setVar("TheRequiemYumKilled",0); player:setVar("TheRequiemRandom",0); player:setVar("TheRequiemAlreadyPoped",0); player:addKeyItem(STAR_RING1); player:messageSpecial(KEYITEM_OBTAINED,STAR_RING1); -- Star Ring (Key Item). elseif (csid == 0x002d) then player:setVar("ANewDawn_Event",6); player:delKeyItem(217); player:addTitle(196); player:addItem(14222,1); player:messageSpecial(ITEM_OBTAINED,14222); player:completeQuest(JEUNO,A_NEW_DAWN); player:addFame(JEUNO, 30); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Mhaura/npcs/Explorer_Moogle.lua
13
1862
----------------------------------- -- Area: Mhaura -- NPC: Explorer Moogle ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local accept = 0; local event = 0x014e; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); local price = 300; if (csid == 0x014e) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/pestle.lua
41
1123
----------------------------------------- -- ID: 18599 -- Item: Pestle -- Additional effect: MP Drain ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance or target:isUndead()) then return 0,0,0; else local drain = math.random(2,8); local params = {}; params.bonusmab = 0; params.includemab = false; -- drain = addBonusesAbility(player, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(player,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); drain = finalMagicNonSpellAdjustments(player,target,ELE_DARK,drain); if (drain > target:getMP()) then drain = target:getMP(); end target:addMP(-drain); return SUBEFFECT_MP_DRAIN, MSGBASIC_ADD_EFFECT_MP_DRAIN, player:addMP(drain); end end;
gpl-3.0
jstewart-amd/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
AlexandreCA/update
scripts/zones/Port_Windurst/npcs/Gold_Skull.lua
17
2228
----------------------------------- -- Area: Port Windurst -- NPC: Gold Skull -- Mission NPC ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(BASTOK) ~= 255) then currentMission = player:getCurrentMission(BASTOK); missionStatus = player:getVar("MissionStatus"); if (player:hasKeyItem(SWORD_OFFERING)) then player:startEvent(0x0035); elseif (player:hasKeyItem(KINDRED_REPORT)) then player:startEvent(0x0044); elseif (currentMission == THE_EMISSARY_WINDURST2) then if (missionStatus == 7) then player:startEvent(0x003e); elseif (missionStatus == 8) then player:showText(npc,GOLD_SKULL_DIALOG + 27); elseif (missionStatus == 9) then player:startEvent(0x0039); end elseif (currentMission == THE_EMISSARY_WINDURST) then if (missionStatus == 2) then player:startEvent(0x0032); elseif (missionStatus == 12) then player:startEvent(0x0036); elseif (missionStatus == 14) then player:showText(npc,GOLD_SKULL_DIALOG); elseif (missionStatus == 15) then player:startEvent(0x0039); end else player:startEvent(0x002b); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0035) then player:addKeyItem(DULL_SWORD); player:messageSpecial(KEYITEM_OBTAINED,DULL_SWORD); player:delKeyItem(SWORD_OFFERING); end end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/spirit_sword.lua
16
1559
----------------------------------------- -- ID: 16613 -- Spirit Sword -- Additional effect: Light damage -- Enchantment: TP+100 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(7,21); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end; ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getFreeSlotsCount() == 0) then result = 308; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addTP(10); -- Core currently makes this *10 stated value, so its 100... end;
gpl-3.0
paly2/minetest-minetestforfun-server
mods/shutdown/init.lua
1
2060
--[[ shutdown par turbogus, code sous licence gpl2 ou sup déclaration du "timer" par Jat ( du mod annonce ) Affiche l'heure dans le chat toute les minutes et arrête votre serveur "proprement" à une heure précise afin de créer une sauvegarde ]]-- -- compatibility with soundset mod local SOUNDVOLUME = 1 local get_volume if (minetest.get_modpath("soundset")) ~= nil then get_volume = soundset.get_gain else get_volume = function (player_name, sound_type) return SOUNDVOLUME end end local function sound_play_all(sound) for _, p in ipairs(minetest.get_connected_players()) do local player_name = p:get_player_name() if player_name then minetest.sound_play(sound, {to_player=player_name, gain=get_volume(player_name, "other")}) end end end local timer = 0 local function tick() local heure = os.date("%H") local minute = os.date("%M") -- Warn every days if heure == "4" then if minute == "00" then minetest.chat_send_all("Rappel : Redémarrage journalier du serveur dans 30 minutes. (Dure 30 minutes)") minetest.chat_send_all("Reminder : Daily reboot of the server in 30 minutes. (Lasts 30 minutes)") sound_play_all("shutdown_shutdown") elseif minute == "15" then minetest.chat_send_all("Rappel : Redémarrage journalier du serveur dans 15 minutes. (Dure 30 minutes)") minetest.chat_send_all("Reminder : Daily reboot of the server in 15 minutes. (Lasts 30 minutes)") sound_play_all("shutdown_shutdown") elseif minute == "25" then minetest.chat_send_all("Rappel : Redémarrage journalier du serveur dans 5 minutes - Pensez à vous deconnecter !") minetest.chat_send_all("Reminder : Daily reboot of the server in 5 minutes - Think about logout!") sound_play_all("shutdown_shutdown") elseif minute == "29" then minetest.chat_send_all("=== ARRET DU SERVEUR - DE NOUVEAU EN LIGNE DANS 30 MIN ===") minetest.chat_send_all("=== SERVER SHUTTING DOWN - ONLINE AGAIN IN 30 MIN ===") sound_play_all("shutdown_shutdown") -- minetest.request_shutdown() end end minetest.after(60, tick) end tick()
unlicense
mobinantispam/test-bot
plugins/quran.lua
11
1413
-- Umbrella Quran Project -- http://umbrella.shayan-soft.ir -- https://telegram.me/umbrellateam -- Programmer : Engineer Shayan Ahmadi -- https://telegram.me/shayansoft do umbrella = "http://umbrella.shayan-soft.ir/quran/" -- database -- get sound of sura local function read_sura(chat_id, target) local readq = http.request(umbrella.."Sura"..target..".mp3") local url = umbrella.."Sura"..target..".mp3" local file = download_to_file(url) local cb_extra = {file_path=file} return send_document("chat#id"..chat_id, file, rmtmp_cb, cb_extra) end -- get text of sura local function view_sura(chat_id, target) local viewq = http.request(umbrella.."quran ("..target..").txt") return viewq end -- run script local function run(msg, matches) local chat_id = msg.to.id if matches[1] == "read" then local target = matches[2] return read_sura(chat_id, target) elseif matches[1] == "sura" then local target = matches[2] return view_sura(chat_id, target) elseif matches [1] == "quran" then local qlist = http.request(umbrella.."list.txt") -- list of suras return qlist end end -- other help and commands return { description = "Umbrella Quran Project", usage = { "!sura (num) : view arabic sura", "!read (num) : send sound of sura", "!quran : sura list of quran", }, patterns = { "^[!/](sura) (.+)$", "^[!/](read) (.+)$", "^[!/](quran)$", }, run = run, } end
gpl-2.0
zhoukk/skynet
service/cslave.lua
50
6448
local skynet = require "skynet" local socket = require "socket" require "skynet.manager" -- import skynet.launch, ... local table = table local slaves = {} local connect_queue = {} local globalname = {} local queryname = {} local harbor = {} local harbor_service local monitor = {} local monitor_master_set = {} local function read_package(fd) local sz = socket.read(fd, 1) assert(sz, "closed") sz = string.byte(sz) local content = assert(socket.read(fd, sz), "closed") return skynet.unpack(content) end local function pack_package(...) local message = skynet.packstring(...) local size = #message assert(size <= 255 , "too long") return string.char(size) .. message end local function monitor_clear(id) local v = monitor[id] if v then monitor[id] = nil for _, v in ipairs(v) do v(true) end end end local function connect_slave(slave_id, address) local ok, err = pcall(function() if slaves[slave_id] == nil then local fd = assert(socket.open(address), "Can't connect to "..address) skynet.error(string.format("Connect to harbor %d (fd=%d), %s", slave_id, fd, address)) slaves[slave_id] = fd monitor_clear(slave_id) socket.abandon(fd) skynet.send(harbor_service, "harbor", string.format("S %d %d",fd,slave_id)) end end) if not ok then skynet.error(err) end end local function ready() local queue = connect_queue connect_queue = nil for k,v in pairs(queue) do connect_slave(k,v) end for name,address in pairs(globalname) do skynet.redirect(harbor_service, address, "harbor", 0, "N " .. name) end end local function response_name(name) local address = globalname[name] if queryname[name] then local tmp = queryname[name] queryname[name] = nil for _,resp in ipairs(tmp) do resp(true, address) end end end local function monitor_master(master_fd) while true do local ok, t, id_name, address = pcall(read_package,master_fd) if ok then if t == 'C' then if connect_queue then connect_queue[id_name] = address else connect_slave(id_name, address) end elseif t == 'N' then globalname[id_name] = address response_name(id_name) if connect_queue == nil then skynet.redirect(harbor_service, address, "harbor", 0, "N " .. id_name) end elseif t == 'D' then local fd = slaves[id_name] slaves[id_name] = false if fd then monitor_clear(id_name) socket.close(fd) end end else skynet.error("Master disconnect") for _, v in ipairs(monitor_master_set) do v(true) end socket.close(master_fd) break end end end local function accept_slave(fd) socket.start(fd) local id = socket.read(fd, 1) if not id then skynet.error(string.format("Connection (fd =%d) closed", fd)) socket.close(fd) return end id = string.byte(id) if slaves[id] ~= nil then skynet.error(string.format("Slave %d exist (fd =%d)", id, fd)) socket.close(fd) return end slaves[id] = fd monitor_clear(id) socket.abandon(fd) skynet.error(string.format("Harbor %d connected (fd = %d)", id, fd)) skynet.send(harbor_service, "harbor", string.format("A %d %d", fd, id)) end skynet.register_protocol { name = "harbor", id = skynet.PTYPE_HARBOR, pack = function(...) return ... end, unpack = skynet.tostring, } skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, pack = function(...) return ... end, unpack = skynet.tostring, } local function monitor_harbor(master_fd) return function(session, source, command) local t = string.sub(command, 1, 1) local arg = string.sub(command, 3) if t == 'Q' then -- query name if globalname[arg] then skynet.redirect(harbor_service, globalname[arg], "harbor", 0, "N " .. arg) else socket.write(master_fd, pack_package("Q", arg)) end elseif t == 'D' then -- harbor down local id = tonumber(arg) if slaves[id] then monitor_clear(id) end slaves[id] = false else skynet.error("Unknown command ", command) end end end function harbor.REGISTER(fd, name, handle) assert(globalname[name] == nil) globalname[name] = handle response_name(name) socket.write(fd, pack_package("R", name, handle)) skynet.redirect(harbor_service, handle, "harbor", 0, "N " .. name) end function harbor.LINK(fd, id) if slaves[id] then if monitor[id] == nil then monitor[id] = {} end table.insert(monitor[id], skynet.response()) else skynet.ret() end end function harbor.LINKMASTER() table.insert(monitor_master_set, skynet.response()) end function harbor.CONNECT(fd, id) if not slaves[id] then if monitor[id] == nil then monitor[id] = {} end table.insert(monitor[id], skynet.response()) else skynet.ret() end end function harbor.QUERYNAME(fd, name) if name:byte() == 46 then -- "." , local name skynet.ret(skynet.pack(skynet.localname(name))) return end local result = globalname[name] if result then skynet.ret(skynet.pack(result)) return end local queue = queryname[name] if queue == nil then queue = { skynet.response() } queryname[name] = queue else table.insert(queue, skynet.response()) end end skynet.start(function() local master_addr = skynet.getenv "master" local harbor_id = tonumber(skynet.getenv "harbor") local slave_address = assert(skynet.getenv "address") local slave_fd = socket.listen(slave_address) skynet.error("slave connect to master " .. tostring(master_addr)) local master_fd = assert(socket.open(master_addr), "Can't connect to master") skynet.dispatch("lua", function (_,_,command,...) local f = assert(harbor[command]) f(master_fd, ...) end) skynet.dispatch("text", monitor_harbor(master_fd)) harbor_service = assert(skynet.launch("harbor", harbor_id, skynet.self())) local hs_message = pack_package("H", harbor_id, slave_address) socket.write(master_fd, hs_message) local t, n = read_package(master_fd) assert(t == "W" and type(n) == "number", "slave shakehand failed") skynet.error(string.format("Waiting for %d harbors", n)) skynet.fork(monitor_master, master_fd) if n > 0 then local co = coroutine.running() socket.start(slave_fd, function(fd, addr) skynet.error(string.format("New connection (fd = %d, %s)",fd, addr)) if pcall(accept_slave,fd) then local s = 0 for k,v in pairs(slaves) do s = s + 1 end if s >= n then skynet.wakeup(co) end end end) skynet.wait() end socket.close(slave_fd) skynet.error("Shakehand ready") skynet.fork(ready) end)
mit
AlexandreCA/update
scripts/globals/items/margherita_pizza.lua
35
1220
----------------------------------------- -- ID: 5695 -- Item: margherita_pizza -- Food Effect: 3hours, All Races ----------------------------------------- -- Attack 10 -- Health Points 30 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5695); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30); target:addMod(MOD_ATT, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30); target:delMod(MOD_ATT, 10); end;
gpl-3.0
KAISER1350/KAISER
plugins/stats.lua
1
3995
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'teleseed' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /kaiser ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (kaiser)",-- Put everything you like :) "^[!/]([Kk]aiser)"-- Put everything you like :) }, run = run } end
gpl-2.0
AlexandreCA/update
scripts/zones/Southern_San_dOria/npcs/Camereine.lua
28
2490
----------------------------------- -- Area: Southern San d'Oria -- NPC: Camereine -- Type: Chocobo Renter -- @pos -8 1 -100 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/chocobo"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 15) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); if (level >= 20) then level = 0; end player:startEvent(0x0257,price,gil,level); else player:startEvent(0x025A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x0257 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); if (player:getMainLvl() >= 20) then local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); else player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,900,true); end player:setPos(-126,-62,274,0x65,0x64); end end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Qulun_Dome/npcs/Magicite.lua
13
1659
----------------------------------- -- Area: Qulun Dome -- NPC: Magicite -- Involved in Mission: Magicite -- @pos 11 25 -81 148 ----------------------------------- package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Qulun_Dome/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_AURASTONE) == false) then if (player:getVar("MissionStatus") < 4) then player:startEvent(0x0000,1); -- play Lion part of the CS (this is first magicite) else player:startEvent(0x0000); -- don't play Lion part of the CS end else player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0000) then player:setVar("MissionStatus",4); player:addKeyItem(MAGICITE_AURASTONE); player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_AURASTONE); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Eastern_Adoulin/Zone.lua
16
1192
----------------------------------- -- -- Zone: Eastern Adoulin -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Eastern_Adoulin/TextIDs"] = nil; require("scripts/zones/Eastern_Adoulin/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-155,0,-19,250); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
niedzielski/premake-4.4-beta4
tests/actions/vstudio/cs2002/test_files.lua
57
2430
-- -- tests/actions/vstudio/cs2002/test_files.lua -- Validate generation of <Files/> block in Visual Studio 2002 .csproj -- Copyright (c) 2009-2012 Jason Perkins and the Premake project -- T.vstudio_cs2002_files = { } local suite = T.vstudio_cs2002_files local cs2002 = premake.vstudio.cs2002 -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() premake.bake.buildconfigs() prj = premake.solution.getproject(sln, 1) sln.vstudio_configs = premake.vstudio.buildconfigs(sln) cs2002.Files(prj) end -- -- Test grouping and nesting -- function suite.SimpleSourceFile() files { "Hello.cs" } prepare() test.capture [[ <File RelPath = "Hello.cs" BuildAction = "Compile" SubType = "Code" /> ]] end function suite.NestedSourceFile() files { "Src/Hello.cs" } prepare() test.capture [[ <File RelPath = "Src\Hello.cs" BuildAction = "Compile" SubType = "Code" /> ]] end -- -- The relative path to the file is correct for files that live outside -- the project's folder. -- function suite.filesUseRelativePath_onOutOfTreePath() files { "../Src/Hello.cs" } prepare() test.capture [[ <File RelPath = "..\Src\Hello.cs" BuildAction = "Compile" SubType = "Code" /> ]] end -- -- Test file dependencies -- function suite.SimpleResourceDependency() files { "Resources.resx", "Resources.cs" } prepare() test.capture [[ <File RelPath = "Resources.cs" BuildAction = "Compile" SubType = "Code" /> <File RelPath = "Resources.resx" BuildAction = "EmbeddedResource" DependentUpon = "Resources.cs" /> ]] end -- -- Test build actions -- function suite.BuildAction_Compile() files { "Hello.png" } configuration "*.png" buildaction "Compile" prepare() test.capture [[ <File RelPath = "Hello.png" BuildAction = "Compile" /> ]] end function suite.BuildAction_Copy() files { "Hello.png" } configuration "*.png" buildaction "Copy" prepare() test.capture [[ <File RelPath = "Hello.png" BuildAction = "Content" /> ]] end function suite.BuildAction_Embed() files { "Hello.png" } configuration "*.png" buildaction "Embed" prepare() test.capture [[ <File RelPath = "Hello.png" BuildAction = "EmbeddedResource" /> ]] end
bsd-3-clause
AlexandreCA/darkstar
scripts/zones/Bastok_Markets/npcs/Nbu_Latteh.lua
26
3365
----------------------------------- -- Area: Bastok Markets -- NPC: Nbu Latteh -- Starts & Finishes Quest: Mom, The Adventurer? -- Starts Quest: The Signpost Marks the Spot ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local pFame = player:getFameLevel(BASTOK); local MomTheAdventurer = player:getQuestStatus(BASTOK,MOM_THE_ADVENTURER) local questStatus = player:getVar("MomTheAdventurer_Event"); if (player:needToZone()) then player:startEvent(127); -- chat about my work elseif (pFame < 2 and MomTheAdventurer ~= QUEST_ACCEPTED and questStatus == 0) then player:startEvent(0x00e6); elseif (MomTheAdventurer >= QUEST_ACCEPTED and questStatus == 2) then if (player:seenKeyItem(LETTER_FROM_ROH_LATTEH)) then player:startEvent(0x00ea); elseif (player:hasKeyItem(LETTER_FROM_ROH_LATTEH)) then player:startEvent(0x00e9); end elseif (pFame >= 2 and player:getQuestStatus(BASTOK,THE_SIGNPOST_MARKS_THE_SPOT) == QUEST_AVAILABLE) then player:startEvent(0x00eb); else player:startEvent(0x007f); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00e6 and option == 0) then if (player:getFreeSlotsCount(0) > 0) then player:addQuest(BASTOK,MOM_THE_ADVENTURER); player:setVar("MomTheAdventurer_Event",1); player:addItem(4096); player:messageSpecial(ITEM_OBTAINED,4096); -- Fire Crystal else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4096); end elseif (csid == 0x00e9 or csid == 0x00ea) then if (player:seenKeyItem(LETTER_FROM_ROH_LATTEH)) then gilReward = 100; else gilReward = 200; end player:needToZone(true); player:delKeyItem(LETTER_FROM_ROH_LATTEH); player:addTitle(RINGBEARER); player:addGil(GIL_RATE*gilReward); player:messageSpecial(GIL_OBTAINED, GIL_RATE*gilReward); player:setVar("MomTheAdventurer_Event",0); if (player:getQuestStatus(BASTOK,MOM_THE_ADVENTURER) == QUEST_ACCEPTED) then player:addFame(BASTOK,50); player:completeQuest(BASTOK,MOM_THE_ADVENTURER); else player:addFame(BASTOK,8) end elseif (csid == 0x00eb and option == 0) then player:addQuest(BASTOK,THE_SIGNPOST_MARKS_THE_SPOT); player:setVar("MomTheAdventurer_Event",0); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/globals/items/bowl_of_loach_soup.lua
18
1596
----------------------------------------- -- ID: 5671 -- Item: Bowl of Loach Soup -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- Dexterity 4 -- Agility 4 -- Accuracy 7% Cap 50 -- HP 7% Cap 50 -- Evasion 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5671); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 4); target:addMod(MOD_FOOD_ACCP, 7); target:addMod(MOD_FOOD_ACC_CAP, 50); target:addMod(MOD_FOOD_HPP, 7); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 4); target:delMod(MOD_FOOD_ACCP, 7); target:delMod(MOD_FOOD_ACC_CAP, 50); target:delMod(MOD_FOOD_HPP, 7); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_EVA, 5); end;
gpl-3.0
martolini/Vana
scripts/npcs/s4holycharge.lua
1
1247
--[[ Copyright (C) 2008-2015 Vana Development Team 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; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] -- Puddle in Horntail's cave dofile("scripts/utils/npcHelper.lua"); if isQuestActive(6280) and getItemAmount(4031454) > 0 then if getItemAmount(4031455) > 0 then addText("You already have " .. blue(itemRef(4031455)) .. "."); sendOk(); else giveItem(4031454, -1); giveItem(4031455, 1); addText("Holy water was contained from spring."); sendOk(); end elseif isQuestActive(6169) and getItemAmount(4031461) < 1 then if giveItem(4031461, 1) then addText("You found a small Life's Root growing in a place of death..."); sendOk(); end end
gpl-2.0
AlexandreCA/darkstar
scripts/globals/items/dil.lua
18
1304
----------------------------------------- -- ID: 5457 -- Item: Dil -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 4 -- Mind -6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5457); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -6); end;
gpl-3.0
nwf/openwrt-luci
modules/luci-mod-admin-full/luasrc/model/cbi/admin_network/proto_ahcp.lua
84
2006
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, apn, service, pincode, username, password local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand mca = s:taboption("ahcp", Value, "multicast_address", translate("Multicast address")) mca.optional = true mca.placeholder = "ff02::cca6:c0f9:e182:5359" mca.datatype = "ip6addr" mca:depends("proto", "ahcp") port = s:taboption("ahcp", Value, "port", translate("Port")) port.optional = true port.placeholder = 5359 port.datatype = "port" port:depends("proto", "ahcp") fam = s:taboption("ahcp", ListValue, "_family", translate("Protocol family")) fam:value("", translate("IPv4 and IPv6")) fam:value("ipv4", translate("IPv4 only")) fam:value("ipv6", translate("IPv6 only")) fam:depends("proto", "ahcp") function fam.cfgvalue(self, section) local v4 = m.uci:get_bool("network", section, "ipv4_only") local v6 = m.uci:get_bool("network", section, "ipv6_only") if v4 then return "ipv4" elseif v6 then return "ipv6" end return "" end function fam.write(self, section, value) if value == "ipv4" then m.uci:set("network", section, "ipv4_only", "true") m.uci:delete("network", section, "ipv6_only") elseif value == "ipv6" then m.uci:set("network", section, "ipv6_only", "true") m.uci:delete("network", section, "ipv4_only") end end function fam.remove(self, section) m.uci:delete("network", section, "ipv4_only") m.uci:delete("network", section, "ipv6_only") end nodns = s:taboption("ahcp", Flag, "no_dns", translate("Disable DNS setup")) nodns.optional = true nodns.enabled = "true" nodns.disabled = "false" nodns.default = nodns.disabled nodns:depends("proto", "ahcp") ltime = s:taboption("ahcp", Value, "lease_time", translate("Lease validity time")) ltime.optional = true ltime.placeholder = 3666 ltime.datatype = "uinteger" ltime:depends("proto", "ahcp")
apache-2.0
AlexandreCA/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/PalardaifaultVDraffles.lua
19
1139
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Palardaifault V Draffles -- @zone 80 -- @pos 9 1 -35 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 11024); -- Greetings, I am Curate Palardaifaut, and I have been assigned to the Knights of the Iron Ram to ensure that its members stray not from the path of the Goddess. end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Altar_Room/npcs/Hooknox.lua
13
1048
----------------------------------- -- Area: Altar Room -- NPC: Hooknox -- Type: Standard NPC -- @zone: 152 -- @pos -265.248 11.693 -102.547 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x002e); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mosavy/leaderbottg
files/lua-redis.lua
580
35599
local redis = { _VERSION = 'redis-lua 2.0.4', _DESCRIPTION = 'A Lua client library for the redis key value storage system.', _COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri', } -- The following line is used for backwards compatibility in order to keep the `Redis` -- global module name. Using `Redis` is now deprecated so you should explicitly assign -- the module to a local variable when requiring it: `local redis = require('redis')`. Redis = redis local unpack = _G.unpack or table.unpack local network, request, response = {}, {}, {} local defaults = { host = '127.0.0.1', port = 6379, tcp_nodelay = true, path = nil } local function merge_defaults(parameters) if parameters == nil then parameters = {} end for k, v in pairs(defaults) do if parameters[k] == nil then parameters[k] = defaults[k] end end return parameters end local function parse_boolean(v) if v == '1' or v == 'true' or v == 'TRUE' then return true elseif v == '0' or v == 'false' or v == 'FALSE' then return false else return nil end end local function toboolean(value) return value == 1 end local function sort_request(client, command, key, params) --[[ params = { by = 'weight_*', get = 'object_*', limit = { 0, 10 }, sort = 'desc', alpha = true, } ]] local query = { key } if params then if params.by then table.insert(query, 'BY') table.insert(query, params.by) end if type(params.limit) == 'table' then -- TODO: check for lower and upper limits table.insert(query, 'LIMIT') table.insert(query, params.limit[1]) table.insert(query, params.limit[2]) end if params.get then if (type(params.get) == 'table') then for _, getarg in pairs(params.get) do table.insert(query, 'GET') table.insert(query, getarg) end else table.insert(query, 'GET') table.insert(query, params.get) end end if params.sort then table.insert(query, params.sort) end if params.alpha == true then table.insert(query, 'ALPHA') end if params.store then table.insert(query, 'STORE') table.insert(query, params.store) end end request.multibulk(client, command, query) end local function zset_range_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_byscore_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.limit then table.insert(opts, 'LIMIT') table.insert(opts, options.limit.offset or options.limit[1]) table.insert(opts, options.limit.count or options.limit[2]) end if options.withscores then table.insert(opts, 'WITHSCORES') end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function zset_range_reply(reply, command, ...) local args = {...} local opts = args[4] if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then local new_reply = { } for i = 1, #reply, 2 do table.insert(new_reply, { reply[i], reply[i + 1] }) end return new_reply else return reply end end local function zset_store_request(client, command, ...) local args, opts = {...}, { } if #args >= 1 and type(args[#args]) == 'table' then local options = table.remove(args, #args) if options.weights and type(options.weights) == 'table' then table.insert(opts, 'WEIGHTS') for _, weight in ipairs(options.weights) do table.insert(opts, weight) end end if options.aggregate then table.insert(opts, 'AGGREGATE') table.insert(opts, options.aggregate) end end for _, v in pairs(opts) do table.insert(args, v) end request.multibulk(client, command, args) end local function mset_filter_args(client, command, ...) local args, arguments = {...}, {} if (#args == 1 and type(args[1]) == 'table') then for k,v in pairs(args[1]) do table.insert(arguments, k) table.insert(arguments, v) end else arguments = args end request.multibulk(client, command, arguments) end local function hash_multi_request_builder(builder_callback) return function(client, command, ...) local args, arguments = {...}, { } if #args == 2 then table.insert(arguments, args[1]) for k, v in pairs(args[2]) do builder_callback(arguments, k, v) end else arguments = args end request.multibulk(client, command, arguments) end end local function parse_info(response) local info = {} local current = info response:gsub('([^\r\n]*)\r\n', function(kv) if kv == '' then return end local section = kv:match('^# (%w+)$') if section then current = {} info[section:lower()] = current return end local k,v = kv:match(('([^:]*):([^:]*)'):rep(1)) if k:match('db%d+') then current[k] = {} v:gsub(',', function(dbkv) local dbk,dbv = kv:match('([^:]*)=([^:]*)') current[k][dbk] = dbv end) else current[k] = v end end) return info end local function load_methods(proto, commands) local client = setmetatable ({}, getmetatable(proto)) for cmd, fn in pairs(commands) do if type(fn) ~= 'function' then redis.error('invalid type for command ' .. cmd .. '(must be a function)') end client[cmd] = fn end for i, v in pairs(proto) do client[i] = v end return client end local function create_client(proto, client_socket, commands) local client = load_methods(proto, commands) client.error = redis.error client.network = { socket = client_socket, read = network.read, write = network.write, } client.requests = { multibulk = request.multibulk, } return client end -- ############################################################################ function network.write(client, buffer) local _, err = client.network.socket:send(buffer) if err then client.error(err) end end function network.read(client, len) if len == nil then len = '*l' end local line, err = client.network.socket:receive(len) if not err then return line else client.error('connection error: ' .. err) end end -- ############################################################################ function response.read(client) local payload = client.network.read(client) local prefix, data = payload:sub(1, -#payload), payload:sub(2) -- status reply if prefix == '+' then if data == 'OK' then return true elseif data == 'QUEUED' then return { queued = true } else return data end -- error reply elseif prefix == '-' then return client.error('redis error: ' .. data) -- integer reply elseif prefix == ':' then local number = tonumber(data) if not number then if res == 'nil' then return nil end client.error('cannot parse '..res..' as a numeric response.') end return number -- bulk reply elseif prefix == '$' then local length = tonumber(data) if not length then client.error('cannot parse ' .. length .. ' as data length') end if length == -1 then return nil end local nextchunk = client.network.read(client, length + 2) return nextchunk:sub(1, -3) -- multibulk reply elseif prefix == '*' then local count = tonumber(data) if count == -1 then return nil end local list = {} if count > 0 then local reader = response.read for i = 1, count do list[i] = reader(client) end end return list -- unknown type of reply else return client.error('unknown response prefix: ' .. prefix) end end -- ############################################################################ function request.raw(client, buffer) local bufferType = type(buffer) if bufferType == 'table' then client.network.write(client, table.concat(buffer)) elseif bufferType == 'string' then client.network.write(client, buffer) else client.error('argument error: ' .. bufferType) end end function request.multibulk(client, command, ...) local args = {...} local argsn = #args local buffer = { true, true } if argsn == 1 and type(args[1]) == 'table' then argsn, args = #args[1], args[1] end buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n" buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n" local table_insert = table.insert for _, argument in pairs(args) do local s_argument = tostring(argument) table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n") end client.network.write(client, table.concat(buffer)) end -- ############################################################################ local function custom(command, send, parse) command = string.upper(command) return function(client, ...) send(client, command, ...) local reply = response.read(client) if type(reply) == 'table' and reply.queued then reply.parser = parse return reply else if parse then return parse(reply, command, ...) end return reply end end end local function command(command, opts) if opts == nil or type(opts) == 'function' then return custom(command, request.multibulk, opts) else return custom(command, opts.request or request.multibulk, opts.response) end end local define_command_impl = function(target, name, opts) local opts = opts or {} target[string.lower(name)] = custom( opts.command or string.upper(name), opts.request or request.multibulk, opts.response or nil ) end local undefine_command_impl = function(target, name) target[string.lower(name)] = nil end -- ############################################################################ local client_prototype = {} client_prototype.raw_cmd = function(client, buffer) request.raw(client, buffer .. "\r\n") return response.read(client) end -- obsolete client_prototype.define_command = function(client, name, opts) define_command_impl(client, name, opts) end -- obsolete client_prototype.undefine_command = function(client, name) undefine_command_impl(client, name) end client_prototype.quit = function(client) request.multibulk(client, 'QUIT') client.network.socket:shutdown() return true end client_prototype.shutdown = function(client) request.multibulk(client, 'SHUTDOWN') client.network.socket:shutdown() end -- Command pipelining client_prototype.pipeline = function(client, block) local requests, replies, parsers = {}, {}, {} local table_insert = table.insert local socket_write, socket_read = client.network.write, client.network.read client.network.write = function(_, buffer) table_insert(requests, buffer) end -- TODO: this hack is necessary to temporarily reuse the current -- request -> response handling implementation of redis-lua -- without further changes in the code, but it will surely -- disappear when the new command-definition infrastructure -- will finally be in place. client.network.read = function() return '+QUEUED' end local pipeline = setmetatable({}, { __index = function(env, name) local cmd = client[name] if not cmd then client.error('unknown redis command: ' .. name, 2) end return function(self, ...) local reply = cmd(client, ...) table_insert(parsers, #requests, reply.parser) return reply end end }) local success, retval = pcall(block, pipeline) client.network.write, client.network.read = socket_write, socket_read if not success then client.error(retval, 0) end client.network.write(client, table.concat(requests, '')) for i = 1, #requests do local reply, parser = response.read(client), parsers[i] if parser then reply = parser(reply) end table_insert(replies, i, reply) end return replies, #requests end -- Publish/Subscribe do local channels = function(channels) if type(channels) == 'string' then channels = { channels } end return channels end local subscribe = function(client, ...) request.multibulk(client, 'subscribe', ...) end local psubscribe = function(client, ...) request.multibulk(client, 'psubscribe', ...) end local unsubscribe = function(client, ...) request.multibulk(client, 'unsubscribe') end local punsubscribe = function(client, ...) request.multibulk(client, 'punsubscribe') end local consumer_loop = function(client) local aborting, subscriptions = false, 0 local abort = function() if not aborting then unsubscribe(client) punsubscribe(client) aborting = true end end return coroutine.wrap(function() while true do local message local response = response.read(client) if response[1] == 'pmessage' then message = { kind = response[1], pattern = response[2], channel = response[3], payload = response[4], } else message = { kind = response[1], channel = response[2], payload = response[3], } end if string.match(message.kind, '^p?subscribe$') then subscriptions = subscriptions + 1 end if string.match(message.kind, '^p?unsubscribe$') then subscriptions = subscriptions - 1 end if aborting and subscriptions == 0 then break end coroutine.yield(message, abort) end end) end client_prototype.pubsub = function(client, subscriptions) if type(subscriptions) == 'table' then if subscriptions.subscribe then subscribe(client, channels(subscriptions.subscribe)) end if subscriptions.psubscribe then psubscribe(client, channels(subscriptions.psubscribe)) end end return consumer_loop(client) end end -- Redis transactions (MULTI/EXEC) do local function identity(...) return ... end local emptytable = {} local function initialize_transaction(client, options, block, queued_parsers) local table_insert = table.insert local coro = coroutine.create(block) if options.watch then local watch_keys = {} for _, key in pairs(options.watch) do table_insert(watch_keys, key) end if #watch_keys > 0 then client:watch(unpack(watch_keys)) end end local transaction_client = setmetatable({}, {__index=client}) transaction_client.exec = function(...) client.error('cannot use EXEC inside a transaction block') end transaction_client.multi = function(...) coroutine.yield() end transaction_client.commands_queued = function() return #queued_parsers end assert(coroutine.resume(coro, transaction_client)) transaction_client.multi = nil transaction_client.discard = function(...) local reply = client:discard() for i, v in pairs(queued_parsers) do queued_parsers[i]=nil end coro = initialize_transaction(client, options, block, queued_parsers) return reply end transaction_client.watch = function(...) client.error('WATCH inside MULTI is not allowed') end setmetatable(transaction_client, { __index = function(t, k) local cmd = client[k] if type(cmd) == "function" then local function queuey(self, ...) local reply = cmd(client, ...) assert((reply or emptytable).queued == true, 'a QUEUED reply was expected') table_insert(queued_parsers, reply.parser or identity) return reply end t[k]=queuey return queuey else return cmd end end }) client:multi() return coro end local function transaction(client, options, coroutine_block, attempts) local queued_parsers, replies = {}, {} local retry = tonumber(attempts) or tonumber(options.retry) or 2 local coro = initialize_transaction(client, options, coroutine_block, queued_parsers) local success, retval if coroutine.status(coro) == 'suspended' then success, retval = coroutine.resume(coro) else -- do not fail if the coroutine has not been resumed (missing t:multi() with CAS) success, retval = true, 'empty transaction' end if #queued_parsers == 0 or not success then client:discard() assert(success, retval) return replies, 0 end local raw_replies = client:exec() if not raw_replies then if (retry or 0) <= 0 then client.error("MULTI/EXEC transaction aborted by the server") else --we're not quite done yet return transaction(client, options, coroutine_block, retry - 1) end end local table_insert = table.insert for i, parser in pairs(queued_parsers) do table_insert(replies, i, parser(raw_replies[i])) end return replies, #queued_parsers end client_prototype.transaction = function(client, arg1, arg2) local options, block if not arg2 then options, block = {}, arg1 elseif arg1 then --and arg2, implicitly options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2 else client.error("Invalid parameters for redis transaction.") end if not options.watch then watch_keys = { } for i, v in pairs(options) do if tonumber(i) then table.insert(watch_keys, v) options[i] = nil end end options.watch = watch_keys elseif not (type(options.watch) == 'table') then options.watch = { options.watch } end if not options.cas then local tx_block = block block = function(client, ...) client:multi() return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine. end end return transaction(client, options, block) end end -- MONITOR context do local monitor_loop = function(client) local monitoring = true -- Tricky since the payload format changed starting from Redis 2.6. local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$' local abort = function() monitoring = false end return coroutine.wrap(function() client:monitor() while monitoring do local message, matched local response = response.read(client) local ok = response:gsub(pattern, function(time, info, cmd, args) message = { timestamp = tonumber(time), client = info:match('%d+.%d+.%d+.%d+:%d+'), database = tonumber(info:match('%d+')) or 0, command = cmd, arguments = args:match('.+'), } matched = true end) if not matched then client.error('Unable to match MONITOR payload: '..response) end coroutine.yield(message, abort) end end) end client_prototype.monitor_messages = function(client) return monitor_loop(client) end end -- ############################################################################ local function connect_tcp(socket, parameters) local host, port = parameters.host, tonumber(parameters.port) local ok, err = socket:connect(host, port) if not ok then redis.error('could not connect to '..host..':'..port..' ['..err..']') end socket:setoption('tcp-nodelay', parameters.tcp_nodelay) return socket end local function connect_unix(socket, parameters) local ok, err = socket:connect(parameters.path) if not ok then redis.error('could not connect to '..parameters.path..' ['..err..']') end return socket end local function create_connection(parameters) if parameters.socket then return parameters.socket end local perform_connection, socket if parameters.scheme == 'unix' then perform_connection, socket = connect_unix, require('socket.unix') assert(socket, 'your build of LuaSocket does not support UNIX domain sockets') else if parameters.scheme then local scheme = parameters.scheme assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme) end perform_connection, socket = connect_tcp, require('socket').tcp end return perform_connection(socket(), parameters) end -- ############################################################################ function redis.error(message, level) error(message, (level or 1) + 1) end function redis.connect(...) local args, parameters = {...}, nil if #args == 1 then if type(args[1]) == 'table' then parameters = args[1] else local uri = require('socket.url') parameters = uri.parse(select(1, ...)) if parameters.scheme then if parameters.query then for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do if k == 'tcp_nodelay' or k == 'tcp-nodelay' then parameters.tcp_nodelay = parse_boolean(v) end end end else parameters.host = parameters.path end end elseif #args > 1 then local host, port = unpack(args) parameters = { host = host, port = port } end local commands = redis.commands or {} if type(commands) ~= 'table' then redis.error('invalid type for the commands table') end local socket = create_connection(merge_defaults(parameters)) local client = create_client(client_prototype, socket, commands) return client end function redis.command(cmd, opts) return command(cmd, opts) end -- obsolete function redis.define_command(name, opts) define_command_impl(redis.commands, name, opts) end -- obsolete function redis.undefine_command(name) undefine_command_impl(redis.commands, name) end -- ############################################################################ -- Commands defined in this table do not take the precedence over -- methods defined in the client prototype table. redis.commands = { -- commands operating on the key space exists = command('EXISTS', { response = toboolean }), del = command('DEL'), type = command('TYPE'), rename = command('RENAME'), renamenx = command('RENAMENX', { response = toboolean }), expire = command('EXPIRE', { response = toboolean }), pexpire = command('PEXPIRE', { -- >= 2.6 response = toboolean }), expireat = command('EXPIREAT', { response = toboolean }), pexpireat = command('PEXPIREAT', { -- >= 2.6 response = toboolean }), ttl = command('TTL'), pttl = command('PTTL'), -- >= 2.6 move = command('MOVE', { response = toboolean }), dbsize = command('DBSIZE'), persist = command('PERSIST', { -- >= 2.2 response = toboolean }), keys = command('KEYS', { response = function(response) if type(response) == 'string' then -- backwards compatibility path for Redis < 2.0 local keys = {} response:gsub('[^%s]+', function(key) table.insert(keys, key) end) response = keys end return response end }), randomkey = command('RANDOMKEY', { response = function(response) if response == '' then return nil else return response end end }), sort = command('SORT', { request = sort_request, }), -- commands operating on string values set = command('SET'), setnx = command('SETNX', { response = toboolean }), setex = command('SETEX'), -- >= 2.0 psetex = command('PSETEX'), -- >= 2.6 mset = command('MSET', { request = mset_filter_args }), msetnx = command('MSETNX', { request = mset_filter_args, response = toboolean }), get = command('GET'), mget = command('MGET'), getset = command('GETSET'), incr = command('INCR'), incrby = command('INCRBY'), incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), decr = command('DECR'), decrby = command('DECRBY'), append = command('APPEND'), -- >= 2.0 substr = command('SUBSTR'), -- >= 2.0 strlen = command('STRLEN'), -- >= 2.2 setrange = command('SETRANGE'), -- >= 2.2 getrange = command('GETRANGE'), -- >= 2.2 setbit = command('SETBIT'), -- >= 2.2 getbit = command('GETBIT'), -- >= 2.2 -- commands operating on lists rpush = command('RPUSH'), lpush = command('LPUSH'), llen = command('LLEN'), lrange = command('LRANGE'), ltrim = command('LTRIM'), lindex = command('LINDEX'), lset = command('LSET'), lrem = command('LREM'), lpop = command('LPOP'), rpop = command('RPOP'), rpoplpush = command('RPOPLPUSH'), blpop = command('BLPOP'), -- >= 2.0 brpop = command('BRPOP'), -- >= 2.0 rpushx = command('RPUSHX'), -- >= 2.2 lpushx = command('LPUSHX'), -- >= 2.2 linsert = command('LINSERT'), -- >= 2.2 brpoplpush = command('BRPOPLPUSH'), -- >= 2.2 -- commands operating on sets sadd = command('SADD'), srem = command('SREM'), spop = command('SPOP'), smove = command('SMOVE', { response = toboolean }), scard = command('SCARD'), sismember = command('SISMEMBER', { response = toboolean }), sinter = command('SINTER'), sinterstore = command('SINTERSTORE'), sunion = command('SUNION'), sunionstore = command('SUNIONSTORE'), sdiff = command('SDIFF'), sdiffstore = command('SDIFFSTORE'), smembers = command('SMEMBERS'), srandmember = command('SRANDMEMBER'), -- commands operating on sorted sets zadd = command('ZADD'), zincrby = command('ZINCRBY'), zrem = command('ZREM'), zrange = command('ZRANGE', { request = zset_range_request, response = zset_range_reply, }), zrevrange = command('ZREVRANGE', { request = zset_range_request, response = zset_range_reply, }), zrangebyscore = command('ZRANGEBYSCORE', { request = zset_range_byscore_request, response = zset_range_reply, }), zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2 request = zset_range_byscore_request, response = zset_range_reply, }), zunionstore = command('ZUNIONSTORE', { -- >= 2.0 request = zset_store_request }), zinterstore = command('ZINTERSTORE', { -- >= 2.0 request = zset_store_request }), zcount = command('ZCOUNT'), zcard = command('ZCARD'), zscore = command('ZSCORE'), zremrangebyscore = command('ZREMRANGEBYSCORE'), zrank = command('ZRANK'), -- >= 2.0 zrevrank = command('ZREVRANK'), -- >= 2.0 zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0 -- commands operating on hashes hset = command('HSET', { -- >= 2.0 response = toboolean }), hsetnx = command('HSETNX', { -- >= 2.0 response = toboolean }), hmset = command('HMSET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, k) table.insert(args, v) end), }), hincrby = command('HINCRBY'), -- >= 2.0 hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6 response = function(reply, command, ...) return tonumber(reply) end, }), hget = command('HGET'), -- >= 2.0 hmget = command('HMGET', { -- >= 2.0 request = hash_multi_request_builder(function(args, k, v) table.insert(args, v) end), }), hdel = command('HDEL'), -- >= 2.0 hexists = command('HEXISTS', { -- >= 2.0 response = toboolean }), hlen = command('HLEN'), -- >= 2.0 hkeys = command('HKEYS'), -- >= 2.0 hvals = command('HVALS'), -- >= 2.0 hgetall = command('HGETALL', { -- >= 2.0 response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }), -- connection related commands ping = command('PING', { response = function(response) return response == 'PONG' end }), echo = command('ECHO'), auth = command('AUTH'), select = command('SELECT'), -- transactions multi = command('MULTI'), -- >= 2.0 exec = command('EXEC'), -- >= 2.0 discard = command('DISCARD'), -- >= 2.0 watch = command('WATCH'), -- >= 2.2 unwatch = command('UNWATCH'), -- >= 2.2 -- publish - subscribe subscribe = command('SUBSCRIBE'), -- >= 2.0 unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0 psubscribe = command('PSUBSCRIBE'), -- >= 2.0 punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0 publish = command('PUBLISH'), -- >= 2.0 -- redis scripting eval = command('EVAL'), -- >= 2.6 evalsha = command('EVALSHA'), -- >= 2.6 script = command('SCRIPT'), -- >= 2.6 -- remote server control commands bgrewriteaof = command('BGREWRITEAOF'), config = command('CONFIG', { -- >= 2.0 response = function(reply, command, ...) if (type(reply) == 'table') then local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end return reply end }), client = command('CLIENT'), -- >= 2.4 slaveof = command('SLAVEOF'), save = command('SAVE'), bgsave = command('BGSAVE'), lastsave = command('LASTSAVE'), flushdb = command('FLUSHDB'), flushall = command('FLUSHALL'), monitor = command('MONITOR'), time = command('TIME'), -- >= 2.6 slowlog = command('SLOWLOG', { -- >= 2.2.13 response = function(reply, command, ...) if (type(reply) == 'table') then local structured = { } for index, entry in ipairs(reply) do structured[index] = { id = tonumber(entry[1]), timestamp = tonumber(entry[2]), duration = tonumber(entry[3]), command = entry[4], } end return structured end return reply end }), info = command('INFO', { response = parse_info, }), } -- ############################################################################ return redis
gpl-3.0
thejeshgn/lib
lustache/renderer.lua
2
9146
local Scanner = require "lustache.scanner" local Context = require "lustache.context" local error, ipairs, loadstring, pairs, setmetatable, tostring, type = error, ipairs, loadstring, pairs, setmetatable, tostring, type local math_floor, math_max, string_find, string_gsub, string_split, string_sub, table_concat, table_insert, table_remove = math.floor, math.max, string.find, string.gsub, string.split, string.sub, table.concat, table.insert, table.remove local patterns = { white = "%s*", space = "%s+", nonSpace = "%S", eq = "%s*=", curly = "%s*}", tag = "[#\\^/>{&=!]" } local html_escape_characters = { ["&"] = "&amp;", ["<"] = "&lt;", [">"] = "&gt;", ['"'] = "&quot;", ["'"] = "&#39;", ["/"] = "&#x2F" } local function is_array(array) local max, n = 0, 0 for k, _ in pairs(array) do if not (type(k) == "number" and k > 0 and math_floor(k) == k) then return false end max = math_max(max, k) n = n + 1 end return n == max end -- Low-level function that compiles the given `tokens` into a -- function that accepts two arguments: a Context and a -- Renderer. local function compile_tokens(tokens) local subs = {} local function subrender(i, tokens) if not subs[i] then local fn = compile_tokens(tokens) subs[i] = function(ctx, rnd) return fn(ctx, rnd) end end return subs[i] end local function render(ctx, rnd) local buf = {} local token, section for i, token in ipairs(tokens) do local t = token.type buf[#buf+1] = t == "#" and rnd:_section( token.value, ctx, subrender(i, token.tokens) ) or t == "^" and rnd:_inverted( token.value, ctx, subrender(i, token.tokens) ) or t == ">" and rnd:_partial(token.value, ctx) or (t == "{" or t == "&") and rnd:_name(token.value, ctx, false) or t == "name" and rnd:_name(token.value, ctx, true) or t == "text" and token.value or "" end return table_concat(buf) end return render end local function escape_tags(tags) return { string_gsub(tags[1], "%%", "%%%%").."%s*", "%s*"..string_gsub(tags[2], "%%", "%%%%"), } end local function nest_tokens(tokens) local tree = {} local collector = tree local sections = {} local token, section for i,token in ipairs(tokens) do if token.type == "#" or token.type == "^" then token.tokens = {} sections[#sections+1] = token collector[#collector+1] = token collector = token.tokens elseif token.type == "/" then if #sections == 0 then error("Unopened section: "..token.value) end -- Make sure there are no open sections when we're done section = table_remove(sections, #sections) if not section.value == token.value then error("Unclosed section: "..section.value) end if #sections > 0 then collector = sections[#sections].tokens else collector = tree end else collector[#collector+1] = token end end section = table_remove(sections, #sections) if section then error("Unclosed section: "..section.value) end return tree end -- Combines the values of consecutive text tokens in the given `tokens` array -- to a single token. local function squash_tokens(tokens) local out, txt = {}, {} for _, v in ipairs(tokens) do if v.type == "text" then txt[#txt+1] = v.value else if #txt > 0 then out[#out+1] = { type = "text", value = table_concat(txt) } txt = {} end out[#out+1] = v end end if #txt > 0 then out[#out+1] = { type = "text", value = table_concat(txt) } end return out end local function make_context(view) if not view then return view end return view.magic == "1235123123" and view or Context:new(view) end local renderer = {} function renderer:clear_cache() self.cache = {} self.partial_cache = {} end function renderer:compile(tokens, tags) tags = tags or self.tags if type(tokens) == "string" then tokens = self:parse(tokens, tags) end local fn = compile_tokens(tokens) return function(view) return fn(make_context(view), self) end end function renderer:compile_partial(name, tokens, tags) tags = tags or self.tags self.partial_cache[name] = self:compile(tokens, tags) return self.partial_cache[name] end function renderer:render(template, view, partials) if partials then for name, body in pairs(partials) do self:compile_partial(name, body) end end if not template then return "" end local fn = self.cache[template] if not fn then fn = self:compile(template, self.tags) self.cache[template] = fn end return fn(view) end function renderer:_section(name, context, callback) local value = context:lookup(name) if type(value) == "table" then if is_array(value) then local buffer = "" for i,v in ipairs(value) do buffer = buffer .. callback(context:push(v), self) end return buffer end return callback(context:push(value), self) elseif type(value) == "function" then local section_text = callback(context, self) local scoped_render = function(template) return self:render(template, context) end return value(self, section_text, scoped_render) or "" else if value then return callback(context, self) end end return "" end function renderer:_inverted(name, context, callback) local value = context:lookup(name) -- From the spec: inverted sections may render text once based on the -- inverse value of the key. That is, they will be rendered if the key -- doesn't exist, is false, or is an empty list. if value == nil or value == false or (is_array(value) and #value == 0) then return callback(context, self) end return "" end function renderer:_partial(name, context) local fn = self.partial_cache[name] return fn and fn(context, self) or "" end function renderer:_name(name, context, escape) local value = context:lookup(name) if type(value) == "function" then value = value(context.view) end local str = value == nil and "" or value str = tostring(str) if escape then return string_gsub(str, '[&<>"\'/]', function(s) return html_escape_characters[s] end) end return str end -- Breaks up the given `template` string into a tree of token objects. If -- `tags` is given here it must be an array with two string values: the -- opening and closing tags used in the template (e.g. ["<%", "%>"]). Of -- course, the default is to use mustaches (i.e. Mustache.tags). function renderer:parse(template, tags) tags = tags or self.tags local tag_patterns = escape_tags(tags) local scanner = Scanner:new(template) local tokens = {} -- token buffer local spaces = {} -- indices of whitespace tokens on the current line local has_tag = false -- is there a {{tag} on the current line? local non_space = false -- is there a non-space char on the current line? -- Strips all whitespace tokens array for the current line if there was -- a {{#tag}} on it and otherwise only space local type, value, chr while not scanner:eos() do value = scanner:scan_until(tag_patterns[1]) if value then for i = 1, #value do chr = string_sub(value,i,i) if string_find(chr, "%s+") then spaces[#spaces+1] = #tokens else non_space = true end tokens[#tokens+1] = { type = "text", value = chr } end end if not scanner:scan(tag_patterns[1]) then break end has_tag = true type = scanner:scan(patterns.tag) or "name" scanner:scan(patterns.white) if type == "=" then value = scanner:scan_until(patterns.eq) scanner:scan(patterns.eq) scanner:scan_until(tag_patterns[2]) elseif type == "{" then local close_pattern = "%s*}"..tags[2] value = scanner:scan_until(close_pattern) scanner:scan(patterns.curly) scanner:scan_until(tag_patterns[2]) else value = scanner:scan_until(tag_patterns[2]) end if not scanner:scan(tag_patterns[2]) then error("Unclosed tag at " .. scanner.pos) end tokens[#tokens+1] = { type = type, value = value } if type == "name" or type == "{" or type == "&" then non_space = true --> what does this do? end if type == "=" then tags = string_split(value, patterns.space) tag_patterns = escape_tags(tags) end end return nest_tokens(squash_tokens(tokens)) end function renderer:new() local out = { cache = {}, partial_cache = {}, tags = {"{{", "}}"} } return setmetatable(out, { __index = self }) end return renderer
bsd-3-clause
AlexandreCA/update
scripts/zones/Crawlers_Nest/Zone.lua
30
1853
----------------------------------- -- -- Zone: Crawlers_Nest (197) -- ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Crawlers_Nest/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17584492,17584493}; SetGroundsTome(tomes); UpdateTreasureSpawnPoint(17584471); UpdateTreasureSpawnPoint(17584472); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(380.617,-34.61,4.581,59); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Crawlers_Nest/npcs/qm4.lua
13
1025
----------------------------------- -- Area: Crawlers' Nest -- NPC: ??? - Drown Crawler (Spawn area 2) -- @pos -74.939 -2.606 244.139 197 ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Crawlers_Nest/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade Rolanberry 881 if (GetMobAction(17584132) == 0 and trade:hasItemQty(4529,1) and trade:getItemCount() == 1) then player:tradeComplete(); if (math.random(1,100)<=50) then SpawnMob(17584132,120):updateClaim(player); -- Drone Crawler npc:setStatus(STATUS_DISAPPEAR) -- hide ??? else player:messageSpecial(NOTHING_SEEMS_TO_HAPPEN); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/PsoXja/npcs/_098.lua
13
2831
----------------------------------- -- Area: Pso'Xja -- NPC: _098 (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos 258.399 -1.925 -70.000 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == 6) then local X=player:getXPos(); if (npc:getAnimation() == 9) then if (X >= 259) then if (GetMobAction(16814089) == 0) then local Rand = math.random(1,2); -- estimated 50% success as per the wiki if (Rand == 1) then -- Spawn Gargoyle player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814089,120):updateClaim(player); -- Gargoyle else player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end player:tradeComplete(); else player:messageSpecial(DOOR_LOCKED); end end end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local X=player:getXPos(); if (npc:getAnimation() == 9) then if (X >= 259) then if (GetMobAction(16814089) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814089,120):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif (X <= 258) then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
thibhul/Jakopter
scripts/test_icon.lua
2
1597
--Boucle de contrôle du drone + affichage vidéo -- package.cpath = package.cpath .. ";?.dylib" l=require("libjakopter") path="../resources/test.png" if l.use_visp() then print("ViSP doesn't handle yet incrusting") os.exit() end l.connect_video() l.connect() --Canal de com navdata (lecture des données) --ccn = l.get_cc(1) --Canal de com de la video pour envoyer les infos --ccv = l.get_cc(2) --Envoi des navdata au module vidéo --vérifier le timestamp pour voir si de nouvelles données sont arrivées --initialement, il vaut 0. tt = 0 tt_new = 0 id_bat = -1 id_icon = -1 while true do --ne mettre à jour les données que si elles ont changé repeat --yield pour éviter d'occuper le CPU avec plein de tests inutiles l.yield() tt_new = l.cc_get_timestamp(1) l.usleep(500*1000) until tt_new > tt tt = tt_new bat = l.cc_read_int(1, 0) alt = l.cc_read_int(1, 4) --angles en millidegrés, il faut les convertir en degrés. pitch = l.cc_read_float(1, 8) / 1000 roll = l.cc_read_float(1, 12) / 1000 yaw = l.cc_read_float(1, 16) / 1000 --send data to video l.cc_write_int(2, 0, bat) l.cc_write_int(2, 4, alt) l.cc_write_float(2, 8, pitch) l.cc_write_float(2, 12, roll) l.cc_write_float(2, 16, yaw) if yaw > 90 and id_icon == -1 then id_icon = l.draw_icon(path, 120, 120, 64, 64) elseif yaw < 90 and id_icon ~= -1 then l.draw_remove(id_icon) --don't forget to reset id_icon otherway it tries each round to delete the icon id_icon = -1 end if (id_bat ~= -1) then l.draw_remove(id_bat) id_bat = -1 end id_bat = l.draw_text("Yaw : " .. yaw, 0, 120) end
lgpl-3.0
AlexandreCA/update
scripts/zones/Empyreal_Paradox/mobs/Prishe.lua
14
2241
----------------------------------- -- Area: Empyreal Paradox -- NPC: Prishe -- Chains of Promathia 8-4 BCNM Fight ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/zones/Empyreal_Paradox/TextIDs"); function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 30); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; function onMobEngaged(mob, target) mob:useMobAbility(1231); end; function onMobFight(mob, target) if (mob:getHPP() == 0 and mob:getLocalVar("Raise") == 1) then mob:entityAnimationPacket("sp00"); mob:messageText(mob, PRISHE_TEXT + 3); mob:addHP(mob:getMaxHP()); mob:addMP(mob:getMaxMP()); mob:setLocalVar("Raise", 0); mob:stun(3000); elseif (mob:getHPP() < 70 and mob:getLocalVar("HF") == 0) then mob:useMobAbility(1229); mob:messageText(mob, PRISHE_TEXT + 6); mob:setLocalVar("HF", 1); elseif (mob:getHPP() < 30 and mob:getLocalVar("Bene") == 0) then mob:useMobAbility(1230); mob:messageText(mob, PRISHE_TEXT + 7); mob:setLocalVar("Bene", 1); end -- mob:setStatus(0); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) mob:messageText(mob, PRISHE_TEXT + 2); end; function onMobRoam(mob) local wait = mob:getLocalVar("wait"); local ready = mob:getLocalVar("ready"); if (ready == 0 and wait > 240) then local baseID = 16924673 + (mob:getBattlefield():getBattlefieldNumber() - 1) * 2 if (GetMobAction(baseID) ~= ACTION_NONE) then mob:entityAnimationPacket("prov"); mob:messageText(mob, PRISHE_TEXT); else mob:entityAnimationPacket("prov"); mob:messageText(mob, PRISHE_TEXT + 1); baseID = baseID + 1; end mob:setLocalVar("ready", baseID); mob:setLocalVar("wait", 0); elseif (ready > 0) then mob:addEnmity(GetMobByID(ready),0,1); mob:addStatusEffectEx(EFFECT_SILENCE,0,0,0,5) else mob:setLocalVar("wait", wait+3); end end;
gpl-3.0
amirmrbad/paydarbot
plugins/all.lua
1321
4661
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
AlexandreCA/update
scripts/zones/Windurst_Woods/npcs/Miiri-Wohri.lua
38
1037
----------------------------------- -- Area: Windurst Woods -- NPC: Miiri-Wohri -- Type: Standard NPC -- @zone: 241 -- @pos 106.766 -6 -30.492 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x006f); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/The_Celestial_Nexus/Zone.lua
30
1741
----------------------------------- -- -- Zone: The_Celestial_Nexus (181) -- ----------------------------------- package.loaded["scripts/zones/The_Celestial_Nexus/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/The_Celestial_Nexus/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-697.114,-6.656,-32.351,0); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/update
scripts/zones/FeiYin/TextIDs.lua
9
2354
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6558; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6563; -- Obtained: <item> GIL_OBTAINED = 6564; -- Obtained <number> gil KEYITEM_OBTAINED = 6566; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7222; -- You can't fish here HOMEPOINT_SET = 10677; -- Home point set! -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7347; -- You unlock the chest! CHEST_FAIL = 7348; -- Fails to open the chest. CHEST_TRAP = 7349; -- The chest was trapped! CHEST_WEAK = 7350; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7351; -- The chest was a mimic! CHEST_MOOGLE = 7352; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7353; -- The chest was but an illusion... CHEST_LOCKED = 7354; -- The chest appears to be locked. -- Other Dialog SENSE_OF_FOREBODING = 6578; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 6577; -- There is nothing out of the ordinary here. -- ACP mission MARK_OF_SEED_HAS_VANISHED = 7490; -- The Mark of Seed has vanished without a trace... MARK_OF_SEED_IS_ABOUT_TO_DISSIPATE = 7489; -- The Mark of Seed is about to dissipate entirely! Only a faint outline remains... MARK_OF_SEED_GROWS_FAINTER = 7488; -- The Mark of Seed grows fainter still. Before long, it will fade away entirely... MARK_OF_SEED_FLICKERS = 7487; -- The glow of the Mark of Seed flickers and dims ever so slightly... SCINTILLATING_BURST_OF_LIGHT = 7478; -- As you extend your hand, there is a scintillating burst of light! YOU_REACH_FOR_THE_LIGHT = 7477; -- You reach for the light, but there is no discernable effect... EVEN_GREATER_INTENSITY = 7476; -- The emblem on your hand glows with even greater intensity! THE_LIGHT_DWINDLES = 7475; -- However, the light dwindles and grows dim almost at once... YOU_REACH_OUT_TO_THE_LIGHT = 7474; -- You reach out to the light, and one facet of a curious seed-shaped emblem materializes on the back of your hand. SOFTLY_SHIMMERING_LIGHT = 7473; -- You see a softly shimmering light... -- conquest Base CONQUEST_BASE = 3;
gpl-3.0
AlexandreCA/update
scripts/zones/Gusgen_Mines/npcs/qm4.lua
17
1436
----------------------------------- -- Area: Gusgen Mines -- NPC: qm4 (???) -- Involved In Quest: Ghosts of the Past -- @pos -174 0 369 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,GHOSTS_OF_THE_PAST) == QUEST_ACCEPTED and player:hasItem(13122) == false) then if (trade:hasItemQty(605,1) and trade:getItemCount() == 1) then -- Trade Pickaxe player:tradeComplete(); SpawnMob(17580337,300):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0