content stringlengths 5 1.05M |
|---|
--!A cross-platform terminal ui library based on Lua
--
-- 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.
--
-- Copyright (C) 2015 - 2018, TBOOX Open Source Group.
--
-- @author ruki
-- @file event.lua
--
--[[ Console User Interface (cui) ]-----------------------------------------
Author: Tiago Dionizio (tiago.dionizio AT gmail.com)
$Id: event.lua 18 2007-06-21 20:43:52Z tngd $
--------------------------------------------------------------------------]]
-- load modules
local log = require("ltui/base/log")
local object = require("ltui/object")
-- define module
local event = event or object { _init = {"type", "command", "extra"} }
-- register event types
function event:register(tag, ...)
local base = self[tag] or 0
local enums = {...}
local n = #enums
for i = 1, n do
self[enums[i]] = i + base
end
self[tag] = base + n
end
-- is key?
function event:is_key(key_name)
return self.type == event.ev_keyboard and self.key_name == key_name
end
-- is command event: cm_xxx?
function event:is_command(command)
return self.type == event.ev_command and self.command == command
end
-- dump event
function event:dump()
if self.type == event.ev_keyboard then
log:print("event(key): %s %s ..", self.key_name, self.key_code)
elseif self.type == event.ev_command then
log:print("event(cmd): %s ..", self.command)
else
log:print("event(%s): ..", self.type)
end
end
-- register event types, event.ev_keyboard = 1, event.ev_mouse = 2, ... , event.ev_idle = 5, event.ev_max = 5
event:register("ev_max", "ev_keyboard", "ev_mouse", "ev_command", "ev_text", "ev_idle")
-- register command event types (ev_command)
event:register("cm_max", "cm_quit", "cm_exit", "cm_enter")
-- define keyboard event
--
-- keyname = key name
-- keycode = key code
-- keymeta = ALT key was pressed
--
event.keyboard = object {_init = { "key_code", "key_name", "key_meta" }, type = event.ev_keyboard}
-- define command event
event.command = object {_init = { "command", "extra" }, type = event.ev_command}
-- define idle event
event.idle = object {_init = {}, type = event.ev_idle}
-- return module
return event
|
local M = {}
M.msgnotext = 'No text selected.'
M.warnedualimit = false
function M:run(func)
local sel = reqbuilder.edit.getsel()
if sel ~= '' then
reqbuilder.edit.replacesel(func(sel))
else
app.showmessage(M.msgnotext)
end
end
function M:spliturl()
local text = reqbuilder.edit.gettext()
if text ~= '' then
text = ctk.string.replace(text,'?','?'..string.char(10))
text = ctk.string.replace(text,'&',string.char(10)..'&')
reqbuilder.edit.settext(text)
end
end
function M:getmethod()
local method = 'GET'
if reqbuilder.request.postdata ~= '' then
method = 'POST'
end
return method
end
function M:getrequestparams()
return {
url = reqbuilder.request.url,
method = self:getmethod(),
postdata = reqbuilder.request.postdata,
headers = reqbuilder.request.headers,
usecookies = reqbuilder.request.usecookies,
usecredentials = reqbuilder.request.usecredentials,
ignorecache = reqbuilder.request.ignorecache,
details = 'Browser Request (Manual)'
}
end
function M:sendrequest()
browser.options.showheaders = true
if reqbuilder.request.url ~= '' then
tab:sendrequest(self:getrequestparams())
end
reqbuilder.edit.setfocus()
end
function M:loadrequest()
if tab:hasloadedurl(true) == true then
browser.options.showheaders = true
if reqbuilder.request.agent ~= '' then
if self.warnedualimit == false then
app.showmessage('User agent spoofing not supported for loading requests.')
self.warnedualimit = true
end
end
if reqbuilder.request.url ~= '' then
tab:loadrequest(self:getrequestparams())
end
end
reqbuilder.edit.setfocus()
end
return M |
--- Lua operators available as functions.
--
-- (similar to the Python module of the same name)
--
-- There is a module field `optable` which maps the operator strings
-- onto these functions, e.g. `operator.optable['()']==operator.call`
--
-- Operator strings like '>' and '{}' can be passed to most Penlight functions
-- expecting a function argument.
--
-- Dependencies: `pl.utils`
-- @module pl.operator
local strfind = string.find
local utils = require 'pl.utils'
local operator = {}
--- apply function to some arguments ()
-- @param fn a function or callable object
-- @param ... arguments
function operator.call(fn,...)
return fn(...)
end
--- get the indexed value from a table []
-- @param t a table or any indexable object
-- @param k the key
function operator.index(t,k)
return t[k]
end
--- returns true if arguments are equal ==
-- @param a value
-- @param b value
function operator.eq(a,b)
return a==b
end
--- returns true if arguments are not equal ~=
-- @param a value
-- @param b value
function operator.neq(a,b)
return a~=b
end
--- returns true if a is less than b <
-- @param a value
-- @param b value
function operator.lt(a,b)
return a < b
end
--- returns true if a is less or equal to b <=
-- @param a value
-- @param b value
function operator.le(a,b)
return a <= b
end
--- returns true if a is greater than b >
-- @param a value
-- @param b value
function operator.gt(a,b)
return a > b
end
--- returns true if a is greater or equal to b >=
-- @param a value
-- @param b value
function operator.ge(a,b)
return a >= b
end
--- returns length of string or table #
-- @param a a string or a table
function operator.len(a)
return #a
end
--- add two values +
-- @param a value
-- @param b value
function operator.add(a,b)
return a+b
end
--- subtract b from a -
-- @param a value
-- @param b value
function operator.sub(a,b)
return a-b
end
--- multiply two values *
-- @param a value
-- @param b value
function operator.mul(a,b)
return a*b
end
--- divide first value by second /
-- @param a value
-- @param b value
function operator.div(a,b)
return a/b
end
--- raise first to the power of second ^
-- @param a value
-- @param b value
function operator.pow(a,b)
return a^b
end
--- modulo; remainder of a divided by b %
-- @param a value
-- @param b value
function operator.mod(a,b)
return a%b
end
--- concatenate two values (either strings or __concat defined) ..
-- @param a value
-- @param b value
function operator.concat(a,b)
return a..b
end
--- return the negative of a value -
-- @param a value
function operator.unm(a)
return -a
end
--- false if value evaluates as true not
-- @param a value
function operator.lnot(a)
return not a
end
--- true if both values evaluate as true and
-- @param a value
-- @param b value
function operator.land(a,b)
return a and b
end
--- true if either value evaluate as true or
-- @param a value
-- @param b value
function operator.lor(a,b)
return a or b
end
--- make a table from the arguments {}
-- @param ... non-nil arguments
-- @return a table
function operator.table (...)
return {...}
end
--- match two strings ~
-- uses @{string.find}
function operator.match (a,b)
return strfind(a,b)~=nil
end
--- the null operation.
-- @param ... arguments
-- @return the arguments
function operator.nop (...)
return ...
end
operator.optable = {
['+']=operator.add,
['-']=operator.sub,
['*']=operator.mul,
['/']=operator.div,
['%']=operator.mod,
['^']=operator.pow,
['..']=operator.concat,
['()']=operator.call,
['[]']=operator.index,
['<']=operator.lt,
['<=']=operator.le,
['>']=operator.gt,
['>=']=operator.ge,
['==']=operator.eq,
['~=']=operator.neq,
['#']=operator.len,
['and']=operator.land,
['or']=operator.lor,
['{}']=operator.table,
['~']=operator.match,
['']=operator.nop,
}
return operator
|
data:extend(
{
{
type = "int-setting",
name = "DrKains_StackMultiplier-baseStackMultiplier",
setting_type = "startup",
minimum_value = 1,
default_value = 10,
maximum_value = 10000,
order = "a-a"
},
{
type = "int-setting",
name = "DrKains_StackMultiplier-constructRobotStackMultiplier",
setting_type = "startup",
minimum_value = 1,
default_value = 1,
maximum_value = 10000,
order = "a-b"
},
{
type = "int-setting",
name = "DrKains_StackMultiplier-logicRobotStackMultiplier",
setting_type = "startup",
minimum_value = 1,
default_value = 1,
maximum_value = 10000,
order = "a-c"
},
{
type = "bool-setting",
name = "DrKains_StackMultiplier-stackSingles",
setting_type = "startup",
default_value = false,
order = "b-a"
}
}
) |
------------------------------------------------------------------------------------------------------------------------
-- Spawn Protect Server
-- Author Morticai (META) - (https://www.coregames.com/user/d1073dbcc404405cbef8ce728e53d380)
-- Date: 2021/4/11
-- Version 0.0.1
------------------------------------------------------------------------------------------------------------------------
------------------------------------------------------------------------------------------------------------------------
-- OBJECTS
------------------------------------------------------------------------------------------------------------------------
local LargeOrcBase = script:GetCustomProperty('OrcBase'):WaitForObject()
local LargeElfBase = script:GetCustomProperty('ElfBase'):WaitForObject()
------------------------------------------------------------------------------------------------------------------------
-- LOCAL VARIABLES
------------------------------------------------------------------------------------------------------------------------
local listeners = {}
------------------------------------------------------------------------------------------------------------------------
-- LOCAL FUNCTIONS
------------------------------------------------------------------------------------------------------------------------
local function IsAValidPlayer(object)
return object and Object.IsValid(object) and object:IsA('Player')
end
local function IsOrcbase(trigger)
return trigger == LargeOrcBase
end
local function IsElfbase(trigger)
return trigger == LargeElfBase
end
local function ClearListeners()
for _, listener in ipairs(listeners) do
if listener and listener.isConnected then
listener:Disconnect()
end
end
listeners = {}
end
local function ClearPlayerFlags()
for _, player in ipairs(Game.GetPlayers()) do
player.serverUserData.SpawnProtect = nil
end
end
local function EnableLargeSpawnProtect()
listeners[#listeners + 1] = LargeElfBase.endOverlapEvent:Connect(OnEndOverlap)
listeners[#listeners + 1] = LargeOrcBase.endOverlapEvent:Connect(OnEndOverlap)
--listeners[#listeners + 1] = LargeOrcBase.beginOverlapEvent:Connect(OnBeginOverLap)
--listeners[#listeners + 1] = LargeElfBase.beginOverlapEvent:Connect(OnBeginOverLap)
end
------------------------------------------------------------------------------------------------------------------------
-- GLOAB FUNCTIONS
------------------------------------------------------------------------------------------------------------------------
function OnBeginOverLap(trigger, object)
if IsAValidPlayer(object) then
if IsOrcbase(trigger) and object.team == 1 then
object.serverUserData.SpawnProtect = true
elseif IsElfbase(trigger) and object.team == 2 then
object.serverUserData.SpawnProtect = true
end
end
end
function OnEndOverlap(trigger, object)
object.serverUserData.SpawnProtect = nil
end
function start()
ClearListeners()
ClearPlayerFlags()
EnableLargeSpawnProtect()
end
start() |
data.raw["mining-drill"][ "electric-mining-drill" ].resource_searching_radius = (500 / 2) - 0.01;
data.raw["mining-drill"]["kr-electric-mining-drill-mk2"].resource_searching_radius = (700 / 2) - 0.01;
data.raw["mining-drill"]["kr-electric-mining-drill-mk3"].resource_searching_radius = (900 / 2) - 0.01;
|
function on_activate(parent, ability)
if game:num_effects_with_tag("trap") > 4 then
game:say_line("Maximum number of traps set.", parent)
return
end
local targets = parent:targets()
local radius = parent:stats().touch_distance
local targeter = parent:create_targeter(ability)
targeter:set_selection_radius(radius)
targeter:set_free_select(radius)
targeter:set_free_select_must_be_passable("1by1")
targeter:set_shape_object_size("1by1")
targeter:add_all_effectable(targets)
targeter:activate()
end
function on_target_select(parent, ability, targets)
local points = targets:affected_points()
local surf = parent:create_surface(ability:name(), points)
surf:set_tag("trap")
surf:set_squares_to_fire_on_moved(1)
local cb = ability:create_callback(parent)
cb:set_on_moved_in_surface_fn("on_entered")
surf:add_callback(cb)
local anim = parent:create_anim("particles/spike_trap_set")
anim:set_position(anim:param(0.0), anim:param(-1.0))
anim:set_particle_size_dist(anim:fixed_dist(1.0), anim:fixed_dist(2.0))
anim:set_draw_below_entities()
surf:add_anim(anim)
surf:apply()
ability:activate(parent)
game:play_sfx("sfx/click_1")
end
function on_entered(parent, ability, targets)
-- only fire on hostiles
if targets:hostile():is_empty() then return end
targets:surface():mark_for_removal()
local target = targets:first()
local points = targets:affected_points()
local point = points[1]
local anim = target:create_anim("particles/spike_trap_fired", 0.5)
anim:set_position(anim:param(point.x), anim:param(point.y - 1.0))
anim:set_particle_size_dist(anim:fixed_dist(1.0), anim:fixed_dist(2.0))
anim:set_draw_above_entities()
anim:activate()
local stats = parent:stats()
local min_dmg = 18 + stats.level / 2 + stats.intellect_bonus / 4
local max_dmg = 28 + stats.level + stats.intellect_bonus / 2
local hit = parent:special_attack(target, "Reflex", "Ranged", min_dmg, max_dmg, 0, "Piercing")
if hit:is_miss() then
game:play_sfx("sfx/swish_2")
elseif hit:is_graze() then
game:play_sfx("sfx/thwack-07")
elseif hit:is_hit() then
game:play_sfx("sfx/thwack-08")
elseif hit:is_crit() then
game:play_sfx("sfx/thwack-09")
end
if not target:is_dead() and parent:ability_level(ability) > 1 then
local effect = target:create_effect(ability:name(), 2)
if hit:is_miss() then return end
if hit:is_graze() then
effect:add_num_bonus("movement_rate", -0.25)
elseif hit:is_hit() then
effect:add_num_bonus("movement_rate", -0.5)
elseif hit:is_crit() then
effect:add_num_bonus("movement_rate", -0.75)
end
local anim = target:create_particle_generator("particles/circle4")
anim:set_initial_gen(10.0)
anim:set_color(anim:param(1.0), anim:param(0.0), anim:param(0.0))
anim:set_gen_rate(anim:param(10.0))
anim:set_moves_with_parent()
anim:set_position(anim:param(0.0), anim:param(0.0))
anim:set_particle_size_dist(anim:fixed_dist(0.3), anim:fixed_dist(0.3))
anim:set_particle_position_dist(anim:dist_param(anim:uniform_dist(-0.5, 0.5), anim:uniform_dist(-1.0, 1.0)),
anim:dist_param(anim:uniform_dist(-0.2, 0.2), anim:uniform_dist(-1.0, 1.0), anim:fixed_dist(5.0)))
anim:set_particle_duration_dist(anim:fixed_dist(0.3))
effect:add_anim(anim)
effect:apply()
end
end |
local original_electric_mining_drill = data.raw["mining-drill"]["electric-mining-drill"]
local beaconed_data = {
machine_energy_usage = original_electric_mining_drill.energy_usage,
machine_emissions = original_electric_mining_drill.energy_source.emissions_per_minute,
machine_crafting_speed = original_electric_mining_drill.mining_speed,
machine_module_slots = original_electric_mining_drill.module_specification.module_slots,
beacon_count = global_electric_mining_drill_beacon_count,
average_beacon_count = global_electric_mining_drill_average_beacon_count,
beacon_effect = global_beacon_transmission_effect,
beacon_module_slots = global_beacon_module_slots,
beacon_module_speed_bonus = global_speed_module_2_speed_bonus,
beacon_module_energy_usage_bonus = global_speed_module_2_energy_usage_bonus,
machine_module_speed_bonus = global_speed_module_2_speed_bonus,
machine_module_energy_usage_bonus = global_speed_module_2_energy_usage_bonus,
original_animation_speed = 0.5,
tier_animation_speed_multiplier = global_tier_2_mining_drill_animation_speed_multiplier,
custom_animation_speed_multiplier = 1,
emission_hack = 1
}
local beaconed_electric_drill_2_animation_speed = beaconed_stats(beaconed_data).beaconed_animation_speed
beaconed_electric_mining_drill_2 = util.table.deepcopy(data.raw["mining-drill"]["electric-mining-drill"])
beaconed_electric_mining_drill_2.name = "beaconed-electric-mining-drill-2"
beaconed_electric_mining_drill_2.icon = "__Built-in-Beacons__/graphics/icons/beaconed-electric-mining-drill-2.png"
beaconed_electric_mining_drill_2.minable.result = "beaconed-electric-mining-drill-2"
beaconed_electric_mining_drill_2.next_upgrade = "beaconed-electric-mining-drill-3"
beaconed_electric_mining_drill_2.mining_speed = beaconed_stats(beaconed_data).beaconed_crafting_speed
beaconed_electric_mining_drill_2.energy_source.emissions_per_minute = beaconed_stats(beaconed_data).beaconed_emissions_per_minute
beaconed_electric_mining_drill_2.energy_source.drain = beaconed_stats(beaconed_data).beaconed_drain_string
beaconed_electric_mining_drill_2.energy_usage = beaconed_stats(beaconed_data).beaconed_energy_usage_string
beaconed_electric_mining_drill_2.allowed_effects = {"productivity", "pollution"}
beaconed_electric_mining_drill_2.module_specification.module_slots = 0
-- if settings.startup["show-module-slot-row-length"].value > 0 then
-- beaconed_electric_mining_drill_2.module_specification.module_info_max_icons_per_row = settings.startup["show-module-slot-row-length"].value
-- end
-- if settings.startup["show-module-slot-rows"].value > 0 then
-- beaconed_electric_mining_drill_2.module_specification.module_info_max_icon_rows = settings.startup["show-module-slot-rows"].value
-- end
local vertical_overlay_graphics =
{
priority = "high",
filename = "__Built-in-Beacons__/graphics/entity/beaconed-electric-mining-drill/electric-mining-drill-overlay.png",
line_length = 6,
width = 78,
height = 82,
frame_count = 30,
animation_speed = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].north_animation.layers[1].animation_speed,
frame_sequence = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].north_animation.layers[1].frame_sequence,
tint = beaconed_electric_mining_drill_2_tint,
shift = util.by_pixel(0, -8),
hr_version =
{
priority = "high",
filename = "__Built-in-Beacons__/graphics/entity/beaconed-electric-mining-drill/hr-electric-mining-drill-overlay.png",
line_length = 6,
width = 154,
height = 164,
frame_count = 30,
animation_speed = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].north_animation.layers[1].hr_version.animation_speed,
frame_sequence = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].north_animation.layers[1].hr_version.frame_sequence,
tint = beaconed_electric_mining_drill_2_tint,
shift = util.by_pixel(0, -8),
scale = 0.5
}
}
local horizontal_overlay_graphics =
{
priority = "high",
filename = "__Built-in-Beacons__/graphics/entity/beaconed-electric-mining-drill/electric-mining-drill-horizontal-overlay.png",
line_length = 6,
width = 36,
height = 86,
frame_count = 30,
animation_speed = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].east_animation.layers[1].animation_speed,
frame_sequence = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].east_animation.layers[1].frame_sequence,
tint = beaconed_electric_mining_drill_2_tint,
shift = util.by_pixel(2, -9),
hr_version =
{
priority = "high",
filename = "__Built-in-Beacons__/graphics/entity/beaconed-electric-mining-drill/hr-electric-mining-drill-horizontal-overlay.png",
line_length = 6,
width = 72,
height = 170,
frame_count = 30,
animation_speed = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].east_animation.layers[1].hr_version.animation_speed,
frame_sequence = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].east_animation.layers[1].hr_version.frame_sequence,
tint = beaconed_electric_mining_drill_2_tint,
shift = util.by_pixel(2, -9),
scale = 0.5
}
}
local horizontal_front_overlay_graphics =
{
priority = "high",
filename = "__Built-in-Beacons__/graphics/entity/beaconed-electric-mining-drill/electric-mining-drill-horizontal-front-overlay.png",
line_length = 6,
width = 30,
height = 74,
frame_count = 30,
animation_speed = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].east_animation.animation_speed,
frame_sequence = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].east_animation.frame_sequence,
tint = beaconed_electric_mining_drill_2_tint,
shift = util.by_pixel(-4, 2),
hr_version =
{
priority = "high",
filename = "__Built-in-Beacons__/graphics/entity/beaconed-electric-mining-drill/hr-electric-mining-drill-horizontal-front-overlay.png",
line_length = 6,
width = 58,
height = 146,
frame_count = 30,
animation_speed = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].east_animation.hr_version.animation_speed,
frame_sequence = beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].east_animation.hr_version.frame_sequence,
tint = beaconed_electric_mining_drill_2_tint,
shift = util.by_pixel(-4.5, 2),
scale = 0.5
}
}
local function create_layers(original, modded)
local original_layers = original
local layers =
{
layers = {
original_layers,
modded
}
}
return layers
end
if settings.startup["modded-entity-graphics"].value == "ON" then
table.insert(beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].north_animation.layers, vertical_overlay_graphics )
table.insert(beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].south_animation.layers, vertical_overlay_graphics )
table.insert(beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].east_animation.layers, horizontal_overlay_graphics )
table.insert(beaconed_electric_mining_drill_2.graphics_set.working_visualisations[3].west_animation.layers, horizontal_overlay_graphics )
beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].east_animation = create_layers(beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].east_animation, horizontal_front_overlay_graphics)
beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].west_animation = create_layers(beaconed_electric_mining_drill_2.graphics_set.working_visualisations[6].west_animation, horizontal_front_overlay_graphics)
end
data:extend({
beaconed_electric_mining_drill_2
})
data:extend({
{
type = "item",
name = "beaconed-electric-mining-drill-2",
icon = "__Built-in-Beacons__/graphics/icons/beaconed-electric-mining-drill-2.png",
icon_size = 64,
icon_mipmaps = 4,
subgroup = "extraction-machine",
order = "a[items]-b[electric-mining-drill]",
place_result = "beaconed-electric-mining-drill-2",
stack_size = 50,
localised_description = {'item-description.beaconed-electric-mining-drill-2', global_electric_mining_drill_beacon_count}
},
})
data:extend({
{
type = "recipe",
name = "beaconed-electric-mining-drill-2",
enabled = false,
icon = "__Built-in-Beacons__/graphics/icons/beaconed-electric-mining-drill-2.png",
icon_size = 64,
icon_mipmaps = 4,
subgroup = "built-in-beacons-2",
order = "j",
ingredients =
{
{"beaconed-electric-mining-drill", 1},
{"speed-module-2", global_electric_mining_drill_average_beacon_count * global_beacon_module_slots}
},
results = {
{type = "item", name = "beaconed-electric-mining-drill-2", amount = 1},
{type = "item", name = "speed-module", amount = global_electric_mining_drill_average_beacon_count * global_beacon_module_slots, show_details_in_recipe_tooltip = false}
},
allow_as_intermediate = false,
main_product = "beaconed-electric-mining-drill-2",
localised_description = {'item-description.beaconed-electric-mining-drill-2', global_electric_mining_drill_beacon_count}
}
})
if global_logging == true then
log(serpent.block( beaconed_data ))
log(serpent.block( beaconed_stats(beaconed_data) ))
end |
slot2 = "FishingJoyFish"
FishingJoyFish = class(slot1)
FishingJoyFish.ctor = function (slot0)
slot3 = slot0
slot6 = "entity.FishingJoyEntityBase"
ClassUtil.extends(slot2, FishingJoyRequireLua(slot5))
slot0.redColorTime = 0
slot0.catchedRadio = 0
slot0.boundingBoxContainer = {}
slot0.appendEffectContainer = {}
slot0.renderData = {}
slot0.renderId = 0
end
FishingJoyFish.getEntityType = function (slot0)
return FISHINGJOY_ENTITY_TYPE_OBJ.FISH
end
FishingJoyFish.getAppendParticle = function (slot0)
if slot0.fishConfig ~= nil then
if slot0.fishConfig.entityParticle == nil then
return ""
end
return slot0.fishConfig.entityParticle
end
return ""
end
FishingJoyFish.setFishRenderData = function (slot0, slot1)
slot0.renderData = slot1
end
FishingJoyFish.getFishRenderData = function (slot0)
return slot0.renderData
end
FishingJoyFish.setEntityRenderId = function (slot0, slot1)
slot0.renderId = slot1
end
FishingJoyFish.getEntityRenderId = function (slot0)
return slot0.renderId or 0
end
FishingJoyFish.setBoundingBoxId = function (slot0, slot1)
slot0.boundingBoxId = slot1
end
FishingJoyFish.setFishTypeId = function (slot0, slot1)
slot0.fishTypeId = slot1
end
FishingJoyFish.getFishTypeId = function (slot0)
return slot0.fishTypeId
end
FishingJoyFish.setFishType = function (slot0, slot1)
slot0.fishType = slot1
end
FishingJoyFish.getFishType = function (slot0)
return slot0.fishType
end
FishingJoyFish.setFishConfig = function (slot0, slot1)
slot0.fishConfig = slot1
end
FishingJoyFish.getFishConfig = function (slot0)
return slot0.fishConfig
end
FishingJoyFish.setBatchId = function (slot0, slot1)
slot0.fishBatchId = slot1
end
FishingJoyFish.getBatchId = function (slot0)
return slot0.fishBatchId
end
FishingJoyFish.setFishScore = function (slot0, slot1)
slot0.fishScore = slot1
end
FishingJoyFish.getFishScore = function (slot0)
return slot0.fishScore
end
FishingJoyFish.appendFishEffect = function (slot0, slot1)
slot5 = slot1
table.insert(slot3, slot0.appendEffectContainer)
end
FishingJoyFish.executeFishEffects = function (slot0, slot1, slot2, slot3, slot4)
slot5 = 0
slot8 = slot0
slot6 = slot0.getEntityId(slot7)
slot7 = ipairs
slot9 = slot2 or {}
for slot10, slot11 in slot7(slot8) do
slot14 = slot11
if slot11.getEntityId(slot13) == slot6 then
return slot5, slot2
end
end
slot9 = slot0
if slot0.getEntityStatus(slot8) < FISHINGJOY_ENTITY_STATUS.DEAD then
slot10 = slot0
table.insert(slot8, slot2)
slot9 = slot0.appendEffectContainer
for slot10, slot11 in pairs(slot8) do
slot19 = slot4
slot5, slot2 = slot11.executeEffect(slot13, slot11, slot0, slot1, slot2, slot3)
end
end
return slot5, slot2
end
FishingJoyFish.appendBoundingBox = function (slot0, slot1, slot2, slot3)
slot0.boundingBoxContainer[#slot0.boundingBoxContainer + 1] = {
entityOffsetx = slot1,
entityOffsety = slot2,
rad = slot3
}
slot10 = slot1
slot8 = math.abs(slot9) + slot3
slot0.catchedRadio = math.max(#slot0.boundingBoxContainer + 1, slot0.catchedRadio)
slot10 = slot2
slot8 = math.abs(slot9) + slot3
slot0.catchedRadio = math.max(#slot0.boundingBoxContainer + 1, slot0.catchedRadio)
end
FishingJoyFish.getBoundingBox = function (slot0)
return slot0.boundingBoxContainer
end
FishingJoyFish.getFishCatchedRadio = function (slot0)
return slot0.catchedRadio or 0
end
FishingJoyFish.onUpdate = function (slot0, slot1)
slot5 = slot1
slot0.super.onUpdate(slot3, slot0)
if slot0.redColorTime > 0 then
slot0.redColorTime = slot0.redColorTime - 1
if slot0.redColorTime == 0 then
slot2 = pairs
slot4 = slot0.entityRenderContainer or {}
for slot5, slot6 in slot2(slot3) do
if slot6.cocosTarget and slot6.entityShadow ~= true and slot6.entitySpecial ~= true then
slot9 = slot6.cocosTarget
slot14 = 255
slot6.cocosTarget.setColor(slot8, cc.c3b(slot11, 255, 255))
end
end
end
end
end
FishingJoyFish.fishHitted = function (slot0)
slot1 = pairs
slot3 = slot0.entityRenderContainer or {}
for slot4, slot5 in slot1(slot2) do
if slot5.cocosTarget and slot5.entityShadow ~= true and slot5.entitySpecial ~= true then
slot8 = slot5.cocosTarget
slot13 = 209
slot5.cocosTarget.setColor(slot7, cc.c3b(slot10, 255, 82))
end
end
slot0.redColorTime = 5
end
return FishingJoyFish
|
--MoveCurve
--H_Tokisaki/curve_Attack_3 curve_Attack_3
return
{
filePath = "H_Tokisaki/curve_Attack_3",
startTime = Fixed64(0) --[[0]],
startRealTime = Fixed64(0) --[[0]],
endTime = Fixed64(104857600) --[[100]],
endRealTime = Fixed64(1048576) --[[1]],
isZoom = false,
isCompensate = false,
curve = {
[1] = {
time = 0 --[[0]],
value = 0 --[[0]],
inTangent = 0 --[[0]],
outTangent = 0 --[[0]],
},
[2] = {
time = 332085 --[[0.3167]],
value = 0 --[[0]],
inTangent = 0 --[[0]],
outTangent = 0 --[[0]],
},
[3] = {
time = 436942 --[[0.4167]],
value = 524288 --[[0.5]],
inTangent = 0 --[[0]],
outTangent = 0 --[[0]],
},
[4] = {
time = 1048576 --[[1]],
value = 524288 --[[0.5]],
inTangent = 0 --[[0]],
outTangent = 0 --[[0]],
},
},
} |
return PlaceObj("ModDef", {
"title", "Fix FindDroneToRepair Log Spam",
"version", 2,
"version_major", 0,
"version_minor", 2,
"saved", 0,
"image", "Preview.png",
"id", "ChoGGi_FixFindDroneToRepairLogSpam",
"pops_any_uuid", "d8a6fb94-bc0b-4ad5-9aea-083ca8f51a93",
"author", "ChoGGi",
"lua_revision", 249143,
"code", {
"Code/Script.lua",
},
"description", [[This seems to be an issue from flying drones and a drone hub being destroyed.
Your log will "fill" up with these errors:
[LUA ERROR] HGE::l_HexAxialDistance:
Mars/Lua/Units/Drone.lua(256): method FindDroneToRepair
Mars/Lua/Units/Drone.lua(548): field Idle
Mars/Dlc/gagarin/Code/FlyingDrone.lua(312): <>
[C](-1): global sprocall
(116): <>
--- end of stack
[LUA ERROR] Mars/Lua/Units/Drone.lua:257: attempt to compare nil with number
Mars/Lua/Units/Drone.lua(548): field Idle
Mars/Dlc/gagarin/Code/FlyingDrone.lua(312): <>
[C](-1): global sprocall
(116): <>
--- end of stack
Thanks to veryinky for that entertaining log.]],
})
|
local History = require("Quadtastic/History")
do
-- Check that a new history is not marked
local history = History()
assert(not history:is_marked())
end
do
-- Check marking
local history = History()
history:mark()
assert(history:is_marked())
end
do
-- Check that a history is no longer marked once something was added
local history = History()
history:add("foo", "bar")
assert(not history:is_marked())
history:mark()
assert(history:is_marked())
history:add("baz", "haz")
assert(not history:is_marked())
end
do
-- Undo, redo stuff
local history = History()
history:add("foo", "bar")
assert(not history:is_marked())
history:mark()
assert(history:is_marked())
assert(history:can_undo())
assert(history:undo() == "bar")
assert(not history:is_marked())
assert(history:can_redo())
assert(history:redo() == "foo")
assert(history:is_marked())
end
do
-- Test diverting history
local history = History()
history:add("foo", "bar")
history:add("baz", "boo")
assert(history:can_undo())
assert(history:undo() == "boo")
assert(history:can_redo())
history:add("fuz", "far")
assert(not history:can_redo())
end
|
local addonName, addonData = ...
local red = function(text)
return format('|cFFFF0000%s|r', text)
end
local L = setmetatable({}, {
__index = function(L, key)
print(red(format('TargetEFC: "%s" localization for "%s" is missing', GetLocale(), key)))
return nil
end,
})
addonData.L = L
|
-- To replace the Caffeinate app
local prefix = require('prefix')
local menu = nil
local function toggle()
local enabled = hs.caffeinate.toggle('displayIdle')
if enabled then
menu = hs.menubar.new()
menu:setTitle('☕')
menu:setMenu({
{ title = 'Turn off Caffeinate', fn = toggle }
})
else
menu:delete()
end
hs.alert.show('Caffeinate '.. (enabled and 'enabled' or 'disabled'), 1)
end
prefix.bind('', 'c', toggle)
prefix.bind('', 's', hs.caffeinate.startScreensaver)
|
package.path = package.path .. ";data/scripts/lib/?.lua"
include("callable")
include("utility")
local Azimuth, Config, Log = unpack(include("buffsinit"))
local Helper = include("BuffsHelper")
-- namespace BuffsMod
BuffsMod = {}
local buffPrefixes = {"BM_", "M_", "MB_", "AB_", "_B"} -- client/server
local callbacks = {} -- client/server
local debugName -- client/server
local statLabels = {} -- client UI
local buffDescriptions, buffs, buffsCount, iconsRenderer, hoveredBuffTooltip, prevHoveredName -- client
local data, pending, isReady, isFirstLaunch, savedEntity -- server
if onClient() then
include("azimuthlib-uiproportionalsplitter")
buffDescriptions = include("BuffsIntegration")
-- PREDEFINED --
function BuffsMod.getUpdateInterval()
return 0.2
end
function BuffsMod.initialize()
buffs = {}
buffsCount = 0
Player():registerCallback("onPostRenderHud", "onPostRenderHud")
local entity = Entity()
debugName = string.format("%s(%s)", entity.name or entity.title, entity.index.string)
entity:registerCallback("onCraftSeatEntered", "onCraftSeatEntered")
if Player().craftIndex == entity.index then
invokeServerFunction("refreshData")
end
end
function BuffsMod.updateClient() -- Otherwise updateParallelSelf doesn't work?!
end
function BuffsMod.updateParallelSelf(timePassed)
local player = Player()
local entity = Entity()
if player.craftIndex ~= Entity().index then return end
if buffsCount == 0 then return end
local res, mousePos
local noClientUpdate = false
if Config.HideShipIconsOverlay or (player.state ~= PlayerStateType.Fly and player.state ~= PlayerStateType.Interact) then
noClientUpdate = true
else
iconsRenderer = UIRenderer()
res = getResolution()
mousePos = Mouse().position
end
local found = false -- if at least one buff was hovered
local i = 0 -- buff number, affects position
for _, buff in ipairs(buffs) do
-- decay buffs
if buff.duration ~= -1 then
buff.redraw = math.floor(buff.duration)
buff.duration = math.max(0, buff.duration - timePassed)
buff.redraw = buff.redraw - math.floor(buff.duration)
end
if not noClientUpdate then
local rx = res.x / 2 + 270 + math.floor(i / 2) * 30
local ry = res.y - 65 + (i % 2) * 30
-- check mouse hover
if not found and mousePos.x >= rx and mousePos.x <= rx + 25 and mousePos.y >= ry and mousePos.y <= ry + 25 then
found = true
if buff.redraw == 1 or prevHoveredName ~= buff.fullname then
prevHoveredName = buff.fullname
hoveredBuffTooltip = TooltipRenderer(Helper.createBuffTooltip(false, buff))
end
end
-- redraw icons 5 times per second instead of FPS time per second
if rx + 35 <= res.x then
iconsRenderer:renderPixelIcon(vec2(rx, ry), Helper.getBuffColor(buff), buff.icon)
end
end
i = i + 1
end
if not found then
prevHoveredName = nil
hoveredBuffTooltip = nil
end
end
-- CALLBACKS --
function BuffsMod.onCraftSeatEntered(entityId, seat, playerIndex)
if Player().index == playerIndex then
invokeServerFunction("refreshData")
local status, value = Player():invokeFunction("buffs.lua", "getHideShipIconsOverlay")
if status ~= 0 then
value = false
end
Config.HideShipIconsOverlay = value
end
end
function BuffsMod.onPostRenderHud(state)
if buffsCount == 0 or Config.HideShipIconsOverlay then return end
local player = Player()
if player.craftIndex ~= Entity().index then return end
if state ~= PlayerStateType.Fly and state ~= PlayerStateType.Interact then return end
if iconsRenderer then
iconsRenderer:display()
end
if hoveredBuffTooltip then
hoveredBuffTooltip:draw(Mouse().position)
end
end
-- CALLABLE --
function BuffsMod.receiveData(_buffs)
Log:Debug("(%s) receiveData: %s", debugName, _buffs)
buffsCount = 0
--buffs = _buffs
local newbuffs = {}
for fullname, buff in pairs(_buffs) do
buff.fullname = fullname
buffsCount = buffsCount + 1
-- custom color
if buff.color then
buff.color = ColorInt(buff.color)
else
buff.color = nil
end
if buff.lowColor then
buff.lowColor = ColorInt(buff.lowColor)
else
buff.lowColor = nil
end
-- icon
if buff.type == 5 then
buff.icon = "data/textures/icons/buffs/" .. (buff.icon and buff.icon or "Buff") .. ".png"
else
buff.icon = "data/textures/icons/buffs/" .. (buff.icon and buff.icon or Helper.BonusNameByIndex[buff.stat]) .. ".png"
-- check if it's a debuff, only simple buffs can be detected as positive/negative
if buff.stat == StatsBonuses.HyperspaceCooldown
or buff.stat == StatsBonuses.HyperspaceRechargeEnergy
or buff.stat == StatsBonuses.ShieldTimeUntilRechargeAfterHit
or buff.stat == StatsBonuses.ShieldTimeUntilRechargeAfterDepletion
or buff.stat == StatsBonuses.PilotsPerFighter
or buff.stat == StatsBonuses.MinersPerTurret
or buff.stat == StatsBonuses.GunnersPerTurret
or buff.stat == StatsBonuses.MechanicsPerTurret then
if buff.type == 2 then
buff.isDebuff = buff.value > 1
else
buff.isDebuff = buff.value > 0
end
else
if buff.type == 2 then
buff.isDebuff = buff.value < 1
else
buff.isDebuff = buff.value < 0
end
end
end
-- description
if not buff.desc then
buff.desc = buffDescriptions[buff.name]
else
buff.desc = buff.desc%_t
end
if buff.desc then
if buff.descArgs then
buff.desc = buff.desc % buff.descArgs
end
buff.desc = buff.desc:split("\n")
end
-- name
buff.name = buff.name%_t
newbuffs[buffsCount] = buff
end
-- sort buffs by priority
table.sort(newbuffs, function(a, b)
local aprio = a.prio or 0
local bprio = b.prio or 0
if aprio > bprio then
return true
elseif aprio == bprio then
return a.name < b.name
end
end)
buffs = newbuffs
end
-- FUNCTIONS --
function BuffsMod.setHideShipIconsOverlay(value)
Config.HideShipIconsOverlay = value
end
-- API --
function BuffsMod.getBuffs()
return buffs and table.deepcopy(buffs) or {}
end
function BuffsMod.getBuff(name, type)
if type and buffPrefixes[type] then
name = buffPrefixes[type] .. name
local buff = buffs[name]
return buff and table.deepcopy(buff) or nil
end
for _, buff in pairs(buffs) do
if buff.name == name then
return table.deepcopy(buff)
end
end
end
else -- onServer
data = {
nextKey = 10000,
freeKeys = {},
buffs = {}
}
pending = {} -- functions that modders tried to call before `restore`
-- local isReady -- immediately true if script was just added, otherwise false until `restore` function
-- PREDEFINED --
function BuffsMod.getUpdateInterval()
return Entity().aiOwned and Config.NPCUpdateInterval or Config.UpdateInterval
end
function BuffsMod.initialize()
local entity = Entity()
savedEntity = entity
debugName = string.format("%s(%s)", entity.name or entity.title, entity.index.string)
-- if script was just added, it will not have
isReady = entity:getValue("Buffs") == nil
if isReady then
isFirstLaunch = true
entity:setValue("Buffs", true)
entity:sendCallback("onBuffsReady", entity.index, {}, true, false)
end
entity:registerCallback("onSectorEntered", "onSectorEntered")
entity:registerCallback("onCraftSeatEntered", "onCraftSeatEntered")
entity:registerCallback("onCraftSeatLeft", "onCraftSeatLeft")
Sector():registerCallback("onRestoredFromDisk", "onRestoredFromDisk")
end
function BuffsMod.update(timePassed) -- Can't use updateParallelSelf because custom callbacks crash the server
local canFixEffects = true
for name, buff in pairs(data.buffs) do
if buff.duration ~= -1 then -- decay duration and remove buffs
buff.duration = math.max(0, buff.duration - timePassed)
if buff.duration == 0 then
BuffsMod.removeBuffWithType(name)
end
end
-- check if entity should have any custom effects
if data.fixEffects and canFixEffects and buff and buff.duration ~= 0 and buff.type == 5 then
for _, effect in ipairs(buff.effects) do
if effect.script then
canFixEffects = false
break
end
end
end
end
if data.fixEffects and canFixEffects then -- some custom effect scripts weren't removed when needed, trying to fix this
Log:Info("(%s) trying to remove old custom effects", debugName)
local entity = Entity()
local scripts = entity:getScripts()
for index, path in pairs(scripts) do
if string.find(path, "data/scripts/entity/buffs/", 1, true) then
Log:Debug("(%s) removing old effect script %i: %s", debugName, index, path)
entity:removeScript(path)
end
end
data.fixEffects = nil
end
end
function BuffsMod.secure()
-- attempting to fix an error
if not savedEntity or not valid(savedEntity) then
Log:Info("(%s) secure - entity is nil or invalid", debugName)
data.shield = nil
data.energy = nil
return data
end
-- save energy and shield
data.shield = savedEntity.shieldDurability
if savedEntity:hasComponent(ComponentType.EnergySystem) then
data.energy = EnergySystem(savedEntity).energy
else
data.energy = nil
end
Log:Debug("(%s) Secure: shield %s, energy %s", debugName, tostring(data.shield), tostring(data.energy))
return data
end
function BuffsMod.restore(_data)
local entity = Entity()
Log:Debug("(%s) Restore", debugName)
data = _data or {
nextKey = 10000,
freeKeys = {},
buffs = {}
}
if not isReady then -- check for pending buffs
-- reapply old buffs
for fullname, buff in pairs(data.buffs) do
if buff.type == 1 then
entity:addKeyedBaseMultiplier(buff.stat, buff.key, buff.value)
elseif buff.type == 2 then
entity:addKeyedMultiplier(buff.stat, buff.key, buff.value)
elseif buff.type == 3 then
entity:addKeyedMultiplyableBias(buff.stat, buff.key, buff.value)
elseif buff.type == 4 then
entity:addKeyedAbsoluteBias(buff.stat, buff.key, buff.value)
elseif buff.type == 5 then
for _, effect in ipairs(buff.effects) do
if effect.type == 1 then
entity:addKeyedBaseMultiplier(effect.stat, effect.key, effect.value)
elseif effect.type == 2 then
entity:addKeyedMultiplier(effect.stat, effect.key, effect.value)
elseif effect.type == 3 then
entity:addKeyedMultiplyableBias(effect.stat, effect.key, effect.value)
elseif effect.type == 4 then
entity:addKeyedAbsoluteBias(effect.stat, effect.key, effect.value)
end
end
end
end
-- restore shield and energy
deferredCallback(0.25, "deferredRestore", data.shield, data.energy)
-- apply pending buffs
isReady = true
local absoluteIgnore = {} -- a fix for pending absolute-duration buffs
for _, v in ipairs(pending) do
absoluteIgnore[v.args[1]] = true
BuffsMod[v.func](unpack(v.args))
end
pending = absoluteIgnore
entity:sendCallback("onBuffsReady", entity.index, table.deepcopy(data.buffs), false, false)
BuffsMod.refreshData()
end
end
function BuffsMod.onRemove()
Log:Info("(%s) onRemove fired for some reason", debugName)
-- in case something happens and script will be removed, reset 'Buffs'
Entity():setValue("Buffs")
end
-- CALLABLE --
function BuffsMod.refreshData() -- send data to clients
if callingPlayer then
local player = Player(callingPlayer)
if player.craftIndex == Entity().index then
invokeClientFunction(player, "receiveData", BuffsMod.prepareClientBuffs())
end
else -- to all pilots
local entity = Entity()
if entity.hasPilot then
local clientBuffs = BuffsMod.prepareClientBuffs()
for _, playerIndex in ipairs({entity:getPilotIndices()}) do
invokeClientFunction(Player(playerIndex), "receiveData", clientBuffs)
end
end
end
end
callable(BuffsMod, "refreshData")
-- CALLBACKS --
function BuffsMod.onSectorEntered()
savedEntity = Entity()
end
function BuffsMod.onRestoredFromDisk(timePassed)
if not pending then pending = {} end
for fullname, buff in pairs(data.buffs) do
if buff.isAbsolute and buff.duration ~= -1 and not pending[buff.name] then
buff.duration = math.max(0, buff.duration - timePassed)
if buff.duration == 0 then
BuffsMod.removeBuffWithType(fullname)
end
end
end
end
function BuffsMod.onCraftSeatEntered(entityId, seat, playerIndex) -- add tied-buffs
if Entity().index == entityId and seat == 0 then
local player = Player(playerIndex)
local playerBuffs = Helper.getBuffs(player)
if not playerBuffs then
Log:Error("(%s) Player '%s'(%i) buffs is nil", debugName, player.name, playerIndex)
else
local funcs = {"_addBaseMultiplier", "_addMultiplier", "_addMultiplyableBias", "_addAbsoluteBias"}
for _, buff in ipairs(playerBuffs) do
if buff.type ~= 5 then -- StatsBonuses
Log:Debug("(%s) Adding tied buff '%s' from player '%s'(%i)", debugName, buff.name, player.name, playerIndex)
BuffsMod[funcs[buff.type]](buff.name, buff.stat, buff.value, buff.duration, Helper.Mode.AddOrRefresh, nil, buff.icon, buff.desc, buff.descArgs, buff.color, buff.lowColor, buff.prio, playerIndex)
elseif #buff.shipEffects > 0 then
Log:Debug("(%s) Adding tied buff '%s' from player '%s'(%i)", debugName, buff.name, player.name, playerIndex)
BuffsMod._addBuff(buff.name, buff.shipEffects, buff.duration, Helper.Mode.AddOrRefresh, nil, buff.icon, buff.desc, buff.descArgs, buff.color, buff.lowColor, buff.prio, playerIndex)
end
end
end
end
end
function BuffsMod.onCraftSeatLeft(entityId, seat, playerIndex) -- remove tied buffs
if Entity().index == entityId and seat == 0 then
for fullname, buff in pairs(data.buffs) do
if buff.player == playerIndex then
Log:Debug("(%s) Removing tied player %i buff '%s'", debugName, playerIndex, fullname)
BuffsMod.removeBuffWithType(fullname)
end
end
end
end
-- FUNCTIONS --
function BuffsMod.getFreeKey(amount) -- Find available keys for stat bonuses
-- single key
if not amount then
local key
local length = #data.freeKeys
if length > 0 then -- try to reuse old keys
key = data.freeKeys[length]
data.freeKeys[length] = nil
return key
end
key = data.nextKey
if key == 11000 then return nil end -- ran out of keys
data.nextKey = data.nextKey + 1
return key
end
-- multiple keys
local freeLen = #data.freeKeys
local available = freeLen + (11000 - data.nextKey)
if amount > available then return nil end -- ran out of keys
local keys = {}
local maxFree = math.min(freeLen, amount)
amount = amount - maxFree
for i = freeLen, 1 + (freeLen - maxFree), -1 do -- try to reuse old keys
keys[#keys+1] = data.freeKeys[i]
data.freeKeys[i] = nil
end
for i = 1, amount do
keys[#keys+1] = data.nextKey
data.nextKey = data.nextKey + 1
end
return keys
end
function BuffsMod.deferredRestore(shield, energy)
local entity = Entity()
Log:Debug("(%s) dataShield: %s, shield: %s, maxShield: %s", debugName, tostring(shield), tostring(entity.shieldDurability), tostring(entity.shieldMaxDurability))
if shield and entity.shieldMaxDurability then
if shield > entity.shieldDurability then
entity.shieldDurability = math.min(shield, entity.shieldMaxDurability)
end
end
Log:Debug("(%s) dataEnergy: %s", debugName, tostring(energy))
if energy and entity:hasComponent(ComponentType.EnergySystem) then
local energySystem = EnergySystem(entity)
Log:Debug("(%s) energy: %s, capacity: %s", debugName, tostring(energySystem.energy), tostring(energySystem.capacity))
if energy > energySystem.energy then
energySystem.energy = math.min(energy, energySystem.capacity)
end
end
end
function BuffsMod.prepareClientBuffs()
local clientBuffs = {}
for fullname, buff in pairs(data.buffs) do
if buff.prio ~= -1000 then -- don't send hidden buffs
clientBuffs[fullname] = buff
end
end
return clientBuffs
end
-- NEVER call this function via 'BuffsMod._addBuff'. Use 'BuffsHelper.addBuff' from the BuffsHelper.lua
function BuffsMod._addBuff(name, effects, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex)
if not isReady then -- add to pending operations
pending[#pending+1] = {
func = "_addBuff",
args = {name, effects, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex}
}
return nil, 0
end
if string.find(name, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if not duration or duration < 0 then duration = -1 end
if not applyMode then applyMode = 1 end
if duration == -1 then -- can't use 'Combine' when duration is infinite
if applyMode == 3 then applyMode = 2
elseif applyMode == 5 then applyMode = 4 end
end
local fullname = "B_"..name
if string.sub(name, 1, 1) == "_" then -- if a buff name starts with _, it's a hidden buff
priority = -1000
end
local buff = data.buffs[fullname]
if applyMode == 1 and buff then return false end -- already exists
if applyMode >= 4 and not buff then return false end -- doesn't exist
local entity = Entity()
if _playerIndex then -- it's a tied buff
local player = Player(_playerIndex)
if player.craft.index ~= entity.index then return nil, 9 end
end
if not buff then
local keysNeeded = 0
for _, effect in ipairs(effects) do
if effect.type then -- only StatsBonuses need keys
keysNeeded = keysNeeded + 1
end
end
local keys = BuffsMod.getFreeKey(keysNeeded)
if not keys then return nil, 2 end -- can't add more than 1000 bonuses
local k = 1
local scripts
for i, effect in ipairs(effects) do
if effect[1] then -- support for a short-hand for vanilla stats
effect = { type = effect[1], stat = effect[2], value = effect[3] }
effects[i] = effect
end
if effect.script then -- custom entity script
if not effect.args then effect.args = {} end
if not scripts then scripts = entity:getScripts() end
entity:addScript("data/scripts/entity/buffs/"..effect.script..".lua", unpack(effect.args))
local newScripts = entity:getScripts()
for j, _ in pairs(newScripts) do -- check the difference between old and new script indexes
if not scripts[j] then
effect.index = j
break
end
end
Log:Debug("(%s) _addBuff, script effect.index: %i", debugName, effect.index or -1)
scripts = newScripts
elseif effect.customStat and effect.target ~= Helper.Target.Player then -- custom stat
local entityStat = Helper.Stats[effect.customStat]
if entityStat then
entityStat.onApply(nil, entity, unpack(effect.args))
end
elseif effect.type then -- vanilla StatsBonuses
effect.key = keys[k]
k = k + 1
if effect.type == 1 then
entity:addKeyedBaseMultiplier(effect.stat, effect.key, effect.value)
elseif effect.type == 2 then
entity:addKeyedMultiplier(effect.stat, effect.key, effect.value)
elseif effect.type == 3 then
entity:addKeyedMultiplyableBias(effect.stat, effect.key, effect.value)
else
entity:addKeyedAbsoluteBias(effect.stat, effect.key, effect.value)
end
end
end
buff = {
name = name,
effects = effects,
duration = duration,
isAbsolute = isAbsoluteDecay and true or nil,
icon = icon,
desc = description,
descArgs = descArgs,
color = color,
lowColor = lowDurationColor,
prio = priority,
type = 5,
player = _playerIndex
}
data.buffs[fullname] = buff
entity:sendCallback("onBuffApplied", entity.index, 5, applyMode, table.deepcopy(buff))
else
local modified = {
duration = buff.duration
}
if applyMode == 2 or applyMode == 4 then
buff.duration = duration
elseif applyMode == 3 or applyMode == 5 then
buff.duration = buff.duration + duration
end
-- allow to modify other stats just in case
if icon then
modified.icon = buff.icon
buff.icon = icon
end
if description then
modified.desc = buff.desc
buff.desc = description
end
if descArgs then
modified.descArgs = buff.descArgs
buff.descArgs = descArgs
end
if color then
modified.color = buff.color
buff.color = color
end
if lowDurationColor then
modified.lowColor = buff.lowColor
buff.lowColor = lowDurationColor
end
if priority then
modified.prio = buff.prio
buff.prio = priority
end
entity:sendCallback("onBuffApplied", entity.index, 5, applyMode, table.deepcopy(buff), modified)
end
BuffsMod.refreshData()
return true
end
-- NEVER call this function via 'BuffsMod._addBaseMultiplier'. Use 'BuffsHelper.addBaseMultiplier' from the BuffsHelper.lua
function BuffsMod._addBaseMultiplier(name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex)
if not isReady then -- add to pending operations
pending[#pending+1] = {
func = "_addBaseMultiplier",
args = {name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex}
}
return nil, 0
end
if string.find(name, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if not duration or duration < 0 then duration = -1 end
if not applyMode then applyMode = 1 end
if duration == -1 then
if applyMode == 3 then applyMode = 2
elseif applyMode == 5 then applyMode = 4 end
end
local fullname = "BM_"..name
if string.sub(name, 1, 1) == "_" then -- if a buff name starts with _, it's a hidden buff
priority = -1000
end
local buff = data.buffs[fullname]
if applyMode == 1 and buff then return false end -- already exists
if applyMode >= 4 and not buff then return false end -- doesn't exist
local entity = Entity()
if _playerIndex then -- it's a tied buff
local player = Player(_playerIndex)
if player.craft.index ~= entity.index then return nil, 9 end
end
if not buff then
local key = BuffsMod.getFreeKey()
if not key then return nil, 2 end -- can't add more than 1000 buffs
entity:addKeyedBaseMultiplier(stat, key, value)
buff = {
name = name,
stat = stat,
value = value,
duration = duration,
isAbsolute = isAbsoluteDecay and true or nil,
icon = icon,
desc = description,
descArgs = descArgs,
color = color,
lowColor = lowDurationColor,
key = key,
prio = priority,
type = 1,
player = _playerIndex
}
data.buffs[fullname] = buff
entity:sendCallback("onBuffApplied", entity.index, 1, applyMode, table.deepcopy(buff))
else
local modified = {
duration = buff.duration
}
if applyMode == 2 or applyMode == 4 then
buff.duration = duration
elseif applyMode == 3 or applyMode == 5 then
buff.duration = buff.duration + duration
end
-- refresh other stats just in case
if icon then
modified.icon = buff.icon
buff.icon = icon
end
if description then
modified.desc = buff.desc
buff.desc = description
end
if descArgs then
modified.descArgs = buff.descArgs
buff.descArgs = descArgs
end
if color then
modified.color = buff.color
buff.color = color
end
if lowDurationColor then
modified.lowColor = buff.lowColor
buff.lowColor = lowDurationColor
end
if priority then
modified.prio = buff.prio
buff.prio = priority
end
entity:sendCallback("onBuffApplied", entity.index, 1, applyMode, table.deepcopy(buff), modified)
end
BuffsMod.refreshData()
return true
end
-- NEVER call this function via 'BuffsMod._addMultiplier'. Use 'BuffsHelper.addMultiplier' from the BuffsHelper.lua
function BuffsMod._addMultiplier(name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex)
if not isReady then -- add to pending operations
pending[#pending+1] = {
func = "_addMultiplier",
args = {name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex}
}
return nil, 0
end
if string.find(name, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if not duration or duration < 0 then duration = -1 end
if not applyMode then applyMode = 1 end
if duration == -1 then
if applyMode == 3 then applyMode = 2
elseif applyMode == 5 then applyMode = 4 end
end
local fullname = "M_"..name
if string.sub(name, 1, 1) == "_" then -- if a buff name starts with _, it's a hidden buff
priority = -1000
end
local buff = data.buffs[fullname]
if applyMode == 1 and buff then return false end -- already exists
if applyMode >= 4 and not buff then return false end -- doesn't exist
local entity = Entity()
if _playerIndex then -- it's a tied buff
local player = Player(_playerIndex)
if player.craft.index ~= entity.index then return nil, 9 end
end
if not buff then
local key = BuffsMod.getFreeKey()
if not key then return nil, 2 end -- can't add more than 1000 buffs
entity:addKeyedMultiplier(stat, key, value)
buff = {
name = name,
stat = stat,
value = value,
duration = duration,
isAbsolute = isAbsoluteDecay and true or nil,
icon = icon,
desc = description,
descArgs = descArgs,
color = color,
lowColor = lowDurationColor,
key = key,
prio = priority,
type = 2,
player = _playerIndex
}
data.buffs[fullname] = buff
entity:sendCallback("onBuffApplied", entity.index, 2, applyMode, table.deepcopy(buff))
else
local modified = {
duration = buff.duration
}
if applyMode == 2 or applyMode == 4 then
buff.duration = duration
elseif applyMode == 3 or applyMode == 5 then
buff.duration = buff.duration + duration
end
-- refresh other stats just in case
if icon then
modified.icon = buff.icon
buff.icon = icon
end
if description then
modified.desc = buff.desc
buff.desc = description
end
if descArgs then
modified.descArgs = buff.descArgs
buff.descArgs = descArgs
end
if color then
modified.color = buff.color
buff.color = color
end
if lowDurationColor then
modified.lowColor = buff.lowColor
buff.lowColor = lowDurationColor
end
if priority then
modified.prio = buff.prio
buff.prio = priority
end
entity:sendCallback("onBuffApplied", entity.index, 2, applyMode, table.deepcopy(buff), modified)
end
BuffsMod.refreshData()
return true
end
-- NEVER call this function via 'BuffsMod._addMultiplyableBias'. Use 'BuffsHelper.addMultiplyableBias' from the BuffsHelper.lua
function BuffsMod._addMultiplyableBias(name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex)
if not isReady then -- add to pending operations
pending[#pending+1] = {
func = "_addMultiplyableBias",
args = {name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex}
}
return nil, 0
end
if string.find(name, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if not duration or duration < 0 then duration = -1 end
if not applyMode then applyMode = 1 end
if duration == -1 then
if applyMode == 3 then applyMode = 2
elseif applyMode == 5 then applyMode = 4 end
end
local fullname = "MB_"..name
if string.sub(name, 1, 1) == "_" then -- if a buff name starts with _, it's a hidden buff
priority = -1000
end
local buff = data.buffs[fullname]
if applyMode == 1 and buff then return false end -- already exists
if applyMode >= 4 and not buff then return false end -- doesn't exist
local entity = Entity()
if _playerIndex then -- it's a tied buff
local player = Player(_playerIndex)
if player.craft.index ~= entity.index then return nil, 9 end
end
if not buff then
local key = BuffsMod.getFreeKey()
if not key then return nil, 2 end -- can't add more than 1000 buffs
entity:addKeyedMultiplyableBias(stat, key, value)
buff = {
name = name,
stat = stat,
value = value,
duration = duration,
isAbsolute = isAbsoluteDecay and true or nil,
icon = icon,
desc = description,
descArgs = descArgs,
color = color,
lowColor = lowDurationColor,
key = key,
prio = priority,
type = 3,
player = _playerIndex
}
data.buffs[fullname] = buff
entity:sendCallback("onBuffApplied", entity.index, 3, applyMode, table.deepcopy(buff))
else
local modified = {
duration = buff.duration
}
if applyMode == 2 or applyMode == 4 then
buff.duration = duration
elseif applyMode == 3 or applyMode == 5 then
buff.duration = buff.duration + duration
end
-- refresh other stats just in case
if icon then
modified.icon = buff.icon
buff.icon = icon
end
if description then
modified.desc = buff.desc
buff.desc = description
end
if descArgs then
modified.descArgs = buff.descArgs
buff.descArgs = descArgs
end
if color then
modified.color = buff.color
buff.color = color
end
if lowDurationColor then
modified.lowColor = buff.lowColor
buff.lowColor = lowDurationColor
end
if priority then
modified.prio = buff.prio
buff.prio = priority
end
entity:sendCallback("onBuffApplied", entity.index, 3, applyMode, table.deepcopy(buff), modified)
end
BuffsMod.refreshData()
return true
end
-- NEVER call this function via 'BuffsMod._addAbsoluteBias'. Use 'BuffsHelper.addAbsoluteBias' from the BuffsHelper.lua
function BuffsMod._addAbsoluteBias(name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex)
if not isReady then -- add to pending operations
pending[#pending+1] = {
func = "_addAbsoluteBias",
args = {name, stat, value, duration, applyMode, isAbsoluteDecay, icon, description, descArgs, color, lowDurationColor, priority, _playerIndex}
}
return nil, 0
end
if string.find(name, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if not duration or duration < 0 then duration = -1 end
if not applyMode then applyMode = 1 end
if duration == -1 then
if applyMode == 3 then applyMode = 2
elseif applyMode == 5 then applyMode = 4 end
end
local fullname = "AB_"..name
if string.sub(name, 1, 1) == "_" then -- if a buff name starts with _, it's a hidden buff
priority = -1000
end
local buff = data.buffs[fullname]
if applyMode == 1 and buff then return false end -- already exists
if applyMode >= 4 and not buff then return false end -- doesn't exist
local entity = Entity()
if _playerIndex then -- it's a tied buff
local player = Player(_playerIndex)
if player.craft.index ~= entity.index then return nil, 9 end
end
if not buff then
local key = BuffsMod.getFreeKey()
if not key then return nil, 2 end -- can't add more than 1000 buffs
entity:addKeyedAbsoluteBias(stat, key, value)
buff = {
name = name,
stat = stat,
value = value,
duration = duration,
isAbsolute = isAbsoluteDecay and true or nil,
icon = icon,
desc = description,
descArgs = descArgs,
color = color,
lowColor = lowDurationColor,
key = key,
prio = priority,
type = 4,
player = _playerIndex
}
data.buffs[fullname] = buff
entity:sendCallback("onBuffApplied", entity.index, 4, applyMode, table.deepcopy(buff))
else
local modified = {
duration = buff.duration
}
if applyMode == 2 or applyMode == 4 then
buff.duration = duration
elseif applyMode == 3 or applyMode == 5 then
buff.duration = buff.duration + duration
end
-- refresh other stats just in case
if icon then
modified.icon = buff.icon
buff.icon = icon
end
if description then
modified.desc = buff.desc
buff.desc = description
end
if descArgs then
modified.descArgs = buff.descArgs
buff.descArgs = descArgs
end
if color then
modified.color = buff.color
buff.color = color
end
if lowDurationColor then
modified.lowColor = buff.lowColor
buff.lowColor = lowDurationColor
end
if priority then
modified.prio = buff.prio
buff.prio = priority
end
entity:sendCallback("onBuffApplied", entity.index, 4, applyMode, table.deepcopy(buff), modified)
end
BuffsMod.refreshData()
return true
end
-- API --
-- The following functions CAN be used directly ('BuffsMod.removeBuff') and via BuffsHelper.lua (BuffsHelper.removeBuff)
function BuffsMod.removeBuff(name)
return BuffsMod.removeBuffWithType("B_"..name)
end
function BuffsMod.removeBaseMultiplier(name)
return BuffsMod.removeBuffWithType("BM_"..name)
end
function BuffsMod.removeMultiplier(name)
return BuffsMod.removeBuffWithType("M_"..name)
end
function BuffsMod.removeMultiplyableBias(name)
return BuffsMod.removeBuffWithType("MB_"..name)
end
function BuffsMod.removeAbsoluteBias(name)
return BuffsMod.removeBuffWithType("AB_"..name)
end
function BuffsMod.removeBuffWithType(fullname, buffType)
if not isReady then -- add to pending operations
pending[#pending+1] = {
func = "removeBuffWithType",
args = {fullname, buffType}
}
return nil, 0
end
if string.find(fullname, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if buffType then
local prefix = buffPrefixes[buffType]
if prefix then
fullname = prefix..fullname
end
end
local buff = data.buffs[fullname]
if not buff then return false end -- can't find
local entity = Entity()
if buff.type == 5 then -- remove all bonuses
local scripts
for _, effect in ipairs(buff.effects) do
if effect.script then -- custom entity script
if effect.index then
if not scripts then scripts = entity:getScripts() end
local effectScript = "data/scripts/entity/buffs/"..effect.script..".lua"
local script = scripts[effect.index]
if script and string.find(script, effectScript, 1, true) then
entity:removeScript(effect.index)
Log:Debug("(%s) Removing buff script: %i", debugName, effect.index)
else
Log:Error("(%s) Couldn't remove buff script '%i', paths don't match: '%s' ~= '%s' - will be automatically fixed when possible", debugName, effect.index, effectScript, script or "")
data.fixEffects = true
end
end
elseif effect.customStat and effect.target ~= Helper.Target.Player then -- custom stat
local entityStat = Helper.Stats[effect.customStat]
if entityStat then
entityStat.onRemove(nil, entity, unpack(effect.args))
end
elseif effect.type then -- vanilla StatsBonuses
entity:removeBonus(effect.key)
data.freeKeys[#data.freeKeys+1] = effect.key
end
end
else
entity:removeBonus(buff.key)
data.freeKeys[#data.freeKeys+1] = buff.key
end
entity:sendCallback("onBuffRemoved", entity.index, buff.type, table.deepcopy(buff))
data.buffs[fullname] = nil
BuffsMod.refreshData()
return true
end
function BuffsMod.getBuffs()
if not isReady then return {}, 0 end
local r = {}
for _, buff in pairs(data.buffs) do
r[#r+1] = table.deepcopy(buff)
end
return r
end
function BuffsMod.getBuff(name, type)
if not isReady then return nil, 0 end
if string.find(name, '.', 1, true) then return nil, 1 end -- names can't contain '.'
if type and buffPrefixes[type] then
name = buffPrefixes[type] .. name
local buff = data.buffs[name]
return buff and table.deepcopy(buff) or nil
end
for _, buff in pairs(data.buffs) do
if buff.name == name then
return table.deepcopy(buff)
end
end
end
function BuffsMod.isReady()
return isReady
end
end |
--アタッチメント・サイバーン
--Script by XyLeN
function c100341001.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(100341001,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetRange(LOCATION_HAND+LOCATION_MZONE)
e1:SetCondition(c100341001.eqcon)
e1:SetTarget(c100341001.eqtg)
e1:SetOperation(c100341001.eqop)
c:RegisterEffect(e1)
--atkup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(600)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(100341001,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_TO_GRAVE)
e3:SetCountLimit(1,100341001)
e3:SetCondition(c100341001.spcon)
e3:SetTarget(c100341001.sptg)
e3:SetOperation(c100341001.spop)
c:RegisterEffect(e3)
end
function c100341001.eqcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():CheckUniqueOnField(tp)
end
function c100341001.filter(c)
return c:IsFaceup() and c:IsRace(RACE_DRAGON+RACE_MACHINE) and c:IsSetCard(0x93)
end
function c100341001.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c100341001.filter(chkc) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c100341001.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c100341001.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c100341001.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
if c:IsLocation(LOCATION_MZONE) and c:IsFacedown() then return end
local tc=Duel.GetFirstTarget()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 or tc:GetControler()~=tp or tc:IsFacedown() or not tc:IsRelateToEffect(e) or not c:CheckUniqueOnField(tp) then
Duel.SendtoGrave(c,REASON_EFFECT)
return
end
c100341001.equip_cyber_monster(c,tp,tc)
end
function c100341001.equip_cyber_monster(c,tp,tc)
if not Duel.Equip(tp,c,tc) then return end
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(c100341001.eqlimit)
e1:SetLabelObject(tc)
c:RegisterEffect(e1)
end
function c100341001.eqlimit(e,c)
return c==e:GetLabelObject()
end
function c100341001.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_SZONE) and not c:IsReason(REASON_LOST_TARGET)
end
function c100341001.spfilter(c,e,tp)
return c:IsRace(RACE_DRAGON+RACE_MACHINE) and c:IsSetCard(0x93) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c100341001.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c100341001.spfilter(chkc,e,tp) and chkc~=c end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c100341001.spfilter,tp,LOCATION_GRAVE,0,1,c,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c100341001.spfilter,tp,LOCATION_GRAVE,0,1,1,c,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c100341001.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
|
local Node = require 'pl.class' ()
function Node:_init(path)
self.path = path or ""
self.dirs = {}
self.pages = {}
self.contents = {}
self.generators = {}
end
function Node:eachDir ()
return ipairs(self.dirs)
end
function Node:eachPage ()
return ipairs(self.pages)
end
function Node:eachContent ()
return ipairs(self.contents)
end
function Node:eachGenerator ()
return ipairs(self.generators)
end
function Node:getDir(idx)
return self.dirs[idx]
end
function Node:getPage(idx)
return self.pages[idx]
end
function Node:getContent(idx)
return self.contents[idx]
end
function Node:getGenerator(idx)
return self.generators[idx]
end
function Node:addDir (path)
local child = Node(path .. "/")
table.insert(self.dirs, child)
return child
end
function Node:addPage (path)
table.insert(self.pages, path)
end
function Node:addContent (path)
table.insert(self.contents, path)
end
function Node:addGenerator (path)
table.insert(self.generators, path)
end
function Node:sort ()
table.sort(self.pages)
table.sort(self.dirs, function (a,b) return a.path < b.path end)
table.sort(self.contents)
table.sort(self.generators)
end
return Node
|
--------------------------------------------------------------------------------
-- dsl-fsm/bootstrap.lua: DSL FSM bootstrap code
-- This file is a part of le-dsl-fsm project
-- Copyright (c) LogicEditor <info@logiceditor.com>
-- Copyright (c) le-dsl-fsm authors
-- See file `COPYRIGHT` for the license.
--------------------------------------------------------------------------------
local unpack, error
= unpack, error
--------------------------------------------------------------------------------
local is_string,
is_table
= import 'lua-nucleo/type.lua'
{
'is_string',
'is_table'
}
local timap,
tset
= import 'lua-nucleo/table-utils.lua'
{
'timap',
'tset'
}
local check_dsl_fsm_handler_chunk
= import 'dsl-fsm/check.lua'
{
'check_dsl_fsm_handler_chunk'
}
--------------------------------------------------------------------------------
local dsl_fsm_bootstrap_chunk = function()
-- TODO: Try to eliminate more copy-paste an boilerplate code.
local check_common_state_param = function(self, param)
if self:good() then
-- Preliminary format validation to improve
-- error handling user-friendliness.
-- (It is not very convenient to see errors at apply() time.)
if is_string(param.from) then
param.from = { param.from }
end
if param.from_init ~= nil then
self:ensure_is("from_init", param.from_init, "boolean")
end
if param.from ~= nil then
self:ensure_is("from", param.from, "table")
if self:good() then
self:ensure("from can't be empty", #param.from > 0)
end
else
self:ensure(
"must be from_init if no from specified",
param.from_init == true
)
end
self:ensure(
"must have ins",
param.from ~= nil or param.from_init ~= nil
)
if self:good() then
self:ensure("must have outs", #param > 0)
end
if param.handler ~= nil then
self:ensure_is("handler", param.handler, "function")
if self:good() then
-- TODO: Improve error reporting by providing more details
-- in the chunk name.
check_dsl_fsm_handler_chunk(
self,
"handler",
param.handler
)
end
end
if param.meta_handler ~= nil then
self:ensure_is("meta_handler", param.meta_handler, "function")
if self:good() then
-- TODO: Improve error reporting by providing more details
-- in the chunk name.
check_dsl_fsm_handler_chunk(
self,
"meta_handler",
param.meta_handler
)
end
end
self:ensure_is("id", param.id, "string")
end
end
local common_extension_states = function(states, param)
local name = param.name
local call_handler = param.call_handler
local call_meta_handler = param.call_meta_handler
local apply_to_id = param.apply_to_id or "(-dsl).<ext*>.apply_to"
local outs = param.outs
states[#states + 1] =
{
type = "index"; id = "(-dsl)." .. name;
from_init = true;
"(-dsl)." .. name .. "{param}";
value = name;
handler = function(self, t, k)
t.states = t.states or { }
end;
}
states[#states + 1] =
{
type = "call"; id = "(-dsl)." .. name .. "{param}";
from = "(-dsl)." .. name;
meta_handler = call_meta_handler; -- may be nil
handler = call_handler;
-- Must be last ones
apply_to_id;
unpack(outs);
}
return states
end
local state_param_checker = function(msg, have_value_field, prepare_states)
return function(self, t, param)
self:ensure_field_call(param)
-- TODO: Get rid of concatenations here
self:ensure_is(msg .. ".param", param, "table")
check_common_state_param(self, param)
if have_value_field and self:good() then
-- TODO: Allow arbitrary key types?
self:ensure_is(msg .. ".value", param.value, "string")
end
if self:good() then
prepare_states(self, t, param)
return t
end
-- Pity user and simplify error handing by failing early.
local res, err = self:context().dsl_env:result()
error(msg .. ": broken meta DSL: " .. err, 2) -- TODO: Tune level
end
end
local default_apply_to_handler = function(self, t, meta_dsl_proxy, _)
-- Note that we can't reliably check for a field call,
-- since meta_dsl_proxy can be our own proxy.
-- We're checking for a single argument instead.
self:ensure_is("single argument only", _, "nil")
self:ensure_is("meta_dsl_proxy", meta_dsl_proxy, "table")
if self:good() then
meta_dsl_proxy._add_states(t.states)
end
if not self:good() then
-- Too broken to continue.
local res, err = self:context().dsl_env:result()
error("broken meta DSL: " .. err, 2) -- TODO: Tune level
end
end
local common_apply_to_states = function(states, param)
local name = param.name or "<ext*>"
local meta_handler = param.meta_handler or default_apply_to_handler
states[#states + 1] =
{
type = "index"; id = "(-dsl)." .. name .. ".apply_to";
from = "(-dsl)." .. name .. ".apply_to(meta_dsl_proxy)";
"(-dsl)." .. name .. ".apply_to(meta_dsl_proxy)";
value = "apply_to";
}
states[#states + 1] =
{
type = "call";
id = "(-dsl)." .. name .. ".apply_to(meta_dsl_proxy)";
from = "(-dsl)." .. name .. ".apply_to";
"(-dsl)." .. name .. ".apply_to";
false;
meta_handler = meta_handler;
}
end
local outs =
{
"(-dsl)._index";
"(-dsl)._call";
"(-dsl)._field_call";
"(-dsl)._method_call";
-- Added below:
-- (-dsl)._final;
}
local extension_states = { }
common_apply_to_states(extension_states, { })
-- (-dsl)._index { param } .apply_to(meta_dsl_proxy)
common_extension_states(
extension_states,
{
outs = outs;
name = "_index";
call_handler = state_param_checker(
"._index",
true,
function(self, t, param)
if self:good() then
param.type = "index"
t.states[#t.states + 1] = param
end
end
);
}
)
-- (-dsl)._call { param } .apply_to(meta_dsl_proxy)
common_extension_states(
extension_states,
{
outs = outs;
name = "_call";
call_handler = state_param_checker(
"._call",
false,
function(self, t, param)
if self:good() then
param.type = "call"
t.states[#t.states + 1] = param
end
end
);
}
)
-- (-dsl)._field_call { param } .apply_to(meta_dsl_proxy)
common_extension_states(
extension_states,
{
outs = outs;
name = "_field_call";
-- TODO: Generalize copy-paste with _method_call below
call_handler = state_param_checker(
"._field_call",
true,
function(self, t, param)
local handler = param.handler
local meta_handler = param.meta_handler
t.states[#t.states + 1] =
{
type = "index"; id = param.id;
from = param.from;
from_init = param.from_init;
param.id .. "()";
value = param.value;
}
local call_state =
{
type = "call"; id = param.id .. "()";
from = param.id;
meta_handler = meta_handler and function(self, t, ...)
self:ensure_field_call((...))
return meta_handler(self, t, ...)
end or nil;
handler = handler and function(self, t, ...)
self:ensure_field_call((...))
return handler(self, t, ...)
end or nil;
}
for i = 1, #param do
call_state[#call_state + 1] = param[i]
end
t.states[#t.states + 1] = call_state
end
);
}
)
-- (-dsl)._method_call { param } .apply_to(meta_dsl_proxy)
common_extension_states(
extension_states,
{
outs = outs;
name = "_method_call";
-- TODO: Generalize copy-paste with _method_call below
call_handler = state_param_checker(
".method_call",
true,
function(self, t, param)
local handler = param.handler
local meta_handler = param.meta_handler
t.states[#t.states + 1] =
{
type = "index"; id = param.id;
from = param.from;
from_init = param.from_init;
param.id .. "()";
value = param.value;
}
local call_state =
{
type = "call"; id = param.id .. "()";
from = param.id;
meta_handler = meta_handler and function(self, t, ...)
self:ensure_method_call((...))
return meta_handler(self, t, ...)
end or nil;
handler = handler and function(self, t, ...)
self:ensure_method_call((...))
return handler(self, t, ...)
end or nil;
}
for i = 1, #param do
call_state[#call_state + 1] = param[i]
end
t.states[#t.states + 1] = call_state
end
);
}
)
-- (-dsl)._extension { ext_list } .apply_to(meta_dsl_proxy)
common_extension_states(
extension_states,
{
outs = { };
name = "_extension";
apply_to_id = "(-dsl)._extension{param}*.apply_to";
call_meta_handler = function(self, t, ext_list)
-- TODO: validate ext_list somehow?
self:ensure_field_call(ext_list)
self:ensure_is("ext_list", ext_list, "table")
if self:good() then
t.states = ext_list
return t
end
-- Pity user and simplify error handing by failing early.
local res, err = self:context().dsl_env:result()
error("broken meta DSL: " .. err, 2) -- TODO: Tune level
end;
}
)
common_apply_to_states(
extension_states,
{
name = "_extension{param}*";
meta_handler = function(self, t, meta_dsl_proxy, _)
-- Note that we can't reliably check for a field call,
-- since meta_dsl_proxy can be our own proxy.
-- We're checking for a single argument instead.
self:ensure_is("single argument only", _, "nil")
self:ensure_is("meta_dsl_proxy", meta_dsl_proxy, "table")
if self:good() then
for i = 1, #t.states do
t.states[i].apply_to(meta_dsl_proxy)
end
end
if not self:good() then
-- Too broken to continue.
local res, err = self:context().dsl_env:result()
error("broken meta DSL: " .. err, 2) -- TODO: Tune level
end
end;
}
)
;(-(-_))._add_states(extension_states)
;(-(-_))._field_call
{
id = "(-dsl)._extend";
from_init = true;
"(-dsl)._add_states";
"(-dsl)._extend";
false;
value = "_extend";
meta_handler = function(self, t, extensions)
self:ensure_is("extensions", extensions, "table")
return t, function()
if self:good() then
local proxy = self:proxy()
for i = 1, #extensions do
extensions[i].apply_to(proxy)
end
end
if not self:good() then
-- Too broken to continue.
local res, err = self:context().dsl_env:result()
error("broken meta DSL: " .. err, 2) -- TODO: Tune level
end
end
end;
}.apply_to(-(-_))
;(-(-_))._extend
{
-- (-dsl)._final { param } .apply_to(meta_dsl_proxy)
(-(-_))._field_call
{
id = "(-dsl)._final";
from_init = true;
-- TODO: Lazy.
from = timap(function(out) return out .. "{param}" end, outs);
value = "_final";
meta_handler = function(self, t, param)
self:ensure_is("extensions", param, "table")
if is_string(param.from) then
param.from = { param.from }
end
self:ensure_is("from", param.from, "table")
if self:good() then
for i = 1, #param.from do
self:ensure_is("from[" .. i .. "]", param.from[i], "string")
end
end
self:ensure_is("handler", param.handler, "function")
if self:good() then
-- TODO: Improve error reporting by providing more details
-- in the chunk name.
check_dsl_fsm_handler_chunk(
self,
"handler",
param.handler
)
end
if self:good() then
param.from = tset(param.from)
t.states[#t.states + 1] =
{
type = "final"; id = false;
-- TODO: Avoid creating closure here.
handler = function(self, t)
if param.from[self:prev_state_id()] then
return param.handler(self, t)
end
return t
end;
}
end
end;
"(-dsl).<ext*>.apply_to";
"(-dsl)._final";
unpack(outs); -- Should be the last one.
}
;
}
end
--------------------------------------------------------------------------------
return
{
dsl_fsm_bootstrap_chunk = dsl_fsm_bootstrap_chunk;
}
|
Code:
--[[
Release by Rain on V3rmillion
Please leave this header intact to encourage future script releases!
Name: cbrohacks.lua
Author: Autumn
Desc: Hacky hacks for bad FPS players like me
Enjoy!
]]
do --SIGHT
local plr = game.Players.LocalPlayer
local allsguis = {}
local enabled = false
local dohax = function(lbplr)
wait() --make sure the character exists
if not lbplr.Character then return end
for _,obj in next,lbplr.Character:children() do
if obj:IsA("BasePart") then
local sguis = {}
local snew = function(...)
for _,face in next,{...} do
local sgui = Instance.new("SurfaceGui",obj)
sgui.Enabled = enabled
sgui.AlwaysOnTop = true
sgui.Face = face
table.insert(sguis,sgui)
sgui.AncestryChanged:connect(function()
for i,v in next,sguis do
if v == sgui then
table.remove(sguis,i)
sgui:destroy()
end
end
end)
end
end
snew("Front", "Back", "Left", "Right", "Top", "Bottom")
for _,sgui in next,sguis do
local sframe = Instance.new("Frame",sgui)
sframe.Size = UDim2.new(1,0,1,0)
sframe.BorderSizePixel = 0
sframe.BackgroundTransparency = .5
sframe.BackgroundColor3 = lbplr.TEEM.Value == plr.TEEM.Value and BrickColor.new("Really blue").Color or BrickColor.new("Really red").Color
end
table.insert(allsguis,sguis)
end
end
end
local connectPlayer = function(lbplr)
if lbplr ~= plr then
dohax(lbplr)
lbplr.CharacterAdded:connect(function(char)
dohax(lbplr)
end)
end
end
for _,v in next,game.Players:GetPlayers() do
connectPlayer(v)
end
game.Players.PlayerAdded:connect(function(p)
connectPlayer(p)
end)
game:GetService("UserInputService").InputBegan:connect(function(input)
if input.KeyCode == Enum.KeyCode.BackSlash then
enabled = not enabled
for _,v in next,allsguis do
for __,vv in next,v do
vv.Enabled = enabled
end
end
end
end)
end
do --AIM
local cam = game:GetService("Workspace").CurrentCamera
local plrs = game:GetService("Players"):GetPlayers()
local lplr = game:GetService("Players").LocalPlayer
local aiming = false
local dolerp = true
game:GetService("RunService"):BindToRenderStep("UpdateCamera", Enum.RenderPriority.Camera.Value, function()
if not aiming or not lplr.Character or not lplr.Character:FindFirstChild("Head") then return end
local cchar,cdist
for _,plr in next,plrs do
if plr ~= lplr and plr.TEEM.Value ~= lplr.TEEM.Value then
local char = plr.Character
if char and char:FindFirstChild("Head") then
local hit = workspace:FindPartOnRay(Ray.new((cam.CFrame*CFrame.new(0,0,-5)).p, char.Head.Position - (cam.CFrame*CFrame.new(0,0,-5)).p))
if hit and hit.Parent and hit.Parent == char or hit.Parent.Parent == char then
local dist = (char.Head.Position - lplr.Character.Head.Position).magnitude
if cdist == nil or dist < cdist then
cdist = dist
cchar = char
end
end
end
end
end
if not cchar then return end
cam.CFrame = dolerp and cam.CFrame:lerp(CFrame.new(cam.CFrame.p, cchar.Head.CFrame.p), .15) or CFrame.new(cam.CFrame.p, cchar.Head.CFrame.p)
end)
game.Players.PlayerAdded:connect(function(plr)
table.insert(plrs,plr)
end)
game.Players.PlayerRemoving:connect(function(plr)
for i,v in next,plrs do
if v == plr then
table.remove(plrs,i)
end
end
end)
game:GetService("UserInputService").InputBegan:connect(function(input)
if input.KeyCode == Enum.KeyCode.CapsLock then
aiming = not aiming
elseif input.KeyCode == Enum.KeyCode.RightBracket then
dolerp = true
elseif input.KeyCode == Enum.KeyCode.LeftBracket then
dolerp = false
end
end)
end
do --OMGWHAT
local plr = game.Players.LocalPlayer
game:GetService("UserInputService").InputBegan:connect(function(input)
if input.KeyCode == Enum.KeyCode.RightAlt then
if not plr.Character or not plr.Character:FindFirstChild("Head") then return end
for _,v in next,game.Players:children() do
if v ~= plr and v.TEEM.Value ~= plr.TEEM.Value and v.Character and v.Character:FindFirstChild("Head") and v.Character:FindFirstChild("Torso") and v.Character.Torso:FindFirstChild("Neck") then
local char = v.Character
local head = char.Head
char.Torso["Neck"]:destroy()
head.Anchored = true
head.CanCollide = false
head.Transparency = 1
head.face:destroy()
for _,vv in next,head:children() do
if vv:IsA("SurfaceGui") then
vv:destroy()
end
end
local rs = game:GetService("RunService").RenderStepped:connect(function()
head.CFrame = plr.Character.Head.CFrame*CFrame.new(0,0,-5)
end)
head.AncestryChanged:connect(function()
rs:disconnect()
end)
plr.Character.Head.AncestryChanged:connect(function()
rs:disconnect()
end)
end
end
end
end)
end
|
LinkLuaModifier("modifier_saber_instinct", "heroes/hero_saber/instinct.lua", LUA_MODIFIER_MOTION_NONE)
saber_instinct = class({
GetIntrinsicModifierName = function() return "modifier_saber_instinct" end,
})
modifier_saber_instinct = class({
IsHidden = function() return true end,
IsPurgable = function() return false end,
})
|
-- Copyright 2006-2017 Mitchell mitchell.att.foicica.com. See LICENSE.
-- Ini LPeg lexer.
local l = require('lexer')
local token, word_match = l.token, l.word_match
local P, R, S = lpeg.P, lpeg.R, lpeg.S
local M = {_NAME = 'ini'}
-- Whitespace.
local ws = token(l.WHITESPACE, l.space^1)
-- Comments.
local comment = token(l.COMMENT, l.starts_line(S(';#')) * l.nonnewline^0)
-- Strings.
local sq_str = l.delimited_range("'")
local dq_str = l.delimited_range('"')
local label = l.delimited_range('[]', true, true)
local string = token(l.STRING, sq_str + dq_str + label)
-- Numbers.
local dec = l.digit^1 * ('_' * l.digit^1)^0
local oct_num = '0' * S('01234567_')^1
local integer = S('+-')^-1 * (l.hex_num + oct_num + dec)
local number = token(l.NUMBER, (l.float + integer))
-- Keywords.
local keyword = token(l.KEYWORD, word_match{
'true', 'false', 'on', 'off', 'yes', 'no'
})
-- Identifiers.
local word = (l.alpha + '_') * (l.alnum + S('_.'))^0
local identifier = token(l.IDENTIFIER, word)
-- Operators.
local operator = token(l.OPERATOR, '=')
M._rules = {
{'whitespace', ws},
{'keyword', keyword},
{'identifier', identifier},
{'string', string},
{'comment', comment},
{'number', number},
{'operator', operator},
}
M._LEXBYLINE = true
return M
|
dgArcFireAtState = {}
local numFire = 5
local maxNumFire = 5
local timeout = 0.6
local steps = {hide=0,attack=1,back=2}
local getOutTime = 1
local shotTime = 1 --1.3
local fireAngle = math.pi/8
local timer=0
local trueAngle
function dgArcFireAtState.load()
--dgArcFireAtState.sheet = love.graphics.newImage()
--dgArcFireAtState.quads = {}
dgArcFireAtState.shots = {}
end
function dgArcFireAtState.start(boss)
dgArcFireAtState.shots.width = bullet.width--100
dgArcFireAtState.shots.height = bullet.height--100
dgArcFireAtState.boss = boss
boss.curr_sheet = boss.fly
startHide()
end
function prepareShots()
local w = love.graphics.getWidth()
local y = love.graphics.getHeight()+dgArcFireAtState.shots.height
local dx = y*math.tan(fireAngle)
local speedX = -dx/shotTime
local speedY = y/shotTime
y = -dgArcFireAtState.shots.height
if love.math.random()>0.5 then
preparePatternShots(speedX, speedY, dx, y, 10)
else
for i=1, numFire do
local x = love.math.random()*(w-dgArcFireAtState.shots.width)+dgArcFireAtState.shots.width/2
table.insert(dgArcFireAtState.shots,{speedX=speedX,timer=timeout*i,isReady=false,x=x+dx,y=y,speedY=speedY,aComp=animComp.newAnim(6,0.7)})
end
end
end
--Make first shot of random to target player
function preparePatternShots(speedX, speedY, dx, y, quant)
local start = dgArcFireAtState.shots.width
local final = love.graphics.getWidth()-dgArcFireAtState.shots.width/2
local dist = (final-start)/quant
for i=1, quant do
table.insert(dgArcFireAtState.shots,{speedX=speedX,timer=timeout*i,isReady=false,x=dx+(i-1)*dist,y=y,speedY=speedY,aComp=animComp.newAnim(6,0.7)})
end
end
function startHide()
local dg = dgArcFireAtState.boss
dgArcFireAtState.destLoc = love.graphics.getWidth()+dg.width
dgArcFireAtState.vel = (dgArcFireAtState.destLoc-dg.x)/getOutTime
dgArcFireAtState.actualStep = steps.hide
end
function updateHide(dt)
local dg = dgArcFireAtState.boss
dg.x = dg.x + dgArcFireAtState.vel*dt
if dg.x>dgArcFireAtState.destLoc then
startAttack()
end
end
function startAttack()
audio.playDgScream()
timer = timeout
dgArcFireAtState.actualStep = steps.attack
--audio
--audio.playDragonScream()
prepareShots()
end
function updateAttack(dt)
local p = player
local h = love.graphics.getHeight()
for i,v in ipairs(dgArcFireAtState.shots) do
--Droping stage
if v.isReady then
--Timeout
if v.timer>0 then
v.timer = v.timer-dt
--Droping
else
v.x = v.x+v.speedX*dt
v.y = v.y+v.speedY*dt
if v.y>h then
table.remove(dgArcFireAtState.shots,i)
elseif contact.isInRectContact(p.x,p.y,p.width,p.height,v.x,v.y,dgArcFireAtState.shots.width,dgArcFireAtState.shots.height) then
p.reset()
end
end
--Mark stage
else
--Timeout
v.timer = v.timer-dt
if v.timer<0 then
v.isReady=true
v.timer = timeout
end
end
end
print(#dgArcFireAtState.shots)
if #dgArcFireAtState.shots==0 then
startShow()
end
end
function startShow()
local dg = dgArcFireAtState.boss
dgArcFireAtState.actualStep = steps.show
dgArcFireAtState.destLoc = love.graphics.getWidth()-dg.width
dgArcFireAtState.vel = (dgArcFireAtState.destLoc-dg.x)/getOutTime
end
function updateShow(dt)
local dg = dgArcFireAtState.boss
dg.x = dg.x+dgArcFireAtState.vel*dt
if dg.x<dgArcFireAtState.destLoc then
dg.x = dgArcFireAtState.destLoc
dg.endState()
end
end
function dgArcFireAtState.update(dt)
local s = dgArcFireAtState.actualStep
if s==steps.hide then
print("hide")
updateHide(dt)
elseif s==steps.attack then
print("attack")
updateAttack(dt)
else
print("show")
updateShow(dt)
end
end
function dgArcFireAtState.draw()
local angle = -(math.pi/2-fireAngle)
--love.graphics.setColor(255,50,50)
for i,v in ipairs(dgArcFireAtState.shots) do
if v.isReady then
--angle = -(math.pi/2-math.atan((stage.velocity-v.speedX)/v.speedY))
love.graphics.draw(bullet.image,bullet.quads[v.aComp.curr_frame],v.x,v.y,angle,bullet.scale,bullet.scale,bullet.offset.x,bullet.offset.y)
--love.graphics.rectangle("fill",v.x,v.y,dgArcFireAtState.shots.width,dgArcFireAtState.shots.height)
end
end
--love.graphics.setColor(255,255,255)
end |
modifier_undeadbuilder_necromancy_lua = modifier_undeadbuilder_necromancy_lua or class({})
function modifier_undeadbuilder_necromancy_lua:IsDebuff()
return false
end
function modifier_undeadbuilder_necromancy_lua:IsStunDebuff()
return false
end
function modifier_undeadbuilder_necromancy_lua:IsHidden()
return false
end
function modifier_undeadbuilder_necromancy_lua:IsAura()
return true
end
function modifier_undeadbuilder_necromancy_lua:IsPermanent()
return true
end
function modifier_undeadbuilder_necromancy_lua:IsAura()
return true
end
function modifier_undeadbuilder_necromancy_lua:DeclareFunctions()
local funcs = {
MODIFIER_EVENT_ON_DEATH
}
return funcs
end
function modifier_undeadbuilder_necromancy_lua:OnDeath()
if (Game.gameState ~= GAMESTATE_FIGHTING) then
return
end
self.npc = self:GetParent()
if (self.npc:GetHealth() ~= 0) then
return
end
if (self.npc == nil or self.npc.unit == nil) then
return
end
self.unit = self.npc.unit
local goldCost = self.unit.goldCost
local zombie =
CreateUnitByName(
"tower_undeadbuilder_resurrected",
self.npc:GetAbsOrigin(),
false,
self.unit,
nil,
self.npc:GetTeamNumber()
)
FindClearSpaceForUnit(zombie, self.npc:GetAbsOrigin(), true)
zombie.nextTarget = self.npc.nextTarget
zombie.player = self.npc.player
zombie.unit = self.unit
--Adjust strength based on gold
zombie:SetMaxHealth(goldCost * 2 / 3 + 40)
zombie:SetHealth(goldCost * 2 / 3 + 40)
zombie:SetPhysicalArmorBaseValue(goldCost / 10 - 3)
zombie:SetBaseDamageMin(12 + 0.085 * goldCost)
zombie:SetModelScale(0.4787234 + 0.00070921 * goldCost)
self:Destroy()
Game:AddEndOfRoundListener(
function()
if (not zombie:IsNull()) then
zombie:ForceKill(false)
end
return nil
end
)
end
function modifier_undeadbuilder_necromancy_lua:RemoveOnDeath()
return true
end
function modifier_undeadbuilder_necromancy_lua:IsPurgable()
return false
end
function modifier_undeadbuilder_necromancy_lua:GetTexture()
return "necrolyte_sadist"
end
|
AddCSLuaFile()
local A = "AMBER"
local R = "RED"
local DR = "D_RED"
local W = "WHITE"
local PI = {}
PI.StateMaterials = {
["main-r"] = {
Index = 22,
States = {
["running-r"] = "photon/override/20explorer_brake"
}
},
["main-l"] = {
Index = 23,
States = {
["running-l"] = "photon/override/20explorer_brake"
}
}
}
PI.Meta = {
headlight = {
AngleOffset = -90,
W = 8.2,
H = 8,
Sprite = "sprites/emv/fpiu20_headlight",
Scale = 2.25,
WMult = 1
},
turn_signal = {
AngleOffset = -90,
W = 10.5,
H = 8,
Sprite = "sprites/emv/fpiu20_turnsignal",
Scale = 1,
WMult = 2
},
rear_turn = {
AngleOffset = 90,
W = 8.0,
H = 8.3,
Sprite = "sprites/emv/fpiu20_rearturn",
Scale = 1,
WMult = 1
},
reverse = {
AngleOffset = 90,
W = 8.0,
H = 8.3,
Sprite = "sprites/emv/fpiu20_reverse",
Scale = 1,
WMult = 1
},
brake_light = {
AngleOffset = 90,
W = 24.0,
H = 19.0,
Sprite = "sprites/emv/fpiu20_brakelight",
Scale = 1.5,
WMult = 1
},
tail_light = {
AngleOffset = 90,
W = 11.2,
H = 10.0,
Sprite = "sprites/emv/fpiu20_taillight",
Scale = 0,
WMult = 0,
SourceOnly = true,
},
tail_glow = {
AngleOffset = 90,
W = 0,
H = 0,
Sprite = "sprites/emv/blank",
Scale = 1.0,
WMult = 2.0,
EmitArray = {
Vector(-6, 0, 0),
Vector(0, 0, 0),
Vector(6, 0, 0)
}
},
running_light = {
AngleOffset = -90,
W = 18,
H = 17,
Sprite = "sprites/emv/fpiu20_running",
Scale = 1,
WMult = 1.5
},
}
PI.Positions = {
[1] = { Vector( 29.1, 110.6, 47.7 ), Angle( 0, 0, 0 ), "headlight" },
[2] = { Vector( -29.1, 110.6, 47.7 ), Angle( 0, 0, 0 ), "headlight" },
[3] = { Vector( 36.9, 105.7, 48.4 ), Angle( 0, 0, 0 ), "headlight" },
[4] = { Vector( -36.9, 105.7, 48.4 ), Angle( 0, 0, 0 ), "headlight" },
[5] = { Vector( -26.8, 114.5, 50.4 ), Angle( 0.73, 21.39, -1.86 ), "turn_signal" },
[6] = { Vector( 26.8, 114.5, 50.4 ), Angle( 180-0.73, -21.39, 180+1.86 ), "turn_signal" },
[7] = { Vector( -35.47, -109.75, 54.01 ), Angle( 180, -26.1, 180 ), "rear_turn" },
[8] = { Vector( 35.47, -109.75, 54.01 ), Angle( 0, 26.1, 0 ), "rear_turn" },
[9] = { Vector( -35.3, -109.47, 48.81 ), Angle( 180, -26.1, 180-5 ), "reverse" },
[10] = { Vector( 35.3, -109.47, 48.81 ), Angle( 0, 26.1, 5 ), "reverse" },
[11] = { Vector( 39.4, -108.57, 54.01 ), Angle( 0, 26.1, 0.5 ), "brake_light" },
[12] = { Vector( -39.4, -108.57, 54.01 ), Angle( 180, -26.1, 180-0.5 ), "brake_light" },
[13] = { Vector( -5.04, -101.37, 79.25 ), Angle( 0, 0, 0 ), "tail_light" },
[14] = { Vector( 5.04, -101.37, 79.25 ), Angle( 0, 0, 0 ), "tail_light" },
[15] = { Vector( 0, -101.37, 79.25 ), Angle( 0, 0, 0 ), "tail_glow" },
[16] = { Vector( -43.19, 99.51, 49.01 ), Angle( 3.92, 78.49, 23.86 ), "running_light" },
[17] = { Vector( 43.19, 99.51, 49.01 ), Angle( 180-3.92, -78.49, 180-23.86 ), "running_light" },
}
PI.States = {}
PI.States.Headlights = {}
PI.States.Brakes = {
{ 11, DR, 1 }, { 12, DR, 1 }, { 13, R, 1 }, { 14, R, 1 }, { 15, R, 1 },
}
PI.States.Blink_Left = {
{ 5, A, 1 }, { 7, A, 1 },
}
PI.States.Blink_Right = {
{ 6, A, 1 }, { 8, A, 1 },
}
PI.States.Reverse = {
{ 9, W, 1 }, { 10, W, 1 },
}
PI.States.Running = {
{ 3, W, .5 }, { 4, W, .5 },
{ 16, A, .5 }, { 17, A, .5 },
{ 11, DR, .5 }, { 12, DR, .5 },
{ "_main-l", "running-l" }, { "_main-r", "running-r" }
}
Photon.VehicleLibrary["sgm_fpiu20"] = PI |
-- Autogenerated from KST: please remove this line if doing any edits by hand!
local luaunit = require("luaunit")
require("params_pass_array_int")
TestParamsPassArrayInt = {}
function TestParamsPassArrayInt:test_params_pass_array_int()
local r = ParamsPassArrayInt:from_file("src/position_to_end.bin")
luaunit.assertEquals(#r.pass_ints.nums, 3)
luaunit.assertEquals(r.pass_ints.nums[1], 513)
luaunit.assertEquals(r.pass_ints.nums[2], 1027)
luaunit.assertEquals(r.pass_ints.nums[3], 1541)
luaunit.assertEquals(#r.pass_ints_calc.nums, 2)
luaunit.assertEquals(r.pass_ints_calc.nums[1], 27643)
luaunit.assertEquals(r.pass_ints_calc.nums[2], 7)
end
|
object_mobile_vehicle_vehicle_atst = object_mobile_vehicle_shared_vehicle_atst:new {
templateType = VEHICLE,
decayRate = 15, -- Damage tick per decay cycle
decayCycle = 600 -- Time in seconds per cycle
}
ObjectTemplates:addTemplate(object_mobile_vehicle_vehicle_atst, "object/mobile/vehicle/vehicle_atst.iff") |
local function trace(s)
io.stderr:write(s)
end
local function rgbaStr(color)
return string.format("#%02x%02x%02x@%02x", rgba.r(color), rgba.g(color), rgba.b(color), rgba.a(color))
end
local function randomCh()
return math.random(0, 255)
end
local function createRandomImage(width, height)
local img = image.new(width, height)
for y = 1, height do
for x = 1, width do
local color = rgba.rgb(randomCh(), randomCh(), randomCh())
img:set(x, y, color)
end
end
return img
end
local function traceImage(img)
for y = 1, img:height() do
for x = 1, img:width() do
trace(rgba.str(img:get(x, y)))
trace(" ")
end
trace("\n")
end
return img
end
local function traceKernel(k)
for y = 1, k:height() do
for x = 1, k:width() do
trace(k:get(x, y))
trace(" ")
end
trace("\n")
end
end
local function makeGaussian(radius)
local width = radius * 2 + 1
local height = width
local values = {}
local r2 = radius * radius
local sr = math.sqrt(radius)
for y = 1, height do
for x = 1, width do
local distance = math.sqrt((x - radius) * (x - radius) + (y - radius) * (y - radius))
table.insert(values, math.exp(-(sr * distance * distance / r2)))
end
end
return kernel.of(width, height, values)
end
local function makeLaplace(radius)
local width = radius * 2 + 1
local height = width
local values = {}
for i = 1, width * height do table.insert(values, -1) end
values[math.ceil(#values / 2)] = width * height - 1
return kernel.of(width, height, values)
end
local gaussian = makeGaussian(5)
local laplace = kernel.of(3, 3, {
-1, -1, -1,
-1, 8, -1,
-1, -1, -1,
})
laplace = makeLaplace(2)
traceKernel(laplace)
return inp:convolve(gaussian)
:convolve(laplace)
|
local d, digits, alpha = '01230120022455012623010202', {}, ('A'):byte()
d:gsub(".",function(c)
digits[string.char(alpha)] = c
alpha = alpha + 1
end)
function soundex(w)
local res = {}
for c in w:upper():gmatch'.'do
local d = digits[c]
if d then
if #res==0 then
res[1] = c
elseif #res==1 or d~= res[#res] then
res[1+#res] = d
end
end
end
if #res == 0 then
return '0000'
else
res = table.concat(res):gsub("0",'')
return (res .. '0000'):sub(1,4)
end
end
-- tests
local tests = {
{"", "0000"}, {"12346", "0000"},
{"he", "H000"}, {"soundex", "S532"},
{"example", "E251"}, {"ciondecks", "C532"},
{"ekzampul", "E251"}, {"résumé", "R250"},
{"Robert", "R163"}, {"Rupert", "R163"},
{"Rubin", "R150"}, {"Ashcraft", "A226"},
{"Ashcroft", "A226"}
}
for i=1,#tests do
local itm = tests[i]
assert( soundex(itm[1])==itm[2] )
end
print"all tests ok"
|
--[[
memo_data make_memo(string receiver_id_or_name,
string key, string value, uint64_t ss, bool enable_logger=false);
]]
function test_make_memo(name, key, value, ss, enable_logger)
local message = "name:" .. name .. ", key:" .. key .. ", ss:"..tostring(ss) .. ", enable_logger: "..tostring(enable_logger)
chainhelper:log(message)
local memo = chainhelper:make_memo(name, key, value, ss, enable_logger);
chainhelper:log(type(memo))
end
|
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- C L I P B O A R D M A N A G E R P L U G I N --
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--- === plugins.finalcutpro.clipboard.manager ===
---
--- Clipboard Manager.
--------------------------------------------------------------------------------
--
-- EXTENSIONS:
--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Logger:
--------------------------------------------------------------------------------
local log = require("hs.logger").new("clipmgr")
--------------------------------------------------------------------------------
-- Hammerspoon Extensions:
--------------------------------------------------------------------------------
local pasteboard = require("hs.pasteboard")
local timer = require("hs.timer")
local uuid = require("hs.host").uuid
--------------------------------------------------------------------------------
-- CommandPost Extensions:
--------------------------------------------------------------------------------
local plist = require("cp.plist")
local protect = require("cp.protect")
local archiver = require("cp.plist.archiver")
local fcp = require("cp.apple.finalcutpro")
local dialog = require("cp.dialog")
local prop = require("cp.prop")
--------------------------------------------------------------------------------
--
-- CONSTANTS:
--
--------------------------------------------------------------------------------
local CLIPBOARD = protect({
--------------------------------------------------------------------------------
-- FCPX Types:
--------------------------------------------------------------------------------
ANCHORED_COLLECTION = "FFAnchoredCollection",
MARKER = "FFAnchoredTimeMarker",
GAP = "FFAnchoredGapGeneratorComponent",
--------------------------------------------------------------------------------
-- The default name used when copying from the Timeline:
--------------------------------------------------------------------------------
TIMELINE_DISPLAY_NAME = "__timelineContainerClip",
--------------------------------------------------------------------------------
-- The pasteboard/clipboard property containing the copied clips:
--------------------------------------------------------------------------------
PASTEBOARD_OBJECT = "ffpasteboardobject",
UTI = "com.apple.flexo.proFFPasteboardUTI"
})
--------------------------------------------------------------------------------
--
-- THE MODULE:
--
--------------------------------------------------------------------------------
local mod = {}
--- plugins.finalcutpro.clipboard.manager.excludedClassnames -> table
--- Variable
--- Table of data we don't want to count when copying.
mod.excludedClassnames = {CLIPBOARD.MARKER}
--- plugins.finalcutpro.clipboard.manager.watcherFrequency -> number
--- Variable
--- The Clipboard Watcher Update frequency.
mod.watcherFrequency = 0.5
--- plugins.finalcutpro.clipboard.manager.excludedClassnames -> table
--- Variable
--- Table of data we don't want to count when copying.
mod._watchersCount = 0
--- plugins.finalcutpro.clipboard.manager.isTimelineClip(data) -> boolean
--- Function
--- Is the data a timeline clip.
---
--- Parameters:
--- * data - The clipboard data you want to check.
---
--- Returns:
--- * `true` if a timeline clip otherwise `false`.
function mod.isTimelineClip(data)
return data.displayName == CLIPBOARD.TIMELINE_DISPLAY_NAME
end
--- plugins.finalcutpro.clipboard.manager.processObject(data) -> string, number
--- Function
--- Processes the provided data object, which should have a '$class' property.
---
--- Parameters:
--- * data - The clipboard data you want to check.
---
--- Returns:
--- * The primary clip name as a string.
--- * The number of clips as number.
function mod.processObject(data)
if type(data) == "table" then
local class = data['$class']
if class then
return mod.processContent(data)
elseif data[1] then
--------------------------------------------------------------------------------
-- It's an array:
--------------------------------------------------------------------------------
return mod.processArray(data)
end
end
return nil, 0
end
--- plugins.finalcutpro.clipboard.manager.isClassnameSupported(classname) -> boolean
--- Function
--- Is the class name supported?
---
--- Parameters:
--- * classname - The class name you want to check
---
--- Returns:
--- * `true` if the class name is supported otherwise `false`.
function mod.isClassnameSupported(classname)
for _,name in ipairs(mod.excludedClassnames) do
if name == classname then
return false
end
end
return true
end
--- plugins.finalcutpro.clipboard.manager.processArray(data) -> string, number
--- Function
--- Processes an 'array' table.
---
--- Parameters:
--- * data - The data object to process
---
--- Returns:
--- * The primary clip name as a string.
--- * The number of clips as number.
function mod.processArray(data)
local name = nil
local count = 0
for _,v in ipairs(data) do
local n,c = mod.processObject(v, data)
if name == nil then
name = n
end
count = count + c
end
return name, count
end
--- plugins.finalcutpro.clipboard.manager.supportsContainedItems(data) -> boolean
--- Function
--- Gets whether or not the data supports contained items.
---
--- Parameters:
--- * data - The data object to process
---
--- Returns:
--- * `true` if supported otherwise `false`.
function mod.supportsContainedItems(data)
local classname = mod.getClassname(data)
return data.containedItems and classname ~= CLIPBOARD.ANCHORED_COLLECTION
end
--- plugins.finalcutpro.clipboard.manager.getClassname(data) -> string
--- Function
--- Gets a class anem from data
---
--- Parameters:
--- * data - The data object to process
---
--- Returns:
--- * Class name as string
function mod.getClassname(data)
return data["$class"]["$classname"]
end
--- plugins.finalcutpro.clipboard.manager.processContent(data) -> string, number
--- Function
--- Process objects which have a `displayName`, such as Compound Clips, Images, etc.
---
--- Parameters:
--- * data - The data object to process
---
--- Returns:
--- * The primary clip name as a string.
--- * The number of clips as number.
function mod.processContent(data)
if not mod.isClassnameSupported(data) then
return nil, 0
end
if mod.isTimelineClip(data) then
--------------------------------------------------------------------------------
-- Just process the contained items directly:
--------------------------------------------------------------------------------
return mod.processObject(data.containedItems)
end
local displayName = data.displayName
local count = displayName and 1 or 0
if mod.getClassname(data) == CLIPBOARD.GAP then
displayName = nil
count = 0
end
local n, c
if mod.supportsContainedItems(data) then
n, c = mod.processObject(data.containedItems)
count = count + c
displayName = displayName or n
end
if data.anchoredItems then
n, c = mod.processObject(data.anchoredItems)
count = count + c
displayName = displayName or n
end
if displayName then
return displayName, count
else
return nil, 0
end
end
--- plugins.finalcutpro.clipboard.manager.processContent(fcpxData, default) -> string, number
--- Function
--- Searches the Pasteboard binary plist data for the first clip name, and returns it.
---
--- Parameters:
--- * fcpxData - The data object to process
--- * default - The default value
---
--- Returns:
--- * Returns the 'default' value if the pasteboard contains a media clip but we could not interpret it, otherwise `nil` if the data did not contain Final Cut Pro Clip data.
---
--- Notes:
--- * Example usage: `local name = mod.findClipName(myFcpxData, "Unknown")`
function mod.findClipName(fcpxData, default)
local data = mod.unarchiveFCPXData(fcpxData)
if data then
local name, count = mod.processObject(data.root.objects)
if name then
if count > 1 then
return name.." (+"..(count-1)..")"
else
return name
end
else
return default
end
end
return nil
end
--- plugins.finalcutpro.clipboard.manager.overrideNextClipName(overrideName) -> None
--- Function
--- Overrides the name for the next clip which is copied from FCPX to the specified
--- value. Once the override has been used, the standard clip name via
--- `mod.findClipName(...)` will be used for subsequent copy operations.
---
--- Parameters:
--- * overrideName - The override name.
---
--- Returns:
--- * None
function mod.overrideNextClipName(overrideName)
mod._overrideName = overrideName
end
--- plugins.finalcutpro.clipboard.manager.copyWithCustomClipName() -> None
--- Function
--- Copy with custom label.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.copyWithCustomClipName()
log.d("Copying Clip with custom Clip Name")
local menuBar = fcp:menuBar()
if menuBar:enabled("Edit", "Copy") then
local result = dialog.displayTextBoxMessage(i18n("overrideClipNamePrompt"), i18n("overrideValueInvalid"), "")
if result == false then return end
mod.overrideNextClipName(result)
menuBar:selectMenu({"Edit", "Copy"})
end
end
--- plugins.finalcutpro.clipboard.manager.copyWithCustomClipName() -> data | nil
--- Function
--- Reads FCPX Data from the Pasteboard as a binary Plist, if present.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The clipboard data or `nil`.
function mod.readFCPXData()
local clipboardContent = pasteboard.allContentTypes()
if clipboardContent ~= nil then
if clipboardContent[1] ~= nil then
if clipboardContent[1][1] == CLIPBOARD.UTI then
return pasteboard.readDataForUTI(CLIPBOARD.UTI)
end
end
end
return nil
end
--- plugins.finalcutpro.clipboard.manager.unarchiveFCPXData(fcpxData) -> data | nil
--- Function
--- Unarchive Final Cut Pro data.
---
--- Parameters:
--- * fcpxData - The data object to process
---
--- Returns:
--- * The unarchived Final Cut Pro Pasteboard data or `nil`.
function mod.unarchiveFCPXData(fcpxData)
if not fcpxData then
fcpxData = mod.readFCPXData()
end
local clipboardTable = plist.binaryToTable(fcpxData)
if clipboardTable then
local base64Data = clipboardTable[CLIPBOARD.PASTEBOARD_OBJECT]
if base64Data then
local fcpxTable, errorMessage = plist.base64ToTable(base64Data)
if fcpxTable then
return archiver.unarchive(fcpxTable)
else
log.ef("plist.base64ToTable Error: %s", errorMessage)
end
end
end
log.e("The clipboard does not contain any FCPX clip data.")
return nil
end
--- plugins.finalcutpro.clipboard.manager.writeFCPXData(fcpxData, quiet) -> boolean
--- Function
--- Write Final Cut Pro data to Pasteboard.
---
--- Parameters:
--- * fcpxData - The data to write
--- * quiet - Whether or not we should stop/start the watcher.
---
--- Returns:
--- * `true` if the operation succeeded, otherwise `false` (which most likely means ownership of the pasteboard has changed).
function mod.writeFCPXData(fcpxData, quiet)
--------------------------------------------------------------------------------
-- Write data back to Clipboard:
--------------------------------------------------------------------------------
if quiet then mod.stopWatching() end
local result = pasteboard.writeDataForUTI(CLIPBOARD.UTI, fcpxData)
if quiet then mod.startWatching() end
return result
end
--- plugins.finalcutpro.clipboard.manager.watch(events) -> table
--- Function
--- Watch events.
---
--- Parameters:
--- * events - Table of events
---
--- Returns:
--- * Table of watchers.
function mod.watch(events)
local startWatching = false
if not mod._watchers then
mod._watchers = {}
mod._watchersCount = 0
startWatching = true
end
local id = uuid()
mod._watchers[id] = {update = events.update}
mod._watchersCount = mod._watchersCount + 1
if startWatching then
mod.startWatching()
end
return {id=id}
end
--- plugins.finalcutpro.clipboard.manager.unwatch(id) -> boolean
--- Function
--- Stop a watcher.
---
--- Parameters:
--- * id - The ID of the watcher you want to stop.
---
--- Returns:
--- * `true` if successful otherwise `false`.
function mod.unwatch(id)
if mod._watchers then
if mod._watchers[id.id] then
mod._watchers[id.id] = nil
mod._watchersCount = mod._watchersCount - 1
if mod._watchersCount < 1 then
mod.stopWatching()
end
return true
end
end
return false
end
--- plugins.finalcutpro.clipboard.manager.startWatching() -> None
--- Function
--- Start Watching the Clipboard.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.startWatching()
if mod._watchersCount < 1 then
return
end
--log.d("Starting Clipboard Watcher.")
if mod._timer then
mod.stopWatching()
end
--------------------------------------------------------------------------------
-- Reset:
--------------------------------------------------------------------------------
mod._lastChange = pasteboard.changeCount()
--------------------------------------------------------------------------------
-- Watch for Clipboard Changes:
--------------------------------------------------------------------------------
mod._timer = timer.new(mod.watcherFrequency, function()
if not mod._watchers then
return
end
local currentChange = pasteboard.changeCount()
if (currentChange > mod._lastChange) then
--------------------------------------------------------------------------------
-- Read Clipboard Data:
--------------------------------------------------------------------------------
local data = mod.readFCPXData()
--------------------------------------------------------------------------------
-- Notify watchers
--------------------------------------------------------------------------------
if data then
local name
-- An override was set
if mod._overrideName ~= nil then
-- apply it
name = mod._overrideName
-- reset it
mod._overrideName = nil
else
-- find the name from inside the clip data
name = mod.findClipName(data, os.date())
end
for _,events in pairs(mod._watchers) do
if events.update then
events.update(data, name)
end
end
end
end
mod._lastChange = currentChange
end)
mod._timer:start()
mod.watching:update()
--log.d("Started Clipboard Watcher")
end
--- plugins.finalcutpro.clipboard.manager.stopWatching() -> None
--- Function
--- Stop Watching the Clipboard.
---
--- Parameters:
--- * None
---
--- Returns:
--- * None
function mod.stopWatching()
if mod._timer then
mod._timer:stop()
mod._timer = nil
mod.watching:update()
--log.d("Stopped Clipboard Watcher")
end
end
--- plugins.finalcutpro.clipboard.manager.watching <cp.prop: boolean>
--- Field
--- Gets whether or not we're watching the clipboard as a boolean.
mod.watching = prop.new(function()
return mod._timer ~= nil
end)
--------------------------------------------------------------------------------
--
-- THE PLUGIN:
--
--------------------------------------------------------------------------------
local plugin = {
id = "finalcutpro.clipboard.manager",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
--------------------------------------------------------------------------------
-- INITIALISE PLUGIN:
--------------------------------------------------------------------------------
function plugin.init(deps)
--------------------------------------------------------------------------------
-- COMMANDS:
--------------------------------------------------------------------------------
deps.fcpxCmds:add("cpCopyWithCustomLabel")
:whenActivated(mod.copyWithCustomClipName)
return mod
end
return plugin
|
EditorFadeToBlack = EditorFadeToBlack or class(MissionScriptEditor)
function EditorFadeToBlack:create_element()
self.super.create_element(self)
self._element.class = "ElementFadeToBlack"
self._element.values.state = false
end
function EditorFadeToBlack:_build_panel()
self:_create_panel()
self:BooleanCtrl("state", {text = "Fade in/out"})
self:Text("Fade in or out, takes 3 seconds. Hardcore.")
end
|
function on_activate(parent, ability)
parent:clear_flag("__sequencer_spell_1")
parent:clear_flag("__sequencer_spell_2")
parent:clear_flag("__sequencer_type")
local cb = ability:create_callback(parent)
cb:set_on_menu_select_fn("spell_select1")
local menu = game:create_menu("Select a Target Type", cb)
menu:add_choice("Self", "self")
menu:add_choice("Friendly", "friendly")
menu:add_choice("Hostile", "hostile")
menu:show(parent)
end
function on_deactivate(parent, ability)
ability:deactivate(parent)
end
function spell_select1(parent, ability, targets, selection)
parent:set_flag("__sequencer_type", selection:value())
local cb = ability:create_callback(parent)
cb:set_on_menu_select_fn("spell_select2")
setup_menu(parent, ability, parent:get_flag("__sequencer_type"), cb, "Select a 1st Spell")
end
function spell_select2(parent, ability, targets, selection)
parent:set_flag("__sequencer_spell_1", selection:value())
local cb = ability:create_callback(parent)
cb:set_on_menu_select_fn("create_sequencer")
setup_menu(parent, ability, parent:get_flag("__sequencer_type"), cb, "Select a 2nd Spell")
end
function setup_menu(parent, ability, target_type, cb, title)
local already_selected = "none"
if parent:has_flag("__sequencer_spell_1") then
already_selected = parent:get_flag("__sequencer_spell_1")
end
local abilities = {}
if target_type == "self" then
abilities = { "heal", "acid_weapon", "rock_armor", "fire_shield", "haste", "air_shield", "luck", "expediate", "minor_heal" }
elseif target_type == "friendly" then
abilities = { "heal", "acid_weapon", "haste", "expediate", "minor_heal" }
else
abilities = { "flare", "acid_bomb", "crush", "frostbite", "slow", "wind_gust", "shock", "firebolt", "dazzle",
"flaming_fingers", "stun" }
end
local menu = game:create_menu(title, cb)
for i = 1, #abilities do
local ability_id = abilities[i]
if already_selected ~= ability_id then
if parent:has_ability(ability_id) then
local ability = parent:get_ability(ability_id)
menu:add_choice(ability:name(), ability_id)
end
end
end
menu:show(parent)
end
function create_sequencer(parent, ability, targets, selection)
parent:set_flag("__sequencer_spell_2", selection:value())
local effect = parent:create_effect(ability:name())
effect:deactivate_with(ability)
local cb = ability:create_callback(parent)
cb:set_on_removed_fn("on_removed")
effect:add_callback(cb)
local gen = parent:create_anim("pulsing_particle")
gen:set_moves_with_parent()
gen:set_position(gen:param(0.0), gen:param(-3.0))
gen:set_color(gen:param(1.0), gen:param(1.0), gen:param(0.0), gen:param(1.0))
gen:set_particle_size_dist(gen:fixed_dist(1.0), gen:fixed_dist(1.0))
gen:set_draw_above_entities()
effect:add_anim(gen)
effect:apply()
ability:activate(parent)
parent:add_ability("activate_sequencer")
game:play_sfx("sfx/atmos02")
end
function on_removed(parent)
parent:clear_flag("__sequencer_spell_1")
parent:clear_flag("__sequencer_spell_2")
parent:clear_flag("__sequencer_type")
parent:remove_ability("activate_sequencer")
end
|
#!/usr/bin/env lua
-- Adapted from the book "Programming in Lua"
function norm (x, y)
local n2 = x^2 + y^2
return math.sqrt(n2)
end
function twice (x)
return 2*x
end
n = norm(3.4, 1.0)
print(twice(m))
-- ^
-- |
-- Bug Here |
-----------------------------
-- Private
-----------------------------
local defaults_values = {
debug = false,
show_ignored = false
}
-----------------------------
-- Export
-----------------------------
local config = {}
config.values = {}
---@param opts table
function config.set_default_values(opts)
config.values = vim.tbl_deep_extend('force', defaults_values, opts or {})
end
---get value
---@param key string
---@return any
function config.get(key)
return config.values[key]
end
return config
|
--
--------------------------------------------------------------------------------
-- FILE: decoder.lua
-- DESCRIPTION: protoc-gen-lua
-- Google's Protocol Buffers project, ported to lua.
-- https://code.google.com/p/protoc-gen-lua/
--
-- Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com
-- All rights reserved.
--
-- Use, modification and distribution are subject to the "New BSD License"
-- as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
--
-- COMPANY: NetEase
-- CREATED: 2010年07月29日 19时30分51秒 CST
--------------------------------------------------------------------------------
--
local string = string
local table = table
local assert = assert
local ipairs = ipairs
local error = error
local print = print
local pb = require "pb"
local encoder = require "encoder"
local wire_format = require "wire_format"
module "decoder"
local _DecodeVarint = pb.varint_decoder
local _DecodeSignedVarint = pb.signed_varint_decoder
local _DecodeVarint32 = pb.varint_decoder
local _DecodeSignedVarint32 = pb.signed_varint_decoder
ReadTag = pb.read_tag
local function _SimpleDecoder(wire_type, decode_value)
return function(field_number, is_repeated, is_packed, key, new_default)
if is_packed then
local DecodeVarint = _DecodeVarint
return function (buffer, pos, pend, message, field_dict)
local value = field_dict[key]
if value == nil then
value = new_default(message)
field_dict[key] = value
end
local endpoint
endpoint, pos = DecodeVarint(buffer, pos)
endpoint = endpoint + pos
if endpoint > pend then
error('Truncated message.')
end
local element
while pos < endpoint do
element, pos = decode_value(buffer, pos)
value[#value + 1] = element
end
if pos > endpoint then
value:remove(#value)
error('Packed element was truncated.')
end
return pos
end
elseif is_repeated then
local tag_bytes = encoder.TagBytes(field_number, wire_type)
local tag_len = #tag_bytes
local sub = string.sub
return function(buffer, pos, pend, message, field_dict)
local value = field_dict[key]
if value == nil then
value = new_default(message)
field_dict[key] = value
end
while 1 do
local element, new_pos = decode_value(buffer, pos)
value:append(element)
pos = new_pos + tag_len
if sub(buffer, new_pos+1, pos) ~= tag_bytes or new_pos >= pend then
if new_pos > pend then
error('Truncated message.')
end
return new_pos
end
end
end
else
return function (buffer, pos, pend, message, field_dict)
field_dict[key], pos = decode_value(buffer, pos)
if pos > pend then
field_dict[key] = nil
error('Truncated message.')
end
return pos
end
end
end
end
local function _ModifiedDecoder(wire_type, decode_value, modify_value)
local InnerDecode = function (buffer, pos)
local result, new_pos = decode_value(buffer, pos)
return modify_value(result), new_pos
end
return _SimpleDecoder(wire_type, InnerDecode)
end
local function _StructPackDecoder(wire_type, value_size, format)
local struct_unpack = pb.struct_unpack
function InnerDecode(buffer, pos)
local new_pos = pos + value_size
local result = struct_unpack(format, buffer, pos)
return result, new_pos
end
return _SimpleDecoder(wire_type, InnerDecode)
end
local function _Boolean(value)
return value ~= 0
end
Int32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeSignedVarint32)
EnumDecoder = Int32Decoder
Int64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeSignedVarint)
UInt32Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32)
UInt64Decoder = _SimpleDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint)
SInt32Decoder = _ModifiedDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint32, wire_format.ZigZagDecode32)
SInt64Decoder = _ModifiedDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint, wire_format.ZigZagDecode64)
Fixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, 4, string.byte('I'))
Fixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, 8, string.byte('Q'))
SFixed32Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, 4, string.byte('i'))
SFixed64Decoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, 8, string.byte('q'))
FloatDecoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED32, 4, string.byte('f'))
DoubleDecoder = _StructPackDecoder(wire_format.WIRETYPE_FIXED64, 8, string.byte('d'))
BoolDecoder = _ModifiedDecoder(wire_format.WIRETYPE_VARINT, _DecodeVarint, _Boolean)
function StringDecoder(field_number, is_repeated, is_packed, key, new_default)
local DecodeVarint = _DecodeVarint
local sub = string.sub
-- local unicode = unicode
assert(not is_packed)
if is_repeated then
local tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local tag_len = #tag_bytes
return function (buffer, pos, pend, message, field_dict)
local value = field_dict[key]
if value == nil then
value = new_default(message)
field_dict[key] = value
end
while 1 do
local size, new_pos
size, pos = DecodeVarint(buffer, pos)
new_pos = pos + size
if new_pos > pend then
error('Truncated string.')
end
value:append(sub(buffer, pos+1, new_pos))
pos = new_pos + tag_len
if sub(buffer, new_pos + 1, pos) ~= tag_bytes or new_pos == pend then
return new_pos
end
end
end
else
return function (buffer, pos, pend, message, field_dict)
local size, new_pos
size, pos = DecodeVarint(buffer, pos)
new_pos = pos + size
if new_pos > pend then
error('Truncated string.')
end
field_dict[key] = sub(buffer, pos + 1, new_pos)
return new_pos
end
end
end
function BytesDecoder(field_number, is_repeated, is_packed, key, new_default)
local DecodeVarint = _DecodeVarint
local sub = string.sub
assert(not is_packed)
if is_repeated then
local tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local tag_len = #tag_bytes
return function (buffer, pos, pend, message, field_dict)
local value = field_dict[key]
if value == nil then
value = new_default(message)
field_dict[key] = value
end
while 1 do
local size, new_pos
size, pos = DecodeVarint(buffer, pos)
new_pos = pos + size
if new_pos > pend then
error('Truncated string.')
end
value:append(sub(buffer, pos + 1, new_pos))
pos = new_pos + tag_len
if sub(buffer, new_pos + 1, pos) ~= tag_bytes or new_pos == pend then
return new_pos
end
end
end
else
return function(buffer, pos, pend, message, field_dict)
local size, new_pos
size, pos = DecodeVarint(buffer, pos)
new_pos = pos + size
if new_pos > pend then
error('Truncated string.')
end
field_dict[key] = sub(buffer, pos + 1, new_pos)
return new_pos
end
end
end
function MessageDecoder(field_number, is_repeated, is_packed, key, new_default)
local DecodeVarint = _DecodeVarint
local sub = string.sub
assert(not is_packed)
if is_repeated then
local tag_bytes = encoder.TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local tag_len = #tag_bytes
return function (buffer, pos, pend, message, field_dict)
local value = field_dict[key]
if value == nil then
value = new_default(message)
field_dict[key] = value
end
while 1 do
local size, new_pos
size, pos = DecodeVarint(buffer, pos)
new_pos = pos + size
if new_pos > pend then
error('Truncated message.')
end
if value:add():_InternalParse(buffer, pos, new_pos) ~= new_pos then
error('Unexpected end-group tag.')
end
pos = new_pos + tag_len
if sub(buffer, new_pos + 1, pos) ~= tag_bytes or new_pos == pend then
return new_pos
end
end
end
else
return function (buffer, pos, pend, message, field_dict)
local value = field_dict[key]
if value == nil then
value = new_default(message)
field_dict[key] = value
end
local size, new_pos
size, pos = DecodeVarint(buffer, pos)
new_pos = pos + size
if new_pos > pend then
error('Truncated message.')
end
if value:_InternalParse(buffer, pos, new_pos) ~= new_pos then
error('Unexpected end-group tag.')
end
return new_pos
end
end
end
function _SkipVarint(buffer, pos, pend)
local value
value, pos = _DecodeVarint(buffer, pos)
return pos
end
function _SkipFixed64(buffer, pos, pend)
pos = pos + 8
if pos > pend then
error('Truncated message.')
end
return pos
end
function _SkipLengthDelimited(buffer, pos, pend)
local size
size, pos = _DecodeVarint(buffer, pos)
pos = pos + size
if pos > pend then
error('Truncated message.')
end
return pos
end
function _SkipFixed32(buffer, pos, pend)
pos = pos + 4
if pos > pend then
error('Truncated message.')
end
return pos
end
function _RaiseInvalidWireType(buffer, pos, pend)
error('Tag had invalid wire type.')
end
function _FieldSkipper()
WIRETYPE_TO_SKIPPER = {
_SkipVarint,
_SkipFixed64,
_SkipLengthDelimited,
_SkipGroup,
_EndGroup,
_SkipFixed32,
_RaiseInvalidWireType,
_RaiseInvalidWireType,
}
-- wiretype_mask = wire_format.TAG_TYPE_MASK
local ord = string.byte
local sub = string.sub
return function (buffer, pos, pend, tag_bytes)
local wire_type = ord(sub(tag_bytes, 1, 1)) % 8 + 1
return WIRETYPE_TO_SKIPPER[wire_type](buffer, pos, pend)
end
end
SkipField = _FieldSkipper()
|
function onSay(cid, words, param, channel)
if(param == '') then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Command param required.")
return true
end
local account, tmp = getAccountIdByName(param), false
if(account == 0) then
account = getAccountIdByAccount(param)
if(account == 0) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Player or account '" .. param .. "' does not exists.")
return true
end
tmp = true
end
local ban = getBanData(account, BAN_ACCOUNT)
if(ban and doRemoveAccountBanishment(account)) then
local name = param
if(tmp) then
name = account
end
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, name .. " has been " .. (ban.expires == -1 and "undeleted" or "unbanned") .. ".")
end
if(tmp) then
return true
end
tmp = getIpByName(param)
if(isIpBanished(tmp) and doRemoveIpBanishment(tmp)) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "IP Banishment on " .. doConvertIntegerToIp(ip) .. " has been lifted.")
end
local guid = getPlayerGUIDByName(param, true)
if(guid == nil) then
return true
end
ban = getBanData(guid, BAN_PLAYER, PLAYERBAN_LOCK)
if(ban and doRemovePlayerBanishment(guid, PLAYERBAN_LOCK)) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, "Namelock from " .. param .. " has been removed.")
end
ban = getBanData(guid, BAN_PLAYER, PLAYERBAN_BANISHMENT)
if(ban and doRemovePlayerBanishment(guid, PLAYERBAN_BANISHMENT)) then
doPlayerSendTextMessage(cid, MESSAGE_STATUS_CONSOLE_BLUE, param .. " has been " .. (ban.expires == -1 and "undeleted" or "unbanned") .. ".")
end
return true
end
|
local tiny = require 'lib/tiny'
local windfield = require 'lib/windfield/windfield'
local box2d_colliders = {}
box2d_colliders.init = tiny.processingSystem()
box2d_colliders.init.filter = tiny.requireAll("collision")
box2d_colliders.world = nil
function box2d_colliders.init:onAdd(e)
-- Create the world if it doesn't exist
local world = box2d_colliders.world
for _, e in ipairs(self.world.entities) do
if world then break end
local filter = tiny.requireAll('box2d', 'world')
if filter(self.world, e) then
world = e
break
end
end
-- Create the collider
local collider = e.collision
local shape = collider.shape
if shape == "rectangle" then
e.collision.collider = world.world:newRectangleCollider(e.x, e.y, e.width, e.height)
end
if shape == "polygon" then
e.collision.collider = world.world:newPolygonCollider(collider.points)
end
if shape == "ellipse" then
print("ellipse not implemented")
end
if e.collision.static then
e.collision.collider:setType('static')
end
-- Add the entity to the collder's userData
local userData = e.collision.collider:getUserData()
userData.entity = e
e.collision.collider:setUserData(userData)
-- Add the world to the box2d_colliders object
box2d_colliders.world = world
end
function box2d_colliders.init:onRemove(e)
if e.collision.collider then
e.collision.collider:destroy()
end
end
box2d_colliders.update = tiny.processingSystem()
box2d_colliders.update.filter = tiny.requireAll("collision")
function box2d_colliders.update:process(e, dt)
local collider = e.collision
-- update the collider's position
if collider.updates_position then
local x, y = e.body:getPosition()
e.x = x
e.y = y
end
end
box2d_colliders.debug = {}
box2d_colliders.debug.draw = tiny.processingSystem()
box2d_colliders.debug.draw.filter = tiny.requireAll("collision")
function box2d_colliders.debug.draw:process(e, dt)
local collider = e.collision
local shape = collider.shape
if shape == "rectangle" then
love.graphics.rectangle("line", e.x, e.y, e.width, e.height)
end
if shape == "polygon" then
love.graphics.polygon("line", collider.points)
end
if shape == "ellipse" then
print("ellipse not implemented")
end
end
return box2d_colliders |
local theme_assets = require("beautiful.theme_assets")
local xresources = require("beautiful.xresources")
local dpi = xresources.apply_dpi
local theme = {}
theme.font = "Inconsolata Nerd Font Mono 10"
theme.bg_normal = "#002b3680"
theme.bg_focus = "#535d6c"
theme.bg_urgent = "#ff0000"
theme.bg_minimize = "#444444"
theme.bg_systray = theme.bg_normal
theme.fg_normal = "#aaaaaa"
theme.fg_focus = "#ffffff"
theme.fg_urgent = "#ffffff"
theme.fg_minimize = "#ffffff"
theme.useless_gap = dpi(3)
theme.border_width = dpi(1)
theme.border_normal = "#000000"
theme.border_focus = "#535d6c"
theme.border_marked = "#91231c"
-- There are other variable sets
-- overriding the default one when
-- defined, the sets are:
-- taglist_[bg|fg]_[focus|urgent|occupied|empty|volatile]
-- tasklist_[bg|fg]_[focus|urgent]
-- titlebar_[bg|fg]_[normal|focus]
-- tooltip_[font|opacity|fg_color|bg_color|border_width|border_color]
-- mouse_finder_[color|timeout|animate_timeout|radius|factor]
-- prompt_[fg|bg|fg_cursor|bg_cursor|font]
-- hotkeys_[bg|fg|border_width|border_color|shape|opacity|modifiers_fg|label_bg|label_fg|group_margin|font|description_font]
-- Example:
--theme.taglist_bg_focus = "#ff0000"
theme.hotkeys_bg = "#002b36"
-- Generate taglist squares:
local taglist_square_size = dpi(4)
theme.taglist_squares_sel = theme_assets.taglist_squares_sel(
taglist_square_size, theme.fg_normal
)
theme.taglist_squares_unsel = theme_assets.taglist_squares_unsel(
taglist_square_size, theme.fg_normal
)
theme.wallpaper = "~/.config/wallpaper/wallpaper.png"
return theme
|
local layout_data = {
{
{0, 0, 1, 1},
},
{
{0.0, 0.0, 0.5, 1.0},
{0.5, 0.0, 0.5, 1.0},
},
{
{0.0, 0.0, 0.5, 1.0},
{0.5, 0.0, 0.5, 0.5},
{0.5, 0.5, 0.5, 0.5},
},
{
{0.0, 0.000, 0.5, 1.000},
{0.5, 0.000, 0.5, 0.333},
{0.5, 0.333, 0.5, 0.333},
{0.5, 0.666, 0.5, 0.333},
},
{
{0.0, 0.00, 0.5, 1.00},
{0.5, 0.00, 0.5, 0.25},
{0.5, 0.25, 0.5, 0.25},
{0.5, 0.50, 0.5, 0.25},
{0.5, 0.75, 0.5, 0.25},
},
}
layout.set(layout_data)
l.config.set_hidden_edges(info.direction.all)
l.config.set_smart_hidden_edges(false)
l.config.set_resize_direction(info.direction.right)
l.config.set_layout_constraints({min_width = 0.1, max_width = 1, min_height = 0.1, max_height = 1})
l.config.set_master_constraints({min_width = 0.1, max_width = 1, min_height = 0.1, max_height = 1})
|
#!/usr/bin/env lua
-- MoonTypes example: fromfile.lua
local types = require("moontypes")
-- Create a group and add the types defined in the given file:
local group = types.group()
group:typedef_from_file("definitions.def")
-- Create an instance of mytype:
local x = group:new('mytype')
x:set("e2", 12, 34, 56)
x:print()
x:print("e2")
x:print("e2.a")
x:print("e2.b")
x:print("e2.c")
-- Copy field e2 to field e1
x:set("e1", x:get("e2"))
x:print()
x:print("e1")
|
local key = string.format("incr:%s:%s", KEYS[1], KEYS[2])
local publishName = string.format("incr_state_%s", KEYS[1])
redis.call('DEL', key)
redis.call("PUBLISH", publishName, KEYS[2] .. "##" .. ARGV[1])
|
require("@vue/runtime-dom")
local compile = function()
if __DEV__ then
-- [ts2lua]lua中0和空字符串也是true,此处__GLOBAL__需要确认
-- [ts2lua]lua中0和空字符串也是true,此处__ESM_BROWSER__需要确认
-- [ts2lua]lua中0和空字符串也是true,此处__ESM_BUNDLER__需要确认
warn( + (__ESM_BUNDLER__ and {} or {(__ESM_BROWSER__ and {} or {(__GLOBAL__ and {} or {})[1]})[1]})[1])
end
end
|
ll['nodeBuilders'] = {}
ll['activeSession'] = nil
function ll.logd(tag, ...)
print(tag, ...)
end
function ll.class(base)
local c = {}
if base then
-- shallow copy of base class members
if type(base) == 'table' then
for i, v in pairs(base) do
c[i] = v
end
end
end
c.__index = c
return c
end
function ll.registerNodeBuilder(name, builder)
ll.nodeBuilders[name] = builder
end
function ll.getNodeBuilder(name)
return ll.nodeBuilders[name]
end
function ll.getNodeBuilderDescriptors()
local sortedKeys = {}
for k in pairs(ll.nodeBuilders) do
table.insert(sortedKeys, k)
end
table.sort(sortedKeys, function(a, b) return a:lower() < b:lower() end)
local output = {}
for _, name in ipairs(sortedKeys) do
local builder = ll.nodeBuilders[name]
-- finds the summary string
local firstLineIndex = builder.doc:find('\n')
local summary = builder.doc:sub(1, firstLineIndex-1)
local desc = ll.NodeBuilderDescriptor.new(builder.type, name, summary)
table.insert(output, desc)
end
return output
end
function ll.castObject(obj)
castTable = {
[ll.ObjectType.Buffer] = ll.impl.castObjectToBuffer,
[ll.ObjectType.Image] = ll.impl.castObjectToImage,
[ll.ObjectType.ImageView] = ll.impl.castObjectToImageView
}
return castTable[obj.type](obj)
end
function ll.castNode(node)
castTable = {
[ll.NodeType.Compute] = ll.impl.castNodeToComputeNode,
[ll.NodeType.Container] = ll.impl.castNodeToContainerNode
}
return castTable[node.type](node)
end
function ll.isValidImage(img, expectedChannelCount, expectedChannelType)
local desc = img.imageDescriptor
if desc.channelType ~= expectedChannelType then
return "expecting channel type " .. expectedChannelType .. ' got: ' .. desc.channelType
end
if desc.channelCount ~= expectedChannelCount then
return "expecting channel count " .. expectedChannelCount .. ' got: ' .. desc.channelCount
end
return nil
end
-----------------------------------------------------------
-- Session
-----------------------------------------------------------
function ll.getHostMemory()
if not ll.activeSession then
error('ll.activeSession nil')
end
return ll.activeSession:getHostMemory()
end
function ll.getProgram(name)
if not ll.activeSession then
error('ll.activeSession nil')
end
return ll.activeSession:getProgram(name)
end
function ll.createComputeNode(name)
if not ll.activeSession then
error('ll.activeSession nil')
end
return ll.activeSession:createComputeNode(name)
end
function ll.createContainerNode(name)
if not ll.activeSession then
error('ll.activeSession nil')
end
return ll.activeSession:createContainerNode(name)
end
function ll.getGoodComputeLocalShape(dimensions)
if not ll.activeSession then
error('ll.activeSession nil')
end
return ll.activeSession:getGoodComputeLocalShape(dimensions)
end
-----------------------------------------------------------
-- ComputeNodeBuilder
-----------------------------------------------------------
ll.ComputeNodeBuilder = ll.class()
ll.ComputeNodeBuilder.type = ll.NodeType.Compute
ll.ComputeNodeBuilder.doc = ""
function ll.ComputeNodeBuilder.newDescriptor()
error('newDescriptor must be implemented by child classes')
end
function ll.ComputeNodeBuilder.onNodeInit(node)
-- do nothing
end
-----------------------------------------------------------
-- ContainerNodeBuilder
-----------------------------------------------------------
ll.ContainerNodeBuilder = ll.class()
ll.ContainerNodeBuilder.type = ll.NodeType.Container
ll.ContainerNodeBuilder.doc = ""
function ll.ContainerNodeBuilder.newDescriptor()
error('newDescriptor must be implemented by child classes')
end
function ll.ContainerNodeBuilder.onNodeInit(node)
-- do nothing
end
function ll.ContainerNodeBuilder.onNodeRecord(node, cmdBuffer)
-- do nothing
end
-----------------------------------------------------------
-- Parameter
-----------------------------------------------------------
function ll.Parameter:get()
-- castTable = {
-- [ll.ParameterType.Int] = self:__getInt(),
-- [ll.ParameterType.Float] = self:__getFloat()
-- }
-- return castTable[self.type]()
if self.type == ll.ParameterType.Int then
return self:__getInt()
end
if self.type == ll.ParameterType.Float then
return self:__getFloat()
end
if self.type == ll.ParameterType.Bool then
return self:__getBool()
end
end
function ll.Parameter:set(value)
if type(value) == 'number' then
self:__setFloat(value)
end
if type(value) == 'boolean' then
self:__setBool(value)
end
-- castTable = {
-- ['number'] = self:__setFloat
-- }
-- castTable[type(value)](value)
end
-----------------------------------------------------------
-- ComputeNodeDescriptor
-----------------------------------------------------------
--- Initialize the descriptor.
--
-- The initialization includes:
-- - Setting the descriptor buildderName to name
-- - Looking for the program with the same name in the registry.
-- - Setting program functionName to main.
-- - Setting the gridShape to (1, 1, 1)
-- - Setting the localShape to
--
-- @param name The name of the descriptor. It is also used
-- for looking for the program in the registry.
function ll.ComputeNodeDescriptor:init(name, dimensions)
self.builderName = name
self.program = ll.getProgram(name)
self.functionName = 'main'
self.localShape = ll.getGoodComputeLocalShape(dimensions)
self.gridShape = ll.vec3ui.new(1, 1, 1)
end
function ll.ComputeNodeDescriptor:setParameter(name, value)
-- this workaround is needed in order to call
-- the correct setter method given Lua type for value
local param = ll.Parameter.new()
param:set(value)
self:__setParameter(name, param)
end
function ll.ComputeNodeDescriptor:getParameter(name)
local param = self:__getParameter(name)
return param:get()
end
-----------------------------------------------------------
-- ComputeNode
-----------------------------------------------------------
function ll.ComputeNode:getPort(name)
return ll.castObject(self:__getPort(name))
end
function ll.ComputeNode:bind(name, obj)
castTable = {
[ll.ObjectType.Buffer] = ll.impl.castBufferToObject,
[ll.ObjectType.Image] = ll.impl.castImageToObject,
[ll.ObjectType.ImageView] = ll.impl.castImageViewToObject
}
self:__bind(name, castTable[obj.type](obj))
end
function ll.ComputeNode:setParameter(name, value)
-- this workaround is needed in order to call
-- the correct setter method given Lua type for value
local param = ll.Parameter.new()
param:set(value)
self:__setParameter(name, param)
end
function ll.ComputeNode:getParameter(name)
local param = self:__getParameter(name)
return param:get()
end
-----------------------------------------------------------
-- ContainerNodeDescriptor
-----------------------------------------------------------
function ll.ContainerNodeDescriptor:setParameter(name, value)
-- this workaround is needed in order to call
-- the correct setter method given Lua type for value
local param = ll.Parameter.new()
param:set(value)
self:__setParameter(name, param)
end
function ll.ContainerNodeDescriptor:getParameter(name)
local param = self:__getParameter(name)
return param:get()
end
-----------------------------------------------------------
-- ContainerNode
-----------------------------------------------------------
function ll.ContainerNode:getPort(name)
return ll.castObject(self:__getPort(name))
end
function ll.ContainerNode:bind(name, obj)
castTable = {
[ll.ObjectType.Buffer] = ll.impl.castBufferToObject,
[ll.ObjectType.Image] = ll.impl.castImageToObject,
[ll.ObjectType.ImageView] = ll.impl.castImageViewToObject
}
self:__bind(name, castTable[obj.type](obj))
end
function ll.ContainerNode:getNode(name)
local node = self:__getNode(name)
if not node then
error(string.format('node with name %s not found', name))
end
return ll.castNode(node)
end
function ll.ContainerNode:bindNode(name, node)
castTable = {
[ll.NodeType.Compute] = ll.impl.castComputeNodeToNode,
[ll.NodeType.Container] = ll.impl.castContainerNodeToNode
}
self:__bindNode(name, castTable[node.type](node))
end
function ll.ContainerNode:setParameter(name, value)
-- this workaround is needed in order to call
-- the correct setter method given Lua type for value
local param = ll.Parameter.new()
param:set(value)
self:__setParameter(name, param)
end
function ll.ContainerNode:getParameter(name)
local param = self:__getParameter(name)
return param:get()
end
|
-----------------------------------
--
-- Zone: Valkurm_Dunes (103)
--
-----------------------------------
local ID = require("scripts/zones/Valkurm_Dunes/IDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/chocobo_digging");
require("scripts/globals/conquest");
require("scripts/globals/missions");
require("scripts/globals/weather");
require("scripts/globals/status");
-----------------------------------
function onChocoboDig(player, precheck)
return tpz.chocoboDig.start(player, precheck)
end;
function onInitialize(zone)
tpz.conq.setRegionalConquestOverseers(zone:getRegionID())
end;
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 60.989, -4.898, -151.001, 198);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 3;
elseif (player:getCurrentMission(WINDURST) == tpz.mission.id.windurst.VAIN and player:getCharVar("MissionStatus") ==1) then
cs = 5;
end
return cs;
end;
function onConquestUpdate(zone, updatetype)
tpz.conq.onConquestUpdate(zone, updatetype)
end;
function onRegionEnter( player, region)
end;
function onEventUpdate( player, csid, option)
if (csid == 3) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
elseif (csid == 5) then
if (player:getZPos() > 45) then
if (player:getZPos() > -301) then
player:updateEvent(0,0,0,0,0,1);
else
player:updateEvent(0,0,0,0,0,3);
end
end
end
end;
function onEventFinish( player, csid, option)
if (csid == 3) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end;
function onZoneWeatherChange(weather)
local qm1 = GetNPCByID(ID.npc.SUNSAND_QM); -- Quest: An Empty Vessel
if (weather == tpz.weather.DUST_STORM) then
qm1:setStatus(tpz.status.NORMAL);
else
qm1:setStatus(tpz.status.DISAPPEAR);
end
end;
|
local nvim_lsp = require('lspconfig')
-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local on_attach = function(client, bufnr)
local function buf_set_keymap(...) vim.api.nvim_buf_set_keymap(bufnr, ...) end
local function buf_set_option(...) vim.api.nvim_buf_set_option(bufnr, ...) end
--Enable completion triggered by <c-x><c-o>
buf_set_option('omnifunc', 'v:lua.vim.lsp.omnifunc')
-- Mappings.
local opts = { noremap=true, silent=true }
-- See `:help vim.lsp.*` for documentation on any of the below functions
buf_set_keymap('n', 'gD', '<cmd>lua vim.lsp.buf.declaration()<CR>', opts)
buf_set_keymap('n', 'gd', '<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'gv', '<C-W>v<cmd>lua vim.lsp.buf.definition()<CR>', opts)
-- I never use split anyways
buf_set_keymap('n', 'gs', '<C-W>v<cmd>lua vim.lsp.buf.definition()<CR>', opts)
buf_set_keymap('n', 'K', '<cmd>lua vim.lsp.buf.hover()<CR>', opts)
buf_set_keymap('n', 'gi', '<cmd>lua vim.lsp.buf.implementation()<CR>', opts)
buf_set_keymap('n', '<C-k>', '<cmd>lua vim.lsp.buf.signature_help()<CR>', opts)
buf_set_keymap('n', '<space>wa', '<cmd>lua vim.lsp.buf.add_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wr', '<cmd>lua vim.lsp.buf.remove_workspace_folder()<CR>', opts)
buf_set_keymap('n', '<space>wl', '<cmd>lua print(vim.inspect(vim.lsp.buf.list_workspace_folders()))<CR>', opts)
buf_set_keymap('n', '<space>D', '<cmd>lua vim.lsp.buf.type_definition()<CR>', opts)
buf_set_keymap('n', '<space>rn', '<cmd>lua vim.lsp.buf.rename()<CR>', opts)
buf_set_keymap('n', '<space>ca', '<cmd>lua vim.lsp.buf.code_action()<CR>', opts)
buf_set_keymap('n', 'gr', '<cmd>lua vim.lsp.buf.references()<CR>', opts)
buf_set_keymap('n', '<space>e', '<cmd>lua vim.lsp.diagnostic.show_line_diagnostics()<CR>', opts)
buf_set_keymap('n', '[d', '<cmd>lua vim.lsp.diagnostic.goto_prev()<CR>', opts)
buf_set_keymap('n', ']d', '<cmd>lua vim.lsp.diagnostic.goto_next()<CR>', opts)
buf_set_keymap('n', '<space>q', '<cmd>lua vim.lsp.diagnostic.set_loclist()<CR>', opts)
buf_set_keymap('n', '<space>f', '<cmd>lua vim.lsp.buf.formatting()<CR>', opts)
end
nvim_lsp.gopls.setup{
on_attach=on_attach,
cmd = {"gopls", "serve"},
settings = {
gopls = {
analyses = {
unusedparams = true,
},
staticcheck = true,
},
},
}
nvim_lsp.intelephense.setup{ on_attach=on_attach }
nvim_lsp.solargraph.setup{
on_attach=on_attach,
settings = {
solargraph = {
diagnostics = false,
},
},
}
nvim_lsp.vuels.setup{ on_attach=on_attach }
nvim_lsp.tailwindcss.setup{ on_attach=on_attach }
nvim_lsp.tsserver.setup{ on_attach=on_attach }
-- nvim_lsp.sorbet.setup{}
|
local comm = require "comm"
local ldap = require "ldap"
local nmap = require "nmap"
local shortport = require "shortport"
local stdnse = require "stdnse"
local string = require "string"
local table = require "table"
description = [[
Attempts to perform an LDAP search and returns all matches.
If no username and password is supplied to the script the Nmap registry
is consulted. If the <code>ldap-brute</code> script has been selected
and it found a valid account, this account will be used. If not
anonymous bind will be used as a last attempt.
]]
---
-- @args ldap.username If set, the script will attempt to perform an LDAP bind using the username and password
-- @args ldap.password If set, used together with the username to authenticate to the LDAP server
-- @args ldap.qfilter If set, specifies a quick filter. The library does not support parsing real LDAP filters.
-- The following values are valid for the filter parameter: computer, users, ad_dcs, custom or all. If no value is specified it defaults to all.
-- @args ldap.searchattrib When used with the 'custom' qfilter, this parameter works in conjunction with ldap.searchvalue to allow the user to specify a custom attribute and value as search criteria.
-- @args ldap.searchvalue When used with the 'custom' qfilter, this parameter works in conjunction with ldap.searchattrib to allow the user to specify a custom attribute and value as search criteria.
-- This parameter DOES PERMIT the use of the asterisk '*' as a wildcard.
-- @args ldap.base If set, the script will use it as a base for the search. By default the defaultNamingContext is retrieved and used.
-- If no defaultNamingContext is available the script iterates over the available namingContexts
-- @args ldap.attrib If set, the search will include only the attributes specified. For a single attribute a string value can be used, if
-- multiple attributes need to be supplied a table should be used instead.
-- @args ldap.maxobjects If set, overrides the number of objects returned by the script (default 20).
-- The value -1 removes the limit completely.
-- @args ldap.savesearch If set, the script will save the output to a file beginning with the specified path and name. The file suffix
-- of .CSV as well as the hostname and port will automatically be added based on the output type selected.
--
-- @usage
-- nmap -p 389 --script ldap-search --script-args 'ldap.username="cn=ldaptest,cn=users,dc=cqure,dc=net",ldap.password=ldaptest,
-- ldap.qfilter=users,ldap.attrib=sAMAccountName' <host>
--
-- nmap -p 389 --script ldap-search --script-args 'ldap.username="cn=ldaptest,cn=users,dc=cqure,dc=net",ldap.password=ldaptest,
-- ldap.qfilter=custom,ldap.searchattrib="operatingSystem",ldap.searchvalue="Windows *Server*",ldap.attrib={operatingSystem,whencreated,OperatingSystemServicePack}' <host>
--
-- @output
-- PORT STATE SERVICE REASON
-- 389/tcp open ldap syn-ack
-- | ldap-search:
-- | DC=cqure,DC=net
-- | dn: CN=Administrator,CN=Users,DC=cqure,DC=net
-- | sAMAccountName: Administrator
-- | dn: CN=Guest,CN=Users,DC=cqure,DC=net
-- | sAMAccountName: Guest
-- | dn: CN=SUPPORT_388945a0,CN=Users,DC=cqure,DC=net
-- | sAMAccountName: SUPPORT_388945a0
-- | dn: CN=EDUSRV011,OU=Domain Controllers,DC=cqure,DC=net
-- | sAMAccountName: EDUSRV011$
-- | dn: CN=krbtgt,CN=Users,DC=cqure,DC=net
-- | sAMAccountName: krbtgt
-- | dn: CN=Patrik Karlsson,CN=Users,DC=cqure,DC=net
-- | sAMAccountName: patrik
-- | dn: CN=VMABUSEXP008,CN=Computers,DC=cqure,DC=net
-- | sAMAccountName: VMABUSEXP008$
-- | dn: CN=ldaptest,CN=Users,DC=cqure,DC=net
-- |_ sAMAccountName: ldaptest
--
--
-- PORT STATE SERVICE REASON
-- 389/tcp open ldap syn-ack
-- | ldap-search:
-- | Context: DC=cqure,DC=net; QFilter: custom; Attributes: operatingSystem,whencreated,OperatingSystemServicePack
-- | dn: CN=USDC01,OU=Domain Controllers,DC=cqure,DC=net
-- | whenCreated: 2010/08/27 17:30:16 UTC
-- | operatingSystem: Windows Server 2008 R2 Datacenter
-- | operatingSystemServicePack: Service Pack 1
-- | dn: CN=TESTBOX,OU=Test Servers,DC=cqure,DC=net
-- | whenCreated: 2010/09/04 00:33:02 UTC
-- | operatingSystem: Windows Server 2008 R2 Standard
-- |_ operatingSystemServicePack: Service Pack 1
-- Credit
-- ------
-- o Martin Swende who provided me with the initial code that got me started writing this.
-- Version 0.8
-- Created 01/12/2010 - v0.1 - created by Patrik Karlsson <patrik@cqure.net>
-- Revised 01/20/2010 - v0.2 - added SSL support
-- Revised 01/26/2010 - v0.3 - Changed SSL support to comm.tryssl, prefixed arguments with ldap, changes in determination of namingContexts
-- Revised 02/17/2010 - v0.4 - Added dependency to ldap-brute and the abilitity to check for ldap accounts (credentials) stored in nmap registry
-- Capped output to 20 entries, use ldap.maxObjects to override
-- Revised 07/16/2010 - v0.5 - Fixed bug with empty contexts, added objectClass person to qfilter users, add error msg for invalid credentials
-- Revised 09/05/2011 - v0.6 - Added support for saving searches to a file via argument ldap.savesearch
-- Revised 10/29/2011 - v0.7 - Added support for custom searches and the ability to leverage LDAP substring search functionality added to LDAP.lua
-- Revised 10/30/2011 - v0.8 - Added support for ad_dcs (AD domain controller ) searches and the ability to leverage LDAP extensibleMatch filter added to LDAP.lua
author = "Patrik Karlsson"
license = "Same as Nmap--See http://nmap.org/book/man-legal.html"
categories = {"discovery", "safe"}
dependencies = {"ldap-brute"}
portrule = shortport.port_or_service({389,636}, {"ldap","ldapssl"})
function action(host,port)
local status
local socket, opt
local args = nmap.registry.args
local username = stdnse.get_script_args('ldap.username')
local password = stdnse.get_script_args('ldap.password')
local qfilter = stdnse.get_script_args('ldap.qfilter')
local searchAttrib = stdnse.get_script_args('ldap.searchattrib')
local searchValue = stdnse.get_script_args('ldap.searchvalue')
local base = stdnse.get_script_args('ldap.base')
local attribs = stdnse.get_script_args('ldap.attrib')
local saveFile = stdnse.get_script_args('ldap.savesearch')
local accounts
local objCount = 0
local maxObjects = tonumber(stdnse.get_script_args('ldap.maxobjects')) or 20
-- In order to discover what protocol to use (SSL/TCP) we need to send a few bytes to the server
-- An anonymous bind should do it
local ldap_anonymous_bind = "\x30\x0c\x02\x01\x01\x60\x07\x02\x01\x03\x04\x00\x80\x00"
local _
socket, _, opt = comm.tryssl( host, port, ldap_anonymous_bind, nil )
if not socket then
return
end
-- Check if ldap-brute stored us some credentials
if ( not(username) and nmap.registry.ldapaccounts~=nil ) then
accounts = nmap.registry.ldapaccounts
end
-- We close and re-open the socket so that the anonymous bind does not distract us
socket:close()
status = socket:connect(host, port, opt)
socket:set_timeout(10000)
local req
local searchResEntries
local contexts = {}
local result = {}
local filter
if base == nil then
req = { baseObject = "", scope = ldap.SCOPE.base, derefPolicy = ldap.DEREFPOLICY.default, attributes = { "defaultNamingContext", "namingContexts" } }
status, searchResEntries = ldap.searchRequest( socket, req )
if not status then
socket:close()
return
end
contexts = ldap.extractAttribute( searchResEntries, "defaultNamingContext" )
-- OpenLDAP does not have a defaultNamingContext
if not contexts then
contexts = ldap.extractAttribute( searchResEntries, "namingContexts" )
end
else
table.insert(contexts, base)
end
if ( not(contexts) or #contexts == 0 ) then
stdnse.debug1( "Failed to retrieve namingContexts" )
contexts = {""}
end
-- perform a bind only if we have valid credentials
if ( username ) then
local bindParam = { version=3, ['username']=username, ['password']=password}
local status, errmsg = ldap.bindRequest( socket, bindParam )
if not status then
stdnse.debug1("ldap-search failed to bind: %s", errmsg)
return " \n ERROR: Authentication failed"
end
-- or if ldap-brute found us something
elseif ( accounts ) then
for username, password in pairs(accounts) do
local bindParam = { version=3, ['username']=username, ['password']=password}
local status, errmsg = ldap.bindRequest( socket, bindParam )
if status then
break
end
end
end
if qfilter == "users" then
filter = { op=ldap.FILTER._or, val=
{
{ op=ldap.FILTER.equalityMatch, obj='objectClass', val='user' },
{ op=ldap.FILTER.equalityMatch, obj='objectClass', val='posixAccount' },
{ op=ldap.FILTER.equalityMatch, obj='objectClass', val='person' }
}
}
elseif qfilter == "computers" or qfilter == "computer" then
filter = { op=ldap.FILTER.equalityMatch, obj='objectClass', val='computer' }
elseif qfilter == "ad_dcs" then
filter = { op=ldap.FILTER.extensibleMatch, obj='userAccountControl', val='1.2.840.113556.1.4.803:=8192' }
elseif qfilter == "custom" then
if searchAttrib == nil or searchValue == nil then
return "\n\nERROR: Please specify both ldap.searchAttrib and ldap.searchValue using using the custom qfilter."
end
if string.find(searchValue, '*') == nil then
filter = { op=ldap.FILTER.equalityMatch, obj=searchAttrib, val=searchValue }
else
filter = { op=ldap.FILTER.substrings, obj=searchAttrib, val=searchValue }
end
elseif qfilter == "all" or qfilter == nil then
filter = nil -- { op=ldap.FILTER}
else
return " \n\nERROR: Unsupported Quick Filter: " .. qfilter
end
if type(attribs) == 'string' then
local tmp = attribs
attribs = {}
table.insert(attribs, tmp)
end
for _, context in ipairs(contexts) do
req = {
baseObject = context,
scope = ldap.SCOPE.sub,
derefPolicy = ldap.DEREFPOLICY.default,
filter = filter,
attributes = attribs,
['maxObjects'] = maxObjects }
status, searchResEntries = ldap.searchRequest( socket, req )
if not status then
if ( searchResEntries:match("DSID[-]0C090627") and not(username) ) then
return "ERROR: Failed to bind as the anonymous user"
else
stdnse.debug1("ldap.searchRequest returned: %s", searchResEntries)
return
end
end
local result_part = ldap.searchResultToTable( searchResEntries )
if saveFile then
local output_file = saveFile .. "_" .. host.ip .. "_" .. port.number .. ".csv"
local save_status, save_err = ldap.searchResultToFile(searchResEntries,output_file)
if not save_status then
stdnse.debug1("%s", save_err)
end
end
objCount = objCount + (result_part and #result_part or 0)
result_part.name = ""
if ( context ) then
result_part.name = ("Context: %s"):format(#context > 0 and context or "<empty>")
end
if ( qfilter ) then
result_part.name = result_part.name .. ("; QFilter: %s"):format(qfilter)
end
if ( attribs ) then
result_part.name = result_part.name .. ("; Attributes: %s"):format(stdnse.strjoin(",", attribs))
end
table.insert( result, result_part )
-- catch any softerrors
if searchResEntries.resultCode ~= 0 then
local output = stdnse.format_output(true, result )
output = output .. string.format("\n\n\n=========== %s ===========", searchResEntries.errorMessage )
return output
end
end
-- perform a unbind only if we have valid credentials
if ( username ) then
status = ldap.unbindRequest( socket )
end
socket:close()
-- if taken a way and ldap returns a single result, it ain't shown....
--result.name = "LDAP Results"
local output = stdnse.format_output(true, result )
if ( maxObjects ~= -1 and objCount == maxObjects ) then
output = output .. ("\n\nResult limited to %d objects (see ldap.maxobjects)"):format(maxObjects)
end
return output
end
|
local M = {}
M.config = function()
-- Autocommands
if lvim.builtin.nonumber_unfocus then
vim.cmd [[
" don't show line number in unfocued window
augroup WindFocus
autocmd!
autocmd WinEnter * set relativenumber number cursorline
autocmd WinLeave * set norelativenumber nonumber nocursorline
augroup END
]]
end
vim.cmd [[
" disable syntax highlighting in big files
function! DisableSyntaxTreesitter()
echo("Big file, disabling syntax, treesitter and folding")
if exists(':TSBufDisable')
exec 'TSBufDisable autotag'
exec 'TSBufDisable highlight'
endif
set foldmethod=manual
syntax clear
syntax off
filetype off
set noundofile
set noswapfile
set noloadplugins
set lazyredraw
endfunction
augroup BigFileDisable
autocmd!
autocmd BufReadPre,FileReadPre * if getfsize(expand("%")) > 1024 * 1024 | exec DisableSyntaxTreesitter() | endif
augroup END
]]
if lvim.builtin.sql_integration.active then
-- Add vim-dadbod-completion in sql files
vim.cmd [[
augroup DadbodSql
au!
autocmd FileType sql,mysql,plsql lua require('cmp').setup.buffer { sources = { { name = 'vim-dadbod-completion' } } }
augroup END
]]
end
local codelens_viewer = "lua require('nvim-lightbulb').update_lightbulb()"
local user = os.getenv "USER"
if user and user == "abz" then
codelens_viewer = "lua require('user.codelens').show_line_sign()"
end
lvim.autocommands.custom_groups = {
{ "CursorHold", "*.rs,*.go,*.ts,*.tsx", codelens_viewer },
-- toggleterm
{ "TermOpen", "term://*", "lua require('user.keybindings').set_terminal_keymaps()" },
-- dashboard
{ "FileType", "alpha", "nnoremap <silent> <buffer> q :q<CR>" },
-- c, cpp
{ "Filetype", "c,cpp", "nnoremap <leader>H <Cmd>ClangdSwitchSourceHeader<CR>" },
-- go
{
"Filetype",
"go",
"nnoremap <leader>H <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='go vet .;read',count=2,direction='float'})<CR>",
},
-- java
{
"Filetype",
"java",
"nnoremap <leader>r <cmd>lua require('toggleterm.terminal').Terminal:new {cmd='mvn package;read', hidden =false}:toggle()<CR>",
},
{
"Filetype",
"java",
"nnoremap <leader>m <cmd>lua require('toggleterm.terminal').Terminal:new {cmd='mvn compile;read', hidden =false}:toggle()<CR>",
},
{
"Filetype",
"scala,sbt,java",
"lua require('user.metals').config()",
},
-- rust
{
"Filetype",
"rust",
"nnoremap <leader>H <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='cargo clippy;read',count=2,direction='float'})<CR>",
},
{ "Filetype", "rust", "nnoremap <leader>lm <Cmd>RustExpandMacro<CR>" },
{ "Filetype", "rust", "nnoremap <leader>lH <Cmd>RustToggleInlayHints<CR>" },
{ "Filetype", "rust", "nnoremap <leader>le <Cmd>RustRunnables<CR>" },
{ "Filetype", "rust", "nnoremap <leader>lh <Cmd>RustHoverActions<CR>" },
{ "Filetype", "rust", "nnoremap <leader>lc <Cmd>RustOpenCargo<CR>" },
-- typescript
{ "Filetype", "typescript,typescriptreact", "nnoremap <leader>lA <Cmd>TSLspImportAll<CR>" },
{ "Filetype", "typescript,typescriptreact", "nnoremap <leader>lR <Cmd>TSLspRenameFile<CR>" },
{ "Filetype", "typescript,typescriptreact", "nnoremap <leader>lO <Cmd>TSLspOrganize<CR>" },
-- uncomment the following if you want to show diagnostics on hover
-- { "CursorHold", "*", "lua vim.lsp.diagnostic.show_line_diagnostics({ show_header = false, border = 'single' })" },
}
end
M.make_run = function()
return {
-- c, cpp
{
"Filetype",
"c,cpp",
"nnoremap <leader>m <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='make ;read',count=2,direction='float'})<CR>",
},
{
"Filetype",
"c,cpp",
"nnoremap <leader>r <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='make run;read',count=3,direction='float'})<CR>",
},
-- go
{
"Filetype",
"go",
"nnoremap <leader>m <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='go build -v .;read',count=2,direction='float'})<CR>",
},
{
"Filetype",
"go",
"nnoremap <leader>r <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='go run .;read',count=3,direction='float'})<CR>",
},
-- python
{
"Filetype",
"python",
"nnoremap <leader>r <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='python "
.. vim.fn.expand "%"
.. ";read',count=2,direction='float'})<CR>",
},
{
"Filetype",
"python",
"nnoremap <leader>m <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='echo \"compile :pepelaugh:\";read',count=2,direction='float'})<CR>",
},
-- rust
{
"Filetype",
"rust",
"nnoremap <leader>m <cmd>lua require('lvim.core.terminal')._exec_toggle({cmd='cargo build;read',count=2,direction='float'})<CR>",
},
{
"Filetype",
"rust",
"nnoremap <leader>r <cmd>lua require('rust-tools.runnables').runnables()<CR>",
},
-- toml
{ "FileType", "toml", "lua require('cmp').setup.buffer { sources = { { name = 'crates' } } }" },
}
end
return M
|
local _M = {}
_M.LOCAL_IP = "127.0.0.1"
_M.LOCAL_HOST = "localhost"
_M.BALANCER_CHASH = "chash"
_M.BALANCER_ROUNDROBIN = "roundrobin"
return _M
|
local meta = FindMetaTable( "Vector" )
--[[---------------------------------------------------------
Vector unary operator
- Allows -Vector( 1, 2, 3 )
-----------------------------------------------------------]]
function meta:__unm()
return -1 * self
end |
function GetTraitors()
local trs = {}
for k, v in ipairs(player.GetAll()) do
if v:GetTraitor() or v:GetHypnotist() then table.insert(trs, v) end
end
return trs
end
function CountTraitors() return #GetTraitors() end
-- Role state communication
-- Send every player their role
local function SendPlayerRoles()
for k, v in pairs(player.GetAll()) do
net.Start("TTT_Role")
net.WriteUInt(v:GetRole(), 4)
net.Send(v)
end
end
local function SendRoleListMessage(role, role_ids, ply_or_rf)
net.Start("TTT_RoleList")
net.WriteUInt(role, 4)
-- list contents
local num_ids = #role_ids
net.WriteUInt(num_ids, 8)
for i = 1, num_ids do
net.WriteUInt(role_ids[i] - 1, 7)
end
if ply_or_rf then net.Send(ply_or_rf)
else net.Broadcast()
end
end
local function SendRoleList(role, ply_or_rf, pred)
local role_ids = {}
for k, v in pairs(player.GetAll()) do
if v:IsRole(role) then
if not pred or (pred and pred(v)) then
table.insert(role_ids, v:EntIndex())
end
end
end
SendRoleListMessage(role, role_ids, ply_or_rf)
end
-- Tell traitors about other traitors
function SendTraitorList(ply_or_rf) SendRoleList(ROLE_TRAITOR, ply_or_rf) end
function SendDetectiveList(ply_or_rf) SendRoleList(ROLE_DETECTIVE, ply_or_rf) end
function SendMercenaryList(ply_or_rf) SendRoleList(ROLE_MERCENARY, ply_or_rf) end
function SendDoctorList(ply_or_rf) SendRoleList(ROLE_DOCTOR, ply_or_rf) end
function SendHypnotistList(ply_or_rf) SendRoleList(ROLE_HYPNOTIST, ply_or_rf) end
function SendGlitchList(ply_or_rf) SendRoleList(ROLE_GLITCH, ply_or_rf) end
function SendJesterList(ply_or_rf) SendRoleList(ROLE_JESTER, ply_or_rf) end
function SendPhantomList(ply_or_rf) SendRoleList(ROLE_PHANTOM, ply_or_rf) end
function SendZombieList(ply_or_rf) SendRoleList(ROLE_ZOMBIE, ply_or_rf) end
function SendVampireList(ply_or_rf) SendRoleList(ROLE_VAMPIRE, ply_or_rf) end
function SendSwapperList(ply_or_rf) SendRoleList(ROLE_SWAPPER, ply_or_rf) end
function SendAssassinList(ply_or_rf) SendRoleList(ROLE_ASSASSIN, ply_or_rf) end
function SendKillerList(ply_or_rf) SendRoleList(ROLE_KILLER, ply_or_rf) end
function SendDetraitorList(ply_or_rf) SendRoleList(ROLE_DETRAITOR, ply_or_rf) end
function SendInnocentList(ply_or_rf) SendRoleList(ROLE_INNOCENT, ply_or_rf) end
function SendConfirmedTraitors(ply_or_rf)
SendTraitorList(ply_or_rf, function(p) return p:GetNWBool("body_searched") end)
end
function SendFullStateUpdate()
SendPlayerRoles()
SendInnocentList()
SendTraitorList()
SendDetectiveList()
SendMercenaryList()
SendDoctorList()
SendHypnotistList()
SendGlitchList()
SendJesterList()
SendPhantomList()
SendZombieList()
SendVampireList()
SendSwapperList()
SendAssassinList()
SendKillerList()
-- not useful to sync confirmed traitors here
end
function SendRoleReset(ply_or_rf)
local plys = player.GetAll()
net.Start("TTT_RoleList")
net.WriteUInt(ROLE_INNOCENT, 4)
net.WriteUInt(#plys, 8)
for k, v in pairs(plys) do
net.WriteUInt(v:EntIndex() - 1, 7)
end
if ply_or_rf then net.Send(ply_or_rf)
else net.Broadcast()
end
end
-- Console commands
local function request_rolelist(ply)
-- Client requested a state update. Note that the client can only use this
-- information after entities have been initialised (e.g. in InitPostEntity).
if GetRoundState() ~= ROUND_WAIT then
SendRoleReset(ply)
SendDetectiveList(ply)
SendMercenaryList(ply)
SendDoctorList(ply)
SendHypnotistList(ply)
SendGlitchList(ply)
SendJesterList(ply)
SendPhantomList(ply)
SendZombieList(ply)
SendVampireList(ply)
SendSwapperList(ply)
SendAssassinList(ply)
SendKillerList(ply)
if ply:IsTraitor() then
SendTraitorList(ply)
else
SendConfirmedTraitors(ply)
end
end
end
concommand.Add("_ttt_request_rolelist", request_rolelist)
local function force_terror(ply)
ply:SetRole(ROLE_INNOCENT)
ply:UnSpectate()
ply:SetTeam(TEAM_TERROR)
ply:StripAll()
ply:Spawn()
ply:PrintMessage(HUD_PRINTTALK, "You are now on the terrorist team.")
SendFullStateUpdate()
end
concommand.Add("ttt_force_terror", force_terror, nil, nil, FCVAR_CHEAT)
local function force_innocent(ply)
ply:SetRole(ROLE_INNOCENT)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_innocent", force_innocent, nil, nil, FCVAR_CHEAT)
local function force_traitor(ply)
ply:SetRole(ROLE_TRAITOR)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_traitor", force_traitor, nil, nil, FCVAR_CHEAT)
local function force_detective(ply)
ply:SetRole(ROLE_DETECTIVE)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_detective", force_detective, nil, nil, FCVAR_CHEAT)
local function force_mercenary(ply)
ply:SetRole(ROLE_MERCENARY)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_mercenary", force_mercenary, nil, nil, FCVAR_CHEAT)
local function force_doctor(ply)
ply:SetRole(ROLE_DOCTOR)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
ply:Give("weapon_doc_defib")
SendFullStateUpdate()
end
concommand.Add("ttt_force_doctor", force_doctor, nil, nil, FCVAR_CHEAT)
local function force_hypnotist(ply)
ply:SetRole(ROLE_HYPNOTIST)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
ply:Give("weapon_hyp_brainwash")
SendFullStateUpdate()
end
concommand.Add("ttt_force_hypnotist", force_hypnotist, nil, nil, FCVAR_CHEAT)
local function force_glitch(ply)
ply:SetRole(ROLE_GLITCH)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_glitch", force_glitch, nil, nil, FCVAR_CHEAT)
local function force_jester(ply)
ply:SetRole(ROLE_JESTER)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_jester", force_jester, nil, nil, FCVAR_CHEAT)
local function force_phantom(ply)
ply:SetRole(ROLE_PHANTOM)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_phantom", force_phantom, nil, nil, FCVAR_CHEAT)
local function force_zombie(ply)
ply:SetRole(ROLE_ZOMBIE)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_zombie", force_zombie, nil, nil, FCVAR_CHEAT)
local function force_vampire(ply)
ply:SetRole(ROLE_VAMPIRE)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_vampire", force_vampire, nil, nil, FCVAR_CHEAT)
local function force_swapper(ply)
ply:SetRole(ROLE_SWAPPER)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
ply:Give("weapon_vam_fangs")
SendFullStateUpdate()
end
concommand.Add("ttt_force_swapper", force_swapper, nil, nil, FCVAR_CHEAT)
local function force_assassin(ply)
ply:SetRole(ROLE_ASSASSIN)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_assassin", force_assassin, nil, nil, FCVAR_CHEAT)
local function force_killer(ply)
ply:SetRole(ROLE_KILLER)
ply:SetMaxHealth(150)
ply:SetHealth(150)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_killer", force_killer, nil, nil, FCVAR_CHEAT)
local function force_spectate(ply, cmd, arg)
if IsValid(ply) then
if #arg == 1 and tonumber(arg[1]) == 0 then
ply:SetForceSpec(false)
else
if not ply:IsSpec() then
ply:Kill()
end
GAMEMODE:PlayerSpawnAsSpectator(ply)
ply:SetTeam(TEAM_SPEC)
ply:SetForceSpec(true)
ply:Spawn()
ply:SetRagdollSpec(false) -- dying will enable this, we don't want it here
end
end
end
local function force_detraitor(ply)
ply:SetRole(ROLE_DETRAITOR)
ply:SetMaxHealth(100)
ply:SetHealth(100)
if ply:HasWeapon("weapon_hyp_brainwash") then
ply:StripWeapon("weapon_hyp_brainwash")
end
if ply:HasWeapon("weapon_doc_defib") then
ply:StripWeapon("weapon_doc_defib")
end
if ply:HasWeapon("weapon_vam_fangs") then
ply:StripWeapon("weapon_vam_fangs")
end
SendFullStateUpdate()
end
concommand.Add("ttt_force_detraitor", force_detraitor, nil, nil, FCVAR_CHEAT)
concommand.Add("ttt_spectate", force_spectate)
net.Receive("TTT_Spectate", function(l, pl)
force_spectate(pl, nil, { net.ReadBool() and 1 or 0 })
end)
|
ardour {
["type"] = "EditorAction",
name = "Align Regions Across Tracks",
license = "MIT",
author = "David Healey",
description = [[Aligns the selected regions across tracks]]
}
function factory ()
return function ()
local sr = Session:nominal_sample_rate()
local sel = Editor:get_selection ()
local rl = sel.regions:regionlist()
local last_r
local last_pos
local last_length
-- FUNCTIONS --
-- check if the region is in the selected regions table
function is_selected(r, selected)
local result = false
for s in selected:iter() do
if (s == r) then
result = true
break
end
end
return result
end
-- sort regions by position
function sortByPosition(a, b)
return a:position() < b:position()
end
-- MAIN --
local add_undo = false -- keep track of changes
Session:begin_reversible_command ("Align Regions")
-- sort regions on each track
local sorted = {}
local playlists = {}
for key, r in pairs(rl:table ()) do
local playlist = r:playlist ()
if sorted[playlist:name ()] == nil then
sorted[playlist: name()] = {}
table.insert(playlists, playlist)
end
table.insert(sorted[playlist:name ()], r)
end
for i = 1, #playlists, 1 do
table.sort(sorted[playlists[i]:name ()], sortByPosition)
end
-- got through each playlist and arrange regions based on position of first playlist
local master = sorted[playlists[1]:name ()] -- first playlist's regions
for i = 2, #playlists, 1 do
regions = sorted[playlists[i]:name ()]
for j = 1, #regions, 1 do
if master[j] == nil then break end
-- preare for undo operation
regions[j]:to_stateful():clear_changes()
regions[j]:set_position(master[j]:position(), 0)
-- create a diff of the performed work, add it to the session's undo stack and check if it is not empty
if not Session:add_stateful_diff_command (regions[j]:to_statefuldestructible()):empty () then
add_undo = true
end
end
end
collectgarbage()
-- all done, commit the combined Undo Operation
if add_undo then
-- the 'nil' Command here mean to use the collected diffs added above
Session:commit_reversible_command(nil)
else
Session:abort_reversible_command()
end
end
end
|
local Export = require "core.utils.export"
describe("Export", function()
it("should fail if no table has been provided", function()
local export = function() return Export("string") end
assert.has.error(export, "Export expects table as an input")
end)
it("should fail if 'create' hasn't been provided", function()
local export = function() return Export { } end
assert.has.error(export, "Export expects 'create' function to be defined: nil")
end)
it("should wrap 'create' as __call by default", function()
local called = 0
local fiction = function() called = called + 1 end
local export = Export { create = fiction }
export()
assert.are.equal(1, called)
end)
it("should pass all arguments to 'create' function", function()
local expected = { 1, 2, "string" }
local actual = { }
local create = function(...)
actual.got = { ... }
end
local export = Export { create = create }
export(1, 2, "string")
assert.are.same(expected, actual.got)
end)
end)
|
--Author Pasky13
-- Player
local pbase = 0x1CD4
local px = pbase + 0x19
local py = pbase + 0x1D
local camx = 0x1BC5
local camy = 0x1BC9
--Player projectiles
local projbase = 0x1D34
--Enemies
local ebase = 0x21B4
--Bosses
local bbase = 0x35F4
--Text scaler
local xs
local ys
local function endian(address)
local result = mainmemory.read_u8(address) + (mainmemory.read_u8(address-1) * 256)
return result
end
local function Toki()
local cx = endian(camx)
local cy = endian(camy)
local x = endian(px) - cx
local y = endian(py) - cy
local xoff = mainmemory.read_s8(pbase + 0x11)
local yoff = mainmemory.read_s8(pbase + 0x15)
local xrad = mainmemory.read_u8(pbase +0x13)
local yrad = mainmemory.read_u8(pbase +0x17)
local flip = mainmemory.read_u8(pbase +1)
if flip == 1 then
xoff = xoff * -1
end
gui.drawBox(x+xoff-xrad,y+yoff-yrad,x+xoff+xrad,y+yoff+yrad,0xFF0000FF,0x300000FF)
end
local function enemies()
local cx = endian(camx)
local cy = endian(camy)
local x
local y
local xoff
local xrad
local yoff
local yrad
local oend = 44
local base = ebase
local flip
local hp
for i = 0,oend,1 do
if i > 0 then
base = ebase + (i * 0x60)
end
flip = mainmemory.read_u8(base +1)
if mainmemory.read_u8(base) > 0 then
hp = mainmemory.read_u8(base + 0xD)
x = endian(base + 0x19) - cx
xrad = mainmemory.read_u8(base + 0x13)
xoff = mainmemory.read_s8(base + 0x11)
yrad = mainmemory.read_u8(base + 0x17)
yoff = mainmemory.read_s8(base + 0x15)
if flip == 1 then
xoff = xoff * -1
end
y = endian(base + 0x1D) - cy
if hp > 0 then
gui.text((x-10) * xs,(y-10) * ys, "HP: " .. hp)
end
gui.drawBox(x+xoff-xrad,y+yoff-yrad,x+xoff+xrad,y+yoff+yrad,0xFFFF0000,0x35FF0000)
end
end
end
local function boss()
local cx = endian(camx)
local cy = endian(camy)
local x = endian(bbase + 0x19) - cx
local y = endian(bbase + 0x1D) - cy
local xrad = mainmemory.read_u8(bbase + 0x11)
local yrad = mainmemory.read_u8(bbase + 0x15)
local hp = mainmemory.read_u8(bbase+ 0x0D)
if hp > 0 then
gui.text((x-10) * xs,(y-10) * ys,"HP: " .. mainmemory.read_u8(bbase + 0x0D))
end
gui.drawBox(x-xrad,y-yrad,x+xrad,y+yrad,0xFFFF0000,0x35FF0000)
end
local function projectiles()
local cx = endian(camx)
local cy = endian(camy)
local x
local y
local xoff
local xrad
local yoff
local yrad
local oend = 11
local base = projbase
local flip
for i = 0,oend,1 do
if i > 0 then
base = projbase + (i * 0x60)
end
flip = mainmemory.read_u8(base +1)
if mainmemory.read_u8(base) > 0 then
x = endian(base + 0x19) - cx
y = endian(base + 0x1D) - cy
xoff = mainmemory.read_s8(base + 0x11)
yoff = mainmemory.read_s8(base + 0x15)
xrad = mainmemory.read_u8(base + 0x13)
yrad = mainmemory.read_u8(base + 0x17)
if flip == 1 then
xoff = xoff * -1
end
gui.drawBox(x+xoff-xrad,y+yoff-yrad,x+xoff+xrad,y+yoff+yrad,0xFFFFFFFF,0x40FFFFFF)
end
end
end
local function scaler()
xs = client.screenwidth() / 320
ys = client.screenheight() / 224
end
while true do
scaler()
Toki()
enemies()
projectiles()
boss()
emu.frameadvance()
end |
print "testing string length overflow"
local longs = string.rep("\0", 2^25)
local function catter (i)
return assert(loadstring(
string.format("return function(a) return a%s end",
string.rep("..a", i-1))))()
end
rep129 = catter(129)
local a, b = pcall(rep129, longs)
print(b)
assert(not a and string.find(b, "overflow"))
print('+')
require "checktable"
--[[ lots of empty lines (to force SETLINEW)
--]]
a,b = nil,nil
while not b do
if a then
b = { -- lots of strings (to force JMPW and PUSHCONSTANTW)
"n1", "n2", "n3", "n4", "n5", "n6", "n7", "n8", "n9", "n10",
"n11", "n12", "j301", "j302", "j303", "j304", "j305", "j306", "j307", "j308",
"j309", "a310", "n311", "n312", "n313", "n314", "n315", "n316", "n317", "n318",
"n319", "n320", "n321", "n322", "n323", "n324", "n325", "n326", "n327", "n328",
"a329", "n330", "n331", "n332", "n333", "n334", "n335", "n336", "n337", "n338",
"n339", "n340", "n341", "z342", "n343", "n344", "n345", "n346", "n347", "n348",
"n349", "n350", "n351", "n352", "r353", "n354", "n355", "n356", "n357", "n358",
"n359", "n360", "n361", "n362", "n363", "n364", "n365", "n366", "z367", "n368",
"n369", "n370", "n371", "n372", "n373", "n374", "n375", "a376", "n377", "n378",
"n379", "n380", "n381", "n382", "n383", "n384", "n385", "n386", "n387", "n388",
"n389", "n390", "n391", "n392", "n393", "n394", "n395", "n396", "n397", "n398",
"n399", "n400", "n13", "n14", "n15", "n16", "n17", "n18", "n19", "n20",
"n21", "n22", "n23", "a24", "n25", "n26", "n27", "n28", "n29", "j30",
"n31", "n32", "n33", "n34", "n35", "n36", "n37", "n38", "n39", "n40",
"n41", "n42", "n43", "n44", "n45", "n46", "n47", "n48", "n49", "n50",
"n51", "n52", "n53", "n54", "n55", "n56", "n57", "n58", "n59", "n60",
"n61", "n62", "n63", "n64", "n65", "a66", "z67", "n68", "n69", "n70",
"n71", "n72", "n73", "n74", "n75", "n76", "n77", "n78", "n79", "n80",
"n81", "n82", "n83", "n84", "n85", "n86", "n87", "n88", "n89", "n90",
"n91", "n92", "n93", "n94", "n95", "n96", "n97", "n98", "n99", "n100",
"n201", "n202", "n203", "n204", "n205", "n206", "n207", "n208", "n209", "n210",
"n211", "n212", "n213", "n214", "n215", "n216", "n217", "n218", "n219", "n220",
"n221", "n222", "n223", "n224", "n225", "n226", "n227", "n228", "n229", "n230",
"n231", "n232", "n233", "n234", "n235", "n236", "n237", "n238", "n239", "a240",
"a241", "a242", "a243", "a244", "a245", "a246", "a247", "a248", "a249", "n250",
"n251", "n252", "n253", "n254", "n255", "n256", "n257", "n258", "n259", "n260",
"n261", "n262", "n263", "n264", "n265", "n266", "n267", "n268", "n269", "n270",
"n271", "n272", "n273", "n274", "n275", "n276", "n277", "n278", "n279", "n280",
"n281", "n282", "n283", "n284", "n285", "n286", "n287", "n288", "n289", "n290",
"n291", "n292", "n293", "n294", "n295", "n296", "n297", "n298", "n299"
; x=23}
else a = 1 end
end
assert(b.x == 23)
print('+')
stat(b)
repeat
a = {
n1 = 1.5, n2 = 2.5, n3 = 3.5, n4 = 4.5, n5 = 5.5, n6 = 6.5, n7 = 7.5,
n8 = 8.5, n9 = 9.5, n10 = 10.5, n11 = 11.5, n12 = 12.5,
j301 = 301.5, j302 = 302.5, j303 = 303.5, j304 = 304.5, j305 = 305.5,
j306 = 306.5, j307 = 307.5, j308 = 308.5, j309 = 309.5, a310 = 310.5,
n311 = 311.5, n312 = 312.5, n313 = 313.5, n314 = 314.5, n315 = 315.5,
n316 = 316.5, n317 = 317.5, n318 = 318.5, n319 = 319.5, n320 = 320.5,
n321 = 321.5, n322 = 322.5, n323 = 323.5, n324 = 324.5, n325 = 325.5,
n326 = 326.5, n327 = 327.5, n328 = 328.5, a329 = 329.5, n330 = 330.5,
n331 = 331.5, n332 = 332.5, n333 = 333.5, n334 = 334.5, n335 = 335.5,
n336 = 336.5, n337 = 337.5, n338 = 338.5, n339 = 339.5, n340 = 340.5,
n341 = 341.5, z342 = 342.5, n343 = 343.5, n344 = 344.5, n345 = 345.5,
n346 = 346.5, n347 = 347.5, n348 = 348.5, n349 = 349.5, n350 = 350.5,
n351 = 351.5, n352 = 352.5, r353 = 353.5, n354 = 354.5, n355 = 355.5,
n356 = 356.5, n357 = 357.5, n358 = 358.5, n359 = 359.5, n360 = 360.5,
n361 = 361.5, n362 = 362.5, n363 = 363.5, n364 = 364.5, n365 = 365.5,
n366 = 366.5, z367 = 367.5, n368 = 368.5, n369 = 369.5, n370 = 370.5,
n371 = 371.5, n372 = 372.5, n373 = 373.5, n374 = 374.5, n375 = 375.5,
a376 = 376.5, n377 = 377.5, n378 = 378.5, n379 = 379.5, n380 = 380.5,
n381 = 381.5, n382 = 382.5, n383 = 383.5, n384 = 384.5, n385 = 385.5,
n386 = 386.5, n387 = 387.5, n388 = 388.5, n389 = 389.5, n390 = 390.5,
n391 = 391.5, n392 = 392.5, n393 = 393.5, n394 = 394.5, n395 = 395.5,
n396 = 396.5, n397 = 397.5, n398 = 398.5, n399 = 399.5, n400 = 400.5,
n13 = 13.5, n14 = 14.5, n15 = 15.5, n16 = 16.5, n17 = 17.5,
n18 = 18.5, n19 = 19.5, n20 = 20.5, n21 = 21.5, n22 = 22.5,
n23 = 23.5, a24 = 24.5, n25 = 25.5, n26 = 26.5, n27 = 27.5,
n28 = 28.5, n29 = 29.5, j30 = 30.5, n31 = 31.5, n32 = 32.5,
n33 = 33.5, n34 = 34.5, n35 = 35.5, n36 = 36.5, n37 = 37.5,
n38 = 38.5, n39 = 39.5, n40 = 40.5, n41 = 41.5, n42 = 42.5,
n43 = 43.5, n44 = 44.5, n45 = 45.5, n46 = 46.5, n47 = 47.5,
n48 = 48.5, n49 = 49.5, n50 = 50.5, n51 = 51.5, n52 = 52.5,
n53 = 53.5, n54 = 54.5, n55 = 55.5, n56 = 56.5, n57 = 57.5,
n58 = 58.5, n59 = 59.5, n60 = 60.5, n61 = 61.5, n62 = 62.5,
n63 = 63.5, n64 = 64.5, n65 = 65.5, a66 = 66.5, z67 = 67.5,
n68 = 68.5, n69 = 69.5, n70 = 70.5, n71 = 71.5, n72 = 72.5,
n73 = 73.5, n74 = 74.5, n75 = 75.5, n76 = 76.5, n77 = 77.5,
n78 = 78.5, n79 = 79.5, n80 = 80.5, n81 = 81.5, n82 = 82.5,
n83 = 83.5, n84 = 84.5, n85 = 85.5, n86 = 86.5, n87 = 87.5,
n88 = 88.5, n89 = 89.5, n90 = 90.5, n91 = 91.5, n92 = 92.5,
n93 = 93.5, n94 = 94.5, n95 = 95.5, n96 = 96.5, n97 = 97.5,
n98 = 98.5, n99 = 99.5, n100 = 100.5, n201 = 201.5, n202 = 202.5,
n203 = 203.5, n204 = 204.5, n205 = 205.5, n206 = 206.5, n207 = 207.5,
n208 = 208.5, n209 = 209.5, n210 = 210.5, n211 = 211.5, n212 = 212.5,
n213 = 213.5, n214 = 214.5, n215 = 215.5, n216 = 216.5, n217 = 217.5,
n218 = 218.5, n219 = 219.5, n220 = 220.5, n221 = 221.5, n222 = 222.5,
n223 = 223.5, n224 = 224.5, n225 = 225.5, n226 = 226.5, n227 = 227.5,
n228 = 228.5, n229 = 229.5, n230 = 230.5, n231 = 231.5, n232 = 232.5,
n233 = 233.5, n234 = 234.5, n235 = 235.5, n236 = 236.5, n237 = 237.5,
n238 = 238.5, n239 = 239.5, a240 = 240.5, a241 = 241.5, a242 = 242.5,
a243 = 243.5, a244 = 244.5, a245 = 245.5, a246 = 246.5, a247 = 247.5,
a248 = 248.5, a249 = 249.5, n250 = 250.5, n251 = 251.5, n252 = 252.5,
n253 = 253.5, n254 = 254.5, n255 = 255.5, n256 = 256.5, n257 = 257.5,
n258 = 258.5, n259 = 259.5, n260 = 260.5, n261 = 261.5, n262 = 262.5,
n263 = 263.5, n264 = 264.5, n265 = 265.5, n266 = 266.5, n267 = 267.5,
n268 = 268.5, n269 = 269.5, n270 = 270.5, n271 = 271.5, n272 = 272.5,
n273 = 273.5, n274 = 274.5, n275 = 275.5, n276 = 276.5, n277 = 277.5,
n278 = 278.5, n279 = 279.5, n280 = 280.5, n281 = 281.5, n282 = 282.5,
n283 = 283.5, n284 = 284.5, n285 = 285.5, n286 = 286.5, n287 = 287.5,
n288 = 288.5, n289 = 289.5, n290 = 290.5, n291 = 291.5, n292 = 292.5,
n293 = 293.5, n294 = 294.5, n295 = 295.5, n296 = 296.5, n297 = 297.5,
n298 = 298.5, n299 = 299.5, j300 = 300} or 1
until 1
assert(a.n299 == 299.5)
xxx = 1
assert(xxx == 1)
stat(a)
function a:findfield (f)
local i,v = next(self, nil)
while i ~= f do
if not i then return end
i,v = next(self, i)
end
return v
end
local ii = 0
i = 1
while b[i] do
local r = a:findfield(b[i]);
assert(a[b[i]] == r)
ii = math.max(ii,i)
i = i+1
end
assert(ii == 299)
function xxxx (x) coroutine.yield('b'); return ii+x end
assert(xxxx(10) == 309)
a = nil
b = nil
a1 = nil
print("tables with table indices:")
i = 1; a={}
while i <= 1023 do a[{}] = i; i=i+1 end
stat(a)
a = nil
print("tables with function indices:")
a={}
for i=1,511 do local x; a[function () return x end] = i end
stat(a)
a = nil
print'OK'
return 'a'
|
QhunUnitHealth.TargetUnitFrame = {}
QhunUnitHealth.TargetUnitFrame.__index = QhunUnitHealth.TargetUnitFrame
function QhunUnitHealth.TargetUnitFrame.new(uiInstance)
-- call super class
local instance =
QhunUnitHealth.AbstractUnitFrame.new(
uiInstance,
"target",
{
"PLAYER_TARGET_CHANGED"
},
TargetFrameHealthBar,
TargetFrameManaBar
)
-- bind current values
setmetatable(instance, QhunUnitHealth.TargetUnitFrame)
-- create the visible frame
instance._healthFrame = instance:createFrame("HEALTH")
instance._powerFrame = instance:createFrame("POWER")
return instance
end
-- set inheritance
setmetatable(QhunUnitHealth.TargetUnitFrame, {__index = QhunUnitHealth.AbstractUnitFrame})
--[[
PUBLIC FUNCTIONS
]]
-- update the player resource frame
function QhunUnitHealth.TargetUnitFrame:update(...)
self:genericUpdate("target")
end
-- get the current storage options for the TargetUnitFrame
function QhunUnitHealth.TargetUnitFrame:getOptions()
return QhunUnitHealth.Storage:get("TARGET")
end
-- is the target frame enabled
function QhunUnitHealth.TargetUnitFrame:isEnabled()
return QhunUnitHealth.Storage:get("TARGET_ENABLED")
end |
ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Washing Machine"
ENT.Author = "vikR"
ENT.Category = "Laundry Job"
ENT.Contact = "none"
ENT.Spawnable = true
ENT.AdminSpawnable = false
function ENT:SetupDataTables()
self:NetworkVar("Float", 0, "WashState")
self:NetworkVar("Float", 1, "ClothType")
self:NetworkVar("Bool", 2, "Washing")
if SERVER then
self:NetworkVarNotify("Washing", self.OnWash)
end
end
|
local m_currentProfile = nil
local m_currentProfileInd = nil
local function GetMyUserInd()
local userID = avatar.GetServerId() or ""
local buildID = avatar.GetActiveBuild() or ""
return userID.."_"..buildID
end
local function LoadCurrentProfileInd()
local lastUsedProfiles = userMods.GetGlobalConfigSection("TR_LastProfileArr")
local currentInd = lastUsedProfiles[GetMyUserInd()]
if currentInd == nil or currentInd == 0 then
currentInd = 1
end
return currentInd
end
local function SetCurrentProfileInd(anInd)
local lastUsedProfiles = userMods.GetGlobalConfigSection("TR_LastProfileArr")
lastUsedProfiles[GetMyUserInd()] = anInd
userMods.SetGlobalConfigSection("TR_LastProfileArr", lastUsedProfiles)
end
function InitializeDefaultSetting()
local allProfiles = userMods.GetGlobalConfigSection("TR_ProfilesArr")
if allProfiles then
return
end
allProfiles = {}
local defaultProfile = {}
local mainFormSettings = {}
mainFormSettings.useRaidSubSystem = true
mainFormSettings.useTargeterSubSystem = true
mainFormSettings.useBuffMngSubSystem = true
mainFormSettings.useBindSubSystem = false
mainFormSettings.useCastSubSystem = true
local raidFormSettings = {}
raidFormSettings.classColorModeButton = false
raidFormSettings.showManaButton = false
raidFormSettings.showShieldButton = true
raidFormSettings.showStandartRaidButton = false
raidFormSettings.showClassIconButton = true
raidFormSettings.showDistanceButton = true
raidFormSettings.showProcentButton = false
raidFormSettings.showArrowButton = true
raidFormSettings.gorisontalModeButton = false
raidFormSettings.woundsShowButton = false
raidFormSettings.showServerNameButton = true
raidFormSettings.highlightSelectedButton = true
raidFormSettings.showRollOverInfo = true
raidFormSettings.raidWidthText = "160"
raidFormSettings.raidHeightText = "50"
raidFormSettings.distanceText = "0"
raidFormSettings.buffSize = "20"
raidFormSettings.raidBuffs = {}
raidFormSettings.raidBuffs.autoDebuffModeButton = false
raidFormSettings.raidBuffs.showImportantButton = true
raidFormSettings.raidBuffs.checkControlsButton = false
raidFormSettings.raidBuffs.checkMovementsButton = false
raidFormSettings.raidBuffs.colorDebuffButton = true
raidFormSettings.raidBuffs.checkFriendCleanableButton = true
raidFormSettings.raidBuffs.customBuffs = {}
local targeterFormSettings = {}
targeterFormSettings.classColorModeButton = false
targeterFormSettings.showManaButton = false
targeterFormSettings.showShieldButton = true
targeterFormSettings.showClassIconButton = true
targeterFormSettings.showProcentButton = false
targeterFormSettings.gorisontalModeButton = false
targeterFormSettings.woundsShowButton = false
targeterFormSettings.showServerNameButton = true
targeterFormSettings.highlightSelectedButton = true
targeterFormSettings.showRollOverInfo = true
targeterFormSettings.hideUnselectableButton = true
targeterFormSettings.lastTargetType = ALL_TARGETS
targeterFormSettings.lastTargetWasActive = true
targeterFormSettings.separateBuffDebuff = false
targeterFormSettings.twoColumnMode = false
targeterFormSettings.raidWidthText = "200"
targeterFormSettings.raidHeightText = "30"
targeterFormSettings.buffSize = "16"
targeterFormSettings.targetLimit = "12"
targeterFormSettings.sortByName = true
targeterFormSettings.sortByHP = false
targeterFormSettings.sortByClass = false
targeterFormSettings.sortByDead = false
targeterFormSettings.raidBuffs = {}
targeterFormSettings.raidBuffs.checkEnemyCleanable = false
targeterFormSettings.raidBuffs.checkControlsButton = false
targeterFormSettings.raidBuffs.checkMovementsButton = false
targeterFormSettings.raidBuffs.customBuffs = {}
targeterFormSettings.myTargets = {}
local buffFormSettings = {}
buffFormSettings.buffGroups = {}
local bindFormSettings = {}
bindFormSettings.actionLeftSwitchRaidSimple = SELECT_CLICK
bindFormSettings.actionLeftSwitchRaidShift = DISABLE_CLICK
bindFormSettings.actionLeftSwitchRaidAlt = DISABLE_CLICK
bindFormSettings.actionLeftSwitchRaidCtrl = DISABLE_CLICK
bindFormSettings.actionRightSwitchRaidSimple = MENU_CLICK
bindFormSettings.actionRightSwitchRaidShift = DISABLE_CLICK
bindFormSettings.actionRightSwitchRaidAlt = DISABLE_CLICK
bindFormSettings.actionRightSwitchRaidCtrl = DISABLE_CLICK
bindFormSettings.actionLeftSwitchTargetSimple = SELECT_CLICK
bindFormSettings.actionLeftSwitchTargetShift = DISABLE_CLICK
bindFormSettings.actionLeftSwitchTargetAlt = DISABLE_CLICK
bindFormSettings.actionLeftSwitchTargetCtrl = DISABLE_CLICK
bindFormSettings.actionRightSwitchTargetSimple = DISABLE_CLICK
bindFormSettings.actionRightSwitchTargetShift = DISABLE_CLICK
bindFormSettings.actionRightSwitchTargetAlt = DISABLE_CLICK
bindFormSettings.actionRightSwitchTargetCtrl = DISABLE_CLICK
bindFormSettings.actionLeftSwitchProgressCastSimple = SELECT_CLICK
bindFormSettings.actionLeftSwitchProgressCastShift = DISABLE_CLICK
bindFormSettings.actionLeftSwitchProgressCastAlt = DISABLE_CLICK
bindFormSettings.actionLeftSwitchProgressCastCtrl = DISABLE_CLICK
bindFormSettings.actionRightSwitchProgressCastSimple = DISABLE_CLICK
bindFormSettings.actionRightSwitchProgressCastShift = DISABLE_CLICK
bindFormSettings.actionRightSwitchProgressCastAlt = DISABLE_CLICK
bindFormSettings.actionRightSwitchProgressCastCtrl = DISABLE_CLICK
local castFormSettings = {}
castFormSettings.showImportantCasts = true
castFormSettings.showImportantBuffs = true
castFormSettings.panelWidthText = "270"
castFormSettings.panelHeightText = "40"
castFormSettings.selectable = false
castFormSettings.fixed = false
castFormSettings.showOnlyMyTarget = false
castFormSettings.ignoreList = {}
defaultProfile.name = "default"
defaultProfile.mainFormSettings = mainFormSettings
defaultProfile.raidFormSettings = raidFormSettings
defaultProfile.targeterFormSettings = targeterFormSettings
defaultProfile.buffFormSettings = buffFormSettings
defaultProfile.bindFormSettings = bindFormSettings
defaultProfile.castFormSettings = castFormSettings
defaultProfile.version = GetSettingsVersion()
table.insert(allProfiles, defaultProfile)
userMods.SetGlobalConfigSection("TR_ProfilesArr", allProfiles)
userMods.SetGlobalConfigSection("TR_LastProfileArr", {})
SetCurrentProfileInd(1)
end
function LoadLastUsedSetting()
LoadSettings(LoadCurrentProfileInd())
end
function LoadSettings(aProfileInd)
local allProfiles = userMods.GetGlobalConfigSection("TR_ProfilesArr")
m_currentProfile = allProfiles[aProfileInd]
m_currentProfileInd = aProfileInd
SetCurrentProfileInd(aProfileInd)
if m_currentProfile.version == 1 or m_currentProfile.version == nil then
local castFormSettings = {}
castFormSettings.showImportantCasts = true
castFormSettings.showImportantBuffs = true
castFormSettings.panelWidthText = "270"
castFormSettings.panelHeightText = "40"
castFormSettings.selectable = false
castFormSettings.fixed = false
castFormSettings.showOnlyMyTarget = false
m_currentProfile.castFormSettings = castFormSettings
m_currentProfile.mainFormSettings.useCastSubSystem = true
m_currentProfile.bindFormSettings.actionLeftSwitchProgressCastSimple = SELECT_CLICK
m_currentProfile.bindFormSettings.actionLeftSwitchProgressCastShift = DISABLE_CLICK
m_currentProfile.bindFormSettings.actionLeftSwitchProgressCastAlt = DISABLE_CLICK
m_currentProfile.bindFormSettings.actionLeftSwitchProgressCastCtrl = DISABLE_CLICK
m_currentProfile.bindFormSettings.actionRightSwitchProgressCastSimple = DISABLE_CLICK
m_currentProfile.bindFormSettings.actionRightSwitchProgressCastShift = DISABLE_CLICK
m_currentProfile.bindFormSettings.actionRightSwitchProgressCastAlt = DISABLE_CLICK
m_currentProfile.bindFormSettings.actionRightSwitchProgressCastCtrl = DISABLE_CLICK
end
if m_currentProfile.version < 2.2 or m_currentProfile.version == nil then
m_currentProfile.raidFormSettings.showRollOverInfo = true
m_currentProfile.targeterFormSettings.showRollOverInfo = true
m_currentProfile.raidFormSettings.highlightSelectedButton = true
m_currentProfile.targeterFormSettings.highlightSelectedButton = true
end
if m_currentProfile.version < 2.3 or m_currentProfile.version == nil then
m_currentProfile.castFormSettings.ignoreList = {}
end
end
function ProfileWasDeleted(anInd)
local lastUsedProfiles = userMods.GetGlobalConfigSection("TR_LastProfileArr")
for i, index in pairs(lastUsedProfiles) do
if index == anInd then
lastUsedProfiles[i] = 0
elseif index > anInd and index > 0 then
lastUsedProfiles[i] = index - 1
end
end
userMods.SetGlobalConfigSection("TR_LastProfileArr", lastUsedProfiles)
LoadLastUsedSetting()
end
function SaveProfiles(aProfileList)
userMods.SetGlobalConfigSection("TR_ProfilesArr", aProfileList)
end
function GetCurrentProfile()
return m_currentProfile
end
function GetCurrentProfileInd()
return m_currentProfileInd
end
function GetAllProfiles()
return userMods.GetGlobalConfigSection("TR_ProfilesArr")
end
function ExportProfileByIndex(anInd)
local allProfiles = userMods.GetGlobalConfigSection("TR_ProfilesArr")
return StartSerialize(allProfiles[anInd])
end
function GetSettingsVersion()
return 2.3;
end
|
--[[--ldoc desc
@module paidiandaxiao_template
@author SinChen
Date 2018-01-09 19:35:02
Last Modified by SinChen
Last Modified time 2018-03-02 16:49:00
]]
local template = [==[
local LibBase = import("..base.LibBase")
local SortUtils = import(".SortUtils")
local M = class(LibBase)
function M:main(data)
local ruleDao = data.ruleDao
end
return M;
]==]
return template; |
newoption {
trigger = "Test",
description = "Generate test projects"
}
newoption {
trigger = "JNI",
description = "Generate LogSimulatorJNI project"
}
newoption {
trigger = "Wno-conversion",
description = "Disable the -Wconversion warning for gcc"
}
newoption {
trigger = "Wno-misleading-indentation",
description = "Disable the -Wmisleading-indentation warning/error for gcc (6.0+)"
}
newoption {
trigger = "Wno-ignored-attributes",
description = "Disable the -Wignored-attributes warning/error for gcc (6.0+)"
}
newoption {
trigger = "platform",
description = "Set the target platform",
}
newoption {
trigger = "verbose",
description = "Print additional information regarding the include and lib paths",
}
if _OPTIONS["Test"] ~= nil then
print("DEBUG: Generate test projects")
end
if _OPTIONS["JNI"] ~= nil then
print("Generate LogSimulatorJNI project")
end
if _OPTIONS["Wno-conversion"] ~= nil then
print("DEBUG: Disable the -Wconversion warning for gcc")
end
if _OPTIONS["Wno-misleading-indentation"] ~= nil then
print("DEBUG: Disable the -Wmisleading-indentation warning/error for gcc (6.0+)")
end
if _OPTIONS["Wno-ignored-attributes"] ~= nil then
print("DEBUG: Disable the -Wignored-attributes warning/error for gcc (6.0+)")
end
PLATFORM = _OPTIONS["platform"]
if PLATFORM == nil then
defaultplatform "Native"
PLATFORM = "Native" -- just a variable for printing the platform name
end
--
if _OPTIONS["verbose"] ~= nil then
local validate_project = premake.validation.elements.project
premake.validation.elements.project = function(prj)
print ("\n")
print ("INFO: project " .. prj.name .. ":")
-- print some debug output
print("INFO: list includedirs")
checkPaths(prj.includedirs)
print("INFO: list libdirs")
checkPaths(prj.libdirs)
print("INFO: list sysincludedirs")
checkPaths(prj.sysincludedirs)
print("INFO: list syslibdirs")
checkPaths(prj.syslibdirs)
-- call the default premake function
return validate_project(prj)
end
end |
classer = require "classer"
local bar = {}
bar.Bar = classer.ncls()
function bar.Bar:_init(x, y, width, height, val)
self.x = x
self.y = y
self.width = width
self.height = height
self.max = val
end
function bar.Bar:draw(dt)
love.graphics.setColor(255, 0, 0, 255)
love.graphics.rectangle("fill", self.x, self.y, math.floor(self.width*self.val) + 1, self.height)
love.graphics.setColor(255, 255, 255, 255)
love.graphics.rectangle("line", self.x, self.y, math.floor(self.width*self.val) + 1, self.height)
love.graphics.setFont(db.fonts.UI)
love.graphics.print("POWER:", math.max(self.x - 60,0), math.max(self.y - 2, 0))
end
return bar |
local _, GlobalFont = ...
GlobalFont.Locale = GetLocale()
-- define font files here
GlobalFont.DefaultFont = [[Interface\AddOns\!GlobalFont_Template\SampleFont.ttf]]
GlobalFont.ChatFont = [[Interface\AddOns\!GlobalFont_Template\SampleChat.ttf]]
-- you can change how to determine font size here
function GlobalFont.CalculateFontSize(sizeWestern, sizeChinese)
if GlobalFont.Locale == "zhCN" or GlobalFont.Locale == "zhTW" then
if sizeWestern >= sizeChinese then
-- sometimes it’s too small to read
-- i.e. the item list in new auction house frame
return sizeWestern
else
-- sometimes it’s too large to display
-- i.e. player lvl in who list frame
return (sizeWestern + sizeChinese) / 2
end
else
return sizeWestern
end
end
function GlobalFont.Register(this, event, ...)
STANDARD_TEXT_FONT = GlobalFont.DefaultFont
UNIT_NAME_FONT = GlobalFont.DefaultFont
DAMAGE_TEXT_FONT = GlobalFont.DefaultFont
-- don’t ask me where they’re applied. these codes were automatically generated from xml files.
if SystemFont_Tiny2 then SystemFont_Tiny2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(8, 8)) end
if SystemFont_Tiny then SystemFont_Tiny:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(9, 9)) end
if SystemFont_Shadow_Small then SystemFont_Shadow_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 15)) end
if Game10Font_o1 then Game10Font_o1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12), "OUTLINE") end
if SystemFont_Small then SystemFont_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12)) end
if SystemFont_Small2 then SystemFont_Small2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(11, 13)) end
if SystemFont_Shadow_Small2 then SystemFont_Shadow_Small2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(11, 13)) end
if SystemFont_Shadow_Med1_Outline then SystemFont_Shadow_Med1_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 15), "OUTLINE") end
if SystemFont_Shadow_Med1 then SystemFont_Shadow_Med1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 15)) end
if SystemFont_Med2 then SystemFont_Med2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(13, 14)) end
if SystemFont_Med3 then SystemFont_Med3:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 13)) end
if SystemFont_Shadow_Med3 then SystemFont_Shadow_Med3:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 14)) end
if SystemFont_Shadow_Med3_Outline then SystemFont_Shadow_Med3_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 14), "OUTLINE") end
if QuestFont_Large then QuestFont_Large:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(15, 15)) end
if QuestFont_Huge then QuestFont_Huge:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(18, 17)) end
if QuestFont_30 then QuestFont_30:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(30, 29)) end
if QuestFont_39 then QuestFont_39:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(39, 38)) end
if SystemFont_Large then SystemFont_Large:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(16, 13)) end
if SystemFont_Shadow_Large_Outline then SystemFont_Shadow_Large_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(16, 17), "OUTLINE") end
if SystemFont_Shadow_Med2 then SystemFont_Shadow_Med2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 16)) end
if SystemFont_Shadow_Med2_Outline then SystemFont_Shadow_Med2_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 16), "OUTLINE") end
if SystemFont_Shadow_Large then SystemFont_Shadow_Large:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(16, 17)) end
if SystemFont_Shadow_Large2 then SystemFont_Shadow_Large2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(18, 19)) end
if Game17Font_Shadow then Game17Font_Shadow:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(17, 17)) end
if SystemFont_Shadow_Huge1 then SystemFont_Shadow_Huge1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(20, 20)) end
if SystemFont_Huge2 then SystemFont_Huge2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(24, 24)) end
if SystemFont_Shadow_Huge2 then SystemFont_Shadow_Huge2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(24, 24)) end
if SystemFont_Shadow_Huge2_Outline then SystemFont_Shadow_Huge2_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(24, 24), "OUTLINE") end
if SystemFont_Shadow_Huge3 then SystemFont_Shadow_Huge3:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(25, 25)) end
if SystemFont_Shadow_Outline_Huge3 then SystemFont_Shadow_Outline_Huge3:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(25, 25), "OUTLINE") end
if SystemFont_Huge4 then SystemFont_Huge4:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(27, 27)) end
if SystemFont_Shadow_Huge4 then SystemFont_Shadow_Huge4:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(27, 27)) end
if SystemFont_Shadow_Huge4_Outline then SystemFont_Shadow_Huge4_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(27, 27), "OUTLINE") end
if SystemFont22_Outline then SystemFont22_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(22, 22), "OUTLINE") end
if SystemFont22_Shadow_Outline then SystemFont22_Shadow_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(22, 22), "OUTLINE") end
if SystemFont_Med1 then SystemFont_Med1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 13)) end
if SystemFont_WTF2 then SystemFont_WTF2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(36, 64)) end
if SystemFont_Outline_WTF2 then SystemFont_Outline_WTF2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(36, 64), "OUTLINE") end
if GameTooltipHeader then GameTooltipHeader:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 16)) end
if System_IME then System_IME:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(16, 16)) end
if NumberFont_Shadow_Tiny then NumberFont_Shadow_Tiny:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(10, 10)) end
if NumberFont_Shadow_Small then NumberFont_Shadow_Small:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(12, 12)) end
if NumberFont_Shadow_Med then NumberFont_Shadow_Med:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 14)) end
if NumberFont_Shadow_Large then NumberFont_Shadow_Large:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(20, 20)) end
if Tooltip_Med then Tooltip_Med:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 13)) end
if Tooltip_Small then Tooltip_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12)) end
if System15Font then System15Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(15, 15)) end
if Game30Font then Game30Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(30, 30)) end
if Game40Font_Shadow2 then Game40Font_Shadow2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(40, 40)) end
if Game52Font_Shadow2 then Game52Font_Shadow2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(52, 52)) end
if Game58Font_Shadow2 then Game58Font_Shadow2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(58, 58)) end
if Game69Font_Shadow2 then Game69Font_Shadow2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(69, 69)) end
if Game72Font then Game72Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(72, 72)) end
if Game72Font_Shadow then Game72Font_Shadow:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(72, 72)) end
if SystemFont_Outline_Small then SystemFont_Outline_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12), "OUTLINE") end
if SystemFont_Outline then SystemFont_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(13, 15), "OUTLINE") end
if SystemFont_InverseShadow_Small then SystemFont_InverseShadow_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 10)) end
if SystemFont_Huge1 then SystemFont_Huge1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(20, 20)) end
if SystemFont_Huge1_Outline then SystemFont_Huge1_Outline:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(20, 20), "OUTLINE") end
if SystemFont_OutlineThick_Huge2 then SystemFont_OutlineThick_Huge2:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(22, 22), "THICKOUTLINE") end
if SystemFont_OutlineThick_Huge4 then SystemFont_OutlineThick_Huge4:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(26, 26), "THICKOUTLINE") end
if SystemFont_OutlineThick_WTF then SystemFont_OutlineThick_WTF:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(32, 32), "THICKOUTLINE") end
if NumberFont_GameNormal then NumberFont_GameNormal:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12)) end
if NumberFont_OutlineThick_Mono_Small then NumberFont_OutlineThick_Mono_Small:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(12, 11), "THICKOUTLINE,MONOCHROME") end
if Number12Font_o1 then Number12Font_o1:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(12, 11), "OUTLINE") end
if NumberFont_Small then NumberFont_Small:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(12, 11)) end
if Number11Font then Number11Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(11, 10)) end
if Number12Font then Number12Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(12, 11)) end
if Number13Font then Number13Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(13, 12)) end
if PriceFont then PriceFont:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 14)) end
if Number15Font then Number15Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(15, 14)) end
if Number16Font then Number16Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(16, 15)) end
if Number18Font then Number18Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(18, 17)) end
if NumberFont_Normal_Med then NumberFont_Normal_Med:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 12)) end
if NumberFont_Outline_Med then NumberFont_Outline_Med:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 12), "OUTLINE") end
if NumberFont_Outline_Large then NumberFont_Outline_Large:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(16, 14), "OUTLINE") end
if NumberFont_Outline_Huge then NumberFont_Outline_Huge:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(30, 20), "OUTLINE") end
if Fancy22Font then Fancy22Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(22, 20)) end
if QuestFont_Outline_Huge then QuestFont_Outline_Huge:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(18, 17), "OUTLINE") end
if QuestFont_Super_Huge then QuestFont_Super_Huge:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(24, 22)) end
if QuestFont_Super_Huge_Outline then QuestFont_Super_Huge_Outline:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(24, 22), "OUTLINE") end
if SplashHeaderFont then SplashHeaderFont:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(24, 24)) end
if Game11Font then Game11Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(11, 11)) end
if Game12Font then Game12Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 12)) end
if Game13Font then Game13Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(13, 13)) end
if Game13FontShadow then Game13FontShadow:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(13, 13)) end
if Game15Font then Game15Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(15, 15)) end
if Game16Font then Game16Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(16, 16)) end
if Game18Font then Game18Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(18, 18)) end
if Game20Font then Game20Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(20, 20)) end
if Game24Font then Game24Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(24, 24)) end
if Game27Font then Game27Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(27, 27)) end
if Game32Font then Game32Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(32, 32)) end
if Game36Font then Game36Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(36, 36)) end
if Game40Font then Game40Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(40, 40)) end
if Game42Font then Game42Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(42, 42)) end
if Game46Font then Game46Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(46, 46)) end
if Game48Font then Game48Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(48, 48)) end
if Game48FontShadow then Game48FontShadow:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(48, 48)) end
if Game60Font then Game60Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(60, 60)) end
if Game120Font then Game120Font:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(120, 120)) end
if Game11Font_o1 then Game11Font_o1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(11, 11), "OUTLINE") end
if Game12Font_o1 then Game12Font_o1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 12), "OUTLINE") end
if Game13Font_o1 then Game13Font_o1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(13, 13), "OUTLINE") end
if Game15Font_o1 then Game15Font_o1:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(15, 15), "OUTLINE") end
if QuestFont_Enormous then QuestFont_Enormous:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(30, 30)) end
if DestinyFontMed then DestinyFontMed:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 14)) end
if DestinyFontLarge then DestinyFontLarge:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(18, 18)) end
if CoreAbilityFont then CoreAbilityFont:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(32, 32)) end
if DestinyFontHuge then DestinyFontHuge:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(32, 32)) end
if QuestFont_Shadow_Small then QuestFont_Shadow_Small:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 13)) end
if MailFont_Large then MailFont_Large:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(15, 15)) end
if SpellFont_Small then SpellFont_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12)) end
if InvoiceFont_Med then InvoiceFont_Med:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 12)) end
if InvoiceFont_Small then InvoiceFont_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 10)) end
if AchievementFont_Small then AchievementFont_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 10)) end
if ReputationDetailFont then ReputationDetailFont:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 12)) end
if FriendsFont_Normal then FriendsFont_Normal:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 15)) end
if FriendsFont_11 then FriendsFont_11:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(11, 14)) end
if FriendsFont_Small then FriendsFont_Small:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(10, 13)) end
if FriendsFont_Large then FriendsFont_Large:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(14, 17)) end
if FriendsFont_UserText then FriendsFont_UserText:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(11, 11)) end
if GameFont_Gigantic then GameFont_Gigantic:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(32, 38)) end
if ChatBubbleFont then ChatBubbleFont:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(13, 15)) end
if Fancy12Font then Fancy12Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(12, 12)) end
if Fancy14Font then Fancy14Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(14, 14)) end
if Fancy16Font then Fancy16Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(16, 16)) end
if Fancy18Font then Fancy18Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(18, 18)) end
if Fancy20Font then Fancy20Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(20, 20)) end
if Fancy24Font then Fancy24Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(24, 24)) end
if Fancy27Font then Fancy27Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(27, 27)) end
if Fancy30Font then Fancy30Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(30, 30)) end
if Fancy32Font then Fancy32Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(32, 32)) end
if Fancy48Font then Fancy48Font:SetFont(GlobalFont.ChatFont, GlobalFont.CalculateFontSize(48, 48)) end
if SystemFont_NamePlate then SystemFont_NamePlate:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(9, 9)) end
if SystemFont_LargeNamePlate then SystemFont_LargeNamePlate:SetFont(GlobalFont.DefaultFont, GlobalFont.CalculateFontSize(12, 12)) end
end
GlobalFont.EventHandler = CreateFrame("Frame")
GlobalFont.EventHandler:SetScript("OnEvent", GlobalFont.Register)
GlobalFont.EventHandler:RegisterEvent("ADDON_LOADED")
|
-- Autogenerated with DRAKON Editor 1.32
require('strict').on()
local table = table
local string = string
local pairs = pairs
local ipairs = ipairs
local io = io
local pcall = pcall
local xpcall = xpcall
local debug = debug
local tostring = tostring
local tonumber = tonumber
local type = type
local clock = require("clock")
local math = require("math")
local log = require("log")
local digest = require("digest")
local fiber = require("fiber")
local json = require("json")
local fio = require("fio")
local os = os
local error = error
local print = print
local utf8 = require("lua-utf8")
local utils = require("utils")
local mail = require("mail")
local ej = require("ej")
local lic = require("lic")
local global_cfg = global_cfg
local external_creds = external_creds
setfenv(1, {})
local module = nil
local globals = {}
function calculate_payment(num_users, product_id, old_license, pricing, now)
-- item 29
local result = {}
-- item 44
local users = tonumber(num_users)
local limits = pricing.products[product_id]
-- item 33
if users then
-- item 35
if users >= limits.min_users then
-- item 39
if users <= limits.max_users then
-- item 60
local months = limits.period_mon
local price = limits.price
-- item 25
local sum = round_cents(
price * users * months
)
-- item 30
local period = utils.months_to_secs(months)
+ days_to_secs(1)
-- item 54
result.sum = sum
result.price = price
result.period = period
-- item 286
local mva_rate = pricing.mva or 0
local without_mva = 0
-- item 46
if (old_license) and (not (old_license.product_id == "basic")) then
-- item 62
local left = take_positive(
old_license.expiry - now
)
-- item 266
local old_period = old_license.period or left
local old_sum = old_license.sum or 0
-- item 52
local remaining_value = left / old_period * old_sum
remaining_value = round_cents(remaining_value)
-- item 53
result.remaining_value = remaining_value
result.effective_start = now
without_mva = take_positive(sum - remaining_value)
else
-- item 56
result.remaining_value = 0
result.effective_start = now
without_mva = sum
end
-- item 61
result.expiry = result.effective_start
+ period
-- item 282
result.mva = mva_rate * without_mva
result.total = without_mva + result.mva
else
-- item 42
result.error = "ERR_NUM_USERS_TOO_LARGE"
end
else
-- item 38
result.error = "ERR_NUM_USERS_TOO_LITTLE"
end
else
-- item 34
result.error = "ERR_NUM_USERS_SPECIFY"
end
-- item 32
return result
end
function check_acc_number(fields, name, min, max)
-- item 186
local value = fields[name]
-- item 187
if type(value) == "string" then
-- item 194
if #value >= min then
-- item 198
if #value <= max then
-- item 200
local chars = utils.string_to_chars(value)
for _, chr in ipairs(chars) do
-- item 203
if utils.is_digit(chr) then
else
-- item 205
error("field '" .. name
.. "' contains non-digits: "
.. tostring(value)
)
break
end
end
else
-- item 197
error("field '" .. name
.. "' is too long: "
.. tostring(value)
)
end
else
-- item 196
error("field '" .. name
.. "' is too short: "
.. tostring(value)
)
end
else
-- item 190
error("field '" .. name
.. "' is not a string: "
.. tostring(value)
)
end
end
function check_card_type(type)
-- item 2130001
if ((type == "visa") or (type == "mastercard")) or (type == "amex") then
else
-- item 224
error(
"unexpected card type: "
.. tostring(type)
)
end
end
function check_int(fields, name, min, max)
-- item 167
local value = fields[name]
-- item 168
if type(value) == "number" then
-- item 172
if value == math.ceil(value) then
-- item 175
if value >= min then
-- item 179
if value <= max then
else
-- item 178
error("field '" .. name
.. "' is too large: "
.. tostring(value)
)
end
else
-- item 177
error("field '" .. name
.. "' is too small: "
.. tostring(value)
)
end
else
-- item 174
error("field '" .. name
.. "' is not an integer: "
.. tostring(value)
)
end
else
-- item 171
error("field '" .. name
.. "' is not a number: "
.. tostring(value)
)
end
end
function check_not_nil(fields, name)
-- item 157
if fields[name] == nil then
-- item 160
error("field '" .. name .. "' is nil")
end
end
function days_to_secs(days)
-- item 99
return days * 24 * 3600
end
function get_or_request_token(trans_id)
-- item 115
local now = os.time()
local message
local description = ""
-- item 116
if ((globals.token) and (globals.expiry)) and (now < globals.expiry) then
-- item 127
return globals.token
else
-- item 128
local call = {
url = make_paypal_url("/v1/oauth2/token"),
data = "grant_type=client_credentials",
mime = "application/x-www-form-urlencoded",
headers = make_paypal_headers(),
user = get_paypal_user()
}
-- item 129
local result = utils.msgpack_call(
"localhost",
global_cfg.https_sender_port,
call
)
-- item 278
if result then
-- item 130
ej.info(
"paypal_auth",
{url = call.url, trans_id=trans_id}
)
-- item 133
if result.error then
-- item 277
message = result.error
description = result.error_description
-- item 136
ej.info(
"paypal_auth_error",
{
url = call.url, trans_id=trans_id,
error = message,
error_description = description
}
)
-- item 132
return nil
else
-- item 228
if result.access_token then
-- item 131
globals.expiry = now + result.expires_in - 60
globals.token = result.access_token
-- item 127
return globals.token
else
-- item 231
message =
"access_token is missing"
-- item 136
ej.info(
"paypal_auth_error",
{
url = call.url, trans_id=trans_id,
error = message,
error_description = description
}
)
-- item 132
return nil
end
end
else
-- item 279
message = "call to https_sender failed"
-- item 136
ej.info(
"paypal_auth_error",
{
url = call.url, trans_id=trans_id,
error = message,
error_description = description
}
)
-- item 132
return nil
end
end
end
function get_paypal_user()
-- item 280
return external_creds.paypal_user
end
function make_paypal_headers()
-- item 143
local headers = {
"Accept: application/json",
"Accept-Language: en_US"
}
-- item 144
return headers
end
function make_paypal_url(path)
-- item 126
return global_cfg.paypal_address .. path
end
function months_to_secs(months)
-- item 92
local secs_in_month = 3600 * 24 * 365.25 / 12
-- item 93
return utils.round(months * secs_in_month)
end
function pay_card(details, user_id)
-- item 161
check_not_nil(details, "trans_id")
check_not_nil(details, "type")
check_not_nil(details, "number")
check_not_nil(details, "expire_year")
check_not_nil(details, "expire_month")
check_not_nil(details, "first_name")
check_not_nil(details, "last_name")
check_not_nil(details, "total")
check_not_nil(details, "currency")
check_not_nil(details, "description")
-- item 206
check_acc_number(details, "number", 13, 19)
check_int(details, "cvv2", 0, 9999)
-- item 207
check_int(details, "expire_month", 1, 12)
check_int(details, "expire_year", 2016, 2050)
-- item 225
check_card_type(details.type)
-- item 274
local total = utils.print_amount(details.total)
-- item 248
local result
-- item 226
local access_token = get_or_request_token(
details.trans_id
)
-- item 244
if access_token then
-- item 250
local payment = {
intent = "sale",
payer = {
payment_method = "credit_card",
funding_instruments = {
{
credit_card = {
number = details.number,
type = details.type,
expire_month = details.expire_month,
expire_year = details.expire_year,
cvv2 = details.cvv2,
first_name = details.first_name,
last_name = details.last_name
}
}
}
},
transactions = {
{
reference_id = trans_id,
amount = {
total = total,
currency = details.currency
},
description = details.description:sub(1, 127)
}
}
}
-- item 254
local headers = make_paypal_headers()
table.insert(
headers,
"Authorization: Bearer " .. access_token
)
-- item 255
local body = {
url = make_paypal_url("/v1/payments/payment"),
data = payment,
headers = headers
}
-- item 260
ej.info(
"paypal_pay",
{url = body.url, trans_id=details.trans_id,
user_id=user_id,
total=total, currency=details.currency}
)
-- item 256
result = utils.msgpack_call(
"localhost",
global_cfg.https_sender_port,
body
)
-- item 257
if result then
-- item 263
if result.state == "approved" then
-- item 267
ej.info(
"paypal_pay_success",
{url = body.url, trans_id=details.trans_id,
card_type = details.type, user_id = user_id,
total=total, currency=details.currency}
)
else
-- item 265
local err_info = json.encode(result)
.. " trans_id=" .. details.trans_id
-- item 261
ej.info(
"paypal_pay_error",
{url = body.url, trans_id=details.trans_id,
paypal_error=result,
card_type = details.type, user_id = user_id,
total=total, currency=details.currency}
)
-- item 262
log.error("paypal_pay_error: " .. err_info)
end
else
-- item 264
result = {}
-- item 265
local err_info = json.encode(result)
.. " trans_id=" .. details.trans_id
-- item 261
ej.info(
"paypal_pay_error",
{url = body.url, trans_id=details.trans_id,
paypal_error=result,
card_type = details.type, user_id = user_id,
total=total, currency=details.currency}
)
-- item 262
log.error("paypal_pay_error: " .. err_info)
end
else
-- item 246
log.error(
"authorization failed: "
.. details.trans_id)
-- item 249
result = nil
end
-- item 227
return result
end
function px2_calculate_payment(num_users, product_id, pricing)
-- item 322
local result = {}
-- item 323
local users = tonumber(num_users)
local limits = pricing.products[product_id]
-- item 300
if users then
-- item 302
if users >= limits.min_users then
-- item 306
if users <= limits.max_users then
-- item 317
local price = limits.price
-- item 318
result.price = price
-- item 319
local mva_rate = pricing.mva or 0
-- item 295
local total = round_cents(
price * users
)
-- item 313
result.sum = round_cents_down(
total / (1 + mva_rate)
)
-- item 320
result.mva = round_cents(total - result.sum)
result.total = total
else
-- item 309
result.error = "ERR_NUM_USERS_TOO_LARGE"
end
else
-- item 305
result.error = "ERR_NUM_USERS_TOO_LITTLE"
end
else
-- item 301
result.error = "ERR_NUM_USERS_SPECIFY"
end
-- item 299
return result
end
function round_cents(amount)
-- item 69
return utils.round(amount, 2)
end
function round_cents_down(amount)
-- item 337
local result = math.floor(amount * 100) / 100
-- item 338
return result
end
function take_positive(number)
-- item 86
return math.max(0, number)
end
module = {
calculate_payment = calculate_payment,
px2_calculate_payment = px2_calculate_payment,
pay_card = pay_card
}
return module
|
--[[
Communications Options Tab for NavComp control screen
]]
function navcomp.ui.control:CreateCommunicationsTab ()
local confirmBuddyToggle = iup.stationtoggle {title=" Confirm Buddy/Guild Member before receiving data", fgcolor=navcomp.ui.fgcolor}
local commTab = iup.pdasubframe_nomargin {
iup.hbox {
iup.fill {size = 5},
iup.vbox {
iup.fill {size = 15},
iup.label {title="Communications Options", font=navcomp.ui.font, expand = "HORIZONTAL"},
iup.hbox {
confirmBuddyToggle;
},
iup.fill {};
expand = "YES"
},
iup.fill {size = 5};
expand = "YES"
};
tabtitle="Communications",
font=navcomp.ui.font,
expand = "YES"
}
function commTab:Initialize ()
confirmBuddyToggle.value = navcomp.ui:GetOnOffSetting (navcomp.data.confirmBuddyCom)
end
commTab:Initialize ()
function commTab:GetConfirmBuddy ()
return confirmBuddyToggle.value == "ON"
end
return commTab
end |
--
-- Created by IntelliJ IDEA.
-- User: nander
-- Date: 21/04/2018
-- Time: 17:19
-- To change this template use File | Settings | File Templates.
--
local R = {}
local font = love.graphics.newFont(20)
local fonts = {}
local fontData = require "assets.fonts.settings"
for k, v in pairs(fontData) do
fonts[k] = love.graphics.newFont("assets/fonts/" .. v.font, v.size)
end
R.renderEventCard = function(card, x, y, scale, building) --named card for copy-paste reasons.
love.graphics.setDefaultFilter("linear", "linear", 2)
love.graphics.push()
love.graphics.scale(scale)
love.graphics.setColor(1, 1, 1)
love.graphics.draw(ICONS["eventCard"].image, x / scale, y / scale, 0)
love.graphics.setColor(0, 0, 0)
local pfont = love.graphics.getFont()
love.graphics.setFont(font)
if card.costs and card.costs.value then
love.graphics.setColor(1, 1, 1)
if card.costs.type == "money" then
love.graphics.draw(ICONS["field-money"].image, x / scale - 2, y / scale - 2, 0, 0.2)
end
if card.costs and card.costs.type == "population" then
love.graphics.draw(ICONS["population"].image, x / scale - 2, y / scale - 2, 0, 0.2)
end
if card.costs and card.costs.type == "happiness" then
love.graphics.draw(ICONS["happiness"].image, x / scale - 2, y / scale - 2, 0, 0.2)
end
love.graphics.print(card.costs.value, (x) / scale + 30, (y) / scale + 8)
end
love.graphics.setColor(0, 0, 0)
if card.requirements then
love.graphics.setFont(fonts["cardSectionTitle"])
if #card.requirements > 0 then
love.graphics.print("Requires", (x) / scale + 40, (y) / scale + 38)
end
love.graphics.setFont(fonts["cardText"])
for i, requirement in ipairs(card.requirements) do
if i == 1 then
love.graphics.print(scripts.helpers.calculations.requirementToString(requirement), (x) / scale + 40, (y) / scale + 38 + 20 * i)
end
end
end
if card.effects then
love.graphics.setFont(fonts["cardSectionTitle"])
love.graphics.print("Effects", (x) / scale + 15, (y) / scale + 250)
love.graphics.setFont(fonts["cardText"])
for i, effect in ipairs(card.effects) do
love.graphics.print(scripts.helpers.calculations.effectToString(effect), (x) / scale + 15, (y) / scale + 250 + 20 * i)
end
end
love.graphics.setColor(1, 1, 1)
love.graphics.setFont(fonts["cardTitle"])
love.graphics.print(card.name, x / scale + 80, (y) / scale + 5)
love.graphics.pop()
love.graphics.setDefaultFilter("nearest", "nearest")
love.graphics.setFont(pfont)
end
R.cardBack = function(card, x, y, scale, building) --named card for copy-paste reasons.
love.graphics.push()
love.graphics.scale(scale)
love.graphics.setColor(1, 1, 1)
love.graphics.draw(ICONS["backCard"].image, x / scale, y / scale, 0)
love.graphics.setColor(1, 1, 1)
love.graphics.setFont(fonts["cardText2"])
love.graphics.print(card.name, x / scale + 70, (y) / scale + 120)
love.graphics.pop()
end
R.renderBuilding = function(card, x, y, scale, building) --named card for copy-paste reasons.
love.graphics.setDefaultFilter("linear", "linear", 2)
love.graphics.push()
love.graphics.scale(scale)
love.graphics.setColor(1, 1, 1)
love.graphics.draw(ICONS["buildingHover"].image, x / scale, y / scale, 0)
love.graphics.setColor(0, 0, 0)
local pfont = love.graphics.getFont()
love.graphics.setFont(font)
if card.effects then
love.graphics.setFont(fonts["cardSectionTitle"])
love.graphics.print("Effects", (x) / scale + 10, (y) / scale + 190)
love.graphics.setFont(fonts["cardText"])
j = 0
for i, effect in ipairs(card.effects) do
local s = scripts.helpers.calculations.effectToString(effect)
for z in s:gmatch("[^\r\n]+") do
love.graphics.print(z, (x) / scale + 10, (y) / scale + 210 + 20 * j)
j = j + 1
end
end
end
if building then
love.graphics.setColor(1, 1, 1)
local b = building
love.graphics.push()
love.graphics.scale(1.5)
GFX[b.asset]:drawDirect(x / scale / 1.5 + 100, y / scale / 1.5 + 80, 0)
love.graphics.pop()
love.graphics.setColor(0, 0, 0)
end
love.graphics.setColor(1, 1, 1)
love.graphics.setFont(fonts["cardTitle"])
love.graphics.print(card.name, x / scale + 80, (y) / scale + 5)
love.graphics.pop()
love.graphics.setDefaultFilter("nearest", "nearest")
love.graphics.setFont(pfont)
end
R.renderCreeper = function(card, x, y, scale)
love.graphics.setDefaultFilter("linear", "linear", 2)
love.graphics.push()
love.graphics.scale(scale)
love.graphics.draw(ICONS["creeperCard"].image, x / scale, y / scale, 0)
love.graphics.setColor(0, 0, 0)
local pfont = love.graphics.getFont()
love.graphics.setFont(font)
love.graphics.setColor(0, 0, 0)
if card.requirements then
if #card.requirements > 0 then
love.graphics.setFont(fonts["cardSectionTitle"])
love.graphics.print("Requires", (x) / scale + 40, (y) / scale + 38)
end
love.graphics.setFont(fonts["cardText"])
for i, requirement in ipairs(card.requirements) do
if i == 1 then
love.graphics.print(scripts.helpers.calculations.requirementToString(requirement), (x) / scale + 40, (y) / scale + 38 + 20 * i)
end
end
end
if card.effects then
love.graphics.setFont(fonts["cardSectionTitle"])
love.graphics.print("Effects", (x) / scale + 15, (y) / scale + 250)
love.graphics.setFont(fonts["cardText"])
for i, effect in ipairs(card.effects) do
love.graphics.print(scripts.helpers.calculations.effectToString(effect), (x) / scale + 15, (y) / scale + 250 + 20 * i)
end
end
love.graphics.setColor(1, 1, 1)
love.graphics.setFont(fonts["cardTitle"])
love.graphics.print(card.name, x / scale + 80, (y) / scale + 5)
love.graphics.pop()
love.graphics.setDefaultFilter("nearest", "nearest")
love.graphics.setFont(pfont)
end
R.renderBuildingCard = function(card, x, y, scale, building)
love.graphics.setDefaultFilter("linear", "linear", 2)
love.graphics.push()
love.graphics.scale(scale)
love.graphics.setColor(1, 1, 1)
love.graphics.draw(ICONS["buildingCard"].image, x / scale, y / scale, 0)
love.graphics.setColor(0, 0, 0)
local pfont = love.graphics.getFont()
love.graphics.setFont(font)
if card.costs and card.costs.value then
love.graphics.setColor(1, 1, 1)
if card.costs.type == "money" then
love.graphics.draw(ICONS["field-money"].image, x / scale - 2, y / scale - 2, 0, 0.2)
end
if card.costs and card.costs.type == "population" then
love.graphics.draw(ICONS["population"].image, x / scale - 2, y / scale - 2, 0, 0.2)
end
if card.costs and card.costs.type == "happiness" then
love.graphics.draw(ICONS["happiness"].image, x / scale - 2, y / scale - 2, 0, 0.2)
end
love.graphics.print(card.costs.value, (x) / scale + 30, (y) / scale + 8)
end
love.graphics.setColor(0, 0, 0)
if card.requirements then
if #card.requirements > 0 then
love.graphics.setFont(fonts["cardSectionTitle"])
love.graphics.print("Requires", (x) / scale + 40, (y) / scale + 38)
end
love.graphics.setFont(fonts["cardText"])
for i, requirement in ipairs(card.requirements) do
if i == 1 then
love.graphics.print(scripts.helpers.calculations.requirementToString(requirement), (x) / scale + 40, (y) / scale + 38 + 20 * i)
end
end
end
if card.effects then
love.graphics.setFont(fonts["cardSectionTitle"])
love.graphics.print("Effects", (x) / scale + 15, (y) / scale + 250)
love.graphics.setFont(fonts["cardText"])
for i, effect in ipairs(card.effects) do
love.graphics.print(scripts.helpers.calculations.effectToString(effect), (x) / scale + 15, (y) / scale + 250 + 20 * i)
end
end
if building then
love.graphics.setColor(1, 1, 1)
local b = building
love.graphics.push()
love.graphics.scale(1.5)
GFX[b.asset]:drawDirect(x / scale / 1.5 + 100, y / scale / 1.5 + 120, 0)
love.graphics.pop()
love.graphics.setColor(0, 0, 0)
end
love.graphics.setColor(1, 1, 1)
love.graphics.setFont(fonts["cardTitle"])
love.graphics.print(card.name, x / scale + 80, (y) / scale + 5)
love.graphics.pop()
love.graphics.setDefaultFilter("nearest", "nearest")
love.graphics.setFont(pfont)
end
R.renderCard = function(card, x, y, scale, ib)
if ib then
R.renderBuilding(card, x, y, scale, card)
return
end
if card.is_creeper then
R.renderCreeper(card, x, y, scale)
return
end
local isBuilding = false
if card.effects then
for _, effect in ipairs(card.effects) do
if effect.type == "place_building" then isBuilding = effect.building end
end
end
if isBuilding then
R.renderBuildingCard(card, x, y, scale, scripts.gameobjects.buildings[isBuilding])
return
end
if card.name == "" then
-- draw empty card
R.cardBack(card, x, y, scale, nil) --named card for copy-paste reasons.
else
R.renderEventCard(card, x, y, scale, nil) --named card for copy-paste reasons.
end
end
return R |
--- GENERATED CODE - DO NOT MODIFY
-- AWS IoT 1-Click Devices Service (devices-2018-05-14)
local M = {}
M.metadata = {
api_version = "2018-05-14",
json_version = "1.1",
protocol = "rest-json",
checksum_format = "",
endpoint_prefix = "devices.iot1click",
service_abbreviation = "",
service_full_name = "AWS IoT 1-Click Devices Service",
signature_version = "v4",
target_prefix = "",
timestamp_format = "",
global_endpoint = "",
uid = "devices-2018-05-14",
}
local keys = {}
local asserts = {}
keys.InvalidRequestException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertInvalidRequestException(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvalidRequestException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.InvalidRequestException[k], "InvalidRequestException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvalidRequestException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>The 400 error message returned by the web server.</p>
-- * Code [__string] <p>400</p>
-- @return InvalidRequestException structure as a key-value pair table
function M.InvalidRequestException(args)
assert(args, "You must provide an argument table when creating InvalidRequestException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertInvalidRequestException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListDevicesRequest = { ["NextToken"] = true, ["DeviceType"] = true, ["MaxResults"] = true, nil }
function asserts.AssertListDevicesRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListDevicesRequest to be of type 'table'")
if struct["NextToken"] then asserts.Assert__string(struct["NextToken"]) end
if struct["DeviceType"] then asserts.Assert__string(struct["DeviceType"]) end
if struct["MaxResults"] then asserts.AssertMaxResults(struct["MaxResults"]) end
for k,_ in pairs(struct) do
assert(keys.ListDevicesRequest[k], "ListDevicesRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListDevicesRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [__string] <p>The token to retrieve the next set of results.</p>
-- * DeviceType [__string] <p>The type of the device, such as "button".</p>
-- * MaxResults [MaxResults] <p>The maximum number of results to return per request. If not set, a default value
-- of 100 is used.</p>
-- @return ListDevicesRequest structure as a key-value pair table
function M.ListDevicesRequest(args)
assert(args, "You must provide an argument table when creating ListDevicesRequest")
local query_args = {
["nextToken"] = args["NextToken"],
["deviceType"] = args["DeviceType"],
["maxResults"] = args["MaxResults"],
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["DeviceType"] = args["DeviceType"],
["MaxResults"] = args["MaxResults"],
}
asserts.AssertListDevicesRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.PreconditionFailedException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertPreconditionFailedException(struct)
assert(struct)
assert(type(struct) == "table", "Expected PreconditionFailedException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.PreconditionFailedException[k], "PreconditionFailedException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type PreconditionFailedException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>An error message explaining the error or its remedy.</p>
-- * Code [__string] <p>412</p>
-- @return PreconditionFailedException structure as a key-value pair table
function M.PreconditionFailedException(args)
assert(args, "You must provide an argument table when creating PreconditionFailedException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertPreconditionFailedException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InitiateDeviceClaimResponse = { ["State"] = true, nil }
function asserts.AssertInitiateDeviceClaimResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected InitiateDeviceClaimResponse to be of type 'table'")
if struct["State"] then asserts.Assert__string(struct["State"]) end
for k,_ in pairs(struct) do
assert(keys.InitiateDeviceClaimResponse[k], "InitiateDeviceClaimResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InitiateDeviceClaimResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * State [__string] <p>The device's final claim state.</p>
-- @return InitiateDeviceClaimResponse structure as a key-value pair table
function M.InitiateDeviceClaimResponse(args)
assert(args, "You must provide an argument table when creating InitiateDeviceClaimResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["State"] = args["State"],
}
asserts.AssertInitiateDeviceClaimResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.RangeNotSatisfiableException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertRangeNotSatisfiableException(struct)
assert(struct)
assert(type(struct) == "table", "Expected RangeNotSatisfiableException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.RangeNotSatisfiableException[k], "RangeNotSatisfiableException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type RangeNotSatisfiableException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>The requested number of results specified by nextToken cannot be
-- satisfied.</p>
-- * Code [__string] <p>416</p>
-- @return RangeNotSatisfiableException structure as a key-value pair table
function M.RangeNotSatisfiableException(args)
assert(args, "You must provide an argument table when creating RangeNotSatisfiableException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertRangeNotSatisfiableException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.FinalizeDeviceClaimRequest = { ["DeviceId"] = true, nil }
function asserts.AssertFinalizeDeviceClaimRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected FinalizeDeviceClaimRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.FinalizeDeviceClaimRequest[k], "FinalizeDeviceClaimRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type FinalizeDeviceClaimRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return FinalizeDeviceClaimRequest structure as a key-value pair table
function M.FinalizeDeviceClaimRequest(args)
assert(args, "You must provide an argument table when creating FinalizeDeviceClaimRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["DeviceId"] = args["DeviceId"],
}
asserts.AssertFinalizeDeviceClaimRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetDeviceMethodsResponse = { ["DeviceMethods"] = true, nil }
function asserts.AssertGetDeviceMethodsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetDeviceMethodsResponse to be of type 'table'")
if struct["DeviceMethods"] then asserts.Assert__listOfDeviceMethod(struct["DeviceMethods"]) end
for k,_ in pairs(struct) do
assert(keys.GetDeviceMethodsResponse[k], "GetDeviceMethodsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetDeviceMethodsResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceMethods [__listOfDeviceMethod] <p>List of available device APIs.</p>
-- @return GetDeviceMethodsResponse structure as a key-value pair table
function M.GetDeviceMethodsResponse(args)
assert(args, "You must provide an argument table when creating GetDeviceMethodsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["DeviceMethods"] = args["DeviceMethods"],
}
asserts.AssertGetDeviceMethodsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeviceEvent = { ["Device"] = true, ["StdEvent"] = true, nil }
function asserts.AssertDeviceEvent(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeviceEvent to be of type 'table'")
if struct["Device"] then asserts.AssertDevice(struct["Device"]) end
if struct["StdEvent"] then asserts.Assert__string(struct["StdEvent"]) end
for k,_ in pairs(struct) do
assert(keys.DeviceEvent[k], "DeviceEvent contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeviceEvent
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Device [Device] <p>An object representing the device associated with the event.</p>
-- * StdEvent [__string] <p>A serialized JSON object representing the device-type specific event.</p>
-- @return DeviceEvent structure as a key-value pair table
function M.DeviceEvent(args)
assert(args, "You must provide an argument table when creating DeviceEvent")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Device"] = args["Device"],
["StdEvent"] = args["StdEvent"],
}
asserts.AssertDeviceEvent(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Empty = { nil }
function asserts.AssertEmpty(struct)
assert(struct)
assert(type(struct) == "table", "Expected Empty to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.Empty[k], "Empty contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Empty
-- <p>On success, an empty object is returned.</p>
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return Empty structure as a key-value pair table
function M.Empty(args)
assert(args, "You must provide an argument table when creating Empty")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertEmpty(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeviceClaimResponse = { ["State"] = true, nil }
function asserts.AssertDeviceClaimResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeviceClaimResponse to be of type 'table'")
if struct["State"] then asserts.Assert__string(struct["State"]) end
for k,_ in pairs(struct) do
assert(keys.DeviceClaimResponse[k], "DeviceClaimResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeviceClaimResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * State [__string] <p>The device's final claim state.</p>
-- @return DeviceClaimResponse structure as a key-value pair table
function M.DeviceClaimResponse(args)
assert(args, "You must provide an argument table when creating DeviceClaimResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["State"] = args["State"],
}
asserts.AssertDeviceClaimResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UpdateDeviceStateRequest = { ["Enabled"] = true, ["DeviceId"] = true, nil }
function asserts.AssertUpdateDeviceStateRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected UpdateDeviceStateRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["Enabled"] then asserts.Assert__boolean(struct["Enabled"]) end
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.UpdateDeviceStateRequest[k], "UpdateDeviceStateRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UpdateDeviceStateRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Enabled [__boolean] <p>If true, the device is enabled. If false, the device is
-- disabled.</p>
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return UpdateDeviceStateRequest structure as a key-value pair table
function M.UpdateDeviceStateRequest(args)
assert(args, "You must provide an argument table when creating UpdateDeviceStateRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["Enabled"] = args["Enabled"],
["DeviceId"] = args["DeviceId"],
}
asserts.AssertUpdateDeviceStateRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListDeviceEventsResponse = { ["NextToken"] = true, ["Events"] = true, nil }
function asserts.AssertListDeviceEventsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListDeviceEventsResponse to be of type 'table'")
if struct["NextToken"] then asserts.Assert__string(struct["NextToken"]) end
if struct["Events"] then asserts.Assert__listOfDeviceEvent(struct["Events"]) end
for k,_ in pairs(struct) do
assert(keys.ListDeviceEventsResponse[k], "ListDeviceEventsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListDeviceEventsResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [__string] <p>The token to retrieve the next set of results.</p>
-- * Events [__listOfDeviceEvent] <p>An array of zero or more elements describing the event(s) associated with the
-- device.</p>
-- @return ListDeviceEventsResponse structure as a key-value pair table
function M.ListDeviceEventsResponse(args)
assert(args, "You must provide an argument table when creating ListDeviceEventsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["Events"] = args["Events"],
}
asserts.AssertListDeviceEventsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ResourceNotFoundException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertResourceNotFoundException(struct)
assert(struct)
assert(type(struct) == "table", "Expected ResourceNotFoundException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.ResourceNotFoundException[k], "ResourceNotFoundException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ResourceNotFoundException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>The requested device could not be found.</p>
-- * Code [__string] <p>404</p>
-- @return ResourceNotFoundException structure as a key-value pair table
function M.ResourceNotFoundException(args)
assert(args, "You must provide an argument table when creating ResourceNotFoundException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertResourceNotFoundException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UnclaimDeviceResponse = { ["State"] = true, nil }
function asserts.AssertUnclaimDeviceResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected UnclaimDeviceResponse to be of type 'table'")
if struct["State"] then asserts.Assert__string(struct["State"]) end
for k,_ in pairs(struct) do
assert(keys.UnclaimDeviceResponse[k], "UnclaimDeviceResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UnclaimDeviceResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * State [__string] <p>The device's final claim state.</p>
-- @return UnclaimDeviceResponse structure as a key-value pair table
function M.UnclaimDeviceResponse(args)
assert(args, "You must provide an argument table when creating UnclaimDeviceResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["State"] = args["State"],
}
asserts.AssertUnclaimDeviceResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListDeviceEventsRequest = { ["ToTimeStamp"] = true, ["NextToken"] = true, ["DeviceId"] = true, ["MaxResults"] = true, ["FromTimeStamp"] = true, nil }
function asserts.AssertListDeviceEventsRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListDeviceEventsRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
assert(struct["FromTimeStamp"], "Expected key FromTimeStamp to exist in table")
assert(struct["ToTimeStamp"], "Expected key ToTimeStamp to exist in table")
if struct["ToTimeStamp"] then asserts.Assert__timestampIso8601(struct["ToTimeStamp"]) end
if struct["NextToken"] then asserts.Assert__string(struct["NextToken"]) end
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
if struct["MaxResults"] then asserts.AssertMaxResults(struct["MaxResults"]) end
if struct["FromTimeStamp"] then asserts.Assert__timestampIso8601(struct["FromTimeStamp"]) end
for k,_ in pairs(struct) do
assert(keys.ListDeviceEventsRequest[k], "ListDeviceEventsRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListDeviceEventsRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * ToTimeStamp [__timestampIso8601] <p>The end date for the device event query, in ISO8061 format. For example,
-- 2018-03-28T15:45:12.880Z
-- </p>
-- * NextToken [__string] <p>The token to retrieve the next set of results.</p>
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- * MaxResults [MaxResults] <p>The maximum number of results to return per request. If not set, a default value
-- of 100 is used.</p>
-- * FromTimeStamp [__timestampIso8601] <p>The start date for the device event query, in ISO8061 format. For example,
-- 2018-03-28T15:45:12.880Z
-- </p>
-- Required key: DeviceId
-- Required key: FromTimeStamp
-- Required key: ToTimeStamp
-- @return ListDeviceEventsRequest structure as a key-value pair table
function M.ListDeviceEventsRequest(args)
assert(args, "You must provide an argument table when creating ListDeviceEventsRequest")
local query_args = {
["toTimeStamp"] = args["ToTimeStamp"],
["nextToken"] = args["NextToken"],
["maxResults"] = args["MaxResults"],
["fromTimeStamp"] = args["FromTimeStamp"],
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["ToTimeStamp"] = args["ToTimeStamp"],
["NextToken"] = args["NextToken"],
["DeviceId"] = args["DeviceId"],
["MaxResults"] = args["MaxResults"],
["FromTimeStamp"] = args["FromTimeStamp"],
}
asserts.AssertListDeviceEventsRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeviceMethod = { ["MethodName"] = true, ["DeviceType"] = true, nil }
function asserts.AssertDeviceMethod(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeviceMethod to be of type 'table'")
if struct["MethodName"] then asserts.Assert__string(struct["MethodName"]) end
if struct["DeviceType"] then asserts.Assert__string(struct["DeviceType"]) end
for k,_ in pairs(struct) do
assert(keys.DeviceMethod[k], "DeviceMethod contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeviceMethod
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * MethodName [__string] <p>The name of the method applicable to the deviceType.</p>
-- * DeviceType [__string] <p>The type of the device, such as "button".</p>
-- @return DeviceMethod structure as a key-value pair table
function M.DeviceMethod(args)
assert(args, "You must provide an argument table when creating DeviceMethod")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["MethodName"] = args["MethodName"],
["DeviceType"] = args["DeviceType"],
}
asserts.AssertDeviceMethod(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InvokeDeviceMethodResponse = { ["DeviceMethodResponse"] = true, nil }
function asserts.AssertInvokeDeviceMethodResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvokeDeviceMethodResponse to be of type 'table'")
if struct["DeviceMethodResponse"] then asserts.Assert__string(struct["DeviceMethodResponse"]) end
for k,_ in pairs(struct) do
assert(keys.InvokeDeviceMethodResponse[k], "InvokeDeviceMethodResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvokeDeviceMethodResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceMethodResponse [__string] <p>A JSON encoded string containing the device method response.</p>
-- @return InvokeDeviceMethodResponse structure as a key-value pair table
function M.InvokeDeviceMethodResponse(args)
assert(args, "You must provide an argument table when creating InvokeDeviceMethodResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["DeviceMethodResponse"] = args["DeviceMethodResponse"],
}
asserts.AssertInvokeDeviceMethodResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ClaimDevicesByClaimCodeResponse = { ["ClaimCode"] = true, ["Total"] = true, nil }
function asserts.AssertClaimDevicesByClaimCodeResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ClaimDevicesByClaimCodeResponse to be of type 'table'")
if struct["ClaimCode"] then asserts.Assert__stringMin12Max40(struct["ClaimCode"]) end
if struct["Total"] then asserts.Assert__integer(struct["Total"]) end
for k,_ in pairs(struct) do
assert(keys.ClaimDevicesByClaimCodeResponse[k], "ClaimDevicesByClaimCodeResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ClaimDevicesByClaimCodeResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * ClaimCode [__stringMin12Max40] <p>The claim code provided by the device manufacturer.</p>
-- * Total [__integer] <p>The total number of devices associated with the claim code that has been processed
-- in the claim request.</p>
-- @return ClaimDevicesByClaimCodeResponse structure as a key-value pair table
function M.ClaimDevicesByClaimCodeResponse(args)
assert(args, "You must provide an argument table when creating ClaimDevicesByClaimCodeResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["ClaimCode"] = args["ClaimCode"],
["Total"] = args["Total"],
}
asserts.AssertClaimDevicesByClaimCodeResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Device = { ["Attributes"] = true, ["Type"] = true, ["DeviceId"] = true, nil }
function asserts.AssertDevice(struct)
assert(struct)
assert(type(struct) == "table", "Expected Device to be of type 'table'")
if struct["Attributes"] then asserts.AssertAttributes(struct["Attributes"]) end
if struct["Type"] then asserts.Assert__string(struct["Type"]) end
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.Device[k], "Device contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Device
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [Attributes] <p>The user specified attributes associated with the device for an event.</p>
-- * Type [__string] <p>The device type, such as "button".</p>
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- @return Device structure as a key-value pair table
function M.Device(args)
assert(args, "You must provide an argument table when creating Device")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["Type"] = args["Type"],
["DeviceId"] = args["DeviceId"],
}
asserts.AssertDevice(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DescribeDeviceRequest = { ["DeviceId"] = true, nil }
function asserts.AssertDescribeDeviceRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected DescribeDeviceRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.DescribeDeviceRequest[k], "DescribeDeviceRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DescribeDeviceRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return DescribeDeviceRequest structure as a key-value pair table
function M.DescribeDeviceRequest(args)
assert(args, "You must provide an argument table when creating DescribeDeviceRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["DeviceId"] = args["DeviceId"],
}
asserts.AssertDescribeDeviceRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeviceEventsResponse = { ["NextToken"] = true, ["Events"] = true, nil }
function asserts.AssertDeviceEventsResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeviceEventsResponse to be of type 'table'")
if struct["NextToken"] then asserts.Assert__string(struct["NextToken"]) end
if struct["Events"] then asserts.Assert__listOfDeviceEvent(struct["Events"]) end
for k,_ in pairs(struct) do
assert(keys.DeviceEventsResponse[k], "DeviceEventsResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeviceEventsResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [__string] <p>The token to retrieve the next set of results.</p>
-- * Events [__listOfDeviceEvent] <p>An array of zero or more elements describing the event(s) associated with the
-- device.</p>
-- @return DeviceEventsResponse structure as a key-value pair table
function M.DeviceEventsResponse(args)
assert(args, "You must provide an argument table when creating DeviceEventsResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["Events"] = args["Events"],
}
asserts.AssertDeviceEventsResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.GetDeviceMethodsRequest = { ["DeviceId"] = true, nil }
function asserts.AssertGetDeviceMethodsRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected GetDeviceMethodsRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.GetDeviceMethodsRequest[k], "GetDeviceMethodsRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type GetDeviceMethodsRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return GetDeviceMethodsRequest structure as a key-value pair table
function M.GetDeviceMethodsRequest(args)
assert(args, "You must provide an argument table when creating GetDeviceMethodsRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["DeviceId"] = args["DeviceId"],
}
asserts.AssertGetDeviceMethodsRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UnclaimDeviceRequest = { ["DeviceId"] = true, nil }
function asserts.AssertUnclaimDeviceRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected UnclaimDeviceRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.UnclaimDeviceRequest[k], "UnclaimDeviceRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UnclaimDeviceRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return UnclaimDeviceRequest structure as a key-value pair table
function M.UnclaimDeviceRequest(args)
assert(args, "You must provide an argument table when creating UnclaimDeviceRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["DeviceId"] = args["DeviceId"],
}
asserts.AssertUnclaimDeviceRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InternalFailureException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertInternalFailureException(struct)
assert(struct)
assert(type(struct) == "table", "Expected InternalFailureException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.InternalFailureException[k], "InternalFailureException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InternalFailureException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>The 500 error message returned by the web server.</p>
-- * Code [__string] <p>500</p>
-- @return InternalFailureException structure as a key-value pair table
function M.InternalFailureException(args)
assert(args, "You must provide an argument table when creating InternalFailureException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertInternalFailureException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ClaimDevicesByClaimCodeRequest = { ["ClaimCode"] = true, nil }
function asserts.AssertClaimDevicesByClaimCodeRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected ClaimDevicesByClaimCodeRequest to be of type 'table'")
assert(struct["ClaimCode"], "Expected key ClaimCode to exist in table")
if struct["ClaimCode"] then asserts.Assert__string(struct["ClaimCode"]) end
for k,_ in pairs(struct) do
assert(keys.ClaimDevicesByClaimCodeRequest[k], "ClaimDevicesByClaimCodeRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ClaimDevicesByClaimCodeRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * ClaimCode [__string] <p>The claim code, starting with "C-", as provided by the device manufacturer.</p>
-- Required key: ClaimCode
-- @return ClaimDevicesByClaimCodeRequest structure as a key-value pair table
function M.ClaimDevicesByClaimCodeRequest(args)
assert(args, "You must provide an argument table when creating ClaimDevicesByClaimCodeRequest")
local query_args = {
}
local uri_args = {
["{claimCode}"] = args["ClaimCode"],
}
local header_args = {
}
local all_args = {
["ClaimCode"] = args["ClaimCode"],
}
asserts.AssertClaimDevicesByClaimCodeRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ListDevicesResponse = { ["NextToken"] = true, ["Devices"] = true, nil }
function asserts.AssertListDevicesResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected ListDevicesResponse to be of type 'table'")
if struct["NextToken"] then asserts.Assert__string(struct["NextToken"]) end
if struct["Devices"] then asserts.Assert__listOfDeviceDescription(struct["Devices"]) end
for k,_ in pairs(struct) do
assert(keys.ListDevicesResponse[k], "ListDevicesResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ListDevicesResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * NextToken [__string] <p>The token to retrieve the next set of results.</p>
-- * Devices [__listOfDeviceDescription] <p>A list of devices.</p>
-- @return ListDevicesResponse structure as a key-value pair table
function M.ListDevicesResponse(args)
assert(args, "You must provide an argument table when creating ListDevicesResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["NextToken"] = args["NextToken"],
["Devices"] = args["Devices"],
}
asserts.AssertListDevicesResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.Attributes = { nil }
function asserts.AssertAttributes(struct)
assert(struct)
assert(type(struct) == "table", "Expected Attributes to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.Attributes[k], "Attributes contains unknown key " .. tostring(k))
end
end
--- Create a structure of type Attributes
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return Attributes structure as a key-value pair table
function M.Attributes(args)
assert(args, "You must provide an argument table when creating Attributes")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertAttributes(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ResourceConflictException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertResourceConflictException(struct)
assert(struct)
assert(type(struct) == "table", "Expected ResourceConflictException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.ResourceConflictException[k], "ResourceConflictException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ResourceConflictException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>An error message explaining the error or its remedy.</p>
-- * Code [__string] <p>409</p>
-- @return ResourceConflictException structure as a key-value pair table
function M.ResourceConflictException(args)
assert(args, "You must provide an argument table when creating ResourceConflictException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertResourceConflictException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DeviceDescription = { ["Attributes"] = true, ["Type"] = true, ["Enabled"] = true, ["DeviceId"] = true, ["RemainingLife"] = true, nil }
function asserts.AssertDeviceDescription(struct)
assert(struct)
assert(type(struct) == "table", "Expected DeviceDescription to be of type 'table'")
if struct["Attributes"] then asserts.AssertDeviceAttributes(struct["Attributes"]) end
if struct["Type"] then asserts.Assert__string(struct["Type"]) end
if struct["Enabled"] then asserts.Assert__boolean(struct["Enabled"]) end
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
if struct["RemainingLife"] then asserts.Assert__doubleMin0Max100(struct["RemainingLife"]) end
for k,_ in pairs(struct) do
assert(keys.DeviceDescription[k], "DeviceDescription contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DeviceDescription
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Attributes [DeviceAttributes] <p>An array of zero or more elements of DeviceAttribute objects
-- providing user specified device attributes.</p>
-- * Type [__string] <p>The type of the device, such as "button".</p>
-- * Enabled [__boolean] <p>A Boolean value indicating whether or not the device is enabled.</p>
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- * RemainingLife [__doubleMin0Max100] <p>A value between 0 and 1 inclusive, representing the fraction of life remaining for
-- the device.</p>
-- @return DeviceDescription structure as a key-value pair table
function M.DeviceDescription(args)
assert(args, "You must provide an argument table when creating DeviceDescription")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Attributes"] = args["Attributes"],
["Type"] = args["Type"],
["Enabled"] = args["Enabled"],
["DeviceId"] = args["DeviceId"],
["RemainingLife"] = args["RemainingLife"],
}
asserts.AssertDeviceDescription(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.UpdateDeviceStateResponse = { nil }
function asserts.AssertUpdateDeviceStateResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected UpdateDeviceStateResponse to be of type 'table'")
for k,_ in pairs(struct) do
assert(keys.UpdateDeviceStateResponse[k], "UpdateDeviceStateResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type UpdateDeviceStateResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- @return UpdateDeviceStateResponse structure as a key-value pair table
function M.UpdateDeviceStateResponse(args)
assert(args, "You must provide an argument table when creating UpdateDeviceStateResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
}
asserts.AssertUpdateDeviceStateResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.FinalizeDeviceClaimResponse = { ["State"] = true, nil }
function asserts.AssertFinalizeDeviceClaimResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected FinalizeDeviceClaimResponse to be of type 'table'")
if struct["State"] then asserts.Assert__string(struct["State"]) end
for k,_ in pairs(struct) do
assert(keys.FinalizeDeviceClaimResponse[k], "FinalizeDeviceClaimResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type FinalizeDeviceClaimResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * State [__string] <p>The device's final claim state.</p>
-- @return FinalizeDeviceClaimResponse structure as a key-value pair table
function M.FinalizeDeviceClaimResponse(args)
assert(args, "You must provide an argument table when creating FinalizeDeviceClaimResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["State"] = args["State"],
}
asserts.AssertFinalizeDeviceClaimResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InvokeDeviceMethodRequest = { ["DeviceMethod"] = true, ["DeviceMethodParameters"] = true, ["DeviceId"] = true, nil }
function asserts.AssertInvokeDeviceMethodRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected InvokeDeviceMethodRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["DeviceMethod"] then asserts.AssertDeviceMethod(struct["DeviceMethod"]) end
if struct["DeviceMethodParameters"] then asserts.Assert__string(struct["DeviceMethodParameters"]) end
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.InvokeDeviceMethodRequest[k], "InvokeDeviceMethodRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InvokeDeviceMethodRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceMethod [DeviceMethod] <p>The device method to invoke.</p>
-- * DeviceMethodParameters [__string] <p>A JSON encoded string containing the device method request parameters.</p>
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return InvokeDeviceMethodRequest structure as a key-value pair table
function M.InvokeDeviceMethodRequest(args)
assert(args, "You must provide an argument table when creating InvokeDeviceMethodRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["DeviceMethod"] = args["DeviceMethod"],
["DeviceMethodParameters"] = args["DeviceMethodParameters"],
["DeviceId"] = args["DeviceId"],
}
asserts.AssertInvokeDeviceMethodRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.DescribeDeviceResponse = { ["DeviceDescription"] = true, nil }
function asserts.AssertDescribeDeviceResponse(struct)
assert(struct)
assert(type(struct) == "table", "Expected DescribeDeviceResponse to be of type 'table'")
if struct["DeviceDescription"] then asserts.AssertDeviceDescription(struct["DeviceDescription"]) end
for k,_ in pairs(struct) do
assert(keys.DescribeDeviceResponse[k], "DescribeDeviceResponse contains unknown key " .. tostring(k))
end
end
--- Create a structure of type DescribeDeviceResponse
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceDescription [DeviceDescription] <p>Device details.</p>
-- @return DescribeDeviceResponse structure as a key-value pair table
function M.DescribeDeviceResponse(args)
assert(args, "You must provide an argument table when creating DescribeDeviceResponse")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["DeviceDescription"] = args["DeviceDescription"],
}
asserts.AssertDescribeDeviceResponse(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.ForbiddenException = { ["Message"] = true, ["Code"] = true, nil }
function asserts.AssertForbiddenException(struct)
assert(struct)
assert(type(struct) == "table", "Expected ForbiddenException to be of type 'table'")
if struct["Message"] then asserts.Assert__string(struct["Message"]) end
if struct["Code"] then asserts.Assert__string(struct["Code"]) end
for k,_ in pairs(struct) do
assert(keys.ForbiddenException[k], "ForbiddenException contains unknown key " .. tostring(k))
end
end
--- Create a structure of type ForbiddenException
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * Message [__string] <p>The 403 error message returned by the web server.</p>
-- * Code [__string] <p>403</p>
-- @return ForbiddenException structure as a key-value pair table
function M.ForbiddenException(args)
assert(args, "You must provide an argument table when creating ForbiddenException")
local query_args = {
}
local uri_args = {
}
local header_args = {
}
local all_args = {
["Message"] = args["Message"],
["Code"] = args["Code"],
}
asserts.AssertForbiddenException(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
keys.InitiateDeviceClaimRequest = { ["DeviceId"] = true, nil }
function asserts.AssertInitiateDeviceClaimRequest(struct)
assert(struct)
assert(type(struct) == "table", "Expected InitiateDeviceClaimRequest to be of type 'table'")
assert(struct["DeviceId"], "Expected key DeviceId to exist in table")
if struct["DeviceId"] then asserts.Assert__string(struct["DeviceId"]) end
for k,_ in pairs(struct) do
assert(keys.InitiateDeviceClaimRequest[k], "InitiateDeviceClaimRequest contains unknown key " .. tostring(k))
end
end
--- Create a structure of type InitiateDeviceClaimRequest
--
-- @param args Table with arguments in key-value form.
-- Valid keys:
-- * DeviceId [__string] <p>The unique identifier of the device.</p>
-- Required key: DeviceId
-- @return InitiateDeviceClaimRequest structure as a key-value pair table
function M.InitiateDeviceClaimRequest(args)
assert(args, "You must provide an argument table when creating InitiateDeviceClaimRequest")
local query_args = {
}
local uri_args = {
["{deviceId}"] = args["DeviceId"],
}
local header_args = {
}
local all_args = {
["DeviceId"] = args["DeviceId"],
}
asserts.AssertInitiateDeviceClaimRequest(all_args)
return {
all = all_args,
query = query_args,
uri = uri_args,
headers = header_args,
}
end
function asserts.Assert__stringMin12Max40(str)
assert(str)
assert(type(str) == "string", "Expected __stringMin12Max40 to be of type 'string'")
assert(#str <= 40, "Expected string to be max 40 characters")
assert(#str >= 12, "Expected string to be min 12 characters")
end
--
function M.__stringMin12Max40(str)
asserts.Assert__stringMin12Max40(str)
return str
end
function asserts.Assert__string(str)
assert(str)
assert(type(str) == "string", "Expected __string to be of type 'string'")
end
--
function M.__string(str)
asserts.Assert__string(str)
return str
end
function asserts.Assert__doubleMin0Max100(double)
assert(double)
assert(type(double) == "number", "Expected __doubleMin0Max100 to be of type 'number'")
end
function M.__doubleMin0Max100(double)
asserts.Assert__doubleMin0Max100(double)
return double
end
function asserts.Assert__double(double)
assert(double)
assert(type(double) == "number", "Expected __double to be of type 'number'")
end
function M.__double(double)
asserts.Assert__double(double)
return double
end
function asserts.Assert__long(long)
assert(long)
assert(type(long) == "number", "Expected __long to be of type 'number'")
assert(long % 1 == 0, "Expected a whole integer number")
end
function M.__long(long)
asserts.Assert__long(long)
return long
end
function asserts.AssertMaxResults(integer)
assert(integer)
assert(type(integer) == "number", "Expected MaxResults to be of type 'number'")
assert(integer % 1 == 0, "Expected a while integer number")
assert(integer <= 250, "Expected integer to be max 250")
assert(integer >= 1, "Expected integer to be min 1")
end
function M.MaxResults(integer)
asserts.AssertMaxResults(integer)
return integer
end
function asserts.Assert__integer(integer)
assert(integer)
assert(type(integer) == "number", "Expected __integer to be of type 'number'")
assert(integer % 1 == 0, "Expected a while integer number")
end
function M.__integer(integer)
asserts.Assert__integer(integer)
return integer
end
function asserts.Assert__boolean(boolean)
assert(boolean)
assert(type(boolean) == "boolean", "Expected __boolean to be of type 'boolean'")
end
function M.__boolean(boolean)
asserts.Assert__boolean(boolean)
return boolean
end
function asserts.AssertDeviceAttributes(map)
assert(map)
assert(type(map) == "table", "Expected DeviceAttributes to be of type 'table'")
for k,v in pairs(map) do
asserts.Assert__string(k)
asserts.Assert__string(v)
end
end
function M.DeviceAttributes(map)
asserts.AssertDeviceAttributes(map)
return map
end
function asserts.Assert__timestampIso8601(timestamp)
assert(timestamp)
assert(type(timestamp) == "string", "Expected __timestampIso8601 to be of type 'string'")
end
function M.__timestampIso8601(timestamp)
asserts.Assert__timestampIso8601(timestamp)
return timestamp
end
function asserts.Assert__timestampUnix(timestamp)
assert(timestamp)
assert(type(timestamp) == "string", "Expected __timestampUnix to be of type 'string'")
end
function M.__timestampUnix(timestamp)
asserts.Assert__timestampUnix(timestamp)
return timestamp
end
function asserts.Assert__listOfDeviceMethod(list)
assert(list)
assert(type(list) == "table", "Expected __listOfDeviceMethod to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertDeviceMethod(v)
end
end
--
-- List of DeviceMethod objects
function M.__listOfDeviceMethod(list)
asserts.Assert__listOfDeviceMethod(list)
return list
end
function asserts.Assert__listOfDeviceDescription(list)
assert(list)
assert(type(list) == "table", "Expected __listOfDeviceDescription to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertDeviceDescription(v)
end
end
--
-- List of DeviceDescription objects
function M.__listOfDeviceDescription(list)
asserts.Assert__listOfDeviceDescription(list)
return list
end
function asserts.Assert__listOfDeviceEvent(list)
assert(list)
assert(type(list) == "table", "Expected __listOfDeviceEvent to be of type ''table")
for _,v in ipairs(list) do
asserts.AssertDeviceEvent(v)
end
end
--
-- List of DeviceEvent objects
function M.__listOfDeviceEvent(list)
asserts.Assert__listOfDeviceEvent(list)
return list
end
local content_type = require "aws-sdk.core.content_type"
local request_headers = require "aws-sdk.core.request_headers"
local request_handlers = require "aws-sdk.core.request_handlers"
local settings = {}
local function endpoint_for_region(region, use_dualstack)
if not use_dualstack then
if region == "us-east-1" then
return "devices.iot1click.amazonaws.com"
end
end
local ss = { "devices.iot1click" }
if use_dualstack then
ss[#ss + 1] = "dualstack"
end
ss[#ss + 1] = region
ss[#ss + 1] = "amazonaws.com"
if region == "cn-north-1" then
ss[#ss + 1] = "cn"
end
return table.concat(ss, ".")
end
function M.init(config)
assert(config, "You must provide a config table")
assert(config.region, "You must provide a region in the config table")
settings.service = M.metadata.endpoint_prefix
settings.protocol = M.metadata.protocol
settings.region = config.region
settings.endpoint = config.endpoint_override or endpoint_for_region(config.region, config.use_dualstack)
settings.signature_version = M.metadata.signature_version
settings.uri = (config.scheme or "https") .. "://" .. settings.endpoint
end
--
-- OPERATIONS
--
--- Call DescribeDevice asynchronously, invoking a callback when done
-- @param DescribeDeviceRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.DescribeDeviceAsync(DescribeDeviceRequest, cb)
assert(DescribeDeviceRequest, "You must provide a DescribeDeviceRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".DescribeDevice",
}
for header,value in pairs(DescribeDeviceRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "GET")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}", DescribeDeviceRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call DescribeDevice synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param DescribeDeviceRequest
-- @return response
-- @return error_type
-- @return error_message
function M.DescribeDeviceSync(DescribeDeviceRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.DescribeDeviceAsync(DescribeDeviceRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call UpdateDeviceState asynchronously, invoking a callback when done
-- @param UpdateDeviceStateRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.UpdateDeviceStateAsync(UpdateDeviceStateRequest, cb)
assert(UpdateDeviceStateRequest, "You must provide a UpdateDeviceStateRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".UpdateDeviceState",
}
for header,value in pairs(UpdateDeviceStateRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "PUT")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/state", UpdateDeviceStateRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call UpdateDeviceState synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param UpdateDeviceStateRequest
-- @return response
-- @return error_type
-- @return error_message
function M.UpdateDeviceStateSync(UpdateDeviceStateRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.UpdateDeviceStateAsync(UpdateDeviceStateRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call UnclaimDevice asynchronously, invoking a callback when done
-- @param UnclaimDeviceRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.UnclaimDeviceAsync(UnclaimDeviceRequest, cb)
assert(UnclaimDeviceRequest, "You must provide a UnclaimDeviceRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".UnclaimDevice",
}
for header,value in pairs(UnclaimDeviceRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "PUT")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/unclaim", UnclaimDeviceRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call UnclaimDevice synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param UnclaimDeviceRequest
-- @return response
-- @return error_type
-- @return error_message
function M.UnclaimDeviceSync(UnclaimDeviceRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.UnclaimDeviceAsync(UnclaimDeviceRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call GetDeviceMethods asynchronously, invoking a callback when done
-- @param GetDeviceMethodsRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.GetDeviceMethodsAsync(GetDeviceMethodsRequest, cb)
assert(GetDeviceMethodsRequest, "You must provide a GetDeviceMethodsRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".GetDeviceMethods",
}
for header,value in pairs(GetDeviceMethodsRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "GET")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/methods", GetDeviceMethodsRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call GetDeviceMethods synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param GetDeviceMethodsRequest
-- @return response
-- @return error_type
-- @return error_message
function M.GetDeviceMethodsSync(GetDeviceMethodsRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.GetDeviceMethodsAsync(GetDeviceMethodsRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ClaimDevicesByClaimCode asynchronously, invoking a callback when done
-- @param ClaimDevicesByClaimCodeRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ClaimDevicesByClaimCodeAsync(ClaimDevicesByClaimCodeRequest, cb)
assert(ClaimDevicesByClaimCodeRequest, "You must provide a ClaimDevicesByClaimCodeRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ClaimDevicesByClaimCode",
}
for header,value in pairs(ClaimDevicesByClaimCodeRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "PUT")
if request_handler then
request_handler(settings.uri, "/claims/{claimCode}", ClaimDevicesByClaimCodeRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ClaimDevicesByClaimCode synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ClaimDevicesByClaimCodeRequest
-- @return response
-- @return error_type
-- @return error_message
function M.ClaimDevicesByClaimCodeSync(ClaimDevicesByClaimCodeRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ClaimDevicesByClaimCodeAsync(ClaimDevicesByClaimCodeRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call InvokeDeviceMethod asynchronously, invoking a callback when done
-- @param InvokeDeviceMethodRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.InvokeDeviceMethodAsync(InvokeDeviceMethodRequest, cb)
assert(InvokeDeviceMethodRequest, "You must provide a InvokeDeviceMethodRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".InvokeDeviceMethod",
}
for header,value in pairs(InvokeDeviceMethodRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "POST")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/methods", InvokeDeviceMethodRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call InvokeDeviceMethod synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param InvokeDeviceMethodRequest
-- @return response
-- @return error_type
-- @return error_message
function M.InvokeDeviceMethodSync(InvokeDeviceMethodRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.InvokeDeviceMethodAsync(InvokeDeviceMethodRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call InitiateDeviceClaim asynchronously, invoking a callback when done
-- @param InitiateDeviceClaimRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.InitiateDeviceClaimAsync(InitiateDeviceClaimRequest, cb)
assert(InitiateDeviceClaimRequest, "You must provide a InitiateDeviceClaimRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".InitiateDeviceClaim",
}
for header,value in pairs(InitiateDeviceClaimRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "PUT")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/initiate-claim", InitiateDeviceClaimRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call InitiateDeviceClaim synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param InitiateDeviceClaimRequest
-- @return response
-- @return error_type
-- @return error_message
function M.InitiateDeviceClaimSync(InitiateDeviceClaimRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.InitiateDeviceClaimAsync(InitiateDeviceClaimRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call FinalizeDeviceClaim asynchronously, invoking a callback when done
-- @param FinalizeDeviceClaimRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.FinalizeDeviceClaimAsync(FinalizeDeviceClaimRequest, cb)
assert(FinalizeDeviceClaimRequest, "You must provide a FinalizeDeviceClaimRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".FinalizeDeviceClaim",
}
for header,value in pairs(FinalizeDeviceClaimRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "PUT")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/finalize-claim", FinalizeDeviceClaimRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call FinalizeDeviceClaim synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param FinalizeDeviceClaimRequest
-- @return response
-- @return error_type
-- @return error_message
function M.FinalizeDeviceClaimSync(FinalizeDeviceClaimRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.FinalizeDeviceClaimAsync(FinalizeDeviceClaimRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListDevices asynchronously, invoking a callback when done
-- @param ListDevicesRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListDevicesAsync(ListDevicesRequest, cb)
assert(ListDevicesRequest, "You must provide a ListDevicesRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListDevices",
}
for header,value in pairs(ListDevicesRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "GET")
if request_handler then
request_handler(settings.uri, "/devices", ListDevicesRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListDevices synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListDevicesRequest
-- @return response
-- @return error_type
-- @return error_message
function M.ListDevicesSync(ListDevicesRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListDevicesAsync(ListDevicesRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
--- Call ListDeviceEvents asynchronously, invoking a callback when done
-- @param ListDeviceEventsRequest
-- @param cb Callback function accepting three args: response, error_type, error_message
function M.ListDeviceEventsAsync(ListDeviceEventsRequest, cb)
assert(ListDeviceEventsRequest, "You must provide a ListDeviceEventsRequest")
local headers = {
[request_headers.CONTENT_TYPE_HEADER] = content_type.from_protocol(M.metadata.protocol, M.metadata.json_version),
[request_headers.AMZ_TARGET_HEADER] = ".ListDeviceEvents",
}
for header,value in pairs(ListDeviceEventsRequest.headers) do
headers[header] = value
end
local request_handler, err = request_handlers.from_protocol_and_method("rest-json", "GET")
if request_handler then
request_handler(settings.uri, "/devices/{deviceId}/events", ListDeviceEventsRequest, headers, settings, cb)
else
cb(false, err)
end
end
--- Call ListDeviceEvents synchronously, returning when done
-- This assumes that the function is called from within a coroutine
-- @param ListDeviceEventsRequest
-- @return response
-- @return error_type
-- @return error_message
function M.ListDeviceEventsSync(ListDeviceEventsRequest, ...)
local co = coroutine.running()
assert(co, "You must call this function from within a coroutine")
M.ListDeviceEventsAsync(ListDeviceEventsRequest, function(response, error_type, error_message)
assert(coroutine.resume(co, response, error_type, error_message))
end)
return coroutine.yield()
end
return M
|
--[[
Most of this file was written (and commented) by /u/changemymindpls1.
I've explicitly noted anything written by me.
--]]
function tprint (tbl, indent)
if not indent then indent = 0 end
local toprint = string.rep(" ", indent) .. "{\r\n"
indent = indent + 2
for k, v in pairs(tbl) do
toprint = toprint .. string.rep(" ", indent)
if (type(k) == "number") then
toprint = toprint .. "[" .. k .. "] = "
elseif (type(k) == "string") then
toprint = toprint .. k .. "= "
end
if (type(v) == "number") then
toprint = toprint .. v .. ",\r\n"
elseif (type(v) == "string") then
toprint = toprint .. "\"" .. v .. "\",\r\n"
elseif (type(v) == "table") then
toprint = toprint .. tprint(v, indent + 2) .. ",\r\n"
else
toprint = toprint .. "\"" .. tostring(v) .. "\",\r\n"
end
end
toprint = toprint .. string.rep(" ", indent-2) .. "}"
return toprint
end
--gets the key and if it's a symbol it removes the symbol: tag and quotations
local keyToString_mine = function(key)
--convert the key to a string
local keyAsString = tostring(key)
--if the string contains symbol: then remove it, otherwise keep the string as is
if (string.match)(keyAsString, "symbol: ") then
keyAsString = (string.sub)(keyAsString, 9)
else
keyAsString = keyAsString
end
--remove any leftover quotations from the string
keyAsString = keyAsString:gsub('"','')
--return the final result
return keyAsString
end
Devtools_PrintSceneDialogs = function(theScene) --This one was written by me! Just a quick test function that I threw together in a pinch. Not very useful.
--In true Droyti fashion, this one isn't very thorougly commented either (or really, at all). Should be fairly self explanitory, though.
local printer = io.open('agents/dlg/' .. theScene .. '_dlg_nodes.txt', "a")
local sceneDialog = Game_GetSceneDialog()
local nodeIDs = DlgGetChainHeadNodes(sceneDialog, "Cutscenes")
for i,theNode in ipairs(nodeIDs) do
printer:write(i .. " - " .. tostring(theNode), "\n")
local nextNode = DlgNodeGetNextNode(sceneDialog, theNode)
while 1 do --I REALLY need to stop doing these.
if nextNode then
local nextNodeType = nextNode.Type
local nextNodeName = nextNode.Name
printer:write(i .. " - " .. tostring(nextNodeType), "\n")
printer:write(i .. " - " .. tostring(nextNodeName), "\n")
nextNode = DlgNodeGetNextNode(sceneDialog, nextNode)
else
break
end
end
end
printer:close()
DialogBox_Okay("Dialog nodes printed!")
end
--prints an entire scene and its contents to a text file
Devtools_PrintSceneList = function(SceneObject)
local main_txt_file = io.open('agents/' .. SceneObject .. "_scene_output.txt", "a") --I added the agents/ subfolder. Just for better organization.
local scene_agents = SceneGetAgents(SceneObject)
local print_agent_transformation = true
local print_agent_properties = true
local print_agent_properties_keyset = false --not that useful
--being looping through the list of agents gathered from the scene
for i, agent_object in pairs(scene_agents) do
--get the agent name and the type
local agent_name = tostring(AgentGetName(agent_object))
local agent_type = tostring(TypeName(agent_object))--type(agent_object)
--start writing the agent information to the file
main_txt_file:write(i, "\n")
main_txt_file:write(i .. " Agent Name: " .. agent_name, "\n")
main_txt_file:write(i .. " Agent Type: " .. agent_type, "\n")
--if true, then it also writes information regarding the transformation properties of the agent
if print_agent_transformation then
local agent_pos = tostring(AgentGetPos(agent_object))
local agent_rot = tostring(AgentGetRot(agent_object))
local agent_pos_world = tostring(AgentGetWorldPos(agent_object))
local agent_rot_world = tostring(AgentGetWorldRot(agent_object))
main_txt_file:write(i .. " Agent Position: " .. agent_pos, "\n")
main_txt_file:write(i .. " Agent Rotation: " .. agent_rot, "\n")
main_txt_file:write(i .. " Agent World Position: " .. agent_pos_world, "\n")
main_txt_file:write(i .. " Agent World Rotation: " .. agent_rot_world, "\n")
end
--get the properties list from the agent
local agent_properties = AgentGetProperties(agent_object)
--if the properties field isnt null and print_agent_properties is true
if agent_properties and print_agent_properties then
--write a quick header to seperate
main_txt_file:write(i .. " --- Agent Properties ---", "\n")
--get the property keys list
local agent_property_keys = PropertyGetKeys(agent_properties)
--begin looping through each property key found in the property keys list
for x, agent_property_key in ipairs(agent_property_keys) do
--get the key type and the value, as well as the value type
local agent_property_key_type = TypeName(PropertyGetKeyType(agent_properties, agent_property_key))
local agent_property_value = PropertyGet(agent_properties, agent_property_key)
local agent_property_value_type = TypeName(PropertyGet(agent_properties, agent_property_key))
--convert these to a string using a special function to format it nicely
local agent_propety_key_string = keyToString_mine(agent_property_key)
local agent_property_key_type_string = keyToString_mine(agent_property_value_type)
--convert these to a string using a special function to format it nicely
local agent_property_value_string = keyToString_mine(agent_property_value)
local agent_property_value_type_string = keyToString_mine(agent_property_key_type)
--begin writing these values to file
main_txt_file:write(i .. " " .. x .. " [Agent Property]", "\n")
main_txt_file:write(i .. " " .. x .. " Key: " .. agent_propety_key_string, "\n")
main_txt_file:write(i .. " " .. x .. " Value: " .. agent_property_value_string, "\n")
main_txt_file:write(i .. " " .. x .. " Key Type: " .. agent_property_key_type_string, "\n")
main_txt_file:write(i .. " " .. x .. " Value Type: " .. agent_property_value_type_string, "\n")
--if the key type is of a table type, then print out the values of the table
if agent_property_key_type_string == "table" then
main_txt_file:write(i .. " " .. x .. " Value Table", "\n")
main_txt_file:write(tprint(agent_property_value), "\n")
end
--for printing the key property set of the agent properties
if print_agent_properties_keyset then
local property_key_set = PropertyGetKeyPropertySet(agent_properties, agent_property_key)
main_txt_file:write(i .. " " .. x .. " [Key Property Set] " .. tostring(property_key_set), "\n")
for y, property_key in pairs(property_key_set) do
main_txt_file:write(i .. " " .. x .. " Key Property Set Key: " .. tostring(property_key), "\n")
main_txt_file:write(i .. " " .. x .. " Key Property Set Value: " .. tostring(PropertyGet(agent_properties, property_key)), "\n")
end
end
end
--write a header to indicate the end of the agent properties information
main_txt_file:write(i .. " ---Agent Properties END ---", "\n")
end
end
--close the file stream
main_txt_file:close()
--for testing/validating
DialogBox_Okay("Printed Output")
end |
local Input = require("nui.input")
local event = require("nui.utils.autocmd").event
local M = {}
M.filters = {
CASE_SPLIT = 'refactor.rewrite.CaseSplit',
MAKE_CASE = 'refactor.rewrite.MakeCase',
MAKE_WITH = 'refactor.rewrite.MakeWith',
MAKE_LEMMA = 'refactor.extract.MakeLemma',
ADD_CLAUSE = 'refactor.rewrite.AddClause',
EXPR_SEARCH = 'refactor.rewrite.ExprSearch',
GEN_DEF = 'refactor.rewrite.GenerateDef',
REF_HOLE = 'refactor.rewrite.RefineHole',
}
local function has_multiple_results(filter)
return filter == M.filters.EXPR_SEARCH
or filter == M.filters.GEN_DEF
or filter == M.filters.REF_HOLE
end
local function single_action_handler(err, result, ctx, config)
if not result or #result == 0 then
vim.notify('No code actions available', vim.log.levels.INFO)
return
end
if #result > 1 then
error('Received code action with multiple results')
return
end
local action = result[1]
if action.edit ~= nil then
vim.lsp.util.apply_workspace_edit(action.edit)
end
end
function M.request_single(filter)
local params = vim.lsp.util.make_range_params()
params['context'] = { diagnostics = {}, only = { filter } }
if has_multiple_results(filter) then
vim.lsp.buf.code_action(params.context)
else
vim.lsp.buf_request(0, 'textDocument/codeAction', params, single_action_handler)
end
end
function M.case_split() M.request_single(M.filters.CASE_SPLIT) end
function M.make_case() M.request_single(M.filters.MAKE_CASE) end
function M.make_with() M.request_single(M.filters.MAKE_WITH) end
function M.make_lemma() M.request_single(M.filters.MAKE_LEMMA) end
function M.add_clause() M.request_single(M.filters.ADD_CLAUSE) end
function M.expr_search() M.request_single(M.filters.EXPR_SEARCH) end
function M.generate_def() M.request_single(M.filters.GEN_DEF) end
function M.refine_hole() M.request_single(M.filters.REF_HOLE) end
local function on_with_hints_results(err, results, ctx, config)
if not results or #results == 0 then
vim.notify('No code actions available', vim.log.levels.INFO)
return
end
local function apply_action(action)
if not action then
return
end
vim.lsp.util.apply_workspace_edit(action.edit)
end
vim.ui.select(results, {
prompt = 'Code actions:',
kind = 'codeaction',
format_item = function(result)
local title = result.title:gsub('\r\n', '\\r\\n')
return title:gsub('\n', '\\n')
end,
}, apply_action)
end
local hints_popup_options = {
relative = "cursor",
position = {
row = 1,
col = 0,
},
size = 30,
border = {
style = "rounded",
highlight = "FloatBorder",
text = {
top = "Hints",
top_align = "left",
},
},
win_options = {
winhighlight = "Normal:Normal",
},
}
function M.refine_hole_hints()
local range = vim.lsp.util.make_range_params()
local input = Input(hints_popup_options, {
prompt = '> ',
default_value = '',
on_submit = function(value)
hints = vim.split(value, ',')
range.context = { diagnostics = {} }
local params = {
command = 'refineHoleWithHints',
arguments = {{
codeAction = range,
hints = hints,
}},
}
vim.lsp.buf_request(0, 'workspace/executeCommand', params, on_with_hints_results)
end,
})
input:mount()
end
function M.expr_search_hints()
local range = vim.lsp.util.make_range_params()
local input = Input(hints_popup_options, {
prompt = '> ',
default_value = '',
on_submit = function(value)
hints = vim.split(value, ',')
range.context = { diagnostics = {} }
local params = {
command = 'exprSearchWithHints',
arguments = {{
codeAction = range,
hints = hints,
}},
}
vim.lsp.buf_request(0, 'workspace/executeCommand', params, on_with_hints_results)
end,
})
input:mount()
end
return M
|
--[[
# Utility Functions
Grab bag of general-use functions useful to all addons.
--]]
---------------------------------------------------------------------
local _, ns = ...
--
-- Solid debugger.
--
function ns.print(pattern, ...)
print(format(pattern, ...))
end
--
-- Laziness.
--
function ns.dump(table)
local t = type(table)
if t ~= "table" then
ns.print("dump: Expected table, found '%s'", t)
return
end
for k,v in pairs(table) do ns.print(k, "-", v) end
end
--
-- Formats a integer with English-style commas.
-- Always returns a string.
--
-- Example: 2500 -> 2,500
--
function ns.format_commas(amount)
local formatted = amount
while true do
formatted, k = string.gsub(formatted, "^(-?%d+)(%d%d%d)", '%1,%2')
if k == 0 then break end
end
return formatted
end
--
-- Basic rounding function.
--
function ns.round(num, idp)
local mult = 10 ^ (idp or 0)
return math.floor(num * mult + 0.5) / mult
end
--
-- Convenience function for checking whether a given value
-- in a table.
--
function ns.in_table (element, table)
for _, v in pairs(table) do
if v == element then return true end
end
return false
end
--
-- Recursive table deep copy.
-- WARNING: Not suitable for very large tables.
--
-- From: http://lua-users.org/wiki/CopyTable
--
function ns.deep_copy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in next, orig, nil do
copy[ns.deep_copy(orig_key)] = ns.deep_copy(orig_value)
end
setmetatable(copy, ns.deep_copy(getmetatable(orig)))
else -- number, string, boolean, etc
copy = orig
end
return copy
end
--
-- Integer shortening (for easy-to-read number readouts).
--
-- Returns shortened string (ex. 1,000,000 is "1m").
-- If "true" is passed as the second argument, the
-- value is also returned.
--
function ns.si(value, ...)
if not value then return "" end
local absvalue = abs(value)
local str, val
if absvalue >= 1e10 then
str, val = "%.0fb", value / 1e9
elseif absvalue >= 1e9 then
str, val = "%.1fb", value / 1e9
elseif absvalue >= 1e7 then
str, val = "%.1fm", value / 1e6
elseif absvalue >= 1e6 then
str, val = "%.2fm", value / 1e6
elseif absvalue >= 1e5 then
str, val = "%.0fk", value / 1e3
elseif absvalue >= 1e3 then
str, val = "%.1fk", value / 1e3
else
str, val = "%d", value
end
local raw = select(1, ...)
if raw then
return str, val
else
return format(str, val)
end
end
|
value = {}
number1 = {}
number2 = {}
value[1] = math.random(77777)+ 22222;
number1[1] = math.random(value[1] - 20000) + 15111;
value[2] = math.random(777777)+ 222222;
number1[2] = math.random(value[2] - 200000) + 151111;
ind = math.random(2)
bound = 10^(4+ind)
znak = math.random(2)
number2[ind] = value[ind] + number1[ind]
sign = "-"
if (znak == 2 or number2[ind] > bound) then
number2[ind] = value[ind] - number1[ind]
sign = "+"
end
|
os.loadAPI("/files/gui.lua")
lastSelectedPage = -1
currentPage = 0
function backP()
currentPage = lastSelectedPage - 1
end
function nextP()
currentPage = lastSelectedPage + 1
end
function toggle(onOff)
if onOff == true then
print("Toggled On")
else
print("Toggled Off")
end
end
while true do
gui.screenCheck()
if currentPage == 0 then
gui.screenReset()
gui.addLabel("Page 1|3", 1)
gui.addSpacer()
gui.addToggle("Test Toggle", toggle)
gui.addButton("Next", nextP)
lastSelectedPage = 0
currentPage = -1
elseif currentPage == 1 then
gui.screenReset()
gui.addLabel("Page 2|3", 1)
gui.addSpacer()
gui.addButton("Next", nextP)
gui.addButton("Back", backP)
lastSelectedPage = 1
currentPage = -1
elseif currentPage == 2 then
gui.screenReset()
gui.addLabel("Page 3|3", 1)
gui.addSpacer()
gui.addButton("Back", backP)
lastSelectedPage = 2
currentPage = -1
end
end
|
--- === AnyComplete ===
---
--- Provides autocomplete functionality anywhere you can type in text.
---
--- Based heavily on Nathan Cahill's code at https://github.com/nathancahill/Anycomplete and some of the enhancement requests.
-- TODO:
-- look up Google and DDG's Terms of Service for this API and see what the query limits should be
local logger = require("hs.logger")
local spoons = require("hs.spoons")
local application = require("hs.application")
local chooser = require("hs.chooser")
local http = require("hs.http")
local hotkey = require("hs.hotkey")
local eventtap = require("hs.eventtap")
local pasteboard = require("hs.pasteboard")
local alert = require("hs.alert")
local json = require("hs.json")
local fnutils = require("hs.fnutils")
local canvas = require("hs.canvas")
local inspect = require("hs.inspect")
local timer = require("hs.timer")
-- not in core yet, so conditionally load it
local axuielement = package.searchpath("hs.axuielement", package.path) and require("hs.axuielement")
local obj = {
-- Metadata
name = "AnyComplete",
author = "A-Ron / Nathan Cahill",
homepage = "https://github.com/Hammerspoon/Spoons",
license = "MIT - https://opensource.org/licenses/MIT",
spoonPath = spoons.scriptPath(),
spoonMeta = "placeholder for _coresetup metadata creation",
}
-- version is outside of obj table definition to facilitate its auto detection by
-- external documentation generation scripts
obj.version = "0.1"
local metadataKeys = {} ; for k, v in fnutils.sortByKeys(obj) do table.insert(metadataKeys, k) end
local _log = logger.new(obj.name)
obj.logger = _log
obj.__index = obj
---------- Local Functions And Variables ----------
-- spoon vars are stored in _internals so we can validate them immediately upon change with the modules __newindex matamethod (see end of file) rather than get a delayed error because the value is the wrong type
local _internals = {}
local _chooser
local _canvas
local _currentApp
local _hotkeys = {}
local _lastKeypressTimer
local _currentChoices = {}
local updateChooserChoices = function(choices)
_currentChoices = choices
_chooser:choices(_currentChoices)
end
local chooserCallback = function(choice)
if choice then
_chooser:query("")
updateChooserChoices({})
if eventtap.checkKeyboardModifiers().shift then
-- holding shift as they choose so load in search page instead
local queryString = http.encodeForQuery(choice.text)
local queryURL = _internals.queryDefinitions[_internals.querySite].searchQuery
hs.execute([[open "]] .. string.format(queryURL, queryString) .. [["]])
else
if _currentApp then _currentApp:activate() end
eventtap.keyStrokes(choice.text)
end
end
end
local updateChooser = function()
local queryString = _chooser:query()
if #queryString == 0 then
updateChooserChoices({})
else
queryString = http.encodeForQuery(queryString)
local queryURL = _internals.queryDefinitions[_internals.querySite].acQuery
http.asyncGet(string.format(queryURL, queryString), nil, function(s, b, h)
if s == 200 then
if b then
local newChoices = _internals.queryDefinitions[_internals.querySite].acParser(b)
if newChoices then
updateChooserChoices(newChoices)
end
end
else
_log.wf("http response code %d; headers: %s; content: %s", s, inspect(h), tostring(b))
end
end)
end
end
local queryChangedCallback = function()
if _internals.queryDebounce == 0 then
updateChooser()
else
local currentTime = timer.secondsSinceEpoch()
if _lastKeypressTimer then _lastKeypressTimer:stop() end
_lastKeypressTimer = timer.doAfter(_internals.queryDebounce, function()
_lastKeypressTimer = nil
updateChooser()
end)
end
end
local showCallback = function()
-- not in core yet, so skip canvas frame with title if we can't get the frame with axuielement
if axuielement then
-- it seems if the chooser is double triggered, it never calls the callback or hide for the initial one
if _canvas then
_canvas:delete()
_canvas = nil
end
local _hammerspoon = axuielement.applicationElementForPID(hs.processInfo.processID)
for i,v in ipairs(_hammerspoon) do
if v.AXTitle == "Chooser" then
-- because of window shadow for chooser, can't perfectly match up lines, so draw canvas
-- slightly larger and make it look like the chooser is part of the canvas
local chooserFrame = v.AXFrame
_canvas = canvas.new{
x = chooserFrame.x - 5,
y = chooserFrame.y - 22,
h = chooserFrame.h + 27,
w = chooserFrame.w + 10
}:show():level(canvas.windowLevels.mainMenu + 3):orderBelow()
_canvas[#_canvas + 1] = {
type = "rectangle",
action = "strokeAndFill",
strokeColor = { list = "System", name = "controlBackgroundColor" },
strokeWidth = 1.5,
fillColor = { list = "System", name = "windowBackgroundColor" },
}
_canvas[#_canvas + 1] = {
type = "text",
frame = { x = 0, y = 0, h = 22, w = chooserFrame.w + 10 },
text = _internals.queryDefinitions[_internals.querySite].title,
textColor = { list="System", name = "textColor" },
textSize = 16,
textAlignment = "center",
}
break
end
end
if #_canvas == 0 then
_log.i("unable to identify chooser window element for drawing frame")
_canvas = nil
end
_currentApp = application.frontmostApplication()
end
-- setup hotkeys
_hotkeys.tab = hotkey.bind('', 'tab', function()
local item = _currentChoices[_chooser:selectedRow()]
-- If no row is selected, but tab was pressed
if not item then return end
_chooser:query(item.text)
updateChooserChoices({})
if _lastKeypressTimer then
_lastKeypressTimer:stop()
_lastKeypressTimer = nil
end
updateChooser()
end)
_hotkeys.copy = hotkey.bind('cmd', 'c', function()
local item = _currentChoices[_chooser:selectedRow()]
if item then
_chooser:hide()
pasteboard.setContents(item.text)
alert.show("Copied to clipboard", 1)
else
alert.show("No search result to copy", 1)
end
end)
end
local hideCallback = function()
if _canvas then
_canvas:delete()
_canvas = nil
end
if _lastKeypressTimer then
_lastKeypressTimer:stop()
_lastKeypressTimer = nil
end
for k,v in pairs(_hotkeys) do
v:delete()
_hotkeys[k] = nil
end
_currentApp = nil
end
local clearBackgroundTasks = hideCallback
---------- Spoon Variables ----------
--- AnyComplete.querySite
--- Variable
--- A string specifying the key for the site definition to use when performing web queries for autocompletion possibilities. Defaults to "duckduckgo"
---
--- Notes:
--- * the string must match the key of a definition in [AnyComplete.queryDefinitions](#queryDefinitions) and assiging a new value will generate an error if the definition does not exist -- make sure to add your customizations to `AnyComplete.queryDefinitions` before setting this to a value other than one of the built in defaults.
_internals.querySite = "duckduckgo"
--- AnyComplete.queryDebounce
--- Variable
--- A number specifying the amount of time in seconds that the keyboard must be idle before performing a new query for possibilit completions. Set to 0 to perform a query after every keystroke. Defaults to 0.3.
---
--- Notes:
--- * it has been suggested by some of the issues posted at https://github.com/nathancahill/Anycomplete that Google may rate limit or even block your IP address if it detects too many queries in a short period of time. This has not been confirmed in any terms of service, nor is there any detail as to how may queries over what period of time is considered "too many", but this variable is provided as a way of reducing the number of queries performed.
_internals.queryDebounce = 0.3
--- AnyComplete.queryDefinitions[]
--- Variable
--- A table containing site definitions for completion queries.
---
--- This table contains key-value pairs defining the site defintions for completion queries. Each key is a string specifying the shorthand name for a completion site, and each value is a table containing the following key-value pairs:
--- * `title` - a string specifying the title to display at the top of the choosers during completion lookup
--- * `acQuery` - a string specifying the URL for perfoming the actual completion query. Use `%s` as a placeholder to specify where the current value in the chooser query field should be inserted.
--- * `searchQuery` - a string specifying the URL to use when the user wants to open a web page with the search results for the entry specified, triggered by holding down the shift key when making your selection.
--- * `acParser` - a function which takes as its sole argument the results from the http query and returns a chooser table where each entry is a table of the form `{ text = "possibility" }`.
---
--- Notes:
--- * definitions for Google ("google") and DuckDuckGo ("duckduckgo") are already defined.
_internals.queryDefinitions = {
google = {
title = "Google AutoComplete Suggestions",
acQuery = "https://suggestqueries.google.com/complete/search?client=firefox&q=%s",
searchQuery = "https://www.google.com/#q=%s",
acParser = function(requestResults)
local ok, results = pcall(function() return json.decode(requestResults) end)
if not ok then return end
return fnutils.imap(results[2], function(entry)
return {
text = entry,
}
end)
end,
},
duckduckgo = {
title = "DuckDuckGo AutoComplete Suggestions",
acQuery = "https://duckduckgo.com/ac/?q=%s",
searchQuery = "https://duckduckgo.com/?q=%s",
acParser = function(requestResults)
local ok, results = pcall(function() return json.decode(requestResults) end)
if not ok then return end
return fnutils.imap(results, function(entry)
return {
text = entry["phrase"],
}
end)
end,
},
}
---------- Spoon Methods ----------
-- obj.init = function(self)
-- -- in case called as function
-- if self ~= obj then self = obj end
--
-- return self
-- end
--- AnyComplete:start() -> self
--- Method
--- Readys the chooser interface for the AnyComplete spoon
---
--- Parameters:
--- * None
---
--- Returns:
--- * the AnyComplete spoon object
---
--- Notes:
--- * This method is included to conform to the expected Spoon format; it will automatically be invoked by [AnyComplete:show](#show) if necessary.
obj.start = function(self)
-- in case called as function
if self ~= obj then self = obj end
if not _chooser then
_chooser = chooser.new(chooserCallback)
:queryChangedCallback(queryChangedCallback)
:showCallback(showCallback)
:hideCallback(hideCallback)
end
return self
end
--- AnyComplete:stop() -> self
--- Method
--- Removes the chooser interface for the NonjourLauncher spoon and any lingering service queries
---
--- Parameters:
--- * None
---
--- Returns:
--- * the AnyComplete spoon object
---
--- Notes:
--- * This method is included to conform to the expected Spoon format; in general, it should be unnecessary to invoke this method directly.
obj.stop = function(self)
-- in case called as function
if self ~= obj then self = obj end
if _chooser then
obj:hide()
_chooser:delete()
_chooser = nil
end
return self
end
--- AnyComplete:show() -> self
--- Method
--- Shows the AnyComplete chooser window.
---
--- Parameters:
--- * None
---
--- Returns:
--- * the AnyComplete spoon object
---
--- Notes:
--- * Automatically invokes [AnyComplete:start()](#start) if this has not already been done.
obj.show = function(self)
-- in case called as function
if self ~= obj then self, st = obj, self end
if not _chooser then obj:start() end
if not _chooser:isVisible() then
_chooser:show()
end
return self
end
--- AnyComplete:hide() -> self
--- Method
--- Hides the AnyComplete chooser window.
---
--- Parameters:
--- * None
---
--- Returns:
--- * the AnyComplete spoon object
obj.hide = function(self)
-- in case called as function
if self ~= obj then self = obj end
if _chooser then
if _chooser:isVisible() then
_chooser:hide()
clearBackgroundTasks()
end
end
return self
end
--- AnyComplete:toggle() -> self
--- Method
--- Toggles the visibility of the AnyComplete chooser window.
---
--- Parameters:
--- * None
---
--- Returns:
--- * the AnyComplete spoon object
---
--- Notes::
--- * If the chooser window is currently visible, this method will invoke [AnyComplete:hide](#hide); otherwise invokes [AnyComplete:show](#show).
obj.toggle = function(self)
-- in case called as function
if self ~= obj then self, st = obj, self end
if _chooser and _chooser:isVisible() then
self:hide()
else
self:show()
end
return self
end
--- AnyComplete:bindHotkeys(mapping) -> self
--- Method
--- Binds hotkeys for the AnyComplete spoon
---
--- Parameters:
--- * `mapping` - A table containing hotkey modifier/key details for one or more of the following commands:
--- * "show" - Show the AnyComplete chooser window
--- * "hide" - Hide the AnyComplete chooser window
--- * "toggle" - Toggles the visibility of the AnyComplete window
---
--- Returns:
--- * the AnyComplete spoon object
---
--- Notes:
--- * the `mapping` table is a table of one or more key-value pairs of the format `command = { { modifiers }, key }` where:
--- * `command` - is one of the commands listed above
--- * `modifiers` - is a table containing keyboard modifiers, as specified in `hs.hotkey.bind()`
--- * `key` - is a string containing the name of a keyboard key, as specified in `hs.hotkey.bind()`
obj.bindHotkeys = function(self, mapping)
-- in case called as function
if self ~= obj then self, mapping = obj, self end
local def = {
toggle = self.toggle,
show = self.show,
hide = self.hide,
}
spoons.bindHotkeysToSpec(def, mapping)
return self
end
return setmetatable(obj, {
-- cleaner, IMHO, then "table: 0x????????????????"
__tostring = function(self)
local result, fieldSize = "", 0
for i, v in ipairs(metadataKeys) do fieldSize = math.max(fieldSize, #v) end
for i, v in ipairs(metadataKeys) do
result = result .. string.format("%-"..tostring(fieldSize) .. "s %s\n", v, self[v])
end
return result
end,
__index = function(self, key)
if key == "_debug" then
return {
_chooser = _chooser,
_canvas = _canvas,
_currentApp = _currentApp,
_hotkeys = _hotkeys,
_lastKeypressTimer = _lastKeypressTimer,
_internals = _internals,
_currentChoices = _currentChoices,
}
else
return _internals[key]
end
end,
__newindex = function(self, key, value)
local errorString = nil
if key == "queryDebounce" then
if type(value) == "number" and value >= 0 then
_internals.queryDebounce = value
else errorString = "must be a positive number or 0" end
elseif key == "querySite" then
if type(value) == "string" and _internals.queryDefinitions[value] then
_internals.querySite = value
else
local keysString = ""
for k, _ in pairs(_internals.queryDefinitions) do
keysString = keysString + k .. ", "
end
keysString = keysString:match("^(.*), $") or keysString
errorString = string.format("must be a string matching a AnyComplete.queryDefinition key (%s)", keysString)
end
elseif key == "queryDefinitions" then
errorString = "you cannot replace the queryDefinition table; add or remove entries with AnyComplete[name] = <definition>"
else errorString = "is unrecognized" end
if errorString then error(string.format("%s.%s %s", obj.name, key, errorString)) end
end,
})
|
local K, C = unpack(select(2, ...))
local Module = K:GetModule("Infobar")
local _G = _G
local string_format = _G.string.format
local table_sort = _G.table.sort
local table_wipe = _G.table.wipe
local ALT_KEY = _G.ALT_KEY
local Ambiguate = _G.Ambiguate
local C_GuildInfo_GuildRoster = _G.C_GuildInfo.GuildRoster
local CURRENT_GUILD_SORTING = _G.CURRENT_GUILD_SORTING
local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS
local GetGuildInfo = _G.GetGuildInfo
local GetGuildRosterInfo = _G.GetGuildRosterInfo
local GetGuildRosterMOTD = _G.GetGuildRosterMOTD
local GetNumGuildMembers = _G.GetNumGuildMembers
local GetQuestDifficultyColor = _G.GetQuestDifficultyColor
local GetRealZoneText = _G.GetRealZoneText
local GUILD = _G.GUILD
local GUILD_MOTD = _G.GUILD_MOTD
local GUILD_ONLINE_LABEL = _G.GUILD_ONLINE_LABEL
local hooksecurefunc = _G.hooksecurefunc
local InCombatLockdown = _G.InCombatLockdown
local IsAltKeyDown = _G.IsAltKeyDown
local IsInGuild = _G.IsInGuild
local IsShiftKeyDown = _G.IsShiftKeyDown
local LOOKINGFORGUILD = _G.LOOKINGFORGUILD
local NOTE_COLON = _G.NOTE_COLON
local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS
local REMOTE_CHAT = _G.REMOTE_CHAT
local UIErrorsFrame = _G.UIErrorsFrame
local UnitInParty = _G.UnitInParty
local UnitInRaid = _G.UnitInRaid
local menuFrame = CreateFrame("Frame", "KKUI_GuildDropDownMenu", UIParent, "UIDropDownMenuTemplate")
local menuList = {
{text = _G.OPTIONS_MENU, isTitle = true, notCheckable = true},
{text = _G.INVITE, hasArrow = true, notCheckable = true},
{text = _G.CHAT_MSG_WHISPER_INFORM, hasArrow = true, notCheckable = true},
}
local guildTable = {}
local function BuildGuildTable()
table_wipe(guildTable)
for i = 1, GetNumGuildMembers() do
local name, rank, _, level, _, zone, note, officernote, connected, status, class, _, _, mobile = GetGuildRosterInfo(i)
name = Ambiguate(name, "none")
guildTable[i] = {name, rank, level, zone, note, officernote, connected, status, class, mobile}
end
table_sort(guildTable, function(a, b)
if (a and b) then
return a[1] < b[1]
end
end)
end
function Module:GuildOnEnter()
if not IsInGuild() then
GameTooltip:SetOwner(_G.GuildMicroButton, "ANCHOR_NONE")
GameTooltip:SetPoint(K.GetAnchors(_G.GuildMicroButton))
GameTooltip:ClearLines()
GameTooltip:AddLine("|cffffffff"..LOOKINGFORGUILD.."|r".." (J)")
GameTooltip:Show()
return
end
if IsInGuild() then
Module.GuildHovered = true
C_GuildInfo_GuildRoster()
local name, rank, level, zone, note, officernote, connected, status, class, isMobile, zone_r, zone_g, zone_b, classc, levelc, grouped
local total, _, online = GetNumGuildMembers()
local gmotd = GetGuildRosterMOTD()
local guildMOTDString = "|cff669dff%s |cffaaaaaa- |cffffffff%s"
GameTooltip:SetOwner(_G.GuildMicroButton, "ANCHOR_NONE")
GameTooltip:SetPoint(K.GetAnchors(_G.GuildMicroButton))
GameTooltip:ClearLines()
GameTooltip:AddLine("|cffffffff"..GUILD.."|r".." (J)")
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(GetGuildInfo("player"), string_format(K.InfoColor.."%s: %d/%d", GUILD_ONLINE_LABEL, online, total))
GameTooltip:AddLine(" ")
if gmotd ~= "" then
GameTooltip:AddLine(string_format(guildMOTDString, GUILD_MOTD, gmotd))
end
if Module.GuildMax ~= 0 and online >= 1 then
GameTooltip:AddLine(" ")
for i = 1, total do
if Module.GuildMax and i > Module.GuildMax then
if online > 2 then
GameTooltip:AddLine(" ")
GameTooltip:AddLine(string_format(K.InfoColor.."%d %s (%s)", online - Module.GuildMax, "Hidden", ALT_KEY))
end
break
end
name, rank, _, level, _, zone, note, officernote, connected, status, class, _, _, isMobile = GetGuildRosterInfo(i)
if (connected or isMobile) and level >= Module.GuildLevelThreshold then
name = Ambiguate(name, "all")
if GetRealZoneText() == zone then
zone_r, zone_g, zone_b = 0.3, 1, 0.3
else
zone_r, zone_g, zone_b = 1, 1, 1
end
if isMobile then
zone = "|cffa5a5a5"..REMOTE_CHAT.."|r"
end
classc, levelc = (CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS)[class], GetQuestDifficultyColor(level)
grouped = (UnitInParty(name) or UnitInRaid(name)) and (GetRealZoneText() == zone and " |cff7fff00*|r" or " |cffff7f00*|r") or ""
if Module.GuildAltKeyDown then
GameTooltip:AddDoubleLine(string_format("%s%s |cff999999- |cffffffff%s", grouped, name, rank), zone, classc.r, classc.g, classc.b, zone_r, zone_g, zone_b)
if note ~= "" then
GameTooltip:AddLine(K.InfoColor.." "..NOTE_COLON.." "..note)
end
if officernote ~= "" and EPGP then
local ep, gp = EPGP:GetEPGP(name)
if ep then
officernote = " EP: "..ep.." GP: "..gp.." PR: "..string_format("%.3f", ep / gp)
else
officernote = " O."..NOTE_COLON.." "..officernote
end
elseif officernote ~= "" then
officernote = " O."..NOTE_COLON.." "..officernote
end
if officernote ~= "" then
GameTooltip:AddLine(officernote, 0.3, 1, 0.3, 1)
end
else
if status == 1 then
status = [[|TInterface\FriendsFrame\StatusIcon-Away:16:16:0:0|t]]
elseif status == 2 then
status = [[|TInterface\FriendsFrame\StatusIcon-DnD:16:16:0:0|t]]
else
status = ""
end
GameTooltip:AddDoubleLine(string_format("|cff%02x%02x%02x%d|r %s%s%s", levelc.r * 255, levelc.g * 255, levelc.b * 255, level, name, status, grouped), zone, classc.r, classc.g, classc.b, zone_r, zone_g, zone_b)
end
end
end
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine(" ", string_format("%s %s", K.GreyColor.."Sorting by|r", K.InfoColor..CURRENT_GUILD_SORTING))
end
GameTooltip:Show()
end
end
function Module:GuildOnLeave()
GameTooltip:Hide()
Module.GuildHovered = false
end
function Module:GuildOnEvent()
if Module.GuildHovered then
Module.GuildFrame:GetScript("OnEnter")(Module.GuildOnEnter)
end
if IsInGuild() then
BuildGuildTable()
local _, _, guildOnline = GetNumGuildMembers()
Module.GuildFont:SetFormattedText("%d", guildOnline)
else
Module.GuildFont:SetText(" ")
end
end
function Module:GuildOnUpdate(elapsed)
if IsInGuild() then
if not Module.GuildHovered then
return
end
if IsAltKeyDown() and not Module.GuildAltKeyDown then
Module.GuildAltKeyDown = true
Module.GuildFrame:GetScript("OnEnter")(Module.GuildOnEnter)
elseif not IsAltKeyDown() and Module.GuildAltKeyDown then
Module.GuildAltKeyDown = false
Module.GuildFrame:GetScript("OnEnter")(Module.GuildOnEnter)
end
if not Module.GuildMOTD then
Module.GuildElapsed = (Module.GuildElapsed or 0) + elapsed
if Module.GuildElapsed > 1 then
C_GuildInfo_GuildRoster()
Module.GuildElapsed = 0
end
if GetGuildRosterMOTD() ~= "" then
Module.GuildMOTD = true
if Module.GuildHovered then
Module.GuildFrame:GetScript("OnEnter")(Module.GuildOnEnter)
end
end
end
end
end
function Module:GuildOnMouseUp(btn)
if InCombatLockdown() then
UIErrorsFrame:AddMessage(K.InfoColor.._G.ERR_NOT_IN_COMBAT)
return
end
if btn == "LeftButton" then
ToggleGuildFrame()
elseif btn == "MiddleButton" and IsInGuild() then
local s = CURRENT_GUILD_SORTING
SortGuildRoster(IsShiftKeyDown() and s or (IsAltKeyDown() and (s == "rank" and "note" or "rank") or s == "class" and "name" or s == "name" and "level" or s == "level" and "zone" or "class"))
Module:GuildOnEnter()
elseif btn == "RightButton" and IsInGuild() then
GameTooltip:Hide()
Module.GuildHovered = false
local grouped
local menuCountWhispers = 0
local menuCountInvites = 0
menuList[2].menuList = {}
menuList[3].menuList = {}
for i = 1, #guildTable do
if (guildTable[i][7] or guildTable[i][10]) and guildTable[i][1] ~= K.Name then
local classc, levelc = (CUSTOM_CLASS_COLORS or RAID_CLASS_COLORS)[guildTable[i][9]], GetQuestDifficultyColor(guildTable[i][3])
if UnitInParty(guildTable[i][1]) or UnitInRaid(guildTable[i][1]) then
grouped = "|cffaaaaaa*|r"
else
grouped = ""
if not guildTable[i][10] then
menuCountInvites = menuCountInvites + 1
menuList[2].menuList[menuCountInvites] = {
text = string_format("|cff%02x%02x%02x%d|r |cff%02x%02x%02x%s|r %s", levelc.r * 255, levelc.g * 255, levelc.b * 255, guildTable[i][3], classc.r * 255, classc.g * 255, classc.b * 255, Ambiguate(guildTable[i][1], "all"), ""),
arg1 = guildTable[i][1],
notCheckable = true,
func = function(_, arg1)
menuFrame:Hide()
InviteUnit(arg1)
end
}
end
end
menuCountWhispers = menuCountWhispers + 1
menuList[3].menuList[menuCountWhispers] = {
text = string_format("|cff%02x%02x%02x%d|r |cff%02x%02x%02x%s|r %s", levelc.r * 255, levelc.g * 255, levelc.b * 255, guildTable[i][3], classc.r * 255, classc.g * 255, classc.b * 255, Ambiguate(guildTable[i][1], "all"), grouped),
arg1 = guildTable[i][1],
notCheckable = true,
func = function(_, arg1)
menuFrame:Hide()
SetItemRef("player:"..arg1, ("|Hplayer:%1$s|h[%1$s]|h"):format(arg1), "LeftButton")
end
}
end
end
EasyMenu(menuList, menuFrame, Module.GuildFrame, 0, 0, "MENU", 2)
end
end
function Module:CreateGuildDataText()
if not C["DataText"].Guild then
return
end
if not GuildMicroButton then
return
end
Module.GuildMax = nil -- Set max members listed, nil means no limit. Alt-key reveals hidden members
Module.GuildLevelThreshold = 1 -- Minimum level displayed (1 - 90)
Module.GuildSorting = "class" -- Default roster sorting: name, level, class, zone, rank, note
hooksecurefunc("SortGuildRoster", function(type)
CURRENT_GUILD_SORTING = type
end)
Module.GuildFrame = CreateFrame("Button", "KKUI_GuildDataText", UIParent)
Module.GuildFrame:SetAllPoints(GuildMicroButton)
Module.GuildFrame:SetSize(GuildMicroButton:GetWidth(), GuildMicroButton:GetHeight())
Module.GuildFrame:SetFrameLevel(GuildMicroButton:GetFrameLevel() + 2)
Module.GuildFont = Module.GuildFrame:CreateFontString("OVERLAY")
Module.GuildFont:FontTemplate(nil, nil, "OUTLINE")
Module.GuildFont:SetPoint("CENTER", Module.GuildFrame, "CENTER", 1, -6)
C_GuildInfo_GuildRoster()
SortGuildRoster(Module.GuildSorting == "note" and "rank" or "note")
SortGuildRoster(Module.GuildSorting)
K:RegisterEvent("PLAYER_ENTERING_WORLD", Module.GuildOnEvent)
K:RegisterEvent("GUILD_ROSTER_UPDATE", Module.GuildOnEvent)
K:RegisterEvent("PLAYER_GUILD_UPDATE", Module.GuildOnEvent)
K:RegisterEvent("GROUP_ROSTER_UPDATE", Module.GuildOnEvent)
Module.GuildFrame:SetScript("OnUpdate", Module.GuildOnUpdate)
Module.GuildFrame:SetScript("OnEvent", Module.GuildOnEvent)
Module.GuildFrame:SetScript("OnMouseUp", Module.GuildOnMouseUp)
Module.GuildFrame:SetScript("OnEnter", Module.GuildOnEnter)
Module.GuildFrame:SetScript("OnLeave", Module.GuildOnLeave)
Module:GuildOnUpdate()
end |
local component = require("component")
local shell = require("shell")
local fs = require("filesystem")
local seria = require("serialization")
if not component.isAvailable("gpu") then
io.stderr:write("GPU not found\n")
return
end
shell.setWorkingDirectory("/SPECTRA")
local move = function(von, nach) fs.remove(nach) fs.rename(von, nach) print(string.format("%s → %s", fs.canonical(von), fs.canonical(nach))) end
if fs.exists("/SPECTRA/autorun.lua") then
move("/SPECTRA/autorun.lua", "/autorun.lua")
end
local app = require("src/app")
app.run() |
local awful = require('awful')
local wibox = require('wibox')
local gears = require('gears')
local beautiful = require('beautiful')
local dpi = beautiful.xresources.apply_dpi
local clickable_container = require('widget.clickable-container')
local icons = require('theme.icons')
return function(_, panel)
local search_widget = wibox.widget {
{
{
{
image = icons.search,
resize = true,
widget = wibox.widget.imagebox
},
top = dpi(12),
bottom = dpi(12),
widget = wibox.container.margin
},
{
text = 'Application Launcher',
font = 'Inter Regular 12',
align = 'left',
valign = 'center',
widget = wibox.widget.textbox
},
spacing = dpi(24),
layout = wibox.layout.fixed.horizontal
},
left = dpi(24),
right = dpi(24),
forced_height = dpi(48),
widget = wibox.container.margin
}
search_button = wibox.widget {
{
search_widget,
widget = clickable_container
},
bg = beautiful.groups_bg,
shape = function(cr, width, height)
gears.shape.rounded_rect(cr, width, height, beautiful.groups_radius)
end,
widget = wibox.container.background
}
search_button:buttons(
awful.util.table.join(
awful.button(
{},
1,
function()
panel:run_rofi()
end
)
)
)
return wibox.widget {
{
{
layout = wibox.layout.fixed.vertical,
spacing = dpi(7),
search_button,
require('layout.left-panel.dashboard.hardware-monitor'),
require('layout.left-panel.dashboard.quick-settings'),
},
nil,
--require('widget.end-session')(),
layout = wibox.layout.align.vertical
},
margins = dpi(16),
widget = wibox.container.margin
}
end
|
---------------------------------------------------------------------------------------------------
-- Common module
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local actions = require("user_modules/sequences/actions")
local utils = require("user_modules/utils")
local commonFunctions = require("user_modules/shared_testcases/commonFunctions")
local commonPreconditions = require('user_modules/shared_testcases/commonPreconditions')
local json = require("modules/json")
local test = require("user_modules/dummy_connecttest")
local events = require('events')
local functionId = require('function_id')
local apiLoader = require("modules/api_loader")
local runner = require('user_modules/script_runner')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
config.defaultProtocolVersion = 2
--[[ Local Variables ]]
local m = {}
local hashId = {}
local preloadedPT = commonFunctions:read_parameter_from_smart_device_link_ini("PreloadedPT")
--[[ Shared Functions ]]
m.Title = runner.Title
m.Step = runner.Step
m.cloneTable = utils.cloneTable
m.wait = utils.wait
m.EMPTY_ARRAY = json.EMPTY_ARRAY
m.start = actions.start
m.registerApp = actions.registerApp
m.registerAppWOPTU = actions.registerAppWOPTU
m.activateApp = actions.activateApp
m.policyTableUpdate = actions.policyTableUpdate
m.getMobileSession = actions.getMobileSession
m.getHMIConnection = actions.getHMIConnection
m.getHMIAppId = actions.getHMIAppId
m.getAppsCount = actions.getAppsCount
m.getConfigAppParams = actions.getConfigAppParams
--[[ Common Functions ]]
--[[ @getShowParams: Provide default parameters for 'Show' RPC
--! @parameters:
--! pAppId: application number (1, 2, etc.)
--! @return: parameters for 'Show' RPC
--]]
function m.getShowParams(pAppId)
return {
requestShowParams = {
mainField1 = "Text_1",
graphic = {
imageType = "DYNAMIC",
value = "icon.png"
}
},
requestShowUiParams = {
showStrings = {
{
fieldName = "mainField1",
fieldText = "Text_1"
}
},
graphic = {
imageType = "DYNAMIC",
value = actions.getPathToFileInStorage("icon.png", pAppId)
}
}
}
end
--[[ @getOnSystemCapabilityParams: Provide default parameters for 'OnSystemCapabilityParams' RPC
--! @parameters:
--! pMaxNumOfWidgetWindows: maximum number of widget windows
--! @return: parameters for 'OnSystemCapabilityParams' RPC
--]]
function m.getOnSystemCapabilityParams(pMaxNumOfWidgetWindows)
if not pMaxNumOfWidgetWindows then pMaxNumOfWidgetWindows = 5 end
return {
systemCapability = {
systemCapabilityType = "DISPLAYS",
displayCapabilities = {
{
displayName = "displayName",
windowTypeSupported = {
{
type = "MAIN",
maximumNumberOfWindows = 1
},
{
type = "WIDGET",
maximumNumberOfWindows = pMaxNumOfWidgetWindows
}
},
windowCapabilities = {
{
windowID = 1,
textFields = {
{
name = "mainField1",
characterSet = "TYPE2SET",
width = 1,
rows = 1
}
},
imageFields = {
{
name = "choiceImage",
imageTypeSupported = { "GRAPHIC_PNG"
},
imageResolution = {
resolutionWidth = 35,
resolutionHeight = 35
}
}
},
imageTypeSupported = {
"STATIC"
},
templatesAvailable = {
"Template1", "Template2", "Template3", "Template4", "Template5"
},
numCustomPresetsAvailable = 100,
buttonCapabilities = {
{
longPressAvailable = true,
name = "VOLUME_UP",
shortPressAvailable = true,
upDownAvailable = false
}
},
softButtonCapabilities = {
{
shortPressAvailable = true,
longPressAvailable = true,
upDownAvailable = true,
imageSupported = true,
textSupported = true
}
}
}
}
}
}
}
}
end
--[[ @setHashId: Set hashId which is required during resumption
--! @parameters:
--! pHashId: application hashId
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.setHashId(pHashId, pAppId)
hashId[pAppId] = pHashId
end
--[[ @getHashId: Get hashId of an app which is required during resumption
--! @parameters:
--! pAppId: application number (1, 2, etc.)
--! @return: app's hashId
--]]
function m.getHashId(pAppId)
return hashId[pAppId]
end
--[[ @updatePreloadedPT: Update preloaded file with additional permissions
--! @parameters: none
--! @return: none
--]]
local function updatePreloadedPT()
local preloadedFile = commonPreconditions:GetPathToSDL() .. preloadedPT
local pt = utils.jsonFileToTable(preloadedFile)
local WidgetSupport = {
rpcs = {
CreateWindow = {
hmi_levels = { "NONE", "BACKGROUND", "LIMITED", "FULL" }
},
DeleteWindow = {
hmi_levels = { "NONE", "BACKGROUND", "LIMITED", "FULL" }
}
}
}
pt.policy_table.app_policies["default"].groups = { "Base-4", "WidgetSupport" }
pt.policy_table.app_policies["default"].steal_focus = true
pt.policy_table.functional_groupings["WidgetSupport"] = WidgetSupport
pt.policy_table.functional_groupings["DataConsent-2"].rpcs = json.null
utils.tableToJsonFile(pt, preloadedFile)
end
function m.precondition()
actions.preconditions()
commonPreconditions:BackupFile(preloadedPT)
updatePreloadedPT()
end
function m.postcondition()
for i = 1, m.getAppsCount() do
test.mobileSession[i]:StopRPC()
:Do(function(_, d)
utils.cprint(35, "Mobile session " .. d.sessionId .. " deleted")
test.mobileSession[i] = nil
end)
end
utils.wait()
:Do(function()
actions.postconditions()
commonPreconditions:RestoreFile(preloadedPT)
end)
end
--[[ @createWindow: Processing CreateWindow RPC
--! @parameters:
--! pParams: Parameters for CreateWindow RPC
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.createWindow(pParams, pAppId)
local params = m.cloneTable(pParams)
if not pAppId then pAppId = 1 end
local cid = m.getMobileSession(pAppId):SendRPC("CreateWindow", params)
params.appID = m.getHMIAppId(pAppId)
m.getHMIConnection():ExpectRequest("UI.CreateWindow", params)
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
m.getMobileSession(pAppId):ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
:Do(function()
local paramsToSDL = m.getOnSystemCapabilityParams()
paramsToSDL.appID = m.getHMIAppId(pAppId)
m.getHMIConnection():SendNotification("BasicCommunication.OnSystemCapabilityUpdated", paramsToSDL)
m.getMobileSession(pAppId):ExpectNotification("OnSystemCapabilityUpdated", m.getOnSystemCapabilityParams())
end)
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ hmiLevel = "NONE", windowID = params.windowID })
end
--[[ @createWindowUnsuccess: Processing CreateWindow with ERROR resultCode
--! @parameters:
--! pParams: Parameters for CreateWindow RPC
--! pResultCode - result error
--! @return: none
--]]
function m.createWindowUnsuccess(pParams, pResultCode)
local cid = m.getMobileSession():SendRPC("CreateWindow", pParams)
m.getHMIConnection():ExpectRequest("UI.CreateWindow")
:Times(0)
m.getMobileSession():ExpectResponse(cid, { success = false, resultCode = pResultCode })
m.getMobileSession():ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
m.getMobileSession():ExpectNotification("OnHMIStatus")
:Times(0)
end
--[[ @deleteWindow: Processing DeleteWindow RPC
--! @parameters:
--! @pWindowID: Parameters for DeleteWindow RPC
--! @return: none
--]]
function m.deleteWindow(pWindowID)
local cid = m.getMobileSession():SendRPC("DeleteWindow", { windowID = pWindowID })
m.getHMIConnection():ExpectRequest("UI.DeleteWindow", { windowID = pWindowID })
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
m.getMobileSession():ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
m.getMobileSession():ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
end
--[[ @deleteWindowUnsuccess: Processing DeleteWindow with ERROR resultCode
--! @parameters:
--! @pWindowID: Parameters for DeleteWindow RPC
--! pResultCode - result error
--! @return: none
--]]
function m.deleteWindowUnsuccess(pWindowID, pResultCode)
local cid = m.getMobileSession():SendRPC("DeleteWindow", { windowID = pWindowID })
m.getHMIConnection():ExpectRequest("UI.DeleteWindow")
:Times(0)
m.getMobileSession():ExpectResponse(cid, { success = false, resultCode = pResultCode })
m.getMobileSession():ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
end
--[[ @deleteWindowHMIwithoutResponse: performs case when HMI did not respond
--! @parameters:
--! @pWindowID: Parameters for DeleteWindow RPC
--! pResultCode - result error
--! @return: none
--]]
function m.deleteWindowHMIwithoutResponse(pWindowID, pResultCode)
local cid = m.getMobileSession():SendRPC("DeleteWindow", { windowID = pWindowID })
m.getHMIConnection():ExpectRequest("UI.DeleteWindow", { windowID = pWindowID })
:Do(function()
-- HMI did not response
end)
m.getMobileSession():ExpectResponse(cid, { success = false, resultCode = pResultCode })
m.getMobileSession():ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
end
--[[ @sendShowToWindow: Processing Show RPC to a main and a widget windows
--! @parameters:
--! @pWindowID: Parameters for Show RPC
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.sendShowToWindow(pWindowId, pAppId)
if not pAppId then pAppId = 1 end
local params = m.getShowParams(pAppId)
if pWindowId then
params.requestShowParams.windowID = pWindowId
params.requestShowUiParams.windowID = pWindowId
end
params.requestShowUiParams.appID = m.getHMIAppId(pAppId)
local cid = m.getMobileSession(pAppId):SendRPC("Show", params.requestShowParams)
m.getHMIConnection():ExpectRequest("UI.Show", params.requestShowUiParams)
:ValidIf(function(_,data)
if pWindowId == nil and data.windowID ~= nil then
return false, "SDL sends not exist window ID to HMI"
else
return true
end
end)
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
m.getMobileSession(pAppId):ExpectResponse(cid, { success = true, resultCode = "SUCCESS" })
:Do(function()
if params.requestShowParams.templateConfiguration ~= nil then
local paramsToSDL = m.getOnSystemCapabilityParams()
paramsToSDL.appID = m.getHMIAppId(pAppId)
m.getHMIConnection():SendNotification("BasicCommunication.OnSystemCapabilityUpdated", paramsToSDL)
m.getMobileSession(pAppId):ExpectNotification("OnSystemCapabilityUpdated", m.getOnSystemCapabilityParams())
else
m.getMobileSession(pAppId):ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
end
end)
end
--[[ @sendShowToWindowUnsuccess: Processing Show RPC with ERROR resultCode
--! @parameters:
--! @pWindowID: Parameters for Show RPC
--! pResultCode - result error
--! @return: none
--]]
function m.sendShowToWindowUnsuccess(pWindowId, pResultCode, pAppId)
if not pAppId then pAppId = 1 end
local params = m.getShowParams(pAppId)
if pWindowId then
params.requestShowParams.windowID = pWindowId
end
local cid = m.getMobileSession(pAppId):SendRPC("Show", params.requestShowParams)
m.getHMIConnection():ExpectRequest("UI.Show")
:Times(0)
m.getMobileSession(pAppId):ExpectResponse(cid, { success = false, resultCode = pResultCode })
m.getMobileSession(pAppId):ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
end
--[[ @sendShowToWindowUnsuccessHMIREJECTED: Processing Show RPC with REJECTED HMI response
--! @parameters:
--! @pWindowID: Parameters for Show RPC
--! pResultCode - result error
--! @return: none
--]]
function m.sendShowToWindowUnsuccessHMIREJECTED(pWindowId, pAppId)
if not pAppId then pAppId = 1 end
local params = m.getShowParams(pAppId)
if pWindowId then
params.requestShowParams.windowID = pWindowId
params.requestShowUiParams.windowID = pWindowId
end
params.requestShowUiParams.appID = m.getHMIAppId(pAppId)
local cid = m.getMobileSession(pAppId):SendRPC("Show", params.requestShowParams)
m.getHMIConnection():ExpectRequest("UI.Show", params.requestShowUiParams)
:Do(function(_, data)
m.getHMIConnection():SendError(data.id, data.method, "REJECTED", "Error code")
m.getMobileSession(pAppId):ExpectNotification("OnSystemCapabilityUpdated")
:Times(0)
end)
m.getMobileSession(pAppId):ExpectResponse(cid, { success = false, resultCode = "REJECTED" })
end
local function checkAbsenceOfOnHMIStatusForOtherApps(pAppId)
for i = 1, m.getAppsCount() do
if i ~= pAppId then
m.getMobileSession(i):ExpectNotification("OnHMIStatus")
:Times(0)
end
end
end
--[[ @activateWidgetFromNoneToFULL: Activate widget from NONE to FULL
--! @parameters:
--! pId: widget id (1, 2, etc.)
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.activateWidgetFromNoneToFULL(pId, pAppId)
if not pAppId then pAppId = 1 end
m.getHMIConnection():SendNotification("BasicCommunication.OnAppActivated",
{ appID = m.getHMIAppId(pAppId), windowID = pId })
m.getHMIConnection():SendNotification("BasicCommunication.OnAppActivated",
{ appID = m.getHMIAppId(pAppId), windowID = pId })
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ hmiLevel = "BACKGROUND", windowID = pId},
{ hmiLevel = "FULL", windowID = pId })
:Times(2)
checkAbsenceOfOnHMIStatusForOtherApps(pAppId)
end
--[[ @activateWidgetFromBackgroundToFULL: Activate widget from BACKGROUND to FULL
--! @parameters:
--! pId: widget id (1, 2, etc.)
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.activateWidgetFromBackgroundToFULL(pId, pAppId)
if not pAppId then pAppId = 1 end
m.getHMIConnection():SendNotification("BasicCommunication.OnAppActivated",
{ appID = m.getHMIAppId(pAppId), windowID = pId })
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ hmiLevel = "FULL", windowID = pId })
checkAbsenceOfOnHMIStatusForOtherApps(pAppId)
end
--[[ @deactivateWidgetFromFullToNone: Deactivate widget from FULL to NONE
--! @parameters:
--! pId: widget id (1, 2, etc.)
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.deactivateWidgetFromFullToNone(pId, pAppId)
if not pAppId then pAppId = 1 end
m.getHMIConnection():SendNotification("BasicCommunication.OnAppDeactivated",
{ appID = m.getHMIAppId(pAppId), windowID = pId })
m.getHMIConnection():SendNotification("BasicCommunication.OnAppDeactivated",
{ appID = m.getHMIAppId(pAppId), windowID = pId })
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ hmiLevel = "BACKGROUND", windowID = pId },
{ hmiLevel = "NONE", windowID = pId })
:Times(2)
checkAbsenceOfOnHMIStatusForOtherApps(pAppId)
end
--[[ @deactivateWidgetFromFullToBackground: Deactivate widget from FULL to BACKGROUND
--! @parameters:
--! pId: widget id (1, 2, etc.)
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.deactivateWidgetFromFullToBackground(pId, pAppId)
if not pAppId then pAppId = 1 end
m.getHMIConnection():SendNotification("BasicCommunication.OnAppDeactivated",
{ appID = m.getHMIAppId(pAppId), windowID = pId })
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ hmiLevel = "BACKGROUND", windowID = pId })
checkAbsenceOfOnHMIStatusForOtherApps(pAppId)
end
--[[ @deactivateAppFromFullToNone: Deactivate app from FULL to NONE
--! @parameters:
--! pAppId: application number (1, 2, etc.)
--! @return: none
--]]
function m.deactivateAppFromFullToNone(pAppId)
if not pAppId then pAppId = 1 end
m.getHMIConnection():SendNotification("BasicCommunication.OnExitApplication",
{ appID = m.getHMIAppId(pAppId), reason = "USER_EXIT" })
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus")
:Times(AtLeast(1))
checkAbsenceOfOnHMIStatusForOtherApps(pAppId)
end
--[[ @unexpectedDisconnect: closing connection
--! @parameters: none
--! @return: none
--]]
function m.unexpectedDisconnect()
test.mobileConnection:Close()
m.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = true })
:Do(function()
for i = 1, m.getAppsCount() do
test.mobileSession[i] = nil
end
end)
end
--[[ @connectMobile: create connection
--! @parameters: none
--! @return: none
--]]
function m.connectMobile()
test.mobileConnection:Connect()
EXPECT_EVENT(events.connectedEvent, "Connected")
:Do(function()
utils.cprint(35, "Mobile connected")
end)
end
--[[ @ignitionOff: IGNITION_OFF sequence
--! @parameters: none
--! @return: none
--]]
function m.ignitionOff()
config.ExitOnCrash = false
local timeout = 5000
local function removeSessions()
for i = 1, m.getAppsCount() do
test.mobileSession[i] = nil
end
end
local event = events.Event()
event.matches = function(event1, event2) return event1 == event2 end
EXPECT_EVENT(event, "SDL shutdown")
:Do(function()
removeSessions()
StopSDL()
config.ExitOnCrash = true
end)
m.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications", { reason = "SUSPEND" })
m.getHMIConnection():ExpectNotification("BasicCommunication.OnSDLPersistenceComplete")
:Do(function()
m.getHMIConnection():SendNotification("BasicCommunication.OnExitAllApplications",{ reason = "IGNITION_OFF" })
for i = 1, m.getAppsCount() do
m.getMobileSession(i):ExpectNotification("OnAppInterfaceUnregistered", { reason = "IGNITION_OFF" })
end
end)
m.getHMIConnection():ExpectNotification("BasicCommunication.OnAppUnregistered", { unexpectedDisconnect = false })
:Times(m.getAppsCount())
local isSDLShutDownSuccessfully = false
m.getHMIConnection():ExpectNotification("BasicCommunication.OnSDLClose")
:Do(function()
utils.cprint(35, "SDL was shutdown successfully")
isSDLShutDownSuccessfully = true
RAISE_EVENT(event, event)
end)
:Timeout(timeout)
local function forceStopSDL()
if isSDLShutDownSuccessfully == false then
utils.cprint(35, "SDL was shutdown forcibly")
RAISE_EVENT(event, event)
end
end
RUN_AFTER(forceStopSDL, timeout + 500)
end
--[[ @expCreateWindowResponse: expectation of CreateWindow response
--! @parameters:
--! pAppId - application number (1, 2, etc.)
--! @return: Expectation for event
--]]
function m.expCreateWindowResponse(pAppId)
local event = events.Event()
event.matches = function(_, data) return data.rpcFunctionId == functionId["CreateWindow"] end
return m.getMobileSession(pAppId):ExpectEvent(event, "CreateWindow response")
end
--[[ @getOnSCUParams: provide parameters for 'OnSystemCapabilityUpdated' notification
--! @parameters:
--! pWindowsArray - array of windows (e.g. {0, 2, 4})
--! pWindowId - window id (1, 2, etc.)
--! @return: parameters for notification
--]]
function m.getOnSCUParams(pWindowsArray, pWindowId)
local params = m.getOnSystemCapabilityParams()
local disCaps = params.systemCapability.displayCapabilities[1]
local defWinCaps = m.cloneTable(disCaps.windowCapabilities[1])
disCaps.windowCapabilities = {}
for _, winId in pairs(pWindowsArray) do
local specificWinCaps = m.cloneTable(defWinCaps)
specificWinCaps.windowID = winId
specificWinCaps.templatesAvailable = { "Template_" .. winId }
table.insert(disCaps.windowCapabilities, specificWinCaps)
end
if pWindowId ~= nil then
for _, winCap in pairs(disCaps.windowCapabilities) do
if winCap.windowID == pWindowId then
disCaps.windowCapabilities = { winCap }
end
end
end
return params
end
--[[ @sendOnSCU: send 'BC.OnSystemCapabilityUpdated' notification from HMI
--! @parameters:
--! pParams - parameters for the notification
--! pAppId - application number (1, 2, etc.)
--! @return: none
--]]
function m.sendOnSCU(pParams, pAppId)
local params = m.cloneTable(pParams)
params.appID = m.getHMIAppId(pAppId)
m.getHMIConnection():SendNotification("BasicCommunication.OnSystemCapabilityUpdated", params)
end
--[[ @checkResumption: function to check resumption
--! @parameters:
--! pWidgetParams - widget window parameters
--! pAppId - application number (1, 2, etc.)
--! @return: none
--]]
local function checkResumption(pWidgetParams, pAppId)
local winCaps = m.getOnSCUParams({ 0, pWidgetParams.windowID })
m.getMobileSession(pAppId):ExpectNotification("OnSystemCapabilityUpdated", winCaps)
m.getHMIConnection():ExpectRequest("UI.CreateWindow", pWidgetParams)
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", { })
m.sendOnSCU(m.getOnSCUParams({ 0, pWidgetParams.windowID }, pWidgetParams.windowID), pAppId)
end)
m.expCreateWindowResponse(pAppId)
:Times(0)
end
--[[ @checkResumption_NONE: function to check resumption for app in NONE HMI level
--! @parameters:
--! pWidgetParams - widget window parameters
--! pAppId - application number (1, 2, etc.)
--! @return: none
--]]
function m.checkResumption_NONE(pWidgetParams, pAppId)
m.getHMIConnection():ExpectRequest("BasicCommunication.CloseApplication", {})
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ windowID = 0, hmiLevel = "NONE" },
{ windowID = pWidgetParams.windowID, hmiLevel = "NONE" })
:Times(2)
checkResumption(pWidgetParams, pAppId)
end
--[[ @checkResumption_LIMITED: function to check resumption for app in LIMITED HMI level
--! @parameters:
--! pWidgetParams - widget window parameters
--! pAppId - application number (1, 2, etc.)
--! @return: none
--]]
function m.checkResumption_LIMITED(pWidgetParams, pAppId)
m.getHMIConnection():ExpectNotification("BasicCommunication.OnResumeAudioSource", { appID = m.getHMIAppId(pAppId) })
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ windowID = 0, hmiLevel = "NONE" },
{ windowID = 0, hmiLevel = "LIMITED" },
{ windowID = pWidgetParams.windowID, hmiLevel = "NONE" })
:Times(3)
checkResumption(pWidgetParams, pAppId)
end
--[[ @checkResumption_FULL: function to check resumption for app in FULL HMI level
--! @parameters:
--! pWidgetParams - widget window parameters
--! pAppId - application number (1, 2, etc.)
--! @return: none
--]]
function m.checkResumption_FULL(pWidgetParams, pAppId)
m.getHMIConnection():ExpectRequest("BasicCommunication.ActivateApp", {})
:Do(function(_, data)
m.getHMIConnection():SendResponse(data.id, data.method, "SUCCESS", {})
end)
m.getMobileSession(pAppId):ExpectNotification("OnHMIStatus",
{ windowID = 0, hmiLevel = "NONE" },
{ windowID = 0, hmiLevel = "FULL" },
{ windowID = pWidgetParams.windowID, hmiLevel = "NONE" })
:Times(3)
checkResumption(pWidgetParams, pAppId)
end
--[[ @reRegisterAppSuccess: re-register application with SUCCESS resultCode
--! @parameters:
--! pWidgetParams - widget window parameters
--! pAppId - application number (1, 2, etc.)
--! pCheckFunc: check function
--! @return: none
--]]
function m.reRegisterAppSuccess(pWidgetParams, pAppId, pCheckFunc, pResultCode)
if not pAppId then pAppId = 1 end
if not pResultCode then pResultCode = "SUCCESS" end
m.getMobileSession(pAppId):StartService(7)
:Do(function()
local params = m.cloneTable(m.getConfigAppParams(pAppId))
params.hashID = m.getHashId(pAppId)
local corId = m.getMobileSession(pAppId):SendRPC("RegisterAppInterface", params)
m.getHMIConnection():ExpectNotification("BasicCommunication.OnAppRegistered", {
application = { appName = m.getConfigAppParams(pAppId).appName }
})
:Do(function()
m.sendOnSCU(m.getOnSCUParams({ 0 }, 0), pAppId)
end)
m.getMobileSession(pAppId):ExpectResponse(corId, { success = true, resultCode = pResultCode })
:Do(function()
m.getMobileSession(pAppId):ExpectNotification("OnPermissionsChange")
end)
end)
pCheckFunc(pWidgetParams, pAppId)
end
function m.spairs(pTbl)
local keys = {}
for k in pairs(pTbl) do
keys[#keys+1] = k
end
local function getStringKey(pKey)
return tostring(string.format("%03d", pKey))
end
table.sort(keys, function(a, b) return getStringKey(a) < getStringKey(b) end)
local i = 0
return function()
i = i + 1
if keys[i] then
return keys[i], pTbl[keys[i]]
end
end
end
local function setSyncMsgVersion()
local mobile = apiLoader.init("data/MOBILE_API.xml")
local schema = mobile.interface[next(mobile.interface)]
local ver = schema.version
for appId = 1, 3 do
local syncMsgVersion = m.getConfigAppParams(appId).syncMsgVersion
syncMsgVersion.majorVersion = tonumber(ver.majorVersion)
syncMsgVersion.minorVersion = tonumber(ver.minorVersion)
syncMsgVersion.patchVersion = tonumber(ver.patchVersion)
end
end
setSyncMsgVersion()
return m
|
return {
run = function(arg, msg)
if not arg then return msg:reply('Nothing to clapify') end
msg:reply(arg:gsub('%S+', function(str) return ' 👏 '..str end))
end,
description = 'Make 👏 text 👏 like 👏 this',
group = 'text',
aliases = {}
}
|
local log = require 'loverocks.log'
local luarocks = require 'loverocks.luarocks'
local install = {}
function install.build(parser)
parser:description
"Installs a package manually."
parser:argument "packages"
:args("+")
:description
"The packages to install."
parser:flag "--only-deps"
:description(
"Only install the packages dependencies. "..
"Analogous to apt-get build-dep.")
parser:option "-s" "--server"
:description
"Fetch rocks/rockspecs from this server as a priority."
parser:option "--only-server"
:description
"Fetch rocks/rockspecs from this server, ignoring other servers."
end
function install.run(conf, args)
local flags = luarocks.make_flags(conf)
flags.init_rocks = true
if args.server then
table.insert(flags.from, 1, args.server)
end
if args.only_server then
flags.only_from = args.only_server
end
for _, pkg in ipairs(args.packages) do
local lr_args = {pkg} -- TODO: specify versions
if args.only_deps then
table.insert(lr_args, "--only-deps")
log:info("Installing dependencies for %q", pkg)
else
log:info("Installing %q", pkg)
end
log:fs("luarocks install %s", table.concat(lr_args, " "))
log:assert(luarocks.sandbox(flags, function()
local lr_install = require 'luarocks.install'
return lr_install.run(unpack(lr_args))
end))
end
end
return install
|
-- PORTALS --
portal = {}
-- Return unit direction of node with position 'pos'.
portal.dir = function(pos)
local node = minetest.get_node(pos)
local back_dir = minetest.facedir_to_dir(node.param2)
local dir = vector.multiply(back_dir, -1)
return dir
end
-- Rotates obj`s collision and selection boxes angles 'rot' (in radians).
-- Rotation occurs relatively to obj`s box rotation!!!
portal.rotate_entity_bounding_box = function(obj, rot)
if not obj:get_luaentity() then return end
if not (math.deg(rot.x) % 90 == 0) or not (math.deg(rot.y) % 90 == 0) or not (math.deg(rot.z) % 90 == 0) then return end
local def = obj:get_properties()
local colbox = def.collisionbox
local selbox = def.selectionbox
local new_colbox = {}
local new_selbox = {}
new_colbox[1] = vector.rotate({x=colbox[1], y=colbox[2], z=colbox[3]}, rot)
new_colbox[2] = vector.rotate({x=colbox[4], y=colbox[5], z=colbox[6]}, rot)
new_selbox[1] = vector.rotate({x=selbox[1], y=selbox[2], z=selbox[3]}, rot)
new_selbox[2] = vector.rotate({x=selbox[4], y=selbox[5], z=selbox[6]}, rot)
local res_colbox = {
new_colbox[1].x, new_colbox[1].y, new_colbox[1].z,
new_colbox[2].x, new_colbox[2].y, new_colbox[2].z
}
local res_selbox = {
new_selbox[1].x, new_selbox[1].y, new_selbox[1].z,
new_selbox[2].x, new_selbox[2].y, new_selbox[2].z
}
return res_colbox, res_selbox
end
-- Called each the node timer step.
--If there are objects within 'catch_box' box and their collision boxes are located at 0.1 distance to the portal surface, then teleport them saving their impulse.
portal.teleport_entity = function(pos)
local connected_to = minetest.deserialize(minetest.get_meta(pos):get_string("connected_to"))
--minetest.debug("connected_to: " .. (connected_to and minetest.pos_to_string(connected_to) or tostring(nil)))
if not connected_to then
--minetest.debug("Nothing can be teleported at the moment as the portal at " .. minetest.pos_to_string(pos) .. " is unconnected!")
return
end
local pdir = minetest.facedir_to_dir(minetest.get_node(pos).param2)
-- Catch_box coordinates are relative to the node`s origin (pos)
local catch_box = {vector.new(-0.4, -0.4, -0.5), vector.new(0.4, 1.4, -0.5)}
local pdir_rot = vector.dir_to_rotation(pdir)
catch_box[1] = vector.rotate(catch_box[1], pdir_rot)
catch_box[2] = vector.add(vector.rotate(catch_box[2], pdir_rot), vector.multiply(pdir, 1.45))
minetest.debug("catch_box: [1]=" .. minetest.pos_to_string(vector.add(pos, catch_box[1])) .. ", [2]=" .. minetest.pos_to_string(vector.add(pos, catch_box[2])))
local catched_objs = minetest.get_objects_in_area(vector.add(pos, catch_box[1]), vector.add(pos, catch_box[2]))
--minetest.debug("#catched_objs: " .. #catched_objs)
local iter_func = function(obj)
local centre_point = vector.add(pos, vector.divide(vector.add(catch_box[1], vector.rotate(vector.new(0.4, 1.4, -0.5), pdir_rot)), 2))
--minetest.debug("centre_point: " .. minetest.pos_to_string(centre_point))
local epos_dir = vector.subtract(obj:get_pos(), centre_point)
--[[local origin_epos_dir = vector.rotate(epos_dir, vector.multiply(vector.dir_to_rotation(epos_dir), -1))
local epos_horiz_dir = vector.rotate(vector.new(origin_epos_dir.x, 0, origin_epos_dir.z), vector.dir_to_rotation(epos_dir))
local abs_epos_horiz_dir = vector.add(centre_point, epos_horiz_dir)]]
local dist_to_epos = vector.length(epos_dir)*math.cos(vector.angle(epos_dir, pdir))
--minetest.debug("dist_to_epos: " .. dist_to_epos)
local rel_epos_horiz_dir = vector.subtract(epos_dir, vector.multiply(pdir, dist_to_epos))
local abs_epos_horiz_dir = vector.add(centre_point, vector.multiply(rel_epos_horiz_dir, -1))
local raycast = minetest.raycast(abs_epos_horiz_dir, obj:get_pos())
for pt in raycast do
if pt.type == "object" and pt.ref == obj then
local dist_to_psurface = vector.distance(abs_epos_horiz_dir, pt.intersection_point)
minetest.debug("dist_to_psurface: " .. dist_to_psurface)
if not (dist_to_psurface < 0.15) then
return
end
end
end
local cportal_dir = minetest.facedir_to_dir(minetest.get_node(connected_to).param2)
minetest.debug("cportal_dir: " .. minetest.pos_to_string(cportal_dir))
local box_rot = vector.subtract(vector.dir_to_rotation(cportal_dir), vector.dir_to_rotation(pdir_rot))
local new_colbox, new_selbox = portal.rotate_entity_bounding_box(obj, box_rot)
local target_pos = vector.add(connected_to, vector.multiply(vector.divide(cportal_dir, 2), dist_to_epos))
minetest.debug("target_pos: " .. minetest.pos_to_string(target_pos))
if minetest.get_node(target_pos).name ~= "air" and not portal.is_pos_busy_by_portal(target_pos) then
return
end
minetest.debug("set_pos()...")
obj:set_pos(target_pos)
obj:set_properties({collisionbox = new_colbox, selectionbox = new_selbox})
if obj:is_player() then
obj:set_look_vertical(obj:get_look_vertical()+box_rot.x)
obj:set_look_horizontal(obj:get_look_horizontal()+box_rot.y)
else
obj:set_rotation(vector.add(obj:get_rotation(), box_rot))
end
local cur_vel = obj:get_velocity()
local target_vel = vector.rotate(cur_vel, box_rot)
obj:add_velocity(vector.subtract(target_vel, cur_vel))
end
for _, obj in ipairs(catched_objs) do
iter_func(obj)
end
end
portal.is_pos_busy_by_portal = function(pos)
local portal_pos = minetest.find_node_near(pos, 1, {"portaltest:portal_orange", "portaltest:portal_blue"}, true)
if not portal_pos then return end
local dir_to_top = minetest.deserialize(minetest.get_meta(portal_pos):get_string("dir_to_top"))
local portal_pos2 = vector.add(portal_pos, dir_to_top)
return vector.distance(pos, portal_pos) < 0.5 or
vector.distance(pos, portal_pos2) < 0.5
end
portal.check_for_portal_footing = function(pos)
local dir_to_top = minetest.deserialize(minetest.get_meta(pos):get_string("dir_to_top"))
local back_dir = vector.multiply(minetest.facedir_to_dir(minetest.get_node(pos).param2), -1)
local node1 = minetest.get_node(vector.add(pos, back_dir))
local node2 = minetest.get_node(vector.add(pos, vector.add(back_dir, dir_to_top)))
if node1.name == "air" or node2.name == "air" then
minetest.remove_node(pos)
end
end
portal.remove = function(pos)
local connected_to = minetest.deserialize(minetest.get_meta(pos):get_string("connected_to"))
if not connected_to or connected_to == {} then
return
end
minetest.get_meta(connected_to):set_string("connected_to", "")
minetest.remove_node(pos)
end
minetest.register_node("portaltest:portal_orange", {
description = "Portal",
drawtype = "mesh",
mesh = "portaltest_portal.b3d",
tiles = {"portaltest_orange_portal.png"},
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
groups = {not_in_creative_inventory=1},
light_source = 14,
collision_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.4, -0.4}, -- Bottom Box
{-0.5, -0.4, -0.5, -0.4, 1.4, -0.4}, -- Left Box
{0.4, -0.4, -0.5, 0.5, 1.4, -0.4}, -- Right Box
{-0.5, 1.4, -0.5, 0.5, 1.5, -0.4} -- Top Box
}
},
selection_box = {
type = "fixed",
fixed = {0, 0, 0, 0, 0, 0}
},
on_construct = function(pos)
local timer = minetest.get_node_timer(pos)
timer:start(0.1)
end,
on_destruct = function(pos)
portal.remove(pos)
end,
on_timer = function(pos, elapsed)
portal.teleport_entity(pos)
portal.check_for_portal_footing(pos)
return true
end
})
minetest.register_node("portaltest:portal_blue", {
description = "Portal",
drawtype = "mesh",
mesh = "portaltest_portal.b3d",
tiles = {"portaltest_blue_portal.png"},
paramtype = "light",
paramtype2 = "facedir",
sunlight_propagates = true,
groups = {not_in_creative_inventory=1},
light_source = 14,
collision_box = {
type = "fixed",
fixed = {
{-0.5, -0.5, -0.5, 0.5, -0.4, -0.4}, -- Bottom Box
{-0.5, -0.4, -0.5, -0.4, 1.4, -0.4}, -- Left Box
{0.4, -0.4, -0.5, 0.5, 1.4, -0.4}, -- Right Box
{-0.5, 1.4, -0.5, 0.5, 1.5, -0.4} -- Top Box
}
},
selection_box = {
type = "fixed",
fixed = {0, 0, 0, 0, 0, 0}
},
on_construct = function(pos)
local timer = minetest.get_node_timer(pos)
timer:start(0.1)
end,
on_destruct = function(pos)
portal.remove(pos)
end,
on_timer = function(pos, elapsed)
portal.teleport_entity(pos)
portal.check_for_portal_footing(pos)
return true
end
})
|
require "aes"
--****f* Support/digestToHex
--* FUNCTION
--* Transform a digest (or any other) binary string to hexadecimal
--* SYNOPSIS
function digestToHex(k, addSpace)
--* PARAMETERS
--* * k -- the binary value
--* * addSpace -- add spaces
--* RETURN VALUE
--* Printable string
--* SOURCE
return (string.gsub(k, ".", function (c)
local res = string.format("%02X", string.byte(c));
if addSpace then res = res .. " " end;
return res;
end))
end
--****
print("\nThis should fail for no key length specified");
b,e = aes.cbc_encrypt("password", "my message")
print(b,e)
print("\nDecryption fail on invalid buffer length");
b,e = aes.cbc_decrypt(" as", "ase")
print(b,e)
print("\nDecryption fail on invalid key length");
b,e = aes.cbc_decrypt(" as", "aseqweqweqweqwea")
print(b,e)
print("\nEncryption");
b,e = aes.cbc_encrypt("This is a password string", "This is my crypted text", 128)
print(digestToHex(b, true),e)
print("\nDecryption");
b,e = aes.cbc_decrypt("This is a password string", b, 128)
print(b,e)
messages = { "this is a short message", "The quick brown fox jumped over the really lazy dog. No how is that? Why would a fox jump over a dog, is he just trying to torment him, or what? I dunno. Maybe we can find out if we check on Wikipedia" }
keysizes = { 128, 192, 256 }
for mi, msg in pairs(messages) do
print("\nCrypt test on", string.len(msg),"bytes");
print(msg);
print("========");
for ki, ksize in pairs(keysizes) do
print("Key size:", ksize);
res, err = aes.cbc_encrypt("This password", msg, ksize);
if res == nil then
print("CBC encryption FAILED!", err)
os.exit(1)
end
res, err = aes.cbc_decrypt("This password", res, ksize);
if res == nil then
print("CBC decryption FAILED!", err)
os.exit(1)
end
-- print("Original:", msg)
-- print("Recovered:", res)
assert(res == msg)
end
print("PASSED")
end
f = io.open("aes_test", "r");
if f == nil then
print ("The file aes_test does not exist. Execute 'make test' to build it");
os.exit(1)
end
msg = f:read("*all");
f:close();
print("\nBinary test on ", msg:len(), "bytes");
for ki, ksize in pairs(keysizes) do
print("Key size:", ksize);
res, err = aes.cbc_encrypt("This password", msg, ksize);
if res == nil then
print("CBC encryption FAILED!", err)
os.exit(1)
end
local cbc = res
res, err = aes.cbc_decrypt("This password", res, ksize);
if res == nil then
print("CBC decryption FAILED!", err)
os.exit(1)
end
res2, err = aes.ecb_encrypt("This password", msg, ksize);
if res2 == nil then
print("ECB encryption FAILED!", err)
os.exit(1)
end
local ecb = res2
assert(cbc ~= ecb)
res2, err = aes.ecb_decrypt("This password", res2, ksize);
if res2 == nil then
print("ECB decryption FAILED!", err)
os.exit(1)
end
-- print("Original:", msg)
-- print("Recovered:", res)
assert(res == msg)
end
print("PASSED")
print("\nUsing binary for key")
res, err = aes.cbc_encrypt(msg, msg, ksize);
if res == nil then
print("CBC encryption FAILED!", err)
os.exit(1)
end
assert(res ~= msg)
res, err = aes.cbc_decrypt(msg, res, ksize);
if res == nil then
print("CBC decryption FAILED!", err)
os.exit(1)
end
assert(res == msg)
print("PASSED")
|
data:extend(
{
{
type = "item",
name = "steel-gear-wheel",
icon = "__spicy-teeth-core_assets__/graphics/icons/steel-gear-wheel.png",
icon_size = 32,
subgroup = "intermediate-product",
order = "ca[steel-gear-wheel]",
stack_size = 100
}
}
)
|
local PANEL = {}
function PANEL:Init()
self:SetSize(ScrW()-492,ScrH()-256)
self:SetTitle("New Game")
self:SetIcon("icon16/world_add.png")
self:Center()
self:MakePopup()
self.SelectedMap = ""
self.Side = vgui.Create("DScrollPanel",self)
self.Side:Dock(LEFT)
self.Side:SetWide(192)
self.Side:DockMargin(4,4,4,4)
self.Side:SetPaintBackground(true)
self.Categories = {}
self.List = vgui.Create("DScrollPanel",self)
self.List:Dock(FILL)
self.List:DockMargin(4,4,4,4)
self.List:SetPaintBackground(true)
self.MapList = vgui.Create("DIconLayout",self.List)
self.MapList:SetSpaceX(4)
self.MapList:SetSpaceY(4)
self.MapList:SetBorder(4)
self.MapList:Dock(FILL)
self.MapList:SetTall(10000)
self.List:AddItem(self.MapList)
self.Settings = vgui.Create("DScrollPanel",self)
self.Settings:Dock(RIGHT)
self.Settings:SetWide(234)
self.Settings:DockMargin(4,4,4,4)
self.Settings:DockPadding(4,4,4,4)
self.Settings:SetPaintBackground(true)
self.btnMaxim:SetVisible(false)
self.btnMinim:SetVisible(false)
self.btnClose.alpha = 128
self.lblTitle.UpdateColors = function(s)
s:SetColor(Color(255,255,255))
end
--[[function self.btnClose:Paint(w,h)
self.alpha = Lerp(0.05,self.alpha,self.Hovered and 255 or 128)
draw.RoundedBox(0,0,2,w,20,Color(244,67,54,self.alpha))
draw.SimpleText("r", "Marlett", w/2, h/2, Color(255,255,255,self.alpha), 1, 1)
end--]]
self:SetupCategories()
self:SetupMaps("Sandbox")
self:SetupSettings()
end
function PANEL:SetupSettings()
local pnlHost = vgui.Create("EditablePanel",self.Settings)
pnlHost:Dock(TOP)
pnlHost:DockMargin(4,4,4,4)
local lblHost = vgui.Create("DLabel",pnlHost)
lblHost:Dock(LEFT)
lblHost:SetText("Hostname:")
lblHost:SizeToContents()
lblHost:SetDark(true)
local hostname = vgui.Create("DTextEntry",pnlHost)
hostname:SetConVar("hostname")
hostname:Dock(FILL)
hostname:DockMargin(16, 0, 0, 0)
self.Settings:Add(pnlHost)
local pnlGM = vgui.Create("EditablePanel",self.Settings)
pnlGM:Dock(TOP)
pnlGM:DockMargin(4,4,4,4)
local lblGM = vgui.Create("DLabel",pnlGM)
lblGM:Dock(LEFT)
lblGM:SetText("Gamemode:")
lblGM:SizeToContents()
lblGM:SetDark(true)
local dropGM = vgui.Create("DComboBox",pnlGM)
dropGM:Dock(FILL)
dropGM:DockMargin(16, 0, 0, 0)
for _, data in pairs(engine.GetGamemodes()) do
if not data.menusystem then continue end
local icon = ("gamemodes/%s/icon24.png"):format(data.name)
local hasIcon = file.Exists(icon, "GAME")
dropGM:AddChoice(data.title, data.name, engine.ActiveGamemode() == data.name, hasIcon and icon or "icon16/brick.png")
end
dropGM.OnSelect = function(s, index, text, val)
RunConsoleCommand("gamemode", val)
end
-- stupid hack
dropGM.OpenMenu = function(s, pControlOpener)
if pControlOpener and pControlOpener == s.TextEntry then
return
end
-- Don't do anything if there aren't any options..
if ( #s.Choices == 0 ) then return end
-- If the menu still exists and hasn't been deleted
-- then just close it and don't open a new one.
if ( IsValid( s.Menu ) ) then
s.Menu:Remove()
s.Menu = nil
end
s.Menu = DermaMenu( false, s )
if ( s:GetSortItems() ) then
local sorted = {}
for k, v in pairs( s.Choices ) do
local val = tostring( v ) --tonumber( v ) || v -- This would make nicer number sorting, but SortedPairsByMemberValue doesn't seem to like number-string mixing
if ( string.len( val ) > 1 and not tonumber( val ) and val:StartWith( "#" ) ) then val = language.GetPhrase( val:sub( 2 ) ) end
table.insert( sorted, { id = k, data = v, label = val } )
end
for k, v in SortedPairsByMemberValue( sorted, "label" ) do
local option = s.Menu:AddOption( v.data, function() s:ChooseOption( v.data, v.id ) end )
if ( s.ChoiceIcons[ v.id ] ) then
option:SetIcon( s.ChoiceIcons[ v.id ] )
option.m_Image:SetSize(16, 16) -- stupid hack
end
end
else
for k, v in pairs( s.Choices ) do
local option = s.Menu:AddOption( v, function() s:ChooseOption( v, k ) end )
if ( s.ChoiceIcons[ k ] ) then
option:SetIcon( s.ChoiceIcons[ k ] )
option.m_Image:SetSize(16, 16) -- stupid hack
end
end
end
local x, y = s:LocalToScreen( 0, s:GetTall() )
s.Menu:SetMinimumWidth( s:GetWide() )
s.Menu:Open( x, y, false, s )
end
local maxplayers = vgui.Create("DNumSlider",self)
maxplayers:SetText("Max Players:")
maxplayers:SetMin(2)
maxplayers:SetMax(128)
maxplayers:SetDecimals(0)
maxplayers:SetValue(tonumber(cookie.GetNumber("cashout_maxplayers")) or 2)
maxplayers:Dock(TOP)
maxplayers:DockMargin(4,4,4,4)
maxplayers:SetDark(true)
function maxplayers:OnValueChanged(value)
cookie.Set("cashout_maxplayers",math.Round(value))
end
self.Settings:Add(maxplayers)
local lan = vgui.Create("DCheckBoxLabel",self.Settings)
lan:Dock(TOP)
lan:DockMargin(4,4,4,4)
lan:SetText("LAN Only")
lan:SetConVar("sv_lan")
lan:SizeToContents()
lan:SetDark(true)
self.Settings:Add(lan)
local p2p = vgui.Create("DCheckBoxLabel",self.Settings)
p2p:Dock(TOP)
p2p:DockMargin(4,4,4,4)
p2p:SetText("P2P Enabled")
p2p:SetConVar("p2p_enabled")
p2p:SizeToContents()
p2p:SetDark(true)
self.Settings:Add(p2p)
local p2p_fo = vgui.Create("DCheckBoxLabel",self.Settings)
p2p_fo:Dock(TOP)
p2p_fo:DockMargin(4,4,4,4)
p2p_fo:SetText("P2P Friends Only")
p2p_fo:SetConVar("p2p_friendsonly")
p2p_fo:SizeToContents()
p2p_fo:SetDark(true)
self.Settings:Add(p2p_fo)
self.sp = vgui.Create("DButton",self.Settings)
self.sp:Dock(TOP)
self.sp:DockMargin(4,4,4,4)
self.sp:SetTall(32)
self.sp:SetText("Singleplayer")
self.Settings:Add(self.sp)
self.sp.DoClick = function(p)
if self.SelectedMap == "" then return end
RunGameUICommand("disconnect")
timer.Simple(0.1, function()
RunConsoleCommand("hostname",hostname:GetValue())
RunConsoleCommand("maxplayers",1)
RunConsoleCommand("map",self.SelectedMap:Trim())
self:Remove()
end)
end
self.sp.Think = function(p) p:SetDisabled(self.SelectedMap == "" and true or false) end
self.mp = vgui.Create("DButton",self.Settings)
self.mp:Dock(TOP)
self.mp:DockMargin(4,4,4,4)
self.mp:SetTall(32)
self.mp:SetText("Multiplayer")
self.Settings:Add(self.mp)
self.mp.DoClick = function(p)
if self.SelectedMap == "" then return end
RunGameUICommand("disconnect")
timer.Simple(0.1, function()
RunConsoleCommand("hostname",hostname:GetValue())
RunConsoleCommand("maxplayers",math.Round(maxplayers:GetValue()))
RunConsoleCommand("map",self.SelectedMap:Trim())
self:Remove()
end)
end
self.mp.Think = function(p) p:SetDisabled(self.SelectedMap == "" and true or false) end
end
function PANEL:SetupCategories()
self.Side:Clear()
local mlist = GetMapList()
for k,v in SortedPairs(mlist) do
self.Categories[k] = vgui.Create("DButton")
local btn = self.Categories[k]
btn:SetText(("%s (%d)"):format(k,#mlist[k]))
btn:Dock(TOP)
btn:DockMargin(4,4,4,4)
btn:SetTall(32)
btn.DoClick = function(p)
self:SetupMaps(k)
end
self.Side:Add(btn)
end
end
function PANEL:SetupMaps(cat)
self.MapList:Clear()
for _,v in SortedPairs(GetMapList()[cat]) do
self.MapList:Add(self:CreateMapIcon(v))
end
timer.Simple(0,function()
self.MapList:SizeToContents()
self.List:InvalidateLayout()
self.List:PerformLayout()
end)
self.List.VBar:AnimateTo( 0, 0.5, 0, 0.5 )
end
function PANEL:CreateMapIcon(name)
local map = vgui.Create("DButton")
map:SetSize(128,144)
map.Paint = function() end
map.MapName = name
map.DoClick = function(p) self.SelectedMap = p.MapName end
local mname = vgui.Create("EditablePanel",map)
mname:Dock(BOTTOM)
mname:SetTall(16)
mname.Paint = function(p,w,h)
draw.RoundedBox(0, 0, 0, w, h, self.SelectedMap == map.MapName and Color(255,128,0) or Color(64,64,64))
draw.SimpleText(name, "DermaDefault", w/2, h/2, Color(255,255,255), 1, 1)
end
local icon = vgui.Create("DImage",map)
icon:Dock(FILL)
if Material("maps/thumb/"..name..".png"):IsError() then
icon:SetImage("gui/noicon.png")
else
icon:SetImage("maps/thumb/"..name..".png")
end
return map
end
--[[function PANEL:Paint(w,h)
draw.RoundedBox(0,0,0,w,h,Color(0,0,0,240))
draw.RoundedBox(0,0,0,w,24,Color(0,96,192))
end--]]
vgui.Register( "CashoutNewGame", PANEL, "DFrame" )
function CashoutNewGame()
if IsValid(_G.NewGameMenu) then _G.NewGameMenu:Remove() end
_G.NewGameMenu = vgui.Create("CashoutNewGame")
end |
object_tangible_meatlump_event_meatlump_map_01_11 = object_tangible_meatlump_event_shared_meatlump_map_01_11:new {
}
ObjectTemplates:addTemplate(object_tangible_meatlump_event_meatlump_map_01_11, "object/tangible/meatlump/event/meatlump_map_01_11.iff")
|
local host = "192.168.4.1"
local ip
local ip_broadcast = "192.168.4.255"
local port = 2018
local socket = require("__socket")
local udp = assert(socket.udp())
local DELIMITER = '*'
local COLOR_CMD = 'color'
local GET_PARAM = 'get_param'
local SET_PARAM = 'set_param'
local tics_timeout_teleop = 0
local autonomous = true
local apds = assert(require('apds9960'))
local ledpin = pio.GPIO19
local n_pins = 24
local led_pow = 10
local min_sat = 60
local min_val = 33
local max_val = 270
local colors = {
-- robotito 5, 2, 0
-- {"orange", 12, 17}, -- 12
{"yellow", 45, 62}, --53-55, 46 - 48, 61 ;: todos
{"green", 159, 185}, -- 162-164, 183, x ;: todos 159, 185
{"blue", 208, 216}, -- 208-210, 212 - 213, x ;: todos 208, 216
{"rose", 250, 271}, -- 264 - 268, 257, 250 ;: todos 250, 271
{"red", 351 , 353}, -- 355 - 357, 343 - 346, x ;: todos 343 , 359
-- {"violet", 221, 240},
}
local offset_led = 2 -- robotito 5 (20), robotito 1,3, 8 (2), robotito 2 (5), robotito 0 (8)
assert(apds.init())
local distC = apds.proximity
assert(distC.enable())
local color = apds.color
assert(color.set_color_table(colors))
assert(color.set_sv_limits(min_sat,min_val,max_val))
assert(color.enable())
local led_const = require('led_ring')
local neo = led_const(ledpin, n_pins, led_pow)
local m = require('omni')
local global_enable = true
local local_enable = false
m.set_enable(global_enable and local_enable)
local ms_dist = 200
local ms_color = 80
local thershold = 251
local histeresis = 3
local H_OFF = {"H_OFF"}
local H_ON = {"H_ON"}
local h_state = H_OFF
local last_color = "NONE"
local tics_same_color = 0
local TICS_NEW_COLOR = 4
local x_dot = 0
local y_dot = 0
local w = 0
-- callback for distC.get_dist_thresh
-- will be called when the robot is over threshold high
local dump_dist = function(b)
if b then
last_color = "NONE"
tics_same_color = 0
h_state = H_ON
local_enable = true
else
x_dot = 0
y_dot = 0
w = 0
local_enable = false
m.set_enable(local_enable and global_enable)
m.drive(x_dot,y_dot,w)
h_state = H_OFF
turn_all_leds(0,0,0)
end
end
-- enable distC change monitoring
distC.get_dist_thresh(ms_dist, thershold, histeresis, dump_dist)
function turn_all_leds(r,g,b)
if (r + g + b) == 0 then -- draw axis
neo.clear()
neo.set_led(offset_led, 50,0,0, true)
neo.set_led((offset_led + 6)%24, 0,50,0 , true)
neo.set_led((offset_led + 12)%24, 0,0,50 , true)
neo.set_led((offset_led + 18)%24,160 , 100, 0, true)
-- robotito 1
-- neo.set_led(2, 50,0,0, true)
-- neo.set_led(8,0,50,0 , true)
-- neo.set_led(14, 0,0,50 , true)
-- neo.set_led(20,160 , 100, 0, true)
else
for pixel= offset_led, offset_led+24, 6 do
neo.set_led((pixel+2)%24, r, g, b, true)
neo.set_led((pixel+3)%24, r, g, b, true)
end
end
end
dump_rgb = function(r,g,b,a,h,s,v, c)
local MAX_VEL = 0.07
local MAX_TICS_TIMEOUT_TELEOP = 10 * 1000 / ms_color -- 10 seg
if not autonomous then
tics_timeout_teleop = tics_timeout_teleop + 1
if tics_timeout_teleop >= MAX_TICS_TIMEOUT_TELEOP then
tics_timeout_teleop = 0
x_dot = 0
y_dot = 0
w = 0
local_enable = false
m.set_enable(local_enable and global_enable)
m.drive(x_dot,y_dot,w)
-- TODO: dont return to autonomous
-- autonomous = true
end
elseif h_state == H_ON then
--print('color', c, 'sv', s, v)
if last_color == c then
if tics_same_color < TICS_NEW_COLOR then
tics_same_color = tics_same_color + 1
elseif tics_same_color == TICS_NEW_COLOR then
tics_same_color = tics_same_color + 1 -- last time that run this code
-- print('new color')
if c == "red" then
x_dot = MAX_VEL
y_dot = 0
w = 0
turn_all_leds(50,0,0)
elseif c == 'blue' then
x_dot = -MAX_VEL
y_dot = 0
w = 0
turn_all_leds(0,0,50)
elseif c == 'green' then
x_dot = 0
y_dot = MAX_VEL
w = 0
turn_all_leds(0,50,0)
elseif c == 'yellow' then --or c == 'orange' then
x_dot = 0
y_dot = -MAX_VEL
w = 0
-- turn_all_leds(255,0,140) -- violet
-- turn_all_leds(255,70,0) -- orange
turn_all_leds(160,100,0) -- yellow
-- else
-- turn_all_leds(0,0,0)
elseif c == 'rose' then
x_dot = 0
y_dot = 0
w = 0.5
turn_all_leds(255,0,140) -- violet
end
m.set_enable(local_enable and global_enable)
m.drive(x_dot,y_dot,w)
end
else
last_color = c
tics_same_color = 0
end
-- neo.clear()
end
local sens_str = COLOR_CMD .. DELIMITER .. tostring(r) .. DELIMITER .. tostring(g) .. DELIMITER .. tostring(b) .. DELIMITER .. tostring(a) .. DELIMITER .. tostring(h) .. DELIMITER .. tostring(s) .. DELIMITER .. tostring(v) .. DELIMITER .. c
udp:sendto(sens_str, ip_broadcast, port)
-- print('ambient:', a, 'rgb:', r, g, b,'hsv:', h, s, v, 'name:', name)
end
-- callback for color.get_continuous
-- will be called with (r,g,b,a [,h,s,v])
-- hsv will be provided if enabled on color.get_continuous
-- r,g,b,a : 16 bits
-- h: 0..360
-- s,v: 0..255
--power on led
local led_color_pin = pio.GPIO32
pio.pin.setdir(pio.OUTPUT, led_color_pin)
pio.pin.sethigh(led_color_pin)
-- enable raw color monitoring, enable hsv mode
color.get_continuous(ms_color, dump_rgb, true)
-- enable color change monitoring, enable hsv mode
-- color.get_change(ms, change_direction)
print("ready to playt with colors")
function split(s, delimiter)
local result = {};
for match in (s..delimiter):gmatch("(.-)"..delimiter) do
table.insert(result, match)
end
return result
end
local VEL_CMD = 'speed'
print("Binding to host '" .. tostring(host) .. "' and port " .. tostring(port) .. "...")
udp:setoption('broadcast', true)
assert(udp:setsockname(host, port))
-- assert(udp:settimeout(5))
ip, port = udp:getsockname()
assert(ip, port)
print("Waiting packets on " .. tostring(ip) .. ":" .. tostring(port) .. "...")
turn_all_leds(0,0,0)
thread.start(function()
local cmd
local dgram
local msg
local namespace, parameter, value
while 1 do
dgram, ip, port = udp:receivefrom()
if dgram then
-- print("Echoing '" .. dgram .. "' to " .. ip .. ":" .. port)
cmd = split(dgram, '*')
if cmd[1] == VEL_CMD then
if #cmd == 5 then
autonomous = false
neo.clear()
neo.set_led((offset_led + 5)%24, 0,50,0 , true)
neo.set_led((offset_led + 6)%24, 0,50,0 , true)
neo.set_led((offset_led + 7)%24, 0,50,0 , true)
tics_timeout_teleop = 0
x_dot = cmd[2]
y_dot = cmd[3]
w = cmd[4]
local_enable = not (x_dot==0 and y_dot==0 and w ==0)
m.set_enable(local_enable and global_enable)
m.drive(x_dot,y_dot,w)
msg = '[INFO] Speed command received (' .. tostring(x_dot) .. ', ' .. tostring(y_dot) .. ')'
else
msg = '[ERROR] Malformed command.'
end
elseif cmd[1] == SET_PARAM then
if #cmd == 4 then
namespace = cmd[2]
parameter = cmd[3]
value = cmd[4]
nvs.write(namespace, parameter, value)
if namespace == 'motors' and parameter == 'enable' then
global_enable = value == 'true'
m.set_enable(global_enable and local_enable)
end
msg = '[INFO] Set parameter command received (' .. tostring(namespace) .. ', ' .. tostring(parameter) .. ', ' .. tostring(value) .. ')'
else
msg = '[ERROR] Malformed command.'
end
elseif cmd[1] == GET_PARAM then
if #cmd == 3 then
namespace = cmd[2]
parameter = string.gsub(cmd[3], "\n", "")
-- print(parameter, '....', namespace)
value = nvs.read(namespace, parameter, 'key not found')
msg = '[INFO] Get parameter command received (' .. tostring(namespace) .. ', ' .. tostring(parameter) .. ', ' .. tostring(value) .. ')'
else
msg = '[ERROR] Malformed command.'
end
else
msg = '[ERROR] Unknown command: ' .. cmd[1]
end
-- print(msg)
udp:sendto(msg, ip_broadcast, port)
end -- if dgram
end -- while true
end) --end thread
|
local gumbo = require "gumbo"
local assert, rawequal, getmetatable = assert, rawequal, getmetatable
local _ENV = nil
do
local input = "<!doctype html><p>no-quirks!</p>"
local document = assert(gumbo.parse(input))
local doctype = assert(document.doctype)
assert(document.compatMode == "CSS1Compat")
assert(doctype.nodeType == document.DOCUMENT_TYPE_NODE)
assert(doctype.nodeName == doctype.name)
assert(doctype.name == "html")
assert(doctype.publicId == "")
assert(doctype.systemId == "")
doctype.publicId = nil
assert(doctype.publicId == "")
doctype.systemId = nil
assert(doctype.systemId == "")
end
do
local pubid = "-//W3C//DTD XHTML 1.1//EN"
local sysid = "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"
local input = ('<!DOCTYPE html PUBLIC "%s" "%s">'):format(pubid, sysid)
local document = assert(gumbo.parse(input))
local doctype = assert(document.doctype)
assert(doctype:isEqualNode(document.childNodes[1]))
assert(rawequal(doctype, document.childNodes[1]))
assert(doctype.name == "html")
assert(doctype.publicId == pubid)
assert(doctype.systemId == sysid)
local clone = assert(doctype:cloneNode())
assert(clone:isEqualNode(doctype))
assert(not rawequal(clone, doctype))
assert(not rawequal(clone, document.childNodes[1]))
assert(clone.name == "html")
assert(clone.publicId == pubid)
assert(clone.systemId == sysid)
assert(getmetatable(clone))
assert(getmetatable(clone) == getmetatable(doctype))
end
|
data:extend({
{
type = "int-setting",
name = "TfC_max_speed_bonus",
setting_type = "runtime-global",
default_value = 6,
minimum_value = 1,
maximum_value = 100
}, {
type = "int-setting",
name = "TfC_max_compensated_ticks",
setting_type = "runtime-global",
maximum_value = 60 * 60 * 60,
default_value = 60 * 60 * 2,
minimum_value = 1
}, {
type = "int-setting",
name = "TfC_minimum_speed_bonus",
setting_type = "runtime-global",
default_value = 0,
minimum_value = -10,
maximum_value = 10
}
})
|
test = require 'u-test'
common = require 'common'
function GetUserProfilesForSocialGroupCpp_Handler()
print("GetUserProfilesForSocialGroupCpp_Handler")
ProfileServiceGetUserProfilesForSocialGroup()
end
function OnProfileServiceGetUserProfilesForSocialGroup()
print("OnProfileServiceGetUserProfilesForSocialGroup")
test.stopTest();
end
test.GetUserProfilesForSocialGroupCpp = function()
common.init(GetUserProfilesForSocialGroupCpp_Handler)
end
|
local _renderMask = 0x2
local _invRenderMask = bit.bnot(_renderMask)
kHiveVisionOutlineColor = enum { [0]='Blue', 'Green', 'KharaaOrange' }
kHiveVisionOutlineColorCount = #kHiveVisionOutlineColor+1
-- Adds a model to the hive vision
function HiveVision_AddModel(model, color)
local renderMask = model:GetRenderMask()
model:SetRenderMask( bit.bor(renderMask, _renderMask) )
local outlineid = Clamp( color or kHiveVisionOutlineColor.KharaaOrange, 0, kHiveVisionOutlineColorCount )
model:SetMaterialParameter("outline", outlineid/kHiveVisionOutlineColorCount + 0.5/kHiveVisionOutlineColorCount )
end
-- Removes a model from the hive vision
function HiveVision_RemoveModel(model)
if model then
local renderMask = model:GetRenderMask()
model:SetRenderMask( bit.band(renderMask, _invRenderMask) )
end
end
|
---@type table<string, module>
local modules = {}
modules["lua-compiler"] = require("models/lua-compiler")
local module = modules["lua-compiler"]
if remote.interfaces["disable-lua-compiler"] then
module.events = nil
module.on_nth_tick = nil
module.commands = nil
module.on_load = nil
module.add_remote_interface = nil
module.add_commands = nil
end
local event_handler
if script.active_mods["zk-lib"] then
event_handler = require("__zk-lib__/static-libs/lualibs/event_handler_vZO.lua")
else
event_handler = require("event_handler")
end
event_handler.add_libraries(modules)
|
if (SERVER) then
ENT.Base = "base_nextbot"
else
ENT.Type = "anim"
ENT.Base = "base_anim"
end
function ENT:SetupDataTables()
self:NetworkVar("String", 0, "StructName");
self:NetworkVar("Int", 1, "StructHealth");
self:NetworkVar("Int", 2, "StructFaction")
self:NetworkVar("Int", 3, "StructID")
self:NetworkVar("Vector", 4, "TargetPOS")
self:NetworkVar("Bool", 5, "Tasked")
self:NetworkVar("Bool", 6, "Worker")
end
function ENT:GetSize()
if (!self.size) then
self.modelMins, self.modelMaxs = self:OBBMins(), self:OBBMaxs()
self.size = self.modelMaxs.x
end
return self.size
end
function ENT:GetGroundTrace()
return util.TraceLine({
start = self:GetPos() + vector_up * 64,
endpos = self:GetPos() + vector_up*-512,
filter = self
})
end
function ENT:GetGroundPos()
return self:GetGroundTrace().HitPos
end
function ENT:GetGroundNormal()
return self:GetGroundTrace().HitNormal
end
local mCircle = Material("sassilization/circle")
function ENT:Draw()
self:DrawModel()
self:DrawCircle(self:GetSize())
end
function ENT:DrawCircle(size, color)
render.SetMaterial(mCircle)
local color = Color(255,0,0,0)
if self:GetTasked() then
color = Color(0, 255, 0)
end
render.DrawQuadEasy(self:GetGroundPos() + Vector(0, 0, 1) * 0.1, self:GetGroundNormal(), size, size, color)
end
|
-- websocket support adaptded from lua-websocket (http://lipp.github.io/lua-websockets/)
local sha1 = require'tasks/http-server/sha1'.sha1_binary
local base64 = require'tasks/http-server/base64'
local tinsert = table.insert
local guid = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
local sec_websocket_accept = function(sec_websocket_key)
local a = sec_websocket_key..guid
local a_sha1 = sha1(a)
assert((#a_sha1 % 2) == 0)
return base64.encode(a_sha1)
end
local http_headers = function(request)
local headers = {}
if not request:match('.*HTTP/1%.1') then
return
end
request = request:match('[^\r\n]+\r\n(.*)')
local empty_line
for line in request:gmatch('[^\r\n]*\r\n') do
local name,val = line:match('([^%s]+)%s*:%s*([^\r\n]+)')
if name and val then
name = name:lower()
if not name:match('sec%-websocket') then
val = val:lower()
end
if not headers[name] then
headers[name] = val
else
headers[name] = headers[name]..','..val
end
elseif line == '\r\n' then
empty_line = true
else
assert(false,line..'('..#line..')')
end
end
return headers,request:match('\r\n\r\n(.*)')
end
local upgrade_request = function(req)
local format = string.format
local lines = {
format('GET %s HTTP/1.1',req.uri or ''),
format('host: %s',req.host),
'upgrade: websocket',
'connection: Upgrade',
format('sec-websocket-key: %s',req.key),
format('sec-websocket-protocol: %s',table.concat(req.protocols,', ')),
'sec-websocket-version: 13',
}
if req.origin then
tinsert(lines,string.format('origin: %s',req.origin))
end
if req.port and req.port ~= 80 then
lines[2] = format('host: %s:%d',req.host,req.port)
end
tinsert(lines,'\r\n')
return table.concat(lines,'\r\n')
end
local accept_upgrade = function(request,protocols)
local headers = request --http_headers(request)
if headers['upgrade'] ~= 'websocket' or
not headers['connection'] or
not headers['connection']:match('Upgrade') or
headers['sec-websocket-key'] == nil or
headers['sec-websocket-version'] ~= '13' then
return 400, nil, nil --'HTTP/1.1 400 Bad Request\r\n\r\n'
end
local prot
if headers['sec-websocket-protocol'] then
for protocol in headers['sec-websocket-protocol']:gmatch('([^,%s]+)%s?,?') do
if protocols[protocol] then
prot = protocol
break
end
end
end
local out_header = {
['upgrade'] = 'websocket',
['connection'] = headers['connection'],
['sec-websocket-accept'] = sec_websocket_accept(headers['sec-websocket-key']),
}
if prot then
out_header['sec-websocket-protocol'] = prot
end
return 101, out_header, prot
end
return {
sec_websocket_accept = sec_websocket_accept,
http_headers = http_headers,
accept_upgrade = accept_upgrade,
upgrade_request = upgrade_request,
}
|
return {
id = "G003",
curtain = true,
type = 1,
scripts = {
{
actor = 201010,
side = 0,
say = "指挥官一定还记得在学校学习过的战斗方法吧?只要在对方的船只和飞机越过警戒线对旗舰造成伤害前击破他们就可以了!"
},
{
actor = 107070,
side = 0,
say = "因为是演习,所以这次装备的都是空包弹,请放心战斗吧~"
}
}
}
|
-- hooks for watching cooldown events
local _, Addon = ...
local GCD_SPELL_ID = 61304
local COOLDOWN_TYPE_LOSS_OF_CONTROL = _G.COOLDOWN_TYPE_LOSS_OF_CONTROL
local GetSpellCooldown = _G.GetSpellCooldown
local GetTime = _G.GetTime
local cooldowns = {}
local Cooldown = {}
-- queries
function Cooldown:CanShow()
local start, duration = self._occ_start, self._occ_duration
-- no active cooldown
if start <= 0 or duration <= 0 then
return false
end
-- text enabled
local sets = self._occ_settings
if not (sets and sets.enableText) then
return false
end
-- at least min duration
if duration < sets.minDuration then
return false
end
local t = GetTime()
-- expired cooldowns
if (start + duration) <= t then
return false
end
-- future cooldowns that don't start for at least a day
-- these are probably buggy ones
if (start - t) > 86400 then
return false
end
-- filter GCD
local gcdStart, gcdDuration = GetSpellCooldown(GCD_SPELL_ID)
if start == gcdStart and duration == gcdDuration then
return false
end
return true
end
function Cooldown:GetKind()
if self.currentCooldownType == COOLDOWN_TYPE_LOSS_OF_CONTROL then
return "loc"
end
local parent = self:GetParent()
if parent and parent.chargeCooldown == self then
return "charge"
end
return "default"
end
function Cooldown:GetPriority()
if self._occ_kind == "charge" then
return 2
end
return 1
end
-- actions
function Cooldown:Initialize()
if cooldowns[self] then return end
cooldowns[self] = true
self._occ_start = 0
self._occ_duration = 0
self._occ_settings = Addon:GetCooldownSettings(self)
self:HookScript("OnShow", Cooldown.OnVisibilityUpdated)
self:HookScript("OnHide", Cooldown.OnVisibilityUpdated)
end
function Cooldown:ShowText()
local oldDisplay = self._occ_display
local newDisplay = Addon.Display:GetOrCreate(self:GetParent() or self)
if oldDisplay ~= newDisplay then
self._occ_display = newDisplay
if oldDisplay then
oldDisplay:RemoveCooldown(self)
end
end
if newDisplay then
newDisplay:AddCooldown(self)
end
end
function Cooldown:HideText()
local display = self._occ_display
if display then
display:RemoveCooldown(self)
self._occ_display = nil
end
end
function Cooldown:UpdateText()
if self._occ_show and self:IsVisible() then
Cooldown.ShowText(self)
else
Cooldown.HideText(self)
end
end
do
local pending = {}
local updater = Addon:CreateHiddenFrame('Frame')
updater:SetScript("OnUpdate", function(self)
for cooldown in pairs(pending) do
Cooldown.UpdateText(cooldown)
pending[cooldown] = nil
end
self:Hide()
end)
function Cooldown:RequestUpdateText()
if not pending[self] then
pending[self] = true
updater:Show()
end
end
end
function Cooldown:Refresh(force)
local start, duration = self:GetCooldownTimes()
start = (start or 0) / 1000
duration = (duration or 0) / 1000
if force then
self._occ_start = nil
self._occ_duration = nil
end
Cooldown.Initialize(self)
Cooldown.SetTimer(self, start, duration)
end
function Cooldown:SetTimer(start, duration)
if self._occ_start == start and self._occ_duration == duration then
return
end
self._occ_start = start
self._occ_duration = duration
self._occ_kind = Cooldown.GetKind(self)
self._occ_show = Cooldown.CanShow(self)
self._occ_priority = Cooldown.GetPriority(self)
Cooldown.RequestUpdateText(self)
end
function Cooldown:SetNoCooldownCount(disable, owner)
owner = owner or true
if disable then
if not self.noCooldownCount then
self.noCooldownCount = owner
Cooldown.HideText(self)
end
elseif self.noCooldownCount == owner then
self.noCooldownCount = nil
Cooldown.Refresh(self, true)
end
end
-- events
function Cooldown:OnSetCooldown(start, duration)
if self.noCooldownCount or self:IsForbidden() then return end
start = start or 0
duration = duration or 0
Cooldown.Initialize(self)
Cooldown.SetTimer(self, start, duration)
end
function Cooldown:OnSetCooldownDuration()
if self.noCooldownCount or self:IsForbidden() then return end
Cooldown.Refresh(self)
end
function Cooldown:SetDisplayAsPercentage()
if self.noCooldownCount or self:IsForbidden() then return end
Cooldown.SetNoCooldownCount(self, true)
end
function Cooldown:OnVisibilityUpdated()
if self.noCooldownCount or self:IsForbidden() then return end
Cooldown.RequestUpdateText(self)
end
-- misc
function Cooldown:SetupHooks()
local Cooldown_MT = getmetatable(ActionButton1Cooldown).__index
hooksecurefunc(Cooldown_MT, "SetCooldown", Cooldown.OnSetCooldown)
hooksecurefunc(Cooldown_MT, "SetCooldownDuration", Cooldown.OnSetCooldownDuration)
hooksecurefunc("CooldownFrame_SetDisplayAsPercentage", Cooldown.SetDisplayAsPercentage)
end
function Cooldown:UpdateSettings()
for cd in pairs(cooldowns) do
local newSettings = Addon:GetCooldownSettings(cd)
if cd._occ_settings ~= newSettings then
cd._occ_settings = newSettings
Cooldown.Refresh(cd, true)
end
end
end
-- exports
Addon.Cooldown = Cooldown |
BeardLib.Items.PopupMenu = BeardLib.Items.PopupMenu or class(BeardLib.Items.Item)
local PopupMenu = BeardLib.Items.PopupMenu
PopupMenu.type_name = "PopupMenu"
PopupMenu.MENU = true
function PopupMenu:InitBasicItem()
PopupMenu.super.InitBasicItem(self)
self._scroll = ScrollablePanelModified:new(self.menu._panel, "ItemsPanel", {
layer = self.parent._popup_menu and self.parent._popup_menu:layer() + 100 or 100,
padding = 0,
scroll_width = self.scrollbar == false and 0 or self.scroll_width,
hide_shade = true,
debug = self.debug,
change_width = true,
color = self.scroll_color or self.highlight_color,
hide_scroll_background = self.hide_scroll_background,
scroll_speed = self.scroll_speed
})
self._popup_menu = self._scroll:panel()
self._popup_menu:set_visible(false)
self._popup_menu:bitmap({
name = "background",
halign = "grow",
valign = "grow",
visible = self.context_background_visible,
render_template = self.context_background_blur and "VertexColorTexturedBlur3D",
texture = self.context_background_blur and "guis/textures/test_blur_df",
color = self.context_background_color,
alpha = self.context_background_alpha
})
self.items_panel = self._scroll:canvas()
end
function PopupMenu:WorkParams(params)
self.auto_height = NotNil(self.auto_height, true)
self:WorkParam("offset", 0)
self:WorkParam("keep_menu_open", false)
PopupMenu.super.WorkParams(self, params)
end
function PopupMenu:RepositionPopupMenu()
local size = (self.font_size or self.size)
local offset_y = self.context_screen_offset_y or 32
local bottom_h = (self.menu._panel:world_bottom() - self.panel:world_bottom()) - offset_y
local top_h = (self.panel:world_y() - self.panel:world_y()) - offset_y
self:AlignItems()
local items_h = self.items_panel:h()
local normal_pos
local best_h = items_h
if items_h < bottom_h then
normal_pos = true
elseif items_h < top_h then
normal_pos = false
elseif bottom_h >= top_h then
normal_pos = true
best_h = bottom_h
else
normal_pos = false
best_h = top_h
end
self._scroll:set_size(self._popup_menu:w(), best_h)
self._popup_menu:set_world_x(self.panel:world_x())
if normal_pos then
self._popup_menu:set_world_y(self.panel:world_bottom())
else
self._popup_menu:set_world_bottom(self.panel:world_y())
end
end
function PopupMenu:UpdateCanvas(h)
if not self:alive() then
return
end
if not self.auto_height and h < self._scroll:scroll_panel():h() then
h = self._scroll:scroll_panel():h()
end
local max_w = 0
for i, panel in pairs(self.items_panel:children()) do
local item = panel:script().menuui_item
if (item and item.visible) or panel:visible() then
local w = panel:right()
if max_w < w then
max_w = w
end
end
end
self._scroll:set_size(max_w + self._scroll._scroll_bar:w(), self._popup_menu:h())
self._scroll:set_canvas_size(nil, h)
end
function PopupMenu:MousePressed(b, x, y)
if self.menu_type and self.opened and self:MousePressedMenuEvent(b, x, y) then
return true
else
return self:MousePressedSelfEvent(b, x, y)
end
end
function PopupMenu:Open()
if not self.menu._popupmenu then
self.menu._popupmenu = self
end
self._popup_menu:show()
self.opened = true
self:RepositionPopupMenu()
end
function PopupMenu:Close()
if self.opened then
if self.menu._popupmenu == self then
self.menu._popupmenu = nil
end
self.opened = false
self._popup_menu:hide()
end
end
function PopupMenu:MousePressedMenuEvent(...)
local ret, item = PopupMenu.super.MousePressedMenuEvent(self, ...)
if not self.keep_menu_open and ret and item.type_name == "Button" then
self:Close()
end
return ret, item
end
function PopupMenu:MousePressedSelfEvent(button, x, y)
if self.opened and self._popup_menu:inside(x,y) then
return true
end
if not self:MouseCheck(true) then
self:Close()
return false, self.UNCLICKABLE
end
if self:MouseInside(x,y) then
if self.on_click then
if self.on_click(self, button, x, y) == false then
return false, self.INTERRUPTED
end
end
if button == self.click_btn then
if self.opened then
self:Close()
else
self:Open()
end
return true
end
self:Close()
return false, self.CLICKABLE
else
self:Close()
return false
end
end
function PopupMenu:MouseFocused(x, y)
if not x and not y then
x,y = managers.mouse_pointer._mouse:world_position()
end
return self:alive() and ((self.opened and self._popup_menu:inside(x,y)) or self.panel:inside(x,y)) and self:Visible()
end
function PopupMenu:MouseMoved(x,y)
return (self.menu_type and self.opened and self:MouseMovedMenuEvent(x,y)) or self:MouseMovedSelfEvent(x,y)
end
function PopupMenu:ItemsWidth() return self.items_panel:w() end
function PopupMenu:ItemsHeight() return self.items_panel:h() end
function PopupMenu:ItemsPanel() return self.items_panel end |
local match = require "luassert.match"
local mock = require "luassert.mock"
local stub = require "luassert.stub"
local spy = require "luassert.spy"
local Optional = require "nvim-lsp-installer.core.optional"
local Result = require "nvim-lsp-installer.core.result"
local go = require "nvim-lsp-installer.core.managers.go"
local spawn = require "nvim-lsp-installer.core.spawn"
local installer = require "nvim-lsp-installer.core.installer"
describe("go manager", function()
---@type InstallContext
local ctx
before_each(function()
ctx = InstallContextGenerator {
spawn = mock.new {
go = mockx.returns {},
},
}
end)
it(
"should call go install",
async_test(function()
ctx.requested_version = Optional.of "42.13.37"
installer.run_installer(ctx, go.packages { "main-package", "supporting-package", "supporting-package2" })
assert.spy(ctx.spawn.go).was_called(3)
assert.spy(ctx.spawn.go).was_called_with(match.tbl_containing {
"install",
"-v",
"main-package@42.13.37",
env = match.list_containing "GOBIN=/tmp/install-dir",
})
assert.spy(ctx.spawn.go).was_called_with(match.tbl_containing {
"install",
"-v",
"supporting-package@latest",
env = match.list_containing "GOBIN=/tmp/install-dir",
})
assert.spy(ctx.spawn.go).was_called_with(match.tbl_containing {
"install",
"-v",
"supporting-package2@latest",
env = match.list_containing "GOBIN=/tmp/install-dir",
})
end)
)
it(
"should provide receipt information",
async_test(function()
ctx.requested_version = Optional.of "42.13.37"
installer.run_installer(ctx, go.packages { "main-package", "supporting-package", "supporting-package2" })
assert.equals(
vim.inspect {
type = "go",
package = "main-package",
},
vim.inspect(ctx.receipt.primary_source)
)
assert.equals(
vim.inspect {
{
type = "go",
package = "supporting-package",
},
{
type = "go",
package = "supporting-package2",
},
},
vim.inspect(ctx.receipt.secondary_sources)
)
end)
)
end)
describe("go version check", function()
local go_version_output = [[
gopls: go1.18
path golang.org/x/tools/gopls
mod golang.org/x/tools/gopls v0.8.1 h1:q5nDpRopYrnF4DN/1o8ZQ7Oar4Yd4I5OtGMx5RyV2/8=
dep github.com/google/go-cmp v0.5.7 h1:81/ik6ipDQS2aGcBfIN5dHDB36BwrStyeAQquSYCV4o=
dep mvdan.cc/xurls/v2 v2.4.0 h1:tzxjVAj+wSBmDcF6zBB7/myTy3gX9xvi8Tyr28AuQgc=
build -compiler=gc
build GOOS=darwin
]]
it("should parse go version output", function()
local parsed = go.parse_mod_version_output(go_version_output)
assert.equals(
vim.inspect {
path = { ["golang.org/x/tools/gopls"] = "" },
mod = { ["golang.org/x/tools/gopls"] = "v0.8.1" },
dep = { ["github.com/google/go-cmp"] = "v0.5.7", ["mvdan.cc/xurls/v2"] = "v2.4.0" },
build = { ["-compiler=gc"] = "", ["GOOS=darwin"] = "" },
},
vim.inspect(parsed)
)
end)
it(
"should return current version",
async_test(function()
spawn.go = spy.new(function()
return Result.success { stdout = go_version_output }
end)
local result = go.get_installed_primary_package_version(
mock.new {
primary_source = mock.new {
type = "go",
package = "golang.org/x/tools/gopls",
},
},
"/tmp/install/dir"
)
assert.spy(spawn.go).was_called(1)
assert.spy(spawn.go).was_called_with {
"version",
"-m",
"gopls",
cwd = "/tmp/install/dir",
}
assert.is_true(result:is_success())
assert.equals("v0.8.1", result:get_or_nil())
spawn.go = nil
end)
)
it(
"should return outdated primary package",
async_test(function()
stub(spawn, "go")
spawn.go.on_call_with({
"list",
"-json",
"-m",
"-versions",
"golang.org/x/tools/gopls",
cwd = "/tmp/install/dir",
}).returns(Result.success {
stdout = [[
{
"Path": "/tmp/install/dir",
"Versions": [
"v1.0.0",
"v1.0.1",
"v2.0.0"
]
}
]],
})
spawn.go.on_call_with({
"version",
"-m",
"gopls",
cwd = "/tmp/install/dir",
}).returns(Result.success {
stdout = go_version_output,
})
local result = go.check_outdated_primary_package(
mock.new {
primary_source = mock.new {
type = "go",
package = "golang.org/x/tools/gopls",
},
},
"/tmp/install/dir"
)
assert.is_true(result:is_success())
assert.equals(
vim.inspect {
name = "golang.org/x/tools/gopls",
current_version = "v0.8.1",
latest_version = "v2.0.0",
},
vim.inspect(result:get_or_nil())
)
spawn.go = nil
end)
)
end)
|
-- Buildat: extension/replicate/init.lua
-- http://www.apache.org/licenses/LICENSE-2.0
-- Copyright 2014 Perttu Ahola <celeron55@gmail.com>
local log = buildat.Logger("extension/replicate")
local magic = require("buildat/extension/urho3d").safe
local dump = buildat.dump
local M = {safe = {}}
-- __buildat_replicated_scene is set by client/replication.lua
M.unsafe_main_scene = __buildat_replicated_scene
M.safe.main_scene = getmetatable(magic.Scene).wrap(__buildat_replicated_scene)
local sync_node_added_subs = {}
-- Callback will be called for each node added to the scene.
-- Callback is called immediately for all existing nodes.
function M.safe.sub_sync_node_added(opts, cb)
-- Add to subscriber table
table.insert(sync_node_added_subs, cb)
-- Handle existing nodes
local function handle_node(node)
local name = node:GetName()
--log:debug("sub_sync_node_added(): node "..node:GetID()..", name="..name)
cb(node)
for i = 0, node:GetNumChildren()-1 do
handle_node(node:GetChild(i))
end
end
-- Handle existing nodes starting from the scene
local scene = M.safe.main_scene
handle_node(scene)
end
-- Override dummy default
function __buildat_replicate_on_node_created(node_id)
log:debug("__buildat_replicate_on_node_created(): id="..node_id)
local node = M.safe.main_scene:GetNode(node_id)
if not node then
return
end
for _, v in ipairs(sync_node_added_subs) do
v(node)
end
end
return M
-- vim: set noet ts=4 sw=4:
|
DRONES_REWRITE.Weapons["Repairer"] = {
Initialize = function(self, pos, ang)
local ent = DRONES_REWRITE.Weapons["Template"].Initialize(self, "models/dronesrewrite/laser/laser.mdl", pos, ang, "models/dronesrewrite/attachment4/attachment4.mdl", pos)
ent:SetMaterial("models/dronesrewrite/guns/laserr_mat")
DRONES_REWRITE.Weapons["Template"].SpawnSource(ent, Vector(40, 0, -1.75))
return ent
end,
Think = function(self, gun)
DRONES_REWRITE.Weapons["Template"].Think(self, gun)
end,
OnAttackStopped = function(self, gun)
self:SwitchLoopSound("Laser", false)
end,
Holster = function(self, gun)
self:SwitchLoopSound("Laser", false)
end,
OnRemove = function(self, gun)
self:SwitchLoopSound("Laser", false)
end,
Attack = function(self, gun)
local tr = self:GetCameraTraceLine()
util.ParticleTracerEx("laser_beam_b_drr", gun.Source:GetPos(), tr.HitPos, false, gun:EntIndex(), -1)
ParticleEffect("laser_hit_b_drr", tr.HitPos, gun:GetLocalCamAng())
local ent = tr.Entity
if CurTime() > gun.NextShoot and ent:IsValid() then
if ent.IS_DRR then
if ent:GetHealth() < ent:GetDefaultHealth() then ent:SetHealthAmount(ent:GetHealth() + 3) end
elseif ent:GetClass() == "dronesrewrite_console" then
ent:Repair()
else
ent:TakeDamage(1)
end
gun.NextShoot = CurTime() + 0.3
end
self:SwitchLoopSound("Laser", true, "ambient/energy/force_field_loop1.wav", 150, 1)
end
} |
if self.xml == nil then
self.xml = require("common.xml2lua.xml2lua")
self.xml_tree_handler = require("common.xml2lua.tree")
end
local html = "<html><h1>hello world</h1></html>"
local tree = self.xml_tree_handler:new()
local parser = self.xml.parser(tree)
parser:parse(html) |
-------------------------------------------------------------------------------
-- Mob Framework Mod by Sapier
--
-- You may copy, use, modify or do nearly anything except removing this
-- copyright notice.
-- And of course you are NOT allow to pretend you have written it.
--
--! @file movement_generic.lua
--! @brief generic movement related functions
--! @copyright Sapier
--! @author Sapier
--! @date 2012-08-09
--
--! @defgroup generic_movement Generic movement functions
--! @brief Movement related functions used by different movement generators
--! @ingroup framework_int
--! @{
-- Contact sapier a t gmx net
-------------------------------------------------------------------------------
mobf_assert_backtrace(not core.global_exists("movement_generic"))
movement_generic = {}
--!@}
-------------------------------------------------------------------------------
-- @function [parent=#movement_generic] get_accel_to(new_pos,entity,ymovement,accel)
--
--! @brief calculate a random speed directed to new_pos
--
--! @param new_pos position to go to
--! @param entity mob to move
--! @param ymovement current movement in y direction
--! @return { x,y,z } random speed directed to new_pos
-------------------------------------------------------------------------------
--
function movement_generic.get_accel_to(new_pos, entity, ymovement, accel)
if new_pos == nil or entity == nil then
minetest.log(LOGLEVEL_CRITICAL,
"MOBF: movement_generic.get_accel_to : Invalid parameters")
end
local old_pos = entity.object:getpos()
local node = minetest.get_node(old_pos)
local maxaccel = entity.data.movement.max_accel
local minaccel = entity.data.movement.min_accel
local yaccel = environment.get_default_gravity(old_pos,
entity.environment.media,
entity.data.movement.canfly)
mobf_assert_backtrace(yaccel ~= nil)
--calculate plane direction to target
local xz_direction =
mobf_calc_yaw(new_pos.x-old_pos.x,new_pos.z-old_pos.z)
local absolute_accel = nil
--find a new speed
if not accel then
absolute_accel = minaccel + (maxaccel - minaccel) * math.random()
else
absolute_accel = accel
end
local new_accel_vector = nil
--flying mob calculate accel towards target
if entity.data.movement.canfly and
yaccel == 0 then
local xz_direction,xy_direction = mobf_calc_direction(old_pos,new_pos)
new_accel_vector =
mobf_calc_vector_components_3d(xz_direction,
xy_direction,
absolute_accel)
if (new_pos.y > old_pos.y) then
mobf_assert_backtrace(new_accel_vector.y >= 0)
end
if (new_pos.y < old_pos.y) then
mobf_assert_backtrace(new_accel_vector.y <= 0)
end
else
new_accel_vector =
mobf_calc_vector_components(xz_direction,absolute_accel)
new_accel_vector.y = yaccel
end
return new_accel_vector
end
-------------------------------------------------------------------------------
-- @function [parent=#movement_generic] calc_new_pos(pos,acceleration,prediction_time)
--
--! @brief calc the position a mob would be after a specified time
-- this doesn't handle velocity changes due to colisions
--
--! @param pos position
--! @param acceleration acceleration to predict pos
--! @param prediction_time time to predict pos
--! @param current_velocity current velocity of mob
--! @return { x,y,z } position after specified time
-------------------------------------------------------------------------------
function movement_generic.calc_new_pos(pos,acceleration,prediction_time,current_velocity)
local predicted_pos = {x=pos.x,y=pos.y,z=pos.z}
predicted_pos.x = predicted_pos.x + current_velocity.x * prediction_time + (acceleration.x/2)*math.pow(prediction_time,2)
predicted_pos.z = predicted_pos.z + current_velocity.z * prediction_time + (acceleration.z/2)*math.pow(prediction_time,2)
return predicted_pos
end
-------------------------------------------------------------------------------
-- @function [parent=#movement_generic] predict_next_block(pos,velocity,acceleration)
--
--! @brief predict next block based on pos velocity and acceleration
--
--! @param pos current position
--! @param velocity current velocity
--! @param acceleration current acceleration
--! @return { x,y,z } position of next block
-------------------------------------------------------------------------------
function movement_generic.predict_next_block(pos,velocity,acceleration)
local prediction_time = 2
local pos_predicted = movement_generic.calc_new_pos(pos,
acceleration,
prediction_time,
velocity
)
local count = 1
--check if after prediction time we would have traveled more than one block and adjust to not predict to far
while mobf_calc_distance(pos,pos_predicted) > 1 do
pos_predicted = movement_generic.calc_new_pos(pos,
acceleration,
prediction_time - (count*0.1),
velocity
)
if (prediction_time - (count*0.1)) < 0 then
minetest.log(LOGLEVEL_WARNING,"MOBF: Bug!!!! didn't find a suitable prediction time. Mob will move more than one block within prediction period")
break
end
count = count +1
end
return pos_predicted
end
-------------------------------------------------------------------------------
-- @function [parent=#movement_generic] predict_enter_next_block(entity,pos,velocity,acceleration)
--
--! @brief predict next block based on pos velocity and acceleration
--
--! @param entity entitiy to do prediction for
--! @param pos current position
--! @param velocity current velocity
--! @param acceleration current acceleration
--! @return { x,y,z } position of next block
-------------------------------------------------------------------------------
function movement_generic.predict_enter_next_block(entity,pos,velocity,acceleration)
local cornerpositions = {}
table.insert(cornerpositions,{x=pos.x + entity.collisionbox[4] -0.01,y=pos.y,z=pos.z + entity.collisionbox[6] -0.01})
table.insert(cornerpositions,{x=pos.x + entity.collisionbox[4] -0.01,y=pos.y,z=pos.z + entity.collisionbox[3] +0.01})
table.insert(cornerpositions,{x=pos.x + entity.collisionbox[1] +0.01,y=pos.y,z=pos.z + entity.collisionbox[6] -0.01})
table.insert(cornerpositions,{x=pos.x + entity.collisionbox[1] +0.01,y=pos.y,z=pos.z + entity.collisionbox[3] +0.01})
local sameblock = function(a,b)
for i=1,#a,1 do
if not mobf_pos_is_same(
mobf_round_pos(a[i]),
mobf_round_pos(b[i])) then
return false
end
end
return true
end
local prediction_time = 0.1
local predicted_corners = {}
for i=1,#cornerpositions,1 do
predicted_corners[i] = movement_generic.calc_new_pos(cornerpositions[i],
acceleration,
prediction_time,
velocity
)
end
--check if any of the corners is in different block after prediction time
while sameblock(cornerpositions,predicted_corners) and
prediction_time < 2 do
prediction_time = prediction_time + 0.1
for i=1,#cornerpositions,1 do
predicted_corners[i] = movement_generic.calc_new_pos(cornerpositions[i],
acceleration,
prediction_time,
velocity
)
end
end
local pos_predicted = movement_generic.calc_new_pos(pos,
acceleration,
prediction_time,
velocity
)
return pos_predicted
end |
require "lang.Signal"
require "specs.Cocos2d-x"
require "Logger"
Log.setLevel(LogLevel.Warning)
local AdManifest = require("royal.AdManifest")
local AdUnit = require("royal.AdUnit")
local LuaFile = require("LuaFile")
describe("AdManifest", function()
local subject
local created
local ttl
local units
before_each(function()
created = 1433289600
units = {{
id = 1
, startdate = 15
, enddate = 16
, url = "http://www.example.com"
, reward = 25
, title = "Title..."
, config = {}
}}
subject = AdManifest(created, units)
end)
it("should have set all values", function()
assert.equals(1433289600, subject.getCreated())
end)
it("should have created AdUnit from dictionary", function()
assert.equal(units, subject.getAdUnits())
end)
describe("isActive", function()
it("should be active if time is less than created time", function()
assert.truthy(subject.isActive(1433289599))
end)
it("should be active if time is equal to created time", function()
assert.truthy(subject.isActive(1433289600))
end)
it("should be inactive if time is greater than created time", function()
assert.falsy(subject.isActive(1433289601))
end)
end)
describe("setAdUnits", function()
local new_units
before_each(function()
new_units = {}
subject.setAdUnits(new_units)
end)
it("should have set the ad units", function()
assert.equal(new_units, subject.getAdUnits())
end)
end)
end)
describe("convert dictionary into AdManifest", function()
local manifest
before_each(function()
-- config will be triggered on evolution 1,4,5 and when the game ends.
local jsonStr = "{'created': 10000, 'units': [{'id': 2, 'startdate': 4, 'enddate': 5, 'url': 'http://www.example.com/endpoint', 'reward': 25, 'title': 'A title!', 'config': [1,4,5,'END']}]}}"
local jsonDict = json.decode(jsonStr)
manifest = AdManifest.fromDictionary(jsonDict)
end)
it("should have inflated AdManifest completely", function()
assert.truthy(manifest)
assert.equal(AdManifest, manifest.getClass())
assert.equal(10000, manifest.getCreated())
local units = manifest.getAdUnits()
assert.equal(1, #units)
local unit = units[1]
assert.equal(2, unit.getId())
assert.equal(4, unit.getStartDate())
assert.equal(5, unit.getEndDate())
assert.equal("http://www.example.com/endpoint", unit.getURL())
assert.equal(25, unit.getReward())
assert.equal("A title!", unit.getTitle())
assert.truthy(table.equals({1,4,5,'END'}, unit.getConfig()))
end)
end)
describe("load manifest from file", function()
local manifest
describe("when the file exists", function()
local fakeManifest
before_each(function()
fakeManifest = AdManifest()
stub(AdManifest, "fromDictionary", fakeManifest)
manifest = AdManifest.fromJson('{"key": 1}')
end)
it("should have called method to convert JSON into AdManifest", function()
assert.equal(fakeManifest, manifest)
end)
end)
--[[
describe("when the file is corrupt", function()
before_each(function()
-- partial data write.
local jsonStr = "{'version': 1, 'created': 10000, 'ttl': 86500, 'units': [{'id': 2, 'reward': 25, 'startdate': 4, 'enddate': 5, 'waitsecs': 86400, 'conf"
stub(AdManifest, "fromDictionary")
manifest = AdManifest.fromJson(jsonStr)
end)
it("should have called method to convert JSON into AdManifest", function()
assert.falsy(manifest)
end)
it("should not have attempted to create a dictionary", function()
assert.stub(AdManifst.fromDictionary).was_not.called()
end)
end)
]]--
describe("when the file contains no data", function()
before_each(function()
stub(AdManifest, "fromDictionary")
manifest = AdManifest.fromJson("")
end)
it("should not have created a manfiest", function()
assert.falsy(manifest)
end)
end)
describe("when the file does not exist", function()
before_each(function()
stub(AdManifest, "fromDictionary")
manifest = AdManifest.fromJson(nil)
end)
it("should not have created a manifest", function()
assert.falsy(manifest)
end)
end)
end)
|
local names = require("namelist")
local function genTable()
for i, name in ipairs(names) do
print(string.format("[%d] = '%s';", i-1, name))
end
end
genTable()
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.